Krita Source Code Documentation
Loading...
Searching...
No Matches
KisApplication Class Reference

Base class for the Krita app. More...

#include <KisApplication.h>

+ Inheritance diagram for KisApplication:

Classes

class  Private
 
class  ResetStarting
 

Public Slots

void executeRemoteArguments (QByteArray message, KisMainWindow *mainWindow)
 
void fileOpenRequested (const QString &url)
 
void remoteArguments (const QString &message)
 
void setSplashScreenLoadingText (const QString &)
 
- Public Slots inherited from QtSingleApplication
void activateWindow ()
 
bool sendMessage (const QString &message, int timeout=5000)
 

Public Member Functions

void addResourceTypes ()
 
void askResetConfig ()
 
bool event (QEvent *event) override
 
KisExtendedModifiersMapperPluginInterface * extendedModifiersPluginInterface ()
 
void hideSplashScreen ()
 
void initializeGlobals (const KisApplicationArguments &args)
 
 KisApplication (const QString &key, int &argc, char **argv)
 
void loadPlugins ()
 
bool notify (QObject *receiver, QEvent *event) override
 Overridden to handle exceptions from event handlers.
 
void processPostponedSynchronizationEvents ()
 
bool registerResources ()
 
void setSplashScreen (QWidget *splash)
 
virtual bool start (const KisApplicationArguments &args)
 
 ~KisApplication () override
 
- Public Member Functions inherited from QtSingleApplication
QWidget * activationWindow () const
 
QString id () const
 
void initialize (bool dummy=true)
 
bool isRunning ()
 
 QtSingleApplication (const QString &id, int &argc, char **argv)
 
 QtSingleApplication (int &argc, char **argv, bool GUIenabled=true)
 
 QtSingleApplication (int &argc, char **argv, Type type)
 
void setActivationWindow (QWidget *aw, bool activateOnMessage=true)
 
void setSingleApplicationReady ()
 

Static Public Member Functions

static bool isStoreApplication ()
 
static void verifyMetatypeRegistration ()
 

Private Slots

void slotSetLongPress (bool enabled)
 

Private Member Functions

void checkAutosaveFiles ()
 
bool createNewDocFromTemplate (const QString &fileName, KisMainWindow *m_mainWindow)
 
void resetConfig ()
 

Private Attributes

QScopedPointer< Private > d
 

Friends

class ResetStarting
 

Additional Inherited Members

- Signals inherited from QtSingleApplication
void messageReceived (const QString &message)
 

Detailed Description

Base class for the Krita app.

This class handles arguments given on the command line and shows a generic about dialog for the Krita app.

In addition it adds the standard directories where Krita can find its images etc.

If the last mainwindow becomes closed, KisApplication automatically calls QApplication::quit.

Definition at line 38 of file KisApplication.h.

Constructor & Destructor Documentation

◆ KisApplication()

KisApplication::KisApplication ( const QString & key,
int & argc,
char ** argv )
explicit

Creates an application object, adds some standard directories and initializes kimgio.

Load platform plugin for modifiers fetching

Definition at line 229 of file KisApplication.cpp.

230 : QtSingleApplication(key, argc, argv)
231 , d(new Private)
232{
233#ifdef Q_OS_ANDROID
234 // The hardware renderer backend on Android doesn't support proper stacking,
235 // causing windows with QtQuick widgets to always stack behind everything
236 // else, including our own dialog decorations.
237 qputenv("QT_QUICK_BACKEND", "software");
238#endif
239#ifdef Q_OS_MACOS
241#endif
242
243 QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath());
244
245#ifndef Q_OS_MACOS
246 setWindowIcon(KisIconUtils::loadIcon("krita-branding"));
247#endif
248
249 // if style is set from config, try to load that
250 KisConfig cfg(true);
251 QString widgetStyleFromConfig = cfg.widgetStyle();
252 QString defaultStyle = style()->objectName().toLower();
253 if (!widgetStyleFromConfig.isEmpty()) {
254 qApp->setStyle(widgetStyleFromConfig);
255 }
256#if defined Q_OS_WIN || defined Q_OS_MACOS || defined Q_OS_ANDROID
257 else {
258 // default to Fusion instead of styles that use native theming
259 qApp->setStyle("fusion");
260 }
261#endif
262
266 {
267 d->extendedModifiersPluginInterface.reset(KisPlatformPluginInterfaceFactory::instance()->createExtendedModifiersMapper());
268 }
269
270 // store the style name
271 qApp->setProperty(currentUnderlyingStyleNameProperty, style()->objectName());
273
274
275#if KRITA_USE_SURFACE_COLOR_MANAGEMENT_API
276
281 struct PlatformWindowCreationFilter : QObject
282 {
283 using QObject::QObject;
284
285 bool eventFilter(QObject *watched, QEvent *event) override {
286 if (event->type() == QEvent::PlatformSurface) {
287 QWidget *widget = qobject_cast<QWidget*>(watched);
288 if (!widget) return false;
289
294 if (watched->property("krita_skip_srgb_surface_manager_assignment").toBool()) {
295 return false;
296 }
297
298 QPlatformSurfaceEvent *surfaceEvent = static_cast<QPlatformSurfaceEvent*>(event);
299 if (surfaceEvent->surfaceEventType() == QPlatformSurfaceEvent::SurfaceCreated) {
300 QWindow *nativeWindow = widget->windowHandle();
301 KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(widget->windowHandle(), false);
302
303 if (!nativeWindow->findChild<KisSRGBSurfaceColorSpaceManager*>()) {
305 }
306 }
307 }
308
309 return false;
310 }
311 };
312
313 this->installEventFilter(new PlatformWindowCreationFilter(this));
314#endif /* KRITA_USE_SURFACE_COLOR_MANAGEMENT_API */
315}
QScopedPointer< Private > d
void processPostponedSynchronizationEvents()
static KisPlatformPluginInterfaceFactory * instance()
static KisSRGBSurfaceColorSpaceManager * tryCreateForCurrentPlatform(QWidget *widget)
static void registerSynchronizedEventBarrier(std::function< void()> callback)
QtSingleApplication(int &argc, char **argv, bool GUIenabled=true)
#define KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(cond, val)
Definition kis_assert.h:129
constexpr const char * currentUnderlyingStyleNameProperty
Definition kis_global.h:116
static QVariantHash defaultStyle
QIcon loadIcon(const QString &name)
void setMouseCoalescingEnabled(bool enabled)
Definition osx.mm:17

References currentUnderlyingStyleNameProperty, d, defaultStyle, KisPlatformPluginInterfaceFactory::instance(), KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE, KisIconUtils::loadIcon(), processPostponedSynchronizationEvents(), KisSynchronizedConnectionBase::registerSynchronizedEventBarrier(), setMouseCoalescingEnabled(), KisSRGBSurfaceColorSpaceManager::tryCreateForCurrentPlatform(), and KisConfig::widgetStyle().

◆ ~KisApplication()

KisApplication::~KisApplication ( )
override

Destructor.

Definition at line 881 of file KisApplication.cpp.

882{
883 if (!isRunning()) {
886 }
887}
static void performHouseKeepingOnExit()
perform optimize and vacuum when necessary
static void deleteTemporaryResources()
Delete all storages that are Unknown or Memory and all resources that are marked temporary or belong ...

References KisResourceCacheDb::deleteTemporaryResources(), QtSingleApplication::isRunning(), and KisResourceCacheDb::performHouseKeepingOnExit().

Member Function Documentation

◆ addResourceTypes()

void KisApplication::addResourceTypes ( )

Definition at line 351 of file KisApplication.cpp.

