~neon/kolourpaint/master

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
/*
   Copyright (c) 2003-2007 Clarence Dang <dang@kde.org>
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#include "kpMainWindow.h"
#include "kpMainWindowPrivate.h"

#include "layers/selections/image/kpAbstractImageSelection.h"
#include "environments/commands/kpCommandEnvironment.h"
#include "environments/tools/kpToolEnvironment.h"
#include "widgets/kpColorCells.h"
#include "widgets/toolbars/kpColorToolBar.h"
#include "commands/kpCommandHistory.h"
#include "kpDefs.h"
#include "document/kpDocument.h"
#include "environments/document/kpDocumentEnvironment.h"
#include "layers/selections/kpSelectionDrag.h"
#include "kpThumbnail.h"
#include "tools/kpTool.h"
#include "widgets/toolbars/kpToolToolBar.h"
#include "views/manager/kpViewManager.h"
#include "kpViewScrollableContainer.h"
#include "generic/kpWidgetMapper.h"
#include "views/kpZoomedThumbnailView.h"
#include "views/kpZoomedView.h"

#include <KSharedConfig>
#include <kconfiggroup.h>
#include <KLocalizedString>

#include <QEvent>
#include <QMenu>
#include <QTimer>
#include <QDropEvent>

#include "kpLogCategories.h"


//---------------------------------------------------------------------

kpMainWindow::kpMainWindow ()
    : KXmlGuiWindow (nullptr/*parent*/)
{
    init ();
    open (QUrl (), true/*create an empty doc*/);

    d->isFullyConstructed = true;
}

//---------------------------------------------------------------------

kpMainWindow::kpMainWindow (const QUrl &url)
    : KXmlGuiWindow (nullptr/*parent*/)
{
    init ();
    open (url, true/*create an empty doc with the same url if url !exist*/);

    d->isFullyConstructed = true;
}

//---------------------------------------------------------------------

kpMainWindow::kpMainWindow (kpDocument *newDoc)
    : KXmlGuiWindow (nullptr/*parent*/)
{
    init ();
    setDocument (newDoc);

    d->isFullyConstructed = true;
}

//---------------------------------------------------------------------


// TODO: Move into appropriate kpMainWindow_*.cpp or another class

// private
void kpMainWindow::readGeneralSettings ()
{
#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "\tkpMainWindow(" << objectName () << ")::readGeneralSettings()";
#endif

    KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupGeneral);

    d->configFirstTime = cfg.readEntry (kpSettingFirstTime, true);
    d->configShowGrid = cfg.readEntry (kpSettingShowGrid, false);
    d->configShowPath = cfg.readEntry (kpSettingShowPath, false);
    d->moreEffectsDialogLastEffect = cfg.readEntry (kpSettingMoreEffectsLastEffect, 0);
    kpToolEnvironment::drawAntiAliased = cfg.readEntry(kpSettingDrawAntiAliased, true);

    if (cfg.hasKey (kpSettingOpenImagesInSameWindow))
    {
        d->configOpenImagesInSameWindow = cfg.readEntry (kpSettingOpenImagesInSameWindow, false);
    }
    else
    {
        d->configOpenImagesInSameWindow = false;
#if DEBUG_KP_MAIN_WINDOW
        qCDebug(kpLogMainWindow) << "\tconfigOpenImagesInSameWindow: first time"
                  << " - writing default: " << d->configOpenImagesInSameWindow;
#endif
        // TODO: More hidden options have to write themselves out on startup,
        //       not on use, to be discoverable (e.g. printing centered on page).
        cfg.writeEntry (kpSettingOpenImagesInSameWindow,
                        d->configOpenImagesInSameWindow);
        cfg.sync ();
    }

    d->configPrintImageCenteredOnPage = cfg.readEntry (kpSettingPrintImageCenteredOnPage, true);


#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "\t\tGeneral Settings: firstTime=" << d->configFirstTime
               << " showGrid=" << d->configShowGrid
               << " showPath=" << d->configShowPath
               << " moreEffectsDialogLastEffect=" << d->moreEffectsDialogLastEffect
               << " openImagesInSameWindow=" << d->configOpenImagesInSameWindow
               << " printImageCenteredOnPage=" << d->configPrintImageCenteredOnPage;
