id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
2,686
utilitypanel.cpp
flameshot-org_flameshot/src/widgets/panel/utilitypanel.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "utilitypanel.h" #include "capturewidget.h" #include <QHBoxLayout> #include <QListWidget> #include <QPropertyAnimation> #include <QPushButton> #include <QScrollArea> #include <QTimer> UtilityPanel::UtilityPanel(CaptureWidget* captureWidget) : QWidget(captureWidget) , m_captureWidget(captureWidget) , m_internalPanel(nullptr) , m_upLayout(nullptr) , m_bottomLayout(nullptr) , m_layout(nullptr) , m_showAnimation(nullptr) , m_hideAnimation(nullptr) , m_layersLayout(nullptr) , m_captureTools(nullptr) , m_buttonDelete(nullptr) , m_buttonMoveUp(nullptr) , m_buttonMoveDown(nullptr) { initInternalPanel(); setAttribute(Qt::WA_TransparentForMouseEvents); setCursor(Qt::ArrowCursor); m_showAnimation = new QPropertyAnimation(m_internalPanel, "geometry", this); m_showAnimation->setEasingCurve(QEasingCurve::InOutQuad); m_showAnimation->setDuration(300); m_hideAnimation = new QPropertyAnimation(m_internalPanel, "geometry", this); m_hideAnimation->setEasingCurve(QEasingCurve::InOutQuad); m_hideAnimation->setDuration(300); connect(m_hideAnimation, &QPropertyAnimation::finished, m_internalPanel, &QWidget::hide); #if (defined(Q_OS_WIN) || defined(Q_OS_MACOS)) move(0, 0); #endif hide(); } QWidget* UtilityPanel::toolWidget() const { return m_toolWidget; } void UtilityPanel::setToolWidget(QWidget* widget) { if (m_toolWidget != nullptr) { m_toolWidget->hide(); m_toolWidget->setParent(this); m_toolWidget->deleteLater(); } if (widget != nullptr) { m_toolWidget = widget; m_toolWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); m_upLayout->addWidget(widget); } } void UtilityPanel::clearToolWidget() { if (m_toolWidget != nullptr) { m_toolWidget->deleteLater(); } } void UtilityPanel::pushWidget(QWidget* widget) { m_layout->insertWidget(m_layout->count() - 1, widget); } void UtilityPanel::show() { setAttribute(Qt::WA_TransparentForMouseEvents, false); m_showAnimation->setStartValue(QRect(-width(), 0, 0, height())); m_showAnimation->setEndValue(QRect(0, 0, width(), height())); m_internalPanel->show(); m_showAnimation->start(); #if (defined(Q_OS_WIN) || defined(Q_OS_MACOS)) move(0, 0); #endif QWidget::show(); } void UtilityPanel::hide() { setAttribute(Qt::WA_TransparentForMouseEvents); m_hideAnimation->setStartValue(QRect(0, 0, width(), height())); m_hideAnimation->setEndValue(QRect(-width(), 0, 0, height())); m_hideAnimation->start(); m_internalPanel->hide(); QWidget::hide(); } void UtilityPanel::toggle() { if (m_internalPanel->isHidden()) { show(); } else { hide(); } } void UtilityPanel::initInternalPanel() { m_internalPanel = new QScrollArea(this); m_internalPanel->setAttribute(Qt::WA_NoMousePropagation); auto* widget = new QWidget(); m_internalPanel->setWidget(widget); m_internalPanel->setWidgetResizable(true); m_layout = new QVBoxLayout(); m_upLayout = new QVBoxLayout(); m_bottomLayout = new QVBoxLayout(); m_layersLayout = new QVBoxLayout(); m_layout->addLayout(m_upLayout); m_layout->addLayout(m_bottomLayout); m_bottomLayout->addLayout(m_layersLayout); widget->setLayout(m_layout); QColor bgColor = palette().window().color(); bgColor.setAlphaF(0.0); m_internalPanel->setStyleSheet( QStringLiteral("QScrollArea {background-color: %1}").arg(bgColor.name())); m_internalPanel->hide(); m_captureTools = new QListWidget(this); connect(m_captureTools, &QListWidget::currentRowChanged, this, &UtilityPanel::onCurrentRowChanged); auto* layersButtons = new QHBoxLayout(); m_layersLayout->addLayout(layersButtons); m_layersLayout->addWidget(m_captureTools); bool isDark = ColorUtils::colorIsDark(bgColor); QString coloredIconPath = isDark ? PathInfo::whiteIconPath() : PathInfo::blackIconPath(); m_buttonDelete = new QPushButton(this); m_buttonDelete->setIcon(QIcon(coloredIconPath + "delete.svg")); m_buttonDelete->setMinimumWidth(m_buttonDelete->height()); m_buttonDelete->setDisabled(true); m_buttonMoveUp = new QPushButton(this); m_buttonMoveUp->setIcon(QIcon(coloredIconPath + "move_up.svg")); m_buttonMoveUp->setMinimumWidth(m_buttonMoveUp->height()); m_buttonMoveUp->setDisabled(true); m_buttonMoveDown = new QPushButton(this); m_buttonMoveDown->setIcon(QIcon(coloredIconPath + "move_down.svg")); m_buttonMoveDown->setMinimumWidth(m_buttonMoveDown->height()); m_buttonMoveDown->setDisabled(true); layersButtons->addWidget(m_buttonDelete); layersButtons->addWidget(m_buttonMoveUp); layersButtons->addWidget(m_buttonMoveDown); layersButtons->addStretch(); connect(m_buttonDelete, &QPushButton::clicked, this, &UtilityPanel::slotButtonDelete); connect(m_buttonMoveUp, &QPushButton::clicked, this, &UtilityPanel::slotUpClicked); connect(m_buttonMoveDown, &QPushButton::clicked, this, &UtilityPanel::slotDownClicked); // Bottom auto* closeButton = new QPushButton(this); closeButton->setText(tr("Close")); connect(closeButton, &QPushButton::clicked, this, &UtilityPanel::toggle); m_bottomLayout->addWidget(closeButton); } void UtilityPanel::fillCaptureTools( const QList<QPointer<CaptureTool>>& captureToolObjects) { int currentSelection = m_captureTools->currentRow(); m_captureTools->clear(); m_captureTools->addItem(tr("<Empty>")); for (auto toolItem : captureToolObjects) { auto* item = new QListWidgetItem( toolItem->icon(QColor(Qt::white), false), toolItem->info()); m_captureTools->addItem(item); } if (currentSelection >= 0 && currentSelection < m_captureTools->count()) { m_captureTools->setCurrentRow(currentSelection); } } void UtilityPanel::setActiveLayer(int index) { Q_ASSERT(index >= -1); m_captureTools->setCurrentRow(index + 1); } int UtilityPanel::activeLayerIndex() { return m_captureTools->currentRow() >= 0 ? m_captureTools->currentRow() - 1 : -1; } void UtilityPanel::onCurrentRowChanged(int currentRow) { m_buttonDelete->setDisabled(currentRow <= 0); m_buttonMoveDown->setDisabled(currentRow == 0 || currentRow + 1 == m_captureTools->count()); m_buttonMoveUp->setDisabled(currentRow <= 1); emit layerChanged(activeLayerIndex()); } void UtilityPanel::slotUpClicked(bool clicked) { Q_UNUSED(clicked); // subtract 1 because there's <empty> in m_captureTools as [0] element int toolRow = m_captureTools->currentRow() - 1; m_captureTools->setCurrentRow(toolRow); emit moveUpClicked(toolRow); } void UtilityPanel::slotDownClicked(bool clicked) { Q_UNUSED(clicked); // subtract 1 because there's <empty> in m_captureTools as [0] element int toolRow = m_captureTools->currentRow() - 1; m_captureTools->setCurrentRow(toolRow + 2); emit moveDownClicked(toolRow); } void UtilityPanel::slotButtonDelete(bool clicked) { Q_UNUSED(clicked) int currentRow = m_captureTools->currentRow(); if (currentRow > 0) { m_captureWidget->removeToolObject(currentRow); if (currentRow >= m_captureTools->count()) { currentRow = m_captureTools->count() - 1; } } else { currentRow = 0; } m_captureTools->setCurrentRow(currentRow); } bool UtilityPanel::isVisible() const { return !m_internalPanel->isHidden(); }
7,948
C++
.cpp
232
29.021552
80
0.690414
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,687
colorgrabwidget.cpp
flameshot-org_flameshot/src/widgets/panel/colorgrabwidget.cpp
#include "colorgrabwidget.h" #include "sidepanelwidget.h" #include "colorutils.h" #include "confighandler.h" #include "overlaymessage.h" #include "src/core/qguiappcurrentscreen.h" #include <QApplication> #include <QDebug> #include <QKeyEvent> #include <QPainter> #include <QScreen> #include <QShortcut> #include <QTimer> #include <stdexcept> // Width (= height) and zoom level of the widget before the user clicks #define WIDTH1 77 #define ZOOM1 11 // Width (= height) and zoom level of the widget after the user clicks #define WIDTH2 165 #define ZOOM2 15 // NOTE: WIDTH1(2) should be divisible by ZOOM1(2) for best precision. // WIDTH1 should be odd so the cursor can be centered on a pixel. ColorGrabWidget::ColorGrabWidget(QPixmap* p, QWidget* parent) : QWidget(parent) , m_pixmap(p) , m_mousePressReceived(false) , m_extraZoomActive(false) , m_magnifierActive(false) { if (p == nullptr) { throw std::logic_error("Pixmap must not be null"); } setAttribute(Qt::WA_DeleteOnClose); // We don't need this widget to receive mouse events because we use // eventFilter on other objects that do setAttribute(Qt::WA_TransparentForMouseEvents); setAttribute(Qt::WA_QuitOnClose, false); // On Windows: don't activate the widget so CaptureWidget remains active setAttribute(Qt::WA_ShowWithoutActivating); setWindowFlags(Qt::BypassWindowManagerHint | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus); setMouseTracking(true); } void ColorGrabWidget::startGrabbing() { // NOTE: grabMouse() would prevent move events being received // With this method we just need to make sure that mouse press and release // events get consumed before they reach their target widget. // This is undone in the destructor. qApp->setOverrideCursor(Qt::CrossCursor); qApp->installEventFilter(this); OverlayMessage::pushKeyMap( { { tr("Enter or Left Click"), tr("Accept color") }, { tr("Hold Left Click"), tr("Precisely select color") }, { tr("Space or Right Click"), tr("Toggle magnifier") }, { tr("Esc"), tr("Cancel") } }); } QColor ColorGrabWidget::color() { return m_color; } bool ColorGrabWidget::eventFilter(QObject*, QEvent* event) { // Consume shortcut events and handle key presses from whole app if (event->type() == QEvent::KeyPress || event->type() == QEvent::Shortcut) { QKeySequence key = event->type() == QEvent::KeyPress ? static_cast<QKeyEvent*>(event)->key() : static_cast<QShortcutEvent*>(event)->key(); if (key == Qt::Key_Escape) { emit grabAborted(); finalize(); } else if (key == Qt::Key_Return || key == Qt::Key_Enter) { emit colorGrabbed(m_color); finalize(); } else if (key == Qt::Key_Space && !m_extraZoomActive) { setMagnifierActive(!m_magnifierActive); } return true; } else if (event->type() == QEvent::MouseMove) { // NOTE: This relies on the fact that CaptureWidget tracks mouse moves if (m_extraZoomActive && !geometry().contains(cursorPos())) { setExtraZoomActive(false); return true; } if (!m_extraZoomActive && !m_magnifierActive) { // This fixes an issue when the mouse leaves the zoom area before // the widget even appears. hide(); } if (!m_extraZoomActive) { // Update only before the user clicks the mouse, after the mouse // press the widget remains static. updateWidget(); } // Hide overlay message when cursor is over it OverlayMessage* overlayMsg = OverlayMessage::instance(); overlayMsg->setVisibility( !overlayMsg->geometry().contains(cursorPos())); m_color = getColorAtPoint(cursorPos()); emit colorUpdated(m_color); return true; } else if (event->type() == QEvent::MouseButtonPress) { m_mousePressReceived = true; auto* e = static_cast<QMouseEvent*>(event); if (e->buttons() == Qt::RightButton) { setMagnifierActive(!m_magnifierActive); } else if (e->buttons() == Qt::LeftButton) { setExtraZoomActive(true); } return true; } else if (event->type() == QEvent::MouseButtonRelease) { if (!m_mousePressReceived) { // Do not consume event if it corresponds to the mouse press that // triggered the color grabbing in the first place. This prevents // focus issues in the capture widget when the color grabber is // closed. return false; } auto* e = static_cast<QMouseEvent*>(event); if (e->button() == Qt::LeftButton && m_extraZoomActive) { emit colorGrabbed(getColorAtPoint(cursorPos())); finalize(); } return true; } else if (event->type() == QEvent::MouseButtonDblClick) { return true; } return false; } void ColorGrabWidget::paintEvent(QPaintEvent*) { QPainter painter(this); painter.drawImage(QRectF(0, 0, width(), height()), m_previewImage); } void ColorGrabWidget::showEvent(QShowEvent*) { updateWidget(); } QPoint ColorGrabWidget::cursorPos() const { return QCursor::pos(QGuiAppCurrentScreen().currentScreen()); } /// @note The point is in screen coordinates. QColor ColorGrabWidget::getColorAtPoint(const QPoint& p) const { if (m_extraZoomActive && geometry().contains(p)) { QPoint point = mapFromGlobal(p); // we divide coordinate-wise to avoid rounding to nearest return m_previewImage.pixel( QPoint(point.x() / ZOOM2, point.y() / ZOOM2)); } QPoint point = p; #if defined(Q_OS_MACOS) QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen(); if (currentScreen) { point = QPoint((p.x() - currentScreen->geometry().x()) * currentScreen->devicePixelRatio(), (p.y() - currentScreen->geometry().y()) * currentScreen->devicePixelRatio()); } #endif QPixmap pixel = m_pixmap->copy(QRect(point, point)); return pixel.toImage().pixel(0, 0); } void ColorGrabWidget::setExtraZoomActive(bool active) { m_extraZoomActive = active; if (!active && !m_magnifierActive) { hide(); } else { if (!isVisible()) { QTimer::singleShot(250, this, [this]() { show(); }); } else { QTimer::singleShot(250, this, [this]() { updateWidget(); }); } } } void ColorGrabWidget::setMagnifierActive(bool active) { m_magnifierActive = active; setVisible(active); } void ColorGrabWidget::updateWidget() { int width = m_extraZoomActive ? WIDTH2 : WIDTH1; float zoom = m_extraZoomActive ? ZOOM2 : ZOOM1; // Set window size and move its center to the mouse cursor QRect rect(0, 0, width, width); auto realCursorPos = cursorPos(); auto adjustedCursorPos = realCursorPos; #if defined(Q_OS_MACOS) QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen(); if (currentScreen) { adjustedCursorPos = QPoint((realCursorPos.x() - currentScreen->geometry().x()) * currentScreen->devicePixelRatio(), (realCursorPos.y() - currentScreen->geometry().y()) * currentScreen->devicePixelRatio()); } #endif rect.moveCenter(cursorPos()); setGeometry(rect); // Store a pixmap containing the zoomed-in section around the cursor QRect sourceRect(0, 0, width / zoom, width / zoom); sourceRect.moveCenter(adjustedCursorPos); m_previewImage = m_pixmap->copy(sourceRect).toImage(); // Repaint update(); } void ColorGrabWidget::finalize() { qApp->removeEventFilter(this); qApp->restoreOverrideCursor(); OverlayMessage::pop(); close(); }
8,032
C++
.cpp
217
30.520737
78
0.644983
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,688
modificationcommand.cpp
flameshot-org_flameshot/src/widgets/capture/modificationcommand.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "modificationcommand.h" #include "capturewidget.h" ModificationCommand::ModificationCommand( CaptureWidget* captureWidget, const CaptureToolObjects& captureToolObjects, const CaptureToolObjects& captureToolObjectsBackup) : m_captureWidget(captureWidget) { m_captureToolObjects = captureToolObjects; m_captureToolObjectsBackup = captureToolObjectsBackup; } void ModificationCommand::undo() { m_captureWidget->setCaptureToolObjects(m_captureToolObjectsBackup); } void ModificationCommand::redo() { m_captureWidget->setCaptureToolObjects(m_captureToolObjects); }
715
C++
.cpp
21
31.714286
72
0.830435
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,689
overlaymessage.cpp
flameshot-org_flameshot/src/widgets/capture/overlaymessage.cpp
#include "overlaymessage.h" #include "colorutils.h" #include "confighandler.h" #include <QApplication> #include <QDebug> #include <QLabel> #include <QPainter> #include <QPen> #include <QScreen> OverlayMessage::OverlayMessage(QWidget* parent, const QRect& targetArea) : QLabel(parent) , m_targetArea(targetArea) { // NOTE: do not call the static functions from the constructor m_instance = this; m_messageStack.push(QString()); // Default message is empty setAttribute(Qt::WA_TransparentForMouseEvents); setAttribute(Qt::WA_AlwaysStackOnTop); setAlignment(Qt::AlignCenter); setTextFormat(Qt::RichText); m_fillColor = ConfigHandler().uiColor(); int opacity = ConfigHandler().contrastOpacity(); m_textColor = (ColorUtils::colorIsDark(m_fillColor) ? Qt::white : Qt::black); // map a background opacity range 0-255 to a fill opacity range 190-160 // we do this because an opaque background makes the box look opaque too m_fillColor.setAlpha(160 + (180 - 220) / (255.0 - 0) * (opacity - 255)); setStyleSheet( QStringLiteral("QLabel { color: %1; }").arg(m_textColor.name())); setMargin(QApplication::fontMetrics().height() / 2); QWidget::hide(); } void OverlayMessage::init(QWidget* parent, const QRect& targetArea) { new OverlayMessage(parent, targetArea); } /** * @brief Push a message to the message stack. * @param msg Message text formatted as rich text */ void OverlayMessage::push(const QString& msg) { m_instance->m_messageStack.push(msg); m_instance->setText(m_instance->m_messageStack.top()); setVisibility(true); } void OverlayMessage::pop() { if (m_instance->m_messageStack.size() > 1) { m_instance->m_messageStack.pop(); } m_instance->setText(m_instance->m_messageStack.top()); setVisibility(m_instance->m_messageStack.size() > 1); } void OverlayMessage::setVisibility(bool visible) { m_instance->updateGeometry(); m_instance->setVisible(visible); } OverlayMessage* OverlayMessage::instance() { return m_instance; } void OverlayMessage::pushKeyMap(const QList<QPair<QString, QString>>& map) { push(compileFromKeyMap(map)); } /** * @brief Compile a message from a set of shortcuts and descriptions. * @param map List of (shortcut, description) pairs */ QString OverlayMessage::compileFromKeyMap( const QList<QPair<QString, QString>>& map) { QString str = QStringLiteral("<table>"); for (const auto& pair : map) { str += QStringLiteral("<tr>" "<td align=\"right\"><b>%1 </b></td>" "<td align=\"left\">&nbsp;&nbsp;%2</td>" "</tr>") .arg(pair.first) .arg(pair.second); } str += QStringLiteral("</table>"); return str; } void OverlayMessage::paintEvent(QPaintEvent* e) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.setBrush(QBrush(m_fillColor, Qt::SolidPattern)); painter.setPen(QPen(m_textColor, 1.5)); float margin = painter.pen().widthF(); painter.drawRoundedRect( rect() - QMarginsF(margin, margin, margin, margin), 5, 5); return QLabel::paintEvent(e); } QRect OverlayMessage::boundingRect() const { QRect geom = QRect(QPoint(), sizeHint()); geom.moveCenter(m_targetArea.center()); return geom; } void OverlayMessage::updateGeometry() { setGeometry(boundingRect()); QLabel::updateGeometry(); } OverlayMessage* OverlayMessage::m_instance = nullptr;
3,556
C++
.cpp
109
28.247706
76
0.685623
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,691
capturetoolbutton.cpp
flameshot-org_flameshot/src/widgets/capture/capturetoolbutton.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "capturetoolbutton.h" #include "src/tools/capturetool.h" #include "src/tools/toolfactory.h" #include "src/utils/colorutils.h" #include "src/utils/confighandler.h" #include "src/utils/globalvalues.h" #include <QApplication> #include <QIcon> #include <QMouseEvent> #include <QPropertyAnimation> #include <QToolTip> // Button represents a single button of the capture widget, it can enable // multiple functionality. CaptureToolButton::CaptureToolButton(const CaptureTool::Type t, QWidget* parent) : CaptureButton(parent) , m_buttonType(t) , m_tool(nullptr) , m_emergeAnimation(nullptr) { initButton(); if (t == CaptureTool::TYPE_SELECTIONINDICATOR) { QFont f = this->font(); setFont(QFont(f.family(), 7, QFont::Bold)); } else { updateIcon(); } } CaptureToolButton::~CaptureToolButton() { if (m_tool) { delete m_tool; m_tool = nullptr; } if (m_emergeAnimation) { delete m_emergeAnimation; m_emergeAnimation = nullptr; } } void CaptureToolButton::initButton() { if (m_tool) { delete m_tool; m_tool = nullptr; } m_tool = ToolFactory().CreateTool(m_buttonType, this); resize(GlobalValues::buttonBaseSize(), GlobalValues::buttonBaseSize()); setMask(QRegion(QRect(-1, -1, GlobalValues::buttonBaseSize() + 2, GlobalValues::buttonBaseSize() + 2), QRegion::Ellipse)); // Set a tooltip showing a shortcut in parentheses (if there is a shortcut) QString tooltip = m_tool->description(); QString shortcut = ConfigHandler().shortcut(QVariant::fromValue(m_buttonType).toString()); if (m_buttonType == CaptureTool::TYPE_COPY && ConfigHandler().copyOnDoubleClick()) { tooltip += QStringLiteral(" (%1Left Double-Click)") .arg(shortcut.isEmpty() ? QString() : shortcut + " or "); } else if (!shortcut.isEmpty()) { tooltip += QStringLiteral(" (%1)").arg(shortcut); } tooltip.replace("Return", "Enter"); setToolTip(tooltip); m_emergeAnimation = new QPropertyAnimation(this, "size", this); m_emergeAnimation->setEasingCurve(QEasingCurve::InOutQuad); m_emergeAnimation->setDuration(80); m_emergeAnimation->setStartValue(QSize(0, 0)); m_emergeAnimation->setEndValue( QSize(GlobalValues::buttonBaseSize(), GlobalValues::buttonBaseSize())); } void CaptureToolButton::updateIcon() { setIcon(icon()); setIconSize(size() * 0.6); } const QList<CaptureTool::Type>& CaptureToolButton::getIterableButtonTypes() { return iterableButtonTypes; } // get icon returns the icon for the type of button QIcon CaptureToolButton::icon() const { return m_tool->icon(m_mainColor, true); } void CaptureToolButton::mousePressEvent(QMouseEvent* e) { activateWindow(); if (e->button() == Qt::LeftButton) { emit pressedButtonLeftClick(this); emit pressed(); } else if (e->button() == Qt::RightButton) { emit pressedButtonRightClick(this); emit pressed(); } } void CaptureToolButton::animatedShow() { if (!isVisible()) { show(); m_emergeAnimation->start(); connect(m_emergeAnimation, &QPropertyAnimation::finished, this, [this]() { updateIcon(); }); } } CaptureTool* CaptureToolButton::tool() const { return m_tool; } void CaptureToolButton::setColor(const QColor& c) { m_mainColor = c; CaptureButton::setColor(c); updateIcon(); } QColor CaptureToolButton::m_mainColor; static std::map<CaptureTool::Type, int> buttonTypeOrder { { CaptureTool::TYPE_PENCIL, 0 }, { CaptureTool::TYPE_DRAWER, 1 }, { CaptureTool::TYPE_ARROW, 2 }, { CaptureTool::TYPE_SELECTION, 3 }, { CaptureTool::TYPE_RECTANGLE, 4 }, { CaptureTool::TYPE_CIRCLE, 5 }, { CaptureTool::TYPE_MARKER, 6 }, { CaptureTool::TYPE_TEXT, 7 }, { CaptureTool::TYPE_PIXELATE, 8 }, { CaptureTool::TYPE_INVERT, 9 }, { CaptureTool::TYPE_CIRCLECOUNT, 10 }, { CaptureTool::TYPE_SELECTIONINDICATOR, 11 }, { CaptureTool::TYPE_MOVESELECTION, 12 }, { CaptureTool::TYPE_UNDO, 13 }, { CaptureTool::TYPE_REDO, 14 }, { CaptureTool::TYPE_COPY, 15 }, { CaptureTool::TYPE_SAVE, 16 }, { CaptureTool::TYPE_IMAGEUPLOADER, 17 }, { CaptureTool::TYPE_ACCEPT, 18 }, #if !defined(Q_OS_MACOS) { CaptureTool::TYPE_OPEN_APP, 19 }, { CaptureTool::TYPE_EXIT, 20 }, { CaptureTool::TYPE_PIN, 21 }, #else { CaptureTool::TYPE_EXIT, 19 }, { CaptureTool::TYPE_PIN, 20 }, #endif { CaptureTool::TYPE_SIZEINCREASE, 22 }, { CaptureTool::TYPE_SIZEDECREASE, 23 }, }; int CaptureToolButton::getPriorityByButton(CaptureTool::Type b) { auto it = buttonTypeOrder.find(b); return it == buttonTypeOrder.cend() ? (int)buttonTypeOrder.size() : it->second; } QList<CaptureTool::Type> CaptureToolButton::iterableButtonTypes = { CaptureTool::TYPE_PENCIL, CaptureTool::TYPE_DRAWER, CaptureTool::TYPE_ARROW, CaptureTool::TYPE_SELECTION, CaptureTool::TYPE_RECTANGLE, CaptureTool::TYPE_CIRCLE, CaptureTool::TYPE_MARKER, CaptureTool::TYPE_TEXT, CaptureTool::TYPE_CIRCLECOUNT, CaptureTool::TYPE_PIXELATE, CaptureTool::TYPE_MOVESELECTION, CaptureTool::TYPE_UNDO, CaptureTool::TYPE_REDO, CaptureTool::TYPE_COPY, CaptureTool::TYPE_SAVE, CaptureTool::TYPE_EXIT, CaptureTool::TYPE_IMAGEUPLOADER, #if !defined(Q_OS_MACOS) CaptureTool::TYPE_OPEN_APP, #endif CaptureTool::TYPE_PIN, CaptureTool::TYPE_SIZEINCREASE, CaptureTool::TYPE_SIZEDECREASE, CaptureTool::TYPE_ACCEPT, };
5,899
C++
.cpp
164
30.646341
80
0.665967
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,692
capturewidget.cpp
flameshot-org_flameshot/src/widgets/capture/capturewidget.cpp
// 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/config/generalconf.h" #include "src/core/flameshot.h" #include "src/core/qguiappcurrentscreen.h" #include "src/tools/toolfactory.h" #include "src/utils/colorutils.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 <QDateTime> #include <QDebug> #include <QDesktopWidget> #include <QFontMetrics> #include <QLabel> #include <QPaintEvent> #include <QPainter> #include <QScreen> #include <QShortcut> #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_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); #if (defined(Q_OS_WIN) || defined(Q_OS_MACOS)) // Top left of the whole set of screens QPoint topLeft(0, 0); #endif if (fullScreen) { // Grab Screenshot bool ok = true; m_context.screenshot = ScreenGrabber().grabEntireDesktop(ok); if (!ok) { AbstractLogger::error() << tr("Unable to capture screen"); this->close(); } m_context.origScreenshot = m_context.screenshot; #if defined(Q_OS_WIN) // Call cmake with -DFLAMESHOT_DEBUG_CAPTURE=ON to enable easier debugging #if !defined(FLAMESHOT_DEBUG_CAPTURE) setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::SubWindow // Hides the taskbar icon ); #endif 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); resize(pixmap().size()); #elif defined(Q_OS_MACOS) // Emulate fullscreen mode // setWindowFlags(Qt::WindowStaysOnTopHint | // Qt::BypassWindowManagerHint | // Qt::FramelessWindowHint | // Qt::NoDropShadowWindowHint | Qt::ToolTip | // Qt::Popup // ); QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen(); move(currentScreen->geometry().x(), currentScreen->geometry().y()); resize(currentScreen->size()); #else // Call cmake with -DFLAMESHOT_DEBUG_CAPTURE=ON to enable easier debugging #if !defined(FLAMESHOT_DEBUG_CAPTURE) setWindowFlags(Qt::BypassWindowManagerHint | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Tool); resize(pixmap().size()); #endif #endif } QVector<QRect> areas; if (m_context.fullscreen) { QPoint topLeftOffset = QPoint(0, 0); #if defined(Q_OS_WIN) topLeftOffset = topLeft; #endif #if defined(Q_OS_MACOS) // MacOS works just with one active display, so we need to append // just one current display and keep multiple displays logic for // other OS QRect r; QScreen* screen = QGuiAppCurrentScreen().currentScreen(); r = screen->geometry(); // all calculations are processed according to (0, 0) start // point so we need to move current object to (0, 0) r.moveTo(0, 0); areas.append(r); #else for (QScreen* const screen : QGuiApplication::screens()) { QRect r = screen->geometry(); r.moveTo(r.x() / screen->devicePixelRatio(), r.y() / screen->devicePixelRatio()); r.moveTo(r.topLeft() - topLeftOffset); areas.append(r); } #endif } 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); 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); // Init notification widget m_notifierBox = new NotifierBox(this); 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); }); initPanel(); m_config.checkAndHandleError(); if (m_config.hasError()) { m_configError = true; } connect(ConfigHandler::getInstance(), &ConfigHandler::error, this, [=]() { m_configError = true; m_configErrorResolved = false; OverlayMessage::instance()->update(); }); connect( ConfigHandler::getInstance(), &ConfigHandler::errorResolved, this, [=]() { m_configError = false; m_configErrorResolved = true; OverlayMessage::instance()->update(); }); OverlayMessage::init(this, QGuiAppCurrentScreen().currentScreen()->geometry()); if (m_config.showHelp()) { initHelpMessage(); OverlayMessage::push(m_helpMessage); } 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(); 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); buttonList->removeOne(CaptureTool::TYPE_IMAGEUPLOADER); 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); if (t == CaptureTool::TYPE_SELECTIONINDICATOR) { m_sizeIndButton = b; } 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, [=]() { 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::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 << QPair(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 << QPair(shortcut, tool->description()); } } keyMap << QPair(tr("Mouse Wheel"), tr("Change tool size")); keyMap << QPair(tr("Right Click"), tr("Show color picker")); keyMap << QPair(ConfigHandler().shortcut("TYPE_TOGGLE_PANEL"), tr("Open side panel")); keyMap << QPair(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::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 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::paintEvent(QPaintEvent* paintEvent) { Q_UNUSED(paintEvent) QPainter painter(this); 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(static_cast<int>(selection.width() * scale)) .arg(static_cast<int>(selection.height() * scale)) .arg(static_cast<int>(selection.left() * scale)) .arg(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)); auto topLeft = mapToGlobal(m_context.selection.topLeft()); topLeft.rx() -= topLeft.x() % m_gridSize; topLeft.ry() -= topLeft.y() % m_gridSize; topLeft = mapFromGlobal(topLeft); const auto scale{ m_context.screenshot.devicePixelRatio() }; const auto step{ m_gridSize * scale }; const auto radius{ 1 * scale }; for (int y = topLeft.y(); y < m_context.selection.bottom(); y += step) { for (int x = topLeft.x(); x < m_context.selection.right(); 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); 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(&copyTool, &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()) : e->pos()); } // update drawing object updateTool(m_activeTool); // Hides the buttons under the mouse. If the mouse leaves, it shows // them. if (m_buttonHandler->buttonsAreInside()) { const bool containsMouse = m_buttonHandler->contains(m_context.mousePos); if (containsMouse) { m_buttonHandler->hide(); } else if (m_selection->isVisible()) { m_buttonHandler->show(); } } } updateCursor(); } void CaptureWidget::mouseReleaseEvent(QMouseEvent* e) { if (e->button() == Qt::LeftButton && m_colorPicker->isVisible()) { // Color picker if (m_colorPicker->isVisible() && m_panel->activeLayerIndex() >= 0 && m_context.color.isValid()) { pushObjectsStateToUndoStack(); } m_colorPicker->hide(); if (!m_context.color.isValid()) { m_context.color = ConfigHandler().drawColor(); m_panel->show(); } } else if (m_mouseIsClicked) { if (m_activeTool) { // end draw/edit m_activeTool->drawEnd(m_context.mousePos); if (m_activeTool->isValid()) { pushToolToStack(); } else if (!m_toolWidget) { releaseActiveTool(); } } else { if (m_activeToolIsMoved) { m_activeToolIsMoved = false; pushObjectsStateToUndoStack(); } } } m_mouseIsClicked = false; m_activeToolIsMoved = false; updateSelectionState(); updateCursor(); } /** * Was updateThickness. * - Update tool mouse preview * - Show notifier box displaying the new thickness * - Update selected object thickness */ void CaptureWidget::setToolSize(int size) { int oldSize = m_context.toolSize; m_context.toolSize = qBound(1, size, maxToolSize); updateTool(activeButtonTool()); QPoint topLeft = QGuiAppCurrentScreen().currentScreen()->geometry().topLeft(); int offset = m_notifierBox->width() / 4; m_notifierBox->move(mapFromGlobal(topLeft) + QPoint(offset, offset)); m_notifierBox->showMessage(QString::number(m_context.toolSize)); if (m_context.toolSize != oldSize) { emit toolSizeChanged(m_context.toolSize); } } void CaptureWidget::keyPressEvent(QKeyEvent* e) { // If the key is a digit, change the tool size bool ok; int digit = e->text().toInt(&ok); if (ok && ((e->modifiers() == Qt::NoModifier) || e->modifiers() == Qt::KeypadModifier)) { // digit received m_toolSizeByKeyboard = 10 * m_toolSizeByKeyboard + digit; setToolSize(m_toolSizeByKeyboard); if (m_context.toolSize != m_toolSizeByKeyboard) { // The tool size was out of range and was clipped by setToolSize m_toolSizeByKeyboard = 0; } } else { m_toolSizeByKeyboard = 0; } if (!m_selection->isVisible()) { return; } else if (e->key() == Qt::Key_Control) { m_adjustmentButtonPressed = true; updateCursor(); } else if (e->key() == Qt::Key_Enter) { // Make no difference for Return and Enter keys QCoreApplication::postEvent( this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Return, Qt::NoModifier)); } } void CaptureWidget::keyReleaseEvent(QKeyEvent* e) { if (e->key() == Qt::Key_Control) { m_adjustmentButtonPressed = false; updateCursor(); } } void CaptureWidget::wheelEvent(QWheelEvent* e) { /* Mouse scroll usually gives value 120, not more or less, just how many * times. * Touchpad gives the value 2 or more (usually 2-8), it doesn't give * too big values like mouse wheel on normal scrolling, so it is almost * impossible to scroll. It's easier to calculate number of requests and do * not accept events faster that one in 200ms. * */ int toolSizeOffset = 0; if (e->angleDelta().y() >= 60) { // mouse scroll (wheel) increment toolSizeOffset = 1; } else if (e->angleDelta().y() <= -60) { // mouse scroll (wheel) decrement toolSizeOffset = -1; } else { // touchpad scroll qint64 current = QDateTime::currentMSecsSinceEpoch(); if ((current - m_lastMouseWheel) > 200) { if (e->angleDelta().y() > 0) { toolSizeOffset = 1; } else if (e->angleDelta().y() < 0) { toolSizeOffset = -1; } m_lastMouseWheel = current; } else { return; } } setToolSize(m_context.toolSize + toolSizeOffset); } void CaptureWidget::resizeEvent(QResizeEvent* e) { QWidget::resizeEvent(e); m_context.widgetOffset = mapToGlobal(QPoint(0, 0)); if (!m_context.fullscreen) { m_panel->setFixedHeight(height()); m_buttonHandler->updateScreenRegions(rect()); } } void CaptureWidget::moveEvent(QMoveEvent* e) { QWidget::moveEvent(e); m_context.widgetOffset = mapToGlobal(QPoint(0, 0)); } void CaptureWidget::changeEvent(QEvent* e) { if (e->type() == QEvent::ActivationChange) { QPoint bottomRight = rect().bottomRight(); // Update the message in the bottom right corner. A rough estimate is // used for the update rect update(QRect(bottomRight - QPoint(1000, 200), bottomRight)); } } void CaptureWidget::initContext(bool fullscreen, const CaptureRequest& req) { m_context.color = m_config.drawColor(); m_context.widgetOffset = mapToGlobal(QPoint(0, 0)); m_context.mousePos = mapFromGlobal(QCursor::pos()); m_context.toolSize = m_config.drawThickness(); m_context.fullscreen = fullscreen; // initialize m_context.request m_context.request = req; } void CaptureWidget::initPanel() { QRect panelRect = rect(); if (m_context.fullscreen) { #if (defined(Q_OS_MACOS) || defined(Q_OS_LINUX)) QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen(); panelRect = currentScreen->geometry(); auto devicePixelRatio = currentScreen->devicePixelRatio(); panelRect.moveTo(static_cast<int>(panelRect.x() / devicePixelRatio), static_cast<int>(panelRect.y() / devicePixelRatio)); #else panelRect = QGuiApplication::primaryScreen()->geometry(); auto devicePixelRatio = QGuiApplication::primaryScreen()->devicePixelRatio(); panelRect.moveTo(panelRect.x() / devicePixelRatio, panelRect.y() / devicePixelRatio); #endif } if (ConfigHandler().showSidePanelButton()) { auto* panelToggleButton = new OrientablePushButton(tr("Tool Settings"), this); makeChild(panelToggleButton); panelToggleButton->setColor(m_uiColor); panelToggleButton->setOrientation( OrientablePushButton::VerticalBottomToTop); #if defined(Q_OS_MACOS) panelToggleButton->move( 0, static_cast<int>(panelRect.height() / 2) - static_cast<int>(panelToggleButton->width() / 2)); #else panelToggleButton->move(panelRect.x(), panelRect.y() + panelRect.height() / 2 - panelToggleButton->width() / 2); #endif panelToggleButton->setCursor(Qt::ArrowCursor); (new DraggableWidgetMaker(this))->makeDraggable(panelToggleButton); connect(panelToggleButton, &QPushButton::clicked, this, &CaptureWidget::togglePanel); } m_panel = new UtilityPanel(this); m_panel->hide(); makeChild(m_panel); #if defined(Q_OS_MACOS) QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen(); panelRect.moveTo(mapFromGlobal(panelRect.topLeft())); m_panel->setFixedWidth(static_cast<int>(m_colorPicker->width() * 1.5)); m_panel->setFixedHeight(currentScreen->geometry().height()); #else panelRect.moveTo(mapFromGlobal(panelRect.topLeft())); panelRect.setWidth(m_colorPicker->width() * 1.5); m_panel->setGeometry(panelRect); #endif connect(m_panel, &UtilityPanel::layerChanged, this, &CaptureWidget::updateActiveLayer); connect(m_panel, &UtilityPanel::moveUpClicked, this, &CaptureWidget::onMoveCaptureToolUp); connect(m_panel, &UtilityPanel::moveDownClicked, this, &CaptureWidget::onMoveCaptureToolDown); m_sidePanel = new SidePanelWidget(&m_context.screenshot, this); connect(m_sidePanel, &SidePanelWidget::colorChanged, this, &CaptureWidget::setDrawColor); connect(m_sidePanel, &SidePanelWidget::toolSizeChanged, this, &CaptureWidget::onToolSizeChanged); connect(this, &CaptureWidget::colorChanged, m_sidePanel, &SidePanelWidget::onColorChanged); connect(this, &CaptureWidget::toolSizeChanged, m_sidePanel, &SidePanelWidget::onToolSizeChanged); connect(m_sidePanel, &SidePanelWidget::togglePanel, m_panel, &UtilityPanel::toggle); connect(m_sidePanel, &SidePanelWidget::displayGridChanged, this, &CaptureWidget::onDisplayGridChanged); connect(m_sidePanel, &SidePanelWidget::gridSizeChanged, this, &CaptureWidget::onGridSizeChanged); // TODO replace with a CaptureWidget signal emit m_sidePanel->colorChanged(m_context.color); emit toolSizeChanged(m_context.toolSize); m_panel->pushWidget(m_sidePanel); // Fill undo/redo/history list widget m_panel->fillCaptureTools(m_captureToolObjects.captureToolObjects()); } #if !defined(DISABLE_UPDATE_CHECKER) void CaptureWidget::showAppUpdateNotification(const QString& appLatestVersion, const QString& appLatestUrl) { if (!ConfigHandler().checkForUpdates()) { // option check for updates disabled return; } if (nullptr == m_updateNotificationWidget) { m_updateNotificationWidget = new UpdateNotificationWidget(this, appLatestVersion, appLatestUrl); } #if defined(Q_OS_MACOS) int ax = (width() - m_updateNotificationWidget->width()) / 2; #elif (defined(Q_OS_LINUX) && QT_VERSION < QT_VERSION_CHECK(5, 10, 0)) QRect helpRect = QGuiApplication::primaryScreen()->geometry(); int ax = helpRect.left() + ((helpRect.width() - m_updateNotificationWidget->width()) / 2); #else QRect helpRect; QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen(); if (currentScreen) { helpRect = currentScreen->geometry(); } else { helpRect = QGuiApplication::primaryScreen()->geometry(); } int ax = helpRect.left() + ((helpRect.width() - m_updateNotificationWidget->width()) / 2); #endif m_updateNotificationWidget->move(ax, 0); makeChild(m_updateNotificationWidget); m_updateNotificationWidget->show(); } #endif void CaptureWidget::initSelection() { // Be mindful of the order of statements, so that slots are called properly m_selection = new SelectionWidget(m_uiColor, this); QRect initialSelection = m_context.request.initialSelection(); connect(m_selection, &SelectionWidget::geometryChanged, this, [this]() { QRect constrainedToCaptureArea = m_selection->geometry().intersected(rect()); m_context.selection = extendedRect(constrainedToCaptureArea); m_buttonHandler->hide(); updateCursor(); updateSizeIndicator(); OverlayMessage::pop(); }); connect(m_selection, &SelectionWidget::geometrySettled, this, [this]() { if (m_selection->isVisibleTo(this)) { auto& req = m_context.request; if (req.tasks() & CaptureRequest::ACCEPT_ON_SELECT) { req.removeTask(CaptureRequest::ACCEPT_ON_SELECT); m_captureDone = true; close(); } m_buttonHandler->updatePosition(m_selection->geometry()); m_buttonHandler->show(); } else { m_buttonHandler->hide(); } }); connect(m_selection, &SelectionWidget::visibilityChanged, this, [this]() { if (!m_selection->isVisible() && !m_helpMessage.isEmpty()) { OverlayMessage::push(m_helpMessage); } }); if (!initialSelection.isNull()) { const qreal scale = m_context.screenshot.devicePixelRatio(); initialSelection.moveTopLeft(initialSelection.topLeft() - mapToGlobal({})); initialSelection.setTop(initialSelection.top() / scale); initialSelection.setBottom(initialSelection.bottom() / scale); initialSelection.setLeft(initialSelection.left() / scale); initialSelection.setRight(initialSelection.right() / scale); } m_selection->setGeometry(initialSelection); m_selection->setVisible(!initialSelection.isNull()); if (!initialSelection.isNull()) { m_context.selection = extendedRect(m_selection->geometry()); emit m_selection->geometrySettled(); } } void CaptureWidget::setState(CaptureToolButton* b) { if (!b) { return; } commitCurrentTool(); if (m_toolWidget && m_activeTool) { if (m_activeTool->isValid()) { pushToolToStack(); } else { releaseActiveTool(); } } if (m_activeButton != b) { auto backup = m_activeTool; // The tool is active during the pressed(). // This must be done in order to handle tool requests correctly. m_activeTool = b->tool(); m_activeTool->pressed(m_context); m_activeTool = backup; } if (b->tool()->isSelectable()) { if (m_activeButton != b) { if (m_activeButton) { m_activeButton->setColor(m_uiColor); } m_activeButton = b; m_activeButton->setColor(m_contrastUiColor); m_panel->setActiveLayer(-1); m_panel->setToolWidget(b->tool()->configurationWidget()); } else if (m_activeButton) { m_panel->clearToolWidget(); m_activeButton->setColor(m_uiColor); m_activeButton = nullptr; } m_context.toolSize = ConfigHandler().toolSize(activeButtonToolType()); emit toolSizeChanged(m_context.toolSize); updateCursor(); updateSelectionState(); updateTool(b->tool()); } } void CaptureWidget::handleToolSignal(CaptureTool::Request r) { switch (r) { case CaptureTool::REQ_CLOSE_GUI: close(); break; case CaptureTool::REQ_HIDE_GUI: hide(); break; case CaptureTool::REQ_UNDO_MODIFICATION: undo(); break; case CaptureTool::REQ_REDO_MODIFICATION: redo(); break; case CaptureTool::REQ_SHOW_COLOR_PICKER: // TODO break; case CaptureTool::REQ_CAPTURE_DONE_OK: m_captureDone = true; break; case CaptureTool::REQ_CLEAR_SELECTION: if (m_panel->activeLayerIndex() >= 0) { m_panel->setActiveLayer(-1); drawToolsData(false); } break; case CaptureTool::REQ_ADD_CHILD_WIDGET: if (!m_activeTool) { break; } if (m_toolWidget) { m_toolWidget->hide(); delete m_toolWidget; m_toolWidget = nullptr; } m_toolWidget = m_activeTool->widget(); if (m_toolWidget) { makeChild(m_toolWidget); m_toolWidget->move(m_context.mousePos); m_toolWidget->show(); m_toolWidget->setFocus(); } break; case CaptureTool::REQ_ADD_EXTERNAL_WIDGETS: if (!m_activeTool) { break; } else { QWidget* w = m_activeTool->widget(); w->setAttribute(Qt::WA_DeleteOnClose); w->activateWindow(); w->show(); Flameshot::instance()->setExternalWidget(true); } break; case CaptureTool::REQ_INCREASE_TOOL_SIZE: setToolSize(m_context.toolSize + 1); break; case CaptureTool::REQ_DECREASE_TOOL_SIZE: setToolSize(m_context.toolSize - 1); break; default: break; } } /** * Was setDrawThickness * - Update config options * - Update tool object thickness */ void CaptureWidget::onToolSizeChanged(int t) { m_context.toolSize = t; CaptureTool* tool = activeButtonTool(); if (tool && tool->showMousePreview()) { setCursor(Qt::BlankCursor); tool->onSizeChanged(t); } // update tool size of object being drawn if (m_activeTool != nullptr) { updateTool(m_activeTool); } // update tool size of selected object auto toolItem = activeToolObject(); if (toolItem) { // Change thickness toolItem->onSizeChanged(t); if (!m_existingObjectIsChanged) { m_captureToolObjectsBackup = m_captureToolObjects; m_existingObjectIsChanged = true; } drawToolsData(); updateTool(toolItem); } // Force a repaint to prevent artifacting this->repaint(); } void CaptureWidget::onToolSizeSettled(int size) { m_config.setToolSize(activeButtonToolType(), size); } void CaptureWidget::setDrawColor(const QColor& c) { m_context.color = c; if (m_context.color.isValid()) { ConfigHandler().setDrawColor(m_context.color); emit colorChanged(c); // Update mouse preview updateTool(activeButtonTool()); // change color for the active tool auto toolItem = activeToolObject(); if (toolItem) { // Change color toolItem->onColorChanged(c); drawToolsData(); } } } void CaptureWidget::updateActiveLayer(int layer) { // TODO - refactor this part, make all objects to work with // m_activeTool->isChanged() and remove m_existingObjectIsChanged if (m_activeTool && m_activeTool->type() == CaptureTool::TYPE_TEXT && m_activeTool->isChanged()) { commitCurrentTool(); } if (m_toolWidget) { // Release active tool if it is in the editing mode but not changed and // has editing widget (ex: text tool) releaseActiveTool(); } if (m_existingObjectIsChanged) { m_existingObjectIsChanged = false; pushObjectsStateToUndoStack(); } drawToolsData(); drawObjectSelection(); updateSelectionState(); } void CaptureWidget::onMoveCaptureToolUp(int captureToolIndex) { m_captureToolObjectsBackup = m_captureToolObjects; pushObjectsStateToUndoStack(); auto tool = m_captureToolObjects.at(captureToolIndex); m_captureToolObjects.removeAt(captureToolIndex); m_captureToolObjects.insert(captureToolIndex - 1, tool); updateLayersPanel(); } void CaptureWidget::onMoveCaptureToolDown(int captureToolIndex) { m_captureToolObjectsBackup = m_captureToolObjects; pushObjectsStateToUndoStack(); auto tool = m_captureToolObjects.at(captureToolIndex); m_captureToolObjects.removeAt(captureToolIndex); m_captureToolObjects.insert(captureToolIndex + 1, tool); updateLayersPanel(); } void CaptureWidget::selectAll() { m_selection->show(); m_selection->setGeometry(rect()); emit m_selection->geometrySettled(); m_buttonHandler->show(); updateSelectionState(); } void CaptureWidget::removeToolObject(int index) { --index; if (index >= 0 && index < m_captureToolObjects.size()) { // in case this tool is circle counter const CaptureTool::Type currentToolType = m_captureToolObjects.at(index)->type(); m_captureToolObjectsBackup = m_captureToolObjects; update( paddedUpdateRect(m_captureToolObjects.at(index)->boundingRect())); if (currentToolType == CaptureTool::TYPE_CIRCLECOUNT) { int removedCircleCount = m_captureToolObjects.at(index)->count(); --m_context.circleCount; // Decrement circle counter numbers starting from deleted circle for (int cnt = 0; cnt < m_captureToolObjects.size(); cnt++) { auto toolItem = m_captureToolObjects.at(cnt); if (toolItem->type() != CaptureTool::TYPE_CIRCLECOUNT) { continue; } auto circleTool = m_captureToolObjects.at(cnt); if (circleTool->count() >= removedCircleCount) { circleTool->setCount(circleTool->count() - 1); } } } m_captureToolObjects.removeAt(index); pushObjectsStateToUndoStack(); drawToolsData(); updateLayersPanel(); } } void CaptureWidget::initShortcuts() { newShortcut( QKeySequence(ConfigHandler().shortcut("TYPE_UNDO")), this, SLOT(undo())); newShortcut( QKeySequence(ConfigHandler().shortcut("TYPE_REDO")), this, SLOT(redo())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_TOGGLE_PANEL")), this, SLOT(togglePanel())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_RESIZE_LEFT")), m_selection, SLOT(resizeLeft())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_RESIZE_RIGHT")), m_selection, SLOT(resizeRight())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_RESIZE_UP")), m_selection, SLOT(resizeUp())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_RESIZE_DOWN")), m_selection, SLOT(resizeDown())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_SYM_RESIZE_LEFT")), m_selection, SLOT(symResizeLeft())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_SYM_RESIZE_RIGHT")), m_selection, SLOT(symResizeRight())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_SYM_RESIZE_UP")), m_selection, SLOT(symResizeUp())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_SYM_RESIZE_DOWN")), m_selection, SLOT(symResizeDown())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_MOVE_LEFT")), m_selection, SLOT(moveLeft())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_MOVE_RIGHT")), m_selection, SLOT(moveRight())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_MOVE_UP")), m_selection, SLOT(moveUp())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_MOVE_DOWN")), m_selection, SLOT(moveDown())); newShortcut( QKeySequence(ConfigHandler().shortcut("TYPE_DELETE_CURRENT_TOOL")), this, SLOT(deleteCurrentTool())); newShortcut( QKeySequence(ConfigHandler().shortcut("TYPE_COMMIT_CURRENT_TOOL")), this, SLOT(commitCurrentTool())); newShortcut(QKeySequence(ConfigHandler().shortcut("TYPE_SELECT_ALL")), this, SLOT(selectAll())); newShortcut(Qt::Key_Escape, this, SLOT(deleteToolWidgetOrClose())); } void CaptureWidget::deleteCurrentTool() { int oldToolSize = m_context.toolSize; m_panel->slotButtonDelete(true); drawObjectSelection(); if (oldToolSize != m_context.toolSize) { emit toolSizeChanged(m_context.toolSize); } } void CaptureWidget::updateSizeIndicator() { if (m_config.showSelectionGeometry()) { showxywh(); } if (m_sizeIndButton) { const QRect& selection = extendedSelection(); m_sizeIndButton->setText(QStringLiteral("%1\n%2") .arg(selection.width()) .arg(selection.height())); } } void CaptureWidget::updateCursor() { if (m_colorPicker && m_colorPicker->isVisible()) { setCursor(Qt::ArrowCursor); } else if (m_activeButton != nullptr && activeButtonToolType() != CaptureTool::TYPE_MOVESELECTION) { setCursor(Qt::CrossCursor); } else if (m_selection->getMouseSide(mapFromGlobal(QCursor::pos())) != SelectionWidget::NO_SIDE) { setCursor(m_selection->cursor()); } else if (activeButtonToolType() == CaptureTool::TYPE_MOVESELECTION) { setCursor(Qt::OpenHandCursor); } else { setCursor(Qt::CrossCursor); } } void CaptureWidget::updateSelectionState() { auto toolType = activeButtonToolType(); if (toolType == CaptureTool::TYPE_MOVESELECTION) { m_selection->setIdleCentralCursor(Qt::OpenHandCursor); m_selection->setIgnoreMouse(false); } else { m_selection->setIdleCentralCursor(Qt::ArrowCursor); if (toolType == CaptureTool::NONE) { m_selection->setIgnoreMouse(m_panel->activeLayerIndex() != -1); } else { m_selection->setIgnoreMouse(true); } } } void CaptureWidget::updateTool(CaptureTool* tool) { if (!tool || !tool->showMousePreview()) { return; } static QRect oldPreviewRect, oldToolObjectRect; QRect previewRect(tool->mousePreviewRect(m_context)); previewRect += QMargins(previewRect.width(), previewRect.height(), previewRect.width(), previewRect.height()); QRect toolObjectRect = paddedUpdateRect(tool->boundingRect()); // old rects are united with current rects to handle sudden mouse movement update(previewRect); update(toolObjectRect); update(oldPreviewRect); update(oldToolObjectRect); oldPreviewRect = previewRect; oldToolObjectRect = toolObjectRect; } void CaptureWidget::updateLayersPanel() { m_panel->fillCaptureTools(m_captureToolObjects.captureToolObjects()); } void CaptureWidget::pushToolToStack() { // append current tool to the new state if (m_activeTool && m_activeButton) { disconnect(this, &CaptureWidget::colorChanged, m_activeTool, &CaptureTool::onColorChanged); disconnect(this, &CaptureWidget::toolSizeChanged, m_activeTool, &CaptureTool::onSizeChanged); if (m_panel->toolWidget()) { disconnect(m_panel->toolWidget(), nullptr, m_activeTool, nullptr); } // disable signal connect for updating layer because it may call this // function again on text objects m_panel->blockSignals(true); m_captureToolObjectsBackup = m_captureToolObjects; m_captureToolObjects.append(m_activeTool); pushObjectsStateToUndoStack(); releaseActiveTool(); drawToolsData(); updateLayersPanel(); // restore signal connection for updating layer m_panel->blockSignals(false); } } void CaptureWidget::drawToolsData(bool drawSelection) { // TODO refactor this for performance. The objects should not all be updated // at once every time QPixmap pixmapItem = m_context.origScreenshot; for (auto toolItem : m_captureToolObjects.captureToolObjects()) { processPixmapWithTool(&pixmapItem, toolItem); update(paddedUpdateRect(toolItem->boundingRect())); } m_context.screenshot = pixmapItem; if (drawSelection) { drawObjectSelection(); } } void CaptureWidget::drawObjectSelection() { auto toolItem = activeToolObject(); if (toolItem && !toolItem->editMode()) { QPainter painter(&m_context.screenshot); toolItem->drawObjectSelection(painter); // TODO move this elsewhere if (m_context.toolSize != toolItem->size()) { m_context.toolSize = toolItem->size(); } if (activeToolObject() && m_activeButton) { uncheckActiveTool(); } } } void CaptureWidget::processPixmapWithTool(QPixmap* pixmap, CaptureTool* tool) { QPainter painter(pixmap); painter.setRenderHint(QPainter::Antialiasing); tool->process(painter, *pixmap); } CaptureTool* CaptureWidget::activeButtonTool() const { if (m_activeButton == nullptr) { return nullptr; } return m_activeButton->tool(); } CaptureTool::Type CaptureWidget::activeButtonToolType() const { auto* activeTool = activeButtonTool(); if (activeTool == nullptr) { return CaptureTool::NONE; } return activeTool->type(); } QPoint CaptureWidget::snapToGrid(const QPoint& point) const { QPoint snapPoint = mapToGlobal(point); const auto scale{ m_context.screenshot.devicePixelRatio() }; snapPoint.setX((qRound(snapPoint.x() / double(m_gridSize)) * m_gridSize) * scale); snapPoint.setY((qRound(snapPoint.y() / double(m_gridSize)) * m_gridSize) * scale); return mapFromGlobal(snapPoint); } QPointer<CaptureTool> CaptureWidget::activeToolObject() { return m_captureToolObjects.at(m_panel->activeLayerIndex()); } void CaptureWidget::makeChild(QWidget* w) { w->setParent(this); w->installEventFilter(m_eventFilter); } void CaptureWidget::restoreCircleCountState() { int largest = 0; for (int cnt = 0; cnt < m_captureToolObjects.size(); cnt++) { auto toolItem = m_captureToolObjects.at(cnt); if (toolItem->type() != CaptureTool::TYPE_CIRCLECOUNT) { continue; } if (toolItem->count() > largest) { largest = toolItem->count(); } } m_context.circleCount = largest + 1; } /** * @brief Wrapper around `new QShortcut`, properly handling Enter/Return. */ QList<QShortcut*> CaptureWidget::newShortcut(const QKeySequence& key, QWidget* parent, const char* slot) { QList<QShortcut*> shortcuts; QString strKey = key.toString(); if (strKey.contains("Enter") || strKey.contains("Return")) { strKey.replace("Enter", "Return"); shortcuts << new QShortcut(strKey, parent, slot); strKey.replace("Return", "Enter"); shortcuts << new QShortcut(strKey, parent, slot); } else { shortcuts << new QShortcut(key, parent, slot); } return shortcuts; } void CaptureWidget::togglePanel() { m_panel->toggle(); } void CaptureWidget::childEnter() { m_previewEnabled = false; updateTool(activeButtonTool()); } void CaptureWidget::childLeave() { m_previewEnabled = true; updateTool(activeButtonTool()); } void CaptureWidget::setCaptureToolObjects( const CaptureToolObjects& captureToolObjects) { // Used for undo/redo m_captureToolObjects = captureToolObjects; drawToolsData(); updateLayersPanel(); drawObjectSelection(); } void CaptureWidget::undo() { if (m_activeTool && (m_activeTool->isChanged() || m_activeTool->editMode())) { // Remove selection on undo, at the same time commit current tool will // be called m_panel->setActiveLayer(-1); } // drawToolsData is called twice to update both previous and new regions // FIXME this is a temporary workaround drawToolsData(); m_undoStack.undo(); drawToolsData(); updateLayersPanel(); restoreCircleCountState(); } void CaptureWidget::redo() { // drawToolsData is called twice to update both previous and new regions // FIXME this is a temporary workaround drawToolsData(); m_undoStack.redo(); drawToolsData(); update(); updateLayersPanel(); restoreCircleCountState(); } QRect CaptureWidget::extendedSelection() const { if (m_selection == nullptr) { return {}; } QRect r = m_selection->geometry(); return extendedRect(r); } QRect CaptureWidget::extendedRect(const QRect& r) const { auto devicePixelRatio = m_context.screenshot.devicePixelRatio(); return { static_cast<int>(r.left() * devicePixelRatio), static_cast<int>(r.top() * devicePixelRatio), static_cast<int>(r.width() * devicePixelRatio), static_cast<int>(r.height() * devicePixelRatio) }; } QRect CaptureWidget::paddedUpdateRect(const QRect& r) const { if (r.isNull()) { return r; } else { return r + QMargins(20, 20, 20, 20); } } void CaptureWidget::drawErrorMessage(const QString& msg, QPainter* painter) { auto textRect = painter->fontMetrics().boundingRect(msg); int w = textRect.width(), h = textRect.height(); textRect = { size().width() - w - 10, size().height() - h - 5, w + 100, h + 100 }; QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen(); if (!textRect.contains(QCursor::pos(currentScreen))) { QColor textColor(Qt::white); painter->setPen(textColor); painter->drawText(textRect, msg); } } void CaptureWidget::drawInactiveRegion(QPainter* painter) { QColor overlayColor(0, 0, 0, m_opacity); painter->setBrush(overlayColor); QRect r; if (m_selection->isVisible()) { r = m_selection->geometry().normalized(); } QRegion grey(rect()); grey = grey.subtracted(r); painter->setClipRegion(grey); painter->drawRect(-1, -1, rect().width() + 1, rect().height() + 1); }
63,444
C++
.cpp
1,757
28.031303
80
0.618575
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,693
capturetoolobjects.cpp
flameshot-org_flameshot/src/widgets/capture/capturetoolobjects.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2021 Yurii Puchkov & Contributors #include "capturetoolobjects.h" #define SEARCH_RADIUS_NEAR 3 #define SEARCH_RADIUS_FAR 5 #define SEARCH_RADIUS_TEXT_HANDICAP 5 CaptureToolObjects::CaptureToolObjects(QObject* parent) : QObject(parent) {} void CaptureToolObjects::append(const QPointer<CaptureTool>& captureTool) { if (!captureTool.isNull()) { m_captureToolObjects.append(captureTool->copy(captureTool->parent())); m_imageCache.clear(); } } void CaptureToolObjects::insert(int index, const QPointer<CaptureTool>& captureTool) { if (!captureTool.isNull() && index >= 0 && index <= m_captureToolObjects.size()) { m_captureToolObjects.insert(index, captureTool->copy(captureTool->parent())); m_imageCache.clear(); } } QPointer<CaptureTool> CaptureToolObjects::at(int index) { if (index >= 0 && index < m_captureToolObjects.size()) { return m_captureToolObjects[index]; } return nullptr; } void CaptureToolObjects::clear() { m_captureToolObjects.clear(); } QList<QPointer<CaptureTool>> CaptureToolObjects::captureToolObjects() { return m_captureToolObjects; } int CaptureToolObjects::size() { return m_captureToolObjects.size(); } void CaptureToolObjects::removeAt(int index) { if (index >= 0 && index < m_captureToolObjects.size()) { m_captureToolObjects.removeAt(index); m_imageCache.clear(); } } int CaptureToolObjects::find(const QPoint& pos, QSize captureSize) { if (m_captureToolObjects.empty()) { return -1; } QPixmap pixmap(captureSize); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); // first attempt to find at exact position int radius = SEARCH_RADIUS_NEAR; int index = findWithRadius(painter, pixmap, pos, radius); if (-1 == index) { // second attempt to find at position with radius radius = SEARCH_RADIUS_FAR; pixmap.fill(Qt::transparent); index = findWithRadius(painter, pixmap, pos, radius); } return index; } int CaptureToolObjects::findWithRadius(QPainter& painter, QPixmap& pixmap, const QPoint& pos, int radius) { int index = m_captureToolObjects.size() - 1; bool useCache = true; m_imageCache.clear(); if (m_imageCache.size() != m_captureToolObjects.size() && index >= 0) { // TODO - is not optimal and cache will be used just after first tool // object selecting m_imageCache.clear(); useCache = false; } for (; index >= 0; --index) { int currentRadius = radius; QImage image; auto toolItem = m_captureToolObjects.at(index); if (useCache) { image = m_imageCache.at(index); } else { // create transparent image in memory and draw toolItem on it toolItem->drawSearchArea(painter, pixmap); // get color at mouse clicked position in area +/- currentRadius image = pixmap.toImage(); m_imageCache.insert(0, image); } if (toolItem->type() == CaptureTool::TYPE_TEXT) { if (currentRadius > SEARCH_RADIUS_NEAR) { // Text already has a big currentRadius and no need to search // with a bit bigger currentRadius than // SEARCH_RADIUS_TEXT_HANDICAP + SEARCH_RADIUS_NEAR continue; } // Text has spaces inside to need to take a bigger currentRadius for // text objects search currentRadius += SEARCH_RADIUS_TEXT_HANDICAP; } for (int x = pos.x() - currentRadius; x <= pos.x() + currentRadius; ++x) { for (int y = pos.y() - currentRadius; y <= pos.y() + currentRadius; ++y) { QRgb rgb = image.pixel(x, y); if (rgb != 0) { // object was found, return it index (layer index) return index; } } } } // no object at current pos found return -1; } CaptureToolObjects& CaptureToolObjects::operator=( const CaptureToolObjects& other) { // remove extra items for this if size is bigger while (this->m_captureToolObjects.size() > other.m_captureToolObjects.size()) { this->m_captureToolObjects.removeLast(); } int count = 0; for (const auto& item : other.m_captureToolObjects) { QPointer<CaptureTool> itemCopy = item->copy(item->parent()); if (count < this->m_captureToolObjects.size()) { this->m_captureToolObjects[count] = itemCopy; } else { this->m_captureToolObjects.append(itemCopy); } count++; } return *this; }
4,990
C++
.cpp
144
26.708333
80
0.609362
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,695
selectionwidget.cpp
flameshot-org_flameshot/src/widgets/capture/selectionwidget.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "selectionwidget.h" #include "capturetool.h" #include "capturetoolbutton.h" #include "src/utils/globalvalues.h" #include <QApplication> #include <QEvent> #include <QMouseEvent> #include <QPainter> #include <QPropertyAnimation> #include <QTimer> #include <utility> #define MARGIN (m_THandle.width()) SelectionWidget::SelectionWidget(QColor c, QWidget* parent) : QWidget(parent) , m_color(std::move(c)) , m_activeSide(NO_SIDE) , m_ignoreMouse(false) { // prevents this widget from consuming CaptureToolButton mouse events setAttribute(Qt::WA_TransparentForMouseEvents); parent->installEventFilter(this); m_animation = new QPropertyAnimation(this, "geometry", this); m_animation->setEasingCurve(QEasingCurve::InOutQuad); m_animation->setDuration(200); connect(m_animation, &QPropertyAnimation::finished, this, [this]() { emit geometrySettled(); }); int sideVal = GlobalValues::buttonBaseSize() * 0.6; int handleSide = sideVal / 2; const QRect areaRect(0, 0, sideVal, sideVal); const QRect handleRect(0, 0, handleSide, handleSide); m_TLHandle = m_TRHandle = m_BLHandle = m_BRHandle = m_LHandle = m_THandle = m_RHandle = m_BHandle = handleRect; m_TLArea = m_TRArea = m_BLArea = m_BRArea = areaRect; m_areaOffset = QPoint(-sideVal / 2, -sideVal / 2); m_handleOffset = QPoint(-handleSide / 2, -handleSide / 2); } /** * @brief Get the side where the mouse cursor is. * @param mousePos Mouse cursor position relative to the parent widget. */ SelectionWidget::SideType SelectionWidget::getMouseSide( const QPoint& mousePos) const { if (!isVisible()) { return NO_SIDE; } QPoint localPos = mapFromParent(mousePos); if (m_TLArea.contains(localPos)) { return TOPLEFT_SIDE; } else if (m_TRArea.contains(localPos)) { return TOPRIGHT_SIDE; } else if (m_BLArea.contains(localPos)) { return BOTTOMLEFT_SIDE; } else if (m_BRArea.contains(localPos)) { return BOTTOMRIGHT_SIDE; } else if (m_LArea.contains(localPos)) { return LEFT_SIDE; } else if (m_TArea.contains(localPos)) { return TOP_SIDE; } else if (m_RArea.contains(localPos)) { return RIGHT_SIDE; } else if (m_BArea.contains(localPos)) { return BOTTOM_SIDE; } else if (rect().contains(localPos)) { return CENTER; } else { return NO_SIDE; } } QVector<QRect> SelectionWidget::handlerAreas() { QVector<QRect> areas; areas << m_TLHandle << m_TRHandle << m_BLHandle << m_BRHandle << m_LHandle << m_THandle << m_RHandle << m_BHandle; return areas; } // helper function SelectionWidget::SideType getProperSide(SelectionWidget::SideType side, const QRect& r) { using SideType = SelectionWidget::SideType; int intSide = side; if (r.right() < r.left()) { intSide ^= SideType::LEFT_SIDE; intSide ^= SideType::RIGHT_SIDE; } if (r.bottom() < r.top()) { intSide ^= SideType::TOP_SIDE; intSide ^= SideType::BOTTOM_SIDE; } return (SideType)intSide; } void SelectionWidget::setIgnoreMouse(bool ignore) { m_ignoreMouse = ignore; updateCursor(); } /** * Set the cursor that will be active when the mouse is inside the selection and * the mouse is not clicked. */ void SelectionWidget::setIdleCentralCursor(const QCursor& cursor) { m_idleCentralCursor = cursor; } void SelectionWidget::setGeometryAnimated(const QRect& r) { if (isVisible()) { m_animation->setStartValue(geometry()); m_animation->setEndValue(r); m_animation->start(); } } void SelectionWidget::setGeometry(const QRect& r) { QWidget::setGeometry(r + QMargins(MARGIN, MARGIN, MARGIN, MARGIN)); updateCursor(); if (isVisible()) { emit geometryChanged(); } } QRect SelectionWidget::geometry() const { return QWidget::geometry() - QMargins(MARGIN, MARGIN, MARGIN, MARGIN); } QRect SelectionWidget::fullGeometry() const { return QWidget::geometry(); } QRect SelectionWidget::rect() const { return QWidget::rect() - QMargins(MARGIN, MARGIN, MARGIN, MARGIN); } bool SelectionWidget::eventFilter(QObject* obj, QEvent* event) { if (m_ignoreMouse && dynamic_cast<QMouseEvent*>(event)) { m_activeSide = NO_SIDE; unsetCursor(); } else if (event->type() == QEvent::MouseButtonRelease) { parentMouseReleaseEvent(static_cast<QMouseEvent*>(event)); } else if (event->type() == QEvent::MouseButtonPress) { parentMousePressEvent(static_cast<QMouseEvent*>(event)); } else if (event->type() == QEvent::MouseMove) { parentMouseMoveEvent(static_cast<QMouseEvent*>(event)); } return false; } void SelectionWidget::parentMousePressEvent(QMouseEvent* e) { if (e->button() != Qt::LeftButton) { return; } m_dragStartPos = e->pos(); m_activeSide = getMouseSide(e->pos()); } void SelectionWidget::parentMouseReleaseEvent(QMouseEvent* e) { // released outside of the selection area if (!getMouseSide(e->pos())) { hide(); } m_activeSide = NO_SIDE; updateCursor(); emit geometrySettled(); } void SelectionWidget::parentMouseMoveEvent(QMouseEvent* e) { updateCursor(); if (e->buttons() != Qt::LeftButton) { return; } SideType mouseSide = m_activeSide; if (!m_activeSide) { mouseSide = getMouseSide(e->pos()); } QPoint pos; if (!isVisible() || !mouseSide) { show(); m_activeSide = TOPLEFT_SIDE; pos = m_dragStartPos; setGeometry({ pos, pos }); } else { pos = e->pos(); } auto geom = geometry(); float aspectRatio = (float)geom.width() / (float)geom.height(); bool symmetryMod = qApp->keyboardModifiers() & Qt::ShiftModifier; bool preserveAspect = qApp->keyboardModifiers() & Qt::ControlModifier; QPoint newTopLeft = geom.topLeft(), newBottomRight = geom.bottomRight(); int oldLeft = newTopLeft.rx(), oldRight = newBottomRight.rx(), oldTop = newTopLeft.ry(), oldBottom = newBottomRight.ry(); int &newLeft = newTopLeft.rx(), &newRight = newBottomRight.rx(), &newTop = newTopLeft.ry(), &newBottom = newBottomRight.ry(); switch (mouseSide) { case TOPLEFT_SIDE: if (m_activeSide) { if (preserveAspect) { if ((float)(oldRight - pos.x()) / (float)(oldBottom - pos.y()) > aspectRatio) { /* width longer than expected width, hence increase * height to compensate for the aspect ratio */ newLeft = pos.x(); newTop = oldBottom - (int)(((float)(oldRight - pos.x())) / aspectRatio); } else { /* height longer than expected height, hence increase * width to compensate for the aspect ratio */ newTop = pos.y(); newLeft = oldRight - (int)(((float)(oldBottom - pos.y())) * aspectRatio); } } else { newTopLeft = pos; } } break; case BOTTOMRIGHT_SIDE: if (m_activeSide) { if (preserveAspect) { if ((float)(pos.x() - oldLeft) / (float)(pos.y() - oldTop) > aspectRatio) { newRight = pos.x(); newBottom = oldTop + (int)(((float)(pos.x() - oldLeft)) / aspectRatio); } else { newBottom = pos.y(); newRight = oldLeft + (int)(((float)(pos.y() - oldTop)) * aspectRatio); } } else { newBottomRight = pos; } } break; case TOPRIGHT_SIDE: if (m_activeSide) { if (preserveAspect) { if ((float)(pos.x() - oldLeft) / (float)(oldBottom - pos.y()) > aspectRatio) { newRight = pos.x(); newTop = oldBottom - (int)(((float)(pos.x() - oldLeft)) / aspectRatio); } else { newTop = pos.y(); newRight = oldLeft + (int)(((float)(oldBottom - pos.y())) * aspectRatio); } } else { newTop = pos.y(); newRight = pos.x(); } } break; case BOTTOMLEFT_SIDE: if (m_activeSide) { if (preserveAspect) { if ((float)(oldRight - pos.x()) / (float)(pos.y() - oldTop) > aspectRatio) { newLeft = pos.x(); newBottom = oldTop + (int)(((float)(oldRight - pos.x())) / aspectRatio); } else { newBottom = pos.y(); newLeft = oldRight - (int)(((float)(pos.y() - oldTop)) * aspectRatio); } } else { newBottom = pos.y(); newLeft = pos.x(); } } break; case LEFT_SIDE: if (m_activeSide) { newLeft = pos.x(); if (preserveAspect) { /* By default bottom edge moves when dragging sides, this * behavior feels natural */ newBottom = oldTop + (int)(((float)(oldRight - pos.x())) / aspectRatio); } } break; case RIGHT_SIDE: if (m_activeSide) { newRight = pos.x(); if (preserveAspect) { newBottom = oldTop + (int)(((float)(pos.x() - oldLeft)) / aspectRatio); } } break; case TOP_SIDE: if (m_activeSide) { newTop = pos.y(); if (preserveAspect) { /* By default right edge moves when dragging sides, this * behavior feels natural */ newRight = oldLeft + (int)(((float)(oldBottom - pos.y()) * aspectRatio)); } } break; case BOTTOM_SIDE: if (m_activeSide) { newBottom = pos.y(); if (preserveAspect) { newRight = oldLeft + (int)(((float)(pos.y() - oldTop) * aspectRatio)); } } break; default: if (m_activeSide) { move(this->pos() + pos - m_dragStartPos); m_dragStartPos = pos; /* do nothing special in case of preserveAspect */ } return; } // finalize geometry change if (m_activeSide) { if (symmetryMod) { QPoint deltaTopLeft = newTopLeft - geom.topLeft(); QPoint deltaBottomRight = newBottomRight - geom.bottomRight(); newTopLeft = geom.topLeft() + deltaTopLeft - deltaBottomRight; newBottomRight = geom.bottomRight() + deltaBottomRight - deltaTopLeft; } geom = { newTopLeft, newBottomRight }; setGeometry(geom.normalized()); m_activeSide = getProperSide(m_activeSide, geom); } m_dragStartPos = e->pos(); } void SelectionWidget::paintEvent(QPaintEvent*) { QPainter p(this); p.setPen(m_color); p.drawRect(rect() + QMargins(0, 0, -1, -1)); p.setRenderHint(QPainter::Antialiasing); p.setBrush(m_color); for (auto rectangle : handlerAreas()) { p.drawEllipse(rectangle); } } void SelectionWidget::resizeEvent(QResizeEvent*) { updateAreas(); if (isVisible()) { emit geometryChanged(); } } void SelectionWidget::moveEvent(QMoveEvent*) { updateAreas(); if (isVisible()) { emit geometryChanged(); } } void SelectionWidget::showEvent(QShowEvent*) { emit visibilityChanged(); } void SelectionWidget::hideEvent(QHideEvent*) { emit visibilityChanged(); } void SelectionWidget::updateColor(const QColor& c) { m_color = c; } void SelectionWidget::moveLeft() { setGeometryByKeyboard(geometry().adjusted(-1, 0, -1, 0)); } void SelectionWidget::moveRight() { setGeometryByKeyboard(geometry().adjusted(1, 0, 1, 0)); } void SelectionWidget::moveUp() { setGeometryByKeyboard(geometry().adjusted(0, -1, 0, -1)); } void SelectionWidget::moveDown() { setGeometryByKeyboard(geometry().adjusted(0, 1, 0, 1)); } void SelectionWidget::resizeLeft() { setGeometryByKeyboard(geometry().adjusted(0, 0, -1, 0)); } void SelectionWidget::resizeRight() { setGeometryByKeyboard(geometry().adjusted(0, 0, 1, 0)); } void SelectionWidget::resizeUp() { setGeometryByKeyboard(geometry().adjusted(0, 0, 0, -1)); } void SelectionWidget::resizeDown() { setGeometryByKeyboard(geometry().adjusted(0, 0, 0, 1)); } void SelectionWidget::symResizeLeft() { setGeometryByKeyboard(geometry().adjusted(1, 0, -1, 0)); } void SelectionWidget::symResizeRight() { setGeometryByKeyboard(geometry().adjusted(-1, 0, 1, 0)); } void SelectionWidget::symResizeUp() { setGeometryByKeyboard(geometry().adjusted(0, -1, 0, 1)); } void SelectionWidget::symResizeDown() { setGeometryByKeyboard(geometry().adjusted(0, 1, 0, -1)); } void SelectionWidget::updateAreas() { QRect r = rect(); m_TLArea.moveTo(r.topLeft() + m_areaOffset); m_TRArea.moveTo(r.topRight() + m_areaOffset); m_BLArea.moveTo(r.bottomLeft() + m_areaOffset); m_BRArea.moveTo(r.bottomRight() + m_areaOffset); m_LArea = QRect(m_TLArea.bottomLeft(), m_BLArea.topRight()); m_TArea = QRect(m_TLArea.topRight(), m_TRArea.bottomLeft()); m_RArea = QRect(m_TRArea.bottomLeft(), m_BRArea.topRight()); m_BArea = QRect(m_BLArea.topRight(), m_BRArea.bottomLeft()); m_TLHandle.moveTo(m_TLArea.center() + m_handleOffset); m_BLHandle.moveTo(m_BLArea.center() + m_handleOffset); m_TRHandle.moveTo(m_TRArea.center() + m_handleOffset); m_BRHandle.moveTo(m_BRArea.center() + m_handleOffset); m_LHandle.moveTo(m_LArea.center() + m_handleOffset); m_THandle.moveTo(m_TArea.center() + m_handleOffset); m_RHandle.moveTo(m_RArea.center() + m_handleOffset); m_BHandle.moveTo(m_BArea.center() + m_handleOffset); } void SelectionWidget::updateCursor() { SideType mouseSide = m_activeSide; if (!m_activeSide) { mouseSide = getMouseSide(parentWidget()->mapFromGlobal(QCursor::pos())); } switch (mouseSide) { case TOPLEFT_SIDE: setCursor(Qt::SizeFDiagCursor); break; case BOTTOMRIGHT_SIDE: setCursor(Qt::SizeFDiagCursor); break; case TOPRIGHT_SIDE: setCursor(Qt::SizeBDiagCursor); break; case BOTTOMLEFT_SIDE: setCursor(Qt::SizeBDiagCursor); break; case LEFT_SIDE: setCursor(Qt::SizeHorCursor); break; case RIGHT_SIDE: setCursor(Qt::SizeHorCursor); break; case TOP_SIDE: setCursor(Qt::SizeVerCursor); break; case BOTTOM_SIDE: setCursor(Qt::SizeVerCursor); break; default: if (m_activeSide) { setCursor(Qt::ClosedHandCursor); } else { setCursor(m_idleCentralCursor); return; } break; } } void SelectionWidget::setGeometryByKeyboard(const QRect& r) { static QTimer timer; QRect rectangle = r.intersected(parentWidget()->rect()); if (rectangle.width() <= 0) { rectangle.setWidth(1); } if (rectangle.height() <= 0) { rectangle.setHeight(1); } setGeometry(rectangle); connect(&timer, &QTimer::timeout, this, &SelectionWidget::geometrySettled, Qt::UniqueConnection); timer.start(400); }
16,995
C++
.cpp
512
24.066406
80
0.560168
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,696
colorpicker.cpp
flameshot-org_flameshot/src/widgets/capture/colorpicker.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "colorpicker.h" #include "src/utils/confighandler.h" #include "src/utils/globalvalues.h" #include <QMouseEvent> #include <QPainter> ColorPicker::ColorPicker(QWidget* parent) : ColorPickerWidget(parent) { setMouseTracking(true); ConfigHandler config; QColor drawColor = config.drawColor(); for (int i = 0; i < m_colorList.size(); ++i) { if (m_colorList.at(i) == drawColor) { m_selectedIndex = i; m_lastIndex = i; break; } } } void ColorPicker::mouseMoveEvent(QMouseEvent* e) { for (int i = 0; i < m_colorList.size(); ++i) { if (m_colorAreaList.at(i).contains(e->pos())) { m_selectedIndex = i; update(m_colorAreaList.at(i) + QMargins(10, 10, 10, 10)); update(m_colorAreaList.at(m_lastIndex) + QMargins(10, 10, 10, 10)); m_lastIndex = i; break; } } } void ColorPicker::showEvent(QShowEvent* event) { grabMouse(); } void ColorPicker::hideEvent(QHideEvent* event) { releaseMouse(); emit colorSelected(m_colorList.at(m_selectedIndex)); }
1,238
C++
.cpp
42
24.214286
79
0.642797
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,697
capturebutton.cpp
flameshot-org_flameshot/src/widgets/capture/capturebutton.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "capturebutton.h" #include "src/utils/colorutils.h" #include "src/utils/confighandler.h" #include "src/utils/globalvalues.h" #include <QGraphicsDropShadowEffect> CaptureButton::CaptureButton(QWidget* parent) : QPushButton(parent) { init(); } CaptureButton::CaptureButton(const QString& text, QWidget* parent) : QPushButton(text, parent) { init(); } CaptureButton::CaptureButton(const QIcon& icon, const QString& text, QWidget* parent) : QPushButton(icon, text, parent) { init(); } void CaptureButton::init() { setCursor(Qt::ArrowCursor); setFocusPolicy(Qt::NoFocus); auto* dsEffect = new QGraphicsDropShadowEffect(this); dsEffect->setBlurRadius(5); dsEffect->setOffset(0); dsEffect->setColor(QColor(Qt::black)); setGraphicsEffect(dsEffect); } QString CaptureButton::globalStyleSheet() { return CaptureButton(nullptr).styleSheet(); } QString CaptureButton::styleSheet() const { QString baseSheet = "CaptureButton { border: none;" "padding: 3px 8px;" "background-color: %1; color: %4 }" "CaptureToolButton { border-radius: %3;" "padding: 0; }" "CaptureButton:hover { background-color: %2; }" "CaptureButton:pressed:!hover { " "background-color: %1; }"; // define color when mouse is hovering QColor contrast = ColorUtils::contrastColor(m_mainColor); // foreground color QColor color = ColorUtils::colorIsDark(m_mainColor) ? Qt::white : Qt::black; return baseSheet.arg(m_mainColor.name()) .arg(contrast.name()) .arg(GlobalValues::buttonBaseSize() / 2) .arg(color.name()); } void CaptureButton::setColor(const QColor& c) { m_mainColor = c; setStyleSheet(styleSheet()); } QColor CaptureButton::m_mainColor;
2,067
C++
.cpp
63
26.444444
80
0.653112
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,698
magnifierwidget.cpp
flameshot-org_flameshot/src/widgets/capture/magnifierwidget.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "magnifierwidget.h" #include <QApplication> #include <QEvent> #include <QMouseEvent> #include <QPainter> #include <QPainterPath> #include <QPen> #include <QPixmap> MagnifierWidget::MagnifierWidget(const QPixmap& p, const QColor& c, bool isSquare, QWidget* parent) : QWidget(parent) , m_color(c) , m_borderColor(c) , m_screenshot(p) , m_square(isSquare) { setFixedSize(parent->width(), parent->height()); setAttribute(Qt::WA_TransparentForMouseEvents); m_color.setAlpha(130); // add padding for circular magnifier QImage padded(p.width() + 2 * m_magPixels, p.height() + 2 * m_magPixels, QImage::Format_ARGB32); padded.fill(Qt::black); QPainter painter(&padded); painter.drawPixmap(m_magPixels, m_magPixels, p); m_paddedScreenshot.convertFromImage(padded); } void MagnifierWidget::paintEvent(QPaintEvent*) { QPainter p(this); if (m_square) { drawMagnifier(p); } else { drawMagnifierCircle(p); } } void MagnifierWidget::drawMagnifierCircle(QPainter& painter) { auto relativeCursor = QCursor::pos(); auto translated = QWidget::mapFromGlobal(relativeCursor); auto x = translated.x() + m_magPixels; auto y = translated.y() + m_magPixels; int magX = static_cast<int>(x * m_devicePixelRatio - m_magPixels); int magY = static_cast<int>(y * m_devicePixelRatio - m_magPixels); QRectF magniRect(magX, magY, m_pixels, m_pixels); qreal drawPosX = x + m_magOffset + m_pixels * magZoom / 2; if (drawPosX > width() - m_pixels * magZoom / 2) { drawPosX = x - m_magOffset - m_pixels * magZoom / 2; } qreal drawPosY = y + m_magOffset + m_pixels * magZoom / 2; if (drawPosY > height() - m_pixels * magZoom / 2) { drawPosY = y - m_magOffset - m_pixels * magZoom / 2; } QPointF drawPos(drawPosX, drawPosY); QRectF crossHairTop(drawPos.x() + magZoom * (-0.5), drawPos.y() - magZoom * (m_magPixels + 0.5), magZoom, magZoom * (m_magPixels)); QRectF crossHairRight(drawPos.x() + magZoom * (0.5), drawPos.y() + magZoom * (-0.5), magZoom * (m_magPixels), magZoom); QRectF crossHairBottom(drawPos.x() + magZoom * (-0.5), drawPos.y() + magZoom * (0.5), magZoom, magZoom * (m_magPixels)); QRectF crossHairLeft(drawPos.x() - magZoom * (m_magPixels + 0.5), drawPos.y() + magZoom * (-0.5), magZoom * (m_magPixels), magZoom); QRectF crossHairBorder(drawPos.x() - magZoom * (m_magPixels + 0.5) - 1, drawPos.y() - magZoom * (m_magPixels + 0.5) - 1, m_pixels * magZoom + 2, m_pixels * magZoom + 2); const auto frag = QPainter::PixmapFragment::create(drawPos, magniRect, magZoom, magZoom); painter.setRenderHint(QPainter::Antialiasing, true); QPainterPath path = QPainterPath(); path.addEllipse(drawPos, m_pixels * magZoom / 2, m_pixels * magZoom / 2); painter.setClipPath(path); painter.drawPixmapFragments( &frag, 1, m_paddedScreenshot, QPainter::OpaqueHint); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); for (const auto& rect : { crossHairTop, crossHairRight, crossHairBottom, crossHairLeft }) { painter.fillRect(rect, m_color); } QPen pen(m_borderColor); pen.setWidth(4); painter.setPen(pen); painter.drawEllipse( drawPos, m_pixels * magZoom / 2, m_pixels * magZoom / 2); } // https://invent.kde.org/graphics/spectacle/-/blob/master/src/QuickEditor/QuickEditor.cpp#L841 void MagnifierWidget::drawMagnifier(QPainter& painter) { auto relativeCursor = QCursor::pos(); auto translated = QWidget::mapFromGlobal(relativeCursor); auto x = translated.x(); auto y = translated.y(); int magX = static_cast<int>(x * m_devicePixelRatio - m_magPixels); int offsetX = 0; if (magX < 0) { offsetX = magX; magX = 0; } else { const int maxX = m_screenshot.width() - m_pixels; if (magX > maxX) { offsetX = magX - maxX; magX = maxX; } } int magY = static_cast<int>(y * m_devicePixelRatio - m_magPixels); int offsetY = 0; if (magY < 0) { offsetY = magY; magY = 0; } else { const int maxY = m_screenshot.height() - m_pixels; if (magY > maxY) { offsetY = magY - maxY; magY = maxY; } } QRectF magniRect(magX, magY, m_pixels, m_pixels); qreal drawPosX = x + m_magOffset + m_pixels * magZoom / 2; if (drawPosX > width() - m_pixels * magZoom / 2) { drawPosX = x - m_magOffset - m_pixels * magZoom / 2; } qreal drawPosY = y + m_magOffset + m_pixels * magZoom / 2; if (drawPosY > height() - m_pixels * magZoom / 2) { drawPosY = y - m_magOffset - m_pixels * magZoom / 2; } QPointF drawPos(drawPosX, drawPosY); QRectF crossHairTop(drawPos.x() + magZoom * (offsetX - 0.5), drawPos.y() - magZoom * (m_magPixels + 0.5), magZoom, magZoom * (m_magPixels + offsetY)); QRectF crossHairRight(drawPos.x() + magZoom * (0.5 + offsetX), drawPos.y() + magZoom * (offsetY - 0.5), magZoom * (m_magPixels - offsetX), magZoom); QRectF crossHairBottom(drawPos.x() + magZoom * (offsetX - 0.5), drawPos.y() + magZoom * (0.5 + offsetY), magZoom, magZoom * (m_magPixels - offsetY)); QRectF crossHairLeft(drawPos.x() - magZoom * (m_magPixels + 0.5), drawPos.y() + magZoom * (offsetY - 0.5), magZoom * (m_magPixels + offsetX), magZoom); QRectF crossHairBorder(drawPos.x() - magZoom * (m_magPixels + 0.5) - 1, drawPos.y() - magZoom * (m_magPixels + 0.5) - 1, m_pixels * magZoom + 2, m_pixels * magZoom + 2); const auto frag = QPainter::PixmapFragment::create(drawPos, magniRect, magZoom, magZoom); painter.fillRect(crossHairBorder, m_borderColor); painter.drawPixmapFragments(&frag, 1, m_screenshot, QPainter::OpaqueHint); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); for (const auto& rect : { crossHairTop, crossHairRight, crossHairBottom, crossHairLeft }) { painter.fillRect(rect, m_color); } }
7,049
C++
.cpp
169
31.982249
95
0.573362
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,700
screengrabber.cpp
flameshot-org_flameshot/src/utils/screengrabber.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "screengrabber.h" #include "abstractlogger.h" #include "src/core/qguiappcurrentscreen.h" #include "src/utils/confighandler.h" #include "src/utils/filenamehandler.h" #include "src/utils/systemnotification.h" #include <QApplication> #include <QDesktopWidget> #include <QGuiApplication> #include <QPixmap> #include <QProcess> #include <QScreen> #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) #include "request.h" #include <QDBusInterface> #include <QDBusReply> #include <QDir> #include <QUrl> #include <QUuid> #endif ScreenGrabber::ScreenGrabber(QObject* parent) : QObject(parent) {} void ScreenGrabber::generalGrimScreenshot(bool& ok, QPixmap& res) { #ifdef USE_WAYLAND_GRIM #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) QProcess Process; QString program = "grim"; QStringList arguments; arguments << "-"; Process.start(program, arguments); if (Process.waitForFinished()) { res.loadFromData(Process.readAll()); ok = true; } else { ok = false; AbstractLogger::error() << tr("The universal wayland screen capture adapter requires Grim as " "the screen capture component of wayland. If the screen " "capture component is missing, please install it!"); } #endif #endif } void ScreenGrabber::freeDesktopPortal(bool& ok, QPixmap& res) { #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) QDBusInterface screenshotInterface( QStringLiteral("org.freedesktop.portal.Desktop"), QStringLiteral("/org/freedesktop/portal/desktop"), QStringLiteral("org.freedesktop.portal.Screenshot")); // unique token QString token = QUuid::createUuid().toString().remove('-').remove('{').remove('}'); // premake interface auto* request = new OrgFreedesktopPortalRequestInterface( QStringLiteral("org.freedesktop.portal.Desktop"), "/org/freedesktop/portal/desktop/request/" + QDBusConnection::sessionBus().baseService().remove(':').replace('.', '_') + "/" + token, QDBusConnection::sessionBus(), this); QEventLoop loop; const auto gotSignal = [&res, &loop](uint status, const QVariantMap& map) { if (status == 0) { // Parse this as URI to handle unicode properly QUrl uri = map.value("uri").toString(); QString uriString = uri.toLocalFile(); res = QPixmap(uriString); res.setDevicePixelRatio(qApp->devicePixelRatio()); QFile imgFile(uriString); imgFile.remove(); } loop.quit(); }; // prevent racy situations and listen before calling screenshot QMetaObject::Connection conn = QObject::connect( request, &org::freedesktop::portal::Request::Response, gotSignal); screenshotInterface.call( QStringLiteral("Screenshot"), "", QMap<QString, QVariant>({ { "handle_token", QVariant(token) }, { "interactive", QVariant(false) } })); loop.exec(); QObject::disconnect(conn); request->Close().waitForFinished(); request->deleteLater(); if (res.isNull()) { ok = false; } #endif } QPixmap ScreenGrabber::grabEntireDesktop(bool& ok) { ok = true; #if defined(Q_OS_MACOS) QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen(); QPixmap screenPixmap( currentScreen->grabWindow(QApplication::desktop()->winId(), currentScreen->geometry().x(), currentScreen->geometry().y(), currentScreen->geometry().width(), currentScreen->geometry().height())); screenPixmap.setDevicePixelRatio(currentScreen->devicePixelRatio()); return screenPixmap; #elif defined(Q_OS_LINUX) || defined(Q_OS_UNIX) if (m_info.waylandDetected()) { QPixmap res; // handle screenshot based on DE switch (m_info.windowManager()) { case DesktopInfo::GNOME: case DesktopInfo::KDE: freeDesktopPortal(ok, res); break; case DesktopInfo::QTILE: case DesktopInfo::SWAY: case DesktopInfo::HYPRLAND: case DesktopInfo::OTHER: { #ifndef USE_WAYLAND_GRIM AbstractLogger::warning() << tr( "If the USE_WAYLAND_GRIM option is not activated, the dbus " "protocol will be used. It should be noted that using the " "dbus protocol under wayland is not recommended. It is " "recommended to recompile with the USE_WAYLAND_GRIM flag to " "activate the grim-based general wayland screenshot adapter"); freeDesktopPortal(ok, res); #else if (!ConfigHandler().disabledGrimWarning()) { AbstractLogger::warning() << tr( "grim's screenshot component is implemented based on " "wlroots, it may not be used in GNOME or similar " "desktop environments"); } generalGrimScreenshot(ok, res); #endif break; } default: ok = false; AbstractLogger::error() << tr("Unable to detect desktop environment (GNOME? KDE? " "Qile? Sway? ...)"); AbstractLogger::error() << tr("Hint: try setting the XDG_CURRENT_DESKTOP environment " "variable."); break; } if (!ok) { AbstractLogger::error() << tr("Unable to capture screen"); } return res; } #endif #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) || defined(Q_OS_WIN) QRect geometry = desktopGeometry(); QPixmap p(QApplication::primaryScreen()->grabWindow( QApplication::desktop()->winId(), geometry.x(), geometry.y(), geometry.width(), geometry.height())); auto screenNumber = QApplication::desktop()->screenNumber(); QScreen* screen = QApplication::screens()[screenNumber]; p.setDevicePixelRatio(screen->devicePixelRatio()); return p; #endif } QRect ScreenGrabber::screenGeometry(QScreen* screen) { QPixmap p; QRect geometry; if (m_info.waylandDetected()) { QPoint topLeft(0, 0); #ifdef Q_OS_WIN for (QScreen* const screen : QGuiApplication::screens()) { QPoint topLeftScreen = screen->geometry().topLeft(); if (topLeft.x() > topLeftScreen.x() || topLeft.y() > topLeftScreen.y()) { topLeft = topLeftScreen; } } #endif geometry = screen->geometry(); geometry.moveTo(geometry.topLeft() - topLeft); } else { QScreen* currentScreen = QGuiAppCurrentScreen().currentScreen(); geometry = currentScreen->geometry(); } return geometry; } QPixmap ScreenGrabber::grabScreen(QScreen* screen, bool& ok) { QPixmap p; QRect geometry = screenGeometry(screen); if (m_info.waylandDetected()) { p = grabEntireDesktop(ok); if (ok) { return p.copy(geometry); } } else { ok = true; return screen->grabWindow(QApplication::desktop()->winId(), geometry.x(), geometry.y(), geometry.width(), geometry.height()); } return p; } QRect ScreenGrabber::desktopGeometry() { QRect geometry; for (QScreen* const screen : QGuiApplication::screens()) { QRect scrRect = screen->geometry(); scrRect.moveTo(scrRect.x() / screen->devicePixelRatio(), scrRect.y() / screen->devicePixelRatio()); geometry = geometry.united(scrRect); } return geometry; }
8,114
C++
.cpp
224
27.383929
80
0.599644
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,701
pathinfo.cpp
flameshot-org_flameshot/src/utils/pathinfo.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "pathinfo.h" #include <QApplication> #include <QDir> #include <QFileInfo> const QString PathInfo::whiteIconPath() { return QStringLiteral(":/img/material/white/"); } const QString PathInfo::blackIconPath() { return QStringLiteral(":/img/material/black/"); } QStringList PathInfo::translationsPaths() { QString binaryPath = QFileInfo(qApp->applicationDirPath()).absoluteFilePath(); QString trPath = QDir::toNativeSeparators(binaryPath + "/translations"); #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) return QStringList() << QStringLiteral(APP_PREFIX) + "/share/flameshot/translations" << trPath << QStringLiteral("/usr/share/flameshot/translations") << QStringLiteral("/usr/local/share/flameshot/translations"); #endif return QStringList() << trPath; }
947
C++
.cpp
27
31.592593
76
0.732533
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,702
strfparse.cpp
flameshot-org_flameshot/src/utils/strfparse.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2021 Jeremy Borgman #include "strfparse.h" namespace strfparse { std::vector<std::string> split(std::string const& s, char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } std::vector<char> create_specifier_list() { std::vector<char> allowed_specifier{ 'Y', 'H', 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'F', 'g', 'G', 'h', 'H', 'I', 'j', 'm', 'M', 'n', 'p', 'r', 'R', 'S', 't', 'T', 'u', 'U', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z' }; return allowed_specifier; } std::string replace_all(std::string input, std::string const& to_find, std::string const& to_replace) { size_t pos = 0; while ((pos = input.find(to_find, pos)) != std::string::npos) { input.replace(pos, to_find.length(), to_replace); pos += to_replace.length(); } return input; } std::vector<char> match_specifiers(std::string const& specifier, std::vector<char> allowed_specifier) { std::vector<char> spec_list; for (size_t i = 0; i < specifier.size() - 1; i++) { if (specifier[i] == '%') { spec_list.push_back(specifier[i + 1]); } } std::sort(spec_list.begin(), spec_list.end()); std::sort(allowed_specifier.begin(), allowed_specifier.end()); std::vector<char> overlap; std::set_intersection(spec_list.begin(), spec_list.end(), allowed_specifier.begin(), allowed_specifier.end(), back_inserter(overlap)); return overlap; } std::string format_time_string(std::string const& specifier) { if (specifier.empty()) { return ""; } std::time_t t = std::time(nullptr); char buff[100]; auto allowed_specifier = create_specifier_list(); auto overlap = match_specifiers(specifier, allowed_specifier); // Create "Safe" string for strftime which is the specfiers delimited by * std::string lookup_string; for (auto const& e : overlap) { lookup_string.push_back('%'); lookup_string.push_back(e); lookup_string.push_back('*'); } std::strftime( buff, sizeof(buff), lookup_string.c_str(), std::localtime(&t)); std::map<char, std::string> lookup_table; auto result = split(buff, '*'); for (size_t i = 0; i < result.size(); i++) { lookup_table.emplace(std::make_pair(overlap[i], result[i])); } // Sub into original string std::string delim = "%"; auto output_string = specifier; for (auto const& row : lookup_table) { auto to_find = delim + row.first; output_string = replace_all(output_string, to_find, row.second); } return output_string; } }
3,172
C++
.cpp
86
28.313953
80
0.548303
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,703
colorutils.cpp
flameshot-org_flameshot/src/utils/colorutils.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "colorutils.h" inline qreal getColorLuma(const QColor& c) { return 0.30 * c.redF() + 0.59 * c.greenF() + 0.11 * c.blueF(); } bool ColorUtils::colorIsDark(const QColor& c) { // when luma <= 0.5, we considor it as a dark color return getColorLuma(c) <= 0.5; } QColor ColorUtils::contrastColor(const QColor& c) { int change = colorIsDark(c) ? 30 : -45; return { qBound(0, c.red() + change, 255), qBound(0, c.green() + change, 255), qBound(0, c.blue() + change, 255) }; }
646
C++
.cpp
19
30.315789
72
0.651125
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,705
valuehandler.cpp
flameshot-org_flameshot/src/utils/valuehandler.cpp
#include "valuehandler.h" #include "capturetool.h" #include "colorpickerwidget.h" #include "confighandler.h" #include "screengrabber.h" #include <QColor> #include <QFileInfo> #include <QImageWriter> #include <QKeySequence> #include <QStandardPaths> #include <QVariant> // VALUE HANDLER QVariant ValueHandler::value(const QVariant& val) { if (!val.isValid() || !check(val)) { return fallback(); } else { return process(val); } } QVariant ValueHandler::fallback() { return {}; } QVariant ValueHandler::representation(const QVariant& val) { return val.toString(); } QString ValueHandler::expected() { return {}; } QVariant ValueHandler::process(const QVariant& val) { return val; } // BOOL Bool::Bool(bool def) : m_def(def) {} bool Bool::check(const QVariant& val) { QString str = val.toString(); if (str != "true" && str != "false") { return false; } return true; } QVariant Bool::fallback() { return m_def; } QString Bool::expected() { return QStringLiteral("true or false"); } // STRING String::String(QString def) : m_def(std::move(def)) {} bool String::check(const QVariant&) { return true; } QVariant String::fallback() { return m_def; } QString String::expected() { return QStringLiteral("string"); } // COLOR Color::Color(QColor def) : m_def(std::move(def)) {} bool Color::check(const QVariant& val) { QString str = val.toString(); // Disable #RGB, #RRRGGGBBB and #RRRRGGGGBBBB formats that QColor supports return QColor::isValidColor(str) && (str[0] != '#' || (str.length() != 4 && str.length() != 10 && str.length() != 13)); } QVariant Color::process(const QVariant& val) { QString str = val.toString(); QColor color(str); if (str.length() == 9 && str[0] == '#') { // Convert #RRGGBBAA (flameshot) to #AARRGGBB (QColor) int blue = color.blue(); color.setBlue(color.green()); color.setGreen(color.red()); color.setRed(color.alpha()); color.setAlpha(blue); } return color; } QVariant Color::fallback() { return m_def; } QVariant Color::representation(const QVariant& val) { QString str = val.toString(); QColor color(str); if (str.length() == 9 && str[0] == '#') { // Convert #AARRGGBB (QColor) to #RRGGBBAA (flameshot) int alpha = color.alpha(); color.setAlpha(color.red()); color.setRed(color.green()); color.setGreen(color.blue()); color.setBlue(alpha); } return color.name(); } QString Color::expected() { return QStringLiteral("color name or hex value"); } // BOUNDED INT BoundedInt::BoundedInt(int min, int max, int def) : m_min(min) , m_max(max) , m_def(def) {} bool BoundedInt::check(const QVariant& val) { QString str = val.toString(); bool conversionOk; int num = str.toInt(&conversionOk); return conversionOk && m_min <= num && num <= m_max; } QVariant BoundedInt::fallback() { return m_def; } QString BoundedInt::expected() { return QStringLiteral("number between %1 and %2").arg(m_min).arg(m_max); } // LOWER BOUNDED INT LowerBoundedInt::LowerBoundedInt(int min, int def) : m_min(min) , m_def(def) {} bool LowerBoundedInt::check(const QVariant& val) { QString str = val.toString(); bool conversionOk; int num = str.toInt(&conversionOk); return conversionOk && num >= m_min; } QVariant LowerBoundedInt::fallback() { return m_def; } QString LowerBoundedInt::expected() { return QStringLiteral("number >= %1").arg(m_min); } // KEY SEQUENCE KeySequence::KeySequence(const QKeySequence& fallback) : m_fallback(fallback) {} bool KeySequence::check(const QVariant& val) { QString str = val.toString(); if (!str.isEmpty() && QKeySequence(str).toString().isEmpty()) { return false; } return true; } QVariant KeySequence::fallback() { return process(m_fallback); } QString KeySequence::expected() { return QStringLiteral("keyboard shortcut"); } QVariant KeySequence::representation(const QVariant& val) { QString str(val.toString()); if (QKeySequence(str) == QKeySequence(Qt::Key_Return)) { return QStringLiteral("Enter"); } return str; } QVariant KeySequence::process(const QVariant& val) { QString str(val.toString()); if (str == "Enter") { return QKeySequence(Qt::Key_Return).toString(); } if (str.length() > 0) { // Make the "main" key in sequence (last one) lower-case. const QCharRef& lastChar = str[str.length() - 1]; str.replace(str.length() - 1, 1, lastChar.toLower()); } return str; } // EXISTING DIR bool ExistingDir::check(const QVariant& val) { if (!val.canConvert(QVariant::String) || val.toString().isEmpty()) { return false; } QFileInfo info(val.toString()); return info.isDir() && info.exists(); } QVariant ExistingDir::fallback() { using SP = QStandardPaths; for (auto location : { SP::PicturesLocation, SP::HomeLocation, SP::TempLocation }) { QString path = SP::writableLocation(location); if (QFileInfo(path).isDir()) { return path; } } return {}; } QString ExistingDir::expected() { return QStringLiteral("existing directory"); } // FILENAME PATTERN bool FilenamePattern::check(const QVariant&) { return true; } QVariant FilenamePattern::fallback() { return ConfigHandler().filenamePatternDefault(); } QVariant FilenamePattern::process(const QVariant& val) { QString str = val.toString(); return !str.isEmpty() ? val : fallback(); } QString FilenamePattern::expected() { return QStringLiteral("please edit using the GUI"); } // BUTTON LIST using BType = CaptureTool::Type; using BList = QList<CaptureTool::Type>; bool ButtonList::check(const QVariant& val) { // TODO stop using CTB using CTB = CaptureToolButton; auto allButtons = CTB::getIterableButtonTypes(); for (int btn : val.value<QList<int>>()) { if (!allButtons.contains(static_cast<BType>(btn))) { return false; } } return true; } // Helper void sortButtons(BList& buttons) { std::sort(buttons.begin(), buttons.end(), [](BType a, BType b) { return CaptureToolButton::getPriorityByButton(a) < CaptureToolButton::getPriorityByButton(b); }); } QVariant ButtonList::process(const QVariant& val) { auto intButtons = val.value<QList<int>>(); auto buttons = ButtonList::fromIntList(intButtons); sortButtons(buttons); return QVariant::fromValue(buttons); } QVariant ButtonList::fallback() { auto buttons = CaptureToolButton::getIterableButtonTypes(); buttons.removeOne(CaptureTool::TYPE_SIZEDECREASE); buttons.removeOne(CaptureTool::TYPE_SIZEINCREASE); sortButtons(buttons); return QVariant::fromValue(buttons); } QVariant ButtonList::representation(const QVariant& val) { auto intList = toIntList(val.value<BList>()); normalizeButtons(intList); return QVariant::fromValue(intList); } QString ButtonList::expected() { return QStringLiteral("please don't edit by hand"); } QList<CaptureTool::Type> ButtonList::fromIntList(const QList<int>& l) { QList<CaptureTool::Type> buttons; buttons.reserve(l.size()); for (auto const i : l) { buttons << static_cast<CaptureTool::Type>(i); } return buttons; } QList<int> ButtonList::toIntList(const QList<CaptureTool::Type>& l) { QList<int> buttons; buttons.reserve(l.size()); for (auto const i : l) { buttons << static_cast<int>(i); } return buttons; } bool ButtonList::normalizeButtons(QList<int>& buttons) { QList<int> listTypesInt = toIntList(CaptureToolButton::getIterableButtonTypes()); bool hasChanged = false; for (int i = 0; i < buttons.size(); i++) { if (!listTypesInt.contains(buttons.at(i))) { buttons.removeAt(i); hasChanged = true; } } return hasChanged; } // USER COLORS UserColors::UserColors(int min, int max) : m_min(min) , m_max(max) {} bool UserColors::check(const QVariant& val) { if (!val.isValid()) { return false; } if (!val.canConvert(QVariant::StringList)) { return false; } for (const QString& str : val.toStringList()) { if (!QColor::isValidColor(str) && str != "picker") { return false; } } int sz = val.toStringList().size(); return sz >= m_min && sz <= m_max; } QVariant UserColors::process(const QVariant& val) { QStringList strColors = val.toStringList(); if (strColors.isEmpty()) { return fallback(); } QVector<QColor> colors; colors.reserve(strColors.size()); for (const QString& str : strColors) { if (str != "picker") { colors.append(QColor(str)); } else { colors.append(QColor()); } } return QVariant::fromValue(colors); } QVariant UserColors::fallback() { if (ConfigHandler().predefinedColorPaletteLarge()) { return QVariant::fromValue( ColorPickerWidget::getDefaultLargeColorPalette()); } else { return QVariant::fromValue( ColorPickerWidget::getDefaultSmallColorPalette()); } } QString UserColors::expected() { return QStringLiteral( "list of colors(min %1 and max %2) separated by comma") .arg(m_min - 1) .arg(m_max - 1); } QVariant UserColors::representation(const QVariant& val) { auto colors = val.value<QVector<QColor>>(); QStringList strColors; for (const auto& col : colors) { if (col.isValid()) { strColors.append(col.name(QColor::HexRgb)); } else { strColors.append(QStringLiteral("picker")); } } return QVariant::fromValue(strColors); } // SET SAVE FILE AS EXTENSION bool SaveFileExtension::check(const QVariant& val) { if (!val.canConvert(QVariant::String) || val.toString().isEmpty()) { return false; } QString extension = val.toString(); if (extension.startsWith(".")) { extension.remove(0, 1); } QStringList imageFormatList; foreach (auto imageFormat, QImageWriter::supportedImageFormats()) imageFormatList.append(imageFormat); if (!imageFormatList.contains(extension)) { return false; } return true; } QVariant SaveFileExtension::process(const QVariant& val) { QString extension = val.toString(); if (extension.startsWith(".")) { extension.remove(0, 1); } return QVariant::fromValue(extension); } QString SaveFileExtension::expected() { return QStringLiteral("supported image extension"); } // REGION bool Region::check(const QVariant& val) { QVariant region = process(val); return region.isValid(); } #include <QApplication> // TODO remove after FIXME (see below) #include <utility> QVariant Region::process(const QVariant& val) { // FIXME: This is temporary, just before D-Bus is removed char** argv = new char*[1]; int* argc = new int{ 0 }; if (QGuiApplication::screens().empty()) { new QApplication(*argc, argv); } QString str = val.toString(); if (str == "all") { return ScreenGrabber().desktopGeometry(); } else if (str.startsWith("screen")) { bool ok; int number = str.midRef(6).toInt(&ok); if (!ok || number < 0) { return {}; } return ScreenGrabber().screenGeometry(qApp->screens()[number]); } QRegExp regex("(-{,1}\\d+)" // number (any sign) "[x,\\.\\s]" // separator ('x', ',', '.', or whitespace) "(-{,1}\\d+)" // number (any sign) "[\\+,\\.\\s]*" // separator ('+',',', '.', or whitespace) "(-{,1}\\d+)" // number (non-negative) "[\\+,\\.\\s]*" // separator ('+', ',', '.', or whitespace) "(-{,1}\\d+)" // number (non-negative) ); if (!regex.exactMatch(str)) { return {}; } int w, h, x, y; bool w_ok, h_ok, x_ok, y_ok; w = regex.cap(1).toInt(&w_ok); h = regex.cap(2).toInt(&h_ok); x = regex.cap(3).toInt(&x_ok); y = regex.cap(4).toInt(&y_ok); if (!(w_ok && h_ok && x_ok && y_ok)) { return {}; } return QRect(x, y, w, h).normalized(); }
12,441
C++
.cpp
471
21.995754
78
0.641846
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,706
abstractlogger.cpp
flameshot-org_flameshot/src/utils/abstractlogger.cpp
#include "abstractlogger.h" #include "systemnotification.h" #include <cassert> #include <QFileInfo> AbstractLogger::AbstractLogger(Channel channel, int targets) : m_defaultChannel(channel) , m_targets(targets) { if (targets & LogFile) { // TODO } } /** * @brief Construct an AbstractLogger with output to a string. * @param additionalChannels Optional additional targets to output to. */ AbstractLogger::AbstractLogger(QString& str, Channel channel, int additionalChannels) : AbstractLogger(channel, additionalChannels) { m_textStreams << new QTextStream(&str); } AbstractLogger::~AbstractLogger() { qDeleteAll(m_textStreams); } AbstractLogger AbstractLogger::info(int targets) { return { Info, targets }; } AbstractLogger AbstractLogger::warning(int targets) { return { Warning, targets }; } AbstractLogger AbstractLogger::error(int targets) { return { Error, targets }; } AbstractLogger& AbstractLogger::sendMessage(const QString& msg, Channel channel) { if (m_targets & Notification) { SystemNotification().sendMessage( msg, messageHeader(channel, Notification), m_notificationPath); } if (!m_textStreams.isEmpty()) { foreach (auto* stream, m_textStreams) { *stream << messageHeader(channel, String) << msg << "\n"; } } if (m_targets & LogFile) { // TODO } if (m_targets & Stderr) { QTextStream stream(stderr); stream << messageHeader(channel, Stderr) << msg << "\n"; } if (m_targets & Stdout) { QTextStream stream(stdout); stream << messageHeader(channel, Stdout) << msg << "\n"; } return *this; } /** * @brief Send a message to the default channel of this logger. * @param msg * @return */ AbstractLogger& AbstractLogger::operator<<(const QString& msg) { sendMessage(msg, m_defaultChannel); return *this; } AbstractLogger& AbstractLogger::addOutputString(QString& str) { m_textStreams << new QTextStream(&str); return *this; } /** * @brief Attach a path to a notification so it can be dragged and dropped. */ AbstractLogger& AbstractLogger::attachNotificationPath(const QString& path) { if (m_targets & Notification) { m_notificationPath = path; } else { assert("Cannot attach notification path to a logger without a " "notification channel."); } return *this; } /** * @brief Enable/disable message header (e.g. "flameshot: info:"). */ AbstractLogger& AbstractLogger::enableMessageHeader(bool enable) { m_enableMessageHeader = enable; return *this; } /** * @brief Generate a message header for the given channel and target. */ QString AbstractLogger::messageHeader(Channel channel, Target target) { if (!m_enableMessageHeader) { return ""; } QString messageChannel; if (channel == Info) { messageChannel = "info"; } else if (channel == Warning) { messageChannel = "warning"; } else if (channel == Error) { messageChannel = "error"; } if (target == Notification) { messageChannel[0] = messageChannel[0].toUpper(); return "Flameshot " + messageChannel; } else { return "flameshot: " + messageChannel + ": "; } }
3,345
C++
.cpp
122
22.893443
80
0.664796
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,707
confighandler.cpp
flameshot-org_flameshot/src/utils/confighandler.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "confighandler.h" #include "abstractlogger.h" #include "src/tools/capturetool.h" #include "valuehandler.h" #include <QCoreApplication> #include <QDebug> #include <QDir> #include <QFile> #include <QFileSystemWatcher> #include <QKeySequence> #include <QMap> #include <QSharedPointer> #include <QStandardPaths> #include <QVector> #include <algorithm> #include <stdexcept> #if defined(Q_OS_MACOS) #include <QProcess> #endif // HELPER FUNCTIONS bool verifyLaunchFile() { #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) QString path = QStandardPaths::locate(QStandardPaths::GenericConfigLocation, "autostart/", QStandardPaths::LocateDirectory) + "Flameshot.desktop"; bool res = QFile(path).exists(); #elif defined(Q_OS_WIN) QSettings bootUpSettings( "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat); bool res = bootUpSettings.value("Flameshot").toString() == QDir::toNativeSeparators(QCoreApplication::applicationFilePath()); #endif return res; } // VALUE HANDLING /** * Use this to declare a setting with a type that is either unrecognized by * QVariant or if you need to place additional constraints on its value. * @param KEY Name of the setting as in the config file * (a C-style string literal) * @param TYPE An instance of a `ValueHandler` derivative. This must be * specified in the form of a constructor, or the macro will * misbehave. */ #define OPTION(KEY, TYPE) \ { \ QStringLiteral(KEY), QSharedPointer<ValueHandler>(new TYPE) \ } #define SHORTCUT(NAME, DEFAULT_VALUE) \ { \ QStringLiteral(NAME), QSharedPointer<KeySequence>(new KeySequence( \ QKeySequence(QLatin1String(DEFAULT_VALUE)))) \ } /** * This map contains all the information that is needed to parse, verify and * preprocess each configuration option in the General section. * NOTE: Please keep it well structured */ // clang-format off static QMap<class QString, QSharedPointer<ValueHandler>> recognizedGeneralOptions = { // KEY TYPE DEFAULT_VALUE OPTION("showHelp" ,Bool ( true )), OPTION("showSidePanelButton" ,Bool ( true )), OPTION("showDesktopNotification" ,Bool ( true )), OPTION("disabledTrayIcon" ,Bool ( false )), OPTION("disabledGrimWarning" ,Bool ( false )), OPTION("historyConfirmationToDelete" ,Bool ( true )), #if !defined(DISABLE_UPDATE_CHECKER) OPTION("checkForUpdates" ,Bool ( true )), #endif OPTION("allowMultipleGuiInstances" ,Bool ( false )), OPTION("showMagnifier" ,Bool ( false )), OPTION("squareMagnifier" ,Bool ( false )), #if !defined(Q_OS_WIN) OPTION("autoCloseIdleDaemon" ,Bool ( false )), #endif OPTION("startupLaunch" ,Bool ( false )), OPTION("showStartupLaunchMessage" ,Bool ( true )), OPTION("copyURLAfterUpload" ,Bool ( true )), OPTION("copyPathAfterSave" ,Bool ( false )), OPTION("antialiasingPinZoom" ,Bool ( true )), OPTION("useJpgForClipboard" ,Bool ( false )), OPTION("uploadWithoutConfirmation" ,Bool ( false )), OPTION("saveAfterCopy" ,Bool ( false )), OPTION("savePath" ,ExistingDir ( )), OPTION("savePathFixed" ,Bool ( false )), OPTION("saveAsFileExtension" ,SaveFileExtension ( )), OPTION("saveLastRegion" ,Bool (false )), OPTION("uploadHistoryMax" ,LowerBoundedInt (0, 25 )), OPTION("undoLimit" ,BoundedInt (0, 999, 100 )), // Interface tab OPTION("uiColor" ,Color ( {116, 0, 150} )), OPTION("contrastUiColor" ,Color ( {39, 0, 50} )), OPTION("contrastOpacity" ,BoundedInt ( 0, 255, 190 )), OPTION("buttons" ,ButtonList ( {} )), // Filename Editor tab OPTION("filenamePattern" ,FilenamePattern ( {} )), // Others OPTION("drawThickness" ,LowerBoundedInt (1 , 3 )), OPTION("drawFontSize" ,LowerBoundedInt (1 , 8 )), OPTION("drawColor" ,Color ( Qt::red )), OPTION("userColors" ,UserColors(3, 17 )), OPTION("ignoreUpdateToVersion" ,String ( "" )), OPTION("keepOpenAppLauncher" ,Bool ( false )), OPTION("fontFamily" ,String ( "" )), // PREDEFINED_COLOR_PALETTE_LARGE is defined in src/CMakeList.txt file and can be overwritten in GitHub actions OPTION("predefinedColorPaletteLarge", Bool ( PREDEFINED_COLOR_PALETTE_LARGE )), // NOTE: If another tool size is added besides drawThickness and // drawFontSize, remember to update ConfigHandler::toolSize OPTION("copyOnDoubleClick" ,Bool ( false )), OPTION("uploadClientSecret" ,String ( "313baf0c7b4d3ff" )), OPTION("showSelectionGeometry" , BoundedInt (0,5,4)), OPTION("showSelectionGeometryHideTime", LowerBoundedInt (0, 3000)), OPTION("jpegQuality", BoundedInt (0,100,75)) }; static QMap<QString, QSharedPointer<KeySequence>> recognizedShortcuts = { // NAME DEFAULT_SHORTCUT SHORTCUT("TYPE_PENCIL" , "P" ), SHORTCUT("TYPE_DRAWER" , "D" ), SHORTCUT("TYPE_ARROW" , "A" ), SHORTCUT("TYPE_SELECTION" , "S" ), SHORTCUT("TYPE_RECTANGLE" , "R" ), SHORTCUT("TYPE_CIRCLE" , "C" ), SHORTCUT("TYPE_MARKER" , "M" ), SHORTCUT("TYPE_MOVESELECTION" , "Ctrl+M" ), SHORTCUT("TYPE_UNDO" , "Ctrl+Z" ), SHORTCUT("TYPE_COPY" , "Ctrl+C" ), SHORTCUT("TYPE_SAVE" , "Ctrl+S" ), SHORTCUT("TYPE_ACCEPT" , "Return" ), SHORTCUT("TYPE_EXIT" , "Ctrl+Q" ), SHORTCUT("TYPE_IMAGEUPLOADER" , ), #if !defined(Q_OS_MACOS) SHORTCUT("TYPE_OPEN_APP" , "Ctrl+O" ), #endif SHORTCUT("TYPE_PIXELATE" , "B" ), SHORTCUT("TYPE_INVERT" , "I" ), SHORTCUT("TYPE_REDO" , "Ctrl+Shift+Z" ), SHORTCUT("TYPE_TEXT" , "T" ), SHORTCUT("TYPE_TOGGLE_PANEL" , "Space" ), SHORTCUT("TYPE_RESIZE_LEFT" , "Shift+Left" ), SHORTCUT("TYPE_RESIZE_RIGHT" , "Shift+Right" ), SHORTCUT("TYPE_RESIZE_UP" , "Shift+Up" ), SHORTCUT("TYPE_RESIZE_DOWN" , "Shift+Down" ), SHORTCUT("TYPE_SYM_RESIZE_LEFT" , "Ctrl+Shift+Left" ), SHORTCUT("TYPE_SYM_RESIZE_RIGHT" , "Ctrl+Shift+Right" ), SHORTCUT("TYPE_SYM_RESIZE_UP" , "Ctrl+Shift+Up" ), SHORTCUT("TYPE_SYM_RESIZE_DOWN" , "Ctrl+Shift+Down" ), SHORTCUT("TYPE_SELECT_ALL" , "Ctrl+A" ), SHORTCUT("TYPE_MOVE_LEFT" , "Left" ), SHORTCUT("TYPE_MOVE_RIGHT" , "Right" ), SHORTCUT("TYPE_MOVE_UP" , "Up" ), SHORTCUT("TYPE_MOVE_DOWN" , "Down" ), SHORTCUT("TYPE_COMMIT_CURRENT_TOOL" , "Ctrl+Return" ), #if defined(Q_OS_MACOS) SHORTCUT("TYPE_DELETE_CURRENT_TOOL" , "Backspace" ), SHORTCUT("TAKE_SCREENSHOT" , "Ctrl+Shift+X" ), SHORTCUT("SCREENSHOT_HISTORY" , "Alt+Shift+X" ), #else SHORTCUT("TYPE_DELETE_CURRENT_TOOL" , "Delete" ), #endif SHORTCUT("TYPE_PIN" , ), SHORTCUT("TYPE_SELECTIONINDICATOR" , ), SHORTCUT("TYPE_SIZEINCREASE" , ), SHORTCUT("TYPE_SIZEDECREASE" , ), SHORTCUT("TYPE_CIRCLECOUNT" , ), }; // clang-format on // CLASS CONFIGHANDLER ConfigHandler::ConfigHandler() : m_settings(QSettings::IniFormat, QSettings::UserScope, qApp->organizationName(), qApp->applicationName()) { static bool firstInitialization = true; if (firstInitialization) { // check for error every time the file changes m_configWatcher.reset(new QFileSystemWatcher()); ensureFileWatched(); QObject::connect(m_configWatcher.data(), &QFileSystemWatcher::fileChanged, [](const QString& fileName) { emit getInstance()->fileChanged(); if (QFile(fileName).exists()) { m_configWatcher->addPath(fileName); } if (m_skipNextErrorCheck) { m_skipNextErrorCheck = false; return; } ConfigHandler().checkAndHandleError(); if (!QFile(fileName).exists()) { // File watcher stops watching a deleted file. // Next time the config is accessed, force it // to check for errors (and watch again). m_errorCheckPending = true; } }); } firstInitialization = false; } /// Serves as an object to which slots can be connected. ConfigHandler* ConfigHandler::getInstance() { static ConfigHandler config; return &config; } // SPECIAL CASES bool ConfigHandler::startupLaunch() { bool res = value(QStringLiteral("startupLaunch")).toBool(); if (res != verifyLaunchFile()) { setStartupLaunch(res); } return res; } void ConfigHandler::setStartupLaunch(const bool start) { if (start == value(QStringLiteral("startupLaunch")).toBool()) { return; } setValue(QStringLiteral("startupLaunch"), start); #if defined(Q_OS_MACOS) /* TODO - there should be more correct way via API, but didn't find it without extra dependencies, there should be something like that: https://stackoverflow.com/questions/3358410/programmatically-run-at-startup-on-mac-os-x But files with this features differs on different MacOS versions and it doesn't work not on a BigSur at lease. */ QProcess process; if (start) { process.start("osascript", QStringList() << "-e" << "tell application \"System Events\" to make login " "item at end with properties {name: " "\"Flameshot\",path:\"/Applications/" "flameshot.app\", hidden:false}"); } else { process.start("osascript", QStringList() << "-e" << "tell application \"System Events\" to " "delete login item \"Flameshot\""); } if (!process.waitForFinished()) { qWarning() << "Login items is changed. " << process.errorString(); } else { qWarning() << "Unable to change login items, error:" << process.readAll(); } #elif defined(Q_OS_LINUX) || defined(Q_OS_UNIX) QString path = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + "/autostart/"; QDir autostartDir(path); if (!autostartDir.exists()) { autostartDir.mkpath("."); } QFile file(path + "Flameshot.desktop"); if (start) { if (file.open(QIODevice::WriteOnly)) { QByteArray data("[Desktop Entry]\nName=flameshot\nIcon=flameshot" "\nExec=flameshot\nTerminal=false\nType=Application" "\nX-GNOME-Autostart-enabled=true\n"); file.write(data); } } else { file.remove(); } #elif defined(Q_OS_WIN) QSettings bootUpSettings( "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat); // set workdir for flameshot on startup QSettings bootUpPath( "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App " "Paths", QSettings::NativeFormat); if (start) { QString app_path = QDir::toNativeSeparators(QCoreApplication::applicationFilePath()); bootUpSettings.setValue("Flameshot", app_path); // set application workdir bootUpPath.beginGroup("flameshot.exe"); bootUpPath.setValue("Path", QCoreApplication::applicationDirPath()); bootUpPath.endGroup(); } else { bootUpSettings.remove("Flameshot"); // remove application workdir bootUpPath.beginGroup("flameshot.exe"); bootUpPath.remove(""); bootUpPath.endGroup(); } #endif } void ConfigHandler::setAllTheButtons() { QList<CaptureTool::Type> buttonlist = CaptureToolButton::getIterableButtonTypes(); setValue(QStringLiteral("buttons"), QVariant::fromValue(buttonlist)); } void ConfigHandler::setToolSize(CaptureTool::Type toolType, int size) { if (toolType == CaptureTool::TYPE_TEXT) { setDrawFontSize(size); } else if (toolType != CaptureTool::NONE) { setDrawThickness(size); } } int ConfigHandler::toolSize(CaptureTool::Type toolType) { if (toolType == CaptureTool::TYPE_TEXT) { return drawFontSize(); } else { return drawThickness(); } } // DEFAULTS QString ConfigHandler::filenamePatternDefault() { return QStringLiteral("%F_%H-%M"); } void ConfigHandler::setDefaultSettings() { foreach (const QString& key, m_settings.allKeys()) { if (isShortcut(key)) { // Do not reset Shortcuts continue; } m_settings.remove(key); } m_settings.sync(); } QString ConfigHandler::configFilePath() const { return m_settings.fileName(); } // GENERIC GETTERS AND SETTERS bool ConfigHandler::setShortcut(const QString& actionName, const QString& shortcut) { qDebug() << actionName; static QVector<QKeySequence> reservedShortcuts = { #if defined(Q_OS_MACOS) Qt::CTRL + Qt::Key_Backspace, Qt::Key_Escape, #else Qt::Key_Backspace, Qt::Key_Escape, #endif }; if (hasError()) { return false; } bool errorFlag = false; m_settings.beginGroup(CONFIG_GROUP_SHORTCUTS); if (shortcut.isEmpty()) { setValue(actionName, ""); } else if (reservedShortcuts.contains(QKeySequence(shortcut))) { // do not allow to set reserved shortcuts errorFlag = true; } else { errorFlag = false; // Make no difference for Return and Enter keys QString newShortcut = KeySequence().value(shortcut).toString(); for (auto& otherAction : m_settings.allKeys()) { if (actionName == otherAction) { continue; } QString existingShortcut = KeySequence().value(m_settings.value(otherAction)).toString(); if (newShortcut == existingShortcut) { errorFlag = true; goto done; } } m_settings.setValue(actionName, KeySequence().value(shortcut)); } done: m_settings.endGroup(); return !errorFlag; } QString ConfigHandler::shortcut(const QString& actionName) { QString setting = CONFIG_GROUP_SHORTCUTS "/" + actionName; QString shortcut = value(setting).toString(); if (!m_settings.contains(setting)) { // The action uses a shortcut that is a flameshot default // (not set explicitly by user) m_settings.beginGroup(CONFIG_GROUP_SHORTCUTS); for (auto& otherAction : m_settings.allKeys()) { if (m_settings.value(otherAction) == shortcut) { // We found an explicit shortcut - it will take precedence m_settings.endGroup(); return {}; } } m_settings.endGroup(); } return shortcut; } void ConfigHandler::setValue(const QString& key, const QVariant& value) { assertKeyRecognized(key); if (!hasError()) { // don't let the file watcher initiate another error check m_skipNextErrorCheck = true; auto val = valueHandler(key)->representation(value); m_settings.setValue(key, val); } } QVariant ConfigHandler::value(const QString& key) const { assertKeyRecognized(key); auto val = m_settings.value(key); auto handler = valueHandler(key); // Check the value for semantic errors if (val.isValid() && !handler->check(val)) { setErrorState(true); } if (m_hasError) { return handler->fallback(); } return handler->value(val); } void ConfigHandler::remove(const QString& key) { m_settings.remove(key); } void ConfigHandler::resetValue(const QString& key) { m_settings.setValue(key, valueHandler(key)->fallback()); } QSet<QString>& ConfigHandler::recognizedGeneralOptions() { #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) auto keys = ::recognizedGeneralOptions.keys(); static QSet<QString> options = QSet<QString>(keys.begin(), keys.end()); #else static QSet<QString> options = QSet<QString>::fromList(::recognizedGeneralOptions.keys()); #endif return options; } QSet<QString>& ConfigHandler::recognizedShortcutNames() { #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) auto keys = recognizedShortcuts.keys(); static QSet<QString> names = QSet<QString>(keys.begin(), keys.end()); #else static QSet<QString> names = QSet<QString>::fromList(recognizedShortcuts.keys()); #endif return names; } /** * @brief Return keys from group `group`. * Use CONFIG_GROUP_GENERAL (General) for general settings. */ QSet<QString> ConfigHandler::keysFromGroup(const QString& group) const { QSet<QString> keys; for (const QString& key : m_settings.allKeys()) { if (group == CONFIG_GROUP_GENERAL && !key.contains('/')) { keys.insert(key); } else if (key.startsWith(group + "/")) { keys.insert(baseName(key)); } } return keys; } // ERROR HANDLING bool ConfigHandler::checkForErrors(AbstractLogger* log) const { return checkUnrecognizedSettings(log) && checkShortcutConflicts(log) && checkSemantics(log); } /** * @brief Parse the config to find settings with unrecognized names. * @return Whether the config passes this check. * * @note An unrecognized option is one that is not included in * `recognizedGeneralOptions` or `recognizedShortcutNames` depending on the * group the option belongs to. */ bool ConfigHandler::checkUnrecognizedSettings(AbstractLogger* log, QList<QString>* offenders) const { // sort the config keys by group QSet<QString> generalKeys = keysFromGroup(CONFIG_GROUP_GENERAL), shortcutKeys = keysFromGroup(CONFIG_GROUP_SHORTCUTS), recognizedGeneralKeys = recognizedGeneralOptions(), recognizedShortcutKeys = recognizedShortcutNames(); // subtract recognized keys generalKeys.subtract(recognizedGeneralKeys); shortcutKeys.subtract(recognizedShortcutKeys); // what is left are the unrecognized keys - hopefully empty bool ok = generalKeys.isEmpty() && shortcutKeys.isEmpty(); if (log != nullptr || offenders != nullptr) { for (const QString& key : generalKeys) { if (log) { *log << tr("Unrecognized setting: '%1'\n").arg(key); } if (offenders) { offenders->append(key); } } for (const QString& key : shortcutKeys) { if (log) { *log << tr("Unrecognized shortcut name: '%1'.\n").arg(key); } if (offenders) { offenders->append(CONFIG_GROUP_SHORTCUTS "/" + key); } } } return ok; } /** * @brief Check if there are multiple actions with the same shortcut. * @return Whether the config passes this check. * * @note It is not considered a conflict if action A uses shortcut S because it * is the flameshot default (not because the user explicitly configured it), and * action B uses the same shortcut. */ bool ConfigHandler::checkShortcutConflicts(AbstractLogger* log) const { bool ok = true; m_settings.beginGroup(CONFIG_GROUP_SHORTCUTS); QStringList shortcuts = m_settings.allKeys(); QStringList reportedInLog; for (auto key1 = shortcuts.begin(); key1 != shortcuts.end(); ++key1) { for (auto key2 = key1 + 1; key2 != shortcuts.end(); ++key2) { // values stored in variables are useful when running debugger QString value1 = m_settings.value(*key1).toString(), value2 = m_settings.value(*key2).toString(); // The check will pass if: // - one shortcut is empty (the action doesn't use a shortcut) // - or one of the settings is not found in m_settings, i.e. // user wants to use flameshot's default shortcut for the action // - or the shortcuts for both actions are different if (!(value1.isEmpty() || !m_settings.contains(*key1) || !m_settings.contains(*key2) || value1 != value2)) { ok = false; if (log == nullptr) { break; } else if (!reportedInLog.contains(*key1) && // No duplicate !reportedInLog.contains(*key2)) { // log entries reportedInLog.append(*key1); reportedInLog.append(*key2); *log << tr("Shortcut conflict: '%1' and '%2' " "have the same shortcut: %3\n") .arg(*key1) .arg(*key2) .arg(value1); } } } } m_settings.endGroup(); return ok; } /** * @brief Check each config value semantically. * @param log Destination for error log output. * @param offenders Destination for the semantically invalid keys. * @return Whether the config passes this check. */ bool ConfigHandler::checkSemantics(AbstractLogger* log, QList<QString>* offenders) const { QStringList allKeys = m_settings.allKeys(); bool ok = true; for (const QString& key : allKeys) { // Test if the key is recognized if (!recognizedGeneralOptions().contains(key) && (!isShortcut(key) || !recognizedShortcutNames().contains(baseName(key)))) { continue; } QVariant val = m_settings.value(key); auto valueHandler = this->valueHandler(key); if (val.isValid() && !valueHandler->check(val)) { // Key does not pass the check ok = false; if (log == nullptr && offenders == nullptr) { break; } if (log != nullptr) { *log << tr("Bad value in '%1'. Expected: %2\n") .arg(key) .arg(valueHandler->expected()); } if (offenders != nullptr) { offenders->append(key); } } } return ok; } /** * @brief Parse the configuration to find any errors in it. * * If the error state changes as a result of the check, it will perform the * appropriate action, e.g. notify the user. * * @see ConfigHandler::setErrorState for all the actions. */ void ConfigHandler::checkAndHandleError() const { if (!QFile(m_settings.fileName()).exists()) { setErrorState(false); } else { setErrorState(!checkForErrors()); } ensureFileWatched(); } /** * @brief Update the tracked error state of the config. * @param error The new error state. * * The error state is tracked so that signals are not emitted and the user is * not spammed every time the config file changes. Instead, only changes in * error state get reported. */ void ConfigHandler::setErrorState(bool error) const { bool hadError = m_hasError; m_hasError = error; // Notify user every time m_hasError changes if (!hadError && m_hasError) { QString msg = errorMessage(); AbstractLogger::error() << msg; emit getInstance()->error(); } else if (hadError && !m_hasError) { auto msg = tr("You have successfully resolved the configuration error."); AbstractLogger::info() << msg; emit getInstance()->errorResolved(); } } /** * @brief Return if the config contains an error. * * If an error check is due, it will be performed. */ bool ConfigHandler::hasError() const { if (m_errorCheckPending) { checkAndHandleError(); m_errorCheckPending = false; } return m_hasError; } /// Error message that can be used by other classes as well QString ConfigHandler::errorMessage() const { return tr( "The configuration contains an error. Open configuration to resolve."); } void ConfigHandler::ensureFileWatched() const { QFile file(m_settings.fileName()); if (!file.exists()) { file.open(QFileDevice::WriteOnly); file.close(); } if (m_configWatcher != nullptr && m_configWatcher->files().isEmpty() && qApp != nullptr // ensures that the organization name can be accessed ) { m_configWatcher->addPath(m_settings.fileName()); } } /** * @brief Obtain a `ValueHandler` for the config option with the given key. * @return Smart pointer to the handler. * * @note If the key is from the CONFIG_GROUP_GENERAL (General) group, the * `recognizedGeneralOptions` map is looked up. If it is from * CONFIG_GROUP_SHORTCUTS (Shortcuts), a generic `KeySequence` value handler is * returned. */ QSharedPointer<ValueHandler> ConfigHandler::valueHandler( const QString& key) const { QSharedPointer<ValueHandler> handler; if (isShortcut(key)) { handler = recognizedShortcuts.value( baseName(key), QSharedPointer<KeySequence>(new KeySequence())); } else { // General group handler = ::recognizedGeneralOptions.value(key); } return handler; } /** * This is used so that we can check if there is a mismatch between a config key * and its getter function. * Debug: throw an exception; Release: set error state */ void ConfigHandler::assertKeyRecognized(const QString& key) const { bool recognized = isShortcut(key) ? recognizedShortcutNames().contains(baseName(key)) : ::recognizedGeneralOptions.contains(key); if (!recognized) { #if defined(QT_DEBUG) // This should never happen, but just in case throw std::logic_error( tr("Bad config key '%1' in ConfigHandler. Please report " "this as a bug.") .arg(key) .toStdString()); #else setErrorState(true); #endif } } bool ConfigHandler::isShortcut(const QString& key) const { return m_settings.group() == QStringLiteral(CONFIG_GROUP_SHORTCUTS) || key.startsWith(QStringLiteral(CONFIG_GROUP_SHORTCUTS "/")); } QString ConfigHandler::baseName(const QString& key) const { return QFileInfo(key).baseName(); } // STATIC MEMBER DEFINITIONS bool ConfigHandler::m_hasError = false; bool ConfigHandler::m_errorCheckPending = true; bool ConfigHandler::m_skipNextErrorCheck = false; QSharedPointer<QFileSystemWatcher> ConfigHandler::m_configWatcher;
29,725
C++
.cpp
739
33.197564
115
0.569117
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,708
winlnkfileparse.cpp
flameshot-org_flameshot/src/utils/winlnkfileparse.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "winlnkfileparse.h" #include <QDir> #include <QDirIterator> #include <QFileSystemModel> #include <QImageWriter> #include <QRegularExpression> #include <QSettings> #include <QString> #include <shlobj.h> WinLnkFileParser::WinLnkFileParser() { QStringList sListImgFileExt; for (const auto& ext : QImageWriter::supportedImageFormats()) { sListImgFileExt.append(ext); } this->getImageFileExtAssociates(sListImgFileExt); } DesktopAppData WinLnkFileParser::parseLnkFile(const QFileInfo& fiLnk, bool& ok) const { DesktopAppData res; ok = true; QFileInfo fiSymlink(fiLnk.symLinkTarget()); if (!fiSymlink.exists() || !fiSymlink.fileName().endsWith(".exe") || fiSymlink.baseName().contains("unins")) { ok = false; return res; } res.name = fiLnk.baseName(); res.exec = fiSymlink.absoluteFilePath(); // Get icon from exe QFileSystemModel* model = new QFileSystemModel; model->setRootPath(fiSymlink.path()); res.icon = model->fileIcon(model->index(fiSymlink.filePath())); if (m_GraphicAppsList.contains(fiSymlink.fileName())) { res.categories = QStringList() << "Graphics"; } else { res.categories = QStringList() << "Utility"; } for (const auto& app : m_appList) { if (app.exec == res.exec) { ok = false; break; } } if (res.exec.isEmpty() || res.name.isEmpty()) { ok = false; } return res; } int WinLnkFileParser::processDirectory(const QDir& dir) { QStringList sListMenuFilter; sListMenuFilter << "Accessibility" << "Administrative Tools" << "Setup" << "System Tools" << "Uninstall" << "Update" << "Updater" << "Windows PowerShell"; const QString sMenuFilter("\\b(" + sListMenuFilter.join('|') + ")\\b"); QRegularExpression regexfilter(sMenuFilter); bool ok; int length = m_appList.length(); // Go through all subfolders and *.lnk files QDirIterator it(dir.absolutePath(), { "*.lnk" }, QDir::NoFilter, QDirIterator::Subdirectories); while (it.hasNext()) { QFileInfo fiLnk(it.next()); if (!regexfilter.match(fiLnk.absoluteFilePath()).hasMatch()) { DesktopAppData app = parseLnkFile(fiLnk, ok); if (ok) { m_appList.append(app); } } } return m_appList.length() - length; } QVector<DesktopAppData> WinLnkFileParser::getAppsByCategory( const QString& category) { QVector<DesktopAppData> res; for (const DesktopAppData& app : qAsConst(m_appList)) { if (app.categories.contains(category)) { res.append(app); } } std::sort(res.begin(), res.end(), CompareAppByName()); return res; } QMap<QString, QVector<DesktopAppData>> WinLnkFileParser::getAppsByCategory( const QStringList& categories) { QMap<QString, QVector<DesktopAppData>> res; QVector<DesktopAppData> tmpAppList; for (const QString& category : categories) { tmpAppList = getAppsByCategory(category); for (const DesktopAppData& app : qAsConst(tmpAppList)) { res[category].append(app); } } return res; } QString WinLnkFileParser::getAllUsersStartMenuPath() { QString sRet(""); WCHAR path[MAX_PATH]; HRESULT hr = SHGetFolderPathW(NULL, CSIDL_COMMON_PROGRAMS, NULL, 0, path); if (SUCCEEDED(hr)) { sRet = QDir(QString::fromWCharArray(path)).absolutePath(); } return sRet; } void WinLnkFileParser::getImageFileExtAssociates(const QStringList& sListImgExt) { const QString sReg("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\" "CurrentVersion\\Explorer\\FileExts\\.%1\\OpenWithList"); for (const auto& sExt : qAsConst(sListImgExt)) { QString sPath(sReg.arg(sExt)); QSettings registry(sPath, QSettings::NativeFormat); for (const auto& key : registry.allKeys()) { if (1 == key.size()) { // Keys for OpenWith apps are a, b, c, ... QString sVal = registry.value(key, "").toString(); if (sVal.endsWith(".exe") && !m_GraphicAppsList.contains(sVal)) { m_GraphicAppsList << sVal; } } } } }
4,640
C++
.cpp
136
26.522059
80
0.615179
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,709
globalvalues.cpp
flameshot-org_flameshot/src/utils/globalvalues.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "globalvalues.h" #include <QApplication> #include <QFontMetrics> int GlobalValues::buttonBaseSize() { return QApplication::fontMetrics().lineSpacing() * 2.2; } QString GlobalValues::versionInfo() { return QStringLiteral("Flameshot " APP_VERSION " (" FLAMESHOT_GIT_HASH ")" "\nCompiled with Qt " QT_VERSION_STR); } QString GlobalValues::iconPath() { #if USE_MONOCHROME_ICON return QString(":img/app/flameshot.monochrome.svg"); #else return { ":img/app/flameshot.svg" }; #endif } QString GlobalValues::iconPathPNG() { #if USE_MONOCHROME_ICON return QString(":img/app/flameshot.monochrome.png"); #else return { ":img/app/flameshot.png" }; #endif }
826
C++
.cpp
30
24.733333
78
0.727273
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,710
systemnotification.cpp
flameshot-org_flameshot/src/utils/systemnotification.cpp
#include "systemnotification.h" #include "src/core/flameshot.h" #include "src/utils/confighandler.h" #include <QApplication> #include <QUrl> #if !(defined(Q_OS_MACOS) || defined(Q_OS_WIN)) #include <QDBusConnection> #include <QDBusInterface> #include <QDBusMessage> #else #include "src/core/flameshotdaemon.h" #endif // work-around for snap, which cannot install icons into // the system folder, so instead the absolute path to the // icon (saved somewhere in /snap/flameshot/...) is passed #ifndef FLAMESHOT_ICON #define FLAMESHOT_ICON "flameshot" #endif SystemNotification::SystemNotification(QObject* parent) : QObject(parent) , m_interface(nullptr) { #if !(defined(Q_OS_MACOS) || defined(Q_OS_WIN)) m_interface = new QDBusInterface(QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("/org/freedesktop/Notifications"), QStringLiteral("org.freedesktop.Notifications"), QDBusConnection::sessionBus(), this); #endif } void SystemNotification::sendMessage(const QString& text, const QString& savePath) { sendMessage(text, tr("Flameshot Info"), savePath); } void SystemNotification::sendMessage(const QString& text, const QString& title, const QString& savePath, const int timeout) { if (!ConfigHandler().showDesktopNotification()) { return; } #if defined(Q_OS_MACOS) || defined(Q_OS_WIN) QMetaObject::invokeMethod( this, [&]() { // The call is queued to avoid recursive static initialization of // Flameshot and ConfigHandler. if (FlameshotDaemon::instance()) FlameshotDaemon::instance()->sendTrayNotification( text, title, timeout); }, Qt::QueuedConnection); #else QList<QVariant> args; QVariantMap hintsMap; if (!savePath.isEmpty()) { QUrl fullPath = QUrl::fromLocalFile(savePath); // allows the notification to be dragged and dropped hintsMap[QStringLiteral("x-kde-urls")] = QStringList({ fullPath.toString() }); } args << (qAppName()) // appname << static_cast<unsigned int>(0) // id << FLAMESHOT_ICON // icon << title // summary << text // body << QStringList() // actions << hintsMap // hints << timeout; // timeout m_interface->callWithArgumentList( QDBus::AutoDetect, QStringLiteral("Notify"), args); #endif }
2,766
C++
.cpp
76
28.763158
75
0.594484
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,711
filenamehandler.cpp
flameshot-org_flameshot/src/utils/filenamehandler.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "filenamehandler.h" #include "abstractlogger.h" #include "src/utils/confighandler.h" #include "src/utils/strfparse.h" #include <QDir> #include <ctime> #include <exception> #include <locale> FileNameHandler::FileNameHandler(QObject* parent) : QObject(parent) { auto err = AbstractLogger::error(AbstractLogger::Stderr); try { std::locale::global(std::locale()); } catch (std::exception& e) { err << "Locales on your system are not properly configured. Falling " "back to defaults"; std::locale::global(std::locale("en_US.UTF-8")); } } QString FileNameHandler::parsedPattern() { return parseFilename(ConfigHandler().filenamePattern()); } QString FileNameHandler::parseFilename(const QString& name) { QString res = name; if (name.isEmpty()) { res = ConfigHandler().filenamePatternDefault(); } // remove trailing characters '%' in the pattern while (res.endsWith('%')) { res.chop(1); } res = QString::fromStdString(strfparse::format_time_string(name.toStdString())); // add the parsed pattern in a correct format for the filesystem res = res.replace(QLatin1String("/"), QStringLiteral("â„")) .replace(QLatin1String(":"), QLatin1String("-")); return res; } /** * @brief Generate a valid destination path from the possibly incomplete `path`. * The input `path` can be one of: * - empty string * - an existing directory * - a file in an existing directory * In each case, the output path will be an absolute path to a file with a * suffix matching the specified `format`. * @note * - If `path` points to a directory, the file name will be generated from the * formatted file name from the user configuration * - If `path` points to a file, its suffix will be changed to match `format` * - If `format` is not given, the suffix will remain untouched, unless `path` * has no suffix, in which case it will be given the "png" suffix * - If the path generated by the previous steps points to an existing file, * "_NUM" will be appended to its base name, where NUM is the first * available number that produces a non-existent path (starting from 1). * @param path Possibly incomplete file name to transform * @param format Desired output file suffix (excluding an initial '.' character) */ QString FileNameHandler::properScreenshotPath(QString path, const QString& format) { QFileInfo info(path); QString suffix = info.suffix(); if (info.isDir()) { // path is a directory => generate filename from configured pattern path = QDir(QDir(path).absolutePath() + "/" + parsedPattern()).path(); } else { // path points to a file => strip it of its suffix for now path = QDir(info.dir().absolutePath() + "/" + info.completeBaseName()) .path(); } if (!format.isEmpty()) { // Override suffix to match format path += "." + format; } else if (!suffix.isEmpty()) { // Leave the suffix as it was path += "." + suffix; } else { path += ".png"; } if (!QFileInfo::exists(path)) { return path; } else { return autoNumerateDuplicate(path); } } QString FileNameHandler::autoNumerateDuplicate(const QString& path) { // add numeration in case of repeated filename in the directory // find unused name adding _n where n is a number QFileInfo checkFile(path); QString directory = checkFile.dir().absolutePath(), filename = checkFile.completeBaseName(), suffix = checkFile.suffix(); if (!suffix.isEmpty()) { suffix = QStringLiteral(".") + suffix; } if (checkFile.exists()) { filename += QLatin1String("_"); int i = 1; while (true) { checkFile.setFile(directory + "/" + filename + QString::number(i) + suffix); if (!checkFile.exists()) { filename += QString::number(i); break; } ++i; } } return checkFile.filePath(); }
4,288
C++
.cpp
117
30.717949
80
0.642531
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,712
desktopfileparse.cpp
flameshot-org_flameshot/src/utils/desktopfileparse.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "desktopfileparse.h" #include <QDir> #include <QFile> #include <QLocale> #include <QString> #include <QTextStream> DesktopFileParser::DesktopFileParser() { QString locale = QLocale().name(); QString localeShort = QLocale().name().left(2); m_localeName = QStringLiteral("Name[%1]").arg(locale); m_localeDescription = QStringLiteral("Comment[%1]").arg(locale); m_localeNameShort = QStringLiteral("Name[%1]").arg(localeShort); m_localeDescriptionShort = QStringLiteral("Comment[%1]").arg(localeShort); m_defaultIcon = QIcon::fromTheme(QStringLiteral("application-x-executable")); } DesktopAppData DesktopFileParser::parseDesktopFile(const QString& fileName, bool& ok) const { DesktopAppData res; ok = true; QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { ok = false; return res; } bool nameLocaleSet = false; bool descriptionLocaleSet = false; bool isApplication = false; bool isService = false; QTextStream in(&file); // enter the desktop entry definition while (!in.atEnd() && in.readLine() != QLatin1String("[Desktop Entry]")) { } // start parsing while (!in.atEnd()) { QString line = in.readLine(); if (line.startsWith(QLatin1String("Icon"))) { res.icon = QIcon::fromTheme( line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(), m_defaultIcon); } else if (!nameLocaleSet && line.startsWith(QLatin1String("Name"))) { if (line.startsWith(m_localeName) || line.startsWith(m_localeNameShort)) { res.name = line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(); nameLocaleSet = true; } else if (line.startsWith(QLatin1String("Name="))) { res.name = line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(); } } else if (!descriptionLocaleSet && line.startsWith(QLatin1String("Comment"))) { if (line.startsWith(m_localeDescription) || line.startsWith(m_localeDescriptionShort)) { res.description = line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(); descriptionLocaleSet = true; } else if (line.startsWith(QLatin1String("Comment="))) { res.description = line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(); } } else if (line.startsWith(QLatin1String("Exec"))) { if (line.contains(QLatin1String("%"))) { res.exec = line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(); } else { ok = false; break; } } else if (line.startsWith(QLatin1String("Type"))) { if (line.contains(QLatin1String("Application"))) { isApplication = true; } if (line.contains(QLatin1String("Service"))) { isService = true; } } else if (line.startsWith(QLatin1String("Categories"))) { res.categories = line.mid(line.indexOf(QLatin1String("=")) + 1) .split(QStringLiteral(";")); } else if (line == QLatin1String("NoDisplay=true")) { ok = false; break; } else if (line == QLatin1String("Terminal=true")) { res.showInTerminal = true; } // ignore the other entries else if (line.startsWith(QLatin1String("["))) { break; } } file.close(); if (res.exec.isEmpty() || res.name.isEmpty() || (!isApplication && !isService)) { ok = false; } return res; } int DesktopFileParser::processDirectory(const QDir& dir) { // Note that // https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html // says files must end in .desktop or .directory // So filtering by .desktop stops us reading things like editor backups // .kdelnk is long deprecated QStringList entries = dir.entryList({ "*.desktop" }, QDir::NoDotAndDotDot | QDir::Files); bool ok; int length = m_appList.length(); for (const QString& file : entries) { DesktopAppData app = parseDesktopFile(dir.absoluteFilePath(file), ok); if (ok) { m_appList.append(app); } } return m_appList.length() - length; } QVector<DesktopAppData> DesktopFileParser::getAppsByCategory( const QString& category) { QVector<DesktopAppData> res; for (const DesktopAppData& app : qAsConst(m_appList)) { if (app.categories.contains(category)) { res.append(app); } } return res; } QMap<QString, QVector<DesktopAppData>> DesktopFileParser::getAppsByCategory( const QStringList& categories) { QMap<QString, QVector<DesktopAppData>> res; for (const DesktopAppData& app : qAsConst(m_appList)) { for (const QString& category : categories) { if (app.categories.contains(category)) { res[category].append(app); } } } return res; }
5,426
C++
.cpp
144
28.923611
95
0.593821
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,714
screenshotsaver.cpp
flameshot-org_flameshot/src/utils/screenshotsaver.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "screenshotsaver.h" #include "abstractlogger.h" #include "src/core/flameshot.h" #include "src/core/flameshotdaemon.h" #include "src/utils/confighandler.h" #include "src/utils/filenamehandler.h" #include "src/utils/globalvalues.h" #include "utils/desktopinfo.h" #if USE_WAYLAND_CLIPBOARD #include <KSystemClipboard> #endif #include <QApplication> #include <QBuffer> #include <QClipboard> #include <QFileDialog> #include <QMessageBox> #include <QMimeData> #include <QStandardPaths> #include <qimagewriter.h> #include <qmimedatabase.h> #if defined(Q_OS_MACOS) #include "src/widgets/capture/capturewidget.h" #endif bool saveToFilesystem(const QPixmap& capture, const QString& path, const QString& messagePrefix) { QString completePath = FileNameHandler().properScreenshotPath( path, ConfigHandler().saveAsFileExtension()); QFile file{ completePath }; file.open(QIODevice::WriteOnly); bool okay; QString saveExtension; saveExtension = QFileInfo(completePath).suffix().toLower(); if (saveExtension == "jpg" || saveExtension == "jpeg") { okay = capture.save(&file, nullptr, ConfigHandler().jpegQuality()); } else { okay = capture.save(&file); } QString saveMessage = messagePrefix; QString notificationPath = completePath; if (!saveMessage.isEmpty()) { saveMessage += " "; } if (okay) { saveMessage += QObject::tr("Capture saved as ") + completePath; AbstractLogger::info().attachNotificationPath(notificationPath) << saveMessage; } else { saveMessage += QObject::tr("Error trying to save as ") + completePath; if (file.error() != QFile::NoError) { saveMessage += ": " + file.errorString(); } notificationPath = ""; AbstractLogger::error().attachNotificationPath(notificationPath) << saveMessage; } return okay; } QString ShowSaveFileDialog(const QString& title, const QString& directory) { QFileDialog dialog(nullptr, title, directory); dialog.setAcceptMode(QFileDialog::AcceptSave); // Build string list of supported image formats QStringList mimeTypeList; foreach (auto mimeType, QImageWriter::supportedMimeTypes()) { // image/heif has several aliases and they cause glitch in save dialog // It is necessary to keep the image/heif (otherwise HEIF plug-in from // kimageformats will not work) but the aliases could be filtered out. if (mimeType != "image/heic" && mimeType != "image/heic-sequence" && mimeType != "image/heif-sequence") { mimeTypeList.append(mimeType); } } dialog.setMimeTypeFilters(mimeTypeList); QString suffix = ConfigHandler().saveAsFileExtension(); if (suffix.isEmpty()) { suffix = "png"; } QString defaultMimeType = QMimeDatabase().mimeTypeForFile("image." + suffix).name(); dialog.selectMimeTypeFilter(defaultMimeType); dialog.setDefaultSuffix(suffix); if (dialog.exec() == QDialog::Accepted) { return dialog.selectedFiles().constFirst(); } else { return {}; } } void saveToClipboardMime(const QPixmap& capture, const QString& imageType) { QByteArray array; QBuffer buffer{ &array }; QImageWriter imageWriter{ &buffer, imageType.toUpper().toUtf8() }; if (imageType == "jpeg") { imageWriter.setQuality(ConfigHandler().jpegQuality()); } imageWriter.write(capture.toImage()); QPixmap formattedPixmap; bool isLoaded = formattedPixmap.loadFromData(reinterpret_cast<uchar*>(array.data()), array.size(), imageType.toUpper().toUtf8()); if (isLoaded) { auto* mimeData = new QMimeData(); #ifdef USE_WAYLAND_CLIPBOARD mimeData->setImageData(formattedPixmap.toImage()); mimeData->setData(QStringLiteral("x-kde-force-image-copy"), QByteArray()); KSystemClipboard::instance()->setMimeData(mimeData, QClipboard::Clipboard); #else mimeData->setData("image/" + imageType, array); QApplication::clipboard()->setMimeData(mimeData); #endif } else { AbstractLogger::error() << QObject::tr("Error while saving to clipboard"); } } // If data is saved to the clipboard before the notification is sent via // dbus, the application freezes. void saveToClipboard(const QPixmap& capture) { // If we are able to properly save the file, save the file and copy to // clipboard. if ((ConfigHandler().saveAfterCopy()) && (!ConfigHandler().savePath().isEmpty())) { saveToFilesystem(capture, ConfigHandler().savePath(), QObject::tr("Capture saved to clipboard.")); } else { AbstractLogger() << QObject::tr("Capture saved to clipboard."); } if (ConfigHandler().useJpgForClipboard()) { // FIXME - it doesn't work on MacOS saveToClipboardMime(capture, "jpeg"); } else { // Need to send message before copying to clipboard #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) if (DesktopInfo().waylandDetected()) { saveToClipboardMime(capture, "png"); } else { QApplication::clipboard()->setPixmap(capture); } #else QApplication::clipboard()->setPixmap(capture); #endif } } bool saveToFilesystemGUI(const QPixmap& capture) { bool okay = false; ConfigHandler config; QString defaultSavePath = ConfigHandler().savePath(); if (defaultSavePath.isEmpty() || !QDir(defaultSavePath).exists() || !QFileInfo(defaultSavePath).isWritable()) { defaultSavePath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); } QString savePath = FileNameHandler().properScreenshotPath( defaultSavePath, ConfigHandler().saveAsFileExtension()); #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 (!config.savePathFixed()) { savePath = QDir::toNativeSeparators( ShowSaveFileDialog(QObject::tr("Save screenshot"), savePath)); } if (savePath == "") { return okay; } QFile file{ savePath }; file.open(QIODevice::WriteOnly); QString saveExtension; saveExtension = QFileInfo(savePath).suffix().toLower(); if (saveExtension == "jpg" || saveExtension == "jpeg") { okay = capture.save(&file, nullptr, ConfigHandler().jpegQuality()); } else { okay = capture.save(&file); } if (okay) { QString pathNoFile = savePath.left(savePath.lastIndexOf(QDir::separator())); ConfigHandler().setSavePath(pathNoFile); QString msg = QObject::tr("Capture saved as ") + savePath; AbstractLogger().attachNotificationPath(savePath) << msg; if (config.copyPathAfterSave()) { FlameshotDaemon::copyToClipboard( savePath, QObject::tr("Path copied to clipboard as ") + savePath); } } else { QString msg = QObject::tr("Error trying to save as ") + savePath; if (file.error() != QFile::NoError) { msg += ": " + file.errorString(); } QMessageBox saveErrBox( QMessageBox::Warning, QObject::tr("Save Error"), msg); saveErrBox.setWindowIcon(QIcon(GlobalValues::iconPath())); saveErrBox.exec(); } return okay; }
7,935
C++
.cpp
213
30.319249
80
0.650897
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,715
history.cpp
flameshot-org_flameshot/src/utils/history.cpp
#include "history.h" #include "src/utils/confighandler.h" #include <QDir> #include <QFile> #include <QProcessEnvironment> #include <QStringList> History::History() { // Get cache history path ConfigHandler config; #ifdef Q_OS_WIN m_historyPath = QDir::homePath() + "/AppData/Roaming/flameshot/history/"; #else QString cachepath = QProcessEnvironment::systemEnvironment().value( "XDG_CACHE_HOME", QDir::homePath() + "/.cache"); m_historyPath = cachepath + "/flameshot/history/"; #endif // Check if directory for history exists and create if doesn't QDir dir = QDir(m_historyPath); if (!dir.exists()) { dir.mkpath("."); } } const QString& History::path() { return m_historyPath; } void History::save(const QPixmap& pixmap, const QString& fileName) { // scale preview only in local disk QPixmap pixmapScaled = QPixmap(pixmap); if (pixmap.height() / HISTORYPIXMAP_MAX_PREVIEW_HEIGHT >= pixmap.width() / HISTORYPIXMAP_MAX_PREVIEW_WIDTH) { pixmapScaled = pixmap.scaledToHeight(HISTORYPIXMAP_MAX_PREVIEW_HEIGHT, Qt::SmoothTransformation); } else { pixmapScaled = pixmap.scaledToWidth(HISTORYPIXMAP_MAX_PREVIEW_WIDTH, Qt::SmoothTransformation); } // save preview QFile file(path() + fileName); file.open(QIODevice::WriteOnly); pixmapScaled.save(&file, "PNG"); history(); } const QList<QString>& History::history() { QDir directory(path()); QStringList images = directory.entryList(QStringList() << "*.png" << "*.PNG", QDir::Files, QDir::Time); int cnt = 0; int max = ConfigHandler().uploadHistoryMax(); m_thumbs.clear(); foreach (QString fileName, images) { if (++cnt <= max) { m_thumbs.append(fileName); } else { QFile file(path() + fileName); file.remove(); } } return m_thumbs; } const HistoryFileName& History::unpackFileName(const QString& fileNamePacked) { int nPathIndex = fileNamePacked.lastIndexOf("/"); QStringList unpackedFileName; if (nPathIndex == -1) { unpackedFileName = fileNamePacked.split("-"); } else { unpackedFileName = fileNamePacked.mid(nPathIndex + 1).split("-"); } switch (unpackedFileName.length()) { case 3: m_unpackedFileName.file = unpackedFileName[2]; m_unpackedFileName.token = unpackedFileName[1]; m_unpackedFileName.type = unpackedFileName[0]; break; case 2: m_unpackedFileName.file = unpackedFileName[1]; m_unpackedFileName.token = ""; m_unpackedFileName.type = unpackedFileName[0]; break; default: m_unpackedFileName.file = unpackedFileName[0]; m_unpackedFileName.token = ""; m_unpackedFileName.type = ""; break; } return m_unpackedFileName; } const QString& History::packFileName(const QString& storageType, const QString& deleteToken, const QString& fileName) { m_packedFileName = fileName; if (storageType.length() > 0) { if (deleteToken.length() > 0) { m_packedFileName = storageType + "-" + deleteToken + "-" + m_packedFileName; } else { m_packedFileName = storageType + "-" + m_packedFileName; } } return m_packedFileName; }
3,684
C++
.cpp
108
25.462963
78
0.590858
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,716
commandlineparser.cpp
flameshot-org_flameshot/src/cli/commandlineparser.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "commandlineparser.h" #include "abstractlogger.h" #include "src/utils/globalvalues.h" #include <QApplication> #include <QTextStream> CommandLineParser::CommandLineParser() : m_description(qApp->applicationName()) {} namespace { AbstractLogger out = AbstractLogger::info(AbstractLogger::Stdout).enableMessageHeader(false); AbstractLogger err = AbstractLogger::error(AbstractLogger::Stderr); auto versionOption = CommandOption({ "v", "version" }, QStringLiteral("Displays version information")); auto helpOption = CommandOption({ "h", "help" }, QStringLiteral("Displays this help")); QString optionsToString(const QList<CommandOption>& options, const QList<CommandArgument>& subcommands) { int size = 0; // track the largest size QStringList dashedOptionList; // save the dashed options and its size in order to print the description // of every option at the same horizontal character position. for (auto const& option : options) { QStringList dashedOptions = option.dashedNames(); QString joinedDashedOptions = dashedOptions.join(QStringLiteral(", ")); if (!option.valueName().isEmpty()) { joinedDashedOptions += QStringLiteral(" <%1>").arg(option.valueName()); } if (joinedDashedOptions.length() > size) { size = joinedDashedOptions.length(); } dashedOptionList << joinedDashedOptions; } // check the length of the subcommands for (auto const& subcommand : subcommands) { if (subcommand.name().length() > size) { size = subcommand.name().length(); } } // generate the text QString result; if (!dashedOptionList.isEmpty()) { result += QObject::tr("Options") + ":\n"; QString linePadding = QStringLiteral(" ").repeated(size + 4).prepend("\n"); for (int i = 0; i < options.length(); ++i) { result += QStringLiteral(" %1 %2\n") .arg(dashedOptionList.at(i).leftJustified(size, ' ')) .arg(options.at(i).description().replace( QLatin1String("\n"), linePadding)); } if (!subcommands.isEmpty()) { result += QLatin1String("\n"); } } if (!subcommands.isEmpty()) { result += QObject::tr("Subcommands") + ":\n"; } for (const auto& subcommand : subcommands) { result += QStringLiteral(" %1 %2\n") .arg(subcommand.name().leftJustified(size, ' ')) .arg(subcommand.description()); } return result; } } // unnamed namespace bool CommandLineParser::processArgs(const QStringList& args, QStringList::const_iterator& actualIt, Node*& actualNode) { QString argument = *actualIt; bool ok = true; bool isValidArg = false; for (Node& n : actualNode->subNodes) { if (n.argument.name() == argument) { actualNode = &n; isValidArg = true; break; } } if (isValidArg) { auto nextArg = actualNode->argument; m_foundArgs.append(nextArg); // check next is help ++actualIt; ok = processIfOptionIsHelp(args, actualIt, actualNode); --actualIt; } else { ok = false; err << QStringLiteral("'%1' is not a valid argument.").arg(argument); } return ok; } bool CommandLineParser::processOptions(const QStringList& args, QStringList::const_iterator& actualIt, Node* const actualNode) { QString arg = *actualIt; bool ok = true; // track values int equalsPos = arg.indexOf(QLatin1String("=")); QString valueStr; if (equalsPos != -1) { valueStr = arg.mid(equalsPos + 1); // right arg = arg.mid(0, equalsPos); // left } // check format -x --xx... bool isDoubleDashed = arg.startsWith(QLatin1String("--")); ok = isDoubleDashed ? arg.length() > 3 : arg.length() == 2; if (!ok) { err << QStringLiteral("the option %1 has a wrong format.").arg(arg); return ok; } arg = isDoubleDashed ? arg.remove(0, 2) : arg.remove(0, 1); // get option auto endIt = actualNode->options.cend(); auto optionIt = endIt; for (auto i = actualNode->options.cbegin(); i != endIt; ++i) { if ((*i).names().contains(arg)) { optionIt = i; break; } } if (optionIt == endIt) { QString argName = actualNode->argument.name(); if (argName.isEmpty()) { argName = qApp->applicationName(); } err << QStringLiteral("the option '%1' is not a valid option " "for the argument '%2'.") .arg(arg) .arg(argName); ok = false; return ok; } // check presence of values CommandOption option = *optionIt; bool requiresValue = !(option.valueName().isEmpty()); if (!requiresValue && equalsPos != -1) { err << QStringLiteral("the option '%1' contains a '=' and it doesn't " "require a value.") .arg(arg); ok = false; return ok; } else if (requiresValue && valueStr.isEmpty()) { // find in the next if (actualIt + 1 != args.cend()) { ++actualIt; } else { err << QStringLiteral("Expected value after the option '%1'.") .arg(arg); ok = false; return ok; } valueStr = *actualIt; } // check the value correctness if (requiresValue) { ok = option.checkValue(valueStr); if (!ok) { QString msg = option.errorMsg(); if (!msg.endsWith(QLatin1String("."))) { msg += QLatin1String("."); } err << msg; return ok; } option.setValue(valueStr); } m_foundOptions.append(option); return ok; } bool CommandLineParser::parse(const QStringList& args) { m_foundArgs.clear(); m_foundOptions.clear(); bool ok = true; Node* actualNode = &m_parseTree; auto it = ++args.cbegin(); // check version option QStringList dashedVersion = versionOption.dashedNames(); if (m_withVersion && args.length() > 1 && dashedVersion.contains(args.at(1))) { if (args.length() == 2) { printVersion(); m_foundOptions << versionOption; } else { err << "Invalid arguments after the version option."; ok = false; } return ok; } // check help option ok = processIfOptionIsHelp(args, it, actualNode); // process the other args for (; it != args.cend() && ok; ++it) { const QString& val = *it; if (val.startsWith(QLatin1String("-"))) { ok = processOptions(args, it, actualNode); } else { ok = processArgs(args, it, actualNode); } } if (!ok && !m_generalErrorMessage.isEmpty()) { err.enableMessageHeader(false); err << m_generalErrorMessage; err.enableMessageHeader(true); } return ok; } CommandOption CommandLineParser::addVersionOption() { m_withVersion = true; return versionOption; } CommandOption CommandLineParser::addHelpOption() { m_withHelp = true; return helpOption; } bool CommandLineParser::AddArgument(const CommandArgument& arg, const CommandArgument& parent) { bool res = true; Node* n = findParent(parent); if (n == nullptr) { res = false; } else { Node child; child.argument = arg; n->subNodes.append(child); } return res; } bool CommandLineParser::AddOption(const CommandOption& option, const CommandArgument& parent) { bool res = true; Node* n = findParent(parent); if (n == nullptr) { res = false; } else { n->options.append(option); } return res; } bool CommandLineParser::AddOptions(const QList<CommandOption>& options, const CommandArgument& parent) { bool res = true; for (auto const& option : options) { if (!AddOption(option, parent)) { res = false; break; } } return res; } void CommandLineParser::setGeneralErrorMessage(const QString& msg) { m_generalErrorMessage = msg; } void CommandLineParser::setDescription(const QString& description) { m_description = description; } bool CommandLineParser::isSet(const CommandArgument& arg) const { return m_foundArgs.contains(arg); } bool CommandLineParser::isSet(const CommandOption& option) const { return m_foundOptions.contains(option); } QString CommandLineParser::value(const CommandOption& option) const { QString value = option.value(); for (const CommandOption& fOption : m_foundOptions) { if (option == fOption) { value = fOption.value(); break; } } return value; } void CommandLineParser::printVersion() { out << GlobalValues::versionInfo(); } void CommandLineParser::printHelp(QStringList args, const Node* node) { args.removeLast(); // remove the help, it's always the last QString helpText; // add usage info QString argName = node->argument.name(); if (argName.isEmpty()) { argName = qApp->applicationName(); } QString argText = node->subNodes.isEmpty() ? "" : "[" + QObject::tr("subcommands") + "]"; helpText += (QObject::tr("Usage") + ": %1 [%2-" + QObject::tr("options") + QStringLiteral("] %3\n\n")) .arg(args.join(QStringLiteral(" "))) .arg(argName) .arg(argText); // short section about default behavior helpText += QObject::tr("Per default runs Flameshot in the background and " "adds a tray icon for configuration."); helpText += "\n\n"; // add command options and subarguments QList<CommandArgument> subcommands; for (const Node& n : node->subNodes) { subcommands.append(n.argument); } auto modifiedOptions = node->options; if (m_withHelp) { modifiedOptions << helpOption; } if (m_withVersion && node == &m_parseTree) { modifiedOptions << versionOption; } helpText += optionsToString(modifiedOptions, subcommands); // print it out << helpText; } CommandLineParser::Node* CommandLineParser::findParent( const CommandArgument& parent) { if (parent == CommandArgument()) { return &m_parseTree; } // find the parent in the subNodes recursively Node* res = nullptr; for (auto& subNode : m_parseTree.subNodes) { res = recursiveParentSearch(parent, subNode); if (res != nullptr) { break; } } return res; } CommandLineParser::Node* CommandLineParser::recursiveParentSearch( const CommandArgument& parent, Node& node) const { Node* res = nullptr; if (node.argument == parent) { res = &node; } else { for (auto& subNode : node.subNodes) { res = recursiveParentSearch(parent, subNode); if (res != nullptr) { break; } } } return res; } bool CommandLineParser::processIfOptionIsHelp( const QStringList& args, QStringList::const_iterator& actualIt, Node*& actualNode) { bool ok = true; auto dashedHelpNames = helpOption.dashedNames(); if (m_withHelp && actualIt != args.cend() && dashedHelpNames.contains(*actualIt)) { if (actualIt + 1 == args.cend()) { m_foundOptions << helpOption; printHelp(args, actualNode); actualIt++; } else { err << "Invalid arguments after the help option."; ok = false; } } return ok; }
12,277
C++
.cpp
383
24.530026
79
0.589296
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,717
commandoption.cpp
flameshot-org_flameshot/src/cli/commandoption.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "commandoption.h" #include <utility> CommandOption::CommandOption(const QString& name, QString description, QString valueName, QString defaultValue) : m_names(name) , m_description(std::move(description)) , m_valueName(std::move(valueName)) , m_value(std::move(defaultValue)) { m_checker = [](QString const&) { return true; }; } CommandOption::CommandOption(QStringList names, QString description, QString valueName, QString defaultValue) : m_names(std::move(names)) , m_description(std::move(description)) , m_valueName(std::move(valueName)) , m_value(std::move(defaultValue)) { m_checker = [](QString const&) -> bool { return true; }; } void CommandOption::setName(const QString& name) { m_names = QStringList() << name; } void CommandOption::setNames(const QStringList& names) { m_names = names; } QStringList CommandOption::names() const { return m_names; } QStringList CommandOption::dashedNames() const { QStringList dashedNames; for (const QString& name : m_names) { // prepend "-" to single character options, and "--" to the others QString dashedName = (name.length() == 1) ? QStringLiteral("-%1").arg(name) : QStringLiteral("--%1").arg(name); dashedNames << dashedName; } return dashedNames; } void CommandOption::setValueName(const QString& name) { m_valueName = name; } QString CommandOption::valueName() const { return m_valueName; } void CommandOption::setValue(const QString& value) { if (m_valueName.isEmpty()) { m_valueName = QLatin1String("value"); } m_value = value; } QString CommandOption::value() const { return m_value; } void CommandOption::addChecker(const function<bool(const QString&)> checker, const QString& errMsg) { m_checker = checker; m_errorMsg = errMsg; } bool CommandOption::checkValue(const QString& value) const { return m_checker(value); } QString CommandOption::description() const { return m_description; } void CommandOption::setDescription(const QString& description) { m_description = description; } QString CommandOption::errorMsg() const { return m_errorMsg; } bool CommandOption::operator==(const CommandOption& option) const { return m_description == option.m_description && m_names == option.m_names && m_valueName == option.m_valueName; }
2,748
C++
.cpp
96
23.125
80
0.652999
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,718
commandargument.cpp
flameshot-org_flameshot/src/cli/commandargument.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "commandargument.h" #include <utility> CommandArgument::CommandArgument() = default; CommandArgument::CommandArgument(QString name, QString description) : m_name(std::move(name)) , m_description(std::move(description)) {} void CommandArgument::setName(const QString& name) { m_name = name; } QString CommandArgument::name() const { return m_name; } void CommandArgument::setDescription(const QString& description) { m_description = description; } QString CommandArgument::description() const { return m_description; } bool CommandArgument::isRoot() const { return m_name.isEmpty() && m_description.isEmpty(); } bool CommandArgument::operator==(const CommandArgument& arg) const { return m_description == arg.m_description && m_name == arg.m_name; }
914
C++
.cpp
33
25.545455
72
0.765786
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,720
cacheutils.cpp
flameshot-org_flameshot/src/config/cacheutils.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2021 Jeremy Borgman #include "cacheutils.h" #include <QDataStream> #include <QDir> #include <QFile> #include <QRect> #include <QStandardPaths> #include <QString> QString getCachePath() { auto cachePath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); if (!QDir(cachePath).exists()) { QDir().mkpath(cachePath); } return cachePath; } void setLastRegion(QRect const& newRegion) { auto cachePath = getCachePath() + "/region.txt"; QFile file(cachePath); if (file.open(QIODevice::WriteOnly)) { QDataStream out(&file); out << newRegion; file.close(); } } QRect getLastRegion() { auto cachePath = getCachePath() + "/region.txt"; QFile file(cachePath); QRect lastRegion; if (file.open(QIODevice::ReadOnly)) { QDataStream input(&file); input >> lastRegion; file.close(); } else { lastRegion = QRect(0, 0, 0, 0); } return lastRegion; }
1,052
C++
.cpp
42
20.785714
70
0.668993
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,721
configerrordetails.cpp
flameshot-org_flameshot/src/config/configerrordetails.cpp
#include "src/config/configerrordetails.h" #include "src/utils/abstractlogger.h" #include "src/utils/confighandler.h" #include <QApplication> #include <QDialogButtonBox> #include <QTextEdit> #include <QVBoxLayout> ConfigErrorDetails::ConfigErrorDetails(QWidget* parent) : QDialog(parent) { // Generate error log message QString str; AbstractLogger stream(str, AbstractLogger::Error); ConfigHandler().checkForErrors(&stream); // Set up dialog setWindowTitle(tr("Configuration errors")); setLayout(new QVBoxLayout(this)); // Add text display auto* textDisplay = new QTextEdit(this); textDisplay->setPlainText(str); textDisplay->setReadOnly(true); layout()->addWidget(textDisplay); // Add Ok button using BBox = QDialogButtonBox; BBox* buttons = new BBox(BBox::Ok); layout()->addWidget(buttons); connect(buttons, &BBox::clicked, this, [this]() { close(); }); show(); qApp->processEvents(); QPoint center = geometry().center(); QRect dialogRect(0, 0, 600, 400); dialogRect.moveCenter(center); setGeometry(dialogRect); }
1,118
C++
.cpp
34
28.882353
66
0.718401
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,722
visualseditor.cpp
flameshot-org_flameshot/src/config/visualseditor.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "visualseditor.h" #include "src/config/buttonlistview.h" #include "src/config/colorpickereditor.h" #include "src/config/extendedslider.h" #include "src/config/uicoloreditor.h" #include "src/utils/confighandler.h" #include <QHBoxLayout> #include <QLabel> VisualsEditor::VisualsEditor(QWidget* parent) : QWidget(parent) { m_layout = new QVBoxLayout(); setLayout(m_layout); initWidgets(); } void VisualsEditor::updateComponents() { m_buttonList->updateComponents(); m_colorEditor->updateComponents(); int opacity = ConfigHandler().contrastOpacity(); m_opacitySlider->setMapedValue(0, opacity, 255); } void VisualsEditor::initOpacitySlider() { m_opacitySlider = new ExtendedSlider(); m_opacitySlider->setFocusPolicy(Qt::NoFocus); m_opacitySlider->setOrientation(Qt::Horizontal); m_opacitySlider->setRange(0, 100); auto* localLayout = new QHBoxLayout(); localLayout->addWidget(new QLabel(QStringLiteral("0%"))); localLayout->addWidget(m_opacitySlider); localLayout->addWidget(new QLabel(QStringLiteral("100%"))); auto* label = new QLabel(); QString labelMsg = tr("Opacity of area outside selection:") + " %1%"; ExtendedSlider* opacitySlider = m_opacitySlider; connect(m_opacitySlider, &ExtendedSlider::valueChanged, this, [labelMsg, label, opacitySlider](int val) { label->setText(labelMsg.arg(val)); ConfigHandler().setContrastOpacity( opacitySlider->mappedValue(0, 255)); }); m_layout->addWidget(label); m_layout->addLayout(localLayout); int opacity = ConfigHandler().contrastOpacity(); m_opacitySlider->setMapedValue(0, opacity, 255); } void VisualsEditor::initWidgets() { m_tabWidget = new QTabWidget(); m_layout->addWidget(m_tabWidget); m_colorEditor = new UIcolorEditor(); m_colorEditorTab = new QWidget(); auto* colorEditorLayout = new QVBoxLayout(m_colorEditorTab); m_colorEditorTab->setLayout(colorEditorLayout); colorEditorLayout->addWidget(m_colorEditor); m_tabWidget->addTab(m_colorEditorTab, tr("UI Color Editor")); m_colorpickerEditor = new ColorPickerEditor(); m_colorpickerEditorTab = new QWidget(); auto* colorpickerEditorLayout = new QVBoxLayout(m_colorpickerEditorTab); colorpickerEditorLayout->addWidget(m_colorpickerEditor); m_tabWidget->addTab(m_colorpickerEditorTab, tr("Colorpicker Editor")); initOpacitySlider(); auto* boxButtons = new QGroupBox(); boxButtons->setTitle(tr("Button Selection")); auto* listLayout = new QVBoxLayout(boxButtons); m_buttonList = new ButtonListView(); m_layout->addWidget(boxButtons); listLayout->addWidget(m_buttonList); auto* setAllButtons = new QPushButton(tr("Select All")); connect(setAllButtons, &QPushButton::clicked, m_buttonList, &ButtonListView::selectAll); listLayout->addWidget(setAllButtons); }
3,115
C++
.cpp
79
34.227848
76
0.717593
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,723
strftimechooserwidget.cpp
flameshot-org_flameshot/src/config/strftimechooserwidget.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "strftimechooserwidget.h" #include <QGridLayout> #include <QMap> #include <QPushButton> StrftimeChooserWidget::StrftimeChooserWidget(QWidget* parent) : QWidget(parent) { auto* layout = new QGridLayout(this); auto k = m_buttonData.keys(); int middle = k.length() / 2; // add the buttons in 2 columns (they need to be even) for (int i = 0; i < 2; i++) { for (int j = 0; j < middle; j++) { QString key = k.last(); k.pop_back(); QString variable = m_buttonData.value(key); auto* button = new QPushButton(this); button->setText(tr(key.toStdString().data())); button->setToolTip(variable); button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); button->setMinimumHeight(25); layout->addWidget(button, j, i); connect(button, &QPushButton::clicked, this, [variable, this]() { emit variableEmitted(variable); }); } } setLayout(layout); } QMap<QString, QString> StrftimeChooserWidget::m_buttonData{ { QT_TR_NOOP("Century (00-99)"), "%C" }, { QT_TR_NOOP("Year (00-99)"), "%y" }, { QT_TR_NOOP("Year (2000)"), "%Y" }, #ifndef Q_OS_WIN // TODO - fix localized names on windows (ex. Cyrillic) { QT_TR_NOOP("Month Name (jan)"), "%b" }, { QT_TR_NOOP("Month Name (january)"), "%B" }, #endif { QT_TR_NOOP("Month (01-12)"), "%m" }, { QT_TR_NOOP("Week Day (1-7)"), "%u" }, { QT_TR_NOOP("Week (01-53)"), "%V" }, #ifndef Q_OS_WIN // TODO - fix localized names on windows (ex. Cyrillic) { QT_TR_NOOP("Day Name (mon)"), "%a" }, { QT_TR_NOOP("Day Name (monday)"), "%A" }, #endif { QT_TR_NOOP("Day (01-31)"), "%d" }, { QT_TR_NOOP("Day of Month (1-31)"), "%e" }, { QT_TR_NOOP("Day (001-366)"), "%j" }, #ifndef Q_OS_WIN // TODO - fix localized names on windows (ex. Cyrillic) { QT_TR_NOOP("Time (%H-%M-%S)"), "%T" }, { QT_TR_NOOP("Time (%H-%M)"), "%R" }, #endif { QT_TR_NOOP("Hour (00-23)"), "%H" }, { QT_TR_NOOP("Hour (01-12)"), "%I" }, { QT_TR_NOOP("Minute (00-59)"), "%M" }, { QT_TR_NOOP("Second (00-59)"), "%S" }, #ifndef Q_OS_WIN // TODO - fix localized names on windows (ex. Cyrillic) { QT_TR_NOOP("Full Date (%m/%d/%y)"), "%D" }, #endif { QT_TR_NOOP("Full Date (%Y-%m-%d)"), "%F" }, };
2,538
C++
.cpp
67
31.940299
77
0.557131
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,724
uicoloreditor.cpp
flameshot-org_flameshot/src/config/uicoloreditor.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "uicoloreditor.h" #include "clickablelabel.h" #include "src/utils/confighandler.h" #include "src/utils/globalvalues.h" #include <QApplication> #include <QComboBox> #include <QHBoxLayout> #include <QMap> #include <QSpacerItem> #include <QVBoxLayout> UIcolorEditor::UIcolorEditor(QWidget* parent) : QWidget(parent) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_hLayout = new QHBoxLayout; m_vLayout = new QVBoxLayout; const int space = QApplication::fontMetrics().lineSpacing(); m_hLayout->addItem(new QSpacerItem(space, space, QSizePolicy::Expanding)); m_vLayout->setAlignment(Qt::AlignVCenter); initButtons(); initColorWheel(); m_vLayout->addSpacing(space); m_hLayout->addLayout(m_vLayout); m_hLayout->addItem(new QSpacerItem(space, space, QSizePolicy::Expanding)); setLayout(m_hLayout); updateComponents(); } void UIcolorEditor::updateComponents() { ConfigHandler config; m_uiColor = config.uiColor(); m_contrastColor = config.contrastUiColor(); m_buttonContrast->setColor(m_contrastColor); m_buttonMainColor->setColor(m_uiColor); if (m_lastButtonPressed == m_buttonMainColor) { m_colorWheel->setColor(m_uiColor); } else { m_colorWheel->setColor(m_contrastColor); } } // updateUIcolor updates the appearance of the buttons void UIcolorEditor::updateUIcolor() { ConfigHandler config; if (m_lastButtonPressed == m_buttonMainColor) { config.setUiColor(m_uiColor); } else { config.setContrastUiColor(m_contrastColor); } } // updateLocalColor updates the local button void UIcolorEditor::updateLocalColor(const QColor c) { if (m_lastButtonPressed == m_buttonMainColor) { m_uiColor = c; } else { m_contrastColor = c; } m_lastButtonPressed->setColor(c); } void UIcolorEditor::initColorWheel() { m_colorWheel = new color_widgets::ColorWheel(this); connect(m_colorWheel, &color_widgets::ColorWheel::colorSelected, this, &UIcolorEditor::updateUIcolor); connect(m_colorWheel, &color_widgets::ColorWheel::colorChanged, this, &UIcolorEditor::updateLocalColor); const int size = GlobalValues::buttonBaseSize() * 3; m_colorWheel->setMinimumSize(size, size); m_colorWheel->setMaximumSize(size * 2, size * 2); m_colorWheel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_colorWheel->setToolTip(tr("Change the color moving the selectors and see" " the changes in the preview buttons.")); m_hLayout->addWidget(m_colorWheel); } void UIcolorEditor::initButtons() { const int extraSize = GlobalValues::buttonBaseSize() / 3; int frameSize = GlobalValues::buttonBaseSize() + extraSize; m_vLayout->addWidget(new QLabel(tr("Select a Button to modify it"), this)); auto* frame = new QGroupBox(); frame->setFixedSize(frameSize, frameSize); m_buttonMainColor = new CaptureToolButton(m_buttonIconType, frame); m_buttonMainColor->move(m_buttonMainColor->x() + extraSize / 2, m_buttonMainColor->y() + extraSize / 2); auto* h1 = new QHBoxLayout(); h1->addWidget(frame); m_labelMain = new ClickableLabel(tr("Main Color"), this); h1->addWidget(m_labelMain); m_vLayout->addLayout(h1); m_buttonMainColor->setToolTip(tr("Click on this button to set the edition" " mode of the main color.")); auto* frame2 = new QGroupBox(); m_buttonContrast = new CaptureToolButton(m_buttonIconType, frame2); m_buttonContrast->move(m_buttonContrast->x() + extraSize / 2, m_buttonContrast->y() + extraSize / 2); auto* h2 = new QHBoxLayout(); h2->addWidget(frame2); frame2->setFixedSize(frameSize, frameSize); m_labelContrast = new ClickableLabel(tr("Contrast Color"), this); m_labelContrast->setStyleSheet(QStringLiteral("color : gray")); h2->addWidget(m_labelContrast); m_vLayout->addLayout(h2); m_buttonContrast->setToolTip(tr("Click on this button to set the edition" " mode of the contrast color.")); connect(m_buttonMainColor, &CaptureToolButton::pressedButtonLeftClick, this, &UIcolorEditor::changeLastButton); connect(m_buttonContrast, &CaptureToolButton::pressedButtonLeftClick, this, &UIcolorEditor::changeLastButton); // clicking the labels changes the button too connect(m_labelMain, &ClickableLabel::clicked, this, [this] { changeLastButton(m_buttonMainColor); }); connect(m_labelContrast, &ClickableLabel::clicked, this, [this] { changeLastButton(m_buttonContrast); }); m_lastButtonPressed = m_buttonMainColor; } // visual update for the selected button void UIcolorEditor::changeLastButton(CaptureToolButton* b) { if (m_lastButtonPressed != b) { m_lastButtonPressed = b; QString offStyle(QStringLiteral("QLabel { color : gray; }")); if (b == m_buttonMainColor) { m_colorWheel->setColor(m_uiColor); m_labelContrast->setStyleSheet(offStyle); m_labelMain->setStyleSheet(styleSheet()); } else { m_colorWheel->setColor(m_contrastColor); m_labelContrast->setStyleSheet(styleSheet()); m_labelMain->setStyleSheet(offStyle); } b->setIcon(b->icon()); } }
5,670
C++
.cpp
146
32.349315
80
0.679876
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,725
styleoverride.cpp
flameshot-org_flameshot/src/config/styleoverride.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2020 Jeremy Borgman <borgman.jeremy@pm.me> // // Created by jeremy on 9/24/20. #include "styleoverride.h" int StyleOverride::styleHint(StyleHint hint, const QStyleOption* option, const QWidget* widget, QStyleHintReturn* returnData) const { if (hint == SH_ToolTip_WakeUpDelay) { return 600; } else { return baseStyle()->styleHint(hint, option, widget, returnData); } }
557
C++
.cpp
16
26.5
72
0.612245
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,726
colorpickereditmode.cpp
flameshot-org_flameshot/src/config/colorpickereditmode.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2022 Dearsh Oberoi #include "colorpickereditmode.h" #include <QMouseEvent> #include <QPainter> ColorPickerEditMode::ColorPickerEditMode(QWidget* parent) : ColorPickerWidget(parent) { m_isPressing = false; m_isDragging = false; installEventFilter(this); } bool ColorPickerEditMode::eventFilter(QObject* obj, QEvent* event) { auto widget = static_cast<QWidget*>(obj); switch (event->type()) { case QEvent::MouseButtonPress: { auto mouseEvent = static_cast<QMouseEvent*>(event); if (mouseEvent->button() == Qt::LeftButton) { m_mousePressPos = mouseEvent->pos(); m_mouseMovePos = m_mousePressPos; for (int i = 1; i < m_colorList.size(); ++i) { if (m_colorAreaList.at(i).contains(m_mousePressPos)) { m_isPressing = true; m_draggedPresetInitialPos = m_colorAreaList[i].topLeft(); m_selectedIndex = i; update(m_colorAreaList.at(i) + QMargins(10, 10, 10, 10)); update(m_colorAreaList.at(m_lastIndex) + QMargins(10, 10, 10, 10)); m_lastIndex = i; emit colorSelected(m_selectedIndex); break; } } } } break; case QEvent::MouseMove: { auto mouseEvent = static_cast<QMouseEvent*>(event); if (m_isPressing) { QPoint eventPos = mouseEvent->pos(); QPoint diff = eventPos - m_mouseMovePos; m_colorAreaList[m_selectedIndex].translate(diff); widget->update(); if (!m_isDragging) { QPoint totalMovedDiff = eventPos - m_mousePressPos; if (totalMovedDiff.manhattanLength() > 3) { m_isDragging = true; } } m_mouseMovePos = eventPos; } } break; case QEvent::MouseButtonRelease: { m_isPressing = false; if (m_isDragging) { QPoint draggedPresetCenter = m_colorAreaList[m_selectedIndex].center(); m_isDragging = false; bool swapped = false; for (int i = 1; i < m_colorList.size(); ++i) { if (i != m_selectedIndex && m_colorAreaList.at(i).contains(draggedPresetCenter)) { // swap colors QColor temp = m_colorList[i]; m_colorList[i] = m_colorList[m_selectedIndex]; m_colorList[m_selectedIndex] = temp; m_config.setUserColors(m_colorList); m_colorAreaList[m_selectedIndex].moveTo( m_draggedPresetInitialPos); m_selectedIndex = i; widget->update(); m_lastIndex = i; emit presetsSwapped(m_selectedIndex); swapped = true; break; } } if (!swapped) { m_colorAreaList[m_selectedIndex].moveTo( m_draggedPresetInitialPos); widget->update(); } } } break; default: break; } return QObject::eventFilter(obj, event); }
3,720
C++
.cpp
91
24.813187
78
0.478141
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,727
buttonlistview.cpp
flameshot-org_flameshot/src/config/buttonlistview.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "buttonlistview.h" #include "src/tools/toolfactory.h" #include "src/utils/confighandler.h" #include <QListWidgetItem> #include <algorithm> ButtonListView::ButtonListView(QWidget* parent) : QListWidget(parent) { setMouseTracking(true); setFlow(QListWidget::TopToBottom); initButtonList(); updateComponents(); connect( this, &QListWidget::itemClicked, this, &ButtonListView::reverseItemCheck); } void ButtonListView::initButtonList() { ToolFactory factory; auto listTypes = CaptureToolButton::getIterableButtonTypes(); for (const CaptureTool::Type t : listTypes) { CaptureTool* tool = factory.CreateTool(t); // add element to the local map m_buttonTypeByName.insert(tool->name(), t); // init the menu option auto* m_buttonItem = new QListWidgetItem(this); // when the background is lighter than gray, it uses the white icons QColor bgColor = this->palette().color(QWidget::backgroundRole()); m_buttonItem->setIcon(tool->icon(bgColor, false)); m_buttonItem->setFlags(Qt::ItemIsUserCheckable); QColor foregroundColor = this->palette().color(QWidget::foregroundRole()); m_buttonItem->setForeground(foregroundColor); m_buttonItem->setText(tool->name()); m_buttonItem->setToolTip(tool->description()); tool->deleteLater(); } } void ButtonListView::updateActiveButtons(QListWidgetItem* item) { CaptureTool::Type bType = m_buttonTypeByName[item->text()]; if (item->checkState() == Qt::Checked) { m_listButtons.append(bType); // TODO refactor so we don't need external sorts using bt = CaptureTool::Type; std::sort(m_listButtons.begin(), m_listButtons.end(), [](bt a, bt b) { return CaptureToolButton::getPriorityByButton(a) < CaptureToolButton::getPriorityByButton(b); }); } else { m_listButtons.removeOne(bType); } ConfigHandler().setButtons(m_listButtons); } void ButtonListView::reverseItemCheck(QListWidgetItem* item) { if (item->checkState() == Qt::Checked) { item->setCheckState(Qt::Unchecked); } else { item->setCheckState(Qt::Checked); } updateActiveButtons(item); } void ButtonListView::selectAll() { ConfigHandler().setAllTheButtons(); for (int i = 0; i < this->count(); ++i) { QListWidgetItem* item = this->item(i); item->setCheckState(Qt::Checked); } } void ButtonListView::updateComponents() { m_listButtons = ConfigHandler().buttons(); auto listTypes = CaptureToolButton::getIterableButtonTypes(); for (int i = 0; i < this->count(); ++i) { QListWidgetItem* item = this->item(i); auto elem = static_cast<CaptureTool::Type>(listTypes.at(i)); if (m_listButtons.contains(elem)) { item->setCheckState(Qt::Checked); } else { item->setCheckState(Qt::Unchecked); } } }
3,111
C++
.cpp
86
30.313953
80
0.671979
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,728
colorpickereditor.cpp
flameshot-org_flameshot/src/config/colorpickereditor.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2022 Dearsh Oberoi #include "colorpickereditor.h" #include "colorpickereditmode.h" #include "src/utils/globalvalues.h" #include <QApplication> #include <QColor> #include <QGridLayout> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QMessageBox> #include <QPushButton> #include <QString> #include <QVector> ColorPickerEditor::ColorPickerEditor(QWidget* parent) : QWidget(parent) , m_selectedIndex(1) { m_color = m_config.drawColor(); m_colorList = m_config.userColors(); m_gLayout = new QGridLayout(this); m_colorpicker = new ColorPickerEditMode(this); m_gLayout->addWidget(m_colorpicker, 0, 0); m_colorWheel = new color_widgets::ColorWheel(this); m_colorWheel->setColor(m_color); const int size = GlobalValues::buttonBaseSize() * 3.5; m_colorWheel->setMinimumSize(size, size); m_gLayout->addWidget(m_colorWheel, 1, 0); auto* m_vLocalLayout1 = new QVBoxLayout(); m_vLocalLayout1->addStretch(); m_colorEditLabel = new QLabel(tr("Edit Preset:"), this); m_vLocalLayout1->addWidget(m_colorEditLabel); m_colorEdit = new QLineEdit(this); m_colorEdit->setText(m_colorList[m_selectedIndex].name(QColor::HexRgb)); m_colorEdit->setToolTip(tr("Enter color to update preset")); connect(m_colorpicker, &ColorPickerEditMode::colorSelected, this, [this](int index) { m_selectedIndex = index; m_colorEdit->setText( m_colorList[m_selectedIndex].name(QColor::HexRgb)); }); connect(m_colorpicker, &ColorPickerEditMode::presetsSwapped, this, [this](int index) { m_selectedIndex = index; m_colorList = m_config.userColors(); m_colorEdit->setText( m_colorList[m_selectedIndex].name(QColor::HexRgb)); }); m_vLocalLayout1->addWidget(m_colorEdit); m_updatePresetButton = new QPushButton(tr("Update"), this); m_updatePresetButton->setToolTip( tr("Press button to update the selected preset")); connect(m_updatePresetButton, &QPushButton::pressed, this, &ColorPickerEditor::onUpdatePreset); m_vLocalLayout1->addWidget(m_updatePresetButton); m_deletePresetButton = new QPushButton(tr("Delete"), this); m_deletePresetButton->setToolTip( tr("Press button to delete the selected preset")); connect(m_deletePresetButton, &QPushButton::pressed, this, &ColorPickerEditor::onDeletePreset); m_vLocalLayout1->addWidget(m_deletePresetButton); m_vLocalLayout1->addStretch(); m_gLayout->addLayout(m_vLocalLayout1, 0, 1); auto* m_vLocalLayout2 = new QVBoxLayout(); m_vLocalLayout2->addStretch(); m_addPresetLabel = new QLabel(tr("Add Preset:"), this); m_vLocalLayout2->addWidget(m_addPresetLabel); m_colorInput = new QLineEdit(this); m_colorInput->setText(m_color.name(QColor::HexRgb)); m_colorInput->setToolTip( tr("Enter color manually or select it using the color-wheel")); connect(m_colorWheel, &color_widgets::ColorWheel::colorSelected, this, [=](QColor c) { m_color = c; m_colorInput->setText(m_color.name(QColor::HexRgb)); }); m_vLocalLayout2->addWidget(m_colorInput); m_addPresetButton = new QPushButton(tr("Add"), this); m_addPresetButton->setToolTip(tr("Press button to add preset")); connect(m_addPresetButton, &QPushButton::pressed, this, &ColorPickerEditor::onAddPreset); m_vLocalLayout2->addWidget(m_addPresetButton); m_vLocalLayout2->addStretch(); m_gLayout->addLayout(m_vLocalLayout2, 1, 1); } void ColorPickerEditor::addPreset() { if (m_colorList.contains(m_color)) { return; } const int maxPresetsAllowed = 17; if (m_colorList.size() >= maxPresetsAllowed) { QMessageBox::critical( this, tr("Error"), tr("Unable to add preset. Maximum limit reached.")); return; } m_colorList << m_color; m_config.setUserColors(m_colorList); } void ColorPickerEditor::deletePreset() { const int minPresetsAllowed = 3; if (m_colorList.size() <= minPresetsAllowed) { QMessageBox::critical( this, tr("Error"), tr("Unable to remove preset. Minimum limit reached.")); return; } m_colorList.remove(m_selectedIndex); m_config.setUserColors(m_colorList); } void ColorPickerEditor::updatePreset() { QColor c = QColor(m_colorEdit->text()); if (m_colorList.contains(c)) { m_colorEdit->setText(m_colorList[m_selectedIndex].name(QColor::HexRgb)); return; } m_colorList[m_selectedIndex] = c; m_config.setUserColors(m_colorList); } void ColorPickerEditor::onAddPreset() { if (QColor::isValidColor(m_colorInput->text())) { m_color = QColor(m_colorInput->text()); m_colorInput->setText(m_color.name(QColor::HexRgb)); } else { m_colorInput->setText(m_color.name(QColor::HexRgb)); return; } addPreset(); m_colorpicker->updateWidget(); m_selectedIndex = 1; m_colorpicker->updateSelection(m_selectedIndex); m_colorEdit->setText(m_colorList[m_selectedIndex].name(QColor::HexRgb)); } void ColorPickerEditor::onDeletePreset() { deletePreset(); m_colorpicker->updateWidget(); m_selectedIndex = 1; m_colorpicker->updateSelection(m_selectedIndex); m_colorEdit->setText(m_colorList[m_selectedIndex].name(QColor::HexRgb)); } void ColorPickerEditor::onUpdatePreset() { if (QColor::isValidColor(m_colorEdit->text())) { QColor c = QColor(m_colorEdit->text()); m_colorEdit->setText(c.name(QColor::HexRgb)); } else { m_colorEdit->setText(m_colorList[m_selectedIndex].name(QColor::HexRgb)); return; } updatePreset(); m_colorpicker->updateWidget(); }
6,127
C++
.cpp
172
29.052326
80
0.662274
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,729
setshortcutwidget.cpp
flameshot-org_flameshot/src/config/setshortcutwidget.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2020 Yurii Puchkov at Namecheap & Contributors #include "setshortcutwidget.h" #include "src/utils/globalvalues.h" #include <QIcon> #include <QKeyEvent> #include <QLabel> #include <QLayout> #include <QPixmap> SetShortcutDialog::SetShortcutDialog(QDialog* parent, const QString& shortcutName) : QDialog(parent) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setWindowIcon(QIcon(GlobalValues::iconPath())); setWindowTitle(tr("Set Shortcut")); m_ks = QKeySequence(); m_layout = new QVBoxLayout(this); m_layout->setAlignment(Qt::AlignHCenter); auto* infoTop = new QLabel(tr("Enter new shortcut to change ")); infoTop->setMargin(10); infoTop->setAlignment(Qt::AlignCenter); m_layout->addWidget(infoTop); auto* infoIcon = new QLabel(); infoIcon->setAlignment(Qt::AlignCenter); infoIcon->setPixmap(QPixmap(":/img/app/keyboard.svg")); m_layout->addWidget(infoIcon); m_layout->addWidget(infoIcon); QString msg = ""; #if defined(Q_OS_MAC) msg = tr( "Press Esc to cancel or ⌘+Backspace to disable the keyboard shortcut."); #else msg = tr("Press Esc to cancel or Backspace to disable the keyboard shortcut."); #endif if (shortcutName == "TAKE_SCREENSHOT" || shortcutName == "SCREENSHOT_HISTORY") { msg += "\n" + tr("Flameshot must be restarted for changes to take effect."); } auto* infoBottom = new QLabel(msg); infoBottom->setMargin(10); infoBottom->setAlignment(Qt::AlignCenter); m_layout->addWidget(infoBottom); } const QKeySequence& SetShortcutDialog::shortcut() { return m_ks; } void SetShortcutDialog::keyPressEvent(QKeyEvent* ke) { if (ke->modifiers() & Qt::ShiftModifier) { m_modifier += "Shift+"; } if (ke->modifiers() & Qt::ControlModifier) { m_modifier += "Ctrl+"; } if (ke->modifiers() & Qt::AltModifier) { m_modifier += "Alt+"; } if (ke->modifiers() & Qt::MetaModifier) { m_modifier += "Meta+"; } QString key = QKeySequence(ke->key()).toString(); m_ks = QKeySequence(m_modifier + key); } void SetShortcutDialog::keyReleaseEvent(QKeyEvent* event) { if (m_ks == QKeySequence(Qt::Key_Escape)) { reject(); } accept(); }
2,392
C++
.cpp
74
27.540541
80
0.666233
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,730
extendedslider.cpp
flameshot-org_flameshot/src/config/extendedslider.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "extendedslider.h" ExtendedSlider::ExtendedSlider(QWidget* parent) : QSlider(parent) { connect(this, &ExtendedSlider::valueChanged, this, &ExtendedSlider::updateTooltip); connect( this, &ExtendedSlider::sliderMoved, this, &ExtendedSlider::fireTimer); m_timer.setSingleShot(true); connect( &m_timer, &QTimer::timeout, this, &ExtendedSlider::modificationsEnded); } int ExtendedSlider::mappedValue(int min, int max) { qreal progress = ((value() - minimum())) / static_cast<qreal>(maximum() - minimum()); return min + (max - min) * progress; } void ExtendedSlider::setMapedValue(int min, int val, int max) { qreal progress = ((val - min) + 1) / static_cast<qreal>(max - min); int value = minimum() + (maximum() - minimum()) * progress; setValue(value); } void ExtendedSlider::updateTooltip() { setToolTip(QString::number(value()) + "%"); } void ExtendedSlider::fireTimer() { m_timer.start(500); }
1,126
C++
.cpp
36
27.333333
77
0.683579
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,731
filenameeditor.cpp
flameshot-org_flameshot/src/config/filenameeditor.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "filenameeditor.h" #include "src/config/strftimechooserwidget.h" #include "src/utils/confighandler.h" #include "src/utils/filenamehandler.h" #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QVBoxLayout> FileNameEditor::FileNameEditor(QWidget* parent) : QWidget(parent) { initWidgets(); initLayout(); } void FileNameEditor::initLayout() { m_layout = new QVBoxLayout(this); auto* infoLabel = new QLabel(tr("Edit the name of your captures:"), this); infoLabel->setFixedHeight(20); m_layout->addWidget(infoLabel); m_layout->addWidget(m_helperButtons); m_layout->addWidget(new QLabel(tr("Edit:"))); m_layout->addWidget(m_nameEditor); m_layout->addWidget(new QLabel(tr("Preview:"))); m_layout->addWidget(m_outputLabel); auto* horizLayout = new QHBoxLayout(); horizLayout->addWidget(m_saveButton); horizLayout->addWidget(m_resetButton); horizLayout->addWidget(m_clearButton); m_layout->addLayout(horizLayout); } void FileNameEditor::initWidgets() { m_nameHandler = new FileNameHandler(this); // editor m_nameEditor = new QLineEdit(this); m_nameEditor->setMaxLength(FileNameHandler::MAX_CHARACTERS); // preview m_outputLabel = new QLineEdit(this); m_outputLabel->setDisabled(true); QString foreground = this->palette().windowText().color().name(); m_outputLabel->setStyleSheet(QStringLiteral("color: %1").arg(foreground)); QPalette pal = m_outputLabel->palette(); QColor color = pal.color(QPalette::Disabled, m_outputLabel->backgroundRole()); pal.setColor(QPalette::Active, m_outputLabel->backgroundRole(), color); m_outputLabel->setPalette(pal); connect(m_nameEditor, &QLineEdit::textChanged, this, &FileNameEditor::showParsedPattern); updateComponents(); // helper buttons m_helperButtons = new StrftimeChooserWidget(this); connect(m_helperButtons, &StrftimeChooserWidget::variableEmitted, this, &FileNameEditor::addToNameEditor); // save m_saveButton = new QPushButton(tr("Save"), this); connect( m_saveButton, &QPushButton::clicked, this, &FileNameEditor::savePattern); m_saveButton->setToolTip(tr("Saves the pattern")); // restore previous saved values m_resetButton = new QPushButton(tr("Restore"), this); connect( m_resetButton, &QPushButton::clicked, this, &FileNameEditor::resetName); m_resetButton->setToolTip(tr("Restores the saved pattern")); // clear m_clearButton = new QPushButton(tr("Clear"), this); connect(m_clearButton, &QPushButton::clicked, this, [this]() { m_nameEditor->setText(ConfigHandler().filenamePatternDefault()); m_nameEditor->selectAll(); m_nameEditor->setFocus(); }); m_clearButton->setToolTip(tr("Deletes the name")); } void FileNameEditor::savePattern() { QString pattern = m_nameEditor->text(); ConfigHandler().setFilenamePattern(pattern); } void FileNameEditor::showParsedPattern(const QString& p) { QString output = m_nameHandler->parseFilename(p); m_outputLabel->setText(output); } void FileNameEditor::resetName() { m_nameEditor->setText(ConfigHandler().filenamePattern()); } void FileNameEditor::addToNameEditor(const QString& s) { m_nameEditor->setText(m_nameEditor->text() + s); m_nameEditor->setFocus(); } void FileNameEditor::updateComponents() { m_nameEditor->setText(ConfigHandler().filenamePattern()); m_outputLabel->setText(m_nameHandler->parsedPattern()); }
3,728
C++
.cpp
104
31.432692
79
0.716542
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,732
shortcutswidget.cpp
flameshot-org_flameshot/src/config/shortcutswidget.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2020 Yurii Puchkov at Namecheap & Contributors #include "shortcutswidget.h" #include "capturetool.h" #include "setshortcutwidget.h" #include "src/core/qguiappcurrentscreen.h" #include "src/utils/globalvalues.h" #include "toolfactory.h" #include <QHeaderView> #include <QIcon> #include <QKeyEvent> #include <QLabel> #include <QStringList> #include <QTableWidget> #include <QVBoxLayout> #include <QVector> #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) #include <QCursor> #include <QRect> #include <QScreen> #endif ShortcutsWidget::ShortcutsWidget(QWidget* parent) : QWidget(parent) { setAttribute(Qt::WA_DeleteOnClose); setWindowIcon(QIcon(GlobalValues::iconPath())); setWindowTitle(tr("Hot Keys")); #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) QRect position = frameGeometry(); QScreen* screen = QGuiAppCurrentScreen().currentScreen(); position.moveCenter(screen->availableGeometry().center()); move(position.topLeft()); #endif m_layout = new QVBoxLayout(this); m_layout->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); initInfoTable(); connect(ConfigHandler::getInstance(), &ConfigHandler::fileChanged, this, &ShortcutsWidget::populateInfoTable); show(); } void ShortcutsWidget::initInfoTable() { m_table = new QTableWidget(this); m_table->setToolTip(tr("Available shortcuts in the screen capture mode.")); m_layout->addWidget(m_table); m_table->setColumnCount(2); m_table->setSelectionMode(QAbstractItemView::NoSelection); m_table->setFocusPolicy(Qt::NoFocus); m_table->verticalHeader()->hide(); // header creation QStringList names; names << tr("Description") << tr("Key"); m_table->setHorizontalHeaderLabels(names); connect(m_table, &QTableWidget::cellClicked, this, &ShortcutsWidget::onShortcutCellClicked); // populate with dynamic data populateInfoTable(); // adjust size m_table->horizontalHeader()->setMinimumSectionSize(200); m_table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); m_table->horizontalHeader()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_table->resizeColumnsToContents(); m_table->resizeRowsToContents(); } void ShortcutsWidget::populateInfoTable() { loadShortcuts(); m_table->setRowCount(m_shortcuts.size()); // add content for (int i = 0; i < m_shortcuts.size(); ++i) { const auto current_shortcut = m_shortcuts.at(i); const auto identifier = current_shortcut.at(0); const auto description = current_shortcut.at(1); const auto key_sequence = current_shortcut.at(2); m_table->setItem(i, 0, new QTableWidgetItem(description)); #if defined(Q_OS_MACOS) auto* item = new QTableWidgetItem(nativeOSHotKeyText(key_sequence)); #else QTableWidgetItem* item = new QTableWidgetItem(key_sequence); #endif item->setTextAlignment(Qt::AlignCenter); m_table->setItem(i, 1, item); if (identifier.isEmpty()) { QFont font; font.setBold(true); item->setFont(font); item->setFlags(item->flags() ^ Qt::ItemIsEnabled); m_table->item(i, 1)->setFont(font); } } // Read-only table items for (int x = 0; x < m_table->rowCount(); ++x) { for (int y = 0; y < m_table->columnCount(); ++y) { QTableWidgetItem* item = m_table->item(x, y); item->setFlags(item->flags() ^ Qt::ItemIsEditable); } } } void ShortcutsWidget::onShortcutCellClicked(int row, int col) { if (col == 1) { // Ignore non-changable shortcuts if (Qt::ItemIsEnabled != (Qt::ItemIsEnabled & m_table->item(row, col)->flags())) { return; } QString shortcutName = m_shortcuts.at(row).at(0); auto* setShortcutDialog = new SetShortcutDialog(nullptr, shortcutName); if (0 != setShortcutDialog->exec()) { QKeySequence shortcutValue = setShortcutDialog->shortcut(); // set no shortcut is Backspace #if defined(Q_OS_MACOS) if (shortcutValue == QKeySequence(Qt::CTRL + Qt::Key_Backspace)) { shortcutValue = QKeySequence(""); } #else if (shortcutValue == QKeySequence(Qt::Key_Backspace)) { shortcutValue = QKeySequence(""); } #endif if (m_config.setShortcut(shortcutName, shortcutValue.toString())) { populateInfoTable(); } } delete setShortcutDialog; } } void ShortcutsWidget::loadShortcuts() { m_shortcuts.clear(); auto buttonTypes = CaptureToolButton::getIterableButtonTypes(); // get shortcuts names from capture buttons for (const CaptureTool::Type& t : buttonTypes) { CaptureTool* tool = ToolFactory().CreateTool(t); QString shortcutName = QVariant::fromValue(t).toString(); appendShortcut(shortcutName, tool->description()); if (shortcutName == "TYPE_COPY") { if (m_config.copyOnDoubleClick()) { m_shortcuts << (QStringList() << "" << tool->description() << tr("Left Double-click")); } } delete tool; } // additional tools that don't have their own buttons appendShortcut("TYPE_TOGGLE_PANEL", tr("Toggle side panel")); appendShortcut("TYPE_RESIZE_LEFT", tr("Resize selection left 1px")); appendShortcut("TYPE_RESIZE_RIGHT", tr("Resize selection right 1px")); appendShortcut("TYPE_RESIZE_UP", tr("Resize selection up 1px")); appendShortcut("TYPE_RESIZE_DOWN", tr("Resize selection down 1px")); appendShortcut("TYPE_SYM_RESIZE_LEFT", tr("Symmetrically decrease width by 2px")); appendShortcut("TYPE_SYM_RESIZE_RIGHT", tr("Symmetrically increase width by 2px")); appendShortcut("TYPE_SYM_RESIZE_UP", tr("Symmetrically increase height by 2px")); appendShortcut("TYPE_SYM_RESIZE_DOWN", tr("Symmetrically decrease height by 2px")); appendShortcut("TYPE_SELECT_ALL", tr("Select entire screen")); appendShortcut("TYPE_MOVE_LEFT", tr("Move selection left 1px")); appendShortcut("TYPE_MOVE_RIGHT", tr("Move selection right 1px")); appendShortcut("TYPE_MOVE_UP", tr("Move selection up 1px")); appendShortcut("TYPE_MOVE_DOWN", tr("Move selection down 1px")); appendShortcut("TYPE_COMMIT_CURRENT_TOOL", tr("Commit text in text area")); appendShortcut("TYPE_DELETE_CURRENT_TOOL", tr("Delete current tool")); // non-editable shortcuts have an empty shortcut name m_shortcuts << (QStringList() << "" << QObject::tr("Quit capture") << QKeySequence(Qt::Key_Escape).toString()); // Global hotkeys #if defined(Q_OS_MACOS) appendShortcut("TAKE_SCREENSHOT", tr("Capture screen")); appendShortcut("SCREENSHOT_HISTORY", tr("Screenshot history")); #elif defined(Q_OS_WIN) m_shortcuts << (QStringList() << "" << QObject::tr("Screenshot history") << "Shift+Print Screen"); m_shortcuts << (QStringList() << "" << QObject::tr("Capture screen") << "Print Screen"); #else // TODO - Linux doesn't support global shortcuts for (XServer and Wayland), // possibly it will be solved in the QHotKey library later. So it is // disabled for now. #endif m_shortcuts << (QStringList() << "" << QObject::tr("Show color picker") << "Right Click"); m_shortcuts << (QStringList() << "" << QObject::tr("Change the tool's size") << "Mouse Wheel"); } void ShortcutsWidget::appendShortcut(const QString& shortcutName, const QString& description) { QString shortcut = ConfigHandler().shortcut(shortcutName); m_shortcuts << (QStringList() << shortcutName << QObject::tr(description.toStdString().c_str()) << shortcut.replace("Return", "Enter")); } #if defined(Q_OS_MACOS) const QString& ShortcutsWidget::nativeOSHotKeyText(const QString& text) { m_res = text; m_res.replace("Ctrl+", "⌘"); m_res.replace("Alt+", "⌥"); m_res.replace("Meta+", "⌃"); m_res.replace("Shift+", "⇧"); return m_res; } #endif
8,585
C++
.cpp
212
33.070755
80
0.63608
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,733
configresolver.cpp
flameshot-org_flameshot/src/config/configresolver.cpp
#include "src/config/configresolver.h" #include "src/config/configerrordetails.h" #include "src/utils/confighandler.h" #include "src/utils/valuehandler.h" #include <QDialogButtonBox> #include <QLabel> #include <QSplitter> #include <QVBoxLayout> ConfigResolver::ConfigResolver(QWidget* parent) : QDialog(parent) { setWindowTitle(tr("Resolve configuration errors")); setMinimumSize({ 250, 200 }); setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); populate(); connect(ConfigHandler::getInstance(), &ConfigHandler::fileChanged, this, [this]() { populate(); }); } QGridLayout* ConfigResolver::layout() { return dynamic_cast<QGridLayout*>(QDialog::layout()); } void ConfigResolver::populate() { ConfigHandler config; QList<QString> unrecognized; QList<QString> semanticallyWrong; config.checkUnrecognizedSettings(nullptr, &unrecognized); config.checkSemantics(nullptr, &semanticallyWrong); // Remove previous layout and children, if any resetLayout(); bool anyErrors = !semanticallyWrong.isEmpty() || !unrecognized.isEmpty(); int row = 0; // No errors detected if (!anyErrors) { accept(); } else { layout()->addWidget( new QLabel( tr("<b>You must resolve all errors before continuing:</b>")), 0, 0, 1, 2); ++row; } // List semantically incorrect settings with a "Reset" button for (const auto& key : semanticallyWrong) { auto* label = new QLabel(key); auto* reset = new QPushButton(tr("Reset")); label->setToolTip("This setting has a bad value."); reset->setToolTip(tr("Reset to the default value.")); layout()->addWidget(label, row, 0); layout()->addWidget(reset, row, 1); reset->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); connect(reset, &QPushButton::clicked, this, [key]() { ConfigHandler().resetValue(key); }); ++row; } // List unrecognized settings with a "Remove" button for (const auto& key : unrecognized) { auto* label = new QLabel(key); auto* remove = new QPushButton(tr("Remove")); label->setToolTip("This setting is unrecognized."); remove->setToolTip(tr("Remove this setting.")); layout()->addWidget(label, row, 0); layout()->addWidget(remove, row, 1); connect(remove, &QPushButton::clicked, this, [key]() { ConfigHandler().remove(key); }); ++row; } if (!config.checkShortcutConflicts()) { auto* conflicts = new QLabel( tr("Some keyboard shortcuts have conflicts.\n" "This will NOT prevent flameshot from starting.\n" "Please solve them manually in the configuration file.")); conflicts->setWordWrap(true); conflicts->setMaximumWidth(geometry().width()); conflicts->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Maximum); layout()->addWidget(conflicts, row, 0, 1, 2, Qt::AlignCenter); ++row; } auto* separator = new QFrame(this); separator->setFrameShape(QFrame::HLine); separator->setFrameShadow(QFrame::Sunken); layout()->addWidget(separator, row, 0, 1, 2); ++row; using BBox = QDialogButtonBox; // Add button box at the bottom auto* buttons = new BBox(this); layout()->addWidget(buttons, row, 0, 1, 2, Qt::AlignCenter); if (anyErrors) { auto* resolveAll = new QPushButton(tr("Resolve all")); resolveAll->setToolTip(tr("Resolve all listed errors.")); buttons->addButton(resolveAll, BBox::ResetRole); connect(resolveAll, &QPushButton::clicked, this, [=]() { for (const auto& key : semanticallyWrong) { ConfigHandler().resetValue(key); } for (const auto& key : unrecognized) { ConfigHandler().remove(key); } }); } auto* details = new QPushButton(tr("Details")); buttons->addButton(details, BBox::HelpRole); connect(details, &QPushButton::clicked, this, [this]() { (new ConfigErrorDetails(this))->exec(); }); buttons->addButton(BBox::Cancel); connect(buttons, &BBox::rejected, this, [this]() { reject(); }); } void ConfigResolver::resetLayout() { for (auto* child : children()) { child->deleteLater(); } delete layout(); setLayout(new QGridLayout()); layout()->setSizeConstraint(QLayout::SetFixedSize); }
4,570
C++
.cpp
125
29.68
77
0.633981
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,734
configwindow.cpp
flameshot-org_flameshot/src/config/configwindow.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "configwindow.h" #include "abstractlogger.h" #include "src/config/configresolver.h" #include "src/config/filenameeditor.h" #include "src/config/generalconf.h" #include "src/config/shortcutswidget.h" #include "src/config/strftimechooserwidget.h" #include "src/config/visualseditor.h" #include "src/utils/colorutils.h" #include "src/utils/confighandler.h" #include "src/utils/globalvalues.h" #include "src/utils/pathinfo.h" #include <QApplication> #include <QDialogButtonBox> #include <QFileSystemWatcher> #include <QIcon> #include <QKeyEvent> #include <QLabel> #include <QSizePolicy> #include <QTabBar> #include <QTextStream> #include <QVBoxLayout> // ConfigWindow contains the menus where you can configure the application ConfigWindow::ConfigWindow(QWidget* parent) : QWidget(parent) { // We wrap QTabWidget in a QWidget because of a Qt bug auto* layout = new QVBoxLayout(this); m_tabWidget = new QTabWidget(this); m_tabWidget->tabBar()->setUsesScrollButtons(false); layout->addWidget(m_tabWidget); setAttribute(Qt::WA_DeleteOnClose); setWindowIcon(QIcon(GlobalValues::iconPath())); setWindowTitle(tr("Configuration")); connect(ConfigHandler::getInstance(), &ConfigHandler::fileChanged, this, &ConfigWindow::updateChildren); QColor background = this->palette().window().color(); bool isDark = ColorUtils::colorIsDark(background); QString modifier = isDark ? PathInfo::whiteIconPath() : PathInfo::blackIconPath(); // visuals m_visuals = new VisualsEditor(); m_visualsTab = new QWidget(); auto* visualsLayout = new QVBoxLayout(m_visualsTab); m_visualsTab->setLayout(visualsLayout); visualsLayout->addWidget(m_visuals); m_tabWidget->addTab( m_visualsTab, QIcon(modifier + "graphics.svg"), tr("Interface")); // filename m_filenameEditor = new FileNameEditor(); m_filenameEditorTab = new QWidget(); auto* filenameEditorLayout = new QVBoxLayout(m_filenameEditorTab); m_filenameEditorTab->setLayout(filenameEditorLayout); filenameEditorLayout->addWidget(m_filenameEditor); m_tabWidget->addTab(m_filenameEditorTab, QIcon(modifier + "name_edition.svg"), tr("Filename Editor")); // general m_generalConfig = new GeneralConf(); m_generalConfigTab = new QWidget(); auto* generalConfigLayout = new QVBoxLayout(m_generalConfigTab); m_generalConfigTab->setLayout(generalConfigLayout); generalConfigLayout->addWidget(m_generalConfig); m_tabWidget->addTab( m_generalConfigTab, QIcon(modifier + "config.svg"), tr("General")); // shortcuts m_shortcuts = new ShortcutsWidget(); m_shortcutsTab = new QWidget(); auto* shortcutsLayout = new QVBoxLayout(m_shortcutsTab); m_shortcutsTab->setLayout(shortcutsLayout); shortcutsLayout->addWidget(m_shortcuts); m_tabWidget->addTab( m_shortcutsTab, QIcon(modifier + "shortcut.svg"), tr("Shortcuts")); // connect update sigslots connect(this, &ConfigWindow::updateChildren, m_filenameEditor, &FileNameEditor::updateComponents); connect(this, &ConfigWindow::updateChildren, m_visuals, &VisualsEditor::updateComponents); connect(this, &ConfigWindow::updateChildren, m_generalConfig, &GeneralConf::updateComponents); // Error indicator (this must come last) initErrorIndicator(m_visualsTab, m_visuals); initErrorIndicator(m_filenameEditorTab, m_filenameEditor); initErrorIndicator(m_generalConfigTab, m_generalConfig); initErrorIndicator(m_shortcutsTab, m_shortcuts); } void ConfigWindow::keyPressEvent(QKeyEvent* e) { if (e->key() == Qt::Key_Escape) { close(); } } void ConfigWindow::initErrorIndicator(QWidget* tab, QWidget* widget) { auto* label = new QLabel(tab); auto* btnResolve = new QPushButton(tr("Resolve"), tab); auto* btnLayout = new QHBoxLayout(); // Set up label label->setText(tr( "<b>Configuration file has errors. Resolve them before continuing.</b>")); label->setStyleSheet(QStringLiteral(":disabled { color: %1; }") .arg(qApp->palette().color(QPalette::Text).name())); label->setVisible(ConfigHandler().hasError()); // Set up "Show errors" button btnResolve->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); btnLayout->addWidget(btnResolve); btnResolve->setVisible(ConfigHandler().hasError()); widget->setEnabled(!ConfigHandler().hasError()); // Add label and button to the parent widget's layout auto* layout = static_cast<QBoxLayout*>(tab->layout()); if (layout != nullptr) { layout->insertWidget(0, label); layout->insertLayout(1, btnLayout); } else { widget->layout()->addWidget(label); widget->layout()->addWidget(btnResolve); } // Sigslots connect(ConfigHandler::getInstance(), &ConfigHandler::error, widget, [=]() { widget->setEnabled(false); label->show(); btnResolve->show(); }); connect(ConfigHandler::getInstance(), &ConfigHandler::errorResolved, widget, [=]() { widget->setEnabled(true); label->hide(); btnResolve->hide(); }); connect(btnResolve, &QPushButton::clicked, this, [this]() { ConfigResolver().exec(); }); }
5,635
C++
.cpp
145
32.8
80
0.686163
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,735
generalconf.cpp
flameshot-org_flameshot/src/config/generalconf.cpp
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "generalconf.h" #include "src/core/flameshot.h" #include "src/utils/confighandler.h" #include <QCheckBox> #include <QComboBox> #include <QFile> #include <QFileDialog> #include <QGroupBox> #include <QImageWriter> #include <QLabel> #include <QLineEdit> #include <QMessageBox> #include <QPushButton> #include <QSettings> #include <QSizePolicy> #include <QSpinBox> #include <QStandardPaths> #include <QTextCodec> #include <QVBoxLayout> GeneralConf::GeneralConf(QWidget* parent) : QWidget(parent) , m_historyConfirmationToDelete(nullptr) , m_undoLimit(nullptr) { m_layout = new QVBoxLayout(this); m_layout->setAlignment(Qt::AlignTop); // Scroll area adapts the size of the content on small screens. // It must be initialized before the checkboxes. initScrollArea(); initAutostart(); #if !defined(Q_OS_WIN) initAutoCloseIdleDaemon(); #endif initShowTrayIcon(); initShowDesktopNotification(); #if !defined(DISABLE_UPDATE_CHECKER) initCheckForUpdates(); #endif initShowStartupLaunchMessage(); initAllowMultipleGuiInstances(); initSaveLastRegion(); initShowHelp(); initShowSidePanelButton(); initUseJpgForClipboard(); initCopyOnDoubleClick(); initSaveAfterCopy(); initCopyPathAfterSave(); initCopyAndCloseAfterUpload(); initUploadWithoutConfirmation(); initHistoryConfirmationToDelete(); initAntialiasingPinZoom(); initUploadHistoryMax(); initUndoLimit(); initUploadClientSecret(); initPredefinedColorPaletteLarge(); initShowSelectionGeometry(); m_layout->addStretch(); initShowMagnifier(); initSquareMagnifier(); initJpegQuality(); // this has to be at the end initConfigButtons(); updateComponents(); } void GeneralConf::_updateComponents(bool allowEmptySavePath) { ConfigHandler config; m_helpMessage->setChecked(config.showHelp()); m_sidePanelButton->setChecked(config.showSidePanelButton()); m_sysNotifications->setChecked(config.showDesktopNotification()); m_autostart->setChecked(config.startupLaunch()); m_copyURLAfterUpload->setChecked(config.copyURLAfterUpload()); m_saveAfterCopy->setChecked(config.saveAfterCopy()); m_copyPathAfterSave->setChecked(config.copyPathAfterSave()); m_antialiasingPinZoom->setChecked(config.antialiasingPinZoom()); m_useJpgForClipboard->setChecked(config.useJpgForClipboard()); m_copyOnDoubleClick->setChecked(config.copyOnDoubleClick()); m_uploadWithoutConfirmation->setChecked(config.uploadWithoutConfirmation()); m_historyConfirmationToDelete->setChecked( config.historyConfirmationToDelete()); #if !defined(DISABLE_UPDATE_CHECKER) m_checkForUpdates->setChecked(config.checkForUpdates()); #endif m_allowMultipleGuiInstances->setChecked(config.allowMultipleGuiInstances()); m_showMagnifier->setChecked(config.showMagnifier()); m_squareMagnifier->setChecked(config.squareMagnifier()); m_saveLastRegion->setChecked(config.saveLastRegion()); #if !defined(Q_OS_WIN) m_autoCloseIdleDaemon->setChecked(config.autoCloseIdleDaemon()); #endif m_predefinedColorPaletteLarge->setChecked( config.predefinedColorPaletteLarge()); m_showStartupLaunchMessage->setChecked(config.showStartupLaunchMessage()); m_screenshotPathFixedCheck->setChecked(config.savePathFixed()); m_uploadHistoryMax->setValue(config.uploadHistoryMax()); m_undoLimit->setValue(config.undoLimit()); if (allowEmptySavePath || !config.savePath().isEmpty()) { m_savePath->setText(config.savePath()); } #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) m_showTray->setChecked(!config.disabledTrayIcon()); #endif } void GeneralConf::updateComponents() { _updateComponents(false); } void GeneralConf::saveLastRegion(bool checked) { ConfigHandler().setSaveLastRegion(checked); } void GeneralConf::showHelpChanged(bool checked) { ConfigHandler().setShowHelp(checked); } void GeneralConf::showSidePanelButtonChanged(bool checked) { ConfigHandler().setShowSidePanelButton(checked); } void GeneralConf::showDesktopNotificationChanged(bool checked) { ConfigHandler().setShowDesktopNotification(checked); } #if !defined(DISABLE_UPDATE_CHECKER) void GeneralConf::checkForUpdatesChanged(bool checked) { ConfigHandler().setCheckForUpdates(checked); } #endif void GeneralConf::allowMultipleGuiInstancesChanged(bool checked) { ConfigHandler().setAllowMultipleGuiInstances(checked); } void GeneralConf::autoCloseIdleDaemonChanged(bool checked) { ConfigHandler().setAutoCloseIdleDaemon(checked); } void GeneralConf::autostartChanged(bool checked) { ConfigHandler().setStartupLaunch(checked); } void GeneralConf::importConfiguration() { QString fileName = QFileDialog::getOpenFileName(this, tr("Import")); if (fileName.isEmpty()) { return; } QFile file(fileName); QTextCodec* codec = QTextCodec::codecForLocale(); if (!file.open(QFile::ReadOnly)) { QMessageBox::about(this, tr("Error"), tr("Unable to read file.")); return; } QString text = codec->toUnicode(file.readAll()); file.close(); QFile config(ConfigHandler().configFilePath()); if (!config.open(QFile::WriteOnly)) { QMessageBox::about(this, tr("Error"), tr("Unable to write file.")); return; } config.write(codec->fromUnicode(text)); config.close(); } void GeneralConf::exportFileConfiguration() { QString defaultFileName = QSettings().fileName(); QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName); // Cancel button or target same as source if (fileName.isNull() || fileName == defaultFileName) { return; } QFile targetFile(fileName); if (targetFile.exists()) { targetFile.remove(); } bool ok = QFile::copy(ConfigHandler().configFilePath(), fileName); if (!ok) { QMessageBox::about(this, tr("Error"), tr("Unable to write file.")); } } void GeneralConf::resetConfiguration() { QMessageBox::StandardButton reply; reply = QMessageBox::question( this, tr("Confirm Reset"), tr("Are you sure you want to reset the configuration?"), QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { m_savePath->setText( QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)); ConfigHandler().setDefaultSettings(); _updateComponents(true); } } void GeneralConf::initScrollArea() { m_scrollArea = new QScrollArea(this); m_layout->addWidget(m_scrollArea); auto* content = new QWidget(m_scrollArea); m_scrollArea->setWidget(content); m_scrollArea->setWidgetResizable(true); m_scrollArea->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Maximum); m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); content->setObjectName("content"); m_scrollArea->setObjectName("scrollArea"); m_scrollArea->setStyleSheet( "#content, #scrollArea { background: transparent; border: 0px; }"); m_scrollAreaLayout = new QVBoxLayout(content); m_scrollAreaLayout->setContentsMargins(0, 0, 20, 0); } void GeneralConf::initShowHelp() { m_helpMessage = new QCheckBox(tr("Show help message"), this); m_helpMessage->setToolTip(tr("Show the help message at the beginning " "in the capture mode")); m_scrollAreaLayout->addWidget(m_helpMessage); connect( m_helpMessage, &QCheckBox::clicked, this, &GeneralConf::showHelpChanged); } void GeneralConf::initSaveLastRegion() { m_saveLastRegion = new QCheckBox(tr("Use last region for GUI mode"), this); m_saveLastRegion->setToolTip( tr("Use the last region as the default selection for the next screenshot " "in GUI mode")); m_scrollAreaLayout->addWidget(m_saveLastRegion); connect(m_saveLastRegion, &QCheckBox::clicked, this, &GeneralConf::saveLastRegion); } void GeneralConf::initShowSidePanelButton() { m_sidePanelButton = new QCheckBox(tr("Show the side panel button"), this); m_sidePanelButton->setToolTip( tr("Show the side panel toggle button in the capture mode")); m_scrollAreaLayout->addWidget(m_sidePanelButton); connect(m_sidePanelButton, &QCheckBox::clicked, this, &GeneralConf::showSidePanelButtonChanged); } void GeneralConf::initShowDesktopNotification() { m_sysNotifications = new QCheckBox(tr("Show desktop notifications"), this); m_sysNotifications->setToolTip(tr("Enable desktop notifications")); m_scrollAreaLayout->addWidget(m_sysNotifications); connect(m_sysNotifications, &QCheckBox::clicked, this, &GeneralConf::showDesktopNotificationChanged); } void GeneralConf::initShowTrayIcon() { #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) m_showTray = new QCheckBox(tr("Show tray icon"), this); m_showTray->setToolTip(tr("Show icon in the system tray")); m_scrollAreaLayout->addWidget(m_showTray); connect(m_showTray, &QCheckBox::clicked, this, [](bool checked) { ConfigHandler().setDisabledTrayIcon(!checked); }); #endif } void GeneralConf::initHistoryConfirmationToDelete() { m_historyConfirmationToDelete = new QCheckBox( tr("Confirmation required to delete screenshot from the latest uploads"), this); m_historyConfirmationToDelete->setToolTip( tr("Ask for confirmation to delete screenshot from the latest uploads")); m_scrollAreaLayout->addWidget(m_historyConfirmationToDelete); connect(m_historyConfirmationToDelete, &QCheckBox::clicked, this, &GeneralConf::historyConfirmationToDelete); } void GeneralConf::initConfigButtons() { auto* buttonLayout = new QHBoxLayout(); auto* box = new QGroupBox(tr("Configuration File")); box->setFlat(true); box->setLayout(buttonLayout); m_layout->addWidget(box); m_exportButton = new QPushButton(tr("Export")); buttonLayout->addWidget(m_exportButton); connect(m_exportButton, &QPushButton::clicked, this, &GeneralConf::exportFileConfiguration); m_importButton = new QPushButton(tr("Import")); buttonLayout->addWidget(m_importButton); connect(m_importButton, &QPushButton::clicked, this, &GeneralConf::importConfiguration); m_resetButton = new QPushButton(tr("Reset")); buttonLayout->addWidget(m_resetButton); connect(m_resetButton, &QPushButton::clicked, this, &GeneralConf::resetConfiguration); } #if !defined(DISABLE_UPDATE_CHECKER) void GeneralConf::initCheckForUpdates() { m_checkForUpdates = new QCheckBox(tr("Automatic check for updates"), this); m_checkForUpdates->setToolTip(tr("Check for updates automatically")); m_scrollAreaLayout->addWidget(m_checkForUpdates); connect(m_checkForUpdates, &QCheckBox::clicked, this, &GeneralConf::checkForUpdatesChanged); } #endif void GeneralConf::initAllowMultipleGuiInstances() { m_allowMultipleGuiInstances = new QCheckBox( tr("Allow multiple flameshot GUI instances simultaneously"), this); m_allowMultipleGuiInstances->setToolTip(tr( "This allows you to take screenshots of Flameshot itself for example")); m_scrollAreaLayout->addWidget(m_allowMultipleGuiInstances); connect(m_allowMultipleGuiInstances, &QCheckBox::clicked, this, &GeneralConf::allowMultipleGuiInstancesChanged); } void GeneralConf::initAutoCloseIdleDaemon() { m_autoCloseIdleDaemon = new QCheckBox( tr("Automatically unload from memory when it is not needed"), this); m_autoCloseIdleDaemon->setToolTip(tr( "Automatically close daemon (background process) when it is not needed")); m_scrollAreaLayout->addWidget(m_autoCloseIdleDaemon); connect(m_autoCloseIdleDaemon, &QCheckBox::clicked, this, &GeneralConf::autoCloseIdleDaemonChanged); } void GeneralConf::initAutostart() { m_autostart = new QCheckBox(tr("Launch in background at startup"), this); m_autostart->setToolTip(tr( "Launch Flameshot daemon (background process) when computer is booted")); m_scrollAreaLayout->addWidget(m_autostart); connect( m_autostart, &QCheckBox::clicked, this, &GeneralConf::autostartChanged); } void GeneralConf::initShowStartupLaunchMessage() { m_showStartupLaunchMessage = new QCheckBox(tr("Show welcome message on launch"), this); ConfigHandler config; m_showStartupLaunchMessage->setToolTip( tr("Show the welcome message box in the middle of the screen while " "taking a screenshot")); m_scrollAreaLayout->addWidget(m_showStartupLaunchMessage); connect(m_showStartupLaunchMessage, &QCheckBox::clicked, [](bool checked) { ConfigHandler().setShowStartupLaunchMessage(checked); }); } void GeneralConf::initPredefinedColorPaletteLarge() { m_predefinedColorPaletteLarge = new QCheckBox(tr("Use large predefined color palette"), this); m_predefinedColorPaletteLarge->setToolTip( tr("Use a large predefined color palette")); m_scrollAreaLayout->addWidget(m_predefinedColorPaletteLarge); connect( m_predefinedColorPaletteLarge, &QCheckBox::clicked, [](bool checked) { ConfigHandler().setPredefinedColorPaletteLarge(checked); }); } void GeneralConf::initCopyOnDoubleClick() { m_copyOnDoubleClick = new QCheckBox(tr("Copy on double click"), this); m_copyOnDoubleClick->setToolTip( tr("Enable Copy to clipboard on Double Click")); m_scrollAreaLayout->addWidget(m_copyOnDoubleClick); connect(m_copyOnDoubleClick, &QCheckBox::clicked, [](bool checked) { ConfigHandler().setCopyOnDoubleClick(checked); }); } void GeneralConf::initCopyAndCloseAfterUpload() { m_copyURLAfterUpload = new QCheckBox(tr("Copy URL after upload"), this); m_copyURLAfterUpload->setToolTip( tr("Copy URL after uploading was successful")); m_scrollAreaLayout->addWidget(m_copyURLAfterUpload); connect(m_copyURLAfterUpload, &QCheckBox::clicked, [](bool checked) { ConfigHandler().setCopyURLAfterUpload(checked); }); } void GeneralConf::initSaveAfterCopy() { m_saveAfterCopy = new QCheckBox(tr("Save image after copy"), this); m_saveAfterCopy->setToolTip( tr("After copying the screenshot, save it to a file as well")); m_scrollAreaLayout->addWidget(m_saveAfterCopy); connect(m_saveAfterCopy, &QCheckBox::clicked, this, &GeneralConf::saveAfterCopyChanged); auto* box = new QGroupBox(tr("Save Path")); box->setFlat(true); m_layout->addWidget(box); auto* vboxLayout = new QVBoxLayout(); box->setLayout(vboxLayout); auto* pathLayout = new QHBoxLayout(); QString path = ConfigHandler().savePath(); m_savePath = new QLineEdit(path, this); m_savePath->setDisabled(true); QString foreground = this->palette().windowText().color().name(); m_savePath->setStyleSheet(QStringLiteral("color: %1").arg(foreground)); pathLayout->addWidget(m_savePath); m_changeSaveButton = new QPushButton(tr("Change..."), this); pathLayout->addWidget(m_changeSaveButton); connect(m_changeSaveButton, &QPushButton::clicked, this, &GeneralConf::changeSavePath); m_screenshotPathFixedCheck = new QCheckBox(tr("Use fixed path for screenshots to save"), this); connect(m_screenshotPathFixedCheck, &QCheckBox::toggled, this, &GeneralConf::togglePathFixed); vboxLayout->addLayout(pathLayout); vboxLayout->addWidget(m_screenshotPathFixedCheck); auto* extensionLayout = new QHBoxLayout(); extensionLayout->addWidget( new QLabel(tr("Preferred save file extension:"))); m_setSaveAsFileExtension = new QComboBox(this); QStringList imageFormatList; foreach (auto mimeType, QImageWriter::supportedImageFormats()) imageFormatList.append(mimeType); m_setSaveAsFileExtension->addItems(imageFormatList); int currentIndex = m_setSaveAsFileExtension->findText(ConfigHandler().saveAsFileExtension()); m_setSaveAsFileExtension->setCurrentIndex(currentIndex); connect(m_setSaveAsFileExtension, &QComboBox::currentTextChanged, this, &GeneralConf::setSaveAsFileExtension); extensionLayout->addWidget(m_setSaveAsFileExtension); vboxLayout->addLayout(extensionLayout); } void GeneralConf::historyConfirmationToDelete(bool checked) { ConfigHandler().setHistoryConfirmationToDelete(checked); } void GeneralConf::initUploadHistoryMax() { auto* box = new QGroupBox(tr("Latest Uploads Max Size")); box->setFlat(true); m_layout->addWidget(box); auto* vboxLayout = new QVBoxLayout(); box->setLayout(vboxLayout); m_uploadHistoryMax = new QSpinBox(this); m_uploadHistoryMax->setMaximum(50); QString foreground = this->palette().windowText().color().name(); m_uploadHistoryMax->setStyleSheet( QStringLiteral("color: %1").arg(foreground)); connect(m_uploadHistoryMax, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &GeneralConf::uploadHistoryMaxChanged); vboxLayout->addWidget(m_uploadHistoryMax); } void GeneralConf::initUploadClientSecret() { auto* box = new QGroupBox(tr("Imgur Application Client ID")); box->setFlat(true); m_layout->addWidget(box); auto* vboxLayout = new QVBoxLayout(); box->setLayout(vboxLayout); m_uploadClientKey = new QLineEdit(this); QString foreground = this->palette().windowText().color().name(); m_uploadClientKey->setStyleSheet( QStringLiteral("color: %1").arg(foreground)); m_uploadClientKey->setText(ConfigHandler().uploadClientSecret()); connect(m_uploadClientKey, &QLineEdit::editingFinished, this, &GeneralConf::uploadClientKeyEdited); vboxLayout->addWidget(m_uploadClientKey); } void GeneralConf::uploadClientKeyEdited() { ConfigHandler().setUploadClientSecret(m_uploadClientKey->text()); } void GeneralConf::uploadHistoryMaxChanged(int max) { ConfigHandler().setUploadHistoryMax(max); } void GeneralConf::initUndoLimit() { auto* box = new QGroupBox(tr("Undo limit")); box->setFlat(true); m_layout->addWidget(box); auto* vboxLayout = new QVBoxLayout(); box->setLayout(vboxLayout); m_undoLimit = new QSpinBox(this); m_undoLimit->setMinimum(1); m_undoLimit->setMaximum(999); QString foreground = this->palette().windowText().color().name(); m_undoLimit->setStyleSheet(QStringLiteral("color: %1").arg(foreground)); connect(m_undoLimit, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &GeneralConf::undoLimit); vboxLayout->addWidget(m_undoLimit); } void GeneralConf::undoLimit(int limit) { ConfigHandler().setUndoLimit(limit); } void GeneralConf::initUseJpgForClipboard() { m_useJpgForClipboard = new QCheckBox(tr("Use JPG format for clipboard (PNG default)"), this); m_useJpgForClipboard->setToolTip( tr("Use lossy JPG format for clipboard (lossless PNG default)")); m_scrollAreaLayout->addWidget(m_useJpgForClipboard); #if defined(Q_OS_MACOS) // FIXME - temporary fix to disable option for MacOS m_useJpgForClipboard->hide(); #endif connect(m_useJpgForClipboard, &QCheckBox::clicked, this, &GeneralConf::useJpgForClipboardChanged); } void GeneralConf::saveAfterCopyChanged(bool checked) { ConfigHandler().setSaveAfterCopy(checked); } void GeneralConf::changeSavePath() { QString path = ConfigHandler().savePath(); path = chooseFolder(path); if (!path.isEmpty()) { m_savePath->setText(path); ConfigHandler().setSavePath(path); } } void GeneralConf::initCopyPathAfterSave() { m_copyPathAfterSave = new QCheckBox(tr("Copy file path after save"), this); m_copyPathAfterSave->setToolTip(tr("Copy the file path to clipboard after " "the file is saved")); m_scrollAreaLayout->addWidget(m_copyPathAfterSave); connect(m_copyPathAfterSave, &QCheckBox::clicked, [](bool checked) { ConfigHandler().setCopyPathAfterSave(checked); }); } void GeneralConf::initAntialiasingPinZoom() { m_antialiasingPinZoom = new QCheckBox(tr("Anti-aliasing image when zoom the pinned image"), this); m_antialiasingPinZoom->setToolTip( tr("After zooming the pinned image, should the image get smoothened or " "stay pixelated")); m_scrollAreaLayout->addWidget(m_antialiasingPinZoom); connect(m_antialiasingPinZoom, &QCheckBox::clicked, [](bool checked) { ConfigHandler().setAntialiasingPinZoom(checked); }); } void GeneralConf::initUploadWithoutConfirmation() { m_uploadWithoutConfirmation = new QCheckBox(tr("Upload image without confirmation"), this); m_uploadWithoutConfirmation->setToolTip( tr("Upload image without confirmation")); m_scrollAreaLayout->addWidget(m_uploadWithoutConfirmation); connect(m_uploadWithoutConfirmation, &QCheckBox::clicked, [](bool checked) { ConfigHandler().setUploadWithoutConfirmation(checked); }); } const QString GeneralConf::chooseFolder(const QString& pathDefault) { QString path; if (pathDefault.isEmpty()) { path = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); } path = QFileDialog::getExistingDirectory( this, tr("Choose a Folder"), path, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (path.isEmpty()) { return path; } if (!QFileInfo(path).isWritable()) { QMessageBox::about( this, tr("Error"), tr("Unable to write to directory.")); return QString(); } return path; } void GeneralConf::initShowMagnifier() { m_showMagnifier = new QCheckBox(tr("Show magnifier"), this); m_showMagnifier->setToolTip(tr("Enable a magnifier while selecting the " "screenshot area")); m_scrollAreaLayout->addWidget(m_showMagnifier); connect(m_showMagnifier, &QCheckBox::clicked, [](bool checked) { ConfigHandler().setShowMagnifier(checked); }); } void GeneralConf::initSquareMagnifier() { m_squareMagnifier = new QCheckBox(tr("Square shaped magnifier"), this); m_squareMagnifier->setToolTip(tr("Make the magnifier to be square-shaped")); m_scrollAreaLayout->addWidget(m_squareMagnifier); connect(m_squareMagnifier, &QCheckBox::clicked, [](bool checked) { ConfigHandler().setSquareMagnifier(checked); }); } void GeneralConf::initShowSelectionGeometry() { auto* tobox = new QHBoxLayout(); int timeout = ConfigHandler().value("showSelectionGeometryHideTime").toInt(); m_xywhTimeout = new QSpinBox(); m_xywhTimeout->setRange(0, INT_MAX); m_xywhTimeout->setToolTip( tr("Milliseconds before geometry display hides; 0 means do not hide")); m_xywhTimeout->setValue(timeout); tobox->addWidget(m_xywhTimeout); tobox->addWidget(new QLabel(tr("Set geometry display timeout (ms)"))); m_scrollAreaLayout->addLayout(tobox); connect(m_xywhTimeout, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &GeneralConf::setSelGeoHideTime); auto* box = new QGroupBox(tr("Selection Geometry Display")); box->setFlat(true); m_layout->addWidget(box); auto* vboxLayout = new QVBoxLayout(); box->setLayout(vboxLayout); auto* selGeoLayout = new QHBoxLayout(); selGeoLayout->addWidget(new QLabel(tr("Display Location"))); m_selectGeometryLocation = new QComboBox(this); m_selectGeometryLocation->addItem(tr("None"), GeneralConf::xywh_none); m_selectGeometryLocation->addItem(tr("Top Left"), GeneralConf::xywh_top_left); m_selectGeometryLocation->addItem(tr("Top Right"), GeneralConf::xywh_top_right); m_selectGeometryLocation->addItem(tr("Bottom Left"), GeneralConf::xywh_bottom_left); m_selectGeometryLocation->addItem(tr("Bottom Right"), GeneralConf::xywh_bottom_right); m_selectGeometryLocation->addItem(tr("Center"), GeneralConf::xywh_center); // pick up int from config and use findData int pos = ConfigHandler().value("showSelectionGeometry").toInt(); m_selectGeometryLocation->setCurrentIndex( m_selectGeometryLocation->findData(pos)); connect( m_selectGeometryLocation, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &GeneralConf::setGeometryLocation); selGeoLayout->addWidget(m_selectGeometryLocation); vboxLayout->addLayout(selGeoLayout); vboxLayout->addStretch(); } void GeneralConf::initJpegQuality() { auto* tobox = new QHBoxLayout(); int quality = ConfigHandler().value("jpegQuality").toInt(); m_jpegQuality = new QSpinBox(); m_jpegQuality->setRange(0, 100); m_jpegQuality->setToolTip(tr("Quality range of 0-100; Higher number is " "better quality and larger file size")); m_jpegQuality->setValue(quality); tobox->addWidget(m_jpegQuality); tobox->addWidget(new QLabel(tr("JPEG Quality"))); m_scrollAreaLayout->addLayout(tobox); connect(m_jpegQuality, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &GeneralConf::setJpegQuality); } void GeneralConf::setSelGeoHideTime(int v) { ConfigHandler().setValue("showSelectionGeometryHideTime", v); } void GeneralConf::setJpegQuality(int v) { ConfigHandler().setJpegQuality(v); } void GeneralConf::setGeometryLocation(int index) { ConfigHandler().setValue("showSelectionGeometry", m_selectGeometryLocation->itemData(index)); } void GeneralConf::togglePathFixed() { ConfigHandler().setSavePathFixed(m_screenshotPathFixedCheck->isChecked()); } void GeneralConf::setSaveAsFileExtension(const QString& extension) { ConfigHandler().setSaveAsFileExtension(extension); } void GeneralConf::useJpgForClipboardChanged(bool checked) { ConfigHandler().setUseJpgForClipboard(checked); }
26,816
C++
.cpp
713
32.169705
80
0.715952
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,754
color_delegate.hpp
flameshot-org_flameshot/external/Qt-Color-Widgets/include/QtColorWidgets/color_delegate.hpp
/** * \file * * \author Mattia Basaglia * * \copyright Copyright (C) 2013-2020 Mattia Basaglia * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef COLOR_DELEGATE_HPP #define COLOR_DELEGATE_HPP #include "colorwidgets_global.hpp" #include <QStyledItemDelegate> namespace color_widgets { class QCP_EXPORT ReadOnlyColorDelegate : public QStyledItemDelegate { Q_OBJECT public: using QStyledItemDelegate::QStyledItemDelegate; void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; void setSizeHintForColor(const QSize& size_hint); const QSize& sizeHintForColor() const; protected: void paintItem(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index, const QBrush& brush) const; private: QSize size_hint{24, 16}; }; /** Delegate to use a ColorSelector in a color list */ class QCP_EXPORT ColorDelegate : public ReadOnlyColorDelegate { Q_OBJECT public: using ReadOnlyColorDelegate::ReadOnlyColorDelegate; QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const Q_DECL_OVERRIDE; void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; protected: bool eventFilter(QObject * watched, QEvent * event) Q_DECL_OVERRIDE; private slots: void close_editor(); void color_changed(); }; } // namespace color_widgets #endif // COLOR_DELEGATE_HPP
2,584
C++
.h
65
35.138462
103
0.742103
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
2,780
flameshot.h
flameshot-org_flameshot/src/core/flameshot.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/core/capturerequest.h" #include <QObject> #include <QPointer> #include <QVersionNumber> class CaptureWidget; class ConfigWindow; class InfoWindow; class CaptureLauncher; class UploadHistory; #if (defined(Q_OS_MAC) || defined(Q_OS_MAC64) || defined(Q_OS_MACOS) || \ defined(Q_OS_MACX)) class QHotkey; #endif class Flameshot : public QObject { Q_OBJECT public: enum Origin { CLI, DAEMON }; static Flameshot* instance(); public slots: CaptureWidget* gui( const CaptureRequest& req = CaptureRequest::GRAPHICAL_MODE); void screen(CaptureRequest req, int const screenNumber = -1); void full(const CaptureRequest& req); void launcher(); void config(); void info(); void history(); void openSavePath(); QVersionNumber getVersion(); public: static void setOrigin(Origin origin); static Origin origin(); void setExternalWidget(bool b); bool haveExternalWidget(); signals: void captureTaken(QPixmap p); void captureFailed(); public slots: void requestCapture(const CaptureRequest& request); void exportCapture(const QPixmap& p, QRect& selection, const CaptureRequest& req); private: Flameshot(); bool resolveAnyConfigErrors(); // class members static Origin m_origin; bool m_haveExternalWidget; QPointer<CaptureWidget> m_captureWindow; QPointer<InfoWindow> m_infoWindow; QPointer<CaptureLauncher> m_launcherWindow; QPointer<ConfigWindow> m_configWindow; #if (defined(Q_OS_MAC) || defined(Q_OS_MAC64) || defined(Q_OS_MACOS) || \ defined(Q_OS_MACX)) QHotkey* m_HotkeyScreenshotCapture; QHotkey* m_HotkeyScreenshotHistory; #endif };
1,905
C++
.h
66
24.424242
80
0.708562
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,781
flameshotdaemon.h
flameshot-org_flameshot/src/core/flameshotdaemon.h
#pragma once #include <QByteArray> #include <QObject> #include <QtDBus/QDBusAbstractAdaptor> class QPixmap; class QRect; class QDBusMessage; class QDBusConnection; class TrayIcon; class CaptureWidget; #if !defined(DISABLE_UPDATE_CHECKER) class QNetworkAccessManager; class QNetworkReply; class QVersionNumber; #endif class FlameshotDaemon : public QObject { Q_OBJECT public: static void start(); static FlameshotDaemon* instance(); static void createPin(const QPixmap& capture, QRect geometry); static void copyToClipboard(const QPixmap& capture); static void copyToClipboard(const QString& text, const QString& notification = ""); static bool isThisInstanceHostingWidgets(); void sendTrayNotification( const QString& text, const QString& title = QStringLiteral("Flameshot Info"), const int timeout = 5000); #if !defined(DISABLE_UPDATE_CHECKER) void showUpdateNotificationIfAvailable(CaptureWidget* widget); public slots: void checkForUpdates(); void getLatestAvailableVersion(); private slots: void handleReplyCheckUpdates(QNetworkReply* reply); signals: void newVersionAvailable(QVersionNumber version); #endif private: FlameshotDaemon(); void quitIfIdle(); void attachPin(const QPixmap& pixmap, QRect geometry); void attachScreenshotToClipboard(const QPixmap& pixmap); void attachPin(const QByteArray& data); void attachScreenshotToClipboard(const QByteArray& screenshot); void attachTextToClipboard(const QString& text, const QString& notification); void initTrayIcon(); void enableTrayIcon(bool enable); private: static QDBusMessage createMethodCall(const QString& method); static void checkDBusConnection(const QDBusConnection& connection); static void call(const QDBusMessage& m); bool m_persist; bool m_hostingClipboard; bool m_clipboardSignalBlocked; QList<QWidget*> m_widgets; TrayIcon* m_trayIcon; #if !defined(DISABLE_UPDATE_CHECKER) QString m_appLatestUrl; QString m_appLatestVersion; bool m_showCheckAppUpdateStatus; QNetworkAccessManager* m_networkCheckUpdates; #endif static FlameshotDaemon* m_instance; friend class FlameshotDBusAdapter; };
2,300
C++
.h
69
28.826087
71
0.763776
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,783
qguiappcurrentscreen.h
flameshot-org_flameshot/src/core/qguiappcurrentscreen.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2021 Yuriy Puchkov <yuriy.puchkov@namecheap.com> #ifndef FLAMESHOT_QGUIAPPCURRENTSCREEN_H #define FLAMESHOT_QGUIAPPCURRENTSCREEN_H #include <QPoint> class QScreen; class QGuiAppCurrentScreen { public: explicit QGuiAppCurrentScreen(); QScreen* currentScreen(); QScreen* currentScreen(const QPoint& pos); private: QScreen* screenAt(const QPoint& pos); // class members private: QScreen* m_currentScreen; }; #endif // FLAMESHOT_QGUIAPPCURRENTSCREEN_H
551
C++
.h
19
26.368421
75
0.790476
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,785
flameshotdbusadapter.h
flameshot-org_flameshot/src/core/flameshotdbusadapter.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QtDBus/QDBusAbstractAdaptor> class FlameshotDBusAdapter : public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.flameshot.Flameshot") public: explicit FlameshotDBusAdapter(QObject* parent = nullptr); virtual ~FlameshotDBusAdapter(); public slots: Q_NOREPLY void attachScreenshotToClipboard(const QByteArray& data); Q_NOREPLY void attachTextToClipboard(const QString& text, const QString& notification); Q_NOREPLY void attachPin(const QByteArray& data); };
692
C++
.h
17
35.352941
72
0.746269
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,787
toolfactory.h
flameshot-org_flameshot/src/tools/toolfactory.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/capturetool.h" #include "src/widgets/capture/capturetoolbutton.h" #include <QObject> class CaptureTool; class ToolFactory : public QObject { Q_OBJECT public: explicit ToolFactory(QObject* parent = nullptr); ToolFactory(const ToolFactory&) = delete; ToolFactory& operator=(const ToolFactory&) = delete; CaptureTool* CreateTool(CaptureTool::Type t, QObject* parent = nullptr); };
556
C++
.h
16
32.0625
76
0.774859
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,788
capturecontext.h
flameshot-org_flameshot/src/tools/capturecontext.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "capturerequest.h" #include <QPainter> #include <QPixmap> #include <QPoint> #include <QRect> struct CaptureContext { // screenshot with modifications QPixmap screenshot; // unmodified screenshot QPixmap origScreenshot; // Selection area QRect selection; // Selected tool color QColor color; // Path where the content has to be saved QString savePath; // Offset of the capture widget based on the system's screen (top-left) QPoint widgetOffset; // Mouse position inside the widget QPoint mousePos; // Size of the active tool int toolSize; // Current circle count int circleCount; // Mode of the capture widget bool fullscreen; CaptureRequest request = CaptureRequest::GRAPHICAL_MODE; QPixmap selectedScreenshotArea() const; };
958
C++
.h
33
25.242424
75
0.736156
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,789
capturetool.h
flameshot-org_flameshot/src/tools/capturetool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/capturecontext.h" #include "src/utils/colorutils.h" #include "src/utils/pathinfo.h" #include <QIcon> #include <QPainter> class CaptureTool : public QObject { Q_OBJECT public: // IMPORTANT: // Add new entries to the BOTTOM so existing user configurations don't get // messed up. // ALSO NOTE: // When adding new types, don't forget to update: // - CaptureToolButton::iterableButtonTypes // - CaptureToolButton::buttonTypeOrder enum Type { NONE = -1, TYPE_PENCIL = 0, TYPE_DRAWER = 1, TYPE_ARROW = 2, TYPE_SELECTION = 3, TYPE_RECTANGLE = 4, TYPE_CIRCLE = 5, TYPE_MARKER = 6, TYPE_SELECTIONINDICATOR = 7, TYPE_MOVESELECTION = 8, TYPE_UNDO = 9, TYPE_COPY = 10, TYPE_SAVE = 11, TYPE_EXIT = 12, TYPE_IMAGEUPLOADER = 13, TYPE_OPEN_APP = 14, TYPE_PIXELATE = 15, TYPE_REDO = 16, TYPE_PIN = 17, TYPE_TEXT = 18, TYPE_CIRCLECOUNT = 19, TYPE_SIZEINCREASE = 20, TYPE_SIZEDECREASE = 21, TYPE_INVERT = 22, TYPE_ACCEPT = 23, }; Q_ENUM(Type); // Request actions on the main widget enum Request { // Call close() in the editor. REQ_CLOSE_GUI, // Call hide() in the editor. REQ_HIDE_GUI, // Undo the last active modification in the stack. REQ_UNDO_MODIFICATION, // Redo the next modification in the stack. REQ_REDO_MODIFICATION, // Open the color picker under the mouse. REQ_SHOW_COLOR_PICKER, // Notify is the screenshot has been saved. REQ_CAPTURE_DONE_OK, // Notify to redraw screenshot with tools without object selection. REQ_CLEAR_SELECTION, // Instance this->widget()'s widget inside the editor under the mouse. REQ_ADD_CHILD_WIDGET, // Instance this->widget()'s widget which handles its own lifetime. REQ_ADD_EXTERNAL_WIDGETS, // increase tool size for all tools REQ_INCREASE_TOOL_SIZE, // decrease tool size for all tools REQ_DECREASE_TOOL_SIZE }; explicit CaptureTool(QObject* parent = nullptr) : QObject(parent) , m_count(0) , m_editMode(false) {} // TODO unused virtual void setCapture(const QPixmap& pixmap){}; // Returns false when the tool is in an inconsistent state and shouldn't // be included in the tool undo/redo stack. virtual bool isValid() const = 0; // Close the capture after the process() call if the tool was activated // from a button press. TODO remove this function virtual bool closeOnButtonPressed() const = 0; // If the tool keeps active after the selection. virtual bool isSelectable() const = 0; // Enable mouse preview. virtual bool showMousePreview() const = 0; virtual QRect mousePreviewRect(const CaptureContext& context) const { return {}; }; virtual QRect boundingRect() const = 0; // The icon of the tool. // inEditor is true when the icon is requested inside the editor // and false otherwise. virtual QIcon icon(const QColor& background, bool inEditor) const = 0; // Name displayed for the tool, this could be translated with tr() virtual QString name() const = 0; // Codename for the tool, this shouldn't change as it is used as ID // for the tool in the internals of Flameshot virtual CaptureTool::Type type() const = 0; // Short description of the tool. virtual QString description() const = 0; // Short tool item info virtual QString info() { return name(); }; // if the type is TYPE_WIDGET the widget is loaded in the main widget. // If the type is TYPE_EXTERNAL_WIDGET it is created outside as an // individual widget. virtual QWidget* widget() { return nullptr; } // When the tool is selected this method is called and the widget is added // to the configuration panel inside the main widget. virtual QWidget* configurationWidget() { return nullptr; } // Return a copy of the tool virtual CaptureTool* copy(QObject* parent = nullptr) = 0; virtual void setEditMode(bool b) { m_editMode = b; }; virtual bool editMode() { return m_editMode; }; // return true if object was change after editMode virtual bool isChanged() { return true; }; // Counter for all object types (currently is used for the CircleCounter // only) virtual void setCount(int count) { m_count = count; }; virtual int count() const { return m_count; }; // Called every time the tool has to draw virtual void process(QPainter& painter, const QPixmap& pixmap) = 0; virtual void drawSearchArea(QPainter& painter, const QPixmap& pixmap) { process(painter, pixmap); }; virtual void drawObjectSelection(QPainter& painter) { drawObjectSelectionRect(painter, boundingRect()); }; // When the tool is selected, this is called when the mouse moves virtual void paintMousePreview(QPainter& painter, const CaptureContext& context) = 0; // Move tool objects virtual void move(const QPoint& pos) { Q_UNUSED(pos) }; virtual const QPoint* pos() { return nullptr; }; signals: void requestAction(Request r); protected: void copyParams(const CaptureTool* from, CaptureTool* to) { to->m_count = from->m_count; } QString iconPath(const QColor& c) const { return ColorUtils::colorIsDark(c) ? PathInfo::whiteIconPath() : PathInfo::blackIconPath(); } void drawObjectSelectionRect(QPainter& painter, QRect rect) { QPen orig_pen = painter.pen(); painter.setPen(QPen(Qt::black, 3)); painter.drawRect(rect); painter.setPen(QPen(Qt::white, 1, Qt::DotLine)); painter.drawRect(rect); painter.setPen(orig_pen); } public slots: // On mouse release. virtual void drawEnd(const QPoint& p) = 0; // Mouse pressed and moving, called once a pixel. virtual void drawMove(const QPoint& p) = 0; // Called when drawMove is needed with an adjustment; // should be overridden in case an adjustment is applicable. virtual void drawMoveWithAdjustment(const QPoint& p) { drawMove(p); } // Called when the tool is activated. virtual void drawStart(const CaptureContext& context) = 0; // Called right after pressing the button which activates the tool. virtual void pressed(CaptureContext& context) = 0; // Called when the color is changed in the editor. virtual void onColorChanged(const QColor& c) = 0; // Called when the size the tool size is changed by the user. virtual void onSizeChanged(int size) = 0; virtual int size() const { return -1; }; private: unsigned int m_count; bool m_editMode; };
7,109
C++
.h
184
32.201087
80
0.65759
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,790
abstracttwopointtool.h
flameshot-org_flameshot/src/tools/abstracttwopointtool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "capturetool.h" class AbstractTwoPointTool : public CaptureTool { Q_OBJECT public: explicit AbstractTwoPointTool(QObject* parent = nullptr); bool isValid() const override; bool closeOnButtonPressed() const override; bool isSelectable() const override; bool showMousePreview() const override; QRect mousePreviewRect(const CaptureContext& context) const override; QRect boundingRect() const override; void move(const QPoint& pos) override; const QPoint* pos() override; int size() const override { return m_thickness; }; const QColor& color() { return m_color; }; const QPair<QPoint, QPoint> points() const { return m_points; }; void paintMousePreview(QPainter& painter, const CaptureContext& context) override; public slots: void drawEnd(const QPoint& p) override; void drawMove(const QPoint& p) override; void drawMoveWithAdjustment(const QPoint& p) override; void onColorChanged(const QColor& c) override; void onSizeChanged(int size) override; virtual void drawStart(const CaptureContext& context) override; private: QPoint adjustedVector(QPoint v) const; protected: void copyParams(const AbstractTwoPointTool* from, AbstractTwoPointTool* to); void setPadding(int padding) { m_padding = padding; }; private: // class members int m_thickness; int m_padding; QColor m_color; QPair<QPoint, QPoint> m_points; protected: // use m_padding to extend the area of the backup bool m_supportsOrthogonalAdj = false; bool m_supportsDiagonalAdj = false; };
1,745
C++
.h
45
34.222222
80
0.739208
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,791
abstractpathtool.h
flameshot-org_flameshot/src/tools/abstractpathtool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "capturetool.h" class AbstractPathTool : public CaptureTool { Q_OBJECT public: explicit AbstractPathTool(QObject* parent = nullptr); bool isValid() const override; bool closeOnButtonPressed() const override; bool isSelectable() const override; bool showMousePreview() const override; QRect mousePreviewRect(const CaptureContext& context) const override; QRect boundingRect() const override; void move(const QPoint& mousePos) override; const QPoint* pos() override; int size() const override { return m_thickness; }; public slots: void drawEnd(const QPoint& p) override; void drawMove(const QPoint& p) override; void onColorChanged(const QColor& c) override; void onSizeChanged(int size) override; protected: void copyParams(const AbstractPathTool* from, AbstractPathTool* to); void addPoint(const QPoint& point); // class members QRect m_pathArea; QColor m_color; QVector<QPoint> m_points; // use m_padding to extend the area of the backup int m_padding; QPoint m_pos; private: int m_thickness; };
1,246
C++
.h
36
30.611111
73
0.745424
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,793
applauncherwidget.h
flameshot-org_flameshot/src/tools/launcher/applauncherwidget.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QMap> #include <QWidget> #if defined(Q_OS_WIN) #include "src/utils/winlnkfileparse.h" #else #include "src/utils/desktopfileparse.h" #endif class QTabWidget; class QCheckBox; class QVBoxLayout; class QLineEdit; class QListWidget; class AppLauncherWidget : public QWidget { Q_OBJECT public: explicit AppLauncherWidget(const QPixmap& p, QWidget* parent = nullptr); private slots: void launch(const QModelIndex& index); void checkboxClicked(const bool enabled); void searchChanged(const QString& text); private: void initListWidget(); void initAppMap(); void configureListView(QListWidget* widget); void addAppsToListWidget(QListWidget* widget, const QVector<DesktopAppData>& appList); void keyPressEvent(QKeyEvent* keyEvent) override; #if defined(Q_OS_WIN) WinLnkFileParser m_parser; #else DesktopFileParser m_parser; #endif QPixmap m_pixmap; QString m_tempFile; bool m_keepOpen; QMap<QString, QVector<DesktopAppData>> m_appsMap; QCheckBox* m_keepOpenCheckbox; QCheckBox* m_terminalCheckbox; QVBoxLayout* m_layout; QLineEdit* m_lineEdit; QListWidget* m_filterList; QTabWidget* m_tabWidget; };
1,356
C++
.h
47
25.191489
76
0.754804
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,794
openwithprogram.h
flameshot-org_flameshot/src/tools/launcher/openwithprogram.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QPixmap> void showOpenWithMenu(const QPixmap& capture);
200
C++
.h
5
38.4
72
0.807292
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,795
terminallauncher.h
flameshot-org_flameshot/src/tools/launcher/terminallauncher.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QObject> struct TerminalApp { QString name; QString arg; }; class TerminalLauncher : public QObject { Q_OBJECT public: explicit TerminalLauncher(QObject* parent = nullptr); static bool launchDetached(const QString& command); private: static TerminalApp getPreferedTerminal(); };
450
C++
.h
18
22.333333
72
0.776995
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,797
markertool.h
flameshot-org_flameshot/src/tools/marker/markertool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/abstracttwopointtool.h" class MarkerTool : public AbstractTwoPointTool { Q_OBJECT public: explicit MarkerTool(QObject* parent = nullptr); QIcon icon(const QColor& background, bool inEditor) const override; QString name() const override; QString description() const override; QRect mousePreviewRect(const CaptureContext& context) const override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; void paintMousePreview(QPainter& painter, const CaptureContext& context) override; protected: CaptureTool::Type type() const override; public slots: void drawStart(const CaptureContext& context) override; void pressed(CaptureContext& context) override; };
954
C++
.h
23
36.913043
73
0.761905
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,800
texttool.h
flameshot-org_flameshot/src/tools/text/texttool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/capturetool.h" #include "textconfig.h" #include <QPoint> #include <QPointer> class TextWidget; class TextConfig; class TextTool : public CaptureTool { Q_OBJECT public: explicit TextTool(QObject* parent = nullptr); ~TextTool() override; [[nodiscard]] bool isValid() const override; [[nodiscard]] bool closeOnButtonPressed() const override; [[nodiscard]] bool isSelectable() const override; [[nodiscard]] bool showMousePreview() const override; [[nodiscard]] QRect boundingRect() const override; [[nodiscard]] QIcon icon(const QColor& background, bool inEditor) const override; [[nodiscard]] QString name() const override; [[nodiscard]] QString description() const override; QString info() override; QWidget* widget() override; QWidget* configurationWidget() override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; void paintMousePreview(QPainter& painter, const CaptureContext& context) override; void move(const QPoint& pos) override; const QPoint* pos() override; void drawObjectSelection(QPainter& painter) override; void setEditMode(bool editMode) override; bool isChanged() override; protected: void copyParams(const TextTool* from, TextTool* to); [[nodiscard]] CaptureTool::Type type() const override; public slots: void drawEnd(const QPoint& point) override; void drawMove(const QPoint& point) override; void drawStart(const CaptureContext& context) override; void pressed(CaptureContext& context) override; void onColorChanged(const QColor& color) override; void onSizeChanged(int size) override; int size() const override { return m_size; }; private slots: void updateText(const QString& string); void updateFamily(const QString& string); void updateFontUnderline(bool underlined); void updateFontStrikeOut(bool strikeout); void updateFontWeight(QFont::Weight weight); void updateFontItalic(bool italic); void updateAlignment(Qt::AlignmentFlag alignment); private: void closeEditor(); QFont m_font; Qt::AlignmentFlag m_alignment; QString m_text; QString m_textOld; int m_size; QColor m_color; QRect m_textArea; QPointer<TextWidget> m_widget; QPointer<TextConfig> m_confW; QPoint m_currentPos; QString m_tempString; };
2,621
C++
.h
69
33.072464
72
0.731284
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,801
textconfig.h
flameshot-org_flameshot/src/tools/text/textconfig.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QWidget> class QVBoxLayout; class QPushButton; class QComboBox; class TextConfig : public QWidget { Q_OBJECT public: explicit TextConfig(QWidget* parent = nullptr); void setFontFamily(const QString& fontFamily); void setUnderline(bool underline); void setStrikeOut(bool strikeout); void setWeight(int weight); void setItalic(bool italic); void setTextAlignment(Qt::AlignmentFlag alignment); signals: void fontFamilyChanged(const QString& f); void fontUnderlineChanged(const bool underlined); void fontStrikeOutChanged(const bool dashed); void fontWeightChanged(const QFont::Weight w); void fontItalicChanged(const bool italic); void alignmentChanged(Qt::AlignmentFlag alignment); public slots: private slots: void weightButtonPressed(bool weight); private: QVBoxLayout* m_layout; QComboBox* m_fontsCB; QPushButton* m_strikeOutButton; QPushButton* m_underlineButton; QPushButton* m_weightButton; QPushButton* m_italicButton; QPushButton* m_leftAlignButton; QPushButton* m_centerAlignButton; QPushButton* m_rightAlignButton; };
1,272
C++
.h
39
28.923077
72
0.777778
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,806
circletool.h
flameshot-org_flameshot/src/tools/circle/circletool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/abstracttwopointtool.h" class CircleTool : public AbstractTwoPointTool { Q_OBJECT public: explicit CircleTool(QObject* parent = nullptr); QIcon icon(const QColor& background, bool inEditor) const override; QString name() const override; QString description() const override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; protected: CaptureTool::Type type() const override; public slots: void pressed(CaptureContext& context) override; };
706
C++
.h
19
33.894737
72
0.775
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,808
pixelatetool.h
flameshot-org_flameshot/src/tools/pixelate/pixelatetool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/abstracttwopointtool.h" class PixelateTool : public AbstractTwoPointTool { Q_OBJECT public: explicit PixelateTool(QObject* parent = nullptr); QIcon icon(const QColor& background, bool inEditor) const override; QString name() const override; QString description() const override; QRect boundingRect() const override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; void drawSearchArea(QPainter& painter, const QPixmap& pixmap) override; void paintMousePreview(QPainter& painter, const CaptureContext& context) override; protected: CaptureTool::Type type() const override; public slots: void pressed(CaptureContext& context) override; };
941
C++
.h
23
36.347826
75
0.757409
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,811
linetool.h
flameshot-org_flameshot/src/tools/line/linetool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/abstracttwopointtool.h" class LineTool : public AbstractTwoPointTool { Q_OBJECT public: explicit LineTool(QObject* parent = nullptr); QIcon icon(const QColor& background, bool inEditor) const override; QString name() const override; QString description() const override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; protected: CaptureTool::Type type() const override; public slots: void pressed(CaptureContext& context) override; };
702
C++
.h
19
33.684211
72
0.773669
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,812
penciltool.h
flameshot-org_flameshot/src/tools/pencil/penciltool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/abstractpathtool.h" class PencilTool : public AbstractPathTool { Q_OBJECT public: explicit PencilTool(QObject* parent = nullptr); QIcon icon(const QColor& background, bool inEditor) const override; QString name() const override; QString description() const override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; void paintMousePreview(QPainter& painter, const CaptureContext& context) override; protected: CaptureTool::Type type() const override; public slots: void drawStart(const CaptureContext& context) override; void pressed(CaptureContext& context) override; };
873
C++
.h
22
35.090909
72
0.754448
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,813
inverttool.h
flameshot-org_flameshot/src/tools/invert/inverttool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/abstracttwopointtool.h" class InvertTool : public AbstractTwoPointTool { Q_OBJECT public: explicit InvertTool(QObject* parent = nullptr); QIcon icon(const QColor& background, bool inEditor) const override; QString name() const override; QString description() const override; QRect boundingRect() const override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; void drawSearchArea(QPainter& painter, const QPixmap& pixmap) override; void paintMousePreview(QPainter& painter, const CaptureContext& context) override; protected: CaptureTool::Type type() const override; public slots: void pressed(CaptureContext& context) override; };
937
C++
.h
23
36.173913
75
0.75634
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,814
selectiontool.h
flameshot-org_flameshot/src/tools/selection/selectiontool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/abstracttwopointtool.h" class SelectionTool : public AbstractTwoPointTool { Q_OBJECT public: explicit SelectionTool(QObject* parent = nullptr); bool closeOnButtonPressed() const override; QIcon icon(const QColor& background, bool inEditor) const override; QString name() const override; QString description() const override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; protected: CaptureTool::Type type() const override; public slots: void pressed(CaptureContext& context) override; };
761
C++
.h
20
34.65
72
0.777626
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,815
circlecounttool.h
flameshot-org_flameshot/src/tools/circlecount/circlecounttool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/abstracttwopointtool.h" class CircleCountTool : public AbstractTwoPointTool { Q_OBJECT public: explicit CircleCountTool(QObject* parent = nullptr); QIcon icon(const QColor& background, bool inEditor) const override; QString name() const override; QString description() const override; QString info() override; bool isValid() const override; QRect mousePreviewRect(const CaptureContext& context) const override; QRect boundingRect() const override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; void paintMousePreview(QPainter& painter, const CaptureContext& context) override; protected: CaptureTool::Type type() const override; void copyParams(const CircleCountTool* from, CircleCountTool* to); public slots: void drawStart(const CaptureContext& context) override; void pressed(CaptureContext& context) override; private: QString m_tempString; bool m_valid; };
1,195
C++
.h
30
35.233333
73
0.758651
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,816
imguploadermanager.h
flameshot-org_flameshot/src/tools/imgupload/imguploadermanager.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: Yurii Puchkov & Contributors // #ifndef FLAMESHOT_IMGUPLOADERMANAGER_H #define FLAMESHOT_IMGUPLOADERMANAGER_H #include "src/tools/imgupload/storages/imguploaderbase.h" #include <QObject> #define IMG_UPLOADER_STORAGE_DEFAULT "imgur" class QPixmap; class QWidget; class ImgUploaderManager : public QObject { Q_OBJECT public: explicit ImgUploaderManager(QObject* parent = nullptr); ImgUploaderBase* uploader(const QPixmap& capture, QWidget* parent = nullptr); ImgUploaderBase* uploader(const QString& imgUploaderPlugin); const QString& url(); const QString& uploaderPlugin(); private: void init(); private: ImgUploaderBase* m_imgUploaderBase; QString m_urlString; QString m_imgUploaderPlugin; }; #endif // FLAMESHOT_IMGUPLOADERMANAGER_H
886
C++
.h
28
27.785714
64
0.761792
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,818
imguploaderbase.h
flameshot-org_flameshot/src/tools/imgupload/storages/imguploaderbase.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QUrl> #include <QWidget> class QNetworkReply; class QNetworkAccessManager; class QHBoxLayout; class QVBoxLayout; class QLabel; class LoadSpinner; class QPushButton; class QUrl; class NotificationWidget; class ImgUploaderBase : public QWidget { Q_OBJECT public: explicit ImgUploaderBase(const QPixmap& capture, QWidget* parent = nullptr); LoadSpinner* spinner(); const QUrl& imageURL(); void setImageURL(const QUrl&); const QPixmap& pixmap(); void setPixmap(const QPixmap&); void setInfoLabelText(const QString&); NotificationWidget* notification(); virtual void deleteImage(const QString& fileName, const QString& deleteToken) = 0; virtual void upload() = 0; signals: void uploadOk(const QUrl& url); void deleteOk(); public slots: void showPostUploadDialog(); private slots: void startDrag(); void openURL(); void copyURL(); void copyImage(); void deleteCurrentImage(); void saveScreenshotToFilesystem(); private: QPixmap m_pixmap; QVBoxLayout* m_vLayout; QHBoxLayout* m_hLayout; // loading QLabel* m_infoLabel; LoadSpinner* m_spinner; // uploaded QPushButton* m_openUrlButton; QPushButton* m_openDeleteUrlButton; QPushButton* m_copyUrlButton; QPushButton* m_toClipboardButton; QPushButton* m_saveToFilesystemButton; QUrl m_imageURL; NotificationWidget* m_notification; public: QString m_currentImageName; };
1,632
C++
.h
59
23.576271
80
0.737821
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,819
imguruploader.h
flameshot-org_flameshot/src/tools/imgupload/storages/imgur/imguruploader.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/imgupload/storages/imguploaderbase.h" #include <QUrl> #include <QWidget> class QNetworkReply; class QNetworkAccessManager; class QUrl; class ImgurUploader : public ImgUploaderBase { Q_OBJECT public: explicit ImgurUploader(const QPixmap& capture, QWidget* parent = nullptr); void deleteImage(const QString& fileName, const QString& deleteToken); private slots: void handleReply(QNetworkReply* reply); private: void upload(); private: QNetworkAccessManager* m_NetworkAM; };
654
C++
.h
22
27.318182
78
0.7968
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,820
pinwidget.h
flameshot-org_flameshot/src/tools/pin/pinwidget.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QWidget> class QLabel; class QVBoxLayout; class QGestureEvent; class QPinchGesture; class QGraphicsDropShadowEffect; class PinWidget : public QWidget { Q_OBJECT public: explicit PinWidget(const QPixmap& pixmap, const QRect& geometry, QWidget* parent = nullptr); protected: void mouseDoubleClickEvent(QMouseEvent*) override; void mousePressEvent(QMouseEvent*) override; void mouseMoveEvent(QMouseEvent*) override; void keyPressEvent(QKeyEvent*) override; void enterEvent(QEvent*) override; void leaveEvent(QEvent*) override; bool event(QEvent* event) override; void paintEvent(QPaintEvent* event) override; private: bool gestureEvent(QGestureEvent* event); bool scrollEvent(QWheelEvent* e); void pinchTriggered(QPinchGesture*); void closePin(); void rotateLeft(); void rotateRight(); void increaseOpacity(); void decreaseOpacity(); QPixmap m_pixmap; QVBoxLayout* m_layout; QLabel* m_label; QPoint m_dragStart; qreal m_offsetX{}, m_offsetY{}; QGraphicsDropShadowEffect* m_shadowEffect; QColor m_baseColor, m_hoverColor; bool m_expanding{ false }; qreal m_scaleFactor{ 1 }; qreal m_opacity{ 1 }; unsigned int m_rotateFactor{ 0 }; qreal m_currentStepScaleFactor{ 1 }; bool m_sizeChanged{ false }; private slots: void showContextMenu(const QPoint& pos); void copyToClipboard(); void saveToFile(); };
1,630
C++
.h
52
26.615385
72
0.724138
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,823
arrowtool.h
flameshot-org_flameshot/src/tools/arrow/arrowtool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/abstracttwopointtool.h" #include <QPainter> #include <QPainterPath> class ArrowTool : public AbstractTwoPointTool { Q_OBJECT public: explicit ArrowTool(QObject* parent = nullptr); QIcon icon(const QColor& background, bool inEditor) const override; QString name() const override; QString description() const override; QRect boundingRect() const override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; protected: void copyParams(const ArrowTool* from, ArrowTool* to); CaptureTool::Type type() const override; public slots: void pressed(CaptureContext& context) override; private: QPainterPath m_arrowPath; };
888
C++
.h
25
32.28
72
0.773099
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,824
rectangletool.h
flameshot-org_flameshot/src/tools/rectangle/rectangletool.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/abstracttwopointtool.h" class RectangleTool : public AbstractTwoPointTool { Q_OBJECT public: explicit RectangleTool(QObject* parent = nullptr); QIcon icon(const QColor& background, bool inEditor) const override; QString name() const override; QString description() const override; CaptureTool* copy(QObject* parent = nullptr) override; void process(QPainter& painter, const QPixmap& pixmap) override; protected: CaptureTool::Type type() const override; public slots: void drawStart(const CaptureContext& context) override; void pressed(CaptureContext& context) override; };
772
C++
.h
20
35.25
72
0.778523
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,825
imguploaddialog.h
flameshot-org_flameshot/src/widgets/imguploaddialog.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QDialog> class QCheckBox; class QLabel; class QDialogButtonBox; class QVBoxLayout; class ImgUploadDialog : public QDialog { Q_OBJECT public: explicit ImgUploadDialog(QDialog* parent = nullptr); private: QCheckBox* m_uploadWithoutConfirmation; QLabel* m_uploadLabel; QDialogButtonBox* buttonBox; QVBoxLayout* layout; };
489
C++
.h
19
23.210526
72
0.793548
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,826
imagelabel.h
flameshot-org_flameshot/src/widgets/imagelabel.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors // This code is a modified version of the KDE software Spectacle // /src/Gui/KSImageWidget.h commit cbbd6d45f6426ccbf1a82b15fdf98613ccccbbe9 #pragma once #include <QColor> #include <QGraphicsDropShadowEffect> #include <QGuiApplication> #include <QLabel> #include <QMouseEvent> #include <QPixmap> #include <QPoint> #include <QStyleHints> class ImageLabel : public QLabel { Q_OBJECT public: explicit ImageLabel(QWidget* parent = nullptr); void setScreenshot(const QPixmap& pixmap); signals: void dragInitiated(); protected: void mousePressEvent(QMouseEvent* event) Q_DECL_OVERRIDE; void mouseReleaseEvent(QMouseEvent* event) Q_DECL_OVERRIDE; void mouseMoveEvent(QMouseEvent* event) Q_DECL_OVERRIDE; void resizeEvent(QResizeEvent* event) Q_DECL_OVERRIDE; private: void setScaledPixmap(); QGraphicsDropShadowEffect* m_DSEffect; QPixmap m_pixmap; QPoint m_dragStartPosition; };
1,048
C++
.h
32
29.96875
75
0.790467
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,827
colorpickerwidget.h
flameshot-org_flameshot/src/widgets/colorpickerwidget.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2022 Dearsh Oberoi #pragma once #include <QWidget> class ColorPickerWidget : public QWidget { Q_OBJECT public: explicit ColorPickerWidget(QWidget* parent = nullptr); static const QVector<QColor>& getDefaultSmallColorPalette(); static const QVector<QColor>& getDefaultLargeColorPalette(); void updateWidget(); void updateSelection(int index); protected: void paintEvent(QPaintEvent* event) override; void repaint(int i, QPainter& painter); int m_colorAreaSize; int m_selectedIndex, m_lastIndex; QVector<QRect> m_colorAreaList; QVector<QColor> m_colorList; QColor m_uiColor; private: void initColorPicker(); static QVector<QColor> defaultSmallColorPalette, defaultLargeColorPalette; };
824
C++
.h
25
29.24
78
0.769912
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,828
updatenotificationwidget.h
flameshot-org_flameshot/src/widgets/updatenotificationwidget.h
// // Created by yuriypuchkov on 09.12.2020. // #ifndef FLAMESHOT_UPDATENOTIFICATIONWIDGET_H #define FLAMESHOT_UPDATENOTIFICATIONWIDGET_H #include <QPointer> #include <QWidget> class QVBoxLayout; class QPropertyAnimation; class QScrollArea; class QPushButton; class QLabel; class UpdateNotificationWidget : public QWidget { Q_OBJECT public: explicit UpdateNotificationWidget(QWidget* parent, const QString& appLatestVersion, QString appLatestUrl); void setAppLatestVersion(const QString& latestVersion); void hide(); void show(); public slots: void ignoreButton(); void laterButton(); void updateButton(); private: void initInternalPanel(); // class members QString m_appLatestVersion; QString m_appLatestUrl; QVBoxLayout* m_layout; QLabel* m_notification; QScrollArea* m_internalPanel; QPropertyAnimation* m_showAnimation; QPropertyAnimation* m_hideAnimation; }; #endif // FLAMESHOT_UPDATENOTIFICATIONWIDGET_H
1,064
C++
.h
38
22.973684
70
0.72763
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,829
notificationwidget.h
flameshot-org_flameshot/src/widgets/notificationwidget.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QWidget> class QLabel; class QTimer; class QPropertyAnimation; class QVBoxLayout; class QFrame; class NotificationWidget : public QWidget { Q_OBJECT public: explicit NotificationWidget(QWidget* parent = nullptr); void showMessage(const QString& msg); private: QLabel* m_label; QPropertyAnimation* m_showAnimation; QPropertyAnimation* m_hideAnimation; QVBoxLayout* m_layout; QFrame* m_content; QTimer* m_timer; void animatedShow(); void animatedHide(); };
647
C++
.h
25
22.84
72
0.76748
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,830
orientablepushbutton.h
flameshot-org_flameshot/src/widgets/orientablepushbutton.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors // Based on https://stackoverflow.com/a/53135675/964478 #pragma once #include "capture/capturebutton.h" #include <QPushButton> class OrientablePushButton : public CaptureButton { Q_OBJECT public: enum Orientation { Horizontal, VerticalTopToBottom, VerticalBottomToTop }; OrientablePushButton(QWidget* parent = nullptr); OrientablePushButton(const QString& text, QWidget* parent = nullptr); OrientablePushButton(const QIcon& icon, const QString& text, QWidget* parent = nullptr); QSize sizeHint() const; OrientablePushButton::Orientation orientation() const; void setOrientation(OrientablePushButton::Orientation orientation); protected: void paintEvent(QPaintEvent* event); private: Orientation m_orientation = Horizontal; };
975
C++
.h
29
28.103448
73
0.726788
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,831
capturelauncher.h
flameshot-org_flameshot/src/widgets/capturelauncher.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2018 Alejandro Sirgo Rica & Contributors #pragma once #include <QDialog> QT_BEGIN_NAMESPACE namespace Ui { class CaptureLauncher; } QT_END_NAMESPACE class CaptureLauncher : public QDialog { Q_OBJECT public: explicit CaptureLauncher(QDialog* parent = nullptr); ~CaptureLauncher(); private: Ui::CaptureLauncher* ui; void connectCaptureSlots() const; void disconnectCaptureSlots() const; private slots: void startCapture(); void onCaptureTaken(QPixmap const& p); void onCaptureFailed(); };
607
C++
.h
24
22.5
72
0.770833
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,832
uploadlineitem.h
flameshot-org_flameshot/src/widgets/uploadlineitem.h
#ifndef UPLOADLINEITEM_H #define UPLOADLINEITEM_H #include <QWidget> struct HistoryFileName; QT_BEGIN_NAMESPACE namespace Ui { class UploadLineItem; } QT_END_NAMESPACE void removeCacheFile(QString const& fullFileName); class UploadLineItem : public QWidget { Q_OBJECT public: UploadLineItem(QWidget* parent, QPixmap const& preview, QString const& timestamp, QString const& url, QString const& fullFileName, HistoryFileName const& unpackFileName); ~UploadLineItem(); signals: void requestedDeletion(); private: Ui::UploadLineItem* ui; }; #endif // UPLOADLINEITEM_H
685
C++
.h
27
19.888889
58
0.693252
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,833
uploadhistory.h
flameshot-org_flameshot/src/widgets/uploadhistory.h
#ifndef UPLOADHISTORY_H #define UPLOADHISTORY_H #include <QWidget> QT_BEGIN_NAMESPACE namespace Ui { class UploadHistory; } QT_END_NAMESPACE void clearHistoryLayout(QLayout* layout); void scaleThumbnail(QPixmap& input); class UploadHistory : public QWidget { Q_OBJECT public: explicit UploadHistory(QWidget* parent = nullptr); ~UploadHistory(); void loadHistory(); public slots: private: void setEmptyMessage(); void addLine(QString const&, QString const&); Ui::UploadHistory* ui; }; #endif // UPLOADHISTORY_H
545
C++
.h
24
20.25
54
0.776265
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,834
trayicon.h
flameshot-org_flameshot/src/widgets/trayicon.h
#include <QSystemTrayIcon> #pragma once class QAction; class TrayIcon : public QSystemTrayIcon { Q_OBJECT public: TrayIcon(QObject* parent = nullptr); virtual ~TrayIcon(); #if !defined(DISABLE_UPDATE_CHECKER) QAction* appUpdates(); #endif private: void initTrayIcon(); void initMenu(); #if !defined(DISABLE_UPDATE_CHECKER) void enableCheckUpdatesAction(bool enable); #endif void startGuiCapture(); QMenu* m_menu; #if !defined(DISABLE_UPDATE_CHECKER) QAction* m_appUpdates; #endif };
530
C++
.h
24
19.125
47
0.747495
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,835
infowindow.h
flameshot-org_flameshot/src/widgets/infowindow.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2021-2022 Jeremy Borgman & Contributors #pragma once #include <QWidget> QT_BEGIN_NAMESPACE namespace Ui { class InfoWindow; } QT_END_NAMESPACE class InfoWindow : public QWidget { Q_OBJECT public: explicit InfoWindow(QWidget* parent = nullptr); ~InfoWindow(); private: Ui::InfoWindow* ui; protected: void keyPressEvent(QKeyEvent* event); private slots: void on_CopyInfoButton_clicked(); }; QString generateKernelString();
526
C++
.h
23
20.434783
66
0.775304
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,836
loadspinner.h
flameshot-org_flameshot/src/widgets/loadspinner.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QWidget> class LoadSpinner : public QWidget { Q_OBJECT public: explicit LoadSpinner(QWidget* parent = nullptr); void setColor(const QColor& c); void setWidth(int w); void setHeight(int h); void start(); void stop(); protected: void paintEvent(QPaintEvent*); private slots: void rotate(); private: QColor m_color; QTimer* m_timer; int m_startAngle = 0; int m_span = 180; bool m_growing; QRect m_frame; void updateFrame(); };
638
C++
.h
27
19.925926
72
0.700997
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,837
draggablewidgetmaker.h
flameshot-org_flameshot/src/widgets/draggablewidgetmaker.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QEvent> #include <QObject> #include <QPoint> #include <QWidget> class DraggableWidgetMaker : public QObject { Q_OBJECT public: DraggableWidgetMaker(QObject* parent = nullptr); void makeDraggable(QWidget* widget); protected: bool eventFilter(QObject* obj, QEvent* event) override; private: bool m_isPressing = false; bool m_isDragging = false; QPoint m_mouseMovePos; QPoint m_mousePressPos; };
572
C++
.h
21
24.428571
72
0.763303
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,838
utilitypanel.h
flameshot-org_flameshot/src/widgets/panel/utilitypanel.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/tools/capturetool.h" #include <QPointer> #include <QWidget> class QVBoxLayout; class QPropertyAnimation; class QScrollArea; class QPushButton; class QListWidget; class QPushButton; class CaptureWidget; class UtilityPanel : public QWidget { Q_OBJECT public: explicit UtilityPanel(CaptureWidget* captureWidget); [[nodiscard]] QWidget* toolWidget() const; void setToolWidget(QWidget* weight); void clearToolWidget(); void pushWidget(QWidget* widget); void hide(); void show(); void fillCaptureTools( const QList<QPointer<CaptureTool>>& captureToolObjectsHistory); void setActiveLayer(int index); int activeLayerIndex(); bool isVisible() const; signals: void layerChanged(int layer); void moveUpClicked(int currentRow); void moveDownClicked(int currentRow); public slots: void toggle(); void slotButtonDelete(bool clicked); void onCurrentRowChanged(int currentRow); private slots: void slotUpClicked(bool clicked); void slotDownClicked(bool clicked); private: void initInternalPanel(); QPointer<QWidget> m_toolWidget; QScrollArea* m_internalPanel; QVBoxLayout* m_upLayout; QVBoxLayout* m_bottomLayout; QVBoxLayout* m_layout; QPropertyAnimation* m_showAnimation; QPropertyAnimation* m_hideAnimation; QVBoxLayout* m_layersLayout; QListWidget* m_captureTools; QPushButton* m_buttonDelete; QPushButton* m_buttonMoveUp; QPushButton* m_buttonMoveDown; CaptureWidget* m_captureWidget; };
1,674
C++
.h
56
26.178571
72
0.766791
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,839
colorgrabwidget.h
flameshot-org_flameshot/src/widgets/panel/colorgrabwidget.h
#ifndef COLORGRABWIDGET_H #define COLORGRABWIDGET_H #include <QWidget> class SidePanelWidget; class OverlayMessage; class ColorGrabWidget : public QWidget { Q_OBJECT public: ColorGrabWidget(QPixmap* p, QWidget* parent = nullptr); void startGrabbing(); QColor color(); signals: void colorUpdated(const QColor& color); void colorGrabbed(const QColor& color); void grabAborted(); private: bool eventFilter(QObject* obj, QEvent* event) override; void paintEvent(QPaintEvent* e) override; void showEvent(QShowEvent* event) override; QPoint cursorPos() const; QColor getColorAtPoint(const QPoint& point) const; void setExtraZoomActive(bool active); void setMagnifierActive(bool active); void updateWidget(); void finalize(); QPixmap* m_pixmap; QImage m_previewImage; QColor m_color; bool m_mousePressReceived; bool m_extraZoomActive; bool m_magnifierActive; }; #endif // COLORGRABWIDGET_H
982
C++
.h
34
24.970588
59
0.751334
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,840
sidepanelwidget.h
flameshot-org_flameshot/src/widgets/panel/sidepanelwidget.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "QtColorWidgets/color_wheel.hpp" #include <QSpinBox> #include <QWidget> class QVBoxLayout; class QPushButton; class QLabel; class QLineEdit; class ColorGrabWidget; class QColorPickingEventFilter; class QSlider; class QCheckBox; constexpr int maxToolSize = 50; constexpr int minSliderWidth = 100; class SidePanelWidget : public QWidget { Q_OBJECT friend class QColorPickingEventFilter; public: explicit SidePanelWidget(QPixmap* p, QWidget* parent = nullptr); signals: void colorChanged(const QColor& color); void toolSizeChanged(int size); void togglePanel(); void displayGridChanged(bool display); void gridSizeChanged(int size); public slots: void onToolSizeChanged(int tool); void onColorChanged(const QColor& color); private slots: void startColorGrab(); void onColorGrabFinished(); void onColorGrabAborted(); void onTemporaryColorUpdated(const QColor& color); private: void finalizeGrab(); void updateColorNoWheel(const QColor& color); bool eventFilter(QObject* obj, QEvent* event) override; void hideEvent(QHideEvent* event) override; QVBoxLayout* m_layout; QPushButton* m_colorGrabButton; ColorGrabWidget* m_colorGrabber{}; color_widgets::ColorWheel* m_colorWheel; QLabel* m_colorLabel; QLineEdit* m_colorHex; QPixmap* m_pixmap; QColor m_color; QColor m_revertColor; QSpinBox* m_toolSizeSpin; QSlider* m_toolSizeSlider; int m_toolSize{}; QCheckBox* m_gridCheck{ nullptr }; QSpinBox* m_gridSizeSpin{ nullptr }; };
1,700
C++
.h
56
26.839286
72
0.765175
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,841
overlaymessage.h
flameshot-org_flameshot/src/widgets/capture/overlaymessage.h
#pragma once #include <QLabel> #include <QStack> /** * @brief Overlay a message in capture mode. * * The message must be initialized by calling `init` before it can be used. That * can be done once per capture session. The class is a singleton. * * To change the active message call `push`. This will automatically show the * widget. Previous messages won't be forgotten and will be reactivated after * you call `pop`. You can show/hide the message using `setVisibility` (this * won't push/pop anything). * * @note You have to make sure that widgets pop the messages they pushed when * they are closed, to avoid potential bugs and resource leaks. */ class OverlayMessage : public QLabel { public: OverlayMessage() = delete; static void init(QWidget* parent, const QRect& targetArea); static void push(const QString& msg); static void pop(); static void setVisibility(bool visible); static OverlayMessage* instance(); static void pushKeyMap(const QList<QPair<QString, QString>>& map); static QString compileFromKeyMap(const QList<QPair<QString, QString>>& map); private: QStack<QString> m_messageStack; QRect m_targetArea; QColor m_fillColor, m_textColor; static OverlayMessage* m_instance; OverlayMessage(QWidget* parent, const QRect& center); void paintEvent(QPaintEvent*) override; QRect boundingRect() const; void updateGeometry(); };
1,423
C++
.h
38
34.210526
80
0.74655
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,842
modificationcommand.h
flameshot-org_flameshot/src/widgets/capture/modificationcommand.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "capturetoolobjects.h" #include <QUndoCommand> #ifndef FLAMESHOT_MODIFICATIONCOMMAND_H #define FLAMESHOT_MODIFICATIONCOMMAND_H class CaptureWidget; class ModificationCommand : public QUndoCommand { public: ModificationCommand(CaptureWidget* captureWidget, const CaptureToolObjects& captureToolObjects, const CaptureToolObjects& captureToolObjectsBackup); virtual void undo() override; virtual void redo() override; private: CaptureToolObjects m_captureToolObjects; CaptureToolObjects m_captureToolObjectsBackup; CaptureWidget* m_captureWidget; }; #endif // FLAMESHOT_MODIFICATIONCOMMAND_H
795
C++
.h
21
33.095238
76
0.782269
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,843
magnifierwidget.h
flameshot-org_flameshot/src/widgets/capture/magnifierwidget.h
#pragma once #include <QWidget> class QPropertyAnimation; class MagnifierWidget : public QWidget { Q_OBJECT public: explicit MagnifierWidget(const QPixmap& p, const QColor& c, bool isSquare, QWidget* parent = nullptr); protected: void paintEvent(QPaintEvent*) override; private: const int m_magPixels = 8; const int m_magOffset = 16; const int magZoom = 10; const int m_pixels = 2 * m_magPixels + 1; const int m_devicePixelRatio = 1; bool m_square; QColor m_color; QColor m_borderColor; QPixmap m_screenshot; QPixmap m_paddedScreenshot; void drawMagnifier(QPainter& painter); void drawMagnifierCircle(QPainter& painter); };
776
C++
.h
27
22.111111
56
0.650538
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,845
capturetoolobjects.h
flameshot-org_flameshot/src/widgets/capture/capturetoolobjects.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2021 Yurii Puchkov & Contributors #ifndef FLAMESHOT_CAPTURETOOLOBJECTS_H #define FLAMESHOT_CAPTURETOOLOBJECTS_H #include "src/tools/capturetool.h" #include <QList> #include <QPointer> class CaptureToolObjects : public QObject { public: explicit CaptureToolObjects(QObject* parent = nullptr); QList<QPointer<CaptureTool>> captureToolObjects(); void append(const QPointer<CaptureTool>& captureTool); void insert(int index, const QPointer<CaptureTool>& captureTool); void removeAt(int index); void clear(); int size(); int find(const QPoint& pos, QSize captureSize); QPointer<CaptureTool> at(int index); CaptureToolObjects& operator=(const CaptureToolObjects& other); private: int findWithRadius(QPainter& painter, QPixmap& pixmap, const QPoint& pos, int radius = 0); // class members QList<QPointer<CaptureTool>> m_captureToolObjects; QVector<QImage> m_imageCache; }; #endif // FLAMESHOT_CAPTURETOOLOBJECTS_H
1,110
C++
.h
30
31.633333
69
0.722533
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,847
selectionwidget.h
flameshot-org_flameshot/src/widgets/capture/selectionwidget.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QWidget> class QPropertyAnimation; class SelectionWidget : public QWidget { Q_OBJECT public: enum SideType { NO_SIDE = 0, TOP_SIDE = 0b0001, BOTTOM_SIDE = 0b0010, RIGHT_SIDE = 0b0100, LEFT_SIDE = 0b1000, TOPLEFT_SIDE = TOP_SIDE | LEFT_SIDE, BOTTOMLEFT_SIDE = BOTTOM_SIDE | LEFT_SIDE, TOPRIGHT_SIDE = TOP_SIDE | RIGHT_SIDE, BOTTOMRIGHT_SIDE = BOTTOM_SIDE | RIGHT_SIDE, CENTER = 0b10000, }; explicit SelectionWidget(QColor c, QWidget* parent = nullptr); SideType getMouseSide(const QPoint& mousePos) const; QVector<QRect> handlerAreas(); void setIgnoreMouse(bool ignore); void setIdleCentralCursor(const QCursor& cursor); void setGeometryAnimated(const QRect& r); void setGeometry(const QRect& r); QRect geometry() const; QRect fullGeometry() const; QRect rect() const; protected: bool eventFilter(QObject*, QEvent*) override; void parentMousePressEvent(QMouseEvent* e); void parentMouseReleaseEvent(QMouseEvent* e); void parentMouseMoveEvent(QMouseEvent* e); void paintEvent(QPaintEvent*) override; void resizeEvent(QResizeEvent*) override; void moveEvent(QMoveEvent*) override; void showEvent(QShowEvent*) override; void hideEvent(QHideEvent*) override; signals: void animationEnded(); void geometryChanged(); void geometrySettled(); void visibilityChanged(); public slots: void updateColor(const QColor& c); void moveLeft(); void moveRight(); void moveUp(); void moveDown(); void resizeLeft(); void resizeRight(); void resizeUp(); void resizeDown(); void symResizeLeft(); void symResizeRight(); void symResizeUp(); void symResizeDown(); private: void updateAreas(); void updateCursor(); void setGeometryByKeyboard(const QRect& r); QPropertyAnimation* m_animation; QColor m_color; QPoint m_areaOffset; QPoint m_handleOffset; QPoint m_dragStartPos; SideType m_activeSide; QCursor m_idleCentralCursor; bool m_ignoreMouse; bool m_mouseStartMove; // naming convention for handles // T top, B bottom, R Right, L left // 2 letters: a corner // 1 letter: the handle on the middle of the corresponding side QRect m_TLHandle, m_TRHandle, m_BLHandle, m_BRHandle; QRect m_LHandle, m_THandle, m_RHandle, m_BHandle; QRect m_TLArea, m_TRArea, m_BLArea, m_BRArea; QRect m_LArea, m_TArea, m_RArea, m_BArea; };
2,678
C++
.h
83
27.13253
72
0.702177
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,848
capturewidget.h
flameshot-org_flameshot/src/widgets/capture/capturewidget.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors // Based on Lightscreen areadialog.h, 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> #pragma once #include "buttonhandler.h" #include "capturetoolbutton.h" #include "capturetoolobjects.h" #include "src/config/generalconf.h" #include "src/tools/capturecontext.h" #include "src/tools/capturetool.h" #include "src/utils/confighandler.h" #include "src/widgets/capture/magnifierwidget.h" #include "src/widgets/capture/selectionwidget.h" #include <QPointer> #include <QTimer> #include <QUndoStack> #include <QWidget> class QLabel; class QPaintEvent; class QResizeEvent; class QMouseEvent; class QShortcut; class QNetworkAccessManager; class QNetworkReply; class ColorPicker; class NotifierBox; class HoverEventFilter; #if !defined(DISABLE_UPDATE_CHECKER) class UpdateNotificationWidget; #endif class UtilityPanel; class SidePanelWidget; class CaptureWidget : public QWidget { Q_OBJECT public: explicit CaptureWidget(const CaptureRequest& req, bool fullScreen = true, QWidget* parent = nullptr); ~CaptureWidget(); QPixmap pixmap(); void setCaptureToolObjects(const CaptureToolObjects& captureToolObjects); #if !defined(DISABLE_UPDATE_CHECKER) void showAppUpdateNotification(const QString& appLatestVersion, const QString& appLatestUrl); #endif public slots: bool commitCurrentTool(); void deleteToolWidgetOrClose(); signals: void colorChanged(const QColor& c); void toolSizeChanged(int size); private slots: void undo(); void redo(); void togglePanel(); void childEnter(); void childLeave(); void deleteCurrentTool(); void setState(CaptureToolButton* b); void handleToolSignal(CaptureTool::Request r); void handleButtonLeftClick(CaptureToolButton* b); void handleButtonRightClick(CaptureToolButton* b); void setDrawColor(const QColor& c); void onToolSizeChanged(int size); void onToolSizeSettled(int size); void updateActiveLayer(int layer); void onMoveCaptureToolUp(int captureToolIndex); void onMoveCaptureToolDown(int captureToolIndex); void selectAll(); void xywhTick(); void onDisplayGridChanged(bool display); void onGridSizeChanged(int size); public: void removeToolObject(int index = -1); void showxywh(); protected: void paintEvent(QPaintEvent* paintEvent) override; void mousePressEvent(QMouseEvent* mouseEvent) override; void mouseMoveEvent(QMouseEvent* mouseEvent) override; void mouseReleaseEvent(QMouseEvent* mouseEvent) override; void mouseDoubleClickEvent(QMouseEvent* event) override; void keyPressEvent(QKeyEvent* keyEvent) override; void keyReleaseEvent(QKeyEvent* keyEvent) override; void wheelEvent(QWheelEvent* wheelEvent) override; void resizeEvent(QResizeEvent* resizeEvent) override; void moveEvent(QMoveEvent* moveEvent) override; void changeEvent(QEvent* changeEvent) override; private: void pushObjectsStateToUndoStack(); void releaseActiveTool(); void uncheckActiveTool(); int selectToolItemAtPos(const QPoint& pos); void showColorPicker(const QPoint& pos); bool startDrawObjectTool(const QPoint& pos); QPointer<CaptureTool> activeToolObject(); void initContext(bool fullscreen, const CaptureRequest& req); void initPanel(); void initSelection(); void initShortcuts(); void initButtons(); void initHelpMessage(); void updateSizeIndicator(); void updateCursor(); void updateSelectionState(); void updateTool(CaptureTool* tool); void updateLayersPanel(); void pushToolToStack(); void makeChild(QWidget* w); void restoreCircleCountState(); QList<QShortcut*> newShortcut(const QKeySequence& key, QWidget* parent, const char* slot); void setToolSize(int size); QRect extendedSelection() const; QRect extendedRect(const QRect& r) const; QRect paddedUpdateRect(const QRect& r) const; void drawErrorMessage(const QString& msg, QPainter* painter); void drawInactiveRegion(QPainter* painter); void drawToolsData(bool drawSelection = true); void drawObjectSelection(); void processPixmapWithTool(QPixmap* pixmap, CaptureTool* tool); CaptureTool* activeButtonTool() const; CaptureTool::Type activeButtonToolType() const; QPoint snapToGrid(const QPoint& point) const; //////////////////////////////////////// // Class members // Context information CaptureContext m_context; // Main ui color QColor m_uiColor; // Secondary ui color QColor m_contrastUiColor; // Outside selection opacity int m_opacity; int m_toolSizeByKeyboard; // utility flags bool m_mouseIsClicked; bool m_newSelection; bool m_movingSelection; bool m_captureDone; bool m_previewEnabled; bool m_adjustmentButtonPressed; bool m_configError; bool m_configErrorResolved; #if !defined(DISABLE_UPDATE_CHECKER) UpdateNotificationWidget* m_updateNotificationWidget; #endif quint64 m_lastMouseWheel; QPointer<CaptureToolButton> m_sizeIndButton; // Last pressed button QPointer<CaptureToolButton> m_activeButton; QPointer<CaptureTool> m_activeTool; bool m_activeToolIsMoved; QPointer<QWidget> m_toolWidget; ButtonHandler* m_buttonHandler; UtilityPanel* m_panel; SidePanelWidget* m_sidePanel; ColorPicker* m_colorPicker; ConfigHandler m_config; NotifierBox* m_notifierBox; HoverEventFilter* m_eventFilter; SelectionWidget* m_selection; MagnifierWidget* m_magnifier; QString m_helpMessage; SelectionWidget::SideType m_mouseOverHandle; QMap<CaptureTool::Type, CaptureTool*> m_tools; CaptureToolObjects m_captureToolObjects; CaptureToolObjects m_captureToolObjectsBackup; QPoint m_mousePressedPos; QPoint m_activeToolOffsetToMouseOnStart; // XYWH display position and timer bool m_xywhDisplay; QTimer m_xywhTimer; QUndoStack m_undoStack; bool m_existingObjectIsChanged; // For start moving after more than X offset QPoint m_startMovePos; bool m_startMove; // Grid bool m_displayGrid{ false }; int m_gridSize{ 10 }; };
6,714
C++
.h
188
30.87234
78
0.744337
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,849
colorpicker.h
flameshot-org_flameshot/src/widgets/capture/colorpicker.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "src/widgets/colorpickerwidget.h" class ColorPicker : public ColorPickerWidget { Q_OBJECT public: explicit ColorPicker(QWidget* parent = nullptr); signals: void colorSelected(QColor c); protected: void showEvent(QShowEvent* event) override; void hideEvent(QHideEvent* event) override; void mouseMoveEvent(QMouseEvent* e) override; };
503
C++
.h
16
28.625
72
0.784232
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,851
capturebutton.h
flameshot-org_flameshot/src/widgets/capture/capturebutton.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QPushButton> class CaptureButton : public QPushButton { Q_OBJECT public: CaptureButton() = delete; CaptureButton(QWidget* parent = nullptr); CaptureButton(const QString& text, QWidget* parent = nullptr); CaptureButton(const QIcon& icon, const QString& text, QWidget* parent = nullptr); static QString globalStyleSheet(); QString styleSheet() const; void setColor(const QColor& c); private: static QColor m_mainColor; void init(); };
659
C++
.h
21
26.333333
72
0.705882
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,852
capturetoolbutton.h
flameshot-org_flameshot/src/widgets/capture/capturetoolbutton.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include "capturebutton.h" #include "src/tools/capturetool.h" #include <QMap> #include <QVector> class QWidget; class QPropertyAnimation; class CaptureToolButton : public CaptureButton { Q_OBJECT public: explicit CaptureToolButton(const CaptureTool::Type, QWidget* parent = nullptr); ~CaptureToolButton(); static const QList<CaptureTool::Type>& getIterableButtonTypes(); static int getPriorityByButton(CaptureTool::Type); QString name() const; QString description() const; QIcon icon() const; CaptureTool* tool() const; void setColor(const QColor& c); void animatedShow(); protected: void mousePressEvent(QMouseEvent* e) override; static QList<CaptureTool::Type> iterableButtonTypes; CaptureTool* m_tool; signals: void pressedButtonLeftClick(CaptureToolButton*); void pressedButtonRightClick(CaptureToolButton*); private: CaptureToolButton(QWidget* parent = nullptr); CaptureTool::Type m_buttonType; QPropertyAnimation* m_emergeAnimation; static QColor m_mainColor; void initButton(); void updateIcon(); };
1,272
C++
.h
39
28.179487
72
0.748768
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,854
strfparse.h
flameshot-org_flameshot/src/utils/strfparse.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2021 Jeremy Borgman #include <algorithm> #include <ctime> #include <map> #include <sstream> #include <vector> namespace strfparse { std::vector<std::string> split(std::string const& s, char delimiter); std::vector<char> create_specifier_list(); std::string replace_all(std::string input, std::string const& to_find, std::string const& to_replace); std::vector<char> match_specifiers(std::string const& specifier, std::vector<char> allowed_specifier); std::string format_time_string(std::string const& specifier); }
676
C++
.h
17
33.529412
72
0.675345
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,855
colorutils.h
flameshot-org_flameshot/src/utils/colorutils.h
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #pragma once #include <QColor> namespace ColorUtils { // namespace bool colorIsDark(const QColor& c); QColor contrastColor(const QColor& c); } // namespace
280
C++
.h
8
33.25
72
0.789474
flameshot-org/flameshot
24,603
1,577
714
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false