352{
353 KisScopedPerformanceLogger perfLog(QStringLiteral("KisApplication::addResourceTypes"));
354
355 // All Krita's resource types
356 KoResourcePaths::addAssetType("markers", "data", "/styles/");
357 KoResourcePaths::addAssetType("kis_pics", "data", "/pics/");
358 KoResourcePaths::addAssetType("kis_images", "data", "/images/");
359 KoResourcePaths::addAssetType("metadata_schema", "data", "/metadata/schemas/");
360 KoResourcePaths::addAssetType("gmic_definitions", "data", "/gmic/");
361 KoResourcePaths::addAssetType("kis_shortcuts", "data", "/shortcuts/");
362 KoResourcePaths::addAssetType("kis_actions", "data", "/actions");
363 KoResourcePaths::addAssetType("kis_actions", "data", "/pykrita");
364 KoResourcePaths::addAssetType("icc_profiles", "data", "/color/icc");
365 KoResourcePaths::addAssetType("icc_profiles", "data", "/profiles/");
366 KoResourcePaths::addAssetType("tags", "data", "/tags/");
367 KoResourcePaths::addAssetType("templates", "data", "/templates");
368 KoResourcePaths::addAssetType("pythonscripts", "data", "/pykrita");
369 KoResourcePaths::addAssetType("preset_icons", "data", "/preset_icons");
370#if defined HAVE_SEEXPR
371 KoResourcePaths::addAssetType(ResourceType::SeExprScripts, "data", "/seexpr_scripts/", true);
372#endif
373
374 // Make directories for all resources we can save, and tags
375 KoResourcePaths::saveLocation("data", "/asl/", true);
376 KoResourcePaths::saveLocation("data", "/css_styles/", true);
377 KoResourcePaths::saveLocation("data", "/input/", true);
378 KoResourcePaths::saveLocation("data", "/pykrita/", true);
379 KoResourcePaths::saveLocation("data", "/color-schemes/", true);
380 KoResourcePaths::saveLocation("data", "/preset_icons/", true);
381 KoResourcePaths::saveLocation("data", "/preset_icons/tool_icons/", true);
382 KoResourcePaths::saveLocation("data", "/preset_icons/emblem_icons/", true);
383}
static void addAssetType(const QString &type, const char *basetype, const QString &relativeName, bool priority=true)
static QString saveLocation(const QString &type, const QString &suffix=QString(), bool create=true)
const QString SeExprScripts

References KoResourcePaths::addAssetType(), KoResourcePaths::saveLocation(), and ResourceType::SeExprScripts.

◆ askResetConfig()

void KisApplication::askResetConfig ( )

Checks if user is holding ctrl+alt+shift keys and asks if the settings file should be cleared.

Typically called during startup before reading the config.

Definition at line 1354 of file KisApplication.cpp.

1355{
1356 bool ok = QMessageBox::question(qApp->activeWindow(),
1357 i18nc("@title:window", "Krita"),
1358 i18n("Do you want to clear the settings file?"),
1359 QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes;
1360 if (ok) {
1361 resetConfig();
1362 }
1363}

References resetConfig().

◆ checkAutosaveFiles()

void KisApplication::checkAutosaveFiles ( )
private
Returns
the number of autosavefiles opened

Definition at line 1186 of file KisApplication.cpp.

1187{
1188 if (d->batchRun) return;
1189
1191
1192 // Check for autosave files from a previous run. There can be several, and
1193 // we want to offer a restore for every one. Including a nice thumbnail!
1194
1195 // Hidden autosave files
1196 QStringList filters = QStringList() << QString(".krita-*-*-autosave.kra");
1197
1198 // all autosave files for our application
1199 QStringList autosaveFiles = dir.entryList(filters, QDir::Files | QDir::Hidden);
1200
1201 // Visible autosave files
1202 filters = QStringList() << QString("krita-*-*-autosave.kra");
1203 autosaveFiles += dir.entryList(filters, QDir::Files);
1204
1205 // Allow the user to make their selection
1206 if (autosaveFiles.size() > 0) {
1207 if (d->splashScreen) {
1208 // hide the splashscreen to see the dialog
1210 }
1211 d->autosaveDialog = new KisAutoSaveRecoveryDialog(autosaveFiles, activeWindow());
1212 QDialog::DialogCode result = (QDialog::DialogCode) d->autosaveDialog->exec();
1213
1214 if (result == QDialog::Accepted) {
1215 QStringList filesToRecover = d->autosaveDialog->recoverableFiles();
1216 Q_FOREACH (const QString &autosaveFile, autosaveFiles) {
1217 if (!filesToRecover.contains(autosaveFile)) {
1218 KisUsageLogger::log(QString("Removing autosave file %1").arg(dir.absolutePath() + "/" + autosaveFile));
1219 QFile::remove(dir.absolutePath() + "/" + autosaveFile);
1220 }
1221 }
1222 autosaveFiles = filesToRecover;
1223 } else {
1224 autosaveFiles.clear();
1225 }
1226
1227 if (autosaveFiles.size() > 0) {
1228 QList<QString> autosavePaths;
1229 Q_FOREACH (const QString &autoSaveFile, autosaveFiles) {
1230 const QString path = dir.absolutePath() + QLatin1Char('/') + autoSaveFile;
1231 autosavePaths << path;
1232 }
1233 if (d->mainWindow) {
1234 Q_FOREACH (const QString &path, autosavePaths) {
1235 KisMainWindow::OpenFlags flags = d->batchRun ? KisMainWindow::BatchMode : KisMainWindow::None;
1236 d->mainWindow->openDocument(path, flags | KisMainWindow::RecoveryFile);
1237 }
1238 }
1239 }
1240 // cleanup
1241 delete d->autosaveDialog;
1242 d->autosaveDialog = nullptr;
1243 }
1244}
QList< QString > QStringList
static void log(const QString &message)
Logs with date/time.

References KisAutoSaveRecoveryDialog::autoSaveLocation(), KisMainWindow::BatchMode, d, hideSplashScreen(), KisUsageLogger::log(), KisMainWindow::None, and KisMainWindow::RecoveryFile.

◆ createNewDocFromTemplate()

bool KisApplication::createNewDocFromTemplate ( const QString & fileName,
KisMainWindow * m_mainWindow )
private

Definition at line 1246 of file KisApplication.cpp.

1247{
1248 QString templatePath;
1249
1250 if (QFile::exists(fileName)) {
1251 templatePath = fileName;
1252 dbgUI << "using full path...";
1253 }
1254 else {
1255 QString desktopName(fileName);
1256 const QString templatesResourcePath = QStringLiteral("templates/");
1257
1258 QStringList paths = KoResourcePaths::findAllAssets("data", templatesResourcePath + "*/" + desktopName);
1259 if (paths.isEmpty()) {
1260 paths = KoResourcePaths::findAllAssets("data", templatesResourcePath + desktopName);
1261 }
1262
1263 if (paths.isEmpty()) {
1264 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"),
1265 i18n("No template found for: %1", desktopName));
1266 } else if (paths.count() > 1) {
1267 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"),
1268 i18n("Too many templates found for: %1", desktopName));
1269 } else {
1270 templatePath = paths.at(0);
1271 }
1272 }
1273
1274 if (!templatePath.isEmpty()) {
1275 KDesktopFile templateInfo(templatePath);
1276
1277 KisMainWindow::OpenFlags batchFlags = d->batchRun ? KisMainWindow::BatchMode : KisMainWindow::None;
1278 if (mainWindow->openDocument(templatePath, KisMainWindow::Import | batchFlags)) {
1279 dbgUI << "Template loaded...";
1280 return true;
1281 }
1282 else {
1283 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"),
1284 i18n("Template %1 failed to load.", fileName));
1285 }
1286 }
1287
1288 return false;
1289}
static QStringList findAllAssets(const QString &type, const QString &filter=QString(), SearchOptions options=NoSearchOptions)
#define dbgUI
Definition kis_debug.h:56

References KisMainWindow::BatchMode, d, dbgUI, KoResourcePaths::findAllAssets(), KisMainWindow::Import, KisMainWindow::None, and KisMainWindow::openDocument().

◆ event()

bool KisApplication::event ( QEvent * event)
override

Definition at line 386 of file KisApplication.cpp.

387{
388
389 #ifdef Q_OS_MACOS
390 if (event->type() == QEvent::FileOpen) {
391 QFileOpenEvent *openEvent = static_cast<QFileOpenEvent *>(event);
392 fileOpenRequested(openEvent->file());
393 return true;
394 }
395 #endif
396 return QApplication::event(event);
397}
bool event(QEvent *event) override
void fileOpenRequested(const QString &url)

References event(), and fileOpenRequested().

◆ executeRemoteArguments

