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