QGIS API Documentation 3.99.0-Master (09f76ad7019)
Loading...
Searching...
No Matches
qgsapplication.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsapplication.cpp - Accessors for application-wide data
3 --------------------------------------
4 Date : 02-Jan-2006
5 Copyright : (C) 2006 by Tom Elwertowski
6 Email : telwertowski at users dot sourceforge dot net
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgsapplication.h"
17
24#include "qgs3dsymbolregistry.h"
30#include "qgsauthmanager.h"
32#include "qgsbookmarkmanager.h"
33#include "qgscalloutsregistry.h"
35#include "qgscolorrampimpl.h"
41#include "qgsdbquerylog.h"
42#include "qgsexception.h"
43#include "qgsexpression.h"
45#include "qgsfeaturestore.h"
47#include "qgsfontmanager.h"
48#include "qgsgeometry.h"
49#include "qgsgpsconnection.h"
50#include "qgsimagecache.h"
51#include "qgsinterval.h"
54#include "qgslayout.h"
58#include "qgslocator.h"
59#include "qgslogger.h"
60#include "qgsmeshlayer.h"
61#include "qgsmessagelog.h"
64#include "qgsnetworkreply.h"
65#include "qgsnewsfeedparser.h"
68#include "qgsplotregistry.h"
72#include "qgsproject.h"
74#include "qgsprojutils.h"
75#include "qgsproviderregistry.h"
77#include "qgsreadwritelocker.h"
81#include "qgsrendererregistry.h"
82#include "qgsruntimeprofiler.h"
85#include "qgssensorregistry.h"
87#include "qgssettings.h"
89#include "qgssourcecache.h"
90#include "qgssqliteutils.h"
91#include "qgsstyle.h"
92#include "qgsstylemodel.h"
93#include "qgssvgcache.h"
95#include "qgssymbollayerutils.h"
96#include "qgstaskmanager.h"
99#include "qgsunittypes.h"
101#include "qgsuserprofile.h"
104
105#include <QAuthenticator>
106#include <QDir>
107#include <QFile>
108#include <QFileInfo>
109#include <QFileOpenEvent>
110#include <QIcon>
111#include <QImageReader>
112#include <QLibraryInfo>
113#include <QLocale>
114#include <QMessageBox>
115#include <QPalette>
116#include <QPixmap>
117#include <QProcess>
118#include <QProcessEnvironment>
119#include <QRecursiveMutex>
120#include <QRegularExpression>
121#include <QScreen>
122#include <QStandardPaths>
123#include <QString>
124#include <QStyle>
125#include <QTextStream>
126#include <QThreadPool>
127
128#include "moc_qgsapplication.cpp"
129
130using namespace Qt::StringLiterals;
131
133
135
137
139
141
142const QgsSettingsEntryInteger *QgsApplication::settingsConnectionPoolMaximumConcurrentConnections = new QgsSettingsEntryInteger( u"connection-pool-maximum-concurrent-connections"_s, QgsSettingsTree::sTreeCore, 4, QObject::tr( "Maximum number of concurrent connections per connection pool" ), Qgis::SettingsOptions(), 4, 999 );
143
144#ifndef Q_OS_WIN
145#include <netinet/in.h>
146#include <pwd.h>
147#else
148#include <winsock.h>
149#include <windows.h>
150#include <lmcons.h>
151#define SECURITY_WIN32
152#include <security.h>
153#ifdef _MSC_VER
154#pragma comment( lib, "Secur32.lib" )
155#endif
156#endif
157
158#include "qgsconfig.h"
159
160#include <gdal.h>
161#include <ogr_api.h>
162#include <cpl_conv.h> // for setting gdal options
163#include <sqlite3.h>
164#include <mutex>
165
166#include <proj.h>
167
168#if defined(Q_OS_LINUX)
169#include <sys/sysinfo.h>
170#endif
171
172#define CONN_POOL_MAX_CONCURRENT_CONNS 4
173
175{
176 std::unique_ptr<QgsSettingsRegistryCore > mSettingsRegistryCore;
177 std::unique_ptr<QgsCoordinateReferenceSystemRegistry > mCrsRegistry;
178 std::unique_ptr<Qgs3DRendererRegistry > m3DRendererRegistry;
179 std::unique_ptr<Qgs3DSymbolRegistry > m3DSymbolRegistry;
180 std::unique_ptr<QgsActionScopeRegistry > mActionScopeRegistry;
181 std::unique_ptr<QgsAnnotationRegistry > mAnnotationRegistry;
182 std::unique_ptr<QgsApplicationThemeRegistry > mApplicationThemeRegistry;
183 std::unique_ptr<QgsColorSchemeRegistry > mColorSchemeRegistry;
184 std::unique_ptr<QgsLocalizedDataPathRegistry > mLocalizedDataPathRegistry;
185 std::unique_ptr<QgsNumericFormatRegistry > mNumericFormatRegistry;
186 std::unique_ptr<QgsFieldFormatterRegistry > mFieldFormatterRegistry;
187 std::unique_ptr<QgsGpsConnectionRegistry > mGpsConnectionRegistry;
188 std::unique_ptr<QgsBabelFormatRegistry > mGpsBabelFormatRegistry;
189 std::unique_ptr<QgsNetworkContentFetcherRegistry > mNetworkContentFetcherRegistry;
190 std::unique_ptr<QgsScaleBarRendererRegistry > mScaleBarRendererRegistry;
191 std::unique_ptr<QgsLabelingEngineRuleRegistry > mLabelingEngineRuleRegistry;
192 std::unique_ptr<QgsValidityCheckRegistry > mValidityCheckRegistry;
193 std::unique_ptr<QgsMessageLog > mMessageLog;
194 std::unique_ptr<QgsPaintEffectRegistry > mPaintEffectRegistry;
195 std::unique_ptr<QgsPluginLayerRegistry > mPluginLayerRegistry;
196 std::unique_ptr<QgsClassificationMethodRegistry > mClassificationMethodRegistry;
197 std::unique_ptr<QgsProcessingRegistry > mProcessingRegistry;
198 std::unique_ptr<QgsConnectionRegistry > mConnectionRegistry;
199 std::unique_ptr<QgsProjectStorageRegistry > mProjectStorageRegistry;
200 std::unique_ptr<QgsLayerMetadataProviderRegistry > mLayerMetadataProviderRegistry;
201 std::unique_ptr<QgsExternalStorageRegistry > mExternalStorageRegistry;
202 std::unique_ptr<QgsProfileSourceRegistry > mProfileSourceRegistry;
203 std::unique_ptr<QgsPageSizeRegistry > mPageSizeRegistry;
204 std::unique_ptr<QgsRasterRendererRegistry > mRasterRendererRegistry;
205 std::unique_ptr<QgsRendererRegistry > mRendererRegistry;
206 std::unique_ptr<QgsPointCloudRendererRegistry > mPointCloudRendererRegistry;
207 std::unique_ptr<QgsTiledSceneRendererRegistry > mTiledSceneRendererRegistry;
208 std::unique_ptr<QgsSvgCache > mSvgCache;
209 std::unique_ptr<QgsImageCache > mImageCache;
210 std::unique_ptr<QgsSourceCache > mSourceCache;
211 std::unique_ptr<QgsSymbolLayerRegistry > mSymbolLayerRegistry;
212 std::unique_ptr<QgsCalloutRegistry > mCalloutRegistry;
213 std::unique_ptr<QgsTaskManager > mTaskManager;
214 std::unique_ptr<QgsLayoutItemRegistry > mLayoutItemRegistry;
215 std::unique_ptr<QgsAnnotationItemRegistry > mAnnotationItemRegistry;
216 std::unique_ptr<QgsSensorRegistry > mSensorRegistry;
217 std::unique_ptr<QgsPlotRegistry > mPlotRegistry;
218 std::unique_ptr<QgsBookmarkManager > mBookmarkManager;
219 std::unique_ptr<QgsTileDownloadManager > mTileDownloadManager;
220 std::unique_ptr<QgsStyleModel > mStyleModel;
221 std::unique_ptr<QgsRecentStyleHandler > mRecentStyleHandler;
222 std::unique_ptr<QgsDatabaseQueryLog > mQueryLogger;
223 std::unique_ptr<QgsFontManager > mFontManager;
225 QStringList mSvgPathCache;
226 bool mSvgPathCacheValid = false;
227
230};
231
232
233QObject *ABISYM( QgsApplication::mFileOpenEventReceiver ) = nullptr;
234bool ABISYM( QgsApplication::mInitialized ) = false;
235bool ABISYM( QgsApplication::mRunningFromBuildDir ) = false;
236const char *QgsApplication::QGIS_ORGANIZATION_NAME = "QGIS";
237const char *QgsApplication::QGIS_ORGANIZATION_DOMAIN = "qgis.org";
238const char *QgsApplication::QGIS_APPLICATION_NAME = "QGIS3";
239QgsApplication::ApplicationMembers *QgsApplication::sApplicationMembers = nullptr;
240QgsAuthManager *QgsApplication::sAuthManager = nullptr;
241int ABISYM( QgsApplication::sMaxThreads ) = -1;
242
243Q_GLOBAL_STATIC( QStringList, sFileOpenEventList )
244Q_GLOBAL_STATIC( QString, sPrefixPath )
245Q_GLOBAL_STATIC( QString, sPluginPath )
246Q_GLOBAL_STATIC( QString, sPkgDataPath )
247Q_GLOBAL_STATIC( QString, sLibraryPath )
248Q_GLOBAL_STATIC( QString, sLibexecPath )
249Q_GLOBAL_STATIC( QString, sQmlImportPath )
250Q_GLOBAL_STATIC( QString, sThemeName )
251Q_GLOBAL_STATIC( QString, sProfilePath )
252
253Q_GLOBAL_STATIC( QStringList, sDefaultSvgPaths )
254Q_GLOBAL_STATIC( QgsStringMap, sSystemEnvVars )
255Q_GLOBAL_STATIC( QString, sConfigPath )
256
257Q_GLOBAL_STATIC( QString, sBuildSourcePath )
258#if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
259Q_GLOBAL_STATIC( QString, sCfgIntDir )
260#endif
261Q_GLOBAL_STATIC( QString, sBuildOutputPath )
262Q_GLOBAL_STATIC( QStringList, sGdalSkipList )
263Q_GLOBAL_STATIC( QStringList, sDeferredSkippedGdalDrivers )
264Q_GLOBAL_STATIC( QString, sAuthDbDirPath )
265Q_GLOBAL_STATIC( QString, sAuthDbUri )
266
267Q_GLOBAL_STATIC( QString, sUserName )
268Q_GLOBAL_STATIC( QString, sUserFullName )
269Q_GLOBAL_STATIC_WITH_ARGS( QString, sPlatformName, ( "external" ) )
270Q_GLOBAL_STATIC( QString, sApplicationFullName )
271Q_GLOBAL_STATIC( QString, sTranslation )
272
273Q_GLOBAL_STATIC( QTemporaryDir, sIconCacheDir )
274
275QgsApplication::QgsApplication( int &argc, char **argv, bool GUIenabled, const QString &profileFolder, const QString &platformName )
276 : QApplication( argc, argv, GUIenabled )
277{
278 *sPlatformName() = platformName;
279
281
282 // Delay application members initialization in desktop app (In desktop app, profile folder is not known at this point)
283 if ( platformName != "desktop"_L1 )
284 {
285 mApplicationMembers = std::make_unique<ApplicationMembers>();
286 try
287 {
288 mApplicationMembers->mSettingsRegistryCore->migrateOldSettings();
289 }
290 catch ( QgsSettingsException &e )
291 {
292 QgsDebugError( u"Error migrating old settings: %1"_s.arg( e.what() ) );
293 }
294 }
295 else
296 {
297 *sProfilePath() = profileFolder;
298 }
299
300}
301
303{
304 qRegisterMetaType<QgsGeometry::Error>( "QgsGeometry::Error" );
305 qRegisterMetaType<QgsDatabaseQueryLogEntry>( "QgsDatabaseQueryLogEntry" );
306 qRegisterMetaType<QgsProcessingFeatureSourceDefinition>( "QgsProcessingFeatureSourceDefinition" );
307 qRegisterMetaType<QgsProcessingOutputLayerDefinition>( "QgsProcessingOutputLayerDefinition" );
308 qRegisterMetaType<Qgis::LayoutUnit>( "Qgis::LayoutUnit" );
309 qRegisterMetaType<QgsUnsetAttributeValue>( "QgsUnsetAttributeValue" );
310 qRegisterMetaType<QgsFeatureId>( "QgsFeatureId" );
311 qRegisterMetaType<QgsFields>( "QgsFields" );
312 qRegisterMetaType<QgsFeatureIds>( "QgsFeatureIds" );
313 qRegisterMetaType<QgsProperty>( "QgsProperty" );
314 qRegisterMetaType<QgsFeatureStoreList>( "QgsFeatureStoreList" );
315 qRegisterMetaType<Qgis::MessageLevel>( "Qgis::MessageLevel" );
316 qRegisterMetaType<Qgis::BrowserItemState>( "Qgis::BrowserItemState" );
317 qRegisterMetaType<Qgis::GpsFixStatus>( "Qgis::GpsFixStatus" );
318 qRegisterMetaType<QgsReferencedRectangle>( "QgsReferencedRectangle" );
319 qRegisterMetaType<QgsReferencedPointXY>( "QgsReferencedPointXY" );
320 qRegisterMetaType<QgsReferencedGeometry>( "QgsReferencedGeometry" );
321 qRegisterMetaType<Qgis::LayoutRenderFlags>( "Qgis::LayoutRenderFlags" );
322 qRegisterMetaType<QgsStyle::StyleEntity>( "QgsStyle::StyleEntity" );
323 qRegisterMetaType<QgsCoordinateReferenceSystem>( "QgsCoordinateReferenceSystem" );
324 qRegisterMetaType<QgsAuthManager::MessageLevel>( "QgsAuthManager::MessageLevel" );
325 qRegisterMetaType<QgsNetworkRequestParameters>( "QgsNetworkRequestParameters" );
326 qRegisterMetaType<QgsNetworkReplyContent>( "QgsNetworkReplyContent" );
327 qRegisterMetaType<QgsFeature>( "QgsFeature" );
328 qRegisterMetaType<QgsGeometry>( "QgsGeometry" );
329 qRegisterMetaType<QgsInterval>( "QgsInterval" );
330 qRegisterMetaType<QgsRectangle>( "QgsRectangle" );
331 qRegisterMetaType<QgsPointXY>( "QgsPointXY" );
332 qRegisterMetaType<QgsPoint>( "QgsPoint" );
333 qRegisterMetaType<QgsDatumTransform::GridDetails>( "QgsDatumTransform::GridDetails" );
334 qRegisterMetaType<QgsDatumTransform::TransformDetails>( "QgsDatumTransform::TransformDetails" );
335 qRegisterMetaType<QgsNewsFeedParser::Entry>( "QgsNewsFeedParser::Entry" );
336 qRegisterMetaType<QgsRectangle>( "QgsRectangle" );
337 qRegisterMetaType<QgsLocatorResult>( "QgsLocatorResult" );
338 qRegisterMetaType<QgsGradientColorRamp>( "QgsGradientColorRamp" );
339 qRegisterMetaType<QgsProcessingModelChildParameterSource>( "QgsProcessingModelChildParameterSource" );
340 qRegisterMetaType<QgsRemappingSinkDefinition>( "QgsRemappingSinkDefinition" );
341 qRegisterMetaType<QgsProcessingModelChildDependency>( "QgsProcessingModelChildDependency" );
342 qRegisterMetaType<QgsTextFormat>( "QgsTextFormat" );
343 qRegisterMetaType<QPainter::CompositionMode>( "QPainter::CompositionMode" );
344 qRegisterMetaType<QgsDateTimeRange>( "QgsDateTimeRange" );
345 qRegisterMetaType<QgsDoubleRange>( "QgsDoubleRange" );
346 qRegisterMetaType<QgsIntRange>( "QgsIntRange" );
347 qRegisterMetaType<QList<QgsMapLayer *>>( "QList<QgsMapLayer*>" );
348 qRegisterMetaType<QMap<QNetworkRequest::Attribute, QVariant>>( "QMap<QNetworkRequest::Attribute,QVariant>" );
349 qRegisterMetaType<QMap<QNetworkRequest::KnownHeaders, QVariant>>( "QMap<QNetworkRequest::KnownHeaders,QVariant>" );
350 qRegisterMetaType<QList<QNetworkReply::RawHeaderPair>>( "QList<QNetworkReply::RawHeaderPair>" );
351 qRegisterMetaType<QNetworkReply::NetworkError>( "QNetworkReply::NetworkError" );
352 qRegisterMetaType< QAuthenticator * >( "QAuthenticator*" );
353 qRegisterMetaType< QgsGpsInformation >( "QgsGpsInformation" );
354 qRegisterMetaType< QgsSensorThingsExpansionDefinition >( "QgsSensorThingsExpansionDefinition" );
355 qRegisterMetaType< QTimeZone >( "QTimeZone" );
356 qRegisterMetaType< QgsSelectiveMaskingSourceSet >( "QgsSelectiveMaskingSourceSet" );
357};
358
359void QgsApplication::init( QString profileFolder )
360{
361 // Initialize application members in desktop app (at this point, profile folder is known)
362 if ( platform() == "desktop"_L1 )
363 {
364 instance()->mApplicationMembers = std::make_unique<ApplicationMembers>();
365 try
366 {
367 instance()->mApplicationMembers->mSettingsRegistryCore->migrateOldSettings();
368 }
369 catch ( QgsSettingsException &e )
370 {
371 QgsDebugError( u"Error migrating old settings: %1"_s.arg( e.what() ) );
372 }
373 }
374
375 if ( profileFolder.isEmpty() )
376 {
377 if ( getenv( "QGIS_CUSTOM_CONFIG_PATH" ) )
378 {
379 profileFolder = getenv( "QGIS_CUSTOM_CONFIG_PATH" );
380 }
381 else
382 {
383 profileFolder = QStandardPaths::standardLocations( QStandardPaths::AppDataLocation ).value( 0 );
384 }
385 // This will normally get here for custom scripts that use QgsApplication.
386 // This doesn't get this hit for QGIS Desktop because we setup the profile via main
387 QString rootProfileFolder = QgsUserProfileManager::resolveProfilesFolder( profileFolder );
388 QgsUserProfileManager manager( rootProfileFolder );
389 std::unique_ptr< QgsUserProfile > profile = manager.getProfile();
390 profileFolder = profile->folder();
391 }
392
393 *sProfilePath() = profileFolder;
394
395 static std::once_flag sMetaTypesRegistered;
396 std::call_once( sMetaTypesRegistered, registerMetaTypes );
397
398 ( void ) resolvePkgPath();
399
400 if ( ABISYM( mRunningFromBuildDir ) )
401 {
402 // we run from source directory - not installed to destination (specified prefix)
403 *sPrefixPath() = QString(); // set invalid path
404#if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
405 setPluginPath( *sBuildOutputPath() + '/' + QString( QGIS_PLUGIN_SUBDIR ) + '/' + *sCfgIntDir() );
406#else
407 setPluginPath( *sBuildOutputPath() + '/' + QStringLiteral( QGIS_PLUGIN_SUBDIR ) );
408#endif
409 setPkgDataPath( *sBuildOutputPath() + u"/data"_s ); // in buildDir/data - used for: doc, resources, svg
410 *sLibraryPath() = *sBuildOutputPath() + '/' + QGIS_LIB_SUBDIR + '/';
411#if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
412 *sLibexecPath() = *sBuildOutputPath() + '/' + QGIS_LIBEXEC_SUBDIR + '/' + *sCfgIntDir() + '/';
413#else
414 *sLibexecPath() = *sBuildOutputPath() + '/' + QGIS_LIBEXEC_SUBDIR + '/';
415#endif
416#if defined( HAVE_QUICK )
417 *sQmlImportPath() = *sBuildOutputPath() + '/' + QGIS_QML_SUBDIR + '/';
418#endif
419 }
420 else
421 {
422 char *prefixPath = getenv( "QGIS_PREFIX_PATH" );
423 if ( !prefixPath )
424 {
425 if ( sPrefixPath()->isNull() )
426 {
427#if defined(Q_OS_WIN) || defined(Q_OS_MACOS) && !defined(QGIS_MAC_BUNDLE)
428 setPrefixPath( applicationDirPath(), true );
429#elif defined(QGIS_MAC_BUNDLE)
430 QDir myDir( applicationDirPath() + "/../.."_L1 );
431 setPrefixPath( myDir.absolutePath(), true );
432#elif defined(ANDROID)
433 // this is "/data/data/org.qgis.qgis" in android
434 QDir myDir( QDir::homePath() );
435 myDir.cdUp();
436 QString myPrefix = myDir.absolutePath();
437 setPrefixPath( myPrefix, true );
438#else
439 QDir myDir( applicationDirPath() );
440 // Fix for server which is one level deeper in /usr/lib/cgi-bin
441 if ( applicationDirPath().contains( u"cgi-bin"_s ) )
442 {
443 myDir.cdUp();
444 }
445 myDir.cdUp(); // Go from /usr/bin or /usr/lib (for server) to /usr
446 QString myPrefix = myDir.absolutePath();
447 setPrefixPath( myPrefix, true );
448#endif
449 }
450 }
451 else
452 {
453 setPrefixPath( prefixPath, true );
454 }
455 }
456
457 *sConfigPath() = profileFolder + '/'; // make sure trailing slash is included
458 *sDefaultSvgPaths() << qgisSettingsDirPath() + u"svg/"_s;
459
460 // Determine the auth DB URI, the first match wins:
461 // 1 - get it from QGIS_AUTH_DB_URI environment variable
462 // 2 - get it from QGIS_AUTH_DB_DIR_PATH environment variable, assume QSQLITE driver and add "qgis-auth.db"
463 // 3 - use the default path from settings dir path, assume QSQLITE and add "qgis-auth.db"
464 *sAuthDbDirPath() = qgisSettingsDirPath();
465
466 if ( getenv( "QGIS_AUTH_DB_DIR_PATH" ) )
467 {
468 setAuthDatabaseDirPath( getenv( "QGIS_AUTH_DB_DIR_PATH" ) );
469 sAuthDbUri()->clear();
470 }
471
472 if ( getenv( "QGIS_AUTH_DB_URI" ) )
473 {
474 *sAuthDbUri() = getenv( "QGIS_AUTH_DB_URI" );
475 }
476
477 // Default to sAuthDbDirPath
478 if ( sAuthDbUri->isEmpty() )
479 {
480 *sAuthDbUri() = u"QSQLITE://"_s + *sAuthDbDirPath() + u"qgis-auth.db"_s;
481 }
482
483 // force use of OpenGL renderer for Qt3d.
484 qputenv( "QT3D_RENDERER", "opengl" );
485
486 // store system environment variables passed to application, before they are adjusted
487 QMap<QString, QString> systemEnvVarMap;
488 QString passfile( u"QGIS_AUTH_PASSWORD_FILE"_s ); // QString, for comparison
489
490 const auto systemEnvironment = QProcessEnvironment::systemEnvironment().toStringList();
491 for ( const QString &varStr : systemEnvironment )
492 {
493 int pos = varStr.indexOf( '='_L1 );
494 if ( pos == -1 )
495 continue;
496 QString varStrName = varStr.left( pos );
497 QString varStrValue = varStr.mid( pos + 1 );
498 if ( varStrName != passfile )
499 {
500 systemEnvVarMap.insert( varStrName, varStrValue );
501 }
502 }
503 *sSystemEnvVars() = systemEnvVarMap;
504
505 // append local user-writable folder as a proj search path
506 QStringList currentProjSearchPaths = QgsProjUtils::searchPaths();
507 currentProjSearchPaths.append( qgisSettingsDirPath() + u"proj"_s );
508#ifdef Q_OS_MACOS
509 // Set bundled proj data path as env var, so it's also available for pyproj and subprocesses (e.g. processing algorithms)
510 const QString projData( QDir::cleanPath( pkgDataPath().append( "/proj" ) ) );
511 if ( QFile::exists( projData ) )
512 {
513 qputenv( "PROJ_DATA", projData.toUtf8() );
514 currentProjSearchPaths.append( projData );
515 }
516#endif // Q_OS_MACOS
517
518 char **newPaths = new char *[currentProjSearchPaths.length()];
519 for ( int i = 0; i < currentProjSearchPaths.count(); ++i )
520 {
521 newPaths[i] = CPLStrdup( currentProjSearchPaths.at( i ).toUtf8().constData() );
522 }
523 proj_context_set_search_paths( nullptr, currentProjSearchPaths.count(), newPaths );
524 for ( int i = 0; i < currentProjSearchPaths.count(); ++i )
525 {
526 CPLFree( newPaths[i] );
527 }
528 delete [] newPaths;
529
530 // allow Qt to search for Qt plugins (e.g. sqldrivers) in our plugin directory
531 QCoreApplication::addLibraryPath( pluginPath() );
532
533 // the default of 256 is not enough for QGIS
534 QImageReader::setAllocationLimit( 512 );
535
536 {
537 QgsScopedRuntimeProfile profile( tr( "Load user fonts" ) );
539 }
540
541 // set max. thread count to -1
542 // this should be read from QgsSettings but we don't know where they are at this point
543 // so we read actual value in main.cpp
544 ABISYM( sMaxThreads ) = -1;
545
546 {
547 QgsScopedRuntimeProfile profile( tr( "Load color schemes" ) );
550 }
551
552 {
553 QgsScopedRuntimeProfile profile( tr( "Load bookmarks" ) );
555 }
556
557 // trigger creation of default style, but defer initialization until
558 // it's actually required
559 QgsStyle *defaultStyle = QgsStyle::defaultStyle( false );
560 if ( !members()->mStyleModel )
561 members()->mStyleModel = std::make_unique<QgsStyleModel>( defaultStyle );
562
563 ABISYM( mInitialized ) = true;
564}
565
566
567void QgsApplication::installTranslators()
568{
569 // Remove translators if any are already installed
570 if ( mQgisTranslator )
571 {
572 removeTranslator( mQgisTranslator.get() );
573 mQgisTranslator.reset( );
574
575 }
576 if ( mQtTranslator )
577 {
578 removeTranslator( mQtTranslator.get() );
579 mQtTranslator.reset( );
580
581 }
582 if ( mQtBaseTranslator )
583 {
584 removeTranslator( mQtBaseTranslator.get() );
585 mQtBaseTranslator.reset( );
586
587 }
588
589 if ( *sTranslation() != "C"_L1 )
590 {
591 mQgisTranslator = std::make_unique<QTranslator>( this );
592 if ( mQgisTranslator->load( u"qgis_"_s + *sTranslation(), i18nPath() ) )
593 {
594 installTranslator( mQgisTranslator.get() );
595 }
596 else
597 {
598 QgsDebugMsgLevel( u"loading of qgis translation failed %1/qgis_%2"_s.arg( i18nPath(), *sTranslation() ), 2 );
599 }
600
601 /* Translation file for Qt.
602 * The strings from the QMenuBar context section are used by Qt/Mac to shift
603 * the About, Preferences and Quit items to the Mac Application menu.
604 * These items must be translated identically in both qt_ and qgis_ files.
605 */
606 QString qtTranslationsPath = QLibraryInfo::location( QLibraryInfo::TranslationsPath );
607#ifdef __MINGW32__
608 QString prefix = QDir( QString( "%1/../" ).arg( QApplication::applicationDirPath() ) ).absolutePath();
609 qtTranslationsPath = prefix + qtTranslationsPath.mid( QLibraryInfo::location( QLibraryInfo::PrefixPath ).length() );
610#endif
611
612 mQtTranslator = std::make_unique<QTranslator>( this );
613 if ( mQtTranslator->load( u"qt_"_s + *sTranslation(), qtTranslationsPath ) )
614 {
615 installTranslator( mQtTranslator.get() );
616 }
617 else
618 {
619 QgsDebugMsgLevel( u"loading of qt translation failed %1/qt_%2"_s.arg( qtTranslationsPath, *sTranslation() ), 2 );
620 }
621
622 mQtBaseTranslator = std::make_unique<QTranslator>( this );
623 if ( mQtBaseTranslator->load( u"qtbase_"_s + *sTranslation(), qtTranslationsPath ) )
624 {
625 installTranslator( mQtBaseTranslator.get() );
626 }
627 else
628 {
629 QgsDebugMsgLevel( u"loading of qtbase translation failed %1/qt_%2"_s.arg( qtTranslationsPath, *sTranslation() ), 2 );
630 }
631 }
632}
633
635{
636 if ( mApplicationMembers )
637 {
638 try
639 {
640 mApplicationMembers->mSettingsRegistryCore->backwardCompatibility();
641 }
642 catch ( QgsSettingsException &e )
643 {
644 QgsDebugError( u"An error occurred while performing backwards compatibility for settings: %1"_s.arg( e.what() ) );
645 }
646 }
647
648 // we do this here as well as in exitQgis() -- it's safe to call as often as we want,
649 // and there's just a *chance* that someone hasn't properly called exitQgis prior to
650 // this destructor...
651 invalidateCaches();
652}
653
654void QgsApplication::invalidateCaches()
655{
656 // invalidate coordinate cache while the PROJ context held by the thread-locale
657 // QgsProjContextStore object is still alive. Otherwise if this later object
658 // is destroyed before the static variables of the cache, we might use freed memory.
662}
663
665{
666 return qobject_cast<QgsApplication *>( QCoreApplication::instance() );
667}
668
670{
671 bool done = false;
672 if ( event->type() == QEvent::FileOpen )
673 {
674 // handle FileOpen event (double clicking a file icon in Mac OS X Finder)
675 if ( ABISYM( mFileOpenEventReceiver ) )
676 {
677 // Forward event to main window.
678 done = notify( ABISYM( mFileOpenEventReceiver ), event );
679 }
680 else
681 {
682 // Store filename because receiver has not registered yet.
683 // If QGIS has been launched by double clicking a file icon, FileOpen will be
684 // the first event; the main window is not yet ready to handle the event.
685 sFileOpenEventList()->append( static_cast<QFileOpenEvent *>( event )->file() );
686 done = true;
687 }
688 }
689 else
690 {
691 // pass other events to base class
692 done = QApplication::event( event );
693 }
694 return done;
695}
696
697bool QgsApplication::notify( QObject *receiver, QEvent *event )
698{
699 bool done = false;
700 // Crashes in customization (especially on Mac), if we're not in the main/UI thread, see #5597
701 if ( thread() == receiver->thread() )
702 emit preNotify( receiver, event, &done );
703
704 if ( done )
705 return true;
706
707 // Send event to receiver and catch unhandled exceptions
708 done = true;
709 try
710 {
711 done = QApplication::notify( receiver, event );
712 }
713 catch ( QgsException &e )
714 {
715 qCritical() << "Caught unhandled QgsException: " << e.what();
716 if ( qApp->thread() == QThread::currentThread() )
717 QMessageBox::critical( activeWindow(), tr( "Exception" ), e.what() );
718 }
719 catch ( std::exception &e )
720 {
721 qCritical() << "Caught unhandled std::exception: " << e.what();
722 if ( qApp->thread() == QThread::currentThread() )
723 QMessageBox::critical( activeWindow(), tr( "Exception" ), e.what() );
724 }
725 catch ( ... )
726 {
727 qCritical() << "Caught unhandled unknown exception";
728 if ( qApp->thread() == QThread::currentThread() )
729 QMessageBox::critical( activeWindow(), tr( "Exception" ), tr( "unknown exception" ) );
730 }
731
732 return done;
733}
734
736{
737 return QgsRuntimeProfiler::threadLocalInstance();
738}
739
741{
742 // Set receiver for FileOpen events
743 ABISYM( mFileOpenEventReceiver ) = receiver;
744 // Propagate any events collected before the receiver has registered.
745 if ( sFileOpenEventList()->count() > 0 )
746 {
747 const QStringList fileOpenEventList = *sFileOpenEventList();
748 for ( const QString &file : fileOpenEventList )
749 {
750 QFileOpenEvent foe( file );
751 QgsApplication::sendEvent( ABISYM( mFileOpenEventReceiver ), &foe );
752 }
753 sFileOpenEventList()->clear();
754 }
755}
756
757void QgsApplication::setPrefixPath( const QString &prefixPath, bool useDefaultPaths )
758{
759 *sPrefixPath() = prefixPath;
760#if defined(Q_OS_WIN)
761 if ( sPrefixPath()->endsWith( "/bin" ) )
762 {
763 sPrefixPath()->chop( 4 );
764 }
765#endif
766 if ( useDefaultPaths && !ABISYM( mRunningFromBuildDir ) )
767 {
768 setPluginPath( *sPrefixPath() + '/' + QStringLiteral( QGIS_PLUGIN_SUBDIR ) );
769 setPkgDataPath( *sPrefixPath() + '/' + QStringLiteral( QGIS_DATA_SUBDIR ) );
770 }
771 *sLibraryPath() = *sPrefixPath() + '/' + QGIS_LIB_SUBDIR + '/';
772 *sLibexecPath() = *sPrefixPath() + '/' + QGIS_LIBEXEC_SUBDIR + '/';
773#if defined( HAVE_QUICK )
774 *sQmlImportPath() = *sPrefixPath() + '/' + QGIS_QML_SUBDIR + '/';
775#endif
776}
777
779{
780 *sPluginPath() = pluginPath;
781}
782
784{
785 *sPkgDataPath() = pkgDataPath;
786
787 QString mySvgPath = pkgDataPath + u"/svg/"_s;
788
789 // avoid duplicate entries
790 if ( !sDefaultSvgPaths()->contains( mySvgPath ) )
791 *sDefaultSvgPaths() << mySvgPath;
792}
793
794void QgsApplication::setDefaultSvgPaths( const QStringList &pathList )
795{
796 *sDefaultSvgPaths() = pathList;
797}
798
799void QgsApplication::setAuthDatabaseDirPath( const QString &authDbDirPath )
800{
801 QFileInfo fi( authDbDirPath );
802 if ( fi.exists() && fi.isDir() && fi.isWritable() )
803 {
804 *sAuthDbDirPath() = fi.canonicalFilePath() + QDir::separator();
805 }
806}
807
809{
810#if 0
811 if ( ABISYM( mRunningFromBuildDir ) )
812 {
813 static bool sOnce = true;
814 if ( sOnce )
815 {
816 QgsMessageLogNotifyBlocker blockNotifications;
817 ( void ) blockNotifications;
818 qWarning( "!!! prefix path was requested, but it is not valid - we do not run from installed path !!!" );
819 }
820 sOnce = false;
821 }
822#endif
823
824 return *sPrefixPath();
825}
827{
828 return *sPluginPath();
829}
830
832{
833 if ( sPkgDataPath()->isNull() )
834 return resolvePkgPath();
835 else
836 return *sPkgDataPath();
837}
838
840{
841 return u":/images/themes/default/"_s;
842}
844{
845 QString usersThemes = userThemesFolder() + QDir::separator() + themeName() + QDir::separator() + "icons/";
846 QDir dir( usersThemes );
847 if ( dir.exists() )
848 {
849 return usersThemes;
850 }
851 else
852 {
853 QString defaultThemes = defaultThemesFolder() + QDir::separator() + themeName() + QDir::separator() + "icons/";
854 return defaultThemes;
855 }
856}
857
859{
860 return iconsPath() + u"qgis-icon-60x60.png"_s;
861}
862
864{
865 return ABISYM( sMaxThreads );
866}
867
868QString QgsApplication::iconPath( const QString &iconFile )
869{
870 // try active theme
871 QString path = activeThemePath();
872 if ( QFile::exists( path + iconFile ) )
873 return path + iconFile;
874
875 // use default theme
876 return defaultThemePath() + iconFile;
877}
878
879QIcon QgsApplication::getThemeIcon( const QString &name, const QColor &fillColor, const QColor &strokeColor )
880{
881 const QString cacheKey = ( name.startsWith( '/' ) ? name.mid( 1 ) : name )
882 + ( fillColor.isValid() ? u"_%1"_s.arg( fillColor.name( QColor::HexArgb ).mid( 1 ) ) : QString() )
883 + ( strokeColor.isValid() ? u"_%1"_s.arg( strokeColor.name( QColor::HexArgb ).mid( 1 ) ) : QString() );
884 QgsApplication *app = instance();
885 if ( app && app->mIconCache.contains( cacheKey ) )
886 return app->mIconCache.value( cacheKey );
887
888 QIcon icon;
889 const bool colorBased = fillColor.isValid() || strokeColor.isValid();
890
891 auto iconFromColoredSvg = [fillColor, strokeColor, cacheKey]( const QString & path ) -> QIcon
892 {
893 // sizes are unused here!
894 const QByteArray svgContent = QgsApplication::svgCache()->svgContent( path, 16, fillColor, strokeColor, 1, 1 );
895
896 const QString iconPath = sIconCacheDir()->filePath( cacheKey + u".svg"_s );
897 if ( const QDir dir = QFileInfo( iconPath ).dir(); !dir.exists() )
898 {
899 dir.mkpath( "." );
900 }
901
902 QFile f( iconPath );
903 if ( f.open( QFile::WriteOnly | QFile::Truncate ) )
904 {
905 f.write( svgContent );
906 f.close();
907 }
908 else
909 {
910 QgsDebugError( u"Could not create colorized icon svg at %1"_s.arg( iconPath ) );
911 return QIcon();
912 }
913
914 return QIcon( f.fileName() );
915 };
916
917 QString preferredPath = activeThemePath() + QDir::separator() + name;
918 QString defaultPath = defaultThemePath() + QDir::separator() + name;
919 if ( QFile::exists( preferredPath ) )
920 {
921 if ( colorBased )
922 {
923 icon = iconFromColoredSvg( preferredPath );
924 }
925 else
926 {
927 icon = QIcon( preferredPath );
928 }
929 }
930 else if ( QFile::exists( defaultPath ) )
931 {
932 //could still return an empty icon if it
933 //doesn't exist in the default theme either!
934 if ( colorBased )
935 {
936 icon = iconFromColoredSvg( defaultPath );
937 }
938 else
939 {
940 icon = QIcon( defaultPath );
941 }
942 }
943 else
944 {
945 icon = QIcon();
946 }
947
948 if ( app )
949 app->mIconCache.insert( cacheKey, icon );
950 return icon;
951}
952
954{
955 QgsApplication *app = instance();
956 if ( app && app->mCursorCache.contains( cursor ) )
957 return app->mCursorCache.value( cursor );
958
959 // All calculations are done on 32x32 icons
960 // Defaults to center, individual cursors may override
961 int activeX = 16;
962 int activeY = 16;
963
964 QString name;
965 switch ( cursor )
966 {
967 case ZoomIn:
968 name = u"mZoomIn.svg"_s;
969 activeX = 13;
970 activeY = 13;
971 break;
972 case ZoomOut:
973 name = u"mZoomOut.svg"_s;
974 activeX = 13;
975 activeY = 13;
976 break;
977 case Identify:
978 activeX = 3;
979 activeY = 6;
980 name = u"mIdentify.svg"_s;
981 break;
982 case CrossHair:
983 name = u"mCrossHair.svg"_s;
984 break;
985 case CapturePoint:
986 name = u"mCapturePoint.svg"_s;
987 break;
988 case Select:
989 name = u"mSelect.svg"_s;
990 activeX = 6;
991 activeY = 6;
992 break;
993 case Sampler:
994 activeX = 5;
995 activeY = 5;
996 name = u"mSampler.svg"_s;
997 break;
998 // No default
999 }
1000 // It should never get here!
1001 Q_ASSERT( ! name.isEmpty( ) );
1002
1003 QIcon icon = getThemeIcon( u"cursors"_s + QDir::separator() + name );
1004 QCursor cursorIcon;
1005 // Check if an icon exists for this cursor (the O.S. default cursor will be used if it does not)
1006 if ( ! icon.isNull( ) )
1007 {
1008 // Apply scaling
1009 float scale = Qgis::UI_SCALE_FACTOR * QgsApplication::fontMetrics().height() / 32.0;
1010 cursorIcon = QCursor( icon.pixmap( std::ceil( scale * 32 ), std::ceil( scale * 32 ) ), std::ceil( scale * activeX ), std::ceil( scale * activeY ) );
1011 }
1012 if ( app )
1013 app->mCursorCache.insert( cursor, cursorIcon );
1014 return cursorIcon;
1015}
1016
1017// TODO: add some caching mechanism ?
1018QPixmap QgsApplication::getThemePixmap( const QString &name, const QColor &foreColor, const QColor &backColor, const int size )
1019{
1020 const QString preferredPath = activeThemePath() + QDir::separator() + name;
1021 const QString defaultPath = defaultThemePath() + QDir::separator() + name;
1022 const QString path = QFile::exists( preferredPath ) ? preferredPath : defaultPath;
1023 if ( foreColor.isValid() || backColor.isValid() )
1024 {
1025 bool fitsInCache = false;
1026 const QImage image = svgCache()->svgAsImage( path, size, backColor, foreColor, 1, 1, fitsInCache );
1027 return QPixmap::fromImage( image );
1028 }
1029
1030 return QPixmap( path );
1031}
1032
1034{
1035 *sThemeName() = themeName;
1036}
1037
1039{
1040 static QString appPath;
1041 if ( appPath.isNull() )
1042 {
1043 if ( QCoreApplication::instance() )
1044 {
1045 appPath = applicationDirPath();
1046 }
1047 else
1048 {
1049 qWarning( "Application path not initialized" );
1050 }
1051 }
1052
1053 if ( !appPath.isNull() || getenv( "QGIS_PREFIX_PATH" ) )
1054 {
1055 QString prefix = getenv( "QGIS_PREFIX_PATH" ) ? getenv( "QGIS_PREFIX_PATH" ) : appPath;
1056
1057 // check if QGIS is run from build directory (not the install directory)
1058 QFile f;
1059 // "/../../.." is for Mac bundled app in build directory
1060 static const QStringList paths { QStringList() << QString() << u"/.."_s << u"/bin"_s << u"/../../.."_s };
1061 for ( const QString &path : paths )
1062 {
1063 f.setFileName( prefix + path + "/qgisbuildpath.txt" );
1064 if ( f.exists() )
1065 break;
1066 }
1067 if ( f.exists() && f.open( QIODevice::ReadOnly ) )
1068 {
1069 ABISYM( mRunningFromBuildDir ) = true;
1070 *sBuildSourcePath() = f.readLine().trimmed();
1071 *sBuildOutputPath() = f.readLine().trimmed();
1072 QgsDebugMsgLevel( u"Running from build directory!"_s, 4 );
1073 QgsDebugMsgLevel( u"- source directory: %1"_s.arg( sBuildSourcePath()->toUtf8().constData() ), 4 );
1074 QgsDebugMsgLevel( u"- output directory of the build: %1"_s.arg( sBuildOutputPath()->toUtf8().constData() ), 4 );
1075#if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
1076 *sCfgIntDir() = prefix.split( '/', Qt::SkipEmptyParts ).last();
1077 qDebug( "- cfg: %s", sCfgIntDir()->toUtf8().constData() );
1078#endif
1079 }
1080 }
1081
1082 QString prefixPath;
1083 if ( getenv( "QGIS_PREFIX_PATH" ) )
1084 prefixPath = getenv( "QGIS_PREFIX_PATH" );
1085 else
1086 {
1087#if defined(ANDROID)
1088 // this is "/data/data/org.qgis.qgis" in android
1089 QDir dir( QDir::homePath() );
1090 dir.cdUp();
1091 prefixPath = dir.absolutePath();
1092#else
1093
1094#if defined(Q_OS_MACOS)
1095 prefixPath = appPath;
1096#elif defined(Q_OS_WIN)
1097 prefixPath = appPath;
1098 if ( prefixPath.endsWith( "/bin" ) )
1099 prefixPath.chop( 4 );
1100#else
1101 QDir dir( appPath );
1102 // Fix for server which is one level deeper in /usr/lib/cgi-bin
1103 if ( appPath.contains( u"cgi-bin"_s ) )
1104 {
1105 dir.cdUp();
1106 }
1107 dir.cdUp(); // Go from /usr/bin or /usr/lib (for server) to /usr
1108 prefixPath = dir.absolutePath();
1109#endif
1110#endif
1111 }
1112
1113 if ( ABISYM( mRunningFromBuildDir ) )
1114 return *sBuildOutputPath() + u"/data"_s;
1115 else
1116 return prefixPath + '/' + QStringLiteral( QGIS_DATA_SUBDIR );
1117}
1118
1120{
1121 return *sThemeName();
1122}
1123
1125{
1126 // Loop all style sheets, find matching name, load it.
1127 const QString path = applicationThemeRegistry()->themeFolder( themeName );
1128 if ( themeName == "default"_L1 || path.isEmpty() )
1129 {
1130 setThemeName( u"default"_s );
1131 qApp->setStyleSheet( QString() );
1133 return;
1134 }
1135
1136 QFile file( path + "/style.qss" );
1137 QFile variablesfile( path + "/variables.qss" );
1138 QFileInfo variableInfo( variablesfile );
1139
1140 if ( !file.open( QIODevice::ReadOnly ) || ( variableInfo.exists() && !variablesfile.open( QIODevice::ReadOnly ) ) )
1141 {
1142 qApp->setStyleSheet( QString() );
1144 return;
1145 }
1146
1147 QFile palettefile( path + "/palette.txt" );
1148 QFileInfo paletteInfo( palettefile );
1149 if ( paletteInfo.exists() && palettefile.open( QIODevice::ReadOnly ) )
1150 {
1151 QPalette pal = qApp->palette();
1152 QTextStream in( &palettefile );
1153 while ( !in.atEnd() )
1154 {
1155 QString line = in.readLine();
1156 QStringList parts = line.split( ':' );
1157 if ( parts.count() == 2 )
1158 {
1159 int role = parts.at( 0 ).trimmed().toInt();
1160 QColor color = QgsSymbolLayerUtils::decodeColor( parts.at( 1 ).trimmed() );
1161 pal.setColor( static_cast< QPalette::ColorRole >( role ), color );
1162 }
1163 }
1164 palettefile.close();
1165 qApp->setPalette( pal );
1166 }
1167
1168 QString styledata = file.readAll();
1169 styledata.replace( "@theme_path"_L1, path );
1170
1171 if ( variableInfo.exists() )
1172 {
1173 QTextStream in( &variablesfile );
1174 while ( !in.atEnd() )
1175 {
1176 QString line = in.readLine();
1177 // This is a variable
1178 if ( line.startsWith( '@' ) )
1179 {
1180 int index = line.indexOf( ':' );
1181 QString name = line.mid( 0, index );
1182 QString value = line.mid( index + 1, line.length() );
1183 styledata.replace( name, value );
1184 }
1185 }
1186 variablesfile.close();
1187 }
1188 file.close();
1189
1190 if ( Qgis::UI_SCALE_FACTOR != 1.0 )
1191 {
1192 // apply OS-specific UI scale factor to stylesheet's em values
1193 int index = 0;
1194 const static QRegularExpression regex( u"(?<=[\\s:])([0-9\\.]+)(?=em)"_s );
1195 QRegularExpressionMatch match = regex.match( styledata, index );
1196 while ( match.hasMatch() )
1197 {
1198 index = match.capturedStart();
1199 styledata.remove( index, match.captured( 0 ).length() );
1200 QString number = QString::number( match.captured( 0 ).toDouble() * Qgis::UI_SCALE_FACTOR );
1201 styledata.insert( index, number );
1202 index += number.length();
1203 match = regex.match( styledata, index );
1204 }
1205 }
1206
1207 qApp->setStyleSheet( styledata );
1208
1211}
1212
1213QHash<QString, QString> QgsApplication::uiThemes()
1214{
1215 QHash<QString, QString> mapping = applicationThemeRegistry()->themeFolders();
1216 mapping.insert( u"default"_s, QString() );
1217 return mapping;
1218}
1219
1221{
1222 return pkgDataPath() + u"/doc/AUTHORS"_s;
1223}
1224
1226{
1227 return pkgDataPath() + u"/doc/CONTRIBUTORS"_s;
1228}
1229
1231{
1232 return pkgDataPath() + u"/doc/SPONSORS"_s;
1233}
1234
1236{
1237 return pkgDataPath() + u"/doc/DONORS"_s;
1238}
1239
1241{
1242 return pkgDataPath() + u"/doc/TRANSLATORS"_s;
1243}
1244
1246{
1247 return pkgDataPath() + u"/doc/LICENSE"_s;
1248}
1249
1251{
1252 if ( ABISYM( mRunningFromBuildDir ) )
1253 return *sBuildOutputPath() + u"/i18n/"_s;
1254 else
1255 return pkgDataPath() + u"/i18n/"_s;
1256}
1257
1259{
1260 return pkgDataPath() + u"/resources/metadata-ISO/"_s;
1261}
1262
1264{
1265 return pkgDataPath() + u"/resources/qgis.db"_s;
1266}
1267
1269{
1270 return *sConfigPath();
1271}
1272
1274{
1275 return qgisSettingsDirPath() + u"qgis.db"_s;
1276}
1277
1279{
1280 return *sAuthDbDirPath() + u"qgis-auth.db"_s;
1281}
1282
1284{
1285 return *sAuthDbUri();
1286}
1287
1289{
1290 return u":/images/splash/"_s;
1291}
1292
1294{
1295 return pkgDataPath() + u"/images/icons/"_s;
1296}
1297
1299{
1300 if ( ABISYM( mRunningFromBuildDir ) )
1301 {
1302 QString tempCopy = QDir::tempPath() + "/srs6.db";
1303
1304 if ( !QFile( tempCopy ).exists() )
1305 {
1306 QFile f( buildSourcePath() + "/resources/srs6.db" );
1307 if ( !f.copy( tempCopy ) )
1308 {
1309 qFatal( "Could not create temporary copy" );
1310 }
1311 }
1312
1313 return tempCopy;
1314 }
1315 else
1316 {
1317 return pkgDataPath() + u"/resources/srs.db"_s;
1318 }
1319}
1320
1321void QgsApplication::setSvgPaths( const QStringList &svgPaths )
1322{
1324 members()->mSvgPathCacheValid = false;
1325}
1326
1328{
1329 static QReadWriteLock lock;
1330
1332
1333 if ( members()->mSvgPathCacheValid )
1334 {
1335 return members()->mSvgPathCache;
1336 }
1337 else
1338 {
1340 //local directories to search when looking for an SVG with a given basename
1341 //defined by user in options dialog
1342 const QStringList pathList = settingsSearchPathsForSVG->value();
1343
1344 // maintain user set order while stripping duplicates
1345 QStringList paths;
1346 for ( const QString &path : pathList )
1347 {
1348 if ( !paths.contains( path ) )
1349 paths.append( path );
1350 }
1351 for ( const QString &path : std::as_const( *sDefaultSvgPaths() ) )
1352 {
1353 if ( !paths.contains( path ) )
1354 paths.append( path );
1355 }
1356 members()->mSvgPathCache = paths;
1357
1358 return paths;
1359 }
1360}
1361
1363{
1364 //local directories to search when looking for an template with a given basename
1365 //defined by user in options dialog
1367}
1368
1369QMap<QString, QString> QgsApplication::systemEnvVars()
1370{
1371 return *sSystemEnvVars();
1372}
1373
1375{
1376 return qgisSettingsDirPath() + u"symbology-style.db"_s;
1377}
1378
1380{
1381 const thread_local QRegularExpression regexp( QRegularExpression::anchoredPattern( u"^[A-Za-z][A-Za-z0-9\\._-]*"_s ) );
1382 return regexp;
1383}
1384
1386{
1387 if ( !sUserName()->isEmpty() )
1388 return *sUserName();
1389
1390#ifdef _MSC_VER
1391 TCHAR name [ UNLEN + 1 ];
1392 DWORD size = UNLEN + 1;
1393
1394 if ( GetUserName( ( TCHAR * )name, &size ) )
1395 {
1396 *sUserName() = QString::fromWCharArray( name );
1397 }
1398
1399
1400#elif QT_CONFIG(process)
1401 QProcess process;
1402
1403 process.start( u"whoami"_s, QStringList() );
1404 process.waitForFinished();
1405 *sUserName() = process.readAllStandardOutput().trimmed();
1406#endif
1407
1408 if ( !sUserName()->isEmpty() )
1409 return *sUserName();
1410
1411 //backup plan - use environment variables
1412 *sUserName() = qgetenv( "USER" );
1413 if ( !sUserName()->isEmpty() )
1414 return *sUserName();
1415
1416 //last resort
1417 *sUserName() = qgetenv( "USERNAME" );
1418 return *sUserName();
1419}
1420
1422{
1423 if ( !sUserFullName()->isEmpty() )
1424 return *sUserFullName();
1425
1426#ifdef _MSC_VER
1427 TCHAR name [ UNLEN + 1 ];
1428 DWORD size = UNLEN + 1;
1429
1430 //note - this only works for accounts connected to domain
1431 if ( GetUserNameEx( NameDisplay, ( TCHAR * )name, &size ) )
1432 {
1433 *sUserFullName() = QString::fromWCharArray( name );
1434 }
1435
1436 //fall back to login name
1437 if ( sUserFullName()->isEmpty() )
1438 *sUserFullName() = userLoginName();
1439#elif defined(Q_OS_ANDROID) || defined(__MINGW32__)
1440 *sUserFullName() = u"Not available"_s;
1441#else
1442 struct passwd *p = getpwuid( getuid() );
1443
1444 if ( p )
1445 {
1446 QString gecosName = QString( p->pw_gecos );
1447 *sUserFullName() = gecosName.left( gecosName.indexOf( ',', 0 ) );
1448 }
1449
1450#endif
1451
1452 return *sUserFullName();
1453}
1454
1456{
1457#if defined(Q_OS_ANDROID)
1458 return "android"_L1;
1459#elif defined(Q_OS_MAC)
1460 return "osx"_L1;
1461#elif defined(Q_OS_WIN)
1462 return "windows"_L1;
1463#elif defined(Q_OS_LINUX)
1464 return u"linux"_s;
1465#elif defined(Q_OS_FREEBSD)
1466 return u"freebsd"_s;
1467#elif defined(Q_OS_OPENBSD)
1468 return u"openbsd"_s;
1469#elif defined(Q_OS_NETBSD)
1470 return u"netbsd"_s;
1471#elif defined(Q_OS_UNIX)
1472 return "unix"_L1;
1473#else
1474 return "unknown"_L1;
1475#endif
1476}
1477
1479{
1480 // Bytes to Mb (using 1024 * 1024)
1481 return static_cast<int>( CPLGetUsablePhysicalRAM() / 1048576 );
1482}
1483
1485{
1486 return *sPlatformName();
1487}
1488
1490{
1491 if ( !sApplicationFullName()->isEmpty() )
1492 return *sApplicationFullName();
1493
1494 //use environment variables
1495 *sApplicationFullName() = qgetenv( "QGIS_APPLICATION_FULL_NAME" );
1496 if ( !sApplicationFullName()->isEmpty() )
1497 return *sApplicationFullName();
1498
1499 //last resort
1500 QgsSettings settings;
1501 *sApplicationFullName() = settings.value(
1502 u"/qgis/application_full_name"_s,
1503 u"%1 %2"_s.arg( applicationName(), platform() )
1504 ).toString();
1505 return *sApplicationFullName();
1506}
1507
1509{
1510 if ( settingsLocaleOverrideFlag->value() )
1511 {
1512 QString locale = settingsLocaleUserLocale->value();
1513 // don't differentiate en_US and en_GB
1514 if ( locale.startsWith( "en"_L1, Qt::CaseInsensitive ) )
1515 {
1516 return locale.left( 2 );
1517 }
1518
1519 return locale;
1520 }
1521 else
1522 {
1523 return QLocale().name().left( 2 );
1524 }
1525}
1526
1527void QgsApplication::setLocale( const QLocale &locale )
1528{
1529 QLocale::setDefault( locale );
1530 emit instance()->localeChanged();
1531}
1532
1534{
1535 return qgisSettingsDirPath() + u"/themes"_s;
1536}
1537
1539{
1540 return pkgDataPath() + u"/resources/symbology-style.xml"_s;
1541}
1542
1544{
1545 return pkgDataPath() + u"/resources/themes"_s;
1546}
1547
1549{
1550 return pkgDataPath() + u"/resources/server/"_s;
1551}
1552
1554{
1555 return *sLibraryPath();
1556}
1557
1559{
1560 return *sLibexecPath();
1561}
1562
1564{
1565 return *sQmlImportPath();
1566}
1567
1569{
1570 return ( htonl( 1 ) == 1 ) ? XDR : NDR;
1571}
1572
1574{
1575 if ( !ABISYM( mInitialized ) && QgsApplication::instance() )
1576 {
1577 init( *sProfilePath() );
1578 }
1579
1580 // set the provider plugin path (this creates provider registry)
1582
1583 // create data item provider registry
1585
1586 // create project instance if doesn't exist
1587 QgsProject::instance(); // skip-keyword-check
1588
1589 // Setup authentication manager for lazy initialization
1591
1592 // Make sure we have a NAM created on the main thread.
1593 // Note that this might call QgsApplication::authManager to
1594 // setup the proxy configuration that's why it needs to be
1595 // called after the QgsAuthManager instance has been created
1597
1598}
1599
1601{
1602 if ( auto *lInstance = instance() )
1603 {
1604 if ( !lInstance->mAuthManager )
1605 {
1606 lInstance->mAuthManager = QgsAuthManager::instance();
1607 }
1608 return lInstance->mAuthManager;
1609 }
1610 else
1611 {
1612 // no QgsApplication instance
1613 if ( !sAuthManager )
1614 sAuthManager = QgsAuthManager::instance();
1615 return sAuthManager;
1616 }
1617}
1618
1623
1624
1626{
1627 // make sure all threads are done before exiting
1628 QThreadPool::globalInstance()->waitForDone();
1629
1630 // don't create to delete
1631 if ( auto *lInstance = instance() )
1632 delete lInstance->mAuthManager;
1633 else
1634 delete sAuthManager;
1635
1636 //Ensure that all remaining deleteLater QObjects are actually deleted before we exit.
1637 QgsApplication::sendPostedEvents( nullptr, QEvent::DeferredDelete );
1638
1639 //delete all registered functions from expression engine (see above comment)
1641
1642 // avoid creating instance just to delete it!
1643 if ( QgsProject::sProject )
1644 delete QgsProject::instance(); // skip-keyword-check
1645
1646 //Ensure that providers/layers which called deleteLater on objects as part of their cleanup
1647 //result in fully deleted objects before we do the provider registry cleanup.
1648 //E.g. the QgsOgrConnPool instance has deleteLater calls when unrefing layers, so clearing
1649 //the project above has not yet fully cleaned up OGR objects, which we MUST do before
1650 //cleaning up the provider
1651 QgsApplication::sendPostedEvents( nullptr, QEvent::DeferredDelete );
1652
1653 // avoid creating instance just to delete it!
1654 if ( QgsProviderRegistry::exists() )
1656
1657 invalidateCaches();
1658
1660
1661 // tear-down GDAL/OGR, but only if there are no remaining opened
1662 // datasets (cf https://github.com/qgis/QGIS/issues/58724)
1663 // Outputting to stdin is obviously absurd, but intended here, since
1664 // we are just interested in the count of still open datasets.
1665 if ( GDALDumpOpenDatasets( stdin ) == 0 )
1666 {
1667 OGRCleanupAll();
1668 GDALDestroyDriverManager();
1669 }
1670 else
1671 QgsDebugMsgLevel( u"Skipping call to GDALDestroyDriverManager() due to still opened datasets"_s, 5 );
1672}
1673
1675{
1676 QString myEnvironmentVar( getenv( "QGIS_PREFIX_PATH" ) );
1677 QString myState = tr( "QgsApplication state:\n"
1678 " - QGIS_PREFIX_PATH env var: %1\n"
1679 " - Prefix: %2\n"
1680 " - Plugin Path: %3\n"
1681 " - Package Data Path: %4\n"
1682 " - Active Theme Name: %5\n"
1683 " - Active Theme Path: %6\n"
1684 " - Default Theme Path: %7\n"
1685 " - SVG Search Paths: %8\n"
1686 " - User DB Path: %9\n"
1687 " - Auth DB Path: %10\n" )
1688 .arg( myEnvironmentVar,
1689 prefixPath(),
1690 pluginPath(),
1691 pkgDataPath(),
1692 themeName(),
1695 svgPaths().join( tr( "\n ", "match indentation of application state" ) ),
1697 .arg( QgsAuthManager::instance()->authenticationDatabaseUriStripped() );
1698 return myState;
1699}
1700
1702{
1703 //
1704 // Make the style sheet desktop preferences aware by using qapplication
1705 // palette as a basis for colors where appropriate
1706 //
1707 // QColor myColor1 = palette().highlight().color();
1708 QColor myColor1( Qt::lightGray );
1709 QColor myColor2 = myColor1;
1710 myColor2 = myColor2.lighter( 110 ); //10% lighter
1711 QString myStyle;
1712 myStyle = QStringLiteral( ".overview{"
1713 " font: 1.82em;"
1714 " font-weight: bold;"
1715 "}"
1716 "body{"
1717 " background: white;"
1718 " color: black;"
1719 " font-family: 'Lato', 'Open Sans', 'Lucida Grande', 'Segoe UI', 'Arial', sans-serif;"
1720 " width: 100%;"
1721 "}"
1722 "h1{ background-color: #F6F6F6;"
1723 " color: #589632; " // from https://qgis.org/styleguide/
1724 " font-size: x-large; "
1725 " font-weight: normal;"
1726 " background: none;"
1727 " padding: 0.75em 0 0;"
1728 " margin: 0;"
1729 " line-height: 3em;"
1730 "}"
1731 "h2{ background-color: #F6F6F6;"
1732 " color: #589632; " // from https://qgis.org/styleguide/
1733 " font-size: medium; "
1734 " font-weight: normal;"
1735 " background: none;"
1736 " padding: 0.75em 0 0;"
1737 " margin: 0;"
1738 " line-height: 1.1em;"
1739 "}"
1740 "h3{ background-color: #F6F6F6;"
1741 " color: #93b023;" // from https://qgis.org/styleguide/
1742 " font-weight: bold;"
1743 " font-size: large;"
1744 " text-align: left;"
1745 " border-bottom: 5px solid #DCEB5C;"
1746 "}"
1747 "h4{ background-color: #F6F6F6;"
1748 " color: #93b023;" // from https://qgis.org/styleguide/
1749 " font-weight: bold;"
1750 " font-size: medium;"
1751 " text-align: left;"
1752 "}"
1753 "h5{ background-color: #F6F6F6;"
1754 " color: #93b023;" // from https://qgis.org/styleguide/
1755 " font-weight: bold;"
1756 " font-size: small;"
1757 " text-align: left;"
1758 "}"
1759 "a{ color: #729FCF;"
1760 " font-family: arial,sans-serif;"
1761 "}"
1762 "label{ background-color: #FFFFCC;"
1763 " border: 1px solid black;"
1764 " margin: 1px;"
1765 " padding: 0px 3px; "
1766 " font-size: small;"
1767 "}"
1768 "th .strong {"
1769 " font-weight: bold;"
1770 "}"
1771 "hr {"
1772 " border: 0;"
1773 " height: 0;"
1774 " border-top: 1px solid black;"
1775 "}"
1776 ".list-view .highlight {"
1777 " text-align: left;"
1778 " border: 0px;"
1779 " width: 20%;"
1780 " padding-right: 15px;"
1781 " padding-left: 20px;"
1782 " font-weight: bold;"
1783 "}"
1784 ".tabular-view .odd-row {"
1785 " background-color: #f9f9f9;"
1786 "}"
1787 ".section {"
1788 " font-weight: bold;"
1789 " padding-top:25px;"
1790 "}" );
1791
1792 // We have some subtle differences between Qt based style and QWebKit style
1793 switch ( styleSheetType )
1794 {
1795 case StyleSheetType::Qt:
1796 myStyle += QStringLiteral(
1797 ".tabular-view{ "
1798 " border-collapse: collapse;"
1799 " width: 95%;"
1800 "}"
1801 ".tabular-view th, .tabular-view td { "
1802 " border:1px solid black;"
1803 "}" );
1804 break;
1805
1807 myStyle += QStringLiteral(
1808 "body { "
1809 " margin: auto;"
1810 " width: 97%;"
1811 "}"
1812 "table.tabular-view, table.list-view { "
1813 " border-collapse: collapse;"
1814 " table-layout:fixed;"
1815 " width: 100% !important;"
1816 " font-size: 90%;"
1817 "}"
1818 // Override
1819 "h1 { "
1820 " line-height: inherit;"
1821 "}"
1822 "td, th {"
1823 " word-wrap: break-word; "
1824 " vertical-align: top;"
1825 "}"
1826 // Set first column width
1827 ".list-view th:first-child, .list-view td:first-child {"
1828 " width: 20%;"
1829 "}"
1830 ".list-view.highlight { "
1831 " padding-left: inherit; "
1832 "}"
1833 // Set first column width for inner tables
1834 ".tabular-view th:first-child, .tabular-view td:first-child { "
1835 " width: 20%; "
1836 "}"
1837 // Makes titles bg stand up
1838 ".tabular-view th.strong { "
1839 " background-color: #eee; "
1840 "}"
1841 // Give some visual appearance to those ugly nested tables
1842 ".tabular-view th, .tabular-view td { "
1843 " border: 1px solid #eee;"
1844 "}"
1845 );
1846 break;
1847 }
1848
1849 return myStyle;
1850}
1851
1853{
1854 if ( 0 >= OGRGetDriverCount() )
1855 {
1856 OGRRegisterAll();
1857 }
1858}
1859
1860QString QgsApplication::absolutePathToRelativePath( const QString &aPath, const QString &targetPath )
1861{
1862 QString aPathUrl = aPath;
1863 QString tPathUrl = targetPath;
1864#if defined( Q_OS_WIN )
1865 const Qt::CaseSensitivity cs = Qt::CaseInsensitive;
1866
1867 aPathUrl.replace( '\\', '/' );
1868 if ( aPathUrl.startsWith( "//" ) )
1869 {
1870 // keep UNC prefix
1871 aPathUrl = "\\\\" + aPathUrl.mid( 2 );
1872 }
1873
1874 tPathUrl.replace( '\\', '/' );
1875 if ( tPathUrl.startsWith( "//" ) )
1876 {
1877 // keep UNC prefix
1878 tPathUrl = "\\\\" + tPathUrl.mid( 2 );
1879 }
1880#else
1881 const Qt::CaseSensitivity cs = Qt::CaseSensitive;
1882#endif
1883
1884 QStringList targetElems = tPathUrl.split( '/', Qt::SkipEmptyParts );
1885 QStringList aPathElems = aPathUrl.split( '/', Qt::SkipEmptyParts );
1886
1887 targetElems.removeAll( u"."_s );
1888 aPathElems.removeAll( u"."_s );
1889
1890 // remove common part
1891 int n = 0;
1892 while ( !aPathElems.isEmpty() &&
1893 !targetElems.isEmpty() &&
1894 aPathElems[0].compare( targetElems[0], cs ) == 0 )
1895 {
1896 aPathElems.removeFirst();
1897 targetElems.removeFirst();
1898 n++;
1899 }
1900
1901 if ( n == 0 )
1902 {
1903 // no common parts; might not even be a file
1904 return aPathUrl;
1905 }
1906
1907 if ( !targetElems.isEmpty() )
1908 {
1909 // go up to the common directory
1910 for ( int i = 0; i < targetElems.size(); i++ )
1911 {
1912 aPathElems.insert( 0, u".."_s );
1913 }
1914 }
1915 else
1916 {
1917 // let it start with . nevertheless,
1918 // so relative path always start with either ./ or ../
1919 aPathElems.insert( 0, u"."_s );
1920 }
1921
1922 return aPathElems.join( '/'_L1 );
1923}
1924
1925QString QgsApplication::relativePathToAbsolutePath( const QString &rpath, const QString &targetPath )
1926{
1927 // relative path should always start with ./ or ../
1928 if ( !rpath.startsWith( "./"_L1 ) && !rpath.startsWith( "../"_L1 ) )
1929 {
1930 return rpath;
1931 }
1932
1933 QString rPathUrl = rpath;
1934 QString targetPathUrl = targetPath;
1935
1936#if defined(Q_OS_WIN)
1937 rPathUrl.replace( '\\', '/' );
1938 targetPathUrl.replace( '\\', '/' );
1939
1940 bool uncPath = targetPathUrl.startsWith( "//" );
1941#endif
1942
1943 QStringList srcElems = rPathUrl.split( '/', Qt::SkipEmptyParts );
1944 QStringList targetElems = targetPathUrl.split( '/', Qt::SkipEmptyParts );
1945
1946#if defined(Q_OS_WIN)
1947 if ( uncPath )
1948 {
1949 targetElems.insert( 0, "" );
1950 targetElems.insert( 0, "" );
1951 }
1952#endif
1953
1954 // append source path elements
1955 targetElems << srcElems;
1956 targetElems.removeAll( u"."_s );
1957
1958 // resolve ..
1959 int pos;
1960 while ( ( pos = targetElems.indexOf( ".."_L1 ) ) > 0 )
1961 {
1962 // remove preceding element and ..
1963 targetElems.removeAt( pos - 1 );
1964 targetElems.removeAt( pos - 1 );
1965 }
1966
1967#if !defined(Q_OS_WIN)
1968 // make path absolute
1969 targetElems.prepend( QString() );
1970#endif
1971
1972 return targetElems.join( '/'_L1 );
1973}
1974
1976{
1977 return *sBuildSourcePath();
1978}
1979
1981{
1982 return *sBuildOutputPath();
1983}
1984
1985#if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
1986QString QgsApplication::cfgIntDir()
1987{
1988 return *sCfgIntDir();
1989}
1990#endif
1991
1992void QgsApplication::skipGdalDriver( const QString &driver )
1993{
1994 if ( sGdalSkipList()->contains( driver ) || driver.isEmpty() )
1995 {
1996 return;
1997 }
1998 *sGdalSkipList() << driver;
2000}
2001
2002void QgsApplication::restoreGdalDriver( const QString &driver )
2003{
2004 if ( !sGdalSkipList()->contains( driver ) )
2005 {
2006 return;
2007 }
2008 int myPos = sGdalSkipList()->indexOf( driver );
2009 if ( myPos >= 0 )
2010 {
2011 sGdalSkipList()->removeAt( myPos );
2012 }
2014}
2015
2017{
2018 return *sGdalSkipList();
2019}
2020
2022 const QStringList &deferredSkippedGdalDrivers )
2023{
2024 *sGdalSkipList() = skippedGdalDrivers;
2025 *sDeferredSkippedGdalDrivers() = deferredSkippedGdalDrivers;
2026
2027 QgsSettings settings;
2028 settings.setValue( u"gdal/skipDrivers"_s, skippedGdalDrivers.join( ','_L1 ) );
2029
2031}
2032
2034{
2035 QgsSettings settings;
2036 QString joinedList, delimiter;
2037 if ( settings.contains( u"gdal/skipDrivers"_s ) )
2038 {
2039 joinedList = settings.value( u"gdal/skipDrivers"_s, QString() ).toString();
2040 delimiter = u","_s;
2041 }
2042 else
2043 {
2044 joinedList = settings.value( u"gdal/skipList"_s, QString() ).toString();
2045 delimiter = u" "_s;
2046 }
2047 QStringList myList;
2048 if ( !joinedList.isEmpty() )
2049 {
2050 myList = joinedList.split( delimiter );
2051 }
2052 *sGdalSkipList() = myList;
2054}
2055
2057{
2058 return *sDeferredSkippedGdalDrivers();
2059}
2060
2062{
2063 sGdalSkipList()->removeDuplicates();
2064 QStringList realDisabledDriverList;
2065 for ( const auto &driverName : *sGdalSkipList() )
2066 {
2067 if ( !sDeferredSkippedGdalDrivers()->contains( driverName ) )
2068 realDisabledDriverList << driverName;
2069 }
2070 QString myDriverList = realDisabledDriverList.join( ',' );
2071 QgsDebugMsgLevel( u"Gdal Skipped driver list set to:"_s, 2 );
2072 QgsDebugMsgLevel( myDriverList, 2 );
2073 CPLSetConfigOption( "GDAL_SKIP", myDriverList.toUtf8() );
2074 GDALAllRegister(); //to update driver list and skip missing ones
2075}
2076
2078{
2079 QString folder = userThemesFolder();
2080 QDir myDir( folder );
2081 if ( !myDir.exists() )
2082 {
2083 myDir.mkpath( folder );
2084 }
2085
2086 return true;
2087}
2088
2089void QgsApplication::copyPath( const QString &src, const QString &dst )
2090{
2091 QDir dir( src );
2092 if ( ! dir.exists() )
2093 return;
2094
2095 const auto subDirectories = dir.entryList( QDir::Dirs | QDir::NoDotAndDotDot );
2096 for ( const QString &d : subDirectories )
2097 {
2098 QString dst_path = dst + QDir::separator() + d;
2099 dir.mkpath( dst_path );
2100 copyPath( src + QDir::separator() + d, dst_path );
2101 }
2102
2103 const auto files = dir.entryList( QDir::Files );
2104 for ( const QString &f : files )
2105 {
2106 QFile::copy( src + QDir::separator() + f, dst + QDir::separator() + f );
2107 }
2108}
2109
2111{
2112 //read values from QgsSettings
2113 QgsSettings settings;
2114
2115 QVariantMap variables;
2116
2117 //check if settings contains any variables
2118 settings.beginGroup( "variables" );
2119 QStringList childKeys = settings.childKeys();
2120 for ( QStringList::const_iterator it = childKeys.constBegin(); it != childKeys.constEnd(); ++it )
2121 {
2122 QString name = *it;
2123 variables.insert( name, settings.value( name ) );
2124 }
2125
2126 return variables;
2127}
2128
2129void QgsApplication::setCustomVariables( const QVariantMap &variables )
2130{
2131 QgsSettings settings;
2132
2133 QVariantMap::const_iterator it = variables.constBegin();
2134 settings.beginGroup( "variables" );
2135 settings.remove( "" );
2136 for ( ; it != variables.constEnd(); ++it )
2137 {
2138 settings.setValue( it.key(), it.value() );
2139 }
2140
2142}
2143
2144void QgsApplication::setCustomVariable( const QString &name, const QVariant &value )
2145{
2146 // save variable to settings
2147 QgsSettings settings;
2148
2149 settings.setValue( u"variables/"_s + name, value );
2150
2152}
2153
2155{
2156 return instance()->mTemporarilyTrustedProjectFolders;
2157}
2158
2159void QgsApplication::setTemporarilyTrustedProjectsFolders( const QStringList &trustedProjectsFolders )
2160{
2161 instance()->mTemporarilyTrustedProjectFolders = trustedProjectsFolders;
2162}
2163
2165{
2166 return instance()->mTemporarilyUntrustedProjectFolders;
2167}
2168
2169void QgsApplication::setTemporarilyUntrustedProjectsFolders( const QStringList &untrustedProjectsFolders )
2170{
2171 instance()->mTemporarilyUntrustedProjectFolders = untrustedProjectsFolders;
2172}
2173
2174int QgsApplication::scaleIconSize( int standardSize, bool applyDevicePixelRatio )
2175{
2176 QFontMetrics fm( ( QFont() ) );
2177 const double scale = 1.1 * standardSize / 24;
2178 int scaledIconSize = static_cast< int >( std::floor( std::max( Qgis::UI_SCALE_FACTOR * fm.height() * scale, static_cast< double >( standardSize ) ) ) );
2179 if ( applyDevicePixelRatio )
2180 {
2181 if ( QWidget *activeWindow = QApplication::activeWindow() )
2182 scaledIconSize *= ( activeWindow->screen() ? QApplication::activeWindow()->screen()->devicePixelRatio() : 1 );
2183 }
2184 return scaledIconSize;
2185}
2186
2191
2193{
2194 *sTranslation() = translation;
2195 if ( auto app = QgsApplication::instance() )
2196 {
2197 app->installTranslators();
2198 }
2199}
2200
2202{
2203 return *sTranslation();
2204}
2205
2207{
2208 emit requestForTranslatableObjects( translationContext );
2209}
2210
2212{
2213 ApplicationMembers *appMembers = members();
2214 if ( appMembers->mNullRepresentation.isNull() )
2215 {
2216 appMembers->mNullRepresentation = QgsSettings().value( u"qgis/nullValue"_s, u"NULL"_s ).toString();
2217 }
2218 return appMembers->mNullRepresentation;
2219}
2220
2222{
2223 ApplicationMembers *appMembers = members();
2224 if ( !appMembers || appMembers->mNullRepresentation == nullRepresentation )
2225 return;
2226
2228 QgsSettings().setValue( u"qgis/nullValue"_s, nullRepresentation );
2229
2230 QgsApplication *app = instance();
2231 if ( app )
2232 emit app->nullRepresentationChanged();
2233}
2234
2236{
2237 return members()->mActionScopeRegistry.get();
2238}
2239
2240bool QgsApplication::createDatabase( QString *errorMessage )
2241{
2242 // set a working directory up for gdal to write .aux.xml files into
2243 // for cases where the raster dir is read only to the user
2244 // if the env var is already set it will be used preferentially
2245 QString myPamPath = qgisSettingsDirPath() + u"gdal_pam/"_s;
2246 QDir myDir( myPamPath );
2247 if ( !myDir.exists() )
2248 {
2249 myDir.mkpath( myPamPath ); //fail silently
2250 }
2251
2252#if defined(Q_OS_WIN)
2253 CPLSetConfigOption( "GDAL_PAM_PROXY_DIR", myPamPath.toUtf8() );
2254#else
2255 //under other OS's we use an environment var so the user can
2256 //override the path if he likes
2257 int myChangeFlag = 0; //whether we want to force the env var to change
2258 setenv( "GDAL_PAM_PROXY_DIR", myPamPath.toUtf8(), myChangeFlag );
2259#endif
2260
2261 // Check qgis.db and make private copy if necessary
2262 QFile qgisPrivateDbFile( QgsApplication::qgisUserDatabaseFilePath() );
2263
2264 // first we look for ~/.qgis/qgis.db
2265 if ( !qgisPrivateDbFile.exists() )
2266 {
2267 // if it doesn't exist we copy it in from the global resources dir
2268 QString qgisMasterDbFileName = QgsApplication::qgisMasterDatabaseFilePath();
2269 QFile masterFile( qgisMasterDbFileName );
2270
2271 // Must be sure there is destination directory ~/.qgis
2272 QDir().mkpath( QgsApplication::qgisSettingsDirPath() );
2273
2274 //now copy the master file into the users .qgis dir
2275 bool isDbFileCopied = masterFile.copy( qgisPrivateDbFile.fileName() );
2276
2277 if ( !isDbFileCopied )
2278 {
2279 if ( errorMessage )
2280 {
2281 *errorMessage = tr( "[ERROR] Can not make qgis.db private copy" );
2282 }
2283 return false;
2284 }
2285
2286 QFile::Permissions perms = QFile( qgisPrivateDbFile.fileName() ).permissions();
2287 if ( !( perms & QFile::WriteOwner ) )
2288 {
2289 if ( !qgisPrivateDbFile.setPermissions( perms | QFile::WriteOwner ) )
2290 {
2291 if ( errorMessage )
2292 {
2293 *errorMessage = tr( "Can not make '%1' user writable" ).arg( qgisPrivateDbFile.fileName() );
2294 }
2295 return false;
2296 }
2297 }
2298 }
2299 else
2300 {
2301 // migrate if necessary
2303 if ( database.open( QgsApplication::qgisUserDatabaseFilePath() ) != SQLITE_OK )
2304 {
2305 if ( errorMessage )
2306 {
2307 *errorMessage = tr( "Could not open qgis.db" );
2308 }
2309 return false;
2310 }
2311
2312 char *errmsg = nullptr;
2313 int res = sqlite3_exec( database.get(), "SELECT srs_id FROM tbl_srs LIMIT 0", nullptr, nullptr, &errmsg );
2314 if ( res != SQLITE_OK )
2315 {
2316 sqlite3_free( errmsg );
2317
2318 // qgis.db is missing tbl_srs, create it
2319 if ( sqlite3_exec( database.get(),
2320 "DROP INDEX IF EXISTS idx_srsauthid;"
2321 "CREATE TABLE tbl_srs ("
2322 "srs_id INTEGER PRIMARY KEY,"
2323 "description text NOT NULL,"
2324 "projection_acronym text NOT NULL,"
2325 "ellipsoid_acronym NOT NULL,"
2326 "parameters text NOT NULL,"
2327 "srid integer,"
2328 "auth_name varchar,"
2329 "auth_id varchar,"
2330 "is_geo integer NOT NULL,"
2331 "deprecated boolean,"
2332 "wkt text);"
2333 "CREATE INDEX idx_srsauthid on tbl_srs(auth_name,auth_id);", nullptr, nullptr, &errmsg ) != SQLITE_OK )
2334 {
2335 if ( errorMessage )
2336 {
2337 *errorMessage = tr( "Creation of missing tbl_srs in the private qgis.db failed.\n%1" ).arg( QString::fromUtf8( errmsg ) );
2338 }
2339 sqlite3_free( errmsg );
2340 return false;
2341 }
2342 }
2343 else
2344 {
2345 // test if wkt column exists in database
2346 res = sqlite3_exec( database.get(), "SELECT wkt FROM tbl_srs LIMIT 0", nullptr, nullptr, &errmsg );
2347 if ( res != SQLITE_OK )
2348 {
2349 // need to add wkt column
2350 sqlite3_free( errmsg );
2351 if ( sqlite3_exec( database.get(),
2352 "DROP INDEX IF EXISTS idx_srsauthid;"
2353 "DROP TABLE IF EXISTS tbl_srs_bak;"
2354 "ALTER TABLE tbl_srs RENAME TO tbl_srs_bak;"
2355 "CREATE TABLE tbl_srs ("
2356 "srs_id INTEGER PRIMARY KEY,"
2357 "description text NOT NULL,"
2358 "projection_acronym text NOT NULL,"
2359 "ellipsoid_acronym NOT NULL,"
2360 "parameters text NOT NULL,"
2361 "srid integer,"
2362 "auth_name varchar,"
2363 "auth_id varchar,"
2364 "is_geo integer NOT NULL,"
2365 "deprecated boolean,"
2366 "wkt text);"
2367 "CREATE INDEX idx_srsauthid on tbl_srs(auth_name,auth_id);"
2368 "INSERT INTO tbl_srs(srs_id,description,projection_acronym,ellipsoid_acronym,parameters,srid,auth_name,auth_id,is_geo,deprecated) SELECT srs_id,description,projection_acronym,ellipsoid_acronym,parameters,srid,'','',is_geo,0 FROM tbl_srs_bak;"
2369 "DROP TABLE tbl_srs_bak", nullptr, nullptr, &errmsg ) != SQLITE_OK )
2370 {
2371 if ( errorMessage )
2372 {
2373 *errorMessage = tr( "Migration of private qgis.db failed.\n%1" ).arg( QString::fromUtf8( errmsg ) );
2374 }
2375 sqlite3_free( errmsg );
2376 return false;
2377 }
2378 }
2379 }
2380
2381 res = sqlite3_exec( database.get(), "SELECT acronym FROM tbl_projection LIMIT 0", nullptr, nullptr, &errmsg );
2382 if ( res != SQLITE_OK )
2383 {
2384 sqlite3_free( errmsg );
2385
2386 // qgis.db is missing tbl_projection, create it
2387 if ( sqlite3_exec( database.get(),
2388 "CREATE TABLE tbl_projection ("
2389 "acronym varchar(20) NOT NULL PRIMARY KEY,"
2390 "name varchar(255) NOT NULL default '',"
2391 "notes varchar(255) NOT NULL default '',"
2392 "parameters varchar(255) NOT NULL default ''"
2393 ")", nullptr, nullptr, &errmsg ) != SQLITE_OK )
2394 {
2395 if ( errorMessage )
2396 {
2397 *errorMessage = tr( "Creation of missing tbl_projection in the private qgis.db failed.\n%1" ).arg( QString::fromUtf8( errmsg ) );
2398 }
2399 sqlite3_free( errmsg );
2400 return false;
2401 }
2402 }
2403
2404 res = sqlite3_exec( database.get(), "SELECT epsg FROM tbl_srs LIMIT 0", nullptr, nullptr, &errmsg );
2405 if ( res == SQLITE_OK )
2406 {
2407 // epsg column exists => need migration
2408 if ( sqlite3_exec( database.get(),
2409 "DROP INDEX IF EXISTS idx_srsauthid;"
2410 "DROP TABLE IF EXISTS tbl_srs_bak;"
2411 "ALTER TABLE tbl_srs RENAME TO tbl_srs_bak;"
2412 "CREATE TABLE tbl_srs ("
2413 "srs_id INTEGER PRIMARY KEY,"
2414 "description text NOT NULL,"
2415 "projection_acronym text NOT NULL,"
2416 "ellipsoid_acronym NOT NULL,"
2417 "parameters text NOT NULL,"
2418 "srid integer,"
2419 "auth_name varchar,"
2420 "auth_id varchar,"
2421 "is_geo integer NOT NULL,"
2422 "deprecated boolean,"
2423 "wkt text);"
2424 "CREATE INDEX idx_srsauthid on tbl_srs(auth_name,auth_id);"
2425 "INSERT INTO tbl_srs(srs_id,description,projection_acronym,ellipsoid_acronym,parameters,srid,auth_name,auth_id,is_geo,deprecated) SELECT srs_id,description,projection_acronym,ellipsoid_acronym,parameters,srid,'','',is_geo,0 FROM tbl_srs_bak;"
2426 "DROP TABLE tbl_srs_bak", nullptr, nullptr, &errmsg ) != SQLITE_OK )
2427 {
2428 if ( errorMessage )
2429 {
2430 *errorMessage = tr( "Migration of private qgis.db failed.\n%1" ).arg( QString::fromUtf8( errmsg ) );
2431 }
2432 sqlite3_free( errmsg );
2433 return false;
2434 }
2435 }
2436 else
2437 {
2438 sqlite3_free( errmsg );
2439 }
2440
2441 if ( sqlite3_exec( database.get(), "DROP VIEW vw_srs", nullptr, nullptr, &errmsg ) != SQLITE_OK )
2442 {
2443 QgsDebugError( u"vw_srs didn't exists in private qgis.db: %1"_s.arg( errmsg ) );
2444 }
2445
2446 if ( sqlite3_exec( database.get(),
2447 "CREATE VIEW vw_srs AS"
2448 " SELECT"
2449 " a.description AS description"
2450 ",a.srs_id AS srs_id"
2451 ",a.is_geo AS is_geo"
2452 ",coalesce(b.name,a.projection_acronym) AS name"
2453 ",a.parameters AS parameters"
2454 ",a.auth_name AS auth_name"
2455 ",a.auth_id AS auth_id"
2456 ",a.deprecated AS deprecated"
2457 " FROM tbl_srs a"
2458 " LEFT OUTER JOIN tbl_projection b ON a.projection_acronym=b.acronym"
2459 " ORDER BY coalesce(b.name,a.projection_acronym),a.description", nullptr, nullptr, &errmsg ) != SQLITE_OK )
2460 {
2461 if ( errorMessage )
2462 {
2463 *errorMessage = tr( "Update of view in private qgis.db failed.\n%1" ).arg( QString::fromUtf8( errmsg ) );
2464 }
2465 sqlite3_free( errmsg );
2466 return false;
2467 }
2468 }
2469 return true;
2470}
2471
2473{
2474 QgsDebugMsgLevel( u"maxThreads: %1"_s.arg( maxThreads ), 2 );
2475
2476 // make sure value is between 1 and #cores, if not set to -1 (use #cores)
2477 if ( maxThreads < 1 || maxThreads > QThread::idealThreadCount() )
2478 maxThreads = -1;
2479
2480 // force at least 2 threads -- anything less risks deadlocks within Qt itself (e.g in QImage internal mutexes)
2481 if ( maxThreads > 0 && maxThreads < 2 )
2482 maxThreads = 2;
2483
2484 // save value
2485 ABISYM( sMaxThreads ) = maxThreads;
2486
2487 // if -1 use #cores
2488 if ( maxThreads == -1 )
2489 maxThreads = QThread::idealThreadCount();
2490
2491 // set max thread count in QThreadPool
2492 QThreadPool::globalInstance()->setMaxThreadCount( maxThreads );
2493 QgsDebugMsgLevel( u"set QThreadPool max thread count to %1"_s.arg( QThreadPool::globalInstance()->maxThreadCount() ), 2 );
2494}
2495
2497{
2498 return members()->mTaskManager.get();
2499}
2500
2502{
2503 return members()->mSettingsRegistryCore.get();
2504}
2505
2507{
2508 return members()->mColorSchemeRegistry.get();
2509}
2510
2512{
2513 return members()->mPaintEffectRegistry.get();
2514}
2515
2517{
2518 return members()->mRendererRegistry.get();
2519}
2520
2522{
2523 return members()->mRasterRendererRegistry.get();
2524}
2525
2527{
2528 return members()->mPointCloudRendererRegistry.get();
2529}
2530
2532{
2533 return members()->mTiledSceneRendererRegistry.get();
2534}
2535
2537{
2538 if ( auto *lInstance = instance() )
2539 {
2540 if ( !instance()->mDataItemProviderRegistry )
2541 {
2542 lInstance->mDataItemProviderRegistry = std::make_unique<QgsDataItemProviderRegistry>();
2543 }
2544 return lInstance->mDataItemProviderRegistry.get();
2545 }
2546 else
2547 {
2548 // no QgsApplication instance
2549 static QgsDataItemProviderRegistry *sDataItemProviderRegistry = nullptr;
2550 if ( !sDataItemProviderRegistry )
2551 sDataItemProviderRegistry = new QgsDataItemProviderRegistry();
2552 return sDataItemProviderRegistry;
2553 }
2554}
2555
2557{
2558 return members()->mCrsRegistry.get();
2559}
2560
2562{
2563 return members()->mSvgCache.get();
2564}
2565
2567{
2568 return members()->mImageCache.get();
2569}
2570
2572{
2573 return members()->mSourceCache.get();
2574}
2575
2577{
2578 return members()->mNetworkContentFetcherRegistry.get();
2579}
2580
2582{
2583 return members()->mValidityCheckRegistry.get();
2584}
2585
2587{
2588 return members()->mSymbolLayerRegistry.get();
2589}
2590
2592{
2593 return members()->mCalloutRegistry.get();
2594}
2595
2597{
2598 return members()->mLayoutItemRegistry.get();
2599}
2600
2602{
2603 return members()->mAnnotationItemRegistry.get();
2604}
2605
2607{
2608 return members()->mSensorRegistry.get();
2609}
2610
2612{
2613 return members()->mPlotRegistry.get();
2614}
2615
2617{
2618 return members()->mGpsConnectionRegistry.get();
2619}
2620
2622{
2623 return members()->mGpsBabelFormatRegistry.get();
2624}
2625
2627{
2628 return members()->mPluginLayerRegistry.get();
2629}
2630
2632{
2633 return members()->mClassificationMethodRegistry.get();
2634}
2635
2637{
2638 return members()->mBookmarkManager.get();
2639}
2640
2642{
2643 return members()->mTileDownloadManager.get();
2644}
2645
2647{
2648 return members()->mRecentStyleHandler.get();
2649}
2650
2652{
2653 return members()->mQueryLogger.get();
2654}
2655
2657{
2658 return members()->mStyleModel.get();
2659}
2660
2662{
2663 return members()->mFontManager.get();
2664}
2665
2667{
2668 return members()->mMessageLog.get();
2669}
2670
2672{
2673 return members()->mProcessingRegistry.get();
2674}
2675
2677{
2678 return members()->mConnectionRegistry.get();
2679}
2680
2682{
2683 return members()->mLayerMetadataProviderRegistry.get();
2684}
2685
2687{
2688 return members()->mPageSizeRegistry.get();
2689}
2690
2692{
2693 return members()->mAnnotationRegistry.get();
2694}
2695
2697{
2698 return members()->mApplicationThemeRegistry.get();
2699}
2700
2702{
2703 return members()->mNumericFormatRegistry.get();
2704}
2705
2707{
2708 return members()->mFieldFormatterRegistry.get();
2709}
2710
2712{
2713 return members()->m3DRendererRegistry.get();
2714}
2715
2717{
2718 return members()->m3DSymbolRegistry.get();
2719}
2720
2722{
2723 return members()->mScaleBarRendererRegistry.get();
2724}
2725
2727{
2728 return members()->mLabelingEngineRuleRegistry.get();
2729}
2730
2732{
2733 return members()->mProjectStorageRegistry.get();
2734}
2735
2737{
2738 return members()->mExternalStorageRegistry.get();
2739}
2740
2742{
2743 return members()->mProfileSourceRegistry.get();
2744}
2745
2747{
2748 return members()->mLocalizedDataPathRegistry.get();
2749}
2750
2752{
2753 // don't use initializer lists or scoped pointers - as more objects are added here we
2754 // will need to be careful with the order of creation/destruction
2755 mSettingsRegistryCore = std::make_unique<QgsSettingsRegistryCore>();
2756 mLocalizedDataPathRegistry = std::make_unique<QgsLocalizedDataPathRegistry>();
2757 mMessageLog = std::make_unique<QgsMessageLog>();
2758 QgsRuntimeProfiler *profiler = QgsRuntimeProfiler::threadLocalInstance();
2759
2760 {
2761 profiler->start( tr( "Create query logger" ) );
2762 mQueryLogger = std::make_unique<QgsDatabaseQueryLog>();
2763 profiler->end();
2764 }
2765 {
2766 profiler->start( tr( "Setup coordinate reference system registry" ) );
2767 mCrsRegistry = std::make_unique<QgsCoordinateReferenceSystemRegistry>();
2768 profiler->end();
2769 }
2770 {
2771 profiler->start( tr( "Create connection registry" ) );
2772 mConnectionRegistry = std::make_unique<QgsConnectionRegistry>();
2773 profiler->end();
2774 }
2775 {
2776 profiler->start( tr( "Create project storage registry" ) );
2777 mProjectStorageRegistry = std::make_unique<QgsProjectStorageRegistry>();
2778 profiler->end();
2779 }
2780 {
2781 profiler->start( tr( "Create layer metadata provider registry" ) );
2782 mLayerMetadataProviderRegistry = std::make_unique<QgsLayerMetadataProviderRegistry>();
2783 profiler->end();
2784 }
2785 {
2786 profiler->start( tr( "Create font manager" ) );
2787 mFontManager = std::make_unique<QgsFontManager>();
2788 profiler->end();
2789 }
2790 {
2791 profiler->start( tr( "Setup task manager" ) );
2792 mTaskManager = std::make_unique<QgsTaskManager>();
2793 profiler->end();
2794 }
2795 {
2796 profiler->start( tr( "Setup action scope registry" ) );
2797 mActionScopeRegistry = std::make_unique<QgsActionScopeRegistry>();
2798 profiler->end();
2799 }
2800 {
2801 profiler->start( tr( "Setup numeric formats" ) );
2802 mNumericFormatRegistry = std::make_unique<QgsNumericFormatRegistry>();
2803 profiler->end();
2804 }
2805 {
2806 profiler->start( tr( "Setup field formats" ) );
2807 mFieldFormatterRegistry = std::make_unique<QgsFieldFormatterRegistry>();
2808 profiler->end();
2809 }
2810 {
2811 profiler->start( tr( "Setup SVG cache" ) );
2812 mSvgCache = std::make_unique<QgsSvgCache>();
2813 profiler->end();
2814 }
2815 {
2816 profiler->start( tr( "Setup image cache" ) );
2817 mImageCache = std::make_unique<QgsImageCache>();
2818 profiler->end();
2819 }
2820 {
2821 profiler->start( tr( "Setup source cache" ) );
2822 mSourceCache = std::make_unique<QgsSourceCache>();
2823 profiler->end();
2824 }
2825 {
2826 profiler->start( tr( "Setup color scheme registry" ) );
2827 mColorSchemeRegistry = std::make_unique<QgsColorSchemeRegistry>();
2828 profiler->end();
2829 }
2830 {
2831 profiler->start( tr( "Setup paint effect" ) );
2832 mPaintEffectRegistry = std::make_unique<QgsPaintEffectRegistry>();
2833 profiler->end();
2834 }
2835 {
2836 profiler->start( tr( "Setup symbol layer registry" ) );
2837 mSymbolLayerRegistry = std::make_unique<QgsSymbolLayerRegistry>();
2838 profiler->end();
2839 }
2840 {
2841 profiler->start( tr( "Recent style handler" ) );
2842 mRecentStyleHandler = std::make_unique<QgsRecentStyleHandler>();
2843 profiler->end();
2844 }
2845 {
2846 profiler->start( tr( "Setup callout registry" ) );
2847 mCalloutRegistry = std::make_unique<QgsCalloutRegistry>();
2848 profiler->end();
2849 }
2850 {
2851 profiler->start( tr( "Setup renderer registry" ) );
2852 mRendererRegistry = std::make_unique<QgsRendererRegistry>();
2853 profiler->end();
2854 }
2855 {
2856 profiler->start( tr( "Setup raster renderer registry" ) );
2857 mRasterRendererRegistry = std::make_unique<QgsRasterRendererRegistry>();
2858 profiler->end();
2859 }
2860 {
2861 profiler->start( tr( "Setup point cloud renderer registry" ) );
2862 mPointCloudRendererRegistry = std::make_unique<QgsPointCloudRendererRegistry>();
2863 profiler->end();
2864 }
2865 {
2866 profiler->start( tr( "Setup tiled scene renderer registry" ) );
2867 mTiledSceneRendererRegistry = std::make_unique<QgsTiledSceneRendererRegistry>();
2868 profiler->end();
2869 }
2870 {
2871 profiler->start( tr( "Setup GPS registry" ) );
2872 mGpsConnectionRegistry = std::make_unique<QgsGpsConnectionRegistry>();
2873 profiler->end();
2874 }
2875 {
2876 profiler->start( tr( "Setup GPSBabel format registry" ) );
2877 mGpsBabelFormatRegistry = std::make_unique<QgsBabelFormatRegistry>();
2878 profiler->end();
2879 }
2880 {
2881 profiler->start( tr( "Setup plugin layer registry" ) );
2882 mPluginLayerRegistry = std::make_unique<QgsPluginLayerRegistry>();
2883 profiler->end();
2884 }
2885 {
2886 profiler->start( tr( "Setup Processing registry" ) );
2887 mProcessingRegistry = std::make_unique<QgsProcessingRegistry>();
2888 profiler->end();
2889 }
2890 mPageSizeRegistry = std::make_unique<QgsPageSizeRegistry>();
2891 {
2892 profiler->start( tr( "Setup layout item registry" ) );
2893 mLayoutItemRegistry = std::make_unique<QgsLayoutItemRegistry>();
2894 mLayoutItemRegistry->populate();
2895 profiler->end();
2896 }
2897 {
2898 profiler->start( tr( "Setup annotation registry" ) );
2899 mAnnotationRegistry = std::make_unique<QgsAnnotationRegistry>();
2900 profiler->end();
2901 }
2902 {
2903 profiler->start( tr( "Setup application theme registry" ) );
2904 mApplicationThemeRegistry = std::make_unique<QgsApplicationThemeRegistry>();
2905 profiler->end();
2906 }
2907 {
2908 profiler->start( tr( "Setup annotation item registry" ) );
2909 mAnnotationItemRegistry = std::make_unique<QgsAnnotationItemRegistry>();
2910 mAnnotationItemRegistry->populate();
2911 profiler->end();
2912 }
2913 {
2914 profiler->start( tr( "Setup labeling engine rule registry" ) );
2915 mLabelingEngineRuleRegistry = std::make_unique<QgsLabelingEngineRuleRegistry>();
2916 profiler->end();
2917 }
2918 {
2919 profiler->start( tr( "Setup sensor registry" ) );
2920 mSensorRegistry = std::make_unique<QgsSensorRegistry>();
2921 mSensorRegistry->populate();
2922 profiler->end();
2923 }
2924 {
2925 profiler->start( tr( "Setup plot registry" ) );
2926 mPlotRegistry = std::make_unique<QgsPlotRegistry>();
2927 mPlotRegistry->populate();
2928 profiler->end();
2929 }
2930 {
2931 profiler->start( tr( "Setup 3D symbol registry" ) );
2932 m3DSymbolRegistry = std::make_unique<Qgs3DSymbolRegistry>();
2933 profiler->end();
2934 }
2935 {
2936 profiler->start( tr( "Setup 3D renderer registry" ) );
2937 m3DRendererRegistry = std::make_unique<Qgs3DRendererRegistry>();
2938 profiler->end();
2939 }
2940 {
2941 profiler->start( tr( "Setup external storage registry" ) );
2942 mExternalStorageRegistry = std::make_unique<QgsExternalStorageRegistry>();
2943 profiler->end();
2944 }
2945 {
2946 profiler->start( tr( "Setup profile source registry" ) );
2947 mProfileSourceRegistry = std::make_unique<QgsProfileSourceRegistry>();
2948 profiler->end();
2949 }
2950 {
2951 profiler->start( tr( "Setup network content cache" ) );
2952 mNetworkContentFetcherRegistry = std::make_unique<QgsNetworkContentFetcherRegistry>();
2953 profiler->end();
2954 }
2955 {
2956 profiler->start( tr( "Setup layout check registry" ) );
2957 mValidityCheckRegistry = std::make_unique<QgsValidityCheckRegistry>();
2958 profiler->end();
2959 }
2960 {
2961 profiler->start( tr( "Setup classification registry" ) );
2962 mClassificationMethodRegistry = std::make_unique<QgsClassificationMethodRegistry>();
2963 profiler->end();
2964 }
2965 {
2966 profiler->start( tr( "Setup bookmark manager" ) );
2967 mBookmarkManager = std::make_unique<QgsBookmarkManager>( nullptr );
2968 profiler->end();
2969 }
2970 {
2971 profiler->start( tr( "Setup tile download manager" ) );
2972 mTileDownloadManager = std::make_unique<QgsTileDownloadManager>();
2973 profiler->end();
2974 }
2975 {
2976 profiler->start( tr( "Setup scalebar registry" ) );
2977 mScaleBarRendererRegistry = std::make_unique<QgsScaleBarRendererRegistry>();
2978 profiler->end();
2979 }
2980}
2981
2983{
2984 // we reset unique_ptr manually because we care about destruction order
2985 mStyleModel.reset();
2986 mTileDownloadManager.reset();
2988 mValidityCheckRegistry.reset();
2989 mActionScopeRegistry.reset();
2990 m3DRendererRegistry.reset();
2991 m3DSymbolRegistry.reset();
2992 mAnnotationRegistry.reset();
2994 mColorSchemeRegistry.reset();
2996 mGpsConnectionRegistry.reset();
2998 mPaintEffectRegistry.reset();
2999 mPluginLayerRegistry.reset();
3000 mProcessingRegistry.reset();
3001 mPageSizeRegistry.reset();
3003 mSensorRegistry.reset();
3004 mPlotRegistry.reset();
3005 mLayoutItemRegistry.reset();
3009 mRendererRegistry.reset();
3010 mSvgCache.reset();
3011 mImageCache.reset();
3012 mSourceCache.reset();
3013 mCalloutRegistry.reset();
3014 mRecentStyleHandler.reset();
3016 mSymbolLayerRegistry.reset();
3018 mProfileSourceRegistry.reset();
3019 mTaskManager.reset();
3022 mNumericFormatRegistry.reset();
3023 mBookmarkManager.reset();
3024 mConnectionRegistry.reset();
3027 mFontManager.reset();
3029 mCrsRegistry.reset();
3030 mQueryLogger.reset();
3031 mMessageLog.reset();
3032}
3033
3034QgsApplication::ApplicationMembers *QgsApplication::members()
3035{
3036 if ( auto *lInstance = instance() )
3037 {
3038 return lInstance->mApplicationMembers.get();
3039 }
3040 else
3041 {
3042 static QRecursiveMutex sMemberMutex;
3043 QMutexLocker lock( &sMemberMutex );
3044 if ( !sApplicationMembers )
3045 sApplicationMembers = new ApplicationMembers();
3046 return sApplicationMembers;
3047 }
3048}
QFlags< SettingsOption > SettingsOptions
Definition qgis.h:748
static const double UI_SCALE_FACTOR
UI scaling factor.
Definition qgis.h:6534
A registry for available 3D renderers.
Registry of available 3D symbol classes.
The action scope registry is an application wide registry that contains a list of available action sc...
Registry of available annotation item types.
Registry of user interface themes.
QHash< QString, QString > themeFolders() const
Returns a map of user interface theme names and folders.
QString themeFolder(const QString &name) const
Returns the user interface theme folder for a matching name.
static QString resolvePkgPath()
Calculate the application pkg path.
static int scaleIconSize(int standardSize, bool applyDevicePixelRatio=false)
Scales an icon size to compensate for display pixel density, making the icon size hi-dpi friendly,...
static void restoreGdalDriver(const QString &driver)
Sets the GDAL_SKIP environment variable to exclude the specified driver and then calls GDALDriverMana...
static QgsLabelingEngineRuleRegistry * labelingEngineRuleRegistry()
Gets the registry of available labeling engine rules.
static void setCustomVariables(const QVariantMap &customVariables)
Custom expression variables for this application.
QString translation() const
Returns the current application translation locale code.
static QString i18nPath()
Returns the path to the translation directory.
static QgsAnnotationItemRegistry * annotationItemRegistry()
Returns the application's annotation item registry, used for annotation item types.
static QString osName()
Returns a string name of the operating system QGIS is running on.
static void registerOgrDrivers()
Register OGR drivers ensuring this only happens once.
static QString sponsorsFilePath()
Returns the path to the sponsors file.
static QgsRecentStyleHandler * recentStyleHandler()
Returns the handler for recently used style items.
endian_t
Constants for endian-ness.
static QString qgisMasterDatabaseFilePath()
Returns the path to the master qgis.db file.
static void skipGdalDriver(const QString &driver)
Sets the GDAL_SKIP environment variable to include the specified driver and then calls GDALDriverMana...
static QString defaultThemePath()
Returns the path to the default theme directory.
static QgsPageSizeRegistry * pageSizeRegistry()
Returns the application's page size registry, used for managing layout page sizes.
static QgsValidityCheckRegistry * validityCheckRegistry()
Returns the application's validity check registry, used for managing validity checks.
static QgsDataItemProviderRegistry * dataItemProviderRegistry()
Returns the application's data item provider registry, which keeps a list of data item providers that...
static QString userStylePath()
Returns the path to user's style.
static QString platform()
Returns the QGIS platform name, e.g., "desktop", "server", "qgis_process" or "external" (for external...
static QgsProcessingRegistry * processingRegistry()
Returns the application's processing registry, used for managing processing providers,...
static QgsLayerMetadataProviderRegistry * layerMetadataProviderRegistry()
Returns registry of available layer metadata provider implementations.
static QgsConnectionRegistry * connectionRegistry()
Returns the application's connection registry, used for managing saved data provider connections.
static void exitQgis()
deletes provider registry and map layer registry
static void setPluginPath(const QString &pluginPath)
Alters plugin path - used by 3rd party apps.
static const QgsSettingsEntryStringList * settingsSearchPathsForSVG
Settings entry search path for SVG.
void themeChanged()
Emitted when the application theme has changed.
static QPixmap getThemePixmap(const QString &name, const QColor &foreColor=QColor(), const QColor &backColor=QColor(), int size=16)
Helper to get a theme icon as a pixmap.
static QString nullRepresentation()
Returns the string used to represent the value NULL throughout QGIS.
static QVariantMap customVariables()
Custom expression variables for this application.
static QgsPointCloudRendererRegistry * pointCloudRendererRegistry()
Returns the application's point cloud renderer registry, used for managing point cloud layer 2D rende...
static QgsPaintEffectRegistry * paintEffectRegistry()
Returns the application's paint effect registry, used for managing paint effects.
static QgsSensorRegistry * sensorRegistry()
Returns the application's sensor registry, used for sensor types.
static QString pluginPath()
Returns the path to the application plugin directory.
static void setUITheme(const QString &themeName)
Set the current UI theme used to style the interface.
static bool createDatabase(QString *errorMessage=nullptr)
initialize qgis.db
static const QgsSettingsEntryBool * settingsLocaleOverrideFlag
Settings entry locale override flag.
static void setTemporarilyUntrustedProjectsFolders(const QStringList &untrustedProjectsFolders)
Sets the list of projects and folders that have been temporarily determined as untrusted by the user.
static QCursor getThemeCursor(Cursor cursor)
Helper to get a theme cursor.
static int systemMemorySizeMb()
Returns the size of the system memory (RAM) in megabytes.
static void setLocale(const QLocale &locale)
Sets the QGIS locale - used mainly by 3rd party apps and tests.
static void init(QString profileFolder=QString())
This method initializes paths etc for QGIS.
static void setThemeName(const QString &themeName)
Set the active theme to the specified theme.
void customVariablesChanged()
Emitted whenever a custom global variable changes.
static QString buildSourcePath()
Returns path to the source directory. Valid only when running from build directory.
static QString buildOutputPath()
Returns path to the build output directory. Valid only when running from build directory.
bool notify(QObject *receiver, QEvent *event) override
Catch exceptions when sending event to receiver.
static int maxThreads()
Gets maximum concurrent thread count.
static QgsColorSchemeRegistry * colorSchemeRegistry()
Returns the application's color scheme registry, used for managing color schemes.
static QgsApplication * instance()
Returns the singleton instance of the QgsApplication.
static QString reportStyleSheet(QgsApplication::StyleSheetType styleSheetType=QgsApplication::StyleSheetType::Qt)
Returns a css style sheet for reports, the styleSheetType argument determines what type of stylesheet...
static QString pkgDataPath()
Returns the common root path of all application data directories.
static QgsScaleBarRendererRegistry * scaleBarRendererRegistry()
Gets the registry of available scalebar renderers.
static QgsLayoutItemRegistry * layoutItemRegistry()
Returns the application's layout item registry, used for layout item types.
static void setFileOpenEventReceiver(QObject *receiver)
Sets the FileOpen event receiver.
static QgsSymbolLayerRegistry * symbolLayerRegistry()
Returns the application's symbol layer registry, used for managing symbol layers.
static QgsRasterRendererRegistry * rasterRendererRegistry()
Returns the application's raster renderer registry, used for managing raster layer renderers.
static void applyGdalSkippedDrivers()
Apply the skipped drivers list to gdal.
static void setMaxThreads(int maxThreads)
Set maximum concurrent thread count.
static QgsNumericFormatRegistry * numericFormatRegistry()
Gets the registry of available numeric formats.
static QgsNetworkContentFetcherRegistry * networkContentFetcherRegistry()
Returns the application's network content registry used for fetching temporary files during QGIS sess...
static QgsProjectStorageRegistry * projectStorageRegistry()
Returns registry of available project storage implementations.
static QString licenceFilePath()
Returns the path to the licence file.
static QString libexecPath()
Returns the path with utility executables (help viewer, crssync, ...).
static QStringList skippedGdalDrivers()
Returns the list of gdal drivers that should be skipped (based on GDAL_SKIP environment variable).
StyleSheetType
The StyleSheetType enum represents the stylesheet type that a widget supports.
@ Qt
StyleSheet for Qt GUI widgets (based on QLabel or QTextBrowser), supports basic CSS and Qt extensions...
@ WebBrowser
StyleSheet for embedded browsers (QtWebKit), supports full standard CSS.
static QString translatorsFilePath()
Returns the path to the sponsors file.
static const QgsSettingsEntryString * settingsLocaleGlobalLocale
Settings entry locale global locale.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static void setNullRepresentation(const QString &nullRepresentation)
Sets the string used to represent the value NULL throughout QGIS.
static QStringList temporarilyTrustedProjectsFolders()
Returns the list of projects and folders that have been temporarily determined as trusted by the user...
static QString applicationFullName()
Returns the QGIS application full name.
static QgsGpsConnectionRegistry * gpsConnectionRegistry()
Returns the application's GPS connection registry, used for managing GPS connections.
static QString locale()
Returns the QGIS locale.
static QgsImageCache * imageCache()
Returns the application's image cache, used for caching resampled versions of raster images.
static QStringList svgPaths()
Returns the paths to svg directories.
static void initQgis()
loads providers
static QString showSettings()
Convenience function to get a summary of the paths used in this application instance useful for debug...
bool event(QEvent *event) override
Watch for QFileOpenEvent.
static void setPkgDataPath(const QString &pkgDataPath)
Alters pkg data path - used by 3rd party apps.
static QString absolutePathToRelativePath(const QString &apath, const QString &targetPath)
Converts absolute path to path relative to target.
static const QgsSettingsEntryString * settingsLocaleUserLocale
Settings entry locale user locale.
static QgsRuntimeProfiler * profiler()
Returns the application runtime profiler.
~QgsApplication() override
static QgsLocalizedDataPathRegistry * localizedDataPathRegistry()
Returns the registry of data repositories These are used as paths for basemaps, logos,...
static const char * QGIS_APPLICATION_NAME
static QgsTileDownloadManager * tileDownloadManager()
Returns the application's tile download manager, used for download of map tiles when rendering.
static const char * QGIS_ORGANIZATION_DOMAIN
static QMap< QString, QString > systemEnvVars()
Returns the system environment variables passed to application.
static void setAuthDatabaseDirPath(const QString &authDbDirPath)
Alters authentication data base directory path - used by 3rd party apps.
static QgsAuthConfigurationStorageRegistry * authConfigurationStorageRegistry()
Returns the application's authentication configuration storage registry.
static QString prefixPath()
Returns the path to the application prefix directory.
static QgsSvgCache * svgCache()
Returns the application's SVG cache, used for caching SVG images and handling parameter replacement w...
static QgsFontManager * fontManager()
Returns the application font manager, which manages available fonts and font installation for the QGI...
static QString qgisSettingsDirPath()
Returns the path to the settings directory in user's home dir.
static QgsDatabaseQueryLog * databaseQueryLog()
Returns the database query log.
static QgsMessageLog * messageLog()
Returns the application's message log.
void preNotify(QObject *receiver, QEvent *event, bool *done)
static bool createThemeFolder()
Create the users theme folder.
static QString metadataPath()
Returns the path to the metadata directory.
void localeChanged()
Emitted when project locale has been changed.
static QgsActionScopeRegistry * actionScopeRegistry()
Returns the action scope registry.
static QgsCoordinateReferenceSystemRegistry * coordinateReferenceSystemRegistry()
Returns the application's coordinate reference system (CRS) registry, which handles known CRS definit...
static const char * QGIS_ORGANIZATION_NAME
static QString contributorsFilePath()
Returns the path to the contributors file.
void collectTranslatableObjects(QgsTranslationContext *translationContext)
Emits the signal to collect all the strings of .qgs to be included in ts file.
static QgsSourceCache * sourceCache()
Returns the application's source cache, used for caching embedded and remote source strings as local ...
static QStringList temporarilyUntrustedProjectsFolders()
Returns the list of projects and folders that have been temporarily determined as untrusted by the us...
static QRegularExpression shortNameRegularExpression()
Returns the short name regular expression for line edit validator.
static QgsTaskManager * taskManager()
Returns the application's task manager, used for managing application wide background task handling.
static QgsProfileSourceRegistry * profileSourceRegistry()
Returns registry of available profile source implementations.
static QgsAnnotationRegistry * annotationRegistry()
Returns the application's annotation registry, used for managing annotation types.
static QgsPluginLayerRegistry * pluginLayerRegistry()
Returns the application's plugin layer registry, used for managing plugin layer types.
static QgsClassificationMethodRegistry * classificationMethodRegistry()
Returns the application's classification methods registry, used in graduated renderer.
static QStringList deferredSkippedGdalDrivers()
Returns the list of gdal drivers that have been disabled in the current session, and thus,...
static QString qgisAuthDatabaseUri()
Returns the URI to the user authentication database.
static QString defaultStylePath()
Returns the path to default style (works as a starting point).
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
static QString qmlImportPath()
Returns the path where QML components are installed for QGIS Quick library.
static QgsApplicationThemeRegistry * applicationThemeRegistry()
Returns the application's theme registry, used for styling the user interface.
QgsApplication(int &argc, char **argv, bool GUIenabled, const QString &profileFolder=QString(), const QString &platformName="external")
Constructor for QgsApplication.
Cursor
The Cursor enum defines constants for QGIS custom cursors.
@ ZoomOut
Zoom out.
@ CrossHair
Precisely identify a point on the canvas.
@ Identify
Identify: obtain information about the object.
@ Select
Select a rectangle.
@ CapturePoint
Select and capture a point or a feature.
@ Sampler
Color/Value picker.
static const QgsSettingsEntryInteger * settingsConnectionPoolMaximumConcurrentConnections
Settings entry to configure the maximum number of concurrent connections within connection pools.
static Q_DECL_DEPRECATED QString qgisAuthDatabaseFilePath()
Returns the path to the user authentication database file: qgis-auth.db.
static QString authorsFilePath()
Returns the path to the authors file.
static QgsBookmarkManager * bookmarkManager()
Returns the application's bookmark manager, used for storing installation-wide bookmarks.
static QString qgisUserDatabaseFilePath()
Returns the path to the user qgis.db file.
static QgsFieldFormatterRegistry * fieldFormatterRegistry()
Gets the registry of available field formatters.
static QString activeThemePath()
Returns the path to the currently active theme directory.
static QString defaultThemesFolder()
Returns the path to default themes folder from install (works as a starting point).
static void setTemporarilyTrustedProjectsFolders(const QStringList &trustedProjectsFolders)
Sets the list of projects and folders that have been temporarily determined as trusted by the user.
static void setSkippedGdalDrivers(const QStringList &skippedGdalDrivers, const QStringList &deferredSkippedGdalDrivers)
Sets the list of gdal drivers that should be disabled (skippedGdalDrivers), but excludes for now the ...
static QgsRendererRegistry * rendererRegistry()
Returns the application's renderer registry, used for managing vector layer renderers.
static void setTranslation(const QString &translation)
Set translation locale code.
static QgsCalloutRegistry * calloutRegistry()
Returns the application's callout registry, used for managing callout types.
static void setPrefixPath(const QString &prefixPath, bool useDefaultPaths=false)
Alters prefix path - used by 3rd party apps.
static QgsStyleModel * defaultStyleModel()
Returns a shared QgsStyleModel containing the default style library (see QgsStyle::defaultStyle()).
static QString relativePathToAbsolutePath(const QString &rpath, const QString &targetPath)
Converts path relative to target to an absolute path.
static void setSvgPaths(const QStringList &svgPaths)
Sets the paths to svg directories and invalidates the svg path list cache.
static QgsBabelFormatRegistry * gpsBabelFormatRegistry()
Returns the application's GPSBabel format registry, used for managing GPSBabel formats.
static endian_t endian()
Returns whether this machine uses big or little endian.
int maxConcurrentConnectionsPerPool() const
The maximum number of concurrent connections per connections pool.
static void setCustomVariable(const QString &name, const QVariant &value)
Set a single custom expression variable.
void requestForTranslatableObjects(QgsTranslationContext *translationContext)
Emitted when project strings which require translation are being collected for inclusion in a ....
static QString iconsPath()
Returns the path to the icons image directory.
static Qgs3DSymbolRegistry * symbol3DRegistry()
Returns registry of available 3D symbols.
static QgsExternalStorageRegistry * externalStorageRegistry()
Returns registry of available external storage implementations.
static QHash< QString, QString > uiThemes()
All themes found in ~/.qgis3/themes folder.
static QString splashPath()
Returns the path to the splash screen image directory.
static QString donorsFilePath()
Returns the path to the donors file.
static QString themeName()
Set the active theme to the specified theme.
void nullRepresentationChanged()
Emitted when the string representing the NULL value is changed.
static QString srsDatabaseFilePath()
Returns the path to the srs.db file.
static QString userThemesFolder()
Returns the path to user's themes folder.
static void registerGdalDriversFromSettings()
Register gdal drivers, excluding the ones mentioned in "gdal/skipList" setting.
static QgsPlotRegistry * plotRegistry()
Returns the application's plot registry, used for plot types.
static Qgs3DRendererRegistry * renderer3DRegistry()
Returns registry of available 3D renderers.
static QString iconPath(const QString &iconFile)
Returns path to the desired icon file.
static QgsTiledSceneRendererRegistry * tiledSceneRendererRegistry()
Returns the application's tiled scene renderer registry, used for managing tiled scene layer 2D rende...
static void setDefaultSvgPaths(const QStringList &pathList)
Alters default svg paths - used by 3rd party apps.
static QString libraryPath()
Returns the path containing qgis_core, qgis_gui, qgispython (and other) libraries.
static QStringList layoutTemplatePaths()
Returns the paths to layout template directories.
static const QgsSettingsEntryBool * settingsLocaleShowGroupSeparator
Settings entry locale show group separator.
static QString userFullName()
Returns the user's operating system login account full display name.
static Q_DECL_DEPRECATED QgsSettingsRegistryCore * settingsRegistryCore()
Returns the application's settings registry, used for managing application settings.
static QString serverResourcesPath()
Returns the path to the server resources directory.
static QString appIconPath()
Gets application icon.
static QString userLoginName()
Returns the user's operating system login account name.
Registry for authentication configuration storages.
Singleton which offers an interface to manage the authentication configuration database and to utiliz...
QgsAuthConfigurationStorageRegistry * authConfigurationStorageRegistry() const
Returns the authentication configuration storage registry.
void setup(const QString &pluginPath=QString(), const QString &authDatabasePath=QString())
Sets up the authentication manager configuration.
static QgsAuthManager * instance()
Enforce singleton pattern.
A registry for QgsAbstractBabelFormat GPSBabel formats.
Manages storage of a set of bookmarks.
void initialize(const QString &filePath)
Initializes the bookmark manager.
Registry of available callout classes.
Manages all known classification methods.
Registry of color schemes.
void addDefaultSchemes()
Adds all default color schemes to this color scheme.
void initStyleScheme()
Initializes the default random style color scheme for the user.
A registry for saved data provider connections, allowing retrieval of saved connections by name and p...
A registry for known coordinate reference system (CRS) definitions, including any user-defined CRSes.
static void invalidateCache(bool disableCache=false)
Clears the internal cache used to initialize QgsCoordinateReferenceSystem objects.
static void invalidateCache(bool disableCache=false)
Clears the internal cache used to initialize QgsCoordinateTransform objects.
A registry for data item providers that may add items to the browser tree.
Handles logging of database queries.
static void applyLocaleChange()
Adjusts the date time display formats according to locale.
static void invalidateCache(bool disableCache=false)
Clears the internal cache used.
Defines a QGIS exception class.
QString what() const
static void cleanRegisteredFunctions()
Deletes all registered functions whose ownership have been transferred to the expression engine.
Registry of external storage backends used by QgsExternalResourceWidget.
A registry which manages classes of QgsFieldFormatter.
Manages available fonts and font installation for a QGIS instance.
void installUserFonts()
Installs user fonts from the profile/fonts directory as application fonts.
Registers existing GPS connections such that the information is available to all classes and plugins.
A cache for images derived from raster files.
A registry for labeling engine rules.
Registry of layer metadata provider backends.
Registry of available layout item types.
static const QgsSettingsEntryStringList * settingsSearchPathForTemplates
Settings entry search path for templates.
Definition qgslayout.h:664
A registry class to hold localized data paths which can be used for basemaps, logos,...
Temporarily blocks the application QgsMessageLog (see QgsApplication::messageLog()) from emitting the...
Interface for logging messages from QGIS in GUI independent way.
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
Registry for temporary fetched files.
A registry which manages classes of QgsNumericFormat.
A registry for known page sizes.
Registry of available paint effects.
Registry of available plot types.
A registry of plugin layers types.
Registry of 2D renderers for point clouds.
Registry for various processing components, including providers, algorithms and various parameters an...
Registry of profile sources used by QgsProfilePlotRenderer.
static QStringList searchPaths()
Returns the current list of Proj file search paths.
Registry of storage backends that QgsProject may use.
static QgsProject * instance()
Returns the QgsProject singleton instance.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
Registry for raster renderers.
A convenience class that simplifies locking and unlocking QReadWriteLocks.
@ Write
Lock for write.
void changeMode(Mode mode)
Change the mode of the lock to mode.
Handles and tracks style items recently used in the QGIS GUI.
Registry of renderers.
Provides a method of recording run time profiles of operations, allowing easy recording of their over...
A registry which manages registered scalebar renderers.
Scoped object for logging of the runtime for a single operation or group of operations.
Registry of available sensor types.
A boolean settings entry.
An integer settings entry.
A string list settings entry.
A string settings entry.
Custom exception class for settings related exceptions.
Used for settings introspection and collects all QgsSettingsEntry instances of core.
static QgsSettingsTreeNode * sTreeLocale
static QgsSettingsTreeNode * sTreeSvg
static QgsSettingsTreeNode * sTreeCore
Stores settings for use within QGIS.
Definition qgssettings.h:68
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
bool contains(const QString &key, QgsSettings::Section section=QgsSettings::NoSection) const
Returns true if there exists a setting called key; returns false otherwise.
void beginGroup(const QString &prefix, QgsSettings::Section section=QgsSettings::NoSection)
Appends prefix to the current group.
QStringList childKeys() const
Returns a list of all top-level keys that can be read using the QSettings object.
void remove(const QString &key, QgsSettings::Section section=QgsSettings::NoSection)
Removes the setting key and any sub-settings of key in a section.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
A cache for source strings that returns a local file path containing the source content.
A QAbstractItemModel subclass for showing symbol and color ramp entities contained within a QgsStyle ...
A database of saved style entities, including symbols, color ramps, text formats and others.
Definition qgsstyle.h:89
static void cleanDefaultStyle()
Deletes the default style. Only to be used by QgsApplication::exitQgis().
Definition qgsstyle.cpp:207
static QgsStyle * defaultStyle(bool initialize=true)
Returns the default application-wide style.
Definition qgsstyle.cpp:150
A cache for images / pictures derived from SVG files.
QImage svgAsImage(const QString &path, double size, const QColor &fill, const QColor &stroke, double strokeWidth, double widthScaleFactor, bool &fitsInCache, double fixedAspectRatio=0, bool blocking=false, const QMap< QString, QString > &parameters=QMap< QString, QString >())
Returns an SVG drawing as a QImage.
QByteArray svgContent(const QString &path, double size, const QColor &fill, const QColor &stroke, double strokeWidth, double widthScaleFactor, double fixedAspectRatio=0, bool blocking=false, const QMap< QString, QString > &parameters=QMap< QString, QString >(), bool *isMissingImage=nullptr)
Gets the SVG content corresponding to the given path.
Registry of available symbol layer classes.
static QColor decodeColor(const QString &str)
Task manager for managing a set of long-running QgsTask tasks.
Tile download manager handles downloads of map tiles for the purpose of map rendering.
QgsTileDownloadManagerReply * get(const QNetworkRequest &request)
Starts a request.
Registry of 2D renderers for tiled scenes.
Used for the collecting of strings from projects for translation and creation of ts files.
A manager for QGIS user profiles.
std::unique_ptr< QgsUserProfile > getProfile(const QString &defaultProfile="default", bool createNew=true, bool initSettings=true)
Returns the profile from the given root profile location.
static QString resolveProfilesFolder(const QString &basePath=QString())
Resolves the profiles folder for the given path.
A registry that keeps a list of QgsAbstractValidityCheck checks which can be used when performing val...
Unique pointer for sqlite3 databases, which automatically closes the database when the pointer goes o...
int open(const QString &path)
Opens the database at the specified file path.
QMap< QString, QString > QgsStringMap
Definition qgis.h:7448
void registerMetaTypes()
QObject * ABISYM(QgsApplication::mFileOpenEventReceiver)
Q_GLOBAL_STATIC_WITH_ARGS(PalPropertyList, palHiddenProperties,({ static_cast< int >(QgsPalLayerSettings::Property::PositionX), static_cast< int >(QgsPalLayerSettings::Property::PositionY), static_cast< int >(QgsPalLayerSettings::Property::Show), static_cast< int >(QgsPalLayerSettings::Property::LabelRotation), static_cast< int >(QgsPalLayerSettings::Property::Family), static_cast< int >(QgsPalLayerSettings::Property::FontStyle), static_cast< int >(QgsPalLayerSettings::Property::Size), static_cast< int >(QgsPalLayerSettings::Property::Bold), static_cast< int >(QgsPalLayerSettings::Property::Italic), static_cast< int >(QgsPalLayerSettings::Property::Underline), static_cast< int >(QgsPalLayerSettings::Property::Color), static_cast< int >(QgsPalLayerSettings::Property::Strikeout), static_cast< int >(QgsPalLayerSettings::Property::MultiLineAlignment), static_cast< int >(QgsPalLayerSettings::Property::BufferSize), static_cast< int >(QgsPalLayerSettings::Property::BufferDraw), static_cast< int >(QgsPalLayerSettings::Property::BufferColor), static_cast< int >(QgsPalLayerSettings::Property::LabelDistance), static_cast< int >(QgsPalLayerSettings::Property::Hali), static_cast< int >(QgsPalLayerSettings::Property::Vali), static_cast< int >(QgsPalLayerSettings::Property::ScaleVisibility), static_cast< int >(QgsPalLayerSettings::Property::MinScale), static_cast< int >(QgsPalLayerSettings::Property::MaxScale), static_cast< int >(QgsPalLayerSettings::Property::AlwaysShow), static_cast< int >(QgsPalLayerSettings::Property::CalloutDraw), static_cast< int >(QgsPalLayerSettings::Property::LabelAllParts) })) Q_GLOBAL_STATIC_WITH_ARGS(SymbolPropertyList
const QString cacheKey(const QString &pathIn)
Q_GLOBAL_STATIC(QReadWriteLock, sDefinitionCacheLock)
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59
std::unique_ptr< QgsBookmarkManager > mBookmarkManager
std::unique_ptr< QgsRasterRendererRegistry > mRasterRendererRegistry
std::unique_ptr< QgsProcessingRegistry > mProcessingRegistry
std::unique_ptr< QgsTaskManager > mTaskManager
std::unique_ptr< QgsAnnotationRegistry > mAnnotationRegistry
std::unique_ptr< QgsCoordinateReferenceSystemRegistry > mCrsRegistry
std::unique_ptr< QgsGpsConnectionRegistry > mGpsConnectionRegistry
std::unique_ptr< QgsLabelingEngineRuleRegistry > mLabelingEngineRuleRegistry
std::unique_ptr< QgsPointCloudRendererRegistry > mPointCloudRendererRegistry
std::unique_ptr< QgsRendererRegistry > mRendererRegistry
std::unique_ptr< Qgs3DSymbolRegistry > m3DSymbolRegistry
std::unique_ptr< QgsPlotRegistry > mPlotRegistry
std::unique_ptr< QgsApplicationThemeRegistry > mApplicationThemeRegistry
std::unique_ptr< QgsRecentStyleHandler > mRecentStyleHandler
std::unique_ptr< QgsClassificationMethodRegistry > mClassificationMethodRegistry
std::unique_ptr< QgsSensorRegistry > mSensorRegistry
std::unique_ptr< QgsPluginLayerRegistry > mPluginLayerRegistry
std::unique_ptr< QgsDatabaseQueryLog > mQueryLogger
std::unique_ptr< QgsScaleBarRendererRegistry > mScaleBarRendererRegistry
std::unique_ptr< QgsNumericFormatRegistry > mNumericFormatRegistry
std::unique_ptr< QgsLayoutItemRegistry > mLayoutItemRegistry
std::unique_ptr< QgsTiledSceneRendererRegistry > mTiledSceneRendererRegistry
std::unique_ptr< QgsStyleModel > mStyleModel
std::unique_ptr< QgsAnnotationItemRegistry > mAnnotationItemRegistry
std::unique_ptr< QgsImageCache > mImageCache
std::unique_ptr< Qgs3DRendererRegistry > m3DRendererRegistry
std::unique_ptr< QgsCalloutRegistry > mCalloutRegistry
std::unique_ptr< QgsSourceCache > mSourceCache
std::unique_ptr< QgsFontManager > mFontManager
std::unique_ptr< QgsSettingsRegistryCore > mSettingsRegistryCore
std::unique_ptr< QgsPageSizeRegistry > mPageSizeRegistry
std::unique_ptr< QgsExternalStorageRegistry > mExternalStorageRegistry
std::unique_ptr< QgsProfileSourceRegistry > mProfileSourceRegistry
std::unique_ptr< QgsSvgCache > mSvgCache
std::unique_ptr< QgsPaintEffectRegistry > mPaintEffectRegistry
std::unique_ptr< QgsColorSchemeRegistry > mColorSchemeRegistry
std::unique_ptr< QgsActionScopeRegistry > mActionScopeRegistry
std::unique_ptr< QgsBabelFormatRegistry > mGpsBabelFormatRegistry
std::unique_ptr< QgsTileDownloadManager > mTileDownloadManager
std::unique_ptr< QgsValidityCheckRegistry > mValidityCheckRegistry
std::unique_ptr< QgsNetworkContentFetcherRegistry > mNetworkContentFetcherRegistry
std::unique_ptr< QgsConnectionRegistry > mConnectionRegistry
std::unique_ptr< QgsFieldFormatterRegistry > mFieldFormatterRegistry
std::unique_ptr< QgsProjectStorageRegistry > mProjectStorageRegistry
std::unique_ptr< QgsMessageLog > mMessageLog
std::unique_ptr< QgsLocalizedDataPathRegistry > mLocalizedDataPathRegistry
std::unique_ptr< QgsLayerMetadataProviderRegistry > mLayerMetadataProviderRegistry
std::unique_ptr< QgsSymbolLayerRegistry > mSymbolLayerRegistry