void KisApplication::executeRemoteArguments ( QByteArray message,
KisMainWindow * mainWindow )
slot

Definition at line 1082 of file KisApplication.cpp.

1083{
1085 const bool doTemplate = args.doTemplate();
1086 const bool doNewImage = args.doNewImage();
1087 const int argsCount = args.filenames().count();
1088 bool documentCreated = false;
1089
1090 // Create a new image, if needed
1091 if (doNewImage) {
1093 if (doc) {
1095 d->mainWindow->addViewAndNotifyLoadingCompleted(doc);
1096 }
1097 }
1098 if (argsCount > 0) {
1099 // Loop through arguments
1100 for (int argNumber = 0; argNumber < argsCount; ++argNumber) {
1101 QString filename = args.filenames().at(argNumber);
1102 // are we just trying to open a template?
1103 if (doTemplate) {
1104 documentCreated |= createNewDocFromTemplate(filename, mainWindow);
1105 }
1106 else if (QFile(filename).exists()) {
1107 KisMainWindow::OpenFlags flags = d->batchRun ? KisMainWindow::BatchMode : KisMainWindow::None;
1108 documentCreated |= mainWindow->openDocument(filename, flags);
1109 }
1110 }
1111 }
1112
1113 //add an image as file-layer if called in another process and singleApplication is enabled
1114 if (!args.fileLayer().isEmpty()){
1115 if (argsCount > 0 && !documentCreated){
1116 //arg was passed but document was not created so don't add the file layer.
1117 QMessageBox::warning(mainWindow, i18nc("@title:window", "Krita:Warning"),
1118 i18n("Couldn't open file %1",args.filenames().at(argsCount - 1)));
1119 }
1120 else if (mainWindow->viewManager()->image()){
1121 KisFileLayer *fileLayer = new KisFileLayer(mainWindow->viewManager()->image(), "",
1122 args.fileLayer(), KisFileLayer::None, "Bicubic",
1123 mainWindow->viewManager()->image()->nextLayerName(i18n("File layer")), OPACITY_OPAQUE_U8);
1124 QFileInfo fi(fileLayer->path());
1125 if (fi.exists()){
1126 KisNodeCommandsAdapter adapter(d->mainWindow->viewManager());
1127 adapter.addNode(fileLayer, d->mainWindow->viewManager()->activeNode()->parent(),
1128 d->mainWindow->viewManager()->activeNode());
1129 }
1130 else{
1131 QMessageBox::warning(mainWindow, i18nc("@title:window", "Krita:Warning"),
1132 i18n("Cannot add %1 as a file layer: the file does not exist.", fileLayer->path()));
1133 }
1134 }
1135 else {
1136 QMessageBox::warning(mainWindow, i18nc("@title:window", "Krita:Warning"),
1137 i18n("Cannot add the file layer: no document is open."));
1138 }
1139 }
1140}
const quint8 OPACITY_OPAQUE_U8
bool createNewDocFromTemplate(const QString &fileName, KisMainWindow *m_mainWindow)
The KisFileLayer class loads a particular file as a layer into the layer stack.
QString path() const
QString nextLayerName(const QString &baseName="") const
Definition kis_image.cc:741
bool openDocument(const QString &path, OpenFlags flags)
KisViewManager * viewManager
static KisPart * instance()
Definition KisPart.cpp:131
void addDocument(KisDocument *document, bool notify=true)
Definition KisPart.cpp:210
KisImageWSP image() const
Return the image this view is displaying.
static KisApplicationArguments deserialize(QByteArray &serialized)
KisDocument * createDocumentFromArguments() const

References KisPart::addDocument(), KisNodeCommandsAdapter::addNode(), KisMainWindow::BatchMode, KisApplicationArguments::createDocumentFromArguments(), createNewDocFromTemplate(), d, KisApplicationArguments::deserialize(), KisApplicationArguments::doNewImage(), KisApplicationArguments::doTemplate, KisApplicationArguments::fileLayer, KisApplicationArguments::filenames, KisViewManager::image(), KisPart::instance(), KisImage::nextLayerName(), KisFileLayer::None, KisMainWindow::None, OPACITY_OPAQUE_U8, KisMainWindow::openDocument(), KisNode::parent, KisFileLayer::path(), and KisMainWindow::viewManager.

◆ extendedModifiersPluginInterface()

KisExtendedModifiersMapperPluginInterface * KisApplication::extendedModifiersPluginInterface ( )

Definition at line 1365 of file KisApplication.cpp.

1366{
1367 return d->extendedModifiersPluginInterface.data();
1368}

References d.

◆ fileOpenRequested

void KisApplication::fileOpenRequested ( const QString & url)
slot

Definition at line 1162 of file KisApplication.cpp.

1163{
1164 if (!d->mainWindow) {
1165 d->earlyFileOpenEvents.append(url);
1166 return;
1167 }
1168
1169 KisMainWindow::OpenFlags flags = d->batchRun ? KisMainWindow::BatchMode : KisMainWindow::None;
1170 d->mainWindow->openDocument(url, flags);
1171}

References KisMainWindow::BatchMode, d, and KisMainWindow::None.

◆ hideSplashScreen()

void KisApplication::hideSplashScreen ( )

Definition at line 905 of file KisApplication.cpp.

906{
907#ifdef Q_OS_ANDROID
909#endif
910 if (d->splashScreen) {
911 // hide the splashscreen to see the dialog
912 d->splashScreen->hide();
913 }
914}
static void setLoaded(bool loaded)

References d, and KisAndroidDonations::setLoaded().

◆ initializeGlobals()

void KisApplication::initializeGlobals ( const KisApplicationArguments & args)

Definition at line 344 of file KisApplication.cpp.

345{
346 Q_UNUSED(args)
347 // There are no globals to initialize from the arguments now. There used
348 // to be the `dpi` argument, but it doesn't do anything anymore.
349}

◆ isStoreApplication()

bool KisApplication::isStoreApplication ( )
static

Tries to detect if Krita has been bought on a store. The user can definitely fake this and it's probably also not 100% reliable, but should be good enough for what we're doing with it. On Android, check KisAndroidDonations for an in-app purchase instead.

Definition at line 988 of file KisApplication.cpp.

989{
990 if (qEnvironmentVariableIsSet("STEAMAPPID") || qEnvironmentVariableIsSet("SteamAppId")
991 || qEnvironmentVariableIsSet("STEAMGAMEID") || qEnvironmentVariableIsSet("SteamGameId")) {
992 return true;
993 }
994
995 for (const QString &arg : arguments()) {
996 if (arg.startsWith("-epicapp=", Qt::CaseInsensitive) || arg.compare("-EpicPortal", Qt::CaseInsensitive) == 0) {
997 return true;
998 }
999 }
1000
1001 if (QDir(applicationDirPath()).exists(".egstore")) {
1002 return true;
1003 }
1004
1005 if (QRegularExpression(QStringLiteral("[/\\\\](?:steam|steamapps|epic\\s*games)[/\\\\]"),
1006 QRegularExpression::CaseInsensitiveOption)
1007 .match(applicationDirPath())
1008 .hasMatch()) {
1009 return true;
1010 }
1011
1012#ifdef Q_OS_WIN
1013 // This is also true for user-installed MSIX, but that's
1014 // likely only true in institutional situations, so whatever.
1016 return true;
1017 }
1018#endif
1019
1020#ifdef Q_OS_MACOS
1021 KisMacosEntitlements entitlements;
1022 if (entitlements.sandbox()) {
1023 return true;
1024 }
1025#endif
1026
1027 return false;
1028}

References KisWindowsPackageUtils::isRunningInPackage(), and KisMacosEntitlements::sandbox().

◆ loadPlugins()

void KisApplication::loadPlugins ( )

Definition at line 469 of file KisApplication.cpp.

470{
471 KisScopedPerformanceLogger perfLog(QStringLiteral("KisApplication::loadPlugins"));
472
474 r->add(new KisShapeSelectionFactory());
483}
static KisActionRegistry * instance()
static KisFilterRegistry * instance()
static KisGeneratorRegistry * instance()
static KisMetadataBackendRegistry * instance()
static KisPaintOpRegistry * instance()
static KoDockRegistry * instance()
static KoShapeRegistry * instance()
static KoToolRegistry * instance()
static KoColorSpaceRegistry * instance()

