Page MenuHomePhabricator (Chris)

No OneTemporary

Authored By
Unknown
Size
36 KB
Referenced Files
None
Subscribers
None
diff --git a/dialogs/areadialog.cpp b/dialogs/areadialog.cpp
index 9d7f2c5..bfcc49c 100644
--- a/dialogs/areadialog.cpp
+++ b/dialogs/areadialog.cpp
@@ -1,576 +1,581 @@
/*
* Copyright (C) 2016 Christian Kaiser
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
******
*
* Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007 Luca Gugelmann <lucag@student.ethz.ch>
* released under the GNU LGPL <http://www.gnu.org/licenses/old-licenses/library.txt>
*
*/
#include "areadialog.h"
#include "../tools/os.h"
#include "../tools/screenshot.h"
#include "../tools/screenshotmanager.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QHBoxLayout>
#include <QMouseEvent>
#include <QPainter>
#include <QPushButton>
#include <QSettings>
#include <QTimer>
#include <QToolTip>
AreaDialog::AreaDialog(Screenshot *screenshot) :
QDialog(0), mScreenshot(screenshot), mMouseDown(false), mMouseMagnifier(false),
mNewSelection(false), mHandleSize(10), mMouseOverHandle(0),
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;
mMouseOverHandle = 0;
setMouseTracking(true);
setWindowTitle(tr("Lightscreen Area Mode"));
setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint);
setCursor(Qt::CrossCursor);
connect(&mIdleTimer, &QTimer::timeout, this, &AreaDialog::displayHelp);
mIdleTimer.start(2000);
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; }");
auto awAcceptButton = new QPushButton(QIcon(":/icons/yes.big"), "", this);
connect(awAcceptButton, &QPushButton::clicked, this, &AreaDialog::grabRect);
awAcceptButton->setCursor(Qt::PointingHandCursor);
awAcceptButton->setIconSize(QSize(48, 48));
auto awRejectButton = new QPushButton(QIcon(":/icons/no.big"), "", this);
connect(awRejectButton, &QPushButton::clicked, this, &AreaDialog::cancel);
awRejectButton->setCursor(Qt::PointingHandCursor);
awRejectButton->setIconSize(QSize(48, 48));
auto 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()
+QRect AreaDialog::resultRect() const
{
- return mSelection;
+ auto devicePixelRatio = mScreenshot->pixmap().devicePixelRatio();
+
+ return QRect(mSelection.left() * devicePixelRatio,
+ mSelection.top() * devicePixelRatio,
+ mSelection.width() * devicePixelRatio,
+ mSelection.height() * devicePixelRatio);
}
void AreaDialog::animationTick(int frame)
{
mOverlayAlpha = frame;
update();
}
void AreaDialog::cancel()
{
reject();
}
void AreaDialog::displayHelp()
{
mShowHelp = true;
update();
}
void AreaDialog::grabRect()
{
QRect r = mSelection.normalized();
if (!r.isNull() && r.isValid()) {
mGrabbing = true;
accept();
}
}
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();
}
}
void AreaDialog::mouseDoubleClickEvent(QMouseEvent *)
{
grabRect();
}
void AreaDialog::mouseMoveEvent(QMouseEvent *e)
{
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);
}
}
}
}
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);
}
} 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 (mMouseOverHandle == 0 && mSelection.contains(e->pos())) {
setCursor(Qt::OpenHandCursor);
}
update();
}
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);
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);
}
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 (!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);
}
void AreaDialog::resizeEvent(QResizeEvent *e)
{
Q_UNUSED(e);
if (mSelection.isNull()) {
return;
}
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();
}
mSelection = r;
}
void AreaDialog::showEvent(QShowEvent *e)
{
Q_UNUSED(e)
QRect geometry = qApp->desktop()->geometry();
if (mScreenshot->options().currentMonitor) {
geometry = qApp->desktop()->screenGeometry(qApp->desktop()->screenNumber(QCursor::pos()));
}
resize(geometry.size());
move(geometry.topLeft());
if (mScreenshot->options().animations) {
os::effect(this, SLOT(animationTick(int)), 85, 300);
} else {
animationTick(85);
}
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()));
}
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;
}
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;
}
diff --git a/dialogs/areadialog.h b/dialogs/areadialog.h
index 7a3c712..c1e100c 100644
--- a/dialogs/areadialog.h
+++ b/dialogs/areadialog.h
@@ -1,99 +1,99 @@
/*
* Copyright (C) 2016 Christian Kaiser
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
******
*
* Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007 Luca Gugelmann <lucag@student.ethz.ch>
* released under the GNU LGPL <http://www.gnu.org/licenses/old-licenses/library.txt>
*
*/
#ifndef AREADIALOG_H
#define AREADIALOG_H
#include <QDialog>
#include <QVector>
#include <QPointer>
#include <QTimer>
#include <QRegion>
#include <QRect>
#include <QPoint>
class QPaintEvent;
class QResizeEvent;
class QMouseEvent;
class Screenshot;
class AreaDialog : public QDialog
{
Q_OBJECT
public:
AreaDialog(Screenshot *screenshot);
- QRect &resultRect();
+ QRect resultRect() const;
protected slots:
void animationTick(int frame);
void cancel();
void displayHelp();
void grabRect();
signals:
void regionGrabbed(const QPixmap &);
protected:
void keyPressEvent(QKeyEvent *e);
void mouseDoubleClickEvent(QMouseEvent *);
void mouseMoveEvent(QMouseEvent *e);
void mousePressEvent(QMouseEvent *e);
void mouseReleaseEvent(QMouseEvent *e);
void paintEvent(QPaintEvent *e);
void resizeEvent(QResizeEvent *e);
void showEvent(QShowEvent *e);
void updateHandles();
QRegion handleMask() const;
QPoint limitPointToRect(const QPoint &p, const QRect &r) const;
Screenshot *mScreenshot;
QPoint mDragStartPoint;
bool mMouseDown;
bool mMouseMagnifier;
bool mNewSelection;
const int mHandleSize;
QRect *mMouseOverHandle;
QPoint mMousePos;
QTimer mIdleTimer;
QRect mSelection;
QRect mSelectionBeforeDrag;
bool mShowHelp;
bool mGrabbing;
int mOverlayAlpha;
bool mAutoclose;
// naming convention for handles
// T top, B bottom, R Right, L left
// 2 letters: a corner
// 1 letter: the handle on the middle of the corresponding side
QRect mTLHandle, mTRHandle, mBLHandle, mBRHandle;
QRect mLHandle, mTHandle, mRHandle, mBHandle;
QVector<QRect *> mHandles;
QPointer<QWidget> mAcceptWidget;
};
#endif
diff --git a/tools/screenshot.cpp b/tools/screenshot.cpp
index a4d15c0..aeb1968 100644
--- a/tools/screenshot.cpp
+++ b/tools/screenshot.cpp
@@ -1,484 +1,485 @@
/*
* Copyright (C) 2016 Christian Kaiser
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <QApplication>
#include <QClipboard>
#include <QDateTime>
#include <QDesktopWidget>
#include <QFileDialog>
#include <QPainter>
#include <QPixmap>
#include <QProcess>
#include <QTextStream>
#include <QScreen>
#include "windowpicker.h"
#include "../dialogs/areadialog.h"
#include "uploader/uploader.h"
#include "screenshot.h"
#include "screenshotmanager.h"
#include "os.h"
#ifdef Q_OS_WIN
#include <windows.h>
#endif
#ifdef Q_OS_LINUX
#include <QX11Info>
#include <X11/X.h>
#include <X11/Xlib.h>
#endif
Screenshot::Screenshot(QObject *parent, Screenshot::Options options):
QObject(parent),
mOptions(options),
mPixmapDelay(false),
mUnloaded(false),
mUnloadFilename()
{
// Here be crickets
}
Screenshot::~Screenshot()
{
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.
for (auto 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();
}
}
}
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;
}
return naming;
}
QString &Screenshot::unloadedFileName()
{
return mUnloadFilename;
}
Screenshot::Options &Screenshot::options()
{
return mOptions;
}
QPixmap &Screenshot::pixmap()
{
return mPixmap;
}
//
void Screenshot::confirm(bool result)
{
if (result) {
save();
} else {
mOptions.result = Screenshot::Cancel;
emit finished();
}
emit cleanup();
mPixmap = QPixmap();
}
void Screenshot::confirmation()
{
emit askConfirmation();
if (mOptions.file) {
unloadPixmap();
}
}
void Screenshot::discard()
{
confirm(false);
}
void Screenshot::markUpload()
{
mOptions.upload = true;
}
void Screenshot::optimize()
{
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()));
QString optiPNG;
#ifdef Q_OS_UNIX
optiPNG = "optipng";
#else
optiPNG = qApp->applicationDirPath() + QDir::separator() + "optipng.exe";
#endif
if (!QFile::exists(optiPNG)) {
emit optimizationDone();
}
process->start(optiPNG, QStringList() << mOptions.fileName);
if (process->state() == QProcess::NotRunning) {
emit optimizationDone();
process->deleteLater();
}
}
void Screenshot::optimizationDone()
{
if (mOptions.upload) {
upload();
} else {
emit finished();
}
}
void Screenshot::save()
{
QString name = "";
QString fileName = "";
Screenshot::Result result = Screenshot::Failure;
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();
for (auto 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;
}
}
}
name = name + " (" + QString::number(count + 1) + ")";
}
if (mOptions.clipboard && !(mOptions.upload && mOptions.urlClipboard)) {
if (mUnloaded) {
mUnloaded = false;
mPixmap = QPixmap(mUnloadFilename);
}
QApplication::clipboard()->setPixmap(mPixmap, QClipboard::Clipboard);
if (!mOptions.file) {
result = Screenshot::Success;
}
}
if (mOptions.file) {
fileName = name + extension();
if (name.isEmpty()) {
result = Screenshot::Cancel;
} else if (mUnloaded) {
result = (QFile::rename(mUnloadFilename, fileName)) ? Screenshot::Success : Screenshot::Failure;
} else if (mPixmap.save(fileName, 0, mOptions.quality)) {
result = Screenshot::Success;
} else {
result = Screenshot::Failure;
}
}
mOptions.fileName = fileName;
mOptions.result = result;
if (!mOptions.result) {
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(const QPixmap &pixmap)
{
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;
}
if (mPixmapDelay) {
return;
}
if (mPixmap.isNull()) {
confirm(false);
} else {
confirmation();
}
}
void Screenshot::upload()
{
if (mOptions.file) {
Uploader::instance()->upload(mOptions.fileName, mOptions.uploadService);
} else if (unloadPixmap()) {
Uploader::instance()->upload(mUnloadFilename, mOptions.uploadService);
} else {
emit finished();
}
}
void Screenshot::uploadDone(const QString &url)
{
if (mOptions.urlClipboard && !url.isEmpty()) {
QApplication::clipboard()->setText(url, QClipboard::Clipboard);
}
emit finished();
}
//
void Screenshot::activeWindow()
{
#ifdef Q_OS_WIN
HWND fWindow = GetForegroundWindow();
if (fWindow == NULL) {
return;
}
if (fWindow == GetDesktopWindow()) {
wholeScreen();
return;
}
mPixmap = os::grabWindow((WId)GetForegroundWindow());
#endif
#if defined(Q_OS_LINUX)
Window focus;
int revert;
XGetInputFocus(QX11Info::display(), &focus, &revert);
mPixmap = QPixmap::grabWindow(focus);
#endif
}
QString Screenshot::extension() const
{
switch (mOptions.format) {
case Screenshot::PNG:
return QStringLiteral(".png");
break;
case Screenshot::BMP:
return QStringLiteral(".bmp");
break;
case Screenshot::JPEG:
default:
return QStringLiteral(".jpg");
break;
}
}
void Screenshot::grabDesktop()
{
QRect geometry;
if (mOptions.currentMonitor) {
geometry = QApplication::primaryScreen()->geometry();
} else {
for (QScreen *screen : QGuiApplication::screens()) {
geometry = geometry.united(screen->geometry());
}
}
mPixmap = QApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId(), geometry.x(), geometry.y(), geometry.width(), geometry.height());
+ mPixmap.setDevicePixelRatio(QApplication::desktop()->devicePixelRatio());
if (mOptions.cursor && !mPixmap.isNull()) {
QPainter painter(&mPixmap);
- painter.drawPixmap(QCursor::pos(), os::cursor());
+ QPixmap cursor = os::cursor();
+ cursor.setDevicePixelRatio(QApplication::desktop()->devicePixelRatio());
+ painter.drawPixmap(QCursor::pos(), cursor);
}
-
- mPixmap.setDevicePixelRatio(QApplication::desktop()->devicePixelRatio());
}
QString Screenshot::newFileName() const
{
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());
// Cleanup
if (path.at(path.size() - 1) != QDir::separator() && !path.isEmpty()) {
path.append(QDir::separator());
}
QString fileName;
fileName.append(path);
fileName.append(naming);
return fileName;
}
void Screenshot::selectedArea()
{
grabDesktop();
if (mPixmap.isNull()) {
return;
}
AreaDialog selector(this);
int result = selector.exec();
if (result == QDialog::Accepted) {
mPixmap = mPixmap.copy(selector.resultRect());
} else {
mPixmap = QPixmap();
}
}
void Screenshot::selectedWindow()
{
WindowPicker *windowPicker = new WindowPicker;
mPixmapDelay = true;
connect(windowPicker, SIGNAL(pixmap(QPixmap)), this, SLOT(setPixmap(QPixmap)));
}
bool Screenshot::unloadPixmap()
{
if (mUnloaded) {
return true;
}
// Unloading the pixmap to reduce memory usage during previews
mUnloadFilename = mOptions.directory.path() + QDir::separator() + QString(".screenshot.%1%2").arg(qrand() * qrand() + QDateTime::currentDateTime().toTime_t()).arg(extension());
mUnloaded = mPixmap.save(mUnloadFilename, 0, mOptions.quality);
if (mUnloaded) {
mPixmap = QPixmap();
}
return mUnloaded;
}
void Screenshot::wholeScreen()
{
grabDesktop();
}

File Metadata

Mime Type
text/x-diff
Expires
Sat, May 16, 7:18 AM (18 h, 8 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
64092
Default Alt Text
(36 KB)

Event Timeline