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