-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathcapturewidget.cpp
More file actions
2073 lines (1881 loc) · 66.3 KB
/
capturewidget.cpp
File metadata and controls
2073 lines (1881 loc) · 66.3 KB
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
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
// Based on Lightscreen areadialog.cpp, Copyright 2017 Christian Kaiser
// <info@ckaiser.com.ar> released under the GNU GPL2
// <https://www.gnu.org/licenses/gpl-2.0.txt>
// Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007
// Luca Gugelmann <lucag@student.ethz.ch> released under the GNU LGPL
// <http://www.gnu.org/licenses/old-licenses/library.txt>
#include "capturewidget.h"
#include "abstractlogger.h"
#include "copytool.h"
#include "src/config/cacheutils.h"
#include "src/core/flameshot.h"
#include "src/core/qguiappcurrentscreen.h"
#include "src/utils/screengrabber.h"
#include "src/utils/screenshotsaver.h"
#include "src/utils/systemnotification.h"
#include "src/widgets/capture/colorpicker.h"
#include "src/widgets/capture/hovereventfilter.h"
#include "src/widgets/capture/modificationcommand.h"
#include "src/widgets/capture/notifierbox.h"
#include "src/widgets/capture/overlaymessage.h"
#include "src/widgets/orientablepushbutton.h"
#include "src/widgets/panel/sidepanelwidget.h"
#include "src/widgets/panel/utilitypanel.h"
#include <QApplication>
#include <QCheckBox>
#include <QDateTime>
#include <QFontMetrics>
#include <QMessageBox>
#include <QPaintEvent>
#include <QPainter>
#include <QScreen>
#include <QShortcut>
#include <QWindow>
#include <draggablewidgetmaker.h>
#if !defined(DISABLE_UPDATE_CHECKER)
#include "src/widgets/updatenotificationwidget.h"
#endif
#define MOUSE_DISTANCE_TO_START_MOVING 3
// CaptureWidget is the main component used to capture the screen. It contains
// an area of selection with its respective buttons.
// enableSaveWindow
CaptureWidget::CaptureWidget(const CaptureRequest& req,
bool fullScreen,
QWidget* parent)
: QWidget(parent)
, m_toolSizeByKeyboard(0)
, m_mouseIsClicked(false)
, m_captureDone(false)
, m_previewEnabled(true)
, m_adjustmentButtonPressed(false)
, m_configError(false)
, m_configErrorResolved(false)
#if !defined(DISABLE_UPDATE_CHECKER)
, m_updateNotificationWidget(nullptr)
#endif
, m_lastMouseWheel(0)
, m_activeButton(nullptr)
, m_activeTool(nullptr)
, m_activeToolIsMoved(false)
, m_toolWidget(nullptr)
, m_panel(nullptr)
, m_sidePanel(nullptr)
, m_colorPicker(nullptr)
, m_selection(nullptr)
, m_magnifier(nullptr)
, m_xywhDisplay(false)
, m_existingObjectIsChanged(false)
, m_startMove(false)
, m_clipboardWorkaroundDone(false)
{
m_undoStack.setUndoLimit(ConfigHandler().undoLimit());
m_context.circleCount = 1;
// Base config of the widget
m_eventFilter = new HoverEventFilter(this);
connect(m_eventFilter,
&HoverEventFilter::hoverIn,
this,
&CaptureWidget::childEnter);
connect(m_eventFilter,
&HoverEventFilter::hoverOut,
this,
&CaptureWidget::childLeave);
connect(&m_xywhTimer, &QTimer::timeout, this, &CaptureWidget::xywhTick);
// else xywhTick keeps triggering when not needed
m_xywhTimer.setSingleShot(true);
setAttribute(Qt::WA_DeleteOnClose);
setAttribute(Qt::WA_QuitOnClose, false);
m_opacity = m_config.contrastOpacity();
m_uiColor = m_config.uiColor();
m_contrastUiColor = m_config.contrastUiColor();
setMouseTracking(true);
initContext(fullScreen, req);
ScreenGrabber grabber;
QScreen* selectedScreen = nullptr;
#if (defined(Q_OS_WIN) || defined(Q_OS_MACOS))
// Top left of the whole set of screens
QPoint topLeft(0, 0);
#endif
if (fullScreen) {
bool ok = true;
int preSelectedMonitor;
if (req.hasSelectedMonitor()) {
preSelectedMonitor = req.selectedMonitor();
} else {
preSelectedMonitor = -1;
}
m_context.screenshot =
grabber.grabEntireDesktop(ok, preSelectedMonitor);
if (!ok) {
// Error already logged in ScreenGrabber
this->close();
}
m_context.origScreenshot = m_context.screenshot;
selectedScreen = grabber.getSelectedScreen();
#if defined(Q_OS_WIN)
#if !defined(FLAMESHOT_DEBUG_CAPTURE)
setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint |
Qt::SubWindow // Hides the taskbar icon
);
#endif
// Position the window at the selected screen's position
// (or the topLeft of all screens if no specific screen was selected)
if (selectedScreen) {
move(selectedScreen->geometry().topLeft());
} else {
for (QScreen* const screen : QGuiApplication::screens()) {
QPoint topLeftScreen = screen->geometry().topLeft();
if (topLeftScreen.x() < topLeft.x()) {
topLeft.setX(topLeftScreen.x());
}
if (topLeftScreen.y() < topLeft.y()) {
topLeft.setY(topLeftScreen.y());
}
}
move(topLeft);
}
// On Windows, account for DPR when sizing the window
QSize windowSize = pixmap().size();
if (pixmap().devicePixelRatio() > 1.0) {
windowSize = QSize(pixmap().width() / pixmap().devicePixelRatio(),
pixmap().height() / pixmap().devicePixelRatio());
}
resize(windowSize);
if (selectedScreen != nullptr && windowHandle()) {
windowHandle()->setScreen(selectedScreen);
}
#elif defined(Q_OS_MACOS)
QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen();
move(currentScreen->geometry().x(), currentScreen->geometry().y());
resize(currentScreen->size());
// LINUX
#else
// Call cmake with -DFLAMESHOT_DEBUG_CAPTURE=ON to enable easier debugging
#if !defined(FLAMESHOT_DEBUG_CAPTURE)
// Note: Qt::BypassWindowManagerHint is removed to fix x11 gnome crash
setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint |
Qt::Tool);
#endif
// Always display on the selected screen (not spanning entire desktop)
if (selectedScreen == nullptr) {
selectedScreen = QGuiApplication::primaryScreen();
}
QRect screenGeom = selectedScreen->geometry();
move(screenGeom.topLeft());
resize(screenGeom.size());
if (selectedScreen != nullptr && windowHandle()) {
windowHandle()->setScreen(selectedScreen);
}
#endif
}
QVector<QRect> areas;
if (m_context.fullscreen) {
// Always display on a single screen, normalized to (0, 0)
QScreen* screenForAreas = selectedScreen;
if (!screenForAreas) {
screenForAreas = QGuiAppCurrentScreen().currentScreen();
}
if (!screenForAreas) {
screenForAreas = QGuiApplication::primaryScreen();
}
QRect r = screenForAreas ? screenForAreas->geometry() : QRect();
r.moveTo(0, 0);
areas.append(r);
} else {
areas.append(rect());
}
m_buttonHandler = new ButtonHandler(this);
m_buttonHandler->updateScreenRegions(areas);
m_buttonHandler->hide();
initButtons();
initSelection(); // button handler must be initialized before
initShortcuts(); // must be called after initSelection
// init magnify
if (m_config.showMagnifier()) {
m_magnifier = new MagnifierWidget(
m_context.screenshot, m_uiColor, m_config.squareMagnifier(), this);
}
// Init color picker
m_colorPicker = new ColorPicker(this);
// Init notification widget
m_notifierBox = new NotifierBox(this);
initPanel();
// TODO: Make it more clear why this has moved. In Qt6 some timing related
// to constructors / connect signals has changed so if initPanel is called
// after the connect a SEGFAULT occurs
connect(m_colorPicker,
&ColorPicker::colorSelected,
this,
[this](const QColor& c) {
m_context.mousePos = mapFromGlobal(QCursor::pos());
setDrawColor(c);
});
m_colorPicker->hide();
// Init tool size sigslots
connect(this,
&CaptureWidget::toolSizeChanged,
this,
&CaptureWidget::onToolSizeChanged);
m_notifierBox->hide();
connect(m_notifierBox, &NotifierBox::hidden, this, [this]() {
// Show cursor if it was hidden while adjusting tool size
updateCursor();
m_toolSizeByKeyboard = 0;
onToolSizeChanged(m_context.toolSize);
onToolSizeSettled(m_context.toolSize);
});
m_config.checkAndHandleError();
if (m_config.hasError()) {
m_configError = true;
}
connect(
ConfigHandler::getInstance(), &ConfigHandler::error, this, [=, this]() {
m_configError = true;
m_configErrorResolved = false;
OverlayMessage::instance()->update();
});
connect(ConfigHandler::getInstance(),
&ConfigHandler::errorResolved,
this,
[=, this]() {
m_configError = false;
m_configErrorResolved = true;
OverlayMessage::instance()->update();
});
// OverlayMessage is a child widget, so use widget-local coordinates
// In fullscreen mode, use the normalized area; otherwise use widget rect
QRect overlayArea =
m_context.fullscreen && !areas.isEmpty() ? areas.first() : rect();
OverlayMessage::init(this, overlayArea);
if (m_config.showHelp()) {
initHelpMessage();
OverlayMessage::push(m_helpMessage);
}
initQuitPrompt();
updateCursor();
}
CaptureWidget::~CaptureWidget()
{
#if defined(Q_OS_MACOS)
for (QWidget* widget : qApp->topLevelWidgets()) {
QString className(widget->metaObject()->className());
if (0 ==
className.compare(CaptureWidget::staticMetaObject.className())) {
widget->showNormal();
widget->hide();
break;
}
}
#endif
if (m_captureDone) {
auto lastRegion = m_selection->geometry();
const qreal scale = m_context.screenshot.devicePixelRatio();
lastRegion.setTop(lastRegion.top() * scale);
lastRegion.setBottom(lastRegion.bottom() * scale);
lastRegion.setLeft(lastRegion.left() * scale);
lastRegion.setRight(lastRegion.right() * scale);
setLastRegion(lastRegion);
QRect geometry(m_context.selection);
geometry.setTopLeft(geometry.topLeft() + m_context.widgetOffset);
Flameshot::instance()->exportCapture(
pixmap(), geometry, m_context.request);
} else {
emit Flameshot::instance()->captureFailed();
}
}
void CaptureWidget::initButtons()
{
auto allButtonTypes = CaptureToolButton::getIterableButtonTypes();
auto visibleButtonTypes = m_config.buttons();
if ((m_context.request.tasks() == CaptureRequest::NO_TASK) ||
(m_context.request.tasks() == CaptureRequest::PRINT_GEOMETRY)) {
allButtonTypes.removeOne(CaptureTool::TYPE_ACCEPT);
visibleButtonTypes.removeOne(CaptureTool::TYPE_ACCEPT);
} else {
// Remove irrelevant buttons from both lists
for (auto* buttonList : { &allButtonTypes, &visibleButtonTypes }) {
buttonList->removeOne(CaptureTool::TYPE_SAVE);
buttonList->removeOne(CaptureTool::TYPE_COPY);
#ifdef ENABLE_IMGUR
buttonList->removeOne(CaptureTool::TYPE_IMAGEUPLOADER);
#endif
buttonList->removeOne(CaptureTool::TYPE_OPEN_APP);
buttonList->removeOne(CaptureTool::TYPE_PIN);
}
}
QVector<CaptureToolButton*> vectorButtons;
// Add all buttons but hide those that were disabled in the Interface config
// This will allow keyboard shortcuts for those buttons to work
for (CaptureTool::Type t : allButtonTypes) {
auto* b = new CaptureToolButton(t, this);
b->setColor(m_uiColor);
b->hide();
// must be enabled for SelectionWidget's eventFilter to work correctly
b->setAttribute(Qt::WA_NoMousePropagation);
makeChild(b);
switch (t) {
case CaptureTool::TYPE_UNDO:
case CaptureTool::TYPE_REDO:
// nothing to do, just skip non-dynamic buttons with existing
// hard coded slots
break;
default:
// Set shortcuts for a tool
QString shortcut =
ConfigHandler().shortcut(QVariant::fromValue(t).toString());
if (!shortcut.isNull()) {
auto shortcuts = newShortcut(shortcut, this, nullptr);
for (auto* sc : shortcuts) {
connect(sc, &QShortcut::activated, this, [=, this]() {
setState(b);
});
}
}
break;
}
m_tools[t] = b->tool();
connect(b->tool(),
&CaptureTool::requestAction,
this,
&CaptureWidget::handleToolSignal);
if (visibleButtonTypes.contains(t)) {
connect(b,
&CaptureToolButton::pressedButtonLeftClick,
this,
&CaptureWidget::handleButtonLeftClick);
if (b->tool()->isSelectable()) {
connect(b,
&CaptureToolButton::pressedButtonRightClick,
this,
&CaptureWidget::handleButtonRightClick);
}
vectorButtons << b;
}
}
m_buttonHandler->setButtons(vectorButtons);
}
void CaptureWidget::handleButtonRightClick(CaptureToolButton* b)
{
if (!b) {
return;
}
// if button already selected, do not deselect it on right click
if (!m_activeButton || m_activeButton != b) {
setState(b);
}
if (!m_panel->isVisible()) {
m_panel->show();
}
}
void CaptureWidget::handleButtonLeftClick(CaptureToolButton* b)
{
if (!b) {
return;
}
setState(b);
}
void CaptureWidget::xywhTick()
{
m_xywhDisplay = false;
update();
}
void CaptureWidget::onDisplayGridChanged(bool display)
{
m_displayGrid = display;
repaint();
}
void CaptureWidget::onGridSizeChanged(int size)
{
m_gridSize = size;
repaint();
}
void CaptureWidget::startColorGrab()
{
if (m_sidePanel) {
m_sidePanel->startColorGrab();
}
}
void CaptureWidget::showxywh()
{
m_xywhDisplay = true;
update();
int timeout = m_config.showSelectionGeometryHideTime();
if (timeout != 0) {
m_xywhTimer.start(timeout);
}
}
void CaptureWidget::initHelpMessage()
{
QList<QPair<QString, QString>> keyMap;
keyMap << std::pair(tr("Mouse"), tr("Select screenshot area"));
using CT = CaptureTool;
for (auto toolType : { CT::TYPE_ACCEPT, CT::TYPE_SAVE, CT::TYPE_COPY }) {
if (!m_tools.contains(toolType)) {
continue;
}
auto* tool = m_tools[toolType];
QString shortcut =
ConfigHandler().shortcut(QVariant::fromValue(toolType).toString());
shortcut.replace("Return", "Enter");
if (!shortcut.isEmpty()) {
keyMap << std::pair(shortcut, tool->description());
}
}
keyMap << std::pair(tr("Mouse Wheel"), tr("Change tool size"));
keyMap << std::pair(tr("Right Click"), tr("Show color picker"));
keyMap << std::pair(ConfigHandler().shortcut("TYPE_TOGGLE_PANEL"),
tr("Open side panel"));
keyMap << std::pair(tr("Esc"), tr("Exit"));
m_helpMessage = OverlayMessage::compileFromKeyMap(keyMap);
}
QPixmap CaptureWidget::pixmap()
{
return m_context.selectedScreenshotArea();
}
// Finish whatever the current tool is doing, if there is a current active
// tool.
bool CaptureWidget::commitCurrentTool()
{
if (m_activeTool) {
processPixmapWithTool(&m_context.screenshot, m_activeTool);
if (m_activeTool->isValid() && !m_activeTool->editMode() &&
m_toolWidget) {
pushToolToStack();
}
if (m_toolWidget) {
m_toolWidget->update();
}
releaseActiveTool();
return true;
}
return false;
}
void CaptureWidget::initQuitPrompt()
{
m_quitPrompt = new QMessageBox;
makeChild(m_quitPrompt);
QString baseSheet = "QDialog { background-color: %1; }"
"QLabel, QCheckBox { color: %2 }"
"QPushButton { background-color: %1; color: %2 }";
QColor text = ColorUtils::colorIsDark(m_uiColor) ? Qt::white : Qt::black;
QString styleSheet = baseSheet.arg(m_uiColor.name(), text.name());
m_quitPrompt->setStyleSheet(styleSheet);
m_quitPrompt->setWindowTitle(tr("Quit Capture"));
m_quitPrompt->setText(tr("Are you sure you want to quit capture?"));
m_quitPrompt->setIcon(QMessageBox::Icon::Question);
m_quitPrompt->setStandardButtons(QMessageBox::Yes | QMessageBox::No);
m_quitPrompt->setDefaultButton(QMessageBox::No);
auto* check = new QCheckBox(tr("Do not show this again"));
m_quitPrompt->setCheckBox(check);
// Call show() first, otherwise the correct geometry cannot be fetched
// for centering the window on the screen
m_quitPrompt->show();
QRect position = m_quitPrompt->frameGeometry();
QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen();
position.moveCenter(currentScreen->availableGeometry().center());
m_quitPrompt->move(position.topLeft());
m_quitPrompt->hide();
QObject::connect(check, &QCheckBox::clicked, [](bool checked) {
ConfigHandler().setShowQuitPrompt(!checked);
});
}
bool CaptureWidget::promptQuit()
{
return m_quitPrompt->exec() == QMessageBox::Yes;
}
void CaptureWidget::deleteToolWidgetOrClose()
{
if (m_activeButton != nullptr) {
uncheckActiveTool();
} else if (m_panel->activeLayerIndex() >= 0) {
// remove active tool selection
m_panel->setActiveLayer(-1);
} else if (m_panel->isVisible()) {
// hide panel if visible
m_panel->hide();
} else if (m_toolWidget) {
// delete toolWidget if exists
m_toolWidget->hide();
delete m_toolWidget;
m_toolWidget = nullptr;
} else if (m_colorPicker && m_colorPicker->isVisible()) {
m_colorPicker->hide();
} else {
// close CaptureWidget
if (m_config.showQuitPrompt()) {
// need to show prompt
if (m_quitPrompt->isHidden() && promptQuit()) {
close();
}
} else {
close();
}
}
}
void CaptureWidget::releaseActiveTool()
{
if (m_activeTool) {
if (m_activeTool->editMode()) {
// Object shouldn't be deleted here because it is in the undo/redo
// stack, just set current pointer to null
m_activeTool->setEditMode(false);
if (m_activeTool->isChanged()) {
pushObjectsStateToUndoStack();
}
} else {
delete m_activeTool;
}
m_activeTool = nullptr;
}
if (m_toolWidget) {
m_toolWidget->hide();
delete m_toolWidget;
m_toolWidget = nullptr;
}
}
void CaptureWidget::uncheckActiveTool()
{
// uncheck active tool
m_panel->setToolWidget(nullptr);
m_activeButton->setColor(m_uiColor);
updateTool(activeButtonTool());
m_activeButton = nullptr;
releaseActiveTool();
updateSelectionState();
updateCursor();
}
void CaptureWidget::closeEvent(QCloseEvent* event)
{
#if !(defined(Q_OS_MACOS) || defined(Q_OS_WIN))
/* GNOME copy problem workaround, copy
operation seems to work only when there
is a visible window to retrieve the
data from. On GNOME, the GUI should
handle the copy operation, not the
daemon.
*/
const bool copyRequested =
(m_context.request.tasks() & CaptureRequest::COPY);
if (m_captureDone && copyRequested) {
DesktopInfo desktopInfo;
const bool needGnomeWorkaround =
desktopInfo.waylandDetected() &&
desktopInfo.windowManager() == DesktopInfo::GNOME;
if (needGnomeWorkaround && !m_clipboardWorkaroundDone) {
event->ignore();
m_clipboardWorkaroundDone = true;
m_context.request.removeTask(CaptureRequest::COPY);
AbstractLogger::info()
<< "GNOME Wayland detected; keeping capture window alive until "
"clipboard data is fetched.";
saveToClipboardGnomeWorkaround(pixmap(), this);
return;
}
}
#endif
QWidget::closeEvent(event);
}
void CaptureWidget::paintEvent(QPaintEvent* paintEvent)
{
Q_UNUSED(paintEvent)
QPainter painter(this);
if (!painter.isActive()) {
return;
}
GeneralConf::xywh_position position =
static_cast<GeneralConf::xywh_position>(m_config.showSelectionGeometry());
/* QPainter::save and restore is somewhat costly so we try to guess
if we need to do it here. What that means is that if you add
anything to the paintEvent and want to save/restore you should
add a test to the below if statement -- also if you change
any of the conditions that current trigger it you'll need to change here,
too
*/
bool save = false;
if (m_xywhDisplay || // clause 1: xywh display
m_displayGrid || // clause 2: display grid
(m_activeTool && m_mouseIsClicked) || // clause 3: tool/click
(m_previewEnabled && activeButtonTool() && // clause 4: mouse preview
m_activeButton->tool()->showMousePreview())) {
painter.save();
save = true;
}
painter.drawPixmap(0, 0, m_context.screenshot);
if (m_selection && m_xywhDisplay) {
const QRect& selection = m_selection->geometry().normalized();
const qreal scale = m_context.screenshot.devicePixelRatio();
QRect xybox;
QFontMetrics fm = painter.fontMetrics();
QString xy =
QString("%1x%2+%3+%4")
.arg(QString::number(static_cast<int>(selection.width() * scale)),
QString::number(static_cast<int>(selection.height() * scale)),
QString::number(static_cast<int>(selection.left() * scale)),
QString::number(static_cast<int>(selection.top() * scale)));
xybox = fm.boundingRect(xy);
// the small numbers here are just margins so the text doesn't
// smack right up to the box; they aren't critical and the box
// size itself is tied to the font metrics
xybox.adjust(0, 0, 10, 12);
// in anticipation of making the position adjustable
int x0, y0;
// Move these to header
switch (position) {
case GeneralConf::xywh_top_left:
x0 = selection.left();
y0 = selection.top();
break;
case GeneralConf::xywh_bottom_left:
x0 = selection.left();
y0 = selection.bottom() - xybox.height();
break;
case GeneralConf::xywh_top_right:
x0 = selection.right() - xybox.width();
y0 = selection.top();
break;
case GeneralConf::xywh_bottom_right:
x0 = selection.right() - xybox.width();
y0 = selection.bottom() - xybox.height();
break;
case GeneralConf::xywh_center:
default:
x0 = selection.left() + (selection.width() - xybox.width()) / 2;
y0 =
selection.top() + (selection.height() - xybox.height()) / 2;
}
QColor uicolor = ConfigHandler().uiColor();
uicolor.setAlpha(200);
painter.fillRect(
x0, y0, xybox.width(), xybox.height(), QBrush(uicolor));
painter.setPen(ColorUtils::colorIsDark(uicolor) ? Qt::white
: Qt::black);
painter.drawText(x0,
y0,
xybox.width(),
xybox.height(),
Qt::AlignVCenter | Qt::AlignHCenter,
xy);
}
if (m_displayGrid) {
QColor uicolor = ConfigHandler().uiColor();
uicolor.setAlpha(100);
painter.setPen(uicolor);
painter.setBrush(QBrush(uicolor));
const auto scale{ m_context.screenshot.devicePixelRatio() };
auto topLeft = mapToGlobal(m_context.selection.topLeft() / scale);
topLeft.rx() -= topLeft.x() % m_gridSize;
topLeft.ry() -= topLeft.y() % m_gridSize;
topLeft = mapFromGlobal(topLeft);
const auto step{ m_gridSize / scale };
const auto radius{ 1 * scale };
for (int y = topLeft.y(); y < m_context.selection.bottom() / scale;
y += step) {
for (int x = topLeft.x(); x < m_context.selection.right() / scale;
x += step) {
painter.drawEllipse(x, y, radius, radius);
}
}
}
if (m_activeTool && m_mouseIsClicked) {
m_activeTool->process(painter, m_context.screenshot);
} else if (m_previewEnabled && activeButtonTool() &&
m_activeButton->tool()->showMousePreview()) {
m_activeButton->tool()->paintMousePreview(painter, m_context);
}
if (save)
painter.restore();
// draw inactive region
drawInactiveRegion(&painter);
if (!isActiveWindow()) {
drawErrorMessage(
tr("Flameshot has lost focus. Keyboard shortcuts won't "
"work until you click somewhere."),
&painter);
} else if (m_configError) {
drawErrorMessage(ConfigHandler().errorMessage(), &painter);
} else if (m_configErrorResolved) {
drawErrorMessage(tr("Configuration error resolved. Launch `flameshot "
"gui` again to apply it."),
&painter);
}
}
void CaptureWidget::showColorPicker(const QPoint& pos)
{
// Try to select new object if current pos out of active object
auto toolItem = activeToolObject();
if (!toolItem || (toolItem && !toolItem->boundingRect().contains(pos))) {
selectToolItemAtPos(pos);
}
// save current state for undo/redo stack
if (m_panel->activeLayerIndex() >= 0) {
m_captureToolObjectsBackup = m_captureToolObjects;
}
// Call color picker
m_colorPicker->move(pos.x() - m_colorPicker->width() / 2,
pos.y() - m_colorPicker->height() / 2);
m_colorPicker->raise();
m_colorPicker->show();
}
bool CaptureWidget::startDrawObjectTool(const QPoint& pos)
{
if (activeButtonToolType() != CaptureTool::NONE &&
activeButtonToolType() != CaptureTool::TYPE_MOVESELECTION) {
if (commitCurrentTool()) {
return false;
}
m_activeTool = m_activeButton->tool()->copy(this);
connect(this,
&CaptureWidget::colorChanged,
m_activeTool,
&CaptureTool::onColorChanged);
connect(this,
&CaptureWidget::toolSizeChanged,
m_activeTool,
&CaptureTool::onSizeChanged);
connect(m_activeTool,
&CaptureTool::requestAction,
this,
&CaptureWidget::handleToolSignal);
m_context.mousePos = m_displayGrid ? snapToGrid(pos) : pos;
m_activeTool->drawStart(m_context);
// TODO this is the wrong place to do this
if (m_activeTool->type() == CaptureTool::TYPE_CIRCLECOUNT) {
m_activeTool->setCount(m_context.circleCount++);
}
return true;
}
return false;
}
void CaptureWidget::pushObjectsStateToUndoStack()
{
m_undoStack.push(new ModificationCommand(
this, m_captureToolObjects, m_captureToolObjectsBackup));
m_captureToolObjectsBackup.clear();
}
int CaptureWidget::selectToolItemAtPos(const QPoint& pos)
{
// Try to select existing tool, "-1" - no active tool
int activeLayerIndex = -1;
auto selectionMouseSide = m_selection->getMouseSide(pos);
if (m_activeButton.isNull() &&
m_captureToolObjects.captureToolObjects().size() > 0 &&
(selectionMouseSide == SelectionWidget::NO_SIDE ||
selectionMouseSide == SelectionWidget::CENTER)) {
auto toolItem = activeToolObject();
if (!toolItem ||
(toolItem && !toolItem->boundingRect().contains(pos))) {
activeLayerIndex = m_captureToolObjects.find(pos, size());
int oldToolSize = m_context.toolSize;
m_panel->setActiveLayer(activeLayerIndex);
drawObjectSelection();
if (oldToolSize != m_context.toolSize) {
emit toolSizeChanged(m_context.toolSize);
}
}
}
return activeLayerIndex;
}
void CaptureWidget::mousePressEvent(QMouseEvent* e)
{
activateWindow();
m_startMove = false;
m_startMovePos = QPoint();
m_mousePressedPos = e->pos();
m_activeToolOffsetToMouseOnStart = QPoint();
if (m_colorPicker->isVisible()) {
updateCursor();
return;
}
// reset object selection if capture area selection is active
if (m_selection->getMouseSide(e->pos()) != SelectionWidget::CENTER) {
m_panel->setActiveLayer(-1);
}
if (e->button() == Qt::RightButton) {
if (m_activeTool && m_activeTool->editMode()) {
return;
}
showColorPicker(m_mousePressedPos);
return;
} else if (e->button() == Qt::LeftButton) {
m_mouseIsClicked = true;
// Click using a tool excluding tool MOVE
if (startDrawObjectTool(m_mousePressedPos)) {
// return if success
return;
}
}
// Commit current tool if it has edit widget and mouse click is outside
// of it
if (m_toolWidget && !m_toolWidget->geometry().contains(e->pos())) {
commitCurrentTool();
m_panel->setToolWidget(nullptr);
drawToolsData();
updateLayersPanel();
}
selectToolItemAtPos(m_mousePressedPos);
updateSelectionState();
updateCursor();
}
void CaptureWidget::mouseDoubleClickEvent(QMouseEvent* event)
{
int activeLayerIndex = m_panel->activeLayerIndex();
if (activeLayerIndex != -1) {
// Start object editing
auto activeTool = m_captureToolObjects.at(activeLayerIndex);
if (activeTool && activeTool->type() == CaptureTool::TYPE_TEXT) {
m_activeTool = activeTool;
m_mouseIsClicked = false;
m_context.mousePos = *m_activeTool->pos();
m_captureToolObjectsBackup = m_captureToolObjects;
m_activeTool->setEditMode(true);
drawToolsData();
updateLayersPanel();
handleToolSignal(CaptureTool::REQ_ADD_CHILD_WIDGET);
if (!m_activeTool.isNull()) {
m_panel->setToolWidget(m_activeTool->configurationWidget());
}
}
} else if (m_selection->geometry().contains(event->pos())) {
if ((event->button() == Qt::LeftButton) &&
(m_config.copyOnDoubleClick())) {
CopyTool copyTool;
connect(©Tool,
&CopyTool::requestAction,
this,
&CaptureWidget::handleToolSignal);
copyTool.pressed(m_context);
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}
}
}
void CaptureWidget::mouseMoveEvent(QMouseEvent* e)
{
if (m_magnifier) {
if (!m_activeButton) {
m_magnifier->show();
m_magnifier->update();
} else {
m_magnifier->hide();
}
}
m_context.mousePos = e->pos();
if (e->buttons() != Qt::LeftButton) {
updateTool(activeButtonTool());
updateCursor();
return;
}
// The rest assumes that left mouse button is clicked
if (!m_activeButton && m_panel->activeLayerIndex() >= 0) {
// Move existing object
if (!m_startMove) {
// Check for the minimal offset to start moving an object
if (m_startMovePos.isNull()) {
m_startMovePos = e->pos();
}
if ((e->pos() - m_startMovePos).manhattanLength() >
MOUSE_DISTANCE_TO_START_MOVING) {
m_startMove = true;
}
}
if (m_startMove) {
QPointer<CaptureTool> activeTool =
m_captureToolObjects.at(m_panel->activeLayerIndex());
if (m_activeToolOffsetToMouseOnStart.isNull()) {
setCursor(Qt::ClosedHandCursor);
m_activeToolOffsetToMouseOnStart =
e->pos() - *activeTool->pos();
}
if (!m_activeToolIsMoved) {
// save state before movement for undo stack
m_captureToolObjectsBackup = m_captureToolObjects;
}
m_activeToolIsMoved = true;
// update the old region of the selection, margins are added to
// ensure selection outline is updated too
update(paddedUpdateRect(activeTool->boundingRect()));
activeTool->move(e->pos() - m_activeToolOffsetToMouseOnStart);
drawToolsData();
}
} else if (m_activeTool) {
// drawing with a tool
if (m_adjustmentButtonPressed) {
m_activeTool->drawMoveWithAdjustment(e->pos());
} else {
m_activeTool->drawMove(m_displayGrid ? snapToGrid(e->pos())