References KoDockRegistry::instance(), KoShapeRegistry::instance(), KoToolRegistry::instance(), KisPaintOpRegistry::instance(), KisFilterRegistry::instance(), KisGeneratorRegistry::instance(), KisMetadataBackendRegistry::instance(), KoColorSpaceRegistry::instance(), and KisActionRegistry::instance().

◆ notify()

bool KisApplication::notify ( QObject * receiver,
QEvent * event )
override

Overridden to handle exceptions from event handlers.

KisApplication::notify() is called for every event loop processed in any thread, so we need to make sure our counters and postponed events queues are stored in a per-thread way.

Definition at line 917 of file KisApplication.cpp.

918{
919 try {
920 bool result = true;
921
927 AppRecursionInfo &info = s_recursionInfo->localData();
928
929 {
930 // QApplication::notify() can throw, so use RAII for counters
931 AppRecursionGuard guard(&info);
932
934
935 if (info.eventRecursionCount > 1) {
937 KIS_SAFE_ASSERT_RECOVER_NOOP(typedEvent->destination == receiver);
938
939 info.postponedSynchronizationEvents.emplace(KisSynchronizedConnectionEvent(*typedEvent));
940 } else {
941 result = QApplication::notify(receiver, event);
942 }
943 } else {
944 result = QApplication::notify(receiver, event);
945 }
946 }
947
948 if (!info.eventRecursionCount) {
950
951 }
952
953 return result;
954
955 } catch (std::exception &e) {
956 qWarning("Error %s sending event %i to object %s",
957 e.what(), event->type(), qPrintable(receiver->objectName()));
958 } catch (...) {
959 qWarning("Error <unknown> sending event %i to object %s",
960 event->type(), qPrintable(receiver->objectName()));
961 }
962 return false;
963}
#define KIS_SAFE_ASSERT_RECOVER_NOOP(cond)
Definition kis_assert.h:130
Event type used for synchronizing connection in KisSynchronizedConnection.

References KisSynchronizedConnectionEvent::destination, event(), KisSynchronizedConnectionBase::eventType(), KIS_SAFE_ASSERT_RECOVER_NOOP, and processPostponedSynchronizationEvents().

◆ processPostponedSynchronizationEvents()

void KisApplication::processPostponedSynchronizationEvents ( )

We must pop event from the queue before we call QApplication::notify(), because it can throw!

Definition at line 965 of file KisApplication.cpp.

966{
967 AppRecursionInfo &info = s_recursionInfo->localData();
968
969 while (!info.postponedSynchronizationEvents.empty()) {
970 // QApplication::notify() can throw, so use RAII for counters
971 AppRecursionGuard guard(&info);
972
975 KisSynchronizedConnectionEvent typedEvent = info.postponedSynchronizationEvents.front();
976 info.postponedSynchronizationEvents.pop();
977
978 if (!typedEvent.destination) {
979 qWarning() << "WARNING: the destination object of KisSynchronizedConnection has been destroyed during postponed delivery";
980 continue;
981 }
982
983 QApplication::notify(typedEvent.destination, &typedEvent);
984 }
985}

References KisSynchronizedConnectionEvent::destination.

◆ registerResources()

bool KisApplication::registerResources ( )

Definition at line 400 of file KisApplication.cpp.

401{
402 KisScopedPerformanceLogger perfLog(QStringLiteral("KisApplication::registerResources"));
403
405
407 QStringList() << "application/x-krita-paintoppreset"));
408
409 reg->add(new KisResourceLoader<KisGbrBrush>(ResourceSubType::GbrBrushes, ResourceType::Brushes, i18n("Brush tips"), QStringList() << "image/x-gimp-brush"));
410 reg->add(new KisResourceLoader<KisImagePipeBrush>(ResourceSubType::GihBrushes, ResourceType::Brushes, i18n("Brush tips"), QStringList() << "image/x-gimp-brush-animated"));
411 reg->add(new KisResourceLoader<KisSvgBrush>(ResourceSubType::SvgBrushes, ResourceType::Brushes, i18n("Brush tips"), QStringList() << "image/svg+xml"));
413
414 reg->add(new KisResourceLoader<KoSegmentGradient>(ResourceSubType::SegmentedGradients, ResourceType::Gradients, i18n("Gradients"), QStringList() << "application/x-gimp-gradient"));
416
427
428
429 reg->add(new KisResourceLoader<KoPattern>(ResourceType::Patterns, ResourceType::Patterns, i18n("Patterns"), {"application/x-gimp-pattern", "image/x-gimp-pat", "application/x-gimp-pattern", "image/bmp", "image/jpeg", "image/png", "image/tiff"}));
430 reg->add(new KisResourceLoader<KisWorkspaceResource>(ResourceType::Workspaces, ResourceType::Workspaces, i18n("Workspaces"), QStringList() << "application/x-krita-workspace"));
431 reg->add(new KisResourceLoader<KoSvgSymbolCollectionResource>(ResourceType::Symbols, ResourceType::Symbols, i18n("SVG symbol libraries"), QStringList() << "image/svg+xml"));
432 reg->add(new KisResourceLoader<KisWindowLayoutResource>(ResourceType::WindowLayouts, ResourceType::WindowLayouts, i18n("Window layouts"), QStringList() << "application/x-krita-windowlayout"));
433 reg->add(new KisResourceLoader<KisSessionResource>(ResourceType::Sessions, ResourceType::Sessions, i18n("Sessions"), QStringList() << "application/x-krita-session"));
434 reg->add(new KisResourceLoader<KoGamutMask>(ResourceType::GamutMasks, ResourceType::GamutMasks, i18n("Gamut masks"), QStringList() << "application/x-krita-gamutmasks"));
435#if defined HAVE_SEEXPR
436 reg->add(new KisResourceLoader<KisSeExprScript>(ResourceType::SeExprScripts, ResourceType::SeExprScripts, i18n("SeExpr Scripts"), QStringList() << "application/x-krita-seexpr-script"));
437#endif
438 // XXX: this covers only individual styles, not the library itself!
441 i18nc("Resource type name", "Layer styles"),
442 QStringList() << "application/x-photoshop-style"));
443
444 reg->add(new KisResourceLoader<KoFontFamily>(ResourceType::FontFamilies, ResourceType::FontFamilies, i18n("Font Families"), QStringList() << "application/x-font-ttf" << "application/x-font-otf"));
445 reg->add(new KisResourceLoader<KoCssStylePreset>(ResourceType::CssStyles, ResourceType::CssStyles, i18n("Style Presets"), QStringList() << "image/svg+xml"));
446
448
449#ifndef Q_OS_ANDROID
450 QString databaseLocation = KoResourcePaths::getAppDataLocation();
451#else
452 // Sqlite doesn't support content URIs (obviously). So, we make database location unconfigurable on android.
453 QString databaseLocation = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
454#endif
455
456 if (!KisResourceCacheDb::initialize(databaseLocation)) {
457 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita: Fatal error"), i18n("%1\n\nKrita will quit now.", KisResourceCacheDb::lastError()));
458 }
459
461 connect(KisResourceLocator::instance(), SIGNAL(progressMessage(const QString&)), this, SLOT(setSplashScreenLoadingText(const QString&)));
462 if (r != KisResourceLocator::LocatorError::Ok && qApp->inherits("KisApplication")) {
463 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita: Fatal error"), KisResourceLocator::instance()->errorMessages().join('\n') + i18n("\n\nKrita will quit now."));
464 return false;
465 }
466 return true;
467}
void setSplashScreenLoadingText(const QString &)
static QString mimeTypeForSuffix(const QString &suffix)
Find the mimetype for a given extension. The extension may have the form "*.xxx" or "xxx".
static bool initialize(const QString &location)
initializes the database and updates the scheme if necessary. Does not actually fill the database wit...
static QString lastError()
lastError returns the last SQL error.
The KisResourceLoaderRegistry class manages the loader plugins for resources. Every resource can be l...
static KisResourceLoaderRegistry * instance()
void registerFixup(int priority, ResourceCacheFixup *fixup)
LocatorError initialize(const QString &installationResourcesLocation)
initialize Setup the resource locator for use.
static KisResourceLocator * instance()
static QString getAppDataLocation()
static QString getApplicationRoot()
const QString GbrBrushes
const QString PngBrushes
const QString GihBrushes
const QString SvgBrushes
const QString StopGradients
const QString KritaPaintOpPresets
const QString SegmentedGradients
const QString Palettes
const QString Symbols
const QString FontFamilies
const QString CssStyles
const QString LayerStyles
const QString Brushes
const QString GamutMasks
const QString Patterns
const QString Gradients
const QString Workspaces
const QString WindowLayouts
const QString Sessions
const QString PaintOpPresets

