79 #include "processing/models/qgsprocessingmodelchildparametersource.h"
80 #include "processing/models/qgsprocessingmodelchilddependency.h"
84 #include <QDesktopWidget>
88 #include <QFileOpenEvent>
89 #include <QMessageBox>
92 #include <QProcessEnvironment>
95 #include <QThreadPool>
98 #include <QLibraryInfo>
99 #include <QStandardPaths>
100 #include <QRegularExpression>
101 #include <QTextStream>
104 #include <netinet/in.h>
110 #define SECURITY_WIN32
111 #include <security.h>
113 #pragma comment( lib, "Secur32.lib" )
117 #include "qgsconfig.h"
121 #include <cpl_conv.h>
125 #if PROJ_VERSION_MAJOR>=6
130 #define CONN_POOL_MAX_CONCURRENT_CONNS 4
132 QObject *
ABISYM( QgsApplication::mFileOpenEventReceiver ) =
nullptr;
133 bool ABISYM( QgsApplication::mInitialized ) =
false;
134 bool ABISYM( QgsApplication::mRunningFromBuildDir ) =
false;
138 QgsApplication::ApplicationMembers *QgsApplication::sApplicationMembers =
nullptr;
140 int ABISYM( QgsApplication::sMaxThreads ) = -1;
157 #if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
171 : QApplication( argc, argv, GUIenabled )
173 *sPlatformName() = platformName;
175 if ( *sTranslation() != QLatin1String(
"C" ) )
177 mQgisTranslator =
new QTranslator();
178 if ( mQgisTranslator->load( QStringLiteral(
"qgis_" ) + *sTranslation(), i18nPath() ) )
180 installTranslator( mQgisTranslator );
184 QgsDebugMsgLevel( QStringLiteral(
"loading of qgis translation failed %1/qgis_%2" ).arg( i18nPath(), *sTranslation() ), 2 );
192 mQtTranslator =
new QTranslator();
193 if ( mQtTranslator->load( QStringLiteral(
"qt_" ) + *sTranslation(), QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ) )
195 installTranslator( mQtTranslator );
199 QgsDebugMsgLevel( QStringLiteral(
"loading of qt translation failed %1/qt_%2" ).arg( QLibraryInfo::location( QLibraryInfo::TranslationsPath ), *sTranslation() ), 2 );
203 mApplicationMembers =
new ApplicationMembers();
205 *sProfilePath() = profileFolder;
210 if ( profileFolder.isEmpty() )
212 if ( getenv(
"QGIS_CUSTOM_CONFIG_PATH" ) )
214 profileFolder = getenv(
"QGIS_CUSTOM_CONFIG_PATH" );
218 profileFolder = QStandardPaths::standardLocations( QStandardPaths::AppDataLocation ).value( 0 );
225 profileFolder = profile->
folder();
229 *sProfilePath() = profileFolder;
231 static std::once_flag sMetaTypesRegistered;
232 std::call_once( sMetaTypesRegistered, []
234 qRegisterMetaType<QgsGeometry::Error>(
"QgsGeometry::Error" );
235 qRegisterMetaType<QgsProcessingFeatureSourceDefinition>(
"QgsProcessingFeatureSourceDefinition" );
236 qRegisterMetaType<QgsProcessingOutputLayerDefinition>(
"QgsProcessingOutputLayerDefinition" );
237 qRegisterMetaType<QgsUnitTypes::LayoutUnit>(
"QgsUnitTypes::LayoutUnit" );
238 qRegisterMetaType<QgsFeatureId>(
"QgsFeatureId" );
239 qRegisterMetaType<QgsFeatureIds>(
"QgsFeatureIds" );
240 qRegisterMetaType<QgsProperty>(
"QgsProperty" );
241 qRegisterMetaType<QgsFeatureStoreList>(
"QgsFeatureStoreList" );
242 qRegisterMetaType<Qgis::MessageLevel>(
"Qgis::MessageLevel" );
243 qRegisterMetaType<QgsReferencedRectangle>(
"QgsReferencedRectangle" );
244 qRegisterMetaType<QgsReferencedPointXY>(
"QgsReferencedPointXY" );
245 qRegisterMetaType<QgsReferencedGeometry>(
"QgsReferencedGeometry" );
246 qRegisterMetaType<QgsLayoutRenderContext::Flags>(
"QgsLayoutRenderContext::Flags" );
247 qRegisterMetaType<QgsStyle::StyleEntity>(
"QgsStyle::StyleEntity" );
248 qRegisterMetaType<QgsCoordinateReferenceSystem>(
"QgsCoordinateReferenceSystem" );
249 qRegisterMetaType<QgsAuthManager::MessageLevel>(
"QgsAuthManager::MessageLevel" );
250 qRegisterMetaType<QgsNetworkRequestParameters>(
"QgsNetworkRequestParameters" );
251 qRegisterMetaType<QgsNetworkReplyContent>(
"QgsNetworkReplyContent" );
252 qRegisterMetaType<QgsGeometry>(
"QgsGeometry" );
253 qRegisterMetaType<QgsDatumTransform::GridDetails>(
"QgsDatumTransform::GridDetails" );
254 qRegisterMetaType<QgsDatumTransform::TransformDetails>(
"QgsDatumTransform::TransformDetails" );
255 qRegisterMetaType<QgsNewsFeedParser::Entry>(
"QgsNewsFeedParser::Entry" );
256 qRegisterMetaType<QgsRectangle>(
"QgsRectangle" );
257 qRegisterMetaType<QgsLocatorResult>(
"QgsLocatorResult" );
258 qRegisterMetaType<QgsProcessingModelChildParameterSource>(
"QgsProcessingModelChildParameterSource" );
259 qRegisterMetaTypeStreamOperators<QgsProcessingModelChildParameterSource>(
"QgsProcessingModelChildParameterSource" );
260 qRegisterMetaType<QgsRemappingSinkDefinition>(
"QgsRemappingSinkDefinition" );
261 qRegisterMetaType<QgsProcessingModelChildDependency>(
"QgsProcessingModelChildDependency" );
262 qRegisterMetaType<QgsTextFormat>(
"QgsTextFormat" );
263 QMetaType::registerComparators<QgsProcessingModelChildDependency>();
264 QMetaType::registerEqualsComparator<QgsProcessingFeatureSourceDefinition>();
265 QMetaType::registerEqualsComparator<QgsProperty>();
266 qRegisterMetaType<QPainter::CompositionMode>(
"QPainter::CompositionMode" );
267 qRegisterMetaType<QgsDateTimeRange>(
"QgsDateTimeRange" );
272 if ( ABISYM( mRunningFromBuildDir ) )
275 *sPrefixPath() = QString();
276 #if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
277 setPluginPath( *sBuildOutputPath() +
'/' + QString( QGIS_PLUGIN_SUBDIR ) +
'/' + *sCfgIntDir() );
279 setPluginPath( *sBuildOutputPath() +
'/' + QStringLiteral( QGIS_PLUGIN_SUBDIR ) );
281 setPkgDataPath( *sBuildOutputPath() + QStringLiteral(
"/data" ) );
282 *sLibraryPath() = *sBuildOutputPath() +
'/' + QGIS_LIB_SUBDIR +
'/';
283 #if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
284 *sLibexecPath() = *sBuildOutputPath() +
'/' + QGIS_LIBEXEC_SUBDIR +
'/' + *sCfgIntDir() +
'/';
286 *sLibexecPath() = *sBuildOutputPath() +
'/' + QGIS_LIBEXEC_SUBDIR +
'/';
288 #if defined( HAVE_QUICK )
289 *sQmlImportPath() = *sBuildOutputPath() +
'/' + QGIS_QML_SUBDIR +
'/';
294 char *
prefixPath = getenv(
"QGIS_PREFIX_PATH" );
297 if ( sPrefixPath()->isNull() )
299 #if defined(Q_OS_MACX) || defined(Q_OS_WIN)
301 #elif defined(ANDROID)
303 QDir myDir( QDir::homePath() );
305 QString myPrefix = myDir.absolutePath();
308 QDir myDir( applicationDirPath() );
310 if ( applicationDirPath().contains( QStringLiteral(
"cgi-bin" ) ) )
315 QString myPrefix = myDir.absolutePath();
326 *sConfigPath() = profileFolder +
'/';
330 if ( getenv(
"QGIS_AUTH_DB_DIR_PATH" ) )
336 QMap<QString, QString> systemEnvVarMap;
337 QString passfile( QStringLiteral(
"QGIS_AUTH_PASSWORD_FILE" ) );
339 const auto systemEnvironment = QProcessEnvironment::systemEnvironment().toStringList();
340 for (
const QString &varStr : systemEnvironment )
342 int pos = varStr.indexOf( QLatin1Char(
'=' ) );
345 QString varStrName = varStr.left( pos );
346 QString varStrValue = varStr.mid( pos + 1 );
347 if ( varStrName != passfile )
349 systemEnvVarMap.insert( varStrName, varStrValue );
352 *sSystemEnvVars() = systemEnvVarMap;
354 #if PROJ_VERSION_MAJOR>=6
360 QString projLib( QDir::cleanPath(
pkgDataPath().append(
"/proj" ) ) );
361 if ( QFile::exists( projLib ) )
363 currentProjSearchPaths.append( projLib );
367 char **newPaths =
new char *[currentProjSearchPaths.length()];
368 for (
int i = 0; i < currentProjSearchPaths.count(); ++i )
370 newPaths[i] = CPLStrdup( currentProjSearchPaths.at( i ).toUtf8().constData() );
372 proj_context_set_search_paths(
nullptr, currentProjSearchPaths.count(), newPaths );
373 for (
int i = 0; i < currentProjSearchPaths.count(); ++i )
375 CPLFree( newPaths[i] );
381 QCoreApplication::addLibraryPath(
pluginPath() );
386 ABISYM( sMaxThreads ) = -1;
399 if ( !members()->mStyleModel )
402 ABISYM( mInitialized ) =
true;
407 delete mDataItemProviderRegistry;
408 delete mApplicationMembers;
409 delete mQgisTranslator;
410 delete mQtTranslator;
418 void QgsApplication::invalidateCaches()
430 return qobject_cast<QgsApplication *>( QCoreApplication::instance() );
436 if (
event->type() == QEvent::FileOpen )
439 if ( ABISYM( mFileOpenEventReceiver ) )
442 done =
notify( ABISYM( mFileOpenEventReceiver ),
event );
449 sFileOpenEventList()->append(
static_cast<QFileOpenEvent *
>(
event )->file() );
456 done = QApplication::event(
event );
465 if ( thread() == receiver->thread() )
475 done = QApplication::notify( receiver,
event );
479 qCritical() <<
"Caught unhandled QgsException: " << e.
what();
480 if ( qApp->thread() == QThread::currentThread() )
481 QMessageBox::critical( activeWindow(), tr(
"Exception" ), e.
what() );
483 catch ( std::exception &e )
485 qCritical() <<
"Caught unhandled std::exception: " << e.
what();
486 if ( qApp->thread() == QThread::currentThread() )
487 QMessageBox::critical( activeWindow(), tr(
"Exception" ), e.
what() );
491 qCritical() <<
"Caught unhandled unknown exception";
492 if ( qApp->thread() == QThread::currentThread() )
493 QMessageBox::critical( activeWindow(), tr(
"Exception" ), tr(
"unknown exception" ) );
501 return QgsRuntimeProfiler::threadLocalInstance();
507 ABISYM( mFileOpenEventReceiver ) = receiver;
509 if ( sFileOpenEventList()->count() > 0 )
511 const QStringList fileOpenEventList = *sFileOpenEventList();
512 for (
const QString &file : fileOpenEventList )
514 QFileOpenEvent foe( file );
515 QgsApplication::sendEvent( ABISYM( mFileOpenEventReceiver ), &foe );
517 sFileOpenEventList()->clear();
524 #if defined(Q_OS_WIN)
525 if ( sPrefixPath()->endsWith(
"/bin" ) )
527 sPrefixPath()->chop( 4 );
530 if ( useDefaultPaths && !ABISYM( mRunningFromBuildDir ) )
532 setPluginPath( *sPrefixPath() +
'/' + QStringLiteral( QGIS_PLUGIN_SUBDIR ) );
533 setPkgDataPath( *sPrefixPath() +
'/' + QStringLiteral( QGIS_DATA_SUBDIR ) );
535 *sLibraryPath() = *sPrefixPath() +
'/' + QGIS_LIB_SUBDIR +
'/';
536 *sLibexecPath() = *sPrefixPath() +
'/' + QGIS_LIBEXEC_SUBDIR +
'/';
537 #if defined( HAVE_QUICK )
538 *sQmlImportPath() = *sPrefixPath() +
'/' + QGIS_QML_SUBDIR +
'/';
551 QString mySvgPath =
pkgDataPath + QStringLiteral(
"/svg/" );
554 if ( !sDefaultSvgPaths()->contains( mySvgPath ) )
555 *sDefaultSvgPaths() << mySvgPath;
560 *sDefaultSvgPaths() = pathList;
565 QFileInfo fi( authDbDirPath );
566 if ( fi.exists() && fi.isDir() && fi.isWritable() )
568 *sAuthDbDirPath() = fi.canonicalFilePath() + QDir::separator();
575 if ( ABISYM( mRunningFromBuildDir ) )
577 static bool sOnce =
true;
581 ( void ) blockNotifications;
582 qWarning(
"!!! prefix path was requested, but it is not valid - we do not run from installed path !!!" );
588 return *sPrefixPath();
592 return *sPluginPath();
597 if ( sPkgDataPath()->isNull() )
600 return *sPkgDataPath();
605 return QStringLiteral(
":/images/themes/default/" );
610 QDir dir( usersThemes );
618 return defaultThemes;
624 return iconsPath() + QStringLiteral(
"qgis-icon-60x60.png" );
629 return ABISYM( sMaxThreads );
636 if ( QFile::exists( path + iconFile ) )
637 return path + iconFile;
646 if ( app && app->mIconCache.contains( name ) )
647 return app->mIconCache.value( name );
651 QString myPreferredPath =
activeThemePath() + QDir::separator() + name;
653 if ( QFile::exists( myPreferredPath ) )
655 icon = QIcon( myPreferredPath );
657 else if ( QFile::exists( myDefaultPath ) )
661 icon = QIcon( myDefaultPath );
669 app->mIconCache.insert( name, icon );
676 if ( app && app->mCursorCache.contains( cursor ) )
677 return app->mCursorCache.value( cursor );
688 name = QStringLiteral(
"mZoomIn.svg" );
693 name = QStringLiteral(
"mZoomOut.svg" );
700 name = QStringLiteral(
"mIdentify.svg" );
703 name = QStringLiteral(
"mCrossHair.svg" );
706 name = QStringLiteral(
"mCapturePoint.svg" );
709 name = QStringLiteral(
"mSelect.svg" );
716 name = QStringLiteral(
"mSampler.svg" );
721 Q_ASSERT( ! name.isEmpty( ) );
723 QIcon icon =
getThemeIcon( QStringLiteral(
"cursors" ) + QDir::separator() + name );
726 if ( ! icon.isNull( ) )
730 cursorIcon = QCursor( icon.pixmap( std::ceil( scale * 32 ), std::ceil( scale * 32 ) ), std::ceil( scale * activeX ), std::ceil( scale * activeY ) );
733 app->mCursorCache.insert( cursor, cursorIcon );
740 const QString preferredPath =
activeThemePath() + QDir::separator() + name;
742 const QString path = QFile::exists( preferredPath ) ? preferredPath : defaultPath;
743 if ( foreColor.isValid() || backColor.isValid() )
745 bool fitsInCache =
false;
746 const QImage image =
svgCache()->
svgAsImage( path, size, backColor, foreColor, 1, 1, fitsInCache );
747 return QPixmap::fromImage( image );
750 return QPixmap( path );
760 static QString appPath;
761 if ( appPath.isNull() )
763 if ( QCoreApplication::instance() )
765 appPath = applicationDirPath();
769 qWarning(
"Application path not initialized" );
773 if ( !appPath.isNull() || getenv(
"QGIS_PREFIX_PATH" ) )
775 QString prefix = getenv(
"QGIS_PREFIX_PATH" ) ? getenv(
"QGIS_PREFIX_PATH" ) : appPath;
780 static const QStringList paths { QStringList() << QString() << QStringLiteral(
"/.." ) << QStringLiteral(
"/bin" ) << QStringLiteral(
"/../../.." ) };
781 for (
const QString &path : paths )
783 f.setFileName( prefix + path +
"/qgisbuildpath.txt" );
787 if ( f.exists() && f.open( QIODevice::ReadOnly ) )
789 ABISYM( mRunningFromBuildDir ) =
true;
790 *sBuildSourcePath() = f.readLine().trimmed();
791 *sBuildOutputPath() = f.readLine().trimmed();
793 QgsDebugMsgLevel( QStringLiteral(
"- source directory: %1" ).arg( sBuildSourcePath()->toUtf8().constData() ), 4 );
794 QgsDebugMsgLevel( QStringLiteral(
"- output directory of the build: %1" ).arg( sBuildOutputPath()->toUtf8().constData() ), 4 );
795 #if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
796 *sCfgIntDir() = prefix.split(
'/', QString::SkipEmptyParts ).last();
797 qDebug(
"- cfg: %s", sCfgIntDir()->toUtf8().constData() );
803 if ( getenv(
"QGIS_PREFIX_PATH" ) )
809 QDir dir( QDir::homePath() );
814 #if defined(Q_OS_MACX)
816 #elif defined(Q_OS_WIN)
823 if ( appPath.contains( QStringLiteral(
"cgi-bin" ) ) )
833 if ( ABISYM( mRunningFromBuildDir ) )
834 return *sBuildOutputPath() + QStringLiteral(
"/data" );
836 return prefixPath +
'/' + QStringLiteral( QGIS_DATA_SUBDIR );
841 return *sThemeName();
851 qApp->setStyleSheet( QString() );
855 QString path = themes.value(
themeName );
856 QString stylesheetname = path +
"/style.qss";
858 QFile file( stylesheetname );
859 QFile variablesfile( path +
"/variables.qss" );
861 QFileInfo variableInfo( variablesfile );
863 if ( !file.open( QIODevice::ReadOnly ) || ( variableInfo.exists() && !variablesfile.open( QIODevice::ReadOnly ) ) )
868 QString styledata = file.readAll();
869 styledata.replace( QLatin1String(
"@theme_path" ), path );
871 if ( variableInfo.exists() )
873 QTextStream in( &variablesfile );
874 while ( !in.atEnd() )
876 QString line = in.readLine();
878 if ( line.startsWith(
'@' ) )
880 int index = line.indexOf(
':' );
881 QString name = line.mid( 0, index );
882 QString value = line.mid( index + 1, line.length() );
883 styledata.replace( name, value );
886 variablesfile.close();
894 const static QRegularExpression regex( QStringLiteral(
"(?<=[\\s:])([0-9\\.]+)(?=em)" ) );
895 QRegularExpressionMatch match = regex.match( styledata, index );
896 while ( match.hasMatch() )
898 index = match.capturedStart();
899 styledata.remove( index, match.captured( 0 ).length() );
901 styledata.insert( index, number );
902 index += number.length();
903 match = regex.match( styledata, index );
907 qApp->setStyleSheet( styledata );
909 QFile palettefile( path +
"/palette.txt" );
910 QFileInfo paletteInfo( palettefile );
911 if ( paletteInfo.exists() && palettefile.open( QIODevice::ReadOnly ) )
913 QPalette
pal = qApp->palette();
914 QTextStream in( &palettefile );
915 while ( !in.atEnd() )
917 QString line = in.readLine();
918 QStringList parts = line.split(
':' );
919 if ( parts.count() == 2 )
921 int role = parts.at( 0 ).trimmed().toInt();
923 pal.setColor(
static_cast< QPalette::ColorRole
>( role ), color );
927 qApp->setPalette(
pal );
936 QHash<QString, QString> mapping;
937 mapping.insert( QStringLiteral(
"default" ), QString() );
938 const auto constPaths = paths;
939 for (
const QString &path : constPaths )
942 QFileInfoList styleFiles = folder.entryInfoList( QDir::Dirs | QDir::NoDotAndDotDot );
943 const auto constStyleFiles = styleFiles;
944 for (
const QFileInfo &info : constStyleFiles )
946 QFileInfo styleFile( info.absoluteFilePath() +
"/style.qss" );
947 if ( !styleFile.exists() )
950 QString name = info.baseName();
951 QString path = info.absoluteFilePath();
952 mapping.insert( name, path );
960 return pkgDataPath() + QStringLiteral(
"/doc/AUTHORS" );
965 return pkgDataPath() + QStringLiteral(
"/doc/CONTRIBUTORS" );
969 return pkgDataPath() + QStringLiteral(
"/doc/developersmap.html" );
974 return pkgDataPath() + QStringLiteral(
"/doc/SPONSORS" );
979 return pkgDataPath() + QStringLiteral(
"/doc/DONORS" );
984 return pkgDataPath() + QStringLiteral(
"/doc/TRANSLATORS" );
989 return pkgDataPath() + QStringLiteral(
"/doc/LICENSE" );
994 if ( ABISYM( mRunningFromBuildDir ) )
995 return *sBuildOutputPath() + QStringLiteral(
"/i18n/" );
1002 return pkgDataPath() + QStringLiteral(
"/resources/metadata-ISO/" );
1007 return pkgDataPath() + QStringLiteral(
"/resources/qgis.db" );
1012 return *sConfigPath();
1022 return *sAuthDbDirPath() + QStringLiteral(
"qgis-auth.db" );
1027 return QStringLiteral(
":/images/splash/" );
1032 return pkgDataPath() + QStringLiteral(
"/images/icons/" );
1037 if ( ABISYM( mRunningFromBuildDir ) )
1039 #if PROJ_VERSION_MAJOR>=6
1040 QString tempCopy = QDir::tempPath() +
"/srs6.db";
1042 QString tempCopy = QDir::tempPath() +
"/srs.db";
1045 if ( !QFile( tempCopy ).exists() )
1047 #if PROJ_VERSION_MAJOR>=6
1052 if ( !f.copy( tempCopy ) )
1054 qFatal(
"Could not create temporary copy" );
1062 return pkgDataPath() + QStringLiteral(
"/resources/srs.db" );
1069 members()->mSvgPathCacheValid =
false;
1074 static QReadWriteLock lock;
1078 if ( members()->mSvgPathCacheValid )
1080 return members()->mSvgPathCache;
1088 const QStringList pathList = settings.
value( QStringLiteral(
"svg/searchPathsForSVG" ) ).toStringList();
1092 for (
const QString &path : pathList )
1094 if ( !paths.contains( path ) )
1095 paths.append( path );
1097 for (
const QString &path : qgis::as_const( *sDefaultSvgPaths() ) )
1099 if ( !paths.contains( path ) )
1100 paths.append( path );
1102 members()->mSvgPathCache = paths;
1113 QStringList pathList = settings.
value( QStringLiteral(
"Layout/searchPathsForTemplates" ), QVariant(),
QgsSettings::Core ).toStringList();
1120 return *sSystemEnvVars();
1130 const thread_local QRegExp regexp( QStringLiteral(
"^[A-Za-z][A-Za-z0-9\\._-]*" ) );
1136 if ( !sUserName()->isEmpty() )
1137 return *sUserName();
1140 TCHAR name [ UNLEN + 1 ];
1141 DWORD size = UNLEN + 1;
1143 if ( GetUserName( ( TCHAR * )name, &size ) )
1145 *sUserName() = QString::fromLocal8Bit( name );
1148 #elif QT_CONFIG(process)
1151 process.start( QStringLiteral(
"whoami" ), QStringList() );
1152 process.waitForFinished();
1153 *sUserName() = process.readAllStandardOutput().trimmed();
1156 if ( !sUserName()->isEmpty() )
1157 return *sUserName();
1160 *sUserName() = qgetenv(
"USER" );
1161 if ( !sUserName()->isEmpty() )
1162 return *sUserName();
1165 *sUserName() = qgetenv(
"USERNAME" );
1166 return *sUserName();
1171 if ( !sUserFullName()->isEmpty() )
1172 return *sUserFullName();
1175 TCHAR name [ UNLEN + 1 ];
1176 DWORD size = UNLEN + 1;
1179 if ( GetUserNameEx( NameDisplay, ( TCHAR * )name, &size ) )
1181 *sUserFullName() = QString::fromLocal8Bit( name );
1185 if ( sUserFullName()->isEmpty() )
1187 #elif defined(Q_OS_ANDROID) || defined(__MINGW32__)
1188 *sUserFullName() = QStringLiteral(
"Not available" );
1190 struct passwd *p = getpwuid( getuid() );
1194 QString gecosName = QString( p->pw_gecos );
1195 *sUserFullName() = gecosName.left( gecosName.indexOf(
',', 0 ) );
1200 return *sUserFullName();
1205 #if defined(Q_OS_ANDROID)
1206 return QLatin1String(
"android" );
1207 #elif defined(Q_OS_MAC)
1208 return QLatin1String(
"osx" );
1209 #elif defined(Q_OS_WIN)
1210 return QLatin1String(
"windows" );
1211 #elif defined(Q_OS_LINUX)
1212 return QStringLiteral(
"linux" );
1213 #elif defined(Q_OS_FREEBSD)
1214 return QStringLiteral(
"freebsd" );
1215 #elif defined(Q_OS_OPENBSD)
1216 return QStringLiteral(
"openbsd" );
1217 #elif defined(Q_OS_NETBSD)
1218 return QStringLiteral(
"netbsd" );
1219 #elif defined(Q_OS_UNIX)
1220 return QLatin1String(
"unix" );
1222 return QLatin1String(
"unknown" );
1228 return *sPlatformName();
1234 bool overrideLocale = settings.
value( QStringLiteral(
"locale/overrideFlag" ),
false ).toBool();
1235 if ( overrideLocale )
1237 QString
locale = settings.
value( QStringLiteral(
"locale/userLocale" ), QString() ).toString();
1239 if (
locale.startsWith( QLatin1String(
"en" ), Qt::CaseInsensitive ) )
1248 return QLocale().name().left( 2 );
1259 return pkgDataPath() + QStringLiteral(
"/resources/symbology-style.xml" );
1264 return pkgDataPath() + QStringLiteral(
"/resources/themes" );
1269 return pkgDataPath() + QStringLiteral(
"/resources/server/" );
1274 return *sLibraryPath();
1279 return *sLibexecPath();
1284 return *sQmlImportPath();
1289 return ( htonl( 1 ) == 1 ) ?
XDR :
NDR;
1296 init( *sProfilePath() );
1321 if (
auto *lInstance =
instance() )
1323 if ( !lInstance->mAuthManager )
1327 return lInstance->mAuthManager;
1332 if ( !sAuthManager )
1334 return sAuthManager;
1342 QThreadPool::globalInstance()->waitForDone();
1345 if (
auto *lInstance =
instance() )
1346 delete lInstance->mAuthManager;
1348 delete sAuthManager;
1353 QgsApplication::sendPostedEvents(
nullptr, QEvent::DeferredDelete );
1361 if ( QgsProviderRegistry::exists() )
1370 GDALDestroyDriverManager();
1375 QString myEnvironmentVar( getenv(
"QGIS_PREFIX_PATH" ) );
1376 QString myState = tr(
"Application state:\n"
1377 "QGIS_PREFIX_PATH env var:\t\t%1\n"
1379 "Plugin Path:\t\t%3\n"
1380 "Package Data Path:\t%4\n"
1381 "Active Theme Name:\t%5\n"
1382 "Active Theme Path:\t%6\n"
1383 "Default Theme Path:\t%7\n"
1384 "SVG Search Paths:\t%8\n"
1385 "User DB Path:\t%9\n"
1386 "Auth DB Path:\t%10\n" )
1387 .arg( myEnvironmentVar,
1394 svgPaths().join( tr(
"\n\t\t",
"match indentation of application state" ) ),
1407 QColor myColor1( Qt::lightGray );
1408 QColor myColor2 = myColor1;
1409 myColor2 = myColor2.lighter( 110 );
1411 myStyle = QStringLiteral(
".overview{"
1413 " font-weight: bold;"
1416 " background: white;"
1418 " font-family: 'Lato', 'Open Sans', 'Lucida Grande', 'Segoe UI', 'Arial', sans-serif;"
1421 "h1{ background-color: #F6F6F6;"
1423 " font-size: x-large; "
1424 " font-weight: normal;"
1425 " background: none;"
1426 " padding: 0.75em 0 0;"
1428 " line-height: 3em;"
1430 "h2{ background-color: #F6F6F6;"
1432 " font-size: medium; "
1433 " font-weight: normal;"
1434 " background: none;"
1435 " padding: 0.75em 0 0;"
1437 " line-height: 1.1em;"
1439 "h3{ background-color: #F6F6F6;"
1441 " font-weight: bold;"
1442 " font-size: large;"
1443 " text-align: left;"
1444 " border-bottom: 5px solid #DCEB5C;"
1446 "h4{ background-color: #F6F6F6;"
1448 " font-weight: bold;"
1449 " font-size: medium;"
1450 " text-align: left;"
1452 "h5{ background-color: #F6F6F6;"
1454 " font-weight: bold;"
1455 " font-size: small;"
1456 " text-align: left;"
1458 "a{ color: #729FCF;"
1459 " font-family: arial,sans-serif;"
1461 "label{ background-color: #FFFFCC;"
1462 " border: 1px solid black;"
1464 " padding: 0px 3px; "
1465 " font-size: small;"
1468 " font-weight: bold;"
1473 " border-top: 1px solid black;"
1475 ".list-view .highlight {"
1476 " text-align: left;"
1479 " padding-right: 15px;"
1480 " padding-left: 20px;"
1481 " font-weight: bold;"
1483 ".tabular-view .odd-row {"
1484 " background-color: #f9f9f9;"
1487 " font-weight: bold;"
1488 " padding-top:25px;"
1492 switch ( styleSheetType )
1494 case StyleSheetType::Qt:
1495 myStyle += QStringLiteral(
1497 " border-collapse: collapse;"
1500 ".tabular-view th, .tabular-view td { "
1501 " border:1px solid black;"
1505 case StyleSheetType::WebBrowser:
1506 myStyle += QStringLiteral(
1511 "table.tabular-view, table.list-view { "
1512 " border-collapse: collapse;"
1513 " table-layout:fixed;"
1514 " width: 100% !important;"
1519 " line-height: inherit;"
1522 " word-wrap: break-word; "
1523 " vertical-align: top;"
1526 ".list-view th:first-child, .list-view td:first-child {"
1529 ".list-view.highlight { "
1530 " padding-left: inherit; "
1533 ".tabular-view th:first-child, .tabular-view td:first-child { "
1537 ".tabular-view th.strong { "
1538 " background-color: #eee; "
1541 ".tabular-view th, .tabular-view td { "
1542 " border: 1px solid #eee;"
1553 if ( 0 >= OGRGetDriverCount() )
1561 QString aPathUrl = aPath;
1562 QString tPathUrl = targetPath;
1563 #if defined( Q_OS_WIN )
1564 const Qt::CaseSensitivity cs = Qt::CaseInsensitive;
1566 aPathUrl.replace(
'\\',
'/' );
1567 if ( aPathUrl.startsWith(
"//" ) )
1570 aPathUrl =
"\\\\" + aPathUrl.mid( 2 );
1573 tPathUrl.replace(
'\\',
'/' );
1574 if ( tPathUrl.startsWith(
"//" ) )
1577 tPathUrl =
"\\\\" + tPathUrl.mid( 2 );
1580 const Qt::CaseSensitivity cs = Qt::CaseSensitive;
1583 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
1584 QStringList targetElems = tPathUrl.split(
'/', QString::SkipEmptyParts );
1585 QStringList aPathElems = aPathUrl.split(
'/', QString::SkipEmptyParts );
1587 QStringList targetElems = tPathUrl.split(
'/', Qt::SkipEmptyParts );
1588 QStringList aPathElems = aPathUrl.split(
'/', Qt::SkipEmptyParts );
1591 targetElems.removeAll( QStringLiteral(
"." ) );
1592 aPathElems.removeAll( QStringLiteral(
"." ) );
1596 while ( !aPathElems.isEmpty() &&
1597 !targetElems.isEmpty() &&
1598 aPathElems[0].compare( targetElems[0], cs ) == 0 )
1600 aPathElems.removeFirst();
1601 targetElems.removeFirst();
1611 if ( !targetElems.isEmpty() )
1614 for (
int i = 0; i < targetElems.size(); i++ )
1616 aPathElems.insert( 0, QStringLiteral(
".." ) );
1623 aPathElems.insert( 0, QStringLiteral(
"." ) );
1626 return aPathElems.join( QLatin1Char(
'/' ) );
1632 if ( !rpath.startsWith( QLatin1String(
"./" ) ) && !rpath.startsWith( QLatin1String(
"../" ) ) )
1637 QString rPathUrl = rpath;
1638 QString targetPathUrl = targetPath;
1640 #if defined(Q_OS_WIN)
1641 rPathUrl.replace(
'\\',
'/' );
1642 targetPathUrl.replace(
'\\',
'/' );
1644 bool uncPath = targetPathUrl.startsWith(
"//" );
1647 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
1648 QStringList srcElems = rPathUrl.split(
'/', QString::SkipEmptyParts );
1649 QStringList targetElems = targetPathUrl.split(
'/', QString::SkipEmptyParts );
1651 QStringList srcElems = rPathUrl.split(
'/', Qt::SkipEmptyParts );
1652 QStringList targetElems = targetPathUrl.split(
'/', Qt::SkipEmptyParts );
1655 #if defined(Q_OS_WIN)
1658 targetElems.insert( 0,
"" );
1659 targetElems.insert( 0,
"" );
1664 targetElems << srcElems;
1665 targetElems.removeAll( QStringLiteral(
"." ) );
1669 while ( ( pos = targetElems.indexOf( QLatin1String(
".." ) ) ) > 0 )
1672 targetElems.removeAt( pos - 1 );
1673 targetElems.removeAt( pos - 1 );
1676 #if !defined(Q_OS_WIN)
1678 targetElems.prepend( QString() );
1681 return targetElems.join( QLatin1Char(
'/' ) );
1686 return *sBuildSourcePath();
1691 return *sBuildOutputPath();
1694 #if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA)
1695 QString QgsApplication::cfgIntDir()
1697 return *sCfgIntDir();
1703 if ( sGdalSkipList()->contains( driver ) || driver.isEmpty() )
1707 *sGdalSkipList() << driver;
1713 if ( !sGdalSkipList()->contains( driver ) )
1717 int myPos = sGdalSkipList()->indexOf( driver );
1720 sGdalSkipList()->removeAt( myPos );
1727 return *sGdalSkipList();
1731 const QStringList &deferredSkippedGdalDrivers )
1745 QString joinedList, delimiter;
1746 if ( settings.
contains( QStringLiteral(
"gdal/skipDrivers" ) ) )
1748 joinedList = settings.
value( QStringLiteral(
"gdal/skipDrivers" ), QString() ).toString();
1749 delimiter = QStringLiteral(
"," );
1753 joinedList = settings.
value( QStringLiteral(
"gdal/skipList" ), QString() ).toString();
1754 delimiter = QStringLiteral(
" " );
1757 if ( !joinedList.isEmpty() )
1759 myList = joinedList.split( delimiter );
1761 *sGdalSkipList() = myList;
1767 return *sDeferredSkippedGdalDrivers();
1772 sGdalSkipList()->removeDuplicates();
1773 QStringList realDisabledDriverList;
1774 for (
const auto &driverName : *sGdalSkipList() )
1776 if ( !sDeferredSkippedGdalDrivers()->contains( driverName ) )
1777 realDisabledDriverList << driverName;
1779 QString myDriverList = realDisabledDriverList.join(
',' );
1780 QgsDebugMsgLevel( QStringLiteral(
"Gdal Skipped driver list set to:" ), 2 );
1782 CPLSetConfigOption(
"GDAL_SKIP", myDriverList.toUtf8() );
1789 QDir myDir( folder );
1790 if ( !myDir.exists() )
1792 myDir.mkpath( folder );
1798 void QgsApplication::copyPath(
const QString &src,
const QString &dst )
1801 if ( ! dir.exists() )
1804 const auto subDirectories = dir.entryList( QDir::Dirs | QDir::NoDotAndDotDot );
1805 for (
const QString &d : subDirectories )
1807 QString dst_path = dst + QDir::separator() + d;
1808 dir.mkpath( dst_path );
1809 copyPath( src + QDir::separator() + d, dst_path );
1812 const auto files = dir.entryList( QDir::Files );
1813 for (
const QString &f : files )
1815 QFile::copy( src + QDir::separator() + f, dst + QDir::separator() + f );
1824 QVariantMap variables;
1828 QStringList childKeys = settings.
childKeys();
1829 for ( QStringList::const_iterator it = childKeys.constBegin(); it != childKeys.constEnd(); ++it )
1832 variables.insert( name, settings.
value( name ) );
1842 QVariantMap::const_iterator it = variables.constBegin();
1845 for ( ; it != variables.constEnd(); ++it )
1847 settings.
setValue( it.key(), it.value() );
1858 settings.
setValue( QStringLiteral(
"variables/" ) + name, value );
1865 QFontMetrics fm( ( QFont() ) );
1866 const double scale = 1.1 * standardSize / 24;
1867 int scaledIconSize =
static_cast< int >( std::floor( std::max(
Qgis::UI_SCALE_FACTOR * fm.height() * scale,
static_cast< double >( standardSize ) ) ) );
1868 if ( applyDevicePixelRatio && QApplication::desktop() )
1869 scaledIconSize *= QApplication::desktop()->devicePixelRatio();
1870 return scaledIconSize;
1880 *sTranslation() = translation;
1890 ApplicationMembers *appMembers = members();
1891 if ( appMembers->mNullRepresentation.isNull() )
1893 appMembers->mNullRepresentation =
QgsSettings().
value( QStringLiteral(
"qgis/nullValue" ), QStringLiteral(
"NULL" ) ).toString();
1895 return appMembers->mNullRepresentation;
1900 ApplicationMembers *appMembers = members();
1914 return members()->mActionScopeRegistry;
1923 QDir myDir( myPamPath );
1924 if ( !myDir.exists() )
1926 myDir.mkpath( myPamPath );
1929 #if defined(Q_OS_WIN)
1930 CPLSetConfigOption(
"GDAL_PAM_PROXY_DIR", myPamPath.toUtf8() );
1934 int myChangeFlag = 0;
1935 setenv(
"GDAL_PAM_PROXY_DIR", myPamPath.toUtf8(), myChangeFlag );
1942 if ( !qgisPrivateDbFile.exists() )
1946 QFile masterFile( qgisMasterDbFileName );
1952 bool isDbFileCopied = masterFile.copy( qgisPrivateDbFile.fileName() );
1954 if ( !isDbFileCopied )
1958 *errorMessage = tr(
"[ERROR] Can not make qgis.db private copy" );
1963 QFile::Permissions perms = QFile( qgisPrivateDbFile.fileName() ).permissions();
1964 if ( !( perms & QFile::WriteOwner ) )
1966 if ( !qgisPrivateDbFile.setPermissions( perms | QFile::WriteOwner ) )
1970 *errorMessage = tr(
"Can not make '%1' user writable" ).arg( qgisPrivateDbFile.fileName() );
1984 *errorMessage = tr(
"Could not open qgis.db" );
1989 char *errmsg =
nullptr;
1990 int res = sqlite3_exec( database.get(),
"SELECT srs_id FROM tbl_srs LIMIT 0",
nullptr,
nullptr, &errmsg );
1991 if ( res != SQLITE_OK )
1993 sqlite3_free( errmsg );
1996 if ( sqlite3_exec( database.get(),
1997 "DROP INDEX IF EXISTS idx_srsauthid;"
1998 "CREATE TABLE tbl_srs ("
1999 "srs_id INTEGER PRIMARY KEY,"
2000 "description text NOT NULL,"
2001 "projection_acronym text NOT NULL,"
2002 "ellipsoid_acronym NOT NULL,"
2003 "parameters text NOT NULL,"
2005 "auth_name varchar,"
2007 "is_geo integer NOT NULL,"
2008 "deprecated boolean,"
2010 "CREATE INDEX idx_srsauthid on tbl_srs(auth_name,auth_id);",
nullptr,
nullptr, &errmsg ) != SQLITE_OK )
2014 *errorMessage = tr(
"Creation of missing tbl_srs in the private qgis.db failed.\n%1" ).arg( QString::fromUtf8( errmsg ) );
2016 sqlite3_free( errmsg );
2023 res = sqlite3_exec( database.get(),
"SELECT wkt FROM tbl_srs LIMIT 0",
nullptr,
nullptr, &errmsg );
2024 if ( res != SQLITE_OK )
2027 sqlite3_free( errmsg );
2028 if ( sqlite3_exec( database.get(),
2029 "DROP INDEX IF EXISTS idx_srsauthid;"
2030 "DROP TABLE IF EXISTS tbl_srs_bak;"
2031 "ALTER TABLE tbl_srs RENAME TO tbl_srs_bak;"
2032 "CREATE TABLE tbl_srs ("
2033 "srs_id INTEGER PRIMARY KEY,"
2034 "description text NOT NULL,"
2035 "projection_acronym text NOT NULL,"
2036 "ellipsoid_acronym NOT NULL,"
2037 "parameters text NOT NULL,"
2039 "auth_name varchar,"
2041 "is_geo integer NOT NULL,"
2042 "deprecated boolean,"
2044 "CREATE INDEX idx_srsauthid on tbl_srs(auth_name,auth_id);"
2045 "INSERT INTO tbl_srs(srs_id,description,projection_acronym,ellipsoid_acronym,parameters,srid,auth_name,auth_id,is_geo,deprecated) SELECT srs_id,description,projection_acronym,ellipsoid_acronym,parameters,srid,'','',is_geo,0 FROM tbl_srs_bak;"
2046 "DROP TABLE tbl_srs_bak",
nullptr,
nullptr, &errmsg ) != SQLITE_OK )
2050 *errorMessage = tr(
"Migration of private qgis.db failed.\n%1" ).arg( QString::fromUtf8( errmsg ) );
2052 sqlite3_free( errmsg );
2058 res = sqlite3_exec( database.get(),
"SELECT acronym FROM tbl_projection LIMIT 0",
nullptr,
nullptr, &errmsg );
2059 if ( res != SQLITE_OK )
2061 sqlite3_free( errmsg );
2064 if ( sqlite3_exec( database.get(),
2065 "CREATE TABLE tbl_projection ("
2066 "acronym varchar(20) NOT NULL PRIMARY KEY,"
2067 "name varchar(255) NOT NULL default '',"
2068 "notes varchar(255) NOT NULL default '',"
2069 "parameters varchar(255) NOT NULL default ''"
2070 ")",
nullptr,
nullptr, &errmsg ) != SQLITE_OK )
2074 *errorMessage = tr(
"Creation of missing tbl_projection in the private qgis.db failed.\n%1" ).arg( QString::fromUtf8( errmsg ) );
2076 sqlite3_free( errmsg );
2081 res = sqlite3_exec( database.get(),
"SELECT epsg FROM tbl_srs LIMIT 0",
nullptr,
nullptr, &errmsg );
2082 if ( res == SQLITE_OK )
2085 if ( sqlite3_exec( database.get(),
2086 "DROP INDEX IF EXISTS idx_srsauthid;"
2087 "DROP TABLE IF EXISTS tbl_srs_bak;"
2088 "ALTER TABLE tbl_srs RENAME TO tbl_srs_bak;"
2089 "CREATE TABLE tbl_srs ("
2090 "srs_id INTEGER PRIMARY KEY,"
2091 "description text NOT NULL,"
2092 "projection_acronym text NOT NULL,"
2093 "ellipsoid_acronym NOT NULL,"
2094 "parameters text NOT NULL,"
2096 "auth_name varchar,"
2098 "is_geo integer NOT NULL,"
2099 "deprecated boolean,"
2101 "CREATE INDEX idx_srsauthid on tbl_srs(auth_name,auth_id);"
2102 "INSERT INTO tbl_srs(srs_id,description,projection_acronym,ellipsoid_acronym,parameters,srid,auth_name,auth_id,is_geo,deprecated) SELECT srs_id,description,projection_acronym,ellipsoid_acronym,parameters,srid,'','',is_geo,0 FROM tbl_srs_bak;"
2103 "DROP TABLE tbl_srs_bak",
nullptr,
nullptr, &errmsg ) != SQLITE_OK )
2107 *errorMessage = tr(
"Migration of private qgis.db failed.\n%1" ).arg( QString::fromUtf8( errmsg ) );
2109 sqlite3_free( errmsg );
2115 sqlite3_free( errmsg );
2118 if ( sqlite3_exec( database.get(),
"DROP VIEW vw_srs",
nullptr,
nullptr, &errmsg ) != SQLITE_OK )
2120 QgsDebugMsg( QStringLiteral(
"vw_srs didn't exists in private qgis.db: %1" ).arg( errmsg ) );
2123 if ( sqlite3_exec( database.get(),
2124 "CREATE VIEW vw_srs AS"
2126 " a.description AS description"
2127 ",a.srs_id AS srs_id"
2128 ",a.is_geo AS is_geo"
2129 ",coalesce(b.name,a.projection_acronym) AS name"
2130 ",a.parameters AS parameters"
2131 ",a.auth_name AS auth_name"
2132 ",a.auth_id AS auth_id"
2133 ",a.deprecated AS deprecated"
2135 " LEFT OUTER JOIN tbl_projection b ON a.projection_acronym=b.acronym"
2136 " ORDER BY coalesce(b.name,a.projection_acronym),a.description",
nullptr,
nullptr, &errmsg ) != SQLITE_OK )
2140 *errorMessage = tr(
"Update of view in private qgis.db failed.\n%1" ).arg( QString::fromUtf8( errmsg ) );
2142 sqlite3_free( errmsg );
2155 if ( maxThreads < 1 || maxThreads > QThread::idealThreadCount() )
2166 QThreadPool::globalInstance()->setMaxThreadCount(
maxThreads );
2167 QgsDebugMsgLevel( QStringLiteral(
"set QThreadPool max thread count to %1" ).arg( QThreadPool::globalInstance()->maxThreadCount() ), 2 );
2172 return members()->mTaskManager;
2177 return members()->mColorSchemeRegistry;
2182 return members()->mPaintEffectRegistry;
2187 return members()->mRendererRegistry;
2192 return members()->mRasterRendererRegistry;
2197 return members()->mPointCloudRendererRegistry;
2202 if (
auto *lInstance =
instance() )
2204 if ( !
instance()->mDataItemProviderRegistry )
2208 return lInstance->mDataItemProviderRegistry;
2214 if ( !sDataItemProviderRegistry )
2216 return sDataItemProviderRegistry;
2222 return members()->mCrsRegistry;
2227 return members()->mSvgCache;
2232 return members()->mImageCache;
2237 return members()->mSourceCache;
2242 return members()->mNetworkContentFetcherRegistry;
2247 return members()->mValidityCheckRegistry;
2252 return members()->mSymbolLayerRegistry;
2257 return members()->mCalloutRegistry;
2262 return members()->mLayoutItemRegistry;
2267 return members()->mAnnotationItemRegistry;
2272 return members()->mGpsConnectionRegistry;
2277 return members()->mPluginLayerRegistry;
2282 return members()->mClassificationMethodRegistry;
2287 return members()->mBookmarkManager;
2292 return members()->mTileDownloadManager;
2297 return members()->mStyleModel;
2302 return members()->mMessageLog;
2307 return members()->mProcessingRegistry;
2312 return members()->mConnectionRegistry;
2317 return members()->mPageSizeRegistry;
2322 return members()->mAnnotationRegistry;
2327 return members()->mNumericFormatRegistry;
2332 return members()->mFieldFormatterRegistry;
2337 return members()->m3DRendererRegistry;
2342 return members()->m3DSymbolRegistry;
2347 return members()->mScaleBarRendererRegistry;
2352 return members()->mProjectStorageRegistry;
2357 return members()->mLocalizedDataPathRegistry;
2360 QgsApplication::ApplicationMembers::ApplicationMembers()
2369 profiler->
start( tr(
"Setup coordinate reference system registry" ) );
2374 profiler->
start( tr(
"Create connection registry" ) );
2379 profiler->
start( tr(
"Setup task manager" ) );
2384 profiler->
start( tr(
"Setup action scope registry" ) );
2389 profiler->
start( tr(
"Setup numeric formats" ) );
2394 profiler->
start( tr(
"Setup field formats" ) );
2399 profiler->
start( tr(
"Setup SVG cache" ) );
2404 profiler->
start( tr(
"Setup image cache" ) );
2409 profiler->
start( tr(
"Setup source cache" ) );
2414 profiler->
start( tr(
"Setup color scheme registry" ) );
2419 profiler->
start( tr(
"Setup paint effect" ) );
2424 profiler->
start( tr(
"Setup symbol layer registry" ) );
2429 profiler->
start( tr(
"Setup callout registry" ) );
2434 profiler->
start( tr(
"Setup renderer registry" ) );
2439 profiler->
start( tr(
"Setup raster renderer registry" ) );
2444 profiler->
start( tr(
"Setup point cloud renderer registry" ) );
2449 profiler->
start( tr(
"Setup GPS registry" ) );
2454 profiler->
start( tr(
"Setup plugin layer registry" ) );
2459 profiler->
start( tr(
"Setup Processing registry" ) );
2465 profiler->
start( tr(
"Setup layout item registry" ) );
2467 mLayoutItemRegistry->populate();
2471 profiler->
start( tr(
"Setup annotation registry" ) );
2472 mAnnotationRegistry =
new QgsAnnotationRegistry();
2476 profiler->
start( tr(
"Setup annotation item registry" ) );
2478 mAnnotationItemRegistry->populate();
2482 profiler->
start( tr(
"Setup 3D symbol registry" ) );
2487 profiler->
start( tr(
"Setup 3D renderer registry" ) );
2492 profiler->
start( tr(
"Setup project storage registry" ) );
2497 profiler->
start( tr(
"Setup network content cache" ) );
2502 profiler->
start( tr(
"Setup layout check registry" ) );
2507 profiler->
start( tr(
"Setup classification registry" ) );
2512 profiler->
start( tr(
"Setup bookmark manager" ) );
2517 profiler->
start( tr(
"Setup tile download manager" ) );
2522 profiler->
start( tr(
"Setup scalebar registry" ) );
2528 QgsApplication::ApplicationMembers::~ApplicationMembers()
2531 delete mTileDownloadManager;
2532 delete mScaleBarRendererRegistry;
2533 delete mValidityCheckRegistry;
2534 delete mActionScopeRegistry;
2535 delete m3DRendererRegistry;
2536 delete m3DSymbolRegistry;
2537 delete mAnnotationRegistry;
2538 delete mColorSchemeRegistry;
2539 delete mFieldFormatterRegistry;
2540 delete mGpsConnectionRegistry;
2542 delete mPaintEffectRegistry;
2543 delete mPluginLayerRegistry;
2544 delete mProcessingRegistry;
2545 delete mProjectStorageRegistry;
2546 delete mPageSizeRegistry;
2547 delete mAnnotationItemRegistry;
2548 delete mLayoutItemRegistry;
2549 delete mPointCloudRendererRegistry;
2550 delete mRasterRendererRegistry;
2551 delete mRendererRegistry;
2554 delete mSourceCache;
2555 delete mCalloutRegistry;
2556 delete mSymbolLayerRegistry;
2557 delete mTaskManager;
2558 delete mNetworkContentFetcherRegistry;
2559 delete mClassificationMethodRegistry;
2560 delete mNumericFormatRegistry;
2561 delete mBookmarkManager;
2562 delete mConnectionRegistry;
2563 delete mLocalizedDataPathRegistry;
2564 delete mCrsRegistry;
2567 QgsApplication::ApplicationMembers *QgsApplication::members()
2569 if (
auto *lInstance =
instance() )
2571 return lInstance->mApplicationMembers;
2575 static QMutex sMemberMutex( QMutex::Recursive );
2576 QMutexLocker lock( &sMemberMutex );
2577 if ( !sApplicationMembers )
2578 sApplicationMembers =
new ApplicationMembers();
2579 return sApplicationMembers;
static const double UI_SCALE_FACTOR
UI scaling factor.
Keeps track of 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.
Extends QApplication to provide access to QGIS specific resources such as theme paths,...
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 void setCustomVariables(const QVariantMap &customVariables)
Custom expression variables for this application.
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.
endian_t
Constants for endian-ness.
static QString qgisMasterDatabaseFilePath()
Returns the path to the master qgis.db file.
static void skipGdalDriver(const QString &driver)
Sets the GDAL_SKIP environment variable to include the specified driver and then calls GDALDriverMana...
static QString defaultThemePath()
Returns the path to the default theme directory.
static QgsPageSizeRegistry * pageSizeRegistry()
Returns the application's page size registry, used for managing layout page sizes.
static QgsValidityCheckRegistry * validityCheckRegistry()
Returns the application's validity check registry, used for managing validity checks.
static QgsDataItemProviderRegistry * dataItemProviderRegistry()
Returns the application's data item provider registry, which keeps a list of data item providers that...
static QString userStylePath()
Returns the path to user's style.
static QString platform()
Returns the QGIS platform name, e.g., "desktop" or "server".
static QgsProcessingRegistry * processingRegistry()
Returns the application's processing registry, used for managing processing providers,...
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 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()
This string is 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 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 QCursor getThemeCursor(Cursor cursor)
Helper to get a theme cursor.
static void init(QString profileFolder=QString())
This method initializes paths etc for QGIS.
static void setThemeName(const QString &themeName)
Set the active theme to the specified theme.
void customVariablesChanged()
Emitted whenever a custom global variable changes.
static QString buildSourcePath()
Returns path to the source directory. Valid only when running from build directory.
static QString buildOutputPath()
Returns path to the build output directory. Valid only when running from build directory.
bool notify(QObject *receiver, QEvent *event) override
Catch exceptions when sending event to receiver.
static int maxThreads()
Gets maximum concurrent thread count.
static QgsColorSchemeRegistry * colorSchemeRegistry()
Returns the application's color scheme registry, used for managing color schemes.
static QgsApplication * instance()
Returns the singleton instance of the QgsApplication.
static QString reportStyleSheet(QgsApplication::StyleSheetType styleSheetType=QgsApplication::StyleSheetType::Qt)
Returns a css style sheet for reports, the styleSheetType argument determines what type of stylesheet...
static QString pkgDataPath()
Returns the common root path of all application data directories.
static QgsScaleBarRendererRegistry * scaleBarRendererRegistry()
Gets the registry of available scalebar renderers.
static QgsLayoutItemRegistry * layoutItemRegistry()
Returns the application's layout item registry, used for layout item types.
static void setFileOpenEventReceiver(QObject *receiver)
Sets the FileOpen event receiver.
static QgsSymbolLayerRegistry * symbolLayerRegistry()
Returns the application's symbol layer registry, used for managing symbol layers.
static QgsRasterRendererRegistry * rasterRendererRegistry()
Returns the application's raster renderer registry, used for managing raster layer renderers.
static void applyGdalSkippedDrivers()
Apply the skipped drivers list to gdal.
static void setMaxThreads(int maxThreads)
Set maximum concurrent thread count.
static QRegExp shortNameRegExp()
Returns the short name regular expression for line edit validator.
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.
static QString translatorsFilePath()
Returns the path to the sponsors file.
static void setNullRepresentation(const QString &nullRepresentation)
This string is used to represent the value NULL throughout QGIS.
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 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 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 QString qgisSettingsDirPath()
Returns the path to the settings directory in user's home dir.
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.
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 QgsTaskManager * taskManager()
Returns the application's task manager, used for managing application wide background task handling.
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 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.
Cursor
The Cursor enum defines constants for QGIS custom cursors.
@ 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 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 setSkippedGdalDrivers(const QStringList &skippedGdalDrivers, const QStringList &deferredSkippedGdalDrivers)
Sets the list of gdal drivers that should be disabled (skippedGdalDrivers), but excludes for now the ...
static QgsRendererRegistry * rendererRegistry()
Returns the application's renderer registry, used for managing vector layer renderers.
static void setTranslation(const QString &translation)
Set translation.
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 QString developersMapFilePath()
Returns the path to the developers map file.
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 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()
This string is used to represent the value NULL throughout QGIS.
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 Qgs3DRendererRegistry * renderer3DRegistry()
Returns registry of available 3D renderers.
static QString iconPath(const QString &iconFile)
Returns path to the desired icon file.
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 QString userFullName()
Returns the user's operating system login account full display name.
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 QIcon getThemeIcon(const QString &name)
Helper to get a theme icon.
Singleton offering an interface to manage the authentication configuration database and to utilize co...
bool init(const QString &pluginPath=QString(), const QString &authDatabasePath=QString())
init initialize QCA, prioritize qca-ossl plugin and optionally set up the authentication database
static QgsAuthManager * instance()
Enforce singleton pattern.
Manages storage of a set of bookmarks.
void initialize(const QString &filePath)
Initializes the bookmark manager.
Registry of available callout classes.
This class 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.
This class keeps a list of data item providers that may add items to the browser tree.
static void invalidateCache(bool disableCache=false)
Clears the internal cache used.
Defines a QGIS exception class.
static void cleanRegisteredFunctions()
Deletes all registered functions whose ownership have been transferred to the expression engine.
A class to register / unregister existing GPS connections such that the information is available to a...
A cache for images derived from raster files.
Registry of available layout item types.
A registry class to hold localized data paths which can be used for basemaps, logos,...
Temporarily blocks the application QgsMessageLog (see QgsApplication::messageLog()) from emitting the...
Interface for logging messages from QGIS in GUI independent way.
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
Registry for temporary fetched files.
A registry for known page sizes.
Registry of available paint effects.
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...
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.
The QgsReadWriteLocker class is a convenience class that simplifies locking and unlocking QReadWriteL...
void changeMode(Mode mode)
Change the mode of the lock to mode.
Provides a method of recording run time profiles of operations, allowing easy recording of their over...
void end(const QString &group="startup")
End the current profile event.
void start(const QString &name, const QString &group="startup")
Start a profile event with the given name.
The QgsScaleBarRendererRegistry manages registered scalebar renderers.
Scoped object for logging of the runtime for a single operation or group of operations.
This class is a composition of two QSettings instances:
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
bool contains(const QString &key, QgsSettings::Section section=QgsSettings::NoSection) const
Returns true if there exists a setting called key; returns false otherwise.
void beginGroup(const QString &prefix, QgsSettings::Section section=QgsSettings::NoSection)
Appends prefix to the current group.
QStringList childKeys() const
Returns a list of all top-level keys that can be read using the QSettings object.
void remove(const QString &key, QgsSettings::Section section=QgsSettings::NoSection)
Removes the setting key and any sub-settings of key in a section.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
A cache for source strings that returns a local file path containing the source content.
A QAbstractItemModel subclass for showing symbol and color ramp entities contained within a QgsStyle ...
static void cleanDefaultStyle()
Deletes the default style. Only to be used by QgsApplication::exitQgis()
static QgsStyle * defaultStyle()
Returns default application-wide style.
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 > ¶meters=QMap< QString, QString >())
Returns an SVG drawing as a QImage.
Registry of available symbol layer classes.
static QColor decodeColor(const QString &str)
Task manager for managing a set of long-running QgsTask tasks.
Tile download manager handles downloads of map tiles for the purpose of map rendering.
Used for the collecting of strings from projects for translation and creation of ts files.
User profile manager is used to manager list, and manage user profiles on the users machine.
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.
User profile contains information about the user profile folders on the machine.
const QString folder() const
The base folder for the user profile.
This class keeps a list of QgsAbstractValidityCheck checks which can be used when performing validity...
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
#define CONN_POOL_MAX_CONCURRENT_CONNS
QObject * ABISYM(QgsApplication::mFileOpenEventReceiver)
Q_GLOBAL_STATIC_WITH_ARGS(PalPropertyList, palHiddenProperties,({ QgsPalLayerSettings::PositionX, QgsPalLayerSettings::PositionY, QgsPalLayerSettings::Show, QgsPalLayerSettings::LabelRotation, QgsPalLayerSettings::Family, QgsPalLayerSettings::FontStyle, QgsPalLayerSettings::Size, QgsPalLayerSettings::Bold, QgsPalLayerSettings::Italic, QgsPalLayerSettings::Underline, QgsPalLayerSettings::Color, QgsPalLayerSettings::Strikeout, QgsPalLayerSettings::MultiLineAlignment, QgsPalLayerSettings::BufferSize, QgsPalLayerSettings::BufferDraw, QgsPalLayerSettings::BufferColor, QgsPalLayerSettings::LabelDistance, QgsPalLayerSettings::Hali, QgsPalLayerSettings::Vali, QgsPalLayerSettings::ScaleVisibility, QgsPalLayerSettings::MinScale, QgsPalLayerSettings::MaxScale, QgsPalLayerSettings::AlwaysShow, QgsPalLayerSettings::CalloutDraw, QgsPalLayerSettings::LabelAllParts })) QgsAuxiliaryLayer
Q_GLOBAL_STATIC(QReadWriteLock, sDefinitionCacheLock)
#define QgsDebugMsgLevel(str, level)