Krita Source Code Documentation
Loading...
Searching...
No Matches
KisMainWindow.cpp
Go to the documentation of this file.
1/* This file is part of the KDE project
2 SPDX-FileCopyrightText: 1998, 1999 Torben Weis <weis@kde.org>
3 SPDX-FileCopyrightText: 2000-2006 David Faure <faure@kde.org>
4 SPDX-FileCopyrightText: 2007, 2009 Thomas zander <zander@kde.org>
5 SPDX-FileCopyrightText: 2010 Benjamin Port <port.benjamin@gmail.com>
6
7 SPDX-License-Identifier: LGPL-2.0-or-later
8*/
9
10#include "KisMainWindow.h"
11
12#include <KoConfig.h>
13
14// qt includes
15#include <QApplication>
16#include <QByteArray>
17#include <QCloseEvent>
18#include <QStandardPaths>
19#include <QDesktopServices>
20#include <QScreen>
21#include <QDialog>
22#include <QDockWidget>
23#include <QIcon>
24#include <QInputDialog>
25#include <QLayout>
26#include <QMdiArea>
27#include <QMdiSubWindow>
28#include <QMutex>
29#include <QMutexLocker>
30#include <QPointer>
31#include <KisSignalMapper.h>
32#include <QTabBar>
33#include <QMoveEvent>
34#include <QUrl>
35#include <QMessageBox>
36#include <QStatusBar>
37#include <QStyleFactory>
38#include <QMenu>
39#include <QMenuBar>
40#include <KisMimeDatabase.h>
41#include <QMimeData>
42#include <QStackedWidget>
43#include <QProxyStyle>
44#include <QScreen>
45#include <QAction>
46#include <QWindow>
47#include <QTemporaryDir>
48#include <QScrollArea>
49#include <QActionGroup>
50
51#include <kactioncollection.h>
52#include <kactionmenu.h>
53#include <kis_debug.h>
54#include <kedittoolbar.h>
55#include <khelpmenu.h>
56#include <klocalizedstring.h>
57#include <kaboutdata.h>
62#include "kis_icon_utils.h"
63#include <krecentfilesaction.h>
64#include "krita_utils.h"
65#include <ktoggleaction.h>
66#include <ktoolbar.h>
67#include <kmainwindow.h>
68#include <kxmlguiwindow.h>
69#include <kxmlguifactory.h>
70#include <kxmlguiclient.h>
71#include <kguiitem.h>
72#include <kwindowconfig.h>
73#include <kacceleratormanager.h>
74
75#include <KoResourcePaths.h>
76#include <KoToolFactoryBase.h>
77#include <KoToolRegistry.h>
78#include <KoDockFactoryBase.h>
81#include <KoDocumentInfoDlg.h>
82#include <KoDocumentInfo.h>
83#include <KoFileDialog.h>
84#include <kis_icon.h>
85#include <KoToolManager.h>
86#include "KoToolDocker.h"
88#include <KoDockRegistry.h>
89#include <KoPluginLoader.h>
90#include <KoColorSpaceEngine.h>
91#include <KoUpdater.h>
92#include <KisResourceModel.h>
94#include <KisResourceIterator.h>
95#include <KisResourceTypes.h>
96#include <KisResourceCacheDb.h>
97#include <KisStorageModel.h>
99#include <KisPlaybackEngine.h>
100
101#ifdef Q_OS_ANDROID
102#include "KisAndroidDonations.h"
104#include <QtAndroid>
105#include <KisAndroidUtils.h>
106#endif
107
109#include <KisUsageLogger.h>
114#include "kis_action_manager.h"
115#include "KisApplication.h"
116#include "kis_canvas2.h"
119#include "kis_clipboard.h"
120#include "kis_config.h"
121#include "kis_config_notifier.h"
125#include <KisDocument.h>
126#include "kis_group_layer.h"
128#include "kis_image.h"
133#include "kis_node.h"
134#include "KisOpenPane.h"
135#include "kis_paintop_box.h"
136#include "KisPart.h"
139#include "kis_statusbar.h"
140#include "KisView.h"
141#include "KisViewManager.h"
142#include "thememanager.h"
149#include "KisWelcomePageWidget.h"
151#include <KritaVersionWrapper.h>
152#include "KisCanvasWindow.h"
153#include "kis_action.h"
154#include <katecommandbar.h>
156#include "KisUiFont.h"
160#include "KisToolBarStateModel.h"
161#include <config-qmdiarea-always-show-subwindow-title.h>
162#include <config-qt-patches-present.h>
164
165#include <mutex>
166
167#if defined(Q_OS_ANDROID) && KRITA_QT_HAS_ANDROID_QPLATFORMSCREEN_DENSITY_ADJUSTMENT
168#include <KisAndroidScaling.h>
169#endif
170
172{
173public:
175
176 QString id() const override {
177 return "sharedtooldocker";
178 }
179
180 QDockWidget* createDockWidget() override {
181 KoToolDocker* dockWidget = new KoToolDocker();
182 return dockWidget;
183 }
184
186 return DockRight;
187 }
188};
189
190class Q_DECL_HIDDEN KisMainWindow::Private
191{
192public:
193 Private(KisMainWindow *parent, QUuid id)
194 : q(parent)
195 , id(id)
196 , styleMenu(new KActionMenu(i18nc("@action:inmenu", "Styles"), parent))
197 , dockWidgetMenu(new KActionMenu(i18nc("@action:inmenu", "&Dockers"), parent))
198 , windowMenu(new KActionMenu(i18nc("@action:inmenu", "&Window"), parent))
199 , documentMenu(new KActionMenu(i18nc("@action:inmenu", "New &View"), parent))
200 , workspaceMenu(new KActionMenu(i18nc("@action:inmenu", "Wor&kspace"), parent))
201 , welcomePage(new KisWelcomePageWidget(parent))
202 , widgetStack(new QStackedWidget(parent))
203 , mdiArea(new QMdiArea(parent))
204 , windowMapper(new KisSignalMapper(parent))
205 , documentMapper(new KisSignalMapper(parent))
206 {
207 if (id.isNull()) this->id = QUuid::createUuid();
208
209 welcomeScroller = new QScrollArea();
210 welcomeScroller->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
211 welcomeScroller->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
212 welcomeScroller->setWidget(welcomePage);
213 welcomeScroller->setWidgetResizable(true);
214
215 widgetStack->addWidget(welcomeScroller);
216 widgetStack->addWidget(mdiArea);
217 mdiArea->setTabsMovable(true);
218 mdiArea->setActivationOrder(QMdiArea::ActivationHistoryOrder);
219 mdiArea->setDocumentMode(true);
220 mdiArea->setOption(QMdiArea::DontMaximizeSubWindowOnActivation);
221#ifdef HAVE_QMDIAREA_ALWAYS_SHOW_SUBWINDOW_TITLE
222 mdiArea->setOption(QMdiArea::AlwaysShowSubwindowNameInTitleBar);
223#endif /* HAVE_QMDIAREA_ALWAYS_SHOW_SUBWINDOW_TITLE */
224
225 commandBar = new KateCommandBar(parent);
226 }
227
229 qDeleteAll(toolbarList);
230 }
231
232 KisMainWindow *q {nullptr};
233 QUuid id;
234
235 KisViewManager *viewManager {nullptr};
236
239
241
242 bool firstTime {true};
243 bool windowSizeDirty {false};
244#ifdef Q_OS_ANDROID
245 bool flashWindowHackInProgress {false};
246#endif
247
248 KisAction *showDocumentInfo {nullptr};
249 KisAction *saveAction {nullptr};
250 KisAction *saveActionAs {nullptr};
251 KisAction *importAnimation {nullptr};
252 KisAction *importVideoAnimation {nullptr};
253 KisAction *renderAnimation {nullptr};
254 KisAction *renderAnimationAgain {nullptr};
255 KisAction *closeAll {nullptr};
256 KisAction *importFile {nullptr};
257 KisAction *exportFile {nullptr};
258 KisAction *exportFileAdvance {nullptr};
259 KisAction *undo {nullptr};
260 KisAction *redo {nullptr};
261 KisAction *close {nullptr};
262 KisAction *mdiCascade {nullptr};
263 KisAction *mdiTile {nullptr};
264 KisAction *mdiNextWindow {nullptr};
265 KisAction *mdiPreviousWindow {nullptr};
266 KisAction *toggleDockers {nullptr};
267 KisAction *resetConfigurations {nullptr};
268 KisAction *toggleDockerTitleBars {nullptr};
269#ifdef Q_OS_ANDROID
270 KisAction *showDonationManagementDialog {nullptr};
271 KisAction *manageSubscriptions {nullptr};
272#if KRITA_QT_HAS_ANDROID_QPLATFORMSCREEN_DENSITY_ADJUSTMENT
273 KisAction *changeInterfaceScale {nullptr};
274#endif
275#else
276 KisAction *toggleDetachCanvas {nullptr};
277 KisAction *newWindow {nullptr};
278#endif
279 KisAction *fullScreenMode {nullptr};
280 KisAction *showSessionManager {nullptr};
281 KisAction *commandBarAction {nullptr};
282 KisAction *expandingSpacers[2];
283
284 KActionMenu *styleMenu {nullptr};
285 QActionGroup* styleActions {nullptr};
286 QMap<QString, QAction*> actionMap;
287
288 KActionMenu *dockWidgetMenu {nullptr};
289 KActionMenu *windowMenu {nullptr};
290 KActionMenu *documentMenu {nullptr};
291 KActionMenu *workspaceMenu {nullptr};
292
293 KisKHelpMenu *helpMenu {nullptr};
294
295 KRecentFilesAction *recentFiles {nullptr};
296 KisResourceModel *workspacemodel {nullptr};
297
298 QScopedPointer<KisUndoActionsUpdateManager> undoActionsUpdateManager;
299
301
302 QMap<QString, QDockWidget *> dockWidgetsMap;
304 KoToolDocker *toolOptionsDocker {nullptr};
305
306 QCloseEvent *deferredClosingEvent {nullptr};
307#ifndef Q_OS_HAIKU
308 Digikam::ThemeManager *themeManager {nullptr};
309#endif
310 QScrollArea *welcomeScroller {nullptr};
311 KisWelcomePageWidget *welcomePage {nullptr};
312
313
314 QStackedWidget *widgetStack {nullptr};
315
316 QMdiArea *mdiArea {nullptr};
317 QMdiSubWindow *activeSubWindow {nullptr};
318 KisSignalMapper *windowMapper {nullptr};
319 KisSignalMapper *documentMapper {nullptr};
320 KisCanvasWindow *canvasWindow {nullptr};
321
323 QScopedPointer<KisSignalCompressorWithParam<int> > tabSwitchCompressor;
325
326 KConfigGroup windowStateConfig;
327
329
330 KateCommandBar *commandBar {nullptr};
331
333 return viewManager->actionManager();
334 }
335
336 QTabBar* findTabBarHACK() {
337 QObjectList objects = mdiArea->children();
338 Q_FOREACH (QObject *object, objects) {
339 QTabBar *bar = qobject_cast<QTabBar*>(object);
340 if (bar) {
341 return bar;
342 }
343 }
344 return 0;
345 }
346};
347
349{
350 QWidget *widget;
351public:
352 ScopedWidgetDisabler(QWidget *widget_)
353 : widget(widget_)
354 {
355 widget->setEnabled(false);
356 }
357
359 {
360 widget->setEnabled(true);
361 }
362};
363
364//This feels like a bit of a hack tbh, but better than digging around in QMdiArea
365class TabBarFilter : public QObject {
366public:
367 TabBarFilter(QMdiArea *mdi)
368 : mdi(mdi)
369 {
370 }
371
372 bool eventFilter(QObject *watched, QEvent *event) override
373 {
374 // This probably has too many checks, but i do not trust it to not trigger them
375 QTabBar *tabBar = dynamic_cast<QTabBar *>(watched);
376 if (!tabBar) {
377 // Shouldn't happen, but better safe than sorry
378 return false;
379 }
380
381 if (event->type() != QEvent::ToolTip) {
382 return false;
383 }
384
385 QHelpEvent *ev = dynamic_cast<QHelpEvent *>(event);
386 if (!ev) {
387 return false;
388 }
389
390 int tabIndex = tabBar->tabAt(ev->pos());
391
392 if (tabIndex == -1 || tabIndex > (mdi->subWindowList().count() - 1)) {
393 return false;
394 }
395
396 QMdiSubWindow *win = mdi->subWindowList()[tabIndex];
397
398 if (!win) {
399 return false;
400 }
401
402 KisView *view = dynamic_cast<KisView *>(win->widget());
403 if (!view) {
404 return false;
405 }
406
407 QString title = view->getTitle();
408
409 if (view->document()->isModified()) {
410 title += "*";
411 }
412
413 tabBar->setTabToolTip(tabIndex, title);
414
415 return false;
416 };
417
418private:
419 QMdiArea *mdi;
420};
421
423 : KXmlGuiWindow()
424 , d(new Private(this, uuid))
425{
426 KisScopedPerformanceLogger perfLog(QStringLiteral("KisMainWindow::KisMainWindow"));
427
428 KAcceleratorManager::setNoAccel(this);
429
430 d->workspacemodel = new KisResourceModel(ResourceType::Workspaces, this);
431 connect(d->workspacemodel, SIGNAL(modelReset()), this, SLOT(updateWindowMenu()));
432 connect(d->workspacemodel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(updateWindowMenu()));
433 connect(d->workspacemodel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(updateWindowMenu()));
434
435 d->viewManager = new KisViewManager(this, actionCollection());
436 KConfigGroup group( KSharedConfig::openConfig(), "theme");
437#ifndef Q_OS_HAIKU
438 d->themeManager = new Digikam::ThemeManager(group.readEntry("Theme", "Krita dark"), this);
439#endif
440 d->windowStateConfig = KSharedConfig::openConfig()->group("MainWindow");
441
443 setTabPosition(Qt::AllDockWidgetAreas, QTabWidget::North);
444 setDockNestingEnabled(true);
445#ifdef Q_OS_ANDROID
446 // On Android, the animations for docks and menus are not only slow, but
447 // also can cause crashes in some circumstances. Turning them off feels
448 // better and avoids those.
449 setAnimated(false);
450#endif
451
452 qApp->setStartDragDistance(25); // 25 px is a distance that works well for Tablet and Mouse events
453
454 connect(this, SIGNAL(restoringDone()), this, SLOT(forceDockTabFonts()));
455 connect(this, SIGNAL(themeChanged()), d->viewManager, SLOT(updateIcons()));
456 connect(this, SIGNAL(themeChanged()), d->viewManager->toolManager(), SLOT(themeChanged()));
457 connect(KisPart::instance(), SIGNAL(documentClosed(QString)), SLOT(updateWindowMenu()));
458 connect(KisPart::instance(), SIGNAL(documentOpened(QString)), SLOT(updateWindowMenu()));
459 connect(KisConfigNotifier::instance(), SIGNAL(configChanged()), this, SLOT(configChanged()));
460
462 KoPluginLoader::instance()->load("Krita/ViewPlugin", KoPluginLoader::PluginsConfig(), d->viewManager, false);
463
464 // Load the per-application plugins (Right now, only Python) We do this only once, when the first mainwindow is being created.
465 KoPluginLoader::instance()->load("Krita/ApplicationPlugin", KoPluginLoader::PluginsConfig(), qApp, true);
466
467 KoToolBoxFactory toolBoxFactory;
468 QDockWidget *toolbox = createDockWidget(&toolBoxFactory);
469
470 KisConfig cfg(true);
471 if (cfg.toolOptionsInDocker()) {
472 ToolDockerFactory toolDockerFactory;
473 d->toolOptionsDocker = qobject_cast<KoToolDocker*>(createDockWidget(&toolDockerFactory));
474 if (d->toolOptionsDocker) {
475 d->toolOptionsDocker->toggleViewAction()->setEnabled(true);
476 }
477 }
478
479 QMap<QString, QAction*> dockwidgetActions;
480
481 if (toolbox) {
482 dockwidgetActions[toolbox->toggleViewAction()->text()] = toolbox->toggleViewAction();
483 }
484
486 QDockWidget *dw = createDockWidget(factory);
487 if (dw) {
488 dockwidgetActions[dw->toggleViewAction()->text()] = dw->toggleViewAction();
489 }
490 }
491
492 if (d->toolOptionsDocker) {
493 dockwidgetActions[d->toolOptionsDocker->toggleViewAction()->text()] = d->toolOptionsDocker->toggleViewAction();
494 }
495 connect(d->viewManager->toolManager(), SIGNAL(toolOptionWidgetsChanged(KoCanvasController*,QList<QPointer<QWidget> >)), this, SLOT(newOptionWidgets(KoCanvasController*,QList<QPointer<QWidget> >)));
496
497 Q_FOREACH (QString title, dockwidgetActions.keys()) {
498 d->dockWidgetMenu->addAction(dockwidgetActions[title]);
499 }
500
501
502 // Style menu actions
503 d->styleActions = new QActionGroup(this);
504 QAction * action;
505
506#ifndef Q_OS_ANDROID
507
508 Q_FOREACH (QString styleName, QStyleFactory::keys()) {
509
510 action = new QAction(styleName, d->styleActions);
511 action->setCheckable(true);
512 d->actionMap.insert(styleName, action);
513 d->styleMenu->addAction(d->actionMap.value(styleName));
514 }
515
516 // select the config value, or the current style if that does not exist
517 QString styleFromConfig = cfg.widgetStyle().toLower();
518 QString styleToSelect = styleFromConfig.isEmpty() ? style()->objectName().toLower() : styleFromConfig;
519
520 Q_FOREACH (auto key, d->actionMap.keys()) {
521 if(key.toLower() == styleToSelect) { // does the key match selection
522 d->actionMap.value(key)->setChecked(true);
523 }
524 }
525
526 connect(d->styleActions, SIGNAL(triggered(QAction*)),
527 this, SLOT(slotUpdateWidgetStyle()));
528#endif
529
530 // Load all the actions from the tool plugins
531 // ToolBoxDocker needs them when at setViewManager()
532 Q_FOREACH(KoToolFactoryBase *toolFactory, KoToolRegistry::instance()->values()) {
533 toolFactory->createActions(actionCollection(), d->viewManager->toolManager());
534 }
535
536
537 Q_FOREACH (QDockWidget *wdg, dockWidgets()) {
538 if ((wdg->features() & QDockWidget::DockWidgetClosable) == 0) {
539 wdg->setVisible(true);
540 }
541 }
542
543 Q_FOREACH (KoCanvasObserverBase* observer, canvasObservers()) {
544 observer->setObservedCanvas(0);
545 KisMainwindowObserver* mainwindowObserver = dynamic_cast<KisMainwindowObserver*>(observer);
546 if (mainwindowObserver) {
547 mainwindowObserver->setViewManager(d->viewManager);
548 }
549 }
550
551 d->mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
552 d->mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
553 d->mdiArea->setTabPosition(QTabWidget::North);
554 d->mdiArea->setTabsClosable(true);
555 d->mdiArea->setAcceptDrops(true);
556
557 themeChanged(); // updates icon styles
558
559 setCentralWidget(d->widgetStack);
560 d->widgetStack->setCurrentIndex(0);
561
562 connect(d->mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)), this, SLOT(subWindowActivated()));
563 connect(d->windowMapper, SIGNAL(mapped(QWidget*)), this, SLOT(setActiveSubWindow(QWidget*)));
564 connect(d->documentMapper, SIGNAL(mapped(QObject*)), this, SLOT(newView(QObject*)));
565
566 d->canvasWindow = new KisCanvasWindow(this);
567 actionCollection()->addAssociatedWidget(d->canvasWindow);
568
570
571 // the welcome screen needs to grab actions...so make sure this line goes after the createAction() so they exist
572 d->welcomePage->setMainWindow(this);
573
574 d->recentFiles->setRecentFilesModel(&KisRecentDocumentsModelWrapper::instance()->model());
575
578
579 if (isHelpMenuEnabled() && !d->helpMenu) {
580 d->helpMenu = new KisKHelpMenu(this, KAboutData::applicationData(), false);
581
582 // workaround-less version:
583 // d->helpMenu = new KisKHelpMenu(this, QString()/*unused*/, false);
584
585 // The difference between using KisKActionCollection->addAction() is that
586 // these actions do not get tied to the MainWindow. What does this all do?
587 KisKActionCollection *actions = d->viewManager->actionCollection();
588 QAction *helpContentsAction = d->helpMenu->action(KisKHelpMenu::menuHelpContents);
589 QAction *whatsThisAction = d->helpMenu->action(KisKHelpMenu::menuWhatsThis);
590 QAction *reportBugAction = d->helpMenu->action(KisKHelpMenu::menuReportBug);
591 QAction *switchLanguageAction = d->helpMenu->action(KisKHelpMenu::menuSwitchLanguage);
592 QAction *aboutAppAction = d->helpMenu->action(KisKHelpMenu::menuAboutApp);
593 QAction *aboutKdeAction = d->helpMenu->action(KisKHelpMenu::menuAboutKDE);
594
595 if (helpContentsAction) {
596 actions->addAction(helpContentsAction->objectName(), helpContentsAction);
597 }
598 if (whatsThisAction) {
599 actions->addAction(whatsThisAction->objectName(), whatsThisAction);
600 }
601 if (reportBugAction) {
602 actions->addAction(reportBugAction->objectName(), reportBugAction);
603 }
604 if (switchLanguageAction) {
605 actions->addAction(switchLanguageAction->objectName(), switchLanguageAction);
606 }
607 if (aboutAppAction) {
608 actions->addAction(aboutAppAction->objectName(), aboutAppAction);
609 }
610 if (aboutKdeAction) {
611 actions->addAction(aboutKdeAction->objectName(), aboutKdeAction);
612 }
613
614 connect(d->helpMenu, SIGNAL(showAboutApplication()), SLOT(showAboutApplication()));
615 }
616
617 // Custom handling of help action for manual URL outside docs.kde.org.
618 QAction *helpAction = actionCollection()->action("help_contents");
619 helpAction->disconnect(SIGNAL(triggered()));
620 connect(helpAction, SIGNAL(triggered()), this, SLOT(showManual()));
621
622#if 0
623 //check for colliding shortcuts
624 QSet<QKeySequence> existingShortcuts;
625 Q_FOREACH (QAction* action, actionCollection()->actions()) {
626 if(action->shortcut() == QKeySequence(0)) {
627 continue;
628 }
629 dbgKrita << "shortcut " << action->text() << " " << action->shortcut();
630 Q_ASSERT(!existingShortcuts.contains(action->shortcut()));
631 existingShortcuts.insert(action->shortcut());
632 }
633#endif
634
636
637 // Make sure the python plugins create their actions in time
639
640 // If we have customized the toolbars, load that first
641 setLocalXMLFile(KoResourcePaths::locateLocal("data", "krita5.xmlgui"));
642 setXMLFile(":/kxmlgui5/krita5.xmlgui");
643
644 guiFactory()->addClient(this);
646 connect(guiFactory(), SIGNAL(makingChanges(bool)), SLOT(slotXmlGuiMakingChanges(bool)));
647
648 // Create and plug toolbar list for Settings menu
650 Q_FOREACH (QWidget* it, guiFactory()->containers("ToolBar")) {
651 KisToolBar * toolBar = ::qobject_cast<KisToolBar *>(it);
652 if (toolBar) {
653 KToggleAction* act = new KToggleAction(i18n("Show %1 Toolbar", toolBar->windowTitle()), this);
654 actionCollection()->addAction(toolBar->objectName().toUtf8(), act);
655 act->setCheckedState(KGuiItem(i18n("Hide %1 Toolbar", toolBar->windowTitle())));
656 connect(act, SIGNAL(toggled(bool)), this, SLOT(slotToolbarToggled(bool)));
657 act->setChecked(!toolBar->isHidden());
658 toolbarList.append(act);
659 } else {
660 warnUI << "Toolbar list contains a " << it->metaObject()->className() << " which is not a toolbar!";
661 }
662 }
663
664 plugActionList("toolbarlist", toolbarList);
665 d->toolbarList = toolbarList;
666
668
669 d->viewManager->updateGUI();
670 d->viewManager->updateIcons();
671
672 QTimer::singleShot(1000, Qt::CoarseTimer, this, SLOT(checkSanity()));
673
674 {
675 using namespace std::placeholders; // For _1 placeholder
676 std::function<void (int)> callback(
677 std::bind(&KisMainWindow::switchTab, this, _1));
678
679 d->tabSwitchCompressor.reset(
681 }
682
683
684 if (cfg.readEntry("CanvasOnlyActive", false)) {
685 QString currentWorkspace = cfg.readEntry<QString>("CurrentWorkspace", "Default");
687 KisWorkspaceResourceSP workspace = rserver->resource("", "", currentWorkspace);
688 if (workspace) {
689 restoreWorkspace(workspace);
690 }
691 cfg.writeEntry("CanvasOnlyActive", false);
692 menuBar()->setVisible(true);
693 }
694
695 this->winId(); // Ensures the native window has been created.
696
697#ifdef Q_OS_ANDROID
698 // HACK: This prevents the mainWindow from going beyond the screen with no
699 // way to bring it back. Apparently the size doesn't matter here as long as
700 // it remains fixed?
701 setFixedSize(KisApplication::primaryScreen()->availableGeometry().size());
702
703 QScreen *s = QGuiApplication::primaryScreen();
704 s->setOrientationUpdateMask(Qt::LandscapeOrientation|Qt::InvertedLandscapeOrientation|Qt::PortraitOrientation|Qt::InvertedPortraitOrientation);
705 connect(s, SIGNAL(orientationChanged(Qt::ScreenOrientation)), this, SLOT(orientationChanged()));
706
707#if KRITA_QT_HAS_ANDROID_QPLATFORMSCREEN_DENSITY_ADJUSTMENT
708 // When the screen's UI scale changes, we have to hide and show it to get
709 // its contents to update, otherwise it fails to re-render altogether.
711 if (androidScaling) {
712 connect(androidScaling,
714 this,
715 &KisMainWindow::slotFlashWindowHack,
716 Qt::QueuedConnection);
717 }
718#endif
719
720 // When Krita starts, Java side sends an event to set applicationState() to active. But, before
721 // the event could reach KisApplication's platform integration, it is cleared by KisOpenGLModeProber::probeFormat.
722 // So, we send it manually when MainWindow shows up.
723 QAndroidJniObject::callStaticMethod<void>("org/qtproject/qt5/android/QtNative", "setApplicationState", "(I)V", Qt::ApplicationActive);
724#endif
725
726 setAcceptDrops(true);
727 QTabBar *tabBar = d->findTabBarHACK();
728 if (tabBar) {
729 tabBar->setElideMode(Qt::ElideRight);
730 // load customized tab style
732 tabBar->setExpanding(true);
733 tabBar->setAcceptDrops(true);
734 tabBar->setChangeCurrentOnDrag(true);
735
736 tabBar->installEventFilter(new TabBarFilter(d->mdiArea));
737 }
738
739 applyMainWindowSettings(d->windowStateConfig);
740}
741
743{
744 // Q_FOREACH (QAction *ac, actionCollection()->actions()) {
745 // QAction *action = qobject_cast<QAction*>(ac);
746 // if (action) {
747 // qDebug() << "<Action"
748 // << "\n\tname=" << action->objectName()
749 // << "\n\ticon=" << action->icon().name()
750 // << "\n\ttext=" << action->text().replace("&", "&amp;")
751 // << "\n\twhatsThis=" << action->whatsThis()
752 // << "\n\ttoolTip=" << action->toolTip().replace("<html>", "").replace("</html>", "")
753 // << "\n\ticonText=" << action->iconText().replace("&", "&amp;")
754 // << "\n\tshortcut=" << action->shortcut().toString()
755 // << "\n\tisCheckable=" << QString((action->isChecked() ? "true" : "false"))
756 // << "\n\tstatusTip=" << action->statusTip()
757 // << "\n/>\n" ;
758 // }
759 // else {
760 // dbgKrita << "Got a non-qaction:" << ac->objectName();
761 // }
762 // }
763
773 Q_FOREACH (QMdiSubWindow *subwin, d->mdiArea->subWindowList()) {
774 if (subwin) {
775 (void) subwin->close();
776 delete subwin;
777 }
778 }
779
780 // The doc and view might still exist (this is the case when closing the window)
782
783 delete d->viewManager;
784 delete d;
785
786}
787
789{
790 return 0;
791}
792
793QUuid KisMainWindow::id() const {
794 return d->id;
795}
796
797void KisMainWindow::addView(KisView *view, QMdiSubWindow *subWindow)
798{
799 if (d->activeView == view && !subWindow) return;
800
801 if (d->activeView) {
802 d->activeView->disconnect(this);
803 }
804
805 // register the newly created view in the input manager
807
808 showView(view, subWindow);
809 Q_EMIT restoringDone();
810
811// QTabBar *tabBar = d->findTabBarHACK();
812// Q_FOREACH(QObject *c, tabBar->children()) {
813// if (QWidget *w = qobject_cast<QWidget*>(c)) {
814// w->setAcceptDrops(true);
815// }
816// }
817}
818
820{
827 if (view->canvasBase() == viewManager()->canvasBase()) {
829 }
830}
831
832
833void KisMainWindow::showView(KisView *imageView, QMdiSubWindow *subwin)
834{
835 if (imageView && activeView() != imageView) {
836 // XXX: find a better way to initialize this!
837 imageView->setViewManager(d->viewManager);
838
839 imageView->canvasBase()->setFavoriteResourceManager(d->viewManager->paintOpBox()->favoriteResourcesManager());
840 imageView->slotLoadingFinished();
841
842 if (!subwin) {
843 QMdiSubWindow *currentSubWin = d->mdiArea->currentSubWindow();
844 bool shouldMaximize = currentSubWin ? currentSubWin->isMaximized() : true;
845 subwin = d->mdiArea->addSubWindow(imageView);
846
859 const bool osManagedSurfacePresent = KisPlatformPluginInterfaceFactory::instance()->surfaceColorManagedByOS();
860 const bool useNativeSurfaceForCanvas = KisConfig(true).effectiveShouldUseNativeSurfaceForCanvas(osManagedSurfacePresent);
861 if (useNativeSurfaceForCanvas) {
862 subwin->setAttribute(Qt::WA_DontCreateNativeAncestors);
863 subwin->setAttribute(Qt::WA_NativeWindow);
864 }
865
866 if (shouldMaximize) {
867 subwin->setWindowState(Qt::WindowMaximized);
868 }
869 } else {
870 subwin->setWidget(imageView);
871 }
872 imageView->setSubWindow(subwin);
873 subwin->setAttribute(Qt::WA_DeleteOnClose, true);
874 connect(subwin, SIGNAL(destroyed()), SLOT(updateWindowMenu()));
875
876 KisConfig cfg(true);
877 subwin->setOption(QMdiSubWindow::RubberBandMove, cfg.readEntry<int>("mdi_rubberband", cfg.useOpenGL()));
878 subwin->setOption(QMdiSubWindow::RubberBandResize, cfg.readEntry<int>("mdi_rubberband", cfg.useOpenGL()));
879 subwin->setWindowIcon(qApp->windowIcon());
880
881#ifdef Q_OS_MACOS
882 connect(subwin, SIGNAL(destroyed()), SLOT(updateSubwindowFlags()));
884#endif
885
886 if (d->mdiArea->subWindowList().size() == 1) {
887 imageView->showMaximized();
888 }
889 else {
890 imageView->show();
891 }
892
913 d->viewManager->toolManager()->initializeCurrentToolForCanvas();
914
915 // No, no, no: do not try to call this _before_ the show() has
916 // been called on the view; only when that has happened is the
917 // opengl context active, and very bad things happen if we tell
918 // the dockers to update themselves with a view if the opengl
919 // context is not active.
920 setActiveView(imageView);
921
923 } else {
925 }
926}
927
929{
930 std::optional<KisDlgPreferences::PageDesc>page = std::nullopt;
931
932 KisAction* action = d->actionManager()->actionByName("options_configure");
933 QVariant data = action->data();
934 if (data.userType() == QMetaType::QVariantList) {
935 // Reset the data first
936 action->setData(QVariant());
937 QList<QVariant> list = data.toList();
938
939 Q_ASSERT(list.length() == 2);
940 Q_ASSERT(list[0].userType() == QMetaType::Int);
941 Q_ASSERT(list[1].userType() == QMetaType::Int);
942
944 int t = list[1].toInt();
946 }
947
948 QScopedPointer<KisDlgPreferences> dlgPreferences(new KisDlgPreferences(this));
949
950 if (dlgPreferences->editPreferences(page)) {
954
955 // XXX: should this be changed for the views in other windows as well?
956 Q_FOREACH (QPointer<KisView> koview, KisPart::instance()->views()) {
957 KisViewManager *view = qobject_cast<KisViewManager*>(koview);
958 if (view) {
959 // Update the settings for all nodes -- they don't query
960 // KisConfig directly because they need the settings during
961 // compositing, and they don't connect to the config notifier
962 // because nodes are not QObjects (because only one base class
963 // can be a QObject).
964 KisNode* node = dynamic_cast<KisNode*>(view->image()->rootLayer().data());
965 if (node) {
966 node->updateSettings();
967 }
968 }
969
970 }
972
973 d->viewManager->showHideScrollbars();
974 }
975}
976
978{
979 // reload action icons!
980 Q_FOREACH (QAction *action, actionCollection()->actions()) {
982 }
983 if (d->mdiArea) {
984 d->mdiArea->setPalette(qApp->palette());
985 for (int i=0; i<d->mdiArea->subWindowList().size(); i++) {
986 QMdiSubWindow *window = d->mdiArea->subWindowList().at(i);
987 if (window) {
988 window->setPalette(qApp->palette());
989 KisView *view = qobject_cast<KisView*>(window->widget());
990 if (view) {
991 view->slotThemeChanged(qApp->palette());
992 }
993 }
994 }
995 }
996
998
999 // Update toolbars
1000 {
1001 Q_FOREACH (KisToolBar* aToolBar, toolBars()) {
1002 QObjectList objects;
1003 objects.append(aToolBar);
1004 while (!objects.isEmpty()) {
1005 QWidget* widget = qobject_cast<QWidget*>(objects.takeFirst());
1006 if (widget) {
1007 objects.append(widget->children());
1008 widget->setPalette(qApp->palette());
1009 }
1010 }
1011 }
1012 }
1013}
1014
1016{
1017 KConfigGroup group(KSharedConfig::openConfig(), "theme");
1018#ifndef Q_OS_HAIKU
1019 if (group.readEntry("Theme", "") == d->themeManager->currentThemeName()) return;
1020
1021 // save theme changes instantly
1022 group.writeEntry("Theme", d->themeManager->currentThemeName());
1023#endif
1024 updateTheme();
1025
1026 // Make the other top level windows update as well
1027 Q_FOREACH (QWidget* topLevelWidget, qApp->topLevelWidgets()) {
1028 if (topLevelWidget == this) {
1029 // Skip if the current top level widget is this window
1030 continue;
1031 }
1032 if (topLevelWidget->isHidden()) {
1033 // Skip unwanted top level widgets like menus, dropdowns, tooltips, etc.
1034 continue;
1035 }
1036 KisMainWindow *topLevelMainWindow = qobject_cast<KisMainWindow*>(topLevelWidget);
1037 if (topLevelMainWindow) {
1038 topLevelMainWindow->updateTheme();
1039 Q_EMIT topLevelMainWindow->themeChanged();
1040 } else {
1041 QObjectList objects;
1042 objects.append(topLevelWidget);
1043 while (!objects.isEmpty()) {
1044 QWidget* widget = qobject_cast<QWidget*>(objects.takeFirst());
1045 if (widget) {
1046 objects.append(widget->children());
1048 }
1049 }
1050 }
1051 }
1052
1054
1055 Q_EMIT themeChanged();
1056}
1057
1059{
1060 // update MDI area theme
1061 // Tab close button override
1062 // just switch this icon out for all OSs so it is easier to see
1063 QString closeButtonImageUrl;
1064 QString closeButtonHoverColor;
1066 closeButtonImageUrl = QStringLiteral(":/dark_close-tab.svg");
1067 closeButtonHoverColor = QStringLiteral("lightcoral");
1068 } else {
1069 closeButtonImageUrl = QStringLiteral(":/light_close-tab.svg");
1070 closeButtonHoverColor = QStringLiteral("darkred");
1071 }
1072 QString tabStyleSheet = QStringLiteral(R"(
1073 QTabBar::close-button {
1074 image: url(%1);
1075 padding: 1.5px;
1076 border-radius: 3px;
1077 }
1078 QTabBar::close-button:hover {
1079 background-color: %2;
1080 }
1081 QTabBar::close-button:pressed {
1082 background-color: red;
1083 }
1084
1085 QHeaderView::section {
1086 padding: 7px;
1087 }
1088
1089 )")
1090 .arg(closeButtonImageUrl, closeButtonHoverColor);
1091
1092
1093 QTabBar* tabBar = d->findTabBarHACK();
1094 if (tabBar) {
1095 tabBar->setStyleSheet(tabStyleSheet);
1096 }
1097
1098}
1099
1101{
1102 return centralWidget() != d->widgetStack;
1103}
1104
1106{
1107#ifdef Q_OS_ANDROID
1108 if (detach) {
1109 QMessageBox::warning(this, i18nc("@title:window", "Krita"),
1110 "Detach Canvas is unsupported on Android");
1111 }
1112#else
1113 if (detach == canvasDetached()) return;
1114
1115 QWidget *outgoingWidget = centralWidget() ? takeCentralWidget() : nullptr;
1116 QWidget *incomingWidget = d->canvasWindow->swapMainWidget(outgoingWidget);
1117
1118 if (incomingWidget) {
1119 setCentralWidget(incomingWidget);
1120 }
1121
1122 if (detach) {
1123 d->canvasWindow->show();
1124 } else {
1125 d->canvasWindow->hide();
1126 }
1127 d->toggleDetachCanvas->setChecked(detach);
1128#endif
1129}
1130
1131QWidget * KisMainWindow::canvasWindow() const
1132{
1133 return d->canvasWindow;
1134}
1135
1140
1142{
1143 KisRecentFilesManager::instance()->remove(QUrl::fromLocalFile(url));
1144}
1145
1146void KisMainWindow::slotUpdateSaveActionTitle(const QString &documentPath)
1147{
1148 const QString fileName = QFileInfo(documentPath).fileName();
1149
1150 if (!fileName.isEmpty()) {
1151 d->saveAction->setToolTip(i18n("Save as %1", fileName));
1152 }
1153 else {
1154 d->saveAction->setToolTip(i18n("Save"));
1155 }
1156}
1157
1159{
1160 Q_UNUSED(readWrite);
1161 d->actionManager()->updateGUI();
1162}
1163
1165{
1166 if (d->activeView) {
1167 return d->activeView;
1168 }
1169 return 0;
1170}
1171
1172bool KisMainWindow::openDocument(const QString &path, OpenFlags flags)
1173{
1174 ScopedWidgetDisabler disabler(d->welcomePage->dropFrameBorder);
1175 QApplication::processEvents(); // make UI more responsive
1176
1177 if (!QFile(path).exists()) {
1178 if (!(flags & BatchMode)) {
1179 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"), i18n("The file %1 does not exist.", path));
1180 }
1181 KisRecentFilesManager::instance()->remove(QUrl::fromLocalFile(path)); //remove the file from the recent-opened-file-list
1182 return false;
1183 }
1184 return openDocumentInternal(path, flags);
1185}
1186
1187bool KisMainWindow::openDocumentInternal(const QString &path, OpenFlags flags)
1188{
1189 if (!QFile(path).exists()) {
1190 qWarning() << "KisMainWindow::openDocumentInternal. Could not open:" << path;
1191 return false;
1192 }
1193
1195
1196 if (flags & BatchMode) {
1197 newdoc->setFileBatchMode(true);
1198 }
1199
1200 d->firstTime = true;
1201 connect(newdoc, SIGNAL(completed()), this, SLOT(slotLoadCompleted()));
1202 connect(newdoc, SIGNAL(canceled(QString)), this, SLOT(slotLoadCanceled(QString)));
1203
1204 KisDocument::OpenFlags openFlags = KisDocument::None;
1205 // XXX: Why this duplication of OpenFlags...
1206 if (flags & RecoveryFile) {
1207 openFlags |= KisDocument::RecoveryFile;
1208 }
1209
1210 bool openRet = !(flags & Import) ? newdoc->openPath(path, openFlags) : newdoc->importDocument(path);
1211
1212 if (!openRet) {
1213 delete newdoc;
1214 return false;
1215 }
1216
1217 KisPart::instance()->addDocument(newdoc);
1218
1219 // Try to determine whether this was an unnamed autosave
1220 if (flags & RecoveryFile &&
1221 ( path.startsWith(QDir::tempPath())
1222 || path.startsWith(QDir::homePath())
1223 ) &&
1224 ( QFileInfo(path).fileName().startsWith(".krita")
1225 || QFileInfo(path).fileName().startsWith("krita")
1226 )
1227 )
1228 {
1229 QString path = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
1230 if (!QFileInfo(path).exists()) {
1231 path = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
1232 }
1233 newdoc->setPath(path + "/" + newdoc->objectName() + ".kra");
1234 }
1235
1236 return true;
1237}
1238
1240 Q_FOREACH(QMdiSubWindow *subwindow, d->mdiArea->subWindowList()) {
1241 KisView *view = qobject_cast<KisView*>(subwindow->widget());
1243
1244 if (view) {
1245 if (view->document() == document) {
1246 setActiveSubWindow(subwindow);
1247 return;
1248 }
1249 }
1250 }
1251
1253}
1254
1256 QMdiSubWindow *subWindow)
1257{
1258 showWelcomeScreen(false); // see workaround in function header
1259
1260 KisView *view = KisPart::instance()->createView(document, d->viewManager, this);
1261 addView(view, subWindow);
1262
1263 Q_EMIT guiLoadingFinished();
1264
1265#ifdef Q_OS_ANDROID
1266 // HACK: When opening documents on Android, the main window sometimes fails
1267 // to update until the application is shunted to the background and brought
1268 // back or the menu bar is fiddled with. Flickering the window fixes this.
1269 // Having a docker that uses QML somehow also fixes this, so this hack is
1270 // gone again in 5.3 with the introduction of the text properties docker.
1271 // UNHACK: But not on Xiaomi devices! There flickering the window makes it
1272 // sorta exit fullscreen, adding black bars at the top and bottom. Just
1273 // opening a document seems to work fine on these devices though, it delays
1274 // for a moment then displays fine, so just skip this there I guess.
1276 slotFlashWindowHack();
1277 }
1278#endif
1279
1280 return view;
1281}
1282
1284{
1285 KoFileDialog dialog(this, KoFileDialog::ImportFiles, "OpenDocument");
1286 dialog.setDefaultDir(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
1288 dialog.setCaption(isImporting ? i18n("Import Images") : i18n("Open Images"));
1289
1290 QStringList filenames = dialog.filenames();
1291 filenames.sort();
1292
1293 return filenames;
1294}
1295
1296// Separate from openDocument to handle async loading (remote URLs)
1298{
1299 KisDocument *newdoc = qobject_cast<KisDocument*>(sender());
1300 if (newdoc && newdoc->image()) {
1302
1303 disconnect(newdoc, SIGNAL(completed()), this, SLOT(slotLoadCompleted()));
1304 disconnect(newdoc, SIGNAL(canceled(QString)), this, SLOT(slotLoadCanceled(QString)));
1305
1306 Q_EMIT loadCompleted();
1307 }
1308}
1309
1310void KisMainWindow::slotLoadCanceled(const QString &errMsg)
1311{
1312 KisUsageLogger::log(QString("Loading canceled: %1.").arg(errMsg));
1313 KisDocument* doc = qobject_cast<KisDocument*>(sender());
1314 Q_ASSERT(doc);
1315 disconnect(doc, SIGNAL(completed()), this, SLOT(slotLoadCompleted()));
1316 disconnect(doc, SIGNAL(canceled(QString)), this, SLOT(slotLoadCanceled(QString)));
1317}
1318
1319void KisMainWindow::slotSaveCanceled(const QString &errMsg)
1320{
1321 if (!errMsg.isEmpty()) { // empty when cancelled by user
1322 KisUsageLogger::log(QString("Saving cancelled. Error:").arg(errMsg));
1323 QMessageBox::critical(this, i18nc("@title:window", "Krita"), errMsg);
1324 }
1325 else {
1326 KisUsageLogger::log(QString("Saving cancelled by the user."));
1327 }
1329}
1330
1332{
1333 KisUsageLogger::log(QString("Saving Completed"));
1334 KisDocument* doc = qobject_cast<KisDocument*>(sender());
1335 if (doc) {
1336 disconnect(doc, SIGNAL(completed()), this, SLOT(slotSaveCompleted()));
1337 disconnect(doc, SIGNAL(canceled(QString)), this, SLOT(slotSaveCanceled(QString)));
1338 }
1339
1340 if (d->deferredClosingEvent) {
1341 KXmlGuiWindow::closeEvent(d->deferredClosingEvent);
1342 }
1343}
1344
1346{
1347 std::unique_lock<QMutex> l(d->savingEntryMutex, std::try_to_lock);
1348 return !l.owns_lock();
1349}
1350
1351bool KisMainWindow::installBundle(const QString &fileName) const
1352{
1353 QFileInfo from(fileName);
1354 QFileInfo to(QStringLiteral("%1/%2").arg(KoResourcePaths::getAppDataLocation(), from.fileName()));
1355 if (to.exists()) {
1356 QFile::remove(to.canonicalFilePath());
1357 }
1358 return QFile::copy(fileName, to.absoluteFilePath());
1359}
1360
1362{
1363 int size = 256;
1364 qreal scale = qreal(size)/qreal(qMax(geometry().width(), geometry().height()));
1365 QImage layoutThumbnail = QImage(qRound(geometry().width()*scale), qRound(geometry().height()*scale), QImage::Format_ARGB32);
1366 QPainter gc(&layoutThumbnail);
1367 gc.fillRect(0, 0, layoutThumbnail.width(), layoutThumbnail.height(), this->palette().dark());
1368
1369 Q_FOREACH(const QObject *child, children()) {
1370 if (child->isWidgetType()) {
1371 const QWidget *w = static_cast<const QWidget *>(child);
1372
1373 if (w->isVisible() && !w->property("_kis_excludeFromLayoutThumbnail").toBool()) {
1374 QRect wRect = QRectF(w->geometry().x()*scale
1375 , w->geometry().y()*scale
1376 , w->geometry().width()*scale
1377 , w->geometry().height()*scale
1378 ).toRect();
1379
1380 wRect = wRect.intersected(layoutThumbnail.rect().adjusted(-1, -1, -1, -1));
1381
1382 gc.setBrush(this->palette().window());
1383 if (w == d->widgetStack) {
1384 gc.setBrush(d->mdiArea->background());
1385 }
1386 gc.setPen(this->palette().windowText().color());
1387 gc.drawRect(wRect);
1388 }
1389 }
1390 }
1391 gc.end();
1392 return layoutThumbnail;
1393}
1394
1395bool KisMainWindow::saveDocument(KisDocument *document, bool saveas, bool isExporting, bool isAdvancedExporting )
1396{
1397 if (!document) {
1398 return true;
1399 }
1400
1408 std::unique_lock<QMutex> l(d->savingEntryMutex, std::try_to_lock);
1409 if (!l.owns_lock()) return false;
1410
1411 // no busy wait for saving because it is dangerous!
1412 KisDelayedSaveDialog dlg(document->image(), KisDelayedSaveDialog::SaveDialog, 0, this);
1413 dlg.blockIfImageIsBusy();
1414
1415 if (dlg.result() == KisDelayedSaveDialog::Rejected) {
1416 return false;
1417 }
1418 else if (dlg.result() == KisDelayedSaveDialog::Ignored) {
1419 QMessageBox::critical(qApp->activeWindow(),
1420 i18nc("@title:window", "Krita"),
1421 i18n("You are saving a file while the image is "
1422 "still rendering. The saved file may be "
1423 "incomplete or corrupted.\n\n"
1424 "Please select a location where the original "
1425 "file will not be overridden!"));
1426
1427
1428 saveas = true;
1429 }
1430
1431 if (document->isRecovered()) {
1432 saveas = true;
1433 }
1434
1435 if (document->path().isEmpty()) {
1436 saveas = true;
1437 }
1438
1439 QFile target(document->path());
1440 if (!target.exists()) { // Possible when file is moved/unmounted during Krita session.
1441 saveas = true;
1442 }
1443
1444 connect(document, SIGNAL(completed()), this, SLOT(slotSaveCompleted()));
1445 connect(document, SIGNAL(canceled(QString)), this, SLOT(slotSaveCanceled(QString)));
1446
1447 QByteArray nativeFormat = document->nativeFormatMimeType();
1448 QByteArray oldMimeFormat = document->mimeType();
1449
1450 QUrl suggestedURL = QUrl::fromLocalFile(document->path());
1451
1453
1455 if (!mimeFilter.contains(oldMimeFormat)) {
1456 dbgUI << "KisMainWindow::saveDocument no export filter for" << oldMimeFormat;
1457
1458 // --- don't setOutputMimeType in case the user cancels the Save As
1459 // dialog and then tries to just plain Save ---
1460
1461 // suggest a different filename extension (yes, we fortunately don't all live in a world of magic :))
1462 QString suggestedFilename = QFileInfo(suggestedURL.toLocalFile()).completeBaseName();
1463
1464 if (!suggestedFilename.isEmpty()) { // ".kra" looks strange for a name
1465 suggestedFilename = suggestedFilename + "." + KisMimeDatabase::suffixesForMimeType(KIS_MIME_TYPE).first();
1466 suggestedURL = suggestedURL.adjusted(QUrl::RemoveFilename);
1467 suggestedURL.setPath(suggestedURL.path() + suggestedFilename);
1468 }
1469
1470 // force the user to choose outputMimeType
1471 saveas = true;
1472 }
1473
1474 bool ret = false;
1475
1476 if (document->path().isEmpty() || isExporting || saveas) {
1477 // if you're just File/Save As'ing to change filter options you
1478 // don't want to be reminded about overwriting files etc.
1479 bool justChangingFilterOptions = false;
1480
1481 KoFileDialog dialog(this, KoFileDialog::SaveFile, "SaveAs");
1482 dialog.setCaption(isExporting ? i18n("Exporting") : i18n("Saving As"));
1483
1484 //qDebug() << ">>>>>" << isExporting << d->lastExportLocation << d->lastExportedFormat << QString::fromLatin1(document->mimeType());
1485
1486 if (isExporting && !d->lastExportLocation.isEmpty() && !d->lastExportLocation.contains(QDir::tempPath())) {
1487
1488 // Use the location where we last exported to, if it's set, as the opening location for the file dialog
1489 QString proposedPath = QFileInfo(d->lastExportLocation).absolutePath();
1490 // If the document doesn't have a filename yet, use the title
1491 QString proposedFileName = suggestedURL.isEmpty() ? document->documentInfo()->aboutInfo("title") : QFileInfo(suggestedURL.toLocalFile()).completeBaseName();
1492 // Use the last mimetype we exported to by default
1493 QString proposedMimeType = d->lastExportedFormat.isEmpty() ? "" : d->lastExportedFormat;
1494 QString proposedExtension = KisMimeDatabase::suffixesForMimeType(proposedMimeType).first().remove("*,");
1495
1496 // Set the default dir: this overrides the one loaded from the config file, since we're exporting and the lastExportLocation is not empty
1497 dialog.setDefaultDir(proposedPath + "/" + proposedFileName + "." + proposedExtension, true);
1498 dialog.setMimeTypeFilters(mimeFilter, proposedMimeType);
1499 }
1500 else {
1501 //This section only runs when the user haven't exported yet during the session, behavior set in the File Handling, Default MimeType setting.
1502 KisConfig cfg(true);
1503 QByteArray default_mime_type = cfg.exportMimeType(false).toUtf8();
1504 QString proposedMimeType = QString::fromLatin1(default_mime_type);
1505
1506 // Get the last used location for saving
1507 KConfigGroup group = KSharedConfig::openConfig()->group("File Dialogs");
1508 QString proposedPath = group.readEntry("SaveAs", "");
1509 // if that is empty, get the last used location for loading
1510 if (proposedPath.isEmpty()) {
1511 proposedPath = group.readEntry("OpenDocument", "");
1512 }
1513 // If that is empty, too, use the Pictures location.
1514 if (proposedPath.isEmpty()) {
1515 proposedPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
1516 }
1517 // But only use that if the suggestedUrl, that is, the document's own url is empty, otherwise
1518 // open the location where the document currently is.
1519
1520 //For if the user picked All Files Supported as the default, where there would not be an extension
1521 if(default_mime_type == "all/mime"){
1522 dialog.setDefaultDir(suggestedURL.isEmpty() ? proposedPath : proposedPath + "/" + QFileInfo(suggestedURL.toLocalFile()).completeBaseName(), true);
1523 }
1524
1525 if (default_mime_type != "all/mime" && !default_mime_type.isEmpty()) {
1526 QString proposedExtension = KisMimeDatabase::suffixesForMimeType(proposedMimeType).first().remove("*,");
1527 //This line is responsible for setting filename, which also manipulates filters.
1528 dialog.setDefaultDir(suggestedURL.isEmpty() ? proposedPath : proposedPath + "/" + QFileInfo(suggestedURL.toLocalFile()).completeBaseName() + "." + proposedExtension, true);
1529 }
1530
1531 if (!isExporting) {
1532 // If Saving, use the document's mimetype, or if that is empty, kra, which is the safest.
1533 dialog.setDefaultDir(suggestedURL.isEmpty() ? proposedPath : suggestedURL.toLocalFile(), true);
1534 default_mime_type = document->mimeType().isEmpty() ? nativeFormat : document->mimeType();
1535 }
1536 dialog.setMimeTypeFilters(mimeFilter, QString::fromLatin1(default_mime_type));
1537 }
1538
1539 QString newFilePath = dialog.filename();
1540
1541 bool bOk = true;
1542 if (newFilePath.isEmpty()) {
1543 bOk = false;
1544 }
1545
1546 if (bOk) {
1547 if (document->documentInfo()->aboutInfo("title") == i18n("Unnamed")) {
1548 QString fn = newFilePath;
1549 QFileInfo info(fn);
1550 document->documentInfo()->setAboutInfo("title", info.completeBaseName());
1551 }
1552
1553 QByteArray outputFormat = nativeFormat;
1554
1555 QString outputFormatString = KisMimeDatabase::mimeTypeForFile(newFilePath, false);
1556 outputFormat = outputFormatString.toLatin1();
1557
1558
1559 if (!isExporting) {
1560 justChangingFilterOptions = (newFilePath == document->path()) && (outputFormat == document->mimeType());
1561 }
1562 else {
1563 QString path = QFileInfo(d->lastExportLocation).absolutePath();
1564 QString filename = QFileInfo(document->path()).completeBaseName();
1565 justChangingFilterOptions = (QFileInfo(newFilePath).absolutePath() == path)
1566 && (QFileInfo(newFilePath).completeBaseName() == filename)
1567 && (outputFormat == d->lastExportedFormat);
1568 }
1569
1570 bool wantToSave = true;
1571
1572 // don't change this line unless you know what you're doing :)
1573 if (!justChangingFilterOptions) {
1574 if (!document->isNativeFormat(outputFormat))
1575 wantToSave = true;
1576 }
1577
1578 if (wantToSave) {
1579 if (!isExporting) { // Save As
1580 ret = document->saveAs(newFilePath, outputFormat, true);
1581 if (ret) {
1582 dbgUI << "Successful Save As!";
1583 KisPart::instance()->queueAddRecentURLToAllMainWindowsOnFileSaved(QUrl::fromLocalFile(newFilePath));
1584 } else {
1585 dbgUI << "Failed Save As!";
1586
1587 }
1588 }
1589 else { // Export
1590 ret = document->exportDocument(newFilePath, outputFormat, isAdvancedExporting, false);
1591 if (ret) {
1592 d->lastExportLocation = newFilePath;
1593 d->lastExportedFormat = outputFormat;
1594 }
1595 }
1596
1597 } // if (wantToSave) {
1598 else
1599 ret = false;
1600 } // if (bOk) {
1601 else
1602 ret = false;
1603 } else { // saving
1604 // We cannot "export" into the currently
1605 // opened document. We are not Gimp.
1606 KIS_ASSERT_RECOVER_NOOP(!isExporting);
1607
1608 // be sure document has the correct outputMimeType!
1609 if (document->isModified()) {
1610 ret = document->save(true, 0);
1611 }
1612
1613 if (!ret) {
1614 dbgUI << "Failed Save!";
1615 }
1616 }
1617
1618 return ret;
1619}
1620
1622{
1623 if (activeView()) {
1624 activeView()->document()->undoStack()->undo();
1625 }
1626}
1627
1629{
1630 if (activeView()) {
1631 activeView()->document()->undoStack()->redo();
1632 }
1633}
1634
1635void KisMainWindow::closeEvent(QCloseEvent *e)
1636{
1637 if (hackIsSaving()) {
1638 e->setAccepted(false);
1639 return;
1640 }
1641
1642 if (!KisPart::instance()->closingSession()) {
1643 QAction *action= d->viewManager->actionCollection()->action("view_show_canvas_only");
1644 if ((action) && (action->isChecked())) {
1645 action->setChecked(false);
1646 }
1647
1648 // Save session when last window is closed
1649 if (KisPart::instance()->mainwindowCount() == 1) {
1650 bool closeAllowed = KisPart::instance()->closeSession();
1651
1652 if (!closeAllowed) {
1653 e->setAccepted(false);
1654 return;
1655 }
1656 }
1657 }
1658
1659 d->mdiArea->closeAllSubWindows();
1660
1661 QList<QMdiSubWindow*> childrenList = d->mdiArea->subWindowList();
1662
1663 if (childrenList.isEmpty()) {
1664 // TODO: that assignment looks really suspicious, because `e`
1665 // is destroyed right after the exit of this function
1666 d->deferredClosingEvent = e;
1667 d->canvasWindow->close();
1668 } else {
1669 e->setAccepted(false);
1670 }
1671}
1672
1674{
1675 KSharedConfigPtr config = KSharedConfig::openConfig();
1676
1677 if (d->windowSizeDirty ) {
1678 dbgUI << "KisMainWindow::saveWindowSettings";
1679 KConfigGroup group = d->windowStateConfig;
1680 KWindowConfig::saveWindowSize(windowHandle(), group);
1681 config->sync();
1682 d->windowSizeDirty = false;
1683 }
1684
1685 if (!d->activeView || d->activeView->document()) {
1686
1687 // Save toolbar position into the config file of the app, under the doc's component name
1688 KConfigGroup group = d->windowStateConfig;
1690
1691 // Save state of dock widgets
1692 for (QMap<QString, QDockWidget*>::const_iterator i = d->dockWidgetsMap.constBegin();
1693 i != d->dockWidgetsMap.constEnd(); ++i) {
1694 if (i.value()->widget()) {
1695 KConfigGroup dockGroup = group.group(QString("DockWidget ") + i.key());
1696 dockGroup.writeEntry("Locked", i.value()->property("Locked").toBool());
1697 dockGroup.writeEntry("DockArea", (int) dockWidgetArea(i.value()));
1698 dockGroup.writeEntry("xPosition", (int) i.value()->widget()->x());
1699 dockGroup.writeEntry("yPosition", (int) i.value()->widget()->y());
1700
1701 dockGroup.writeEntry("width", (int) i.value()->widget()->width());
1702 dockGroup.writeEntry("height", (int) i.value()->widget()->height());
1703 }
1704 }
1705
1706 }
1707
1708 KSharedConfig::openConfig()->sync();
1709 resetAutoSaveSettings(); // Don't let KisKMainWindow override the good stuff we wrote down
1710
1711}
1712
1713void KisMainWindow::resizeEvent(QResizeEvent * e)
1714{
1715 d->windowSizeDirty = true;
1716 KXmlGuiWindow::resizeEvent(e);
1717}
1718
1719
1720void KisMainWindow::dragMoveEvent(QDragMoveEvent *event)
1721{
1722 dragMove(event);
1723 event->accept();
1724}
1725
1726void KisMainWindow::dragLeaveEvent(QDragLeaveEvent *event)
1727{
1728 dragLeave();
1729 event->accept();
1730}
1731
1733{
1734 QAction *action= d->viewManager->actionCollection()->action("view_show_canvas_only");
1735 return !action || !action->isChecked();
1736}
1737
1738void KisMainWindow::showEvent(QShowEvent *event)
1739{
1740 // we're here because, we need to make sure everything (dockers, toolbars etc) is loaded and ready before
1741 // we can hide it.
1742 if (!event->spontaneous()) {
1743 setMainWindowLayoutForCurrentMainWidget(d->widgetStack->currentIndex(), false);
1744 }
1745#ifdef Q_OS_ANDROID
1746 // The user can conceivably purchase a product from the splash screen while
1747 // Krita is still loading. In that case, the "pending" flag will be set. The
1748 // dialog in question will clear the flag.
1750 if (androidDonations && androidDonations->isShowDonationManagementDialogPending()) {
1751 QTimer::singleShot(0, this, &KisMainWindow::slotShowDonationManagementDialog);
1752 }
1753#endif
1754 return KXmlGuiWindow::showEvent(event);
1755}
1756
1757void KisMainWindow::setMainWindowLayoutForCurrentMainWidget(int widgetIndex, bool widgetIndexChanged)
1758{
1759
1760 if (widgetIndex == 0) {
1761 if (widgetIndexChanged) {
1766
1767 if (d->mdiArea->subWindowList().isEmpty()) {
1772 saveWindowState(true);
1773 } else {
1774 saveMainWindowSettings(d->windowStateConfig);
1775 }
1776 }
1778 }
1779 else {
1780 setAutoSaveSettings(d->windowStateConfig, false);
1781 statusBar()->setVisible(KisConfig(true).showStatusBar());
1782 }
1783
1784 QList<QAction *> actions = d->dockWidgetMenu->menu()->actions();
1785 actions.append(toolBarMenuAction()->menu()->actions());
1786 for (QAction *action : actions) {
1787 if (action) {
1788 action->setEnabled(widgetIndex);
1789 }
1790 }
1791}
1792
1794{
1795 // This makes sure we don't save window state when we're in welcome page mode, because all the dockers
1796 // etc are hidden while the user is here.
1798
1799 toggleDockersVisibility(false, true);
1800 if (statusBar()) {
1801 statusBar()->hide();
1802 }
1803 QList<QToolBar *> toolbars = findChildren<QToolBar *>();
1804 for (QToolBar *toolbar : toolbars) {
1805 if (toolbar->objectName() != "mainToolBar") {
1806 toolbar->hide();
1807 }
1808 }
1809}
1810
1812{
1813 d->activeView = view;
1814
1815 if (d->undoActionsUpdateManager) {
1816 d->undoActionsUpdateManager->setCurrentDocument(view ? view->document() : 0);
1817 }
1818
1819 d->viewManager->setCurrentView(view);
1820
1821 d->activeViewConnections.clear();
1822 d->activeViewConnections.addConnection(view->document(),
1823 SIGNAL(sigPathChanged(QString)),
1824 this, SLOT(slotUpdateSaveActionTitle(QString)));
1825 slotUpdateSaveActionTitle(view->document()->path());
1826 d->activeViewConnections.addConnection(view->document(),
1827 SIGNAL(sigReadWriteChanged(bool)),
1828 this, SLOT(slotUpdateReadWriteMode(bool)));
1829 slotUpdateReadWriteMode(view->document()->isReadWrite());
1830
1832
1833 Q_EMIT activeViewChanged();
1834}
1835
1837{
1838 d->activeViewConnections.clear();
1839 slotUpdateSaveActionTitle(QString());
1841}
1842
1843void KisMainWindow::dragMove(QDragMoveEvent * event)
1844{
1845 QTabBar *tabBar = d->findTabBarHACK();
1846
1847 if (!tabBar && d->mdiArea->viewMode() == QMdiArea::TabbedView) {
1848 qWarning() << "WARNING!!! Cannot find QTabBar in the main window! Looks like Qt has changed behavior. Drag & Drop between multiple tabs might not work properly (tabs will not switch automatically)!";
1849 }
1850
1851 if (tabBar && tabBar->isVisible()) {
1852 QPoint pos = tabBar->mapFromGlobal(mapToGlobal(event->pos()));
1853 if (tabBar->rect().contains(pos)) {
1854 const int tabIndex = tabBar->tabAt(pos);
1855
1856 if (tabIndex >= 0 && tabBar->currentIndex() != tabIndex) {
1857 d->tabSwitchCompressor->start(tabIndex);
1858 }
1859 } else if (d->tabSwitchCompressor->isActive()) {
1860 d->tabSwitchCompressor->stop();
1861 }
1862 }
1863}
1864
1866{
1867 if (d->tabSwitchCompressor->isActive()) {
1868 d->tabSwitchCompressor->stop();
1869 }
1870}
1871
1872
1874{
1875 QTabBar *tabBar = d->findTabBarHACK();
1876 if (!tabBar) return;
1877
1878 tabBar->setCurrentIndex(index);
1879}
1880
1882{
1883 const int currentIndex = show ? 0 : 1;
1884 if (d->widgetStack->currentIndex() != currentIndex) {
1885 setUpdatesEnabled(false);
1886 // These have to be done in different sequence to avoid graphical
1887 // layout glitch during the switch.
1888 if (show) {
1889 setMainWindowLayoutForCurrentMainWidget(currentIndex, true);
1890 d->widgetStack->setCurrentIndex(currentIndex);
1891 } else {
1892 d->widgetStack->setCurrentIndex(currentIndex);
1893 setMainWindowLayoutForCurrentMainWidget(currentIndex, true);
1894 }
1895 setUpdatesEnabled(true);
1896 }
1897}
1898
1900{
1902 dlg->exec();
1903 dlg->deleteLater();
1904}
1905
1907{
1908 dbgUI << "slotImportFile()";
1909 slotFileOpen(true);
1910}
1911
1912
1913void KisMainWindow::slotFileOpen(bool isImporting)
1914{
1915 QStringList urls = showOpenFileDialog(isImporting);
1916
1917 if (urls.isEmpty())
1918 return;
1919
1920 Q_FOREACH (const QString& url, urls) {
1921
1922 if (!url.isEmpty()) {
1923 OpenFlags flags = isImporting ? Import : None;
1924 bool res = openDocument(url, flags);
1925 if (!res) {
1926 warnKrita << "Loading" << url << "failed";
1927 }
1928 }
1929 }
1930}
1931
1933{
1934 (void) openDocument(url.toLocalFile(), None);
1935}
1936
1938{
1939 if (saveDocument(d->activeView->document(), false, false,false)) {
1940 Q_EMIT documentSaved();
1941 }
1942}
1943
1945{
1946#if defined(Q_OS_ANDROID) && KRITA_QT_HAS_ANDROID_QPLATFORMSCREEN_DENSITY_ADJUSTMENT
1948 if (androidScaling) {
1949 androidScaling->showDialog();
1950 }
1951#endif
1952}
1953
1955{
1956 if (saveDocument(d->activeView->document(), true, false,false)) {
1957 Q_EMIT documentSaved();
1958 }
1959}
1960
1962{
1963 if (saveDocument(d->activeView->document(), true, true,false)) {
1964 Q_EMIT documentSaved();
1965 }
1966}
1968{
1969 if (saveDocument(d->activeView->document(), true, true,true)) {
1970 Q_EMIT documentSaved();
1971 }
1972}
1973
1977
1978#ifdef Q_OS_ANDROID
1979void KisMainWindow::slotShowDonationManagementDialog()
1980{
1981 // Don't show the donation management dialog on top of another dialog
1982 // that may have triggered a donation flow, such as the bundle manager.
1983 QWidget *win = qApp->activeWindow();
1984 if (win && !qobject_cast<KisMainWindow *>(win) && (win->isModal() || win->windowModality() != Qt::NonModal)) {
1985 return;
1986 }
1987
1988 // We don't use `exec` here because the purchase stuff runs in Android's
1989 // event loop, so it's legitimately possible that we get hit by another
1990 // request to show the donation management dialog while it's already up
1991 // and it's more convenient for the dialog to handle the deduplication.
1992 QString objectName = QStringLiteral("kisdonationmanagementdialog");
1993 KisDonationManagementDialog *dlg = findChild<KisDonationManagementDialog *>(objectName, Qt::FindDirectChildrenOnly);
1994 if (dlg) {
1995 dlg->reshow();
1996 } else {
1997 dlg = new KisDonationManagementDialog(this);
1998
1999 QAction *action = actionCollection()->action("manage_supporter_bundles");
2000 if (action) {
2001 connect(dlg, &KisDonationManagementDialog::sigShowSupporterBundles, action, &QAction::trigger);
2002 }
2003
2004 dlg->setAttribute(Qt::WA_DeleteOnClose);
2005 dlg->setObjectName(objectName);
2006 dlg->show();
2007 }
2008}
2009
2010void KisMainWindow::slotFlashWindowHack()
2011{
2012 if (!d->flashWindowHackInProgress) {
2013 d->flashWindowHackInProgress = true;
2014 QTimer::singleShot(0, this, [this] {
2015 hide();
2016 QTimer::singleShot(0, this, [this] {
2017 show();
2018 d->flashWindowHackInProgress = false;
2019 });
2020 });
2021 }
2022}
2023#endif
2024
2026{
2027 return d->viewManager->canvasResourceProvider()->resourceManager();
2028}
2029
2031{
2032 return d->mdiArea->subWindowList().size();
2033}
2034
2035const KConfigGroup &KisMainWindow::windowStateConfig() const
2036{
2037 return d->windowStateConfig;
2038}
2039
2040void KisMainWindow::saveWindowState(bool restoreNormalState)
2041{
2042 // We don't need to save welcome page's layout
2043 if (d->widgetStack->currentIndex() == 0) {
2044 // TODO(sh_zam): We should still save position/geometry, right?
2045 return;
2046 }
2047
2048 if (restoreNormalState) {
2049 QAction *showCanvasOnly = d->viewManager->actionCollection()->action("view_show_canvas_only");
2050
2051 if (showCanvasOnly && showCanvasOnly->isChecked()) {
2052 showCanvasOnly->setChecked(false);
2053 }
2054
2055 d->windowStateConfig.writeEntry("ko_geometry", saveGeometry().toBase64());
2056 d->windowStateConfig.writeEntry("State", saveState().toBase64());
2057
2058 // if the dockers are hidden at this time, save their state.
2059 if (!d->toggleDockers->isChecked()) {
2060 restoreState(d->dockerStateBeforeHiding);
2061 }
2062
2063 statusBar()->setVisible(true);
2064 menuBar()->setVisible(true);
2065
2067
2068 } else {
2069 saveMainWindowSettings(d->windowStateConfig);
2070 }
2071
2072}
2073
2074bool KisMainWindow::restoreWorkspaceState(const QByteArray &state)
2075{
2076 QByteArray oldState = saveState();
2077 const bool showTitlebars = KisConfig(false).showDockerTitleBars();
2078
2079 // needed because otherwise the layout isn't correctly restored in some situations
2080 Q_FOREACH (QDockWidget *dock, dockWidgets()) {
2081 if (dock) {
2082 dock->setProperty("Locked", false); // Unlock invisible dockers
2083 dock->toggleViewAction()->setEnabled(true);
2084 dock->hide();
2085 if (dock->titleBarWidget() && !dock->titleBarWidget()->inherits("KisUtilityTitleBar")) {
2086 dock->titleBarWidget()->setVisible(showTitlebars);
2087 }
2088 }
2089 }
2090
2091 bool success = KXmlGuiWindow::restoreState(state);
2092
2093 if (!success) {
2094 KXmlGuiWindow::restoreState(oldState);
2095 Q_FOREACH (QDockWidget *dock, dockWidgets()) {
2096 if (dock->titleBarWidget() && !dock->titleBarWidget()->inherits("KisUtilityTitleBar")) {
2097 dock->titleBarWidget()->setVisible(showTitlebars || dock->isFloating());
2098 }
2099 }
2100 return false;
2101 }
2102 return success;
2103}
2104
2106{
2107 QString md5 = sender()->property("md5").toString();
2109 KoResourceSP resource = rserver->resource(md5, "", "");
2110 if (resource) {
2111 restoreWorkspace(resource);
2112 }
2113 else {
2114 qWarning() << "Could not retrieve resource for" << md5;
2115 }
2116}
2117
2119{
2120 QList<KisKActionCollection *> actionCollections;
2121
2122 auto clients = guiFactory()->clients();
2123 int actionsCount = 0;
2124 for (const KisKXMLGUIClient *c : clients) {
2125 if (!c) {
2126 continue;
2127 }
2128 if (auto collection = c->actionCollection()) {
2129 actionCollections.append(collection);
2130 actionsCount += collection->count();
2131 }
2132 }
2133
2134 if (activeKisView()) {
2135 KisKActionCollection *layerActionCollection = new KisKActionCollection(0, "layeractions (disposable)");
2136 layerActionCollection->setComponentDisplayName(i18n("Layers/Masks"));
2137 KisNodeActivationActionCreatorVisitor v(layerActionCollection, viewManager()->nodeManager());
2138 activeKisView()->image()->rootLayer()->accept(v);
2139 actionCollections.append(layerActionCollection);
2140 actionsCount += layerActionCollection->count();
2141 }
2142
2143 d->commandBar->updateBar(actionCollections, actionsCount);
2144
2145 // The following line is needed to work around input method not working
2146 // on Windows.
2147 // See https://bugs.kde.org/show_bug.cgi?id=395598
2148 // and https://bugs.kde.org/show_bug.cgi?id=438122
2149 d->commandBar->activateWindow();
2150
2151 // The following line is present in Kate's version and was ported over
2152 // but I am sceptical of its use. I worry that it may subtly cause other
2153 // issues, and since the command bar appears to work fine without it, I
2154 // believe it may be better to leave it out. -- Alvin
2155 // centralWidget()->setFocusProxy(d->commandBar);
2156}
2157
2158void KisMainWindow::slotStoragesWarning(const QString &/*location*/)
2159{
2160 QString warning;
2162 warning = i18n("You don't have any resource bundles enabled.");
2163 }
2164
2165 if (!checkPaintOpAvailable()) {
2166 warning += i18n("\nThere are no brush presets available. Please enable a bundle that has presets before continuing.\n");
2167 QMessageBox::critical(this, i18nc("@title:window", "Krita"), warning);
2168
2169 QAction *action = actionCollection()->action("manage_bundles");
2170 if (action) {
2171 action->trigger();
2172 }
2173 }
2174
2176 QMessageBox::warning(this, i18nc("@title:window", "Krita"), warning + i18n("\nOnly your local resources are available."));
2177 }
2178
2179}
2180
2182{
2183 KisWorkspaceResourceSP workspace = res.dynamicCast<KisWorkspaceResource>();
2184
2185 bool success = restoreWorkspaceState(workspace->dockerState());
2186
2187 const bool showTitlebars = KisConfig(false).showDockerTitleBars();
2188 Q_FOREACH (QDockWidget *dock, dockWidgets()) {
2189 if (dock->titleBarWidget() && !dock->titleBarWidget()->inherits("KisUtilityTitleBar")) {
2190 dock->titleBarWidget()->setVisible(showTitlebars || dock->isFloating());
2191 }
2192 }
2193
2194 if (activeKisView()) {
2195 activeKisView()->resourceProvider()->notifyLoadingWorkspace(workspace);
2196 }
2197
2198 d->viewManager->notifyWorkspaceLoaded();
2199
2200 return success;
2201}
2202
2204{
2205 QByteArray currentWorkspace = saveState();
2206
2207 if (!d->workspaceBorrowedBy.isNull()) {
2208 if (other->id() == d->workspaceBorrowedBy) {
2209 // We're swapping our original workspace back
2210 d->workspaceBorrowedBy = QUuid();
2211 return currentWorkspace;
2212 } else {
2213 // Get our original workspace back before swapping with a third window
2214 KisMainWindow *borrower = KisPart::instance()->windowById(d->workspaceBorrowedBy);
2215 if (borrower) {
2216 QByteArray originalLayout = borrower->borrowWorkspace(this);
2217 borrower->restoreWorkspaceState(currentWorkspace);
2218
2219 d->workspaceBorrowedBy = other->id();
2220 return originalLayout;
2221 }
2222 }
2223 }
2224
2225 d->workspaceBorrowedBy = other->id();
2226 return currentWorkspace;
2227}
2228
2230{
2231 QByteArray workspaceA = a->borrowWorkspace(b);
2232 QByteArray workspaceB = b->borrowWorkspace(a);
2233
2234 a->restoreWorkspaceState(workspaceB);
2235 b->restoreWorkspaceState(workspaceA);
2236}
2237
2239{
2240 return d->viewManager;
2241}
2242
2244{
2245 if (!d->activeView->document())
2246 return;
2247
2248 KoDocumentInfo *docInfo = d->activeView->document()->documentInfo();
2249
2250 if (!docInfo)
2251 return;
2252
2253 KoDocumentInfoDlg *dlg = d->activeView->document()->createDocumentInfoDialog(this, docInfo);
2254
2255 if (dlg->exec()) {
2256 if (dlg->isDocumentSaved()) {
2257 d->activeView->document()->setModified(false);
2258 } else {
2259 d->activeView->document()->setModified(true);
2260 }
2261 }
2262
2263 delete dlg;
2264}
2265
2267{
2268 Q_FOREACH (QMdiSubWindow *subwin, d->mdiArea->subWindowList()) {
2269 if (subwin) {
2270 if(!subwin->close())
2271 return false;
2272 }
2273 }
2274
2275 return true;
2276}
2277
2279{
2280 // Do not close while KisMainWindow has the savingEntryMutex locked, bug409395.
2281 // After the background saving job is initiated, KisDocument blocks closing
2282 // while it saves itself.
2283 if (hackIsSaving()) {
2284 return;
2285 }
2287}
2288
2290{
2291 if (!activeView()) return;
2292
2293 KisDocument *document = activeView()->document();
2294 if (!document) return;
2295
2296 KisDlgImportImageSequence dlg(this, document);
2297
2298 if (dlg.exec() == QDialog::Accepted) {
2299 QStringList files = dlg.files();
2300 int firstFrame = dlg.firstFrame();
2301 int step = dlg.step();
2302 bool startFrom1 = dlg.startFrom1();
2303 bool autoAddHoldframes = dlg.autoAddHoldframes();
2304
2305
2306 KoUpdaterPtr updater =
2307 !document->fileBatchMode() ? viewManager()->createUnthreadedUpdater(i18n("Import frames")) : 0;
2308 KisAnimationImporter importer(document->image(), updater);
2309 int isAscending = dlg.isAscending();
2310 KisImportExportErrorCode status = importer.import(files, firstFrame, step, autoAddHoldframes, startFrom1, isAscending); // modify here, add a flag
2311
2312 if (!status.isOk() && !status.isInternalError()) {
2313 QString msg = status.errorMessage();
2314 if (!msg.isEmpty())
2315 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"), i18n("Could not finish import animation:\n%1", msg));
2316 }
2317 activeView()->canvasBase()->refetchDataFromImage();
2318 }
2319}
2320
2322{
2323 // Importing video requires ffmpeg, which is not available on Android.
2324#ifndef Q_OS_ANDROID
2325 KisDocument *document;
2327
2328 if (dlg.exec() == QDialog::Accepted) {
2329 const QTemporaryDir outputLocation(QDir::tempPath() + QDir::separator() + "krita" + QDir::separator() + "import_files");
2330 RenderedFrames renderedFrames = dlg.renderFrames(QDir(outputLocation.path()));
2331 dbgFile << "Frames rendered to directory: " << outputLocation.path();
2332 QStringList documentInfoList = dlg.documentInfo();
2333
2334 if (renderedFrames.isEmpty()) return;
2335
2336 dbgFile << "Animation Import options: " << documentInfoList;
2337
2338 int firstFrame = 0;
2339 const int step = documentInfoList[0].toInt();
2340 const int fps = documentInfoList[1].toInt();
2341 const int totalFrames = renderedFrames.framesNeedRelocation() ? (renderedFrames.renderedFrameTargetTimes.last() + 1) : renderedFrames.size() * step;
2342 const QString name = QFileInfo(documentInfoList[3]).fileName();
2343 const bool useCurrentDocument = documentInfoList[4].toInt();
2344 bool useDocumentColorSpace = false;
2345
2346 if ( useCurrentDocument ) {
2347 document = activeView()->document();
2348
2349 dbgFile << "Current frames:" << document->image()->animationInterface()->totalLength() << "total frames:" << totalFrames;
2350 if ( document->image()->animationInterface()->totalLength() < totalFrames ) {
2351 document->image()->animationInterface()->setDocumentRangeStartFrame(0);
2352 document->image()->animationInterface()->setDocumentRangeEndFrame(totalFrames);
2353 }
2354 } else {
2355 const int width = documentInfoList[5].toInt();
2356 const int height = documentInfoList[6].toInt();
2357 const double resolution = documentInfoList[7].toDouble();
2358
2359 const QString colorModel = documentInfoList[8];
2360 const QString colorDepth = documentInfoList[9];
2361 const QString profile = documentInfoList[10];
2362 useDocumentColorSpace = profile != "Default";
2363
2364 document = KisPart::instance()->createDocument();
2365 document->setObjectName(name);
2366
2367 KisPart::instance()->addDocument(document, false);
2368 const KoColorSpace *cs = KoColorSpaceRegistry::instance()->colorSpace(colorModel, colorDepth, profile);
2369 Q_ASSERT(cs);
2370
2371 QColor qc(Qt::white);
2372 qc.setAlpha(0);
2373 KoColor bgColor(qc, cs);
2374
2375 if (!document->newImage(name, width, height, cs, bgColor, KisConfig::RASTER_LAYER, 1, "", double(resolution / 72) )) {
2376 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"), i18n("Failed to create new document. Animation import aborted."));
2377 return;
2378 }
2379
2380 document->image()->animationInterface()->setFramerate(fps);
2381 document->image()->animationInterface()->setDocumentRangeStartFrame(0);
2382 document->image()->animationInterface()->setDocumentRangeEndFrame(totalFrames);
2383
2384 this->showDocument(document);
2385 }
2386
2387 KoUpdaterPtr updater =
2388 !document->fileBatchMode() ? viewManager()->createUnthreadedUpdater(i18n("Import frames")) : 0;
2389 KisAnimationImporter importer(document->image(), updater);
2390 KisImportExportErrorCode status = importer.import(renderedFrames.renderedFrameFiles, firstFrame, step, false, false, 0, useDocumentColorSpace, renderedFrames.renderedFrameTargetTimes);
2391
2392 if (!status.isOk() && !status.isInternalError()) {
2393 QString msg = status.errorMessage();
2394 if (!msg.isEmpty())
2395 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"), i18n("Could not finish import animation:\n%1", msg));
2396 }
2397
2398 activeView()->canvasBase()->refetchDataFromImage();
2399 document->image()->refreshGraphAsync();
2400 document->image()->waitForDone();
2401
2402 }
2403#endif
2404}
2405
2407{
2408 if (!activeView()) return;
2409
2410 KisImageSP image = viewManager()->image();
2411
2412 if (!image) return;
2413 if (!image->animationInterface()->hasAnimation()) return;
2414
2415 KisDocument *doc = viewManager()->document();
2416
2417 KisDlgAnimationRenderer dlgAnimationRenderer(doc, viewManager()->mainWindow());
2418 dlgAnimationRenderer.setCaption(i18n("Render Animation"));
2419 if (dlgAnimationRenderer.exec() == QDialog::Accepted) {
2420 KisAnimationRenderingOptions encoderOptions = dlgAnimationRenderer.getEncoderOptions();
2421 KisAnimationRender::render(doc, viewManager(), encoderOptions);
2422 }
2423}
2424
2426{
2427 if (!activeView()) return;
2428
2429 KisImageSP image = viewManager()->image();
2430
2431 if (!image) return;
2432 if (!image->animationInterface()->hasAnimation()) return;
2433
2434 KisDocument *doc = viewManager()->document();
2435
2436 KisConfig cfg(true);
2437
2438 KisPropertiesConfigurationSP settings = cfg.exportConfiguration("ANIMATION_EXPORT");
2439
2440 KisAnimationRenderingOptions encoderOptions;
2441 encoderOptions.fromProperties(settings);
2442
2443 KisAnimationRender::render(doc, viewManager(), encoderOptions);
2444}
2445
2447{
2449 KisKEditToolBar edit(factory(), this);
2450 connect(&edit, SIGNAL(newToolBarConfig()), this, SLOT(slotNewToolbarConfig()));
2451 (void) edit.exec();
2453}
2454
2456{
2457 KisApplication *kisApp = static_cast<KisApplication*>(qApp);
2458 kisApp->askResetConfig();
2459}
2460
2462{
2463 applyMainWindowSettings(d->windowStateConfig);
2464
2466 Q_UNUSED(factory);
2467
2468 // Check if there's an active view
2469 if (!d->activeView)
2470 return;
2471
2472 plugActionList("toolbarlist", d->toolbarList);
2473
2481}
2482
2484{
2485 //dbgUI <<"KisMainWindow::slotToolbarToggled" << sender()->name() <<" toggle=" << true;
2486 // The action (sender) and the toolbar have the same name
2487 KisToolBar * bar = toolBar(sender()->objectName());
2488 if (bar) {
2489 if (toggle) {
2490 bar->show();
2491 }
2492 else {
2493 bar->hide();
2494 }
2495
2496 if (d->activeView && d->activeView->document()) {
2498 }
2499 } else
2500 warnUI << "slotToolbarToggled : Toolbar " << sender()->objectName() << " not found!";
2501}
2502
2504{
2505#ifdef Q_OS_ANDROID
2506 // Full-screening on Android applies to the entire application, not this
2507 // window in particular. Qt tries to paper over that matter, but it causes
2508 // some pretty horrid flickering when the main window gets hidden. We just
2509 // talk to the Android interface directly to get around that.
2511 d->fullScreenMode->setChecked(fullScreen);
2512#else
2513 KisConfig cfg(false);
2514 cfg.setFullscreenMode(fullScreen);
2515
2516 if (fullScreen) {
2517 setWindowState(windowState() | Qt::WindowFullScreen); // set
2518 } else {
2519 setWindowState(windowState() & ~Qt::WindowFullScreen); // reset
2520 }
2521 d->fullScreenMode->setChecked(isFullScreen());
2522#endif
2523}
2524
2526{
2527 QDockWidget* dockWidget = 0;
2528 const bool showTitlebars = KisConfig(false).showDockerTitleBars();
2529
2530 if (!d->dockWidgetsMap.contains(factory->id())) {
2531 KisScopedPerformanceLogger perfLog(QStringLiteral("KisMainWindow::createDockWidget(%1)").arg(factory->id()));
2532 dockWidget = factory->createDockWidget();
2533 KAcceleratorManager::setNoAccel(dockWidget);
2534
2535 // It is quite possible that a dock factory cannot create the dock; don't
2536 // do anything in that case.
2537 if (!dockWidget) {
2538 warnKrita << "Could not create docker for" << factory->id();
2539 return 0;
2540 }
2541
2542 KoDockWidgetTitleBar *titleBar = dynamic_cast<KoDockWidgetTitleBar*>(dockWidget->titleBarWidget());
2543
2544 // Check if the dock widget is supposed to be collapsible
2545 if (!dockWidget->titleBarWidget()) {
2546 titleBar = new KoDockWidgetTitleBar(dockWidget);
2547 dockWidget->setTitleBarWidget(titleBar);
2548 }
2549 if (titleBar) {
2550 titleBar->setFont(KisUiFont::dockFont());
2551 }
2552
2553 if (dockWidget->titleBarWidget() && !dockWidget->titleBarWidget()->inherits("KisUtilityTitleBar")) {
2554 dockWidget->titleBarWidget()->setVisible(showTitlebars);
2555 }
2556
2557 dockWidget->setObjectName(factory->id());
2558 dockWidget->setParent(this);
2559
2560 if (dockWidget->widget() && dockWidget->widget()->layout())
2561 dockWidget->widget()->layout()->setContentsMargins(1, 1, 1, 1);
2562
2563 Qt::DockWidgetArea side = Qt::RightDockWidgetArea;
2564 bool visible = true;
2565
2566 switch (factory->defaultDockPosition()) {
2568 dockWidget->setFloating(true); // position nicely?
2569 break;
2571 side = Qt::TopDockWidgetArea; break;
2573 side = Qt::LeftDockWidgetArea; break;
2575 side = Qt::BottomDockWidgetArea; break;
2577 side = Qt::RightDockWidgetArea; break;
2579 default:
2580 side = Qt::RightDockWidgetArea;
2581 visible = false;
2582 }
2583
2584 KConfigGroup group = d->windowStateConfig.group("DockWidget " + factory->id());
2585 side = static_cast<Qt::DockWidgetArea>(group.readEntry("DockArea", static_cast<int>(side)));
2586 if (side == Qt::NoDockWidgetArea) side = Qt::RightDockWidgetArea;
2587
2588 addDockWidget(side, dockWidget);
2589 if (!visible) {
2590 dockWidget->hide();
2591 }
2592
2593 bool locked = group.readEntry("Locked", false);
2594 if (titleBar && locked) {
2595 titleBar->setLocked(true);
2596 }
2597 else if ( dockWidget->titleBarWidget()->inherits("KisUtilityTitleBar") && locked){
2598 KisUtilityTitleBar *utilityTitleBar = dynamic_cast<KisUtilityTitleBar*>(dockWidget->titleBarWidget());
2599 utilityTitleBar->setLocked(true);
2600 }
2601
2602 d->dockWidgetsMap.insert(factory->id(), dockWidget);
2603 }
2604 else {
2605 dockWidget = d->dockWidgetsMap[factory->id()];
2606 }
2607
2608#ifdef Q_OS_MACOS
2609 dockWidget->setAttribute(Qt::WA_MacSmallSize, true);
2610#endif
2611 dockWidget->setFont(KisUiFont::dockFont());
2612
2613 connect(dockWidget, SIGNAL(dockLocationChanged(Qt::DockWidgetArea)), this, SLOT(forceDockTabFonts()));
2614
2615 return dockWidget;
2616}
2617
2619{
2620 Q_FOREACH (QObject *child, children()) {
2621 if (child->inherits("QTabBar")) {
2622 ((QTabBar *)child)->setFont(KisUiFont::dockFont());
2623 }
2624 }
2625}
2626
2628{
2629 KisConfig cfg(true);
2630 QString themeFromConfig = cfg.widgetStyle();
2631
2632 Q_FOREACH (auto key, d->actionMap.keys()) { // find checked style to save to config
2633 if(d->actionMap.value(key)->isChecked()) {
2634 cfg.setWidgetStyle(key);
2635 qApp->setProperty(currentUnderlyingStyleNameProperty, key);
2636 qApp->setStyle(key);
2637
2638 // When switching to a style that uses system colors, reset the theme
2639#ifndef Q_OS_HAIKU
2640 QString currentStyle = qApp->style()->objectName();
2641#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
2642 if (currentStyle == "macintosh" || currentStyle == "windowsvista") {
2643 d->themeManager->setCurrentTheme("System");
2644 }
2645#else
2646 if (currentStyle == "macos" || currentStyle == "windowsvista" || currentStyle == "windows11") {
2647 d->themeManager->setCurrentTheme("System");
2648 }
2649#endif
2650#endif
2651 }
2652 }
2653}
2654
2656{
2657 return d->dockWidgetsMap.values();
2658}
2659
2660QDockWidget* KisMainWindow::dockWidget(const QString &id)
2661{
2662 if (!d->dockWidgetsMap.contains(id)) return 0;
2663 return d->dockWidgetsMap[id];
2664}
2665
2667{
2669
2670 observers.append(static_cast<KoCanvasObserverBase*>(KisPart::instance()->playbackEngine()));
2671
2672 Q_FOREACH (QDockWidget *docker, dockWidgets()) {
2673 KoCanvasObserverBase *observer = dynamic_cast<KoCanvasObserverBase*>(docker);
2674 if (observer) {
2675 observers << observer;
2676 }
2677 else {
2678 warnKrita << docker << "is not a canvas observer";
2679 }
2680 }
2681
2682 return observers;
2683}
2684
2685
2686void KisMainWindow::toggleDockersVisibility(bool visible, bool onWelcomePage)
2687{
2688 if (!visible) {
2689 d->dockerStateBeforeHiding = saveState();
2690
2691 Q_FOREACH (QObject* widget, children()) {
2692 if (widget->inherits("QDockWidget")) {
2693 QDockWidget* dw = static_cast<QDockWidget*>(widget);
2694 if (dw->isVisible() && !(onWelcomePage && dw->property("ShowOnWelcomePage").toBool())) {
2695 dw->hide();
2696 }
2697 }
2698 }
2699 }
2700 else {
2701 restoreState(d->dockerStateBeforeHiding);
2702 }
2703}
2704
2706{
2707 bool enabled = (activeKisView() != 0);
2708
2709 d->mdiCascade->setEnabled(enabled);
2710 d->mdiNextWindow->setEnabled(enabled);
2711 d->mdiPreviousWindow->setEnabled(enabled);
2712 d->mdiTile->setEnabled(enabled);
2713 d->close->setEnabled(enabled);
2714 d->closeAll->setEnabled(enabled);
2715
2716 setActiveSubWindow(d->mdiArea->activeSubWindow());
2717
2727 QMdiSubWindow *subWindow = d->mdiArea->currentSubWindow();
2728 if (subWindow) {
2729 QMenu *menu = subWindow->systemMenu();
2730 if (menu && menu->actions().size() == 8) {
2731 Q_FOREACH (QAction *action, menu->actions()) {
2732 action->setShortcut(QKeySequence());
2733
2734 }
2735 menu->actions().last()->deleteLater();
2736 }
2737 }
2738
2739 d->actionManager()->updateGUI();
2740}
2741
2743{
2747 if (viewManager() && viewManager()->selectionManager()) {
2749 }
2750
2751 KisPart *kisPart = KisPart::instance();
2753 if (!layoutManager->primaryWorkspaceFollowsFocus()) return;
2754
2755 QUuid primary = layoutManager->primaryWindowId();
2756 if (primary.isNull()) return;
2757
2758 if (d->id == primary) {
2759 if (!d->workspaceBorrowedBy.isNull()) {
2760 KisMainWindow *borrower = kisPart->windowById(d->workspaceBorrowedBy);
2761 if (!borrower) return;
2762 swapWorkspaces(this, borrower);
2763 }
2764 } else {
2765 if (d->workspaceBorrowedBy == primary) return;
2766
2767 KisMainWindow *primaryWindow = kisPart->windowById(primary);
2768 if (!primaryWindow) return;
2769 swapWorkspaces(this, primaryWindow);
2770 }
2771}
2772
2773
2775{
2776 QMenu *menu = d->windowMenu->menu();
2777 menu->clear();
2778
2779#ifndef Q_OS_ANDROID
2780 menu->addAction(d->newWindow);
2781#endif
2782 menu->addAction(d->documentMenu);
2783
2784 QMenu *docMenu = d->documentMenu->menu();
2785 docMenu->clear();
2786
2787 QFontMetrics fontMetrics = docMenu->fontMetrics();
2788 QRect geom = this->geometry();
2789 QPoint p(geom.width() / 2 + geom.left(), geom.height() / 2 + geom.top());
2790 QScreen *screen = qApp->screenAt(p);
2791 int fileStringWidth = 300;
2792 if (screen) {
2793 fileStringWidth = int(screen->availableGeometry().width() * .40f);
2794 }
2795 Q_FOREACH (QPointer<KisDocument> doc, KisPart::instance()->documents()) {
2796 if (doc) {
2797 QString title = fontMetrics.elidedText(doc->path(), Qt::ElideMiddle, fileStringWidth);
2798 if (title.isEmpty() && doc->image()) {
2799 title = doc->image()->objectName();
2800 }
2801 QAction *action = docMenu->addAction(title);
2802 action->setIcon(qApp->windowIcon());
2803 connect(action, SIGNAL(triggered()), d->documentMapper, SLOT(map()));
2804 d->documentMapper->setMapping(action, doc);
2805 }
2806 }
2807
2808 menu->addAction(d->workspaceMenu);
2809 QMenu *workspaceMenu = d->workspaceMenu->menu();
2810 workspaceMenu->clear();
2812 KisResourceIterator resourceIterator(&resourceModel);
2813 KisMainWindow *m_this = this;
2814
2815 while (resourceIterator.hasNext()) {
2816 KisResourceItemSP resource = resourceIterator.next();
2817 QAction *action = workspaceMenu->addAction(resource->name());
2818 action->setProperty("md5", QVariant::fromValue<QString>(resource->md5sum()));
2819 connect(action, SIGNAL(triggered()), this, SLOT(restoreWorkspace()));
2820 }
2821 workspaceMenu->addSeparator();
2822 connect(workspaceMenu->addAction(i18nc("@action:inmenu", "&Import Workspace...")),
2823 &QAction::triggered,
2824 this,
2825 [&]()
2826 {
2828
2829 KoFileDialog dialog(0, KoFileDialog::OpenFile, "OpenDocument");
2830 dialog.setMimeTypeFilters(mimeTypes);
2831 dialog.setCaption(i18nc("@title:window", "Choose File to Add"));
2832 QString filename = dialog.filename();
2833
2835 });
2836
2837 connect(workspaceMenu->addAction(i18nc("@action:inmenu", "&New Workspace...")),
2838 &QAction::triggered,
2839 this,
2840 [=]() {
2841 QString name;
2842 name = QInputDialog::getText(this, i18nc("@title:window", "New Workspace..."),
2843 i18nc("@label:textbox", "Name:"));
2844 if (name.isEmpty()) {
2845 return;
2846 }
2847
2849 workspace->setDockerState(m_this->saveState());
2850 workspace->setImage(layoutThumbnail());
2851 workspace->setValid(true);
2852
2853 // this line must happen before we save the workspace to resource folder or other places
2854 // because it mostly just triggers palettes to be saved into the workspace
2855 d->viewManager->canvasResourceProvider()->notifySavingWorkspace(workspace);
2856 workspace->setValid(true);
2857
2858 workspace->setFilename(name.replace(" ", "_") + workspace->defaultFileExtension());
2859 workspace->setName(name);
2860
2862 });
2863
2864 // TODO: What to do about delete?
2865 // workspaceMenu->addAction(i18nc("@action:inmenu", "&Delete Workspace..."));
2866
2867 menu->addSeparator();
2868 menu->addAction(d->close);
2869 menu->addAction(d->closeAll);
2870 if (d->mdiArea->viewMode() == QMdiArea::SubWindowView) {
2871 menu->addSeparator();
2872 menu->addAction(d->mdiTile);
2873 menu->addAction(d->mdiCascade);
2874 }
2875 menu->addSeparator();
2876 menu->addAction(d->mdiNextWindow);
2877 menu->addAction(d->mdiPreviousWindow);
2878 menu->addSeparator();
2879
2880 QList<QMdiSubWindow *> windows = d->mdiArea->subWindowList();
2881 for (int i = 0; i < windows.size(); ++i) {
2882 QPointer<KisView>child = qobject_cast<KisView*>(windows.at(i)->widget());
2883 if (child && child->document()) {
2884 QString text;
2885 if (i < 9) {
2886 text = i18n("&%1 %2", i + 1, fontMetrics.elidedText(child->document()->path(), Qt::ElideMiddle, fileStringWidth));
2887 }
2888 else {
2889 text = i18n("%1 %2", i + 1, fontMetrics.elidedText(child->document()->path(), Qt::ElideMiddle, fileStringWidth));
2890 }
2891
2892 QAction *action = menu->addAction(text);
2893 action->setIcon(qApp->windowIcon());
2894 action->setCheckable(true);
2895 action->setChecked(child == activeKisView());
2896 connect(action, SIGNAL(triggered()), d->windowMapper, SLOT(map()));
2897 d->windowMapper->setMapping(action, windows.at(i));
2898 }
2899 }
2900
2901 bool showMdiArea = windows.count( ) > 0;
2902 if (!showMdiArea) {
2903 showWelcomeScreen(true); // see workaround in function in header
2904 }
2905
2906 // enable/disable the toolbox docker if there are no documents open
2907 Q_FOREACH (QObject* widget, children()) {
2908 if (widget->inherits("QDockWidget")) {
2909 QDockWidget* dw = static_cast<QDockWidget*>(widget);
2910
2911 if ( dw->objectName() == "ToolBox") {
2912 dw->setEnabled(showMdiArea);
2913 }
2914 }
2915 }
2916}
2917
2919{
2920 bool onlyOne = false;
2921 if (d->mdiArea->subWindowList().size() == 1 && d->mdiArea->viewMode() == QMdiArea::SubWindowView) {
2922 onlyOne = true;
2923 }
2924 Q_FOREACH (QMdiSubWindow *subwin, d->mdiArea->subWindowList()) {
2925 if (onlyOne) {
2926 subwin->setWindowFlags(subwin->windowFlags() | Qt::FramelessWindowHint);
2927 subwin->showMaximized();
2928 } else {
2929 subwin->setWindowFlags((subwin->windowFlags() | Qt::FramelessWindowHint) ^ Qt::FramelessWindowHint);
2930 }
2931 }
2932}
2933
2935{
2936 if (!window) {
2938 return;
2939 }
2940 QMdiSubWindow *subwin = qobject_cast<QMdiSubWindow *>(window);
2941 //dbgKrita << "setActiveSubWindow();" << subwin << d->activeSubWindow;
2942
2943 if (subwin && subwin != d->activeSubWindow) {
2944 KisView *view = qobject_cast<KisView *>(subwin->widget());
2945 //dbgKrita << "\t" << view << activeView();
2946 if (view && view != activeView()) {
2947 setActiveView(view);
2948 }
2949 d->activeSubWindow = subwin;
2950 }
2952 d->actionManager()->updateGUI();
2953}
2954
2956{
2957 KisConfig cfg(true);
2958 QMdiArea::ViewMode viewMode = (QMdiArea::ViewMode)cfg.readEntry<int>("mdi_viewmode", (int)QMdiArea::TabbedView);
2959 d->mdiArea->setViewMode(viewMode);
2960 //Do it here to avoid the wrong icon briefly flashing
2962
2963 Q_FOREACH (QMdiSubWindow *subwin, d->mdiArea->subWindowList()) {
2964 subwin->setOption(QMdiSubWindow::RubberBandMove, cfg.readEntry<int>("mdi_rubberband", cfg.useOpenGL()));
2965 subwin->setOption(QMdiSubWindow::RubberBandResize, cfg.readEntry<int>("mdi_rubberband", cfg.useOpenGL()));
2966 if (viewMode == QMdiArea::TabbedView) {
2967 subwin->setWindowState(Qt::WindowMaximized);
2968 }
2969
2977 if (viewMode == QMdiArea::TabbedView) {
2978 Qt::WindowFlags oldFlags = subwin->windowFlags();
2979 Qt::WindowFlags flags = oldFlags;
2980
2981 flags &= ~Qt::WindowStaysOnTopHint;
2982 flags &= ~Qt::WindowStaysOnBottomHint;
2983
2984 if (flags != oldFlags) {
2985 subwin->setWindowFlags(flags);
2986 subwin->showMaximized();
2987 }
2988 }
2989 }
2990#ifdef Q_OS_MACOS
2992#endif
2993
2994 KConfigGroup group( KSharedConfig::openConfig(), "theme");
2995#ifndef Q_OS_HAIKU
2996 d->themeManager->setCurrentTheme(group.readEntry("Theme", "Krita dark"));
2997#endif
2998 d->actionManager()->updateGUI();
2999
3000 QString s = cfg.getMDIBackgroundColor();
3002 QBrush brush(c.toQColor());
3003 d->mdiArea->setBackground(brush);
3004
3005 QString backgroundImage = cfg.getMDIBackgroundImage();
3006 if (backgroundImage != "") {
3007 QImage image(backgroundImage);
3008 QBrush brush(image);
3009 d->mdiArea->setBackground(brush);
3010 }
3011
3012 d->mdiArea->update();
3013
3014 qApp->setFont(KisUiFont::normalFont());
3015
3016 Q_FOREACH (QObject* widget, children()) {
3017 if (widget->inherits("QDockWidget")) {
3018 QDockWidget* dw = static_cast<QDockWidget*>(widget);
3019 dw->setFont(KisUiFont::dockFont());
3020 }
3021 }
3022}
3023
3024KisView* KisMainWindow::newView(QObject *document, QMdiSubWindow *subWindow)
3025{
3026 KisDocument *doc = qobject_cast<KisDocument*>(document);
3027 KisView *view = addViewAndNotifyLoadingCompleted(doc, subWindow);
3028 d->actionManager()->updateGUI();
3029
3030 return view;
3031}
3032
3034{
3035#ifdef Q_OS_ANDROID
3036 // Check if current mainwindow exists, just to be sure.
3037 if (KisPart::instance()->currentMainwindow()) {
3038 QMessageBox::warning(this, i18nc("@title:window", "Krita"),
3039 "Creating a New Main Window is unsupported on Android");
3040 return;
3041 }
3042#endif
3044 mainWindow->initializeGeometry();
3045 mainWindow->show();
3046}
3047
3049{
3050 if (d->mdiArea->currentSubWindow()) {
3051 d->mdiArea->currentSubWindow()->close();
3052 d->actionManager()->updateGUI();
3053 }
3054}
3055
3057{
3058 // print error if the lcms engine is not available
3059 if (!KoColorSpaceEngineRegistry::instance()->contains("icc")) {
3060 // need to wait 1 event since exiting here would not work.
3061 m_errorMessage = i18n("The Krita LittleCMS color management plugin is not installed. Krita will quit now.");
3062 m_dieOnError = true;
3063 QTimer::singleShot(0, this, SLOT(showErrorAndDie()));
3064 return;
3065 }
3066
3068
3069 // window is created signal (used in Python)
3070 // there must be some asynchronous things happening in the constructor, because the window cannot
3071 // be referenced until after this timeout is done
3073}
3074
3076{
3077 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Installation error"), m_errorMessage);
3078 if (m_dieOnError) {
3079 exit(10);
3080 }
3081}
3082
3084{
3085 KisAboutApplication dlg(this);
3086 dlg.exec();
3087}
3088
3090{
3091 if (!d->mdiArea) return 0;
3092 QMdiSubWindow *activeSubWindow = d->mdiArea->activeSubWindow();
3093 //dbgKrita << "activeKisView" << activeSubWindow;
3094 if (!activeSubWindow) return 0;
3095 return qobject_cast<KisView*>(activeSubWindow->widget());
3096}
3097
3099{
3100 KIS_ASSERT_RECOVER_NOOP(controller == d->viewManager->toolManager()->activeCanvasController());
3101 bool isOurOwnView = false;
3102
3103 Q_FOREACH (QPointer<KisView> view, KisPart::instance()->views()) {
3104 if (view && view->canvasController() == controller) {
3105 isOurOwnView = view->mainWindow() == this;
3106 }
3107 }
3108
3109 if (!isOurOwnView) return;
3110
3111 Q_FOREACH (QWidget *w, optionWidgetList) {
3112#ifdef Q_OS_MACOS
3113 w->setAttribute(Qt::WA_MacSmallSize, true);
3114#endif
3115 w->setFont(KisUiFont::dockFont());
3116 }
3117
3118 if (d->toolOptionsDocker) {
3119 d->toolOptionsDocker->setOptionWidgets(optionWidgetList);
3120 }
3121 else {
3122 d->viewManager->paintOpBox()->newOptionWidgets(optionWidgetList);
3123 }
3124}
3125
3127{
3128 KisActionManager *actionManager = d->actionManager();
3129
3130
3131
3136 d->fullScreenMode = actionManager->createStandardAction(KStandardAction::FullScreen, this, SLOT(viewFullscreen(bool)));
3137
3138 d->recentFiles = KStandardAction::openRecent(this, SLOT(slotFileOpenRecent(QUrl)), actionCollection());
3139
3141 d->saveAction->setActivationFlags(KisAction::IMAGE_IS_WRITABLE);
3142
3144 d->saveActionAs->setActivationFlags(KisAction::ACTIVE_IMAGE);
3145
3147 d->undo->setActivationFlags(KisAction::ACTIVE_IMAGE);
3148
3150 d->redo->setActivationFlags(KisAction::ACTIVE_IMAGE);
3151
3152 d->undoActionsUpdateManager.reset(new KisUndoActionsUpdateManager(d->undo, d->redo));
3153 d->undoActionsUpdateManager->setCurrentDocument(d->activeView ? d->activeView->document() : 0);
3154
3155 d->importAnimation = actionManager->createAction("file_import_animation");
3156 connect(d->importAnimation, SIGNAL(triggered()), this, SLOT(importAnimation()));
3157
3158 // Importing video requires ffmpeg, which is not available on Android.
3159#ifndef Q_OS_ANDROID
3160 d->importVideoAnimation = actionManager->createAction("file_import_video_animation");
3161 connect(d->importVideoAnimation, SIGNAL(triggered()), this, SLOT(importVideoAnimation()));
3162#endif
3163
3164 d->renderAnimation = actionManager->createAction("render_animation");
3165 d->renderAnimation->setActivationFlags(KisAction::IMAGE_HAS_ANIMATION);
3166 connect( d->renderAnimation, SIGNAL(triggered()), this, SLOT(renderAnimation()));
3167
3168 d->renderAnimationAgain = actionManager->createAction("render_animation_again");
3169 d->renderAnimationAgain->setActivationFlags(KisAction::IMAGE_HAS_ANIMATION);
3170 connect( d->renderAnimationAgain, SIGNAL(triggered()), this, SLOT(renderAnimationAgain()));
3171
3172 d->closeAll = actionManager->createAction("file_close_all");
3173 connect(d->closeAll, SIGNAL(triggered()), this, SLOT(slotFileCloseAll()));
3174
3175 d->importFile = actionManager->createAction("file_import_file");
3176 d->importFile->setActivationFlags(KisAction::IMAGE_IS_WRITABLE);
3177 connect(d->importFile, SIGNAL(triggered(bool)), this, SLOT(slotImportFile()));
3178
3179 d->exportFile = actionManager->createAction("file_export_file");
3180 connect(d->exportFile, SIGNAL(triggered(bool)), this, SLOT(slotExportFile()));
3181
3182 d->exportFileAdvance = actionManager->createAction("file_export_advanced");
3183 connect(d->exportFileAdvance, SIGNAL(triggered(bool)), this, SLOT(slotExportAdvance()));
3184
3185 /* The following entry opens the document information dialog. Since the action is named so it
3186 intends to show data this entry should not have a trailing ellipses (...). */
3187 d->showDocumentInfo = actionManager->createAction("file_documentinfo");
3188 connect(d->showDocumentInfo, SIGNAL(triggered(bool)), this, SLOT(slotDocumentInfo()));
3189#ifndef Q_OS_HAIKU
3190 d->themeManager->setThemeMenuAction(new KActionMenu(i18nc("@action:inmenu", "&Themes"), this));
3191 d->themeManager->registerThemeActions(actionCollection());
3192 connect(d->themeManager, SIGNAL(signalThemeChanged()), this, SLOT(slotThemeChanged()), Qt::QueuedConnection);
3193 connect(this, SIGNAL(themeChanged()), d->welcomePage, SLOT(slotUpdateThemeColors()), Qt::UniqueConnection);
3194#endif
3195 d->toggleDockers = actionManager->createAction("view_toggledockers");
3196
3197
3198 KisConfig(true).showDockers(true);
3199 d->toggleDockers->setChecked(true);
3200 connect(d->toggleDockers, SIGNAL(toggled(bool)), SLOT(toggleDockersVisibility(bool)));
3201
3202 d->resetConfigurations = actionManager->createAction("reset_configurations");
3203 connect(d->resetConfigurations, SIGNAL(triggered()), this, SLOT(slotResetConfigurations()));
3204
3205#ifndef Q_OS_ANDROID
3206 d->toggleDetachCanvas = actionManager->createAction("view_detached_canvas");
3207 d->toggleDetachCanvas->setChecked(false);
3208 connect(d->toggleDetachCanvas, SIGNAL(toggled(bool)), SLOT(setCanvasDetached(bool)));
3209#endif
3210 setCanvasDetached(false);
3211
3212 d->toggleDockerTitleBars = actionManager->createAction("view_toggledockertitlebars");
3213 d->toggleDockerTitleBars->setChecked(KisConfig(false).showDockerTitleBars());
3214 connect(d->toggleDockerTitleBars, SIGNAL(toggled(bool)), SLOT(showDockerTitleBars(bool)));
3215
3216 actionCollection()->addAction("settings_dockers_menu", d->dockWidgetMenu);
3217 actionCollection()->addAction("window", d->windowMenu);
3218
3219 actionCollection()->addAction("style_menu", d->styleMenu); // for widget styles: breeze, fusion, etc
3220
3221 d->mdiCascade = actionManager->createAction("windows_cascade");
3222 connect(d->mdiCascade, SIGNAL(triggered()), d->mdiArea, SLOT(cascadeSubWindows()));
3223
3224 d->mdiTile = actionManager->createAction("windows_tile");
3225 connect(d->mdiTile, SIGNAL(triggered()), d->mdiArea, SLOT(tileSubWindows()));
3226
3227 d->mdiNextWindow = actionManager->createAction("windows_next");
3228 connect(d->mdiNextWindow, SIGNAL(triggered()), d->mdiArea, SLOT(activateNextSubWindow()));
3229
3230 d->mdiPreviousWindow = actionManager->createAction("windows_previous");
3231 connect(d->mdiPreviousWindow, SIGNAL(triggered()), d->mdiArea, SLOT(activatePreviousSubWindow()));
3232
3233#ifdef Q_OS_ANDROID
3234 d->showDonationManagementDialog = actionManager->createAction("manage_donations");
3235 connect(d->showDonationManagementDialog,
3236 &QAction::triggered,
3237 this,
3238 &KisMainWindow::slotShowDonationManagementDialog);
3239
3241 if (androidDonations) {
3242 d->manageSubscriptions = actionManager->createAction("manage_subscriptions");
3243 connect(d->manageSubscriptions,
3244 &QAction::triggered,
3245 androidDonations,
3247 connect(androidDonations,
3249 this,
3250 &KisMainWindow::slotShowDonationManagementDialog,
3251 Qt::QueuedConnection);
3252 }
3253#if KRITA_QT_HAS_ANDROID_QPLATFORMSCREEN_DENSITY_ADJUSTMENT
3255 if (androidScaling && androidScaling->isSupported()) {
3256 d->changeInterfaceScale = actionManager->createAction("change_interface_scale");
3257 connect(d->changeInterfaceScale, &QAction::triggered, this, &KisMainWindow::slotChangeInterfaceScale);
3258 }
3259#endif
3260#else
3261 d->newWindow = actionManager->createAction("view_newwindow");
3262 connect(d->newWindow, SIGNAL(triggered(bool)), this, SLOT(newWindow()));
3263#endif
3264
3266
3267 d->showSessionManager = actionManager->createAction("file_sessions");
3268 connect(d->showSessionManager, SIGNAL(triggered(bool)), this, SLOT(slotShowSessionManager()));
3269
3270 d->commandBarAction = actionManager->createAction("command_bar_open");
3271 connect(d->commandBarAction, SIGNAL(triggered(bool)), this, SLOT(openCommandBar()));
3272
3274
3275 for (int i = 0; i < 2; i++) {
3276 d->expandingSpacers[i] = new KisAction(i18n("Expanding Spacer"));
3277 d->expandingSpacers[i]->setDefaultWidget(new QWidget(this));
3278 d->expandingSpacers[i]->defaultWidget()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
3279 actionManager->addAction(QString("expanding_spacer_%1").arg(i), d->expandingSpacers[i]);
3280 }
3281
3282 {
3283 using namespace KisWidgetConnectionUtils;
3284
3285 QAction *action = actionManager->createAction("lock_toolbars");
3286 connectControl(action, KisToolBar::toolBarStateModel(), "toolBarsLocked");
3287 }
3288}
3289
3291{
3292 Q_FOREACH (KisToolBar *toolBar, toolBars()) {
3293 toolBar->layout()->setSpacing(4);
3294 toolBar->setStyleSheet("QToolBar { border: none }"); // has a border in "Fusion" style that people don't like
3295
3296 // Hide text for buttons with an icon in the toolbar
3297 Q_FOREACH (QAction *ac, toolBar->actions()){
3298 if (ac->icon().pixmap(QSize(1,1)).isNull() == false){
3299 ac->setPriority(QAction::LowPriority);
3300 } else {
3301 ac->setIcon(QIcon());
3302 }
3303 }
3304 }
3305}
3306
3308{
3309 // if the user didn's specify the geometry on the command line (does anyone do that still?),
3310 // we first figure out some good default size and restore the x,y position. See bug 285804Z.
3311 KConfigGroup cfg = d->windowStateConfig;
3312 QByteArray geom = QByteArray::fromBase64(cfg.readEntry("ko_geometry", QByteArray()));
3313 if (!restoreGeometry(geom)) {
3314 QRect desk = this->screen()->availableGeometry();
3315
3316 quint32 x = desk.x();
3317 quint32 y = desk.y();
3318 quint32 w = 0;
3319 quint32 h = 0;
3320
3321 // Default size -- maximize on small screens, something useful on big screens
3322 const int deskWidth = desk.width();
3323 if (deskWidth > 1024) {
3324 // a nice width, and slightly less than total available
3325 // height to compensate for the window decs
3326 w = (deskWidth / 3) * 2;
3327 h = (desk.height() / 3) * 2;
3328 }
3329 else {
3330 w = desk.width();
3331 h = desk.height();
3332 }
3333
3334 x += (desk.width() - w) / 2;
3335 y += (desk.height() - h) / 2;
3336
3337 move(x,y);
3338 setGeometry(geometry().x(), geometry().y(), w, h);
3339 }
3340#ifdef Q_OS_ANDROID
3341 // We handle full-screening differently on Android, see viewFullScreen.
3342 bool fullScreen = KisAndroidUtils::isInFullScreen();
3343#else
3344 bool fullScreen = isFullScreen();
3345#endif
3346 d->fullScreenMode->setChecked(fullScreen);
3347}
3348
3350{
3351 QDesktopServices::openUrl(QUrl("https://docs.krita.org"));
3352}
3353
3355{
3356 Q_FOREACH (QDockWidget *dock, dockWidgets()) {
3357 if (dock->titleBarWidget() && !dock->titleBarWidget()->inherits("KisUtilityTitleBar")) {
3358 dock->titleBarWidget()->setVisible(show || dock->isFloating());
3359 }
3360 }
3361
3362 KisConfig cfg(true);
3363 cfg.setShowDockerTitleBars(show);
3364}
3365
3367{
3368 if (finished) {
3370 }
3371}
3372
3374{
3375 QScreen *screen = QGuiApplication::primaryScreen();
3376
3377 for (QWindow* window: QGuiApplication::topLevelWindows()) {
3378 // Android: we shouldn't transform Window managers independent of its child
3379 if ((window->type() == Qt::Popup)
3380 && (window->flags() & Qt::FramelessWindowHint) == 0
3381 && (window->geometry().topLeft() != QPoint(0, 0))) {
3382 // We are using reversed values. Because geometry returned is not the updated
3383 // one, but the previous one.
3384 int screenHeight = screen->geometry().width();
3385 int screenWidth = screen->geometry().height();
3386
3387 // scaling
3388 int new_x = (window->position().x() * screenWidth) / screenHeight;
3389 int new_y = (window->position().y() * screenHeight) / screenWidth;
3390
3391 // window width or height shouldn't change
3392 int winWidth = window->geometry().width();
3393 int winHeight = window->geometry().height();
3394
3395 // Try best to not let the window go beyond screen.
3396 if (new_x > screenWidth - winWidth) {
3397 new_x = screenWidth - winWidth;
3398 if (new_x < 0)
3399 new_x = 0;
3400 }
3401 if (new_y > screenHeight - winHeight) {
3402 new_y = screenHeight - winHeight;
3403 if (new_y < 0)
3404 new_y = 0;
3405 }
3406
3407 window->setPosition(QPoint(new_x, new_y));
3408 }
3409 }
3410}
3411
3422
3428
3429// One action has only one icon override, local XML contains ActionIconOverrides like so:
3430// <ActionIconOverrides>
3431// <Action name="erase_action" icon="wheel-sectors"/>
3432// <Action name="about_krita" icon="application-exit"/>
3433// </ActionIconOverrides>
3434// This function will rerender the actions with icons in UI (toolbars, shortcuts options etc.)
3436{
3437 QString xmlPath = KoResourcePaths::locateLocal("data", "krita5.xmlgui");
3438 QFile file(xmlPath);
3439 if (!file.exists()) {
3440 return;
3441 }
3442
3443 QDomDocument doc;
3444 if (!file.open(QIODevice::ReadOnly) || !doc.setContent(&file)) {
3445 return;
3446 }
3447
3448 QDomNodeList overridesList = doc.elementsByTagName(QStringLiteral("ActionIconOverrides"));
3449 if (!overridesList.isEmpty()) {
3450 QDomElement overridesElement = overridesList.at(0).toElement();
3451 QDomNodeList actions = overridesElement.elementsByTagName(QStringLiteral("Action"));
3452 for (int i = 0; i < actions.count(); ++i) {
3453 QDomElement actionElement = actions.at(i).toElement();
3454 QString name = actionElement.attribute(QStringLiteral("name"));
3455 QString icon = actionElement.attribute(QStringLiteral("icon"));
3456 if (!name.isEmpty() && !icon.isEmpty()) {
3457 QAction *qa = actionCollection()->action(name);
3458 if (qa) {
3459 qa->setIcon(KisIconUtils::loadIcon(icon));
3460 }
3461 }
3462 }
3463 }
3464}
3465
3467{
3468 // Add all actions with a menu property to the main window
3469 KisActionManager::synchronizeDynamicActions(this->actionCollection()->actions(), this->menuBar()->actions());
3470}
3471
3472#include <moc_KisMainWindow.cpp>
const Params2D p
qreal v
#define KIS_MIME_TYPE
Definition KisDocument.h:57
KisMagneticGraph::vertex_descriptor target(typename KisMagneticGraph::edge_descriptor e, KisMagneticGraph g)
QList< QString > QStringList
Recent files action.
KDE top level main window with predefined action layout
QAction * toolBarMenuAction()
void setStandardToolBarMenuEnabled(bool enable)
void applyMainWindowSettings(const KConfigGroup &config) override
bool event(QEvent *event) override
virtual KisKXMLGUIFactory * guiFactory()
bool isHelpMenuEnabled() const
A KisActionManager class keeps track of KisActions. These actions are always associated with the GUI....
KisAction * createAction(const QString &name)
static void synchronizeDynamicActions(QList< QAction * > newActions, const QList< QAction * > &menuBarActions)
void addAction(const QString &name, KisAction *action)
KisAction * createStandardAction(KStandardAction::StandardAction, const QObject *receiver, const char *member)
@ ACTIVE_IMAGE
Activate if there is at least one image.
Definition kis_action.h:43
@ IMAGE_IS_WRITABLE
Activate KisDocument::isReadWrite() is active.
Definition kis_action.h:62
@ IMAGE_HAS_ANIMATION
Activate if the image has an animation.
Definition kis_action.h:58
static KisAndroidDonations * instance()
void sigShowDonationManagementDialogRequested()
bool isShowDonationManagementDialogPending() const
void sigInterfaceScaleChanged()
static KisAndroidScaling * instance()
bool isSupported() const
void fromProperties(KisPropertiesConfigurationSP config)
Base class for the Krita app.
void setFavoriteResourceManager(KisFavoriteResourceManager *favoriteResourceManager)
static KisConfigNotifier * instance()
QString widgetStyle(bool defaultValue=false)
void setFullscreenMode(const bool value) const
void setWidgetStyle(QString name)
void writeEntry(const QString &name, const T &value)
Definition kis_config.h:904
QString getMDIBackgroundColor(bool defaultValue=false) const
QString getMDIBackgroundImage(bool defaultValue=false) const
bool showDockerTitleBars(bool defaultValue=false) const
bool effectiveShouldUseNativeSurfaceForCanvas(bool osManagedSurfacePresent) const
QString exportMimeType(bool defaultValue) const
void setShowDockerTitleBars(const bool value) const
bool toolOptionsInDocker(bool defaultValue=false) const
T readEntry(const QString &name, const T &defaultValue=T())
Definition kis_config.h:914
bool showDockers(bool defaultValue=false) const
bool useOpenGL(bool defaultValue=false) const
void setFileBatchMode(const bool batchMode)
KisImageSP image
void setPath(const QString &path)
bool importDocument(const QString &path)
bool openPath(const QString &path, OpenFlags flags=None)
openPath Open a Path
static KisImageConfigNotifier * instance()
KisGroupLayerSP rootLayer() const
KisImageAnimationInterface * animationInterface() const
static QStringList supportedMimeTypes(Direction direction)
void removeTrackedCanvas(KisCanvas2 *canvas)
void addTrackedCanvas(KisCanvas2 *canvas)
A container for a set of QAction objects.
void setComponentDisplayName(const QString &displayName)
Q_INVOKABLE QAction * addAction(const QString &name, QAction *action)
QAction * action(int index) const
void addAssociatedWidget(QWidget *widget)
A dialog used to customize or configure toolbars.
Standard KDE help menu with dialog boxes.
Definition khelpmenu.h:106
void setAutoSaveSettings(const QString &groupName=QLatin1String("MainWindow"), bool saveWindowSize=true)
void resetAutoSaveSettings()
void saveMainWindowSettings(KConfigGroup &config)
KisToolBar * toolBar(const QString &name=QString())
void closeEvent(QCloseEvent *) override
QList< KisToolBar * > toolBars() const
void setLocalXMLFile(const QString &file)
QAction * action(const char *name) const
KisKXMLGUIFactory * factory() const
void setXMLFile(const QString &file, bool merge=false, bool setXMLDoc=true)
void plugActionList(const QString &name, const QList< QAction * > &actionList)
virtual KisKActionCollection * actionCollection() const
void addClient(KisKXMLGUIClient *client)
QList< KisKXMLGUIClient * > clients() const
Main window for Krita.
QMenu * createPopupMenu() override
KisActionManager * actionManager()
bool installBundle(const QString &fileName) const
Copy the given file into the bundle directory.
QPointer< KisView > activeKisView()
virtual void showAboutApplication()
showAboutApplication show the about box
QScopedPointer< KisUndoActionsUpdateManager > undoActionsUpdateManager
QDockWidget * dockWidget(const QString &id)
void applyActionIconOverridesFromLocalXML()
KisMainWindow(QUuid id=QUuid())
void setCanvasDetached(bool detached)
void guiLoadingFinished()
void dragLeaveEvent(QDragLeaveEvent *event) override
QImage layoutThumbnail()
layoutThumbnail
QTabBar * findTabBarHACK()
KisAction * newWindow
KisSignalAutoConnectionsStore activeViewConnections
QStringList showOpenFileDialog(bool isImporting)
void slotUpdateWidgetStyle()
bool checkPaintOpAvailable()
void dragMove(QDragMoveEvent *event)
void showWelcomeScreen(bool show)
void setActiveSubWindow(QWidget *window)
bool windowsLayoutSavingAllowed() const override
void slotLoadCanceled(const QString &)
void slotConfigureToolbars()
QList< KoCanvasObserverBase * > canvasObservers() const override
void slotStoragesWarning(const QString &location=QString())
void slotNewToolbarConfig()
void themeChanged()
This signal is emitted when the color theme changes.
QMdiSubWindow * activeSubWindow
bool restoreWorkspaceState(const QByteArray &state)
KConfigGroup windowStateConfig
KisAction * renderAnimation
void updateSubwindowFlags()
void slotShowSessionManager()
void slotResetConfigurations()
void showErrorAndDie()
Quits Krita with error message from m_errorMessage.
QMap< QString, QAction * > actionMap
void slotUpdateReadWriteMode(bool readWrite)
bool checkActiveBundlesAvailable()
checkActiveStorages checks whether there is at least one bundle available and at least one paintop pr...
KisView * newView(QObject *document, QMdiSubWindow *subWindow=0)
bool openDocument(const QString &path, OpenFlags flags)
void toggleDockersVisibility(bool visible, bool onWelcomePage=false)
void showDocument(KisDocument *document)
void slotXmlGuiMakingChanges(bool finished)
void newOptionWidgets(KoCanvasController *controller, const QList< QPointer< QWidget > > &optionWidgetList)
KisView * addViewAndNotifyLoadingCompleted(KisDocument *document, QMdiSubWindow *subWindow=0)
QList< QDockWidget * > dockWidgets() const
Return the list of dock widgets belonging to this main window.
bool openDocumentInternal(const QString &path, KisMainWindow::OpenFlags f=KisMainWindow::OpenFlags())
QDockWidget * createDockWidget(KoDockFactoryBase *factory)
void loadCompleted()
void resizeEvent(QResizeEvent *e) override
KisAction * renderAnimationAgain
virtual void showView(KisView *view, QMdiSubWindow *subWindow=0)
showView shows the given view, in subWindow if not null, in a new tab otherwise.
void addView(KisView *view, QMdiSubWindow *subWindow=0)
void setMainWindowLayoutForCurrentMainWidget(int widgetIndex, bool widgetIndexChanged)
QPointer< KisView > activeView
void slotUpdateSaveActionTitle(const QString &documentPath)
Private *const d
void slotPreferences()
slotPreferences open the preferences dialog
void slotFileOpenRecent(const QUrl &)
QString lastExportLocation
bool saveDocument(KisDocument *document, bool saveas, bool isExporting, bool isAdvancedExporting=false)
QByteArray lastExportedFormat
void showEvent(QShowEvent *event) override
KisViewManager * viewManager
bool hackIsSaving() const
QString m_errorMessage
void slotFileOpen(bool isImporting=false)
KisAction * undo
QMap< QString, QDockWidget * > dockWidgetsMap
void saveWindowState(bool restoreNormalState=false)
bool canvasDetached() const
void slotChangeInterfaceScale()
KActionMenu * workspaceMenu
void viewFullscreen(bool fullScreen)
void documentSaved()
QList< QAction * > toolbarList
void restoringDone()
This signal is emitted right after the docker states have been successfully restored from config.
void activeViewChanged()
emitted when the current view has changed
KisCanvasWindow * canvasWindow
void notifyChildViewDestroyed(KisView *view)
void synchronizeDynamicActions()
void adjustLayoutForWelcomePage()
int viewCount() const
void setActiveView(KisView *view)
Set the active view, this will update the undo/redo actions.
void showDockerTitleBars(bool show)
static void swapWorkspaces(KisMainWindow *a, KisMainWindow *b)
KisAction * importAnimation
QByteArray dockerStateBeforeHiding
void removeRecentFile(QString url)
void slotSaveCanceled(const QString &)
KisAction * importVideoAnimation
Private(KisMainWindow *parent, QUuid id)
KisAction * redo
void switchTab(int index)
QByteArray borrowWorkspace(KisMainWindow *borrower)
~KisMainWindow() override
QScopedPointer< KisSignalCompressorWithParam< int > > tabSwitchCompressor
void dragMoveEvent(QDragMoveEvent *event) override
void slotToolbarToggled(bool toggle)
void closeEvent(QCloseEvent *e) override
KoCanvasResourceProvider * resourceManager() const
The KisMainwindowObserver class is an interface for dock widgets that want to keep track of the main ...
virtual void setViewManager(KisViewManager *kisview)=0
static QStringList suffixesForMimeType(const QString &mimeType)
static QString mimeTypeForFile(const QString &file, bool checkExistingFiles=true)
Find the mimetype for the given filename. The filename must include a suffix.
bool closeSession(bool keepWindows=false)
Definition KisPart.cpp:381
void removeMainWindow(KisMainWindow *mainWindow)
Definition KisPart.cpp:439
KisView * createView(KisDocument *document, KisViewManager *viewManager, QWidget *parent)
Definition KisPart.cpp:276
static KisPart * instance()
Definition KisPart.cpp:131
void addDocument(KisDocument *document, bool notify=true)
Definition KisPart.cpp:210
void queueAddRecentURLToAllMainWindowsOnFileSaved(QUrl url, QUrl oldUrl=QUrl())
Definition KisPart.cpp:605
void sigMainWindowCreated()
KisMainWindow * windowById(QUuid id) const
Definition KisPart.cpp:479
KisDocument * createDocument() const
Definition KisPart.cpp:229
void showSessionManager()
Definition KisPart.cpp:625
void notifyMainWindowIsBeingCreated(KisMainWindow *mainWindow)
notifyMainWindowIsBeingCreated emits the sigMainWindowCreated signal
Definition KisPart.cpp:270
KisMainWindow * createMainWindow(QUuid id=QUuid())
Definition KisPart.cpp:259
static KisPlatformPluginInterfaceFactory * instance()
static KisRecentDocumentsModelWrapper * instance()
void remove(const QUrl &url)
static KisRecentFilesManager * instance()
The KisResourceIterator class provides an iterator for a KisResourceModel.
const KisResourceItemSP next()
static KisResourceLoaderRegistry * instance()
QStringList mimeTypes(const QString &resourceType) const
The KisResourceModel class provides the main access to resources. It is possible to filter the resour...
static KisResourceServerProvider * instance()
KoResourceServer< KisWorkspaceResource > * workspaceServer()
KisPaintOpPresetResourceServer * paintOpPresetServer()
static QString storageTypeToUntranslatedString(StorageType storageType)
static KoResourceSP importResourceFileWithUserInput(QWidget *widgetParent, QString storageLocation, QString resourceType, QString resourceFilepath)
static bool addResourceWithUserInput(QWidget *widgetParent, KoResourceSP resource, QString storageLocation="")
The KisSignalMapper class bundles signals from identifiable senders.
@ ByStorageType
Pass a string list of storage types.
void setFilter(FilterType filterType, QVariant filter)
static KisStorageModel * instance()
Floatable toolbar with auto resize.
Definition ktoolbar.h:47
static KisToolBarStateModel * toolBarStateModel()
static void log(const QString &message)
Logs with date/time.
A special utility titlebar with a title and controls, as well as a central area for adding frequently...
KisDocument * document() const
void setCurrentView(KisView *view)
KisInputManager * inputManager() const
Filters events and sends them to canvas actions.
QPointer< KoUpdater > createUnthreadedUpdater(const QString &name)
create a new progress updater
KisSelectionManager * selectionManager()
KisImageWSP image() const
Return the image this view is displaying.
KisCanvas2 * canvasBase() const
Definition KisView.cpp:434
void slotThemeChanged(QPalette pal)
Definition KisView.cpp:1232
QString getTitle()
Definition KisView.cpp:1249
void setSubWindow(QMdiSubWindow *subWindow)
Definition KisView.cpp:1100
QPointer< KisDocument > document
Definition KisView.cpp:121
void slotLoadingFinished()
Definition KisView.cpp:1413
void setViewManager(KisViewManager *view)
Definition KisView.cpp:337
A widget for displaying if no documents are open. This will display in the MDI area.
static KisWindowLayoutManager * instance()
void activeDocumentChanged(KisDocument *document)
Resource for storing of workspaces.
void setObservedCanvas(KoCanvasBase *canvas)
static KoColorSpaceEngineRegistry * instance()
static KoColor fromXML(const QDomElement &elt, const QString &channelDepthId)
Definition KoColor.cpp:350
void toQColor(QColor *c) const
a convenience method for the above.
Definition KoColor.cpp:198
@ DockRight
Right of the centra widget.
@ DockTop
Above the central widget.
@ DockBottom
Below the central widget.
@ DockMinimized
Not docked, but reachable via the menu.
@ DockLeft
Left of the centra widget.
@ DockTornOff
Floating as its own top level window.
static KoDockRegistry * instance()
QList< KoDockFactoryBase * > sortedDockWidgetFactories()
A custom title bar for dock widgets.
The dialog that shows information about the document.
The class containing all meta information about a document.
void load(const QString &serviceType, const PluginsConfig &config=PluginsConfig(), QObject *owner=0, bool cache=true)
static KoPluginLoader * instance()
static QString locateLocal(const QString &type, const QString &filename, bool createDir=false)
static QString getAppDataLocation()
int resourceCount() const
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...
QList< QAction * > createActions(KisKActionCollection *actionCollection, KoToolManager *toolManager)
static KoToolRegistry * instance()
ScopedWidgetDisabler(QWidget *widget_)
bool eventFilter(QObject *watched, QEvent *event) override
TabBarFilter(QMdiArea *mdi)
DockPosition defaultDockPosition() const override
QDockWidget * createDockWidget() override
QString id() const override
#define KIS_ASSERT_RECOVER_NOOP(cond)
Definition kis_assert.h:97
#define KIS_SAFE_ASSERT_RECOVER_NOOP(cond)
Definition kis_assert.h:130
#define dbgKrita
Definition kis_debug.h:49
#define warnKrita
Definition kis_debug.h:94
#define dbgUI
Definition kis_debug.h:56
#define dbgFile
Definition kis_debug.h:57
#define warnUI
Definition kis_debug.h:101
constexpr const char * currentUnderlyingStyleNameProperty
Definition kis_global.h:116
typedef void(QOPENGLF_APIENTRYP PFNGLINVALIDATEBUFFERDATAPROC)(GLuint buffer)
KRecentFilesAction * openRecent(const QObject *recvr, const char *slot, QObject *parent)
const char * name(StandardAction id)
KRITAUI_EXPORT void show()
void setFullScreen(bool fullScreen)
KRITAUI_EXPORT bool render(KisDocument *doc, KisViewManager *viewManager, KisAnimationRenderingOptions encoderOptions)
int size(const Forest< T > &forest)
Definition KisForest.h:1232
QIcon loadIcon(const QString &name)
void updateIconCommon(QObject *object)
void updateIcon(QAbstractButton *button)
QFont normalFont()
Gets a font for normal UI widgets to use.
Definition KisUiFont.cpp:81
QFont dockFont()
Gets a font with a smallish font size for dock widgets to use.
Definition KisUiFont.cpp:98
const QString Workspaces
virtual void updateSettings()
const KoColorSpace * colorSpace(const QString &colorModelId, const QString &colorDepthId, const KoColorProfile *profile)
static KoColorSpaceRegistry * instance()
QList< int > renderedFrameTargetTimes