/
testhelper.cpp
2415 lines (1993 loc) · 97.9 KB
/
testhelper.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 2016, 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 "testhelper.h"
#include <QClipboard>
#include <QPainter>
#include <QLoggingCategory>
#include "imagelayer.h"
#include "projectmanager.h"
#include "utils.h"
Q_LOGGING_CATEGORY(lcTestHelper, "tests.testhelper")
TestHelper::TestHelper(int &argc, char **argv) :
app(argc, argv, QStringLiteral("Slate Test Suite")),
window(qobject_cast<QQuickWindow*>(app.qmlEngine()->rootObjects().first())),
tilesetBasename("test-tileset.png")
{
mTools.append(ImageCanvas::PenTool);
mTools.append(ImageCanvas::EyeDropperTool);
mTools.append(ImageCanvas::EraserTool);
mTools.append(ImageCanvas::FillTool);
mTools.append(ImageCanvas::SelectionTool);/*,
mTools.append(ImageCanvas::CropTool); TODO: not implemented yet*/
allProjectTypes << Project::TilesetType << Project::ImageType << Project::LayeredImageType;
allRightClickBehaviours << ImageCanvas::PenToolRightClickAppliesEraser << ImageCanvas::PenToolRightClickAppliesEyeDropper
<< ImageCanvas::PenToolRightClickAppliesBackgroundColour;
}
TestHelper::~TestHelper()
{
}
void TestHelper::initTestCase()
{
// Tests could have failed on the last run, so just enforce the default settings.
app.settings()->setGridVisible(app.settings()->defaultGridVisible());
QVERIFY(app.settings()->isGridVisible());
app.settings()->setRulersVisible(false);
QVERIFY(!app.settings()->areRulersVisible());
app.settings()->setGuidesLocked(false);
QVERIFY(!app.settings()->areGuidesLocked());
// However, this should never change.
QVERIFY(!app.settings()->loadLastOnStartup());
QVERIFY(window->property("overlay").isValid());
overlay = window->property("overlay").value<QQuickItem*>();
QVERIFY(overlay);
projectManager = app.projectManager();
// Whenever the project manager's project changes, it means we should
// reset our errorOccurred spy, as createNewProject() is about to be called on it.
connect(projectManager.data(), &ProjectManager::temporaryProjectChanged, this, &TestHelper::resetCreationErrorSpy);
// The project would have already been created by now, as a layered image project is always
// loaded by default, so we have to manually create the spy now.
resetCreationErrorSpy();
layeredImageCanvas = window->findChild<LayeredImageCanvas*>("layeredImageCanvas");
QVERIFY(layeredImageCanvas);
project = projectManager->project();
QVERIFY(project);
layeredImageProject = qobject_cast<LayeredImageProject*>(project.data());
QVERIFY(layeredImageProject);
toolBar = window->findChild<QQuickItem*>("toolBar");
QVERIFY(toolBar);
canvasSizeToolButton = window->findChild<QQuickItem*>("canvasSizeToolButton");
QVERIFY(canvasSizeToolButton);
imageSizeToolButton = window->findChild<QQuickItem*>("imageSizeToolButton");
QVERIFY(imageSizeToolButton);
cropToSelectionToolButton = window->findChild<QQuickItem*>("cropToSelectionToolButton");
QVERIFY(cropToSelectionToolButton);
modeToolButton = window->findChild<QQuickItem*>("modeToolButton");
QVERIFY(modeToolButton);
penToolButton = window->findChild<QQuickItem*>("penToolButton");
QVERIFY(penToolButton);
eyeDropperToolButton = window->findChild<QQuickItem*>("eyeDropperToolButton");
QVERIFY(eyeDropperToolButton);
fillToolButton = window->findChild<QQuickItem*>("fillToolButton");
QVERIFY(fillToolButton);
eraserToolButton = window->findChild<QQuickItem*>("eraserToolButton");
QVERIFY(eraserToolButton);
selectionToolButton = window->findChild<QQuickItem*>("selectionToolButton");
QVERIFY(selectionToolButton);
toolSizeButton = window->findChild<QQuickItem*>("toolSizeButton");
QVERIFY(toolSizeButton);
toolShapeButton = window->findChild<QQuickItem*>("toolShapeButton");
QVERIFY(toolShapeButton);
rotate90CcwToolButton = window->findChild<QQuickItem*>("rotate90CcwToolButton");
QVERIFY(rotate90CcwToolButton);
rotate90CwToolButton = window->findChild<QQuickItem*>("rotate90CwToolButton");
QVERIFY(rotate90CwToolButton);
flipHorizontallyToolButton = window->findChild<QQuickItem*>("flipHorizontallyToolButton");
QVERIFY(flipHorizontallyToolButton);
flipVerticallyToolButton = window->findChild<QQuickItem*>("flipVerticallyToolButton");
QVERIFY(flipVerticallyToolButton);
undoToolButton = window->findChild<QQuickItem*>("undoToolButton");
QVERIFY(undoToolButton);
redoToolButton = window->findChild<QQuickItem*>("redoToolButton");
QVERIFY(redoToolButton);
splitScreenToolButton = window->findChild<QQuickItem*>("splitScreenToolButton");
QVERIFY(splitScreenToolButton);
lockSplitterToolButton = window->findChild<QQuickItem*>("lockSplitterToolButton");
QVERIFY(lockSplitterToolButton);
penForegroundColourButton = window->findChild<QQuickItem*>("penForegroundColourButton");
QVERIFY(penForegroundColourButton);
penBackgroundColourButton = window->findChild<QQuickItem*>("penBackgroundColourButton");
QVERIFY(penBackgroundColourButton);
lighterButton = window->findChild<QQuickItem*>("lighterButton");
QVERIFY(lighterButton);
darkerButton = window->findChild<QQuickItem*>("darkerButton");
QVERIFY(darkerButton);
saturateButton = window->findChild<QQuickItem*>("saturateButton");
QVERIFY(saturateButton);
desaturateButton = window->findChild<QQuickItem*>("desaturateButton");
QVERIFY(desaturateButton);
fullScreenToolButton = window->findChild<QQuickItem*>("fullScreenToolButton");
QVERIFY(fullScreenToolButton);
// This is not in a Loader, and hence it is always available.
swatchesPanel = window->findChild<QQuickItem*>("swatchesPanel");
QVERIFY(swatchesPanel);
QPixmap checkerPixmap = QPixmap(":/images/checker.png");
QCOMPARE(checkerPixmap.isNull(), false);
mCheckerImage = checkerPixmap.toImage();
}
void TestHelper::cleanup()
{
failureMessage.clear();
app.settings()->clearRecentFiles();
if (layeredImageProject)
layeredImageProject->setAutoExportEnabled(false);
qGuiApp->clipboard()->setImage(QImage());
}
void TestHelper::resetCreationErrorSpy()
{
if (projectManager->temporaryProject()) {
projectCreationFailedSpy.reset(new QSignalSpy(projectManager, SIGNAL(creationFailed(QString))));
}
}
void TestHelper::mouseEventOnCentre(QQuickItem *item, TestMouseEventType eventType, Qt::MouseButton button)
{
QQuickWindow *itemWindow = item->window();
Q_ASSERT(itemWindow);
const QPoint centre = item->mapToScene(QPointF(item->width() / 2, item->height() / 2)).toPoint();
switch (eventType) {
case MousePress:
QTest::mousePress(itemWindow, button, Qt::NoModifier, centre);
break;
case MouseRelease:
QTest::mouseRelease(itemWindow, button, Qt::NoModifier, centre);
break;
case MouseClick:
QTest::mouseClick(itemWindow, button, Qt::NoModifier, centre);
break;
case MouseDoubleClick:
QTest::mouseDClick(itemWindow, button, Qt::NoModifier, centre);
break;
}
}
void TestHelper::mouseEvent(QQuickItem *item, const QPointF &localPos,
TestMouseEventType eventType, Qt::MouseButton button, Qt::KeyboardModifiers modifiers, int delay)
{
const QPoint centre = item->mapToScene(localPos).toPoint();
switch (eventType) {
case MousePress:
QTest::mousePress(item->window(), button, modifiers, centre, delay);
break;
case MouseRelease:
QTest::mouseRelease(item->window(), button, modifiers, centre, delay);
break;
case MouseClick:
QTest::mouseClick(item->window(), button, modifiers, centre, delay);
break;
case MouseDoubleClick:
QTest::mouseDClick(item->window(), button, modifiers, centre, delay);
break;
}
}
void TestHelper::wheelEvent(QQuickItem *item, const QPoint &localPos, const int degrees)
{
QWheelEvent wheelEvent(localPos, item->window()->mapToGlobal(localPos), QPoint(0, 0), QPoint(0, degrees * 8), 0, Qt::Vertical, Qt::NoButton, 0);
QSpontaneKeyEvent::setSpontaneous(&wheelEvent);
if (!qApp->notify(item->window(), &wheelEvent))
QTest::qWarn("Wheel event not accepted by receiving window");
}
void TestHelper::keyClicks(const QString &text)
{
for (const auto ch : qAsConst(text))
QTest::keySequence(window, QKeySequence(ch));
}
bool TestHelper::clearAndEnterText(QQuickItem *textField, const QString &text)
{
VERIFY(textField->property("text").isValid());
VERIFY(textField->hasActiveFocus());
if (!textField->property("text").toString().isEmpty()) {
QTest::keySequence(window, QKeySequence::SelectAll);
VERIFY(!textField->property("selectedText").toString().isEmpty());
QTest::keySequence(window, QKeySequence::Backspace);
VERIFY(textField->property("text").toString().isEmpty());
}
keyClicks(text);
VERIFY(textField->property("text").toString() == text);
return true;
}
bool TestHelper::changeCanvasSize(int width, int height, CloseDialogFlag closeDialog)
{
// Open the canvas size popup.
mouseEventOnCentre(canvasSizeToolButton, MouseClick);
const QObject *canvasSizePopup = findPopupFromTypeName("CanvasSizePopup");
VERIFY(canvasSizePopup);
TRY_VERIFY2(canvasSizePopup->property("opened").toBool(), "Failed to open CanvasSizePopup");
// Change the values and then cancel.
// TODO: use actual input events...
QQuickItem *widthSpinBox = canvasSizePopup->findChild<QQuickItem*>("changeCanvasWidthSpinBox");
VERIFY(widthSpinBox);
// We want it to be easy to change the values with the keyboard..
VERIFY(widthSpinBox->hasActiveFocus());
const int originalWidthSpinBoxValue = widthSpinBox->property("value").toInt();
VERIFY(widthSpinBox->setProperty("value", originalWidthSpinBoxValue + 1));
VERIFY(widthSpinBox->property("value").toInt() == originalWidthSpinBoxValue + 1);
QQuickItem *heightSpinBox = canvasSizePopup->findChild<QQuickItem*>("changeCanvasHeightSpinBox");
const int originalHeightSpinBoxValue = heightSpinBox->property("value").toInt();
VERIFY(heightSpinBox);
VERIFY(heightSpinBox->setProperty("value", originalHeightSpinBoxValue - 1));
VERIFY(heightSpinBox->property("value").toInt() == originalHeightSpinBoxValue - 1);
QQuickItem *cancelButton = canvasSizePopup->findChild<QQuickItem*>("canvasSizePopupCancelButton");
VERIFY(cancelButton);
mouseEventOnCentre(cancelButton, MouseClick);
TRY_VERIFY2(!canvasSizePopup->property("visible").toBool(), "Failed to cancel CanvasSizePopup");
VERIFY(project->size().width() == originalWidthSpinBoxValue);
VERIFY(project->size().height() == originalHeightSpinBoxValue);
VERIFY(canvas->hasActiveFocus());
// Open the popup again.
mouseEventOnCentre(canvasSizeToolButton, MouseClick);
VERIFY(canvasSizePopup);
TRY_VERIFY2(canvasSizePopup->property("opened").toBool(), "Failed to reopen CanvasSizePopup");
// The old values should be restored.
VERIFY(widthSpinBox->property("value").toInt() == originalWidthSpinBoxValue);
VERIFY(heightSpinBox->property("value").toInt() == originalHeightSpinBoxValue);
VERIFY(widthSpinBox->hasActiveFocus());
// Change the values.
VERIFY(widthSpinBox->setProperty("value", width));
VERIFY(widthSpinBox->property("value").toInt() == width);
VERIFY(heightSpinBox->setProperty("value", height));
VERIFY(heightSpinBox->property("value").toInt() == height);
if (closeDialog == CloseDialog) {
// Press OK to close the dialog.
QQuickItem *okButton = canvasSizePopup->findChild<QQuickItem*>("canvasSizePopupOkButton");
VERIFY(okButton);
mouseEventOnCentre(okButton, MouseClick);
TRY_VERIFY2(!canvasSizePopup->property("visible").toBool(), "Failed to accept CanvasSizePopup");
VERIFY(project->size().width() == width);
VERIFY(project->size().height() == height);
VERIFY(widthSpinBox->property("value").toInt() == width);
VERIFY(heightSpinBox->property("value").toInt() == height);
VERIFY(canvas->hasActiveFocus());
}
return true;
}
bool TestHelper::changeImageSize(int width, int height)
{
// Open the image size popup.
mouseEventOnCentre(imageSizeToolButton, MouseClick);
const QObject *imageSizePopup = findPopupFromTypeName("ImageSizePopup");
VERIFY(imageSizePopup);
VERIFY(imageSizePopup->property("visible").toBool());
// Change the values and then cancel.
// TODO: use actual input events...
QQuickItem *widthSpinBox = imageSizePopup->findChild<QQuickItem*>("changeImageWidthSpinBox");
VERIFY(widthSpinBox);
// We want it to be easy to change the values with the keyboard..
VERIFY(widthSpinBox->hasActiveFocus());
const int originalWidthSpinBoxValue = widthSpinBox->property("value").toInt();
VERIFY(widthSpinBox->setProperty("value", originalWidthSpinBoxValue + 1));
VERIFY(widthSpinBox->property("value").toInt() == originalWidthSpinBoxValue + 1);
QQuickItem *heightSpinBox = imageSizePopup->findChild<QQuickItem*>("changeImageHeightSpinBox");
const int originalHeightSpinBoxValue = heightSpinBox->property("value").toInt();
VERIFY(heightSpinBox);
VERIFY(heightSpinBox->setProperty("value", originalHeightSpinBoxValue - 1));
VERIFY(heightSpinBox->property("value").toInt() == originalHeightSpinBoxValue - 1);
QQuickItem *cancelButton = imageSizePopup->findChild<QQuickItem*>("imageSizePopupCancelButton");
VERIFY(cancelButton);
mouseEventOnCentre(cancelButton, MouseClick);
VERIFY(!imageSizePopup->property("visible").toBool());
VERIFY(project->size().width() == originalWidthSpinBoxValue);
VERIFY(project->size().height() == originalHeightSpinBoxValue);
// Open the popup again.
mouseEventOnCentre(imageSizeToolButton, MouseClick);
VERIFY(imageSizePopup);
VERIFY(imageSizePopup->property("visible").toBool());
// The old values should be restored.
VERIFY(widthSpinBox->property("value").toInt() == originalWidthSpinBoxValue);
VERIFY(heightSpinBox->property("value").toInt() == originalHeightSpinBoxValue);
// Change the values and then press OK.
VERIFY(widthSpinBox->setProperty("value", width));
VERIFY(widthSpinBox->property("value").toInt() == width);
VERIFY(heightSpinBox->setProperty("value", height));
VERIFY(heightSpinBox->property("value").toInt() == height);
QQuickItem *okButton = imageSizePopup->findChild<QQuickItem*>("imageSizePopupOkButton");
VERIFY(okButton);
mouseEventOnCentre(okButton, MouseClick);
VERIFY(!imageSizePopup->property("visible").toBool());
VERIFY(project->size().width() == width);
VERIFY(project->size().height() == height);
VERIFY(widthSpinBox->property("value").toInt() == width);
VERIFY(heightSpinBox->property("value").toInt() == height);
return true;
}
bool TestHelper::changeToolSize(int size)
{
mouseEventOnCentre(toolSizeButton, MouseClick);
const QObject *toolSizePopup = findPopupFromTypeName("ToolSizePopup");
VERIFY(toolSizePopup);
VERIFY(toolSizePopup->property("visible").toBool() == true);
QQuickItem *toolSizeSlider = toolSizePopup->findChild<QQuickItem*>("toolSizeSlider");
VERIFY(toolSizeSlider);
QQuickItem *toolSizeSliderHandle = toolSizeSlider->property("handle").value<QQuickItem*>();
VERIFY(toolSizeSliderHandle);
// Move the slider to the right to find the max pos.
VERIFY(toolSizeSlider->setProperty("value", toolSizeSlider->property("to").toReal()));
VERIFY(toolSizeSlider->property("value") == toolSizeSlider->property("to"));
const QPoint handleMaxPos = toolSizeSliderHandle->mapToScene(
QPointF(toolSizeSliderHandle->width() / 2, toolSizeSliderHandle->height() / 2)).toPoint();
// Move/reset the slider to the left since we move from left to right.
VERIFY(toolSizeSlider->setProperty("value", toolSizeSlider->property("from").toReal()));
VERIFY(toolSizeSlider->property("value") == toolSizeSlider->property("from"));
const QPoint handleMinPos = toolSizeSliderHandle->mapToScene(
QPointF(toolSizeSliderHandle->width() / 2, toolSizeSlider->height() / 2)).toPoint();
QPoint sliderHandlePos = handleMinPos;
QTest::mousePress(toolSizeSlider->window(), Qt::LeftButton, Qt::NoModifier, sliderHandlePos);
VERIFY(toolSizeSlider->property("pressed").toBool() == true);
VERIFY(window->mouseGrabberItem() == toolSizeSlider);
QTest::mouseMove(toolSizeSlider->window(), sliderHandlePos, 5);
// Move the slider's handle until we find the value we want.
for (;
sliderValue(toolSizeSlider) != size && sliderHandlePos.x() < handleMaxPos.x();
++sliderHandlePos.rx()) {
QTest::mouseMove(toolSizeSlider->window(), sliderHandlePos, 5);
}
--sliderHandlePos.rx();
QTest::mouseRelease(toolSizeSlider->window(), Qt::LeftButton, Qt::NoModifier, sliderHandlePos);
VERIFY(toolSizeSlider->property("pressed").toBool() == false);
VERIFY(sliderValue(toolSizeSlider) == size);
// Close the popup.
QTest::keyClick(window, Qt::Key_Escape);
VERIFY(toolSizePopup->property("visible").toBool() == false);
return true;
}
bool TestHelper::changeToolShape(ImageCanvas::ToolShape toolShape)
{
if (canvas->toolShape() == toolShape)
return true;
mouseEventOnCentre(toolShapeButton, MouseClick);
const QObject *toolShapeMenu = window->findChild<QObject*>("toolShapeMenu");
VERIFY(toolShapeMenu);
TRY_VERIFY(toolShapeMenu->property("opened").toBool() == true);
if (toolShape == ImageCanvas::SquareToolShape) {
QQuickItem *squareToolShapeMenuItem = toolShapeMenu->findChild<QQuickItem*>("squareToolShapeMenuItem");
VERIFY(squareToolShapeMenuItem);
mouseEventOnCentre(squareToolShapeMenuItem, MouseClick);
VERIFY(canvas->toolShape() == ImageCanvas::SquareToolShape);
} else {
QQuickItem *circleToolShapeMenuItem = toolShapeMenu->findChild<QQuickItem*>("circleToolShapeMenuItem");
VERIFY(circleToolShapeMenuItem);
mouseEventOnCentre(circleToolShapeMenuItem, MouseClick);
VERIFY(canvas->toolShape() == ImageCanvas::CircleToolShape);
}
return true;
}
bool TestHelper::moveContents(int x, int y, bool onlyVisibleLayers)
{
const QImage originalContents = project->exportedImage();
// Open the move contents dialog.
VERIFY2(triggerShortcut("moveContentsShortcut", app.settings()->moveContentsShortcut()), failureMessage);
const QObject *moveContentsDialog = findPopupFromTypeName("MoveContentsDialog");
VERIFY(moveContentsDialog);
VERIFY(moveContentsDialog->property("visible").toBool());
// Change the values and then cancel.
// TODO: use actual input events...
QQuickItem *moveContentsXSpinBox = moveContentsDialog->findChild<QQuickItem*>("moveContentsXSpinBox");
VERIFY(moveContentsXSpinBox);
// We want it to be easy to change the values with the keyboard..
VERIFY(moveContentsXSpinBox->hasActiveFocus());
const int originalXSpinBoxValue = moveContentsXSpinBox->property("value").toInt();
VERIFY(moveContentsXSpinBox->setProperty("value", originalXSpinBoxValue + 1));
VERIFY(moveContentsXSpinBox->property("value").toInt() == originalXSpinBoxValue + 1);
QQuickItem *moveContentsYSpinBox = moveContentsDialog->findChild<QQuickItem*>("moveContentsYSpinBox");
const int originalYSpinBoxValue = moveContentsYSpinBox->property("value").toInt();
VERIFY(moveContentsYSpinBox);
VERIFY(moveContentsYSpinBox->setProperty("value", originalYSpinBoxValue - 1));
VERIFY(moveContentsYSpinBox->property("value").toInt() == originalYSpinBoxValue - 1);
QQuickItem *cancelButton = moveContentsDialog->findChild<QQuickItem*>("moveContentsDialogCancelButton");
VERIFY(cancelButton);
mouseEventOnCentre(cancelButton, MouseClick);
VERIFY(!moveContentsDialog->property("visible").toBool());
VERIFY(project->exportedImage() == originalContents);
// Open the dialog again.
VERIFY(triggerShortcut("moveContentsShortcut", app.settings()->moveContentsShortcut()));
VERIFY(moveContentsDialog->property("visible").toBool());
// The old values should be restored.
VERIFY(moveContentsXSpinBox->property("value").toInt() == originalXSpinBoxValue);
VERIFY(moveContentsYSpinBox->property("value").toInt() == originalYSpinBoxValue);
// Change the values and then press OK.
VERIFY(moveContentsXSpinBox->setProperty("value", x));
VERIFY(moveContentsXSpinBox->property("value").toInt() == x);
VERIFY(moveContentsYSpinBox->setProperty("value", y));
VERIFY(moveContentsYSpinBox->property("value").toInt() == y);
if (onlyVisibleLayers) {
QQuickItem *onlyMoveVisibleLayersCheckBox = moveContentsDialog->findChild<QQuickItem*>("onlyMoveVisibleLayersCheckBox");
VERIFY(onlyMoveVisibleLayersCheckBox);
if (onlyMoveVisibleLayersCheckBox->property("checked").toBool() != onlyVisibleLayers) {
mouseEventOnCentre(onlyMoveVisibleLayersCheckBox, MouseClick);
VERIFY(onlyMoveVisibleLayersCheckBox->property("checked").toBool() == onlyVisibleLayers);
}
}
QImage movedContents(originalContents.size(), QImage::Format_ARGB32_Premultiplied);
movedContents.fill(Qt::transparent);
QPainter painter(&movedContents);
painter.drawImage(x, y, originalContents);
painter.end();
QQuickItem *okButton = moveContentsDialog->findChild<QQuickItem*>("moveContentsDialogOkButton");
VERIFY(okButton);
mouseEventOnCentre(okButton, MouseClick);
VERIFY(!moveContentsDialog->property("visible").toBool());
VERIFY(project->exportedImage() == movedContents);
VERIFY(moveContentsXSpinBox->property("value").toInt() == x);
VERIFY(moveContentsYSpinBox->property("value").toInt() == y);
return true;
}
int TestHelper::sliderValue(QQuickItem *slider) const
{
const qreal position = slider->property("position").toReal();
qreal value = 0;
QMetaObject::invokeMethod(slider, "valueAt", Qt::DirectConnection, Q_RETURN_ARG(qreal, value), Q_ARG(qreal, position));
return qFloor(value);
}
bool TestHelper::selectColourAtCursorPos()
{
if (tilesetProject) {
FAIL("Not implemented yet");
} else {
if (!switchTool(TileCanvas::EyeDropperTool))
return false;
QTest::mouseMove(window, cursorWindowPos);
QTest::mousePress(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
const QColor actualColour = canvas->penForegroundColour();
const QColor expectedColour = canvas->currentProjectImage()->pixelColor(cursorPos);
VERIFY2(actualColour == expectedColour,
qPrintable(QString::fromLatin1("Expected canvas foreground colour to be %1, but it's %2")
.arg(expectedColour.name(), actualColour.name())));
QTest::mouseRelease(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
}
return true;
}
bool TestHelper::drawPixelAtCursorPos()
{
if (tilesetProject) {
const Tile *targetTile = tilesetProject->tileAt(cursorPos);
VERIFY(targetTile);
if (!switchTool(TileCanvas::PenTool))
return false;
if (!switchMode(TileCanvas::PixelMode))
return false;
// Draw on some pixels of the current tile.
const QImage originalTileImage = targetTile->tileset()->image()->copy(targetTile->sourceRect());
QImage expectedImage = originalTileImage;
expectedImage.setPixelColor(tileCanvas->scenePosToTilePixelPos(cursorPos), tileCanvas->penForegroundColour());
QTest::mouseMove(window, cursorPos);
QTest::mousePress(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
VERIFY(targetTile->tileset()->image()->copy(targetTile->sourceRect()) != originalTileImage);
VERIFY(targetTile->tileset()->image()->copy(targetTile->sourceRect()) == expectedImage);
VERIFY(tilesetProject->hasUnsavedChanges());
// Don't check that the title contains the change marker, as that won't happen
// until release if this is the first change in the stack.
QTest::mouseRelease(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
VERIFY(targetTile->tileset()->image()->copy(targetTile->sourceRect()) == expectedImage);
VERIFY(tilesetProject->hasUnsavedChanges());
VERIFY(window->title().contains("*"));
} else {
if (!switchTool(TileCanvas::PenTool))
return false;
QTest::mouseMove(window, cursorWindowPos);
QTest::mousePress(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
QColor actualColour = canvas->currentProjectImage()->pixelColor(cursorPos);
QColor expectedColour = canvas->penForegroundColour();
if (actualColour != expectedColour) {
QString message;
QDebug stream(&message);
stream << "Expected current project image pixel at" << cursorPos << "to be" << expectedColour.name()
<< "after mouse press, but it's" << actualColour.name();
FAIL(qPrintable(message));
}
VERIFY(project->hasUnsavedChanges());
// Don't check that the title contains the change marker, as that won't happen
// until release if this is the first change in the stack.
QTest::mouseRelease(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
if (actualColour != expectedColour) {
QString message;
QDebug stream(&message);
stream << "Expected current project image pixel at" << cursorPos << "to be" << expectedColour.name()
<< "after mouse release, but it's" << actualColour.name();
FAIL(qPrintable(message));
}
VERIFY(project->hasUnsavedChanges());
VERIFY(window->title().contains("*"));
}
return true;
}
bool TestHelper::drawTileAtCursorPos()
{
if (!switchTool(TileCanvas::PenTool))
return false;
if (!switchMode(TileCanvas::TileMode))
return false;
QTest::mouseMove(window, cursorWindowPos);
QTest::mousePress(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
QTest::mouseRelease(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
const int penId = tileCanvas->penTile()->id();
const Tile *tile = tilesetProject->tileAt(cursorPos);
VERIFY(tile);
VERIFY(tile->id() == penId);
return true;
}
bool TestHelper::selectArea(const QRect &area)
{
// Switch to the selection tool.
if (!switchTool(ImageCanvas::SelectionTool))
return false;
if (canvas->hasSelection()) {
failureMessage = "Can't select area when there's already an existing selection";
return false;
}
// Select the area.
setCursorPosInScenePixels(area.topLeft());
QTest::mousePress(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
// If area is {0, 0, 5, 5}, we need to move to {x=5, y=5} to ensure
// that we've selected all 5x5 pixels.
setCursorPosInScenePixels(area.bottomRight() + QPoint(1, 1));
QTest::mouseMove(window, cursorWindowPos);
QTest::mouseRelease(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
VERIFY(canvas->hasSelection());
VERIFY(canvas->selectionArea() == area);
return true;
}
bool TestHelper::dragSelection(const QPoint &newTopLeft)
{
if (!canvas->hasSelection()) {
failureMessage = "No selection to drag";
return false;
}
const QRect oldSelectionArea = canvas->selectionArea();
QRect newSelectionArea = oldSelectionArea;
newSelectionArea.moveTo(newTopLeft);
setCursorPosInScenePixels(canvas->selectionArea().topLeft());
QTest::mouseMove(window, cursorWindowPos);
QTest::mousePress(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
setCursorPosInScenePixels(newTopLeft);
QTest::mouseMove(window, cursorWindowPos);
QTest::mouseRelease(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
VERIFY(canvas->selectionArea() == newSelectionArea);
return true;
}
static QString fuzzyColourCompareFailMsg(const QColor &colour1, const QColor &colour2,
const QChar &componentName, int difference, int fuzz)
{
return QString::fromLatin1("colour1 %1 is not equal to colour2 %2; %3 difference of %4 is larger than fuzz of %5")
.arg(colour1.name()).arg(colour2.name()).arg(componentName).arg(difference).arg(fuzz);
}
bool TestHelper::fuzzyColourCompare(const QColor &colour1, const QColor &colour2, int fuzz)
{
const int rDiff = qAbs(colour2.red() - colour1.red());
VERIFY2(rDiff <= fuzz, qPrintable(fuzzyColourCompareFailMsg(colour1, colour2, QLatin1Char('r'), rDiff, fuzz)));
const int gDiff = qAbs(colour2.green() - colour1.green());
VERIFY2(gDiff <= fuzz, qPrintable(fuzzyColourCompareFailMsg(colour1, colour2, QLatin1Char('g'), gDiff, fuzz)));
const int bDiff = qAbs(colour2.blue() - colour1.blue());
VERIFY2(bDiff <= fuzz, qPrintable(fuzzyColourCompareFailMsg(colour1, colour2, QLatin1Char('b'), bDiff, fuzz)));
const int aDiff = qAbs(colour2.alpha() - colour1.alpha());
VERIFY2(aDiff <= fuzz, qPrintable(fuzzyColourCompareFailMsg(colour1, colour2, QLatin1Char('a'), aDiff, fuzz)));
return true;
}
bool TestHelper::fuzzyImageCompare(const QImage &image1, const QImage &image2)
{
VERIFY(image1.size() == image2.size());
for (int y = 0; y < image1.height(); ++y) {
for (int x = 0; x < image1.width(); ++x) {
if (!fuzzyColourCompare(image1.pixelColor(x, y), image2.pixelColor(x, y)))
return false;
}
}
return true;
}
bool TestHelper::everyPixelIs(const QImage &image, const QColor &colour)
{
for (int y = 0; y < image.size().height(); ++y) {
for (int x = 0; x < image.size().width(); ++x) {
if (image.pixelColor(x, y) != colour) {
QString message;
QDebug debug(&message);
debug.nospace() << "Expected every pixel of " << image << " to be " << colour
<< ", but pixel at " << x << ", " << y << " is " << image.pixelColor(x, y);
failureMessage = message.toLatin1();
return false;
}
}
}
return true;
}
bool TestHelper::compareSwatches(const Swatch &actualSwatch, const Swatch &expectedSwatch)
{
if (actualSwatch.colours() == expectedSwatch.colours())
return true;
QString message;
message = "Swatches are not equal:";
message += "\n actual ";
QDebug(&message) << actualSwatch.colours();
message += "\nexpected ";
QDebug(&message) << expectedSwatch.colours();
failureMessage = qPrintable(message);
return false;
}
bool TestHelper::enableAutoSwatch()
{
// The swatches panel is hidden by default when testing; see updateVariables().
if (!togglePanel("swatchesPanel", true))
return false;
// Wait until the previous view is destroyed (if any).
TRY_VERIFY(!window->findChild<QQuickItem*>("autoSwatchGridView"));
// Sanity check.
VERIFY(!app.settings()->isAutoSwatchEnabled());
// Enable auto swatch.
app.settings()->setAutoSwatchEnabled(true);
return true;
}
bool TestHelper::swatchViewDelegateExists(const QQuickItem *viewContentItem, const QColor &colour)
{
const auto childItems = viewContentItem->childItems();
for (const QQuickItem *delegateItem : childItems) {
if (delegateItem->property("color").value<QColor>() == colour)
return true;
}
QString message;
QDebug debug(&message);
debug.nospace() << "Couldn't find a delegate in swatch view content item " << viewContentItem
<< " whose contentItem colour is " << colour;
failureMessage = message.toLatin1();
return false;
}
QQuickItem *TestHelper::findSwatchViewDelegateAtIndex(int index)
{
QQuickItem *swatchGridView = window->findChild<QQuickItem*>("swatchGridView");
if (!swatchGridView)
return nullptr;
return findViewDelegateAtIndex(swatchGridView, index);
}
bool TestHelper::addSwatchWithForegroundColour()
{
// Roll back to the previous value in case of test failure.
const bool oldExpandedValue = swatchesPanel->property("expanded").toBool();
Utils::ScopeGuard swatchPanelExpandedGuard([=](){
swatchesPanel->setProperty("expanded", oldExpandedValue);
});
swatchesPanel->setProperty("expanded", true);
QQuickItem *swatchGridView = window->findChild<QQuickItem*>("swatchGridView");
VERIFY(swatchGridView);
VERIFY(QMetaObject::invokeMethod(swatchGridView, "forceLayout"));
QQuickItem *viewContentItem = swatchGridView->property("contentItem").value<QQuickItem*>();
VERIFY(viewContentItem);
const int previousDelegateCount = swatchGridView->property("count").toInt();
const QString expectedDelegateObjectName = QString::fromLatin1("swatchGridView_Delegate_%1_%2")
.arg(previousDelegateCount).arg(canvas->penForegroundColour().name(QColor::HexArgb));
// Add the swatch.
QQuickItem *newSwatchColourButton = window->findChild<QQuickItem*>("newSwatchColourButton");
VERIFY(newSwatchColourButton);
mouseEventOnCentre(newSwatchColourButton, MouseClick);
VERIFY(QMetaObject::invokeMethod(swatchGridView, "forceLayout"));
VERIFY2(swatchGridView->property("count").toInt() == previousDelegateCount + 1,
qPrintable(QString::fromLatin1("Expected %1 swatch delegates after adding one, but there are %2")
.arg(previousDelegateCount + 1).arg(swatchGridView->property("count").toInt())));
// findChild() doesn't work here for some reason.
const auto childItems = viewContentItem->childItems();
QQuickItem *swatchDelegate = nullptr;
for (const auto childItem : qAsConst(childItems)) {
if (childItem->objectName() == expectedDelegateObjectName) {
swatchDelegate = childItem;
break;
}
}
if (!swatchDelegate) {
QString message;
QDebug stream(&message);
stream.nospace() << "Expected a swatch delegate to exist named " << expectedDelegateObjectName
<< " but there wasn't. Swatch delegates: " << viewContentItem->childItems();
FAIL(qPrintable(message));
}
return true;
}
bool TestHelper::renameSwatchColour(int index, const QString &name)
{
// Open the context menu by right clicking on the delegate.
QQuickItem *delegate = findSwatchViewDelegateAtIndex(index);
VERIFY(delegate);
mouseEventOnCentre(delegate, MouseClick, Qt::RightButton);
QObject *swatchContextMenu = findPopupFromTypeName("SwatchContextMenu");
VERIFY(swatchContextMenu);
TRY_VERIFY(swatchContextMenu->property("opened").toBool());
// Select the rename menu item.
QQuickItem *renameSwatchColourMenuItem = window->findChild<QQuickItem*>("renameSwatchColourMenuItem");
VERIFY(renameSwatchColourMenuItem);
// TODO: mouse event isn't getting through to the menu item without this.
// This is likely caused by https://codereview.qt-project.org/#/c/225747/
// and is probably the same issue encountered in the tests there.
// Replace with Qt API if https://bugreports.qt.io/browse/QTBUG-71224 ever gets done.
QTest::qWait(50);
mouseEventOnCentre(renameSwatchColourMenuItem, MouseClick);
TRY_VERIFY(!swatchContextMenu->property("opened").toBool());
QObject *renameSwatchColourDialog = findPopupFromTypeName("RenameSwatchColourDialog");
VERIFY(renameSwatchColourDialog);
TRY_VERIFY(renameSwatchColourDialog->property("opened").toBool());
// Do the renaming.
QQuickItem *swatchNameTextField = window->findChild<QQuickItem*>("swatchNameTextField");
VERIFY(swatchNameTextField);
VERIFY2(clearAndEnterText(swatchNameTextField, name), failureMessage);
QTest::keyClick(window, Qt::Key_Return);
TRY_VERIFY(!renameSwatchColourDialog->property("opened").toBool());
return true;
}
bool TestHelper::deleteSwatchColour(int index)
{
// Open the context menu by right clicking on the delegate.
QQuickItem *delegate = findSwatchViewDelegateAtIndex(index);
VERIFY(delegate);
mouseEventOnCentre(delegate, MouseClick, Qt::RightButton);
QObject *swatchContextMenu = findPopupFromTypeName("SwatchContextMenu");
VERIFY(swatchContextMenu);
TRY_VERIFY(swatchContextMenu->property("opened").toBool());
QQuickItem *deleteSwatchColourMenuItem = window->findChild<QQuickItem*>("deleteSwatchColourMenuItem");
VERIFY(deleteSwatchColourMenuItem);
mouseEventOnCentre(deleteSwatchColourMenuItem, MouseClick);
TRY_VERIFY(!swatchContextMenu->property("opened").toBool());
return true;
}
bool TestHelper::addNewGuide(Qt::Orientation orientation, int position)
{
if (!app.settings()->areRulersVisible()) {
if (!triggerRulersVisible())
return false;
VERIFY(app.settings()->areRulersVisible());
}
const bool horizontal = orientation == Qt::Horizontal;
const int originalGuideCount = project->guides().size();
const int newGuideIndex = originalGuideCount;
const QPoint originalOffset = canvas->currentPane()->integerOffset();
const qreal originalZoomLevel = canvas->currentPane()->zoomLevel();
QQuickItem *ruler = canvas->findChild<QQuickItem*>(horizontal
? "firstHorizontalRuler" : "firstVerticalRuler");
VERIFY(ruler);
const qreal rulerThickness = horizontal ? ruler->height() : ruler->width();
// Pan so that the top left of the canvas is at the rulers' corners.
if (!panTopLeftTo(rulerThickness, rulerThickness))
return false;
canvas->currentPane()->setZoomLevel(1.0);
// Drop a horizontal guide onto the canvas.
const QPoint pressPos(
horizontal ? 50 : rulerThickness / 2,
horizontal ? rulerThickness / 2 : 50);
setCursorPosInPixels(pressPos);
QTest::mouseMove(window, cursorWindowPos);
VERIFY(!canvas->pressedRuler());
QTest::mousePress(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
VERIFY(canvas->pressedRuler());
// Do the actual moving onto the canvas.
const QPoint releasePos(
horizontal ? 50 : rulerThickness + position,
horizontal ? rulerThickness + position : 50);
setCursorPosInPixels(releasePos);
QTest::mouseMove(window, cursorWindowPos);
// Now it should be visible on the canvas.
VERIFY(imageGrabber.requestImage(canvas));
TRY_VERIFY(imageGrabber.isReady());
const QImage grabWithGuide = imageGrabber.takeImage();
VERIFY(grabWithGuide.pixelColor(releasePos.x(), releasePos.y()) == QColor(Qt::cyan));
QTest::mouseRelease(window, Qt::LeftButton, Qt::NoModifier, cursorWindowPos);
VERIFY(!canvas->pressedRuler());
VERIFY2(project->guides().size() == originalGuideCount + 1, qPrintable(QString::fromLatin1(
"Expected %1 guide(s), but got %2").arg(originalGuideCount + 1).arg(project->guides().size())));
VERIFY(project->guides().at(newGuideIndex).position() == position);
VERIFY(project->undoStack()->canUndo());
canvas->currentPane()->setOffset(originalOffset);
canvas->currentPane()->setZoomLevel(originalZoomLevel);
return true;
}
QObject *TestHelper::findPopupFromTypeName(const QString &typeName) const
{
QObject *popup = nullptr;
foreach (QQuickItem *child, overlay->childItems()) {
if (QString::fromLatin1(child->metaObject()->className()) == "QQuickPopupItem") {
if (QString::fromLatin1(child->parent()->metaObject()->className()).contains(typeName)) {
popup = child->parent();
break;
}
}
}
return popup;
}
QQuickItem *TestHelper::findDialogButtonFromText(const QObject *dialog, const QString &text)
{
QQuickItem *footer = dialog->property("footer").value<QQuickItem*>();
if (!footer)
return nullptr;
return findChildWithText(footer, text);
}
QQuickItem *TestHelper::findDialogButtonFromObjectName(const QObject *dialog, const QString &objectName)
{
QQuickItem *footer = dialog->property("footer").value<QQuickItem*>();
if (!footer)
return nullptr;
return footer->findChild<QQuickItem*>(objectName);
}
QQuickItem *TestHelper::findListViewChild(QQuickItem *listView, const QString &childObjectName) const
{