#endif
}

//---------------------------------------------------------------------

// private
void kpMainWindow::readThumbnailSettings ()
{
#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "\tkpMainWindow(" << objectName () << ")::readThumbnailSettings()";
#endif

    KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupThumbnail);

    d->configThumbnailShown = cfg.readEntry (kpSettingThumbnailShown, false);
    d->configThumbnailGeometry = cfg.readEntry (kpSettingThumbnailGeometry, QRect ());
    d->configZoomedThumbnail = cfg.readEntry (kpSettingThumbnailZoomed, true);
    d->configThumbnailShowRectangle = cfg.readEntry (kpSettingThumbnailShowRectangle, true);

#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "\t\tThumbnail Settings: shown=" << d->configThumbnailShown
               << " geometry=" << d->configThumbnailGeometry
               << " zoomed=" << d->configZoomedThumbnail
               << " showRectangle=" << d->configThumbnailShowRectangle;
#endif
}

//---------------------------------------------------------------------

void kpMainWindow::finalizeGUI(KXMLGUIClient *client)
{
  if ( client == this )
  {
    const QList<QMenu *> menuToHide = findChildren<QMenu *>(QStringLiteral("toolToolBarHiddenMenu"));
    // should only contain one but...
    for (auto *menu : menuToHide)
    {
        menu->menuAction()->setVisible(false);
    }
  }
}

//---------------------------------------------------------------------

// private
void kpMainWindow::init ()
{
#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "kpMainWindow(" << objectName () << ")::init()";
    QTime totalTime; totalTime.start ();
#endif

    d = new kpMainWindowPrivate;

    //
    // set mainwindow properties
    //

    setMinimumSize (320, 260);
    setAcceptDrops (true);

    //
    // read config
    //

    // KConfig::readEntry() does not actually reread from disk, hence doesn't
    // realize what other processes have done e.g. Settings / Show Path
    KSharedConfig::openConfig ()->reparseConfiguration ();

    readGeneralSettings ();
    readThumbnailSettings ();

    //
    // create GUI
    //
    setupActions ();
    createStatusBar ();
    createGUI ();

    createColorBox ();
    createToolBox ();


    // Let the Tool Box take all the vertical space, since it can be quite
    // tall with all its tool option widgets.  This also avoids occasional
    // bugs like the Tool Box overlapping the Color Tool Bar.
    setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
    setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);

    // no tabbed docks; does not make sense with only 2 dock widgets
    setDockOptions(QMainWindow::AnimatedDocks | QMainWindow::AllowNestedDocks);

    addDockWidget(Qt::BottomDockWidgetArea, d->colorToolBar, Qt::Horizontal);

    d->scrollView = new kpViewScrollableContainer (this);
    d->scrollView->setObjectName ( QStringLiteral("scrollView" ));

    connect (d->scrollView, &kpViewScrollableContainer::beganDocResize,
             this, &kpMainWindow::slotBeganDocResize);

    connect (d->scrollView, &kpViewScrollableContainer::continuedDocResize,
             this, &kpMainWindow::slotContinuedDocResize);

    connect (d->scrollView, &kpViewScrollableContainer::cancelledDocResize,
             this, &kpMainWindow::slotCancelledDocResize);

    connect (d->scrollView, &kpViewScrollableContainer::endedDocResize,
             this, &kpMainWindow::slotEndedDocResize);

    connect (d->scrollView, &kpViewScrollableContainer::statusMessageChanged,
             this, &kpMainWindow::slotDocResizeMessageChanged);

    connect (d->scrollView, &kpViewScrollableContainer::contentsMoved,
             this, &kpMainWindow::slotScrollViewAfterScroll);

    setCentralWidget (d->scrollView);

    //
    // set initial pos/size of GUI
    //

    setAutoSaveSettings ();

    // our non-XMLGUI tools-toolbar will get initially the toolButtonStyle as
    // all other toolbars, but we want to show only icons for the tools by default
    // (have to do this _after_ setAutoSaveSettings as that applies the default settings)
    if (d->configFirstTime)
    {
      d->toolToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);

      KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral);

      cfg.writeEntry(kpSettingFirstTime, d->configFirstTime = false);
      cfg.sync();
    }