References KoGenericRegistry< T >::add(), ResourceType::Brushes, ResourceType::CssStyles, ResourceType::FontFamilies, ResourceType::GamutMasks, ResourceSubType::GbrBrushes, KoResourcePaths::getAppDataLocation(), KoResourcePaths::getApplicationRoot(), ResourceSubType::GihBrushes, ResourceType::Gradients, KisResourceLocator::initialize(), KisResourceCacheDb::initialize(), KisResourceLoaderRegistry::instance(), KisResourceLocator::instance(), ResourceSubType::KritaPaintOpPresets, KisResourceCacheDb::lastError(), ResourceType::LayerStyles, KisMimeDatabase::mimeTypeForSuffix(), KisResourceLocator::Ok, ResourceType::PaintOpPresets, ResourceType::Palettes, ResourceType::Patterns, ResourceSubType::PngBrushes, KisResourceLoaderRegistry::registerFixup(), ResourceType::SeExprScripts, ResourceSubType::SegmentedGradients, ResourceType::Sessions, setSplashScreenLoadingText(), ResourceSubType::StopGradients, ResourceSubType::SvgBrushes, ResourceType::Symbols, ResourceType::WindowLayouts, and ResourceType::Workspaces.

◆ remoteArguments

void KisApplication::remoteArguments ( const QString & message)
slot

Definition at line 1143 of file KisApplication.cpp.

1144{
1145 // check if we have any mainwindow
1146 KisMainWindow *mw = qobject_cast<KisMainWindow*>(qApp->activeWindow());
1147
1148 if (!mw && KisPart::instance()->mainWindows().size() > 0) {
1149 mw = KisPart::instance()->mainWindows().first();
1150 }
1151
1152 const QByteArray unpackedMessage =
1153 QByteArray::fromBase64(message.toLatin1());
1154
1155 if (!mw) {
1156 d->earlyRemoteArguments << unpackedMessage;
1157 return;
1158 }
1159 executeRemoteArguments(unpackedMessage, mw);
1160}
void executeRemoteArguments(QByteArray message, KisMainWindow *mainWindow)
Main window for Krita.
QList< QPointer< KisMainWindow > > mainWindows
Definition KisPart.cpp:107
int size(const Forest< T > &forest)
Definition KisForest.h:1232

References d, executeRemoteArguments(), KisPart::instance(), and KisPart::mainWindows.

◆ resetConfig()

void KisApplication::resetConfig ( )
private

Definition at line 1291 of file KisApplication.cpp.

1292{
1293 KIS_ASSERT_RECOVER_RETURN(qApp->thread() == QThread::currentThread());
1294
1295 KSharedConfigPtr config = KSharedConfig::openConfig();
1296 config->markAsClean();
1297
1298 // find user settings file
1299 const QString configPath = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
1300 QString kritarcPath = configPath + QStringLiteral("/kritarc");
1301
1302 QFile kritarcFile(kritarcPath);
1303
1304 if (kritarcFile.exists()) {
1305 if (kritarcFile.open(QFile::ReadWrite)) {
1306 QString backupKritarcPath = kritarcPath + QStringLiteral(".backup");
1307
1308 QFile backupKritarcFile(backupKritarcPath);
1309
1310 if (backupKritarcFile.exists()) {
1311 backupKritarcFile.remove();
1312 }
1313
1314 QMessageBox::information(qApp->activeWindow(),
1315 i18nc("@title:window", "Krita"),
1316 i18n("Krita configurations reset!\n\n"
1317 "Backup file was created at: %1\n\n"
1318 "Restart Krita for changes to take effect.",
1319 backupKritarcPath),
1320 QMessageBox::Ok, QMessageBox::Ok);
1321
1322 // clear file
1323 kritarcFile.rename(backupKritarcPath);
1324
1325 kritarcFile.close();
1326 }
1327 else {
1328 QMessageBox::warning(qApp->activeWindow(),
1329 i18nc("@title:window", "Krita"),
1330 i18n("Failed to clear %1\n\n"
1331 "Please make sure no other program is using the file and try again.",
1332 kritarcPath),
1333 QMessageBox::Ok, QMessageBox::Ok);
1334 }
1335 }
1336
1337 // reload from disk; with the user file settings cleared,
1338 // this should load any default configuration files shipping with the program
1339 config->reparseConfiguration();
1340 config->sync();
1341
1342 // Restore to default workspace
1343 KConfigGroup cfg = KSharedConfig::openConfig()->group("MainWindow");
1344
1345 QString currentWorkspace = cfg.readEntry<QString>("CurrentWorkspace", "Default");
1347 KisWorkspaceResourceSP workspace = rserver->resource("", "", currentWorkspace);
1348
1349 if (workspace) {
1350 d->mainWindow->restoreWorkspace(workspace);
1351 }
1352}
static KisResourceServerProvider * instance()
KoResourceServer< KisWorkspaceResource > * workspaceServer()
#define KIS_ASSERT_RECOVER_RETURN(cond)
Definition kis_assert.h:75

References d, KisResourceServerProvider::instance(), KIS_ASSERT_RECOVER_RETURN, and KisResourceServerProvider::workspaceServer().

◆ setSplashScreen()

void KisApplication::setSplashScreen ( QWidget * splash)

Tell KisApplication to show this splashscreen when you call start(); when start returns, the splashscreen is hidden. Use KSplashScreen to have the splash show correctly on Xinerama displays.

Definition at line 889 of file KisApplication.cpp.

890{
891 d->splashScreen = qobject_cast<KisSplashScreen*>(splashScreen);
892}

References d.

◆ setSplashScreenLoadingText

void KisApplication::setSplashScreenLoadingText ( const QString & textToLoad)
slot

Definition at line 894 of file KisApplication.cpp.

895{
896 if (d->splashScreen) {
897 d->splashScreen->setLoadingText(textToLoad);
898 d->splashScreen->repaint();
899 }
900#ifdef Q_OS_ANDROID
902#endif
903}
static void setLoadingText(const QString &text)

References d, and KisAndroidDonations::setLoadingText().

◆ slotSetLongPress

void KisApplication::slotSetLongPress ( bool enabled)
privateslot

Definition at line 1174 of file KisApplication.cpp.

1175{
1176 if (enabled && !d->longPressEventFilter) {
1177 d->longPressEventFilter = new KisLongPressEventFilter(this);
1178 installEventFilter(d->longPressEventFilter);
1179 } else if (!enabled && d->longPressEventFilter) {
1180 removeEventFilter(d->longPressEventFilter);
1181 d->longPressEventFilter->deleteLater();
1182 d->longPressEventFilter = nullptr;
1183 }
1184}

References d.

◆ start()

bool KisApplication::start ( const KisApplicationArguments & args)
virtual

Call this to start the application.

Parses command line arguments and creates the initial main windows and docs from them (or an empty doc if no cmd-line argument is specified ).

You must call this method directly before calling QApplication::exec.

It is valid behaviour not to call this method at all. In this case you have to process your command line parameters by yourself.

Definition at line 485 of file KisApplication.cpp.

