-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgscoordinatereferencesystem.cpp
3567 lines (3118 loc) · 110 KB
/
qgscoordinatereferencesystem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
qgscoordinatereferencesystem.cpp
-------------------
begin : 2007
copyright : (C) 2007 by Gary E. Sherman
email : sherman@mrcc.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgscoordinatereferencesystem.h"
#include "qgscoordinatereferencesystem_p.h"
#include "qgscoordinatereferencesystem_legacy.h"
#include "qgsreadwritelocker.h"
#include <cmath>
#include <QDir>
#include <QDomNode>
#include <QDomElement>
#include <QFileInfo>
#include <QRegExp>
#include <QTextStream>
#include <QFile>
#include <QRegularExpression>
#include "qgsapplication.h"
#include "qgslogger.h"
#include "qgsmessagelog.h"
#include "qgis.h" //const vals declared here
#include "qgslocalec.h"
#include "qgssettings.h"
#include "qgsogrutils.h"
#include <sqlite3.h>
#if PROJ_VERSION_MAJOR>=6
#include "qgsprojutils.h"
#include <proj.h>
#include <proj_experimental.h>
#else
#include <proj_api.h>
#endif
//gdal and ogr includes (needed for == operator)
#include <ogr_srs_api.h>
#include <cpl_error.h>
#include <cpl_conv.h>
#include <cpl_csv.h>
//! The length of the string "+lat_1="
const int LAT_PREFIX_LEN = 7;
CUSTOM_CRS_VALIDATION QgsCoordinateReferenceSystem::sCustomSrsValidation = nullptr;
typedef QHash< long, QgsCoordinateReferenceSystem > SrIdCrsCacheHash;
typedef QHash< QString, QgsCoordinateReferenceSystem > StringCrsCacheHash;
Q_GLOBAL_STATIC( QReadWriteLock, sSrIdCacheLock )
Q_GLOBAL_STATIC( SrIdCrsCacheHash, sSrIdCache )
bool QgsCoordinateReferenceSystem::sDisableSrIdCache = false;
Q_GLOBAL_STATIC( QReadWriteLock, sOgcLock )
Q_GLOBAL_STATIC( StringCrsCacheHash, sOgcCache )
bool QgsCoordinateReferenceSystem::sDisableOgcCache = false;
Q_GLOBAL_STATIC( QReadWriteLock, sProj4CacheLock )
Q_GLOBAL_STATIC( StringCrsCacheHash, sProj4Cache )
bool QgsCoordinateReferenceSystem::sDisableProjCache = false;
Q_GLOBAL_STATIC( QReadWriteLock, sCRSWktLock )
Q_GLOBAL_STATIC( StringCrsCacheHash, sWktCache )
bool QgsCoordinateReferenceSystem::sDisableWktCache = false;
Q_GLOBAL_STATIC( QReadWriteLock, sCRSSrsIdLock )
Q_GLOBAL_STATIC( SrIdCrsCacheHash, sSrsIdCache )
bool QgsCoordinateReferenceSystem::sDisableSrsIdCache = false;
Q_GLOBAL_STATIC( QReadWriteLock, sCrsStringLock )
Q_GLOBAL_STATIC( StringCrsCacheHash, sStringCache )
bool QgsCoordinateReferenceSystem::sDisableStringCache = false;
#if PROJ_VERSION_MAJOR>=6
QString getFullProjString( PJ *obj )
{
// see https://lists.osgeo.org/pipermail/proj/2019-May/008565.html, it's not sufficient to just
// use proj_as_proj_string
QgsProjUtils::proj_pj_unique_ptr boundCrs( proj_crs_create_bound_crs_to_WGS84( QgsProjContext::get(), obj, nullptr ) );
if ( boundCrs )
{
if ( const char *proj4src = proj_as_proj_string( QgsProjContext::get(), boundCrs.get(), PJ_PROJ_4, nullptr ) )
{
return QString( proj4src );
}
}
return QString( proj_as_proj_string( QgsProjContext::get(), obj, PJ_PROJ_4, nullptr ) );
}
#endif
//--------------------------
QgsCoordinateReferenceSystem::QgsCoordinateReferenceSystem()
{
d = new QgsCoordinateReferenceSystemPrivate();
}
QgsCoordinateReferenceSystem::QgsCoordinateReferenceSystem( const QString &definition )
{
d = new QgsCoordinateReferenceSystemPrivate();
createFromString( definition );
}
QgsCoordinateReferenceSystem::QgsCoordinateReferenceSystem( const long id, CrsType type )
{
d = new QgsCoordinateReferenceSystemPrivate();
Q_NOWARN_DEPRECATED_PUSH
createFromId( id, type );
Q_NOWARN_DEPRECATED_POP
}
QgsCoordinateReferenceSystem::QgsCoordinateReferenceSystem( const QgsCoordinateReferenceSystem &srs ) //NOLINT
: d( srs.d )
, mValidationHint( srs.mValidationHint )
{
}
QgsCoordinateReferenceSystem &QgsCoordinateReferenceSystem::operator=( const QgsCoordinateReferenceSystem &srs ) //NOLINT
{
d = srs.d;
mValidationHint = srs.mValidationHint;
return *this;
}
QList<long> QgsCoordinateReferenceSystem::validSrsIds()
{
QList<long> results;
// check both standard & user defined projection databases
QStringList dbs = QStringList() << QgsApplication::srsDatabaseFilePath() << QgsApplication::qgisUserDatabaseFilePath();
const auto constDbs = dbs;
for ( const QString &db : constDbs )
{
QFileInfo myInfo( db );
if ( !myInfo.exists() )
{
QgsDebugMsg( "failed : " + db + " does not exist!" );
continue;
}
sqlite3_database_unique_ptr database;
sqlite3_statement_unique_ptr statement;
//check the db is available
int result = openDatabase( db, database );
if ( result != SQLITE_OK )
{
QgsDebugMsg( "failed : " + db + " could not be opened!" );
continue;
}
QString sql = QStringLiteral( "select srs_id from tbl_srs" );
int rc;
statement = database.prepare( sql, rc );
while ( true )
{
// this one is an infinitive loop, intended to fetch any row
int ret = statement.step();
if ( ret == SQLITE_DONE )
{
// there are no more rows to fetch - we can stop looping
break;
}
if ( ret == SQLITE_ROW )
{
results.append( statement.columnAsInt64( 0 ) );
}
else
{
QgsMessageLog::logMessage( QObject::tr( "SQLite error: %2\nSQL: %1" ).arg( sql, sqlite3_errmsg( database.get() ) ), QObject::tr( "SpatiaLite" ) );
break;
}
}
}
std::sort( results.begin(), results.end() );
return results;
}
QgsCoordinateReferenceSystem QgsCoordinateReferenceSystem::fromOgcWmsCrs( const QString &ogcCrs )
{
QgsCoordinateReferenceSystem crs;
crs.createFromOgcWmsCrs( ogcCrs );
return crs;
}
QgsCoordinateReferenceSystem QgsCoordinateReferenceSystem::fromEpsgId( long epsg )
{
QgsCoordinateReferenceSystem res = fromOgcWmsCrs( "EPSG:" + QString::number( epsg ) );
if ( res.isValid() )
return res;
// pre proj6 builds allowed use of ESRI: codes here (e.g. 54030), so we need to keep compatibility
res = fromOgcWmsCrs( "ESRI:" + QString::number( epsg ) );
if ( res.isValid() )
return res;
return QgsCoordinateReferenceSystem();
}
QgsCoordinateReferenceSystem QgsCoordinateReferenceSystem::fromProj4( const QString &proj4 )
{
return fromProj( proj4 );
}
QgsCoordinateReferenceSystem QgsCoordinateReferenceSystem::fromProj( const QString &proj )
{
QgsCoordinateReferenceSystem crs;
crs.createFromProj( proj );
return crs;
}
QgsCoordinateReferenceSystem QgsCoordinateReferenceSystem::fromWkt( const QString &wkt )
{
QgsCoordinateReferenceSystem crs;
crs.createFromWkt( wkt );
return crs;
}
QgsCoordinateReferenceSystem QgsCoordinateReferenceSystem::fromSrsId( long srsId )
{
QgsCoordinateReferenceSystem crs;
crs.createFromSrsId( srsId );
return crs;
}
QgsCoordinateReferenceSystem::~QgsCoordinateReferenceSystem() //NOLINT
{
}
bool QgsCoordinateReferenceSystem::createFromId( const long id, CrsType type )
{
bool result = false;
switch ( type )
{
case InternalCrsId:
result = createFromSrsId( id );
break;
case PostgisCrsId:
result = createFromPostgisSrid( id );
break;
case EpsgCrsId:
result = createFromOgcWmsCrs( QStringLiteral( "EPSG:%1" ).arg( id ) );
break;
default:
//THIS IS BAD...THIS PART OF CODE SHOULD NEVER BE REACHED...
QgsDebugMsg( QStringLiteral( "Unexpected case reached!" ) );
};
return result;
}
bool QgsCoordinateReferenceSystem::createFromString( const QString &definition )
{
QgsReadWriteLocker locker( *sCrsStringLock(), QgsReadWriteLocker::Read );
if ( !sDisableStringCache )
{
QHash< QString, QgsCoordinateReferenceSystem >::const_iterator crsIt = sStringCache()->constFind( definition );
if ( crsIt != sStringCache()->constEnd() )
{
// found a match in the cache
*this = crsIt.value();
return true;
}
}
locker.unlock();
bool result = false;
QRegularExpression reCrsId( QStringLiteral( "^(epsg|esri|osgeo|ignf|zangi|iau2000|postgis|internal|user)\\:(\\w+)$" ), QRegularExpression::CaseInsensitiveOption );
QRegularExpressionMatch match = reCrsId.match( definition );
if ( match.capturedStart() == 0 )
{
QString authName = match.captured( 1 ).toLower();
if ( authName == QLatin1String( "epsg" ) )
{
result = createFromOgcWmsCrs( definition );
}
else if ( authName == QLatin1String( "postgis" ) )
{
const long id = match.captured( 2 ).toLong();
result = createFromPostgisSrid( id );
}
else if ( authName == QLatin1String( "esri" ) || authName == QLatin1String( "osgeo" ) || authName == QLatin1String( "ignf" ) || authName == QLatin1String( "zangi" ) || authName == QLatin1String( "iau2000" ) )
{
result = createFromOgcWmsCrs( definition );
}
else
{
const long id = match.captured( 2 ).toLong();
Q_NOWARN_DEPRECATED_PUSH
result = createFromId( id, InternalCrsId );
Q_NOWARN_DEPRECATED_POP
}
}
else
{
QRegularExpression reCrsStr( "^(?:(wkt|proj4)\\:)?(.+)$", QRegularExpression::CaseInsensitiveOption );
match = reCrsStr.match( definition );
if ( match.capturedStart() == 0 )
{
if ( match.captured( 1 ).compare( QLatin1String( "proj4" ), Qt::CaseInsensitive ) == 0 )
{
result = createFromProj( match.captured( 2 ) );
}
else
{
result = createFromWkt( match.captured( 2 ) );
}
}
}
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableStringCache )
sStringCache()->insert( definition, *this );
return result;
}
bool QgsCoordinateReferenceSystem::createFromUserInput( const QString &definition )
{
QString userWkt;
OGRSpatialReferenceH crs = OSRNewSpatialReference( nullptr );
#if PROJ_VERSION_MAJOR<6
// make sure towgs84 parameter is loaded if using an ESRI definition and gdal >= 1.9
if ( definition.startsWith( QLatin1String( "ESRI::" ) ) )
{
Q_NOWARN_DEPRECATED_PUSH
setupESRIWktFix();
Q_NOWARN_DEPRECATED_POP
}
#endif
if ( OSRSetFromUserInput( crs, definition.toLocal8Bit().constData() ) == OGRERR_NONE )
{
userWkt = QgsOgrUtils::OGRSpatialReferenceToWkt( crs );
OSRDestroySpatialReference( crs );
}
//QgsDebugMsg( "definition: " + definition + " wkt = " + wkt );
return createFromWkt( userWkt );
}
void QgsCoordinateReferenceSystem::setupESRIWktFix()
{
// make sure towgs84 parameter is loaded if gdal >= 1.9
// this requires setting GDAL_FIX_ESRI_WKT=GEOGCS (see qgis bug #5598 and gdal bug #4673)
const char *configOld = CPLGetConfigOption( "GDAL_FIX_ESRI_WKT", "" );
const char *configNew = "GEOGCS";
// only set if it was not set, to let user change the value if needed
if ( strcmp( configOld, "" ) == 0 )
{
CPLSetConfigOption( "GDAL_FIX_ESRI_WKT", configNew );
if ( strcmp( configNew, CPLGetConfigOption( "GDAL_FIX_ESRI_WKT", "" ) ) != 0 )
QgsLogger::warning( QStringLiteral( "GDAL_FIX_ESRI_WKT could not be set to %1 : %2" )
.arg( configNew, CPLGetConfigOption( "GDAL_FIX_ESRI_WKT", "" ) ) );
QgsDebugMsgLevel( QStringLiteral( "set GDAL_FIX_ESRI_WKT : %1" ).arg( configNew ), 4 );
}
else
{
QgsDebugMsgLevel( QStringLiteral( "GDAL_FIX_ESRI_WKT was already set : %1" ).arg( configNew ), 4 );
}
}
bool QgsCoordinateReferenceSystem::createFromOgcWmsCrs( const QString &crs )
{
QgsReadWriteLocker locker( *sOgcLock(), QgsReadWriteLocker::Read );
if ( !sDisableOgcCache )
{
QHash< QString, QgsCoordinateReferenceSystem >::const_iterator crsIt = sOgcCache()->constFind( crs );
if ( crsIt != sOgcCache()->constEnd() )
{
// found a match in the cache
*this = crsIt.value();
return true;
}
}
locker.unlock();
QString wmsCrs = crs;
QRegExp re_uri( "http://www\\.opengis\\.net/def/crs/([^/]+).+/([^/]+)", Qt::CaseInsensitive );
QRegExp re_urn( "urn:ogc:def:crs:([^:]+).+([^:]+)", Qt::CaseInsensitive );
if ( re_uri.exactMatch( wmsCrs ) )
{
wmsCrs = re_uri.cap( 1 ) + ':' + re_uri.cap( 2 );
}
else if ( re_urn.exactMatch( wmsCrs ) )
{
wmsCrs = re_urn.cap( 1 ) + ':' + re_urn.cap( 2 );
}
else
{
re_urn.setPattern( QStringLiteral( "(user|custom|qgis):(\\d+)" ) );
if ( re_urn.exactMatch( wmsCrs ) && createFromSrsId( re_urn.cap( 2 ).toInt() ) )
{
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableOgcCache )
sOgcCache()->insert( crs, *this );
return true;
}
}
#if PROJ_VERSION_MAJOR>=6
// first chance for proj 6 - scan through legacy systems and try to use authid directly
const QString legacyKey = wmsCrs.toLower();
for ( auto it = sAuthIdToQgisSrsIdMap.constBegin(); it != sAuthIdToQgisSrsIdMap.constEnd(); ++it )
{
if ( it.key().compare( legacyKey, Qt::CaseInsensitive ) == 0 )
{
const QStringList parts = it.key().split( ':' );
const QString auth = parts.at( 0 );
const QString code = parts.at( 1 );
if ( loadFromAuthCode( auth, code ) )
{
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableOgcCache )
sOgcCache()->insert( crs, *this );
return true;
}
}
}
#endif
if ( loadFromDatabase( QgsApplication::srsDatabaseFilePath(), QStringLiteral( "lower(auth_name||':'||auth_id)" ), wmsCrs.toLower() ) )
{
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableOgcCache )
sOgcCache()->insert( crs, *this );
return true;
}
// NAD27
if ( wmsCrs.compare( QLatin1String( "CRS:27" ), Qt::CaseInsensitive ) == 0 ||
wmsCrs.compare( QLatin1String( "OGC:CRS27" ), Qt::CaseInsensitive ) == 0 )
{
// TODO: verify same axis orientation
return createFromOgcWmsCrs( QStringLiteral( "EPSG:4267" ) );
}
// NAD83
if ( wmsCrs.compare( QLatin1String( "CRS:83" ), Qt::CaseInsensitive ) == 0 ||
wmsCrs.compare( QLatin1String( "OGC:CRS83" ), Qt::CaseInsensitive ) == 0 )
{
// TODO: verify same axis orientation
return createFromOgcWmsCrs( QStringLiteral( "EPSG:4269" ) );
}
// WGS84
if ( wmsCrs.compare( QLatin1String( "CRS:84" ), Qt::CaseInsensitive ) == 0 ||
wmsCrs.compare( QLatin1String( "OGC:CRS84" ), Qt::CaseInsensitive ) == 0 )
{
if ( loadFromDatabase( QgsApplication::srsDatabaseFilePath(), QStringLiteral( "lower(auth_name||':'||auth_id)" ), QStringLiteral( "epsg:4326" ) ) )
{
d->mAxisInverted = false;
d->mAxisInvertedDirty = false;
}
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableOgcCache )
sOgcCache()->insert( crs, *this );
return d->mIsValid;
}
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableOgcCache )
sOgcCache()->insert( crs, QgsCoordinateReferenceSystem() );
return false;
}
// Misc helper functions -----------------------
void QgsCoordinateReferenceSystem::validate()
{
if ( d->mIsValid || !sCustomSrsValidation )
return;
// try to validate using custom validation routines
if ( sCustomSrsValidation )
sCustomSrsValidation( *this );
}
bool QgsCoordinateReferenceSystem::createFromSrid( const long id )
{
return createFromPostgisSrid( id );
}
bool QgsCoordinateReferenceSystem::createFromPostgisSrid( const long id )
{
QgsReadWriteLocker locker( *sSrIdCacheLock(), QgsReadWriteLocker::Read );
if ( !sDisableSrIdCache )
{
QHash< long, QgsCoordinateReferenceSystem >::const_iterator crsIt = sSrIdCache()->constFind( id );
if ( crsIt != sSrIdCache()->constEnd() )
{
// found a match in the cache
*this = crsIt.value();
return true;
}
}
locker.unlock();
#if PROJ_VERSION_MAJOR>=6
// first chance for proj 6 - scan through legacy systems and try to use authid directly
for ( auto it = sAuthIdToQgisSrsIdMap.constBegin(); it != sAuthIdToQgisSrsIdMap.constEnd(); ++it )
{
if ( it.value().endsWith( QStringLiteral( ",%1" ).arg( id ) ) )
{
const QStringList parts = it.key().split( ':' );
const QString auth = parts.at( 0 );
const QString code = parts.at( 1 );
if ( loadFromAuthCode( auth, code ) )
{
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableSrIdCache )
sSrIdCache()->insert( id, *this );
return true;
}
}
}
#endif
bool result = loadFromDatabase( QgsApplication::srsDatabaseFilePath(), QStringLiteral( "srid" ), QString::number( id ) );
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableSrIdCache )
sSrIdCache()->insert( id, *this );
return result;
}
bool QgsCoordinateReferenceSystem::createFromSrsId( const long id )
{
QgsReadWriteLocker locker( *sCRSSrsIdLock(), QgsReadWriteLocker::Read );
if ( !sDisableSrsIdCache )
{
QHash< long, QgsCoordinateReferenceSystem >::const_iterator crsIt = sSrsIdCache()->constFind( id );
if ( crsIt != sSrsIdCache()->constEnd() )
{
// found a match in the cache
*this = crsIt.value();
return true;
}
}
locker.unlock();
#if PROJ_VERSION_MAJOR>=6
// first chance for proj 6 - scan through legacy systems and try to use authid directly
for ( auto it = sAuthIdToQgisSrsIdMap.constBegin(); it != sAuthIdToQgisSrsIdMap.constEnd(); ++it )
{
if ( it.value().startsWith( QString::number( id ) + ',' ) )
{
const QStringList parts = it.key().split( ':' );
const QString auth = parts.at( 0 );
const QString code = parts.at( 1 );
if ( loadFromAuthCode( auth, code ) )
{
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableSrsIdCache )
sSrsIdCache()->insert( id, *this );
return true;
}
}
}
#endif
bool result = loadFromDatabase( id < USER_CRS_START_ID ? QgsApplication::srsDatabaseFilePath() :
QgsApplication::qgisUserDatabaseFilePath(),
QStringLiteral( "srs_id" ), QString::number( id ) );
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableSrsIdCache )
sSrsIdCache()->insert( id, *this );
return result;
}
bool QgsCoordinateReferenceSystem::loadFromDatabase( const QString &db, const QString &expression, const QString &value )
{
d.detach();
QgsDebugMsgLevel( "load CRS from " + db + " where " + expression + " is " + value, 3 );
d->mIsValid = false;
QFileInfo myInfo( db );
if ( !myInfo.exists() )
{
QgsDebugMsg( "failed : " + db + " does not exist!" );
return d->mIsValid;
}
sqlite3_database_unique_ptr database;
sqlite3_statement_unique_ptr statement;
int myResult;
//check the db is available
myResult = openDatabase( db, database );
if ( myResult != SQLITE_OK )
{
return d->mIsValid;
}
/*
srs_id INTEGER PRIMARY KEY,
description text NOT NULL,
projection_acronym text NOT NULL,
ellipsoid_acronym NOT NULL,
parameters text NOT NULL,
srid integer NOT NULL,
auth_name varchar NOT NULL,
auth_id integer NOT NULL,
is_geo integer NOT NULL);
*/
QString mySql = "select srs_id,description,projection_acronym,"
"ellipsoid_acronym,parameters,srid,auth_name||':'||auth_id,is_geo,wkt "
"from tbl_srs where " + expression + '=' + QgsSqliteUtils::quotedString( value ) + " order by deprecated";
statement = database.prepare( mySql, myResult );
QString wkt;
// XXX Need to free memory from the error msg if one is set
if ( myResult == SQLITE_OK && statement.step() == SQLITE_ROW )
{
d->mSrsId = statement.columnAsText( 0 ).toLong();
d->mDescription = statement.columnAsText( 1 );
d->mProjectionAcronym = statement.columnAsText( 2 );
#if PROJ_VERSION_MAJOR>=6
d->mEllipsoidAcronym.clear();
#else
d->mEllipsoidAcronym = statement.columnAsText( 3 );
#endif
d->mProj4 = statement.columnAsText( 4 );
d->mSRID = statement.columnAsText( 5 ).toLong();
d->mAuthId = statement.columnAsText( 6 );
d->mIsGeographic = statement.columnAsText( 7 ).toInt() != 0;
wkt = statement.columnAsText( 8 );
d->mAxisInvertedDirty = true;
if ( d->mSrsId >= USER_CRS_START_ID && d->mAuthId.isEmpty() )
{
d->mAuthId = QStringLiteral( "USER:%1" ).arg( d->mSrsId );
}
else if ( !d->mAuthId.startsWith( QLatin1String( "USER:" ), Qt::CaseInsensitive ) )
{
#if PROJ_VERSION_MAJOR>=6
QStringList parts = d->mAuthId.split( ':' );
QString auth = parts.at( 0 );
QString code = parts.at( 1 );
{
QgsProjUtils::proj_pj_unique_ptr crs( proj_create_from_database( QgsProjContext::get(), auth.toLatin1(), code.toLatin1(), PJ_CATEGORY_CRS, false, nullptr ) );
d->setPj( QgsProjUtils::crsToSingleCrs( crs.get() ) );
}
d->mIsValid = d->hasPj();
#else
OSRDestroySpatialReference( d->mCRS );
d->mCRS = OSRNewSpatialReference( nullptr );
d->mIsValid = OSRSetFromUserInput( d->mCRS, d->mAuthId.toLower().toLatin1() ) == OGRERR_NONE;
#endif
setMapUnits();
}
if ( !d->mIsValid )
{
if ( !wkt.isEmpty() )
setWktString( wkt, false );
else
setProjString( d->mProj4 );
}
}
else
{
QgsDebugMsgLevel( "failed : " + mySql, 4 );
}
return d->mIsValid;
}
#if PROJ_VERSION_MAJOR>=6
void QgsCoordinateReferenceSystem::removeFromCacheObjectsBelongingToCurrentThread( PJ_CONTEXT *pj_context )
{
// Not completely sure about object order destruction after main() has
// exited. So it is safer to check sDisableCache before using sCacheLock
// in case sCacheLock would have been destroyed before the current TLS
// QgsProjContext object that has called us...
if ( !sDisableSrIdCache )
{
QgsReadWriteLocker locker( *sSrIdCacheLock(), QgsReadWriteLocker::Write );
if ( !sDisableSrIdCache )
{
for ( auto it = sSrIdCache()->begin(); it != sSrIdCache()->end(); )
{
auto &v = it.value();
if ( v.d->removeObjectsBelongingToCurrentThread( pj_context ) )
it = sSrIdCache()->erase( it );
else
++it;
}
}
}
if ( !sDisableOgcCache )
{
QgsReadWriteLocker locker( *sOgcLock(), QgsReadWriteLocker::Write );
if ( !sDisableOgcCache )
{
for ( auto it = sOgcCache()->begin(); it != sOgcCache()->end(); )
{
auto &v = it.value();
if ( v.d->removeObjectsBelongingToCurrentThread( pj_context ) )
it = sOgcCache()->erase( it );
else
++it;
}
}
}
if ( !sDisableProjCache )
{
QgsReadWriteLocker locker( *sProj4CacheLock(), QgsReadWriteLocker::Write );
if ( !sDisableProjCache )
{
for ( auto it = sProj4Cache()->begin(); it != sProj4Cache()->end(); )
{
auto &v = it.value();
if ( v.d->removeObjectsBelongingToCurrentThread( pj_context ) )
it = sProj4Cache()->erase( it );
else
++it;
}
}
}
if ( !sDisableWktCache )
{
QgsReadWriteLocker locker( *sCRSWktLock(), QgsReadWriteLocker::Write );
if ( !sDisableWktCache )
{
for ( auto it = sWktCache()->begin(); it != sWktCache()->end(); )
{
auto &v = it.value();
if ( v.d->removeObjectsBelongingToCurrentThread( pj_context ) )
it = sWktCache()->erase( it );
else
++it;
}
}
}
if ( !sDisableSrsIdCache )
{
QgsReadWriteLocker locker( *sCRSSrsIdLock(), QgsReadWriteLocker::Write );
if ( !sDisableSrsIdCache )
{
for ( auto it = sSrsIdCache()->begin(); it != sSrsIdCache()->end(); )
{
auto &v = it.value();
if ( v.d->removeObjectsBelongingToCurrentThread( pj_context ) )
it = sSrsIdCache()->erase( it );
else
++it;
}
}
}
if ( !sDisableStringCache )
{
QgsReadWriteLocker locker( *sCrsStringLock(), QgsReadWriteLocker::Write );
if ( !sDisableStringCache )
{
for ( auto it = sStringCache()->begin(); it != sStringCache()->end(); )
{
auto &v = it.value();
if ( v.d->removeObjectsBelongingToCurrentThread( pj_context ) )
it = sStringCache()->erase( it );
else
++it;
}
}
}
}
#endif
bool QgsCoordinateReferenceSystem::hasAxisInverted() const
{
if ( d->mAxisInvertedDirty )
{
#if PROJ_VERSION_MAJOR>=6
d->mAxisInverted = QgsProjUtils::axisOrderIsSwapped( d->threadLocalProjObject() );
#else
OGRAxisOrientation orientation;
OSRGetAxis( d->mCRS, OSRIsGeographic( d->mCRS ) ? "GEOGCS" : "PROJCS", 0, &orientation );
// If axis orientation is unknown, try again with OSRImportFromEPSGA for EPSG crs
if ( orientation == OAO_Other && d->mAuthId.startsWith( QLatin1String( "EPSG:" ), Qt::CaseInsensitive ) )
{
OGRSpatialReferenceH crs = OSRNewSpatialReference( nullptr );
if ( OSRImportFromEPSGA( crs, d->mAuthId.midRef( 5 ).toInt() ) == OGRERR_NONE )
{
OSRGetAxis( crs, OSRIsGeographic( crs ) ? "GEOGCS" : "PROJCS", 0, &orientation );
}
OSRDestroySpatialReference( crs );
}
d->mAxisInverted = orientation == OAO_North;
#endif
d->mAxisInvertedDirty = false;
}
return d->mAxisInverted;
}
bool QgsCoordinateReferenceSystem::createFromWkt( const QString &wkt )
{
d.detach();
QgsReadWriteLocker locker( *sCRSWktLock(), QgsReadWriteLocker::Read );
if ( !sDisableWktCache )
{
QHash< QString, QgsCoordinateReferenceSystem >::const_iterator crsIt = sWktCache()->constFind( wkt );
if ( crsIt != sWktCache()->constEnd() )
{
// found a match in the cache
*this = crsIt.value();
return true;
}
}
locker.unlock();
d->mIsValid = false;
d->mProj4.clear();
if ( wkt.isEmpty() )
{
QgsDebugMsgLevel( QStringLiteral( "theWkt is uninitialized, operation failed" ), 4 );
return d->mIsValid;
}
// try to match against user crs
QgsCoordinateReferenceSystem::RecordMap record = getRecord( "select * from tbl_srs where wkt=" + QgsSqliteUtils::quotedString( wkt ) + " order by deprecated" );
if ( !record.empty() )
{
long srsId = record[QStringLiteral( "srs_id" )].toLong();
if ( srsId > 0 )
{
createFromSrsId( srsId );
}
}
else
{
setWktString( wkt );
if ( d->mSrsId == 0 )
{
#if PROJ_VERSION_MAJOR>=6
// lastly, try a tolerant match of the created proj object against all user CRSes (allowing differences in parameter order during the comparison)
long id = matchToUserCrs();
if ( id >= USER_CRS_START_ID )
{
createFromSrsId( id );
}
#endif
}
}
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableWktCache )
sWktCache()->insert( wkt, *this );
return d->mIsValid;
//setMapunits will be called by createfromproj above
}
bool QgsCoordinateReferenceSystem::isValid() const
{
return d->mIsValid;
}
bool QgsCoordinateReferenceSystem::createFromProj4( const QString &proj4String )
{
return createFromProj( proj4String );
}
bool QgsCoordinateReferenceSystem::createFromProj( const QString &projString )
{
d.detach();
if ( projString.trimmed().isEmpty() )
{
d->mIsValid = false;
d->mProj4.clear();
return false;
}
QgsReadWriteLocker locker( *sProj4CacheLock(), QgsReadWriteLocker::Read );
if ( !sDisableProjCache )
{
QHash< QString, QgsCoordinateReferenceSystem >::const_iterator crsIt = sProj4Cache()->constFind( projString );
if ( crsIt != sProj4Cache()->constEnd() )
{
// found a match in the cache
*this = crsIt.value();
return true;
}
}
locker.unlock();
//
// Examples:
// +proj=tmerc +lat_0=0 +lon_0=-62 +k=0.999500 +x_0=400000 +y_0=0
// +ellps=clrk80 +towgs84=-255,-15,71,0,0,0,0 +units=m +no_defs
//
// +proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=2.337229166666664 +k_0=0.99987742
// +x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515.000000472 +units=m +no_defs
//
QString myProj4String = projString.trimmed();
myProj4String.remove( QStringLiteral( "+type=crs" ) );
myProj4String = myProj4String.trimmed();
d->mIsValid = false;
#if PROJ_VERSION_MAJOR>=6
// first, try to use proj to do this for us...
const QString projCrsString = myProj4String + ( myProj4String.contains( QStringLiteral( "+type=crs" ) ) ? QString() : QStringLiteral( " +type=crs" ) );
QgsProjUtils::proj_pj_unique_ptr crs( proj_create( QgsProjContext::get(), projCrsString.toLatin1().constData() ) );
if ( crs )
{
QString authName;
QString authCode;
if ( QgsProjUtils::identifyCrs( crs.get(), authName, authCode, QgsProjUtils::FlagMatchBoundCrsToUnderlyingSourceCrs ) )
{
const QString authid = QStringLiteral( "%1:%2" ).arg( authName, authCode );
if ( createFromOgcWmsCrs( authid ) )
{
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableProjCache )
sProj4Cache()->insert( projString, *this );
return true;
}
}
}
// try a direct match against user crses
QgsCoordinateReferenceSystem::RecordMap myRecord = getRecord( "select * from tbl_srs where parameters=" + QgsSqliteUtils::quotedString( myProj4String ) + " order by deprecated" );
long id = 0;
if ( !myRecord.empty() )
{
id = myRecord[QStringLiteral( "srs_id" )].toLong();
if ( id >= USER_CRS_START_ID )
{
createFromSrsId( id );
}
}
if ( id < USER_CRS_START_ID )
{
// no direct matches, so go ahead and create a new proj object based on the proj string alone.
setProjString( myProj4String );
// lastly, try a tolerant match of the created proj object against all user CRSes (allowing differences in parameter order during the comparison)
id = matchToUserCrs();
if ( id >= USER_CRS_START_ID )
{
createFromSrsId( id );
}
}
#else
QRegExp myProjRegExp( "\\+proj=(\\S+)" );
int myStart = myProjRegExp.indexIn( myProj4String );
if ( myStart == -1 )
{
locker.changeMode( QgsReadWriteLocker::Write );
if ( !sDisableProjCache )
sProj4Cache()->insert( projString, *this );
return d->mIsValid;
}
d->mProjectionAcronym = myProjRegExp.cap( 1 );
QRegExp myEllipseRegExp( "\\+ellps=(\\S+)" );
myStart = myEllipseRegExp.indexIn( myProj4String );
if ( myStart == -1 )
{
d->mEllipsoidAcronym.clear();
}
else
{
d->mEllipsoidAcronym = myEllipseRegExp.cap( 1 );