KisViewManager.cpp 44 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/*
 *  This file is part of KimageShop^WKrayon^WKrita
 *
 *  Copyright (c) 1999 Matthias Elter  <me@kde.org>
 *                1999 Michael Koch    <koch@kde.org>
 *                1999 Carsten Pfeiffer <pfeiffer@kde.org>
 *                2002 Patrick Julien <freak@codepimps.org>
 *                2003-2011 Boudewijn Rempt <boud@valdyas.org>
 *                2004 Clarence Dang <dang@kde.org>
 *                2011 José Luis Vergara <pentalis@gmail.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <stdio.h>

#include "KisViewManager.h"
#include <QPrinter>

Halla Rempt's avatar
Halla Rempt committed
32 33 34 35
#include <QAction>
#include <QApplication>
#include <QBuffer>
#include <QByteArray>
36 37 38 39
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QGridLayout>
#include <QMainWindow>
Halla Rempt's avatar
Halla Rempt committed
40 41
#include <QMenu>
#include <QMenuBar>
Halla Rempt's avatar
Halla Rempt committed
42
#include <QMessageBox>
Halla Rempt's avatar
Halla Rempt committed
43
#include <QObject>
44
#include <QPoint>
Halla Rempt's avatar
Halla Rempt committed
45 46 47 48 49
#include <QPrintDialog>
#include <QRect>
#include <QScrollBar>
#include <QStatusBar>
#include <QToolBar>
Halla Rempt's avatar
Halla Rempt committed
50
#include <QUrl>
Halla Rempt's avatar
Halla Rempt committed
51 52
#include <QWidget>

53
#include <kactioncollection.h>
54
#include <klocalizedstring.h>
55
#include <KoResourcePaths.h>
56
#include <kselectaction.h>
57 58 59 60 61 62 63 64 65 66 67 68 69

#include <KoCanvasController.h>
#include <KoCompositeOp.h>
#include <KoDockRegistry.h>
#include <KoDockWidgetTitleBar.h>
#include <KoProperties.h>
#include <KoResourceItemChooserSync.h>
#include <KoSelection.h>
#include <KoStore.h>
#include <KoToolManager.h>
#include <KoToolRegistry.h>
#include <KoViewConverter.h>
#include <KoZoomHandler.h>
70
#include <KoPluginLoader.h>
71
#include <KoDocumentInfo.h>
72
#include <KoGlobal.h>
73
#include <KoColorSpaceRegistry.h>
74

75
#include "input/kis_input_manager.h"
76 77 78 79 80 81
#include "canvas/kis_canvas2.h"
#include "canvas/kis_canvas_controller.h"
#include "canvas/kis_grid_manager.h"
#include "dialogs/kis_dlg_blacklist_cleanup.h"
#include "input/kis_input_profile_manager.h"
#include "kis_action_manager.h"
82
#include "kis_action.h"
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
#include "kis_canvas_controls_manager.h"
#include "kis_canvas_resource_provider.h"
#include "kis_composite_progress_proxy.h"
#include "kis_config.h"
#include "kis_config_notifier.h"
#include "kis_control_frame.h"
#include "kis_coordinates_converter.h"
#include "KisDocument.h"
#include "kis_favorite_resource_manager.h"
#include "kis_filter_manager.h"
#include "kis_group_layer.h"
#include <kis_image.h>
#include "kis_image_manager.h"
#include <kis_layer.h>
#include "kis_mainwindow_observer.h"
#include "kis_mask_manager.h"
#include "kis_mimedata.h"
#include "kis_mirror_manager.h"
#include "kis_node_commands_adapter.h"
#include "kis_node.h"
#include "kis_node_manager.h"
#include "kis_painting_assistants_manager.h"
#include <kis_paint_layer.h>
#include "kis_paintop_box.h"
Halla Rempt's avatar
Halla Rempt committed
107
#include <brushengine/kis_paintop_preset.h>
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
#include "KisPart.h"
#include "KisPrintJob.h"
#include "kis_progress_widget.h"
#include "kis_resource_server_provider.h"
#include "kis_selection.h"
#include "kis_selection_manager.h"
#include "kis_shape_controller.h"
#include "kis_shape_layer.h"
#include <kis_signal_compressor.h>
#include "kis_statusbar.h"
#include <KisTemplateCreateDia.h>
#include <kis_tool_freehand.h>
#include "kis_tooltip_manager.h"
#include <kis_undo_adapter.h>
#include "KisView.h"
#include "kis_zoom_manager.h"
#include "widgets/kis_floating_message.h"
125
#include "kis_signal_auto_connection.h"
126
#include "kis_icon_utils.h"
127
#include "kis_guides_manager.h"
128
#include "kis_derived_resources.h"
129
#include "dialogs/kis_delayed_save_dialog.h"
130

131

132 133
class BlockingUserInputEventFilter : public QObject
{
134
    bool eventFilter(QObject *watched, QEvent *event) override
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    {
        Q_UNUSED(watched);
        if(dynamic_cast<QWheelEvent*>(event)
                || dynamic_cast<QKeyEvent*>(event)
                || dynamic_cast<QMouseEvent*>(event)) {
            return true;
        }
        else {
            return false;
        }
    }
};

class KisViewManager::KisViewManagerPrivate
{

public:

153
    KisViewManagerPrivate(KisViewManager *_q, KActionCollection *_actionCollection, QWidget *_q_parent)
154
        : filterManager(_q)
155 156 157 158 159 160
        , createTemplate(0)
        , saveIncremental(0)
        , saveIncrementalBackup(0)
        , openResourcesDirectory(0)
        , rotateCanvasRight(0)
        , rotateCanvasLeft(0)
161
        , resetCanvasRotation(0)
162
        , wrapAroundAction(0)
163
        , levelOfDetailAction(0)
164
        , showRulersAction(0)
165
        , rulersTrackMouseAction(0)
166
        , zoomTo100pct(0)
167 168
        , zoomIn(0)
        , zoomOut(0)
169 170 171 172 173 174 175 176
        , selectionManager(_q)
        , statusBar(_q)
        , controlFrame(_q, _q_parent)
        , nodeManager(_q)
        , imageManager(_q)
        , gridManager(_q)
        , canvasControlsManager(_q)
        , paintingAssistantsManager(_q)
177
        , actionManager(_q, _actionCollection)
178 179 180
        , mainWindow(0)
        , showFloatingMessage(true)
        , currentImageView(0)
181 182 183
        , canvasResourceProvider(_q)
        , canvasResourceManager()
        , guiUpdateCompressor(30, KisSignalCompressor::POSTPONE, _q)
184
        , actionCollection(_actionCollection)
185 186
        , mirrorManager(_q)
        , inputManager(_q)
187
        , actionAuthor(0)
188
    {
189 190 191
        canvasResourceManager.addDerivedResourceConverter(toQShared(new KisCompositeOpResourceConverter));
        canvasResourceManager.addDerivedResourceConverter(toQShared(new KisEffectiveCompositeOpResourceConverter));
        canvasResourceManager.addDerivedResourceConverter(toQShared(new KisOpacityResourceConverter));
192 193
        canvasResourceManager.addDerivedResourceConverter(toQShared(new KisFlowResourceConverter));
        canvasResourceManager.addDerivedResourceConverter(toQShared(new KisSizeResourceConverter));
194 195
        canvasResourceManager.addDerivedResourceConverter(toQShared(new KisLodAvailabilityResourceConverter));
        canvasResourceManager.addDerivedResourceConverter(toQShared(new KisEraserModeResourceConverter));
196
        canvasResourceManager.addResourceUpdateMediator(toQShared(new KisPresetUpdateMediator));
197 198 199
    }

public:
200
    KisFilterManager filterManager;
201
    KisAction *createTemplate;
202
    KisAction *createCopy;
203 204 205 206 207
    KisAction *saveIncremental;
    KisAction *saveIncrementalBackup;
    KisAction *openResourcesDirectory;
    KisAction *rotateCanvasRight;
    KisAction *rotateCanvasLeft;
208
    KisAction *resetCanvasRotation;
209
    KisAction *wrapAroundAction;
210
    KisAction *levelOfDetailAction;
211
    KisAction *showRulersAction;
212
    KisAction *rulersTrackMouseAction;
213
    KisAction *zoomTo100pct;
214 215
    KisAction *zoomIn;
    KisAction *zoomOut;
216 217
    KisAction *softProof;
    KisAction *gamutCheck;
218

219
    KisSelectionManager selectionManager;
220
    KisGuidesManager guidesManager;
221 222 223 224 225 226 227 228
    KisStatusBar statusBar;

    KisControlFrame controlFrame;
    KisNodeManager nodeManager;
    KisImageManager imageManager;
    KisGridManager gridManager;
    KisCanvasControlsManager canvasControlsManager;
    KisPaintingAssistantsManager paintingAssistantsManager;
229
    BlockingUserInputEventFilter blockingEventFilter;
230
    KisActionManager actionManager;
231 232 233 234
    QMainWindow* mainWindow;
    QPointer<KisFloatingMessage> savedFloatingMessage;
    bool showFloatingMessage;
    QPointer<KisView> currentImageView;
235 236 237
    KisCanvasResourceProvider canvasResourceProvider;
    KoCanvasResourceManager canvasResourceManager;
    KisSignalCompressor guiUpdateCompressor;
238
    KActionCollection *actionCollection;
239 240
    KisMirrorManager mirrorManager;
    KisInputManager inputManager;
241

242
    KisSignalAutoConnectionsStore viewConnections;
243
    KSelectAction *actionAuthor; // Select action for author profile.
244 245

    QByteArray canvasState;
246 247

    bool blockUntillOperationsFinishedImpl(KisImageSP image, bool force);
248 249 250
};


251
KisViewManager::KisViewManager(QWidget *parent, KActionCollection *_actionCollection)
252
    : d(new KisViewManagerPrivate(this, _actionCollection, parent))
253 254 255
{
    d->actionCollection = _actionCollection;
    d->mainWindow = dynamic_cast<QMainWindow*>(parent);
256 257
    d->canvasResourceProvider.setResourceManager(&d->canvasResourceManager);
    connect(&d->guiUpdateCompressor, SIGNAL(timeout()), this, SLOT(guiUpdateTimeout()));
258 259

    createActions();
260
    setupManagers();
261

262 263 264
    // These initialization functions must wait until KisViewManager ctor is complete.
    d->statusBar.setup();
    d->controlFrame.setup(parent);
265 266 267 268

    //Check to draw scrollbars after "Canvas only mode" toggle is created.
    this->showHideScrollbars();

Dmitry Kazakov's avatar
Dmitry Kazakov committed
269
    QScopedPointer<KoDummyCanvasController> dummy(new KoDummyCanvasController(actionCollection()));
Stefano Bonicatti's avatar
Stefano Bonicatti committed
270
    KoToolManager::instance()->registerToolActions(actionCollection(), dummy.data());
271

272
    QTimer::singleShot(0, this, SLOT(initializeStatusBarVisibility()));
273 274

    connect(KoToolManager::instance(), SIGNAL(inputDeviceChanged(KoInputDevice)),
275
            d->controlFrame.paintopBox(), SLOT(slotInputDeviceChanged(KoInputDevice)));
276 277

    connect(KoToolManager::instance(), SIGNAL(changedTool(KoCanvasController*,int)),
278
            d->controlFrame.paintopBox(), SLOT(slotToolChanged(KoCanvasController*,int)));
279

280
    connect(&d->nodeManager, SIGNAL(sigNodeActivated(KisNodeSP)),
281 282 283
            resourceProvider(), SLOT(slotNodeActivated(KisNodeSP)));

    connect(resourceProvider()->resourceManager(), SIGNAL(canvasResourceChanged(int,QVariant)),
284
            d->controlFrame.paintopBox(), SLOT(slotCanvasResourceChanged(int,QVariant)));
285

286 287 288
    connect(KisPart::instance(), SIGNAL(sigViewAdded(KisView*)), SLOT(slotViewAdded(KisView*)));
    connect(KisPart::instance(), SIGNAL(sigViewRemoved(KisView*)), SLOT(slotViewRemoved(KisView*)));

289 290
    connect(KisConfigNotifier::instance(), SIGNAL(configChanged()), SLOT(slotUpdateAuthorProfileActions()));

291
    KisInputProfileManager::instance()->loadProfiles();
292 293 294 295

    KisConfig cfg;
    d->showFloatingMessage = cfg.showCanvasMessages();

296 297 298 299 300 301 302 303
}


KisViewManager::~KisViewManager()
{
    KisConfig cfg;
    if (resourceProvider() && resourceProvider()->currentPreset()) {
        cfg.writeEntry("LastPreset", resourceProvider()->currentPreset()->name());
304 305 306
        cfg.writeKoColor("LastForeGroundColor",resourceProvider()->fgColor());
        cfg.writeKoColor("LastBackGroundColor",resourceProvider()->bgColor());

307
    }
308

309 310 311 312 313 314 315 316 317 318
    cfg.writeEntry("baseLength", KoResourceItemChooserSync::instance()->baseLength());

    delete d;
}

KActionCollection *KisViewManager::actionCollection() const
{
    return d->actionCollection;
}

319 320
void KisViewManager::slotViewAdded(KisView *view)
{
321
    d->inputManager.addTrackedCanvas(view->canvasBase());
322

323
    if (viewCount() != 0) {
324 325
        d->statusBar.showAllStatusBarItems();
    }
326 327 328 329
}

void KisViewManager::slotViewRemoved(KisView *view)
{
330
    d->inputManager.removeTrackedCanvas(view->canvasBase());
331 332 333 334

    if (viewCount() == 0) {
        d->statusBar.hideAllStatusBarItems();
    }
335 336
}

337 338 339 340
void KisViewManager::setCurrentView(KisView *view)
{
    bool first = true;
    if (d->currentImageView) {
341 342
        d->currentImageView->notifyCurrentStateChanged(false);

343
        d->currentImageView->canvasBase()->setCursor(QCursor(Qt::ArrowCursor));
344 345 346 347 348
        first = false;
        KisDocument* doc = d->currentImageView->document();
        if (doc) {
            doc->disconnect(this);
        }
349
        d->currentImageView->canvasController()->proxyObject->disconnect(&d->statusBar);
350
        d->viewConnections.clear();
351 352
    }

353

354 355 356
    d->softProof->setChecked(view->softProofing());
    d->gamutCheck->setChecked(view->gamutCheck());

357 358 359 360 361 362 363 364
    QPointer<KisView>imageView = qobject_cast<KisView*>(view);

    if (imageView) {
        // Wait for the async image to have loaded
        KisDocument* doc = view->document();
        //        connect(canvasController()->proxyObject, SIGNAL(documentMousePositionChanged(QPointF)), d->statusBar, SLOT(documentMousePositionChanged(QPointF)));

        d->currentImageView = imageView;
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        // Restore the last used brush preset, color and background color.
        if (first) {
            KisConfig cfg;
            KisPaintOpPresetResourceServer * rserver = KisResourceServerProvider::instance()->paintOpPresetServer();
            QString lastPreset = cfg.readEntry("LastPreset", QString("Basic_tip_default"));
            KisPaintOpPresetSP preset = rserver->resourceByName(lastPreset);
            if (!preset) {
                preset = rserver->resourceByName("Basic_tip_default");
            }

            if (!preset) {
                preset = rserver->resources().first();
            }
            if (preset) {
                paintOpBox()->restoreResource(preset.data());
            }

            const KoColorSpace *cs = KoColorSpaceRegistry::instance()->rgb8();
            KoColor foreground(Qt::black, cs);
            d->canvasResourceProvider.setFGColor(cfg.readKoColor("LastForeGroundColor",foreground));
            KoColor background(Qt::white, cs);
            d->canvasResourceProvider.setBGColor(cfg.readKoColor("LastBackGroundColor",background));

        }

390
        KisCanvasController *canvasController = dynamic_cast<KisCanvasController*>(d->currentImageView->canvasController());
391

392
        d->viewConnections.addUniqueConnection(&d->nodeManager, SIGNAL(sigNodeActivated(KisNodeSP)), doc->image(), SLOT(requestStrokeEndActiveNode()));
393 394
        d->viewConnections.addUniqueConnection(d->rotateCanvasRight, SIGNAL(triggered()), canvasController, SLOT(rotateCanvasRight15()));
        d->viewConnections.addUniqueConnection(d->rotateCanvasLeft, SIGNAL(triggered()),canvasController, SLOT(rotateCanvasLeft15()));
395
        d->viewConnections.addUniqueConnection(d->resetCanvasRotation, SIGNAL(triggered()),canvasController, SLOT(resetCanvasRotation()));
396

397
        d->viewConnections.addUniqueConnection(d->wrapAroundAction, SIGNAL(toggled(bool)), canvasController, SLOT(slotToggleWrapAroundMode(bool)));
398
        d->wrapAroundAction->setChecked(canvasController->wrapAroundMode());
399 400 401 402

        d->viewConnections.addUniqueConnection(d->levelOfDetailAction, SIGNAL(toggled(bool)), canvasController, SLOT(slotToggleLevelOfDetailMode(bool)));
        d->levelOfDetailAction->setChecked(canvasController->levelOfDetailMode());

403
        d->viewConnections.addUniqueConnection(d->currentImageView->image(), SIGNAL(sigColorSpaceChanged(const KoColorSpace*)), d->controlFrame.paintopBox(), SLOT(slotColorSpaceChanged(const KoColorSpace*)));
404 405
        d->viewConnections.addUniqueConnection(d->showRulersAction, SIGNAL(toggled(bool)), imageView->zoomManager(), SLOT(setShowRulers(bool)));
        d->viewConnections.addUniqueConnection(d->rulersTrackMouseAction, SIGNAL(toggled(bool)), imageView->zoomManager(), SLOT(setRulersTrackMouse(bool)));
406
        d->viewConnections.addUniqueConnection(d->zoomTo100pct, SIGNAL(triggered()), imageView->zoomManager(), SLOT(zoomTo100()));
407 408
        d->viewConnections.addUniqueConnection(d->zoomIn, SIGNAL(triggered()), imageView->zoomController()->zoomAction(), SLOT(zoomIn()));
        d->viewConnections.addUniqueConnection(d->zoomOut, SIGNAL(triggered()), imageView->zoomController()->zoomAction(), SLOT(zoomOut()));
409

410 411 412
        d->viewConnections.addUniqueConnection(d->softProof, SIGNAL(toggled(bool)), view, SLOT(slotSoftProofing(bool)) );
        d->viewConnections.addUniqueConnection(d->gamutCheck, SIGNAL(toggled(bool)), view, SLOT(slotGamutCheck(bool)) );

413 414
        imageView->zoomManager()->setShowRulers(d->showRulersAction->isChecked());
        imageView->zoomManager()->setRulersTrackMouse(d->rulersTrackMouseAction->isChecked());
415

416
        showHideScrollbars();
417 418
    }

419 420
    d->filterManager.setView(imageView);
    d->selectionManager.setView(imageView);
421
    d->guidesManager.setView(imageView);
422 423 424 425 426 427 428 429
    d->nodeManager.setView(imageView);
    d->imageManager.setView(imageView);
    d->canvasControlsManager.setView(imageView);
    d->actionManager.setView(imageView);
    d->gridManager.setView(imageView);
    d->statusBar.setView(imageView);
    d->paintingAssistantsManager.setView(imageView);
    d->mirrorManager.setView(imageView);
430 431

    if (d->currentImageView) {
432
        d->currentImageView->notifyCurrentStateChanged(true);
433
        d->currentImageView->canvasController()->activate();
434 435
        d->currentImageView->canvasController()->setFocus();
    }
436

437
    d->actionManager.updateGUI();
438

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    d->viewConnections.addUniqueConnection(
        image(), SIGNAL(sigSizeChanged(const QPointF&, const QPointF&)),
        resourceProvider(), SLOT(slotImageSizeChanged()));

    d->viewConnections.addUniqueConnection(
        image(), SIGNAL(sigResolutionChanged(double,double)),
        resourceProvider(), SLOT(slotOnScreenResolutionChanged()));

    d->viewConnections.addUniqueConnection(
        image(), SIGNAL(sigNodeChanged(KisNodeSP)),
        this, SLOT(updateGUI()));

    d->viewConnections.addUniqueConnection(
        view->zoomManager()->zoomController(),
        SIGNAL(zoomChanged(KoZoomMode::Mode,qreal)),
        resourceProvider(), SLOT(slotOnScreenResolutionChanged()));

    resourceProvider()->slotImageSizeChanged();
    resourceProvider()->slotOnScreenResolutionChanged();
458 459


460
    Q_EMIT viewChanged();
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
}


KoZoomController *KisViewManager::zoomController() const
{
    if (d->currentImageView) {
        return d->currentImageView->zoomController();
    }
    return 0;
}

KisImageWSP KisViewManager::image() const
{
    if (document()) {
        return document()->image();
    }
    return 0;
}

KisCanvasResourceProvider * KisViewManager::resourceProvider()
{
482
    return &d->canvasResourceProvider;
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
}

KisCanvas2 * KisViewManager::canvasBase() const
{
    if (d && d->currentImageView) {
        return d->currentImageView->canvasBase();
    }
    return 0;
}

QWidget* KisViewManager::canvas() const
{
    if (d && d->currentImageView && d->currentImageView->canvasBase()->canvasWidget()) {
        return d->currentImageView->canvasBase()->canvasWidget();
    }
    return 0;
}

KisStatusBar * KisViewManager::statusBar() const
{
503
    return &d->statusBar;
504 505
}

506
void KisViewManager::addStatusBarItem(QWidget *widget, int stretch, bool permanent)
507
{
508
    d->statusBar.addStatusBarItem(widget, stretch, permanent);
509 510
}

511
void KisViewManager::removeStatusBarItem(QWidget *widget)
512
{
513
    d->statusBar.removeStatusBarItem(widget);
514 515 516 517
}

KisPaintopBox* KisViewManager::paintOpBox() const
{
518
    return d->controlFrame.paintopBox();
519 520 521 522
}

KoProgressUpdater* KisViewManager::createProgressUpdater(KoProgressUpdater::Mode mode)
{
523
    return new KisProgressUpdater(d->statusBar.progress(), document()->progressProxy(), mode);
524 525 526 527
}

KisSelectionManager * KisViewManager::selectionManager()
{
528
    return &d->selectionManager;
529 530 531 532
}

KisNodeSP KisViewManager::activeNode()
{
533
    return d->nodeManager.activeNode();
534 535 536 537
}

KisLayerSP KisViewManager::activeLayer()
{
538
    return d->nodeManager.activeLayer();
539 540 541 542
}

KisPaintDeviceSP KisViewManager::activeDevice()
{
543
    return d->nodeManager.activePaintDevice();
544 545 546 547 548 549 550 551 552 553 554 555
}

KisZoomManager * KisViewManager::zoomManager()
{
    if (d->currentImageView) {
        return d->currentImageView->zoomManager();
    }
    return 0;
}

KisFilterManager * KisViewManager::filterManager()
{
556
    return &d->filterManager;
557 558 559 560
}

KisImageManager * KisViewManager::imageManager()
{
561
    return &d->imageManager;
562 563
}

564 565
KisInputManager* KisViewManager::inputManager() const
{
566
    return &d->inputManager;
567 568
}

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
KisSelectionSP KisViewManager::selection()
{
    if (d->currentImageView) {
        return d->currentImageView->selection();
    }
    return 0;

}

bool KisViewManager::selectionEditable()
{
    KisLayerSP layer = activeLayer();
    if (layer) {
        KoProperties properties;
        QList<KisNodeSP> masks = layer->childNodes(QStringList("KisSelectionMask"), properties);
        if (masks.size() == 1) {
            return masks[0]->isEditable();
        }
    }
    // global selection is always editable
    return true;
}

KisUndoAdapter * KisViewManager::undoAdapter()
{
    if (!document()) return 0;

    KisImageWSP image = document()->image();
    Q_ASSERT(image);

    return image->undoAdapter();
}

void KisViewManager::createActions()
{
604 605
    KisConfig cfg;

Michael Abrahams's avatar
Michael Abrahams committed
606
    d->saveIncremental = actionManager()->createAction("save_incremental_version");
607 608
    connect(d->saveIncremental, SIGNAL(triggered()), this, SLOT(slotSaveIncremental()));

Michael Abrahams's avatar
Michael Abrahams committed
609
    d->saveIncrementalBackup = actionManager()->createAction("save_incremental_backup");
610 611 612 613 614 615 616
    connect(d->saveIncrementalBackup, SIGNAL(triggered()), this, SLOT(slotSaveIncrementalBackup()));

    connect(mainWindow(), SIGNAL(documentSaved()), this, SLOT(slotDocumentSaved()));

    d->saveIncremental->setEnabled(false);
    d->saveIncrementalBackup->setEnabled(false);

Michael Abrahams's avatar
Michael Abrahams committed
617
    KisAction *tabletDebugger = actionManager()->createAction("tablet_debugger");
618 619
    connect(tabletDebugger, SIGNAL(triggered()), this, SLOT(toggleTabletLogger()));

Michael Abrahams's avatar
Michael Abrahams committed
620
    d->createTemplate = actionManager()->createAction("create_template");
621 622
    connect(d->createTemplate, SIGNAL(triggered()), this, SLOT(slotCreateTemplate()));

Michael Abrahams's avatar
Michael Abrahams committed
623
    d->createCopy = actionManager()->createAction("create_copy");
624 625
    connect(d->createCopy, SIGNAL(triggered()), this, SLOT(slotCreateCopy()));

Michael Abrahams's avatar
Michael Abrahams committed
626
    d->openResourcesDirectory = actionManager()->createAction("open_resources_directory");
627 628
    connect(d->openResourcesDirectory, SIGNAL(triggered()), SLOT(openResourcesDirectory()));

629 630
    d->rotateCanvasRight   = actionManager()->createAction("rotate_canvas_right");
    d->rotateCanvasLeft    = actionManager()->createAction("rotate_canvas_left");
631
    d->resetCanvasRotation = actionManager()->createAction("reset_canvas_rotation");
632
    d->wrapAroundAction    = actionManager()->createAction("wrap_around_mode");
Michael Abrahams's avatar
Michael Abrahams committed
633
    d->levelOfDetailAction = actionManager()->createAction("level_of_detail_mode");
634 635
    d->softProof           = actionManager()->createAction("softProof");
    d->gamutCheck          = actionManager()->createAction("gamutCheck");
636

Michael Abrahams's avatar
Michael Abrahams committed
637
    KisAction *tAction = actionManager()->createAction("showStatusBar");
638
    tAction->setChecked(cfg.showStatusBar());
639 640
    connect(tAction, SIGNAL(toggled(bool)), this, SLOT(showStatusBar(bool)));

641
    tAction = actionManager()->createAction("view_show_canvas_only");
642
    tAction->setChecked(false);
Halla Rempt's avatar
Halla Rempt committed
643
    connect(tAction, SIGNAL(toggled(bool)), this, SLOT(switchCanvasOnly(bool)));
644 645

    //Workaround, by default has the same shortcut as mirrorCanvas
646
    KisAction *a = dynamic_cast<KisAction*>(actionCollection()->action("format_italic"));
647
    if (a) {
648
        a->setDefaultShortcut(QKeySequence());
649 650
    }

Michael Abrahams's avatar
Michael Abrahams committed
651
    a = actionManager()->createAction("edit_blacklist_cleanup");
652 653
    connect(a, SIGNAL(triggered()), this, SLOT(slotBlacklistCleanup()));

654
    d->showRulersAction = actionManager()->createAction("view_ruler");
655
    d->showRulersAction->setChecked(cfg.showRulers());
656
    connect(d->showRulersAction, SIGNAL(toggled(bool)), SLOT(slotSaveShowRulersState(bool)));
657

658 659 660
    d->rulersTrackMouseAction = actionManager()->createAction("rulers_track_mouse");
    d->rulersTrackMouseAction->setChecked(cfg.rulersTrackMouse());
    connect(d->rulersTrackMouseAction, SIGNAL(toggled(bool)), SLOT(slotSaveRulersTrackMouseState(bool)));
661

Michael Abrahams's avatar
Michael Abrahams committed
662
    d->zoomTo100pct = actionManager()->createAction("zoom_to_100pct");
Halla Rempt's avatar
Halla Rempt committed
663

664 665 666
    d->zoomIn = actionManager()->createStandardAction(KStandardAction::ZoomIn, 0, "");
    d->zoomOut = actionManager()->createStandardAction(KStandardAction::ZoomOut, 0, "");

667
    d->actionAuthor  = new KSelectAction(KisIconUtils::loadIcon("im-user"), i18n("Active Author Profile"), this);
668 669 670
    connect(d->actionAuthor, SIGNAL(triggered(const QString &)), this, SLOT(changeAuthorProfile(const QString &)));
    actionCollection()->addAction("settings_active_author", d->actionAuthor);
    slotUpdateAuthorProfileActions();
Halla Rempt's avatar
Halla Rempt committed
671

672 673
}

674
void KisViewManager::setupManagers()
675 676 677 678 679
{
    // Create the managers for filters, selections, layers etc.
    // XXX: When the currentlayer changes, call updateGUI on all
    // managers

680
    d->filterManager.setup(actionCollection(), actionManager());
681

682
    d->selectionManager.setup(actionManager());
683

684 685
    d->guidesManager.setup(actionManager());

686
    d->nodeManager.setup(actionCollection(), actionManager());
687

688
    d->imageManager.setup(actionManager());
689

690
    d->gridManager.setup(actionManager());
691

692
    d->paintingAssistantsManager.setup(actionManager());
693

694
    d->canvasControlsManager.setup(actionManager());
695

696
    d->mirrorManager.setup(actionCollection());
697 698 699 700 701

}

void KisViewManager::updateGUI()
{
702
    d->guiUpdateCompressor.start();
703 704 705 706 707 708 709 710 711 712
}

void KisViewManager::slotBlacklistCleanup()
{
    KisDlgBlacklistCleanup dialog;
    dialog.exec();
}

KisNodeManager * KisViewManager::nodeManager() const
{
713
    return &d->nodeManager;
714 715 716 717
}

KisActionManager* KisViewManager::actionManager() const
{
718
    return &d->actionManager;
719 720 721 722
}

KisGridManager * KisViewManager::gridManager() const
{
723
    return &d->gridManager;
724 725
}

726
KisGuidesManager * KisViewManager::guidesManager() const
727
{
728
    return &d->guidesManager;
729 730 731 732
}

KisPaintingAssistantsManager* KisViewManager::paintingAssistantsManager() const
{
733
    return &d->paintingAssistantsManager;
734 735 736 737 738 739 740 741 742 743
}

KisDocument *KisViewManager::document() const
{
    if (d->currentImageView && d->currentImageView->document()) {
        return d->currentImageView->document();
    }
    return 0;
}

744 745 746 747 748 749 750 751 752
int KisViewManager::viewCount() const
{
    KisMainWindow *mw  = qobject_cast<KisMainWindow*>(d->mainWindow);
    if (mw) {
        return mw->viewCount();
    }
    return 0;
}

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
bool KisViewManager::KisViewManagerPrivate::blockUntillOperationsFinishedImpl(KisImageSP image, bool force)
{
    const int busyWaitDelay = 1000;
    KisDelayedSaveDialog dialog(image, !force ? KisDelayedSaveDialog::GeneralDialog : KisDelayedSaveDialog::ForcedDialog, busyWaitDelay, mainWindow);
    dialog.blockIfImageIsBusy();

    return dialog.result() == QDialog::Accepted;
}


bool KisViewManager::blockUntillOperationsFinished(KisImageSP image)
{
    return d->blockUntillOperationsFinishedImpl(image, false);
}

void KisViewManager::blockUntillOperationsFinishedForced(KisImageSP image)
{
    d->blockUntillOperationsFinishedImpl(image, true);
}

773 774 775
void KisViewManager::slotCreateTemplate()
{
    if (!document()) return;
776
    KisTemplateCreateDia::createTemplate( QStringLiteral("templates/"), ".kra", document(), mainWindow());
777 778
}

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
void KisViewManager::slotCreateCopy()
{
    if (!document()) return;
    KisDocument *doc = KisPart::instance()->createDocument();

    QString name = document()->documentInfo()->aboutInfo("name");
    if (name.isEmpty()) {
        name = document()->url().toLocalFile();
    }
    name = i18n("%1 (Copy)", name);
    doc->documentInfo()->setAboutInfo("title", name);
    KisImageWSP image = document()->image();
    KisImageSP newImage = new KisImage(doc->createUndoStore(), image->width(), image->height(), image->colorSpace(), name);
    newImage->setRootLayer(dynamic_cast<KisGroupLayer*>(image->rootLayer()->clone().data()));
    doc->setCurrentImage(newImage);
    KisPart::instance()->addDocument(doc);
    KisMainWindow *mw  = qobject_cast<KisMainWindow*>(d->mainWindow);
796
    mw->addViewAndNotifyLoadingCompleted(doc);
797 798 799
}


800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
QMainWindow* KisViewManager::qtMainWindow() const
{
    if (d->mainWindow)
        return d->mainWindow;

    //Fallback for when we have not yet set the main window.
    QMainWindow* w = qobject_cast<QMainWindow*>(qApp->activeWindow());
    if(w)
        return w;

    return mainWindow();
}

void KisViewManager::setQtMainWindow(QMainWindow* newMainWindow)
{
    d->mainWindow = newMainWindow;
}


void KisViewManager::slotDocumentSaved()
{
    d->saveIncremental->setEnabled(true);
    d->saveIncrementalBackup->setEnabled(true);
}

void KisViewManager::slotSaveIncremental()
{
    if (!document()) return;

    bool foundVersion;
    bool fileAlreadyExists;
    bool isBackup;
    QString version = "000";
    QString newVersion;
    QString letter;
    QString fileName = document()->localFilePath();

    // Find current version filenames
    // v v Regexp to find incremental versions in the filename, taking our backup scheme into account as well
    // Considering our incremental version and backup scheme, format is filename_001~001.ext
    QRegExp regex("_\\d{1,4}[.]|_\\d{1,4}[a-z][.]|_\\d{1,4}[~]|_\\d{1,4}[a-z][~]");
    regex.indexIn(fileName);     //  Perform the search
    QStringList matches = regex.capturedTexts();
    foundVersion = matches.at(0).isEmpty() ? false : true;

    // Ensure compatibility with Save Incremental Backup
    // If this regex is not kept separate, the entire algorithm needs modification;
    // It's simpler to just add this.
    QRegExp regexAux("_\\d{1,4}[~]|_\\d{1,4}[a-z][~]");
    regexAux.indexIn(fileName);     //  Perform the search
    QStringList matchesAux = regexAux.capturedTexts();
    isBackup = matchesAux.at(0).isEmpty() ? false : true;

    // If the filename has a version, prepare it for incrementation
    if (foundVersion) {
        version = matches.at(matches.count() - 1);     //  Look at the last index, we don't care about other matches
        if (version.contains(QRegExp("[a-z]"))) {
            version.chop(1);             //  Trim "."
            letter = version.right(1);   //  Save letter
            version.chop(1);             //  Trim letter
        } else {
            version.chop(1);             //  Trim "."
        }
        version.remove(0, 1);            //  Trim "_"
    } else {
        // ...else, simply add a version to it so the next loop works
        QRegExp regex2("[.][a-z]{2,4}$");  //  Heuristic to find file extension
        regex2.indexIn(fileName);
        QStringList matches2 = regex2.capturedTexts();
        QString extensionPlusVersion = matches2.at(0);
        extensionPlusVersion.prepend(version);
        extensionPlusVersion.prepend("_");
        fileName.replace(regex2, extensionPlusVersion);
    }

    // Prepare the base for new version filename
    int intVersion = version.toInt(0);
    ++intVersion;
    QString baseNewVersion = QString::number(intVersion);
    while (baseNewVersion.length() < version.length()) {
        baseNewVersion.prepend("0");
    }

    // Check if the file exists under the new name and search until options are exhausted (test appending a to z)
    do {
        newVersion = baseNewVersion;
        newVersion.prepend("_");
        if (!letter.isNull()) newVersion.append(letter);
        if (isBackup) {
            newVersion.append("~");
        } else {
            newVersion.append(".");
        }
        fileName.replace(regex, newVersion);
894
        fileAlreadyExists = QFile(fileName).exists();
895 896 897 898 899 900 901 902 903 904 905 906
        if (fileAlreadyExists) {
            if (!letter.isNull()) {
                char letterCh = letter.at(0).toLatin1();
                ++letterCh;
                letter = QString(QChar(letterCh));
            } else {
                letter = 'a';
            }
        }
    } while (fileAlreadyExists && letter != "{");  // x, y, z, {...

    if (letter == "{") {
Halla Rempt's avatar
Halla Rempt committed
907
        QMessageBox::critical(mainWindow(), i18nc("@title:window", "Couldn't save incremental version"), i18n("Alternative names exhausted, try manually saving with a higher number"));
908 909
        return;
    }
910
    document()->setFileBatchMode(true);
Halla Rempt's avatar
Halla Rempt committed
911
    document()->saveAs(QUrl::fromUserInput(fileName));
912
    document()->setFileBatchMode(false);
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964

    if (mainWindow()) {
        mainWindow()->updateCaption();
    }

}

void KisViewManager::slotSaveIncrementalBackup()
{
    if (!document()) return;

    bool workingOnBackup;
    bool fileAlreadyExists;
    QString version = "000";
    QString newVersion;
    QString letter;
    QString fileName = document()->localFilePath();

    // First, discover if working on a backup file, or a normal file
    QRegExp regex("~\\d{1,4}[.]|~\\d{1,4}[a-z][.]");
    regex.indexIn(fileName);     //  Perform the search
    QStringList matches = regex.capturedTexts();
    workingOnBackup = matches.at(0).isEmpty() ? false : true;

    if (workingOnBackup) {
        // Try to save incremental version (of backup), use letter for alt versions
        version = matches.at(matches.count() - 1);     //  Look at the last index, we don't care about other matches
        if (version.contains(QRegExp("[a-z]"))) {
            version.chop(1);             //  Trim "."
            letter = version.right(1);   //  Save letter
            version.chop(1);             //  Trim letter
        } else {
            version.chop(1);             //  Trim "."
        }
        version.remove(0, 1);            //  Trim "~"

        // Prepare the base for new version filename
        int intVersion = version.toInt(0);
        ++intVersion;
        QString baseNewVersion = QString::number(intVersion);
        QString backupFileName = document()->localFilePath();
        while (baseNewVersion.length() < version.length()) {
            baseNewVersion.prepend("0");
        }

        // Check if the file exists under the new name and search until options are exhausted (test appending a to z)
        do {
            newVersion = baseNewVersion;
            newVersion.prepend("~");
            if (!letter.isNull()) newVersion.append(letter);
            newVersion.append(".");
            backupFileName.replace(regex, newVersion);
965
            fileAlreadyExists = QFile(backupFileName).exists();
966 967 968 969 970 971 972 973 974 975 976 977
            if (fileAlreadyExists) {
                if (!letter.isNull()) {
                    char letterCh = letter.at(0).toLatin1();
                    ++letterCh;
                    letter = QString(QChar(letterCh));
                } else {
                    letter = 'a';
                }
            }
        } while (fileAlreadyExists && letter != "{");  // x, y, z, {...

        if (letter == "{") {
Halla Rempt's avatar
Halla Rempt committed
978
            QMessageBox::critical(mainWindow(), i18nc("@title:window", "Couldn't save incremental backup"), i18n("Alternative names exhausted, try manually saving with a higher number"));
979 980 981
            return;
        }
        QFile::copy(fileName, backupFileName);
Halla Rempt's avatar
Halla Rempt committed
982
        document()->saveAs(QUrl::fromUserInput(fileName));
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

        if (mainWindow()) mainWindow()->updateCaption();
    }
    else { // if NOT working on a backup...
        // Navigate directory searching for latest backup version, ignore letters
        const quint8 HARDCODED_DIGIT_COUNT = 3;
        QString baseNewVersion = "000";
        QString backupFileName = document()->localFilePath();
        QRegExp regex2("[.][a-z]{2,4}$");  //  Heuristic to find file extension
        regex2.indexIn(backupFileName);
        QStringList matches2 = regex2.capturedTexts();
        QString extensionPlusVersion = matches2.at(0);
        extensionPlusVersion.prepend(baseNewVersion);
        extensionPlusVersion.prepend("~");
        backupFileName.replace(regex2, extensionPlusVersion);

        // Save version with 1 number higher than the highest version found ignoring letters
        do {
            newVersion = baseNewVersion;
            newVersion.prepend("~");
            newVersion.append(".");
            backupFileName.replace(regex, newVersion);
1005
            fileAlreadyExists = QFile(backupFileName).exists();
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
            if (fileAlreadyExists) {
                // Prepare the base for new version filename, increment by 1
                int intVersion = baseNewVersion.toInt(0);
                ++intVersion;
                baseNewVersion = QString::number(intVersion);
                while (baseNewVersion.length() < HARDCODED_DIGIT_COUNT) {
                    baseNewVersion.prepend("0");
                }
            }
        } while (fileAlreadyExists);

        // Save both as backup and on current file for interapplication workflow
1018
        document()->setFileBatchMode(true);
1019
        QFile::copy(fileName, backupFileName);
Halla Rempt's avatar
Halla Rempt committed
1020
        document()->saveAs(QUrl::fromUserInput(fileName));
1021
        document()->setFileBatchMode(false);
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

        if (mainWindow()) mainWindow()->updateCaption();
    }
}

void KisViewManager::disableControls()
{
    // prevents possible crashes, if somebody changes the paintop during dragging by using the mousewheel
    // this is for Bug 250944
    // the solution blocks all wheel, mouse and key event, while dragging with the freehand tool
    // see KisToolFreehand::initPaint() and endPaint()
1033
    d->controlFrame.paintopBox()->installEventFilter(&d->blockingEventFilter);
1034
    Q_FOREACH (QObject* child, d->controlFrame.paintopBox()->children()) {
1035 1036 1037 1038 1039 1040
        child->installEventFilter(&d->blockingEventFilter);
    }
}

void KisViewManager::enableControls()
{
1041
    d->controlFrame.paintopBox()->removeEventFilter(&d->blockingEventFilter);
1042
    Q_FOREACH (QObject* child, d->controlFrame.paintopBox()->children()) {
1043 1044 1045 1046 1047 1048
        child->removeEventFilter(&d->blockingEventFilter);
    }
}

void KisViewManager::showStatusBar(bool toggled)
{
1049 1050 1051 1052 1053
    KisMainWindow *mw = mainWindow();
    if(mw && mw->statusBar()) {
        mw->statusBar()->setVisible(toggled);
        KisConfig cfg;
        cfg.setShowStatusBar(toggled);
1054 1055 1056
    }
}

Halla Rempt's avatar
Halla Rempt committed
1057
void KisViewManager::switchCanvasOnly(bool toggled)
1058 1059 1060 1061 1062 1063 1064 1065 1066
{
    KisConfig cfg;
    KisMainWindow* main = mainWindow();

    if(!main) {
        dbgUI << "Unable to switch to canvas-only mode, main window not found";
        return;
    }

1067 1068 1069 1070
    if (toggled) {
        d->canvasState = qtMainWindow()->saveState();
    }

1071
    if (cfg.hideStatusbarFullscreen()) {