486{
487 KisScopedPerformanceLogger perfLog(QStringLiteral("KisApplication::start"));
488#ifdef Q_OS_ANDROID
490#endif
491
492 KisConfig cfg(false);
493
494 auto iconsInMenuMode = cfg.iconsInMenu();
495 if (iconsInMenuMode == KisConfig::IIM_Yes) {
496 QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, false);
497 } else if (iconsInMenuMode == KisConfig::IIM_No) {
498 QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, true);
499 }
500
501#if defined(Q_OS_WIN)
502#ifdef ENV32BIT
503
504 if (isWow64() && !cfg.readEntry("WarnedAbout32Bits", false)) {
505 QMessageBox::information(qApp->activeWindow(),
506 i18nc("@title:window", "Krita: Warning"),
507 i18n("You are running a 32 bits build on a 64 bits Windows.\n"
508 "This is not recommended.\n"
509 "Please download and install the x64 build instead."));
510 cfg.writeEntry("WarnedAbout32Bits", true);
511
512 }
513#endif
514#endif
515
516 QString opengl = cfg.canvasState();
517 if (opengl == "OPENGL_NOT_TRIED" ) {
518 cfg.setCanvasState("TRY_OPENGL");
519 }
520 else if (opengl != "OPENGL_SUCCESS" && opengl != "TRY_OPENGL") {
521 cfg.setCanvasState("OPENGL_FAILED");
522 }
523
524 setSplashScreenLoadingText(i18n("Initializing Globals..."));
525 processEvents();
526 initializeGlobals(args);
527
528#if defined(Q_OS_ANDROID) && KRITA_QT_HAS_ANDROID_QPLATFORMSCREEN_DENSITY_ADJUSTMENT
529 d->androidScaling = new KisAndroidScaling(cfg, this);
530#endif
531
532 const bool doNewImage = args.doNewImage();
533 const bool doTemplate = args.doTemplate();
534 const bool exportAs = args.exportAs();
535 const bool exportSequence = args.exportSequence();
536 const QString exportFileName = args.exportFileName();
537
538 d->batchRun = (exportAs || exportSequence || !exportFileName.isEmpty());
539 const bool needsMainWindow = (!exportAs && !exportSequence);
540 // only show the mainWindow when no command-line mode option is passed
541 bool showmainWindow = (!exportAs && !exportSequence); // would be !batchRun;
542
543#ifndef Q_OS_ANDROID
544 const bool showSplashScreen = !d->batchRun && qEnvironmentVariableIsEmpty("NOSPLASH");
545 if (showSplashScreen && d->splashScreen) {
546 d->splashScreen->show();
547 d->splashScreen->repaint();
548 processEvents();
549 }
550#endif
551
552 KConfigGroup group(KSharedConfig::openConfig(), "theme");
553#ifndef Q_OS_HAIKU
554 Digikam::ThemeManager themeManager;
555 themeManager.setCurrentTheme(group.readEntry("Theme", "Krita dark"));
556#endif
557
558 ResetStarting resetStarting(d->splashScreen, args.filenames().count()); // remove the splash when done
559 Q_UNUSED(resetStarting);
560
561 // Make sure we can save resources and tags
562 setSplashScreenLoadingText(i18n("Adding resource types..."));
563 processEvents();
565
566 setSplashScreenLoadingText(i18n("Loading plugins..."));
567 processEvents();
568 // Load the plugins
569 loadPlugins();
570
571 // Load all resources
572 setSplashScreenLoadingText(i18n("Loading resources..."));
573 processEvents();
574 if (!registerResources()) {
575 return false;
576 }
577
578 KisPart *kisPart = KisPart::instance();
579 if (needsMainWindow) {
580 // show a mainWindow asap, if we want that
581 setSplashScreenLoadingText(i18n("Loading Main Window..."));
582 processEvents();
583
584
585 bool sessionNeeded = true;
586 auto sessionMode = cfg.sessionOnStartup();
587
588 if (!args.session().isEmpty()) {
589 sessionNeeded = !kisPart->restoreSession(args.session());
590 } else if (sessionMode == KisConfig::SOS_ShowSessionManager) {
591 showmainWindow = false;
592 sessionNeeded = false;
593 kisPart->showSessionManager();
594 } else if (sessionMode == KisConfig::SOS_PreviousSession) {
595 KConfigGroup sessionCfg = KSharedConfig::openConfig()->group("session");
596 const QString &sessionName = sessionCfg.readEntry("previousSession");
597
598 sessionNeeded = !kisPart->restoreSession(sessionName);
599 }
600
601 if (sessionNeeded) {
602 kisPart->startBlankSession();
603 }
604
605 if (!args.windowLayout().isEmpty()) {
607 KisWindowLayoutResourceSP windowLayout = rserver->resource("", "", args.windowLayout());
608 if (windowLayout) {
609 windowLayout->applyLayout();
610 }
611 }
612
613 setSplashScreenLoadingText(i18n("Launching..."));
614
615 if (showmainWindow) {
616 d->mainWindow = kisPart->currentMainwindow();
617
618 if (!args.workspace().isEmpty()) {
620 KisWorkspaceResourceSP workspace = rserver->resource("", "", args.workspace());
621 if (workspace) {
622 d->mainWindow->restoreWorkspace(workspace);
623 }
624 }
625
626 if (args.canvasOnly()) {
627 d->mainWindow->viewManager()->switchCanvasOnly(true);
628 }
629
630 if (args.fullScreen()) {
631 d->mainWindow->showFullScreen();
632 }
633 } else {
634 d->mainWindow = kisPart->createMainWindow();
635 }
636 }
637
638 // Check for autosave files that can be restored, if we're not running a batch run (test)
639 if (!d->batchRun) {
641 }
642
643 setSplashScreenLoadingText(QString()); // done loading, so clear out label
644#ifdef Q_OS_ANDROID
646#endif
647 processEvents();
648
649 //configure the unit manager
651 connect(this, &KisApplication::aboutToQuit, qApp, &KisSpinBoxUnitManagerFactory::clearUnitManagerBuilder); //ensure the builder is destroyed when the application leave.
652 //the new syntax slot syntax allow to connect to a non q_object static method.
653
654 // Long-press emulation.
657 slotSetLongPress(cfg.longPressEnabled());
658
659 // Xiaomi workaround: their stylus inexplicably inputs page up and down keys
660 // when pressing stylus buttons. This flag causes the Android platform
661 // integration to turn those into right and middle clicks instead.
662#if KRITA_QT_HAS_ANDROID_EMULATE_MOUSE_BUTTONS_FOR_PAGE_UP_DOWN
663 auto setPageUpDownMouseButtonEmulationWorkaround = [](bool enabled) {
664 QCoreApplication::setKritaAttribute(KRITA_QATTRIBUTE_ANDROID_EMULATE_MOUSE_BUTTONS_FOR_PAGE_UP_DOWN, enabled);
665 };
666 connect(cfgNotifier,
667 &KisConfigNotifier::sigUsePageUpDownMouseButtonEmulationWorkaroundChanged,
668 this,
669 setPageUpDownMouseButtonEmulationWorkaround);
670 setPageUpDownMouseButtonEmulationWorkaround(cfg.usePageUpDownMouseButtonEmulationWorkaround());
671#endif
672
673 // OnePlus workaround: their stylus inexplicably inputs the F21 key when
674 // pressing the stylus button. This flag causes the Android platform
675 // integration to turn it into middle clicks instead. Currently
676 // unconditional because a setting requires translation-relevant text
677 // changes, but later versions of Krita let you toggle it like the Xiaomi
678 // workarounds above.
679#if KRITA_QT_HAS_ANDROID_EMULATE_MOUSE_BUTTONS_FOR_HIGH_FUNCTION_KEYS
680 QCoreApplication::setKritaAttribute(KRITA_QATTRIBUTE_ANDROID_EMULATE_MOUSE_BUTTONS_FOR_HIGH_FUNCTION_KEYS, true);
681 auto setHighFunctionKeyMouseButtonEmulationWorkaround = [](bool enabled) {
682 // QCoreApplication::setKritaAttribute(KRITA_QATTRIBUTE_ANDROID_EMULATE_MOUSE_BUTTONS_FOR_HIGH_FUNCTION_KEYS, enabled);
683 };
684 connect(cfgNotifier,
685 &KisConfigNotifier::sigUseHighFunctionKeyMouseButtonEmulationWorkaroundChanged,
686 this,
687 setHighFunctionKeyMouseButtonEmulationWorkaround);
688 setHighFunctionKeyMouseButtonEmulationWorkaround(cfg.useHighFunctionKeyMouseButtonEmulationWorkaround());
689#endif
690
691 // Xiaomi workaround: historic tablet motion events are garbage, they just
692 // connect the actual points that the tablet sampled with a straight line
693 // and no pressure emulation, leading to jagged curves that don't get
694 // smoothed out. This flag disables reading those historic events.
695#if KRITA_QT_HAS_ANDROID_IGNORE_HISTORIC_TABLET_EVENTS
696 auto setIgnoreHistoricTabletEventsWorkaround = [](bool enabled) {
697 QCoreApplication::setKritaAttribute(KRITA_QATTRIBUTE_ANDROID_IGNORE_HISTORIC_TABLET_EVENTS, enabled);
698 };
699 connect(cfgNotifier,
700 &KisConfigNotifier::sigUseIgnoreHistoricTabletEventsWorkaroundChanged,
701 this,
702 setIgnoreHistoricTabletEventsWorkaround);
703 setIgnoreHistoricTabletEventsWorkaround(cfg.useIgnoreHistoricTabletEventsWorkaround());
704#endif
705
706 // Wacom and XPPEN workaround: these devices have broken cursors for stylus
707 // events, which will show up when hovering the stylus and disappear when
708 // pressing it down. Support for this is in Java code, so no #if.
709#ifdef Q_OS_ANDROID
711 auto setHideTouchAndStylusCursorsWorkaround = [](bool enabled) {
713 };
714 connect(cfgNotifier,
715 &KisConfigNotifier::sigHideTouchAndStylusCursorsWorkaroundChanged,
716 this,
717 setHideTouchAndStylusCursorsWorkaround);
718 setHideTouchAndStylusCursorsWorkaround(cfg.hideTouchAndStylusCursorsWorkaround());
719 }
720#endif
721
722 // Create a new image, if needed
723 if (doNewImage) {
725 if (doc) {
726 kisPart->addDocument(doc);
727 d->mainWindow->addViewAndNotifyLoadingCompleted(doc);
728 }
729 }
730
731 // Get the command line arguments which we have to parse
732 int argsCount = args.filenames().count();
733 if (argsCount > 0) {
734 // Loop through arguments
735 for (int argNumber = 0; argNumber < argsCount; argNumber++) {
736 QString fileName = args.filenames().at(argNumber);
737 // are we just trying to open a template?
738 if (doTemplate) {
739 // called in mix with batch options? ignore and silently skip
740 if (d->batchRun) {
741 continue;
742 }
743 createNewDocFromTemplate(fileName, d->mainWindow);
744 // now try to load
745 }
746 else {
747 if (exportAs) {
748 QString outputMimetype = KisMimeDatabase::mimeTypeForFile(exportFileName, false);
749 if (outputMimetype == "application/octetstream") {
750 dbgKrita << i18n("Mimetype not found, try using the -mimetype option") << Qt::endl;
751 return false;
752 }
753
754 KisDocument *doc = kisPart->createDocument();
755 doc->setFileBatchMode(d->batchRun);
756 bool result = doc->openPath(fileName);
757
758 if (!result) {
759 errKrita << "Could not load " << fileName << ":" << doc->errorMessage();
760 QTimer::singleShot(0, this, SLOT(quit()));
761 return false;
762 }
763
764 if (exportFileName.isEmpty()) {
765 errKrita << "Export destination is not specified for" << fileName << "Please specify export destination with --export-filename option";
766 QTimer::singleShot(0, this, SLOT(quit()));
767 return false;
768 }
769
770 qApp->processEvents(); // For vector layers to be updated
771
772 doc->setFileBatchMode(true);
773 doc->image()->waitForDone();
774
775 if (!doc->exportDocumentSync(exportFileName, outputMimetype.toLatin1())) {
776 errKrita << "Could not export " << fileName << "to" << exportFileName << ":" << doc->errorMessage();
777 }
778 QTimer::singleShot(0, this, SLOT(quit()));
779 return true;
780 }
781 else if (exportSequence) {
782 KisDocument *doc = kisPart->createDocument();
783 doc->setFileBatchMode(d->batchRun);
784 doc->openPath(fileName);
785 qApp->processEvents(); // For vector layers to be updated
786
787 if (!doc->image()->animationInterface()->hasAnimation()) {
788 errKrita << "This file has no animation." << Qt::endl;
789 QTimer::singleShot(0, this, SLOT(quit()));
790 return false;
791 }
792
793 doc->setFileBatchMode(true);
794 int sequenceStart = 0;
795
796
797 qDebug() << ppVar(exportFileName);
800 exportFileName,
801 sequenceStart,
802 false,
803 0);
804
805 exporter.setBatchMode(d->batchRun);
806
807 KisAsyncAnimationFramesSaveDialog::Result result = exporter.regenerateRange(nullptr);
808 qDebug() << ppVar(result);
809
811 errKrita << i18n("Failed to render animation frames!") << Qt::endl;
812 }
813
814 QTimer::singleShot(0, this, SLOT(quit()));
815 return true;
816 }
817 else if (d->mainWindow) {
818 if (QFileInfo(fileName).fileName().endsWith(".bundle", Qt::CaseInsensitive)) {
819 d->mainWindow->installBundle(fileName);
820 }
821 else {
822 KisMainWindow::OpenFlags flags = d->batchRun ? KisMainWindow::BatchMode : KisMainWindow::None;
823
824 d->mainWindow->openDocument(fileName, flags);
825 }
826 }
827 }
828 }
829 }
830
831 //add an image as file-layer
832 if (!args.fileLayer().isEmpty()){
833 if (d->mainWindow->viewManager()->image()){
834 KisFileLayer *fileLayer = new KisFileLayer(d->mainWindow->viewManager()->image(), "",
835 args.fileLayer(), KisFileLayer::None, "Bicubic",
836 d->mainWindow->viewManager()->image()->nextLayerName(i18n("File layer")), OPACITY_OPAQUE_U8);
837 QFileInfo fi(fileLayer->path());
838 if (fi.exists()){
839 KisNodeCommandsAdapter adapter(d->mainWindow->viewManager());
840 adapter.addNode(fileLayer, d->mainWindow->viewManager()->activeNode()->parent(),
841 d->mainWindow->viewManager()->activeNode());
842 }
843 else{
844 QMessageBox::warning(qApp->activeWindow(), i18nc("@title:window", "Krita:Warning"),
845 i18n("Cannot add %1 as a file layer: the file does not exist.", fileLayer->path()));
846 }
847 }
848 else if (this->isRunning()){
849 QMessageBox::warning(qApp->activeWindow(), i18nc("@title:window", "Krita:Warning"),
850 i18n("Cannot add the file layer: no document is open.\n\n"
851"You can create a new document using the --new-image option, or you can open an existing file.\n\n"
852"If you instead want to add the file layer to a document in an already running instance of Krita, check the \"Allow only one instance of Krita\" checkbox in the settings (Settings -> General -> Window)."));
853 }
854 else {
855 QMessageBox::warning(qApp->activeWindow(), i18nc("@title:window", "Krita: Warning"),
856 i18n("Cannot add the file layer: no document is open.\n"
857 "You can either create a new file using the --new-image option, or you can open an existing file."));
858 }
859 }
860
861 Q_FOREACH(const QByteArray &message, d->earlyRemoteArguments) {
862 executeRemoteArguments(message, d->mainWindow);
863 }
864
866
867 // process File open event files
868 if (!d->earlyFileOpenEvents.isEmpty()) {
870 Q_FOREACH(QString fileName, d->earlyFileOpenEvents) {
871 d->mainWindow->openDocument(fileName, QFlags<KisMainWindow::OpenFlag>());
872 }
873 }
874
876
877 // not calling this before since the program will quit there.
878 return true;
879}
void setCurrentTheme(const QString &name)
static void showDonationDialog(bool splash)
friend class ResetStarting
void slotSetLongPress(bool enabled)
void initializeGlobals(const KisApplicationArguments &args)
static void verifyMetatypeRegistration()
void sigLongPressChanged(bool enabled)
static KisConfigNotifier * instance()
@ SOS_PreviousSession
Definition kis_config.h:393
@ SOS_ShowSessionManager
Definition kis_config.h:394
void setFileBatchMode(const bool batchMode)
KisImageSP image
QString errorMessage() const
bool exportDocumentSync(const QString &path, const QByteArray &mimeType, KisPropertiesConfigurationSP exportConfiguration=0)
bool openPath(const QString &path, OpenFlags flags=None)
openPath Open a Path
const KisTimeSpan & documentPlaybackRange() const
documentPlaybackRange
void waitForDone()
KisImageAnimationInterface * animationInterface() const
static QString mimeTypeForFile(const QString &file, bool checkExistingFiles=true)
Find the mimetype for the given filename. The filename must include a suffix.
bool restoreSession(const QString &sessionName)
Definition KisPart.cpp:644
KisMainWindow * currentMainwindow() const
Definition KisPart.cpp:458
void startBlankSession()
Definition KisPart.cpp:636
KisDocument * createDocument() const
Definition KisPart.cpp:229
void showSessionManager()
Definition KisPart.cpp:625
KisMainWindow * createMainWindow(QUuid id=QUuid())
Definition KisPart.cpp:259
KoResourceServer< KisWindowLayoutResource > * windowLayoutServer()
static void setDefaultUnitManagerBuilder(KisSpinBoxUnitManagerBuilder *pBuilder)
set a builder the factory can use. The factory should take on the lifecycle of the builder,...
static QString screenInformation()
Returns information about all available screens.
static void writeSysInfo(const QString &message)
Writes to the system information file and Krita log.
QSharedPointer< T > resource(const QString &md5, const QString &fileName, const QString &name)
resource retrieves a resource. If the md5sum is not empty, the resource will only be retrieved if a r...
#define dbgKrita
Definition kis_debug.h:49
#define errKrita
Definition kis_debug.h:115
#define ppVar(var)
Definition kis_debug.h:163
QAction * quit(const QObject *recvr, const char *slot, QObject *parent)
void setHideTouchAndStylusCursors(bool hide)
bool canHideTouchAndStylusCursors()

