From 7737b77671b3ba7bdbf61bf067d0397338d407ba Mon Sep 17 00:00:00 2001 From: ArsenArsen Date: Sat, 6 May 2017 13:21:12 +0200 Subject: [PATCH] Great reformat of 2k17 --- cropeditor/cropeditor.cpp | 45 +- cropeditor/cropeditor.hpp | 25 +- cropeditor/cropscene.cpp | 238 +++++---- cropeditor/cropscene.hpp | 72 +-- cropeditor/cropview.cpp | 33 +- cropeditor/cropview.hpp | 11 +- cropeditor/drawing/bluritem.cpp | 47 +- cropeditor/drawing/bluritem.hpp | 30 +- cropeditor/drawing/dotitem.cpp | 24 +- cropeditor/drawing/dotitem.hpp | 18 +- cropeditor/drawing/drawitem.hpp | 22 +- cropeditor/drawing/lineitem.cpp | 28 +- cropeditor/drawing/lineitem.hpp | 22 +- cropeditor/drawing/pathitem.cpp | 37 +- cropeditor/drawing/pathitem.hpp | 24 +- cropeditor/drawing/textitem.cpp | 30 +- cropeditor/drawing/textitem.hpp | 16 +- cropeditor/settings/blurdialog.cpp | 60 +-- cropeditor/settings/blurdialog.hpp | 26 +- cropeditor/settings/brushpenselection.cpp | 73 ++- cropeditor/settings/brushpenselection.hpp | 36 +- formatter.cpp | 23 +- formatter.hpp | 3 +- hotkeying.cpp | 55 +- hotkeying.hpp | 3 +- io/ioutils.cpp | 105 ++-- io/ioutils.hpp | 17 +- main.cpp | 84 +-- mainwindow.cpp | 247 ++++----- mainwindow.hpp | 56 +- notifications.cpp | 8 +- notifications.hpp | 6 +- screenshotter.cpp | 26 +- screenshotter.hpp | 3 +- screenshotutil.cpp | 25 +- screenshotutil.hpp | 3 +- settings.cpp | 21 +- settings.hpp | 3 +- uploaders/customuploader.cpp | 607 ++++++++++------------ uploaders/customuploader.hpp | 49 +- uploaders/default/clipboarduploader.cpp | 7 +- uploaders/default/clipboarduploader.hpp | 17 +- uploaders/default/imguruploader.cpp | 34 +- uploaders/default/imguruploader.hpp | 17 +- uploaders/uploader.hpp | 11 +- uploaders/uploadersingleton.cpp | 128 ++--- uploaders/uploadersingleton.hpp | 42 +- 47 files changed, 1174 insertions(+), 1343 deletions(-) diff --git a/cropeditor/cropeditor.cpp b/cropeditor/cropeditor.cpp index 46e5b06..96a310f 100644 --- a/cropeditor/cropeditor.cpp +++ b/cropeditor/cropeditor.cpp @@ -8,34 +8,29 @@ #include #include -CropEditor::CropEditor(QPixmap *image, QObject *parent) : QObject(parent) -{ - scene = new CropScene(parent, image); - view = new CropView(scene); - QPixmap *scaled = new QPixmap(); - image->scaled(view->width(), view->height()).swap(*scaled); - pixmapItem = new QGraphicsPixmapItem(*image); - pixmapItem->setZValue(-1); - scene->addItem(pixmapItem); - scene->setSceneRect(image->rect()); - view->setGeometry(0, 0, image->width(), image->height()); - view->showFullScreen(); +CropEditor::CropEditor(QPixmap *image, QObject *parent) : QObject(parent) { + scene = new CropScene(parent, image); + view = new CropView(scene); + QPixmap *scaled = new QPixmap(); + image->scaled(view->width(), view->height()).swap(*scaled); + pixmapItem = new QGraphicsPixmapItem(*image); + pixmapItem->setZValue(-1); + scene->addItem(pixmapItem); + scene->setSceneRect(image->rect()); + view->setGeometry(0, 0, image->width(), image->height()); + view->showFullScreen(); - QTimer::singleShot(0, [&] { view->showFullScreen(); }); + QTimer::singleShot(0, [&] { view->showFullScreen(); }); - connect(scene, &CropScene::closedWithRect, this, &CropEditor::crop); + connect(scene, &CropScene::closedWithRect, this, &CropEditor::crop); } -CropEditor::~CropEditor() -{ - delete scene; -} +CropEditor::~CropEditor() { delete scene; } -void CropEditor::crop(QRect rect) -{ - QPixmap map = view->grab(rect); - QPixmap *cropp = new QPixmap; - map.swap(*cropp); - delete view; - emit cropped(cropp); +void CropEditor::crop(QRect rect) { + QPixmap map = view->grab(rect); + QPixmap *cropp = new QPixmap; + map.swap(*cropp); + delete view; + emit cropped(cropp); } diff --git a/cropeditor/cropeditor.hpp b/cropeditor/cropeditor.hpp index 104f22b..1f804bb 100644 --- a/cropeditor/cropeditor.hpp +++ b/cropeditor/cropeditor.hpp @@ -8,20 +8,19 @@ #include #include -class CropEditor : public QObject -{ - Q_OBJECT - public: - CropEditor(QPixmap *image, QObject *parent = 0); - ~CropEditor(); - signals: - QPixmap *cropped(QPixmap *pixmap); +class CropEditor : public QObject { + Q_OBJECT +public: + CropEditor(QPixmap *image, QObject *parent = 0); + ~CropEditor(); +signals: + QPixmap *cropped(QPixmap *pixmap); - private: - void crop(QRect rect); - CropScene *scene = nullptr; - CropView *view = nullptr; - QGraphicsPixmapItem *pixmapItem = nullptr; +private: + void crop(QRect rect); + CropScene *scene = nullptr; + CropView *view = nullptr; + QGraphicsPixmapItem *pixmapItem = nullptr; }; #endif // CROPEDITOR_HPP diff --git a/cropeditor/cropscene.cpp b/cropeditor/cropscene.cpp index 4795e4f..51e587d 100644 --- a/cropeditor/cropscene.cpp +++ b/cropeditor/cropscene.cpp @@ -17,152 +17,162 @@ #include CropScene::CropScene(QObject *parent, QPixmap *pixmap) -: QGraphicsScene(parent), prevButtons(Qt::NoButton), drawingSelectionMaker([] { return nullptr; }), - _font(settings::settings().value("font", QFont()).value()) { - pen().setColor(settings::settings().value("penColor", pen().color()).value()); - pen().setCosmetic(settings::settings().value("penCosmetic", pen().isCosmetic()).toBool()); - pen().setWidthF(settings::settings().value("penWidth", pen().widthF()).toFloat()); - brush().setColor(settings::settings().value("brushColor", brush().color()).value()); + : QGraphicsScene(parent), prevButtons(Qt::NoButton), + drawingSelectionMaker([] { return nullptr; }), + _font(settings::settings().value("font", QFont()).value()) { + pen().setColor( + settings::settings().value("penColor", pen().color()).value()); + pen().setCosmetic( + settings::settings().value("penCosmetic", pen().isCosmetic()).toBool()); + pen().setWidthF( + settings::settings().value("penWidth", pen().widthF()).toFloat()); + brush().setColor(settings::settings() + .value("brushColor", brush().color()) + .value()); - addDrawingAction(menu, "Dot", [] { return new DotItem; }); - addDrawingAction(menu, "Path", [] { return new PathItem; }); - addDrawingAction(menu, "Blur", [] { return new BlurItem; }); - addDrawingAction(menu, "Straight line", [] { return new LineItem; }); - addDrawingAction(menu, "Text", [] { return new TextItem; }); + addDrawingAction(menu, "Dot", [] { return new DotItem; }); + addDrawingAction(menu, "Path", [] { return new PathItem; }); + addDrawingAction(menu, "Blur", [] { return new BlurItem; }); + addDrawingAction(menu, "Straight line", [] { return new LineItem; }); + addDrawingAction(menu, "Text", [] { return new TextItem; }); - QAction *reset = menu.addAction("Reset"); - connect(reset, &QAction::triggered, [&] { setDrawingSelection("None", [] { return nullptr; }); }); + QAction *reset = menu.addAction("Reset"); + connect(reset, &QAction::triggered, + [&] { setDrawingSelection("None", [] { return nullptr; }); }); - menu.addSeparator(); - QAction *settings = new QAction; - settings->setText("Settings"); - menu.addSeparator(); - display = menu.addAction(drawingName); - display->setDisabled(true); - connect(settings, &QAction::triggered, [&] { BrushPenSelection(this).exec(); }); - menu.addAction(settings); + menu.addSeparator(); + QAction *settings = new QAction; + settings->setText("Settings"); + menu.addSeparator(); + display = menu.addAction(drawingName); + display->setDisabled(true); + connect(settings, &QAction::triggered, + [&] { BrushPenSelection(this).exec(); }); + menu.addAction(settings); - connect(menu.addAction("Set Font"), &QAction::triggered, this, &CropScene::fontAsk); + connect(menu.addAction("Set Font"), &QAction::triggered, this, + &CropScene::fontAsk); - _pixmap = pixmap; - QTimer::singleShot(0, [&] { - QPolygonF poly; - poly.append(sceneRect().topLeft()); - poly.append(sceneRect().topRight()); - poly.append(sceneRect().bottomRight()); - poly.append(sceneRect().bottomLeft()); - polyItem = new QGraphicsPolygonItem(poly); - polyItem->setBrush(QBrush(QColor(0, 0, 0, 191))); - polyItem->setPen(QPen(Qt::NoPen)); - addItem(polyItem); - }); + _pixmap = pixmap; + QTimer::singleShot(0, [&] { + QPolygonF poly; + poly.append(sceneRect().topLeft()); + poly.append(sceneRect().topRight()); + poly.append(sceneRect().bottomRight()); + poly.append(sceneRect().bottomLeft()); + polyItem = new QGraphicsPolygonItem(poly); + polyItem->setBrush(QBrush(QColor(0, 0, 0, 191))); + polyItem->setPen(QPen(Qt::NoPen)); + addItem(polyItem); + }); } -CropScene::~CropScene() { - delete drawingSelection; -} +CropScene::~CropScene() { delete drawingSelection; } -QPen &CropScene::pen() { - return _pen; -} +QPen &CropScene::pen() { return _pen; } -QBrush &CropScene::brush() { - return _brush; -} +QBrush &CropScene::brush() { return _brush; } -QFont &CropScene::font() { - return _font; -} +QFont &CropScene::font() { return _font; } -void CropScene::setDrawingSelection(QString name, std::function drawAction) { - drawingSelectionMaker = drawAction; - drawingSelection = drawAction(); - drawingName = name; - if (drawingSelection) drawingSelection->init(this); +void CropScene::setDrawingSelection(QString name, + std::function drawAction) { + drawingSelectionMaker = drawAction; + drawingSelection = drawAction(); + drawingName = name; + if (drawingSelection) + drawingSelection->init(this); } void CropScene::fontAsk() { - bool ok = false; - QFont font = QFontDialog::getFont(&ok, this->font(), nullptr, "Font to use"); - if (ok) _font = font; + bool ok = false; + QFont font = QFontDialog::getFont(&ok, this->font(), nullptr, "Font to use"); + if (ok) + _font = font; } void CropScene::mouseMoveEvent(QGraphicsSceneMouseEvent *e) { - auto buttons = e->buttons(); - if (buttons == Qt::LeftButton || prevButtons == Qt::NoButton) { - if (drawingSelection) { - drawingSelection->mouseDragEvent(e, this); + auto buttons = e->buttons(); + if (buttons == Qt::LeftButton || prevButtons == Qt::NoButton) { + if (drawingSelection) { + drawingSelection->mouseDragEvent(e, this); + } else { + QPointF p = e->scenePos(); + if (rect == nullptr) { + rect = new QGraphicsRectItem(p.x(), p.y(), 1, 1); + initPos = p; + QPen pen(Qt::NoBrush, 1); + pen.setColor(Qt::cyan); + rect->setPen(pen); + addItem(rect); + } else { + if (prevButtons == Qt::NoButton) { + initPos = p; + rect->setRect(p.x(), p.y(), 1, 1); } else { - QPointF p = e->scenePos(); - if (rect == nullptr) { - rect = new QGraphicsRectItem(p.x(), p.y(), 1, 1); - initPos = p; - QPen pen(Qt::NoBrush, 1); - pen.setColor(Qt::cyan); - rect->setPen(pen); - addItem(rect); - } else { - if (prevButtons == Qt::NoButton) { - initPos = p; - rect->setRect(p.x(), p.y(), 1, 1); - } else { - rect->setRect(QRect(qMin(initPos.x(), p.x()), qMin(initPos.y(), p.y()), qAbs(initPos.x() - p.x()), - qAbs(initPos.y() - p.y()))); - } - } - QPolygonF poly; - QPointF theMagicWikipediaPoint(rect->rect().right(), sceneRect().bottom()); - poly << sceneRect().topLeft(); - poly << sceneRect().topRight(); - poly << sceneRect().bottomRight(); - poly << theMagicWikipediaPoint; - poly << rect->rect().bottomRight(); - poly << rect->rect().topRight(); - poly << rect->rect().topLeft(); - poly << rect->rect().bottomLeft(); - poly << rect->rect().bottomRight(); - poly << theMagicWikipediaPoint; - poly << sceneRect().bottomLeft(); - poly << sceneRect().topLeft(); - - this->polyItem->setPolygon(poly); - e->accept(); + rect->setRect( + QRect(qMin(initPos.x(), p.x()), qMin(initPos.y(), p.y()), + qAbs(initPos.x() - p.x()), qAbs(initPos.y() - p.y()))); } + } + QPolygonF poly; + QPointF theMagicWikipediaPoint(rect->rect().right(), + sceneRect().bottom()); + poly << sceneRect().topLeft(); + poly << sceneRect().topRight(); + poly << sceneRect().bottomRight(); + poly << theMagicWikipediaPoint; + poly << rect->rect().bottomRight(); + poly << rect->rect().topRight(); + poly << rect->rect().topLeft(); + poly << rect->rect().bottomLeft(); + poly << rect->rect().bottomRight(); + poly << theMagicWikipediaPoint; + poly << sceneRect().bottomLeft(); + poly << sceneRect().topLeft(); + + this->polyItem->setPolygon(poly); + e->accept(); } - prevButtons = buttons; + } + prevButtons = buttons; } void CropScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *e) { - qDebug() << "release"; - if (drawingSelection) { - drawingSelection->mouseDragEndEvent(e, this); - delete drawingSelection; - drawingSelection = drawingSelectionMaker(); - if (drawingSelection) drawingSelection->init(this); - } - prevButtons = Qt::NoButton; + qDebug() << "release"; + if (drawingSelection) { + drawingSelection->mouseDragEndEvent(e, this); + delete drawingSelection; + drawingSelection = drawingSelectionMaker(); + if (drawingSelection) + drawingSelection->init(this); + } + prevButtons = Qt::NoButton; } -void CropScene::addDrawingAction(QMenu &menu, QString name, std::function item) { - QAction *action = new QAction; - action->setText(name); - connect(action, &QAction::triggered, [this, item, name](bool) { setDrawingSelection(name, item); }); - menu.addAction(action); +void CropScene::addDrawingAction(QMenu &menu, QString name, + std::function item) { + QAction *action = new QAction; + action->setText(name); + connect(action, &QAction::triggered, + [this, item, name](bool) { setDrawingSelection(name, item); }); + menu.addAction(action); } void CropScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) { - display->setText(drawingName); - menu.exec(e->screenPos()); - e->accept(); + display->setText(drawingName); + menu.exec(e->screenPos()); + e->accept(); } void CropScene::keyReleaseEvent(QKeyEvent *event) { - if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) done(); // Segfault + if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) + done(); // Segfault } void CropScene::done() { - if (rect) { - rect->setPen(QPen(Qt::NoPen)); - emit closedWithRect(rect->rect().toRect()); - } + if (rect) { + rect->setPen(QPen(Qt::NoPen)); + emit closedWithRect(rect->rect().toRect()); + } } diff --git a/cropeditor/cropscene.hpp b/cropeditor/cropscene.hpp index 0f8d531..66e9173 100644 --- a/cropeditor/cropscene.hpp +++ b/cropeditor/cropscene.hpp @@ -14,47 +14,47 @@ class CropScene; #include class CropScene : public QGraphicsScene { - Q_OBJECT - public: - CropScene(QObject *parent, QPixmap *pixmap); - ~CropScene(); - QPen &pen(); - QBrush &brush(); - QFont &font(); - void setDrawingSelection(QString name, std::function drawAction); - QPixmap *pixmap() { - return _pixmap; - } + Q_OBJECT +public: + CropScene(QObject *parent, QPixmap *pixmap); + ~CropScene(); + QPen &pen(); + QBrush &brush(); + QFont &font(); + void setDrawingSelection(QString name, + std::function drawAction); + QPixmap *pixmap() { return _pixmap; } - public slots: - void fontAsk(); +public slots: + void fontAsk(); - signals: - void closedWithRect(QRect rect); +signals: + void closedWithRect(QRect rect); - protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent *e) override; - void mouseReleaseEvent(QGraphicsSceneMouseEvent *e) override; - void contextMenuEvent(QGraphicsSceneContextMenuEvent *e) override; +protected: + void mouseMoveEvent(QGraphicsSceneMouseEvent *e) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *e) override; + void contextMenuEvent(QGraphicsSceneContextMenuEvent *e) override; - void keyReleaseEvent(QKeyEvent *e) override; + void keyReleaseEvent(QKeyEvent *e) override; - private: - void addDrawingAction(QMenu &menu, QString name, std::function item); - void done(); - std::function drawingSelectionMaker; - QFlags prevButtons; - QPixmap *_pixmap; - QGraphicsRectItem *rect = nullptr; - QPointF initPos; - QPen _pen; - QBrush _brush; - QFont _font; - QGraphicsPolygonItem *polyItem = nullptr; - DrawItem *drawingSelection = nullptr; - QMenu menu; - QString drawingName = "None"; - QAction *display; +private: + void addDrawingAction(QMenu &menu, QString name, + std::function item); + void done(); + std::function drawingSelectionMaker; + QFlags prevButtons; + QPixmap *_pixmap; + QGraphicsRectItem *rect = nullptr; + QPointF initPos; + QPen _pen; + QBrush _brush; + QFont _font; + QGraphicsPolygonItem *polyItem = nullptr; + DrawItem *drawingSelection = nullptr; + QMenu menu; + QString drawingName = "None"; + QAction *display; }; #endif // CROPSCENE_HPP diff --git a/cropeditor/cropview.cpp b/cropeditor/cropview.cpp index 30dc3ac..2432153 100644 --- a/cropeditor/cropview.cpp +++ b/cropeditor/cropview.cpp @@ -1,22 +1,21 @@ #include "cropview.hpp" -CropView::CropView(QGraphicsScene *scene) : QGraphicsView(scene) -{ - setFrameShape(QFrame::NoFrame); // Time taken to solve: A george99g and 38 minutes. - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint); - setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing); - setCursor(QCursor(Qt::CrossCursor)); +CropView::CropView(QGraphicsScene *scene) : QGraphicsView(scene) { + setFrameShape( + QFrame::NoFrame); // Time taken to solve: A george99g and 38 minutes. + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint); + setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | + QPainter::HighQualityAntialiasing); + setCursor(QCursor(Qt::CrossCursor)); } -void CropView::keyPressEvent(QKeyEvent *e) -{ - if (e->key() == Qt::Key_Escape) - { - close(); - e->accept(); - return; - } - QGraphicsView::keyPressEvent(e); +void CropView::keyPressEvent(QKeyEvent *e) { + if (e->key() == Qt::Key_Escape) { + close(); + e->accept(); + return; + } + QGraphicsView::keyPressEvent(e); } diff --git a/cropeditor/cropview.hpp b/cropeditor/cropview.hpp index 15eeaaa..d56fc88 100644 --- a/cropeditor/cropview.hpp +++ b/cropeditor/cropview.hpp @@ -4,13 +4,12 @@ #include #include -class CropView : public QGraphicsView -{ - public: - CropView(QGraphicsScene *scene); +class CropView : public QGraphicsView { +public: + CropView(QGraphicsScene *scene); - protected: - void keyPressEvent(QKeyEvent *e) override; +protected: + void keyPressEvent(QKeyEvent *e) override; }; #endif // CROPVIEW_HPP diff --git a/cropeditor/drawing/bluritem.cpp b/cropeditor/drawing/bluritem.cpp index 2e735ca..9424955 100644 --- a/cropeditor/drawing/bluritem.cpp +++ b/cropeditor/drawing/bluritem.cpp @@ -3,33 +3,30 @@ #include #include -void BlurItem::init(CropScene *) -{ - effect = new QGraphicsBlurEffect; - BlurDialog(effect).exec(); +void BlurItem::init(CropScene *) { + effect = new QGraphicsBlurEffect; + BlurDialog(effect).exec(); } -void BlurItem::mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) -{ - if (pos.isNull()) - { - pos = e->scenePos(); - rect = scene->addRect(QRect(e->scenePos().toPoint(), QSize(1, 1)), QPen(Qt::cyan), Qt::NoBrush); - pixmap = scene->addPixmap(scene->pixmap()->copy(rect->rect().toRect())); - pixmap->setPos(e->scenePos()); - pixmap->setZValue(rect->zValue() - 0.1); - pixmap->setGraphicsEffect(effect); - } - else - { - QPointF p = e->scenePos(); - rect->setRect(QRect(qMin(pos.x(), p.x()), qMin(pos.y(), p.y()), qAbs(pos.x() - p.x()), qAbs(pos.y() - p.y()))); - pixmap->setPixmap(scene->pixmap()->copy(rect->rect().toRect())); - pixmap->setPos(rect->rect().topLeft()); - } +void BlurItem::mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) { + if (pos.isNull()) { + pos = e->scenePos(); + rect = scene->addRect(QRect(e->scenePos().toPoint(), QSize(1, 1)), + QPen(Qt::cyan), Qt::NoBrush); + pixmap = scene->addPixmap(scene->pixmap()->copy(rect->rect().toRect())); + pixmap->setPos(e->scenePos()); + pixmap->setZValue(rect->zValue() - 0.1); + pixmap->setGraphicsEffect(effect); + } else { + QPointF p = e->scenePos(); + rect->setRect(QRect(qMin(pos.x(), p.x()), qMin(pos.y(), p.y()), + qAbs(pos.x() - p.x()), qAbs(pos.y() - p.y()))); + pixmap->setPixmap(scene->pixmap()->copy(rect->rect().toRect())); + pixmap->setPos(rect->rect().topLeft()); + } } -void BlurItem::mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) -{ - if (rect != nullptr) rect->setPen(Qt::NoPen); +void BlurItem::mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) { + if (rect != nullptr) + rect->setPen(Qt::NoPen); } diff --git a/cropeditor/drawing/bluritem.hpp b/cropeditor/drawing/bluritem.hpp index 7a7bdb1..db8188b 100644 --- a/cropeditor/drawing/bluritem.hpp +++ b/cropeditor/drawing/bluritem.hpp @@ -5,26 +5,20 @@ #include -class BlurItem : public DrawItem -{ - public: - QString name() - { - return "Blur"; - } - ~BlurItem() - { - } +class BlurItem : public DrawItem { +public: + QString name() { return "Blur"; } + ~BlurItem() {} - void init(CropScene *) override; - void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) override; - void mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) override; + void init(CropScene *) override; + void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) override; + void mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) override; - private: - QGraphicsBlurEffect *effect; - QPointF pos; - QGraphicsRectItem *rect; - QGraphicsPixmapItem *pixmap; +private: + QGraphicsBlurEffect *effect; + QPointF pos; + QGraphicsRectItem *rect; + QGraphicsPixmapItem *pixmap; }; #endif // BLURITEM_HPP diff --git a/cropeditor/drawing/dotitem.cpp b/cropeditor/drawing/dotitem.cpp index b1e77d7..c0b186a 100644 --- a/cropeditor/drawing/dotitem.cpp +++ b/cropeditor/drawing/dotitem.cpp @@ -1,18 +1,14 @@ #include "dotitem.hpp" -DotItem::DotItem() -{ +DotItem::DotItem() {} + +DotItem::~DotItem() {} + +void DotItem::mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) { + scene + ->addEllipse(e->pos().x() - 1.5, e->pos().y() - 1.5, 3, 3, scene->pen(), + scene->brush()) + ->setPos(e->scenePos()); } -DotItem::~DotItem() -{ -} - -void DotItem::mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) -{ - scene->addEllipse(e->pos().x() - 1.5, e->pos().y() - 1.5, 3, 3, scene->pen(), scene->brush())->setPos(e->scenePos()); -} - -void DotItem::mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) -{ -} +void DotItem::mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) {} diff --git a/cropeditor/drawing/dotitem.hpp b/cropeditor/drawing/dotitem.hpp index e95b4ad..ae104fb 100644 --- a/cropeditor/drawing/dotitem.hpp +++ b/cropeditor/drawing/dotitem.hpp @@ -4,17 +4,13 @@ #include "../cropscene.hpp" #include "drawitem.hpp" -class DotItem : public DrawItem -{ - public: - DotItem(); - ~DotItem(); - QString name() - { - return "Dots (drag to add)"; - } - void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene); - void mouseDragEndEvent(QGraphicsSceneMouseEvent *e, CropScene *scene); +class DotItem : public DrawItem { +public: + DotItem(); + ~DotItem(); + QString name() { return "Dots (drag to add)"; } + void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene); + void mouseDragEndEvent(QGraphicsSceneMouseEvent *e, CropScene *scene); }; #endif // DOTITEM_HPP diff --git a/cropeditor/drawing/drawitem.hpp b/cropeditor/drawing/drawitem.hpp index e5b1705..ceece7f 100644 --- a/cropeditor/drawing/drawitem.hpp +++ b/cropeditor/drawing/drawitem.hpp @@ -6,19 +6,15 @@ class DrawItem; #include #include -class DrawItem -{ - public: - virtual ~DrawItem() - { - } - virtual QString name() = 0; - virtual void init(CropScene *scene) - { - Q_UNUSED(scene) - } - virtual void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) = 0; - virtual void mouseDragEndEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) = 0; +class DrawItem { +public: + virtual ~DrawItem() {} + virtual QString name() = 0; + virtual void init(CropScene *scene) { Q_UNUSED(scene) } + virtual void mouseDragEvent(QGraphicsSceneMouseEvent *e, + CropScene *scene) = 0; + virtual void mouseDragEndEvent(QGraphicsSceneMouseEvent *e, + CropScene *scene) = 0; }; #endif // DRAWITEM_HPP diff --git a/cropeditor/drawing/lineitem.cpp b/cropeditor/drawing/lineitem.cpp index 8de1206..bd2486a 100644 --- a/cropeditor/drawing/lineitem.cpp +++ b/cropeditor/drawing/lineitem.cpp @@ -1,22 +1,14 @@ #include "lineitem.hpp" -LineItem::LineItem() -{ +LineItem::LineItem() {} + +void LineItem::mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) { + if (init.isNull()) { + init = e->scenePos(); + line = scene->addLine(QLineF(init, init), scene->pen()); + } else { + line->setLine(QLineF(init, e->scenePos())); + } } -void LineItem::mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) -{ - if (init.isNull()) - { - init = e->scenePos(); - line = scene->addLine(QLineF(init, init), scene->pen()); - } - else - { - line->setLine(QLineF(init, e->scenePos())); - } -} - -void LineItem::mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) -{ -} +void LineItem::mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) {} diff --git a/cropeditor/drawing/lineitem.hpp b/cropeditor/drawing/lineitem.hpp index aedaaf7..fe8bf48 100644 --- a/cropeditor/drawing/lineitem.hpp +++ b/cropeditor/drawing/lineitem.hpp @@ -3,20 +3,16 @@ #include "drawitem.hpp" -class LineItem : public DrawItem -{ - public: - LineItem(); - QString name() override - { - return "Straight line"; - } - void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) override; - void mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) override; +class LineItem : public DrawItem { +public: + LineItem(); + QString name() override { return "Straight line"; } + void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) override; + void mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) override; - private: - QPointF init; - QGraphicsLineItem *line; +private: + QPointF init; + QGraphicsLineItem *line; }; #endif // LINEITEM_HPP diff --git a/cropeditor/drawing/pathitem.cpp b/cropeditor/drawing/pathitem.cpp index a8f933f..bc8a946 100644 --- a/cropeditor/drawing/pathitem.cpp +++ b/cropeditor/drawing/pathitem.cpp @@ -1,28 +1,17 @@ #include "pathitem.hpp" -PathItem::PathItem() -{ +PathItem::PathItem() {} + +PathItem::~PathItem() { delete path; } + +void PathItem::mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) { + if (path == nullptr) { + path = new QPainterPath(e->scenePos()); + pathItem = scene->addPath(*path, scene->pen(), scene->brush()); + } else { + path->quadTo(path->currentPosition(), e->scenePos()); + pathItem->setPath(*path); + } } -PathItem::~PathItem() -{ - delete path; -} - -void PathItem::mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) -{ - if (path == nullptr) - { - path = new QPainterPath(e->scenePos()); - pathItem = scene->addPath(*path, scene->pen(), scene->brush()); - } - else - { - path->quadTo(path->currentPosition(), e->scenePos()); - pathItem->setPath(*path); - } -} - -void PathItem::mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) -{ -} +void PathItem::mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) {} diff --git a/cropeditor/drawing/pathitem.hpp b/cropeditor/drawing/pathitem.hpp index 19cafd7..981a70d 100644 --- a/cropeditor/drawing/pathitem.hpp +++ b/cropeditor/drawing/pathitem.hpp @@ -4,21 +4,17 @@ #include "../cropscene.hpp" #include "drawitem.hpp" -class PathItem : public DrawItem -{ - public: - PathItem(); - ~PathItem(); - QString name() - { - return "Path"; - } - void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene); - void mouseDragEndEvent(QGraphicsSceneMouseEvent *e, CropScene *scene); +class PathItem : public DrawItem { +public: + PathItem(); + ~PathItem(); + QString name() { return "Path"; } + void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene); + void mouseDragEndEvent(QGraphicsSceneMouseEvent *e, CropScene *scene); - private: - QPainterPath *path = nullptr; - QGraphicsPathItem *pathItem = nullptr; +private: + QPainterPath *path = nullptr; + QGraphicsPathItem *pathItem = nullptr; }; #endif // PATHITEM_HPP diff --git a/cropeditor/drawing/textitem.cpp b/cropeditor/drawing/textitem.cpp index 5e1ac9d..28508d0 100644 --- a/cropeditor/drawing/textitem.cpp +++ b/cropeditor/drawing/textitem.cpp @@ -3,25 +3,23 @@ #include void TextItem::init(CropScene *) { - text = QInputDialog::getText(nullptr, "Text to add", "Input"); + text = QInputDialog::getText(nullptr, "Text to add", "Input"); } void TextItem::mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) { - if (!textItem) { - textItem = scene->addSimpleText(text, scene->font()); - textItem->setPos(e->scenePos()); - textItem->setPen(scene->pen()); - textItem->setBrush(scene->brush()); - } else { - auto ee - = 180 + qRadiansToDegrees(qAtan2((textItem->pos().y() - e->scenePos().y()), (textItem->pos().x() - e->scenePos().x()))); - textItem->setRotation(ee); - } + if (!textItem) { + textItem = scene->addSimpleText(text, scene->font()); + textItem->setPos(e->scenePos()); + textItem->setPen(scene->pen()); + textItem->setBrush(scene->brush()); + } else { + auto ee = 180 + qRadiansToDegrees( + qAtan2((textItem->pos().y() - e->scenePos().y()), + (textItem->pos().x() - e->scenePos().x()))); + textItem->setRotation(ee); + } } -void TextItem::mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) { -} +void TextItem::mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) {} -QString TextItem::name() { - return "Text"; -} +QString TextItem::name() { return "Text"; } diff --git a/cropeditor/drawing/textitem.hpp b/cropeditor/drawing/textitem.hpp index a2882ad..43ff683 100644 --- a/cropeditor/drawing/textitem.hpp +++ b/cropeditor/drawing/textitem.hpp @@ -5,15 +5,15 @@ #include class TextItem : public DrawItem { - public: - QString name() override; - void init(CropScene *) override; - void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) override; - void mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) override; +public: + QString name() override; + void init(CropScene *) override; + void mouseDragEvent(QGraphicsSceneMouseEvent *e, CropScene *scene) override; + void mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) override; - private: - QGraphicsSimpleTextItem *textItem = nullptr; - QString text; +private: + QGraphicsSimpleTextItem *textItem = nullptr; + QString text; }; #endif // TEXTITEM_HPP diff --git a/cropeditor/settings/blurdialog.cpp b/cropeditor/settings/blurdialog.cpp index 401bc49..cc002bd 100644 --- a/cropeditor/settings/blurdialog.cpp +++ b/cropeditor/settings/blurdialog.cpp @@ -6,38 +6,38 @@ #include #include -BlurDialog::BlurDialog(QGraphicsBlurEffect *e, QWidget *parent) : QDialog(parent), ui(new Ui::BlurDialog) -{ - effect = e; - ui->setupUi(this); - ui->animated->setChecked(effect->blurHints().testFlag(QGraphicsBlurEffect::AnimationHint)); - ui->performance->setChecked(effect->blurHints().testFlag(QGraphicsBlurEffect::PerformanceHint)); - ui->quality->setChecked(effect->blurHints().testFlag(QGraphicsBlurEffect::QualityHint)); - ui->radSlider->setValue(effect->blurRadius() * 100); - ui->radSpinner->setValue(effect->blurRadius()); - connect(ui->buttonBox, &QDialogButtonBox::accepted, [&] { - QFlags hints; - hints.setFlag(QGraphicsBlurEffect::AnimationHint, ui->animated->isChecked()); - hints.setFlag(QGraphicsBlurEffect::PerformanceHint, ui->performance->isChecked()); - hints.setFlag(QGraphicsBlurEffect::QualityHint, ui->quality->isChecked()); - effect->setBlurHints(hints); - effect->setBlurRadius(ui->radSpinner->value()); - close(); - }); - connect(ui->buttonBox, &QDialogButtonBox::rejected, [&] { close(); }); +BlurDialog::BlurDialog(QGraphicsBlurEffect *e, QWidget *parent) + : QDialog(parent), ui(new Ui::BlurDialog) { + effect = e; + ui->setupUi(this); + ui->animated->setChecked( + effect->blurHints().testFlag(QGraphicsBlurEffect::AnimationHint)); + ui->performance->setChecked( + effect->blurHints().testFlag(QGraphicsBlurEffect::PerformanceHint)); + ui->quality->setChecked( + effect->blurHints().testFlag(QGraphicsBlurEffect::QualityHint)); + ui->radSlider->setValue(effect->blurRadius() * 100); + ui->radSpinner->setValue(effect->blurRadius()); + connect(ui->buttonBox, &QDialogButtonBox::accepted, [&] { + QFlags hints; + hints.setFlag(QGraphicsBlurEffect::AnimationHint, + ui->animated->isChecked()); + hints.setFlag(QGraphicsBlurEffect::PerformanceHint, + ui->performance->isChecked()); + hints.setFlag(QGraphicsBlurEffect::QualityHint, ui->quality->isChecked()); + effect->setBlurHints(hints); + effect->setBlurRadius(ui->radSpinner->value()); + close(); + }); + connect(ui->buttonBox, &QDialogButtonBox::rejected, [&] { close(); }); } -BlurDialog::~BlurDialog() -{ - delete ui; +BlurDialog::~BlurDialog() { delete ui; } + +void BlurDialog::on_radSpinner_valueChanged(double arg1) { + ui->radSlider->setValue(arg1 * 100); } -void BlurDialog::on_radSpinner_valueChanged(double arg1) -{ - ui->radSlider->setValue(arg1 * 100); -} - -void BlurDialog::on_radSlider_sliderMoved(int position) -{ - ui->radSpinner->setValue(position / 100.); +void BlurDialog::on_radSlider_sliderMoved(int position) { + ui->radSpinner->setValue(position / 100.); } diff --git a/cropeditor/settings/blurdialog.hpp b/cropeditor/settings/blurdialog.hpp index 639feb8..f931a02 100644 --- a/cropeditor/settings/blurdialog.hpp +++ b/cropeditor/settings/blurdialog.hpp @@ -4,26 +4,24 @@ #include #include -namespace Ui -{ +namespace Ui { class BlurDialog; } -class BlurDialog : public QDialog -{ - Q_OBJECT +class BlurDialog : public QDialog { + Q_OBJECT - public: - explicit BlurDialog(QGraphicsBlurEffect *effect, QWidget *parent = 0); - ~BlurDialog(); +public: + explicit BlurDialog(QGraphicsBlurEffect *effect, QWidget *parent = 0); + ~BlurDialog(); - private slots: - void on_radSpinner_valueChanged(double arg1); - void on_radSlider_sliderMoved(int position); +private slots: + void on_radSpinner_valueChanged(double arg1); + void on_radSlider_sliderMoved(int position); - private: - Ui::BlurDialog *ui; - QGraphicsBlurEffect *effect; +private: + Ui::BlurDialog *ui; + QGraphicsBlurEffect *effect; }; #endif // BLURDIALOG_HPP diff --git a/cropeditor/settings/brushpenselection.cpp b/cropeditor/settings/brushpenselection.cpp index c5ec3fd..09e6dd7 100644 --- a/cropeditor/settings/brushpenselection.cpp +++ b/cropeditor/settings/brushpenselection.cpp @@ -9,56 +9,45 @@ #include #include -BrushPenSelection::BrushPenSelection(CropScene *scene) : QDialog(), ui(new Ui::BrushPenSelection) -{ - ui->setupUi(this); - ui->cosmetic->setChecked(scene->pen().isCosmetic()); - ui->widthSlider->setValue(scene->pen().width()); - ui->widthSpinner->setValue(scene->pen().widthF()); - pen = scene->pen().color(); - brush = scene->brush().color(); - this->scene = scene; +BrushPenSelection::BrushPenSelection(CropScene *scene) + : QDialog(), ui(new Ui::BrushPenSelection) { + ui->setupUi(this); + ui->cosmetic->setChecked(scene->pen().isCosmetic()); + ui->widthSlider->setValue(scene->pen().width()); + ui->widthSpinner->setValue(scene->pen().widthF()); + pen = scene->pen().color(); + brush = scene->brush().color(); + this->scene = scene; } -BrushPenSelection::~BrushPenSelection() -{ - delete ui; +BrushPenSelection::~BrushPenSelection() { delete ui; } + +void BrushPenSelection::on_penColor_clicked(bool) { + pen = QColorDialog::getColor(pen, this, "Pen Color"); } -void BrushPenSelection::on_penColor_clicked(bool) -{ - pen = QColorDialog::getColor(pen, this, "Pen Color"); +void BrushPenSelection::on_brushColor_clicked(bool) { + brush = QColorDialog::getColor(brush, this, "Brush Color"); } -void BrushPenSelection::on_brushColor_clicked(bool) -{ - brush = QColorDialog::getColor(brush, this, "Brush Color"); +void BrushPenSelection::on_buttonBox_accepted() { + scene->pen().setColor(pen); + scene->pen().setCosmetic(ui->cosmetic->isChecked()); + scene->pen().setWidthF(ui->widthSpinner->value()); + scene->brush().setColor(brush); + settings::settings().setValue("penColor", scene->pen().color()); + settings::settings().setValue("penCosmetic", scene->pen().isCosmetic()); + settings::settings().setValue("penWidth", scene->pen().widthF()); + settings::settings().setValue("brushColor", scene->brush().color()); + close(); } -void BrushPenSelection::on_buttonBox_accepted() -{ - scene->pen().setColor(pen); - scene->pen().setCosmetic(ui->cosmetic->isChecked()); - scene->pen().setWidthF(ui->widthSpinner->value()); - scene->brush().setColor(brush); - settings::settings().setValue("penColor", scene->pen().color()); - settings::settings().setValue("penCosmetic", scene->pen().isCosmetic()); - settings::settings().setValue("penWidth", scene->pen().widthF()); - settings::settings().setValue("brushColor", scene->brush().color()); - close(); +void BrushPenSelection::on_buttonBox_rejected() { close(); } + +void BrushPenSelection::on_widthSlider_sliderMoved(int position) { + ui->widthSpinner->setValue(position / 100.); } -void BrushPenSelection::on_buttonBox_rejected() -{ - close(); -} - -void BrushPenSelection::on_widthSlider_sliderMoved(int position) -{ - ui->widthSpinner->setValue(position / 100.); -} - -void BrushPenSelection::on_widthSpinner_valueChanged(double arg) -{ - ui->widthSlider->setValue(arg * 100); +void BrushPenSelection::on_widthSpinner_valueChanged(double arg) { + ui->widthSlider->setValue(arg * 100); } diff --git a/cropeditor/settings/brushpenselection.hpp b/cropeditor/settings/brushpenselection.hpp index 8986162..9b8ac0b 100644 --- a/cropeditor/settings/brushpenselection.hpp +++ b/cropeditor/settings/brushpenselection.hpp @@ -4,33 +4,31 @@ #include #include -namespace Ui -{ +namespace Ui { class BrushPenSelection; } -class BrushPenSelection : public QDialog -{ - Q_OBJECT +class BrushPenSelection : public QDialog { + Q_OBJECT - public: - explicit BrushPenSelection(CropScene *scene); - ~BrushPenSelection(); +public: + explicit BrushPenSelection(CropScene *scene); + ~BrushPenSelection(); - private slots: - void on_penColor_clicked(bool); - void on_brushColor_clicked(bool); +private slots: + void on_penColor_clicked(bool); + void on_brushColor_clicked(bool); - void on_buttonBox_accepted(); - void on_buttonBox_rejected(); + void on_buttonBox_accepted(); + void on_buttonBox_rejected(); - void on_widthSlider_sliderMoved(int position); - void on_widthSpinner_valueChanged(double arg1); + void on_widthSlider_sliderMoved(int position); + void on_widthSpinner_valueChanged(double arg1); - private: - Ui::BrushPenSelection *ui; - CropScene *scene; - QColor brush, pen; +private: + Ui::BrushPenSelection *ui; + CropScene *scene; + QColor brush, pen; }; #endif // BRUSHPENSELECTION_HPP diff --git a/formatter.cpp b/formatter.cpp index 7f0084f..b79958e 100644 --- a/formatter.cpp +++ b/formatter.cpp @@ -3,16 +3,15 @@ #include #include -QString formatter::format(QString toFormat) -{ - QRegExp dateRegex("%\\((.+)\\)date"); - dateRegex.indexIn(toFormat); - QStringList capturedTexts(dateRegex.capturedTexts()); - QString formatted(toFormat); - QDateTime date = QDateTime::currentDateTime(); - for (int i = 0; i < capturedTexts.length(); i += 2) - { - formatted = formatted.replace(capturedTexts.at(i), date.toString(capturedTexts.at(i + 1))); - } - return formatted; +QString formatter::format(QString toFormat) { + QRegExp dateRegex("%\\((.+)\\)date"); + dateRegex.indexIn(toFormat); + QStringList capturedTexts(dateRegex.capturedTexts()); + QString formatted(toFormat); + QDateTime date = QDateTime::currentDateTime(); + for (int i = 0; i < capturedTexts.length(); i += 2) { + formatted = formatted.replace(capturedTexts.at(i), + date.toString(capturedTexts.at(i + 1))); + } + return formatted; } diff --git a/formatter.hpp b/formatter.hpp index c551721..c537ff9 100644 --- a/formatter.hpp +++ b/formatter.hpp @@ -4,8 +4,7 @@ #include #include -namespace formatter -{ +namespace formatter { QString format(QString toFormat); } diff --git a/hotkeying.cpp b/hotkeying.cpp index 48e1917..e287855 100644 --- a/hotkeying.cpp +++ b/hotkeying.cpp @@ -8,39 +8,38 @@ QMap hotkeys; // func gets bound only on first set, or load -void hotkeying::hotkey(QString seqName, QKeySequence seq, std::function func) -{ - if (hotkeys.contains(seqName)) - hotkeys.value(seqName)->setShortcut(seq, true); - else - { - QHotkey *hotkey = new QHotkey(seq, true); - QObject::connect(hotkey, &QHotkey::activated, func); - hotkeys.insert(seqName, hotkey); - } - settings::settings().setValue(seqName.prepend("hotkey_"), seq.toString()); +void hotkeying::hotkey(QString seqName, QKeySequence seq, + std::function func) { + if (hotkeys.contains(seqName)) + hotkeys.value(seqName)->setShortcut(seq, true); + else { + QHotkey *hotkey = new QHotkey(seq, true); + QObject::connect(hotkey, &QHotkey::activated, func); + hotkeys.insert(seqName, hotkey); + } + settings::settings().setValue(seqName.prepend("hotkey_"), seq.toString()); } // forces the hotkey from settings -void hotkeying::load(QString seqName, std::function func) -{ - QHotkey *h; - QString name = seqName; - name.prepend("hotkey_"); - if (settings::settings().contains(name)) - h = new QHotkey(QKeySequence(settings::settings().value(name).toString()), true); - else - h = new QHotkey; - QObject::connect(h, &QHotkey::activated, func); - hotkeys.insert(seqName, h); +void hotkeying::load(QString seqName, std::function func) { + QHotkey *h; + QString name = seqName; + name.prepend("hotkey_"); + if (settings::settings().contains(name)) + h = new QHotkey(QKeySequence(settings::settings().value(name).toString()), + true); + else + h = new QHotkey; + QObject::connect(h, &QHotkey::activated, func); + hotkeys.insert(seqName, h); } -bool hotkeying::valid(QString seq) -{ - return seq.isEmpty() || !QKeySequence(seq).toString().isEmpty(); +bool hotkeying::valid(QString seq) { + return seq.isEmpty() || !QKeySequence(seq).toString().isEmpty(); } -QString hotkeying::sequence(QString seqName) -{ - return hotkeys.contains(seqName) ? hotkeys.value(seqName)->shortcut().toString() : ""; +QString hotkeying::sequence(QString seqName) { + return hotkeys.contains(seqName) + ? hotkeys.value(seqName)->shortcut().toString() + : ""; } diff --git a/hotkeying.hpp b/hotkeying.hpp index c45ace4..14fab77 100644 --- a/hotkeying.hpp +++ b/hotkeying.hpp @@ -5,8 +5,7 @@ #include #include -namespace hotkeying -{ +namespace hotkeying { void hotkey(QString seqName, QKeySequence seq, std::function func); bool valid(QString seq); void load(QString seqName, std::function func); diff --git a/io/ioutils.cpp b/io/ioutils.cpp index 074f953..0f9c9d5 100644 --- a/io/ioutils.cpp +++ b/io/ioutils.cpp @@ -4,69 +4,62 @@ #include #include -namespace ioutils -{ +namespace ioutils { QNetworkAccessManager networkManager; } -void ioutils::getJson(QUrl target, QList> headers, std::function callback) -{ - QNetworkRequest req(target); - for (auto header : headers) - { - req.setRawHeader(header.first.toUtf8(), header.second.toUtf8()); - } - QNetworkReply *reply = networkManager.get(req); - QObject::connect(reply, &QNetworkReply::finished, [reply, callback] { - callback(QJsonDocument::fromJson(reply->readAll()), reply); - reply->deleteLater(); - }); +void ioutils::getJson( + QUrl target, QList> headers, + std::function callback) { + QNetworkRequest req(target); + for (auto header : headers) { + req.setRawHeader(header.first.toUtf8(), header.second.toUtf8()); + } + QNetworkReply *reply = networkManager.get(req); + QObject::connect(reply, &QNetworkReply::finished, [reply, callback] { + callback(QJsonDocument::fromJson(reply->readAll()), reply); + reply->deleteLater(); + }); } -void ioutils::postJson(QUrl target, - QList> headers, - QByteArray body, - std::function callback) -{ - QNetworkRequest req(target); - for (auto header : headers) - { - req.setRawHeader(header.first.toUtf8(), header.second.toUtf8()); - } - QNetworkReply *reply = networkManager.post(req, body); - QObject::connect(reply, &QNetworkReply::finished, [reply, callback] { - callback(QJsonDocument::fromJson(reply->readAll()), reply); - delete reply; - }); +void ioutils::postJson( + QUrl target, QList> headers, QByteArray body, + std::function callback) { + QNetworkRequest req(target); + for (auto header : headers) { + req.setRawHeader(header.first.toUtf8(), header.second.toUtf8()); + } + QNetworkReply *reply = networkManager.post(req, body); + QObject::connect(reply, &QNetworkReply::finished, [reply, callback] { + callback(QJsonDocument::fromJson(reply->readAll()), reply); + delete reply; + }); } -void ioutils::getData(QUrl target, QList> headers, std::function callback) -{ - QNetworkRequest req(target); - for (auto header : headers) - { - req.setRawHeader(header.first.toUtf8(), header.second.toUtf8()); - } - QNetworkReply *reply = networkManager.get(req); - QObject::connect(reply, &QNetworkReply::finished, [reply, callback] { - callback(reply->readAll(), reply); - delete reply; - }); +void ioutils::getData( + QUrl target, QList> headers, + std::function callback) { + QNetworkRequest req(target); + for (auto header : headers) { + req.setRawHeader(header.first.toUtf8(), header.second.toUtf8()); + } + QNetworkReply *reply = networkManager.get(req); + QObject::connect(reply, &QNetworkReply::finished, [reply, callback] { + callback(reply->readAll(), reply); + delete reply; + }); } -void ioutils::postData(QUrl target, - QList> headers, - QByteArray body, - std::function callback) -{ - QNetworkRequest req(target); - for (auto header : headers) - { - req.setRawHeader(header.first.toUtf8(), header.second.toUtf8()); - } - QNetworkReply *reply = networkManager.post(req, body); - QObject::connect(reply, &QNetworkReply::finished, [reply, callback] { - callback(reply->readAll(), reply); - delete reply; - }); +void ioutils::postData( + QUrl target, QList> headers, QByteArray body, + std::function callback) { + QNetworkRequest req(target); + for (auto header : headers) { + req.setRawHeader(header.first.toUtf8(), header.second.toUtf8()); + } + QNetworkReply *reply = networkManager.post(req, body); + QObject::connect(reply, &QNetworkReply::finished, [reply, callback] { + callback(reply->readAll(), reply); + delete reply; + }); } diff --git a/io/ioutils.hpp b/io/ioutils.hpp index 842c9a8..8c6c959 100644 --- a/io/ioutils.hpp +++ b/io/ioutils.hpp @@ -7,13 +7,18 @@ #include #include -namespace ioutils -{ +namespace ioutils { extern QNetworkAccessManager networkManager; -void getJson(QUrl target, QList> headers, std::function callback); -void postJson(QUrl target, QList> headers, QByteArray body, std::function callback); -void getData(QUrl target, QList> headers, std::function callback); -void postData(QUrl target, QList> headers, QByteArray body, std::function callback); +void getJson(QUrl target, QList> headers, + std::function callback); +void postJson(QUrl target, QList> headers, + QByteArray body, + std::function callback); +void getData(QUrl target, QList> headers, + std::function callback); +void postData(QUrl target, QList> headers, + QByteArray body, + std::function callback); } #endif // IOUTILS_HPP diff --git a/main.cpp b/main.cpp index 99bddb2..40d6b59 100644 --- a/main.cpp +++ b/main.cpp @@ -7,51 +7,51 @@ bool verbose = false; -void handler(QtMsgType type, const QMessageLogContext &, const QString &msg) -{ - QByteArray localMsg = msg.toLocal8Bit(); - switch (type) - { - case QtDebugMsg: - if (verbose) fprintf(stderr, "DEBUG: %s\n", localMsg.constData()); - break; - case QtInfoMsg: - fprintf(stderr, "INFO: %s\n", localMsg.constData()); - break; - case QtWarningMsg: - fprintf(stderr, "WARN: %s\n", localMsg.constData()); - break; - case QtCriticalMsg: - fprintf(stderr, "CRIT: %s\n", localMsg.constData()); - break; - case QtFatalMsg: - fprintf(stderr, "FATAL: %s\n", localMsg.constData()); - break; - } +void handler(QtMsgType type, const QMessageLogContext &, const QString &msg) { + QByteArray localMsg = msg.toLocal8Bit(); + switch (type) { + case QtDebugMsg: + if (verbose) + fprintf(stderr, "DEBUG: %s\n", localMsg.constData()); + break; + case QtInfoMsg: + fprintf(stderr, "INFO: %s\n", localMsg.constData()); + break; + case QtWarningMsg: + fprintf(stderr, "WARN: %s\n", localMsg.constData()); + break; + case QtCriticalMsg: + fprintf(stderr, "CRIT: %s\n", localMsg.constData()); + break; + case QtFatalMsg: + fprintf(stderr, "FATAL: %s\n", localMsg.constData()); + break; + } } -int main(int argc, char *argv[]) -{ - qInstallMessageHandler(handler); - QApplication a(argc, argv); - a.setApplicationName("KShare"); - a.setOrganizationName("ArsenArsen"); - a.setApplicationVersion("1.1"); +int main(int argc, char *argv[]) { + qInstallMessageHandler(handler); + QApplication a(argc, argv); + a.setApplicationName("KShare"); + a.setOrganizationName("ArsenArsen"); + a.setApplicationVersion("1.1"); - QCommandLineParser parser; - parser.addHelpOption(); + QCommandLineParser parser; + parser.addHelpOption(); - QCommandLineOption h({ "b", "background" }, "Does not show the main window, starts in tray."); - QCommandLineOption v({ "v", "verbose" }, "Enables QtDebugMsg outputs"); - parser.addOption(h); - parser.addOption(v); - parser.process(a); - verbose = parser.isSet(v); + QCommandLineOption h({"b", "background"}, + "Does not show the main window, starts in tray."); + QCommandLineOption v({"v", "verbose"}, "Enables QtDebugMsg outputs"); + parser.addOption(h); + parser.addOption(v); + parser.process(a); + verbose = parser.isSet(v); - MainWindow w; - w.show(); - QTimer::singleShot(0, [&] { - if (parser.isSet(h)) w.hide(); - }); - return a.exec(); + MainWindow w; + w.show(); + QTimer::singleShot(0, [&] { + if (parser.isSet(h)) + w.hide(); + }); + return a.exec(); } diff --git a/mainwindow.cpp b/mainwindow.cpp index df03282..648f04f 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -19,162 +19,143 @@ MainWindow *MainWindow::instance; -void addHotkeyItem(QString text, QString name, std::function *func) -{ - QListWidgetItem *item = new QListWidgetItem(text, MainWindow::inst()->ui->hotkeys); - item->setData(Qt::UserRole + 1, name); - MainWindow::inst()->fncs.insert(name, func); - hotkeying::load(name, *func); +void addHotkeyItem(QString text, QString name, std::function *func) { + QListWidgetItem *item = + new QListWidgetItem(text, MainWindow::inst()->ui->hotkeys); + item->setData(Qt::UserRole + 1, name); + MainWindow::inst()->fncs.insert(name, func); + hotkeying::load(name, *func); } +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), ui(new Ui::MainWindow) { + instance = this; + ui->setupUi(this); + setWindowIcon(QIcon(":/icons/icon.png")); + tray = new QSystemTrayIcon(windowIcon(), this); + tray->setToolTip("KShare"); + tray->setVisible(true); + QMenu *menu = new QMenu(this); + QAction *quit = new QAction("Quit", this); + QAction *shtoggle = new QAction("Show/Hide", this); + QAction *fullscreen = new QAction("Take fullscreen shot", this); + QAction *area = new QAction("Take area shot", this); + menu->addActions({quit, shtoggle}); + menu->addSeparator(); + menu->addActions({fullscreen, area}); + connect(quit, &QAction::triggered, this, &MainWindow::quit); + connect(shtoggle, &QAction::triggered, this, &MainWindow::toggleVisible); + connect(tray, &QSystemTrayIcon::messageClicked, this, + &MainWindow::toggleVisible); + connect(tray, &QSystemTrayIcon::activated, this, + [this](QSystemTrayIcon::ActivationReason reason) { + if (reason == QSystemTrayIcon::DoubleClick) + toggleVisible(); + }); + connect(fullscreen, &QAction::triggered, this, + [] { screenshotter::fullscreenDelayed(); }); + connect(area, &QAction::triggered, this, + [] { screenshotter::areaDelayed(); }); + tray->setContextMenu(menu); -MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) -{ - instance = this; - ui->setupUi(this); - setWindowIcon(QIcon(":/icons/icon.png")); - tray = new QSystemTrayIcon(windowIcon(), this); - tray->setToolTip("KShare"); - tray->setVisible(true); - QMenu *menu = new QMenu(this); - QAction *quit = new QAction("Quit", this); - QAction *shtoggle = new QAction("Show/Hide", this); - QAction *fullscreen = new QAction("Take fullscreen shot", this); - QAction *area = new QAction("Take area shot", this); - menu->addActions({ quit, shtoggle }); - menu->addSeparator(); - menu->addActions({ fullscreen, area }); - connect(quit, &QAction::triggered, this, &MainWindow::quit); - connect(shtoggle, &QAction::triggered, this, &MainWindow::toggleVisible); - connect(tray, &QSystemTrayIcon::messageClicked, this, &MainWindow::toggleVisible); - connect(tray, &QSystemTrayIcon::activated, this, [this](QSystemTrayIcon::ActivationReason reason) { - if (reason == QSystemTrayIcon::DoubleClick) toggleVisible(); - }); - connect(fullscreen, &QAction::triggered, this, [] { screenshotter::fullscreenDelayed(); }); - connect(area, &QAction::triggered, this, [] { screenshotter::areaDelayed(); }); - tray->setContextMenu(menu); + ui->uploaderList->setSelectionBehavior(QAbstractItemView::SelectRows); + ui->uploaderList->setSelectionMode(QAbstractItemView::SingleSelection); - ui->uploaderList->setSelectionBehavior(QAbstractItemView::SelectRows); - ui->uploaderList->setSelectionMode(QAbstractItemView::SingleSelection); + // Add items to uploader selection + for (Uploader *u : UploaderSingleton::inst().uploaderList()) + newUploader(u); + connect(&UploaderSingleton::inst(), &UploaderSingleton::newUploader, this, + &MainWindow::newUploader); - // Add items to uploader selection - for (Uploader *u : UploaderSingleton::inst().uploaderList()) newUploader(u); - connect(&UploaderSingleton::inst(), &UploaderSingleton::newUploader, this, &MainWindow::newUploader); + // Set filename scheme + if ((settings::settings().contains("fileFormat"))) + setScheme(settings::settings().value("fileFormat").toString()); + else + setScheme("Screenshot %(yyyy-MM-dd HH:mm:ss)date"); - // Set filename scheme - if ((settings::settings().contains("fileFormat"))) - setScheme(settings::settings().value("fileFormat").toString()); - else - setScheme("Screenshot %(yyyy-MM-dd HH:mm:ss)date"); + auto errors = UploaderSingleton::inst().errors(); + if (errors.length() == 1) + statusBar()->showMessage(errors.at(0).what()); + else + statusBar()->showMessage( + QString("Errors visible in console (if present). Count: " + + QString::number(errors.size()))); - auto errors = UploaderSingleton::inst().errors(); - if (errors.length() == 1) - statusBar()->showMessage(errors.at(0).what()); - else - statusBar()->showMessage(QString("Errors visible in console (if present). Count: " + QString::number(errors.size()))); + // Set delay + if ((settings::settings().contains("delay"))) + ui->delay->setValue(settings::settings().value("delay").toDouble()); + else + ui->delay->setValue(0.25); - // Set delay - if ((settings::settings().contains("delay"))) - ui->delay->setValue(settings::settings().value("delay").toDouble()); - else - ui->delay->setValue(0.25); + ui->hotkeys->setSelectionMode(QListWidget::SingleSelection); - ui->hotkeys->setSelectionMode(QListWidget::SingleSelection); - - addHotkeyItem("Fullscreen image", "fullscreen", new std::function([] { screenshotter::fullscreen(); })); - addHotkeyItem("Area image", "area", new std::function([] { screenshotter::area(); })); + addHotkeyItem("Fullscreen image", "fullscreen", + new std::function([] { screenshotter::fullscreen(); })); + addHotkeyItem("Area image", "area", + new std::function([] { screenshotter::area(); })); } -MainWindow::~MainWindow() -{ - delete ui; +MainWindow::~MainWindow() { delete ui; } + +void MainWindow::setScheme(QString scheme) { ui->nameScheme->setText(scheme); } + +QDoubleSpinBox *MainWindow::delay() { return ui->delay; } + +MainWindow *MainWindow::inst() { return instance; } + +void MainWindow::closeEvent(QCloseEvent *event) { + event->ignore(); + QTimer::singleShot(0, this, &MainWindow::hide); } -void MainWindow::setScheme(QString scheme) -{ - ui->nameScheme->setText(scheme); +void MainWindow::quit() { QCoreApplication::quit(); } + +void MainWindow::toggleVisible() { + this->setVisible(!this->isVisible()); + if (this->isVisible()) { + this->raise(); + } } -QDoubleSpinBox *MainWindow::delay() -{ - return ui->delay; +void MainWindow::newUploader(Uploader *u) { + QListWidgetItem *item = new QListWidgetItem(u->name()); + item->setToolTip(u->description()); + ui->uploaderList->addItem(item); + if (u->name() == UploaderSingleton::inst().selectedUploader()) + item->setSelected(true); } -MainWindow *MainWindow::inst() -{ - return instance; +void MainWindow::on_actionQuit_triggered() { quit(); } + +void MainWindow::on_actionFullscreen_triggered() { + screenshotter::fullscreenDelayed(); } -void MainWindow::closeEvent(QCloseEvent *event) -{ - event->ignore(); - QTimer::singleShot(0, this, &MainWindow::hide); +void MainWindow::on_actionArea_triggered() { screenshotter::areaDelayed(); } + +void MainWindow::on_uploaderList_clicked(const QModelIndex &) { + QList index = ui->uploaderList->selectedItems(); + if (index.size() == 1) { + UploaderSingleton::inst().set(index.at(0)->text()); + } } -void MainWindow::quit() -{ - QCoreApplication::quit(); +void MainWindow::on_nameScheme_textEdited(const QString &arg1) { + settings::settings().setValue("fileFormat", arg1); } -void MainWindow::toggleVisible() -{ - this->setVisible(!this->isVisible()); - if (this->isVisible()) - { - this->raise(); - } +void MainWindow::on_delay_valueChanged(double arg1) { + settings::settings().setValue("delay", arg1); } -void MainWindow::newUploader(Uploader *u) -{ - QListWidgetItem *item = new QListWidgetItem(u->name()); - item->setToolTip(u->description()); - ui->uploaderList->addItem(item); - if (u->name() == UploaderSingleton::inst().selectedUploader()) item->setSelected(true); -} - -void MainWindow::on_actionQuit_triggered() -{ - quit(); -} - -void MainWindow::on_actionFullscreen_triggered() -{ - screenshotter::fullscreenDelayed(); -} - -void MainWindow::on_actionArea_triggered() -{ - screenshotter::areaDelayed(); -} - -void MainWindow::on_uploaderList_clicked(const QModelIndex &) -{ - QList index = ui->uploaderList->selectedItems(); - if (index.size() == 1) - { - UploaderSingleton::inst().set(index.at(0)->text()); - } -} - -void MainWindow::on_nameScheme_textEdited(const QString &arg1) -{ - settings::settings().setValue("fileFormat", arg1); -} - -void MainWindow::on_delay_valueChanged(double arg1) -{ - settings::settings().setValue("delay", arg1); -} - -void MainWindow::on_hotkeys_doubleClicked(const QModelIndex &) -{ - if (ui->hotkeys->selectedItems().length() == 1) - { - QListWidgetItem *i = ui->hotkeys->selectedItems().at(0); - QString str = i->data(Qt::UserRole + 1).toString(); - QString seq = QInputDialog::getText(ui->centralWidget, "Hotkey Input", "Insert hotkey:", QLineEdit::Normal, - hotkeying::sequence(str)); - if (hotkeying::valid(seq)) hotkeying::hotkey(str, QKeySequence(seq), *fncs.value(str)); - } +void MainWindow::on_hotkeys_doubleClicked(const QModelIndex &) { + if (ui->hotkeys->selectedItems().length() == 1) { + QListWidgetItem *i = ui->hotkeys->selectedItems().at(0); + QString str = i->data(Qt::UserRole + 1).toString(); + QString seq = QInputDialog::getText(ui->centralWidget, "Hotkey Input", + "Insert hotkey:", QLineEdit::Normal, + hotkeying::sequence(str)); + if (hotkeying::valid(seq)) + hotkeying::hotkey(str, QKeySequence(seq), *fncs.value(str)); + } } diff --git a/mainwindow.hpp b/mainwindow.hpp index 679913a..eab9faf 100644 --- a/mainwindow.hpp +++ b/mainwindow.hpp @@ -9,46 +9,44 @@ #include -namespace Ui -{ +namespace Ui { class MainWindow; } -class MainWindow : public QMainWindow -{ - Q_OBJECT - private slots: - void quit(); - void toggleVisible(); - void newUploader(Uploader *u); +class MainWindow : public QMainWindow { + Q_OBJECT +private slots: + void quit(); + void toggleVisible(); + void newUploader(Uploader *u); - void on_actionQuit_triggered(); - void on_actionFullscreen_triggered(); - void on_actionArea_triggered(); - void on_uploaderList_clicked(const QModelIndex &); - void on_nameScheme_textEdited(const QString &arg1); + void on_actionQuit_triggered(); + void on_actionFullscreen_triggered(); + void on_actionArea_triggered(); + void on_uploaderList_clicked(const QModelIndex &); + void on_nameScheme_textEdited(const QString &arg1); - void on_delay_valueChanged(double arg1); + void on_delay_valueChanged(double arg1); - void on_hotkeys_doubleClicked(const QModelIndex &index); + void on_hotkeys_doubleClicked(const QModelIndex &index); - public: - explicit MainWindow(QWidget *parent = 0); - ~MainWindow(); - Ui::MainWindow *ui; +public: + explicit MainWindow(QWidget *parent = 0); + ~MainWindow(); + Ui::MainWindow *ui; - QSystemTrayIcon *tray; - void setScheme(QString scheme); - QDoubleSpinBox *delay(); + QSystemTrayIcon *tray; + void setScheme(QString scheme); + QDoubleSpinBox *delay(); - static MainWindow *inst(); - QMap *> fncs; + static MainWindow *inst(); + QMap *> fncs; - private: - static MainWindow *instance; +private: + static MainWindow *instance; - protected: - void closeEvent(QCloseEvent *event); +protected: + void closeEvent(QCloseEvent *event); }; #endif // MAINWINDOW_HPP diff --git a/notifications.cpp b/notifications.cpp index 1bf1785..5f8e9cb 100644 --- a/notifications.cpp +++ b/notifications.cpp @@ -3,8 +3,8 @@ #include "mainwindow.hpp" #include -void notifications::notify(QString title, QString body, QSystemTrayIcon::MessageIcon icon) -{ - MainWindow::inst()->tray->showMessage(title, body, icon, 5000); - MainWindow::inst()->statusBar()->showMessage(title + ": " + body); +void notifications::notify(QString title, QString body, + QSystemTrayIcon::MessageIcon icon) { + MainWindow::inst()->tray->showMessage(title, body, icon, 5000); + MainWindow::inst()->statusBar()->showMessage(title + ": " + body); } diff --git a/notifications.hpp b/notifications.hpp index 4684b75..d8b3dd5 100644 --- a/notifications.hpp +++ b/notifications.hpp @@ -4,9 +4,9 @@ #include #include -namespace notifications -{ -void notify(QString title, QString body, QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::Information); +namespace notifications { +void notify(QString title, QString body, + QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::Information); } #endif // NOTIFICATIONS_HPP diff --git a/screenshotter.cpp b/screenshotter.cpp index b21bb69..a694e35 100644 --- a/screenshotter.cpp +++ b/screenshotter.cpp @@ -6,23 +6,23 @@ #include #include -void screenshotter::area() -{ - CropEditor *editor = new CropEditor(screenshotutil::fullscreen()); - QObject::connect(editor, &CropEditor::cropped, [&](QPixmap *pixmap) { UploaderSingleton::inst().upload(pixmap); }); +void screenshotter::area() { + CropEditor *editor = new CropEditor(screenshotutil::fullscreen()); + QObject::connect(editor, &CropEditor::cropped, [&](QPixmap *pixmap) { + UploaderSingleton::inst().upload(pixmap); + }); } -void screenshotter::fullscreen() -{ - UploaderSingleton::inst().upload(screenshotutil::fullscreen()); +void screenshotter::fullscreen() { + UploaderSingleton::inst().upload(screenshotutil::fullscreen()); } -void screenshotter::areaDelayed() -{ - QTimer::singleShot(MainWindow::inst()->delay()->value() * 1000, &screenshotter::area); +void screenshotter::areaDelayed() { + QTimer::singleShot(MainWindow::inst()->delay()->value() * 1000, + &screenshotter::area); } -void screenshotter::fullscreenDelayed() -{ - QTimer::singleShot(MainWindow::inst()->delay()->value() * 1000, &screenshotter::fullscreen); +void screenshotter::fullscreenDelayed() { + QTimer::singleShot(MainWindow::inst()->delay()->value() * 1000, + &screenshotter::fullscreen); } diff --git a/screenshotter.hpp b/screenshotter.hpp index c78d2eb..7fbe711 100644 --- a/screenshotter.hpp +++ b/screenshotter.hpp @@ -1,8 +1,7 @@ #ifndef SCREENSHOTTER_HPP #define SCREENSHOTTER_HPP -namespace screenshotter -{ +namespace screenshotter { void fullscreen(); void area(); void fullscreenDelayed(); diff --git a/screenshotutil.cpp b/screenshotutil.cpp index cd477b0..cb3c29d 100644 --- a/screenshotutil.cpp +++ b/screenshotutil.cpp @@ -5,21 +5,16 @@ #include #include -QPixmap *screenshotutil::fullscreen() -{ - return window(0); +QPixmap *screenshotutil::fullscreen() { return window(0); } + +QPixmap *screenshotutil::window(long wid) { + QScreen *w = QApplication::primaryScreen(); + QPixmap screen = w->grabWindow(wid); + QPixmap *pm = new QPixmap(screen.size()); + screen.swap(*pm); + return pm; } -QPixmap *screenshotutil::window(long wid) -{ - QScreen *w = QApplication::primaryScreen(); - QPixmap screen = w->grabWindow(wid); - QPixmap *pm = new QPixmap(screen.size()); - screen.swap(*pm); - return pm; -} - -void screenshotutil::toClipboard(QString value) -{ - QApplication::clipboard()->setText(value); +void screenshotutil::toClipboard(QString value) { + QApplication::clipboard()->setText(value); } diff --git a/screenshotutil.hpp b/screenshotutil.hpp index 3a1d5b2..e8778ca 100644 --- a/screenshotutil.hpp +++ b/screenshotutil.hpp @@ -3,8 +3,7 @@ #include -namespace screenshotutil -{ +namespace screenshotutil { QPixmap *fullscreen(); QPixmap *window(long wid); void toClipboard(QString value); diff --git a/settings.cpp b/settings.cpp index 2ceddcd..1f4dc3a 100644 --- a/settings.cpp +++ b/settings.cpp @@ -2,14 +2,15 @@ #include -QSettings &settings::settings() -{ - static QDir configDir(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)); - if (configDir.path() == QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)) - { - configDir.mkdir("KShare"); - configDir.cd("KShare"); - } - static QSettings settings(configDir.absoluteFilePath("settings.ini"), QSettings::IniFormat); - return settings; +QSettings &settings::settings() { + static QDir configDir( + QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)); + if (configDir.path() == + QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)) { + configDir.mkdir("KShare"); + configDir.cd("KShare"); + } + static QSettings settings(configDir.absoluteFilePath("settings.ini"), + QSettings::IniFormat); + return settings; } diff --git a/settings.hpp b/settings.hpp index 6e43223..e2a7870 100644 --- a/settings.hpp +++ b/settings.hpp @@ -4,8 +4,7 @@ #include #include -namespace settings -{ +namespace settings { QSettings &settings(); } diff --git a/uploaders/customuploader.cpp b/uploaders/customuploader.cpp index 5312b58..93da1cc 100644 --- a/uploaders/customuploader.cpp +++ b/uploaders/customuploader.cpp @@ -12,350 +12,317 @@ using std::runtime_error; -void error(QString absFilePath, QString err) -{ - throw runtime_error((QString("Invalid file: ").append(absFilePath) + ": " + err).toStdString()); +void error(QString absFilePath, QString err) { + throw runtime_error( + (QString("Invalid file: ").append(absFilePath) + ": " + err) + .toStdString()); } -CustomUploader::CustomUploader(QString absFilePath) -{ - types.insert("PNG", "image/png"); // This is a list of supported formats, too - types.insert("GIF", "image/gif"); - types.insert("JPG", "image/jpeg"); - types.insert("JPEG", "image/jpeg"); - types.insert("WEBM", "video/webm"); - types.insert("MP4", "video/mp4"); - // Let's go - QFile file(absFilePath); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) error(absFilePath, file.errorString()); - QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); - if (!doc.isObject()) - { - error(absFilePath, "Root not an object"); - } - QJsonObject obj = doc.object(); - if (!obj["name"].isString()) - error(absFilePath, "name is not a string"); +CustomUploader::CustomUploader(QString absFilePath) { + types.insert("PNG", "image/png"); // This is a list of supported formats, too + types.insert("GIF", "image/gif"); + types.insert("JPG", "image/jpeg"); + types.insert("JPEG", "image/jpeg"); + types.insert("WEBM", "video/webm"); + types.insert("MP4", "video/mp4"); + // Let's go + QFile file(absFilePath); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + error(absFilePath, file.errorString()); + QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); + if (!doc.isObject()) { + error(absFilePath, "Root not an object"); + } + QJsonObject obj = doc.object(); + if (!obj["name"].isString()) + error(absFilePath, "name is not a string"); + else + uName = obj["name"].toString(); + if (!obj.contains("desc")) { + if (!obj["desc"].isString()) + /*t*/ error(absFilePath, "desc not a string"); else - uName = obj["name"].toString(); - if (!obj.contains("desc")) - { - if (!obj["desc"].isString()) - /*t*/ error(absFilePath, "desc not a string"); - else - desc = obj["desc"].toString(); - } + desc = obj["desc"].toString(); + } else + desc = absFilePath; + QJsonValue m = obj["method"]; + if (!m.isUndefined() && !m.isNull()) { + if (!m.isString()) + error(absFilePath, "method not a string"); + QString toCheck = m.toString().toLower(); + if (toCheck == "post") + method = HttpMethod::POST; else - desc = absFilePath; - QJsonValue m = obj["method"]; - if (!m.isUndefined() && !m.isNull()) - { - if (!m.isString()) error(absFilePath, "method not a string"); - QString toCheck = m.toString().toLower(); - if (toCheck == "post") - method = HttpMethod::POST; - else - error(absFilePath, "method invalid"); - } - QJsonValue url = obj["target"]; - if (!url.isString()) - { - error(absFilePath, "target missing"); - } - QUrl target(url.toString()); - if (!target.isValid()) error(absFilePath, "target not URL"); - this->target = target; - QJsonValue formatValue = obj["format"]; - if (!formatValue.isUndefined() && !formatValue.isNull()) - { - if (formatValue.isString()) - { - QString formatString = formatValue.toString().toLower(); - if (formatString == "x-www-form-urlencoded") - format = RequestFormat::X_WWW_FORM_URLENCODED; - else if (formatString == "json") - format = RequestFormat::JSON; - else if (formatString == "plain") - format = RequestFormat::PLAIN; - else - error(absFilePath, "format invalid"); - } + error(absFilePath, "method invalid"); + } + QJsonValue url = obj["target"]; + if (!url.isString()) { + error(absFilePath, "target missing"); + } + QUrl target(url.toString()); + if (!target.isValid()) + error(absFilePath, "target not URL"); + this->target = target; + QJsonValue formatValue = obj["format"]; + if (!formatValue.isUndefined() && !formatValue.isNull()) { + if (formatValue.isString()) { + QString formatString = formatValue.toString().toLower(); + if (formatString == "x-www-form-urlencoded") + format = RequestFormat::X_WWW_FORM_URLENCODED; + else if (formatString == "json") + format = RequestFormat::JSON; + else if (formatString == "plain") + format = RequestFormat::PLAIN; + else + error(absFilePath, "format invalid"); } + } else + error(absFilePath, "format provided but not string"); + QJsonValue imageValue = obj["imageformat"]; + if (!imageValue.isString()) { + error(absFilePath, "imageformat not string"); + } + QString imageFormat = imageValue.toString(); + if (imageFormat == "base64" || + QRegExp("base64\\([^+]+\\+[^+]+)").exactMatch(imageFormat) || + QRegExp("[^+]+\\+[^+]+").exactMatch(imageFormat)) { + this->iFormat = imageFormat; + } else + error(absFilePath, "imageformat invalid"); + QJsonValue bodyValue = obj["body"]; + if (format != RequestFormat::PLAIN) { + if (bodyValue.isUndefined()) + error(absFilePath, "body not set"); + if (bodyValue.isObject()) + body = bodyValue; else - error(absFilePath, "format provided but not string"); - QJsonValue imageValue = obj["imageformat"]; - if (!imageValue.isString()) - { - error(absFilePath, "imageformat not string"); - } - QString imageFormat = imageValue.toString(); - if (imageFormat == "base64" || QRegExp("base64\\([^+]+\\+[^+]+)").exactMatch(imageFormat) - || QRegExp("[^+]+\\+[^+]+").exactMatch(imageFormat)) - { - this->iFormat = imageFormat; - } - else - error(absFilePath, "imageformat invalid"); - QJsonValue bodyValue = obj["body"]; - if (format != RequestFormat::PLAIN) - { - if (bodyValue.isUndefined()) error(absFilePath, "body not set"); - if (bodyValue.isObject()) - body = bodyValue; - else - error(absFilePath, "body not object"); - } - else - { - if (bodyValue.isString()) - { - body = bodyValue; - } - else - error(absFilePath, "body not string (reason: format: PLAIN)"); - } - QJsonValue headerVal = obj["headers"]; - if (!(headerVal.isUndefined() || headerVal.isNull())) - { - if (!headerVal.isObject()) error(absFilePath, "headers must be object"); - headers = headerVal.toObject(); - } - else - headers = QJsonObject(); - QJsonValue returnPsVal = obj["return"]; - if (returnPsVal.isString()) - { - returnPathspec = returnPsVal.toString(); - } - else - error(absFilePath, "return invalid"); + error(absFilePath, "body not object"); + } else { + if (bodyValue.isString()) { + body = bodyValue; + } else + error(absFilePath, "body not string (reason: format: PLAIN)"); + } + QJsonValue headerVal = obj["headers"]; + if (!(headerVal.isUndefined() || headerVal.isNull())) { + if (!headerVal.isObject()) + error(absFilePath, "headers must be object"); + headers = headerVal.toObject(); + } else + headers = QJsonObject(); + QJsonValue returnPsVal = obj["return"]; + if (returnPsVal.isString()) { + returnPathspec = returnPsVal.toString(); + } else + error(absFilePath, "return invalid"); } -QString CustomUploader::name() -{ - return uName; -} +QString CustomUploader::name() { return uName; } -QString CustomUploader::description() -{ - return desc; -} +QString CustomUploader::description() { return desc; } -QString getCType(RequestFormat format, QString plainType) -{ - switch (format) - { - case RequestFormat::X_WWW_FORM_URLENCODED: - return "application/x-www-form-urlencoded"; - case RequestFormat::JSON: - return "application/json"; - case RequestFormat::PLAIN: - return plainType; - } +QString getCType(RequestFormat format, QString plainType) { + switch (format) { + case RequestFormat::X_WWW_FORM_URLENCODED: + return "application/x-www-form-urlencoded"; + case RequestFormat::JSON: + return "application/json"; + case RequestFormat::PLAIN: return plainType; + } + return plainType; } -QList> getHeaders(QJsonObject h, QString imageFormat, QMap types, RequestFormat format) -{ - QList> headers; - for (QString s : h.keys()) - { - if (s.toLower() == "content-type") continue; - QJsonValue v = h[s]; - if (!v.isString()) - headers << QPair(s, QJsonDocument::fromVariant(v.toVariant()).toJson()); - else - headers << QPair(s, v.toString()); +QList> getHeaders(QJsonObject h, QString imageFormat, + QMap types, + RequestFormat format) { + QList> headers; + for (QString s : h.keys()) { + if (s.toLower() == "content-type") + continue; + QJsonValue v = h[s]; + if (!v.isString()) + headers << QPair( + s, QJsonDocument::fromVariant(v.toVariant()).toJson()); + else + headers << QPair(s, v.toString()); + } + headers << QPair( + "Content-Type", getCType(format, types.value(imageFormat))); + return headers; +} + +QByteArray imageBytes(QPixmap *pixmap, QString format) { + QByteArray returnVal; + QBuffer buff(&returnVal); + buff.open(QIODevice::WriteOnly); + pixmap->save(&buff, format.toUpper().toLocal8Bit().constData()); + return returnVal; +} + +QString CustomUploader::getFormatString(bool animated) { + if (iFormat == "base64") + return animated ? "GIF" : "PNG"; + else if (QRegExp("[^+]+\\+[^+]+").exactMatch(iFormat)) + return iFormat.split('+')[(int)animated]; + else if (QRegExp("base64\\([^+]+\\+[^+]+)").exactMatch(iFormat)) + return iFormat.mid(7, iFormat.length() - 8).split('+')[(int)animated]; + return ""; +} + +QJsonObject recurseAndReplace(QJsonObject &body, QByteArray &data, + QString contentType) { + QJsonObject o; + for (QString s : body.keys()) { + QJsonValue v = body[s]; + if (v.isObject()) { + QJsonObject vo = v.toObject(); + o.insert(s, recurseAndReplace(vo, data, contentType)); + } else if (v.isString()) { + QString str = v.toString(); + if (str.startsWith("/") && str.endsWith("/")) { + o.insert( + s, + str.replace("%image", data).replace("%contenttype", contentType)); + } } - headers << QPair("Content-Type", getCType(format, types.value(imageFormat))); - return headers; + } + return o; } -QByteArray imageBytes(QPixmap *pixmap, QString format) -{ - QByteArray returnVal; - QBuffer buff(&returnVal); - buff.open(QIODevice::WriteOnly); - pixmap->save(&buff, format.toUpper().toLocal8Bit().constData()); - return returnVal; -} - -QString CustomUploader::getFormatString(bool animated) -{ - if (iFormat == "base64") - return animated ? "GIF" : "PNG"; - else if (QRegExp("[^+]+\\+[^+]+").exactMatch(iFormat)) - return iFormat.split('+')[(int)animated]; - else if (QRegExp("base64\\([^+]+\\+[^+]+)").exactMatch(iFormat)) - return iFormat.mid(7, iFormat.length() - 8).split('+')[(int)animated]; +QString parsePathspec(QJsonDocument &response, QString &pathspec) { + if (!pathspec.startsWith(".")) { + // Does not point to anything return ""; -} - -QJsonObject recurseAndReplace(QJsonObject &body, QByteArray &data, QString contentType) -{ - QJsonObject o; - for (QString s : body.keys()) - { - QJsonValue v = body[s]; - if (v.isObject()) - { - QJsonObject vo = v.toObject(); - o.insert(s, recurseAndReplace(vo, data, contentType)); - } - else if (v.isString()) - { - QString str = v.toString(); - if (str.startsWith("/") && str.endsWith("/")) - { - o.insert(s, str.replace("%image", data).replace("%contenttype", contentType)); - } - } + } else { + if (!response.isObject()) + return ""; + QStringList fields = pathspec.right(pathspec.length() - 1) + .split('.', QString::SkipEmptyParts); + QJsonObject o = response.object(); + if (pathspec == ".") { + return QString::fromUtf8(response.toJson()); } - return o; -} - -QString parsePathspec(QJsonDocument &response, QString &pathspec) -{ - if (!pathspec.startsWith(".")) - { - // Does not point to anything + QJsonValue val = o[fields.at(0)]; + if (val.isUndefined() || val.isNull()) + return ""; + else if (val.isString()) + return val.toString(); + else if (!val.isObject()) + return QString::fromUtf8( + QJsonDocument::fromVariant(val.toVariant()).toJson()); + for (int i = 1; i < fields.size(); i++) { + if (val.isUndefined() || val.isNull()) return ""; + else if (val.isString()) + return val.toString(); + else if (!val.isObject()) + return QString::fromUtf8( + QJsonDocument::fromVariant(val.toVariant()).toJson()); + else + val = val.toObject()[fields.at(i)]; } - else - { - if (!response.isObject()) return ""; - QStringList fields = pathspec.right(pathspec.length() - 1).split('.', QString::SkipEmptyParts); - QJsonObject o = response.object(); - if (pathspec == ".") - { - return QString::fromUtf8(response.toJson()); - } - QJsonValue val = o[fields.at(0)]; - if (val.isUndefined() || val.isNull()) - return ""; - else if (val.isString()) - return val.toString(); - else if (!val.isObject()) - return QString::fromUtf8(QJsonDocument::fromVariant(val.toVariant()).toJson()); - for (int i = 1; i < fields.size(); i++) - { - if (val.isUndefined() || val.isNull()) - return ""; - else if (val.isString()) - return val.toString(); - else if (!val.isObject()) - return QString::fromUtf8(QJsonDocument::fromVariant(val.toVariant()).toJson()); - else - val = val.toObject()[fields.at(i)]; - } - if (val.isUndefined() || val.isNull()) - return ""; - else if (val.isString()) - return val.toString(); - else if (!val.isObject()) - return QString::fromUtf8(QJsonDocument::fromVariant(val.toVariant()).toJson()); - } - return ""; + if (val.isUndefined() || val.isNull()) + return ""; + else if (val.isString()) + return val.toString(); + else if (!val.isObject()) + return QString::fromUtf8( + QJsonDocument::fromVariant(val.toVariant()).toJson()); + } + return ""; } -void parseResult(QJsonDocument result, QString returnPathspec, QString name) -{ - if (result.isObject()) - { - qDebug() << result.object()[".url"]; - QString url = parsePathspec(result, returnPathspec); - if (!url.isEmpty()) - { - QApplication::clipboard()->setText(url); - notifications::notify("KShare Custom Uploader " + name, "Copied upload link to clipboard!"); - } - else - notifications::notify("KShare Custom Uploader " + name, "Upload done, but result empty!"); - } - else - notifications::notify("KShare Custom Uploader " + name, "Upload done, but result is not JSON Object!"); +void parseResult(QJsonDocument result, QString returnPathspec, QString name) { + if (result.isObject()) { + qDebug() << result.object()[".url"]; + QString url = parsePathspec(result, returnPathspec); + if (!url.isEmpty()) { + QApplication::clipboard()->setText(url); + notifications::notify("KShare Custom Uploader " + name, + "Copied upload link to clipboard!"); + } else + notifications::notify("KShare Custom Uploader " + name, + "Upload done, but result empty!"); + } else + notifications::notify("KShare Custom Uploader " + name, + "Upload done, but result is not JSON Object!"); } -void CustomUploader::doUpload(QPixmap *pixmap) -{ - auto h = getHeaders(headers, getFormatString(false), types, this->format); - QString format = getFormatString(false); // Soon:tm: - QByteArray data; - QByteArray imgData = imageBytes(pixmap, format); - if (iFormat == "base64" || QRegExp("base64\\([^+]\\+[^+]\\)").exactMatch(iFormat)) imgData = imgData.toBase64(); - switch (this->format) - { - case RequestFormat::PLAIN: - { - data = imgData; +void CustomUploader::doUpload(QPixmap *pixmap) { + auto h = getHeaders(headers, getFormatString(false), types, this->format); + QString format = getFormatString(false); // Soon:tm: + QByteArray data; + QByteArray imgData = imageBytes(pixmap, format); + if (iFormat == "base64" || + QRegExp("base64\\([^+]\\+[^+]\\)").exactMatch(iFormat)) + imgData = imgData.toBase64(); + switch (this->format) { + case RequestFormat::PLAIN: { + data = imgData; + } break; + case RequestFormat::JSON: { + if (body.isString()) { + QStringList split = body.toString() + .replace("%contenttype", types.value(format)) + .split("%imagedata"); + for (int i = 0; i < split.size(); i++) { + data.append(split[i]); + if (i < split.size() - 1) + data.append(imgData); + } + } else { + QJsonObject vo = body.toObject(); + data = QJsonDocument::fromVariant( + recurseAndReplace(vo, imgData, types.value(format)) + .toVariantMap()) + .toJson(); + } + } break; + case RequestFormat::X_WWW_FORM_URLENCODED: { + QJsonObject body = this->body.toObject(); + for (QString key : body.keys()) { + QJsonValue val = body[key]; + if (val.isString()) { + QString str = val.toString(); + QByteArray strB; + if (str.startsWith("/") && str.endsWith("/")) { + str = str.mid(1, str.length() - 2); + QStringList split = str.replace("%contenttype", types.value(format)) + .split("%imagedata"); + for (int i = 0; i < split.size(); i++) { + strB.append(split[i]); + if (i < split.size() - 1) + strB.append(imgData); + } + } + data.append(QUrl::toPercentEncoding(key)).append('=').append(strB); + } else { + if (!data.isEmpty()) + data.append('&'); + data.append(QUrl::toPercentEncoding(key)) + .append('=') + .append(QUrl::toPercentEncoding( + QJsonDocument::fromVariant(body[key].toVariant()).toJson())); + } + } + } break; + } + switch (method) { + case HttpMethod::POST: + if (returnPathspec == "|") { + ioutils::postData( + target, h, data, [&](QByteArray result, QNetworkReply *) { + QApplication::clipboard()->setText(QString::fromUtf8(result)); + notifications::notify("KShare Custom Uploader " + name(), + "Copied upload result to clipboard!"); + }); + } else { + ioutils::postJson(target, h, data, + [&](QJsonDocument result, QNetworkReply *) { + parseResult(result, returnPathspec, name()); + }); } break; - case RequestFormat::JSON: - { - if (body.isString()) - { - QStringList split = body.toString().replace("%contenttype", types.value(format)).split("%imagedata"); - for (int i = 0; i < split.size(); i++) - { - data.append(split[i]); - if (i < split.size() - 1) data.append(imgData); - } - } - else - { - QJsonObject vo = body.toObject(); - data = QJsonDocument::fromVariant(recurseAndReplace(vo, imgData, types.value(format)).toVariantMap()).toJson(); - } - } - break; - case RequestFormat::X_WWW_FORM_URLENCODED: - { - QJsonObject body = this->body.toObject(); - for (QString key : body.keys()) - { - QJsonValue val = body[key]; - if (val.isString()) - { - QString str = val.toString(); - QByteArray strB; - if (str.startsWith("/") && str.endsWith("/")) - { - str = str.mid(1, str.length() - 2); - QStringList split = str.replace("%contenttype", types.value(format)).split("%imagedata"); - for (int i = 0; i < split.size(); i++) - { - strB.append(split[i]); - if (i < split.size() - 1) strB.append(imgData); - } - } - data.append(QUrl::toPercentEncoding(key)).append('=').append(strB); - } - else - { - if (!data.isEmpty()) data.append('&'); - data.append(QUrl::toPercentEncoding(key)) - .append('=') - .append(QUrl::toPercentEncoding(QJsonDocument::fromVariant(body[key].toVariant()).toJson())); - } - } - } - break; - } - switch (method) - { - case HttpMethod::POST: - if (returnPathspec == "|") - { - ioutils::postData(target, h, data, [&](QByteArray result, QNetworkReply *) { - QApplication::clipboard()->setText(QString::fromUtf8(result)); - notifications::notify("KShare Custom Uploader " + name(), "Copied upload result to clipboard!"); - }); - } - else - { - ioutils::postJson(target, h, data, - [&](QJsonDocument result, QNetworkReply *) { parseResult(result, returnPathspec, name()); }); - } - break; - } + } } diff --git a/uploaders/customuploader.hpp b/uploaders/customuploader.hpp index e85c985..2f1e36f 100644 --- a/uploaders/customuploader.hpp +++ b/uploaders/customuploader.hpp @@ -6,38 +6,29 @@ #include #include -enum class HttpMethod -{ - POST -}; +enum class HttpMethod { POST }; -enum class RequestFormat -{ - X_WWW_FORM_URLENCODED, - JSON, - PLAIN -}; +enum class RequestFormat { X_WWW_FORM_URLENCODED, JSON, PLAIN }; -class CustomUploader : public Uploader -{ - public: - CustomUploader(QString absFilePath); - QString name(); - QString description(); - void doUpload(QPixmap *pixmap); - QString getFormatString(bool animated); - QMap types; +class CustomUploader : public Uploader { +public: + CustomUploader(QString absFilePath); + QString name(); + QString description(); + void doUpload(QPixmap *pixmap); + QString getFormatString(bool animated); + QMap types; - private: - QString desc; - QString uName; - RequestFormat format = RequestFormat::JSON; - HttpMethod method = HttpMethod::POST; - QUrl target; - QJsonValue body; - QJsonObject headers; - QString returnPathspec; - QString iFormat; +private: + QString desc; + QString uName; + RequestFormat format = RequestFormat::JSON; + HttpMethod method = HttpMethod::POST; + QUrl target; + QJsonValue body; + QJsonObject headers; + QString returnPathspec; + QString iFormat; }; #endif // CUSTOMUPLOADER_HPP diff --git a/uploaders/default/clipboarduploader.cpp b/uploaders/default/clipboarduploader.cpp index d413e14..6e91176 100644 --- a/uploaders/default/clipboarduploader.cpp +++ b/uploaders/default/clipboarduploader.cpp @@ -4,8 +4,7 @@ #include #include -void ClipboardUploader::doUpload(QPixmap *pixmap) -{ - QApplication::clipboard()->setImage(pixmap->toImage()); - notifications::notify("KShare", "Copied to clipboard!"); +void ClipboardUploader::doUpload(QPixmap *pixmap) { + QApplication::clipboard()->setImage(pixmap->toImage()); + notifications::notify("KShare", "Copied to clipboard!"); } diff --git a/uploaders/default/clipboarduploader.hpp b/uploaders/default/clipboarduploader.hpp index 5616b75..463b176 100644 --- a/uploaders/default/clipboarduploader.hpp +++ b/uploaders/default/clipboarduploader.hpp @@ -4,18 +4,11 @@ #include #include -class ClipboardUploader : public Uploader -{ - public: - QString name() - { - return "clipboard"; - } - QString description() - { - return "Copies the image to clipboard"; - } - void doUpload(QPixmap *pixmap); +class ClipboardUploader : public Uploader { +public: + QString name() { return "clipboard"; } + QString description() { return "Copies the image to clipboard"; } + void doUpload(QPixmap *pixmap); }; #endif // CLIPBOARDUPLOADER_HPP diff --git a/uploaders/default/imguruploader.cpp b/uploaders/default/imguruploader.cpp index e6dd179..397c659 100644 --- a/uploaders/default/imguruploader.cpp +++ b/uploaders/default/imguruploader.cpp @@ -7,19 +7,23 @@ #include #include -void ImgurUploader::doUpload(QPixmap *pixmap) -{ - QByteArray byteArray; - QBuffer buffer(&byteArray); - pixmap->save(&buffer, "PNG"); - ioutils::postJson(QUrl("https://api.imgur.com/3/image"), - QList>() - << QPair("Content-Type", "application/x-www-form-urlencoded") - << QPair("Authorization", "Client-ID 8a98f183fc895da"), - byteArray, [](QJsonDocument res, QNetworkReply *) { - QString result = res.object()["data"].toObject()["link"].toString(); - screenshotutil::toClipboard(result); - notifications::notify("KShare imgur Uploader ", - result.isEmpty() ? "Failed upload!" : "Upload done, but result empty!"); - }); +void ImgurUploader::doUpload(QPixmap *pixmap) { + QByteArray byteArray; + QBuffer buffer(&byteArray); + pixmap->save(&buffer, "PNG"); + ioutils::postJson( + QUrl("https://api.imgur.com/3/image"), + QList>() + << QPair("Content-Type", + "application/x-www-form-urlencoded") + << QPair("Authorization", + "Client-ID 8a98f183fc895da"), + byteArray, [](QJsonDocument res, QNetworkReply *) { + QString result = res.object()["data"].toObject()["link"].toString(); + screenshotutil::toClipboard(result); + notifications::notify("KShare imgur Uploader ", + result.isEmpty() + ? "Failed upload!" + : "Upload done, but result empty!"); + }); } diff --git a/uploaders/default/imguruploader.hpp b/uploaders/default/imguruploader.hpp index b76acb5..844e136 100644 --- a/uploaders/default/imguruploader.hpp +++ b/uploaders/default/imguruploader.hpp @@ -3,18 +3,11 @@ #include "../uploader.hpp" -class ImgurUploader : public Uploader -{ - public: - QString name() - { - return "imgur"; - } - QString description() - { - return "imgur.com uploader"; - } - void doUpload(QPixmap *pixmap); +class ImgurUploader : public Uploader { +public: + QString name() { return "imgur"; } + QString description() { return "imgur.com uploader"; } + void doUpload(QPixmap *pixmap); }; #endif // IMGURUPLOADER_HPP diff --git a/uploaders/uploader.hpp b/uploaders/uploader.hpp index 3da10b3..4c5a03d 100644 --- a/uploaders/uploader.hpp +++ b/uploaders/uploader.hpp @@ -4,12 +4,11 @@ #include #include -class Uploader -{ - public: - virtual void doUpload(QPixmap *pixmap) = 0; - virtual QString name() = 0; - virtual QString description() = 0; +class Uploader { +public: + virtual void doUpload(QPixmap *pixmap) = 0; + virtual QString name() = 0; + virtual QString description() = 0; }; #endif // UPLOADER_HPP diff --git a/uploaders/uploadersingleton.cpp b/uploaders/uploadersingleton.cpp index 6b5d5ba..2642603 100644 --- a/uploaders/uploadersingleton.cpp +++ b/uploaders/uploadersingleton.cpp @@ -8,86 +8,70 @@ #include #include -UploaderSingleton::UploaderSingleton() : QObject() -{ - QDir configDir(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)); - configDir.mkpath("KShare/uploaders"); - configDir.cd("KShare/uploaders"); - configDir.setNameFilters({ "*.uploader" }); - for (QString file : configDir.entryList()) - { - try - { - registerUploader(new CustomUploader(configDir.absoluteFilePath(file))); - } - catch (std::runtime_error e) - { - qWarning() << e.what(); - errs << e; - } +UploaderSingleton::UploaderSingleton() : QObject() { + QDir configDir( + QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)); + configDir.mkpath("KShare/uploaders"); + configDir.cd("KShare/uploaders"); + configDir.setNameFilters({"*.uploader"}); + for (QString file : configDir.entryList()) { + try { + registerUploader(new CustomUploader(configDir.absoluteFilePath(file))); + } catch (std::runtime_error e) { + qWarning() << e.what(); + errs << e; } + } - // UPLOADERS - registerUploader(new ImgurUploader); - registerUploader(new ClipboardUploader); - // --------- + // UPLOADERS + registerUploader(new ImgurUploader); + registerUploader(new ClipboardUploader); + // --------- - if (settings::settings().contains("uploader")) - uploader = settings::settings().value("uploader").toString(); - else - settings::settings().setValue("uploader", uploader); - if (!uploaders.contains(uploader)) - { - settings::settings().setValue("uploader", uploader); - uploader = "imgur"; + if (settings::settings().contains("uploader")) + uploader = settings::settings().value("uploader").toString(); + else + settings::settings().setValue("uploader", uploader); + if (!uploaders.contains(uploader)) { + settings::settings().setValue("uploader", uploader); + uploader = "imgur"; + } +} + +void UploaderSingleton::registerUploader(Uploader *uploader) { + if (uploaders.contains(uploader->name())) { + throw std::runtime_error( + ("Ambigious uploader " + uploader->name()).toStdString()); + } + uploaders.insert(uploader->name(), uploader); + emit newUploader(uploader); +} + +void UploaderSingleton::upload(QPixmap *pixmap) { + if (settings::settings().contains("fileFormat")) { + QString format = settings::settings().value("fileFormat").toString(); + if (!format.isEmpty()) { + pixmap->save(QDir(QStandardPaths::writableLocation( + QStandardPaths::PicturesLocation)) + .absoluteFilePath(formatter::format(format) + ".png"), + "PNG"); } + } + uploaders.value(uploader)->doUpload(pixmap); + delete pixmap; } -void UploaderSingleton::registerUploader(Uploader *uploader) -{ - if (uploaders.contains(uploader->name())) - { - throw std::runtime_error(("Ambigious uploader " + uploader->name()).toStdString()); - } - uploaders.insert(uploader->name(), uploader); - emit newUploader(uploader); +QList UploaderSingleton::uploaderList() { + return uploaders.values(); } -void UploaderSingleton::upload(QPixmap *pixmap) -{ - if (settings::settings().contains("fileFormat")) - { - QString format = settings::settings().value("fileFormat").toString(); - if (!format.isEmpty()) - { - pixmap->save(QDir(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)).absoluteFilePath(formatter::format(format) + ".png"), - "PNG"); - } - } - uploaders.value(uploader)->doUpload(pixmap); - delete pixmap; +void UploaderSingleton::set(QString uploader) { + if (uploaders.contains(uploader)) { + this->uploader = uploader; + settings::settings().setValue("uploader", uploader); + } } -QList UploaderSingleton::uploaderList() -{ - return uploaders.values(); -} +QString UploaderSingleton::selectedUploader() { return uploader; } -void UploaderSingleton::set(QString uploader) -{ - if (uploaders.contains(uploader)) - { - this->uploader = uploader; - settings::settings().setValue("uploader", uploader); - } -} - -QString UploaderSingleton::selectedUploader() -{ - return uploader; -} - -QList UploaderSingleton::errors() -{ - return errs; -} +QList UploaderSingleton::errors() { return errs; } diff --git a/uploaders/uploadersingleton.hpp b/uploaders/uploadersingleton.hpp index 9c857bf..f3ebe4c 100644 --- a/uploaders/uploadersingleton.hpp +++ b/uploaders/uploadersingleton.hpp @@ -4,29 +4,27 @@ #include "uploader.hpp" #include -class UploaderSingleton : public QObject -{ - Q_OBJECT - public: - static UploaderSingleton &inst() - { - static UploaderSingleton inst; - return inst; - } - void registerUploader(Uploader *uploader); - void upload(QPixmap *pixmap); - QList uploaderList(); - void set(QString uploader); - QString selectedUploader(); - QList errors(); - signals: - void newUploader(Uploader *u); +class UploaderSingleton : public QObject { + Q_OBJECT +public: + static UploaderSingleton &inst() { + static UploaderSingleton inst; + return inst; + } + void registerUploader(Uploader *uploader); + void upload(QPixmap *pixmap); + QList uploaderList(); + void set(QString uploader); + QString selectedUploader(); + QList errors(); +signals: + void newUploader(Uploader *u); - private: - UploaderSingleton(); - QMap uploaders; - QString uploader = "imgur"; - QList errs; +private: + UploaderSingleton(); + QMap uploaders; + QString uploader = "imgur"; + QList errs; }; #endif // UPLOADERSINGLETON_HPP