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