#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "\tall done in " << totalTime.elapsed () << "msec";
#endif
}

//---------------------------------------------------------------------

// private virtual [base KMainWindow]
void kpMainWindow::readProperties (const KConfigGroup &configGroup)
{
#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "kpMainWindow<" << this << ">::readProperties()";
#endif

    // No document at all?
    if (!configGroup.hasKey (kpSessionSettingDocumentUrl))
    {
    #if DEBUG_KP_MAIN_WINDOW
        qCDebug(kpLogMainWindow) << "\tno url - no document";
    #endif
        setDocument (nullptr);
    }
    // Have a document.
    else
    {
        const QUrl url = QUrl (configGroup.readEntry (kpSessionSettingDocumentUrl,
                                                QString ()));
    #if DEBUG_KP_MAIN_WINDOW
        qCDebug(kpLogMainWindow) << "\turl=" << url;
    #endif

        const QSize notFromURLDocSize =
            configGroup.readEntry (kpSessionSettingNotFromUrlDocumentSize,
                                   QSize ());

        // Is from URL?
        if (notFromURLDocSize.isEmpty ())
        {
            // If this fails, the empty document that kpMainWindow::kpMainWindow()
            // created is left untouched.
            openInternal (url, defaultDocSize (),
                false/*show error message if url !exist*/);
        }
        // Not from URL?
        else
        {
        #if DEBUG_KP_MAIN_WINDOW
            qCDebug(kpLogMainWindow) << "\tnot from url; doc size=" << notFromURLDocSize;
        #endif
            // Either we have an empty URL or we have a "kolourpaint doesnotexist.png"
            // URL.  Regarding the latter case, if a file now actually exists at that
            // URL, we do open it - ignoring notFromURLDocSize - to avoid putting
            // the user in a situation where he might accidentally overwrite an
            // existing file.
            openInternal (url, notFromURLDocSize,
                true/*create an empty doc with the same url if url !exist*/);
        }
    }

}

//---------------------------------------------------------------------

// private virtual [base KMainWindow]
// WARNING: KMainWindow API Doc says "No user interaction is allowed
//          in this function!"
void kpMainWindow::saveProperties (KConfigGroup &configGroup)
{
#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "kpMainWindow<" << this << ">::saveProperties()";
#endif

    // No document at all?
    if (!d->document)
    {
    #if DEBUG_KP_MAIN_WINDOW
        qCDebug(kpLogMainWindow) << "\tno url - no document";
    #endif
    }
    // Have a document.
    else
    {
        // Save URL in all cases:
        //
        //    a) d->document->isFromExistingURL()
        //    b) !d->document->isFromExistingURL() [save size in this case]
        //       i) No URL
        //       ii) URL (from "kolourpaint doesnotexist.png")

        const QUrl url = d->document->url ();
    #if DEBUG_KP_MAIN_WINDOW
        qCDebug(kpLogMainWindow) << "\turl=" << url;
    #endif
        configGroup.writeEntry (kpSessionSettingDocumentUrl, url.url ());

        // Not from URL e.g. "kolourpaint doesnotexist.png"?
        //
        // Note that "kolourpaint doesexist.png" is considered to be from
        // a URL even if it was deleted in the background. This is because the user expects
        // it to be from a URL, so when we session restore, we pop up a
        // "cannot find file" dialog, instead of silently creating a new,
        // blank document.
        if (!d->document->isFromExistingURL ())
        {
            // If we don't have a URL either:
            //
            // a) it was not modified - so we can use either width() or
            //    constructorWidth() (they'll be equal).
            // b) the changes were discarded so we use the initial width,
            //    constructorWidth().
            //
            // Similarly for height() and constructorHeight().
            const QSize docSize (d->document->constructorWidth (),
                                 d->document->constructorHeight ());
        #if DEBUG_KP_MAIN_WINDOW
            qCDebug(kpLogMainWindow) << "\tnot from url; doc size=" << docSize;
        #endif
            configGroup.writeEntry (kpSessionSettingNotFromUrlDocumentSize, docSize);
        }
    }
}

