From 75c4bf92d1a5c8891cffa4b92726a399798421d4 Mon Sep 17 00:00:00 2001 From: Christian Kaiser Date: Sun, 20 Mar 2016 18:37:17 -0300 Subject: [PATCH] Project-wide code style changes, (tentatively) fixed multi monitor support, fixed the area DPI fix. --- dialogs/areadialog.cpp | 896 ++++++++++---------- dialogs/historydialog.cpp | 347 ++++---- dialogs/namingdialog.cpp | 71 +- dialogs/optionsdialog.cpp | 1094 ++++++++++++------------ dialogs/previewdialog.cpp | 530 ++++++------ dialogs/updaterdialog.cpp | 39 +- lightscreenwindow.cpp | 1351 +++++++++++++++--------------- lightscreenwindow.h | 166 ++-- main.cpp | 118 ++- tools/os.cpp | 365 ++++---- tools/os.h | 49 +- tools/screenshot.cpp | 572 ++++++------- tools/screenshot.h | 196 +++-- tools/screenshotmanager.cpp | 201 ++--- tools/screenshotmanager.h | 61 +- tools/uploader/imageuploader.cpp | 9 +- tools/uploader/imageuploader.h | 42 +- tools/uploader/imguruploader.cpp | 131 ++- tools/uploader/imguruploader.h | 18 +- tools/uploader/uploader.cpp | 218 ++--- tools/uploader/uploader.h | 50 +- tools/windowpicker.cpp | 419 +++++---- tools/windowpicker.h | 30 +- updater/updater.cpp | 28 +- updater/updater.h | 14 +- widgets/hotkeywidget.cpp | 167 ++-- widgets/hotkeywidget.h | 34 +- 27 files changed, 3577 insertions(+), 3639 deletions(-) diff --git a/dialogs/areadialog.cpp b/dialogs/areadialog.cpp index 57317dc..e65feff 100644 --- a/dialogs/areadialog.cpp +++ b/dialogs/areadialog.cpp @@ -37,546 +37,540 @@ #include AreaDialog::AreaDialog(Screenshot *screenshot) : - QDialog(0), mScreenshot(screenshot), mMouseDown(false), mMouseMagnifier(false), - mNewSelection(false), mHandleSize(10), mMouseOverHandle(0), mIdleTimer(), - mShowHelp(true), mGrabbing(false), mOverlayAlpha(1), mAutoclose(false), - mTLHandle(0, 0, mHandleSize, mHandleSize), mTRHandle(0, 0, mHandleSize, mHandleSize), - mBLHandle(0, 0, mHandleSize, mHandleSize), mBRHandle(0, 0, mHandleSize, mHandleSize), - mLHandle(0, 0, mHandleSize, mHandleSize), mTHandle(0, 0, mHandleSize, mHandleSize), - mRHandle(0, 0, mHandleSize, mHandleSize), mBHandle(0, 0, mHandleSize, mHandleSize) + QDialog(0), mScreenshot(screenshot), mMouseDown(false), mMouseMagnifier(false), + mNewSelection(false), mHandleSize(10), mMouseOverHandle(0), mIdleTimer(), + mShowHelp(true), mGrabbing(false), mOverlayAlpha(1), mAutoclose(false), + mTLHandle(0, 0, mHandleSize, mHandleSize), mTRHandle(0, 0, mHandleSize, mHandleSize), + mBLHandle(0, 0, mHandleSize, mHandleSize), mBRHandle(0, 0, mHandleSize, mHandleSize), + mLHandle(0, 0, mHandleSize, mHandleSize), mTHandle(0, 0, mHandleSize, mHandleSize), + mRHandle(0, 0, mHandleSize, mHandleSize), mBHandle(0, 0, mHandleSize, mHandleSize) { - mHandles << &mTLHandle << &mTRHandle << &mBLHandle << &mBRHandle - << &mLHandle << &mTHandle << &mRHandle << &mBHandle; + mHandles << &mTLHandle << &mTRHandle << &mBLHandle << &mBRHandle + << &mLHandle << &mTHandle << &mRHandle << &mBHandle; - mMouseOverHandle = 0; + mMouseOverHandle = 0; - setMouseTracking(true); - setWindowTitle(tr("Lightscreen Area Mode")); - setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint); + setMouseTracking(true); + setWindowTitle(tr("Lightscreen Area Mode")); + setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint); - setCursor(Qt::CrossCursor); + setCursor(Qt::CrossCursor); - connect(&mIdleTimer, SIGNAL(timeout()), this, SLOT(displayHelp())); - mIdleTimer.start(2000); + connect(&mIdleTimer, SIGNAL(timeout()), this, SLOT(displayHelp())); + mIdleTimer.start(2000); - mAutoclose = ScreenshotManager::instance()->settings()->value("options/areaAutoclose").toBool(); + mAutoclose = ScreenshotManager::instance()->settings()->value("options/areaAutoclose").toBool(); - if (mAutoclose) - return; // Avoid creating the accept widget if it's not going to get used. - - // Creating accept widget: - mAcceptWidget = new QWidget(this); - mAcceptWidget->resize(140, 70); - mAcceptWidget->setWindowOpacity(0.4); - mAcceptWidget->setStyleSheet("QWidget { background: rgba(255, 255, 255, 200); border: 4px solid #232323; padding: 0; } QPushButton { background: transparent; border: none; height: 50px; padding: 5px; } QPushButton:hover { cursor: hand; }"); - - QPushButton *awAcceptButton = new QPushButton(QIcon(":/icons/yes.big"), "", this); - connect(awAcceptButton, SIGNAL(clicked()), this, SLOT(grabRect())); - awAcceptButton->setCursor(Qt::PointingHandCursor); - awAcceptButton->setIconSize(QSize(48, 48)); - - QPushButton *awRejectButton = new QPushButton(QIcon(":/icons/no.big"), "", this); - connect(awRejectButton, SIGNAL(clicked()), this, SLOT(cancel())); - awRejectButton->setCursor(Qt::PointingHandCursor); - awRejectButton->setIconSize(QSize(48, 48)); - - QHBoxLayout *awLayout = new QHBoxLayout(this); - awLayout->addWidget(awAcceptButton); - awLayout->addWidget(awRejectButton); - awLayout->setMargin(0); - awLayout->setSpacing(0); + if (mAutoclose) { + return; // Avoid creating the accept widget if it's not going to get used. + } - mAcceptWidget->setLayout(awLayout); - mAcceptWidget->setVisible(false); + // Creating accept widget: + mAcceptWidget = new QWidget(this); + mAcceptWidget->resize(140, 70); + mAcceptWidget->setWindowOpacity(0.4); + mAcceptWidget->setStyleSheet("QWidget { background: rgba(255, 255, 255, 200); border: 4px solid #232323; padding: 0; } QPushButton { background: transparent; border: none; height: 50px; padding: 5px; } QPushButton:hover { cursor: hand; }"); + + QPushButton *awAcceptButton = new QPushButton(QIcon(":/icons/yes.big"), "", this); + connect(awAcceptButton, SIGNAL(clicked()), this, SLOT(grabRect())); + awAcceptButton->setCursor(Qt::PointingHandCursor); + awAcceptButton->setIconSize(QSize(48, 48)); + + QPushButton *awRejectButton = new QPushButton(QIcon(":/icons/no.big"), "", this); + connect(awRejectButton, SIGNAL(clicked()), this, SLOT(cancel())); + awRejectButton->setCursor(Qt::PointingHandCursor); + awRejectButton->setIconSize(QSize(48, 48)); + + QHBoxLayout *awLayout = new QHBoxLayout(this); + awLayout->addWidget(awAcceptButton); + awLayout->addWidget(awRejectButton); + awLayout->setMargin(0); + awLayout->setSpacing(0); + + mAcceptWidget->setLayout(awLayout); + mAcceptWidget->setVisible(false); } QRect &AreaDialog::resultRect() { - return mSelection; + return mSelection; } void AreaDialog::animationTick(int frame) { - mOverlayAlpha = frame; - update(); + mOverlayAlpha = frame; + update(); } void AreaDialog::cancel() { - reject(); + reject(); } void AreaDialog::displayHelp() { - mShowHelp = true; - update(); + mShowHelp = true; + update(); } void AreaDialog::grabRect() { - QRect r = mSelection.normalized(); - if (!r.isNull() && r.isValid()) { - mGrabbing = true; - accept(); - } + QRect r = mSelection.normalized(); + if (!r.isNull() && r.isValid()) { + mGrabbing = true; + accept(); + } } -void AreaDialog::keyPressEvent(QKeyEvent* e) +void AreaDialog::keyPressEvent(QKeyEvent *e) { - if (e->key() == Qt::Key_Escape) { - cancel(); - } - else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) { - grabRect(); - } - else { - e->ignore(); - } + if (e->key() == Qt::Key_Escape) { + cancel(); + } else if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) { + grabRect(); + } else { + e->ignore(); + } } -void AreaDialog::mouseDoubleClickEvent(QMouseEvent*) +void AreaDialog::mouseDoubleClickEvent(QMouseEvent *) { - grabRect(); + grabRect(); } -void AreaDialog::mouseMoveEvent(QMouseEvent* e) +void AreaDialog::mouseMoveEvent(QMouseEvent *e) { - mMouseMagnifier = false; - - if (mMouseDown) { - - mMousePos = e->pos(); - - if (mNewSelection) { - QRect r = rect(); - - mSelection = QRect(mDragStartPoint, limitPointToRect(mMousePos, r)).normalized(); + mMouseMagnifier = false; + + if (mMouseDown) { + + mMousePos = e->pos(); + + if (mNewSelection) { + QRect r = rect(); + + mSelection = QRect(mDragStartPoint, limitPointToRect(mMousePos, r)).normalized(); + } else if (mMouseOverHandle == 0) { // moving the whole selection + QRect r = rect().normalized(), s = mSelectionBeforeDrag.normalized(); + QPoint p = s.topLeft() + e->pos() - mDragStartPoint; + r.setBottomRight(r.bottomRight() - QPoint(s.width(), s.height())); + + if (!r.isNull() && r.isValid()) { + mSelection.moveTo(limitPointToRect(p, r)); + } + } else { // dragging a handle + QRect r = mSelectionBeforeDrag; + QPoint offset = e->pos() - mDragStartPoint; + + if (mMouseOverHandle == &mTLHandle || mMouseOverHandle == &mTHandle + || mMouseOverHandle == &mTRHandle) { // dragging one of the top handles + r.setTop(r.top() + offset.y()); + } + + if (mMouseOverHandle == &mTLHandle || mMouseOverHandle == &mLHandle + || mMouseOverHandle == &mBLHandle) { // dragging one of the left handles + r.setLeft(r.left() + offset.x()); + } + + if (mMouseOverHandle == &mBLHandle || mMouseOverHandle == &mBHandle + || mMouseOverHandle == &mBRHandle) { // dragging one of the bottom handles + r.setBottom(r.bottom() + offset.y()); + } + + if (mMouseOverHandle == &mTRHandle || mMouseOverHandle == &mRHandle + || mMouseOverHandle == &mBRHandle) { // dragging one of the right handles + r.setRight(r.right() + offset.x()); + } + + r = r.normalized(); + r.setTopLeft(limitPointToRect(r.topLeft(), rect())); + r.setBottomRight(limitPointToRect(r.bottomRight(), rect())); + mSelection = r; + } + + if (qApp->keyboardModifiers() & Qt::ControlModifier) { + // The lazy 1:1 aspect ratio approach! + mSelection.setHeight(mSelection.width()); + } + + if (mAcceptWidget) { + QPoint acceptPos = e->pos(); + QRect acceptRect = QRect(acceptPos, QSize(120, 70)); + + // Prevent the widget from overlapping the handles + if (acceptRect.intersects(mTLHandle)) { + acceptPos = mTLHandle.bottomRight() + QPoint(2, 2); // Corner case + } + + if (acceptRect.intersects(mBRHandle)) { + acceptPos = mBRHandle.bottomRight(); + } + + if (acceptRect.intersects(mBHandle)) { + acceptPos = mBHandle.bottomRight(); + } + + if (acceptRect.intersects(mRHandle)) { + acceptPos = mRHandle.topRight(); + } + + if (acceptRect.intersects(mTHandle)) { + acceptPos = mTHandle.bottomRight(); + } + + if ((acceptPos.x() + 120) > mScreenshot->pixmap().rect().width()) { + acceptPos.setX(acceptPos.x() - 120); + } + + if ((acceptPos.y() + 70) > mScreenshot->pixmap().rect().height()) { + acceptPos.setY(acceptPos.y() - 70); + } + + mAcceptWidget->move(acceptPos); + } + + update(); + } else { + if (mSelection.isNull()) { + mMouseMagnifier = true; + update(); + return; + } + + bool found = false; + foreach (QRect *r, mHandles) { + if (r->contains(e->pos())) { + mMouseOverHandle = r; + found = true; + break; + } + } + + if (!found) { + mMouseOverHandle = 0; + if (mSelection.contains(e->pos())) { + setCursor(Qt::OpenHandCursor); + } else if (mAcceptWidget && QRect(mAcceptWidget->mapToParent(mAcceptWidget->pos()), QSize(100, 60)).contains(e->pos())) { + setCursor(Qt::PointingHandCursor); + } else { + setCursor(Qt::CrossCursor); + } + } else { + if (mMouseOverHandle == &mTLHandle || mMouseOverHandle == &mBRHandle) { + setCursor(Qt::SizeFDiagCursor); + } + if (mMouseOverHandle == &mTRHandle || mMouseOverHandle == &mBLHandle) { + setCursor(Qt::SizeBDiagCursor); + } + if (mMouseOverHandle == &mLHandle || mMouseOverHandle == &mRHandle) { + setCursor(Qt::SizeHorCursor); + } + if (mMouseOverHandle == &mTHandle || mMouseOverHandle == &mBHandle) { + setCursor(Qt::SizeVerCursor); + } + } } - else if (mMouseOverHandle == 0) { // moving the whole selection - QRect r = rect().normalized(), s = mSelectionBeforeDrag.normalized(); - QPoint p = s.topLeft() + e->pos() - mDragStartPoint; - r.setBottomRight(r.bottomRight() - QPoint(s.width(), s.height())); +} - if (!r.isNull() && r.isValid()) - mSelection.moveTo(limitPointToRect(p, r)); - } - else {// dragging a handle - QRect r = mSelectionBeforeDrag; - QPoint offset = e->pos() - mDragStartPoint; - - if (mMouseOverHandle == &mTLHandle || mMouseOverHandle == &mTHandle - || mMouseOverHandle == &mTRHandle) // dragging one of the top handles - { - r.setTop(r.top() + offset.y()); - } - - if (mMouseOverHandle == &mTLHandle || mMouseOverHandle == &mLHandle - || mMouseOverHandle == &mBLHandle) // dragging one of the left handles - { - r.setLeft(r.left() + offset.x()); - } - - if (mMouseOverHandle == &mBLHandle || mMouseOverHandle == &mBHandle - || mMouseOverHandle == &mBRHandle) // dragging one of the bottom handles - { - r.setBottom(r.bottom() + offset.y()); - } - - if (mMouseOverHandle == &mTRHandle || mMouseOverHandle == &mRHandle - || mMouseOverHandle == &mBRHandle) // dragging one of the right handles - { - r.setRight(r.right() + offset.x()); - } - - r = r.normalized(); - r.setTopLeft(limitPointToRect(r.topLeft(), rect())); - r.setBottomRight(limitPointToRect(r.bottomRight(), rect())); - mSelection = r; - } +void AreaDialog::mousePressEvent(QMouseEvent *e) +{ + mShowHelp = false; + mIdleTimer.stop(); - if (qApp->keyboardModifiers() & Qt::ControlModifier) - { - // The lazy 1:1 aspect ratio approach! - mSelection.setHeight(mSelection.width()); + if (mAcceptWidget) { + mAcceptWidget->hide(); } - if (mAcceptWidget) { - QPoint acceptPos = e->pos(); - QRect acceptRect = QRect(acceptPos, QSize(120, 70)); + if (e->button() == Qt::LeftButton) { + mMouseDown = true; + mDragStartPoint = e->pos(); + mSelectionBeforeDrag = mSelection; + if (!mSelection.contains(e->pos())) { + mNewSelection = true; + mSelection = QRect(); + mShowHelp = true; + setCursor(Qt::CrossCursor); + } else { + setCursor(Qt::ClosedHandCursor); + } + } else if (e->button() == Qt::RightButton + || e->button() == Qt::MidButton) { + cancel(); + } - // Prevent the widget from overlapping the handles - if (acceptRect.intersects(mTLHandle)) { - acceptPos = mTLHandle.bottomRight() + QPoint(2, 2); // Corner case - } + update(); +} - if (acceptRect.intersects(mBRHandle)) { - acceptPos = mBRHandle.bottomRight(); - } +void AreaDialog::mouseReleaseEvent(QMouseEvent *e) +{ + if (mAutoclose) { + grabRect(); + } - if (acceptRect.intersects(mBHandle)) { - acceptPos = mBHandle.bottomRight(); - } + if (!mSelection.isNull() && mAcceptWidget) { + mAcceptWidget->show(); + } - if (acceptRect.intersects(mRHandle)) { - acceptPos = mRHandle.topRight(); - } + mMouseDown = false; + mNewSelection = false; + mIdleTimer.start(); - if (acceptRect.intersects(mTHandle)) { - acceptPos = mTHandle.bottomRight(); - } + if (mMouseOverHandle == 0 && mSelection.contains(e->pos())) { + setCursor(Qt::OpenHandCursor); + } - if ((acceptPos.x()+120) > mScreenshot->pixmap().rect().width()) - acceptPos.setX(acceptPos.x()-120); + update(); +} - if ((acceptPos.y()+70) > mScreenshot->pixmap().rect().height()) - acceptPos.setY(acceptPos.y()-70); +void AreaDialog::paintEvent(QPaintEvent *e) +{ + Q_UNUSED(e); - mAcceptWidget->move(acceptPos); + if (mGrabbing) { // grabWindow() should just get the background + return; } - update(); - } - else - { - if (mSelection.isNull()) { - mMouseMagnifier = true; - update(); - return; + QPainter painter(this); + + QPalette pal = palette(); + QFont font = QToolTip::font(); + + QColor handleColor(85, 160, 188, 220); + QColor overlayColor(0, 0, 0, mOverlayAlpha); + QColor textColor = pal.color(QPalette::Active, QPalette::Text); + QColor textBackgroundColor = pal.color(QPalette::Active, QPalette::Base); + painter.drawPixmap(0, 0, mScreenshot->pixmap()); + painter.setFont(font); + + QRect r = mSelection.normalized().adjusted(0, 0, -1, -1); + + QRegion grey(rect()); + grey = grey.subtracted(r); + painter.setPen(handleColor); + painter.setBrush(overlayColor); + painter.setClipRegion(grey); + painter.drawRect(-1, -1, rect().width() + 1, rect().height() + 1); + painter.setClipRect(rect()); + painter.setBrush(Qt::NoBrush); + painter.drawRect(r); + + if (mShowHelp) { + //Drawing the explanatory text. + QRect helpRect = qApp->desktop()->screenGeometry(qApp->desktop()->primaryScreen()); + QString helpTxt = tr("Lightscreen area mode:\nUse your mouse to draw a rectangle to capture.\nPress any key or right click to exit."); + + helpRect.setHeight(qRound((float)(helpRect.height() / 10))); // We get a decently sized rect where the text should be drawn (centered) + + // We draw the white contrasting background for the text, using the same text and options to get the boundingRect that the text will have. + painter.setPen(QPen(Qt::white)); + painter.setBrush(QBrush(QColor(255, 255, 255, 180), Qt::SolidPattern)); + QRectF bRect = painter.boundingRect(helpRect, Qt::AlignCenter, helpTxt); + + // These four calls provide padding for the rect + bRect.setWidth(bRect.width() + 12); + bRect.setHeight(bRect.height() + 10); + bRect.setX(bRect.x() - 12); + bRect.setY(bRect.y() - 10); + + painter.drawRoundedRect(bRect, 8, 8); + + // Draw the text: + painter.setPen(QPen(Qt::black)); + painter.drawText(helpRect, Qt::AlignCenter, helpTxt); } - bool found = false; - foreach(QRect* r, mHandles) { - if (r->contains(e->pos())) { - mMouseOverHandle = r; - found = true; - break; - } + if (!mSelection.isNull()) { + // The grabbed region is everything which is covered by the drawn + // rectangles (border included). This means that there is no 0px + // selection, since a 0px wide rectangle will always be drawn as a line. + QString txt = QString("%1x%2").arg(mSelection.width() == 0 ? 2 : mSelection.width()) + .arg(mSelection.height() == 0 ? 2 : mSelection.height()); + QRect textRect = painter.boundingRect(rect(), Qt::AlignLeft, txt); + QRect boundingRect = textRect.adjusted(-4, 0, 0, 0); + + if (textRect.width() < r.width() - 2 * mHandleSize && + textRect.height() < r.height() - 2 * mHandleSize && + (r.width() > 100 && r.height() > 100)) { // center, unsuitable for small selections + boundingRect.moveCenter(r.center()); + textRect.moveCenter(r.center()); + } else if (r.y() - 3 > textRect.height() && + r.x() + textRect.width() < rect().right()) { // on top, left aligned + boundingRect.moveBottomLeft(QPoint(r.x(), r.y() - 3)); + textRect.moveBottomLeft(QPoint(r.x() + 2, r.y() - 3)); + } else if (r.x() - 3 > textRect.width()) { // left, top aligned + boundingRect.moveTopRight(QPoint(r.x() - 3, r.y())); + textRect.moveTopRight(QPoint(r.x() - 5, r.y())); + } else if (r.bottom() + 3 + textRect.height() < rect().bottom() && + r.right() > textRect.width()) { // at bottom, right aligned + boundingRect.moveTopRight(QPoint(r.right(), r.bottom() + 3)); + textRect.moveTopRight(QPoint(r.right() - 2, r.bottom() + 3)); + } else if (r.right() + textRect.width() + 3 < rect().width()) { // right, bottom aligned + boundingRect.moveBottomLeft(QPoint(r.right() + 3, r.bottom())); + textRect.moveBottomLeft(QPoint(r.right() + 5, r.bottom())); + } + // if the above didn't catch it, you are running on a very tiny screen... + painter.setPen(textColor); + painter.setBrush(textBackgroundColor); + painter.drawRect(boundingRect); + painter.drawText(textRect, txt); + + if ((r.height() > mHandleSize * 2 && r.width() > mHandleSize * 2) + || !mMouseDown) { + updateHandles(); + painter.setPen(handleColor); + handleColor.setAlpha(80); + painter.setBrush(handleColor); + painter.drawRects(handleMask().rects()); + } } - if (!found) { - mMouseOverHandle = 0; - if (mSelection.contains(e->pos())) - setCursor(Qt::OpenHandCursor); - else if (mAcceptWidget && QRect(mAcceptWidget->mapToParent(mAcceptWidget->pos()), QSize(100, 60)).contains(e->pos())) - setCursor(Qt::PointingHandCursor); - else - setCursor(Qt::CrossCursor); + if (!mScreenshot->options().magnify) { + return; } - else { - if (mMouseOverHandle == &mTLHandle || mMouseOverHandle == &mBRHandle) - setCursor(Qt::SizeFDiagCursor); - if (mMouseOverHandle == &mTRHandle || mMouseOverHandle == &mBLHandle) - setCursor(Qt::SizeBDiagCursor); - if (mMouseOverHandle == &mLHandle || mMouseOverHandle == &mRHandle) - setCursor(Qt::SizeHorCursor); - if (mMouseOverHandle == &mTHandle || mMouseOverHandle == &mBHandle) - setCursor(Qt::SizeVerCursor); - } - } -} -void AreaDialog::mousePressEvent(QMouseEvent* e) -{ - mShowHelp = false; - mIdleTimer.stop(); - - if (mAcceptWidget) - mAcceptWidget->hide(); - - if (e->button() == Qt::LeftButton) { - mMouseDown = true; - mDragStartPoint = e->pos(); - mSelectionBeforeDrag = mSelection; - if (!mSelection.contains(e->pos())) { - mNewSelection = true; - mSelection = QRect(); - mShowHelp = true; - setCursor(Qt::CrossCursor); - } - else { - setCursor(Qt::ClosedHandCursor); + // Drawing the magnified version + QPoint magStart, magEnd, drawPosition; + QRect newRect; + + QRect pixmapRect = mScreenshot->pixmap().rect(); + + if (mMouseMagnifier) { + drawPosition = mMousePos - QPoint(100, 100); + + magStart = mMousePos - QPoint(50, 50); + magEnd = mMousePos + QPoint(50, 50); + + newRect = QRect(magStart, magEnd); + } else { + // So pretty.. oh so pretty. + if (mMouseOverHandle == &mTLHandle) { + magStart = mSelection.topLeft(); + } else if (mMouseOverHandle == &mTRHandle) { + magStart = mSelection.topRight(); + } else if (mMouseOverHandle == &mBLHandle) { + magStart = mSelection.bottomLeft(); + } else if (mMouseOverHandle == &mBRHandle) { + magStart = mSelection.bottomRight(); + } else if (mMouseOverHandle == &mLHandle) { + magStart = QPoint(mSelection.left(), mSelection.center().y()); + } else if (mMouseOverHandle == &mTHandle) { + magStart = QPoint(mSelection.center().x(), mSelection.top()); + } else if (mMouseOverHandle == &mRHandle) { + magStart = QPoint(mSelection.right(), mSelection.center().y()); + } else if (mMouseOverHandle == &mBHandle) { + magStart = QPoint(mSelection.center().x(), mSelection.bottom()); + } else if (mMouseOverHandle == 0) { + magStart = mMousePos; + } + + magEnd = magStart; + drawPosition = mSelection.bottomRight(); + + magStart -= QPoint(50, 50); + magEnd += QPoint(50, 50); + + newRect = QRect(magStart, magEnd); + + if ((drawPosition.x() + newRect.width() * 2) > pixmapRect.width()) { + drawPosition.setX(drawPosition.x() - newRect.width() * 2); + } + + if ((drawPosition.y() + newRect.height() * 2) > pixmapRect.height()) { + drawPosition.setY(drawPosition.y() - newRect.height() * 2); + } + + if (drawPosition.y() == mSelection.bottomRight().y() - newRect.height() * 2 + && drawPosition.x() == mSelection.bottomRight().x() - newRect.width() * 2) { + painter.setOpacity(0.7); + } } - } - else if (e->button() == Qt::RightButton - || e->button() == Qt::MidButton) - { - cancel(); - } - - update(); -} - -void AreaDialog::mouseReleaseEvent(QMouseEvent* e) -{ - if (mAutoclose) - grabRect(); - - if (!mSelection.isNull() && mAcceptWidget) - mAcceptWidget->show(); - mMouseDown = false; - mNewSelection = false; - mIdleTimer.start(); + if (!pixmapRect.contains(newRect, true) || drawPosition.x() <= 0 || drawPosition.y() <= 0) { + return; + } - if (mMouseOverHandle == 0 && mSelection.contains(e->pos())) - setCursor(Qt::OpenHandCursor); + QPixmap magnified = mScreenshot->pixmap().copy(newRect).scaled(QSize(newRect.width() * 2, newRect.height() * 2)); - update(); -} + QPainter magPainter(&magnified); + magPainter.setPen(QPen(QBrush(QColor(35, 35, 35)), 2)); // Same border pen + magPainter.drawRect(magnified.rect()); -void AreaDialog::paintEvent(QPaintEvent* e) -{ - Q_UNUSED(e); - - if (mGrabbing) // grabWindow() should just get the background - return; - - QPainter painter(this); - - QPalette pal = palette(); - QFont font = QToolTip::font(); - - QColor handleColor(85, 160, 188, 220); - QColor overlayColor(0, 0, 0, mOverlayAlpha); - QColor textColor = pal.color(QPalette::Active, QPalette::Text); - QColor textBackgroundColor = pal.color(QPalette::Active, QPalette::Base); - mScreenshot->pixmap().setDevicePixelRatio(devicePixelRatio()); - painter.setFont(font); - - QRect r = mSelection.normalized().adjusted(0, 0, -1, -1); - - QRegion grey(rect()); - grey = grey.subtracted(r); - painter.setPen(handleColor); - painter.setBrush(overlayColor); - painter.setClipRegion(grey); - painter.drawRect(-1, -1, rect().width() + 1, rect().height() + 1); - painter.setClipRect(rect()); - painter.setBrush(Qt::NoBrush); - painter.drawRect(r); - - if (mShowHelp) { - //Drawing the explanatory text. - QRect helpRect = qApp->desktop()->screenGeometry(qApp->desktop()->primaryScreen()); - QString helpTxt = tr("Lightscreen area mode:\nUse your mouse to draw a rectangle to capture.\nPress any key or right click to exit."); - - helpRect.setHeight(qRound((float)(helpRect.height() / 10))); // We get a decently sized rect where the text should be drawn (centered) - - // We draw the white contrasting background for the text, using the same text and options to get the boundingRect that the text will have. - painter.setPen(QPen(Qt::white)); - painter.setBrush(QBrush(QColor(255, 255, 255, 180), Qt::SolidPattern)); - QRectF bRect = painter.boundingRect(helpRect, Qt::AlignCenter, helpTxt); - - // These four calls provide padding for the rect - bRect.setWidth(bRect.width() + 12); - bRect.setHeight(bRect.height() + 10); - bRect.setX(bRect.x() - 12); - bRect.setY(bRect.y() - 10); - - painter.drawRoundedRect(bRect, 8, 8); - - // Draw the text: - painter.setPen(QPen(Qt::black)); - painter.drawText(helpRect, Qt::AlignCenter, helpTxt); - } - - if (!mSelection.isNull()) { - // The grabbed region is everything which is covered by the drawn - // rectangles (border included). This means that there is no 0px - // selection, since a 0px wide rectangle will always be drawn as a line. - QString txt = QString("%1x%2").arg(mSelection.width() == 0 ? 2 : mSelection.width()) - .arg(mSelection.height() == 0 ? 2 : mSelection.height()); - QRect textRect = painter.boundingRect(rect(), Qt::AlignLeft, txt); - QRect boundingRect = textRect.adjusted(-4, 0, 0, 0); - - if (textRect.width() < r.width() - 2*mHandleSize && - textRect.height() < r.height() - 2*mHandleSize && - (r.width() > 100 && r.height() > 100)) // center, unsuitable for small selections - { - boundingRect.moveCenter(r.center()); - textRect.moveCenter(r.center()); - } - else if (r.y() - 3 > textRect.height() && - r.x() + textRect.width() < rect().right()) // on top, left aligned - { - boundingRect.moveBottomLeft(QPoint(r.x(), r.y() - 3)); - textRect.moveBottomLeft(QPoint(r.x() + 2, r.y() - 3)); - } - else if (r.x() - 3 > textRect.width()) // left, top aligned - { - boundingRect.moveTopRight(QPoint(r.x() - 3, r.y())); - textRect.moveTopRight(QPoint(r.x() - 5, r.y())); - } - else if (r.bottom() + 3 + textRect.height() < rect().bottom() && - r.right() > textRect.width()) // at bottom, right aligned - { - boundingRect.moveTopRight(QPoint(r.right(), r.bottom() + 3)); - textRect.moveTopRight(QPoint(r.right() - 2, r.bottom() + 3)); - } - else if (r.right() + textRect.width() + 3 < rect().width()) // right, bottom aligned - { - boundingRect.moveBottomLeft(QPoint(r.right() + 3, r.bottom())); - textRect.moveBottomLeft(QPoint(r.right() + 5, r.bottom())); + if (!mMouseMagnifier) { + magPainter.drawText(magnified.rect().center() - QPoint(4, -4), "+"); //Center minus the 4 pixels wide and across of the "+" -- TODO: Test alternative DPI settings. } - // if the above didn't catch it, you are running on a very tiny screen... - painter.setPen(textColor); - painter.setBrush(textBackgroundColor); - painter.drawRect(boundingRect); - painter.drawText(textRect, txt); - - if ((r.height() > mHandleSize*2 && r.width() > mHandleSize*2) - || !mMouseDown) - { - updateHandles(); - painter.setPen(handleColor); - handleColor.setAlpha(80); - painter.setBrush(handleColor); - painter.drawRects(handleMask().rects()); - } - } - - if (!mScreenshot->options().magnify) - return; - - // Drawing the magnified version - QPoint magStart, magEnd, drawPosition; - QRect newRect; - - QRect pixmapRect = mScreenshot->pixmap().rect(); - - if (mMouseMagnifier) { - drawPosition = mMousePos - QPoint(100, 100); - - magStart = mMousePos - QPoint(50, 50); - magEnd = mMousePos + QPoint(50, 50); - - newRect = QRect(magStart, magEnd); - } - else { - // So pretty.. oh so pretty. - if (mMouseOverHandle == &mTLHandle) - magStart = mSelection.topLeft(); - else if (mMouseOverHandle == &mTRHandle) - magStart = mSelection.topRight(); - else if (mMouseOverHandle == &mBLHandle) - magStart = mSelection.bottomLeft(); - else if (mMouseOverHandle == &mBRHandle) - magStart = mSelection.bottomRight(); - else if (mMouseOverHandle == &mLHandle) - magStart = QPoint(mSelection.left(), mSelection.center().y()); - else if (mMouseOverHandle == &mTHandle) - magStart = QPoint(mSelection.center().x(), mSelection.top()); - else if (mMouseOverHandle == &mRHandle) - magStart = QPoint(mSelection.right(), mSelection.center().y()); - else if (mMouseOverHandle == &mBHandle) - magStart = QPoint(mSelection.center().x(), mSelection.bottom()); - else if (mMouseOverHandle == 0) - magStart = mMousePos; - - magEnd = magStart; - drawPosition = mSelection.bottomRight(); - - magStart -= QPoint(50, 50); - magEnd += QPoint(50, 50); - - newRect = QRect(magStart, magEnd); - - if ((drawPosition.x()+newRect.width()*2) > pixmapRect.width()) - drawPosition.setX(drawPosition.x()-newRect.width()*2); - - if ((drawPosition.y()+newRect.height()*2) > pixmapRect.height()) - drawPosition.setY(drawPosition.y()-newRect.height()*2); - - if (drawPosition.y() == mSelection.bottomRight().y()-newRect.height()*2 - && drawPosition.x() == mSelection.bottomRight().x()-newRect.width()*2) - painter.setOpacity(0.7); - } - - if (!pixmapRect.contains(newRect, true) || drawPosition.x() <= 0 || drawPosition.y() <= 0) { - return; - } - - QPixmap magnified = mScreenshot->pixmap().copy(newRect).scaled(QSize(newRect.width()*2, newRect.height()*2)); - - QPainter magPainter(&magnified); - magPainter.setPen(QPen(QBrush(QColor(35, 35, 35)), 2)); // Same border pen - magPainter.drawRect(magnified.rect()); - - if (!mMouseMagnifier) { - magPainter.drawText(magnified.rect().center()-QPoint(4, -4), "+"); //Center minus the 4 pixels wide and across of the "+" -- TODO: Test alternative DPI settings. - } - - painter.drawPixmap(drawPosition, magnified); + + painter.drawPixmap(drawPosition, magnified); } -void AreaDialog::resizeEvent(QResizeEvent* e) +void AreaDialog::resizeEvent(QResizeEvent *e) { - Q_UNUSED(e); + Q_UNUSED(e); - if (mSelection.isNull()) - return; + if (mSelection.isNull()) { + return; + } - QRect r = mSelection; - r.setTopLeft(limitPointToRect(r.topLeft(), rect())); - r.setBottomRight(limitPointToRect(r.bottomRight(), rect())); + QRect r = mSelection; + r.setTopLeft(limitPointToRect(r.topLeft(), rect())); + r.setBottomRight(limitPointToRect(r.bottomRight(), rect())); - if (r.width() <= 1 || r.height() <= 1) //this just results in ugly drawing... - r = QRect(); + if (r.width() <= 1 || r.height() <= 1) { //this just results in ugly drawing... + r = QRect(); + } - mSelection = r; + mSelection = r; } -void AreaDialog::showEvent(QShowEvent* e) +void AreaDialog::showEvent(QShowEvent *e) { - Q_UNUSED(e) + Q_UNUSED(e) - QRect geometry = qApp->desktop()->geometry(); + QRect geometry = qApp->desktop()->geometry(); - if (mScreenshot->options().currentMonitor) { - geometry = qApp->desktop()->screenGeometry(qApp->desktop()->screenNumber(QCursor::pos())); - } + if (mScreenshot->options().currentMonitor) { + geometry = qApp->desktop()->screenGeometry(qApp->desktop()->screenNumber(QCursor::pos())); + } - resize(geometry.size()); - move(geometry.topLeft()); + resize(geometry.size()); + move(geometry.topLeft()); - if (mScreenshot->options().animations) { - os::effect(this, SLOT(animationTick(int)), 85, 300); - } - else { - animationTick(85); - } + if (mScreenshot->options().animations) { + os::effect(this, SLOT(animationTick(int)), 85, 300); + } else { + animationTick(85); + } - setMouseTracking(true); + setMouseTracking(true); } void AreaDialog::updateHandles() { - QRect r = mSelection.normalized().adjusted(0, 0, -1, -1); - int s2 = mHandleSize / 2; - - mTLHandle.moveTopLeft(r.topLeft()); - mTRHandle.moveTopRight(r.topRight()); - mBLHandle.moveBottomLeft(r.bottomLeft()); - mBRHandle.moveBottomRight(r.bottomRight()); - - mLHandle.moveTopLeft(QPoint(r.x(), r.y() + r.height() / 2 - s2)); - mTHandle.moveTopLeft(QPoint(r.x() + r.width() / 2 - s2, r.y())); - mRHandle.moveTopRight(QPoint(r.right(), r.y() + r.height() / 2 - s2)); - mBHandle.moveBottomLeft(QPoint(r.x() + r.width() / 2 - s2, r.bottom())); + QRect r = mSelection.normalized().adjusted(0, 0, -1, -1); + int s2 = mHandleSize / 2; + + mTLHandle.moveTopLeft(r.topLeft()); + mTRHandle.moveTopRight(r.topRight()); + mBLHandle.moveBottomLeft(r.bottomLeft()); + mBRHandle.moveBottomRight(r.bottomRight()); + + mLHandle.moveTopLeft(QPoint(r.x(), r.y() + r.height() / 2 - s2)); + mTHandle.moveTopLeft(QPoint(r.x() + r.width() / 2 - s2, r.y())); + mRHandle.moveTopRight(QPoint(r.right(), r.y() + r.height() / 2 - s2)); + mBHandle.moveBottomLeft(QPoint(r.x() + r.width() / 2 - s2, r.bottom())); } QRegion AreaDialog::handleMask() const { - // note: not normalized QRects are bad here, since they will not be drawn - QRegion mask; - foreach(QRect* rect, mHandles) mask += QRegion(*rect); - return mask; + // note: not normalized QRects are bad here, since they will not be drawn + QRegion mask; + foreach(QRect * rect, mHandles) mask += QRegion(*rect); + return mask; } QPoint AreaDialog::limitPointToRect(const QPoint &p, const QRect &r) const { - QPoint q; - q.setX(p.x() < r.x() ? r.x() : p.x() < r.right() ? p.x() : r.right()); - q.setY(p.y() < r.y() ? r.y() : p.y() < r.bottom() ? p.y() : r.bottom()); - return q; + QPoint q; + q.setX(p.x() < r.x() ? r.x() : p.x() < r.right() ? p.x() : r.right()); + q.setY(p.y() < r.y() ? r.y() : p.y() < r.bottom() ? p.y() : r.bottom()); + return q; } diff --git a/dialogs/historydialog.cpp b/dialogs/historydialog.cpp index 0581fe4..a8099a0 100644 --- a/dialogs/historydialog.cpp +++ b/dialogs/historydialog.cpp @@ -23,264 +23,247 @@ HistoryDialog::HistoryDialog(QWidget *parent) : QDialog(parent), ui(new Ui::HistoryDialog) { - ui->setupUi(this); - - ui->filterEdit->setText(tr("Filter..")); - ui->filterEdit->installEventFilter(this); - - if (QSqlDatabase::database().isOpen()) - { - mModel = new QSqlTableModel(this); - mModel->setTable("history"); - mModel->setHeaderData(0, Qt::Horizontal, tr("Screenshot")); - mModel->setHeaderData(1, Qt::Horizontal, tr("URL")); - mModel->select(); - - mFilterModel = new QSortFilterProxyModel(mModel); - mFilterModel->setSourceModel(mModel); - mFilterModel->setDynamicSortFilter(true); - mFilterModel->setSortCaseSensitivity(Qt::CaseInsensitive); - mFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive); - mFilterModel->setFilterKeyColumn(-1); - - while (mModel->canFetchMore()) { - mModel->fetchMore(); + ui->setupUi(this); + + ui->filterEdit->setText(tr("Filter..")); + ui->filterEdit->installEventFilter(this); + + if (QSqlDatabase::database().isOpen()) { + mModel = new QSqlTableModel(this); + mModel->setTable("history"); + mModel->setHeaderData(0, Qt::Horizontal, tr("Screenshot")); + mModel->setHeaderData(1, Qt::Horizontal, tr("URL")); + mModel->select(); + + mFilterModel = new QSortFilterProxyModel(mModel); + mFilterModel->setSourceModel(mModel); + mFilterModel->setDynamicSortFilter(true); + mFilterModel->setSortCaseSensitivity(Qt::CaseInsensitive); + mFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive); + mFilterModel->setFilterKeyColumn(-1); + + while (mModel->canFetchMore()) { + mModel->fetchMore(); + } + + ui->tableView->setWordWrap(false); + ui->tableView->setModel(mFilterModel); + + ui->tableView->hideColumn(2); // No delete hash. + ui->tableView->hideColumn(3); // No timestamp. + + ui->tableView->horizontalHeader()->setSectionsClickable(false); + ui->tableView->horizontalHeader()->setSectionsMovable(false); + + ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); + ui->tableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + + ui->tableView->verticalHeader()->hide(); + + ui->tableView->setTextElideMode(Qt::ElideLeft); + ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); + ui->tableView->setAlternatingRowColors(true); + ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection); + ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu); + ui->tableView->setSortingEnabled(true); + + if (ui->tableView->model()->rowCount() > 0) { + ui->clearButton->setEnabled(true); + ui->filterEdit->setEnabled(true); + } + + connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(selectionChanged(QItemSelection, QItemSelection))); + connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(open(QModelIndex))); + connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenu(QPoint))); + } else { + ui->tableView->setEnabled(false); + ui->clearButton->setEnabled(false); } - ui->tableView->setWordWrap(false); - ui->tableView->setModel(mFilterModel); - - ui->tableView->hideColumn(2); // No delete hash. - ui->tableView->hideColumn(3); // No timestamp. - - ui->tableView->horizontalHeader()->setSectionsClickable(false); - ui->tableView->horizontalHeader()->setSectionsMovable(false); - - ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); - ui->tableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); - - ui->tableView->verticalHeader()->hide(); - - ui->tableView->setTextElideMode(Qt::ElideLeft); - ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); - ui->tableView->setAlternatingRowColors(true); - ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection); - ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu); - ui->tableView->setSortingEnabled(true); - - if (ui->tableView->model()->rowCount() > 0) - { - ui->clearButton->setEnabled(true); - ui->filterEdit->setEnabled(true); + if (Uploader::instance()->progress() > 0) { + ui->uploadProgressBar->setValue(Uploader::instance()->progress()); + } else { + ui->uploadProgressWidget->setVisible(false); } - connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged(QItemSelection,QItemSelection))); - connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(open(QModelIndex))); - connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenu(QPoint))); - } - else { - ui->tableView->setEnabled(false); - ui->clearButton->setEnabled(false); - } + ui->cancelUploadButton->setIcon(os::icon("no")); - if (Uploader::instance()->progress() > 0) { - ui->uploadProgressBar->setValue(Uploader::instance()->progress()); - } - else { - ui->uploadProgressWidget->setVisible(false); - } + connect(Uploader::instance(), SIGNAL(progress(int)), this, SLOT(uploadProgress(int))); + connect(Uploader::instance(), SIGNAL(done(QString, QString, QString)), this, SLOT(refresh())); - ui->cancelUploadButton->setIcon(os::icon("no")); + connect(ui->uploadButton , SIGNAL(clicked()), this , SLOT(upload())); + connect(ui->cancelUploadButton, SIGNAL(clicked()), Uploader::instance() , SLOT(cancel())); + connect(ui->cancelUploadButton, SIGNAL(clicked()), ui->uploadProgressWidget, SLOT(hide())); - connect(Uploader::instance(), SIGNAL(progress(int)), this, SLOT(uploadProgress(int))); - connect(Uploader::instance(), SIGNAL(done(QString,QString,QString)), this, SLOT(refresh())); - - connect(ui->uploadButton , SIGNAL(clicked()), this , SLOT(upload())); - connect(ui->cancelUploadButton, SIGNAL(clicked()), Uploader::instance() , SLOT(cancel())); - connect(ui->cancelUploadButton, SIGNAL(clicked()), ui->uploadProgressWidget, SLOT(hide())); - - connect(ui->clearButton , SIGNAL(clicked()), this , SLOT(clear())); + connect(ui->clearButton , SIGNAL(clicked()), this , SLOT(clear())); } HistoryDialog::~HistoryDialog() { - delete ui; + delete ui; } void HistoryDialog::clear() { - if (QMessageBox::question(this, - tr("Clearing the screenshot history"), - tr("Are you sure you want to clear your entire screenshot history?\nThis cannot be undone."), - tr("Clear History"), - tr("Don't Clear")) == 1) { - return; - } - - ScreenshotManager::instance()->clearHistory(); - close(); + if (QMessageBox::question(this, + tr("Clearing the screenshot history"), + tr("Are you sure you want to clear your entire screenshot history?\nThis cannot be undone."), + tr("Clear History"), + tr("Don't Clear")) == 1) { + return; + } + + ScreenshotManager::instance()->clearHistory(); + close(); } void HistoryDialog::contextMenu(QPoint point) { - mContextIndex = ui->tableView->indexAt(point);; + mContextIndex = ui->tableView->indexAt(point);; - QMenu contextMenu(ui->tableView); + QMenu contextMenu(ui->tableView); - QAction copyAction((mContextIndex.column() == 0) ? tr("Copy Path") : tr("Copy URL"), &contextMenu); - connect(©Action, SIGNAL(triggered()), this, SLOT(copy())); - contextMenu.addAction(©Action); + QAction copyAction((mContextIndex.column() == 0) ? tr("Copy Path") : tr("Copy URL"), &contextMenu); + connect(©Action, SIGNAL(triggered()), this, SLOT(copy())); + contextMenu.addAction(©Action); - QAction deleteAction(tr("Delete from imgur.com"), &contextMenu); - QAction locationAction(tr("Open Location"), &contextMenu); + QAction deleteAction(tr("Delete from imgur.com"), &contextMenu); + QAction locationAction(tr("Open Location"), &contextMenu); - QAction removeAction(tr("Remove history entry"), &contextMenu); + QAction removeAction(tr("Remove history entry"), &contextMenu); - if (mContextIndex.data().toString().isEmpty()) { - copyAction.setEnabled(false); - deleteAction.setEnabled(false); - } + if (mContextIndex.data().toString().isEmpty()) { + copyAction.setEnabled(false); + deleteAction.setEnabled(false); + } - if (mContextIndex.column() == 0) { - connect(&locationAction, SIGNAL(triggered()), this, SLOT(location())); - contextMenu.addAction(&locationAction); - } - else { - connect(&deleteAction, SIGNAL(triggered()), this, SLOT(deleteImage())); - contextMenu.addAction(&deleteAction); - } + if (mContextIndex.column() == 0) { + connect(&locationAction, SIGNAL(triggered()), this, SLOT(location())); + contextMenu.addAction(&locationAction); + } else { + connect(&deleteAction, SIGNAL(triggered()), this, SLOT(deleteImage())); + contextMenu.addAction(&deleteAction); + } - connect(&removeAction, SIGNAL(triggered()), this, SLOT(removeHistoryEntry())); - contextMenu.addAction(&removeAction); - contextMenu.exec(QCursor::pos()); + connect(&removeAction, SIGNAL(triggered()), this, SLOT(removeHistoryEntry())); + contextMenu.addAction(&removeAction); + contextMenu.exec(QCursor::pos()); } void HistoryDialog::copy() { - qApp->clipboard()->setText(mContextIndex.data().toString()); + qApp->clipboard()->setText(mContextIndex.data().toString()); } void HistoryDialog::deleteImage() { - QDesktopServices::openUrl(mContextIndex.sibling(mContextIndex.row(), 2).data().toString()); + QDesktopServices::openUrl(mContextIndex.sibling(mContextIndex.row(), 2).data().toString()); } void HistoryDialog::location() { - QDesktopServices::openUrl("file:///" + QFileInfo(mContextIndex.data().toString()).absolutePath()); + QDesktopServices::openUrl("file:///" + QFileInfo(mContextIndex.data().toString()).absolutePath()); } void HistoryDialog::removeHistoryEntry() { - if (mContextIndex.column() == 0) { - // File got right clicked: - ScreenshotManager::instance()->removeHistory(mContextIndex.data().toString(), mContextIndex.sibling(mContextIndex.row(), 3).data().toLongLong()); - } - else { - // Screenshot URL got right clicked: - ScreenshotManager::instance()->removeHistory(mContextIndex.sibling(mContextIndex.row(), 0).data().toString(), mContextIndex.sibling(mContextIndex.row(), 3).data().toLongLong()); - } - - refresh(); + if (mContextIndex.column() == 0) { + // File got right clicked: + ScreenshotManager::instance()->removeHistory(mContextIndex.data().toString(), mContextIndex.sibling(mContextIndex.row(), 3).data().toLongLong()); + } else { + // Screenshot URL got right clicked: + ScreenshotManager::instance()->removeHistory(mContextIndex.sibling(mContextIndex.row(), 0).data().toString(), mContextIndex.sibling(mContextIndex.row(), 3).data().toLongLong()); + } + + refresh(); } void HistoryDialog::refresh() { - mModel->select(); + mModel->select(); } void HistoryDialog::open(const QModelIndex &index) { - if (index.column() == 0) { - QDesktopServices::openUrl(QUrl("file:///" + index.data().toString())); - } - else { - QDesktopServices::openUrl(index.data().toUrl()); - } + if (index.column() == 0) { + QDesktopServices::openUrl(QUrl("file:///" + index.data().toString())); + } else { + QDesktopServices::openUrl(index.data().toUrl()); + } } void HistoryDialog::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { - Q_UNUSED(deselected); + Q_UNUSED(deselected); - if (selected.indexes().count() == 0){ - return; - } + if (selected.indexes().count() == 0) { + return; + } - QModelIndex index = selected.indexes().at(0); + QModelIndex index = selected.indexes().at(0); - QString screenshot; + QString screenshot; - if (index.column() == 0) { - screenshot = index.data().toString(); - } - else { - screenshot = ui->tableView->model()->index(index.row(), 0).data().toString(); - } + if (index.column() == 0) { + screenshot = index.data().toString(); + } else { + screenshot = ui->tableView->model()->index(index.row(), 0).data().toString(); + } - mSelectedScreenshot = screenshot; + mSelectedScreenshot = screenshot; - ui->uploadButton->setEnabled(QFile::exists(screenshot)); + ui->uploadButton->setEnabled(QFile::exists(screenshot)); } void HistoryDialog::upload() { - Uploader::instance()->upload(mSelectedScreenshot); - ui->uploadProgressWidget->setVisible(true); + Uploader::instance()->upload(mSelectedScreenshot); + ui->uploadProgressWidget->setVisible(true); } void HistoryDialog::uploadProgress(int progress) { - ui->uploadProgressWidget->setVisible(true); - ui->uploadProgressBar->setValue(progress); + ui->uploadProgressWidget->setVisible(true); + ui->uploadProgressBar->setValue(progress); } bool HistoryDialog::eventFilter(QObject *object, QEvent *event) { - if (object == ui->filterEdit) { - if (event->type() == QEvent::FocusIn) - { - if (ui->filterEdit->text() == tr("Filter..")) { - ui->filterEdit->setStyleSheet(""); - ui->filterEdit->setText(""); - mFilterModel->setFilterWildcard(""); - mFilterModel->sort(3, Qt::DescendingOrder); - } - } - else if (event->type() == QEvent::FocusOut) - { - if (ui->filterEdit->text().isEmpty()) { - ui->filterEdit->setStyleSheet("color: palette(mid);"); - ui->filterEdit->setText(tr("Filter..")); - mFilterModel->sort(3, Qt::DescendingOrder); - } + if (object == ui->filterEdit) { + if (event->type() == QEvent::FocusIn) { + if (ui->filterEdit->text() == tr("Filter..")) { + ui->filterEdit->setStyleSheet(""); + ui->filterEdit->setText(""); + mFilterModel->setFilterWildcard(""); + mFilterModel->sort(3, Qt::DescendingOrder); + } + } else if (event->type() == QEvent::FocusOut) { + if (ui->filterEdit->text().isEmpty()) { + ui->filterEdit->setStyleSheet("color: palette(mid);"); + ui->filterEdit->setText(tr("Filter..")); + mFilterModel->sort(3, Qt::DescendingOrder); + } + } else if (event->type() == QEvent::KeyRelease) { + if (ui->filterEdit->text() != tr("Filter..") && !ui->filterEdit->text().isEmpty()) { + mFilterModel->setFilterWildcard(ui->filterEdit->text()); + mFilterModel->sort(3, Qt::DescendingOrder); + } else { + mFilterModel->setFilterWildcard(""); + mFilterModel->sort(3, Qt::DescendingOrder); + } + } } - else if (event->type() == QEvent::KeyRelease) - { - if (ui->filterEdit->text() != tr("Filter..") && !ui->filterEdit->text().isEmpty()) { - mFilterModel->setFilterWildcard(ui->filterEdit->text()); - mFilterModel->sort(3, Qt::DescendingOrder); - } - else { - mFilterModel->setFilterWildcard(""); - mFilterModel->sort(3, Qt::DescendingOrder); - } - } - } - return QDialog::eventFilter(object, event); + return QDialog::eventFilter(object, event); } bool HistoryDialog::event(QEvent *event) { - if (event->type() == QEvent::Show) - { - restoreGeometry(ScreenshotManager::instance()->settings()->value("geometry/historyDialog").toByteArray()); - } - else if (event->type() == QEvent::Close) - { - ScreenshotManager::instance()->settings()->setValue("geometry/historyDialog", saveGeometry()); - } - - return QDialog::event(event); + if (event->type() == QEvent::Show) { + restoreGeometry(ScreenshotManager::instance()->settings()->value("geometry/historyDialog").toByteArray()); + } else if (event->type() == QEvent::Close) { + ScreenshotManager::instance()->settings()->setValue("geometry/historyDialog", saveGeometry()); + } + + return QDialog::event(event); } diff --git a/dialogs/namingdialog.cpp b/dialogs/namingdialog.cpp index ff17fc2..ebe61c8 100644 --- a/dialogs/namingdialog.cpp +++ b/dialogs/namingdialog.cpp @@ -26,66 +26,65 @@ #include #include -NamingDialog::NamingDialog(Screenshot::Naming naming,QWidget *parent) : +NamingDialog::NamingDialog(Screenshot::Naming naming, QWidget *parent) : QDialog(parent) { - ui.setupUi(this); - setModal(true); - setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint); + ui.setupUi(this); + setModal(true); + setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint); - ui.dateFormatComboBox->installEventFilter(this); + ui.dateFormatComboBox->installEventFilter(this); - // Settings - QSettings *s = ScreenshotManager::instance()->settings(); - ui.flipNamingCheckBox->setChecked(s->value("options/flip", false).toBool()); + // Settings + QSettings *s = ScreenshotManager::instance()->settings(); + ui.flipNamingCheckBox->setChecked(s->value("options/flip", false).toBool()); - ui.dateFormatComboBox->setCurrentIndex( + ui.dateFormatComboBox->setCurrentIndex( ui.dateFormatComboBox->findText(s->value("options/naming/dateFormat", "yyyy-MM-dd").toString()) - ); + ); - if (ui.dateFormatComboBox->currentIndex() == -1) { - ui.dateFormatComboBox->addItem(s->value("options/naming/dateFormat", "yyyy-MM-dd").toString()); - ui.dateFormatComboBox->setCurrentIndex(ui.dateFormatComboBox->count()-1); - } + if (ui.dateFormatComboBox->currentIndex() == -1) { + ui.dateFormatComboBox->addItem(s->value("options/naming/dateFormat", "yyyy-MM-dd").toString()); + ui.dateFormatComboBox->setCurrentIndex(ui.dateFormatComboBox->count() - 1); + } - ui.leadingZerosSpinBox->setValue(s->value("options/naming/leadingZeros", 0).toInt()); + ui.leadingZerosSpinBox->setValue(s->value("options/naming/leadingZeros", 0).toInt()); - // Signals/Slots - connect(ui.buttonBox , SIGNAL(accepted()), this, SLOT(saveSettings())); - connect(ui.dateHelpLabel, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString))); + // Signals/Slots + connect(ui.buttonBox , SIGNAL(accepted()), this, SLOT(saveSettings())); + connect(ui.dateHelpLabel, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString))); - // Stack & window size adjustments - ui.stack->setCurrentIndex((int)naming); - ui.stack->currentWidget()->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + // Stack & window size adjustments + ui.stack->setCurrentIndex((int)naming); + ui.stack->currentWidget()->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - resize(minimumSizeHint()); + resize(minimumSizeHint()); } void NamingDialog::openUrl(QString url) { - QDesktopServices::openUrl(QUrl(url)); + QDesktopServices::openUrl(QUrl(url)); } void NamingDialog::saveSettings() { - QSettings *s = ScreenshotManager::instance()->settings(); - s->setValue("options/flip" , ui.flipNamingCheckBox->isChecked()); - s->setValue("options/naming/dateFormat" , ui.dateFormatComboBox->currentText()); - s->setValue("options/naming/leadingZeros", ui.leadingZerosSpinBox->value()); + QSettings *s = ScreenshotManager::instance()->settings(); + s->setValue("options/flip" , ui.flipNamingCheckBox->isChecked()); + s->setValue("options/naming/dateFormat" , ui.dateFormatComboBox->currentText()); + s->setValue("options/naming/leadingZeros", ui.leadingZerosSpinBox->value()); } bool NamingDialog::eventFilter(QObject *object, QEvent *event) { - if (event->type() == QEvent::KeyPress - && object == ui.dateFormatComboBox) - { - QKeyEvent *keyEvent = (QKeyEvent*)(event); - if (QRegExp("[?:\\\\/*\"<>|]").exactMatch(keyEvent->text())) { - event->ignore(); - return true; + if (event->type() == QEvent::KeyPress + && object == ui.dateFormatComboBox) { + QKeyEvent *keyEvent = (QKeyEvent *)(event); + if (QRegExp("[?:\\\\/*\"<>|]").exactMatch(keyEvent->text())) { + event->ignore(); + return true; + } } - } - return QDialog::eventFilter(object, event); + return QDialog::eventFilter(object, event); } diff --git a/dialogs/optionsdialog.cpp b/dialogs/optionsdialog.cpp index 4dc3db4..31e7582 100644 --- a/dialogs/optionsdialog.cpp +++ b/dialogs/optionsdialog.cpp @@ -33,7 +33,7 @@ #include #ifdef Q_OS_WIN - #include + #include #endif #include "optionsdialog.h" @@ -46,268 +46,271 @@ #include "../updater/updater.h" OptionsDialog::OptionsDialog(QWidget *parent) : - QDialog(parent) + QDialog(parent) { - ui.setupUi(this); - setModal(true); + ui.setupUi(this); + setModal(true); #if defined(Q_OS_LINUX) - // KDE-specific style tweaks. - if (qApp->style()->objectName() == "oxygen") { - ui.browsePushButton->setMaximumWidth(30); - ui.namingOptionsButton->setMaximumWidth(30); - - ui.fileGroupBox->setFlat(false); - ui.startupGroupBox->setFlat(false); - ui.capturesGroupBox->setFlat(false); - ui.controlGroupBox->setFlat(false); - ui.interfaceGroupBox->setFlat(false); - ui.screenshotsGroupBox->setFlat(false); - ui.previewGroupBox->setFlat(false); - ui.updaterGroupBox->setFlat(false); - ui.historyGroupBox->setFlat(false); - ui.clipboardGroupBox->setFlat(false); - - ui.optionsTab->layout()->setContentsMargins(0, 0, 6, 0); - ui.aboutTab->layout()->setMargin(8); - } + // KDE-specific style tweaks. + if (qApp->style()->objectName() == "oxygen") { + ui.browsePushButton->setMaximumWidth(30); + ui.namingOptionsButton->setMaximumWidth(30); + + ui.fileGroupBox->setFlat(false); + ui.startupGroupBox->setFlat(false); + ui.capturesGroupBox->setFlat(false); + ui.controlGroupBox->setFlat(false); + ui.interfaceGroupBox->setFlat(false); + ui.screenshotsGroupBox->setFlat(false); + ui.previewGroupBox->setFlat(false); + ui.updaterGroupBox->setFlat(false); + ui.historyGroupBox->setFlat(false); + ui.clipboardGroupBox->setFlat(false); + + ui.optionsTab->layout()->setContentsMargins(0, 0, 6, 0); + ui.aboutTab->layout()->setMargin(8); + } #endif - QTimer::singleShot(0, this, SLOT(init())); - QTimer::singleShot(1, this, SLOT(loadSettings())); + QTimer::singleShot(0, this, SLOT(init())); + QTimer::singleShot(1, this, SLOT(loadSettings())); } void OptionsDialog::accepted() { - if (hotkeyCollision()) { - QMessageBox::critical(this, tr("Hotkey conflict"), tr("You have assigned the same hotkeys to more than one action.")); - return; - } - - if (ui.prefixLineEdit->text().contains(QRegExp("[?:\\\\/*\"<>|]"))) { - QMessageBox::critical(this, tr("Filename character error"), tr("The filename can't contain any of the following characters: ? : \\ / * \" < > |")); - return; - } - - if (!ui.fileGroupBox->isChecked() && !ui.clipboardCheckBox->isChecked()) { - QMessageBox::critical(this, tr("Final Destination"), tr("You can't take screenshots unless you enable either file saving or the clipboard.")); - return; - } - - saveSettings(); - accept(); + if (hotkeyCollision()) { + QMessageBox::critical(this, tr("Hotkey conflict"), tr("You have assigned the same hotkeys to more than one action.")); + return; + } + + if (ui.prefixLineEdit->text().contains(QRegExp("[?:\\\\/*\"<>|]"))) { + QMessageBox::critical(this, tr("Filename character error"), tr("The filename can't contain any of the following characters: ? : \\ / * \" < > |")); + return; + } + + if (!ui.fileGroupBox->isChecked() && !ui.clipboardCheckBox->isChecked()) { + QMessageBox::critical(this, tr("Final Destination"), tr("You can't take screenshots unless you enable either file saving or the clipboard.")); + return; + } + + saveSettings(); + accept(); } void OptionsDialog::checkUpdatesNow() { - Updater updater; - updater.checkWithFeedback(); + Updater updater; + updater.checkWithFeedback(); } void OptionsDialog::exportSettings() { - QString exportFileName = QFileDialog::getSaveFileName(this, - tr("Export Settings"), - QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + QDir::separator() + "config.ini", - tr("Lightscreen Settings (*.ini)")); + QString exportFileName = QFileDialog::getSaveFileName(this, + tr("Export Settings"), + QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + QDir::separator() + "config.ini", + tr("Lightscreen Settings (*.ini)")); - if (exportFileName.isEmpty()) - return; + if (exportFileName.isEmpty()) { + return; + } - if (QFile::exists(exportFileName)) { - QFile::remove(exportFileName); - } + if (QFile::exists(exportFileName)) { + QFile::remove(exportFileName); + } - QSettings exportedSettings(exportFileName, QSettings::IniFormat); + QSettings exportedSettings(exportFileName, QSettings::IniFormat); - foreach(const QString &key, settings()->allKeys()) { - exportedSettings.setValue(key, settings()->value(key)); - } + foreach (const QString &key, settings()->allKeys()) { + exportedSettings.setValue(key, settings()->value(key)); + } } void OptionsDialog::imgurAuthorize() -{ // TODO: Tuck this into Uploader - if (ui.imgurAuthButton->text() == tr("Deauthorize")) - { - ui.imgurAuthUserLabel->setText(tr("none")); - ui.imgurAuthButton->setText(tr("Authorize")); +{ + // TODO: Tuck this into Uploader + if (ui.imgurAuthButton->text() == tr("Deauthorize")) { + ui.imgurAuthUserLabel->setText(tr("none")); + ui.imgurAuthButton->setText(tr("Authorize")); - ui.imgurRefreshAlbumButton->setEnabled(false); - ui.imgurAlbumComboBox->setEnabled(false); - ui.imgurAlbumComboBox->clear(); - ui.imgurAlbumComboBox->addItem(tr("- None -")); - - settings()->setValue("upload/imgur/access_token", ""); - settings()->setValue("upload/imgur/refresh_token", ""); - settings()->setValue("upload/imgur/account_username", ""); - settings()->setValue("upload/imgur/expires_in", 0); - return; - } - - openUrl("https://api.imgur.com/oauth2/authorize?client_id=3ebe94c791445c1&response_type=pin"); //TODO: get the client-id from somewhere? - - bool ok; - QString pin = QInputDialog::getText(this, tr("Imgur Authorization"), - tr("PIN:"), QLineEdit::Normal, - "", &ok); - if (ok) { - QByteArray parameters; - parameters.append(QString("client_id=").toUtf8()); - parameters.append(QUrl::toPercentEncoding("3ebe94c791445c1")); - parameters.append(QString("&client_secret=").toUtf8()); - parameters.append(QUrl::toPercentEncoding("0546b05d6a80b2092dcea86c57b792c9c9faebf0")); // TODO: TA.png - parameters.append(QString("&grant_type=pin").toUtf8()); - parameters.append(QString("&pin=").toUtf8()); - parameters.append(QUrl::toPercentEncoding(pin)); - - QNetworkRequest request(QUrl("https://api.imgur.com/oauth2/token")); - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - - QNetworkReply* reply = Uploader::instance()->nam()->post(request, parameters); - connect(reply, SIGNAL(finished()), this, SLOT(imgurToken())); - - ui.imgurAuthButton->setText(tr("Authorizing..")); - ui.imgurAuthButton->setEnabled(false); - } + ui.imgurRefreshAlbumButton->setEnabled(false); + ui.imgurAlbumComboBox->setEnabled(false); + ui.imgurAlbumComboBox->clear(); + ui.imgurAlbumComboBox->addItem(tr("- None -")); + + settings()->setValue("upload/imgur/access_token", ""); + settings()->setValue("upload/imgur/refresh_token", ""); + settings()->setValue("upload/imgur/account_username", ""); + settings()->setValue("upload/imgur/expires_in", 0); + return; + } + + openUrl("https://api.imgur.com/oauth2/authorize?client_id=3ebe94c791445c1&response_type=pin"); //TODO: get the client-id from somewhere? + + bool ok; + QString pin = QInputDialog::getText(this, tr("Imgur Authorization"), + tr("PIN:"), QLineEdit::Normal, + "", &ok); + if (ok) { + QByteArray parameters; + parameters.append(QString("client_id=").toUtf8()); + parameters.append(QUrl::toPercentEncoding("3ebe94c791445c1")); + parameters.append(QString("&client_secret=").toUtf8()); + parameters.append(QUrl::toPercentEncoding("0546b05d6a80b2092dcea86c57b792c9c9faebf0")); // TODO: TA.png + parameters.append(QString("&grant_type=pin").toUtf8()); + parameters.append(QString("&pin=").toUtf8()); + parameters.append(QUrl::toPercentEncoding(pin)); + + QNetworkRequest request(QUrl("https://api.imgur.com/oauth2/token")); + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + + QNetworkReply *reply = Uploader::instance()->nam()->post(request, parameters); + connect(reply, SIGNAL(finished()), this, SLOT(imgurToken())); + + ui.imgurAuthButton->setText(tr("Authorizing..")); + ui.imgurAuthButton->setEnabled(false); + } } void OptionsDialog::imgurToken() { - QNetworkReply* reply = qobject_cast(sender()); - ui.imgurAuthButton->setEnabled(true); + QNetworkReply *reply = qobject_cast(sender()); + ui.imgurAuthButton->setEnabled(true); - if (reply->error() != QNetworkReply::NoError) { - QMessageBox::critical(this, tr("Imgur Authorization Error"), tr("There's been an error authorizing your account with Imgur, please try again.")); - ui.imgurAuthButton->setText(tr("Authorize")); - return; - } + if (reply->error() != QNetworkReply::NoError) { + QMessageBox::critical(this, tr("Imgur Authorization Error"), tr("There's been an error authorizing your account with Imgur, please try again.")); + ui.imgurAuthButton->setText(tr("Authorize")); + return; + } - QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object(); + QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object(); - settings()->setValue("upload/imgur/access_token" , imgurResponse.value("access_token").toString()); - settings()->setValue("upload/imgur/refresh_token" , imgurResponse.value("refresh_token").toString()); - settings()->setValue("upload/imgur/account_username", imgurResponse.value("account_username").toString()); - settings()->setValue("upload/imgur/expires_in" , imgurResponse.value("expires_in").toInt()); - settings()->sync(); + settings()->setValue("upload/imgur/access_token" , imgurResponse.value("access_token").toString()); + settings()->setValue("upload/imgur/refresh_token" , imgurResponse.value("refresh_token").toString()); + settings()->setValue("upload/imgur/account_username", imgurResponse.value("account_username").toString()); + settings()->setValue("upload/imgur/expires_in" , imgurResponse.value("expires_in").toInt()); + settings()->sync(); - ui.imgurAuthUserLabel->setText("" + imgurResponse.value("account_username").toString() + ""); - ui.imgurAuthButton->setText(tr("Deauthorize")); + ui.imgurAuthUserLabel->setText("" + imgurResponse.value("account_username").toString() + ""); + ui.imgurAuthButton->setText(tr("Deauthorize")); - QTimer::singleShot(0, this, &OptionsDialog::imgurRequestAlbumList); + QTimer::singleShot(0, this, &OptionsDialog::imgurRequestAlbumList); } void OptionsDialog::importSettings() { - QString importFileName = QFileDialog::getOpenFileName(this, - tr("Import Settings"), - QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), - tr("Lightscreen Settings (*.ini)")); + QString importFileName = QFileDialog::getOpenFileName(this, + tr("Import Settings"), + QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), + tr("Lightscreen Settings (*.ini)")); - QSettings importedSettings(importFileName, QSettings::IniFormat); + QSettings importedSettings(importFileName, QSettings::IniFormat); - saveSettings(); + saveSettings(); - foreach(const QString &key, importedSettings.allKeys()) { - if (settings()->contains(key)) - settings()->setValue(key, importedSettings.value(key)); - } + foreach (const QString &key, importedSettings.allKeys()) { + if (settings()->contains(key)) { + settings()->setValue(key, importedSettings.value(key)); + } + } - loadSettings(); + loadSettings(); } -void OptionsDialog::imgurRequestAlbumList() { +void OptionsDialog::imgurRequestAlbumList() +{ - QString username = settings()->value("upload/imgur/account_username").toString(); + QString username = settings()->value("upload/imgur/account_username").toString(); - if (username.isEmpty()) { - return; - } + if (username.isEmpty()) { + return; + } - ui.imgurRefreshAlbumButton->setEnabled(true); - ui.imgurAlbumComboBox->clear(); - ui.imgurAlbumComboBox->setEnabled(false); - ui.imgurAlbumComboBox->addItem(tr("Loading album data...")); + ui.imgurRefreshAlbumButton->setEnabled(true); + ui.imgurAlbumComboBox->clear(); + ui.imgurAlbumComboBox->setEnabled(false); + ui.imgurAlbumComboBox->addItem(tr("Loading album data...")); - QNetworkRequest request(QUrl("https://api.imgur.com/3/account/" + username + "/albums/")); - request.setRawHeader("Authorization", QByteArray("Bearer ") + settings()->value("upload/imgur/access_token").toByteArray()); + QNetworkRequest request(QUrl("https://api.imgur.com/3/account/" + username + "/albums/")); + request.setRawHeader("Authorization", QByteArray("Bearer ") + settings()->value("upload/imgur/access_token").toByteArray()); - QNetworkReply* reply = Uploader::instance()->nam()->get(request); - connect(reply, SIGNAL(finished()), this, SLOT(imgurAlbumList())); + QNetworkReply *reply = Uploader::instance()->nam()->get(request); + connect(reply, SIGNAL(finished()), this, SLOT(imgurAlbumList())); } -void OptionsDialog::imgurAlbumList() { - QNetworkReply* reply = qobject_cast(sender()); +void OptionsDialog::imgurAlbumList() +{ + QNetworkReply *reply = qobject_cast(sender()); + + if (reply->error() != QNetworkReply::NoError) { + if (reply->error() == QNetworkReply::ContentOperationNotPermittedError || + reply->error() == QNetworkReply::AuthenticationRequiredError) { + Uploader::instance()->imgurAuthRefresh(); + } - if (reply->error() != QNetworkReply::NoError) { - if (reply->error() == QNetworkReply::ContentOperationNotPermittedError || - reply->error() == QNetworkReply::AuthenticationRequiredError) { - Uploader::instance()->imgurAuthRefresh(); + ui.imgurAlbumComboBox->addItem(tr("Loading failed :(")); + return; } - ui.imgurAlbumComboBox->addItem(tr("Loading failed :(")); - return; - } - - QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object(); + QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object(); - if (imgurResponse["success"].toBool() != true || imgurResponse["status"].toInt() != 200) { - return; - } + if (imgurResponse["success"].toBool() != true || imgurResponse["status"].toInt() != 200) { + return; + } - QJsonArray albumList = imgurResponse["data"].toArray(); + QJsonArray albumList = imgurResponse["data"].toArray(); - ui.imgurAlbumComboBox->clear(); - ui.imgurAlbumComboBox->setEnabled(true); - ui.imgurAlbumComboBox->addItem(tr("- None -"), ""); - ui.imgurRefreshAlbumButton->setEnabled(true); + ui.imgurAlbumComboBox->clear(); + ui.imgurAlbumComboBox->setEnabled(true); + ui.imgurAlbumComboBox->addItem(tr("- None -"), ""); + ui.imgurRefreshAlbumButton->setEnabled(true); - int settingsIndex = 0; + int settingsIndex = 0; - foreach (const QJsonValue &albumValue, albumList) { - QJsonObject album = albumValue.toObject(); - ui.imgurAlbumComboBox->addItem(album["title"].toString(), album["id"].toString()); + foreach (const QJsonValue &albumValue, albumList) { + QJsonObject album = albumValue.toObject(); + ui.imgurAlbumComboBox->addItem(album["title"].toString(), album["id"].toString()); - if (album["id"].toString() == settings()->value("upload/imgur/album").toString()) { - settingsIndex = ui.imgurAlbumComboBox->count() - 1; - } - } + if (album["id"].toString() == settings()->value("upload/imgur/album").toString()) { + settingsIndex = ui.imgurAlbumComboBox->count() - 1; + } + } - ui.imgurAlbumComboBox->setCurrentIndex(settingsIndex); + ui.imgurAlbumComboBox->setCurrentIndex(settingsIndex); } void OptionsDialog::loadSettings() { - settings()->sync(); - setUpdatesEnabled(false); + settings()->sync(); + setUpdatesEnabled(false); - if (!settings()->contains("file/format")) { - // If there are no settings, get rid of the cancel button so that the user is forced to save them - ui.buttonBox->clear(); - ui.buttonBox->addButton(QDialogButtonBox::Ok); - } + if (!settings()->contains("file/format")) { + // If there are no settings, get rid of the cancel button so that the user is forced to save them + ui.buttonBox->clear(); + ui.buttonBox->addButton(QDialogButtonBox::Ok); + } - ui.startupCheckBox->toggle(); - ui.trayCheckBox->toggle(); - ui.previewAutocloseCheckBox->toggle(); + ui.startupCheckBox->toggle(); + ui.trayCheckBox->toggle(); + ui.previewAutocloseCheckBox->toggle(); - QString targetDefault; + QString targetDefault; - if (ScreenshotManager::instance()->portableMode()) { - targetDefault = tr("Screenshots"); - } - else { - targetDefault = os::getDocumentsPath() + QDir::separator() + tr("Screenshots"); - } + if (ScreenshotManager::instance()->portableMode()) { + targetDefault = tr("Screenshots"); + } else { + targetDefault = os::getDocumentsPath() + QDir::separator() + tr("Screenshots"); + } - settings()->beginGroup("file"); + settings()->beginGroup("file"); ui.formatComboBox->setCurrentIndex(settings()->value("format", 1).toInt()); ui.prefixLineEdit->setText(settings()->value("prefix", tr("screenshot.")).toString()); ui.namingComboBox->setCurrentIndex(settings()->value("naming", 0).toInt()); ui.targetLineEdit->setText(settings()->value("target", targetDefault).toString()); ui.fileGroupBox->setChecked(settings()->value("enabled", true).toBool()); - settings()->endGroup(); + settings()->endGroup(); - settings()->beginGroup("options"); + settings()->beginGroup("options"); ui.startupCheckBox->setChecked(settings()->value("startup", false).toBool()); ui.startupHideCheckBox->setChecked(settings()->value("startupHide", true).toBool()); ui.hideCheckBox->setChecked(settings()->value("hide", true).toBool()); @@ -344,14 +347,14 @@ void OptionsDialog::loadSettings() #ifdef Q_OS_WIN if (!QFile::exists(qApp->applicationDirPath() + QDir::separator() + "optipng.exe")) { - ui.optiPngCheckBox->setEnabled(false); - ui.optiPngLabel->setText("optipng.exe not found"); + ui.optiPngCheckBox->setEnabled(false); + ui.optiPngLabel->setText("optipng.exe not found"); } #elif defined(Q_OS_LINUX) if (!QProcess::startDetached("optipng")) { - ui.optiPngCheckBox->setChecked(false); - ui.optiPngCheckBox->setEnabled(false); - ui.optiPngLabel->setText(tr("Install 'OptiPNG'")); + ui.optiPngCheckBox->setChecked(false); + ui.optiPngCheckBox->setEnabled(false); + ui.optiPngLabel->setText(tr("Install 'OptiPNG'")); } //TODO: Sound cue support on Linux @@ -362,9 +365,9 @@ void OptionsDialog::loadSettings() ui.cursorCheckBox->setVisible(false); ui.cursorCheckBox->setChecked(false); #endif - settings()->endGroup(); + settings()->endGroup(); - settings()->beginGroup("actions"); + settings()->beginGroup("actions"); // This toggle is for the first run ui.screenCheckBox->toggle(); ui.areaCheckBox->toggle(); @@ -374,84 +377,82 @@ void OptionsDialog::loadSettings() ui.directoryCheckBox->toggle(); settings()->beginGroup("screen"); - ui.screenCheckBox->setChecked(settings()->value("enabled", true).toBool()); - ui.screenHotkeyWidget->setHotkey(settings()->value("hotkey", "Print").toString()); + ui.screenCheckBox->setChecked(settings()->value("enabled", true).toBool()); + ui.screenHotkeyWidget->setHotkey(settings()->value("hotkey", "Print").toString()); settings()->endGroup(); settings()->beginGroup("area"); - ui.areaCheckBox->setChecked(settings()->value("enabled").toBool()); - ui.areaHotkeyWidget->setHotkey(settings()->value("hotkey", "Ctrl+Print").toString()); + ui.areaCheckBox->setChecked(settings()->value("enabled").toBool()); + ui.areaHotkeyWidget->setHotkey(settings()->value("hotkey", "Ctrl+Print").toString()); settings()->endGroup(); settings()->beginGroup("window"); - ui.windowCheckBox->setChecked(settings()->value("enabled").toBool()); - ui.windowHotkeyWidget->setHotkey(settings()->value("hotkey", "Alt+Print").toString()); + ui.windowCheckBox->setChecked(settings()->value("enabled").toBool()); + ui.windowHotkeyWidget->setHotkey(settings()->value("hotkey", "Alt+Print").toString()); settings()->endGroup(); settings()->beginGroup("windowPicker"); - ui.windowPickerCheckBox->setChecked(settings()->value("enabled").toBool()); - ui.windowPickerHotkeyWidget->setHotkey(settings()->value("hotkey", "Ctrl+Alt+Print").toString()); + ui.windowPickerCheckBox->setChecked(settings()->value("enabled").toBool()); + ui.windowPickerHotkeyWidget->setHotkey(settings()->value("hotkey", "Ctrl+Alt+Print").toString()); settings()->endGroup(); settings()->beginGroup("open"); - ui.openCheckBox->setChecked(settings()->value("enabled").toBool()); - ui.openHotkeyWidget->setHotkey(settings()->value("hotkey", "Ctrl+PgUp").toString()); + ui.openCheckBox->setChecked(settings()->value("enabled").toBool()); + ui.openHotkeyWidget->setHotkey(settings()->value("hotkey", "Ctrl+PgUp").toString()); settings()->endGroup(); settings()->beginGroup("directory"); - ui.directoryCheckBox->setChecked(settings()->value("enabled").toBool()); - ui.directoryHotkeyWidget->setHotkey(settings()->value("hotkey", "Ctrl+PgDown").toString()); + ui.directoryCheckBox->setChecked(settings()->value("enabled").toBool()); + ui.directoryHotkeyWidget->setHotkey(settings()->value("hotkey", "Ctrl+PgDown").toString()); + settings()->endGroup(); settings()->endGroup(); - settings()->endGroup(); - settings()->beginGroup("upload"); + settings()->beginGroup("upload"); //ui.serviceComboBox->setCurrentIndex(settings()->value("service").toInt()); settings()->beginGroup("imgur"); - ui.imgurAuthGroupBox->setChecked(!settings()->value("anonymous", true).toBool()); - ui.imgurAuthUserLabel->setText(settings()->value("account_username", tr("none")).toString()); + ui.imgurAuthGroupBox->setChecked(!settings()->value("anonymous", true).toBool()); + ui.imgurAuthUserLabel->setText(settings()->value("account_username", tr("none")).toString()); - if (settings()->value("account_username").toString().isEmpty()) { + if (settings()->value("account_username").toString().isEmpty()) { ui.imgurAuthUserLabel->setText(tr("none")); ui.imgurAlbumComboBox->setEnabled(false); ui.imgurRefreshAlbumButton->setEnabled(false); - } - else { + } else { ui.imgurAuthButton->setText(tr("Deauthorize")); ui.imgurAuthUserLabel->setText("" + ui.imgurAuthUserLabel->text() + ""); ui.imgurRefreshAlbumButton->setEnabled(true); - } + } + settings()->endGroup(); settings()->endGroup(); - settings()->endGroup(); - QTimer::singleShot(0, this, SLOT(updatePreview())); - QTimer::singleShot(1, this, SLOT(imgurRequestAlbumList())); + QTimer::singleShot(0, this, SLOT(updatePreview())); + QTimer::singleShot(1, this, SLOT(imgurRequestAlbumList())); - setEnabled(true); - setUpdatesEnabled(true); + setEnabled(true); + setUpdatesEnabled(true); } void OptionsDialog::openUrl(QString url) { - if (url == "#aboutqt") { - qApp->aboutQt(); - } - else { - QDesktopServices::openUrl(QUrl(url)); - } + if (url == "#aboutqt") { + qApp->aboutQt(); + } else { + QDesktopServices::openUrl(QUrl(url)); + } } void OptionsDialog::saveSettings() { - settings()->beginGroup("file"); + settings()->beginGroup("file"); settings()->setValue("format", ui.formatComboBox->currentIndex()); settings()->setValue("prefix", ui.prefixLineEdit->text()); settings()->setValue("naming", ui.namingComboBox->currentIndex()); settings()->setValue("target", ui.targetLineEdit->text()); settings()->setValue("enabled", ui.fileGroupBox->isChecked()); - settings()->endGroup(); + settings()->endGroup(); - settings()->beginGroup("options"); + settings()->beginGroup("options"); settings()->setValue("startup", ui.startupCheckBox->isChecked()); settings()->setValue("startupHide", ui.startupHideCheckBox->isChecked()); settings()->setValue("hide", ui.hideCheckBox->isChecked()); @@ -485,76 +486,77 @@ void OptionsDialog::saveSettings() //Upload settings()->setValue("uploadAuto", ui.uploadCheckBox->isChecked()); - settings()->endGroup(); + settings()->endGroup(); - settings()->beginGroup("actions"); + settings()->beginGroup("actions"); settings()->beginGroup("screen"); - settings()->setValue("enabled", ui.screenCheckBox->isChecked()); - settings()->setValue("hotkey" , ui.screenHotkeyWidget->hotkey()); + settings()->setValue("enabled", ui.screenCheckBox->isChecked()); + settings()->setValue("hotkey" , ui.screenHotkeyWidget->hotkey()); settings()->endGroup(); settings()->beginGroup("area"); - settings()->setValue("enabled", ui.areaCheckBox->isChecked()); - settings()->setValue("hotkey" , ui.areaHotkeyWidget->hotkey()); + settings()->setValue("enabled", ui.areaCheckBox->isChecked()); + settings()->setValue("hotkey" , ui.areaHotkeyWidget->hotkey()); settings()->endGroup(); settings()->beginGroup("window"); - settings()->setValue("enabled", ui.windowCheckBox->isChecked()); - settings()->setValue("hotkey" , ui.windowHotkeyWidget->hotkey()); + settings()->setValue("enabled", ui.windowCheckBox->isChecked()); + settings()->setValue("hotkey" , ui.windowHotkeyWidget->hotkey()); settings()->endGroup(); settings()->beginGroup("windowPicker"); - settings()->setValue("enabled", ui.windowPickerCheckBox->isChecked()); - settings()->setValue("hotkey" , ui.windowPickerHotkeyWidget->hotkey()); + settings()->setValue("enabled", ui.windowPickerCheckBox->isChecked()); + settings()->setValue("hotkey" , ui.windowPickerHotkeyWidget->hotkey()); settings()->endGroup(); settings()->beginGroup("open"); - settings()->setValue("enabled", ui.openCheckBox->isChecked()); - settings()->setValue("hotkey" , ui.openHotkeyWidget->hotkey()); + settings()->setValue("enabled", ui.openCheckBox->isChecked()); + settings()->setValue("hotkey" , ui.openHotkeyWidget->hotkey()); settings()->endGroup(); settings()->beginGroup("directory"); - settings()->setValue("enabled", ui.directoryCheckBox->isChecked()); - settings()->setValue("hotkey" , ui.directoryHotkeyWidget->hotkey()); + settings()->setValue("enabled", ui.directoryCheckBox->isChecked()); + settings()->setValue("hotkey" , ui.directoryHotkeyWidget->hotkey()); settings()->endGroup(); - settings()->endGroup(); + settings()->endGroup(); - settings()->beginGroup("upload"); + settings()->beginGroup("upload"); //settings()->setValue("service", ui.serviceComboBox->currentIndex()); settings()->beginGroup("imgur"); - settings()->setValue("anonymous",!ui.imgurAuthGroupBox->isChecked()); - settings()->setValue("album" , ui.imgurAlbumComboBox->property("currentData").toString()); + settings()->setValue("anonymous", !ui.imgurAuthGroupBox->isChecked()); + settings()->setValue("album" , ui.imgurAlbumComboBox->property("currentData").toString()); settings()->endGroup(); - settings()->endGroup(); + settings()->endGroup(); } void OptionsDialog::updatePreview() { - Screenshot::NamingOptions options; + Screenshot::NamingOptions options; - options.naming = (Screenshot::Naming) ui.namingComboBox->currentIndex(); - options.flip = settings()->value("options/flip", false).toBool(); - options.leadingZeros = settings()->value("options/naming/leadingZeros", 0).toInt(); - options.dateFormat = settings()->value("options/naming/dateFormat", "yyyy-MM-dd").toString(); + options.naming = (Screenshot::Naming) ui.namingComboBox->currentIndex(); + options.flip = settings()->value("options/flip", false).toBool(); + options.leadingZeros = settings()->value("options/naming/leadingZeros", 0).toInt(); + options.dateFormat = settings()->value("options/naming/dateFormat", "yyyy-MM-dd").toString(); - if (ui.fileGroupBox->isChecked()) // Only change the naming button when file options are enabled. - ui.namingOptionsButton->setDisabled((options.naming == Screenshot::Empty)); + if (ui.fileGroupBox->isChecked()) { // Only change the naming button when file options are enabled. + ui.namingOptionsButton->setDisabled((options.naming == Screenshot::Empty)); + } - QString preview = Screenshot::getName(options, - ui.prefixLineEdit->text(), - QDir(ui.targetLineEdit->text())); + QString preview = Screenshot::getName(options, + ui.prefixLineEdit->text(), + QDir(ui.targetLineEdit->text())); - preview = QString("%1.%2").arg(preview).arg(ui.formatComboBox->currentText().toLower()); + preview = QString("%1.%2").arg(preview).arg(ui.formatComboBox->currentText().toLower()); - if (preview.length() >= 40) { - preview.truncate(37); - preview.append("..."); - } + if (preview.length() >= 40) { + preview.truncate(37); + preview.append("..."); + } - ui.previewLabel->setText(preview); + ui.previewLabel->setText(preview); } void OptionsDialog::viewHistory() @@ -565,38 +567,36 @@ void OptionsDialog::viewHistory() // -bool OptionsDialog::event(QEvent* event) +bool OptionsDialog::event(QEvent *event) { - if (event->type() == QEvent::Close || event->type() == QEvent::Hide) { - settings()->setValue("geometry/optionsDialog", saveGeometry()); - - if (!settings()->contains("file/format")) { - // I'm afraid I can't let you do that, Dave. - event->ignore(); - return false; + if (event->type() == QEvent::Close || event->type() == QEvent::Hide) { + settings()->setValue("geometry/optionsDialog", saveGeometry()); + + if (!settings()->contains("file/format")) { + // I'm afraid I can't let you do that, Dave. + event->ignore(); + return false; + } + } else if (event->type() == QEvent::Show) { + restoreGeometry(settings()->value("geometry/optionsDialog").toByteArray()); } - } - else if (event->type() == QEvent::Show) - { - restoreGeometry(settings()->value("geometry/optionsDialog").toByteArray()); - } - return QDialog::event(event); + return QDialog::event(event); } #ifdef Q_OS_WIN // Qt does not send the print screen key as a regular QKeyPress event, so we must use the Windows API bool OptionsDialog::nativeEvent(const QByteArray &eventType, void *message, long *result) { - if (eventType == "windows_generic_MSG") { - MSG* m = static_cast(message); + if (eventType == "windows_generic_MSG") { + MSG *m = static_cast(message); - if ((m->message == WM_KEYUP || m->message == WM_SYSKEYUP) && m->wParam == VK_SNAPSHOT) { - qApp->postEvent(qApp->focusWidget(), new QKeyEvent(QEvent::KeyPress, Qt::Key_Print, qApp->queryKeyboardModifiers())); + if ((m->message == WM_KEYUP || m->message == WM_SYSKEYUP) && m->wParam == VK_SNAPSHOT) { + qApp->postEvent(qApp->focusWidget(), new QKeyEvent(QEvent::KeyPress, Qt::Key_Print, qApp->queryKeyboardModifiers())); + } } - } - return QDialog::nativeEvent(eventType, message, result); + return QDialog::nativeEvent(eventType, message, result); } #endif @@ -604,296 +604,324 @@ bool OptionsDialog::nativeEvent(const QByteArray &eventType, void *message, long void OptionsDialog::browse() { - QString fileName = QFileDialog::getExistingDirectory(this, - tr("Select where you want to save the screenshots"), - ui.targetLineEdit->text()); + QString fileName = QFileDialog::getExistingDirectory(this, + tr("Select where you want to save the screenshots"), + ui.targetLineEdit->text()); - if (fileName.isEmpty()) - return; + if (fileName.isEmpty()) { + return; + } - ui.targetLineEdit->setText(fileName); - updatePreview(); + ui.targetLineEdit->setText(fileName); + updatePreview(); } void OptionsDialog::dialogButtonClicked(QAbstractButton *button) { - if (ui.buttonBox->buttonRole(button) == QDialogButtonBox::ResetRole) { - QPushButton *pb = qobject_cast(button); - pb->showMenu(); - } + if (ui.buttonBox->buttonRole(button) == QDialogButtonBox::ResetRole) { + QPushButton *pb = qobject_cast(button); + pb->showMenu(); + } } void OptionsDialog::restoreDefaults() { - QMessageBox msgBox; - msgBox.setWindowTitle(tr("Lightscreen - Restore Default Options")); - msgBox.setText(tr("Restoring the default options will cause you to lose all of your current configuration.")); - msgBox.setIcon(QMessageBox::Warning); + QMessageBox msgBox; + msgBox.setWindowTitle(tr("Lightscreen - Restore Default Options")); + msgBox.setText(tr("Restoring the default options will cause you to lose all of your current configuration.")); + msgBox.setIcon(QMessageBox::Warning); - msgBox.addButton(tr("Restore"), QMessageBox::ActionRole); - QPushButton *dontRestoreButton = msgBox.addButton(tr("Don't Restore"), QMessageBox::ActionRole); + msgBox.addButton(tr("Restore"), QMessageBox::ActionRole); + QPushButton *dontRestoreButton = msgBox.addButton(tr("Don't Restore"), QMessageBox::ActionRole); - msgBox.setDefaultButton(dontRestoreButton); - msgBox.exec(); + msgBox.setDefaultButton(dontRestoreButton); + msgBox.exec(); - if (msgBox.clickedButton() == dontRestoreButton) - return; + if (msgBox.clickedButton() == dontRestoreButton) { + return; + } - settings()->clear(); - loadSettings(); + settings()->clear(); + loadSettings(); } void OptionsDialog::flipToggled(bool checked) { - setUpdatesEnabled(false); + setUpdatesEnabled(false); - ui.filenameLayout->removeWidget(ui.prefixLineEdit); - ui.filenameLayout->removeWidget(ui.namingComboBox); + ui.filenameLayout->removeWidget(ui.prefixLineEdit); + ui.filenameLayout->removeWidget(ui.namingComboBox); - if (checked) { - ui.filenameLayout->addWidget(ui.namingComboBox); - ui.filenameLayout->addWidget(ui.prefixLineEdit); - } - else { - ui.filenameLayout->addWidget(ui.prefixLineEdit); - ui.filenameLayout->addWidget(ui.namingComboBox); - } + if (checked) { + ui.filenameLayout->addWidget(ui.namingComboBox); + ui.filenameLayout->addWidget(ui.prefixLineEdit); + } else { + ui.filenameLayout->addWidget(ui.prefixLineEdit); + ui.filenameLayout->addWidget(ui.namingComboBox); + } - if (ui.prefixLineEdit->text() == tr("screenshot.") - && checked) - ui.prefixLineEdit->setText(tr(".screenshot")); + if (ui.prefixLineEdit->text() == tr("screenshot.") + && checked) { + ui.prefixLineEdit->setText(tr(".screenshot")); + } - if (ui.prefixLineEdit->text() == tr(".screenshot") - && !checked) - ui.prefixLineEdit->setText(tr("screenshot.")); + if (ui.prefixLineEdit->text() == tr(".screenshot") + && !checked) { + ui.prefixLineEdit->setText(tr("screenshot.")); + } - setUpdatesEnabled(true); // Avoids flicker + setUpdatesEnabled(true); // Avoids flicker } void OptionsDialog::init() { - // Make the scroll area share the Tab Widget background color - QPalette optionsPalette = ui.optionsScrollArea->palette(); - optionsPalette.setColor(QPalette::Window, ui.tabWidget->palette().color(QPalette::Base)); - ui.optionsScrollArea->setPalette(optionsPalette); - - ui.browsePushButton->setIcon(os::icon("folder")); - ui.namingOptionsButton->setIcon(os::icon("configure")); - - // Export/Import menu . - QMenu* optionsMenu = new QMenu(tr("Options")); - - QAction *exportAction = new QAction(tr("&Export.."), optionsMenu); - connect(exportAction, SIGNAL(triggered()), this, SLOT(exportSettings())); - - QAction *importAction = new QAction(tr("&Import.."), optionsMenu); - connect(importAction, SIGNAL(triggered()), this, SLOT(importSettings())); - - QAction *restoreAction = new QAction(tr("&Restore Defaults"), optionsMenu); - connect(restoreAction, SIGNAL(triggered()), this, SLOT(restoreDefaults())); - - optionsMenu->addAction(exportAction); - optionsMenu->addAction(importAction); - optionsMenu->addSeparator(); - optionsMenu->addAction(restoreAction); - - QPushButton *optionsButton = new QPushButton(tr("Options"), this); - optionsButton->setMenu(optionsMenu); - ui.buttonBox->addButton(optionsButton, QDialogButtonBox::ResetRole); - - // Set up the autocomplete for the directory. - QCompleter *completer = new QCompleter(this); - completer->setModel(new QDirModel(QStringList(), QDir::Dirs, QDir::Name, completer)); - ui.targetLineEdit->setCompleter(completer); - - // HotkeyWidget icons. - ui.screenHotkeyWidget->setIcon (os::icon("screen")); - ui.windowHotkeyWidget->setIcon (os::icon("window")); - ui.windowPickerHotkeyWidget->setIcon(os::icon("pickWindow")); - ui.areaHotkeyWidget->setIcon (os::icon("area")); - ui.openHotkeyWidget->setIcon (QIcon(":/icons/lightscreen.small")); - ui.directoryHotkeyWidget->setIcon (os::icon("folder")); - - // Version - ui.versionLabel->setText(tr("Version %1").arg(qApp->applicationVersion())); - - setEnabled(false); // We disable the widgets to prevent any user interaction until the settings have loaded. - - // - // Connections - // - - connect(Uploader::instance(), &Uploader::imgurAuthRefreshed, this, &OptionsDialog::imgurRequestAlbumList); - - connect(ui.buttonBox , SIGNAL(clicked(QAbstractButton*)), this , SLOT(dialogButtonClicked(QAbstractButton*))); - connect(ui.buttonBox , SIGNAL(accepted()) , this , SLOT(accepted())); - connect(ui.namingOptionsButton , SIGNAL(clicked()) , this , SLOT(namingOptions())); - - connect(ui.prefixLineEdit , SIGNAL(textEdited(QString)) , this , SLOT(updatePreview())); - connect(ui.formatComboBox , SIGNAL(currentIndexChanged(int)) , this , SLOT(updatePreview())); - connect(ui.namingComboBox , SIGNAL(currentIndexChanged(int)) , this , SLOT(updatePreview())); - - connect(ui.browsePushButton , SIGNAL(clicked()) , this , SLOT(browse())); - connect(ui.checkUpdatesPushButton , SIGNAL(clicked()) , this , SLOT(checkUpdatesNow())); - connect(ui.historyPushButton , SIGNAL(clicked()) , this , SLOT(viewHistory())); - connect(ui.imgurAuthButton , SIGNAL(clicked()) , this , SLOT(imgurAuthorize())); - connect(ui.imgurRefreshAlbumButton, SIGNAL(clicked()) , this , SLOT(imgurRequestAlbumList())); - - connect(ui.screenCheckBox , SIGNAL(toggled(bool)), ui.screenHotkeyWidget , SLOT(setEnabled(bool))); - connect(ui.areaCheckBox , SIGNAL(toggled(bool)), ui.areaHotkeyWidget , SLOT(setEnabled(bool))); - connect(ui.windowCheckBox , SIGNAL(toggled(bool)), ui.windowHotkeyWidget , SLOT(setEnabled(bool))); - connect(ui.windowPickerCheckBox, SIGNAL(toggled(bool)), ui.windowPickerHotkeyWidget, SLOT(setEnabled(bool))); - connect(ui.openCheckBox , SIGNAL(toggled(bool)), ui.openHotkeyWidget , SLOT(setEnabled(bool))); - connect(ui.directoryCheckBox , SIGNAL(toggled(bool)), ui.directoryHotkeyWidget, SLOT(setEnabled(bool))); - - // "Save as" disables the file target input field. - connect(ui.saveAsCheckBox , SIGNAL(toggled(bool)), ui.targetLineEdit , SLOT(setDisabled(bool))); - connect(ui.saveAsCheckBox , SIGNAL(toggled(bool)), ui.browsePushButton , SLOT(setDisabled(bool))); - connect(ui.saveAsCheckBox , SIGNAL(toggled(bool)), ui.directoryLabel , SLOT(setDisabled(bool))); - - connect(ui.startupCheckBox , SIGNAL(toggled(bool)), ui.startupHideCheckBox , SLOT(setEnabled(bool))); - connect(ui.qualitySlider , SIGNAL(valueChanged(int)), ui.qualityValueLabel, SLOT(setNum(int))); - connect(ui.trayCheckBox , SIGNAL(toggled(bool)), ui.messageCheckBox , SLOT(setEnabled(bool))); - - // Auto-upload disables the default action button in the previews. - connect(ui.uploadCheckBox , SIGNAL(toggled(bool)), ui.previewDefaultActionLabel , SLOT(setDisabled(bool))); - connect(ui.uploadCheckBox , SIGNAL(toggled(bool)), ui.previewDefaultActionComboBox, SLOT(setDisabled(bool))); - connect(ui.directoryCheckBox , SIGNAL(toggled(bool)), ui.directoryHotkeyWidget, SLOT(setEnabled(bool))); - - connect(ui.mainLabel , SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString))); - connect(ui.licenseAboutLabel, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString))); - connect(ui.linksLabel, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString))); + // Make the scroll area share the Tab Widget background color + QPalette optionsPalette = ui.optionsScrollArea->palette(); + optionsPalette.setColor(QPalette::Window, ui.tabWidget->palette().color(QPalette::Base)); + ui.optionsScrollArea->setPalette(optionsPalette); + + ui.browsePushButton->setIcon(os::icon("folder")); + ui.namingOptionsButton->setIcon(os::icon("configure")); + + // Export/Import menu . + QMenu *optionsMenu = new QMenu(tr("Options")); + + QAction *exportAction = new QAction(tr("&Export.."), optionsMenu); + connect(exportAction, SIGNAL(triggered()), this, SLOT(exportSettings())); + + QAction *importAction = new QAction(tr("&Import.."), optionsMenu); + connect(importAction, SIGNAL(triggered()), this, SLOT(importSettings())); + + QAction *restoreAction = new QAction(tr("&Restore Defaults"), optionsMenu); + connect(restoreAction, SIGNAL(triggered()), this, SLOT(restoreDefaults())); + + optionsMenu->addAction(exportAction); + optionsMenu->addAction(importAction); + optionsMenu->addSeparator(); + optionsMenu->addAction(restoreAction); + + QPushButton *optionsButton = new QPushButton(tr("Options"), this); + optionsButton->setMenu(optionsMenu); + ui.buttonBox->addButton(optionsButton, QDialogButtonBox::ResetRole); + + // Set up the autocomplete for the directory. + QCompleter *completer = new QCompleter(this); + completer->setModel(new QDirModel(QStringList(), QDir::Dirs, QDir::Name, completer)); + ui.targetLineEdit->setCompleter(completer); + + // HotkeyWidget icons. + ui.screenHotkeyWidget->setIcon(os::icon("screen")); + ui.windowHotkeyWidget->setIcon(os::icon("window")); + ui.windowPickerHotkeyWidget->setIcon(os::icon("pickWindow")); + ui.areaHotkeyWidget->setIcon(os::icon("area")); + ui.openHotkeyWidget->setIcon(QIcon(":/icons/lightscreen.small")); + ui.directoryHotkeyWidget->setIcon(os::icon("folder")); + + // Version + ui.versionLabel->setText(tr("Version %1").arg(qApp->applicationVersion())); + + setEnabled(false); // We disable the widgets to prevent any user interaction until the settings have loaded. + + // + // Connections + // + + connect(Uploader::instance(), &Uploader::imgurAuthRefreshed, this, &OptionsDialog::imgurRequestAlbumList); + + connect(ui.buttonBox , SIGNAL(clicked(QAbstractButton *)), this , SLOT(dialogButtonClicked(QAbstractButton *))); + connect(ui.buttonBox , SIGNAL(accepted()) , this , SLOT(accepted())); + connect(ui.namingOptionsButton , SIGNAL(clicked()) , this , SLOT(namingOptions())); + + connect(ui.prefixLineEdit , SIGNAL(textEdited(QString)) , this , SLOT(updatePreview())); + connect(ui.formatComboBox , SIGNAL(currentIndexChanged(int)) , this , SLOT(updatePreview())); + connect(ui.namingComboBox , SIGNAL(currentIndexChanged(int)) , this , SLOT(updatePreview())); + + connect(ui.browsePushButton , SIGNAL(clicked()) , this , SLOT(browse())); + connect(ui.checkUpdatesPushButton , SIGNAL(clicked()) , this , SLOT(checkUpdatesNow())); + connect(ui.historyPushButton , SIGNAL(clicked()) , this , SLOT(viewHistory())); + connect(ui.imgurAuthButton , SIGNAL(clicked()) , this , SLOT(imgurAuthorize())); + connect(ui.imgurRefreshAlbumButton, SIGNAL(clicked()) , this , SLOT(imgurRequestAlbumList())); + + connect(ui.screenCheckBox , SIGNAL(toggled(bool)), ui.screenHotkeyWidget , SLOT(setEnabled(bool))); + connect(ui.areaCheckBox , SIGNAL(toggled(bool)), ui.areaHotkeyWidget , SLOT(setEnabled(bool))); + connect(ui.windowCheckBox , SIGNAL(toggled(bool)), ui.windowHotkeyWidget , SLOT(setEnabled(bool))); + connect(ui.windowPickerCheckBox, SIGNAL(toggled(bool)), ui.windowPickerHotkeyWidget, SLOT(setEnabled(bool))); + connect(ui.openCheckBox , SIGNAL(toggled(bool)), ui.openHotkeyWidget , SLOT(setEnabled(bool))); + connect(ui.directoryCheckBox , SIGNAL(toggled(bool)), ui.directoryHotkeyWidget, SLOT(setEnabled(bool))); + + // "Save as" disables the file target input field. + connect(ui.saveAsCheckBox , SIGNAL(toggled(bool)), ui.targetLineEdit , SLOT(setDisabled(bool))); + connect(ui.saveAsCheckBox , SIGNAL(toggled(bool)), ui.browsePushButton , SLOT(setDisabled(bool))); + connect(ui.saveAsCheckBox , SIGNAL(toggled(bool)), ui.directoryLabel , SLOT(setDisabled(bool))); + + connect(ui.startupCheckBox , SIGNAL(toggled(bool)), ui.startupHideCheckBox , SLOT(setEnabled(bool))); + connect(ui.qualitySlider , SIGNAL(valueChanged(int)), ui.qualityValueLabel, SLOT(setNum(int))); + connect(ui.trayCheckBox , SIGNAL(toggled(bool)), ui.messageCheckBox , SLOT(setEnabled(bool))); + + // Auto-upload disables the default action button in the previews. + connect(ui.uploadCheckBox , SIGNAL(toggled(bool)), ui.previewDefaultActionLabel , SLOT(setDisabled(bool))); + connect(ui.uploadCheckBox , SIGNAL(toggled(bool)), ui.previewDefaultActionComboBox, SLOT(setDisabled(bool))); + connect(ui.directoryCheckBox , SIGNAL(toggled(bool)), ui.directoryHotkeyWidget, SLOT(setEnabled(bool))); + + connect(ui.mainLabel , SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString))); + connect(ui.licenseAboutLabel, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString))); + connect(ui.linksLabel, SIGNAL(linkActivated(QString)), this, SLOT(openUrl(QString))); } void OptionsDialog::namingOptions() { - NamingDialog namingDialog((Screenshot::Naming) ui.namingComboBox->currentIndex()); + NamingDialog namingDialog((Screenshot::Naming) ui.namingComboBox->currentIndex()); - namingDialog.exec(); - flipToggled(settings()->value("options/flip").toBool()); - updatePreview(); + namingDialog.exec(); + flipToggled(settings()->value("options/flip").toBool()); + updatePreview(); } // bool OptionsDialog::hotkeyCollision() { - // Check for hotkey collision (there's probably a better way to do this...=) - - if (ui.screenCheckBox->isChecked()) { - if (ui.screenHotkeyWidget->hotkey() == ui.areaHotkeyWidget->hotkey() - && ui.areaCheckBox->isChecked()) - return true; - - if (ui.screenHotkeyWidget->hotkey() == ui.windowHotkeyWidget->hotkey() - && ui.windowCheckBox->isChecked()) - return true; - - if (ui.screenHotkeyWidget->hotkey() == ui.windowPickerHotkeyWidget->hotkey() - && ui.windowPickerCheckBox->isChecked()) - return true; - - if (ui.screenHotkeyWidget->hotkey() == ui.openHotkeyWidget->hotkey() - && ui.openCheckBox->isChecked()) - return true; - - if (ui.screenHotkeyWidget->hotkey() == ui.directoryHotkeyWidget->hotkey() - && ui.directoryCheckBox->isChecked()) - return true; - } - - if (ui.areaCheckBox->isChecked()) { - if (ui.areaHotkeyWidget->hotkey() == ui.screenHotkeyWidget->hotkey() - && ui.screenCheckBox->isChecked()) - return true; - - if (ui.areaHotkeyWidget->hotkey() == ui.windowHotkeyWidget->hotkey() - && ui.windowCheckBox->isChecked()) - return true; - - if (ui.areaHotkeyWidget->hotkey() == ui.windowPickerHotkeyWidget->hotkey() - && ui.windowPickerCheckBox->isChecked()) - return true; - - if (ui.areaHotkeyWidget->hotkey() == ui.openHotkeyWidget->hotkey() - && ui.openCheckBox->isChecked()) - return true; - - if (ui.areaHotkeyWidget->hotkey() == ui.directoryHotkeyWidget->hotkey() - && ui.directoryCheckBox->isChecked()) - return true; - } - - if (ui.windowCheckBox->isChecked()) { - if (ui.windowHotkeyWidget->hotkey() == ui.screenHotkeyWidget->hotkey() - && ui.screenCheckBox->isChecked()) - return true; - - if (ui.windowHotkeyWidget->hotkey() == ui.areaHotkeyWidget->hotkey() - && ui.areaCheckBox->isChecked()) - return true; - - if (ui.windowHotkeyWidget->hotkey() == ui.windowPickerHotkeyWidget->hotkey() - && ui.windowPickerCheckBox->isChecked()) - return true; - - if (ui.windowHotkeyWidget->hotkey() == ui.openHotkeyWidget->hotkey() - && ui.openCheckBox->isChecked()) - return true; - - if (ui.windowHotkeyWidget->hotkey() == ui.directoryHotkeyWidget->hotkey() - && ui.directoryCheckBox->isChecked()) - return true; - } - - if (ui.openCheckBox->isChecked()) { - if (ui.openHotkeyWidget->hotkey() == ui.screenHotkeyWidget->hotkey() - && ui.screenCheckBox->isChecked()) - return true; - - if (ui.openHotkeyWidget->hotkey() == ui.areaHotkeyWidget->hotkey() - && ui.areaCheckBox->isChecked()) - return true; - - if (ui.openHotkeyWidget->hotkey() == ui.windowPickerHotkeyWidget->hotkey() - && ui.windowPickerCheckBox->isChecked()) - return true; - - if (ui.openHotkeyWidget->hotkey() == ui.windowHotkeyWidget->hotkey() - && ui.windowCheckBox->isChecked()) - return true; - - if (ui.openHotkeyWidget->hotkey() == ui.directoryHotkeyWidget->hotkey() - && ui.directoryCheckBox->isChecked()) - return true; - } - - if (ui.directoryCheckBox->isChecked()) { - if (ui.directoryHotkeyWidget->hotkey() == ui.screenHotkeyWidget->hotkey() - && ui.screenCheckBox->isChecked()) - return true; - - if (ui.directoryHotkeyWidget->hotkey() == ui.areaHotkeyWidget->hotkey() - && ui.areaCheckBox->isChecked()) - return true; - - if (ui.directoryHotkeyWidget->hotkey() == ui.windowPickerHotkeyWidget->hotkey() - && ui.windowPickerCheckBox->isChecked()) - return true; - - if (ui.directoryHotkeyWidget->hotkey() == ui.windowHotkeyWidget->hotkey() - && ui.windowCheckBox->isChecked()) - return true; - - if (ui.directoryHotkeyWidget->hotkey() == ui.openHotkeyWidget->hotkey() - && ui.openCheckBox->isChecked()) - return true; - } - - return false; + // Check for hotkey collision (there's probably a better way to do this...=) + + if (ui.screenCheckBox->isChecked()) { + if (ui.screenHotkeyWidget->hotkey() == ui.areaHotkeyWidget->hotkey() + && ui.areaCheckBox->isChecked()) { + return true; + } + + if (ui.screenHotkeyWidget->hotkey() == ui.windowHotkeyWidget->hotkey() + && ui.windowCheckBox->isChecked()) { + return true; + } + + if (ui.screenHotkeyWidget->hotkey() == ui.windowPickerHotkeyWidget->hotkey() + && ui.windowPickerCheckBox->isChecked()) { + return true; + } + + if (ui.screenHotkeyWidget->hotkey() == ui.openHotkeyWidget->hotkey() + && ui.openCheckBox->isChecked()) { + return true; + } + + if (ui.screenHotkeyWidget->hotkey() == ui.directoryHotkeyWidget->hotkey() + && ui.directoryCheckBox->isChecked()) { + return true; + } + } + + if (ui.areaCheckBox->isChecked()) { + if (ui.areaHotkeyWidget->hotkey() == ui.screenHotkeyWidget->hotkey() + && ui.screenCheckBox->isChecked()) { + return true; + } + + if (ui.areaHotkeyWidget->hotkey() == ui.windowHotkeyWidget->hotkey() + && ui.windowCheckBox->isChecked()) { + return true; + } + + if (ui.areaHotkeyWidget->hotkey() == ui.windowPickerHotkeyWidget->hotkey() + && ui.windowPickerCheckBox->isChecked()) { + return true; + } + + if (ui.areaHotkeyWidget->hotkey() == ui.openHotkeyWidget->hotkey() + && ui.openCheckBox->isChecked()) { + return true; + } + + if (ui.areaHotkeyWidget->hotkey() == ui.directoryHotkeyWidget->hotkey() + && ui.directoryCheckBox->isChecked()) { + return true; + } + } + + if (ui.windowCheckBox->isChecked()) { + if (ui.windowHotkeyWidget->hotkey() == ui.screenHotkeyWidget->hotkey() + && ui.screenCheckBox->isChecked()) { + return true; + } + + if (ui.windowHotkeyWidget->hotkey() == ui.areaHotkeyWidget->hotkey() + && ui.areaCheckBox->isChecked()) { + return true; + } + + if (ui.windowHotkeyWidget->hotkey() == ui.windowPickerHotkeyWidget->hotkey() + && ui.windowPickerCheckBox->isChecked()) { + return true; + } + + if (ui.windowHotkeyWidget->hotkey() == ui.openHotkeyWidget->hotkey() + && ui.openCheckBox->isChecked()) { + return true; + } + + if (ui.windowHotkeyWidget->hotkey() == ui.directoryHotkeyWidget->hotkey() + && ui.directoryCheckBox->isChecked()) { + return true; + } + } + + if (ui.openCheckBox->isChecked()) { + if (ui.openHotkeyWidget->hotkey() == ui.screenHotkeyWidget->hotkey() + && ui.screenCheckBox->isChecked()) { + return true; + } + + if (ui.openHotkeyWidget->hotkey() == ui.areaHotkeyWidget->hotkey() + && ui.areaCheckBox->isChecked()) { + return true; + } + + if (ui.openHotkeyWidget->hotkey() == ui.windowPickerHotkeyWidget->hotkey() + && ui.windowPickerCheckBox->isChecked()) { + return true; + } + + if (ui.openHotkeyWidget->hotkey() == ui.windowHotkeyWidget->hotkey() + && ui.windowCheckBox->isChecked()) { + return true; + } + + if (ui.openHotkeyWidget->hotkey() == ui.directoryHotkeyWidget->hotkey() + && ui.directoryCheckBox->isChecked()) { + return true; + } + } + + if (ui.directoryCheckBox->isChecked()) { + if (ui.directoryHotkeyWidget->hotkey() == ui.screenHotkeyWidget->hotkey() + && ui.screenCheckBox->isChecked()) { + return true; + } + + if (ui.directoryHotkeyWidget->hotkey() == ui.areaHotkeyWidget->hotkey() + && ui.areaCheckBox->isChecked()) { + return true; + } + + if (ui.directoryHotkeyWidget->hotkey() == ui.windowPickerHotkeyWidget->hotkey() + && ui.windowPickerCheckBox->isChecked()) { + return true; + } + + if (ui.directoryHotkeyWidget->hotkey() == ui.windowHotkeyWidget->hotkey() + && ui.windowCheckBox->isChecked()) { + return true; + } + + if (ui.directoryHotkeyWidget->hotkey() == ui.openHotkeyWidget->hotkey() + && ui.openCheckBox->isChecked()) { + return true; + } + } + + return false; } QSettings *OptionsDialog::settings() const { - return ScreenshotManager::instance()->settings(); + return ScreenshotManager::instance()->settings(); } diff --git a/dialogs/previewdialog.cpp b/dialogs/previewdialog.cpp index ba38e7a..130b978 100644 --- a/dialogs/previewdialog.cpp +++ b/dialogs/previewdialog.cpp @@ -42,367 +42,357 @@ PreviewDialog::PreviewDialog(QWidget *parent) : QDialog(parent), mAutoclose(0) { - setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint); - setWindowTitle(tr("Screenshot Preview")); + setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint); + setWindowTitle(tr("Screenshot Preview")); - QSettings *settings = ScreenshotManager::instance()->settings(); + QSettings *settings = ScreenshotManager::instance()->settings(); - mSize = settings->value("options/previewSize", 300).toInt(); - mPosition = settings->value("options/previewPosition", 3).toInt(); + mSize = settings->value("options/previewSize", 300).toInt(); + mPosition = settings->value("options/previewPosition", 3).toInt(); - if (settings->value("options/previewAutoclose", false).toBool()) { - mAutoclose = settings->value("options/previewAutocloseTime").toInt(); - mAutocloseReset = mAutoclose; - mAutocloseAction = settings->value("options/previewAutocloseAction").toInt(); - } + if (settings->value("options/previewAutoclose", false).toBool()) { + mAutoclose = settings->value("options/previewAutocloseTime").toInt(); + mAutocloseReset = mAutoclose; + mAutocloseAction = settings->value("options/previewAutocloseAction").toInt(); + } - QHBoxLayout *l = new QHBoxLayout; - mStack = new QStackedLayout; - connect(mStack, SIGNAL(currentChanged(int)), this, SLOT(indexChanged(int))); + QHBoxLayout *l = new QHBoxLayout; + mStack = new QStackedLayout; + connect(mStack, SIGNAL(currentChanged(int)), this, SLOT(indexChanged(int))); - mPrevButton = new QPushButton(os::icon("arrow-left"), "", this); - connect(mPrevButton, SIGNAL(clicked()), this, SLOT(previous())); + mPrevButton = new QPushButton(os::icon("arrow-left"), "", this); + connect(mPrevButton, SIGNAL(clicked()), this, SLOT(previous())); - mNextButton = new QPushButton(os::icon("arrow-right"), "", this); - connect(mNextButton, SIGNAL(clicked()), this, SLOT(next())); + mNextButton = new QPushButton(os::icon("arrow-right"), "", this); + connect(mNextButton, SIGNAL(clicked()), this, SLOT(next())); - mPrevButton->setCursor(Qt::PointingHandCursor); - mPrevButton->setFlat(true); - mPrevButton->setGraphicsEffect(os::shadow(Qt::white)); - mPrevButton->setIconSize(QSize(24, 24)); - mPrevButton->setVisible(false); + mPrevButton->setCursor(Qt::PointingHandCursor); + mPrevButton->setFlat(true); + mPrevButton->setGraphicsEffect(os::shadow(Qt::white)); + mPrevButton->setIconSize(QSize(24, 24)); + mPrevButton->setVisible(false); - mNextButton->setCursor(Qt::PointingHandCursor); - mNextButton->setFlat(true); - mNextButton->setGraphicsEffect(os::shadow(Qt::white)); - mNextButton->setIconSize(QSize(24, 24)); - mNextButton->setVisible(false); + mNextButton->setCursor(Qt::PointingHandCursor); + mNextButton->setFlat(true); + mNextButton->setGraphicsEffect(os::shadow(Qt::white)); + mNextButton->setIconSize(QSize(24, 24)); + mNextButton->setVisible(false); - l->addWidget(mPrevButton); - l->addLayout(mStack); - l->addWidget(mNextButton); + l->addWidget(mPrevButton); + l->addLayout(mStack); + l->addWidget(mNextButton); - l->setMargin(0); - l->setContentsMargins(6, 6, 6, 6); + l->setMargin(0); + l->setContentsMargins(6, 6, 6, 6); - mStack->setMargin(0); + mStack->setMargin(0); - setMaximumHeight(mSize); - setLayout(l); + setMaximumHeight(mSize); + setLayout(l); - if (mAutoclose) { - startTimer(1000); - } + if (mAutoclose) { + startTimer(1000); + } } void PreviewDialog::add(Screenshot *screenshot) { - if (!isVisible()) { - show(); - } - - if (mAutoclose) { - mAutoclose = mAutocloseReset; - } - - QLabel *label = new QLabel(this); - label->setGraphicsEffect(os::shadow()); - - bool small = false; - - QSize size = screenshot->pixmap().size(); - - if (size.width() > mSize || size.height() > mSize) { - size.scale(mSize, mSize, Qt::KeepAspectRatio); - } - else { - small = true; - } - - QPixmap thumbnail = screenshot->pixmap().scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); - - label->setPixmap(thumbnail); - - thumbnail = QPixmap(); + if (!isVisible()) { + show(); + } - label->setAlignment(Qt::AlignCenter); + if (mAutoclose) { + mAutoclose = mAutocloseReset; + } - if (size.height() < 120) { - label->setMinimumHeight(120); - } + QLabel *label = new QLabel(this); + label->setGraphicsEffect(os::shadow()); - if (size.width() < 140) { - label->setMinimumWidth(140); - } + bool small = false; - label->resize(size); + QSize size = screenshot->pixmap().size(); - QPushButton *discardPushButton = new QPushButton(os::icon("no") , "", label); - QPushButton *enlargePushButton = new QPushButton(os::icon("preview"), "", label); - QToolButton *confirmPushButton = new QToolButton(label); + if (size.width() > mSize || size.height() > mSize) { + size.scale(mSize, mSize, Qt::KeepAspectRatio); + } else { + small = true; + } - confirmPushButton->setIconSize(QSize(24, 24)); - confirmPushButton->setCursor(Qt::PointingHandCursor); - confirmPushButton->setGraphicsEffect(os::shadow(Qt::white)); + QPixmap thumbnail = screenshot->pixmap().scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); - if (ScreenshotManager::instance()->settings()->value("options/previewDefaultAction", 0).toInt() == 0 - || ScreenshotManager::instance()->settings()->value("options/uploadAuto").toBool()) { - // Default button, confirm & upload. - confirmPushButton->setIcon(os::icon("yes")); + label->setPixmap(thumbnail); - if (!ScreenshotManager::instance()->settings()->value("options/uploadAuto").toBool()) { - QMenu *confirmMenu = new QMenu(confirmPushButton); - confirmMenu->setObjectName("confirmMenu"); + thumbnail = QPixmap(); - QAction *uploadAction = new QAction(os::icon("imgur"), tr("Upload"), confirmPushButton); - connect(uploadAction, SIGNAL(triggered()), screenshot, SLOT(markUpload())); - connect(uploadAction, SIGNAL(triggered()), screenshot, SLOT(confirm())); - connect(uploadAction, SIGNAL(triggered()), this, SLOT(closePreview())); - connect(this, SIGNAL(uploadAll()), uploadAction, SLOT(trigger())); + label->setAlignment(Qt::AlignCenter); - confirmMenu->addAction(uploadAction); - confirmPushButton->setMenu(confirmMenu); - confirmPushButton->setPopupMode(QToolButton::MenuButtonPopup); + if (size.height() < 120) { + label->setMinimumHeight(120); } - connect(this, SIGNAL(acceptAll()), confirmPushButton, SLOT(click())); - connect(confirmPushButton, SIGNAL(clicked()), screenshot, SLOT(confirm())); - connect(confirmPushButton, SIGNAL(clicked()), this, SLOT(closePreview())); - } - else { - // Reversed button, upload & confirm. - confirmPushButton->setIcon(os::icon("imgur")); - - QMenu *confirmMenu = new QMenu(confirmPushButton); - confirmMenu->setObjectName("confirmMenu"); - - QAction *confirmAction = new QAction(os::icon("yes"), tr("Save"), confirmPushButton); - connect(this, SIGNAL(acceptAll()), confirmAction, SLOT(trigger())); - connect(confirmAction, SIGNAL(triggered()), screenshot, SLOT(confirm())); - connect(confirmAction, SIGNAL(triggered()), this, SLOT(closePreview())); - - connect(confirmPushButton, SIGNAL(clicked()), screenshot, SLOT(markUpload())); - connect(confirmPushButton, SIGNAL(clicked()), screenshot, SLOT(confirm())); - connect(confirmPushButton, SIGNAL(clicked()), this, SLOT(closePreview())); - connect(this, SIGNAL(uploadAll()), confirmPushButton, SLOT(click())); + if (size.width() < 140) { + label->setMinimumWidth(140); + } - confirmMenu->addAction(confirmAction); - confirmPushButton->setMenu(confirmMenu); - confirmPushButton->setPopupMode(QToolButton::MenuButtonPopup); - } + label->resize(size); + + QPushButton *discardPushButton = new QPushButton(os::icon("no") , "", label); + QPushButton *enlargePushButton = new QPushButton(os::icon("preview"), "", label); + QToolButton *confirmPushButton = new QToolButton(label); + + confirmPushButton->setIconSize(QSize(24, 24)); + confirmPushButton->setCursor(Qt::PointingHandCursor); + confirmPushButton->setGraphicsEffect(os::shadow(Qt::white)); + + if (ScreenshotManager::instance()->settings()->value("options/previewDefaultAction", 0).toInt() == 0 + || ScreenshotManager::instance()->settings()->value("options/uploadAuto").toBool()) { + // Default button, confirm & upload. + confirmPushButton->setIcon(os::icon("yes")); + + if (!ScreenshotManager::instance()->settings()->value("options/uploadAuto").toBool()) { + QMenu *confirmMenu = new QMenu(confirmPushButton); + confirmMenu->setObjectName("confirmMenu"); + + QAction *uploadAction = new QAction(os::icon("imgur"), tr("Upload"), confirmPushButton); + connect(uploadAction, SIGNAL(triggered()), screenshot, SLOT(markUpload())); + connect(uploadAction, SIGNAL(triggered()), screenshot, SLOT(confirm())); + connect(uploadAction, SIGNAL(triggered()), this, SLOT(closePreview())); + connect(this, SIGNAL(uploadAll()), uploadAction, SLOT(trigger())); + + confirmMenu->addAction(uploadAction); + confirmPushButton->setMenu(confirmMenu); + confirmPushButton->setPopupMode(QToolButton::MenuButtonPopup); + } + + connect(this, SIGNAL(acceptAll()), confirmPushButton, SLOT(click())); + connect(confirmPushButton, SIGNAL(clicked()), screenshot, SLOT(confirm())); + connect(confirmPushButton, SIGNAL(clicked()), this, SLOT(closePreview())); + } else { + // Reversed button, upload & confirm. + confirmPushButton->setIcon(os::icon("imgur")); + + QMenu *confirmMenu = new QMenu(confirmPushButton); + confirmMenu->setObjectName("confirmMenu"); + + QAction *confirmAction = new QAction(os::icon("yes"), tr("Save"), confirmPushButton); + connect(this, SIGNAL(acceptAll()), confirmAction, SLOT(trigger())); + connect(confirmAction, SIGNAL(triggered()), screenshot, SLOT(confirm())); + connect(confirmAction, SIGNAL(triggered()), this, SLOT(closePreview())); + + connect(confirmPushButton, SIGNAL(clicked()), screenshot, SLOT(markUpload())); + connect(confirmPushButton, SIGNAL(clicked()), screenshot, SLOT(confirm())); + connect(confirmPushButton, SIGNAL(clicked()), this, SLOT(closePreview())); + connect(this, SIGNAL(uploadAll()), confirmPushButton, SLOT(click())); + + confirmMenu->addAction(confirmAction); + confirmPushButton->setMenu(confirmMenu); + confirmPushButton->setPopupMode(QToolButton::MenuButtonPopup); + } - confirmPushButton->setAutoRaise(true); - confirmPushButton->setVisible(false); + confirmPushButton->setAutoRaise(true); + confirmPushButton->setVisible(false); - discardPushButton->setIconSize(QSize(24, 24)); - discardPushButton->setCursor(Qt::PointingHandCursor); - discardPushButton->setGraphicsEffect(os::shadow(Qt::white)); - discardPushButton->setFlat(true); - discardPushButton->setVisible(false); + discardPushButton->setIconSize(QSize(24, 24)); + discardPushButton->setCursor(Qt::PointingHandCursor); + discardPushButton->setGraphicsEffect(os::shadow(Qt::white)); + discardPushButton->setFlat(true); + discardPushButton->setVisible(false); - enlargePushButton->setIconSize(QSize(22, 22)); - enlargePushButton->setCursor(Qt::PointingHandCursor); - enlargePushButton->setGraphicsEffect(os::shadow(Qt::white)); - enlargePushButton->setFlat(true); - enlargePushButton->setVisible(false); + enlargePushButton->setIconSize(QSize(22, 22)); + enlargePushButton->setCursor(Qt::PointingHandCursor); + enlargePushButton->setGraphicsEffect(os::shadow(Qt::white)); + enlargePushButton->setFlat(true); + enlargePushButton->setVisible(false); - enlargePushButton->setDisabled(small); + enlargePushButton->setDisabled(small); - connect(this, SIGNAL(rejectAll()), discardPushButton, SLOT(click())); + connect(this, SIGNAL(rejectAll()), discardPushButton, SLOT(click())); - connect(discardPushButton, SIGNAL(clicked()), screenshot, SLOT(discard())); - connect(discardPushButton, SIGNAL(clicked()), this, SLOT(closePreview())); + connect(discardPushButton, SIGNAL(clicked()), screenshot, SLOT(discard())); + connect(discardPushButton, SIGNAL(clicked()), this, SLOT(closePreview())); - connect(enlargePushButton, SIGNAL(clicked()), this, SLOT(enlargePreview())); + connect(enlargePushButton, SIGNAL(clicked()), this, SLOT(enlargePreview())); - QHBoxLayout *wlayout = new QHBoxLayout; - wlayout->addWidget(confirmPushButton); - wlayout->addStretch(); - wlayout->addWidget(enlargePushButton); - wlayout->addStretch(); - wlayout->addWidget(discardPushButton); - wlayout->setMargin(0); + QHBoxLayout *wlayout = new QHBoxLayout; + wlayout->addWidget(confirmPushButton); + wlayout->addStretch(); + wlayout->addWidget(enlargePushButton); + wlayout->addStretch(); + wlayout->addWidget(discardPushButton); + wlayout->setMargin(0); - QVBoxLayout *wl = new QVBoxLayout; - wl->addStretch(); - wl->addLayout(wlayout); - wl->setMargin(0); + QVBoxLayout *wl = new QVBoxLayout; + wl->addStretch(); + wl->addLayout(wlayout); + wl->setMargin(0); - label->setLayout(wl); + label->setLayout(wl); - mStack->addWidget(label); - mStack->setCurrentIndex(mStack->count()-1); + mStack->addWidget(label); + mStack->setCurrentIndex(mStack->count() - 1); - mNextButton->setEnabled(false); + mNextButton->setEnabled(false); - if (mStack->count() >= 2 && !mNextButton->isVisible()) { - mNextButton->setVisible(true); - mPrevButton->setVisible(true); - } + if (mStack->count() >= 2 && !mNextButton->isVisible()) { + mNextButton->setVisible(true); + mPrevButton->setVisible(true); + } - relocate(); + relocate(); } int PreviewDialog::count() const { - return mStack->count(); + return mStack->count(); } // void PreviewDialog::closePreview() { - QWidget *widget = mStack->currentWidget(); - mStack->removeWidget(widget); - widget->deleteLater(); - - if (mStack->count() == 0) { - close(); - } - else { - relocate(); - } + QWidget *widget = mStack->currentWidget(); + mStack->removeWidget(widget); + widget->deleteLater(); + + if (mStack->count() == 0) { + close(); + } else { + relocate(); + } } void PreviewDialog::enlargePreview() { - Screenshot *screenshot = qobject_cast(ScreenshotManager::instance()->children().at(mStack->currentIndex())); + Screenshot *screenshot = qobject_cast(ScreenshotManager::instance()->children().at(mStack->currentIndex())); - if (screenshot) { - QFileInfo info(screenshot->unloadedFileName()); - QDesktopServices::openUrl(QUrl(info.absoluteFilePath())); - } + if (screenshot) { + QFileInfo info(screenshot->unloadedFileName()); + QDesktopServices::openUrl(QUrl(info.absoluteFilePath())); + } } void PreviewDialog::indexChanged(int i) { - if (i == mStack->count()-1) { - mNextButton->setEnabled(false); - mPrevButton->setEnabled(true); - } + if (i == mStack->count() - 1) { + mNextButton->setEnabled(false); + mPrevButton->setEnabled(true); + } - if (i == 0 && mStack->count() > 1) { - mNextButton->setEnabled(true); - mPrevButton->setEnabled(false); - } + if (i == 0 && mStack->count() > 1) { + mNextButton->setEnabled(true); + mPrevButton->setEnabled(false); + } - if (i != 0 && i != mStack->count()-1) { - mNextButton->setEnabled(true); - mPrevButton->setEnabled(true); - } + if (i != 0 && i != mStack->count() - 1) { + mNextButton->setEnabled(true); + mPrevButton->setEnabled(true); + } - if (mStack->count() < 2) { - mNextButton->setEnabled(false); - mPrevButton->setEnabled(false); - } + if (mStack->count() < 2) { + mNextButton->setEnabled(false); + mPrevButton->setEnabled(false); + } - if (mStack->widget(i)) { - mStack->widget(i)->setFocus(); - } + if (mStack->widget(i)) { + mStack->widget(i)->setFocus(); + } - if (mStack->count() > 1) { - setWindowTitle(tr("Screenshot Preview (%1 of %2)").arg(mStack->currentIndex()+1).arg(mStack->count())); - } - else { - setWindowTitle(tr("Screenshot Preview")); - } + if (mStack->count() > 1) { + setWindowTitle(tr("Screenshot Preview (%1 of %2)").arg(mStack->currentIndex() + 1).arg(mStack->count())); + } else { + setWindowTitle(tr("Screenshot Preview")); + } } void PreviewDialog::next() { - mStack->setCurrentIndex(mStack->currentIndex()+1); - relocate(); + mStack->setCurrentIndex(mStack->currentIndex() + 1); + relocate(); } void PreviewDialog::previous() { - mStack->setCurrentIndex(mStack->currentIndex()-1); - relocate(); + mStack->setCurrentIndex(mStack->currentIndex() - 1); + relocate(); } void PreviewDialog::relocate() { - updateGeometry(); - resize(minimumSizeHint()); - QApplication::sendEvent(this, new QEvent(QEvent::Enter)); // Ensures the buttons are visible. - - QPoint where; - switch (mPosition) - { - case 0: - where = QApplication::desktop()->availableGeometry(this).topLeft(); - break; - case 1: - where = QApplication::desktop()->availableGeometry(this).topRight(); - where.setX(where.x() - frameGeometry().width()); - break; - case 2: - where = QApplication::desktop()->availableGeometry(this).bottomLeft(); - where.setY(where.y() - frameGeometry().height()); - break; - case 3: - default: - where = QApplication::desktop()->availableGeometry(this).bottomRight(); - where.setX(where.x() - frameGeometry().width()); - where.setY(where.y() - frameGeometry().height()); - break; - } - - move(where); + updateGeometry(); + resize(minimumSizeHint()); + QApplication::sendEvent(this, new QEvent(QEvent::Enter)); // Ensures the buttons are visible. + + QPoint where; + switch (mPosition) { + case 0: + where = QApplication::desktop()->availableGeometry(this).topLeft(); + break; + case 1: + where = QApplication::desktop()->availableGeometry(this).topRight(); + where.setX(where.x() - frameGeometry().width()); + break; + case 2: + where = QApplication::desktop()->availableGeometry(this).bottomLeft(); + where.setY(where.y() - frameGeometry().height()); + break; + case 3: + default: + where = QApplication::desktop()->availableGeometry(this).bottomRight(); + where.setX(where.x() - frameGeometry().width()); + where.setY(where.y() - frameGeometry().height()); + break; + } + + move(where); } // bool PreviewDialog::event(QEvent *event) { - if ((event->type() == QEvent::Enter || event->type() == QEvent::Leave) - && mStack->currentWidget()) - { - foreach (QObject *child, mStack->currentWidget()->children()) { - QWidget *widget = qobject_cast(child); - - if (widget) { - // Lets avoid disappearing buttons and bail if the menu is open. - QMenu *confirmMenu = widget->findChild("confirmMenu"); - if (confirmMenu && confirmMenu->isVisible()) - return false; - - widget->setVisible((event->type() == QEvent::Enter)); - } + if ((event->type() == QEvent::Enter || event->type() == QEvent::Leave) + && mStack->currentWidget()) { + foreach (QObject *child, mStack->currentWidget()->children()) { + QWidget *widget = qobject_cast(child); + + if (widget) { + // Lets avoid disappearing buttons and bail if the menu is open. + QMenu *confirmMenu = widget->findChild("confirmMenu"); + if (confirmMenu && confirmMenu->isVisible()) { + return false; + } + + widget->setVisible((event->type() == QEvent::Enter)); + } + } + } else if (event->type() == QEvent::Close) { + if (mStack->count() != 0) { + emit rejectAll(); + } + + deleteLater(); + } else if (event->type() == QEvent::MouseButtonDblClick) { + enlargePreview(); } - } - else if (event->type() == QEvent::Close) { - if (mStack->count() != 0) - emit rejectAll(); - - deleteLater(); - } - else if (event->type() == QEvent::MouseButtonDblClick) { - enlargePreview(); - } - - return QDialog::event(event); + + return QDialog::event(event); } void PreviewDialog::timerEvent(QTimerEvent *event) { - if (mAutoclose == 0) { - if (mAutocloseAction == 0) { - emit acceptAll(); - } - else if (mAutocloseAction == 1) { - emit uploadAll(); - } - else { - emit rejectAll(); + if (mAutoclose == 0) { + if (mAutocloseAction == 0) { + emit acceptAll(); + } else if (mAutocloseAction == 1) { + emit uploadAll(); + } else { + emit rejectAll(); + } + } else if (mAutoclose < 0) { + killTimer(event->timerId()); + } else { + setWindowTitle(tr("Preview: Closing in %1").arg(mAutoclose)); + mAutoclose--; } - } - else if (mAutoclose < 0) { - killTimer(event->timerId()); - } - else { - setWindowTitle(tr("Preview: Closing in %1").arg(mAutoclose)); - mAutoclose--; - } } diff --git a/dialogs/updaterdialog.cpp b/dialogs/updaterdialog.cpp index d73a432..e8e9c52 100644 --- a/dialogs/updaterdialog.cpp +++ b/dialogs/updaterdialog.cpp @@ -27,39 +27,38 @@ #include "../tools/os.h" UpdaterDialog::UpdaterDialog(QWidget *parent) : -QProgressDialog("", tr("Cancel"), 0, 0, parent) + QProgressDialog("", tr("Cancel"), 0, 0, parent) { - setWindowTitle(tr("Updater - Lightscreen")); - setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint); - setAutoClose(false); + setWindowTitle(tr("Updater - Lightscreen")); + setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint); + setAutoClose(false); - QProgressBar *bar = new QProgressBar(this); - bar->setTextVisible(false); - bar->setRange(0, 0); + QProgressBar *bar = new QProgressBar(this); + bar->setTextVisible(false); + bar->setRange(0, 0); - QLabel *label = new QLabel(tr("Checking for updates..."), this); - connect(label, SIGNAL(linkActivated(QString)), this, SLOT(link(QString))); + QLabel *label = new QLabel(tr("Checking for updates..."), this); + connect(label, SIGNAL(linkActivated(QString)), this, SLOT(link(QString))); - setLabel(label); - setBar(bar); + setLabel(label); + setBar(bar); } void UpdaterDialog::updateDone(bool result) { - if (result) { - setLabelText(tr("There's a new version available,
please see the Lighscreen website.").arg(qApp->applicationVersion())); - } - else { - setLabelText(tr("No new versions available.")); - } + if (result) { + setLabelText(tr("There's a new version available,
please see the Lighscreen website.").arg(qApp->applicationVersion())); + } else { + setLabelText(tr("No new versions available.")); + } - setMaximum(1); + setMaximum(1); - setCancelButtonText(tr("Close")); + setCancelButtonText(tr("Close")); } void UpdaterDialog::link(QString url) { - QDesktopServices::openUrl(url); + QDesktopServices::openUrl(url); } diff --git a/lightscreenwindow.cpp b/lightscreenwindow.cpp index 79c4417..ac0628d 100644 --- a/lightscreenwindow.cpp +++ b/lightscreenwindow.cpp @@ -35,8 +35,8 @@ #include #ifdef Q_OS_WIN - #include - #include + #include + #include #endif /* @@ -56,813 +56,800 @@ #include "updater/updater.h" LightscreenWindow::LightscreenWindow(QWidget *parent) : - QMainWindow(parent), - mDoCache(false), - mHideTrigger(false), - mReviveMain(false), - mWasVisible(true), - mLastMessage(0), - mLastMode(-1), - mLastScreenshot(), - mHasTaskbarButton(false) + QMainWindow(parent), + mDoCache(false), + mHideTrigger(false), + mReviveMain(false), + mWasVisible(true), + mLastMessage(0), + mLastMode(-1), + mLastScreenshot(), + mHasTaskbarButton(false) { - ui.setupUi(this); + ui.setupUi(this); - ui.screenPushButton->setIcon(os::icon("screen.big")); - ui.areaPushButton->setIcon(os::icon("area.big")); - ui.windowPushButton->setIcon(os::icon("pickWindow.big")); + ui.screenPushButton->setIcon(os::icon("screen.big")); + ui.areaPushButton->setIcon(os::icon("area.big")); + ui.windowPushButton->setIcon(os::icon("pickWindow.big")); - ui.optionsPushButton->setIcon(os::icon("configure")); - ui.folderPushButton->setIcon(os::icon("folder")); - ui.imgurPushButton->setIcon(os::icon("imgur")); + ui.optionsPushButton->setIcon(os::icon("configure")); + ui.folderPushButton->setIcon(os::icon("folder")); + ui.imgurPushButton->setIcon(os::icon("imgur")); - createUploadMenu(); + createUploadMenu(); #ifdef Q_OS_WIN - if (QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS7) { - mTaskbarButton = new QWinTaskbarButton(this); - mHasTaskbarButton = true; - - if (QtWin::isCompositionEnabled()) { - setAttribute(Qt::WA_NoSystemBackground); - QtWin::enableBlurBehindWindow(this); - QtWin::extendFrameIntoClientArea(this, QMargins(-1, -1, -1, -1)); + if (QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS7) { + mTaskbarButton = new QWinTaskbarButton(this); + mHasTaskbarButton = true; + + if (QtWin::isCompositionEnabled()) { + setAttribute(Qt::WA_NoSystemBackground); + QtWin::enableBlurBehindWindow(this); + QtWin::extendFrameIntoClientArea(this, QMargins(-1, -1, -1, -1)); + } } - } - if (QSysInfo::WindowsVersion < QSysInfo::WV_WINDOWS7) { - ui.centralWidget->setStyleSheet("QPushButton { padding: 2px; border: 1px solid #acacac; background: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #eaeaea, stop:1 #e5e5e5);} QPushButton:hover { border: 1px solid #7eb4ea; background-color: #e4f0fc; }"); - } + if (QSysInfo::WindowsVersion < QSysInfo::WV_WINDOWS7) { + ui.centralWidget->setStyleSheet("QPushButton { padding: 2px; border: 1px solid #acacac; background: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #eaeaea, stop:1 #e5e5e5);} QPushButton:hover { border: 1px solid #7eb4ea; background-color: #e4f0fc; }"); + } #endif - setMaximumSize(size()); - setMinimumSize(size()); - - setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint); - - // Actions - connect(ui.screenPushButton, SIGNAL(clicked()), this, SLOT(screenshotAction())); - connect(ui.areaPushButton , SIGNAL(clicked()), this, SLOT(areaHotkey())); - connect(ui.windowPushButton, SIGNAL(clicked()), this, SLOT(windowPickerHotkey())); - - connect(ui.optionsPushButton, SIGNAL(clicked()), this, SLOT(showOptions())); - connect(ui.folderPushButton , SIGNAL(clicked()), this, SLOT(goToFolder())); - - // Shortcuts - mGlobalHotkeys = new UGlobalHotkeys(this); - - connect(mGlobalHotkeys, &UGlobalHotkeys::activated, [&](size_t id) { - if (id <= 3) { - screenshotAction(id); - } - else if (id == 4) { - show(); - } - else if (id == 5) { - goToFolder(); - } - else { - qWarning() << "Uknown hotkey ID: " << id; - } - }); - - // Uploader - connect(Uploader::instance(), SIGNAL(progress(int)), this, SLOT(uploadProgress(int))); - connect(Uploader::instance(), SIGNAL(done(QString, QString, QString)), this, SLOT(showUploaderMessage(QString, QString))); - connect(Uploader::instance(), SIGNAL(error(QString)), this, SLOT(showUploaderError(QString))); - - // Manager - connect(ScreenshotManager::instance(), SIGNAL(confirm(Screenshot*)), this, SLOT(preview(Screenshot*))); - connect(ScreenshotManager::instance(), SIGNAL(windowCleanup(Screenshot::Options&)), this, SLOT(cleanup(Screenshot::Options&))); - connect(ScreenshotManager::instance(), SIGNAL(activeCountChange()), this, SLOT(updateStatus())); - - if (!settings()->contains("file/format")) { - showOptions(); // There are no options (or the options config is invalid or incomplete) - } - else { - QTimer::singleShot(0 , this, SLOT(applySettings())); - QTimer::singleShot(5000, this, SLOT(checkForUpdates())); - } + setMaximumSize(size()); + setMinimumSize(size()); + + setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint); + + // Actions + connect(ui.screenPushButton, SIGNAL(clicked()), this, SLOT(screenshotAction())); + connect(ui.areaPushButton , SIGNAL(clicked()), this, SLOT(areaHotkey())); + connect(ui.windowPushButton, SIGNAL(clicked()), this, SLOT(windowPickerHotkey())); + + connect(ui.optionsPushButton, SIGNAL(clicked()), this, SLOT(showOptions())); + connect(ui.folderPushButton , SIGNAL(clicked()), this, SLOT(goToFolder())); + + // Shortcuts + mGlobalHotkeys = new UGlobalHotkeys(this); + + connect(mGlobalHotkeys, &UGlobalHotkeys::activated, [&](size_t id) { + if (id <= 3) { + screenshotAction(id); + } else if (id == 4) { + show(); + } else if (id == 5) { + goToFolder(); + } else { + qWarning() << "Uknown hotkey ID: " << id; + } + }); + + // Uploader + connect(Uploader::instance(), SIGNAL(progress(int)), this, SLOT(uploadProgress(int))); + connect(Uploader::instance(), SIGNAL(done(QString, QString, QString)), this, SLOT(showUploaderMessage(QString, QString))); + connect(Uploader::instance(), SIGNAL(error(QString)), this, SLOT(showUploaderError(QString))); + + // Manager + connect(ScreenshotManager::instance(), SIGNAL(confirm(Screenshot *)), this, SLOT(preview(Screenshot *))); + connect(ScreenshotManager::instance(), SIGNAL(windowCleanup(Screenshot::Options &)), this, SLOT(cleanup(Screenshot::Options &))); + connect(ScreenshotManager::instance(), SIGNAL(activeCountChange()), this, SLOT(updateStatus())); + + if (!settings()->contains("file/format")) { + showOptions(); // There are no options (or the options config is invalid or incomplete) + } else { + QTimer::singleShot(0 , this, SLOT(applySettings())); + QTimer::singleShot(5000, this, SLOT(checkForUpdates())); + } } LightscreenWindow::~LightscreenWindow() { - settings()->setValue("lastScreenshot", mLastScreenshot); - settings()->sync(); - mGlobalHotkeys->unregisterAllHotkeys(); + settings()->setValue("lastScreenshot", mLastScreenshot); + settings()->sync(); + mGlobalHotkeys->unregisterAllHotkeys(); } void LightscreenWindow::action(int mode) { - if (mode == 4) { - goToFolder(); - } - else { - show(); - } + if (mode == 4) { + goToFolder(); + } else { + show(); + } } void LightscreenWindow::areaHotkey() { - screenshotAction(2); + screenshotAction(2); } void LightscreenWindow::checkForUpdates() { - if (settings()->value("options/disableUpdater", false).toBool()) - return; + if (settings()->value("options/disableUpdater", false).toBool()) { + return; + } - if (settings()->value("lastUpdateCheck").toInt() + 7 - > QDate::currentDate().dayOfYear()) - return; // If 7 days have not passed since the last update check. + if (settings()->value("lastUpdateCheck").toInt() + 7 + > QDate::currentDate().dayOfYear()) { + return; // If 7 days have not passed since the last update check. + } - mUpdater = new Updater(this); + mUpdater = new Updater(this); - connect(mUpdater, SIGNAL(done(bool)), this, SLOT(updaterDone(bool))); - mUpdater->check(); + connect(mUpdater, SIGNAL(done(bool)), this, SLOT(updaterDone(bool))); + mUpdater->check(); } void LightscreenWindow::cleanup(Screenshot::Options &options) { - // Reversing settings - if (settings()->value("options/hide").toBool()) { + // Reversing settings + if (settings()->value("options/hide").toBool()) { #ifndef Q_OS_LINUX // X is not quick enough and the notification ends up everywhere but in the icon - if (settings()->value("options/tray").toBool() && mTrayIcon) { - mTrayIcon->show(); - } + if (settings()->value("options/tray").toBool() && mTrayIcon) { + mTrayIcon->show(); + } #endif - if (mPreviewDialog) { - if (mPreviewDialog->count() <= 1 && mWasVisible) { - show(); - } + if (mPreviewDialog) { + if (mPreviewDialog->count() <= 1 && mWasVisible) { + show(); + } - mPreviewDialog->show(); - } - else if (mWasVisible) { - show(); - } + mPreviewDialog->show(); + } else if (mWasVisible) { + show(); + } - mHideTrigger = false; - } + mHideTrigger = false; + } - if (settings()->value("options/tray").toBool() && mTrayIcon) { - notify(options.result); + if (settings()->value("options/tray").toBool() && mTrayIcon) { + notify(options.result); - if (settings()->value("options/message").toBool() && options.file && !options.upload) { - // This message wll get shown only when messages are enabled and the file won't get another upload pop-up soon. - showScreenshotMessage(options.result, options.fileName); + if (settings()->value("options/message").toBool() && options.file && !options.upload) { + // This message wll get shown only when messages are enabled and the file won't get another upload pop-up soon. + showScreenshotMessage(options.result, options.fileName); + } } - } - if (settings()->value("options/playSound", false).toBool()) { - if (options.result == Screenshot::Success) { - QSound::play("sounds/ls.screenshot.wav"); - } - else { + if (settings()->value("options/playSound", false).toBool()) { + if (options.result == Screenshot::Success) { + QSound::play("sounds/ls.screenshot.wav"); + } else { #ifdef Q_OS_WIN - QSound::play("afakepathtomakewindowsplaythedefaultsoundtheresprobablyabetterwaybuticantbebothered"); + QSound::play("afakepathtomakewindowsplaythedefaultsoundtheresprobablyabetterwaybuticantbebothered"); #else - QSound::play("sound/ls.error.wav"); + QSound::play("sound/ls.error.wav"); #endif - } + } - } + } - updateStatus(); + updateStatus(); - if (options.result != Screenshot::Success) - return; + if (options.result != Screenshot::Success) { + return; + } - mLastScreenshot = options.fileName; + mLastScreenshot = options.fileName; } void LightscreenWindow::closeToTrayWarning() { - if (!settings()->value("options/closeToTrayWarning", true).toBool()) - return; + if (!settings()->value("options/closeToTrayWarning", true).toBool()) { + return; + } - mLastMessage = 3; - mTrayIcon->showMessage(tr("Closed to tray"), tr("Lightscreen will keep running, you can disable this in the options menu.")); - settings()->setValue("options/closeToTrayWarning", false); + mLastMessage = 3; + mTrayIcon->showMessage(tr("Closed to tray"), tr("Lightscreen will keep running, you can disable this in the options menu.")); + settings()->setValue("options/closeToTrayWarning", false); } bool LightscreenWindow::closingWithoutTray() { - if (settings()->value("options/disableHideAlert", false).toBool()) - return false; - - QMessageBox msgBox; - msgBox.setWindowTitle(tr("Lightscreen")); - msgBox.setText(tr("You have chosen to hide Lightscreen when there's no system tray icon, so you will not be able to access the program unless you have selected a hotkey to do so.
What do you want to do?")); - msgBox.setIcon(QMessageBox::Warning); - - msgBox.setStyleSheet("QPushButton { padding: 4px 8px; }"); - - QPushButton *enableButton = msgBox.addButton(tr("Hide but enable tray"), - QMessageBox::ActionRole); - QPushButton *enableAndDenotifyButton = msgBox.addButton(tr("Hide and don't warn"), - QMessageBox::ActionRole); - QPushButton *hideButton = msgBox.addButton(tr("Just hide"), - QMessageBox::ActionRole); - QPushButton *abortButton = msgBox.addButton(QMessageBox::Cancel); - - Q_UNUSED(abortButton); - - msgBox.exec(); + if (settings()->value("options/disableHideAlert", false).toBool()) { + return false; + } - if (msgBox.clickedButton() == hideButton) { - return true; - } - else if (msgBox.clickedButton() == enableAndDenotifyButton) { - settings()->setValue("options/disableHideAlert", true); - applySettings(); - return true; - } - else if (msgBox.clickedButton() == enableButton) { - settings()->setValue("options/tray", true); - applySettings(); - return true; - } + QMessageBox msgBox; + msgBox.setWindowTitle(tr("Lightscreen")); + msgBox.setText(tr("You have chosen to hide Lightscreen when there's no system tray icon, so you will not be able to access the program unless you have selected a hotkey to do so.
What do you want to do?")); + msgBox.setIcon(QMessageBox::Warning); + + msgBox.setStyleSheet("QPushButton { padding: 4px 8px; }"); + + QPushButton *enableButton = msgBox.addButton(tr("Hide but enable tray"), + QMessageBox::ActionRole); + QPushButton *enableAndDenotifyButton = msgBox.addButton(tr("Hide and don't warn"), + QMessageBox::ActionRole); + QPushButton *hideButton = msgBox.addButton(tr("Just hide"), + QMessageBox::ActionRole); + QPushButton *abortButton = msgBox.addButton(QMessageBox::Cancel); + + Q_UNUSED(abortButton); + + msgBox.exec(); + + if (msgBox.clickedButton() == hideButton) { + return true; + } else if (msgBox.clickedButton() == enableAndDenotifyButton) { + settings()->setValue("options/disableHideAlert", true); + applySettings(); + return true; + } else if (msgBox.clickedButton() == enableButton) { + settings()->setValue("options/tray", true); + applySettings(); + return true; + } - return false; // Cancel. + return false; // Cancel. } void LightscreenWindow::createUploadMenu() { - QMenu* imgurMenu = new QMenu(tr("Upload")); + QMenu *imgurMenu = new QMenu(tr("Upload")); - QAction *uploadAction = new QAction(os::icon("imgur"), tr("&Upload last"), imgurMenu); - uploadAction->setToolTip(tr("Upload the last screenshot you took to imgur.com")); - connect(uploadAction, SIGNAL(triggered()), this, SLOT(uploadLast())); + QAction *uploadAction = new QAction(os::icon("imgur"), tr("&Upload last"), imgurMenu); + uploadAction->setToolTip(tr("Upload the last screenshot you took to imgur.com")); + connect(uploadAction, SIGNAL(triggered()), this, SLOT(uploadLast())); - QAction *cancelAction = new QAction(os::icon("no"), tr("&Cancel upload"), imgurMenu); - cancelAction->setToolTip(tr("Cancel the currently uploading screenshots")); - cancelAction->setEnabled(false); + QAction *cancelAction = new QAction(os::icon("no"), tr("&Cancel upload"), imgurMenu); + cancelAction->setToolTip(tr("Cancel the currently uploading screenshots")); + cancelAction->setEnabled(false); - connect(this, SIGNAL(uploading(bool)), cancelAction, SLOT(setEnabled(bool))); - connect(cancelAction, SIGNAL(triggered()), this, SLOT(uploadCancel())); + connect(this, SIGNAL(uploading(bool)), cancelAction, SLOT(setEnabled(bool))); + connect(cancelAction, SIGNAL(triggered()), this, SLOT(uploadCancel())); - QAction *historyAction = new QAction(os::icon("view-history"), tr("View &History"), imgurMenu); - connect(historyAction, SIGNAL(triggered()), this, SLOT(showHistoryDialog())); + QAction *historyAction = new QAction(os::icon("view-history"), tr("View &History"), imgurMenu); + connect(historyAction, SIGNAL(triggered()), this, SLOT(showHistoryDialog())); - imgurMenu->addAction(uploadAction); - imgurMenu->addAction(cancelAction); - imgurMenu->addAction(historyAction); - imgurMenu->addSeparator(); + imgurMenu->addAction(uploadAction); + imgurMenu->addAction(cancelAction); + imgurMenu->addAction(historyAction); + imgurMenu->addSeparator(); - connect(imgurMenu, SIGNAL(aboutToShow()), this, SLOT(uploadMenuShown())); + connect(imgurMenu, SIGNAL(aboutToShow()), this, SLOT(uploadMenuShown())); - ui.imgurPushButton->setMenu(imgurMenu); + ui.imgurPushButton->setMenu(imgurMenu); } void LightscreenWindow::goToFolder() { #ifdef Q_OS_WIN - if (!mLastScreenshot.isEmpty() && QFile::exists(mLastScreenshot)) { - QProcess::startDetached("explorer /select, \"" + mLastScreenshot +"\""); - } - else { + if (!mLastScreenshot.isEmpty() && QFile::exists(mLastScreenshot)) { + QProcess::startDetached("explorer /select, \"" + mLastScreenshot + "\""); + } else { #endif - QDir path(settings()->value("file/target").toString()); + QDir path(settings()->value("file/target").toString()); - // We might want to go to the folder without it having been created by taking a screenshot yet. - if (!path.exists()) { - path.mkpath(path.absolutePath()); - } + // We might want to go to the folder without it having been created by taking a screenshot yet. + if (!path.exists()) { + path.mkpath(path.absolutePath()); + } - QDesktopServices::openUrl(QUrl::fromLocalFile(path.absolutePath() + QDir::separator())); + QDesktopServices::openUrl(QUrl::fromLocalFile(path.absolutePath() + QDir::separator())); #ifdef Q_OS_WIN - } + } #endif } void LightscreenWindow::messageClicked() { - if (mLastMessage == 1) { - goToFolder(); - } - else if (mLastMessage == 3) { - QTimer::singleShot(0, this, SLOT(showOptions())); - } - else { - QDesktopServices::openUrl(QUrl(Uploader::instance()->lastUrl())); - } + if (mLastMessage == 1) { + goToFolder(); + } else if (mLastMessage == 3) { + QTimer::singleShot(0, this, SLOT(showOptions())); + } else { + QDesktopServices::openUrl(QUrl(Uploader::instance()->lastUrl())); + } } void LightscreenWindow::messageReceived(const QString &message) { - if (message.contains(' ')) { - foreach (QString argument, message.split(' ')) { - messageReceived(argument); + if (message.contains(' ')) { + foreach (QString argument, message.split(' ')) { + messageReceived(argument); + } } - } - if (message == "--wake") { - show(); - qApp->alert(this, 500); - return; - } + if (message == "--wake") { + show(); + qApp->alert(this, 500); + return; + } - if (message == "--screen") - screenshotAction(); - else if (message == "--area") - screenshotAction(2); - else if (message == "--activewindow") - screenshotAction(1); - else if (message == "--pickwindow") - screenshotAction(3); - else if (message == "--folder") - action(4); - else if (message == "--uploadlast") - uploadLast(); - else if (message == "--viewhistory") - showHistoryDialog(); - else if (message == "--options") - showOptions(); - else if (message == "--quit") - qApp->quit(); + if (message == "--screen") { + screenshotAction(); + } else if (message == "--area") { + screenshotAction(2); + } else if (message == "--activewindow") { + screenshotAction(1); + } else if (message == "--pickwindow") { + screenshotAction(3); + } else if (message == "--folder") { + action(4); + } else if (message == "--uploadlast") { + uploadLast(); + } else if (message == "--viewhistory") { + showHistoryDialog(); + } else if (message == "--options") { + showOptions(); + } else if (message == "--quit") { + qApp->quit(); + } } void LightscreenWindow::notify(const Screenshot::Result &result) { - switch (result) - { - case Screenshot::Success: - mTrayIcon->setIcon(QIcon(":/icons/lightscreen.yes")); + switch (result) { + case Screenshot::Success: + mTrayIcon->setIcon(QIcon(":/icons/lightscreen.yes")); - if (mHasTaskbarButton) { - mTaskbarButton->setOverlayIcon(os::icon("yes")); - } + if (mHasTaskbarButton) { + mTaskbarButton->setOverlayIcon(os::icon("yes")); + } - setWindowTitle(tr("Success!")); - break; - case Screenshot::Fail: - mTrayIcon->setIcon(QIcon(":/icons/lightscreen.no")); - setWindowTitle(tr("Failed!")); + setWindowTitle(tr("Success!")); + break; + case Screenshot::Fail: + mTrayIcon->setIcon(QIcon(":/icons/lightscreen.no")); + setWindowTitle(tr("Failed!")); - if (mHasTaskbarButton) { - mTaskbarButton->setOverlayIcon(os::icon("no")); - } + if (mHasTaskbarButton) { + mTaskbarButton->setOverlayIcon(os::icon("no")); + } - break; - case Screenshot::Cancel: - setWindowTitle(tr("Cancelled!")); - break; - } + break; + case Screenshot::Cancel: + setWindowTitle(tr("Cancelled!")); + break; + } - QTimer::singleShot(2000, this, SLOT(restoreNotification())); + QTimer::singleShot(2000, this, SLOT(restoreNotification())); } -void LightscreenWindow::preview(Screenshot* screenshot) +void LightscreenWindow::preview(Screenshot *screenshot) { - if (screenshot->options().preview) { - if (!mPreviewDialog) { - mPreviewDialog = new PreviewDialog(this); - } + if (screenshot->options().preview) { + if (!mPreviewDialog) { + mPreviewDialog = new PreviewDialog(this); + } - mPreviewDialog->add(screenshot); - } - else { - screenshot->confirm(true); - } + mPreviewDialog->add(screenshot); + } else { + screenshot->confirm(true); + } } void LightscreenWindow::quit() { - settings()->setValue("position", pos()); + settings()->setValue("position", pos()); - int answer = 0; - QString doing; + int answer = 0; + QString doing; + + if (ScreenshotManager::instance()->activeCount() > 0) { + doing = tr("processing"); + } - if (ScreenshotManager::instance()->activeCount() > 0) { - doing = tr("processing"); - } + if (Uploader::instance()->uploading() > 0) { + if (doing.isEmpty()) { + doing = tr("uploading"); + } else { + doing = tr("processing and uploading"); + } + } - if (Uploader::instance()->uploading() > 0) { - if (doing.isEmpty()) { - doing = tr("uploading"); + if (!doing.isEmpty()) { + answer = QMessageBox::question(this, + tr("Are you sure you want to quit?"), + tr("Lightscreen is currently %1 screenshots. Are you sure you want to quit?").arg(doing), + tr("Quit"), + tr("Don't Quit")); } - else { - doing = tr("processing and uploading"); + + if (answer == 0) { + emit finished(); } - } - - if (!doing.isEmpty()) { - answer = QMessageBox::question(this, - tr("Are you sure you want to quit?"), - tr("Lightscreen is currently %1 screenshots. Are you sure you want to quit?").arg(doing), - tr("Quit"), - tr("Don't Quit")); - } - - if (answer == 0) - emit finished(); } void LightscreenWindow::restoreNotification() { - if (mTrayIcon) - mTrayIcon->setIcon(QIcon(":/icons/lightscreen.small")); + if (mTrayIcon) { + mTrayIcon->setIcon(QIcon(":/icons/lightscreen.small")); + } - if (mHasTaskbarButton) { - mTaskbarButton->clearOverlayIcon(); - mTaskbarButton->progress()->setVisible(false); - mTaskbarButton->progress()->stop(); - mTaskbarButton->progress()->reset(); - } + if (mHasTaskbarButton) { + mTaskbarButton->clearOverlayIcon(); + mTaskbarButton->progress()->setVisible(false); + mTaskbarButton->progress()->stop(); + mTaskbarButton->progress()->reset(); + } - updateStatus(); + updateStatus(); } void LightscreenWindow::screenshotAction(int mode) { - int delayms = -1; + int delayms = -1; - bool optionsHide = settings()->value("options/hide").toBool(); // Option cache, used a couple of times. + bool optionsHide = settings()->value("options/hide").toBool(); // Option cache, used a couple of times. - if (!mHideTrigger) { - mWasVisible = isVisible(); - mHideTrigger = true; - } + if (!mHideTrigger) { + mWasVisible = isVisible(); + mHideTrigger = true; + } - // Applying pre-screenshot settings - if (optionsHide) { - hide(); + // Applying pre-screenshot settings + if (optionsHide) { + hide(); #ifndef Q_OS_LINUX // X is not quick enough and the notification ends up everywhere but in the icon - if (mTrayIcon) - mTrayIcon->hide(); + if (mTrayIcon) { + mTrayIcon->hide(); + } #endif - } + } - // Screenshot delay - delayms = settings()->value("options/delay", 0).toInt(); - delayms = delayms * 1000; // Converting the delay to milliseconds. + // Screenshot delay + delayms = settings()->value("options/delay", 0).toInt(); + delayms = delayms * 1000; // Converting the delay to milliseconds. - delayms += 400; + delayms += 400; - if (optionsHide && mPreviewDialog) { - if (mPreviewDialog->count() >= 1) { - mPreviewDialog->hide(); + if (optionsHide && mPreviewDialog) { + if (mPreviewDialog->count() >= 1) { + mPreviewDialog->hide(); + } } - } - // The delayed functions works using the static variable lastMode - // which keeps the argument so a QTimer can call this function again. - if (delayms > 0) { - if (mLastMode < 0) { - mLastMode = mode; - - QTimer::singleShot(delayms, this, SLOT(screenshotAction())); - return; - } - else { - mode = mLastMode; - mLastMode = -1; + // The delayed functions works using the static variable lastMode + // which keeps the argument so a QTimer can call this function again. + if (delayms > 0) { + if (mLastMode < 0) { + mLastMode = mode; + + QTimer::singleShot(delayms, this, SLOT(screenshotAction())); + return; + } else { + mode = mLastMode; + mLastMode = -1; + } } - } - - static Screenshot::Options options; - - if (!mDoCache) { - // Populating the option object that will then be passed to the screenshot engine (sounds fancy huh?) - options.file = settings()->value("file/enabled").toBool(); - options.format = (Screenshot::Format) settings()->value("file/format").toInt(); - options.prefix = settings()->value("file/prefix").toString(); - - QDir dir(settings()->value("file/target").toString()); - dir.makeAbsolute(); - - options.directory = dir; - options.quality = settings()->value("options/quality", 100).toInt(); - options.currentMonitor = settings()->value("options/currentMonitor", false).toBool(); - options.clipboard = settings()->value("options/clipboard", true).toBool(); - options.imgurClipboard = settings()->value("options/imgurClipboard", false).toBool(); - options.preview = settings()->value("options/preview", false).toBool(); - options.magnify = settings()->value("options/magnify", false).toBool(); - options.cursor = settings()->value("options/cursor", true).toBool(); - options.saveAs = settings()->value("options/saveAs", false).toBool(); - options.animations = settings()->value("options/animations", true).toBool(); - options.replace = settings()->value("options/replace", false).toBool(); - options.upload = settings()->value("options/uploadAuto", false).toBool(); - options.optimize = settings()->value("options/optipng", false).toBool(); - - Screenshot::NamingOptions namingOptions; - namingOptions.naming = (Screenshot::Naming) settings()->value("file/naming").toInt(); - namingOptions.leadingZeros = settings()->value("options/naming/leadingZeros", 0).toInt(); - namingOptions.flip = settings()->value("options/flip", false).toBool(); - namingOptions.dateFormat = settings()->value("options/naming/dateFormat", "yyyy-MM-dd").toString(); - - options.namingOptions = namingOptions; - - mDoCache = true; - } + static Screenshot::Options options; + + if (!mDoCache) { + // Populating the option object that will then be passed to the screenshot engine (sounds fancy huh?) + options.file = settings()->value("file/enabled").toBool(); + options.format = (Screenshot::Format) settings()->value("file/format").toInt(); + options.prefix = settings()->value("file/prefix").toString(); + + QDir dir(settings()->value("file/target").toString()); + dir.makeAbsolute(); + + options.directory = dir; + + options.quality = settings()->value("options/quality", 100).toInt(); + options.currentMonitor = settings()->value("options/currentMonitor", false).toBool(); + options.clipboard = settings()->value("options/clipboard", true).toBool(); + options.imgurClipboard = settings()->value("options/imgurClipboard", false).toBool(); + options.preview = settings()->value("options/preview", false).toBool(); + options.magnify = settings()->value("options/magnify", false).toBool(); + options.cursor = settings()->value("options/cursor", true).toBool(); + options.saveAs = settings()->value("options/saveAs", false).toBool(); + options.animations = settings()->value("options/animations", true).toBool(); + options.replace = settings()->value("options/replace", false).toBool(); + options.upload = settings()->value("options/uploadAuto", false).toBool(); + options.optimize = settings()->value("options/optipng", false).toBool(); + + Screenshot::NamingOptions namingOptions; + namingOptions.naming = (Screenshot::Naming) settings()->value("file/naming").toInt(); + namingOptions.leadingZeros = settings()->value("options/naming/leadingZeros", 0).toInt(); + namingOptions.flip = settings()->value("options/flip", false).toBool(); + namingOptions.dateFormat = settings()->value("options/naming/dateFormat", "yyyy-MM-dd").toString(); + + options.namingOptions = namingOptions; + + mDoCache = true; + } - options.mode = mode; + options.mode = mode; - ScreenshotManager::instance()->take(options); + ScreenshotManager::instance()->take(options); } -void LightscreenWindow::screenshotActionTriggered(QAction* action) +void LightscreenWindow::screenshotActionTriggered(QAction *action) { - screenshotAction(action->data().toInt()); + screenshotAction(action->data().toInt()); } void LightscreenWindow::screenHotkey() { - screenshotAction(0); + screenshotAction(0); } void LightscreenWindow::showHotkeyError(const QStringList &hotkeys) { - static bool dontShow = false; + static bool dontShow = false; - if (dontShow) - return; + if (dontShow) { + return; + } - QString messageText; + QString messageText; - messageText = tr("Some hotkeys could not be registered, they might already be in use"); + messageText = tr("Some hotkeys could not be registered, they might already be in use"); - if (hotkeys.count() > 1) { - messageText += tr("
The failed hotkeys are the following:") + "
    "; + if (hotkeys.count() > 1) { + messageText += tr("
    The failed hotkeys are the following:") + "
      "; - foreach(const QString &hotkey, hotkeys) { - messageText += QString("%1%2%3").arg("
    • ").arg(hotkey).arg("
    • "); - } + foreach (const QString &hotkey, hotkeys) { + messageText += QString("%1%2%3").arg("
    • ").arg(hotkey).arg("
    • "); + } - messageText += "
    "; - } - else { - messageText += tr("
    The failed hotkey is %1").arg(hotkeys[0]); - } + messageText += "
"; + } else { + messageText += tr("
The failed hotkey is %1").arg(hotkeys[0]); + } - messageText += tr("
What do you want to do?"); + messageText += tr("
What do you want to do?"); - QMessageBox msgBox(this); - msgBox.setWindowTitle(tr("Lightscreen")); - msgBox.setText(messageText); + QMessageBox msgBox(this); + msgBox.setWindowTitle(tr("Lightscreen")); + msgBox.setText(messageText); - QPushButton *changeButton = msgBox.addButton(tr("Change") , QMessageBox::ActionRole); - QPushButton *disableButton = msgBox.addButton(tr("Disable"), QMessageBox::ActionRole); - QPushButton *exitButton = msgBox.addButton(tr("Quit") , QMessageBox::ActionRole); + QPushButton *changeButton = msgBox.addButton(tr("Change") , QMessageBox::ActionRole); + QPushButton *disableButton = msgBox.addButton(tr("Disable"), QMessageBox::ActionRole); + QPushButton *exitButton = msgBox.addButton(tr("Quit") , QMessageBox::ActionRole); - msgBox.exec(); + msgBox.exec(); - if (msgBox.clickedButton() == exitButton) { - dontShow = true; - QTimer::singleShot(10, this, SLOT(quit())); - } - else if (msgBox.clickedButton() == changeButton) { - showOptions(); - } - else if (msgBox.clickedButton() == disableButton) { - foreach(const QString &hotkey, hotkeys) { - settings()->setValue(QString("actions/%1/enabled").arg(hotkey), false); - } - } + if (msgBox.clickedButton() == exitButton) { + dontShow = true; + QTimer::singleShot(10, this, SLOT(quit())); + } else if (msgBox.clickedButton() == changeButton) { + showOptions(); + } else if (msgBox.clickedButton() == disableButton) { + foreach (const QString &hotkey, hotkeys) { + settings()->setValue(QString("actions/%1/enabled").arg(hotkey), false); + } + } } void LightscreenWindow::showHistoryDialog() { - HistoryDialog historyDialog(this); - historyDialog.exec(); + HistoryDialog historyDialog(this); + historyDialog.exec(); - updateStatus(); + updateStatus(); } void LightscreenWindow::showOptions() { - mGlobalHotkeys->unregisterAllHotkeys(); - QPointer optionsDialog = new OptionsDialog(this); + mGlobalHotkeys->unregisterAllHotkeys(); + QPointer optionsDialog = new OptionsDialog(this); - optionsDialog->exec(); - optionsDialog->deleteLater(); + optionsDialog->exec(); + optionsDialog->deleteLater(); - applySettings(); + applySettings(); } void LightscreenWindow::showScreenshotMessage(const Screenshot::Result &result, const QString &fileName) { - if (result == Screenshot::Cancel) - return; + if (result == Screenshot::Cancel) { + return; + } - // Showing message. - QString title; - QString message; + // Showing message. + QString title; + QString message; - if (result == Screenshot::Success) { - title = QFileInfo(fileName).fileName(); + if (result == Screenshot::Success) { + title = QFileInfo(fileName).fileName(); - if (settings()->value("file/target").toString().isEmpty()) { - message = QDir::toNativeSeparators(QCoreApplication::applicationDirPath()); - } - else { - message = tr("Saved to \"%1\"").arg(settings()->value("file/target").toString()); + if (settings()->value("file/target").toString().isEmpty()) { + message = QDir::toNativeSeparators(QCoreApplication::applicationDirPath()); + } else { + message = tr("Saved to \"%1\"").arg(settings()->value("file/target").toString()); + } + } else { + title = tr("The screenshot was not taken"); + message = tr("An error occurred."); } - } - else { - title = tr("The screenshot was not taken"); - message = tr("An error occurred."); - } - - mLastMessage = 1; - mTrayIcon->showMessage(title, message); + + mLastMessage = 1; + mTrayIcon->showMessage(title, message); } void LightscreenWindow::showUploaderError(const QString &error) { - mLastMessage = -1; - updateStatus(); + mLastMessage = -1; + updateStatus(); - if (mTrayIcon && !error.isEmpty() && settings()->value("options/message").toBool()) { - mTrayIcon->showMessage(tr("Upload error"), error); - } + if (mTrayIcon && !error.isEmpty() && settings()->value("options/message").toBool()) { + mTrayIcon->showMessage(tr("Upload error"), error); + } - notify(Screenshot::Fail); + notify(Screenshot::Fail); } void LightscreenWindow::showUploaderMessage(QString fileName, QString url) { - if (mTrayIcon && settings()->value("options/message").toBool() && !url.isEmpty()) { - QString screenshot = QFileInfo(fileName).fileName(); + if (mTrayIcon && settings()->value("options/message").toBool() && !url.isEmpty()) { + QString screenshot = QFileInfo(fileName).fileName(); - if (screenshot.startsWith(".lstemp.")) - screenshot = tr("Screenshot"); + if (screenshot.startsWith(".lstemp.")) { + screenshot = tr("Screenshot"); + } - mLastMessage = 2; - mTrayIcon->showMessage(tr("%1 uploaded").arg(screenshot), tr("Click here to go to %1").arg(url)); - } + mLastMessage = 2; + mTrayIcon->showMessage(tr("%1 uploaded").arg(screenshot), tr("Click here to go to %1").arg(url)); + } - updateStatus(); + updateStatus(); } void LightscreenWindow::toggleVisibility(QSystemTrayIcon::ActivationReason reason) { - if (reason != QSystemTrayIcon::DoubleClick) - return; - - if (isVisible()) { - hide(); - } - else { - show(); - os::setForegroundWindow(this); - } + if (reason != QSystemTrayIcon::DoubleClick) { + return; + } + + if (isVisible()) { + hide(); + } else { + show(); + os::setForegroundWindow(this); + } } void LightscreenWindow::updateStatus() { - int uploadCount = Uploader::instance()->uploading(); - int activeCount = ScreenshotManager::instance()->activeCount(); - - if (mHasTaskbarButton) { - mTaskbarButton->progress()->setPaused(true); - mTaskbarButton->progress()->setVisible(true); - } - - if (uploadCount > 0) { - setStatus(tr("%1 uploading").arg(uploadCount)); + int uploadCount = Uploader::instance()->uploading(); + int activeCount = ScreenshotManager::instance()->activeCount(); if (mHasTaskbarButton) { - mTaskbarButton->progress()->setRange(0, 100); - mTaskbarButton->progress()->resume(); + mTaskbarButton->progress()->setPaused(true); + mTaskbarButton->progress()->setVisible(true); } - emit uploading(true); - } - else { - if (activeCount > 1) { - setStatus(tr("%1 processing").arg(activeCount)); - } - else if (activeCount == 1) { - setStatus(tr("processing")); - } - else { - setStatus(); + if (uploadCount > 0) { + setStatus(tr("%1 uploading").arg(uploadCount)); - if (mHasTaskbarButton) { - mTaskbarButton->progress()->setVisible(false); - } - } + if (mHasTaskbarButton) { + mTaskbarButton->progress()->setRange(0, 100); + mTaskbarButton->progress()->resume(); + } + + emit uploading(true); + } else { + if (activeCount > 1) { + setStatus(tr("%1 processing").arg(activeCount)); + } else if (activeCount == 1) { + setStatus(tr("processing")); + } else { + setStatus(); + + if (mHasTaskbarButton) { + mTaskbarButton->progress()->setVisible(false); + } + } - emit uploading(false); - } + emit uploading(false); + } } void LightscreenWindow::updaterDone(bool result) { - settings()->setValue("lastUpdateCheck", QDate::currentDate().dayOfYear()); + settings()->setValue("lastUpdateCheck", QDate::currentDate().dayOfYear()); - if (!result) - return; + if (!result) { + return; + } - QMessageBox msgBox; - msgBox.setWindowTitle(tr("Lightscreen")); - msgBox.setText(tr("There's a new version of Lightscreen available.
Would you like to see more information?
(You can turn this notification off)")); - msgBox.setIcon(QMessageBox::Information); + QMessageBox msgBox; + msgBox.setWindowTitle(tr("Lightscreen")); + msgBox.setText(tr("There's a new version of Lightscreen available.
Would you like to see more information?
(You can turn this notification off)")); + msgBox.setIcon(QMessageBox::Information); - QPushButton *yesButton = msgBox.addButton(QMessageBox::Yes); - QPushButton *turnOffButton = msgBox.addButton(tr("Turn Off"), QMessageBox::ActionRole); - QPushButton *remindButton = msgBox.addButton(tr("Remind Me Later"), QMessageBox::RejectRole); + QPushButton *yesButton = msgBox.addButton(QMessageBox::Yes); + QPushButton *turnOffButton = msgBox.addButton(tr("Turn Off"), QMessageBox::ActionRole); + QPushButton *remindButton = msgBox.addButton(tr("Remind Me Later"), QMessageBox::RejectRole); - Q_UNUSED(remindButton); + Q_UNUSED(remindButton); - msgBox.exec(); + msgBox.exec(); - if (msgBox.clickedButton() == yesButton) { - QDesktopServices::openUrl(QUrl("https://lightscreen.com.ar/whatsnew?from=" + qApp->applicationVersion())); - } - else if (msgBox.clickedButton() == turnOffButton) { - settings()->setValue("options/disableUpdater", true); - } + if (msgBox.clickedButton() == yesButton) { + QDesktopServices::openUrl(QUrl("https://lightscreen.com.ar/whatsnew?from=" + qApp->applicationVersion())); + } else if (msgBox.clickedButton() == turnOffButton) { + settings()->setValue("options/disableUpdater", true); + } - mUpdater->deleteLater(); + mUpdater->deleteLater(); } void LightscreenWindow::upload(const QString &fileName) { - Uploader::instance()->upload(fileName); + Uploader::instance()->upload(fileName); } void LightscreenWindow::uploadCancel() { - if (Uploader::instance()->uploading() <= 0) { - return; - } + if (Uploader::instance()->uploading() <= 0) { + return; + } - int confirm = QMessageBox::question(this, tr("Upload cancel"), tr("Do you want to cancel all screenshot uploads?"), tr("Cancel"), tr("Don't Cancel")); + int confirm = QMessageBox::question(this, tr("Upload cancel"), tr("Do you want to cancel all screenshot uploads?"), tr("Cancel"), tr("Don't Cancel")); - if (confirm == 0) { - Uploader::instance()->cancel(); - updateStatus(); - } + if (confirm == 0) { + Uploader::instance()->cancel(); + updateStatus(); + } } void LightscreenWindow::uploadLast() { - upload(mLastScreenshot); - updateStatus(); + upload(mLastScreenshot); + updateStatus(); } void LightscreenWindow::uploadProgress(int progress) { - if (mHasTaskbarButton) { - mTaskbarButton->progress()->setVisible(true); - mTaskbarButton->progress()->setValue(progress); - } + if (mHasTaskbarButton) { + mTaskbarButton->progress()->setVisible(true); + mTaskbarButton->progress()->setValue(progress); + } - if (isVisible() && progress > 0) { - int uploadCount = Uploader::instance()->uploading(); + if (isVisible() && progress > 0) { + int uploadCount = Uploader::instance()->uploading(); - if (uploadCount > 1) { - setWindowTitle(tr("%1% of %2 uploads - Lightscreen").arg(progress).arg(uploadCount)); - } - else { - setWindowTitle(tr("%1% - Lightscreen").arg(progress)); + if (uploadCount > 1) { + setWindowTitle(tr("%1% of %2 uploads - Lightscreen").arg(progress).arg(uploadCount)); + } else { + setWindowTitle(tr("%1% - Lightscreen").arg(progress)); + } } - } } void LightscreenWindow::uploadMenuShown() { - QMenu *imgurMenu = qobject_cast(sender()); - imgurMenu->actions().at(0)->setEnabled(!mLastScreenshot.isEmpty()); + QMenu *imgurMenu = qobject_cast(sender()); + imgurMenu->actions().at(0)->setEnabled(!mLastScreenshot.isEmpty()); } void LightscreenWindow::windowHotkey() { - screenshotAction(1); + screenshotAction(1); } void LightscreenWindow::windowPickerHotkey() { - screenshotAction(3); + screenshotAction(3); } void LightscreenWindow::applySettings() { - bool tray = settings()->value("options/tray", true).toBool(); + bool tray = settings()->value("options/tray", true).toBool(); - if (tray && !mTrayIcon) { - createTrayIcon(); - mTrayIcon->setVisible(true); - } - else if (!tray && mTrayIcon) { - mTrayIcon->setVisible(false); - } + if (tray && !mTrayIcon) { + createTrayIcon(); + mTrayIcon->setVisible(true); + } else if (!tray && mTrayIcon) { + mTrayIcon->setVisible(false); + } - connectHotkeys(); + connectHotkeys(); - mDoCache = false; + mDoCache = false; - if (settings()->value("lastScreenshot").isValid() && mLastScreenshot.isEmpty()) - mLastScreenshot = settings()->value("lastScreenshot").toString(); + if (settings()->value("lastScreenshot").isValid() && mLastScreenshot.isEmpty()) { + mLastScreenshot = settings()->value("lastScreenshot").toString(); + } - os::setStartup(settings()->value("options/startup").toBool(), settings()->value("options/startupHide").toBool()); + os::setStartup(settings()->value("options/startup").toBool(), settings()->value("options/startupHide").toBool()); } void LightscreenWindow::connectHotkeys() @@ -888,165 +875,159 @@ void LightscreenWindow::connectHotkeys() void LightscreenWindow::createTrayIcon() { - mTrayIcon = new QSystemTrayIcon(QIcon(":/icons/lightscreen.small"), this); - updateStatus(); - - connect(mTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(toggleVisibility(QSystemTrayIcon::ActivationReason))); - connect(mTrayIcon, SIGNAL(messageClicked()), this, SLOT(messageClicked())); - - QAction *hideAction = new QAction(QIcon(":/icons/lightscreen.small"), tr("Show&/Hide"), mTrayIcon); - connect(hideAction, SIGNAL(triggered()), this, SLOT(toggleVisibility())); - - QAction *screenAction = new QAction(os::icon("screen"), tr("&Screen"), mTrayIcon); - screenAction->setData(QVariant(0)); - - QAction *windowAction = new QAction(os::icon("window"), tr("Active &Window"), this); - windowAction->setData(QVariant(1)); - - QAction *windowPickerAction = new QAction(os::icon("pickWindow"), tr("&Pick Window"), this); - windowPickerAction->setData(QVariant(3)); - - QAction *areaAction = new QAction(os::icon("area"), tr("&Area"), mTrayIcon); - areaAction->setData(QVariant(2)); - - QActionGroup *screenshotGroup = new QActionGroup(mTrayIcon); - screenshotGroup->addAction(screenAction); - screenshotGroup->addAction(areaAction); - screenshotGroup->addAction(windowAction); - screenshotGroup->addAction(windowPickerAction); - - connect(screenshotGroup, SIGNAL(triggered(QAction*)), this, SLOT(screenshotActionTriggered(QAction*))); - - // Duplicated for the screenshot button :( - QAction *uploadAction = new QAction(os::icon("imgur"), tr("&Upload last"), mTrayIcon); - uploadAction->setToolTip(tr("Upload the last screenshot you took to imgur.com")); - connect(uploadAction, SIGNAL(triggered()), this, SLOT(uploadLast())); - - QAction *cancelAction = new QAction(os::icon("no"), tr("&Cancel upload"), mTrayIcon); - cancelAction->setToolTip(tr("Cancel the currently uploading screenshots")); - cancelAction->setEnabled(false); - connect(this, SIGNAL(uploading(bool)), cancelAction, SLOT(setEnabled(bool))); - connect(cancelAction, SIGNAL(triggered()), this, SLOT(uploadCancel())); - - QAction *historyAction = new QAction(os::icon("view-history"), tr("View History"), mTrayIcon); - connect(historyAction, SIGNAL(triggered()), this, SLOT(showHistoryDialog())); - // - - QAction *optionsAction = new QAction(os::icon("configure"), tr("View &Options"), mTrayIcon); - connect(optionsAction, SIGNAL(triggered()), this, SLOT(showOptions())); - - QAction *goAction = new QAction(os::icon("folder"), tr("&Go to Folder"), mTrayIcon); - connect(goAction, SIGNAL(triggered()), this, SLOT(goToFolder())); - - QAction *quitAction = new QAction(tr("&Quit"), mTrayIcon); - connect(quitAction, SIGNAL(triggered()), this, SLOT(quit())); - - QMenu* screenshotMenu = new QMenu(tr("Screenshot")); - screenshotMenu->addAction(screenAction); - screenshotMenu->addAction(areaAction); - screenshotMenu->addAction(windowAction); - screenshotMenu->addAction(windowPickerAction); - - // Duplicated for the screenshot button :( - QMenu* imgurMenu = new QMenu(tr("Upload")); - imgurMenu->addAction(uploadAction); - imgurMenu->addAction(cancelAction); - imgurMenu->addAction(historyAction); - imgurMenu->addSeparator(); - - QMenu* trayIconMenu = new QMenu; - trayIconMenu->addAction(hideAction); - trayIconMenu->addSeparator(); - trayIconMenu->addMenu(imgurMenu); - trayIconMenu->addSeparator(); - trayIconMenu->addMenu(screenshotMenu); - trayIconMenu->addAction(optionsAction); - trayIconMenu->addAction(goAction); - trayIconMenu->addSeparator(); - trayIconMenu->addAction(quitAction); - - mTrayIcon->setContextMenu(trayIconMenu); + mTrayIcon = new QSystemTrayIcon(QIcon(":/icons/lightscreen.small"), this); + updateStatus(); + + connect(mTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(toggleVisibility(QSystemTrayIcon::ActivationReason))); + connect(mTrayIcon, SIGNAL(messageClicked()), this, SLOT(messageClicked())); + + QAction *hideAction = new QAction(QIcon(":/icons/lightscreen.small"), tr("Show&/Hide"), mTrayIcon); + connect(hideAction, SIGNAL(triggered()), this, SLOT(toggleVisibility())); + + QAction *screenAction = new QAction(os::icon("screen"), tr("&Screen"), mTrayIcon); + screenAction->setData(QVariant(0)); + + QAction *windowAction = new QAction(os::icon("window"), tr("Active &Window"), this); + windowAction->setData(QVariant(1)); + + QAction *windowPickerAction = new QAction(os::icon("pickWindow"), tr("&Pick Window"), this); + windowPickerAction->setData(QVariant(3)); + + QAction *areaAction = new QAction(os::icon("area"), tr("&Area"), mTrayIcon); + areaAction->setData(QVariant(2)); + + QActionGroup *screenshotGroup = new QActionGroup(mTrayIcon); + screenshotGroup->addAction(screenAction); + screenshotGroup->addAction(areaAction); + screenshotGroup->addAction(windowAction); + screenshotGroup->addAction(windowPickerAction); + + connect(screenshotGroup, SIGNAL(triggered(QAction *)), this, SLOT(screenshotActionTriggered(QAction *))); + + // Duplicated for the screenshot button :( + QAction *uploadAction = new QAction(os::icon("imgur"), tr("&Upload last"), mTrayIcon); + uploadAction->setToolTip(tr("Upload the last screenshot you took to imgur.com")); + connect(uploadAction, SIGNAL(triggered()), this, SLOT(uploadLast())); + + QAction *cancelAction = new QAction(os::icon("no"), tr("&Cancel upload"), mTrayIcon); + cancelAction->setToolTip(tr("Cancel the currently uploading screenshots")); + cancelAction->setEnabled(false); + connect(this, SIGNAL(uploading(bool)), cancelAction, SLOT(setEnabled(bool))); + connect(cancelAction, SIGNAL(triggered()), this, SLOT(uploadCancel())); + + QAction *historyAction = new QAction(os::icon("view-history"), tr("View History"), mTrayIcon); + connect(historyAction, SIGNAL(triggered()), this, SLOT(showHistoryDialog())); + // + + QAction *optionsAction = new QAction(os::icon("configure"), tr("View &Options"), mTrayIcon); + connect(optionsAction, SIGNAL(triggered()), this, SLOT(showOptions())); + + QAction *goAction = new QAction(os::icon("folder"), tr("&Go to Folder"), mTrayIcon); + connect(goAction, SIGNAL(triggered()), this, SLOT(goToFolder())); + + QAction *quitAction = new QAction(tr("&Quit"), mTrayIcon); + connect(quitAction, SIGNAL(triggered()), this, SLOT(quit())); + + QMenu *screenshotMenu = new QMenu(tr("Screenshot")); + screenshotMenu->addAction(screenAction); + screenshotMenu->addAction(areaAction); + screenshotMenu->addAction(windowAction); + screenshotMenu->addAction(windowPickerAction); + + // Duplicated for the screenshot button :( + QMenu *imgurMenu = new QMenu(tr("Upload")); + imgurMenu->addAction(uploadAction); + imgurMenu->addAction(cancelAction); + imgurMenu->addAction(historyAction); + imgurMenu->addSeparator(); + + QMenu *trayIconMenu = new QMenu; + trayIconMenu->addAction(hideAction); + trayIconMenu->addSeparator(); + trayIconMenu->addMenu(imgurMenu); + trayIconMenu->addSeparator(); + trayIconMenu->addMenu(screenshotMenu); + trayIconMenu->addAction(optionsAction); + trayIconMenu->addAction(goAction); + trayIconMenu->addSeparator(); + trayIconMenu->addAction(quitAction); + + mTrayIcon->setContextMenu(trayIconMenu); } void LightscreenWindow::setStatus(QString status) { - if (status.isEmpty()) { - status = tr("Lightscreen"); - } - else { - status += tr(" - Lightscreen"); - } - - if (mTrayIcon) { - mTrayIcon->setToolTip(status); - } - - setWindowTitle(status); + if (status.isEmpty()) { + status = tr("Lightscreen"); + } else { + status += tr(" - Lightscreen"); + } + + if (mTrayIcon) { + mTrayIcon->setToolTip(status); + } + + setWindowTitle(status); } QSettings *LightscreenWindow::settings() const { - return ScreenshotManager::instance()->settings(); + return ScreenshotManager::instance()->settings(); } // Event handling bool LightscreenWindow::event(QEvent *event) { - if (event->type() == QEvent::Show) - { - QPoint savedPosition = settings()->value("position").toPoint(); + if (event->type() == QEvent::Show) { + QPoint savedPosition = settings()->value("position").toPoint(); - if (!savedPosition.isNull() && qApp->desktop()->availableGeometry().contains(QRect(savedPosition, size()))) { - move(savedPosition); - } + if (!savedPosition.isNull() && qApp->desktop()->availableGeometry().contains(QRect(savedPosition, size()))) { + move(savedPosition); + } - if (mHasTaskbarButton) { - mTaskbarButton->setWindow(windowHandle()); - } - } - else if (event->type() == QEvent::Hide) { - settings()->setValue("position", pos()); - } - else if (event->type() == QEvent::Close) { - if (settings()->value("options/tray").toBool() && settings()->value("options/closeHide").toBool()) { - closeToTrayWarning(); - hide(); - } - else if (settings()->value("options/closeHide").toBool()) { - if (closingWithoutTray()) - hide(); - } - else { - quit(); - } - } - else if (event->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast(event); + if (mHasTaskbarButton) { + mTaskbarButton->setWindow(windowHandle()); + } + } else if (event->type() == QEvent::Hide) { + settings()->setValue("position", pos()); + } else if (event->type() == QEvent::Close) { + if (settings()->value("options/tray").toBool() && settings()->value("options/closeHide").toBool()) { + closeToTrayWarning(); + hide(); + } else if (settings()->value("options/closeHide").toBool()) { + if (closingWithoutTray()) { + hide(); + } + } else { + quit(); + } + } else if (event->type() == QEvent::KeyPress) { + QKeyEvent *keyEvent = static_cast(event); #ifdef Q_WS_MAC - if (keyEvent->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_Period) { - keyEvent->ignore(); + if (keyEvent->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_Period) { + keyEvent->ignore(); - if(isVisible()) - toggleVisibility(); + if (isVisible()) { + toggleVisibility(); + } - return false; - } - else + return false; + } else #endif - if (!keyEvent->modifiers() && keyEvent->key() == Qt::Key_Escape) { - keyEvent->ignore(); + if (!keyEvent->modifiers() && keyEvent->key() == Qt::Key_Escape) { + keyEvent->ignore(); - if(isVisible()) - toggleVisibility(); + if (isVisible()) { + toggleVisibility(); + } - return false; + return false; + } + } else if (event->type() == QEvent::LanguageChange) { + ui.retranslateUi(this); + resize(minimumSizeHint()); } - } - else if (event->type() == QEvent::LanguageChange) { - ui.retranslateUi(this); - resize(minimumSizeHint()); - } - return QMainWindow::event(event); + return QMainWindow::event(event); } diff --git a/lightscreenwindow.h b/lightscreenwindow.h index ffea47a..cf2b7f9 100644 --- a/lightscreenwindow.h +++ b/lightscreenwindow.h @@ -40,106 +40,108 @@ class LightscreenWindow : public QMainWindow Q_OBJECT public: - LightscreenWindow(QWidget *parent = 0); - ~LightscreenWindow(); + LightscreenWindow(QWidget *parent = 0); + ~LightscreenWindow(); public slots: - void action(int mode = 3); - void areaHotkey(); - void checkForUpdates(); - void cleanup(Screenshot::Options &options); - void closeToTrayWarning(); - bool closingWithoutTray(); - void createUploadMenu(); - void goToFolder(); - void messageClicked(); - void messageReceived(const QString &message); - void notify(const Screenshot::Result &result); - void preview(Screenshot* screenshot); - void quit(); - void restoreNotification(); - void setStatus(QString status = ""); - void screenshotAction(int mode = 0); - void screenshotActionTriggered(QAction* action); - void screenHotkey(); - void showHotkeyError(const QStringList &hotkeys); - void showHistoryDialog(); - void showOptions(); - void showScreenshotMessage(const Screenshot::Result &result, const QString &fileName); - void showUploaderError(const QString &error); - void showUploaderMessage(QString fileName, QString url); - void toggleVisibility(QSystemTrayIcon::ActivationReason reason = QSystemTrayIcon::DoubleClick); - void updateStatus(); - void updaterDone(bool result); - void upload(const QString &fileName); - void uploadCancel(); - void uploadLast(); - void uploadProgress(int progress); - void uploadMenuShown(); - void windowHotkey(); - void windowPickerHotkey(); + void action(int mode = 3); + void areaHotkey(); + void checkForUpdates(); + void cleanup(Screenshot::Options &options); + void closeToTrayWarning(); + bool closingWithoutTray(); + void createUploadMenu(); + void goToFolder(); + void messageClicked(); + void messageReceived(const QString &message); + void notify(const Screenshot::Result &result); + void preview(Screenshot *screenshot); + void quit(); + void restoreNotification(); + void setStatus(QString status = ""); + void screenshotAction(int mode = 0); + void screenshotActionTriggered(QAction *action); + void screenHotkey(); + void showHotkeyError(const QStringList &hotkeys); + void showHistoryDialog(); + void showOptions(); + void showScreenshotMessage(const Screenshot::Result &result, const QString &fileName); + void showUploaderError(const QString &error); + void showUploaderMessage(QString fileName, QString url); + void toggleVisibility(QSystemTrayIcon::ActivationReason reason = QSystemTrayIcon::DoubleClick); + void updateStatus(); + void updaterDone(bool result); + void upload(const QString &fileName); + void uploadCancel(); + void uploadLast(); + void uploadProgress(int progress); + void uploadMenuShown(); + void windowHotkey(); + void windowPickerHotkey(); private slots: - void applySettings(); + void applySettings(); signals: - void uploading(bool uploading); - void finished(); + void uploading(bool uploading); + void finished(); private: - void connectHotkeys(); - void createTrayIcon(); + void connectHotkeys(); + void createTrayIcon(); #ifdef Q_OS_WIN - bool winEvent(MSG *message, long *result); + bool winEvent(MSG *message, long *result); #endif - // Convenience function - QSettings *settings() const; + // Convenience function + QSettings *settings() const; protected: - bool event(QEvent *event); + bool event(QEvent *event); private: - bool mDoCache; - bool mHideTrigger; - bool mReviveMain; - bool mWasVisible; - int mLastMessage; - int mLastMode; - QString mLastScreenshot; - QPointer mTrayIcon; - QPointer mPreviewDialog; - QPointer mUpdater; - Ui::LightscreenWindowClass ui; - - QPointer mGlobalHotkeys; - - bool mHasTaskbarButton; + bool mDoCache; + bool mHideTrigger; + bool mReviveMain; + bool mWasVisible; + int mLastMessage; + int mLastMode; + QString mLastScreenshot; + QPointer mTrayIcon; + QPointer mPreviewDialog; + QPointer mUpdater; + Ui::LightscreenWindowClass ui; + + QPointer mGlobalHotkeys; + + bool mHasTaskbarButton; #ifdef Q_OS_WIN - QPointer mTaskbarButton; + QPointer mTaskbarButton; #else - class QWinTaskbarProgressDummy { - public: - void setVisible(bool v) { Q_UNUSED(v) } - void setPaused(bool p) { Q_UNUSED(p) } - void resume() {} - void stop() {} - void reset() {} - void setRange(int m, int m2) { Q_UNUSED(m) Q_UNUSED(m2) } - void setValue(int v) { Q_UNUSED(v) } - - }; - - class QWinTaskbarDummy : public QObject { - public: - void setOverlayIcon(QIcon i) { Q_UNUSED(i) } - void clearOverlayIcon() {} - QWinTaskbarProgressDummy* progress() { return 0; } - void setWindow(QWindow* w) { Q_UNUSED(w) } - }; - - QWinTaskbarDummy* mTaskbarButton; + class QWinTaskbarProgressDummy + { + public: + void setVisible(bool v) { Q_UNUSED(v) } + void setPaused(bool p) { Q_UNUSED(p) } + void resume() {} + void stop() {} + void reset() {} + void setRange(int m, int m2) { Q_UNUSED(m) Q_UNUSED(m2) } + void setValue(int v) { Q_UNUSED(v) } + + }; + + class QWinTaskbarDummy : public QObject + { + public: + void setOverlayIcon(QIcon i) { Q_UNUSED(i) } + void clearOverlayIcon() {} + QWinTaskbarProgressDummy *progress() { return 0; } + void setWindow(QWindow *w) { Q_UNUSED(w) } + }; + + QWinTaskbarDummy *mTaskbarButton; #endif }; diff --git a/main.cpp b/main.cpp index 3a35630..5dd8afb 100644 --- a/main.cpp +++ b/main.cpp @@ -31,76 +31,74 @@ int main(int argc, char *argv[]) { #ifdef QT_DEBUG - qSetMessagePattern("%{message} @%{line}[%{function}()]"); + qSetMessagePattern("%{message} @%{line}[%{function}()]"); #endif - QtSingleApplication application(argc, argv); - application.setOrganizationName("K"); - application.setApplicationName ("Lightscreen"); - application.setApplicationVersion("2.2"); - application.setQuitOnLastWindowClosed(false); - - if (application.isRunning()) { - if (application.arguments().size() > 1) { - QStringList arguments = application.arguments(); - arguments.removeFirst(); - application.sendMessage(arguments.join(" ")); + QtSingleApplication application(argc, argv); + application.setOrganizationName("K"); + application.setApplicationName("Lightscreen"); + application.setApplicationVersion("2.2"); + application.setQuitOnLastWindowClosed(false); + + if (application.isRunning()) { + if (application.arguments().size() > 1) { + QStringList arguments = application.arguments(); + arguments.removeFirst(); + application.sendMessage(arguments.join(" ")); + } else { + application.sendMessage("--wake"); + } + + return 0; } - else { - application.sendMessage("--wake"); - } - - return 0; - } - LightscreenWindow lightscreen; + LightscreenWindow lightscreen; #ifdef Q_OS_WIN - if (QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS7) { - QWinJumpList* jumplist = new QWinJumpList(&lightscreen); - - QColor backgroundColor = qApp->palette("QToolTip").color(QPalette::Background); - - if (QSysInfo::WindowsVersion == QSysInfo::WV_WINDOWS10) - { // contrast r hard - backgroundColor = Qt::black; + if (QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS7) { + QWinJumpList *jumplist = new QWinJumpList(&lightscreen); + + QColor backgroundColor = qApp->palette("QToolTip").color(QPalette::Background); + + if (QSysInfo::WindowsVersion == QSysInfo::WV_WINDOWS10) { + // contrast r hard + backgroundColor = Qt::black; + } + + QWinJumpListCategory *screenshotCategory = new QWinJumpListCategory("Screenshot"); + screenshotCategory->setVisible(true); + screenshotCategory->addLink(os::icon("screen", backgroundColor), QObject::tr("Screen") , application.applicationFilePath(), QStringList("--screen")); + screenshotCategory->addLink(os::icon("area", backgroundColor), QObject::tr("Area") , application.applicationFilePath(), QStringList("--area")); + screenshotCategory->addLink(os::icon("pickWindow", backgroundColor), QObject::tr("Pick Window") , application.applicationFilePath(), QStringList("--pickwindow")); + + QWinJumpListCategory *uploadCategory = new QWinJumpListCategory("Upload"); + uploadCategory->setVisible(true); + uploadCategory->addLink(os::icon("imgur", backgroundColor), QObject::tr("Upload Last") , application.applicationFilePath(), QStringList("--uploadlast")); + uploadCategory->addLink(os::icon("view-history", backgroundColor), QObject::tr("View History") , application.applicationFilePath(), QStringList("--viewhistory")); + + QWinJumpListCategory *actionsCategory = new QWinJumpListCategory("Actions"); + actionsCategory->setVisible(true); + actionsCategory->addLink(os::icon("configure", backgroundColor), QObject::tr("Options") , application.applicationFilePath(), QStringList("--options")); + actionsCategory->addLink(os::icon("folder", backgroundColor), QObject::tr("Go to Folder") , application.applicationFilePath(), QStringList("--folder")); + actionsCategory->addLink(os::icon("no.big", backgroundColor), QObject::tr("Quit Lightscreen") , application.applicationFilePath(), QStringList("--quit")); + + jumplist->addCategory(screenshotCategory); + jumplist->addCategory(uploadCategory); + jumplist->addCategory(actionsCategory); } - - QWinJumpListCategory* screenshotCategory = new QWinJumpListCategory("Screenshot"); - screenshotCategory->setVisible(true); - screenshotCategory->addLink(os::icon("screen", backgroundColor ), QObject::tr("Screen") , application.applicationFilePath(), QStringList("--screen")); - screenshotCategory->addLink(os::icon("area", backgroundColor ), QObject::tr("Area") , application.applicationFilePath(), QStringList("--area")); - screenshotCategory->addLink(os::icon("pickWindow", backgroundColor), QObject::tr("Pick Window") , application.applicationFilePath(), QStringList("--pickwindow")); - - QWinJumpListCategory* uploadCategory = new QWinJumpListCategory("Upload"); - uploadCategory->setVisible(true); - uploadCategory->addLink(os::icon("imgur", backgroundColor ), QObject::tr("Upload Last") , application.applicationFilePath(), QStringList("--uploadlast")); - uploadCategory->addLink(os::icon("view-history", backgroundColor), QObject::tr("View History") , application.applicationFilePath(), QStringList("--viewhistory")); - - QWinJumpListCategory* actionsCategory = new QWinJumpListCategory("Actions"); - actionsCategory->setVisible(true); - actionsCategory->addLink(os::icon("configure", backgroundColor), QObject::tr("Options") , application.applicationFilePath(), QStringList("--options")); - actionsCategory->addLink(os::icon("folder", backgroundColor ), QObject::tr("Go to Folder") , application.applicationFilePath(), QStringList("--folder")); - actionsCategory->addLink(os::icon("no.big", backgroundColor ), QObject::tr("Quit Lightscreen") , application.applicationFilePath(), QStringList("--quit")); - - jumplist->addCategory(screenshotCategory); - jumplist->addCategory(uploadCategory); - jumplist->addCategory(actionsCategory); - } #endif - if (application.arguments().size() > 1) { - foreach (QString argument, application.arguments()) { - lightscreen.messageReceived(argument); + if (application.arguments().size() > 1) { + foreach (QString argument, application.arguments()) { + lightscreen.messageReceived(argument); + } + } else { + lightscreen.show(); } - } - else { - lightscreen.show(); - } - QObject::connect(&application, SIGNAL(messageReceived(const QString&)), &lightscreen, SLOT(messageReceived(const QString&))); - QObject::connect(&lightscreen, SIGNAL(finished()), &application, SLOT(quit())); + QObject::connect(&application, SIGNAL(messageReceived(const QString &)), &lightscreen, SLOT(messageReceived(const QString &))); + QObject::connect(&lightscreen, SIGNAL(finished()), &application, SLOT(quit())); - int result = application.exec(); - return result; + int result = application.exec(); + return result; } diff --git a/tools/os.cpp b/tools/os.cpp index e151d1b..8529e44 100644 --- a/tools/os.cpp +++ b/tools/os.cpp @@ -41,15 +41,15 @@ #include #ifdef Q_OS_WIN - #include - #include - #include + #include + #include + #include #elif defined(Q_OS_LINUX) - #include - #include - #include - #include - #include + #include + #include + #include + #include + #include #endif #include "os.h" @@ -57,291 +57,292 @@ QPixmap os::cursor() { #ifdef Q_OS_WIN - /* - * Taken from: git://github.com/arrai/mumble-record.git > src > mumble > Overlay.cpp - * BSD License. - */ + /* + * Taken from: git://github.com/arrai/mumble-record.git > src > mumble > Overlay.cpp + * BSD License. + */ - QPixmap pixmap; + QPixmap pixmap; - CURSORINFO cursorInfo; - cursorInfo.cbSize = sizeof(cursorInfo); - ::GetCursorInfo(&cursorInfo); + CURSORINFO cursorInfo; + cursorInfo.cbSize = sizeof(cursorInfo); + ::GetCursorInfo(&cursorInfo); - HICON cursor = cursorInfo.hCursor; + HICON cursor = cursorInfo.hCursor; - ICONINFO iconInfo; - ::GetIconInfo(cursor, &iconInfo); + ICONINFO iconInfo; + ::GetIconInfo(cursor, &iconInfo); - ICONINFO info; - ZeroMemory(&info, sizeof(info)); + ICONINFO info; + ZeroMemory(&info, sizeof(info)); - if (::GetIconInfo(cursor, &info)) { - if (info.hbmColor) { - pixmap = QtWin::fromHBITMAP(info.hbmColor, QtWin::HBitmapAlpha); - } - else { - QBitmap orig(QtWin::fromHBITMAP(info.hbmMask)); - QImage img = orig.toImage(); + if (::GetIconInfo(cursor, &info)) { + if (info.hbmColor) { + pixmap = QtWin::fromHBITMAP(info.hbmColor, QtWin::HBitmapAlpha); + } else { + QBitmap orig(QtWin::fromHBITMAP(info.hbmMask)); + QImage img = orig.toImage(); - int h = img.height() / 2; - int w = img.bytesPerLine() / sizeof(quint32); + int h = img.height() / 2; + int w = img.bytesPerLine() / sizeof(quint32); - QImage out(img.width(), h, QImage::Format_MonoLSB); - QImage outmask(img.width(), h, QImage::Format_MonoLSB); + QImage out(img.width(), h, QImage::Format_MonoLSB); + QImage outmask(img.width(), h, QImage::Format_MonoLSB); - for (int i=0;i(img.scanLine(i + h)); - const quint32 *srcmask = reinterpret_cast(img.scanLine(i)); + for (int i = 0; i < h; ++i) { + const quint32 *srcimg = reinterpret_cast(img.scanLine(i + h)); + const quint32 *srcmask = reinterpret_cast(img.scanLine(i)); - quint32 *dstimg = reinterpret_cast(out.scanLine(i)); - quint32 *dstmask = reinterpret_cast(outmask.scanLine(i)); + quint32 *dstimg = reinterpret_cast(out.scanLine(i)); + quint32 *dstmask = reinterpret_cast(outmask.scanLine(i)); - for (int j=0;jsetFrameRange(0, frames); + QTimeLine *timeLine = new QTimeLine(duration); + timeLine->setFrameRange(0, frames); - timeLine->connect(timeLine, SIGNAL(frameChanged(int)), target, slot); + timeLine->connect(timeLine, SIGNAL(frameChanged(int)), target, slot); - if (cleanup != 0) - timeLine->connect(timeLine, SIGNAL(finished()), target, SLOT(cleanup())); + if (cleanup != 0) { + timeLine->connect(timeLine, SIGNAL(finished()), target, SLOT(cleanup())); + } - timeLine->connect(timeLine, SIGNAL(finished()), timeLine, SLOT(deleteLater())); + timeLine->connect(timeLine, SIGNAL(finished()), timeLine, SLOT(deleteLater())); - timeLine->start(); + timeLine->start(); } QString os::getDocumentsPath() { #ifdef Q_OS_WIN - TCHAR szPath[MAX_PATH]; + TCHAR szPath[MAX_PATH]; - if (SUCCEEDED(SHGetFolderPath(NULL, - CSIDL_PERSONAL|CSIDL_FLAG_CREATE, - NULL, - 0, - szPath))) - { - std::wstring path(szPath); + if (SUCCEEDED(SHGetFolderPath(NULL, + CSIDL_PERSONAL | CSIDL_FLAG_CREATE, + NULL, + 0, + szPath))) { + std::wstring path(szPath); - return QString::fromWCharArray(path.c_str()); - } + return QString::fromWCharArray(path.c_str()); + } - return QDir::homePath() + QDir::separator() + "My Documents"; + return QDir::homePath() + QDir::separator() + "My Documents"; #else - return QDir::homePath() + QDir::separator() + "Documents"; + return QDir::homePath() + QDir::separator() + "Documents"; #endif } QPixmap os::grabWindow(WId winId) { #ifdef Q_OS_WIN - RECT rcWindow; + RECT rcWindow; - HWND hwndId = (HWND)winId; + HWND hwndId = (HWND)winId; - GetWindowRect(hwndId, &rcWindow); + GetWindowRect(hwndId, &rcWindow); - int margin = GetSystemMetrics(SM_CXSIZEFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER)/2; + int margin = GetSystemMetrics(SM_CXSIZEFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER) / 2; - rcWindow.right -= margin; - rcWindow.left += margin; + rcWindow.right -= margin; + rcWindow.left += margin; - if (IsZoomed(hwndId)) { - rcWindow.top += margin; - } else { - rcWindow.top += GetSystemMetrics(SM_CXPADDEDBORDER); - } + if (IsZoomed(hwndId)) { + rcWindow.top += margin; + } else { + rcWindow.top += GetSystemMetrics(SM_CXPADDEDBORDER); + } - rcWindow.bottom -= margin; + rcWindow.bottom -= margin; - int width, height; - width = rcWindow.right - rcWindow.left; - height = rcWindow.bottom - rcWindow.top; + int width, height; + width = rcWindow.right - rcWindow.left; + height = rcWindow.bottom - rcWindow.top; - RECT rcScreen; - GetWindowRect(GetDesktopWindow(), &rcScreen); + RECT rcScreen; + GetWindowRect(GetDesktopWindow(), &rcScreen); - RECT rcResult; - UnionRect(&rcResult, &rcWindow, &rcScreen); + RECT rcResult; + UnionRect(&rcResult, &rcWindow, &rcScreen); - QPixmap pixmap; + QPixmap pixmap; - // Comparing the rects to determine if the window is outside the boundaries of the screen, - // the window DC method has the disadvantage that it does not show Aero glass transparency, - // so we'll avoid it for the screenshots that don't need it. + // Comparing the rects to determine if the window is outside the boundaries of the screen, + // the window DC method has the disadvantage that it does not show Aero glass transparency, + // so we'll avoid it for the screenshots that don't need it. - HDC hdcMem; - HBITMAP hbmCapture; + HDC hdcMem; + HBITMAP hbmCapture; - if (EqualRect(&rcScreen, &rcResult)) { - // Grabbing the window from the Screen DC. - HDC hdcScreen = GetDC(NULL); + if (EqualRect(&rcScreen, &rcResult)) { + // Grabbing the window from the Screen DC. + HDC hdcScreen = GetDC(NULL); - BringWindowToTop(hwndId); + BringWindowToTop(hwndId); - hdcMem = CreateCompatibleDC(hdcScreen); - hbmCapture = CreateCompatibleBitmap(hdcScreen, width, height); - SelectObject(hdcMem, hbmCapture); + hdcMem = CreateCompatibleDC(hdcScreen); + hbmCapture = CreateCompatibleBitmap(hdcScreen, width, height); + SelectObject(hdcMem, hbmCapture); - BitBlt(hdcMem, 0, 0, width, height, hdcScreen, rcWindow.left, rcWindow.top, SRCCOPY); - } - else { - // Grabbing the window by its own DC - HDC hdcWindow = GetWindowDC(hwndId); + BitBlt(hdcMem, 0, 0, width, height, hdcScreen, rcWindow.left, rcWindow.top, SRCCOPY); + } else { + // Grabbing the window by its own DC + HDC hdcWindow = GetWindowDC(hwndId); - hdcMem = CreateCompatibleDC(hdcWindow); - hbmCapture = CreateCompatibleBitmap(hdcWindow, width, height); - SelectObject(hdcMem, hbmCapture); + hdcMem = CreateCompatibleDC(hdcWindow); + hbmCapture = CreateCompatibleBitmap(hdcWindow, width, height); + SelectObject(hdcMem, hbmCapture); - BitBlt(hdcMem, 0, 0, width, height, hdcWindow, 0, 0, SRCCOPY); - } + BitBlt(hdcMem, 0, 0, width, height, hdcWindow, 0, 0, SRCCOPY); + } - ReleaseDC(hwndId, hdcMem); - DeleteDC(hdcMem); + ReleaseDC(hwndId, hdcMem); + DeleteDC(hdcMem); - pixmap = QtWin::fromHBITMAP(hbmCapture); + pixmap = QtWin::fromHBITMAP(hbmCapture); - DeleteObject(hbmCapture); + DeleteObject(hbmCapture); - return pixmap; + return pixmap; #else - return QPixmap::grabWindow(winId); + return QPixmap::grabWindow(winId); #endif } void os::setForegroundWindow(QWidget *window) { #ifdef Q_OS_WIN - ShowWindow((HWND)window->winId(), SW_RESTORE); - SetForegroundWindow((HWND)window->winId()); + ShowWindow((HWND)window->winId(), SW_RESTORE); + SetForegroundWindow((HWND)window->winId()); #else - Q_UNUSED(window) + Q_UNUSED(window) #endif } void os::setStartup(bool startup, bool hide) { - QString lightscreen = QDir::toNativeSeparators(qApp->applicationFilePath()); + QString lightscreen = QDir::toNativeSeparators(qApp->applicationFilePath()); - if (hide) - lightscreen.append(" -h"); + if (hide) { + lightscreen.append(" -h"); + } #ifdef Q_OS_WIN - // Windows startup settings - QSettings init("Microsoft", "Windows"); - init.beginGroup("CurrentVersion"); - init.beginGroup("Run"); - - if (startup) { - init.setValue("Lightscreen", lightscreen); - } - else { - init.remove("Lightscreen"); - } - - init.endGroup(); - init.endGroup(); + // Windows startup settings + QSettings init("Microsoft", "Windows"); + init.beginGroup("CurrentVersion"); + init.beginGroup("Run"); + + if (startup) { + init.setValue("Lightscreen", lightscreen); + } else { + init.remove("Lightscreen"); + } + + init.endGroup(); + init.endGroup(); #endif #if defined(Q_OS_LINUX) - QFile desktopFile(QDir::homePath() + "/.config/autostart/lightscreen.desktop"); + QFile desktopFile(QDir::homePath() + "/.config/autostart/lightscreen.desktop"); - desktopFile.remove(); + desktopFile.remove(); - if (startup) { - desktopFile.open(QIODevice::WriteOnly); - desktopFile.write(QString("[Desktop Entry]\nExec=%1\nType=Application").arg(lightscreen).toLatin1()); - } + if (startup) { + desktopFile.open(QIODevice::WriteOnly); + desktopFile.write(QString("[Desktop Entry]\nExec=%1\nType=Application").arg(lightscreen).toLatin1()); + } #endif } -QGraphicsEffect* os::shadow(QColor color, int blurRadius, int offset) { - QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect; - shadowEffect->setBlurRadius(blurRadius); - shadowEffect->setOffset(offset); - shadowEffect->setColor(color); +QGraphicsEffect *os::shadow(QColor color, int blurRadius, int offset) +{ + QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect; + shadowEffect->setBlurRadius(blurRadius); + shadowEffect->setOffset(offset); + shadowEffect->setColor(color); - return shadowEffect; + return shadowEffect; } QIcon os::icon(QString name, QColor backgroundColor) { - if (!backgroundColor.isValid()) - backgroundColor = qApp->palette().color(QPalette::Button); - - if (backgroundColor.value() > 125) { - return QIcon(":/icons/" + name); - } - else { - return QIcon(":/icons/inv/" + name); - } + if (!backgroundColor.isValid()) { + backgroundColor = qApp->palette().color(QPalette::Button); + } + + if (backgroundColor.value() > 125) { + return QIcon(":/icons/" + name); + } else { + return QIcon(":/icons/inv/" + name); + } } #ifdef Q_OS_LINUX // Taken from KSnapshot. Oh KDE, what would I do without you :D Window os::findRealWindow(Window w, int depth) { - if( depth > 5 ) { + if (depth > 5) { return None; } - static Atom wm_state = XInternAtom( QX11Info::display(), "WM_STATE", False ); + static Atom wm_state = XInternAtom(QX11Info::display(), "WM_STATE", False); Atom type; int format; unsigned long nitems, after; - unsigned char* prop; + unsigned char *prop; - if( XGetWindowProperty( QX11Info::display(), w, wm_state, 0, 0, False, AnyPropertyType, - &type, &format, &nitems, &after, &prop ) == Success ) { - if( prop != NULL ) { - XFree( prop ); + if (XGetWindowProperty(QX11Info::display(), w, wm_state, 0, 0, False, AnyPropertyType, + &type, &format, &nitems, &after, &prop) == Success) { + if (prop != NULL) { + XFree(prop); } - if( type != None ) { + if (type != None) { return w; } } Window root, parent; - Window* children; + Window *children; unsigned int nchildren; Window ret = None; - if( XQueryTree( QX11Info::display(), w, &root, &parent, &children, &nchildren ) != 0 ) { - for( unsigned int i = 0; - i < nchildren && ret == None; - ++i ) { - ret = os::findRealWindow( children[ i ], depth + 1 ); + if (XQueryTree(QX11Info::display(), w, &root, &parent, &children, &nchildren) != 0) { + for (unsigned int i = 0; + i < nchildren && ret == None; + ++i) { + ret = os::findRealWindow(children[ i ], depth + 1); } - if( children != NULL ) { - XFree( children ); + if (children != NULL) { + XFree(children); } } @@ -355,17 +356,17 @@ Window os::windowUnderCursor(bool includeDecorations) uint mask; int rootX, rootY, winX, winY; - XQueryPointer( QX11Info::display(), QX11Info::appRootWindow(), &root, &child, - &rootX, &rootY, &winX, &winY, &mask ); + XQueryPointer(QX11Info::display(), QX11Info::appRootWindow(), &root, &child, + &rootX, &rootY, &winX, &winY, &mask); - if( child == None ) { + if (child == None) { child = QX11Info::appRootWindow(); } - if( !includeDecorations ) { - Window real_child = os::findRealWindow( child ); + if (!includeDecorations) { + Window real_child = os::findRealWindow(child); - if( real_child != None ) { // test just in case + if (real_child != None) { // test just in case child = real_child; } } diff --git a/tools/os.h b/tools/os.h index 0b67f26..4eef6de 100644 --- a/tools/os.h +++ b/tools/os.h @@ -29,43 +29,42 @@ class QGraphicsEffect; class QIcon; #if defined(Q_OS_LINUX) - typedef unsigned long XID; - typedef XID Window; + typedef unsigned long XID; + typedef XID Window; #endif -namespace os -{ - // Returns the cursor pixmap in Windows - QPixmap cursor(); +namespace os { +// Returns the cursor pixmap in Windows +QPixmap cursor(); - // A QTimeLine based effect for a slot (TODO: look at the new effect classes) - void effect(QObject* target, const char* slot, int frames, int duration = 400, const char* cleanup = 0); +// A QTimeLine based effect for a slot (TODO: look at the new effect classes) +void effect(QObject *target, const char *slot, int frames, int duration = 400, const char *cleanup = 0); - // Returns the current users's Documents/My Documents folder - QString getDocumentsPath(); +// Returns the current users's Documents/My Documents folder +QString getDocumentsPath(); - // Returns the pixmap of the given window id. - QPixmap grabWindow(WId winId); +// Returns the pixmap of the given window id. +QPixmap grabWindow(WId winId); - // Set the target window as the foreground window (Windows only) - void setForegroundWindow(QWidget *window); +// Set the target window as the foreground window (Windows only) +void setForegroundWindow(QWidget *window); - // Adds lightscreen to the startup list in Windows & Linux (KDE, Gnome and Xfce for now). - void setStartup(bool startup, bool hide); +// Adds lightscreen to the startup list in Windows & Linux (KDE, Gnome and Xfce for now). +void setStartup(bool startup, bool hide); - // Creates a new QGraphicsDropShadowEffect to apply to widgets. - QGraphicsEffect* shadow(QColor color = Qt::black, int blurRadius = 6, int offset = 1); +// Creates a new QGraphicsDropShadowEffect to apply to widgets. +QGraphicsEffect *shadow(QColor color = Qt::black, int blurRadius = 6, int offset = 1); - // Translates the ui to the given language name. - void translate(QString language); +// Translates the ui to the given language name. +void translate(QString language); - // Returns a QIcon for the given icon name (taking into account color schemes and whatnot). - QIcon icon(QString name, QColor backgroundColor = QColor()); +// Returns a QIcon for the given icon name (taking into account color schemes and whatnot). +QIcon icon(QString name, QColor backgroundColor = QColor()); - // X11-specific functions for the Window Picker +// X11-specific functions for the Window Picker #if defined(Q_OS_LINUX) - Window findRealWindow(Window w, int depth = 0); - Window windowUnderCursor(bool includeDecorations = true); + Window findRealWindow(Window w, int depth = 0); + Window windowUnderCursor(bool includeDecorations = true); #endif } diff --git a/tools/screenshot.cpp b/tools/screenshot.cpp index 1d64837..888a99f 100644 --- a/tools/screenshot.cpp +++ b/tools/screenshot.cpp @@ -36,331 +36,316 @@ #include "os.h" #ifdef Q_OS_WIN - #include + #include #endif #ifdef Q_OS_LINUX - #include - #include - #include + #include + #include + #include #endif Screenshot::Screenshot(QObject *parent, Screenshot::Options options): - QObject(parent), - mOptions(options), - mPixmapDelay(false), - mUnloaded(false), - mUnloadFilename() + QObject(parent), + mOptions(options), + mPixmapDelay(false), + mUnloaded(false), + mUnloadFilename() { - // Here be crickets + // Here be crickets } Screenshot::~Screenshot() { - if (!mUnloadFilename.isEmpty()) { - QFile::remove(mUnloadFilename); - } + if (!mUnloadFilename.isEmpty()) { + QFile::remove(mUnloadFilename); + } } QString Screenshot::getName(const NamingOptions &options, const QString &prefix, const QDir &directory) { - QString naming; - int naming_largest = 0; - - if (options.flip) { - naming = "%1" + prefix; - } - else { - naming = prefix + "%1"; - } - - switch (options.naming) - { - case Screenshot::Numeric: // Numeric - // Iterating through the folder to find the largest numeric naming. - foreach(QString file, directory.entryList(QDir::Files)) - { - if (file.contains(prefix)) { - file.chop(file.size() - file.lastIndexOf(".")); - file.remove(prefix); - - if (file.toInt()> naming_largest) { - naming_largest = file.toInt(); - } - } + QString naming; + int naming_largest = 0; + + if (options.flip) { + naming = "%1" + prefix; + } else { + naming = prefix + "%1"; } - if (options.leadingZeros > 0) { - //Pretty, huh? - QString format; - QTextStream (&format) << "%0" << (options.leadingZeros+1) << "d"; + switch (options.naming) { + case Screenshot::Numeric: // Numeric + // Iterating through the folder to find the largest numeric naming. + foreach (QString file, directory.entryList(QDir::Files)) { + if (file.contains(prefix)) { + file.chop(file.size() - file.lastIndexOf(".")); + file.remove(prefix); + + if (file.toInt() > naming_largest) { + naming_largest = file.toInt(); + } + } + } - naming = naming.arg(QString().sprintf(format.toLatin1(), naming_largest + 1)); - } - else { - naming = naming.arg(naming_largest + 1); + if (options.leadingZeros > 0) { + //Pretty, huh? + QString format; + QTextStream(&format) << "%0" << (options.leadingZeros + 1) << "d"; + + naming = naming.arg(QString().sprintf(format.toLatin1(), naming_largest + 1)); + } else { + naming = naming.arg(naming_largest + 1); + } + break; + case Screenshot::Date: // Date + naming = naming.arg(QLocale().toString(QDateTime::currentDateTime(), options.dateFormat)); + break; + case Screenshot::Timestamp: // Timestamp + naming = naming.arg(QDateTime::currentDateTime().toTime_t()); + break; + case Screenshot::Empty: + naming = naming.arg(""); + break; } - break; - case Screenshot::Date: // Date - naming = naming.arg(QLocale().toString(QDateTime::currentDateTime(), options.dateFormat)); - break; - case Screenshot::Timestamp: // Timestamp - naming = naming.arg(QDateTime::currentDateTime().toTime_t()); - break; - case Screenshot::Empty: - naming = naming.arg(""); - break; - } - - return naming; + + return naming; } -QString& Screenshot::unloadedFileName() +QString &Screenshot::unloadedFileName() { - return mUnloadFilename; + return mUnloadFilename; } Screenshot::Options &Screenshot::options() { - return mOptions; + return mOptions; } QPixmap &Screenshot::pixmap() { - return mPixmap; + return mPixmap; } // void Screenshot::confirm(bool result) { - if (result) { - save(); - } - else { - mOptions.result = Screenshot::Cancel; - emit finished(); - } + if (result) { + save(); + } else { + mOptions.result = Screenshot::Cancel; + emit finished(); + } - emit cleanup(); + emit cleanup(); - mPixmap = QPixmap(); + mPixmap = QPixmap(); } void Screenshot::confirmation() { - emit askConfirmation(); + emit askConfirmation(); - if (mOptions.file) { - unloadPixmap(); - } + if (mOptions.file) { + unloadPixmap(); + } } void Screenshot::discard() { - confirm(false); + confirm(false); } void Screenshot::markUpload() { - mOptions.upload = true; + mOptions.upload = true; } void Screenshot::optimize() { - QProcess* process = new QProcess(this); + QProcess *process = new QProcess(this); - // Delete the QProcess once it's done. - connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), this , SLOT(optimizationDone())); - connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), process, SLOT(deleteLater())); + // Delete the QProcess once it's done. + connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), this , SLOT(optimizationDone())); + connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), process, SLOT(deleteLater())); - QString optiPNG; + QString optiPNG; #ifdef Q_OS_UNIX - optiPNG = "optipng"; + optiPNG = "optipng"; #else - optiPNG = qApp->applicationDirPath() + QDir::separator() + "optipng.exe"; + optiPNG = qApp->applicationDirPath() + QDir::separator() + "optipng.exe"; #endif - if (!QFile::exists(optiPNG)) { - emit optimizationDone(); - } + if (!QFile::exists(optiPNG)) { + emit optimizationDone(); + } - process->start(optiPNG, QStringList() << mOptions.fileName); + process->start(optiPNG, QStringList() << mOptions.fileName); - if (process->state() == QProcess::NotRunning) { - emit optimizationDone(); - process->deleteLater(); - } + if (process->state() == QProcess::NotRunning) { + emit optimizationDone(); + process->deleteLater(); + } } void Screenshot::optimizationDone() { - if (mOptions.upload) { - upload(); - } - else { - emit finished(); - } + if (mOptions.upload) { + upload(); + } else { + emit finished(); + } } void Screenshot::save() { - QString name = ""; - QString fileName = ""; - Screenshot::Result result = Screenshot::Fail; - - if (mOptions.file && !mOptions.saveAs) { - name = newFileName(); - } - else if (mOptions.file && mOptions.saveAs) { - name = QFileDialog::getSaveFileName(0, tr("Save as.."), newFileName(), "*" + extension()); - } - - if (!mOptions.replace && QFile::exists(name+extension())) { - // Ugly? You should see my wife! - int count = 0; - int cunt = 0; - - QString naming = QFileInfo(name).fileName(); - - foreach(QString file, QFileInfo(name+extension()).dir().entryList(QDir::Files)) { - if (file.contains(naming)) { - file.remove(naming); - file.remove(" ("); - file.remove(")"); - file.remove(extension()); - - cunt = file.toInt(); - - if (cunt > count) { - count = cunt; - } - } + QString name = ""; + QString fileName = ""; + Screenshot::Result result = Screenshot::Fail; + + if (mOptions.file && !mOptions.saveAs) { + name = newFileName(); + } else if (mOptions.file && mOptions.saveAs) { + name = QFileDialog::getSaveFileName(0, tr("Save as.."), newFileName(), "*" + extension()); } - name = name + " (" + QString::number(count+1) + ")"; - } + if (!mOptions.replace && QFile::exists(name + extension())) { + // Ugly? You should see my wife! + int count = 0; + int cunt = 0; - if (mOptions.clipboard && !(mOptions.upload && mOptions.imgurClipboard)) { - if (mUnloaded) { - mUnloaded = false; - mPixmap = QPixmap(mUnloadFilename); - } + QString naming = QFileInfo(name).fileName(); - QApplication::clipboard()->setPixmap(mPixmap, QClipboard::Clipboard); + foreach (QString file, QFileInfo(name + extension()).dir().entryList(QDir::Files)) { + if (file.contains(naming)) { + file.remove(naming); + file.remove(" ("); + file.remove(")"); + file.remove(extension()); - if (!mOptions.file) { - result = (Screenshot::Result)1; - } - } + cunt = file.toInt(); - // In the following code I use (Screenshot::Result)1 instead of Screenshot::Success because of some weird issue with the X11 headers. //TODO - if (mOptions.file) { - fileName = name + extension(); + if (cunt > count) { + count = cunt; + } + } + } - if (name.isEmpty()) { - result = Screenshot::Cancel; + name = name + " (" + QString::number(count + 1) + ")"; } - else if (mUnloaded) { - result = (QFile::rename(mUnloadFilename, fileName)) ? (Screenshot::Result)1: Screenshot::Fail; - } - else if (mPixmap.save(fileName, 0, mOptions.quality)) { - result = (Screenshot::Result)1; - } - else { - result = Screenshot::Fail; + + if (mOptions.clipboard && !(mOptions.upload && mOptions.imgurClipboard)) { + if (mUnloaded) { + mUnloaded = false; + mPixmap = QPixmap(mUnloadFilename); + } + + QApplication::clipboard()->setPixmap(mPixmap, QClipboard::Clipboard); + + if (!mOptions.file) { + result = (Screenshot::Result)1; + } } - } - mOptions.fileName = fileName; - mOptions.result = result; + // In the following code I use (Screenshot::Result)1 instead of Screenshot::Success because of some weird issue with the X11 headers. //TODO + if (mOptions.file) { + fileName = name + extension(); + + if (name.isEmpty()) { + result = Screenshot::Cancel; + } else if (mUnloaded) { + result = (QFile::rename(mUnloadFilename, fileName)) ? (Screenshot::Result)1 : Screenshot::Fail; + } else if (mPixmap.save(fileName, 0, mOptions.quality)) { + result = (Screenshot::Result)1; + } else { + result = Screenshot::Fail; + } + } - if (!mOptions.result) - emit finished(); + mOptions.fileName = fileName; + mOptions.result = result; - if (mOptions.format == Screenshot::PNG && mOptions.optimize && mOptions.file) { - if (!mOptions.upload) { - ScreenshotManager::instance()->saveHistory(mOptions.fileName); + if (!mOptions.result) { + emit finished(); } - optimize(); - } - else if (mOptions.upload) { - upload(); - } - else if (mOptions.file) { - ScreenshotManager::instance()->saveHistory(mOptions.fileName); - emit finished(); - } - else { - emit finished(); - } + if (mOptions.format == Screenshot::PNG && mOptions.optimize && mOptions.file) { + if (!mOptions.upload) { + ScreenshotManager::instance()->saveHistory(mOptions.fileName); + } + + optimize(); + } else if (mOptions.upload) { + upload(); + } else if (mOptions.file) { + ScreenshotManager::instance()->saveHistory(mOptions.fileName); + emit finished(); + } else { + emit finished(); + } } void Screenshot::setPixmap(QPixmap pixmap) { - mPixmap = pixmap; - - if (mPixmap.isNull()) { - emit confirm(false); - } - else { - confirmation(); - } + mPixmap = pixmap; + + if (mPixmap.isNull()) { + emit confirm(false); + } else { + confirmation(); + } } void Screenshot::take() { - switch (mOptions.mode) - { - case Screenshot::WholeScreen: - wholeScreen(); - break; - - case Screenshot::SelectedArea: - selectedArea(); - break; - - case Screenshot::ActiveWindow: - activeWindow(); - break; - - case Screenshot::SelectedWindow: - selectedWindow(); - break; - } + switch (mOptions.mode) { + case Screenshot::WholeScreen: + wholeScreen(); + break; + + case Screenshot::SelectedArea: + selectedArea(); + break; + + case Screenshot::ActiveWindow: + activeWindow(); + break; + + case Screenshot::SelectedWindow: + selectedWindow(); + break; + } - if (mPixmapDelay) - return; + if (mPixmapDelay) { + return; + } - if (mPixmap.isNull()) { - confirm(false); - } - else { - confirmation(); - } + if (mPixmap.isNull()) { + confirm(false); + } else { + confirmation(); + } } void Screenshot::upload() { - if (mOptions.file) { - Uploader::instance()->upload(mOptions.fileName); - } - else if (unloadPixmap()) { - Uploader::instance()->upload(mUnloadFilename); - } - else { - emit finished(); - } + if (mOptions.file) { + Uploader::instance()->upload(mOptions.fileName); + } else if (unloadPixmap()) { + Uploader::instance()->upload(mUnloadFilename); + } else { + emit finished(); + } } void Screenshot::uploadDone(QString url) { - if (mOptions.imgurClipboard && !url.isEmpty()) - QApplication::clipboard()->setText(url, QClipboard::Clipboard); + if (mOptions.imgurClipboard && !url.isEmpty()) { + QApplication::clipboard()->setText(url, QClipboard::Clipboard); + } - emit finished(); + emit finished(); } // @@ -368,136 +353,135 @@ void Screenshot::uploadDone(QString url) void Screenshot::activeWindow() { #ifdef Q_OS_WIN - HWND fWindow = GetForegroundWindow(); + HWND fWindow = GetForegroundWindow(); - if (fWindow == NULL) - return; + if (fWindow == NULL) { + return; + } - if (fWindow == GetDesktopWindow()) { - wholeScreen(); - return; - } + if (fWindow == GetDesktopWindow()) { + wholeScreen(); + return; + } - mPixmap = os::grabWindow((WId)GetForegroundWindow()); + mPixmap = os::grabWindow((WId)GetForegroundWindow()); #endif #if defined(Q_OS_LINUX) - Window focus; - int revert; + Window focus; + int revert; - XGetInputFocus(QX11Info::display(), &focus, &revert); + XGetInputFocus(QX11Info::display(), &focus, &revert); - mPixmap = QPixmap::grabWindow(focus); + mPixmap = QPixmap::grabWindow(focus); #endif } QString Screenshot::extension() const { - switch (mOptions.format) { + switch (mOptions.format) { case Screenshot::PNG: - return ".png"; - break; + return ".png"; + break; case Screenshot::BMP: - return ".bmp"; - break; + return ".bmp"; + break; case Screenshot::JPEG: default: - return ".jpg"; - break; - } + return ".jpg"; + break; + } } void Screenshot::grabDesktop() { - if (mOptions.currentMonitor) { - /* - * TODO QRect geometry; - foreach (QScreen *screen, QGuiApplication::screens()) { - geometry.setWidth(geometry.width() + screen->geometry().width()); - geometry.setHeight(geometry.height() + screen->geometry().height()); + if (mOptions.currentMonitor) { + geometry = QApplication::primaryScreen()->geometry(); + } else { + foreach (QScreen *screen, QGuiApplication::screens()) { + geometry = geometry.united(screen->geometry()); + } + } + + mPixmap = QApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId(), geometry.x(), geometry.y(), geometry.width(), geometry.height()); + + if (mOptions.cursor && !mPixmap.isNull()) { + QPainter painter(&mPixmap); + painter.drawPixmap(QCursor::pos(), os::cursor()); } - mPixmap = QApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId()); - */ - } - else { - mPixmap = QApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId()); - } - - if (mOptions.cursor && !mPixmap.isNull()) { - QPainter painter(&mPixmap); - painter.drawPixmap(QCursor::pos(), os::cursor()); - } + mPixmap.setDevicePixelRatio(QApplication::desktop()->devicePixelRatio()); } QString Screenshot::newFileName() const { - if (!mOptions.directory.exists()) { - mOptions.directory.mkpath(mOptions.directory.path()); - } + if (!mOptions.directory.exists()) { + mOptions.directory.mkpath(mOptions.directory.path()); + } - QString naming = Screenshot::getName(mOptions.namingOptions, mOptions.prefix, mOptions.directory); - QString path = QDir::toNativeSeparators(mOptions.directory.path()); + QString naming = Screenshot::getName(mOptions.namingOptions, mOptions.prefix, mOptions.directory); + QString path = QDir::toNativeSeparators(mOptions.directory.path()); - // Cleanup - if (path.at(path.size()-1) != QDir::separator() && !path.isEmpty()) { - path.append(QDir::separator()); - } + // Cleanup + if (path.at(path.size() - 1) != QDir::separator() && !path.isEmpty()) { + path.append(QDir::separator()); + } - QString fileName; - fileName.append(path); - fileName.append(naming); + QString fileName; + fileName.append(path); + fileName.append(naming); - return fileName; + return fileName; } void Screenshot::selectedArea() { - grabDesktop(); + grabDesktop(); - if (mPixmap.isNull()) - return; + if (mPixmap.isNull()) { + return; + } - AreaDialog selector(this); - int result = selector.exec(); + AreaDialog selector(this); + int result = selector.exec(); - if (result == QDialog::Accepted) { - mPixmap = mPixmap.copy(selector.resultRect()); - } - else { - mPixmap = QPixmap(); - } + if (result == QDialog::Accepted) { + mPixmap = mPixmap.copy(selector.resultRect()); + } else { + mPixmap = QPixmap(); + } } void Screenshot::selectedWindow() { - WindowPicker* windowPicker = new WindowPicker; - mPixmapDelay = true; + WindowPicker *windowPicker = new WindowPicker; + mPixmapDelay = true; - connect(windowPicker, SIGNAL(pixmap(QPixmap)), this, SLOT(setPixmap(QPixmap))); + connect(windowPicker, SIGNAL(pixmap(QPixmap)), this, SLOT(setPixmap(QPixmap))); } bool Screenshot::unloadPixmap() { - if (mUnloaded) - return true; + if (mUnloaded) { + return true; + } - // Unloading the pixmap to reduce memory usage during previews - mUnloadFilename = mOptions.directory.path() + QDir::separator() + QString(".lstemp.%1%2").arg(qrand() * qrand() + QDateTime::currentDateTime().toTime_t()).arg(extension()); - mUnloaded = mPixmap.save(mUnloadFilename, 0, mOptions.quality); + // Unloading the pixmap to reduce memory usage during previews + mUnloadFilename = mOptions.directory.path() + QDir::separator() + QString(".lstemp.%1%2").arg(qrand() * qrand() + QDateTime::currentDateTime().toTime_t()).arg(extension()); + mUnloaded = mPixmap.save(mUnloadFilename, 0, mOptions.quality); - if (mUnloaded) { - mPixmap = QPixmap(); - } + if (mUnloaded) { + mPixmap = QPixmap(); + } - return mUnloaded; + return mUnloaded; } void Screenshot::wholeScreen() { - grabDesktop(); + grabDesktop(); } diff --git a/tools/screenshot.h b/tools/screenshot.h index 587be9b..c713cfe 100644 --- a/tools/screenshot.h +++ b/tools/screenshot.h @@ -25,117 +25,111 @@ class Screenshot : public QObject { - Q_OBJECT + Q_OBJECT public: - enum Format - { - PNG = 0, - JPEG = 1, - BMP = 2, - TIFF = 3 - }; - - enum Naming - { - Numeric = 0, - Date = 1, - Timestamp = 2, - Empty = 3 - }; - - enum Mode - { - WholeScreen = 0, - ActiveWindow = 1, - SelectedArea = 2, - SelectedWindow = 3 - }; - - enum Result - { - Fail = 0, - Success = 1, - Cancel = 2 - }; - - struct NamingOptions - { - Naming naming; - bool flip; - int leadingZeros; - QString dateFormat; - }; - - struct Options - { - QString fileName; - Result result; - - Format format; - NamingOptions namingOptions; - QDir directory; - QString prefix; - - int mode; - int quality; - - bool animations; - bool clipboard; - bool imgurClipboard; - bool currentMonitor; - bool cursor; - bool file; - bool magnify; - bool optimize; - bool preview; - bool replace; - bool saveAs; - bool upload; - }; - - Screenshot(QObject *parent, Screenshot::Options options); - ~Screenshot(); - - Screenshot::Options &options(); - QPixmap &pixmap(); - static QString getName(const NamingOptions &options, const QString &prefix, const QDir &directory); - QString &unloadedFileName(); + enum Format { + PNG = 0, + JPEG = 1, + BMP = 2, + TIFF = 3 + }; + + enum Naming { + Numeric = 0, + Date = 1, + Timestamp = 2, + Empty = 3 + }; + + enum Mode { + WholeScreen = 0, + ActiveWindow = 1, + SelectedArea = 2, + SelectedWindow = 3 + }; + + enum Result { + Fail = 0, + Success = 1, + Cancel = 2 + }; + + struct NamingOptions { + Naming naming; + bool flip; + int leadingZeros; + QString dateFormat; + }; + + struct Options { + QString fileName; + Result result; + + Format format; + NamingOptions namingOptions; + QDir directory; + QString prefix; + + int mode; + int quality; + + bool animations; + bool clipboard; + bool imgurClipboard; + bool currentMonitor; + bool cursor; + bool file; + bool magnify; + bool optimize; + bool preview; + bool replace; + bool saveAs; + bool upload; + }; + + Screenshot(QObject *parent, Screenshot::Options options); + ~Screenshot(); + + Screenshot::Options &options(); + QPixmap &pixmap(); + static QString getName(const NamingOptions &options, const QString &prefix, const QDir &directory); + QString &unloadedFileName(); public slots: - void confirm(bool result = true); - void confirmation(); - void discard(); - void markUpload(); - void optimize(); - void optimizationDone(); - void save(); - void setPixmap(QPixmap pixmap); - void take(); - void upload(); - void uploadDone(QString url); + void confirm(bool result = true); + void confirmation(); + void discard(); + void markUpload(); + void optimize(); + void optimizationDone(); + void save(); + void setPixmap(QPixmap pixmap); + void take(); + void upload(); + void uploadDone(QString url); signals: - void askConfirmation(); - void cleanup(); - void finished(); + void askConfirmation(); + void cleanup(); + void finished(); private: - void activeWindow(); - QString extension() const; - void grabDesktop(); - QString newFileName() const; - void selectedArea(); - void selectedWindow(); - bool unloadPixmap(); - void wholeScreen(); + void activeWindow(); + QString extension() const; + void grabDesktop(); + QString newFileName() const; + void selectedArea(); + void selectedWindow(); + bool unloadPixmap(); + void wholeScreen(); private: - Screenshot::Options mOptions; - QPixmap mPixmap; - bool mPixmapDelay; - bool mUnloaded; - QString mUnloadFilename; + Screenshot::Options mOptions; + QPixmap mPixmap; + bool mPixmapDelay; + bool mUnloaded; + QString mUnloadFilename; }; diff --git a/tools/screenshotmanager.cpp b/tools/screenshotmanager.cpp index c0df7d5..2117b02 100644 --- a/tools/screenshotmanager.cpp +++ b/tools/screenshotmanager.cpp @@ -32,100 +32,101 @@ ScreenshotManager::ScreenshotManager(QObject *parent = 0) : QObject(parent) { - if (QFile::exists(qApp->applicationDirPath() + QDir::separator() + "config.ini")) { - mSettings = new QSettings(qApp->applicationDirPath() + QDir::separator() + "config.ini", QSettings::IniFormat); - mPortableMode = true; - mHistoryPath = qApp->applicationDirPath() + QDir::separator(); - } - else { - mSettings = new QSettings(); - mPortableMode = false; - mHistoryPath = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QDir::separator(); - } - - initHistory(); - - connect(Uploader::instance(), SIGNAL(done(QString, QString, QString)), this, SLOT(uploadDone(QString, QString, QString))); + if (QFile::exists(qApp->applicationDirPath() + QDir::separator() + "config.ini")) { + mSettings = new QSettings(qApp->applicationDirPath() + QDir::separator() + "config.ini", QSettings::IniFormat); + mPortableMode = true; + mHistoryPath = qApp->applicationDirPath() + QDir::separator(); + } else { + mSettings = new QSettings(); + mPortableMode = false; + mHistoryPath = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QDir::separator(); + } + + initHistory(); + + connect(Uploader::instance(), SIGNAL(done(QString, QString, QString)), this, SLOT(uploadDone(QString, QString, QString))); } ScreenshotManager::~ScreenshotManager() { - delete mSettings; + delete mSettings; } void ScreenshotManager::initHistory() { - // Creating the SQLite database. - QSqlDatabase history = QSqlDatabase::addDatabase("QSQLITE"); + // Creating the SQLite database. + QSqlDatabase history = QSqlDatabase::addDatabase("QSQLITE"); - QDir hp(mHistoryPath); + QDir hp(mHistoryPath); - if (!hp.exists()) - hp.mkpath(mHistoryPath); + if (!hp.exists()) { + hp.mkpath(mHistoryPath); + } - history.setHostName("localhost"); - history.setDatabaseName(mHistoryPath + "history.sqlite"); + history.setHostName("localhost"); + history.setDatabaseName(mHistoryPath + "history.sqlite"); - if (history.open()) { - history.exec("CREATE TABLE IF NOT EXISTS history (fileName text, URL text, deleteURL text, time integer)"); - } - else { - qCritical() << "Could not open SQLite DB."; - } + if (history.open()) { + history.exec("CREATE TABLE IF NOT EXISTS history (fileName text, URL text, deleteURL text, time integer)"); + } else { + qCritical() << "Could not open SQLite DB."; + } } int ScreenshotManager::activeCount() const { - return mScreenshots.count(); + return mScreenshots.count(); } bool ScreenshotManager::portableMode() { - return mPortableMode; + return mPortableMode; } void ScreenshotManager::saveHistory(QString fileName, QString url, QString deleteHash) { - if (!mSettings->value("/options/history", true).toBool()) - return; + if (!mSettings->value("/options/history", true).toBool()) { + return; + } - QString deleteUrl; + QString deleteUrl; - if (!deleteHash.isEmpty()) - deleteUrl = "https://imgur.com/delete/" + deleteHash; + if (!deleteHash.isEmpty()) { + deleteUrl = "https://imgur.com/delete/" + deleteHash; + } - QSqlQuery query; - query.prepare("INSERT INTO history (fileName, URL, deleteURL, time) VALUES(?, ?, ?, ?)"); - query.addBindValue(fileName); - query.addBindValue(url); - query.addBindValue(deleteUrl); - query.addBindValue(QDateTime::currentMSecsSinceEpoch()); - query.exec(); + QSqlQuery query; + query.prepare("INSERT INTO history (fileName, URL, deleteURL, time) VALUES(?, ?, ?, ?)"); + query.addBindValue(fileName); + query.addBindValue(url); + query.addBindValue(deleteUrl); + query.addBindValue(QDateTime::currentMSecsSinceEpoch()); + query.exec(); } void ScreenshotManager::updateHistory(QString fileName, QString url, QString deleteHash) { - if (!mSettings->value("/options/history", true).toBool() || url.isEmpty()) - return; - - QSqlQuery query; - query.prepare("SELECT fileName FROM history WHERE URL IS NOT EMPTY AND fileName = ?"); - query.addBindValue(fileName); - query.exec(); - - if (query.record().count() > 0) { - QSqlQuery updateQuery; - updateQuery.prepare("UPDATE history SET URL = ?, deleteURL = ?, time = ? WHERE fileName = ?"); - updateQuery.addBindValue(url); - updateQuery.addBindValue("https://imgur.com/delete/" + deleteHash); - updateQuery.addBindValue(QDateTime::currentMSecsSinceEpoch()); - updateQuery.addBindValue(fileName); - - updateQuery.exec(); - } - else { - saveHistory(fileName, url, deleteHash); - } + if (!mSettings->value("/options/history", true).toBool() || url.isEmpty()) { + return; + } + + QSqlQuery query; + query.prepare("SELECT fileName FROM history WHERE URL IS NOT EMPTY AND fileName = ?"); + query.addBindValue(fileName); + query.exec(); + + if (query.record().count() > 0) { + QSqlQuery updateQuery; + updateQuery.prepare("UPDATE history SET URL = ?, deleteURL = ?, time = ? WHERE fileName = ?"); + updateQuery.addBindValue(url); + updateQuery.addBindValue("https://imgur.com/delete/" + deleteHash); + updateQuery.addBindValue(QDateTime::currentMSecsSinceEpoch()); + updateQuery.addBindValue(fileName); + + updateQuery.exec(); + } else { + saveHistory(fileName, url, deleteHash); + } } void ScreenshotManager::removeHistory(QString fileName, qint64 time) @@ -140,75 +141,75 @@ void ScreenshotManager::removeHistory(QString fileName, qint64 time) void ScreenshotManager::clearHistory() { - QSqlQuery clearQuery("DROP TABLE history"); - clearQuery.exec(); + QSqlQuery clearQuery("DROP TABLE history"); + clearQuery.exec(); - initHistory(); + initHistory(); } // void ScreenshotManager::askConfirmation() { - Screenshot* s = qobject_cast(sender()); - emit confirm(s); + Screenshot *s = qobject_cast(sender()); + emit confirm(s); } void ScreenshotManager::cleanup() { - Screenshot* screenshot = qobject_cast(sender()); - emit windowCleanup(screenshot->options()); + Screenshot *screenshot = qobject_cast(sender()); + emit windowCleanup(screenshot->options()); } void ScreenshotManager::finished() { - Screenshot* screenshot = qobject_cast(sender()); - mScreenshots.removeOne(screenshot); - emit activeCountChange(); - screenshot->deleteLater(); + Screenshot *screenshot = qobject_cast(sender()); + mScreenshots.removeOne(screenshot); + emit activeCountChange(); + screenshot->deleteLater(); } void ScreenshotManager::take(Screenshot::Options &options) { - Screenshot* newScreenshot = new Screenshot(this, options); - mScreenshots.append(newScreenshot); + Screenshot *newScreenshot = new Screenshot(this, options); + mScreenshots.append(newScreenshot); - connect(newScreenshot, SIGNAL(askConfirmation()), this, SLOT(askConfirmation())); - connect(newScreenshot, SIGNAL(cleanup()) , this, SLOT(cleanup())); - connect(newScreenshot, SIGNAL(finished()) , this, SLOT(finished())); + connect(newScreenshot, SIGNAL(askConfirmation()), this, SLOT(askConfirmation())); + connect(newScreenshot, SIGNAL(cleanup()) , this, SLOT(cleanup())); + connect(newScreenshot, SIGNAL(finished()) , this, SLOT(finished())); - newScreenshot->take(); + newScreenshot->take(); } void ScreenshotManager::uploadDone(QString fileName, QString url, QString deleteHash) { - foreach (Screenshot* screenshot, mScreenshots) { - if (screenshot->options().fileName == fileName - || screenshot->unloadedFileName() == fileName) { - screenshot->uploadDone(url); - - if (screenshot->options().file) { - updateHistory(fileName, url, deleteHash); - } - else { - saveHistory("", url, deleteHash); - } - - return; + foreach (Screenshot *screenshot, mScreenshots) { + if (screenshot->options().fileName == fileName + || screenshot->unloadedFileName() == fileName) { + screenshot->uploadDone(url); + + if (screenshot->options().file) { + updateHistory(fileName, url, deleteHash); + } else { + saveHistory("", url, deleteHash); + } + + return; + } } - } - // If we get here, it's because the screenshot upload wasn't on the current screenshot list, which means it's a View History/Upload Later upload. - updateHistory(fileName, url, deleteHash); + // If we get here, it's because the screenshot upload wasn't on the current screenshot list, which means it's a View History/Upload Later upload. + updateHistory(fileName, url, deleteHash); } // Singleton -ScreenshotManager* ScreenshotManager::mInstance = 0; +ScreenshotManager *ScreenshotManager::mInstance = 0; ScreenshotManager *ScreenshotManager::instance() { - if (!mInstance) - mInstance = new ScreenshotManager(); + if (!mInstance) { + mInstance = new ScreenshotManager(); + } - return mInstance; + return mInstance; } diff --git a/tools/screenshotmanager.h b/tools/screenshotmanager.h index 98afa0f..e114fb0 100644 --- a/tools/screenshotmanager.h +++ b/tools/screenshotmanager.h @@ -27,48 +27,47 @@ class QSettings; class ScreenshotManager : public QObject { - Q_OBJECT + Q_OBJECT public: - enum State - { - Idle = 0, - Busy = 1, - Disabled = 2 - }; + enum State { + Idle = 0, + Busy = 1, + Disabled = 2 + }; public: - ScreenshotManager(QObject *parent); - ~ScreenshotManager(); - static ScreenshotManager *instance(); + ScreenshotManager(QObject *parent); + ~ScreenshotManager(); + static ScreenshotManager *instance(); - void initHistory(); - int activeCount() const; - bool portableMode(); - void saveHistory(QString fileName, QString url = "", QString deleteHash = ""); - void updateHistory(QString fileName, QString url, QString deleteHash); - void removeHistory(QString fileName, qint64 time); - void clearHistory(); - QSettings *settings() const { return mSettings; } + void initHistory(); + int activeCount() const; + bool portableMode(); + void saveHistory(QString fileName, QString url = "", QString deleteHash = ""); + void updateHistory(QString fileName, QString url, QString deleteHash); + void removeHistory(QString fileName, qint64 time); + void clearHistory(); + QSettings *settings() const { return mSettings; } public slots: - void askConfirmation(); - void cleanup(); - void finished(); - void take(Screenshot::Options &options); - void uploadDone(QString fileName, QString url, QString deleteHash); + void askConfirmation(); + void cleanup(); + void finished(); + void take(Screenshot::Options &options); + void uploadDone(QString fileName, QString url, QString deleteHash); signals: - void confirm(Screenshot* screenshot); - void windowCleanup(Screenshot::Options &options); - void activeCountChange(); + void confirm(Screenshot *screenshot); + void windowCleanup(Screenshot::Options &options); + void activeCountChange(); private: - static ScreenshotManager* mInstance; - QList mScreenshots; - QSettings *mSettings; - QString mHistoryPath; - bool mPortableMode; + static ScreenshotManager *mInstance; + QList mScreenshots; + QSettings *mSettings; + QString mHistoryPath; + bool mPortableMode; }; #endif // SCREENSHOTMANAGER_H diff --git a/tools/uploader/imageuploader.cpp b/tools/uploader/imageuploader.cpp index 8f9cb22..14806ac 100644 --- a/tools/uploader/imageuploader.cpp +++ b/tools/uploader/imageuploader.cpp @@ -1,10 +1,11 @@ #include "imageuploader.h" #include "imguruploader.h" -ImageUploader* ImageUploader::getNewUploader(const QString &name, const QVariantHash &options) +ImageUploader *ImageUploader::getNewUploader(const QString &name, const QVariantHash &options) { - if (name == "imgur") - return new ImgurUploader(options); + if (name == "imgur") { + return new ImgurUploader(options); + } - return 0; + return 0; } diff --git a/tools/uploader/imageuploader.h b/tools/uploader/imageuploader.h index a01aed6..cc5c868 100644 --- a/tools/uploader/imageuploader.h +++ b/tools/uploader/imageuploader.h @@ -7,38 +7,38 @@ class QNetworkReply; class ImageUploader : public QObject { -Q_OBJECT + Q_OBJECT public: - static ImageUploader* getNewUploader(const QString &name, const QVariantHash &options = QVariantHash()); + static ImageUploader *getNewUploader(const QString &name, const QVariantHash &options = QVariantHash()); - enum Error { - FileError, - NetworkError, - HostError, - CancelError, - OtherError - }; + enum Error { + FileError, + NetworkError, + HostError, + CancelError, + OtherError + }; public: - inline ImageUploader(const QVariantHash &options) : QObject(0), mProgress(0), mOptions(options) {} - QVariantHash &options() { return mOptions; } + inline ImageUploader(const QVariantHash &options) : QObject(0), mProgress(0), mOptions(options) {} + QVariantHash &options() { return mOptions; } public slots: - virtual void upload(const QString &fileName) = 0; - virtual void cancel() = 0; - virtual void retry() = 0; - int progress() const { return mProgress; } - void setProgress(int progress) { mProgress = progress; } + virtual void upload(const QString &fileName) = 0; + virtual void cancel() = 0; + virtual void retry() = 0; + int progress() const { return mProgress; } + void setProgress(int progress) { mProgress = progress; } signals: - void uploaded(QString, QString, QString); - void error(Error, QString, QString); - void progressChange(int); + void uploaded(QString, QString, QString); + void error(Error, QString, QString); + void progressChange(int); protected: - QVariantHash mOptions; - int mProgress; + QVariantHash mOptions; + int mProgress; }; diff --git a/tools/uploader/imguruploader.cpp b/tools/uploader/imguruploader.cpp index 04d6e85..fa6172a 100644 --- a/tools/uploader/imguruploader.cpp +++ b/tools/uploader/imguruploader.cpp @@ -6,104 +6,99 @@ ImgurUploader::ImgurUploader(const QVariantHash &options) : ImageUploader(option void ImgurUploader::upload(const QString &fileName) { - QFile *file = new QFile(fileName); + QFile *file = new QFile(fileName); - if (!file->open(QIODevice::ReadOnly)) { - emit error(ImageUploader::FileError, tr("Unable to read screenshot file"), fileName); - file->deleteLater(); - return; - } + if (!file->open(QIODevice::ReadOnly)) { + emit error(ImageUploader::FileError, tr("Unable to read screenshot file"), fileName); + file->deleteLater(); + return; + } - QNetworkRequest request(QUrl("https://api.imgur.com/3/image")); - request.setRawHeader("Authorization", "Client-ID 3ebe94c791445c1"); + QNetworkRequest request(QUrl("https://api.imgur.com/3/image")); + request.setRawHeader("Authorization", "Client-ID 3ebe94c791445c1"); - QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); + QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); - if (!mOptions.value("anonymous", true).toBool()) - { - request.setRawHeader("Authorization", QByteArray("Bearer ") + mOptions.value("access_token").toByteArray()); + if (!mOptions.value("anonymous", true).toBool()) { + request.setRawHeader("Authorization", QByteArray("Bearer ") + mOptions.value("access_token").toByteArray()); - if (!mOptions.value("album").toString().isEmpty()) - { - QHttpPart albumPart; - albumPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"album\"")); - albumPart.setBody(mOptions.value("album").toByteArray()); - multiPart->append(albumPart); + if (!mOptions.value("album").toString().isEmpty()) { + QHttpPart albumPart; + albumPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"album\"")); + albumPart.setBody(mOptions.value("album").toByteArray()); + multiPart->append(albumPart); + } } - } - QHttpPart imagePart; - imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QMimeDatabase().mimeTypeForFile(fileName, QMimeDatabase::MatchExtension).name()); - imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"")); + QHttpPart imagePart; + imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QMimeDatabase().mimeTypeForFile(fileName, QMimeDatabase::MatchExtension).name()); + imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"")); - imagePart.setBodyDevice(file); - file->setParent(multiPart); - multiPart->append(imagePart); + imagePart.setBodyDevice(file); + file->setParent(multiPart); + multiPart->append(imagePart); - QNetworkReply *reply = mOptions.value("networkManager").value()->post(request, multiPart); - reply->setProperty("fileName", fileName); - this->setProperty("fileName", fileName); + QNetworkReply *reply = mOptions.value("networkManager").value()->post(request, multiPart); + reply->setProperty("fileName", fileName); + this->setProperty("fileName", fileName); - connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress(qint64, qint64))); - connect(this , SIGNAL(cancelRequest()), reply, SLOT(abort())); - connect(this , SIGNAL(cancelRequest()), reply, SLOT(deleteLater())); - connect(reply, SIGNAL(finished()), this, SLOT(finished())); + connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(uploadProgress(qint64, qint64))); + connect(this , SIGNAL(cancelRequest()), reply, SLOT(abort())); + connect(this , SIGNAL(cancelRequest()), reply, SLOT(deleteLater())); + connect(reply, SIGNAL(finished()), this, SLOT(finished())); } void ImgurUploader::retry() { - upload(property("fileName").toString()); + upload(property("fileName").toString()); } void ImgurUploader::cancel() { - emit cancelRequest(); + emit cancelRequest(); } void ImgurUploader::finished() { - QNetworkReply* reply = qobject_cast(sender()); - reply->deleteLater(); - - QString fileName = reply->property("fileName").toString(); - - if (reply->error() != QNetworkReply::NoError) { - if (reply->error() == QNetworkReply::OperationCanceledError) { - emit error(ImageUploader::CancelError, "", fileName); - } - else if (reply->error() == QNetworkReply::ContentOperationNotPermittedError || - reply->error() == QNetworkReply::AuthenticationRequiredError) { - emit needAuthRefresh(); + QNetworkReply *reply = qobject_cast(sender()); + reply->deleteLater(); + + QString fileName = reply->property("fileName").toString(); + + if (reply->error() != QNetworkReply::NoError) { + if (reply->error() == QNetworkReply::OperationCanceledError) { + emit error(ImageUploader::CancelError, "", fileName); + } else if (reply->error() == QNetworkReply::ContentOperationNotPermittedError || + reply->error() == QNetworkReply::AuthenticationRequiredError) { + emit needAuthRefresh(); + } else { + emit error(ImageUploader::NetworkError, reply->errorString(), fileName); + } + + return; } - else { - emit error(ImageUploader::NetworkError, reply->errorString(), fileName); - } - - return; - } - if (reply->rawHeader("X-RateLimit-Remaining") == "0") { - emit error(ImageUploader::HostError, tr("Imgur upload limit reached"), fileName); - return; - } + if (reply->rawHeader("X-RateLimit-Remaining") == "0") { + emit error(ImageUploader::HostError, tr("Imgur upload limit reached"), fileName); + return; + } - QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object(); + QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object(); - if (imgurResponse.value("success").toBool() == true && imgurResponse.value("status").toInt() == 200) { - QJsonObject imageData = imgurResponse.value("data").toObject(); + if (imgurResponse.value("success").toBool() == true && imgurResponse.value("status").toInt() == 200) { + QJsonObject imageData = imgurResponse.value("data").toObject(); - emit uploaded(fileName, imageData["link"].toString(), imageData["deletehash"].toString()); - } - else { - emit error(ImageUploader::HostError, tr("Imgur error"), fileName); - } + emit uploaded(fileName, imageData["link"].toString(), imageData["deletehash"].toString()); + } else { + emit error(ImageUploader::HostError, tr("Imgur error"), fileName); + } } void ImgurUploader::uploadProgress(qint64 bytesReceived, qint64 bytesTotal) { - float b = (float) bytesReceived/bytesTotal; - int p = qRound(b*100); - setProgress(p); - emit progressChange(p); + float b = (float) bytesReceived / bytesTotal; + int p = qRound(b * 100); + setProgress(p); + emit progressChange(p); } diff --git a/tools/uploader/imguruploader.h b/tools/uploader/imguruploader.h index f88df61..769f9eb 100644 --- a/tools/uploader/imguruploader.h +++ b/tools/uploader/imguruploader.h @@ -8,23 +8,23 @@ class ImgurUploader : public ImageUploader { -Q_OBJECT + Q_OBJECT public: - ImgurUploader(const QVariantHash &options); + ImgurUploader(const QVariantHash &options); public slots: - void upload(const QString &fileName); - void retry(); - void cancel(); + void upload(const QString &fileName); + void retry(); + void cancel(); private slots: - void finished(); - void uploadProgress(qint64 bytesReceived, qint64 bytesTotal); + void finished(); + void uploadProgress(qint64 bytesReceived, qint64 bytesTotal); signals: - void cancelRequest(); - void needAuthRefresh(); + void cancelRequest(); + void needAuthRefresh(); }; diff --git a/tools/uploader/uploader.cpp b/tools/uploader/uploader.cpp index 399127a..ddf5ab2 100644 --- a/tools/uploader/uploader.cpp +++ b/tools/uploader/uploader.cpp @@ -23,182 +23,182 @@ #include #include -Uploader* Uploader::mInstance = 0; +Uploader *Uploader::mInstance = 0; Uploader::Uploader(QObject *parent) : QObject(parent), mProgress(0) { - mNetworkAccessManager = new QNetworkAccessManager(this); + mNetworkAccessManager = new QNetworkAccessManager(this); } Uploader *Uploader::instance() { - if (!mInstance) - mInstance = new Uploader(); + if (!mInstance) { + mInstance = new Uploader(); + } - return mInstance; + return mInstance; } int Uploader::progress() const { - return mProgress; + return mProgress; } -QNetworkAccessManager* Uploader::nam() +QNetworkAccessManager *Uploader::nam() { - return mNetworkAccessManager; + return mNetworkAccessManager; } QString Uploader::lastUrl() const { - return mLastUrl; + return mLastUrl; } void Uploader::cancel() { - mUploaders.clear(); - mProgress = 0; - emit cancelAll(); + mUploaders.clear(); + mProgress = 0; + emit cancelAll(); } void Uploader::upload(const QString &fileName) { - if (fileName.isEmpty()) { - return; - } - - QVariantHash options; - QSettings *s = ScreenshotManager::instance()->settings(); - options["type"] = "imgur"; - options["networkManager"].setValue(mNetworkAccessManager); - options["anonymous"] = s->value("upload/imgur/anonymous", true).toBool(); - options["album"] = s->value("upload/imgur/album", "").toString(); - options["access_token"] = s->value("upload/imgur/access_token", "").toString(); - options["refresh_token"] = s->value("upload/imgur/refresh_token", "").toString(); - - if (options["access_token"].toString().isEmpty() || options["refresh_token"].toString().isEmpty()) - { - options["anonymous"] = true; - } - - ImgurUploader *uploader = new ImgurUploader(options); - - connect(uploader, &ImgurUploader::uploaded , this, &Uploader::uploaded); - connect(uploader, &ImgurUploader::error , this, &Uploader::uploaderError); - connect(uploader, &ImgurUploader::progressChange , this, &Uploader::progressChange); - connect(uploader, &ImgurUploader::needAuthRefresh, this, &Uploader::imgurAuthRefresh); - - connect(this , SIGNAL(cancelAll()), uploader, SLOT(cancel())); - - uploader->upload(fileName); - mUploaders.append(uploader); + if (fileName.isEmpty()) { + return; + } + + QVariantHash options; + QSettings *s = ScreenshotManager::instance()->settings(); + options["type"] = "imgur"; + options["networkManager"].setValue(mNetworkAccessManager); + options["anonymous"] = s->value("upload/imgur/anonymous", true).toBool(); + options["album"] = s->value("upload/imgur/album", "").toString(); + options["access_token"] = s->value("upload/imgur/access_token", "").toString(); + options["refresh_token"] = s->value("upload/imgur/refresh_token", "").toString(); + + if (options["access_token"].toString().isEmpty() || options["refresh_token"].toString().isEmpty()) { + options["anonymous"] = true; + } + + ImgurUploader *uploader = new ImgurUploader(options); + + connect(uploader, &ImgurUploader::uploaded , this, &Uploader::uploaded); + connect(uploader, &ImgurUploader::error , this, &Uploader::uploaderError); + connect(uploader, &ImgurUploader::progressChange , this, &Uploader::progressChange); + connect(uploader, &ImgurUploader::needAuthRefresh, this, &Uploader::imgurAuthRefresh); + + connect(this , SIGNAL(cancelAll()), uploader, SLOT(cancel())); + + uploader->upload(fileName); + mUploaders.append(uploader); } void Uploader::uploaded(const QString &file, const QString &url, const QString &deleteHash) { - mLastUrl = url; - mUploaders.removeAll(qobject_cast(sender())); + mLastUrl = url; + mUploaders.removeAll(qobject_cast(sender())); - if (mUploaders.isEmpty()) - mProgress = 0; + if (mUploaders.isEmpty()) { + mProgress = 0; + } - sender()->deleteLater(); - emit done(file, url, deleteHash); + sender()->deleteLater(); + emit done(file, url, deleteHash); } void Uploader::imgurAuthRefresh() { - for (int i = 0; i < mUploaders.size(); ++i) { - if (mUploaders[i]->options().value("type") == "imgur") { - mUploaders[i]->cancel(); + for (int i = 0; i < mUploaders.size(); ++i) { + if (mUploaders[i]->options().value("type") == "imgur") { + mUploaders[i]->cancel(); + } } - } - - QByteArray parameters; - parameters.append(QString("refresh_token=").toUtf8()); - parameters.append(QUrl::toPercentEncoding(ScreenshotManager::instance()->settings()->value("upload/imgur/refresh_token").toString())); - parameters.append(QString("&client_id=").toUtf8()); - parameters.append(QUrl::toPercentEncoding("3ebe94c791445c1")); - parameters.append(QString("&client_secret=").toUtf8()); - parameters.append(QUrl::toPercentEncoding("0546b05d6a80b2092dcea86c57b792c9c9faebf0")); // TODO: TA.png - parameters.append(QString("&grant_type=refresh_token").toUtf8()); - - QNetworkRequest request(QUrl("https://api.imgur.com/oauth2/token")); - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - - QNetworkReply* reply = Uploader::instance()->nam()->post(request, parameters); - connect(reply, SIGNAL(finished()), this, SLOT(imgurToken())); + + QByteArray parameters; + parameters.append(QString("refresh_token=").toUtf8()); + parameters.append(QUrl::toPercentEncoding(ScreenshotManager::instance()->settings()->value("upload/imgur/refresh_token").toString())); + parameters.append(QString("&client_id=").toUtf8()); + parameters.append(QUrl::toPercentEncoding("3ebe94c791445c1")); + parameters.append(QString("&client_secret=").toUtf8()); + parameters.append(QUrl::toPercentEncoding("0546b05d6a80b2092dcea86c57b792c9c9faebf0")); // TODO: TA.png + parameters.append(QString("&grant_type=refresh_token").toUtf8()); + + QNetworkRequest request(QUrl("https://api.imgur.com/oauth2/token")); + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + + QNetworkReply *reply = Uploader::instance()->nam()->post(request, parameters); + connect(reply, SIGNAL(finished()), this, SLOT(imgurToken())); } void Uploader::imgurToken() { - QNetworkReply* reply = qobject_cast(sender()); + QNetworkReply *reply = qobject_cast(sender()); - if (reply->error() != QNetworkReply::NoError) { - emit error(reply->errorString()); - return; - } + if (reply->error() != QNetworkReply::NoError) { + emit error(reply->errorString()); + return; + } - QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object(); + QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object(); - QSettings* s = ScreenshotManager::instance()->settings(); - s->setValue("upload/imgur/access_token" , imgurResponse["access_token"].toString()); - s->setValue("upload/imgur/refresh_token" , imgurResponse["refresh_token"].toString()); - s->setValue("upload/imgur/account_username", imgurResponse["account_username"].toString()); - s->setValue("upload/imgur/expires_in" , imgurResponse["expires_in"].toString()); + QSettings *s = ScreenshotManager::instance()->settings(); + s->setValue("upload/imgur/access_token" , imgurResponse["access_token"].toString()); + s->setValue("upload/imgur/refresh_token" , imgurResponse["refresh_token"].toString()); + s->setValue("upload/imgur/account_username", imgurResponse["account_username"].toString()); + s->setValue("upload/imgur/expires_in" , imgurResponse["expires_in"].toString()); - for (int i = 0; i < mUploaders.size(); ++i) { - if (mUploaders[i]->options().value("type") == "imgur") { - mUploaders[i]->options().remove("access_token"); - mUploaders[i]->options().remove("refresh_token"); + for (int i = 0; i < mUploaders.size(); ++i) { + if (mUploaders[i]->options().value("type") == "imgur") { + mUploaders[i]->options().remove("access_token"); + mUploaders[i]->options().remove("refresh_token"); - mUploaders[i]->options().insert("access_token" , imgurResponse["access_token"].toString()); - mUploaders[i]->options().insert("refresh_token", imgurResponse["refresh_token"].toString()); + mUploaders[i]->options().insert("access_token" , imgurResponse["access_token"].toString()); + mUploaders[i]->options().insert("refresh_token", imgurResponse["refresh_token"].toString()); - mUploaders[i]->retry(); + mUploaders[i]->retry(); + } } - } - emit imgurAuthRefreshed(); + emit imgurAuthRefreshed(); } void Uploader::uploaderError(ImageUploader::Error code, QString errorString, QString fileName) { - mUploaders.removeAll(qobject_cast(sender())); - sender()->deleteLater(); - mProgress = 0; + mUploaders.removeAll(qobject_cast(sender())); + sender()->deleteLater(); + mProgress = 0; - if (code != ImageUploader::CancelError) { - if (errorString.isEmpty()) { - emit error(tr("Upload Error ") + code); - } - else { - emit error(errorString); + if (code != ImageUploader::CancelError) { + if (errorString.isEmpty()) { + emit error(tr("Upload Error ") + code); + } else { + emit error(errorString); + } } - } - emit done(fileName, "", ""); + emit done(fileName, "", ""); } int Uploader::uploading() { - return mUploaders.count(); + return mUploaders.count(); } void Uploader::progressChange(int p) { - if (mUploaders.size() <= 0) { - mProgress = p; - emit progress(p); - return; - } + if (mUploaders.size() <= 0) { + mProgress = p; + emit progress(p); + return; + } - int totalProgress = 0; + int totalProgress = 0; - for (int i = 0; i < mUploaders.size(); ++i) { - totalProgress += mUploaders[i]->progress(); - } + for (int i = 0; i < mUploaders.size(); ++i) { + totalProgress += mUploaders[i]->progress(); + } - mProgress = totalProgress / mUploaders.size(); - emit progress(mProgress); + mProgress = totalProgress / mUploaders.size(); + emit progress(mProgress); } diff --git a/tools/uploader/uploader.h b/tools/uploader/uploader.h index c0d63f9..65eff72 100644 --- a/tools/uploader/uploader.h +++ b/tools/uploader/uploader.h @@ -25,40 +25,40 @@ class Uploader : public QObject { - Q_OBJECT + Q_OBJECT public: - Uploader(QObject *parent = 0); - static Uploader* instance(); - QString lastUrl() const; - int progress() const; - QNetworkAccessManager *nam(); + Uploader(QObject *parent = 0); + static Uploader *instance(); + QString lastUrl() const; + int progress() const; + QNetworkAccessManager *nam(); public slots: - void cancel(); - //void error(const QString &file, const QtImgur::Error e); - void upload(const QString &fileName); - void uploaded(const QString &fileName, const QString &url, const QString &deleteHash); - void uploaderError(ImageUploader::Error code, QString errorString, QString fileName); - int uploading(); - void progressChange(int p); - void imgurAuthRefresh(); - void imgurToken(); + void cancel(); + //void error(const QString &file, const QtImgur::Error e); + void upload(const QString &fileName); + void uploaded(const QString &fileName, const QString &url, const QString &deleteHash); + void uploaderError(ImageUploader::Error code, QString errorString, QString fileName); + int uploading(); + void progressChange(int p); + void imgurAuthRefresh(); + void imgurToken(); signals: - void done(QString, QString, QString); - void error(QString); - void progress(int); - void cancelAll(); - void imgurAuthRefreshed(); + void done(QString, QString, QString); + void error(QString); + void progress(int); + void cancelAll(); + void imgurAuthRefreshed(); private: - static Uploader* mInstance; - QNetworkAccessManager *mNetworkAccessManager; + static Uploader *mInstance; + QNetworkAccessManager *mNetworkAccessManager; - int mProgress; - QString mLastUrl; - QList mUploaders; + int mProgress; + QString mLastUrl; + QList mUploaders; }; #endif // UPLOADER_H diff --git a/tools/windowpicker.cpp b/tools/windowpicker.cpp index 7af5898..e2be937 100644 --- a/tools/windowpicker.cpp +++ b/tools/windowpicker.cpp @@ -30,280 +30,275 @@ #include "os.h" #if defined(Q_OS_WIN) - #include - #include + #include + #include -#ifdef _WIN64 - #define GCL_HICON GCLP_HICON - #define GCL_HICONSM GCLP_HICONSM -#endif + #ifdef _WIN64 + #define GCL_HICON GCLP_HICON + #define GCL_HICONSM GCLP_HICONSM + #endif #elif defined(Q_OS_LINUX) - #include - #include - #include - #include - #include + #include + #include + #include + #include + #include #endif WindowPicker::WindowPicker() : QWidget(0), mCrosshair(":/icons/picker"), mWindowLabel(0), mTaken(false) { #if defined(Q_OS_WIN) - setWindowFlags(Qt::SplashScreen | Qt::WindowStaysOnTopHint); + setWindowFlags(Qt::SplashScreen | Qt::WindowStaysOnTopHint); #elif defined(Q_OS_LINUX) - setWindowFlags(Qt::WindowStaysOnTopHint); + setWindowFlags(Qt::WindowStaysOnTopHint); #endif - setWindowTitle(tr("Lightscreen Window Picker")); - setStyleSheet("QWidget { color: #000; } #frame { padding: 7px 10px; border: 4px solid #232323; background-color: rgba(250, 250, 250, 255); }"); - - QLabel *helpLabel = new QLabel(tr("Grab the window picker by clicking and holding down the mouse button, then drag it to the window of your choice and release it to capture."), this); - helpLabel->setMinimumWidth(400); - helpLabel->setMaximumWidth(400); - helpLabel->setWordWrap(true); - - mWindowIcon = new QLabel(this); - mWindowIcon->setMinimumSize(22, 22); - mWindowIcon->setMaximumSize(22, 22); - mWindowIcon->setScaledContents(true); - - mWindowLabel = new QLabel(tr(" - Start dragging to select windows"), this); - mWindowLabel->setStyleSheet("font-weight: bold"); - - mCrosshairLabel = new QLabel(this); - mCrosshairLabel->setAlignment(Qt::AlignHCenter); - mCrosshairLabel->setPixmap(mCrosshair); - - QPushButton *closeButton = new QPushButton(tr("Close")); - connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); - - QHBoxLayout *windowLayout = new QHBoxLayout; - windowLayout->addWidget(mWindowIcon); - windowLayout->addWidget(mWindowLabel); - windowLayout->setMargin(0); - - QHBoxLayout *buttonLayout = new QHBoxLayout; - buttonLayout->addStretch(0); - buttonLayout->addWidget(closeButton); - buttonLayout->setMargin(0); - - QHBoxLayout *crosshairLayout = new QHBoxLayout; - crosshairLayout->addStretch(0); - crosshairLayout->addWidget(mCrosshairLabel); - crosshairLayout->addStretch(0); - crosshairLayout->setMargin(0); - - QVBoxLayout *fl = new QVBoxLayout; - fl->addWidget(helpLabel); - fl->addLayout(windowLayout); - fl->addLayout(crosshairLayout); - fl->addLayout(buttonLayout); - fl->setMargin(0); - - QFrame *frame = new QFrame(this); - frame->setObjectName("frame"); - frame->setLayout(fl); - - QVBoxLayout *l = new QVBoxLayout; - l->setMargin(0); - l->addWidget(frame); - - setLayout(l); - - resize(sizeHint()); - move(QApplication::desktop()->screenGeometry(QApplication::desktop()->screenNumber(QCursor::pos())).center()-QPoint(width()/2, height()/2)); - show(); + setWindowTitle(tr("Lightscreen Window Picker")); + setStyleSheet("QWidget { color: #000; } #frame { padding: 7px 10px; border: 4px solid #232323; background-color: rgba(250, 250, 250, 255); }"); + + QLabel *helpLabel = new QLabel(tr("Grab the window picker by clicking and holding down the mouse button, then drag it to the window of your choice and release it to capture."), this); + helpLabel->setMinimumWidth(400); + helpLabel->setMaximumWidth(400); + helpLabel->setWordWrap(true); + + mWindowIcon = new QLabel(this); + mWindowIcon->setMinimumSize(22, 22); + mWindowIcon->setMaximumSize(22, 22); + mWindowIcon->setScaledContents(true); + + mWindowLabel = new QLabel(tr(" - Start dragging to select windows"), this); + mWindowLabel->setStyleSheet("font-weight: bold"); + + mCrosshairLabel = new QLabel(this); + mCrosshairLabel->setAlignment(Qt::AlignHCenter); + mCrosshairLabel->setPixmap(mCrosshair); + + QPushButton *closeButton = new QPushButton(tr("Close")); + connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); + + QHBoxLayout *windowLayout = new QHBoxLayout; + windowLayout->addWidget(mWindowIcon); + windowLayout->addWidget(mWindowLabel); + windowLayout->setMargin(0); + + QHBoxLayout *buttonLayout = new QHBoxLayout; + buttonLayout->addStretch(0); + buttonLayout->addWidget(closeButton); + buttonLayout->setMargin(0); + + QHBoxLayout *crosshairLayout = new QHBoxLayout; + crosshairLayout->addStretch(0); + crosshairLayout->addWidget(mCrosshairLabel); + crosshairLayout->addStretch(0); + crosshairLayout->setMargin(0); + + QVBoxLayout *fl = new QVBoxLayout; + fl->addWidget(helpLabel); + fl->addLayout(windowLayout); + fl->addLayout(crosshairLayout); + fl->addLayout(buttonLayout); + fl->setMargin(0); + + QFrame *frame = new QFrame(this); + frame->setObjectName("frame"); + frame->setLayout(fl); + + QVBoxLayout *l = new QVBoxLayout; + l->setMargin(0); + l->addWidget(frame); + + setLayout(l); + + resize(sizeHint()); + move(QApplication::desktop()->screenGeometry(QApplication::desktop()->screenNumber(QCursor::pos())).center() - QPoint(width() / 2, height() / 2)); + show(); } -WindowPicker::~WindowPicker() { - qApp->restoreOverrideCursor(); +WindowPicker::~WindowPicker() +{ + qApp->restoreOverrideCursor(); } -void WindowPicker::cancel() { - mWindowIcon->setPixmap(QPixmap()); - mCrosshairLabel->setPixmap(mCrosshair); - qApp->restoreOverrideCursor(); +void WindowPicker::cancel() +{ + mWindowIcon->setPixmap(QPixmap()); + mCrosshairLabel->setPixmap(mCrosshair); + qApp->restoreOverrideCursor(); } -void WindowPicker::closeEvent(QCloseEvent*) +void WindowPicker::closeEvent(QCloseEvent *) { - if (!mTaken) - emit pixmap(QPixmap()); + if (!mTaken) { + emit pixmap(QPixmap()); + } - qApp->restoreOverrideCursor(); - deleteLater(); + qApp->restoreOverrideCursor(); + deleteLater(); } void WindowPicker::mouseMoveEvent(QMouseEvent *event) { - QString windowName; + QString windowName; #if defined(Q_OS_WIN) - POINT mousePos; - mousePos.x = event->globalX(); - mousePos.y = event->globalY(); + POINT mousePos; + mousePos.x = event->globalX(); + mousePos.y = event->globalY(); - HWND cWindow = GetAncestor(WindowFromPoint(mousePos), GA_ROOT); + HWND cWindow = GetAncestor(WindowFromPoint(mousePos), GA_ROOT); - mCurrentWindow = (WId) cWindow; + mCurrentWindow = (WId) cWindow; - if (mCurrentWindow == winId()) { - mWindowIcon->setPixmap(QPixmap()); - mWindowLabel->setText(""); - return; - } + if (mCurrentWindow == winId()) { + mWindowIcon->setPixmap(QPixmap()); + mWindowLabel->setText(""); + return; + } - // Text - WCHAR str[60]; - HICON icon; + // Text + WCHAR str[60]; + HICON icon; - ::GetWindowText((HWND)mCurrentWindow, str, 60); - windowName = QString::fromWCharArray(str); - /// + ::GetWindowText((HWND)mCurrentWindow, str, 60); + windowName = QString::fromWCharArray(str); + /// - // Retrieving the application icon - icon = (HICON)::GetClassLong((HWND)mCurrentWindow, GCL_HICON); + // Retrieving the application icon + icon = (HICON)::GetClassLong((HWND)mCurrentWindow, GCL_HICON); - if (icon != NULL) { - mWindowIcon->setPixmap(QtWin::fromHICON(icon)); - } - else { - mWindowIcon->setPixmap(QPixmap()); - } + if (icon != NULL) { + mWindowIcon->setPixmap(QtWin::fromHICON(icon)); + } else { + mWindowIcon->setPixmap(QPixmap()); + } #elif defined(Q_OS_LINUX) - Window cWindow = os::windowUnderCursor(false); + Window cWindow = os::windowUnderCursor(false); - if (cWindow == mCurrentWindow) { - return; - } + if (cWindow == mCurrentWindow) { + return; + } - mCurrentWindow = cWindow; + mCurrentWindow = cWindow; - if (mCurrentWindow == winId()) { - mWindowIcon->setPixmap(QPixmap()); - mWindowLabel->setText(""); - return; - } - - // Getting the window name property. - XTextProperty tp; - char **text; - int count; - - if (XGetTextProperty(QX11Info::display(), cWindow, &tp, XA_WM_NAME) != 0 && tp.value != NULL ) { - if (tp.encoding == XA_STRING) { - windowName = QString::fromLocal8Bit((const char*) tp.value); + if (mCurrentWindow == winId()) { + mWindowIcon->setPixmap(QPixmap()); + mWindowLabel->setText(""); + return; } - else if (XmbTextPropertyToTextList( QX11Info::display(), &tp, &text, &count) == Success && - text != NULL && count > 0) { - windowName = QString::fromLocal8Bit(text[0]); - XFreeStringList(text); + + // Getting the window name property. + XTextProperty tp; + char **text; + int count; + + if (XGetTextProperty(QX11Info::display(), cWindow, &tp, XA_WM_NAME) != 0 && tp.value != NULL) { + if (tp.encoding == XA_STRING) { + windowName = QString::fromLocal8Bit((const char *) tp.value); + } else if (XmbTextPropertyToTextList(QX11Info::display(), &tp, &text, &count) == Success && + text != NULL && count > 0) { + windowName = QString::fromLocal8Bit(text[0]); + XFreeStringList(text); + } + + XFree(tp.value); } - XFree(tp.value); - } - - // Retrieving the _NET_WM_ICON property. - Atom type_ret = None; - unsigned char *data = 0; - int format = 0; - unsigned long n = 0; - unsigned long extra = 0; - int width = 0; - int height = 0; - - Atom _net_wm_icon = XInternAtom(QX11Info::display(), "_NET_WM_ICON", False); - - if (XGetWindowProperty(QX11Info::display(), cWindow, _net_wm_icon, 0, 1, False, - XA_CARDINAL, &type_ret, &format, &n, &extra, (unsigned char **)&data) == Success && data) - { - width = data[0]; - XFree(data); - } - - if (XGetWindowProperty(QX11Info::display(), cWindow, _net_wm_icon, 1, 1, False, - XA_CARDINAL, &type_ret, &format, &n, &extra, (unsigned char **)&data) == Success && data) - { - height = data[0]; - XFree(data); - } - - if (XGetWindowProperty(QX11Info::display(), cWindow, _net_wm_icon, 2, width*height, False, - XA_CARDINAL, &type_ret, &format, &n, &extra, (unsigned char **)&data) == Success && data) - { - QImage img(data, width, height, QImage::Format_ARGB32); - mWindowIcon->setPixmap(QPixmap::fromImage(img)); - XFree(data); - } - else { - mWindowIcon->setPixmap(QPixmap()); - } + // Retrieving the _NET_WM_ICON property. + Atom type_ret = None; + unsigned char *data = 0; + int format = 0; + unsigned long n = 0; + unsigned long extra = 0; + int width = 0; + int height = 0; + + Atom _net_wm_icon = XInternAtom(QX11Info::display(), "_NET_WM_ICON", False); + + if (XGetWindowProperty(QX11Info::display(), cWindow, _net_wm_icon, 0, 1, False, + XA_CARDINAL, &type_ret, &format, &n, &extra, (unsigned char **)&data) == Success && data) { + width = data[0]; + XFree(data); + } + + if (XGetWindowProperty(QX11Info::display(), cWindow, _net_wm_icon, 1, 1, False, + XA_CARDINAL, &type_ret, &format, &n, &extra, (unsigned char **)&data) == Success && data) { + height = data[0]; + XFree(data); + } + + if (XGetWindowProperty(QX11Info::display(), cWindow, _net_wm_icon, 2, width * height, False, + XA_CARDINAL, &type_ret, &format, &n, &extra, (unsigned char **)&data) == Success && data) { + QImage img(data, width, height, QImage::Format_ARGB32); + mWindowIcon->setPixmap(QPixmap::fromImage(img)); + XFree(data); + } else { + mWindowIcon->setPixmap(QPixmap()); + } #endif - QString windowText; - - if (!mWindowIcon->pixmap()) { - windowText = QString(" - %1").arg(windowName); - } - else { - windowText = windowName; - } - - if (windowText == " - ") { - mWindowLabel->setText(""); - return; - } - - if (windowText.length() == 62) { - mWindowLabel->setText(windowText + "..."); - } - else { - mWindowLabel->setText(windowText); - } + QString windowText; + + if (!mWindowIcon->pixmap()) { + windowText = QString(" - %1").arg(windowName); + } else { + windowText = windowName; + } + + if (windowText == " - ") { + mWindowLabel->setText(""); + return; + } + + if (windowText.length() == 62) { + mWindowLabel->setText(windowText + "..."); + } else { + mWindowLabel->setText(windowText); + } } void WindowPicker::mousePressEvent(QMouseEvent *event) { - qApp->setOverrideCursor(QCursor(mCrosshair)); - mCrosshairLabel->setMinimumWidth(mCrosshairLabel->width()); - mCrosshairLabel->setMinimumHeight(mCrosshairLabel->height()); - mCrosshairLabel->setPixmap(QPixmap()); - QWidget::mousePressEvent(event); + qApp->setOverrideCursor(QCursor(mCrosshair)); + mCrosshairLabel->setMinimumWidth(mCrosshairLabel->width()); + mCrosshairLabel->setMinimumHeight(mCrosshairLabel->height()); + mCrosshairLabel->setPixmap(QPixmap()); + QWidget::mousePressEvent(event); } void WindowPicker::mouseReleaseEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton) { + if (event->button() == Qt::LeftButton) { #if defined(Q_OS_WIN) - POINT mousePos; - mousePos.x = event->globalX(); - mousePos.y = event->globalY(); + POINT mousePos; + mousePos.x = event->globalX(); + mousePos.y = event->globalY(); - HWND nativeWindow = GetAncestor(WindowFromPoint(mousePos), GA_ROOT); + HWND nativeWindow = GetAncestor(WindowFromPoint(mousePos), GA_ROOT); #elif defined(Q_OS_LINUX) - Window nativeWindow = os::windowUnderCursor(false); + Window nativeWindow = os::windowUnderCursor(false); #endif - if ((WId)nativeWindow == winId()) { - cancel(); - return; - } + if ((WId)nativeWindow == winId()) { + cancel(); + return; + } - mTaken = true; + mTaken = true; - setWindowFlags(windowFlags() ^ Qt::WindowStaysOnTopHint); - close(); + setWindowFlags(windowFlags() ^ Qt::WindowStaysOnTopHint); + close(); #ifdef Q_OS_LINUX - emit pixmap(QPixmap::grabWindow(mCurrentWindow)); + emit pixmap(QPixmap::grabWindow(mCurrentWindow)); #else - emit pixmap(os::grabWindow((WId)nativeWindow)); + emit pixmap(os::grabWindow((WId)nativeWindow)); #endif - return; - } + return; + } - close(); + close(); } diff --git a/tools/windowpicker.h b/tools/windowpicker.h index d3471b5..f08b7f3 100644 --- a/tools/windowpicker.h +++ b/tools/windowpicker.h @@ -26,31 +26,31 @@ class QRect; class QRubberBand; class WindowPicker : public QWidget { - Q_OBJECT + Q_OBJECT public: - WindowPicker(); - ~WindowPicker(); + WindowPicker(); + ~WindowPicker(); signals: - void pixmap(QPixmap pixmap); + void pixmap(QPixmap pixmap); protected: - void closeEvent(QCloseEvent*); - void mouseMoveEvent(QMouseEvent *event); - void mousePressEvent(QMouseEvent *event); - void mouseReleaseEvent(QMouseEvent *event); + void closeEvent(QCloseEvent *); + void mouseMoveEvent(QMouseEvent *event); + void mousePressEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); private: - void cancel(); + void cancel(); private: - QPixmap mCrosshair; - QLabel *mCrosshairLabel; - QLabel *mWindowIcon; - QLabel *mWindowLabel; - WId mCurrentWindow; - bool mTaken; + QPixmap mCrosshair; + QLabel *mCrosshairLabel; + QLabel *mWindowIcon; + QLabel *mWindowLabel; + WId mCurrentWindow; + bool mTaken; }; #endif // WINDOWPICKER_H diff --git a/updater/updater.cpp b/updater/updater.cpp index 9eeb5da..d0d7693 100644 --- a/updater/updater.cpp +++ b/updater/updater.cpp @@ -27,38 +27,38 @@ #include "../dialogs/updaterdialog.cpp" Updater::Updater(QObject *parent) : - QObject(parent) + QObject(parent) { - connect(&mNetwork, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*))); + connect(&mNetwork, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished(QNetworkReply *))); } void Updater::check() { - QString platform = "unknown"; + QString platform = "unknown"; #ifdef Q_OS_WIN - platform = QString("Windows_%1").arg(QSysInfo::WindowsVersion); + platform = QString("Windows_%1").arg(QSysInfo::WindowsVersion); #else - platform = "Linux"; + platform = "Linux"; #endif - QNetworkRequest request(QUrl("https://lightscreen.com.ar/version?from=" + qApp->applicationVersion() + "&platform=" + platform)); - mNetwork.get(request); + QNetworkRequest request(QUrl("https://lightscreen.com.ar/version?from=" + qApp->applicationVersion() + "&platform=" + platform)); + mNetwork.get(request); } void Updater::checkWithFeedback() { - UpdaterDialog updaterDialog; - connect(this, SIGNAL(done(bool)), &updaterDialog, SLOT(updateDone(bool))); + UpdaterDialog updaterDialog; + connect(this, SIGNAL(done(bool)), &updaterDialog, SLOT(updateDone(bool))); - check(); - updaterDialog.exec(); + check(); + updaterDialog.exec(); } void Updater::finished(QNetworkReply *reply) { - QByteArray data = reply->readAll(); - double version = QString(data).toDouble(); + QByteArray data = reply->readAll(); + double version = QString(data).toDouble(); - emit done((version > qApp->applicationVersion().toDouble())); + emit done((version > qApp->applicationVersion().toDouble())); } diff --git a/updater/updater.h b/updater/updater.h index 89a08eb..e71cb42 100644 --- a/updater/updater.h +++ b/updater/updater.h @@ -24,22 +24,22 @@ class Updater : public QObject { - Q_OBJECT + Q_OBJECT public: - Updater(QObject *parent = 0); + Updater(QObject *parent = 0); signals: - void done(bool result); + void done(bool result); public slots: - void check(); - void checkWithFeedback(); + void check(); + void checkWithFeedback(); private slots: - void finished(QNetworkReply* reply); + void finished(QNetworkReply *reply); private: - QNetworkAccessManager mNetwork; + QNetworkAccessManager mNetwork; }; diff --git a/widgets/hotkeywidget.cpp b/widgets/hotkeywidget.cpp index 0259215..418e66a 100644 --- a/widgets/hotkeywidget.cpp +++ b/widgets/hotkeywidget.cpp @@ -26,142 +26,137 @@ #include "hotkeywidget.h" HotkeyWidget::HotkeyWidget(QWidget *parent) : - QPushButton(parent), mHotkey(QKeySequence()), mShowingError(false), mKeyboardFocus(false) + QPushButton(parent), mHotkey(QKeySequence()), mShowingError(false), mKeyboardFocus(false) { - mDefaultStyleSheet = "text-align: left; padding: 3px 6px;"; - setStyleSheet(mDefaultStyleSheet); - - setText(tr("Click to select hotkey...")); - setObjectName("HotkeyWidget"); - - if (qApp->style()->objectName() == "oxygen") { - setMinimumWidth(130); - } - else { - setMinimumWidth(110); - } + mDefaultStyleSheet = "text-align: left; padding: 3px 6px;"; + setStyleSheet(mDefaultStyleSheet); + + setText(tr("Click to select hotkey...")); + setObjectName("HotkeyWidget"); + + if (qApp->style()->objectName() == "oxygen") { + setMinimumWidth(130); + } else { + setMinimumWidth(110); + } } void HotkeyWidget::setHotkey(QString hotkeyString) { - mHotkey = QKeySequence().fromString(hotkeyString, QKeySequence::NativeText); - setHotkeyText(); + mHotkey = QKeySequence().fromString(hotkeyString, QKeySequence::NativeText); + setHotkeyText(); } QString HotkeyWidget::hotkey() const { - return mHotkey.toString(QKeySequence::PortableText); + return mHotkey.toString(QKeySequence::PortableText); } void HotkeyWidget::showError() { - if (mShowingError) - return; + if (mShowingError) { + return; + } - mShowingError = true; + mShowingError = true; - setStyleSheet(mDefaultStyleSheet + "color: #d90000;"); - QTimer::singleShot(1000, this, SLOT(hideError())); + setStyleSheet(mDefaultStyleSheet + "color: #d90000;"); + QTimer::singleShot(1000, this, SLOT(hideError())); } void HotkeyWidget::setHotkeyText() { - QString hotkeyText = mHotkey.toString(QKeySequence::NativeText); + QString hotkeyText = mHotkey.toString(QKeySequence::NativeText); - setText(hotkeyText); - parentWidget()->setFocus(); + setText(hotkeyText); + parentWidget()->setFocus(); } bool HotkeyWidget::event(QEvent *event) { - if (event->type() == QEvent::LanguageChange) { - setHotkeyText(); - } - else if (event->type() == QEvent::KeyPress) { - keyPressEvent(static_cast(event)); - return true; - } - else if (event->type() == QEvent::FocusIn) { - QFocusEvent* focusEvent = static_cast(event); - - if (focusEvent->reason() != Qt::TabFocusReason) { - setText(tr("Type your hotkey")); - mKeyboardFocus = false; - grabKeyboard(); - } - else { - mKeyboardFocus = true; - } - } - else if (event->type() == QEvent::FocusOut) { - if (text() == tr("Invalid hotkey")) { - emit invalidHotkeyError(); - showError(); + if (event->type() == QEvent::LanguageChange) { + setHotkeyText(); + } else if (event->type() == QEvent::KeyPress) { + keyPressEvent(static_cast(event)); + return true; + } else if (event->type() == QEvent::FocusIn) { + QFocusEvent *focusEvent = static_cast(event); + + if (focusEvent->reason() != Qt::TabFocusReason) { + setText(tr("Type your hotkey")); + mKeyboardFocus = false; + grabKeyboard(); + } else { + mKeyboardFocus = true; + } + } else if (event->type() == QEvent::FocusOut) { + if (text() == tr("Invalid hotkey")) { + emit invalidHotkeyError(); + showError(); + } + + releaseKeyboard(); + setHotkeyText(); // Reset the text + } else if ((event->type() == QEvent::KeyPress || event->type() == QEvent::ShortcutOverride || event->type() == QEvent::Shortcut) && hasFocus()) { + event->accept(); + return true; } - releaseKeyboard(); - setHotkeyText(); // Reset the text - } - else if ((event->type() == QEvent::KeyPress || event->type() == QEvent::ShortcutOverride || event->type() == QEvent::Shortcut) && hasFocus()) { - event->accept(); - return true; - } - - return QPushButton::event(event); + return QPushButton::event(event); } void HotkeyWidget::keyPressEvent(QKeyEvent *event) { - if (mKeyboardFocus) - return; + if (mKeyboardFocus) { + return; + } - if (isModifier(event->key())) - return; + if (isModifier(event->key())) { + return; + } - if (!isValid(event->key())) { - setText(tr("Invalid hotkey")); - parentWidget()->setFocus(); - return; - } + if (!isValid(event->key())) { + setText(tr("Invalid hotkey")); + parentWidget()->setFocus(); + return; + } - mHotkey = QKeySequence(event->key() + (event->modifiers() & ~Qt::KeypadModifier)); + mHotkey = QKeySequence(event->key() + (event->modifiers() & ~Qt::KeypadModifier)); - setHotkeyText(); + setHotkeyText(); } void HotkeyWidget::hideError() { - setStyleSheet(mDefaultStyleSheet); - mShowingError = false; + setStyleSheet(mDefaultStyleSheet); + mShowingError = false; } bool HotkeyWidget::isValid(int key) const { - switch (key) - { + switch (key) { case 0: case Qt::Key_Escape: case Qt::Key_unknown: - return false; - } + return false; + } - return !isModifier(key); + return !isModifier(key); } bool HotkeyWidget::isModifier(int key) const { - switch (key) - { - case Qt::Key_Shift: - case Qt::Key_Control: - case Qt::Key_Meta: - case Qt::Key_Alt: - case Qt::Key_AltGr: - case Qt::Key_Super_L: - case Qt::Key_Super_R: - case Qt::Key_Menu: + switch (key) { + case Qt::Key_Shift: + case Qt::Key_Control: + case Qt::Key_Meta: + case Qt::Key_Alt: + case Qt::Key_AltGr: + case Qt::Key_Super_L: + case Qt::Key_Super_R: + case Qt::Key_Menu: return true; - } + } - return false; + return false; } diff --git a/widgets/hotkeywidget.h b/widgets/hotkeywidget.h index 677c31c..1c1f756 100644 --- a/widgets/hotkeywidget.h +++ b/widgets/hotkeywidget.h @@ -23,37 +23,37 @@ class HotkeyWidget : public QPushButton { - Q_OBJECT + Q_OBJECT public: - HotkeyWidget(QWidget *parent = 0); + HotkeyWidget(QWidget *parent = 0); - void setHotkey(QString hotkey); - QString hotkey() const; + void setHotkey(QString hotkey); + QString hotkey() const; signals: - void invalidHotkeyError(); + void invalidHotkeyError(); private: - void setHotkeyText(); - void showError(); + void setHotkeyText(); + void showError(); private slots: - void hideError(); + void hideError(); protected: - // Event overrides: - bool event(QEvent* event); - void keyPressEvent(QKeyEvent* event); + // Event overrides: + bool event(QEvent *event); + void keyPressEvent(QKeyEvent *event); private: - QKeySequence mHotkey; - bool mShowingError; - bool mKeyboardFocus; - QString mDefaultStyleSheet; + QKeySequence mHotkey; + bool mShowingError; + bool mKeyboardFocus; + QString mDefaultStyleSheet; - bool isValid(int key) const; - bool isModifier(int key) const; + bool isValid(int key) const; + bool isModifier(int key) const; }; #endif // HOTKEYWIDGET_H