References KisPart::addDocument(), KisNodeCommandsAdapter::addNode(), addResourceTypes(), KisImage::animationInterface(), KisMainWindow::BatchMode, KisAndroidUtils::canHideTouchAndStylusCursors(), KisApplicationArguments::canvasOnly, KisConfig::canvasState(), checkAutosaveFiles(), KisSpinBoxUnitManagerFactory::clearUnitManagerBuilder(), KisPart::createDocument(), KisApplicationArguments::createDocumentFromArguments(), KisPart::createMainWindow(), createNewDocFromTemplate(), KisPart::currentMainwindow(), d, dbgKrita, KisImageAnimationInterface::documentPlaybackRange(), KisApplicationArguments::doNewImage(), KisApplicationArguments::doTemplate, errKrita, KisDocument::errorMessage(), executeRemoteArguments(), KisApplicationArguments::exportAs, KisDocument::exportDocumentSync(), KisApplicationArguments::exportFileName, KisApplicationArguments::exportSequence, KisApplicationArguments::fileLayer, KisApplicationArguments::filenames, KisApplicationArguments::fullScreen, KisImageAnimationInterface::hasAnimation(), hideSplashScreen(), KisConfig::iconsInMenu(), KisConfig::IIM_No, KisConfig::IIM_Yes, KisDocument::image, initializeGlobals(), KisConfigNotifier::instance(), KisPart::instance(), KisResourceServerProvider::instance(), QtSingleApplication::isRunning(), loadPlugins(), KisConfig::longPressEnabled(), KisMimeDatabase::mimeTypeForFile(), KisFileLayer::None, KisMainWindow::None, OPACITY_OPAQUE_U8, KisDocument::openPath(), KisNode::parent, KisFileLayer::path(), ppVar, KisConfig::readEntry(), KisAsyncAnimationFramesSaveDialog::regenerateRange(), registerResources(), KisAsyncAnimationRenderDialogBase::RenderComplete, KoResourceServer< T >::resource(), KisPart::restoreSession(), KisUsageLogger::screenInformation(), KisApplicationArguments::session, KisConfig::sessionOnStartup(), KisAsyncAnimationRenderDialogBase::setBatchMode(), KisConfig::setCanvasState(), Digikam::ThemeManager::setCurrentTheme(), KisSpinBoxUnitManagerFactory::setDefaultUnitManagerBuilder(), KisDocument::setFileBatchMode(), KisAndroidUtils::setHideTouchAndStylusCursors(), KisAndroidDonations::setLoaded(), setSplashScreenLoadingText(), KisAndroidDonations::showDonationDialog(), KisPart::showSessionManager(), KisConfigNotifier::sigLongPressChanged(), slotSetLongPress(), KisConfig::SOS_PreviousSession, KisConfig::SOS_ShowSessionManager, KisPart::startBlankSession(), verifyMetatypeRegistration(), KisImage::waitForDone(), KisApplicationArguments::windowLayout, KisResourceServerProvider::windowLayoutServer(), KisApplicationArguments::workspace, KisResourceServerProvider::workspaceServer(), KisConfig::writeEntry(), and KisUsageLogger::writeSysInfo().