//---------------------------------------------------------------------


kpMainWindow::~kpMainWindow ()
{
    d->isFullyConstructed = false;

    // Get the kpTool to finish up.  This makes sure that the kpTool destructor
    // will not need to access any other class (that might be deleted before
    // the destructor is called by the QObject child-deletion mechanism).
    if (tool ()) {
        tool ()->endInternal ();
    }

    // Delete document & views.
    // Note: This will disconnects signals from the current kpTool, so kpTool
    //       must not be destructed yet.
    setDocument (nullptr);

    delete d->commandHistory; d->commandHistory = nullptr;
    delete d->scrollView; d->scrollView = nullptr;

    delete d; d = nullptr;
}

//---------------------------------------------------------------------


// public
kpDocument *kpMainWindow::document () const
{
    return d->document;
}

//---------------------------------------------------------------------

// public
kpDocumentEnvironment *kpMainWindow::documentEnvironment ()
{
    if (!d->documentEnvironment) {
        d->documentEnvironment = new kpDocumentEnvironment (this);
    }

    return d->documentEnvironment;
}

//---------------------------------------------------------------------

// public
kpViewManager *kpMainWindow::viewManager () const
{
    return d->viewManager;
}

//---------------------------------------------------------------------

// public
kpColorToolBar *kpMainWindow::colorToolBar () const
{
    return d->colorToolBar;
}

//---------------------------------------------------------------------

// public
kpColorCells *kpMainWindow::colorCells () const
{
    return d->colorToolBar ? d->colorToolBar->colorCells () : nullptr;
}

//---------------------------------------------------------------------

// public
kpToolToolBar *kpMainWindow::toolToolBar () const
{
    return d->toolToolBar;
}

//---------------------------------------------------------------------

// public
kpCommandHistory *kpMainWindow::commandHistory () const
{
    return d->commandHistory;
}

//---------------------------------------------------------------------

kpCommandEnvironment *kpMainWindow::commandEnvironment ()
{
    if (!d->commandEnvironment) {
        d->commandEnvironment = new kpCommandEnvironment (this);
    }

    return d->commandEnvironment;
}

//---------------------------------------------------------------------

// private
void kpMainWindow::setupActions ()
{
    setupFileMenuActions ();
    setupEditMenuActions ();
    setupViewMenuActions ();
    setupImageMenuActions ();
    setupColorsMenuActions ();
    setupSettingsMenuActions ();

    setupTextToolBarActions ();
    setupToolActions ();
}

//---------------------------------------------------------------------

// private
void kpMainWindow::enableDocumentActions (bool enable)
{
    enableFileMenuDocumentActions (enable);
    enableEditMenuDocumentActions (enable);
    enableViewMenuDocumentActions (enable);
    enableImageMenuDocumentActions (enable);
    enableColorsMenuDocumentActions (enable);
    enableSettingsMenuDocumentActions (enable);
}

//---------------------------------------------------------------------

// private
void kpMainWindow::setDocument (kpDocument *newDoc)
{
    //qCDebug(kpLogMainWindow) << newDoc;

    // is it a close operation?
    if (!newDoc)
    {
    #if DEBUG_KP_MAIN_WINDOW
        qCDebug(kpLogMainWindow) << "\tdisabling actions";
    #endif

        // sync with the bit marked "sync" below

        // TODO: Never disable the Color Box because the user should be
        //       able to manipulate the colors, even without a currently
        //       open document.
        //
        //       We just have to make sure that signals from the Color
        //       Box aren't fired and received unexpectedly when there's
        //       no document.
        Q_ASSERT (d->colorToolBar);
        d->colorToolBar->setEnabled (false);

        enableTextToolBarActions (false);
    }

    // Always disable the tools.
    // If we decide to open a new document/mainView we want
    // kpTool::begin() to be called again e.g. in case it sets the cursor.
    // kpViewManager won't do this because we nuke it to avoid stale state.
    enableToolsDocumentActions (false);

    if (!newDoc)
    {
        enableDocumentActions (false);
    }

    delete d->mainView; d->mainView = nullptr;
    slotDestroyThumbnail ();

    // viewManager will die and so will the selection
    d->actionCopy->setEnabled (false);
    d->actionCut->setEnabled (false);
    d->actionDelete->setEnabled (false);
    d->actionDeselect->setEnabled (false);
    d->actionCopyToFile->setEnabled (false);

    delete d->viewManager; d->viewManager = nullptr;

#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "\tdestroying document";
    qCDebug(kpLogMainWindow) << "\t\td->document=" << d->document;
#endif
    // destroy current document
    delete d->document;
    d->document = newDoc;


    if (!d->lastCopyToURL.isEmpty ())
    {
        // remove file name from path
        QString path = d->lastCopyToURL.path ();
        path = path.left (path.lastIndexOf (QLatin1Char ('/')) + 1);
        d->lastCopyToURL.setPath (path);
    }
    d->copyToFirstTime = true;

    if (!d->lastExportURL.isEmpty ())
    {
        QString path = d->lastExportURL.path ();
        path = path.left (path.lastIndexOf (QLatin1Char ('/')) + 1);
        d->lastExportURL.setPath (path);
    }
    d->exportFirstTime = true;


    // not a close operation?
    if (d->document)
    {
    #if DEBUG_KP_MAIN_WINDOW
        qCDebug(kpLogMainWindow) << "\treparenting doc that may have been created into a"
                  << " different mainWindiow";
    #endif
        d->document->setEnviron (documentEnvironment ());

        d->viewManager = new kpViewManager (this);

        d->mainView = new kpZoomedView (d->document, d->toolToolBar, d->viewManager,
                                       nullptr/*buddyView*/,
                                       d->scrollView,
                                       d->scrollView->viewport ());
        d->mainView->setObjectName ( QStringLiteral("mainView" ));

        d->viewManager->registerView (d->mainView);
        d->scrollView->setView (d->mainView);
        d->mainView->show ();

    #if DEBUG_KP_MAIN_WINDOW
        qCDebug(kpLogMainWindow) << "\thooking up document signals";
    #endif

        // Copy/Cut/Deselect/Delete
        connect (d->document, &kpDocument::selectionEnabled,
                 d->actionCut, &QAction::setEnabled);

        connect (d->document, &kpDocument::selectionEnabled,
                 d->actionCopy, &QAction::setEnabled);

        connect (d->document, &kpDocument::selectionEnabled,
                 d->actionDelete, &QAction::setEnabled);

        connect (d->document, &kpDocument::selectionEnabled,
                 d->actionDeselect, &QAction::setEnabled);

        connect (d->document, &kpDocument::selectionEnabled,
                 d->actionCopyToFile, &QAction::setEnabled);

        // this code won't actually enable any actions at this stage
        // (fresh document) but better safe than sorry
        d->actionCopy->setEnabled (d->document->selection ());
        d->actionCut->setEnabled (d->document->selection ());
        d->actionDeselect->setEnabled (d->document->selection ());
        d->actionDelete->setEnabled (d->document->selection ());
        d->actionCopyToFile->setEnabled (d->document->selection ());

        connect (d->document, &kpDocument::selectionEnabled,
                 this, &kpMainWindow::slotImageMenuUpdateDueToSelection);

        connect (d->document, &kpDocument::selectionIsTextChanged,
                 this, &kpMainWindow::slotImageMenuUpdateDueToSelection);

        // Status bar
        connect (d->document, &kpDocument::documentOpened,
                 this, &kpMainWindow::recalculateStatusBar);

        connect (d->document, SIGNAL (sizeChanged(QSize)),
                 this, SLOT (setStatusBarDocSize(QSize)));

        // Caption (url, modified)
        connect (d->document, &kpDocument::documentModified,
                 this, &kpMainWindow::slotUpdateCaption);

        connect (d->document, &kpDocument::documentOpened,
                 this, &kpMainWindow::slotUpdateCaption);

        connect (d->document, &kpDocument::documentSaved,
                 this, &kpMainWindow::slotUpdateCaption);

        // File/Reload action only available with non-empty URL
        connect (d->document, &kpDocument::documentSaved,
                 this, &kpMainWindow::slotEnableReload);

        connect (d->document, &kpDocument::documentSaved,
                 this, &kpMainWindow::slotEnableSettingsShowPath);

        // Command history
        Q_ASSERT (d->commandHistory);
        connect (d->commandHistory, &kpCommandHistory::documentRestored,
                 this, &kpMainWindow::slotDocumentRestored); // caption "!modified"

        connect (d->document, &kpDocument::documentSaved,
                 d->commandHistory, &kpCommandHistory::documentSaved);

        // Sync document -> views
        connect (d->document, &kpDocument::contentsChanged,
                 d->viewManager, &kpViewManager::updateViews);

        connect (d->document, static_cast<void (kpDocument::*)(int, int)>(&kpDocument::sizeChanged),
                 d->viewManager, &kpViewManager::adjustViewsToEnvironment);

        connect (d->document,
                 static_cast<void (kpDocument::*)(int, int)>(&kpDocument::sizeChanged),
                 d->viewManager, &kpViewManager::adjustViewsToEnvironment);

    #if DEBUG_KP_MAIN_WINDOW
        qCDebug(kpLogMainWindow) << "\tenabling actions";
    #endif

        // sync with the bit marked "sync" above

        Q_ASSERT (d->colorToolBar);
        d->colorToolBar->setEnabled (true);


        // Hide the text toolbar - it will be shown by kpToolText::begin()
        enableTextToolBarActions (false);

        enableToolsDocumentActions (true);

        enableDocumentActions (true);
    }

#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "\tupdating mainWindow elements";
#endif

    slotImageMenuUpdateDueToSelection ();
    recalculateStatusBar ();
    slotUpdateCaption ();  // Untitled to start with
    slotEnableReload ();
    slotEnableSettingsShowPath ();

    if (d->commandHistory) {
        d->commandHistory->clear ();
    }

#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "\tdocument and views ready to go!";
#endif
}

//---------------------------------------------------------------------

// private virtual [base QWidget]
void kpMainWindow::dragEnterEvent (QDragEnterEvent *e)
{
    // It's faster to test for QMimeData::hasText() first due to the
    // lazy evaluation of the '||' operator.
    e->setAccepted (e->mimeData ()->hasText () ||
                    e->mimeData ()->hasUrls () ||
                    kpSelectionDrag::canDecode (e->mimeData ()));
}

//---------------------------------------------------------------------

// private virtual [base QWidget]
void kpMainWindow::dropEvent (QDropEvent *e)
{
#if DEBUG_KP_MAIN_WINDOW
    qCDebug(kpLogMainWindow) << "kpMainWindow::dropEvent" << e->pos ();
#endif

    QList<QUrl> urls;

    kpAbstractImageSelection *sel = kpSelectionDrag::decode (e->mimeData ());
    if (sel)
    {
        // TODO: How do you actually drop a selection or ordinary images on
        //       the clipboard)?  Will this code path _ever_ execute?
        sel->setTransparency (imageSelectionTransparency ());
        // TODO: drop at point like with QTextDrag below?
        paste (*sel);
        delete sel;
    }
    else if (!(urls = e->mimeData ()->urls ()).isEmpty ())
    {
        // LOTODO: kpSetOverrideCursorSaver cursorSaver (Qt::waitCursor);
        //
        //         However, you would need to prefix all possible error/warning
        //         dialogs that might be called, with Qt::arrowCursor e.g. in
        //         kpDocument  and probably a lot more places.
        for (const auto &u : urls)
            open (u);
    }
    else if (e->mimeData ()->hasText ())
    {
        const QString text = e->mimeData ()->text ();

        QPoint selTopLeft = KP_INVALID_POINT;
        const QPoint globalPos = QWidget::mapToGlobal (e->pos ());
    #if DEBUG_KP_MAIN_WINDOW
        qCDebug(kpLogMainWindow) << "\tpos toGlobal=" << globalPos;
    #endif

        kpView *view = nullptr;

        if (d->viewManager)
        {
            view = d->viewManager->viewUnderCursor ();
        #if DEBUG_KP_MAIN_WINDOW
            qCDebug(kpLogMainWindow) << "\t\tviewUnderCursor=" << view;
        #endif
            if (!view)
            {
                // HACK: see kpViewManager::setViewUnderCursor() to see why
                //       it's not reliable
            #if DEBUG_KP_MAIN_WINDOW
                qCDebug(kpLogMainWindow) << "\t\tattempting to discover view";

                if (d->mainView && d->scrollView)
                {
                    qCDebug(kpLogMainWindow) << "\t\t\tmainView->globalRect="
                            << kpWidgetMapper::toGlobal (d->mainView, d->mainView->rect ())
                            << " scrollView->globalRect="
                            << kpWidgetMapper::toGlobal (d->scrollView,
                                    QRect (0, 0,
                                            d->scrollView->viewport()->width (),
                                            d->scrollView->viewport()->height ()));
                }
            #endif
                if (d->thumbnailView &&
                    kpWidgetMapper::toGlobal (d->thumbnailView, d->thumbnailView->rect ())
                        .contains (globalPos))
                {
                    // TODO: Code will never get executed.
                    //       Thumbnail doesn't accept drops.
                    view = d->thumbnailView;
                }
                else if (d->mainView &&
                         kpWidgetMapper::toGlobal (d->mainView, d->mainView->rect ())
                             .contains (globalPos) &&
                         d->scrollView &&
                         kpWidgetMapper::toGlobal (d->scrollView,
                             QRect (0, 0,
                                    d->scrollView->viewport()->width (),
                                    d->scrollView->viewport()->height ()))
                             .contains (globalPos))
                {
                    view = d->mainView;
                }
            }
        }

        if (view)
        {
            const QPoint viewPos = view->mapFromGlobal (globalPos);
            const QPoint docPoint = view->transformViewToDoc (viewPos);

            // viewUnderCursor() is hacky and can return a view when we aren't
            // over one thanks to drags.
            if (d->document && d->document->rect ().contains (docPoint))
            {
                selTopLeft = docPoint;

                // TODO: In terms of doc pixels, would be inconsistent behaviour
                //       based on zoomLevel of view.
                // selTopLeft -= QPoint (-view->selectionResizeHandleAtomicSize (),
                //                       -view->selectionResizeHandleAtomicSize ());
            }
        }

        pasteText (text, true/*force new text selection*/, selTopLeft);
    }
}

