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