◆ verifyMetatypeRegistration()

void KisApplication::verifyMetatypeRegistration ( )
static

Verify that all our statically registered types are actually registered. This check is skipped in release builds, when HIDE_SAFE_ASSERTS is defined

Definition at line 1031 of file KisApplication.cpp.

1032{
1037#if !defined(HIDE_SAFE_ASSERTS) || defined(CRASH_ON_SAFE_ASSERTS)
1038
1039 auto verifyTypeRegistered = [] (const char *type) {
1040 const int typeId = QMetaType::type(type);
1041
1042 if (typeId <= 0) {
1043 qFatal("ERROR: type-id for metatype %s is not found", type);
1044 }
1045
1046 if (!QMetaType::isRegistered(typeId)) {
1047 qFatal("ERROR: metatype %s is not registered", type);
1048 }
1049 };
1050
1051 verifyTypeRegistered("KisBrushSP");
1052 verifyTypeRegistered("KoSvgText::AutoValue");
1053 verifyTypeRegistered("KoSvgText::BackgroundProperty");
1054 verifyTypeRegistered("KoSvgText::StrokeProperty");
1055 verifyTypeRegistered("KoSvgText::TextTransformInfo");
1056 verifyTypeRegistered("KoSvgText::TextIndentInfo");
1057 verifyTypeRegistered("KoSvgText::TabSizeInfo");
1058 verifyTypeRegistered("KoSvgText::LineHeightInfo");
1059 verifyTypeRegistered("KisPaintopLodLimitations");
1060 verifyTypeRegistered("KisImageSP");
1061 verifyTypeRegistered("KisImageSignalType");
1062 verifyTypeRegistered("KisNodeSP");
1063 verifyTypeRegistered("KisNodeList");
1064 verifyTypeRegistered("KisPaintDeviceSP");
1065 verifyTypeRegistered("KisTimeSpan");
1066 verifyTypeRegistered("KoColor");
1067 verifyTypeRegistered("KoResourceSP");
1068 verifyTypeRegistered("KoResourceCacheInterfaceSP");
1069 verifyTypeRegistered("KisAsyncAnimationRendererBase::CancelReason");
1070 verifyTypeRegistered("KisGridConfig");
1071 verifyTypeRegistered("KisGuidesConfig");
1072 verifyTypeRegistered("KisUpdateInfoSP");
1073 verifyTypeRegistered("KisToolChangesTrackerDataSP");
1074 verifyTypeRegistered("QVector<QImage>");
1075 verifyTypeRegistered("SnapshotDirInfoList");
1076 verifyTypeRegistered("TransformTransactionProperties");
1077 verifyTypeRegistered("ToolTransformArgs");
1078 verifyTypeRegistered("QPainterPath");
1079#endif
1080}

Friends And Related Symbol Documentation

◆ ResetStarting

friend class ResetStarting
friend

Definition at line 132 of file KisApplication.h.

Member Data Documentation

◆ d

QScopedPointer<Private> KisApplication::d
private

Definition at line 130 of file KisApplication.h.


The documentation for this class was generated from the following files: