/
tst_app.cpp
7112 lines (5850 loc) · 307 KB
/
tst_app.cpp
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
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2023, Mitch Curtis
This file is part of Slate.
Slate 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 3 of the License, or
(at your option) any later version.
Slate 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 Slate. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QClipboard>
#include <QCursor>
#include <QGuiApplication>
#include <QPainter>
#include <QQmlEngine>
#include <QSharedPointer>
#include <QtTest>
#include <QQuickItemGrabResult>
#include <QQuickWindow>
#include <QtQuickTest>
// Need this otherwise we get linker errors.
extern "C" {
#include "bitmap/bmp.h"
#include "bitmap/misc/gif.h"
}
#include "application.h"
#include "applypixelpencommand.h"
#include "imagelayer.h"
#include "imageutils.h"
#include "tilecanvas.h"
#include "probabilityswatch.h"
#include "project.h"
#include "projectmanager.h"
#include "qtutils.h"
#include "swatch.h"
#include "testhelper.h"
#include "tileset.h"
class tst_App : public TestHelper
{
Q_OBJECT
public:
tst_App(int &argc, char **argv);
private Q_SLOTS:
// Project management.
void newProjectWithNewTileset();
void repeatedNewProject_data();
void repeatedNewProject();
void openClose_data();
void openClose();
void saveTilesetProject();
void saveAsAndLoadTilesetProject();
void saveAsAndLoad_data();
void saveAsAndLoad();
void versionCheck_data();
void versionCheck();
void loadTilesetProjectWithInvalidTileset();
void loadLayeredImageProjectAfterTilesetProject();
void loadInvalidProjects_data();
void loadInvalidProjects();
void recentFiles();
void newProjectSizeFromClipboard_data();
void newProjectSizeFromClipboard();
void splitViewStateAcrossProjects();
void saveOnPrompt();
void loadPaneFractionalOffset();
// Tools, misc.
void keyboardShortcuts();
void optionsShortcutCancelled();
void optionsTransparencyCancelled();
void showGrid();
void undoPixels();
void undoLargePixelPen();
void undoTiles();
void undoWithDuplicates();
void undoTilesetCanvasSizeChange();
void undoImageCanvasSizeChange();
void undoImageSizeChange();
void undoLayeredImageSizeChange();
void undoRearrangeContentsIntoGridChange_data();
void undoRearrangeContentsIntoGridChange();
void undoPixelFill();
void undoTileFill();
void undoThickSquarePen();
void undoThickRoundPen();
void penSubpixelPosition();
void penSubpixelPositionWithThickBrush_data();
void penSubpixelPositionWithThickBrush();
void colours_data();
void colours();
void colourPickerSaturationHex();
void panes();
void altEyedropper();
void eyedropper();
void eyedropperBackgroundColour();
void zoomAndPan();
void zoomAndCentre();
void penWhilePannedAndZoomed_data();
void penWhilePannedAndZoomed();
void centrePanes();
void useTilesetSwatch();
void tilesetSwatchContextMenu();
void tilesetSwatchNavigation();
void cursorShapeAfterClickingLighter();
void colourPickerHexField();
void colourPickerHexFieldTranslucent();
void eraseImageCanvas_data();
void eraseImageCanvas();
void splitterSettingsMouse_data();
void splitterSettingsMouse();
void fillImageCanvas_data();
void fillImageCanvas();
void fillLayeredImageCanvas();
void greedyPixelFillImageCanvas_data();
void greedyPixelFillImageCanvas();
void texturedFillVariance_data();
void texturedFillVariance();
void texturedFillSwatch_data();
void texturedFillSwatch();
void pixelLineToolImageCanvas_data();
void pixelLineToolImageCanvas();
void pixelLineToolTransparent_data();
void pixelLineToolTransparent();
void lineMiddleMouseButton();
void penToolRightClickBehaviour_data();
void penToolRightClickBehaviour();
void splitScreenRendering();
void formatNotModifiable();
void models();
// Rulers, guides, notes, etc.
void rulersAndGuides_data();
void rulersAndGuides();
void rulersSplitScreen();
void addAndDeleteMultipleGuides();
void loadDuplicateGuides();
void notes_data();
void notes();
void dragNoteWithoutMoving();
void saveAndLoadNotes();
// Swatches.
void autoSwatch_data();
void autoSwatch();
void autoSwatchGridViewContentY();
void autoSwatchPasteConfirmation();
void swatches();
void importSwatches_data();
void importSwatches();
// Selection-related stuff.
void selectionToolImageCanvas();
void selectionToolTileCanvas();
void cancelSelectionToolImageCanvas();
void moveSelectionImageCanvas_data();
void moveSelectionImageCanvas();
void moveSelectionWithKeysImageCanvas();
void deleteSelectionImageCanvas_data();
void deleteSelectionImageCanvas();
void copyPaste_data();
void copyPaste();
void undoCopyPasteWithTransparency();
void pasteFromExternalSource_data();
void pasteFromExternalSource();
void undoAfterMovedPaste();
void undoPasteAcrossLayers_data();
void undoPasteAcrossLayers();
void flipPastedImage();
void flipOnTransparentBackground();
void panThenMoveSelection();
void selectionCursorGuide();
void rotateSelection_data();
void rotateSelection();
void rotateSelectionAtEdge_data();
void rotateSelectionAtEdge();
void rotateSelectionTransparentBackground_data();
void rotateSelectionTransparentBackground();
void hueSaturation_data();
void hueSaturation();
void opacityDialog_data();
void opacityDialog();
void cropToSelection_data();
void cropToSelection();
// Animation.
void animationPlayback_data();
void animationPlayback();
void playNonLoopingAnimationTwice();
void animationGifExport();
void newAnimations_data();
void newAnimations();
void duplicateAnimations_data();
void duplicateAnimations();
void saveAnimations();
void clickOnCurrentAnimation();
void renameAnimation();
void reverseAnimation();
void animationFrameWidthTooLarge();
void animationPreviewUpdated();
void seekAnimation();
void animationFrameMarkers();
// Layers.
void addAndRemoveLayers();
void newLayerIndex();
void layerVisibility();
void moveLayerUpAndDown();
void mergeLayerUpAndDown();
void renameLayers();
void duplicateLayers();
void saveAndLoadLayeredImageProject();
void layerVisibilityAfterMoving();
// void undoAfterAddLayer();
void selectionConfirmedWhenSwitchingLayers();
void newLayerAfterMovingSelection();
void undoAfterMovingTwoSelections();
void autoExport();
void exportFileNamedLayers();
void disableToolsWhenLayerHidden();
void undoMoveContents();
void undoMoveContentsOfVisibleLayers();
void selectNextLayer();
};
typedef QVector<Project::Type> ProjectTypeVector;
tst_App::tst_App(int &argc, char **argv) :
TestHelper(argc, argv)
{
}
void tst_App::newProjectWithNewTileset()
{
QVERIFY2(createNewTilesetProject(32, 32, 5, 5), failureMessage);
// Make sure that any changes are reflected in the image after it's saved.
// First, establish what we expect the image to look like in the end.
const int expectedWidth = 32 * 5;
const int expectedHeight = 32 * 5;
QCOMPARE(tilesetProject->tileset()->image()->width(), expectedWidth);
QCOMPARE(tilesetProject->tileset()->image()->height(), expectedHeight);
QImage expectedTilesetImage(ImageUtils::filledImage(expectedWidth, expectedHeight, Qt::white));
expectedTilesetImage.setPixelColor(10, 10, tileCanvas->penForegroundColour());
// Draw a tile on.
QVERIFY2(switchMode(TileCanvas::TileMode), failureMessage);
setCursorPosInTiles(0, 0);
QTest::mouseClick(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
QVERIFY(tilesetProject->tileAt(QPoint(0, 0)));
QVERIFY(tilesetProject->hasUnsavedChanges());
// Draw a pixel on that tile.
QVERIFY2(switchMode(TileCanvas::PixelMode), failureMessage);
setCursorPosInScenePixels(10, 10);
QTest::mouseClick(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
QVERIFY2(compareImages(*tilesetProject->tileset()->image(), expectedTilesetImage), failureMessage);
// Save the project.
const QUrl saveFileName = QUrl::fromLocalFile(tempProjectDir->path() + "/mytileset.stp");
QVERIFY(tilesetProject->saveAs(saveFileName));
// Should save the image at the same location as the project.
const QString tilesetPath = tempProjectDir->path() + "/mytileset.png";
QCOMPARE(tilesetProject->tilesetUrl(), QUrl::fromLocalFile(tilesetPath));
QVERIFY(QFile::exists(tilesetPath));
QVERIFY2(compareImages(*tilesetProject->tileset()->image(), expectedTilesetImage), failureMessage);
}
void tst_App::repeatedNewProject_data()
{
QTest::addColumn<ProjectTypeVector>("projectTypes");
QTest::newRow("TilesetType, ImageType") << (ProjectTypeVector() << Project::TilesetType << Project::ImageType);
QTest::newRow("ImageType, LayeredImageType") << (ProjectTypeVector() << Project::ImageType << Project::LayeredImageType);
QTest::newRow("LayeredImageType, TilesetType") << (ProjectTypeVector() << Project::LayeredImageType << Project::TilesetType);
}
void tst_App::repeatedNewProject()
{
QFETCH(ProjectTypeVector, projectTypes);
foreach (auto projectType, projectTypes) {
// Shouldn't crash on repeated opening of new projects.
QVERIFY2(createNewProject(projectType), failureMessage);
}
}
void tst_App::openClose_data()
{
addAllProjectTypes();
}
void tst_App::openClose()
{
QFETCH(Project::Type, projectType);
// Create a new, valid project.
QVERIFY2(createNewProject(projectType), failureMessage);
if (projectType == Project::TilesetType) {
// Test an invalid tileset URL.
QTest::ignoreMessage(QtWarningMsg, "QFSFileEngine::open: No file name specified");
const QUrl badUrl("doesnotexist.stp");
const QRegularExpression errorMessage(QLatin1String("Failed to open tileset project's STP file at "));
QVERIFY2(loadProject(badUrl, errorMessage), failureMessage);
// There was a project open before we attempted to load the invalid one.
QCOMPARE(project->hasLoaded(), true);
}
// Check that the cursor goes blank when the canvas has focus.
QVERIFY(canvas->hasActiveFocus());
// Move the mouse a bit to trigger a cursor update since mContainsMouse was reset.
QTest::mouseMove(window, canvas->mapToScene(
QPointF(canvas->width() / 2, canvas->height() / 2)).toPoint());
QTRY_COMPARE(window->cursor().shape(), Qt::BlankCursor);
// Test closing a valid project.
project->close();
QVERIFY_NO_CREATION_ERRORS_OCCURRED();
QCOMPARE(project->url(), QUrl());
QCOMPARE(project->hasLoaded(), false);
// Some tool buttons need a project open...
QCOMPARE(canvasSizeToolButton->property("enabled").toBool(), false);
// ... while others don't.
QCOMPARE(fullScreenToolButton->property("enabled").toBool(), true);
// Hovering over the canvas should result in the default cursor being displayed.
QTest::mouseMove(window, canvas->mapToScene(
QPointF(canvas->width() / 2, canvas->height() / 2)).toPoint());
QCOMPARE(window->cursor().shape(), Qt::ArrowCursor);
QVERIFY2(createNewProject(projectType), failureMessage);
}
void tst_App::saveTilesetProject()
{
QVERIFY2(createNewTilesetProject(), failureMessage);
// Store a snapshot of the canvas before we alter it.
QVERIFY(imageGrabber.requestImage(tileCanvas));
QTRY_VERIFY(imageGrabber.isReady());
const QImage originalImage = imageGrabber.takeImage();
// Draw a tile on first.
QVERIFY2(switchMode(TileCanvas::TileMode), failureMessage);
// QTBUG-53466
setCursorPosInScenePixels(10, 10);
QTest::mouseClick(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
QVERIFY(tilesetProject->tileAt(QPoint(0, 0)));
QVERIFY(tilesetProject->hasUnsavedChanges());
QVERIFY(window->title().contains("*"));
// Save our drawing.
const QUrl saveUrl = QUrl::fromLocalFile(tempProjectDir->path() + "/project.stp");
QVERIFY(tilesetProject->saveAs(saveUrl));
QVERIFY(!tilesetProject->hasUnsavedChanges());
QVERIFY(imageGrabber.requestImage(tileCanvas));
QTRY_VERIFY(imageGrabber.isReady());
QVERIFY(imageGrabber.takeImage() != originalImage);
// Check that what's on disk matches the image that we currently have.
QImage savedImage(tempTilesetUrl.toLocalFile());
QVERIFY(!savedImage.isNull());
QCOMPARE(savedImage, *tilesetProject->tileAt(QPoint(0, 0))->tileset()->image());
QTRY_VERIFY_WITH_TIMEOUT(!window->title().contains("*"), 10);
}
void tst_App::saveAsAndLoadTilesetProject()
{
QSKIP("SplitView part fails; TODO: check if still failing with Qt 6");
QVERIFY2(createNewTilesetProject(), failureMessage);
// Save the untouched project.
const QString originalProjectPath = tempProjectDir->path() + "/project.stp";
QVERIFY(tilesetProject->saveAs(QUrl::fromLocalFile(originalProjectPath)));
QVERIFY(!tilesetProject->hasUnsavedChanges());
QVERIFY(!window->title().contains("*"));
QCOMPARE(tilesetProject->url().toLocalFile(), originalProjectPath);
// Save the original project file contents, along with a screenshot.
QByteArray originalProjectFileContents;
{
QFile file(originalProjectPath);
QVERIFY2(file.open(QIODevice::ReadOnly), qPrintable(file.errorString()));
originalProjectFileContents = file.readAll();
QVERIFY(!originalProjectFileContents.isEmpty());
}
QVERIFY(imageGrabber.requestImage(tileCanvas));
QTRY_VERIFY(imageGrabber.isReady());
const QImage originalCanvasImage = imageGrabber.takeImage();
// Save the project to a new file.
const QString savedProjectPath = tempProjectDir->path() + "/project2.stp";
QVERIFY(tilesetProject->saveAs(QUrl::fromLocalFile(savedProjectPath)));
QCOMPARE(tilesetProject->url().toLocalFile(), savedProjectPath);
QVERIFY(imageGrabber.requestImage(tileCanvas));
QTRY_VERIFY(imageGrabber.isReady());
QCOMPARE(imageGrabber.takeImage(), originalCanvasImage);
QVERIFY2(switchMode(TileCanvas::TileMode), failureMessage);
// Draw on the canvas. We want to check that the latest
// saved project is modified and not the original.
setCursorPosInTiles(0, 0);
QTest::mouseMove(window, cursorWindowPos);
QCOMPARE(tileCanvas->tool(), TileCanvas::PenTool);
QTest::mousePress(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
QTest::mouseRelease(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
QVERIFY(tilesetProject->hasUnsavedChanges());
QVERIFY(window->title().contains("*"));
// Save our project.
QVERIFY(tilesetProject->save());
QVERIFY(!tilesetProject->hasUnsavedChanges());
QVERIFY(imageGrabber.requestImage(tileCanvas));
QTRY_VERIFY(imageGrabber.isReady());
QVERIFY(imageGrabber.takeImage() != originalCanvasImage);
QTRY_VERIFY_WITH_TIMEOUT(!window->title().contains("*"), 10);
// Check that what's on disk matches the tileset image that we currently have.
const Tile *modifiedTile = tilesetProject->tileAt(QPoint(0, 0));
QImage savedImage(modifiedTile->tileset()->fileName());
QCOMPARE(savedImage, *modifiedTile->tileset()->image());
// Check that what's on disk for the original project matches the original project that we have.
{
QFile file(originalProjectPath);
QVERIFY(file.open(QIODevice::ReadOnly));
QCOMPARE(file.readAll(), originalProjectFileContents);
}
// Check that what's on disk for the saved project doesn't match that of the original project.
{
QFile file(savedProjectPath);
QVERIFY(file.open(QIODevice::ReadOnly));
QVERIFY(file.readAll() != originalProjectFileContents);
}
// Load the saved file.
QVERIFY2(triggerCloseProject(), failureMessage);
QVERIFY(!tilesetProject->hasLoaded());
QVERIFY(imageGrabber.requestImage(tileCanvas));
QTRY_VERIFY(imageGrabber.isReady());
const QImage closedCanvasImage = imageGrabber.takeImage();
QVERIFY2(loadProject(QUrl::fromLocalFile(savedProjectPath)), failureMessage);
QVERIFY(imageGrabber.requestImage(tileCanvas));
QTRY_VERIFY(imageGrabber.isReady());
QVERIFY(imageGrabber.takeImage() != closedCanvasImage);
}
void tst_App::saveAsAndLoad_data()
{
addActualProjectTypes();
}
void tst_App::saveAsAndLoad()
{
QSKIP("SplitView part fails; TODO: check if still failing with Qt 6");
// Ensure that things that are common to all project types are saved,
// like guides, pane offset and zoom, etc.
QFETCH(Project::Type, projectType);
QFETCH(QString, projectExtension);
QVERIFY2(createNewProject(projectType), failureMessage);
// TestHelper hides rulers for new projects.
QCOMPARE(canvas->areRulersVisible(), false);
QCOMPARE(canvas->areGuidesVisible(), true);
QCOMPARE(canvas->areGuidesLocked(), false);
// Add an opaque red to the swatch.
canvas->setPenForegroundColour(Qt::red);
QVERIFY2(addSwatchWithForegroundColour(), failureMessage);
// Add a translucent red to the swatch.
const QColor translucentRed = QColor::fromRgba(0xaaff0000);
canvas->setPenForegroundColour(translucentRed);
QVERIFY2(addSwatchWithForegroundColour(), failureMessage);
// Having this visible interferes with the rest of the test, and since I'm too lazy
// to check why and it's not necessary to have it open, just close it.
QVERIFY(swatchesPanel->setProperty("expanded", QVariant(false)));
// Temporarily show rulers so we can drag some guides out.
if (!canvas->areRulersVisible()) {
QVERIFY2(triggerRulersVisible(), failureMessage);
QCOMPARE(canvas->areRulersVisible(), true);
}
QQuickItem *firstHorizontalRuler = findChildItem(canvas, "firstHorizontalRuler");
QVERIFY(firstHorizontalRuler);
const qreal rulerThickness = firstHorizontalRuler->height();
// TODO: fix this failure so that we can test it properly
// QVERIFY2(panTopLeftTo(rulerThickness, rulerThickness), failureMessage);
canvas->firstPane()->setIntegerOffset(QPoint(rulerThickness, rulerThickness));
// Drop a horizontal guide onto the canvas.
setCursorPosInPixels(QPoint(50, rulerThickness / 2));
QTest::mouseMove(window, cursorWindowPos);
QTest::mousePress(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
setCursorPosInPixels(QPoint(50, rulerThickness + 10));
QTest::mouseMove(window, cursorWindowPos);
QTest::mouseRelease(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
QCOMPARE(project->guides().size(), 1);
QCOMPARE(project->guides().first().position(), 10);
// Zoom in.
setCursorPosInPixels(QPoint(0, 0));
QVERIFY2(zoomTo(5), failureMessage);
// Ensure that the splitter is not locked.
QCOMPARE(canvas->isSplitScreen(), true);
QVERIFY2(setSplitterLocked(false), failureMessage);
// Resize the first pane to make it smaller.
const QPoint splitterCentre(canvas->width() / 2, canvas->height() / 2);
QTest::mouseMove(window, splitterCentre);
QCOMPARE(window->cursor().shape(), Qt::SplitHCursor);
QTest::mousePress(window, Qt::LeftButton, Qt::NoModifier, splitterCentre);
QTest::mouseMove(window, QPoint(canvas->width() / 4, canvas->height() / 2));
QTest::mouseRelease(window, Qt::LeftButton, Qt::NoModifier, QPoint(canvas->width() / 4, canvas->height() / 2));
QVERIFY(qAbs(canvas->firstPane()->size() - 0.25) < 0.001);
QVERIFY(qAbs(canvas->secondPane()->size() - 0.75) < 0.001);
// Test SplitView state serialisation.
// First, resize the panel column.
QPointer<QQuickItem> panelSplitView = window->findChild<QQuickItem*>("panelSplitView");
QVERIFY(panelSplitView);
const qreal defaultPanelSplitViewWidth = panelSplitView->width();
QPointer<QQuickItem> mainSplitViewHandle = findSplitViewHandle("mainSplitView", 0);
QVERIFY(mainSplitViewHandle);
const QPoint mainSplitViewHandleCentreAfterMoving = QPoint(
panelSplitView->width() / 2 - 10, panelSplitView->height() / 2);
QPoint mainSplitViewHandleCentre;
QVERIFY2(dragSplitViewHandle("mainSplitView", 0,
mainSplitViewHandleCentreAfterMoving, &mainSplitViewHandleCentre), failureMessage);
const qreal resizedPanelSplitViewWidth = panelSplitView->width();
QVERIFY(resizedPanelSplitViewWidth > defaultPanelSplitViewWidth);
// Set these to the opposite of the defaults to tet that they're serialised properly.
QVERIFY2(triggerGuidesVisible(), failureMessage);
QCOMPARE(canvas->areGuidesVisible(), false);
QVERIFY2(triggerRulersVisible(), failureMessage);
QCOMPARE(canvas->areRulersVisible(), false);
QVERIFY2(clickButton(lockGuidesToolButton), failureMessage);
QCOMPARE(canvas->areGuidesLocked(), true);
// Store the expected pane offsets, etc.
// Do it after resizing the splitview to avoid it affecting it.
const QPoint firstPaneOffset = canvas->firstPane()->integerOffset();
const int firstPaneZoomLevel = canvas->firstPane()->integerZoomLevel();
const qreal firstPaneSize = canvas->firstPane()->size();
const QPoint secondPaneOffset = canvas->secondPane()->integerOffset();
const int secondPaneZoomLevel = canvas->secondPane()->integerZoomLevel();
const qreal secondPaneSize = canvas->secondPane()->size();
// Save the project.
const QString savedProjectPath = tempProjectDir->path() + "/saveAsAndLoad-project." + projectExtension;
QVERIFY(project->saveAs(QUrl::fromLocalFile(savedProjectPath)));
QCOMPARE(project->url().toLocalFile(), savedProjectPath);
QCOMPARE(project->modificationVersion().toString(), qApp->applicationVersion());
// Resize the SplitView back to its old proportions so that we
// can check that the state is actually restored,
// as the view won't be destroyed between saving and loading,
// so it will keep its values if we don't do this.
QVERIFY2(dragSplitViewHandle("mainSplitView", 0, mainSplitViewHandleCentre), failureMessage);
// We were getting some failures where the actual was 240.333333333 where the expected was 240.
// Such small differences don't matter.
QCOMPARE(int(panelSplitView->width()), int(defaultPanelSplitViewWidth));
// Close the project.
QVERIFY2(triggerCloseProject(), failureMessage);
QVERIFY(!project->hasLoaded());
// Load the saved file.
QVERIFY2(loadProject(QUrl::fromLocalFile(savedProjectPath)), failureMessage);
QCOMPARE(project->modificationVersion(), QVersionNumber::fromString(qApp->applicationVersion()));
// Test SplitView state serialisation.
panelSplitView = window->findChild<QQuickItem*>("panelSplitView");
QVERIFY(panelSplitView);
QTRY_COMPARE_WITH_TIMEOUT(panelSplitView->width(), resizedPanelSplitViewWidth, 100);
if (projectType == Project::LayeredImageType) {
// Test that the save shortcut works by drawing and then saving.
setCursorPosInScenePixels(0, 0);
QVERIFY2(drawPixelAtCursorPos(), failureMessage);
QVERIFY2(triggerSaveProject(), failureMessage);
QVERIFY(!project->hasUnsavedChanges());
}
// Check guides and panes.
QCOMPARE(project->guides().size(), 1);
QCOMPARE(project->guides().first().position(), 10);
QCOMPARE(canvas->firstPane()->integerOffset(), firstPaneOffset);
QCOMPARE(canvas->firstPane()->integerZoomLevel(), firstPaneZoomLevel);
QCOMPARE(canvas->firstPane()->size(), firstPaneSize);
QCOMPARE(canvas->secondPane()->integerOffset(), secondPaneOffset);
QCOMPARE(canvas->secondPane()->integerZoomLevel(), secondPaneZoomLevel);
QCOMPARE(canvas->secondPane()->size(), secondPaneSize);
QCOMPARE(canvas->areGuidesVisible(), false);
QCOMPARE(canvas->areGuidesLocked(), true);
QCOMPARE(canvas->areRulersVisible(), false);
QVector<SwatchColour> expectedSwatchColours;
expectedSwatchColours.append(SwatchColour(QString(), Qt::red));
expectedSwatchColours.append(SwatchColour(QString(), translucentRed));
if (project->swatch()->colours() != expectedSwatchColours) {
QString message;
QDebug stream(&message);
stream << "\n Actual: " << project->swatch()->colours()
<< "\n Expected: " << expectedSwatchColours;
QFAIL(qPrintable(message));
}
}
enum ValidationCheck {
NoExtraValidation = 0x0,
HasVersion = 0x1,
HasAnimation = 0x2
};
Q_DECLARE_FLAGS(ValidationChecks, ValidationCheck)
Q_DECLARE_METATYPE(ValidationCheck)
Q_DECLARE_METATYPE(ValidationChecks)
void tst_App::versionCheck_data()
{
QTest::addColumn<QString>("projectFileName");
QTest::addColumn<QVersionNumber>("version");
QTest::addColumn<ValidationChecks>("validation");
QTest::newRow("version-check-v0.2.1.slp") << QString::fromLatin1("version-check-v0.2.1.slp")
<< QVersionNumber(0, 2, 1) << ValidationChecks(NoExtraValidation);
QTest::newRow("version-check-v0.8.0.slp") << QString::fromLatin1("version-check-v0.8.0.slp")
<< QVersionNumber(0, 8, 0) << ValidationChecks(NoExtraValidation);
// 0.9 and newer should have a version number saved in the file.
// 0.9 only had one animation. We should support it by converting it to the first animation in our list of animations.
QTest::newRow("version-check-v0.9.0.slp") << QString::fromLatin1("version-check-v0.9.0.slp")
<< QVersionNumber(0, 9, 0) << ValidationChecks(HasVersion | HasAnimation);
}
// Tests that old project files (within reason) can still be loaded.
void tst_App::versionCheck()
{
QFETCH(QString, projectFileName);
QFETCH(QVersionNumber, version);
QFETCH(ValidationChecks, validation);
// Ensure that we have a temporary directory.
if (projectManager->projectTypeForFileName(projectFileName) == Project::LayeredImageType)
QVERIFY2(setupTempLayeredImageProjectDir(), failureMessage);
else
QVERIFY2(setupTempTilesetProjectDir(), failureMessage);
// Copy the project file from resources into our temporary directory.
QVERIFY2(copyFileFromResourcesToTempProjectDir(projectFileName), failureMessage);
// Try to load the project; there shouldn't be any errors.
const QString absolutePath = QDir(tempProjectDir->path()).absoluteFilePath(projectFileName);
QVERIFY2(loadProject(QUrl::fromLocalFile(absolutePath)), failureMessage);
if (validation.testFlag(HasVersion)) {
QCOMPARE(project->creationVersion(), version);
QCOMPARE(project->modificationVersion(), version);
}
if (validation.testFlag(HasAnimation)) {
// Only LayeredImageProject supports saving animations.
QVERIFY(layeredImageProject);
QVERIFY(layeredImageProject->isUsingAnimation());
const auto animationSystem = layeredImageProject->animationSystem();
QCOMPARE(animationSystem->animationCount(), 1);
}
}
void tst_App::loadTilesetProjectWithInvalidTileset()
{
// Set up a temporary directory for the test.
QVERIFY2(setupTempTilesetProjectDir(), failureMessage);
// Copy the files we need to our temporary directory.
const QString projectFileName = QLatin1String("invalid-tileset.stp");
QVERIFY2(copyFileFromResourcesToTempProjectDir(projectFileName), failureMessage);
// Load it. It shouldn't crash.
const QString absolutePath = QDir(tempProjectDir->path()).absoluteFilePath(projectFileName);
const QRegularExpression expectedFailureMessage(QLatin1String("Failed to open project's tileset at /nope/nope/nope"));
QVERIFY2(loadProject(QUrl::fromLocalFile(absolutePath), expectedFailureMessage), failureMessage);
}
// There was an issue where there would be a large gap between
// the swatches and layers panels where the tileset swatch panel
// used to be after switching to an .slp after having an .stp open.
void tst_App::loadLayeredImageProjectAfterTilesetProject()
{
QVERIFY2(createNewTilesetProject(), failureMessage);
QVERIFY2(triggerCloseProject(), failureMessage);
QVERIFY2(createNewLayeredImageProject(), failureMessage);
QQuickItem *layersLoader = window->findChild<QQuickItem*>("layersLoader");
QVERIFY(layersLoader);
QVERIFY(swatchesPanel);
const int splitViewHandleSize = 4;
QTRY_COMPARE(layersLoader->y(), swatchesPanel->y() + swatchesPanel->height() + splitViewHandleSize);
}
void tst_App::loadInvalidProjects_data()
{
QTest::addColumn<QString>("projectFileName");
QTest::addColumn<QRegularExpression>("expectedErrorMessage");
QTest::newRow("loadInvalidProjects-empty.slp")
<< QString::fromLatin1("loadInvalidProjects-empty.slp")
<< QRegularExpression("Layered image project file is missing a \"project\" key.*");
QTest::newRow("loadInvalidProjects-empty.stp")
<< QString::fromLatin1("loadInvalidProjects-empty.stp")
<< QRegularExpression("Tileset project file is missing a \"project\" key.*");
}
void tst_App::loadInvalidProjects()
{
QFETCH(QString, projectFileName);
QFETCH(QRegularExpression, expectedErrorMessage);
// Ensure that we have a temporary directory.
if (projectManager->projectTypeForFileName(projectFileName) == Project::LayeredImageType)
QVERIFY2(setupTempLayeredImageProjectDir(), failureMessage);
else
QVERIFY2(setupTempTilesetProjectDir(), failureMessage);
// Copy the project file from resources into our temporary directory.
QVERIFY2(copyFileFromResourcesToTempProjectDir(projectFileName), failureMessage);
// Try to load the project; there should be an error.
const QString absolutePath = QDir(tempProjectDir->path()).absoluteFilePath(projectFileName);
QVERIFY2(loadProject(QUrl::fromLocalFile(absolutePath), expectedErrorMessage), failureMessage);
}
void tst_App::recentFiles()
{
QVERIFY2(createNewLayeredImageProject(), failureMessage);
// Should be no recent files until the new project is saved.
QObject *recentFilesInstantiator = window->findChild<QObject*>("recentFilesInstantiator");
QVERIFY(recentFilesInstantiator);
QCOMPARE(recentFilesInstantiator->property("count").toInt(), 0);
// Save.
QVERIFY(project->saveAs(QUrl::fromLocalFile(tempProjectDir->path() + "/recentFiles.png")));
QCOMPARE(recentFilesInstantiator->property("count").toInt(), 1);
// Get the recent file menu item from the instantiator and ensure its text is correct.
{
QObject *recentFileMenuItem = nullptr;
QVERIFY(QMetaObject::invokeMethod(recentFilesInstantiator, "objectAt", Qt::DirectConnection,
Q_RETURN_ARG(QObject*, recentFileMenuItem), Q_ARG(int, 0)));
QVERIFY(recentFileMenuItem);
QCOMPARE(recentFileMenuItem->property("text").toString(), project->url().toLocalFile());
}
// Can't click platform types from tests, so clear the recent items manually.
app.settings()->clearRecentFiles();
QCOMPARE(recentFilesInstantiator->property("count").toInt(), 0);
{
QObject *recentFileMenuItem = nullptr;
QVERIFY(QMetaObject::invokeMethod(recentFilesInstantiator, "objectAt", Qt::DirectConnection,
Q_RETURN_ARG(QObject*, recentFileMenuItem), Q_ARG(int, 0)));
QVERIFY(!recentFileMenuItem);
}
}
void tst_App::newProjectSizeFromClipboard_data()
{
QTest::addColumn<Project::Type>("projectType");
QTest::addColumn<QImage>("clipboardImage");
const QImage clipboardImage = ImageUtils::filledImage(100, 200, Qt::red);
QTest::newRow("ImageType, 100x200") << Project::ImageType << clipboardImage;
QTest::newRow("ImageType, (none)") << Project::ImageType << QImage();
QTest::newRow("LayeredImageType, 100x200") << Project::LayeredImageType << clipboardImage;
QTest::newRow("LayeredImageType, (none)") << Project::LayeredImageType << QImage();
}
void tst_App::newProjectSizeFromClipboard()
{
// If there is an image in the clipboard, use it to suggest a project size.
QFETCH(Project::Type, projectType);
QFETCH(QImage, clipboardImage);
qGuiApp->clipboard()->setImage(clipboardImage);
// Don't want to use createNewLayeredImageProject() here, because we need to test the new project popup.
QVERIFY2(triggerNewProject(), failureMessage);
const QObject *newProjectPopup = findOpenPopupFromTypeName("NewProjectPopup");
QVERIFY(newProjectPopup);
QTRY_VERIFY(newProjectPopup->property("opened").toBool());
QVERIFY2(newProjectPopup->property("activeFocus").toBool(),
qPrintable(QString::fromLatin1("NewProjectPopup doesn't have active focus (%1 does)")
.arg(window->activeFocusItem()->objectName())));
QString newProjectButtonObjectName;
if (projectType == Project::ImageType)
newProjectButtonObjectName = QLatin1String("imageProjectButton");
else
newProjectButtonObjectName = QLatin1String("layeredImageProjectButton");
// Click on the appropriate project type button.
QQuickItem *tilesetProjectButton = newProjectPopup->findChild<QQuickItem*>(newProjectButtonObjectName);
QVERIFY(tilesetProjectButton);
QVERIFY2(clickButton(tilesetProjectButton), failureMessage);
QCOMPARE(tilesetProjectButton->property("checked").toBool(), true);
QTRY_COMPARE(newProjectPopup->property("visible").toBool(), false);
// Now the new project popup should be visible.
QObject *newImageProjectPopup = nullptr;
QVERIFY2(ensureNewImageProjectPopupVisible(projectType, &newImageProjectPopup), failureMessage);
// Ensure that the width and height values match the clipboard data.
QQuickItem *imageWidthSpinBox = newImageProjectPopup->findChild<QQuickItem*>("imageWidthSpinBox");
QVERIFY(imageWidthSpinBox);
if (!clipboardImage.isNull())
QCOMPARE(imageWidthSpinBox->property("value").toInt(), clipboardImage.width());
else
QCOMPARE(imageWidthSpinBox->property("value").toInt(), 256);
QQuickItem *imageHeightSpinBox = newImageProjectPopup->findChild<QQuickItem*>("imageHeightSpinBox");
QVERIFY(imageHeightSpinBox);
if (!clipboardImage.isNull())
QCOMPARE(imageHeightSpinBox->property("value").toInt(), clipboardImage.height());
else
QCOMPARE(imageHeightSpinBox->property("value").toInt(), 256);
QTest::keyClick(window, Qt::Key_Escape);
QTRY_VERIFY(!newImageProjectPopup->property("visible").toBool());
}
void tst_App::splitViewStateAcrossProjects()
{
QSKIP("SplitView part fails; TODO: check if still failing with Qt 6");
QVERIFY2(createNewLayeredImageProject(), failureMessage);
// Make the panel split item larger.
QPointer<QQuickItem> mainSplitView = window->findChild<QQuickItem*>("mainSplitView");
QVERIFY(mainSplitView);
QPointer<QQuickItem> panelSplitView = window->findChild<QQuickItem*>("panelSplitView");
QVERIFY(panelSplitView);
const qreal defaultPanelSplitItemWidth = panelSplitView->width();
QPointer<QQuickItem> mainSplitViewHandle = findSplitViewHandle("mainSplitView", 0);
QVERIFY(mainSplitViewHandle);
const QPoint mainSplitViewHandleCentreAfterMoving = QPoint(
mainSplitView->width() / 2, mainSplitView->height() / 2);
QVERIFY2(dragSplitViewHandle("mainSplitView", 0, mainSplitViewHandleCentreAfterMoving), failureMessage);
const qreal resizedPanelSplitItemWidth = panelSplitView->width();
QVERIFY(resizedPanelSplitItemWidth > defaultPanelSplitItemWidth);
// Save the project with the new split size.
QVERIFY(layeredImageProject->canSave());
const QUrl saveUrl = QUrl::fromLocalFile(tempProjectDir->path() + QLatin1String("/splitViewStateAcrossProjects.slp"));
QVERIFY(layeredImageProject->saveAs(saveUrl));
QVERIFY(!layeredImageProject->hasUnsavedChanges());
// Create a new project. It should have the default panel split item size.
QVERIFY2(createNewLayeredImageProject(), failureMessage);
QCOMPARE(panelSplitView->width(), defaultPanelSplitItemWidth);
}
// Tests that saving changes when prompted actually saves those changes.
// Note that we can only test this for projects that were already saved,
// as we can't interact with a native save dialog.
void tst_App::saveOnPrompt()
{
if (offscreenPlatform)
QSKIP("Doesn't work with offscreen platform");
QVERIFY2(createNewLayeredImageProject(), failureMessage);
const QUrl saveUrl = QUrl::fromLocalFile(tempProjectDir->path() + QLatin1String("/saveOnPrompt.slp"));
QVERIFY(layeredImageProject->saveAs(saveUrl));
QVERIFY(!layeredImageProject->hasUnsavedChanges());
setCursorPosInScenePixels(1, 1);
QVERIFY2(drawPixelAtCursorPos(), failureMessage);
QVERIFY2(triggerCloseProject(), failureMessage);
QVERIFY2(saveChanges(), failureMessage);
}
// Tests that pane offset is correctly read from a project file when either coordinate is not a whole number.
void tst_App::loadPaneFractionalOffset()
{
// Ensure that we have a temporary directory.
QVERIFY2(setupTempLayeredImageProjectDir(), failureMessage);
// Copy the project file from resources into our temporary directory.
const QString projectFileName = QLatin1String("loadPaneFractionalOffset.slp");
QVERIFY2(copyFileFromResourcesToTempProjectDir(projectFileName), failureMessage);
// Load the project and make sure the offset is correct.
const QString absolutePath = QDir(tempProjectDir->path()).absoluteFilePath(projectFileName);
const QUrl projectUrl = QUrl::fromLocalFile(absolutePath);
QVERIFY2(loadProject(projectUrl), failureMessage);
QCOMPARE(canvas->firstPane()->offset(), QPointF(257, 235));
}
void tst_App::keyboardShortcuts()
{
QVERIFY2(createNewTilesetProject(), failureMessage);
QTest::keyPress(window, Qt::Key_1);
QCOMPARE(tileCanvas->tool(), TileCanvas::PenTool);
QTest::keyRelease(window, Qt::Key_1);
QCOMPARE(tileCanvas->tool(), TileCanvas::PenTool);
QTest::keyPress(window, Qt::Key_2);
QCOMPARE(tileCanvas->tool(), TileCanvas::EyeDropperTool);
QTest::keyRelease(window, Qt::Key_2);
QCOMPARE(tileCanvas->tool(), TileCanvas::EyeDropperTool);
QTest::keyPress(window, Qt::Key_3);
QCOMPARE(tileCanvas->tool(), TileCanvas::EraserTool);
QTest::keyRelease(window, Qt::Key_3);
QCOMPARE(tileCanvas->tool(), TileCanvas::EraserTool);
// Open the behaviour tab of the options dialog.
QObject *optionsDialog = nullptr;
QVERIFY2(openOptionsTab("behaviourTabButton", &optionsDialog), failureMessage);
// Bring the "New Project" shortcut row into view.
QVERIFY2(ensureScrollViewChildVisible("behaviourScrollView", "newShortcutRow"), failureMessage);
// Give "New Project" shortcut editor focus.
QQuickItem *newShortcutButton = optionsDialog->findChild<QQuickItem*>("newShortcutButton");
QVERIFY(newShortcutButton);
QCOMPARE(newShortcutButton->property("text").toString(), app.settings()->defaultNewShortcut());
QVERIFY2(clickButton(newShortcutButton), failureMessage);
QQuickItem *newShortcutEditor = optionsDialog->findChild<QQuickItem*>("newShortcutEditor");
QVERIFY(newShortcutEditor);
QVERIFY(newShortcutEditor->hasActiveFocus());
// The toolbutton should display the shortcut that has been entered so far (nothing).
QCOMPARE(newShortcutButton->property("text").toString(), QString());
// Begin inputting a shortcut.
QTest::keyClick(window, Qt::Key_M, Qt::ControlModifier);
QCOMPARE(newShortcutButton->property("text").toString(), QLatin1String("Ctrl+M"));
// Cancel editing; shortcut shouldn't have changed.
QTest::keyClick(window, Qt::Key_Escape);
// The dialog should still be visible: QTBUG-57098
QVERIFY(optionsDialog->property("visible").toBool());
QVERIFY(!newShortcutEditor->hasActiveFocus());
QCOMPARE(newShortcutButton->property("text").toString(), app.settings()->defaultNewShortcut());
// Give "New Project" shortcut editor focus again.
QVERIFY2(clickButton(newShortcutButton), failureMessage);
QVERIFY(newShortcutEditor->hasActiveFocus());
// Input another shortcut.
QTest::keyClick(window, Qt::Key_U, Qt::ControlModifier);
QCOMPARE(newShortcutButton->property("text").toString(), QLatin1String("Ctrl+U"));
// Press Enter to accept it.
QTest::keyClick(window, Qt::Key_Return);
QVERIFY(!newShortcutEditor->hasActiveFocus());
QCOMPARE(newShortcutButton->property("text").toString(), QLatin1String("Ctrl+U"));