//---------------------------------------------------------------------

// private slot
void kpMainWindow::slotScrollViewAfterScroll ()
{
    // OPT: Why can't this be moved into kpViewScrollableContainer::slotDragScroll(),
    //      grouping all drag-scroll-related repaints, which would potentially avoid
    //      double repainting?
    if (tool ())
    {
        tool ()->somethingBelowTheCursorChanged ();
    }
}

//---------------------------------------------------------------------

// private virtual [base QWidget]
void kpMainWindow::moveEvent (QMoveEvent * /*e*/)
{
    if (d->thumbnail)
    {
        // Disabled because it lags too far behind the mainWindow
        // d->thumbnail->move (d->thumbnail->pos () + (e->pos () - e->oldPos ()));

        notifyThumbnailGeometryChanged ();
    }
}

//---------------------------------------------------------------------

// private slot
void kpMainWindow::slotUpdateCaption ()
{
    if (d->document)
    {
        setCaption (d->configShowPath ? d->document->prettyUrl ()
                                     : d->document->prettyFilename (),
                    d->document->isModified ());
    }
    else
    {
        setCaption (QString(), false);
    }
}

//---------------------------------------------------------------------

// private slot
void kpMainWindow::slotDocumentRestored ()
{
    if (d->document) {
        d->document->setModified (false);
    }
    slotUpdateCaption ();
}

//---------------------------------------------------------------------