reformatted to Mozilla code style

This commit is contained in:
Jeremy Borgman
2020-09-04 20:16:33 -05:00
committed by borgmanJeremy
parent c0e2e48db4
commit c8d15205be
176 changed files with 12695 additions and 11269 deletions

View File

@@ -1,89 +1,2 @@
Language: Cpp Language: Cpp
# BasedOnStyle: Google BasedOnStyle: Mozilla
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlinesLeft: true
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: true
AfterStruct: true
AfterUnion: true
BeforeCatch: true
BeforeElse: true
IndentBraces: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakConstructorInitializersBeforeComma: false
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 0
ContinuationIndentWidth: 2
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeCategories:
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IndentCaseLabels: true
IndentWidth: 2
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Auto
TabWidth: 2
UseTab: Never

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -24,58 +24,58 @@
namespace color_widgets { namespace color_widgets {
namespace detail { namespace detail {
QColor color_from_lch(qreal hue, qreal chroma, qreal luma, qreal alpha ) QColor
color_from_lch(qreal hue, qreal chroma, qreal luma, qreal alpha)
{ {
qreal h1 = hue*6; qreal h1 = hue * 6;
qreal x = chroma*(1-qAbs(std::fmod(h1,2)-1)); qreal x = chroma * (1 - qAbs(std::fmod(h1, 2) - 1));
QColor col; QColor col;
if ( h1 >= 0 && h1 < 1 ) if (h1 >= 0 && h1 < 1)
col = QColor::fromRgbF(chroma,x,0); col = QColor::fromRgbF(chroma, x, 0);
else if ( h1 < 2 ) else if (h1 < 2)
col = QColor::fromRgbF(x,chroma,0); col = QColor::fromRgbF(x, chroma, 0);
else if ( h1 < 3 ) else if (h1 < 3)
col = QColor::fromRgbF(0,chroma,x); col = QColor::fromRgbF(0, chroma, x);
else if ( h1 < 4 ) else if (h1 < 4)
col = QColor::fromRgbF(0,x,chroma); col = QColor::fromRgbF(0, x, chroma);
else if ( h1 < 5 ) else if (h1 < 5)
col = QColor::fromRgbF(x,0,chroma); col = QColor::fromRgbF(x, 0, chroma);
else if ( h1 < 6 ) else if (h1 < 6)
col = QColor::fromRgbF(chroma,0,x); col = QColor::fromRgbF(chroma, 0, x);
qreal m = luma - color_lumaF(col); qreal m = luma - color_lumaF(col);
return QColor::fromRgbF( return QColor::fromRgbF(qBound(0.0, col.redF() + m, 1.0),
qBound(0.0,col.redF()+m,1.0), qBound(0.0, col.greenF() + m, 1.0),
qBound(0.0,col.greenF()+m,1.0), qBound(0.0, col.blueF() + m, 1.0),
qBound(0.0,col.blueF()+m,1.0),
alpha); alpha);
} }
QColor color_from_hsl(qreal hue, qreal sat, qreal lig, qreal alpha ) QColor
color_from_hsl(qreal hue, qreal sat, qreal lig, qreal alpha)
{ {
qreal chroma = (1 - qAbs(2*lig-1))*sat; qreal chroma = (1 - qAbs(2 * lig - 1)) * sat;
qreal h1 = hue*6; qreal h1 = hue * 6;
qreal x = chroma*(1-qAbs(std::fmod(h1,2)-1)); qreal x = chroma * (1 - qAbs(std::fmod(h1, 2) - 1));
QColor col; QColor col;
if ( h1 >= 0 && h1 < 1 ) if (h1 >= 0 && h1 < 1)
col = QColor::fromRgbF(chroma,x,0); col = QColor::fromRgbF(chroma, x, 0);
else if ( h1 < 2 ) else if (h1 < 2)
col = QColor::fromRgbF(x,chroma,0); col = QColor::fromRgbF(x, chroma, 0);
else if ( h1 < 3 ) else if (h1 < 3)
col = QColor::fromRgbF(0,chroma,x); col = QColor::fromRgbF(0, chroma, x);
else if ( h1 < 4 ) else if (h1 < 4)
col = QColor::fromRgbF(0,x,chroma); col = QColor::fromRgbF(0, x, chroma);
else if ( h1 < 5 ) else if (h1 < 5)
col = QColor::fromRgbF(x,0,chroma); col = QColor::fromRgbF(x, 0, chroma);
else if ( h1 < 6 ) else if (h1 < 6)
col = QColor::fromRgbF(chroma,0,x); col = QColor::fromRgbF(chroma, 0, x);
qreal m = lig-chroma/2; qreal m = lig - chroma / 2;
return QColor::fromRgbF( return QColor::fromRgbF(qBound(0.0, col.redF() + m, 1.0),
qBound(0.0,col.redF()+m,1.0), qBound(0.0, col.greenF() + m, 1.0),
qBound(0.0,col.greenF()+m,1.0), qBound(0.0, col.blueF() + m, 1.0),
qBound(0.0,col.blueF()+m,1.0),
alpha); alpha);
} }

View File

@@ -21,14 +21,14 @@
*/ */
#include "color_wheel.hpp" #include "color_wheel.hpp"
#include <cmath>
#include <QMouseEvent>
#include <QPainterPath>
#include <QPainter>
#include <QLineF>
#include <QDragEnterEvent>
#include <QMimeData>
#include "color_utils.hpp" #include "color_utils.hpp"
#include <QDragEnterEvent>
#include <QLineF>
#include <QMimeData>
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include <cmath>
namespace color_widgets { namespace color_widgets {
@@ -39,14 +39,16 @@ enum MouseStatus
DragSquare DragSquare
}; };
static const ColorWheel::DisplayFlags hard_default_flags = ColorWheel::SHAPE_TRIANGLE|ColorWheel::ANGLE_ROTATING|ColorWheel::COLOR_HSV; static const ColorWheel::DisplayFlags hard_default_flags =
ColorWheel::SHAPE_TRIANGLE | ColorWheel::ANGLE_ROTATING |
ColorWheel::COLOR_HSV;
static ColorWheel::DisplayFlags default_flags = hard_default_flags; static ColorWheel::DisplayFlags default_flags = hard_default_flags;
static const double selector_radius = 6; static const double selector_radius = 6;
class ColorWheel::Private class ColorWheel::Private
{ {
private: private:
ColorWheel * const w; ColorWheel* const w;
public: public:
qreal hue, sat, val; qreal hue, sat, val;
@@ -56,15 +58,20 @@ public:
QPixmap hue_ring; QPixmap hue_ring;
QImage inner_selector; QImage inner_selector;
DisplayFlags display_flags; DisplayFlags display_flags;
QColor (*color_from)(qreal,qreal,qreal,qreal); QColor (*color_from)(qreal, qreal, qreal, qreal);
QColor (*rainbow_from_hue)(qreal); QColor (*rainbow_from_hue)(qreal);
int max_size = 128; int max_size = 128;
explicit Private(ColorWheel *widget) explicit Private(ColorWheel* widget)
: w(widget), hue(0), sat(0), val(0), : w(widget)
wheel_width(20), mouse_status(Nothing), , hue(0)
display_flags(FLAGS_DEFAULT), , sat(0)
color_from(&QColor::fromHsvF), rainbow_from_hue(&detail::rainbow_hsv) , val(0)
, wheel_width(20)
, mouse_status(Nothing)
, display_flags(FLAGS_DEFAULT)
, color_from(&QColor::fromHsvF)
, rainbow_from_hue(&detail::rainbow_hsv)
{ {
QColor bgColor = widget->palette().window().color(); QColor bgColor = widget->palette().window().color();
bgBrightness = color_widgets::detail::color_lumaF(bgColor); bgBrightness = color_widgets::detail::color_lumaF(bgColor);
@@ -73,37 +80,26 @@ public:
/// Calculate outer wheel radius from idget center /// Calculate outer wheel radius from idget center
qreal outer_radius() const qreal outer_radius() const
{ {
return qMin(w->geometry().width(), w->geometry().height())/2; return qMin(w->geometry().width(), w->geometry().height()) / 2;
} }
/// Calculate inner wheel radius from idget center /// Calculate inner wheel radius from idget center
qreal inner_radius() const qreal inner_radius() const { return outer_radius() - wheel_width; }
{
return outer_radius()-wheel_width;
}
/// Calculate the edge length of the inner square /// Calculate the edge length of the inner square
qreal square_size() const qreal square_size() const { return inner_radius() * qSqrt(2); }
{
return inner_radius()*qSqrt(2);
}
/// Calculate the height of the inner triangle /// Calculate the height of the inner triangle
qreal triangle_height() const qreal triangle_height() const { return inner_radius() * 3 / 2; }
{
return inner_radius()*3/2;
}
/// Calculate the side of the inner triangle /// Calculate the side of the inner triangle
qreal triangle_side() const qreal triangle_side() const { return inner_radius() * qSqrt(3); }
{
return inner_radius()*qSqrt(3);
}
/// return line from center to given point /// return line from center to given point
QLineF line_to_point(const QPoint &p) const QLineF line_to_point(const QPoint& p) const
{ {
return QLineF (w->geometry().width()/2, w->geometry().height()/2, p.x(), p.y()); return QLineF(
w->geometry().width() / 2, w->geometry().height() / 2, p.x(), p.y());
} }
void render_square() void render_square()
@@ -112,39 +108,36 @@ public:
QSize size(width, width); QSize size(width, width);
inner_selector = QImage(size, QImage::Format_RGB32); inner_selector = QImage(size, QImage::Format_RGB32);
for ( int y = 0; y < width; ++y ) for (int y = 0; y < width; ++y) {
{ for (int x = 0; x < width; ++x) {
for ( int x = 0; x < width; ++x ) inner_selector.setPixel(
{ x, y, color_from(hue, double(x) / width, double(y) / width, 1).rgb());
inner_selector.setPixel( x, y,
color_from(hue,double(x)/width,double(y)/width,1).rgb());
} }
} }
} }
/** /**
* \brief renders the selector as a triangle * \brief renders the selector as a triangle
* \note It's the same as a square with the edge with value=0 collapsed to a single point * \note It's the same as a square with the edge with value=0 collapsed to a
* single point
*/ */
void render_triangle() void render_triangle()
{ {
QSizeF size = selector_size(); QSizeF size = selector_size();
if ( size.height() > max_size ) if (size.height() > max_size)
size *= max_size / size.height(); size *= max_size / size.height();
qreal ycenter = size.height()/2; qreal ycenter = size.height() / 2;
inner_selector = QImage(size.toSize(), QImage::Format_RGB32); inner_selector = QImage(size.toSize(), QImage::Format_RGB32);
for (int x = 0; x < inner_selector.width(); x++ ) for (int x = 0; x < inner_selector.width(); x++) {
{
qreal pval = x / size.height(); qreal pval = x / size.height();
qreal slice_h = size.height() * pval; qreal slice_h = size.height() * pval;
for (int y = 0; y < inner_selector.height(); y++ ) for (int y = 0; y < inner_selector.height(); y++) {
{ qreal ymin = ycenter - slice_h / 2;
qreal ymin = ycenter-slice_h/2; qreal psat = qBound(0.0, (y - ymin) / slice_h, 1.0);
qreal psat = qBound(0.0,(y-ymin)/slice_h,1.0);
inner_selector.setPixel(x,y,color_from(hue,psat,pval,1).rgb()); inner_selector.setPixel(x, y, color_from(hue, psat, pval, 1).rgb());
} }
} }
} }
@@ -152,7 +145,7 @@ public:
/// Updates the inner image that displays the saturation-value selector /// Updates the inner image that displays the saturation-value selector
void render_inner_selector() void render_inner_selector()
{ {
if ( display_flags & ColorWheel::SHAPE_TRIANGLE ) if (display_flags & ColorWheel::SHAPE_TRIANGLE)
render_triangle(); render_triangle();
else else
render_square(); render_square();
@@ -161,9 +154,9 @@ public:
/// Offset of the selector image /// Offset of the selector image
QPointF selector_image_offset() QPointF selector_image_offset()
{ {
if ( display_flags & SHAPE_TRIANGLE ) if (display_flags & SHAPE_TRIANGLE)
return QPointF(-inner_radius(),-triangle_side()/2); return QPointF(-inner_radius(), -triangle_side() / 2);
return QPointF(-square_size()/2,-square_size()/2); return QPointF(-square_size() / 2, -square_size() / 2);
} }
/** /**
@@ -171,25 +164,21 @@ public:
*/ */
QSizeF selector_size() QSizeF selector_size()
{ {
if ( display_flags & SHAPE_TRIANGLE ) if (display_flags & SHAPE_TRIANGLE)
return QSizeF(triangle_height(), triangle_side()); return QSizeF(triangle_height(), triangle_side());
return QSizeF(square_size(), square_size()); return QSizeF(square_size(), square_size());
} }
/// Rotation of the selector image /// Rotation of the selector image
qreal selector_image_angle() qreal selector_image_angle()
{ {
if ( display_flags & SHAPE_TRIANGLE ) if (display_flags & SHAPE_TRIANGLE) {
{ if (display_flags & ANGLE_ROTATING)
if ( display_flags & ANGLE_ROTATING ) return -hue * 360 - 60;
return -hue*360-60;
return -150; return -150;
} } else {
else if (display_flags & ANGLE_ROTATING)
{ return -hue * 360 - 45;
if ( display_flags & ANGLE_ROTATING )
return -hue*360-45;
else else
return 180; return 180;
} }
@@ -198,50 +187,42 @@ public:
/// Updates the outer ring that displays the hue selector /// Updates the outer ring that displays the hue selector
void render_ring() void render_ring()
{ {
hue_ring = QPixmap(outer_radius()*2,outer_radius()*2); hue_ring = QPixmap(outer_radius() * 2, outer_radius() * 2);
hue_ring.fill(Qt::transparent); hue_ring.fill(Qt::transparent);
QPainter painter(&hue_ring); QPainter painter(&hue_ring);
painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::Antialiasing);
painter.setCompositionMode(QPainter::CompositionMode_Source); painter.setCompositionMode(QPainter::CompositionMode_Source);
const int hue_stops = 24; const int hue_stops = 24;
QConicalGradient gradient_hue(0, 0, 0); QConicalGradient gradient_hue(0, 0, 0);
if ( gradient_hue.stops().size() < hue_stops ) if (gradient_hue.stops().size() < hue_stops) {
{ for (double a = 0; a < 1.0; a += 1.0 / (hue_stops - 1)) {
for ( double a = 0; a < 1.0; a+=1.0/(hue_stops-1) ) gradient_hue.setColorAt(a, rainbow_from_hue(a));
{
gradient_hue.setColorAt(a,rainbow_from_hue(a));
} }
gradient_hue.setColorAt(1,rainbow_from_hue(0)); gradient_hue.setColorAt(1, rainbow_from_hue(0));
} }
painter.translate(outer_radius(),outer_radius()); painter.translate(outer_radius(), outer_radius());
painter.setPen(Qt::NoPen); painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(gradient_hue)); painter.setBrush(QBrush(gradient_hue));
painter.drawEllipse(QPointF(0,0),outer_radius(),outer_radius()); painter.drawEllipse(QPointF(0, 0), outer_radius(), outer_radius());
painter.setBrush(Qt::transparent);//palette().background()); painter.setBrush(Qt::transparent); // palette().background());
painter.drawEllipse(QPointF(0,0),inner_radius(),inner_radius()); painter.drawEllipse(QPointF(0, 0), inner_radius(), inner_radius());
} }
void set_color(const QColor& c) void set_color(const QColor& c)
{ {
if ( display_flags & ColorWheel::COLOR_HSV ) if (display_flags & ColorWheel::COLOR_HSV) {
{
hue = qMax(0.0, c.hsvHueF()); hue = qMax(0.0, c.hsvHueF());
sat = c.hsvSaturationF(); sat = c.hsvSaturationF();
val = c.valueF(); val = c.valueF();
} } else if (display_flags & ColorWheel::COLOR_HSL) {
else if ( display_flags & ColorWheel::COLOR_HSL )
{
hue = qMax(0.0, c.hueF()); hue = qMax(0.0, c.hueF());
sat = detail::color_HSL_saturationF(c); sat = detail::color_HSL_saturationF(c);
val = detail::color_lightnessF(c); val = detail::color_lightnessF(c);
} } else if (display_flags & ColorWheel::COLOR_LCH) {
else if ( display_flags & ColorWheel::COLOR_LCH )
{
hue = qMax(0.0, c.hsvHueF()); hue = qMax(0.0, c.hsvHueF());
sat = detail::color_chromaF(c); sat = detail::color_chromaF(c);
val = detail::color_lumaF(c); val = detail::color_lumaF(c);
@@ -249,8 +230,9 @@ public:
} }
}; };
ColorWheel::ColorWheel(QWidget *parent) : ColorWheel::ColorWheel(QWidget* parent)
QWidget(parent), p(new Private(this)) : QWidget(parent)
, p(new Private(this))
{ {
setDisplayFlags(FLAGS_DEFAULT); setDisplayFlags(FLAGS_DEFAULT);
setAcceptDrops(true); setAcceptDrops(true);
@@ -261,158 +243,158 @@ ColorWheel::~ColorWheel()
delete p; delete p;
} }
QColor ColorWheel::color() const QColor
ColorWheel::color() const
{ {
return p->color_from(p->hue, p->sat, p->val, 1); return p->color_from(p->hue, p->sat, p->val, 1);
} }
QSize ColorWheel::sizeHint() const QSize
ColorWheel::sizeHint() const
{ {
return QSize(p->wheel_width*5, p->wheel_width*5); return QSize(p->wheel_width * 5, p->wheel_width * 5);
} }
qreal ColorWheel::hue() const qreal
ColorWheel::hue() const
{ {
if ( (p->display_flags & COLOR_LCH) && p->sat > 0.01 ) if ((p->display_flags & COLOR_LCH) && p->sat > 0.01)
return color().hueF(); return color().hueF();
return p->hue; return p->hue;
} }
qreal ColorWheel::saturation() const qreal
ColorWheel::saturation() const
{ {
return color().hsvSaturationF(); return color().hsvSaturationF();
} }
qreal ColorWheel::value() const qreal
ColorWheel::value() const
{ {
return color().valueF(); return color().valueF();
} }
unsigned int ColorWheel::wheelWidth() const unsigned int
ColorWheel::wheelWidth() const
{ {
return p->wheel_width; return p->wheel_width;
} }
void ColorWheel::setWheelWidth(unsigned int w) void
ColorWheel::setWheelWidth(unsigned int w)
{ {
p->wheel_width = w; p->wheel_width = w;
p->render_inner_selector(); p->render_inner_selector();
update(); update();
} }
void ColorWheel::paintEvent(QPaintEvent * ) void
ColorWheel::paintEvent(QPaintEvent*)
{ {
QPainter painter(this); QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::Antialiasing);
painter.translate(geometry().width()/2,geometry().height()/2); painter.translate(geometry().width() / 2, geometry().height() / 2);
// hue wheel // hue wheel
if(p->hue_ring.isNull()) if (p->hue_ring.isNull())
p->render_ring(); p->render_ring();
painter.drawPixmap(-p->outer_radius(), -p->outer_radius(), p->hue_ring); painter.drawPixmap(-p->outer_radius(), -p->outer_radius(), p->hue_ring);
// hue selector // hue selector
QColor penColor = p->bgBrightness < 0.6 ? Qt::white : Qt::black; QColor penColor = p->bgBrightness < 0.6 ? Qt::white : Qt::black;
painter.setPen(QPen(penColor,3)); painter.setPen(QPen(penColor, 3));
painter.setBrush(Qt::NoBrush); painter.setBrush(Qt::NoBrush);
QLineF ray(0, 0, p->outer_radius(), 0); QLineF ray(0, 0, p->outer_radius(), 0);
ray.setAngle(p->hue*360); ray.setAngle(p->hue * 360);
QPointF h1 = ray.p2(); QPointF h1 = ray.p2();
ray.setLength(p->inner_radius()); ray.setLength(p->inner_radius());
QPointF h2 = ray.p2(); QPointF h2 = ray.p2();
painter.drawLine(h1,h2); painter.drawLine(h1, h2);
// lum-sat square // lum-sat square
if(p->inner_selector.isNull()) if (p->inner_selector.isNull())
p->render_inner_selector(); p->render_inner_selector();
painter.rotate(p->selector_image_angle()); painter.rotate(p->selector_image_angle());
painter.translate(p->selector_image_offset()); painter.translate(p->selector_image_offset());
QPointF selector_position; QPointF selector_position;
if ( p->display_flags & SHAPE_SQUARE ) if (p->display_flags & SHAPE_SQUARE) {
{
qreal side = p->square_size(); qreal side = p->square_size();
selector_position = QPointF(p->sat*side, p->val*side); selector_position = QPointF(p->sat * side, p->val * side);
} } else if (p->display_flags & SHAPE_TRIANGLE) {
else if ( p->display_flags & SHAPE_TRIANGLE )
{
qreal side = p->triangle_side(); qreal side = p->triangle_side();
qreal height = p->triangle_height(); qreal height = p->triangle_height();
qreal slice_h = side * p->val; qreal slice_h = side * p->val;
qreal ymin = side/2-slice_h/2; qreal ymin = side / 2 - slice_h / 2;
selector_position = QPointF(p->val*height, ymin + p->sat*slice_h); selector_position = QPointF(p->val * height, ymin + p->sat * slice_h);
QPolygonF triangle; QPolygonF triangle;
triangle.append(QPointF(0,side/2)); triangle.append(QPointF(0, side / 2));
triangle.append(QPointF(height,0)); triangle.append(QPointF(height, 0));
triangle.append(QPointF(height,side)); triangle.append(QPointF(height, side));
QPainterPath clip; QPainterPath clip;
clip.addPolygon(triangle); clip.addPolygon(triangle);
painter.setClipPath(clip); painter.setClipPath(clip);
} }
painter.drawImage(QRectF(QPointF(0, 0), p->selector_size()), p->inner_selector); painter.drawImage(QRectF(QPointF(0, 0), p->selector_size()),
p->inner_selector);
painter.setClipping(false); painter.setClipping(false);
// lum-sat selector // lum-sat selector
// we define the color of the selecto based on the background color of the widget // we define the color of the selecto based on the background color of the
// in order to improve the contrast // widget in order to improve the contrast
qreal colorBrightness = color_widgets::detail::color_lumaF(color()); qreal colorBrightness = color_widgets::detail::color_lumaF(color());
if (p->bgBrightness < 0.6) // dark theme if (p->bgBrightness < 0.6) // dark theme
{ {
bool isWhite = (colorBrightness < 0.7); bool isWhite = (colorBrightness < 0.7);
painter.setPen(QPen(isWhite ? Qt::white : Qt::black, 3)); painter.setPen(QPen(isWhite ? Qt::white : Qt::black, 3));
} } else // light theme
else // light theme
{ {
bool isWhite = (colorBrightness < 0.4 && p->val < 0.3); bool isWhite = (colorBrightness < 0.4 && p->val < 0.3);
painter.setPen(QPen(isWhite ? Qt::white : Qt::black, 3)); painter.setPen(QPen(isWhite ? Qt::white : Qt::black, 3));
} }
painter.setBrush(Qt::NoBrush); painter.setBrush(Qt::NoBrush);
painter.drawEllipse(selector_position, selector_radius, selector_radius); painter.drawEllipse(selector_position, selector_radius, selector_radius);
} }
void ColorWheel::mouseMoveEvent(QMouseEvent *ev) void
ColorWheel::mouseMoveEvent(QMouseEvent* ev)
{ {
if (p->mouse_status == DragCircle ) if (p->mouse_status == DragCircle) {
{ p->hue = p->line_to_point(ev->pos()).angle() / 360.0;
p->hue = p->line_to_point(ev->pos()).angle()/360.0;
p->render_inner_selector(); p->render_inner_selector();
emit colorSelected(color()); emit colorSelected(color());
emit colorChanged(color()); emit colorChanged(color());
update(); update();
} } else if (p->mouse_status == DragSquare) {
else if(p->mouse_status == DragSquare)
{
QLineF glob_mouse_ln = p->line_to_point(ev->pos()); QLineF glob_mouse_ln = p->line_to_point(ev->pos());
QLineF center_mouse_ln ( QPointF(0,0), QLineF center_mouse_ln(QPointF(0, 0),
glob_mouse_ln.p2() - glob_mouse_ln.p1() ); glob_mouse_ln.p2() - glob_mouse_ln.p1());
center_mouse_ln.setAngle(center_mouse_ln.angle()+p->selector_image_angle()); center_mouse_ln.setAngle(center_mouse_ln.angle() +
center_mouse_ln.setP2(center_mouse_ln.p2()-p->selector_image_offset()); p->selector_image_angle());
center_mouse_ln.setP2(center_mouse_ln.p2() - p->selector_image_offset());
if ( p->display_flags & SHAPE_SQUARE ) if (p->display_flags & SHAPE_SQUARE) {
{ p->sat = qBound(0.0, center_mouse_ln.x2() / p->square_size(), 1.0);
p->sat = qBound(0.0, center_mouse_ln.x2()/p->square_size(), 1.0); p->val = qBound(0.0, center_mouse_ln.y2() / p->square_size(), 1.0);
p->val = qBound(0.0, center_mouse_ln.y2()/p->square_size(), 1.0); } else if (p->display_flags & SHAPE_TRIANGLE) {
}
else if ( p->display_flags & SHAPE_TRIANGLE )
{
QPointF pt = center_mouse_ln.p2(); QPointF pt = center_mouse_ln.p2();
qreal side = p->triangle_side(); qreal side = p->triangle_side();
p->val = qBound(0.0, pt.x() / p->triangle_height(), 1.0); p->val = qBound(0.0, pt.x() / p->triangle_height(), 1.0);
qreal slice_h = side * p->val; qreal slice_h = side * p->val;
qreal ycenter = side/2; qreal ycenter = side / 2;
qreal ymin = ycenter-slice_h/2; qreal ymin = ycenter - slice_h / 2;
if ( slice_h > 0 ) if (slice_h > 0)
p->sat = qBound(0.0, (pt.y()-ymin)/slice_h, 1.0); p->sat = qBound(0.0, (pt.y() - ymin) / slice_h, 1.0);
} }
emit colorSelected(color()); emit colorSelected(color());
@@ -421,15 +403,15 @@ void ColorWheel::mouseMoveEvent(QMouseEvent *ev)
} }
} }
void ColorWheel::mousePressEvent(QMouseEvent *ev) void
ColorWheel::mousePressEvent(QMouseEvent* ev)
{ {
if ( ev->buttons() & Qt::LeftButton ) if (ev->buttons() & Qt::LeftButton) {
{
setFocus(); setFocus();
QLineF ray = p->line_to_point(ev->pos()); QLineF ray = p->line_to_point(ev->pos());
if ( ray.length() <= p->inner_radius() ) if (ray.length() <= p->inner_radius())
p->mouse_status = DragSquare; p->mouse_status = DragSquare;
else if ( ray.length() <= p->outer_radius() ) else if (ray.length() <= p->outer_radius())
p->mouse_status = DragCircle; p->mouse_status = DragCircle;
// Update the color // Update the color
@@ -437,80 +419,79 @@ void ColorWheel::mousePressEvent(QMouseEvent *ev)
} }
} }
void ColorWheel::mouseReleaseEvent(QMouseEvent *ev) void
ColorWheel::mouseReleaseEvent(QMouseEvent* ev)
{ {
mouseMoveEvent(ev); mouseMoveEvent(ev);
p->mouse_status = Nothing; p->mouse_status = Nothing;
emit mouseReleaseOnColor(color()); emit mouseReleaseOnColor(color());
} }
void ColorWheel::resizeEvent(QResizeEvent *) void
ColorWheel::resizeEvent(QResizeEvent*)
{ {
p->render_ring(); p->render_ring();
p->render_inner_selector(); p->render_inner_selector();
} }
void ColorWheel::setColor(QColor c) void
ColorWheel::setColor(QColor c)
{ {
qreal oldh = p->hue; qreal oldh = p->hue;
p->set_color(c); p->set_color(c);
if (!qFuzzyCompare(oldh+1, p->hue+1)) if (!qFuzzyCompare(oldh + 1, p->hue + 1))
p->render_inner_selector(); p->render_inner_selector();
update(); update();
emit colorChanged(c); emit colorChanged(c);
} }
void ColorWheel::setHue(qreal h) void
ColorWheel::setHue(qreal h)
{ {
p->hue = qBound(0.0, h, 1.0); p->hue = qBound(0.0, h, 1.0);
p->render_inner_selector(); p->render_inner_selector();
update(); update();
} }
void ColorWheel::setSaturation(qreal s) void
ColorWheel::setSaturation(qreal s)
{ {
p->sat = qBound(0.0, s, 1.0); p->sat = qBound(0.0, s, 1.0);
update(); update();
} }
void ColorWheel::setValue(qreal v) void
ColorWheel::setValue(qreal v)
{ {
p->val = qBound(0.0, v, 1.0); p->val = qBound(0.0, v, 1.0);
update(); update();
} }
void
void ColorWheel::setDisplayFlags(DisplayFlags flags) ColorWheel::setDisplayFlags(DisplayFlags flags)
{ {
if ( ! (flags & COLOR_FLAGS) ) if (!(flags & COLOR_FLAGS))
flags |= default_flags & COLOR_FLAGS; flags |= default_flags & COLOR_FLAGS;
if ( ! (flags & ANGLE_FLAGS) ) if (!(flags & ANGLE_FLAGS))
flags |= default_flags & ANGLE_FLAGS; flags |= default_flags & ANGLE_FLAGS;
if ( ! (flags & SHAPE_FLAGS) ) if (!(flags & SHAPE_FLAGS))
flags |= default_flags & SHAPE_FLAGS; flags |= default_flags & SHAPE_FLAGS;
if ( (flags & COLOR_FLAGS) != (p->display_flags & COLOR_FLAGS) ) if ((flags & COLOR_FLAGS) != (p->display_flags & COLOR_FLAGS)) {
{
QColor old_col = color(); QColor old_col = color();
if ( flags & ColorWheel::COLOR_HSL ) if (flags & ColorWheel::COLOR_HSL) {
{
p->hue = old_col.hueF(); p->hue = old_col.hueF();
p->sat = detail::color_HSL_saturationF(old_col); p->sat = detail::color_HSL_saturationF(old_col);
p->val = detail::color_lightnessF(old_col); p->val = detail::color_lightnessF(old_col);
p->color_from = &detail::color_from_hsl; p->color_from = &detail::color_from_hsl;
p->rainbow_from_hue = &detail::rainbow_hsv; p->rainbow_from_hue = &detail::rainbow_hsv;
} } else if (flags & ColorWheel::COLOR_LCH) {
else if ( flags & ColorWheel::COLOR_LCH )
{
p->hue = old_col.hueF(); p->hue = old_col.hueF();
p->sat = detail::color_chromaF(old_col); p->sat = detail::color_chromaF(old_col);
p->val = detail::color_lumaF(old_col); p->val = detail::color_lumaF(old_col);
p->color_from = &detail::color_from_lch; p->color_from = &detail::color_from_lch;
p->rainbow_from_hue = &detail::rainbow_lch; p->rainbow_from_hue = &detail::rainbow_lch;
} } else {
else
{
p->hue = old_col.hsvHueF(); p->hue = old_col.hsvHueF();
p->sat = old_col.hsvSaturationF(); p->sat = old_col.hsvSaturationF();
p->val = old_col.valueF(); p->val = old_col.valueF();
@@ -526,51 +507,54 @@ void ColorWheel::setDisplayFlags(DisplayFlags flags)
emit displayFlagsChanged(flags); emit displayFlagsChanged(flags);
} }
ColorWheel::DisplayFlags ColorWheel::displayFlags(DisplayFlags mask) const ColorWheel::DisplayFlags
ColorWheel::displayFlags(DisplayFlags mask) const
{ {
return p->display_flags & mask; return p->display_flags & mask;
} }
void ColorWheel::setDefaultDisplayFlags(DisplayFlags flags) void
ColorWheel::setDefaultDisplayFlags(DisplayFlags flags)
{ {
if ( !(flags & COLOR_FLAGS) ) if (!(flags & COLOR_FLAGS))
flags |= hard_default_flags & COLOR_FLAGS; flags |= hard_default_flags & COLOR_FLAGS;
if ( !(flags & ANGLE_FLAGS) ) if (!(flags & ANGLE_FLAGS))
flags |= hard_default_flags & ANGLE_FLAGS; flags |= hard_default_flags & ANGLE_FLAGS;
if ( !(flags & SHAPE_FLAGS) ) if (!(flags & SHAPE_FLAGS))
flags |= hard_default_flags & SHAPE_FLAGS; flags |= hard_default_flags & SHAPE_FLAGS;
default_flags = flags; default_flags = flags;
} }
ColorWheel::DisplayFlags ColorWheel::defaultDisplayFlags(DisplayFlags mask) ColorWheel::DisplayFlags
ColorWheel::defaultDisplayFlags(DisplayFlags mask)
{ {
return default_flags & mask; return default_flags & mask;
} }
void ColorWheel::setDisplayFlag(DisplayFlags flag, DisplayFlags mask) void
ColorWheel::setDisplayFlag(DisplayFlags flag, DisplayFlags mask)
{ {
setDisplayFlags((p->display_flags&~mask)|flag); setDisplayFlags((p->display_flags & ~mask) | flag);
} }
void ColorWheel::dragEnterEvent(QDragEnterEvent* event) void
ColorWheel::dragEnterEvent(QDragEnterEvent* event)
{ {
if ( event->mimeData()->hasColor() || if (event->mimeData()->hasColor() ||
( event->mimeData()->hasText() && QColor(event->mimeData()->text()).isValid() ) ) (event->mimeData()->hasText() &&
QColor(event->mimeData()->text()).isValid()))
event->acceptProposedAction(); event->acceptProposedAction();
} }
void ColorWheel::dropEvent(QDropEvent* event) void
ColorWheel::dropEvent(QDropEvent* event)
{ {
if ( event->mimeData()->hasColor() ) if (event->mimeData()->hasColor()) {
{
setColor(event->mimeData()->colorData().value<QColor>()); setColor(event->mimeData()->colorData().value<QColor>());
event->accept(); event->accept();
} } else if (event->mimeData()->hasText()) {
else if ( event->mimeData()->hasText() )
{
QColor col(event->mimeData()->text()); QColor col(event->mimeData()->text());
if ( col.isValid() ) if (col.isValid()) {
{
setColor(col); setColor(col);
event->accept(); event->accept();
} }

View File

@@ -22,46 +22,47 @@
#include <cstdlib> #include <cstdlib>
#include <QtCore/QByteArray>
#include <QtCore/QCryptographicHash>
#include <QtCore/QDataStream>
#include <QtCore/QDir> #include <QtCore/QDir>
#include <QtCore/QProcess> #include <QtCore/QProcess>
#include <QtCore/QByteArray>
#include <QtCore/QSemaphore> #include <QtCore/QSemaphore>
#include <QtCore/QSharedMemory> #include <QtCore/QSharedMemory>
#include <QtCore/QStandardPaths> #include <QtCore/QStandardPaths>
#include <QtCore/QCryptographicHash>
#include <QtCore/QDataStream>
#include <QtNetwork/QLocalServer> #include <QtNetwork/QLocalServer>
#include <QtNetwork/QLocalSocket> #include <QtNetwork/QLocalSocket>
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
#include <signal.h> #include <signal.h>
#include <unistd.h> #include <unistd.h>
#endif #endif
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
#include <windows.h> #include <lmcons.h>
#include <lmcons.h> #include <windows.h>
#endif #endif
#include "singleapplication.h" #include "singleapplication.h"
#include "singleapplication_p.h" #include "singleapplication_p.h"
SingleApplicationPrivate::SingleApplicationPrivate(SingleApplication* q_ptr)
SingleApplicationPrivate::SingleApplicationPrivate( SingleApplication *q_ptr ) : q_ptr( q_ptr ) { : q_ptr(q_ptr)
{
server = nullptr; server = nullptr;
socket = nullptr; socket = nullptr;
} }
SingleApplicationPrivate::~SingleApplicationPrivate() SingleApplicationPrivate::~SingleApplicationPrivate()
{ {
if( socket != nullptr ) { if (socket != nullptr) {
socket->close(); socket->close();
delete socket; delete socket;
} }
memory->lock(); memory->lock();
InstancesInfo* inst = static_cast<InstancesInfo*>(memory->data()); InstancesInfo* inst = static_cast<InstancesInfo*>(memory->data());
if( server != nullptr ) { if (server != nullptr) {
server->close(); server->close();
delete server; delete server;
inst->primary = false; inst->primary = false;
@@ -72,52 +73,57 @@ SingleApplicationPrivate::~SingleApplicationPrivate()
delete memory; delete memory;
} }
void SingleApplicationPrivate::genBlockServerName( int timeout ) void
SingleApplicationPrivate::genBlockServerName(int timeout)
{ {
QCryptographicHash appData( QCryptographicHash::Sha256 ); QCryptographicHash appData(QCryptographicHash::Sha256);
appData.addData( "SingleApplication", 17 ); appData.addData("SingleApplication", 17);
appData.addData( SingleApplication::app_t::applicationName().toUtf8() ); appData.addData(SingleApplication::app_t::applicationName().toUtf8());
appData.addData( SingleApplication::app_t::organizationName().toUtf8() ); appData.addData(SingleApplication::app_t::organizationName().toUtf8());
appData.addData( SingleApplication::app_t::organizationDomain().toUtf8() ); appData.addData(SingleApplication::app_t::organizationDomain().toUtf8());
if( ! (options & SingleApplication::Mode::ExcludeAppVersion) ) { if (!(options & SingleApplication::Mode::ExcludeAppVersion)) {
appData.addData( SingleApplication::app_t::applicationVersion().toUtf8() ); appData.addData(SingleApplication::app_t::applicationVersion().toUtf8());
} }
if( ! (options & SingleApplication::Mode::ExcludeAppPath) ) { if (!(options & SingleApplication::Mode::ExcludeAppPath)) {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
appData.addData( SingleApplication::app_t::applicationFilePath().toLower().toUtf8() ); appData.addData(
SingleApplication::app_t::applicationFilePath().toLower().toUtf8());
#else #else
appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() ); appData.addData(SingleApplication::app_t::applicationFilePath().toUtf8());
#endif #endif
} }
// User level block requires a user specific data in the hash // User level block requires a user specific data in the hash
if( options & SingleApplication::Mode::User ) { if (options & SingleApplication::Mode::User) {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
Q_UNUSED(timeout); Q_UNUSED(timeout);
wchar_t username [ UNLEN + 1 ]; wchar_t username[UNLEN + 1];
// Specifies size of the buffer on input // Specifies size of the buffer on input
DWORD usernameLength = UNLEN + 1; DWORD usernameLength = UNLEN + 1;
if( GetUserNameW( username, &usernameLength ) ) { if (GetUserNameW(username, &usernameLength)) {
appData.addData( QString::fromWCharArray(username).toUtf8() ); appData.addData(QString::fromWCharArray(username).toUtf8());
} else { } else {
appData.addData( QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).join("").toUtf8() ); appData.addData(
QStandardPaths::standardLocations(QStandardPaths::HomeLocation)
.join("")
.toUtf8());
} }
#endif #endif
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
QProcess process; QProcess process;
process.start( QStringLiteral("whoami"),QStringList{} ); process.start(QStringLiteral("whoami"), QStringList{});
if( process.waitForFinished( timeout ) && if (process.waitForFinished(timeout) &&
process.exitCode() == QProcess::NormalExit) { process.exitCode() == QProcess::NormalExit) {
appData.addData( process.readLine() ); appData.addData(process.readLine());
} else { } else {
appData.addData( appData.addData(
QDir( QDir(QStandardPaths::standardLocations(QStandardPaths::HomeLocation)
QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).first() .first())
).absolutePath().toUtf8() .absolutePath()
); .toUtf8());
} }
#endif #endif
} }
@@ -127,7 +133,8 @@ void SingleApplicationPrivate::genBlockServerName( int timeout )
blockServerName = appData.result().toBase64().replace("/", "_"); blockServerName = appData.result().toBase64().replace("/", "_");
} }
void SingleApplicationPrivate::startPrimary( bool resetMemory ) void
SingleApplicationPrivate::startPrimary(bool resetMemory)
{ {
Q_Q(SingleApplication); Q_Q(SingleApplication);
@@ -138,30 +145,28 @@ void SingleApplicationPrivate::startPrimary( bool resetMemory )
#endif #endif
// Successful creation means that no main process exists // Successful creation means that no main process exists
// So we start a QLocalServer to listen for connections // So we start a QLocalServer to listen for connections
QLocalServer::removeServer( blockServerName ); QLocalServer::removeServer(blockServerName);
server = new QLocalServer(); server = new QLocalServer();
// Restrict access to the socket according to the // Restrict access to the socket according to the
// SingleApplication::Mode::User flag on User level or no restrictions // SingleApplication::Mode::User flag on User level or no restrictions
if( options & SingleApplication::Mode::User ) { if (options & SingleApplication::Mode::User) {
server->setSocketOptions( QLocalServer::UserAccessOption ); server->setSocketOptions(QLocalServer::UserAccessOption);
} else { } else {
server->setSocketOptions( QLocalServer::WorldAccessOption ); server->setSocketOptions(QLocalServer::WorldAccessOption);
} }
server->listen( blockServerName ); server->listen(blockServerName);
QObject::connect( QObject::connect(server,
server,
&QLocalServer::newConnection, &QLocalServer::newConnection,
this, this,
&SingleApplicationPrivate::slotConnectionEstablished &SingleApplicationPrivate::slotConnectionEstablished);
);
// Reset the number of connections // Reset the number of connections
memory->lock(); memory->lock();
InstancesInfo* inst = static_cast<InstancesInfo*>(memory->data()); InstancesInfo* inst = static_cast<InstancesInfo*>(memory->data());
if( resetMemory ) { if (resetMemory) {
inst->secondary = 0; inst->secondary = 0;
} }
@@ -173,7 +178,8 @@ void SingleApplicationPrivate::startPrimary( bool resetMemory )
instanceNumber = 0; instanceNumber = 0;
} }
void SingleApplicationPrivate::startSecondary() void
SingleApplicationPrivate::startSecondary()
{ {
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
// Handle any further termination signals to ensure the // Handle any further termination signals to ensure the
@@ -182,31 +188,33 @@ void SingleApplicationPrivate::startSecondary()
#endif #endif
} }
void SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType connectionType ) void
SingleApplicationPrivate::connectToPrimary(int msecs,
ConnectionType connectionType)
{ {
// Connect to the Local Server of the Primary Instance if not already // Connect to the Local Server of the Primary Instance if not already
// connected. // connected.
if( socket == nullptr ) { if (socket == nullptr) {
socket = new QLocalSocket(); socket = new QLocalSocket();
} }
// If already connected - we are done; // If already connected - we are done;
if( socket->state() == QLocalSocket::ConnectedState ) if (socket->state() == QLocalSocket::ConnectedState)
return; return;
// If not connect // If not connect
if( socket->state() == QLocalSocket::UnconnectedState || if (socket->state() == QLocalSocket::UnconnectedState ||
socket->state() == QLocalSocket::ClosingState ) { socket->state() == QLocalSocket::ClosingState) {
socket->connectToServer( blockServerName ); socket->connectToServer(blockServerName);
} }
// Wait for being connected // Wait for being connected
if( socket->state() == QLocalSocket::ConnectingState ) { if (socket->state() == QLocalSocket::ConnectingState) {
socket->waitForConnected( msecs ); socket->waitForConnected(msecs);
} }
// Initialisation message according to the SingleApplication protocol // Initialisation message according to the SingleApplication protocol
if( socket->state() == QLocalSocket::ConnectedState ) { if (socket->state() == QLocalSocket::ConnectedState) {
// Notify the parent that a new instance had been started; // Notify the parent that a new instance had been started;
QByteArray initMsg; QByteArray initMsg;
QDataStream writeStream(&initMsg, QIODevice::WriteOnly); QDataStream writeStream(&initMsg, QIODevice::WriteOnly);
@@ -214,16 +222,18 @@ void SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType conne
writeStream << blockServerName.toLatin1(); writeStream << blockServerName.toLatin1();
writeStream << static_cast<quint8>(connectionType); writeStream << static_cast<quint8>(connectionType);
writeStream << instanceNumber; writeStream << instanceNumber;
quint16 checksum = qChecksum(initMsg.constData(), static_cast<quint32>(initMsg.length())); quint16 checksum =
qChecksum(initMsg.constData(), static_cast<quint32>(initMsg.length()));
writeStream << checksum; writeStream << checksum;
socket->write( initMsg ); socket->write(initMsg);
socket->flush(); socket->flush();
socket->waitForBytesWritten( msecs ); socket->waitForBytesWritten(msecs);
} }
} }
qint64 SingleApplicationPrivate::primaryPid() qint64
SingleApplicationPrivate::primaryPid()
{ {
qint64 pid; qint64 pid;
@@ -236,47 +246,51 @@ qint64 SingleApplicationPrivate::primaryPid()
} }
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
void SingleApplicationPrivate::crashHandler() void
{ SingleApplicationPrivate::crashHandler()
{
// Handle any further termination signals to ensure the // Handle any further termination signals to ensure the
// QSharedMemory block is deleted even if the process crashes // QSharedMemory block is deleted even if the process crashes
signal( SIGHUP, SingleApplicationPrivate::terminate ); // 1 signal(SIGHUP, SingleApplicationPrivate::terminate); // 1
signal( SIGINT, SingleApplicationPrivate::terminate ); // 2 signal(SIGINT, SingleApplicationPrivate::terminate); // 2
signal( SIGQUIT, SingleApplicationPrivate::terminate ); // 3 signal(SIGQUIT, SingleApplicationPrivate::terminate); // 3
signal( SIGILL, SingleApplicationPrivate::terminate ); // 4 signal(SIGILL, SingleApplicationPrivate::terminate); // 4
signal( SIGABRT, SingleApplicationPrivate::terminate ); // 6 signal(SIGABRT, SingleApplicationPrivate::terminate); // 6
signal( SIGFPE, SingleApplicationPrivate::terminate ); // 8 signal(SIGFPE, SingleApplicationPrivate::terminate); // 8
signal( SIGBUS, SingleApplicationPrivate::terminate ); // 10 signal(SIGBUS, SingleApplicationPrivate::terminate); // 10
signal( SIGSEGV, SingleApplicationPrivate::terminate ); // 11 signal(SIGSEGV, SingleApplicationPrivate::terminate); // 11
signal( SIGSYS, SingleApplicationPrivate::terminate ); // 12 signal(SIGSYS, SingleApplicationPrivate::terminate); // 12
signal( SIGPIPE, SingleApplicationPrivate::terminate ); // 13 signal(SIGPIPE, SingleApplicationPrivate::terminate); // 13
signal( SIGALRM, SingleApplicationPrivate::terminate ); // 14 signal(SIGALRM, SingleApplicationPrivate::terminate); // 14
signal( SIGTERM, SingleApplicationPrivate::terminate ); // 15 signal(SIGTERM, SingleApplicationPrivate::terminate); // 15
signal( SIGXCPU, SingleApplicationPrivate::terminate ); // 24 signal(SIGXCPU, SingleApplicationPrivate::terminate); // 24
signal( SIGXFSZ, SingleApplicationPrivate::terminate ); // 25 signal(SIGXFSZ, SingleApplicationPrivate::terminate); // 25
} }
void SingleApplicationPrivate::terminate( int signum ) void
{ SingleApplicationPrivate::terminate(int signum)
{
delete ((SingleApplication*)QCoreApplication::instance())->d_ptr; delete ((SingleApplication*)QCoreApplication::instance())->d_ptr;
::exit( 128 + signum ); ::exit(128 + signum);
} }
#endif #endif
/** /**
* @brief Executed when a connection has been made to the LocalServer * @brief Executed when a connection has been made to the LocalServer
*/ */
void SingleApplicationPrivate::slotConnectionEstablished() void
SingleApplicationPrivate::slotConnectionEstablished()
{ {
Q_Q(SingleApplication); Q_Q(SingleApplication);
QLocalSocket *nextConnSocket = server->nextPendingConnection(); QLocalSocket* nextConnSocket = server->nextPendingConnection();
quint32 instanceId = 0; quint32 instanceId = 0;
ConnectionType connectionType = InvalidConnection; ConnectionType connectionType = InvalidConnection;
if( nextConnSocket->waitForReadyRead( 100 ) ) { if (nextConnSocket->waitForReadyRead(100)) {
// read all data from message in same order/format as written // read all data from message in same order/format as written
QByteArray msgBytes = nextConnSocket->read(nextConnSocket->bytesAvailable() - static_cast<qint64>(sizeof(quint16))); QByteArray msgBytes = nextConnSocket->read(
nextConnSocket->bytesAvailable() - static_cast<qint64>(sizeof(quint16)));
QByteArray checksumBytes = nextConnSocket->read(sizeof(quint16)); QByteArray checksumBytes = nextConnSocket->read(sizeof(quint16));
QDataStream readStream(msgBytes); QDataStream readStream(msgBytes);
readStream.setVersion(QDataStream::Qt_5_2); readStream.setVersion(QDataStream::Qt_5_2);
@@ -296,60 +310,62 @@ void SingleApplicationPrivate::slotConnectionEstablished()
checksumStream.setVersion(QDataStream::Qt_5_2); checksumStream.setVersion(QDataStream::Qt_5_2);
checksumStream >> msgChecksum; checksumStream >> msgChecksum;
const quint16 actualChecksum = qChecksum(msgBytes.constData(), static_cast<quint32>(msgBytes.length())); const quint16 actualChecksum =
qChecksum(msgBytes.constData(), static_cast<quint32>(msgBytes.length()));
if (readStream.status() != QDataStream::Ok || QLatin1String(latin1Name) != blockServerName || msgChecksum != actualChecksum) { if (readStream.status() != QDataStream::Ok ||
QLatin1String(latin1Name) != blockServerName ||
msgChecksum != actualChecksum) {
connectionType = InvalidConnection; connectionType = InvalidConnection;
} }
} }
if( connectionType == InvalidConnection ) { if (connectionType == InvalidConnection) {
nextConnSocket->close(); nextConnSocket->close();
delete nextConnSocket; delete nextConnSocket;
return; return;
} }
QObject::connect( QObject::connect(nextConnSocket,
nextConnSocket,
&QLocalSocket::aboutToClose, &QLocalSocket::aboutToClose,
this, this,
[nextConnSocket, instanceId, this]() { [nextConnSocket, instanceId, this]() {
emit this->slotClientConnectionClosed( nextConnSocket, instanceId ); emit this->slotClientConnectionClosed(nextConnSocket,
} instanceId);
); });
QObject::connect( QObject::connect(nextConnSocket,
nextConnSocket,
&QLocalSocket::readyRead, &QLocalSocket::readyRead,
this, this,
[nextConnSocket, instanceId, this]() { [nextConnSocket, instanceId, this]() {
emit this->slotDataAvailable( nextConnSocket, instanceId ); emit this->slotDataAvailable(nextConnSocket, instanceId);
} });
);
if( connectionType == NewInstance || ( if (connectionType == NewInstance ||
connectionType == SecondaryInstance && (connectionType == SecondaryInstance &&
options & SingleApplication::Mode::SecondaryNotification options & SingleApplication::Mode::SecondaryNotification)) {
)
) {
emit q->instanceStarted(); emit q->instanceStarted();
} }
if( nextConnSocket->bytesAvailable() > 0 ) { if (nextConnSocket->bytesAvailable() > 0) {
emit this->slotDataAvailable( nextConnSocket, instanceId ); emit this->slotDataAvailable(nextConnSocket, instanceId);
} }
} }
void SingleApplicationPrivate::slotDataAvailable( QLocalSocket *dataSocket, quint32 instanceId ) void
SingleApplicationPrivate::slotDataAvailable(QLocalSocket* dataSocket,
quint32 instanceId)
{ {
Q_Q(SingleApplication); Q_Q(SingleApplication);
emit q->receivedMessage( instanceId, dataSocket->readAll() ); emit q->receivedMessage(instanceId, dataSocket->readAll());
} }
void SingleApplicationPrivate::slotClientConnectionClosed( QLocalSocket *closedSocket, quint32 instanceId ) void
SingleApplicationPrivate::slotClientConnectionClosed(QLocalSocket* closedSocket,
quint32 instanceId)
{ {
if( closedSocket->bytesAvailable() > 0 ) if (closedSocket->bytesAvailable() > 0)
emit slotDataAvailable( closedSocket, instanceId ); emit slotDataAvailable(closedSocket, instanceId);
closedSocket->deleteLater(); closedSocket->deleteLater();
} }
@@ -360,8 +376,13 @@ void SingleApplicationPrivate::slotClientConnectionClosed( QLocalSocket *closedS
* @param argv * @param argv
* @param {bool} allowSecondaryInstances * @param {bool} allowSecondaryInstances
*/ */
SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSecondary, Options options, int timeout ) SingleApplication::SingleApplication(int& argc,
: app_t( argc, argv ), d_ptr( new SingleApplicationPrivate( this ) ) char* argv[],
bool allowSecondary,
Options options,
int timeout)
: app_t(argc, argv)
, d_ptr(new SingleApplicationPrivate(this))
{ {
Q_D(SingleApplication); Q_D(SingleApplication);
@@ -370,41 +391,42 @@ SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSeconda
// Generating an application ID used for identifying the shared memory // Generating an application ID used for identifying the shared memory
// block and QLocalServer // block and QLocalServer
d->genBlockServerName( timeout ); d->genBlockServerName(timeout);
// Guarantee thread safe behaviour with a shared memory block. Also by // Guarantee thread safe behaviour with a shared memory block. Also by
// explicitly attaching it and then deleting it we make sure that the // explicitly attaching it and then deleting it we make sure that the
// memory is deleted even if the process had crashed on Unix. // memory is deleted even if the process had crashed on Unix.
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
d->memory = new QSharedMemory( d->blockServerName ); d->memory = new QSharedMemory(d->blockServerName);
d->memory->attach(); d->memory->attach();
delete d->memory; delete d->memory;
#endif #endif
d->memory = new QSharedMemory( d->blockServerName ); d->memory = new QSharedMemory(d->blockServerName);
// Create a shared memory block // Create a shared memory block
if( d->memory->create( sizeof( InstancesInfo ) ) ) { if (d->memory->create(sizeof(InstancesInfo))) {
d->startPrimary( true ); d->startPrimary(true);
return; return;
} else { } else {
// Attempt to attach to the memory segment // Attempt to attach to the memory segment
if( d->memory->attach() ) { if (d->memory->attach()) {
d->memory->lock(); d->memory->lock();
InstancesInfo* inst = static_cast<InstancesInfo*>(d->memory->data()); InstancesInfo* inst = static_cast<InstancesInfo*>(d->memory->data());
if( ! inst->primary ) { if (!inst->primary) {
d->startPrimary( false ); d->startPrimary(false);
d->memory->unlock(); d->memory->unlock();
return; return;
} }
// Check if another instance can be started // Check if another instance can be started
if( allowSecondary ) { if (allowSecondary) {
inst->secondary += 1; inst->secondary += 1;
d->instanceNumber = inst->secondary; d->instanceNumber = inst->secondary;
d->startSecondary(); d->startSecondary();
if( d->options & Mode::SecondaryNotification ) { if (d->options & Mode::SecondaryNotification) {
d->connectToPrimary( timeout, SingleApplicationPrivate::SecondaryInstance ); d->connectToPrimary(timeout,
SingleApplicationPrivate::SecondaryInstance);
} }
d->memory->unlock(); d->memory->unlock();
return; return;
@@ -414,9 +436,9 @@ SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSeconda
} }
} }
d->connectToPrimary( timeout, SingleApplicationPrivate::NewInstance ); d->connectToPrimary(timeout, SingleApplicationPrivate::NewInstance);
delete d; delete d;
::exit( EXIT_SUCCESS ); ::exit(EXIT_SUCCESS);
} }
/** /**
@@ -428,42 +450,48 @@ SingleApplication::~SingleApplication()
delete d; delete d;
} }
bool SingleApplication::isPrimary() bool
SingleApplication::isPrimary()
{ {
Q_D(SingleApplication); Q_D(SingleApplication);
return d->server != nullptr; return d->server != nullptr;
} }
bool SingleApplication::isSecondary() bool
SingleApplication::isSecondary()
{ {
Q_D(SingleApplication); Q_D(SingleApplication);
return d->server == nullptr; return d->server == nullptr;
} }
quint32 SingleApplication::instanceId() quint32
SingleApplication::instanceId()
{ {
Q_D(SingleApplication); Q_D(SingleApplication);
return d->instanceNumber; return d->instanceNumber;
} }
qint64 SingleApplication::primaryPid() qint64
SingleApplication::primaryPid()
{ {
Q_D(SingleApplication); Q_D(SingleApplication);
return d->primaryPid(); return d->primaryPid();
} }
bool SingleApplication::sendMessage( QByteArray message, int timeout ) bool
SingleApplication::sendMessage(QByteArray message, int timeout)
{ {
Q_D(SingleApplication); Q_D(SingleApplication);
// Nobody to connect to // Nobody to connect to
if( isPrimary() ) return false; if (isPrimary())
return false;
// Make sure the socket is connected // Make sure the socket is connected
d->connectToPrimary( timeout, SingleApplicationPrivate::Reconnect ); d->connectToPrimary(timeout, SingleApplicationPrivate::Reconnect);
d->socket->write( message ); d->socket->write(message);
bool dataWritten = d->socket->flush(); bool dataWritten = d->socket->flush();
d->socket->waitForBytesWritten( timeout ); d->socket->waitForBytesWritten(timeout);
return dataWritten; return dataWritten;
} }

View File

@@ -27,7 +27,7 @@
#include <QtNetwork/QLocalSocket> #include <QtNetwork/QLocalSocket>
#ifndef QAPPLICATION_CLASS #ifndef QAPPLICATION_CLASS
#define QAPPLICATION_CLASS QCoreApplication #define QAPPLICATION_CLASS QCoreApplication
#endif #endif
#include QT_STRINGIFY(QAPPLICATION_CLASS) #include QT_STRINGIFY(QAPPLICATION_CLASS)
@@ -56,7 +56,8 @@ public:
* block will be user wide. * block will be user wide.
* @enum * @enum
*/ */
enum Mode { enum Mode
{
User = 1 << 0, User = 1 << 0,
System = 1 << 1, System = 1 << 1,
SecondaryNotification = 1 << 2, SecondaryNotification = 1 << 2,
@@ -85,7 +86,11 @@ public:
* Usually 4*timeout would be the worst case (fail) scenario. * Usually 4*timeout would be the worst case (fail) scenario.
* @see See the corresponding QAPPLICATION_CLASS constructor for reference * @see See the corresponding QAPPLICATION_CLASS constructor for reference
*/ */
explicit SingleApplication( int &argc, char *argv[], bool allowSecondary = false, Options options = Mode::User, int timeout = 100 ); explicit SingleApplication(int& argc,
char* argv[],
bool allowSecondary = false,
Options options = Mode::User,
int timeout = 100);
~SingleApplication(); ~SingleApplication();
/** /**
@@ -119,14 +124,14 @@ public:
* @note sendMessage() will return false if invoked from the primary * @note sendMessage() will return false if invoked from the primary
* instance. * instance.
*/ */
bool sendMessage( QByteArray message, int timeout = 100 ); bool sendMessage(QByteArray message, int timeout = 100);
Q_SIGNALS: Q_SIGNALS:
void instanceStarted(); void instanceStarted();
void receivedMessage( quint32 instanceId, QByteArray message ); void receivedMessage(quint32 instanceId, QByteArray message);
private: private:
SingleApplicationPrivate *d_ptr; SingleApplicationPrivate* d_ptr;
Q_DECLARE_PRIVATE(SingleApplication) Q_DECLARE_PRIVATE(SingleApplication)
}; };

View File

@@ -32,21 +32,24 @@
#ifndef SINGLEAPPLICATION_P_H #ifndef SINGLEAPPLICATION_P_H
#define SINGLEAPPLICATION_P_H #define SINGLEAPPLICATION_P_H
#include "singleapplication.h"
#include <QtCore/QSharedMemory> #include <QtCore/QSharedMemory>
#include <QtNetwork/QLocalServer> #include <QtNetwork/QLocalServer>
#include <QtNetwork/QLocalSocket> #include <QtNetwork/QLocalSocket>
#include "singleapplication.h"
struct InstancesInfo { struct InstancesInfo
{
bool primary; bool primary;
quint32 secondary; quint32 secondary;
qint64 primaryPid; qint64 primaryPid;
}; };
class SingleApplicationPrivate : public QObject { class SingleApplicationPrivate : public QObject
Q_OBJECT {
Q_OBJECT
public: public:
enum ConnectionType : quint8 { enum ConnectionType : quint8
{
InvalidConnection = 0, InvalidConnection = 0,
NewInstance = 1, NewInstance = 1,
SecondaryInstance = 2, SecondaryInstance = 2,
@@ -54,32 +57,32 @@ public:
}; };
Q_DECLARE_PUBLIC(SingleApplication) Q_DECLARE_PUBLIC(SingleApplication)
SingleApplicationPrivate( SingleApplication *q_ptr ); SingleApplicationPrivate(SingleApplication* q_ptr);
~SingleApplicationPrivate(); ~SingleApplicationPrivate();
void genBlockServerName( int msecs ); void genBlockServerName(int msecs);
void startPrimary( bool resetMemory ); void startPrimary(bool resetMemory);
void startSecondary(); void startSecondary();
void connectToPrimary(int msecs, ConnectionType connectionType ); void connectToPrimary(int msecs, ConnectionType connectionType);
qint64 primaryPid(); qint64 primaryPid();
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
void crashHandler(); void crashHandler();
static void terminate( int signum ); static void terminate(int signum);
#endif #endif
QSharedMemory *memory; QSharedMemory* memory;
SingleApplication *q_ptr; SingleApplication* q_ptr;
QLocalSocket *socket; QLocalSocket* socket;
QLocalServer *server; QLocalServer* server;
quint32 instanceNumber; quint32 instanceNumber;
QString blockServerName; QString blockServerName;
SingleApplication::Options options; SingleApplication::Options options;
public Q_SLOTS: public Q_SLOTS:
void slotConnectionEstablished(); void slotConnectionEstablished();
void slotDataAvailable( QLocalSocket*, quint32 ); void slotDataAvailable(QLocalSocket*, quint32);
void slotClientConnectionClosed( QLocalSocket*, quint32 ); void slotClientConnectionClosed(QLocalSocket*, quint32);
}; };
#endif // SINGLEAPPLICATION_P_H #endif // SINGLEAPPLICATION_P_H

View File

@@ -17,38 +17,46 @@
#include "commandargument.h" #include "commandargument.h"
CommandArgument::CommandArgument() { CommandArgument::CommandArgument() {}
} CommandArgument::CommandArgument(const QString& name,
const QString& description)
: m_name(name)
, m_description(description)
{}
CommandArgument::CommandArgument(const QString &name, void
const QString &description) : CommandArgument::setName(const QString& name)
m_name(name), m_description(description)
{ {
}
void CommandArgument::setName(const QString &name) {
m_name = name; m_name = name;
} }
QString CommandArgument::name() const { QString
CommandArgument::name() const
{
return m_name; return m_name;
} }
void CommandArgument::setDescription(const QString &description) { void
CommandArgument::setDescription(const QString& description)
{
m_description = description; m_description = description;
} }
QString CommandArgument::description() const { QString
CommandArgument::description() const
{
return m_description; return m_description;
} }
bool CommandArgument::isRoot() const { bool
CommandArgument::isRoot() const
{
return m_name.isEmpty() && m_description.isEmpty(); return m_name.isEmpty() && m_description.isEmpty();
} }
bool CommandArgument::operator ==(const CommandArgument &arg) const { bool
return m_description == arg.m_description CommandArgument::operator==(const CommandArgument& arg) const
&& m_name == arg.m_name; {
return m_description == arg.m_description && m_name == arg.m_name;
} }

View File

@@ -19,20 +19,21 @@
#include <QString> #include <QString>
class CommandArgument { class CommandArgument
{
public: public:
CommandArgument(); CommandArgument();
explicit CommandArgument(const QString &name, const QString &description); explicit CommandArgument(const QString& name, const QString& description);
void setName(const QString &name); void setName(const QString& name);
QString name() const; QString name() const;
void setDescription(const QString &description); void setDescription(const QString& description);
QString description() const; QString description() const;
bool isRoot() const; bool isRoot() const;
bool operator ==(const CommandArgument &arg) const; bool operator==(const CommandArgument& arg) const;
private: private:
QString m_name; QString m_name;

View File

@@ -19,34 +19,34 @@
#include <QApplication> #include <QApplication>
#include <QTextStream> #include <QTextStream>
CommandLineParser::CommandLineParser() : CommandLineParser::CommandLineParser()
m_description(qApp->applicationName()) : m_description(qApp->applicationName())
{ {}
}
namespace { namespace {
QTextStream out(stdout); QTextStream out(stdout);
QTextStream err(stderr); QTextStream err(stderr);
auto versionOption = CommandOption({"v", "version"}, auto versionOption =
CommandOption({ "v", "version" },
QStringLiteral("Displays version information")); QStringLiteral("Displays version information"));
auto helpOption = CommandOption({"h", "help"}, auto helpOption =
QStringLiteral("Displays this help")); CommandOption({ "h", "help" }, QStringLiteral("Displays this help"));
QString optionsToString(const QList<CommandOption> &options, QString
const QList<CommandArgument> &arguments) { optionsToString(const QList<CommandOption>& options,
const QList<CommandArgument>& arguments)
{
int size = 0; // track the largest size int size = 0; // track the largest size
QStringList dashedOptionList; QStringList dashedOptionList;
// save the dashed options and its size in order to print the description // save the dashed options and its size in order to print the description
// of every option at the same horizontal character position. // of every option at the same horizontal character position.
for (auto const &option: options) { for (auto const& option : options) {
QStringList dashedOptions = option.dashedNames(); QStringList dashedOptions = option.dashedNames();
QString joinedDashedOptions = dashedOptions.join(QStringLiteral(", ")); QString joinedDashedOptions = dashedOptions.join(QStringLiteral(", "));
if (!option.valueName().isEmpty()) { if (!option.valueName().isEmpty()) {
joinedDashedOptions += QStringLiteral(" <%1>") joinedDashedOptions += QStringLiteral(" <%1>").arg(option.valueName());
.arg(option.valueName());
} }
if (joinedDashedOptions.length() > size) { if (joinedDashedOptions.length() > size) {
size = joinedDashedOptions.length(); size = joinedDashedOptions.length();
@@ -54,20 +54,20 @@ QString optionsToString(const QList<CommandOption> &options,
dashedOptionList << joinedDashedOptions; dashedOptionList << joinedDashedOptions;
} }
// check the length of the arguments // check the length of the arguments
for (auto const &arg: arguments) { for (auto const& arg : arguments) {
if(arg.name().length() > size) if (arg.name().length() > size)
size = arg.name().length(); size = arg.name().length();
} }
// generate the text // generate the text
QString result; QString result;
if(!dashedOptionList.isEmpty()) { if (!dashedOptionList.isEmpty()) {
result += QLatin1String("Options:\n"); result += QLatin1String("Options:\n");
QString linePadding = QStringLiteral(" ").repeated(size + 4).prepend("\n"); QString linePadding = QStringLiteral(" ").repeated(size + 4).prepend("\n");
for (int i = 0; i < options.length(); ++i) { for (int i = 0; i < options.length(); ++i) {
result += QStringLiteral(" %1 %2\n") result += QStringLiteral(" %1 %2\n")
.arg(dashedOptionList.at(i).leftJustified(size, ' ')) .arg(dashedOptionList.at(i).leftJustified(size, ' '))
.arg(options.at(i).description() .arg(options.at(i).description().replace(QLatin1String("\n"),
.replace(QLatin1String("\n"), linePadding)); linePadding));
} }
if (!arguments.isEmpty()) { if (!arguments.isEmpty()) {
result += QLatin1String("\n"); result += QLatin1String("\n");
@@ -86,14 +86,15 @@ QString optionsToString(const QList<CommandOption> &options,
} // unnamed namespace } // unnamed namespace
bool CommandLineParser::processArgs(const QStringList &args, bool
QStringList::const_iterator &actualIt, CommandLineParser::processArgs(const QStringList& args,
Node * &actualNode) QStringList::const_iterator& actualIt,
Node*& actualNode)
{ {
QString argument = *actualIt; QString argument = *actualIt;
bool ok = true; bool ok = true;
bool isValidArg = false; bool isValidArg = false;
for (Node &n: actualNode->subNodes) { for (Node& n : actualNode->subNodes) {
if (n.argument.name() == argument) { if (n.argument.name() == argument) {
actualNode = &n; actualNode = &n;
isValidArg = true; isValidArg = true;
@@ -114,9 +115,10 @@ bool CommandLineParser::processArgs(const QStringList &args,
return ok; return ok;
} }
bool CommandLineParser::processOptions(const QStringList &args, bool
QStringList::const_iterator &actualIt, CommandLineParser::processOptions(const QStringList& args,
Node *const actualNode) QStringList::const_iterator& actualIt,
Node* const actualNode)
{ {
QString arg = *actualIt; QString arg = *actualIt;
bool ok = true; bool ok = true;
@@ -124,20 +126,17 @@ bool CommandLineParser::processOptions(const QStringList &args,
int equalsPos = arg.indexOf(QLatin1String("=")); int equalsPos = arg.indexOf(QLatin1String("="));
QString valueStr; QString valueStr;
if (equalsPos != -1) { if (equalsPos != -1) {
valueStr = arg.mid(equalsPos +1); // right valueStr = arg.mid(equalsPos + 1); // right
arg = arg.mid(0, equalsPos); // left arg = arg.mid(0, equalsPos); // left
} }
// check format -x --xx... // check format -x --xx...
bool isDoubleDashed = arg.startsWith(QLatin1String("--")); bool isDoubleDashed = arg.startsWith(QLatin1String("--"));
ok = isDoubleDashed ? arg.length() > 3 : ok = isDoubleDashed ? arg.length() > 3 : arg.length() == 2;
arg.length() == 2;
if (!ok) { if (!ok) {
out << QStringLiteral("the option %1 has a wrong format.").arg(arg); out << QStringLiteral("the option %1 has a wrong format.").arg(arg);
return ok; return ok;
} }
arg = isDoubleDashed ? arg = isDoubleDashed ? arg.remove(0, 2) : arg.remove(0, 1);
arg.remove(0, 2) :
arg.remove(0, 1);
// get option // get option
auto endIt = actualNode->options.cend(); auto endIt = actualNode->options.cend();
auto optionIt = endIt; auto optionIt = endIt;
@@ -153,7 +152,8 @@ bool CommandLineParser::processOptions(const QStringList &args,
argName = qApp->applicationName(); argName = qApp->applicationName();
} }
out << QStringLiteral("the option '%1' is not a valid option " out << QStringLiteral("the option '%1' is not a valid option "
"for the argument '%2'.").arg(arg) "for the argument '%2'.")
.arg(arg)
.arg(argName); .arg(argName);
ok = false; ok = false;
return ok; return ok;
@@ -163,12 +163,13 @@ bool CommandLineParser::processOptions(const QStringList &args,
bool requiresValue = !(option.valueName().isEmpty()); bool requiresValue = !(option.valueName().isEmpty());
if (!requiresValue && equalsPos != -1) { if (!requiresValue && equalsPos != -1) {
out << QStringLiteral("the option '%1' contains a '=' and it doesn't " out << QStringLiteral("the option '%1' contains a '=' and it doesn't "
"require a value.").arg(arg); "require a value.")
.arg(arg);
ok = false; ok = false;
return ok; return ok;
} else if (requiresValue && valueStr.isEmpty()) { } else if (requiresValue && valueStr.isEmpty()) {
// find in the next // find in the next
if (actualIt+1 != args.cend()) { if (actualIt + 1 != args.cend()) {
++actualIt; ++actualIt;
} else { } else {
out << QStringLiteral("Expected value after the option '%1'.").arg(arg); out << QStringLiteral("Expected value after the option '%1'.").arg(arg);
@@ -193,17 +194,18 @@ bool CommandLineParser::processOptions(const QStringList &args,
return ok; return ok;
} }
bool CommandLineParser::parse(const QStringList &args) { bool
CommandLineParser::parse(const QStringList& args)
{
m_foundArgs.clear(); m_foundArgs.clear();
m_foundOptions.clear(); m_foundOptions.clear();
bool ok = true; bool ok = true;
Node *actualNode = &m_parseTree; Node* actualNode = &m_parseTree;
auto it = ++args.cbegin(); auto it = ++args.cbegin();
// check version option // check version option
QStringList dashedVersion = versionOption.dashedNames(); QStringList dashedVersion = versionOption.dashedNames();
if (m_withVersion && args.length() > 1 && if (m_withVersion && args.length() > 1 &&
dashedVersion.contains(args.at(1))) dashedVersion.contains(args.at(1))) {
{
if (args.length() == 2) { if (args.length() == 2) {
printVersion(); printVersion();
m_foundOptions << versionOption; m_foundOptions << versionOption;
@@ -212,13 +214,12 @@ bool CommandLineParser::parse(const QStringList &args) {
ok = false; ok = false;
} }
return ok; return ok;
} }
// check help option // check help option
ok = processIfOptionIsHelp(args, it, actualNode); ok = processIfOptionIsHelp(args, it, actualNode);
// process the other args // process the other args
for (; it != args.cend() && ok; ++it) { for (; it != args.cend() && ok; ++it) {
const QString &value = *it; const QString& value = *it;
if (value.startsWith(QLatin1String("-"))) { if (value.startsWith(QLatin1String("-"))) {
ok = processOptions(args, it, actualNode); ok = processOptions(args, it, actualNode);
@@ -232,21 +233,26 @@ bool CommandLineParser::parse(const QStringList &args) {
return ok; return ok;
} }
CommandOption CommandLineParser::addVersionOption() { CommandOption
CommandLineParser::addVersionOption()
{
m_withVersion = true; m_withVersion = true;
return versionOption; return versionOption;
} }
CommandOption CommandLineParser::addHelpOption() { CommandOption
CommandLineParser::addHelpOption()
{
m_withHelp = true; m_withHelp = true;
return helpOption; return helpOption;
} }
bool CommandLineParser::AddArgument(const CommandArgument &arg, bool
const CommandArgument &parent) CommandLineParser::AddArgument(const CommandArgument& arg,
const CommandArgument& parent)
{ {
bool res = true; bool res = true;
Node *n = findParent(parent); Node* n = findParent(parent);
if (n == nullptr) { if (n == nullptr) {
res = false; res = false;
} else { } else {
@@ -257,11 +263,12 @@ bool CommandLineParser::AddArgument(const CommandArgument &arg,
return res; return res;
} }
bool CommandLineParser::AddOption(const CommandOption &option, bool
const CommandArgument &parent) CommandLineParser::AddOption(const CommandOption& option,
const CommandArgument& parent)
{ {
bool res = true; bool res = true;
Node *n = findParent(parent); Node* n = findParent(parent);
if (n == nullptr) { if (n == nullptr) {
res = false; res = false;
} else { } else {
@@ -270,11 +277,12 @@ bool CommandLineParser::AddOption(const CommandOption &option,
return res; return res;
} }
bool CommandLineParser::AddOptions(const QList<CommandOption> &options, bool
const CommandArgument &parent) CommandLineParser::AddOptions(const QList<CommandOption>& options,
const CommandArgument& parent)
{ {
bool res = true; bool res = true;
for (auto const &option: options) { for (auto const& option : options) {
if (!AddOption(option, parent)) { if (!AddOption(option, parent)) {
res = false; res = false;
break; break;
@@ -283,26 +291,35 @@ bool CommandLineParser::AddOptions(const QList<CommandOption> &options,
return res; return res;
} }
void CommandLineParser::setGeneralErrorMessage(const QString &msg) { void
CommandLineParser::setGeneralErrorMessage(const QString& msg)
{
m_generalErrorMessage = msg; m_generalErrorMessage = msg;
} }
void CommandLineParser::setDescription(const QString &description) { void
CommandLineParser::setDescription(const QString& description)
{
m_description = description; m_description = description;
} }
bool CommandLineParser::isSet(const CommandArgument &arg) const { bool
CommandLineParser::isSet(const CommandArgument& arg) const
{
return m_foundArgs.contains(arg); return m_foundArgs.contains(arg);
} }
bool
bool CommandLineParser::isSet(const CommandOption &option) const { CommandLineParser::isSet(const CommandOption& option) const
{
return m_foundOptions.contains(option); return m_foundOptions.contains(option);
} }
QString CommandLineParser::value(const CommandOption &option) const { QString
CommandLineParser::value(const CommandOption& option) const
{
QString value = option.value(); QString value = option.value();
for (const CommandOption &fOption: m_foundOptions) { for (const CommandOption& fOption : m_foundOptions) {
if (option == fOption) { if (option == fOption) {
value = fOption.value(); value = fOption.value();
break; break;
@@ -311,12 +328,16 @@ QString CommandLineParser::value(const CommandOption &option) const {
return value; return value;
} }
void CommandLineParser::printVersion() { void
CommandLineParser::printVersion()
{
out << "Flameshot " << qApp->applicationVersion() << "\nCompiled with Qt " out << "Flameshot " << qApp->applicationVersion() << "\nCompiled with Qt "
<< static_cast<QString>(QT_VERSION_STR) << "\n"; << static_cast<QString>(QT_VERSION_STR) << "\n";
} }
void CommandLineParser::printHelp(QStringList args, const Node *node) { void
CommandLineParser::printHelp(QStringList args, const Node* node)
{
args.removeLast(); // remove the help, it's always the last args.removeLast(); // remove the help, it's always the last
QString helpText; QString helpText;
// add usage info // add usage info
@@ -327,10 +348,11 @@ void CommandLineParser::printHelp(QStringList args, const Node *node) {
QString argText = node->subNodes.isEmpty() ? "" : "[arguments]"; QString argText = node->subNodes.isEmpty() ? "" : "[arguments]";
helpText += QStringLiteral("Usage: %1 [%2-options] %3\n\n") helpText += QStringLiteral("Usage: %1 [%2-options] %3\n\n")
.arg(args.join(QStringLiteral(" "))) .arg(args.join(QStringLiteral(" ")))
.arg(argName).arg(argText); .arg(argName)
.arg(argText);
// add command options and subarguments // add command options and subarguments
QList<CommandArgument> subArgs; QList<CommandArgument> subArgs;
for (const Node &n: node->subNodes) for (const Node& n : node->subNodes)
subArgs.append(n.argument); subArgs.append(n.argument);
auto modifiedOptions = node->options; auto modifiedOptions = node->options;
if (m_withHelp) if (m_withHelp)
@@ -343,17 +365,16 @@ void CommandLineParser::printHelp(QStringList args, const Node *node) {
out << helpText; out << helpText;
} }
CommandLineParser::Node* CommandLineParser::findParent( CommandLineParser::Node*
const CommandArgument &parent) CommandLineParser::findParent(const CommandArgument& parent)
{ {
if (parent == CommandArgument()) { if (parent == CommandArgument()) {
return &m_parseTree; return &m_parseTree;
} }
//find the parent in the subNodes recursively // find the parent in the subNodes recursively
Node *res = nullptr; Node* res = nullptr;
for (auto i = m_parseTree.subNodes.begin(); for (auto i = m_parseTree.subNodes.begin(); i != m_parseTree.subNodes.end();
i != m_parseTree.subNodes.end(); ++i) ++i) {
{
res = recursiveParentSearch(parent, *i); res = recursiveParentSearch(parent, *i);
if (res != nullptr) { if (res != nullptr) {
break; break;
@@ -362,14 +383,15 @@ CommandLineParser::Node* CommandLineParser::findParent(
return res; return res;
} }
CommandLineParser::Node* CommandLineParser::recursiveParentSearch( CommandLineParser::Node*
const CommandArgument &parent, Node &node) const CommandLineParser::recursiveParentSearch(const CommandArgument& parent,
Node& node) const
{ {
Node * res = nullptr; Node* res = nullptr;
if (node.argument == parent) { if (node.argument == parent) {
res = &node; res = &node;
} else { } else {
for (auto i = node.subNodes.begin(); i != node.subNodes.end(); ++i){ for (auto i = node.subNodes.begin(); i != node.subNodes.end(); ++i) {
res = recursiveParentSearch(parent, *i); res = recursiveParentSearch(parent, *i);
if (res != nullptr) { if (res != nullptr) {
break; break;
@@ -379,17 +401,16 @@ CommandLineParser::Node* CommandLineParser::recursiveParentSearch(
return res; return res;
} }
bool CommandLineParser::processIfOptionIsHelp( bool
const QStringList &args, CommandLineParser::processIfOptionIsHelp(const QStringList& args,
QStringList::const_iterator &actualIt, QStringList::const_iterator& actualIt,
Node * &actualNode) Node*& actualNode)
{ {
bool ok = true; bool ok = true;
auto dashedHelpNames = helpOption.dashedNames(); auto dashedHelpNames = helpOption.dashedNames();
if (m_withHelp && actualIt != args.cend() && if (m_withHelp && actualIt != args.cend() &&
dashedHelpNames.contains(*actualIt)) dashedHelpNames.contains(*actualIt)) {
{ if (actualIt + 1 == args.cend()) {
if (actualIt+1 == args.cend()) {
m_foundOptions << helpOption; m_foundOptions << helpOption;
printHelp(args, actualNode); printHelp(args, actualNode);
actualIt++; actualIt++;

View File

@@ -21,32 +21,33 @@
#include "src/cli/commandoption.h" #include "src/cli/commandoption.h"
#include <QMap> #include <QMap>
class CommandLineParser { class CommandLineParser
{
public: public:
CommandLineParser(); CommandLineParser();
bool parse(const QStringList &args); bool parse(const QStringList& args);
CommandArgument rootArgument() const { return CommandArgument(); } CommandArgument rootArgument() const { return CommandArgument(); }
CommandOption addVersionOption(); CommandOption addVersionOption();
CommandOption addHelpOption(); CommandOption addHelpOption();
bool AddArgument(const CommandArgument &arg, bool AddArgument(const CommandArgument& arg,
const CommandArgument &parent = CommandArgument()); const CommandArgument& parent = CommandArgument());
bool AddOption(const CommandOption &option, bool AddOption(const CommandOption& option,
const CommandArgument &parent = CommandArgument()); const CommandArgument& parent = CommandArgument());
bool AddOptions(const QList<CommandOption> &options, bool AddOptions(const QList<CommandOption>& options,
const CommandArgument &parent = CommandArgument()); const CommandArgument& parent = CommandArgument());
void setGeneralErrorMessage(const QString &msg); void setGeneralErrorMessage(const QString& msg);
void setDescription(const QString &description); void setDescription(const QString& description);
bool isSet(const CommandArgument &arg) const; bool isSet(const CommandArgument& arg) const;
bool isSet(const CommandOption &option) const; bool isSet(const CommandOption& option) const;
QString value(const CommandOption &option) const; QString value(const CommandOption& option) const;
private: private:
bool m_withHelp = false; bool m_withHelp = false;
@@ -54,12 +55,15 @@ private:
QString m_description; QString m_description;
QString m_generalErrorMessage; QString m_generalErrorMessage;
struct Node { struct Node
explicit Node(const CommandArgument &arg) : argument(arg) {} {
explicit Node(const CommandArgument& arg)
: argument(arg)
{}
Node() {} Node() {}
bool operator==(const Node &n) const { bool operator==(const Node& n) const
return argument == n.argument && {
options == n.options && return argument == n.argument && options == n.options &&
subNodes == n.subNodes; subNodes == n.subNodes;
} }
CommandArgument argument; CommandArgument argument;
@@ -73,17 +77,16 @@ private:
// helper functions // helper functions
void printVersion(); void printVersion();
void printHelp(QStringList args, const Node *node); void printHelp(QStringList args, const Node* node);
Node* findParent(const CommandArgument &parent); Node* findParent(const CommandArgument& parent);
Node* recursiveParentSearch(const CommandArgument &parent, Node* recursiveParentSearch(const CommandArgument& parent, Node& node) const;
Node &node) const; bool processIfOptionIsHelp(const QStringList& args,
bool processIfOptionIsHelp(const QStringList &args, QStringList::const_iterator& actualIt,
QStringList::const_iterator &actualIt, Node*& actualNode);
Node * &actualNode); bool processArgs(const QStringList& args,
bool processArgs(const QStringList &args, QStringList::const_iterator& actualIt,
QStringList::const_iterator &actualIt, Node*& actualNode);
Node * &actualNode); bool processOptions(const QStringList& args,
bool processOptions(const QStringList &args, QStringList::const_iterator& actualIt,
QStringList::const_iterator &actualIt, Node* const actualNode);
Node *const actualNode);
}; };

View File

@@ -17,96 +17,124 @@
#include "commandoption.h" #include "commandoption.h"
CommandOption::CommandOption(const QString &name, const QString &description, CommandOption::CommandOption(const QString& name,
const QString &valueName, const QString& description,
const QString &defaultValue) : const QString& valueName,
m_names(name), m_description(description), m_valueName(valueName), const QString& defaultValue)
m_value(defaultValue) : m_names(name)
, m_description(description)
, m_valueName(valueName)
, m_value(defaultValue)
{ {
m_checker = [](QString const&){ return true; }; m_checker = [](QString const&) { return true; };
} }
CommandOption::CommandOption(const QStringList &names, CommandOption::CommandOption(const QStringList& names,
const QString &description, const QString& description,
const QString &valueName, const QString& valueName,
const QString &defaultValue) : const QString& defaultValue)
m_names(names), m_description(description), m_valueName(valueName), : m_names(names)
m_value(defaultValue) , m_description(description)
, m_valueName(valueName)
, m_value(defaultValue)
{ {
m_checker = [](QString const&) -> bool { return true; }; m_checker = [](QString const&) -> bool { return true; };
} }
void CommandOption::setName(const QString &name) { void
CommandOption::setName(const QString& name)
{
m_names = QStringList() << name; m_names = QStringList() << name;
} }
void CommandOption::setNames(const QStringList &names) { void
CommandOption::setNames(const QStringList& names)
{
m_names = names; m_names = names;
} }
QStringList CommandOption::names() const { QStringList
CommandOption::names() const
{
return m_names; return m_names;
} }
QStringList CommandOption::dashedNames() const { QStringList
CommandOption::dashedNames() const
{
QStringList dashedNames; QStringList dashedNames;
for (const QString &name: m_names) { for (const QString& name : m_names) {
// prepend "-" to single character options, and "--" to the others // prepend "-" to single character options, and "--" to the others
QString dashedName = (name.length() == 1) ? QString dashedName = (name.length() == 1)
QStringLiteral("-%1").arg(name) : ? QStringLiteral("-%1").arg(name)
QStringLiteral("--%1").arg(name); : QStringLiteral("--%1").arg(name);
dashedNames << dashedName; dashedNames << dashedName;
} }
return dashedNames; return dashedNames;
} }
void CommandOption::setValueName(const QString &name) { void
CommandOption::setValueName(const QString& name)
{
m_valueName = name; m_valueName = name;
} }
QString CommandOption::valueName() const { QString
CommandOption::valueName() const
{
return m_valueName; return m_valueName;
} }
void CommandOption::setValue(const QString &value) { void
CommandOption::setValue(const QString& value)
{
if (m_valueName.isEmpty()) { if (m_valueName.isEmpty()) {
m_valueName = QLatin1String("value"); m_valueName = QLatin1String("value");
} }
m_value = value; m_value = value;
} }
QString CommandOption::value() const { QString
CommandOption::value() const
{
return m_value; return m_value;
} }
void CommandOption::addChecker(const function<bool (const QString &)> checker, void
const QString &errMsg) CommandOption::addChecker(const function<bool(const QString&)> checker,
const QString& errMsg)
{ {
m_checker = checker; m_checker = checker;
m_errorMsg = errMsg; m_errorMsg = errMsg;
} }
bool CommandOption::checkValue(const QString &value) const { bool
CommandOption::checkValue(const QString& value) const
{
return m_checker(value); return m_checker(value);
} }
QString CommandOption::description() const QString
CommandOption::description() const
{ {
return m_description; return m_description;
} }
void CommandOption::setDescription(const QString &description) void
CommandOption::setDescription(const QString& description)
{ {
m_description = description; m_description = description;
} }
QString CommandOption::errorMsg() const { QString
CommandOption::errorMsg() const
{
return m_errorMsg; return m_errorMsg;
} }
bool CommandOption::operator ==(const CommandOption &option) const bool
CommandOption::operator==(const CommandOption& option) const
{ {
return m_description == option.m_description return m_description == option.m_description && m_names == option.m_names &&
&& m_names == option.m_names m_valueName == option.m_valueName;
&& m_valueName == option.m_valueName;
} }

View File

@@ -22,36 +22,40 @@
using std::function; using std::function;
class CommandOption { class CommandOption
{
public: public:
CommandOption(const QString &name, const QString &description, CommandOption(const QString& name,
const QString &valueName = QString(), const QString& description,
const QString &defaultValue = QString()); const QString& valueName = QString(),
const QString& defaultValue = QString());
CommandOption(const QStringList &names, const QString &description, CommandOption(const QStringList& names,
const QString &valueName = QString(), const QString& description,
const QString &defaultValue = QString()); const QString& valueName = QString(),
const QString& defaultValue = QString());
void setName(const QString &name); void setName(const QString& name);
void setNames(const QStringList &names); void setNames(const QStringList& names);
QStringList names() const; QStringList names() const;
QStringList dashedNames() const; QStringList dashedNames() const;
void setValueName(const QString &name); void setValueName(const QString& name);
QString valueName() const; QString valueName() const;
void setValue(const QString &value); void setValue(const QString& value);
QString value() const; QString value() const;
void addChecker(const function<bool(QString const&)> checker, const QString &errMsg); void addChecker(const function<bool(QString const&)> checker,
bool checkValue(const QString &value) const; const QString& errMsg);
bool checkValue(const QString& value) const;
QString description() const; QString description() const;
void setDescription(const QString &description); void setDescription(const QString& description);
QString errorMsg() const; QString errorMsg() const;
bool operator==(const CommandOption &option) const; bool operator==(const CommandOption& option) const;
private: private:
QStringList m_names; QStringList m_names;

View File

@@ -21,27 +21,31 @@
#include <QListWidgetItem> #include <QListWidgetItem>
#include <algorithm> #include <algorithm>
ButtonListView::ButtonListView(QWidget *parent) : QListWidget(parent) { ButtonListView::ButtonListView(QWidget* parent)
: QListWidget(parent)
{
setMouseTracking(true); setMouseTracking(true);
setFlow(QListWidget::TopToBottom); setFlow(QListWidget::TopToBottom);
initButtonList(); initButtonList();
updateComponents(); updateComponents();
connect(this, &QListWidget::itemClicked, this, connect(
&ButtonListView::reverseItemCheck); this, &QListWidget::itemClicked, this, &ButtonListView::reverseItemCheck);
} }
void ButtonListView::initButtonList() { void
ButtonListView::initButtonList()
{
ToolFactory factory; ToolFactory factory;
auto listTypes = CaptureButton::getIterableButtonTypes(); auto listTypes = CaptureButton::getIterableButtonTypes();
for (const CaptureButton::ButtonType t: listTypes) { for (const CaptureButton::ButtonType t : listTypes) {
CaptureTool *tool = factory.CreateTool(t); CaptureTool* tool = factory.CreateTool(t);
// add element to the local map // add element to the local map
m_buttonTypeByName.insert(tool->name(), t); m_buttonTypeByName.insert(tool->name(), t);
// init the menu option // init the menu option
QListWidgetItem *m_buttonItem = new QListWidgetItem(this); QListWidgetItem* m_buttonItem = new QListWidgetItem(this);
// when the background is lighter than gray, it uses the white icons // when the background is lighter than gray, it uses the white icons
QColor bgColor = this->palette().color(QWidget::backgroundRole()); QColor bgColor = this->palette().color(QWidget::backgroundRole());
@@ -57,13 +61,15 @@ void ButtonListView::initButtonList() {
} }
} }
void ButtonListView::updateActiveButtons(QListWidgetItem *item) { void
ButtonListView::updateActiveButtons(QListWidgetItem* item)
{
CaptureButton::ButtonType bType = m_buttonTypeByName[item->text()]; CaptureButton::ButtonType bType = m_buttonTypeByName[item->text()];
if (item->checkState() == Qt::Checked) { if (item->checkState() == Qt::Checked) {
m_listButtons.append(bType); m_listButtons.append(bType);
// TODO refactor so we don't need external sorts // TODO refactor so we don't need external sorts
using bt = CaptureButton::ButtonType; using bt = CaptureButton::ButtonType;
std::sort(m_listButtons.begin(), m_listButtons.end(), [](bt a, bt b){ std::sort(m_listButtons.begin(), m_listButtons.end(), [](bt a, bt b) {
return CaptureButton::getPriorityByButton(a) < return CaptureButton::getPriorityByButton(a) <
CaptureButton::getPriorityByButton(b); CaptureButton::getPriorityByButton(b);
}); });
@@ -73,7 +79,9 @@ void ButtonListView::updateActiveButtons(QListWidgetItem *item) {
ConfigHandler().setButtons(m_listButtons); ConfigHandler().setButtons(m_listButtons);
} }
void ButtonListView::reverseItemCheck(QListWidgetItem *item){ void
ButtonListView::reverseItemCheck(QListWidgetItem* item)
{
if (item->checkState() == Qt::Checked) { if (item->checkState() == Qt::Checked) {
item->setCheckState(Qt::Unchecked); item->setCheckState(Qt::Unchecked);
} else { } else {
@@ -82,18 +90,22 @@ void ButtonListView::reverseItemCheck(QListWidgetItem *item){
updateActiveButtons(item); updateActiveButtons(item);
} }
void ButtonListView::selectAll() { void
ButtonListView::selectAll()
{
ConfigHandler().setAllTheButtons(); ConfigHandler().setAllTheButtons();
for(int i = 0; i < this->count(); ++i) { for (int i = 0; i < this->count(); ++i) {
QListWidgetItem* item = this->item(i); QListWidgetItem* item = this->item(i);
item->setCheckState(Qt::Checked); item->setCheckState(Qt::Checked);
} }
} }
void ButtonListView::updateComponents() { void
ButtonListView::updateComponents()
{
m_listButtons = ConfigHandler().getButtons(); m_listButtons = ConfigHandler().getButtons();
auto listTypes = CaptureButton::getIterableButtonTypes(); auto listTypes = CaptureButton::getIterableButtonTypes();
for(int i = 0; i < this->count(); ++i) { for (int i = 0; i < this->count(); ++i) {
QListWidgetItem* item = this->item(i); QListWidgetItem* item = this->item(i);
auto elem = static_cast<CaptureButton::ButtonType>(listTypes.at(i)); auto elem = static_cast<CaptureButton::ButtonType>(listTypes.at(i));
if (m_listButtons.contains(elem)) { if (m_listButtons.contains(elem)) {

View File

@@ -20,16 +20,17 @@
#include "src/widgets/capture/capturebutton.h" #include "src/widgets/capture/capturebutton.h"
#include <QListWidget> #include <QListWidget>
class ButtonListView : public QListWidget { class ButtonListView : public QListWidget
{
public: public:
explicit ButtonListView(QWidget *parent= nullptr); explicit ButtonListView(QWidget* parent = nullptr);
public slots: public slots:
void selectAll(); void selectAll();
void updateComponents(); void updateComponents();
private slots: private slots:
void reverseItemCheck(QListWidgetItem *); void reverseItemCheck(QListWidgetItem*);
protected: protected:
void initButtonList(); void initButtonList();
@@ -38,5 +39,5 @@ private:
QVector<CaptureButton::ButtonType> m_listButtons; QVector<CaptureButton::ButtonType> m_listButtons;
QMap<QString, CaptureButton::ButtonType> m_buttonTypeByName; QMap<QString, CaptureButton::ButtonType> m_buttonTypeByName;
void updateActiveButtons(QListWidgetItem *); void updateActiveButtons(QListWidgetItem*);
}; };

View File

@@ -17,14 +17,18 @@
#include "clickablelabel.h" #include "clickablelabel.h"
ClickableLabel::ClickableLabel(QWidget *parent) : QLabel(parent) { ClickableLabel::ClickableLabel(QWidget* parent)
: QLabel(parent)
{}
} ClickableLabel::ClickableLabel(QString s, QWidget* parent)
: QLabel(parent)
ClickableLabel::ClickableLabel(QString s, QWidget *parent) : QLabel(parent) { {
setText(s); setText(s);
} }
void ClickableLabel::mousePressEvent(QMouseEvent *) { void
ClickableLabel::mousePressEvent(QMouseEvent*)
{
emit clicked(); emit clicked();
} }

View File

@@ -19,15 +19,16 @@
#include <QLabel> #include <QLabel>
class ClickableLabel : public QLabel { class ClickableLabel : public QLabel
{
Q_OBJECT Q_OBJECT
public: public:
explicit ClickableLabel(QWidget *parent = nullptr); explicit ClickableLabel(QWidget* parent = nullptr);
ClickableLabel(QString s, QWidget *parent = nullptr); ClickableLabel(QString s, QWidget* parent = nullptr);
signals: signals:
void clicked(); void clicked();
private: private:
void mousePressEvent (QMouseEvent *); void mousePressEvent(QMouseEvent*);
}; };

View File

@@ -16,31 +16,33 @@
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "configwindow.h" #include "configwindow.h"
#include "src/utils/colorutils.h"
#include "src/utils/confighandler.h"
#include "src/utils/pathinfo.h"
#include "src/widgets/capture/capturebutton.h"
#include "src/config/geneneralconf.h"
#include "src/config/filenameeditor.h" #include "src/config/filenameeditor.h"
#include "src/config/geneneralconf.h"
#include "src/config/strftimechooserwidget.h" #include "src/config/strftimechooserwidget.h"
#include "src/config/visualseditor.h" #include "src/config/visualseditor.h"
#include "src/utils/colorutils.h"
#include "src/utils/confighandler.h"
#include "src/utils/globalvalues.h" #include "src/utils/globalvalues.h"
#include <QIcon> #include "src/utils/pathinfo.h"
#include <QVBoxLayout> #include "src/widgets/capture/capturebutton.h"
#include <QLabel>
#include <QKeyEvent>
#include <QFileSystemWatcher> #include <QFileSystemWatcher>
#include <QIcon>
#include <QKeyEvent>
#include <QLabel>
#include <QVBoxLayout>
// ConfigWindow contains the menus where you can configure the application // ConfigWindow contains the menus where you can configure the application
ConfigWindow::ConfigWindow(QWidget *parent) : QTabWidget(parent) { ConfigWindow::ConfigWindow(QWidget* parent)
: QTabWidget(parent)
{
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
const int size = GlobalValues::buttonBaseSize() * 12; const int size = GlobalValues::buttonBaseSize() * 12;
setMinimumSize(size, size); setMinimumSize(size, size);
setWindowIcon(QIcon(":img/app/flameshot.svg")); setWindowIcon(QIcon(":img/app/flameshot.svg"));
setWindowTitle(tr("Configuration")); setWindowTitle(tr("Configuration"));
auto changedSlot = [this](QString s){ auto changedSlot = [this](QString s) {
QStringList files = m_configWatcher->files(); QStringList files = m_configWatcher->files();
if (!files.contains(s)) { if (!files.contains(s)) {
this->m_configWatcher->addPath(s); this->m_configWatcher->addPath(s);
@@ -49,39 +51,45 @@ ConfigWindow::ConfigWindow(QWidget *parent) : QTabWidget(parent) {
}; };
m_configWatcher = new QFileSystemWatcher(this); m_configWatcher = new QFileSystemWatcher(this);
m_configWatcher->addPath(ConfigHandler().configFilePath()); m_configWatcher->addPath(ConfigHandler().configFilePath());
connect(m_configWatcher, &QFileSystemWatcher::fileChanged, connect(m_configWatcher, &QFileSystemWatcher::fileChanged, this, changedSlot);
this, changedSlot);
QColor background = this->palette().window().color(); QColor background = this->palette().window().color();
bool isDark = ColorUtils::colorIsDark(background); bool isDark = ColorUtils::colorIsDark(background);
QString modifier = isDark ? PathInfo::whiteIconPath() : QString modifier =
PathInfo::blackIconPath(); isDark ? PathInfo::whiteIconPath() : PathInfo::blackIconPath();
// visuals // visuals
m_visuals = new VisualsEditor(); m_visuals = new VisualsEditor();
addTab(m_visuals, QIcon(modifier + "graphics.svg"), addTab(m_visuals, QIcon(modifier + "graphics.svg"), tr("Interface"));
tr("Interface"));
// filename // filename
m_filenameEditor = new FileNameEditor(); m_filenameEditor = new FileNameEditor();
addTab(m_filenameEditor, QIcon(modifier + "name_edition.svg"), addTab(m_filenameEditor,
QIcon(modifier + "name_edition.svg"),
tr("Filename Editor")); tr("Filename Editor"));
// general // general
m_generalConfig = new GeneneralConf(); m_generalConfig = new GeneneralConf();
addTab(m_generalConfig, QIcon(modifier + "config.svg"), addTab(m_generalConfig, QIcon(modifier + "config.svg"), tr("General"));
tr("General"));
// connect update sigslots // connect update sigslots
connect(this, &ConfigWindow::updateChildren, connect(this,
m_filenameEditor, &FileNameEditor::updateComponents); &ConfigWindow::updateChildren,
connect(this, &ConfigWindow::updateChildren, m_filenameEditor,
m_visuals, &VisualsEditor::updateComponents); &FileNameEditor::updateComponents);
connect(this, &ConfigWindow::updateChildren, connect(this,
m_generalConfig, &GeneneralConf::updateComponents); &ConfigWindow::updateChildren,
m_visuals,
&VisualsEditor::updateComponents);
connect(this,
&ConfigWindow::updateChildren,
m_generalConfig,
&GeneneralConf::updateComponents);
} }
void ConfigWindow::keyPressEvent(QKeyEvent *e) { void
ConfigWindow::keyPressEvent(QKeyEvent* e)
{
if (e->key() == Qt::Key_Escape) { if (e->key() == Qt::Key_Escape) {
close(); close();
} }

View File

@@ -24,20 +24,21 @@ class GeneneralConf;
class QFileSystemWatcher; class QFileSystemWatcher;
class VisualsEditor; class VisualsEditor;
class ConfigWindow : public QTabWidget { class ConfigWindow : public QTabWidget
{
Q_OBJECT Q_OBJECT
public: public:
explicit ConfigWindow(QWidget *parent = nullptr); explicit ConfigWindow(QWidget* parent = nullptr);
signals: signals:
void updateChildren(); void updateChildren();
protected: protected:
void keyPressEvent(QKeyEvent *); void keyPressEvent(QKeyEvent*);
private: private:
FileNameEditor *m_filenameEditor; FileNameEditor* m_filenameEditor;
GeneneralConf *m_generalConfig; GeneneralConf* m_generalConfig;
VisualsEditor *m_visuals; VisualsEditor* m_visuals;
QFileSystemWatcher *m_configWatcher; QFileSystemWatcher* m_configWatcher;
}; };

View File

@@ -17,34 +17,41 @@
#include "extendedslider.h" #include "extendedslider.h"
ExtendedSlider::ExtendedSlider(QWidget *parent) ExtendedSlider::ExtendedSlider(QWidget* parent)
: QSlider(parent) : QSlider(parent)
{ {
connect(this, &ExtendedSlider::valueChanged, connect(
this, &ExtendedSlider::updateTooltip); this, &ExtendedSlider::valueChanged, this, &ExtendedSlider::updateTooltip);
connect(this, &ExtendedSlider::sliderMoved, connect(this, &ExtendedSlider::sliderMoved, this, &ExtendedSlider::fireTimer);
this, &ExtendedSlider::fireTimer);
m_timer.setSingleShot(true); m_timer.setSingleShot(true);
connect(&m_timer, &QTimer::timeout, connect(
this, &ExtendedSlider::modificationsEnded); &m_timer, &QTimer::timeout, this, &ExtendedSlider::modificationsEnded);
} }
int ExtendedSlider::mappedValue(int min, int max) { int
ExtendedSlider::mappedValue(int min, int max)
{
qreal progress = qreal progress =
((value() - minimum())) / static_cast<qreal>(maximum() - minimum()); ((value() - minimum())) / static_cast<qreal>(maximum() - minimum());
return min + (max - min) * progress; return min + (max - min) * progress;
} }
void ExtendedSlider::setMapedValue(int min, int val, int max) { void
ExtendedSlider::setMapedValue(int min, int val, int max)
{
qreal progress = ((val - min) + 1) / static_cast<qreal>(max - min); qreal progress = ((val - min) + 1) / static_cast<qreal>(max - min);
int value = minimum() + (maximum() - minimum()) * progress; int value = minimum() + (maximum() - minimum()) * progress;
setValue(value); setValue(value);
} }
void ExtendedSlider::updateTooltip() { void
setToolTip(QString::number(value())+"%"); ExtendedSlider::updateTooltip()
{
setToolTip(QString::number(value()) + "%");
} }
void ExtendedSlider::fireTimer() { void
ExtendedSlider::fireTimer()
{
m_timer.start(500); m_timer.start(500);
} }

View File

@@ -20,10 +20,11 @@
#include <QSlider> #include <QSlider>
#include <QTimer> #include <QTimer>
class ExtendedSlider : public QSlider { class ExtendedSlider : public QSlider
{
Q_OBJECT Q_OBJECT
public: public:
explicit ExtendedSlider(QWidget *parent = nullptr); explicit ExtendedSlider(QWidget* parent = nullptr);
int mappedValue(int min, int max); int mappedValue(int min, int max);
void setMapedValue(int min, int val, int max); void setMapedValue(int min, int val, int max);

View File

@@ -16,21 +16,25 @@
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "filenameeditor.h" #include "filenameeditor.h"
#include "src/utils/filenamehandler.h"
#include "src/utils/confighandler.h"
#include "src/config/strftimechooserwidget.h" #include "src/config/strftimechooserwidget.h"
#include <QVBoxLayout> #include "src/utils/confighandler.h"
#include "src/utils/filenamehandler.h"
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QLineEdit>
#include <QLabel> #include <QLabel>
#include <QLineEdit>
#include <QPushButton> #include <QPushButton>
#include <QVBoxLayout>
FileNameEditor::FileNameEditor(QWidget *parent) : QWidget(parent) { FileNameEditor::FileNameEditor(QWidget* parent)
: QWidget(parent)
{
initWidgets(); initWidgets();
initLayout(); initLayout();
} }
void FileNameEditor::initLayout() { void
FileNameEditor::initLayout()
{
m_layout = new QVBoxLayout(this); m_layout = new QVBoxLayout(this);
auto infoLabel = new QLabel(tr("Edit the name of your captures:"), this); auto infoLabel = new QLabel(tr("Edit the name of your captures:"), this);
infoLabel->setFixedHeight(20); infoLabel->setFixedHeight(20);
@@ -41,14 +45,16 @@ void FileNameEditor::initLayout() {
m_layout->addWidget(new QLabel(tr("Preview:"))); m_layout->addWidget(new QLabel(tr("Preview:")));
m_layout->addWidget(m_outputLabel); m_layout->addWidget(m_outputLabel);
QHBoxLayout *horizLayout = new QHBoxLayout(); QHBoxLayout* horizLayout = new QHBoxLayout();
horizLayout->addWidget(m_saveButton); horizLayout->addWidget(m_saveButton);
horizLayout->addWidget(m_resetButton); horizLayout->addWidget(m_resetButton);
horizLayout->addWidget(m_clearButton); horizLayout->addWidget(m_clearButton);
m_layout->addLayout(horizLayout); m_layout->addLayout(horizLayout);
} }
void FileNameEditor::initWidgets() { void
FileNameEditor::initWidgets()
{
m_nameHandler = new FileNameHandler(this); m_nameHandler = new FileNameHandler(this);
// editor // editor
@@ -65,51 +71,67 @@ void FileNameEditor::initWidgets() {
pal.setColor(QPalette::Active, m_outputLabel->backgroundRole(), color); pal.setColor(QPalette::Active, m_outputLabel->backgroundRole(), color);
m_outputLabel->setPalette(pal); m_outputLabel->setPalette(pal);
connect(m_nameEditor, &QLineEdit::textChanged, this, connect(m_nameEditor,
&QLineEdit::textChanged,
this,
&FileNameEditor::showParsedPattern); &FileNameEditor::showParsedPattern);
updateComponents(); updateComponents();
// helper buttons // helper buttons
m_helperButtons = new StrftimeChooserWidget(this); m_helperButtons = new StrftimeChooserWidget(this);
connect(m_helperButtons, &StrftimeChooserWidget::variableEmitted, connect(m_helperButtons,
this, &FileNameEditor::addToNameEditor); &StrftimeChooserWidget::variableEmitted,
this,
&FileNameEditor::addToNameEditor);
// save // save
m_saveButton = new QPushButton(tr("Save"), this); m_saveButton = new QPushButton(tr("Save"), this);
connect(m_saveButton, &QPushButton::clicked, this, &FileNameEditor::savePattern); connect(
m_saveButton, &QPushButton::clicked, this, &FileNameEditor::savePattern);
m_saveButton->setToolTip(tr("Saves the pattern")); m_saveButton->setToolTip(tr("Saves the pattern"));
// reset // reset
m_resetButton = new QPushButton(tr("Reset"), this); m_resetButton = new QPushButton(tr("Reset"), this);
connect(m_resetButton, &QPushButton::clicked, connect(
this, &FileNameEditor::resetName); m_resetButton, &QPushButton::clicked, this, &FileNameEditor::resetName);
m_resetButton->setToolTip(tr("Restores the saved pattern")); m_resetButton->setToolTip(tr("Restores the saved pattern"));
// clear // clear
m_clearButton = new QPushButton(tr("Clear"), this); m_clearButton = new QPushButton(tr("Clear"), this);
connect(m_clearButton, &QPushButton::clicked, this, connect(m_clearButton, &QPushButton::clicked, this, [this]() {
[this](){ m_nameEditor->setText(QString()); m_nameEditor->setText(QString());
}); });
m_clearButton->setToolTip(tr("Deletes the name"));} m_clearButton->setToolTip(tr("Deletes the name"));
}
void FileNameEditor::savePattern() { void
FileNameEditor::savePattern()
{
QString pattern = m_nameEditor->text(); QString pattern = m_nameEditor->text();
m_nameHandler->setPattern(pattern); m_nameHandler->setPattern(pattern);
} }
void FileNameEditor::showParsedPattern(const QString &p) { void
FileNameEditor::showParsedPattern(const QString& p)
{
QString output = m_nameHandler->parseFilename(p); QString output = m_nameHandler->parseFilename(p);
m_outputLabel->setText(output); m_outputLabel->setText(output);
} }
void FileNameEditor::resetName() { void
FileNameEditor::resetName()
{
m_nameEditor->setText(ConfigHandler().filenamePatternValue()); m_nameEditor->setText(ConfigHandler().filenamePatternValue());
} }
void FileNameEditor::addToNameEditor(QString s) { void
FileNameEditor::addToNameEditor(QString s)
{
m_nameEditor->setText(m_nameEditor->text() + s); m_nameEditor->setText(m_nameEditor->text() + s);
m_nameEditor->setFocus(); m_nameEditor->setFocus();
} }
void FileNameEditor::updateComponents() { void
FileNameEditor::updateComponents()
{
m_nameEditor->setText(ConfigHandler().filenamePatternValue()); m_nameEditor->setText(ConfigHandler().filenamePatternValue());
m_outputLabel->setText(m_nameHandler->parsedPattern()); m_outputLabel->setText(m_nameHandler->parsedPattern());
} }

View File

@@ -17,8 +17,8 @@
#pragma once #pragma once
#include <QWidget>
#include <QPointer> #include <QPointer>
#include <QWidget>
class QVBoxLayout; class QVBoxLayout;
class QLineEdit; class QLineEdit;
@@ -26,20 +26,21 @@ class FileNameHandler;
class QPushButton; class QPushButton;
class StrftimeChooserWidget; class StrftimeChooserWidget;
class FileNameEditor : public QWidget { class FileNameEditor : public QWidget
{
Q_OBJECT Q_OBJECT
public: public:
explicit FileNameEditor(QWidget *parent = nullptr); explicit FileNameEditor(QWidget* parent = nullptr);
private: private:
QVBoxLayout *m_layout; QVBoxLayout* m_layout;
QLineEdit *m_outputLabel; QLineEdit* m_outputLabel;
QLineEdit *m_nameEditor; QLineEdit* m_nameEditor;
FileNameHandler *m_nameHandler; FileNameHandler* m_nameHandler;
StrftimeChooserWidget *m_helperButtons; StrftimeChooserWidget* m_helperButtons;
QPushButton *m_saveButton; QPushButton* m_saveButton;
QPushButton *m_resetButton; QPushButton* m_resetButton;
QPushButton *m_clearButton; QPushButton* m_clearButton;
void initLayout(); void initLayout();
void initWidgets(); void initWidgets();
@@ -50,6 +51,6 @@ public slots:
private slots: private slots:
void savePattern(); void savePattern();
void showParsedPattern(const QString &); void showParsedPattern(const QString&);
void resetName(); void resetName();
}; };

View File

@@ -16,20 +16,21 @@
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "geneneralconf.h" #include "geneneralconf.h"
#include "src/utils/confighandler.h"
#include "src/utils/confighandler.h"
#include "src/core/controller.h" #include "src/core/controller.h"
#include <QVBoxLayout> #include "src/utils/confighandler.h"
#include <QHBoxLayout>
#include <QCheckBox> #include <QCheckBox>
#include <QPushButton>
#include <QMessageBox>
#include <QFileDialog>
#include <QFile> #include <QFile>
#include <QTextCodec> #include <QFileDialog>
#include <QGroupBox> #include <QGroupBox>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QPushButton>
#include <QTextCodec>
#include <QVBoxLayout>
GeneneralConf::GeneneralConf(QWidget *parent) : QWidget(parent) { GeneneralConf::GeneneralConf(QWidget* parent)
: QWidget(parent)
{
m_layout = new QVBoxLayout(this); m_layout = new QVBoxLayout(this);
m_layout->setAlignment(Qt::AlignTop); m_layout->setAlignment(Qt::AlignTop);
initShowHelp(); initShowHelp();
@@ -44,28 +45,37 @@ GeneneralConf::GeneneralConf(QWidget *parent) : QWidget(parent) {
updateComponents(); updateComponents();
} }
void GeneneralConf::updateComponents() { void
GeneneralConf::updateComponents()
{
ConfigHandler config; ConfigHandler config;
m_helpMessage->setChecked(config.showHelpValue()); m_helpMessage->setChecked(config.showHelpValue());
m_sysNotifications->setChecked(config.desktopNotificationValue()); m_sysNotifications->setChecked(config.desktopNotificationValue());
m_autostart->setChecked(config.startupLaunchValue()); m_autostart->setChecked(config.startupLaunchValue());
m_closeAfterCapture->setChecked(config.closeAfterScreenshotValue()); m_closeAfterCapture->setChecked(config.closeAfterScreenshotValue());
m_copyAndCloseAfterUpload->setChecked(config.copyAndCloseAfterUploadEnabled()); m_copyAndCloseAfterUpload->setChecked(
config.copyAndCloseAfterUploadEnabled());
#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX)
m_showTray->setChecked(!config.disabledTrayIconValue()); m_showTray->setChecked(!config.disabledTrayIconValue());
#endif #endif
} }
void GeneneralConf::showHelpChanged(bool checked) { void
GeneneralConf::showHelpChanged(bool checked)
{
ConfigHandler().setShowHelp(checked); ConfigHandler().setShowHelp(checked);
} }
void GeneneralConf::showDesktopNotificationChanged(bool checked) { void
GeneneralConf::showDesktopNotificationChanged(bool checked)
{
ConfigHandler().setDesktopNotification(checked); ConfigHandler().setDesktopNotification(checked);
} }
void GeneneralConf::showTrayIconChanged(bool checked) { void
GeneneralConf::showTrayIconChanged(bool checked)
{
auto controller = Controller::getInstance(); auto controller = Controller::getInstance();
if (checked) { if (checked) {
controller->enableTrayIcon(); controller->enableTrayIcon();
@@ -74,21 +84,27 @@ void GeneneralConf::showTrayIconChanged(bool checked) {
} }
} }
void GeneneralConf::autostartChanged(bool checked) { void
GeneneralConf::autostartChanged(bool checked)
{
ConfigHandler().setStartupLaunch(checked); ConfigHandler().setStartupLaunch(checked);
} }
void GeneneralConf::closeAfterCaptureChanged(bool checked) { void
GeneneralConf::closeAfterCaptureChanged(bool checked)
{
ConfigHandler().setCloseAfterScreenshot(checked); ConfigHandler().setCloseAfterScreenshot(checked);
} }
void GeneneralConf::importConfiguration() { void
GeneneralConf::importConfiguration()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Import")); QString fileName = QFileDialog::getOpenFileName(this, tr("Import"));
if (fileName.isEmpty()) { if (fileName.isEmpty()) {
return; return;
} }
QFile file(fileName); QFile file(fileName);
QTextCodec *codec = QTextCodec::codecForLocale(); QTextCodec* codec = QTextCodec::codecForLocale();
if (!file.open(QFile::ReadOnly)) { if (!file.open(QFile::ReadOnly)) {
QMessageBox::about(this, tr("Error"), tr("Unable to read file.")); QMessageBox::about(this, tr("Error"), tr("Unable to read file."));
return; return;
@@ -105,9 +121,11 @@ void GeneneralConf::importConfiguration() {
config.close(); config.close();
} }
void GeneneralConf::exportFileConfiguration() { void
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), GeneneralConf::exportFileConfiguration()
QStringLiteral("flameshot.conf")); {
QString fileName = QFileDialog::getSaveFileName(
this, tr("Save File"), QStringLiteral("flameshot.conf"));
// Cancel button // Cancel button
if (fileName.isNull()) { if (fileName.isNull()) {
@@ -124,10 +142,13 @@ void GeneneralConf::exportFileConfiguration() {
} }
} }
void GeneneralConf::resetConfiguration() { void
GeneneralConf::resetConfiguration()
{
QMessageBox::StandardButton reply; QMessageBox::StandardButton reply;
reply = QMessageBox::question( reply = QMessageBox::question(
this, tr("Confirm Reset"), this,
tr("Confirm Reset"),
tr("Are you sure you want to reset the configuration?"), tr("Are you sure you want to reset the configuration?"),
QMessageBox::Yes | QMessageBox::No); QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) { if (reply == QMessageBox::Yes) {
@@ -135,8 +156,9 @@ void GeneneralConf::resetConfiguration() {
} }
} }
void
void GeneneralConf::initShowHelp() { GeneneralConf::initShowHelp()
{
m_helpMessage = new QCheckBox(tr("Show help message"), this); m_helpMessage = new QCheckBox(tr("Show help message"), this);
ConfigHandler config; ConfigHandler config;
bool checked = config.showHelpValue(); bool checked = config.showHelpValue();
@@ -145,24 +167,29 @@ void GeneneralConf::initShowHelp() {
"in the capture mode.")); "in the capture mode."));
m_layout->addWidget(m_helpMessage); m_layout->addWidget(m_helpMessage);
connect(m_helpMessage, &QCheckBox::clicked, this, connect(
&GeneneralConf::showHelpChanged); m_helpMessage, &QCheckBox::clicked, this, &GeneneralConf::showHelpChanged);
} }
void GeneneralConf::initShowDesktopNotification() { void
m_sysNotifications = GeneneralConf::initShowDesktopNotification()
new QCheckBox(tr("Show desktop notifications"), this); {
m_sysNotifications = new QCheckBox(tr("Show desktop notifications"), this);
ConfigHandler config; ConfigHandler config;
bool checked = config.desktopNotificationValue(); bool checked = config.desktopNotificationValue();
m_sysNotifications->setChecked(checked); m_sysNotifications->setChecked(checked);
m_sysNotifications->setToolTip(tr("Show desktop notifications")); m_sysNotifications->setToolTip(tr("Show desktop notifications"));
m_layout->addWidget(m_sysNotifications); m_layout->addWidget(m_sysNotifications);
connect(m_sysNotifications, &QCheckBox::clicked, this, connect(m_sysNotifications,
&QCheckBox::clicked,
this,
&GeneneralConf::showDesktopNotificationChanged); &GeneneralConf::showDesktopNotificationChanged);
} }
void GeneneralConf::initShowTrayIcon() { void
GeneneralConf::initShowTrayIcon()
{
#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX)
m_showTray = new QCheckBox(tr("Show tray icon"), this); m_showTray = new QCheckBox(tr("Show tray icon"), this);
ConfigHandler config; ConfigHandler config;
@@ -171,49 +198,62 @@ void GeneneralConf::initShowTrayIcon() {
m_showTray->setToolTip(tr("Show the systemtray icon")); m_showTray->setToolTip(tr("Show the systemtray icon"));
m_layout->addWidget(m_showTray); m_layout->addWidget(m_showTray);
connect(m_showTray, &QCheckBox::stateChanged, this, connect(m_showTray,
&QCheckBox::stateChanged,
this,
&GeneneralConf::showTrayIconChanged); &GeneneralConf::showTrayIconChanged);
#endif #endif
} }
void GeneneralConf::initConfingButtons() { void
QHBoxLayout *buttonLayout = new QHBoxLayout(); GeneneralConf::initConfingButtons()
{
QHBoxLayout* buttonLayout = new QHBoxLayout();
m_layout->addStretch(); m_layout->addStretch();
QGroupBox *box = new QGroupBox(tr("Configuration File")); QGroupBox* box = new QGroupBox(tr("Configuration File"));
box->setFlat(true); box->setFlat(true);
box->setLayout(buttonLayout); box->setLayout(buttonLayout);
m_layout->addWidget(box); m_layout->addWidget(box);
m_exportButton = new QPushButton(tr("Export")); m_exportButton = new QPushButton(tr("Export"));
buttonLayout->addWidget(m_exportButton); buttonLayout->addWidget(m_exportButton);
connect(m_exportButton, &QPushButton::clicked, this, connect(m_exportButton,
&QPushButton::clicked,
this,
&GeneneralConf::exportFileConfiguration); &GeneneralConf::exportFileConfiguration);
m_importButton = new QPushButton(tr("Import")); m_importButton = new QPushButton(tr("Import"));
buttonLayout->addWidget(m_importButton); buttonLayout->addWidget(m_importButton);
connect(m_importButton, &QPushButton::clicked, this, connect(m_importButton,
&QPushButton::clicked,
this,
&GeneneralConf::importConfiguration); &GeneneralConf::importConfiguration);
m_resetButton = new QPushButton(tr("Reset")); m_resetButton = new QPushButton(tr("Reset"));
buttonLayout->addWidget(m_resetButton); buttonLayout->addWidget(m_resetButton);
connect(m_resetButton, &QPushButton::clicked, this, connect(m_resetButton,
&QPushButton::clicked,
this,
&GeneneralConf::resetConfiguration); &GeneneralConf::resetConfiguration);
} }
void GeneneralConf::initAutostart() { void
m_autostart = GeneneralConf::initAutostart()
new QCheckBox(tr("Launch at startup"), this); {
m_autostart = new QCheckBox(tr("Launch at startup"), this);
ConfigHandler config; ConfigHandler config;
bool checked = config.startupLaunchValue(); bool checked = config.startupLaunchValue();
m_autostart->setChecked(checked); m_autostart->setChecked(checked);
m_autostart->setToolTip(tr("Launch Flameshot")); m_autostart->setToolTip(tr("Launch Flameshot"));
m_layout->addWidget(m_autostart); m_layout->addWidget(m_autostart);
connect(m_autostart, &QCheckBox::clicked, this, connect(
&GeneneralConf::autostartChanged); m_autostart, &QCheckBox::clicked, this, &GeneneralConf::autostartChanged);
} }
void GeneneralConf::initCloseAfterCapture() { void
GeneneralConf::initCloseAfterCapture()
{
m_closeAfterCapture = new QCheckBox(tr("Close after capture"), this); m_closeAfterCapture = new QCheckBox(tr("Close after capture"), this);
ConfigHandler config; ConfigHandler config;
bool checked = config.closeAfterScreenshotValue(); bool checked = config.closeAfterScreenshotValue();
@@ -221,16 +261,21 @@ void GeneneralConf::initCloseAfterCapture() {
m_closeAfterCapture->setToolTip(tr("Close after taking a screenshot")); m_closeAfterCapture->setToolTip(tr("Close after taking a screenshot"));
m_layout->addWidget(m_closeAfterCapture); m_layout->addWidget(m_closeAfterCapture);
connect(m_closeAfterCapture, &QCheckBox::clicked, this, connect(m_closeAfterCapture,
&QCheckBox::clicked,
this,
&GeneneralConf::closeAfterCaptureChanged); &GeneneralConf::closeAfterCaptureChanged);
} }
void GeneneralConf::initCopyAndCloseAfterUpload() void
GeneneralConf::initCopyAndCloseAfterUpload()
{ {
m_copyAndCloseAfterUpload = new QCheckBox(tr("Copy URL after upload"), this); m_copyAndCloseAfterUpload = new QCheckBox(tr("Copy URL after upload"), this);
ConfigHandler config; ConfigHandler config;
m_copyAndCloseAfterUpload->setChecked(config.copyAndCloseAfterUploadEnabled()); m_copyAndCloseAfterUpload->setChecked(
m_copyAndCloseAfterUpload->setToolTip(tr("Copy URL and close window after upload")); config.copyAndCloseAfterUploadEnabled());
m_copyAndCloseAfterUpload->setToolTip(
tr("Copy URL and close window after upload"));
m_layout->addWidget(m_copyAndCloseAfterUpload); m_layout->addWidget(m_copyAndCloseAfterUpload);
connect(m_copyAndCloseAfterUpload, &QCheckBox::clicked, [](bool checked) { connect(m_copyAndCloseAfterUpload, &QCheckBox::clicked, [](bool checked) {

View File

@@ -23,10 +23,11 @@ class QVBoxLayout;
class QCheckBox; class QCheckBox;
class QPushButton; class QPushButton;
class GeneneralConf : public QWidget { class GeneneralConf : public QWidget
{
Q_OBJECT Q_OBJECT
public: public:
explicit GeneneralConf(QWidget *parent = nullptr); explicit GeneneralConf(QWidget* parent = nullptr);
public slots: public slots:
void updateComponents(); void updateComponents();
@@ -42,16 +43,16 @@ private slots:
void resetConfiguration(); void resetConfiguration();
private: private:
QVBoxLayout *m_layout; QVBoxLayout* m_layout;
QCheckBox *m_sysNotifications; QCheckBox* m_sysNotifications;
QCheckBox *m_showTray; QCheckBox* m_showTray;
QCheckBox *m_helpMessage; QCheckBox* m_helpMessage;
QCheckBox *m_autostart; QCheckBox* m_autostart;
QCheckBox *m_closeAfterCapture; QCheckBox* m_closeAfterCapture;
QCheckBox *m_copyAndCloseAfterUpload; QCheckBox* m_copyAndCloseAfterUpload;
QPushButton *m_importButton; QPushButton* m_importButton;
QPushButton *m_exportButton; QPushButton* m_exportButton;
QPushButton *m_resetButton; QPushButton* m_resetButton;
void initShowHelp(); void initShowHelp();
void initShowDesktopNotification(); void initShowDesktopNotification();

View File

@@ -16,53 +16,56 @@
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "strftimechooserwidget.h" #include "strftimechooserwidget.h"
#include <QMap>
#include <QGridLayout> #include <QGridLayout>
#include <QMap>
#include <QPushButton> #include <QPushButton>
StrftimeChooserWidget::StrftimeChooserWidget(QWidget *parent) : QWidget(parent) { StrftimeChooserWidget::StrftimeChooserWidget(QWidget* parent)
QGridLayout *layout = new QGridLayout(this); : QWidget(parent)
{
QGridLayout* layout = new QGridLayout(this);
auto k = m_buttonData.keys(); auto k = m_buttonData.keys();
int middle = k.length()/2; int middle = k.length() / 2;
// add the buttons in 2 columns (they need to be even) // add the buttons in 2 columns (they need to be even)
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
for (int j = 0; j < middle; j++) { for (int j = 0; j < middle; j++) {
QString key = k.last(); QString key = k.last();
k.pop_back(); k.pop_back();
QString variable = m_buttonData.value(key); QString variable = m_buttonData.value(key);
QPushButton *button = new QPushButton(this); QPushButton* button = new QPushButton(this);
button->setText(tr(key.toStdString().data())); button->setText(tr(key.toStdString().data()));
button->setToolTip(variable); button->setToolTip(variable);
button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
button->setMinimumHeight(25); button->setMinimumHeight(25);
layout->addWidget(button, j, i); layout->addWidget(button, j, i);
connect(button, &QPushButton::clicked, connect(button, &QPushButton::clicked, this, [variable, this]() {
this, [variable, this](){emit variableEmitted(variable);}); emit variableEmitted(variable);
});
} }
} }
setLayout(layout); setLayout(layout);
} }
QMap<QString, QString> StrftimeChooserWidget::m_buttonData { QMap<QString, QString> StrftimeChooserWidget::m_buttonData{
{ QT_TR_NOOP("Century (00-99)"), "%C"}, { QT_TR_NOOP("Century (00-99)"), "%C" },
{ QT_TR_NOOP("Year (00-99)"), "%y"}, { QT_TR_NOOP("Year (00-99)"), "%y" },
{ QT_TR_NOOP("Year (2000)"), "%Y"}, { QT_TR_NOOP("Year (2000)"), "%Y" },
{ QT_TR_NOOP("Month Name (jan)"), "%b"}, { QT_TR_NOOP("Month Name (jan)"), "%b" },
{ QT_TR_NOOP("Month Name (january)"), "%B"}, { QT_TR_NOOP("Month Name (january)"), "%B" },
{ QT_TR_NOOP("Month (01-12)"), "%m"}, { QT_TR_NOOP("Month (01-12)"), "%m" },
{ QT_TR_NOOP("Week Day (1-7)"), "%u"}, { QT_TR_NOOP("Week Day (1-7)"), "%u" },
{ QT_TR_NOOP("Week (01-53)"), "%V"}, { QT_TR_NOOP("Week (01-53)"), "%V" },
{ QT_TR_NOOP("Day Name (mon)"), "%a"}, { QT_TR_NOOP("Day Name (mon)"), "%a" },
{ QT_TR_NOOP("Day Name (monday)"), "%A"}, { QT_TR_NOOP("Day Name (monday)"), "%A" },
{ QT_TR_NOOP("Day (01-31)"), "%d"}, { QT_TR_NOOP("Day (01-31)"), "%d" },
{ QT_TR_NOOP("Day of Month (1-31)"), "%e"}, { QT_TR_NOOP("Day of Month (1-31)"), "%e" },
{ QT_TR_NOOP("Day (001-366)"), "%j"}, { QT_TR_NOOP("Day (001-366)"), "%j" },
{ QT_TR_NOOP("Time (%H-%M-%S)"), "%T"}, { QT_TR_NOOP("Time (%H-%M-%S)"), "%T" },
{ QT_TR_NOOP("Time (%H-%M)"), "%R"}, { QT_TR_NOOP("Time (%H-%M)"), "%R" },
{ QT_TR_NOOP("Hour (00-23)"), "%H"}, { QT_TR_NOOP("Hour (00-23)"), "%H" },
{ QT_TR_NOOP("Hour (01-12)"), "%I"}, { QT_TR_NOOP("Hour (01-12)"), "%I" },
{ QT_TR_NOOP("Minute (00-59)"), "%M"}, { QT_TR_NOOP("Minute (00-59)"), "%M" },
{ QT_TR_NOOP("Second (00-59)"), "%S"}, { QT_TR_NOOP("Second (00-59)"), "%S" },
{ QT_TR_NOOP("Full Date (%m/%d/%y)"), "%D"}, { QT_TR_NOOP("Full Date (%m/%d/%y)"), "%D" },
{ QT_TR_NOOP("Full Date (%Y-%m-%d)"), "%F"}, { QT_TR_NOOP("Full Date (%Y-%m-%d)"), "%F" },
}; };

View File

@@ -19,13 +19,14 @@
#include <QWidget> #include <QWidget>
class StrftimeChooserWidget : public QWidget { class StrftimeChooserWidget : public QWidget
{
Q_OBJECT Q_OBJECT
public: public:
explicit StrftimeChooserWidget(QWidget *parent = nullptr); explicit StrftimeChooserWidget(QWidget* parent = nullptr);
signals: signals:
void variableEmitted(const QString &); void variableEmitted(const QString&);
private: private:
static QMap<QString, QString> m_buttonData; static QMap<QString, QString> m_buttonData;

View File

@@ -15,18 +15,20 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "src/utils/confighandler.h"
#include "uicoloreditor.h" #include "uicoloreditor.h"
#include "clickablelabel.h" #include "clickablelabel.h"
#include "src/utils/confighandler.h"
#include "src/utils/globalvalues.h" #include "src/utils/globalvalues.h"
#include <QHBoxLayout>
#include <QApplication> #include <QApplication>
#include <QVBoxLayout>
#include <QComboBox> #include <QComboBox>
#include <QHBoxLayout>
#include <QMap> #include <QMap>
#include <QSpacerItem> #include <QSpacerItem>
#include <QVBoxLayout>
UIcolorEditor::UIcolorEditor(QWidget *parent) : QGroupBox(parent) { UIcolorEditor::UIcolorEditor(QWidget* parent)
: QGroupBox(parent)
{
setTitle(tr("UI Color Editor")); setTitle(tr("UI Color Editor"));
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_hLayout = new QHBoxLayout; m_hLayout = new QHBoxLayout;
@@ -46,7 +48,9 @@ UIcolorEditor::UIcolorEditor(QWidget *parent) : QGroupBox(parent) {
updateComponents(); updateComponents();
} }
void UIcolorEditor::updateComponents() { void
UIcolorEditor::updateComponents()
{
ConfigHandler config; ConfigHandler config;
m_uiColor = config.uiMainColorValue(); m_uiColor = config.uiMainColorValue();
m_contrastColor = config.uiContrastColorValue(); m_contrastColor = config.uiContrastColorValue();
@@ -60,7 +64,9 @@ void UIcolorEditor::updateComponents() {
} }
// updateUIcolor updates the appearance of the buttons // updateUIcolor updates the appearance of the buttons
void UIcolorEditor::updateUIcolor() { void
UIcolorEditor::updateUIcolor()
{
ConfigHandler config; ConfigHandler config;
if (m_lastButtonPressed == m_buttonMainColor) { if (m_lastButtonPressed == m_buttonMainColor) {
config.setUIMainColor(m_uiColor); config.setUIMainColor(m_uiColor);
@@ -70,7 +76,9 @@ void UIcolorEditor::updateUIcolor() {
} }
// updateLocalColor updates the local button // updateLocalColor updates the local button
void UIcolorEditor::updateLocalColor(const QColor c) { void
UIcolorEditor::updateLocalColor(const QColor c)
{
if (m_lastButtonPressed == m_buttonMainColor) { if (m_lastButtonPressed == m_buttonMainColor) {
m_uiColor = c; m_uiColor = c;
} else { } else {
@@ -79,16 +87,22 @@ void UIcolorEditor::updateLocalColor(const QColor c) {
m_lastButtonPressed->setColor(c); m_lastButtonPressed->setColor(c);
} }
void UIcolorEditor::initColorWheel() { void
UIcolorEditor::initColorWheel()
{
m_colorWheel = new color_widgets::ColorWheel(this); m_colorWheel = new color_widgets::ColorWheel(this);
connect(m_colorWheel, &color_widgets::ColorWheel::mouseReleaseOnColor, this, connect(m_colorWheel,
&color_widgets::ColorWheel::mouseReleaseOnColor,
this,
&UIcolorEditor::updateUIcolor); &UIcolorEditor::updateUIcolor);
connect(m_colorWheel, &color_widgets::ColorWheel::colorChanged, this, connect(m_colorWheel,
&color_widgets::ColorWheel::colorChanged,
this,
&UIcolorEditor::updateLocalColor); &UIcolorEditor::updateLocalColor);
const int size = GlobalValues::buttonBaseSize() * 3; const int size = GlobalValues::buttonBaseSize() * 3;
m_colorWheel->setMinimumSize(size, size); m_colorWheel->setMinimumSize(size, size);
m_colorWheel->setMaximumSize(size*2, size*2); m_colorWheel->setMaximumSize(size * 2, size * 2);
m_colorWheel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_colorWheel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_colorWheel->setToolTip(tr("Change the color moving the selectors and see" m_colorWheel->setToolTip(tr("Change the color moving the selectors and see"
" the changes in the preview buttons.")); " the changes in the preview buttons."));
@@ -96,18 +110,21 @@ void UIcolorEditor::initColorWheel() {
m_hLayout->addWidget(m_colorWheel); m_hLayout->addWidget(m_colorWheel);
} }
void UIcolorEditor::initButtons() { void
UIcolorEditor::initButtons()
{
const int extraSize = GlobalValues::buttonBaseSize() / 3; const int extraSize = GlobalValues::buttonBaseSize() / 3;
int frameSize = GlobalValues::buttonBaseSize() + extraSize; int frameSize = GlobalValues::buttonBaseSize() + extraSize;
m_vLayout->addWidget(new QLabel(tr("Select a Button to modify it"), this)); m_vLayout->addWidget(new QLabel(tr("Select a Button to modify it"), this));
QGroupBox *frame = new QGroupBox(); QGroupBox* frame = new QGroupBox();
frame->setFixedSize(frameSize, frameSize); frame->setFixedSize(frameSize, frameSize);
m_buttonMainColor = new CaptureButton(m_buttonIconType, frame); m_buttonMainColor = new CaptureButton(m_buttonIconType, frame);
m_buttonMainColor->move(m_buttonMainColor->x() + extraSize/2, m_buttonMainColor->y() + extraSize/2); m_buttonMainColor->move(m_buttonMainColor->x() + extraSize / 2,
QHBoxLayout *h1 = new QHBoxLayout(); m_buttonMainColor->y() + extraSize / 2);
QHBoxLayout* h1 = new QHBoxLayout();
h1->addWidget(frame); h1->addWidget(frame);
m_labelMain = new ClickableLabel(tr("Main Color"), this); m_labelMain = new ClickableLabel(tr("Main Color"), this);
h1->addWidget(m_labelMain); h1->addWidget(m_labelMain);
@@ -116,12 +133,12 @@ void UIcolorEditor::initButtons() {
m_buttonMainColor->setToolTip(tr("Click on this button to set the edition" m_buttonMainColor->setToolTip(tr("Click on this button to set the edition"
" mode of the main color.")); " mode of the main color."));
QGroupBox *frame2 = new QGroupBox(); QGroupBox* frame2 = new QGroupBox();
m_buttonContrast = new CaptureButton(m_buttonIconType, frame2); m_buttonContrast = new CaptureButton(m_buttonIconType, frame2);
m_buttonContrast->move(m_buttonContrast->x() + extraSize/2, m_buttonContrast->move(m_buttonContrast->x() + extraSize / 2,
m_buttonContrast->y() + extraSize/2); m_buttonContrast->y() + extraSize / 2);
QHBoxLayout *h2 = new QHBoxLayout(); QHBoxLayout* h2 = new QHBoxLayout();
h2->addWidget(frame2); h2->addWidget(frame2);
frame2->setFixedSize(frameSize, frameSize); frame2->setFixedSize(frameSize, frameSize);
m_labelContrast = new ClickableLabel(tr("Contrast Color"), this); m_labelContrast = new ClickableLabel(tr("Contrast Color"), this);
@@ -132,20 +149,28 @@ void UIcolorEditor::initButtons() {
m_buttonContrast->setToolTip(tr("Click on this button to set the edition" m_buttonContrast->setToolTip(tr("Click on this button to set the edition"
" mode of the contrast color.")); " mode of the contrast color."));
connect(m_buttonMainColor, &CaptureButton::pressedButton, connect(m_buttonMainColor,
this, &UIcolorEditor::changeLastButton); &CaptureButton::pressedButton,
connect(m_buttonContrast, &CaptureButton::pressedButton, this,
this, &UIcolorEditor::changeLastButton); &UIcolorEditor::changeLastButton);
connect(m_buttonContrast,
&CaptureButton::pressedButton,
this,
&UIcolorEditor::changeLastButton);
// clicking the labels changes the button too // clicking the labels changes the button too
connect(m_labelMain, &ClickableLabel::clicked, connect(m_labelMain, &ClickableLabel::clicked, this, [this] {
this, [this]{ changeLastButton(m_buttonMainColor); }); changeLastButton(m_buttonMainColor);
connect(m_labelContrast, &ClickableLabel::clicked, });
this, [this]{ changeLastButton(m_buttonContrast); }); connect(m_labelContrast, &ClickableLabel::clicked, this, [this] {
changeLastButton(m_buttonContrast);
});
m_lastButtonPressed = m_buttonMainColor; m_lastButtonPressed = m_buttonMainColor;
} }
// visual update for the selected button // visual update for the selected button
void UIcolorEditor::changeLastButton(CaptureButton *b) { void
UIcolorEditor::changeLastButton(CaptureButton* b)
{
if (m_lastButtonPressed != b) { if (m_lastButtonPressed != b) {
m_lastButtonPressed = b; m_lastButtonPressed = b;

View File

@@ -26,10 +26,11 @@ class QHBoxLayout;
class CaptureButton; class CaptureButton;
class ClickableLabel; class ClickableLabel;
class UIcolorEditor : public QGroupBox { class UIcolorEditor : public QGroupBox
{
Q_OBJECT Q_OBJECT
public: public:
explicit UIcolorEditor(QWidget *parent = nullptr); explicit UIcolorEditor(QWidget* parent = nullptr);
public slots: public slots:
void updateComponents(); void updateComponents();
@@ -37,21 +38,22 @@ public slots:
private slots: private slots:
void updateUIcolor(); void updateUIcolor();
void updateLocalColor(const QColor); void updateLocalColor(const QColor);
void changeLastButton(CaptureButton *); void changeLastButton(CaptureButton*);
private: private:
QColor m_uiColor, m_contrastColor; QColor m_uiColor, m_contrastColor;
CaptureButton *m_buttonMainColor; CaptureButton* m_buttonMainColor;
ClickableLabel *m_labelMain; ClickableLabel* m_labelMain;
CaptureButton *m_buttonContrast; CaptureButton* m_buttonContrast;
ClickableLabel *m_labelContrast; ClickableLabel* m_labelContrast;
CaptureButton *m_lastButtonPressed; CaptureButton* m_lastButtonPressed;
color_widgets::ColorWheel *m_colorWheel; color_widgets::ColorWheel* m_colorWheel;
static const CaptureButton::ButtonType m_buttonIconType = CaptureButton::TYPE_CIRCLE; static const CaptureButton::ButtonType m_buttonIconType =
CaptureButton::TYPE_CIRCLE;
QHBoxLayout *m_hLayout; QHBoxLayout* m_hLayout;
QVBoxLayout *m_vLayout; QVBoxLayout* m_vLayout;
void initColorWheel(); void initColorWheel();
void initButtons(); void initButtons();

View File

@@ -17,44 +17,52 @@
#include "visualseditor.h" #include "visualseditor.h"
#include "src/config/buttonlistview.h" #include "src/config/buttonlistview.h"
#include "src/config/extendedslider.h"
#include "src/config/uicoloreditor.h" #include "src/config/uicoloreditor.h"
#include "src/utils/confighandler.h" #include "src/utils/confighandler.h"
#include "src/config/extendedslider.h" #include <QHBoxLayout>
#include <QLabel> #include <QLabel>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QHBoxLayout>
VisualsEditor::VisualsEditor(QWidget *parent) : QWidget(parent) { VisualsEditor::VisualsEditor(QWidget* parent)
m_layout= new QVBoxLayout(); : QWidget(parent)
{
m_layout = new QVBoxLayout();
setLayout(m_layout); setLayout(m_layout);
initWidgets(); initWidgets();
} }
void VisualsEditor::updateComponents() { void
VisualsEditor::updateComponents()
{
m_buttonList->updateComponents(); m_buttonList->updateComponents();
m_colorEditor->updateComponents(); m_colorEditor->updateComponents();
int opacity = ConfigHandler().contrastOpacityValue(); int opacity = ConfigHandler().contrastOpacityValue();
m_opacitySlider->setMapedValue(0, opacity, 255); m_opacitySlider->setMapedValue(0, opacity, 255);
} }
void VisualsEditor::initOpacitySlider() { void
VisualsEditor::initOpacitySlider()
{
m_opacitySlider = new ExtendedSlider(); m_opacitySlider = new ExtendedSlider();
m_opacitySlider->setFocusPolicy(Qt::NoFocus); m_opacitySlider->setFocusPolicy(Qt::NoFocus);
m_opacitySlider->setOrientation(Qt::Horizontal); m_opacitySlider->setOrientation(Qt::Horizontal);
m_opacitySlider->setRange(0, 100); m_opacitySlider->setRange(0, 100);
connect(m_opacitySlider, &ExtendedSlider::modificationsEnded, connect(m_opacitySlider,
this, &VisualsEditor::saveOpacity); &ExtendedSlider::modificationsEnded,
QHBoxLayout *localLayout = new QHBoxLayout(); this,
&VisualsEditor::saveOpacity);
QHBoxLayout* localLayout = new QHBoxLayout();
localLayout->addWidget(new QLabel(QStringLiteral("0%"))); localLayout->addWidget(new QLabel(QStringLiteral("0%")));
localLayout->addWidget(m_opacitySlider); localLayout->addWidget(m_opacitySlider);
localLayout->addWidget(new QLabel(QStringLiteral("100%"))); localLayout->addWidget(new QLabel(QStringLiteral("100%")));
QLabel *label = new QLabel(); QLabel* label = new QLabel();
QString labelMsg = tr("Opacity of area outside selection:") + " %1%"; QString labelMsg = tr("Opacity of area outside selection:") + " %1%";
connect(m_opacitySlider, &ExtendedSlider::valueChanged, connect(m_opacitySlider,
this, [labelMsg, label](int val){ &ExtendedSlider::valueChanged,
label->setText(labelMsg.arg(val)); this,
}); [labelMsg, label](int val) { label->setText(labelMsg.arg(val)); });
m_layout->addWidget(label); m_layout->addWidget(label);
m_layout->addLayout(localLayout); m_layout->addLayout(localLayout);
@@ -62,12 +70,16 @@ void VisualsEditor::initOpacitySlider() {
m_opacitySlider->setMapedValue(0, opacity, 255); m_opacitySlider->setMapedValue(0, opacity, 255);
} }
void VisualsEditor::saveOpacity() { void
VisualsEditor::saveOpacity()
{
int value = m_opacitySlider->mappedValue(0, 255); int value = m_opacitySlider->mappedValue(0, 255);
ConfigHandler().setContrastOpacity(value); ConfigHandler().setContrastOpacity(value);
} }
void VisualsEditor::initWidgets() { void
VisualsEditor::initWidgets()
{
m_colorEditor = new UIcolorEditor(); m_colorEditor = new UIcolorEditor();
m_layout->addWidget(m_colorEditor); m_layout->addWidget(m_colorEditor);
@@ -81,7 +93,9 @@ void VisualsEditor::initWidgets() {
listLayout->addWidget(m_buttonList); listLayout->addWidget(m_buttonList);
QPushButton* setAllButtons = new QPushButton(tr("Select All")); QPushButton* setAllButtons = new QPushButton(tr("Select All"));
connect(setAllButtons, &QPushButton::clicked, connect(setAllButtons,
m_buttonList, &ButtonListView::selectAll); &QPushButton::clicked,
m_buttonList,
&ButtonListView::selectAll);
listLayout->addWidget(setAllButtons); listLayout->addWidget(setAllButtons);
} }

View File

@@ -24,10 +24,11 @@ class QVBoxLayout;
class ButtonListView; class ButtonListView;
class UIcolorEditor; class UIcolorEditor;
class VisualsEditor : public QWidget { class VisualsEditor : public QWidget
{
Q_OBJECT Q_OBJECT
public: public:
explicit VisualsEditor(QWidget *parent = nullptr); explicit VisualsEditor(QWidget* parent = nullptr);
public slots: public slots:
void updateComponents(); void updateComponents();
@@ -36,10 +37,10 @@ private slots:
void saveOpacity(); void saveOpacity();
private: private:
QVBoxLayout *m_layout; QVBoxLayout* m_layout;
ButtonListView *m_buttonList; ButtonListView* m_buttonList;
UIcolorEditor *m_colorEditor; UIcolorEditor* m_colorEditor;
ExtendedSlider *m_opacitySlider; ExtendedSlider* m_opacitySlider;
void initWidgets(); void initWidgets();
void initOpacitySlider(); void initOpacitySlider();

View File

@@ -17,60 +17,80 @@
#include "capturerequest.h" #include "capturerequest.h"
#include "src/utils/screenshotsaver.h" #include "src/utils/screenshotsaver.h"
#include <QVector>
#include <QDateTime> #include <QDateTime>
#include <QVector>
CaptureRequest::CaptureRequest(CaptureRequest::CaptureMode mode, CaptureRequest::CaptureRequest(CaptureRequest::CaptureMode mode,
const uint delay, const QString &path, const uint delay,
const QVariant &data, const QString& path,
CaptureRequest::ExportTask tasks) : const QVariant& data,
m_mode(mode), m_delay(delay), m_path(path), m_tasks(tasks), CaptureRequest::ExportTask tasks)
m_data(data), m_forcedID(false), m_id(0) : m_mode(mode)
, m_delay(delay)
, m_path(path)
, m_tasks(tasks)
, m_data(data)
, m_forcedID(false)
, m_id(0)
{}
void
CaptureRequest::setStaticID(uint id)
{ {
}
void CaptureRequest::setStaticID(uint id) {
m_forcedID = true; m_forcedID = true;
m_id = id; m_id = id;
} }
uint CaptureRequest::id() const { uint
CaptureRequest::id() const
{
if (m_forcedID) { if (m_forcedID) {
return m_id; return m_id;
} }
uint id = 0; uint id = 0;
QVector<uint>v; QVector<uint> v;
v << qHash(m_mode) << qHash(m_delay * QDateTime::currentMSecsSinceEpoch()) v << qHash(m_mode) << qHash(m_delay * QDateTime::currentMSecsSinceEpoch())
<< qHash(m_path) << qHash(m_tasks) << m_data.toInt(); << qHash(m_path) << qHash(m_tasks) << m_data.toInt();
for(uint i : v) { for (uint i : v) {
id ^= i + 0x9e3779b9 + (id << 6) + (id >> 2); id ^= i + 0x9e3779b9 + (id << 6) + (id >> 2);
} }
return id; return id;
} }
CaptureRequest::CaptureMode CaptureRequest::captureMode() const { CaptureRequest::CaptureMode
CaptureRequest::captureMode() const
{
return m_mode; return m_mode;
} }
uint CaptureRequest::delay() const { uint
CaptureRequest::delay() const
{
return m_delay; return m_delay;
} }
QString CaptureRequest::path() const { QString
CaptureRequest::path() const
{
return m_path; return m_path;
} }
QVariant CaptureRequest::data() const { QVariant
CaptureRequest::data() const
{
return m_data; return m_data;
} }
void CaptureRequest::addTask(CaptureRequest::ExportTask task) { void
CaptureRequest::addTask(CaptureRequest::ExportTask task)
{
m_tasks |= task; m_tasks |= task;
} }
void CaptureRequest::exportCapture(const QPixmap &p) { void
CaptureRequest::exportCapture(const QPixmap& p)
{
if ((m_tasks & ExportTask::FILESYSTEM_SAVE_TASK) != ExportTask::NO_TASK) { if ((m_tasks & ExportTask::FILESYSTEM_SAVE_TASK) != ExportTask::NO_TASK) {
if (m_path.isEmpty()) { if (m_path.isEmpty()) {
ScreenshotSaver().saveToFilesystemGUI(p); ScreenshotSaver().saveToFilesystemGUI(p);
@@ -82,5 +102,4 @@ void CaptureRequest::exportCapture(const QPixmap &p) {
if ((m_tasks & ExportTask::CLIPBOARD_SAVE_TASK) != ExportTask::NO_TASK) { if ((m_tasks & ExportTask::CLIPBOARD_SAVE_TASK) != ExportTask::NO_TASK) {
ScreenshotSaver().saveToClipboard(p); ScreenshotSaver().saveToClipboard(p);
} }
} }

View File

@@ -17,19 +17,22 @@
#pragma once #pragma once
#include <QString>
#include <QPixmap> #include <QPixmap>
#include <QString>
#include <QVariant> #include <QVariant>
class CaptureRequest { class CaptureRequest
{
public: public:
enum CaptureMode { enum CaptureMode
{
FULLSCREEN_MODE, FULLSCREEN_MODE,
GRAPHICAL_MODE, GRAPHICAL_MODE,
SCREEN_MODE, SCREEN_MODE,
}; };
enum ExportTask { enum ExportTask
{
NO_TASK = 0, NO_TASK = 0,
CLIPBOARD_SAVE_TASK = 1, CLIPBOARD_SAVE_TASK = 1,
FILESYSTEM_SAVE_TASK = 2, FILESYSTEM_SAVE_TASK = 2,
@@ -37,8 +40,8 @@ public:
CaptureRequest(CaptureMode mode, CaptureRequest(CaptureMode mode,
const uint delay = 0, const uint delay = 0,
const QString &path = QLatin1String(""), const QString& path = QLatin1String(""),
const QVariant &data = QVariant(), const QVariant& data = QVariant(),
ExportTask tasks = NO_TASK); ExportTask tasks = NO_TASK);
void setStaticID(uint id); void setStaticID(uint id);
@@ -50,7 +53,7 @@ public:
CaptureMode captureMode() const; CaptureMode captureMode() const;
void addTask(ExportTask task); void addTask(ExportTask task);
void exportCapture(const QPixmap &p); void exportCapture(const QPixmap& p);
private: private:
CaptureMode m_mode; CaptureMode m_mode;
@@ -65,16 +68,21 @@ private:
using eTask = CaptureRequest::ExportTask; using eTask = CaptureRequest::ExportTask;
inline eTask operator|(const eTask &a, const eTask &b) { inline eTask
operator|(const eTask& a, const eTask& b)
{
return static_cast<eTask>(static_cast<int>(a) | static_cast<int>(b)); return static_cast<eTask>(static_cast<int>(a) | static_cast<int>(b));
} }
inline eTask operator&(const eTask &a, const eTask &b) { inline eTask
operator&(const eTask& a, const eTask& b)
{
return static_cast<eTask>(static_cast<int>(a) & static_cast<int>(b)); return static_cast<eTask>(static_cast<int>(a) & static_cast<int>(b));
} }
inline eTask& operator|=(eTask &a, const eTask &b) { inline eTask&
operator|=(eTask& a, const eTask& b)
{
a = static_cast<eTask>(static_cast<int>(a) | static_cast<int>(b)); a = static_cast<eTask>(static_cast<int>(a) | static_cast<int>(b));
return a; return a;
} }

View File

@@ -16,20 +16,20 @@
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "controller.h" #include "controller.h"
#include "src/widgets/capture/capturewidget.h"
#include "src/utils/confighandler.h"
#include "src/widgets/infowindow.h"
#include "src/config/configwindow.h" #include "src/config/configwindow.h"
#include "src/widgets/capture/capturebutton.h" #include "src/utils/confighandler.h"
#include "src/widgets/capturelauncher.h"
#include "src/utils/systemnotification.h"
#include "src/utils/screengrabber.h" #include "src/utils/screengrabber.h"
#include <QFile> #include "src/utils/systemnotification.h"
#include <QApplication> #include "src/widgets/capture/capturebutton.h"
#include <QSystemTrayIcon> #include "src/widgets/capture/capturewidget.h"
#include "src/widgets/capturelauncher.h"
#include "src/widgets/infowindow.h"
#include <QAction> #include <QAction>
#include <QMenu> #include <QApplication>
#include <QDesktopWidget> #include <QDesktopWidget>
#include <QFile>
#include <QMenu>
#include <QSystemTrayIcon>
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
#include "src/core/globalshortcutfilter.h" #include "src/core/globalshortcutfilter.h"
@@ -38,7 +38,9 @@
// Controller is the core component of Flameshot, creates the trayIcon and // Controller is the core component of Flameshot, creates the trayIcon and
// launches the capture widget // launches the capture widget
Controller::Controller() : m_captureWindow(nullptr) { Controller::Controller()
: m_captureWindow(nullptr)
{
qApp->setQuitOnLastWindowClosed(false); qApp->setQuitOnLastWindowClosed(false);
// init tray icon // init tray icon
@@ -49,10 +51,9 @@ Controller::Controller() : m_captureWindow(nullptr) {
#elif defined(Q_OS_WIN) #elif defined(Q_OS_WIN)
enableTrayIcon(); enableTrayIcon();
GlobalShortcutFilter *nativeFilter = new GlobalShortcutFilter(this); GlobalShortcutFilter* nativeFilter = new GlobalShortcutFilter(this);
qApp->installNativeEventFilter(nativeFilter); qApp->installNativeEventFilter(nativeFilter);
connect(nativeFilter, &GlobalShortcutFilter::printPressed, connect(nativeFilter, &GlobalShortcutFilter::printPressed, this, [this]() {
this, [this](){
this->requestCapture(CaptureRequest(CaptureRequest::GRAPHICAL_MODE)); this->requestCapture(CaptureRequest(CaptureRequest::GRAPHICAL_MODE));
}); });
#endif #endif
@@ -61,51 +62,62 @@ Controller::Controller() : m_captureWindow(nullptr) {
qApp->setStyleSheet(StyleSheet); qApp->setStyleSheet(StyleSheet);
} }
Controller *Controller::getInstance() { Controller*
Controller::getInstance()
{
static Controller c; static Controller c;
return &c; return &c;
} }
void Controller::enableExports() { void
connect(this, &Controller::captureTaken, Controller::enableExports()
this, &Controller::handleCaptureTaken); {
connect(this, &Controller::captureFailed, connect(
this, &Controller::handleCaptureFailed); this, &Controller::captureTaken, this, &Controller::handleCaptureTaken);
connect(
this, &Controller::captureFailed, this, &Controller::handleCaptureFailed);
} }
void Controller::requestCapture(const CaptureRequest &request) { void
Controller::requestCapture(const CaptureRequest& request)
{
uint id = request.id(); uint id = request.id();
m_requestMap.insert(id, request); m_requestMap.insert(id, request);
switch (request.captureMode()) { switch (request.captureMode()) {
case CaptureRequest::FULLSCREEN_MODE: case CaptureRequest::FULLSCREEN_MODE:
doLater(request.delay(), this, [this, id](){ doLater(request.delay(), this, [this, id]() {
this->startFullscreenCapture(id); this->startFullscreenCapture(id);
}); });
break; break;
// TODO: Figure out the code path that gets here so the deprated warning can be fixed // TODO: Figure out the code path that gets here so the deprated warning can
// be fixed
case CaptureRequest::SCREEN_MODE: { case CaptureRequest::SCREEN_MODE: {
int &&number = request.data().toInt(); int&& number = request.data().toInt();
doLater(request.delay(), this, [this, id, number](){ doLater(request.delay(), this, [this, id, number]() {
this->startScreenGrab(id, number); this->startScreenGrab(id, number);
}); });
break; break;
} case CaptureRequest::GRAPHICAL_MODE: { }
QString &&path = request.path(); case CaptureRequest::GRAPHICAL_MODE: {
doLater(request.delay(), this, [this, id, path](){ QString&& path = request.path();
doLater(request.delay(), this, [this, id, path]() {
this->startVisualCapture(id, path); this->startVisualCapture(id, path);
}); });
break; break;
} default: }
default:
emit captureFailed(id); emit captureFailed(id);
break; break;
} }
} }
// creation of a new capture in GUI mode // creation of a new capture in GUI mode
void Controller::startVisualCapture(const uint id, const QString &forcedSavePath) { void
Controller::startVisualCapture(const uint id, const QString& forcedSavePath)
{
if (!m_captureWindow) { if (!m_captureWindow) {
QWidget *modalWidget = nullptr; QWidget* modalWidget = nullptr;
do { do {
modalWidget = qApp->activeModalWidget(); modalWidget = qApp->activeModalWidget();
if (modalWidget) { if (modalWidget) {
@@ -115,24 +127,30 @@ void Controller::startVisualCapture(const uint id, const QString &forcedSavePath
} while (modalWidget); } while (modalWidget);
m_captureWindow = new CaptureWidget(id, forcedSavePath); m_captureWindow = new CaptureWidget(id, forcedSavePath);
//m_captureWindow = new CaptureWidget(id, forcedSavePath, false); // debug // m_captureWindow = new CaptureWidget(id, forcedSavePath, false); // debug
connect(m_captureWindow, &CaptureWidget::captureFailed, connect(m_captureWindow,
this, &Controller::captureFailed); &CaptureWidget::captureFailed,
connect(m_captureWindow, &CaptureWidget::captureTaken, this,
this, &Controller::captureTaken); &Controller::captureFailed);
connect(m_captureWindow,
&CaptureWidget::captureTaken,
this,
&Controller::captureTaken);
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
m_captureWindow->show(); m_captureWindow->show();
#else #else
m_captureWindow->showFullScreen(); m_captureWindow->showFullScreen();
//m_captureWindow->show(); // Debug // m_captureWindow->show(); // Debug
#endif #endif
} else { } else {
emit captureFailed(id); emit captureFailed(id);
} }
} }
void Controller::startScreenGrab(const uint id, const int screenNumber) { void
Controller::startScreenGrab(const uint id, const int screenNumber)
{
bool ok = true; bool ok = true;
int n = screenNumber; int n = screenNumber;
@@ -149,7 +167,9 @@ void Controller::startScreenGrab(const uint id, const int screenNumber) {
} }
// creation of the configuration window // creation of the configuration window
void Controller::openConfigWindow() { void
Controller::openConfigWindow()
{
if (!m_configWindow) { if (!m_configWindow) {
m_configWindow = new ConfigWindow(); m_configWindow = new ConfigWindow();
m_configWindow->show(); m_configWindow->show();
@@ -157,41 +177,45 @@ void Controller::openConfigWindow() {
} }
// creation of the window of information // creation of the window of information
void Controller::openInfoWindow() { void
Controller::openInfoWindow()
{
if (!m_infoWindow) { if (!m_infoWindow) {
m_infoWindow = new InfoWindow(); m_infoWindow = new InfoWindow();
} }
} }
void Controller::openLauncherWindow() { void
CaptureLauncher *w = new CaptureLauncher(); Controller::openLauncherWindow()
{
CaptureLauncher* w = new CaptureLauncher();
w->show(); w->show();
} }
void Controller::enableTrayIcon() { void
Controller::enableTrayIcon()
{
if (m_trayIcon) { if (m_trayIcon) {
return; return;
} }
ConfigHandler().setDisabledTrayIcon(false); ConfigHandler().setDisabledTrayIcon(false);
QAction *captureAction = new QAction(tr("&Take Screenshot"), this); QAction* captureAction = new QAction(tr("&Take Screenshot"), this);
connect(captureAction, &QAction::triggered, this, [this](){ connect(captureAction, &QAction::triggered, this, [this]() {
// Wait 400 ms to hide the QMenu // Wait 400 ms to hide the QMenu
doLater(400, this, [this](){ this->startVisualCapture(); }); doLater(400, this, [this]() { this->startVisualCapture(); });
}); });
QAction *launcherAction = new QAction(tr("&Open Launcher"), this); QAction* launcherAction = new QAction(tr("&Open Launcher"), this);
connect(launcherAction, &QAction::triggered, this, connect(
&Controller::openLauncherWindow); launcherAction, &QAction::triggered, this, &Controller::openLauncherWindow);
QAction *configAction = new QAction(tr("&Configuration"), this); QAction* configAction = new QAction(tr("&Configuration"), this);
connect(configAction, &QAction::triggered, this, connect(
&Controller::openConfigWindow); configAction, &QAction::triggered, this, &Controller::openConfigWindow);
QAction *infoAction = new QAction(tr("&Information"), this); QAction* infoAction = new QAction(tr("&Information"), this);
connect(infoAction, &QAction::triggered, this, connect(infoAction, &QAction::triggered, this, &Controller::openInfoWindow);
&Controller::openInfoWindow); QAction* quitAction = new QAction(tr("&Quit"), this);
QAction *quitAction = new QAction(tr("&Quit"), this); connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
connect(quitAction, &QAction::triggered, qApp,
&QCoreApplication::quit);
QMenu *trayIconMenu = new QMenu(); QMenu* trayIconMenu = new QMenu();
trayIconMenu->addAction(captureAction); trayIconMenu->addAction(captureAction);
trayIconMenu->addAction(launcherAction); trayIconMenu->addAction(launcherAction);
trayIconMenu->addSeparator(); trayIconMenu->addSeparator();
@@ -203,10 +227,11 @@ void Controller::enableTrayIcon() {
m_trayIcon = new QSystemTrayIcon(); m_trayIcon = new QSystemTrayIcon();
m_trayIcon->setToolTip(QStringLiteral("Flameshot")); m_trayIcon->setToolTip(QStringLiteral("Flameshot"));
m_trayIcon->setContextMenu(trayIconMenu); m_trayIcon->setContextMenu(trayIconMenu);
QIcon trayicon = QIcon::fromTheme("flameshot-tray", QIcon(":img/app/flameshot.png")); QIcon trayicon =
QIcon::fromTheme("flameshot-tray", QIcon(":img/app/flameshot.png"));
m_trayIcon->setIcon(trayicon); m_trayIcon->setIcon(trayicon);
auto trayIconActivated = [this](QSystemTrayIcon::ActivationReason r){ auto trayIconActivated = [this](QSystemTrayIcon::ActivationReason r) {
if (r == QSystemTrayIcon::Trigger) { if (r == QSystemTrayIcon::Trigger) {
startVisualCapture(); startVisualCapture();
} }
@@ -215,7 +240,9 @@ void Controller::enableTrayIcon() {
m_trayIcon->show(); m_trayIcon->show();
} }
void Controller::disableTrayIcon() { void
Controller::disableTrayIcon()
{
#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX)
if (m_trayIcon) { if (m_trayIcon) {
m_trayIcon->deleteLater(); m_trayIcon->deleteLater();
@@ -224,9 +251,9 @@ void Controller::disableTrayIcon() {
#endif #endif
} }
void Controller::sendTrayNotification( void
const QString &text, Controller::sendTrayNotification(const QString& text,
const QString &title, const QString& title,
const int timeout) const int timeout)
{ {
if (m_trayIcon) { if (m_trayIcon) {
@@ -234,13 +261,17 @@ void Controller::sendTrayNotification(
} }
} }
void Controller::updateConfigComponents() { void
Controller::updateConfigComponents()
{
if (m_configWindow) { if (m_configWindow) {
m_configWindow->updateChildren(); m_configWindow->updateChildren();
} }
} }
void Controller::startFullscreenCapture(const uint id) { void
Controller::startFullscreenCapture(const uint id)
{
bool ok = true; bool ok = true;
QPixmap p(ScreenGrabber().grabEntireDesktop(ok)); QPixmap p(ScreenGrabber().grabEntireDesktop(ok));
if (ok) { if (ok) {
@@ -250,7 +281,9 @@ void Controller::startFullscreenCapture(const uint id) {
} }
} }
void Controller::handleCaptureTaken(uint id, QPixmap p) { void
Controller::handleCaptureTaken(uint id, QPixmap p)
{
auto it = m_requestMap.find(id); auto it = m_requestMap.find(id);
if (it != m_requestMap.end()) { if (it != m_requestMap.end()) {
it.value().exportCapture(p); it.value().exportCapture(p);
@@ -261,7 +294,9 @@ void Controller::handleCaptureTaken(uint id, QPixmap p) {
} }
} }
void Controller::handleCaptureFailed(uint id) { void
Controller::handleCaptureFailed(uint id)
{
m_requestMap.remove(id); m_requestMap.remove(id);
if (ConfigHandler().closeAfterScreenshotValue()) { if (ConfigHandler().closeAfterScreenshotValue()) {
@@ -269,10 +304,14 @@ void Controller::handleCaptureFailed(uint id) {
} }
} }
void Controller::doLater(int msec, QObject *receiver, lambda func) { void
QTimer *timer = new QTimer(receiver); Controller::doLater(int msec, QObject* receiver, lambda func)
QObject::connect(timer, &QTimer::timeout, receiver, {
[timer, func](){ func(); timer->deleteLater(); }); QTimer* timer = new QTimer(receiver);
QObject::connect(timer, &QTimer::timeout, receiver, [timer, func]() {
func();
timer->deleteLater();
});
timer->setInterval(msec); timer->setInterval(msec);
timer->start(); timer->start();
} }

View File

@@ -18,10 +18,10 @@
#pragma once #pragma once
#include "src/core/capturerequest.h" #include "src/core/capturerequest.h"
#include <QObject>
#include <QPointer>
#include <QPixmap>
#include <QMap> #include <QMap>
#include <QObject>
#include <QPixmap>
#include <QPointer>
#include <QTimer> #include <QTimer>
#include <functional> #include <functional>
@@ -32,14 +32,15 @@ class QSystemTrayIcon;
using lambda = std::function<void(void)>; using lambda = std::function<void(void)>;
class Controller : public QObject { class Controller : public QObject
{
Q_OBJECT Q_OBJECT
public: public:
static Controller* getInstance(); static Controller* getInstance();
Controller(const Controller&) = delete; Controller(const Controller&) = delete;
void operator =(const Controller&) = delete; void operator=(const Controller&) = delete;
void enableExports(); void enableExports();
@@ -48,15 +49,16 @@ signals:
void captureFailed(uint id); void captureFailed(uint id);
public slots: public slots:
void requestCapture(const CaptureRequest &request); void requestCapture(const CaptureRequest& request);
void openConfigWindow(); void openConfigWindow();
void openInfoWindow(); void openInfoWindow();
void openLauncherWindow(); void openLauncherWindow();
void enableTrayIcon(); void enableTrayIcon();
void disableTrayIcon(); void disableTrayIcon();
void sendTrayNotification(const QString &text, void sendTrayNotification(
const QString &title = QStringLiteral("Flameshot Info"), const QString& text,
const QString& title = QStringLiteral("Flameshot Info"),
const int timeout = 5000); const int timeout = 5000);
void updateConfigComponents(); void updateConfigComponents();
@@ -64,7 +66,7 @@ public slots:
private slots: private slots:
void startFullscreenCapture(const uint id = 0); void startFullscreenCapture(const uint id = 0);
void startVisualCapture(const uint id = 0, void startVisualCapture(const uint id = 0,
const QString &forcedSavePath = QString()); const QString& forcedSavePath = QString());
void startScreenGrab(const uint id = 0, const int screenNumber = -1); void startScreenGrab(const uint id = 0, const int screenNumber = -1);
void handleCaptureTaken(uint id, QPixmap p); void handleCaptureTaken(uint id, QPixmap p);
@@ -75,7 +77,7 @@ private:
// replace QTimer::singleShot introduced in Qt 5.4 // replace QTimer::singleShot introduced in Qt 5.4
// the actual target Qt version is 5.3 // the actual target Qt version is 5.3
void doLater(int msec, QObject *receiver, lambda func); void doLater(int msec, QObject* receiver, lambda func);
QMap<uint, CaptureRequest> m_requestMap; QMap<uint, CaptureRequest> m_requestMap;
QPointer<CaptureWidget> m_captureWindow; QPointer<CaptureWidget> m_captureWindow;

View File

@@ -16,37 +16,44 @@
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "flameshotdbusadapter.h" #include "flameshotdbusadapter.h"
#include "src/core/controller.h"
#include "src/utils/confighandler.h" #include "src/utils/confighandler.h"
#include "src/utils/screengrabber.h" #include "src/utils/screengrabber.h"
#include "src/core/controller.h"
#include "src/utils/screenshotsaver.h" #include "src/utils/screenshotsaver.h"
#include "src/utils/systemnotification.h" #include "src/utils/systemnotification.h"
#include <QBuffer> #include <QBuffer>
FlameshotDBusAdapter::FlameshotDBusAdapter(QObject *parent) FlameshotDBusAdapter::FlameshotDBusAdapter(QObject* parent)
: QDBusAbstractAdaptor(parent) : QDBusAbstractAdaptor(parent)
{ {
auto controller = Controller::getInstance(); auto controller = Controller::getInstance();
connect(controller, &Controller::captureFailed, connect(controller,
this, &FlameshotDBusAdapter::captureFailed); &Controller::captureFailed,
connect(controller, &Controller::captureTaken, this,
this, &FlameshotDBusAdapter::handleCaptureTaken); &FlameshotDBusAdapter::captureFailed);
connect(controller,
&Controller::captureTaken,
this,
&FlameshotDBusAdapter::handleCaptureTaken);
} }
FlameshotDBusAdapter::~FlameshotDBusAdapter() { FlameshotDBusAdapter::~FlameshotDBusAdapter() {}
} void
FlameshotDBusAdapter::graphicCapture(QString path, int delay, uint id)
void FlameshotDBusAdapter::graphicCapture(QString path, int delay, uint id) { {
CaptureRequest req(CaptureRequest::GRAPHICAL_MODE, delay, path); CaptureRequest req(CaptureRequest::GRAPHICAL_MODE, delay, path);
// if (toClipboard) { // if (toClipboard) {
// req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); // req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK);
// } // }
req.setStaticID(id); req.setStaticID(id);
Controller::getInstance()->requestCapture(req); Controller::getInstance()->requestCapture(req);
} }
void FlameshotDBusAdapter::fullScreen( void
QString path, bool toClipboard, int delay, uint id) FlameshotDBusAdapter::fullScreen(QString path,
bool toClipboard,
int delay,
uint id)
{ {
CaptureRequest req(CaptureRequest::FULLSCREEN_MODE, delay, path); CaptureRequest req(CaptureRequest::FULLSCREEN_MODE, delay, path);
if (toClipboard) { if (toClipboard) {
@@ -59,12 +66,18 @@ void FlameshotDBusAdapter::fullScreen(
Controller::getInstance()->requestCapture(req); Controller::getInstance()->requestCapture(req);
} }
void FlameshotDBusAdapter::openLauncher() { void
FlameshotDBusAdapter::openLauncher()
{
Controller::getInstance()->openLauncherWindow(); Controller::getInstance()->openLauncherWindow();
} }
void FlameshotDBusAdapter::captureScreen(int number, QString path, void
bool toClipboard, int delay, uint id) FlameshotDBusAdapter::captureScreen(int number,
QString path,
bool toClipboard,
int delay,
uint id)
{ {
CaptureRequest req(CaptureRequest::SCREEN_MODE, delay, path, number); CaptureRequest req(CaptureRequest::SCREEN_MODE, delay, path, number);
if (toClipboard) { if (toClipboard) {
@@ -77,11 +90,15 @@ void FlameshotDBusAdapter::captureScreen(int number, QString path,
Controller::getInstance()->requestCapture(req); Controller::getInstance()->requestCapture(req);
} }
void FlameshotDBusAdapter::openConfig() { void
FlameshotDBusAdapter::openConfig()
{
Controller::getInstance()->openConfigWindow(); Controller::getInstance()->openConfigWindow();
} }
void FlameshotDBusAdapter::trayIconEnabled(bool enabled) { void
FlameshotDBusAdapter::trayIconEnabled(bool enabled)
{
auto controller = Controller::getInstance(); auto controller = Controller::getInstance();
if (enabled) { if (enabled) {
controller->enableTrayIcon(); controller->enableTrayIcon();
@@ -90,14 +107,18 @@ void FlameshotDBusAdapter::trayIconEnabled(bool enabled) {
} }
} }
void FlameshotDBusAdapter::autostartEnabled(bool enabled) { void
FlameshotDBusAdapter::autostartEnabled(bool enabled)
{
ConfigHandler().setStartupLaunch(enabled); ConfigHandler().setStartupLaunch(enabled);
auto controller = Controller::getInstance(); auto controller = Controller::getInstance();
// Autostart is not saved in a .ini file, requires manual update // Autostart is not saved in a .ini file, requires manual update
controller->updateConfigComponents(); controller->updateConfigComponents();
} }
void FlameshotDBusAdapter::handleCaptureTaken(uint id, const QPixmap &p) { void
FlameshotDBusAdapter::handleCaptureTaken(uint id, const QPixmap& p)
{
QByteArray byteArray; QByteArray byteArray;
QBuffer buffer(&byteArray); QBuffer buffer(&byteArray);
p.save(&buffer, "PNG"); p.save(&buffer, "PNG");

View File

@@ -17,15 +17,16 @@
#pragma once #pragma once
#include <QtDBus/QDBusAbstractAdaptor>
#include "src/core/controller.h" #include "src/core/controller.h"
#include <QtDBus/QDBusAbstractAdaptor>
class FlameshotDBusAdapter : public QDBusAbstractAdaptor { class FlameshotDBusAdapter : public QDBusAbstractAdaptor
{
Q_OBJECT Q_OBJECT
Q_CLASSINFO("D-Bus Interface", "org.dharkael.Flameshot") Q_CLASSINFO("D-Bus Interface", "org.dharkael.Flameshot")
public: public:
explicit FlameshotDBusAdapter(QObject *parent = nullptr); explicit FlameshotDBusAdapter(QObject* parent = nullptr);
virtual ~FlameshotDBusAdapter(); virtual ~FlameshotDBusAdapter();
signals: signals:
@@ -35,12 +36,16 @@ signals:
public slots: public slots:
Q_NOREPLY void graphicCapture(QString path, int delay, uint id); Q_NOREPLY void graphicCapture(QString path, int delay, uint id);
Q_NOREPLY void fullScreen(QString path, bool toClipboard, int delay, uint id); Q_NOREPLY void fullScreen(QString path, bool toClipboard, int delay, uint id);
Q_NOREPLY void captureScreen(int number, QString path, bool toClipboard, int delay, uint id); Q_NOREPLY void captureScreen(int number,
QString path,
bool toClipboard,
int delay,
uint id);
Q_NOREPLY void openLauncher(); Q_NOREPLY void openLauncher();
Q_NOREPLY void openConfig(); Q_NOREPLY void openConfig();
Q_NOREPLY void trayIconEnabled(bool enabled); Q_NOREPLY void trayIconEnabled(bool enabled);
Q_NOREPLY void autostartEnabled(bool enabled); Q_NOREPLY void autostartEnabled(bool enabled);
private slots: private slots:
void handleCaptureTaken(uint id, const QPixmap &p); void handleCaptureTaken(uint id, const QPixmap& p);
}; };

View File

@@ -19,8 +19,8 @@
#include "src/core/controller.h" #include "src/core/controller.h"
#include <qt_windows.h> #include <qt_windows.h>
GlobalShortcutFilter::GlobalShortcutFilter(QObject *parent) : GlobalShortcutFilter::GlobalShortcutFilter(QObject* parent)
QObject(parent) : QObject(parent)
{ {
// Forced Print Screen // Forced Print Screen
if (RegisterHotKey(NULL, 1, 0, VK_SNAPSHOT)) { if (RegisterHotKey(NULL, 1, 0, VK_SNAPSHOT)) {
@@ -28,18 +28,18 @@ GlobalShortcutFilter::GlobalShortcutFilter(QObject *parent) :
} }
} }
bool GlobalShortcutFilter::nativeEventFilter( bool
const QByteArray &eventType, GlobalShortcutFilter::nativeEventFilter(const QByteArray& eventType,
void *message, void* message,
long *result) long* result)
{ {
Q_UNUSED(eventType); Q_UNUSED(eventType);
Q_UNUSED(result); Q_UNUSED(result);
MSG* msg = static_cast<MSG*>(message); MSG* msg = static_cast<MSG*>(message);
if (msg->message == WM_HOTKEY) { if (msg->message == WM_HOTKEY) {
//const quint32 keycode = HIWORD(msg->lParam); // const quint32 keycode = HIWORD(msg->lParam);
//const quint32 modifiers = LOWORD(msg->lParam); // const quint32 modifiers = LOWORD(msg->lParam);
// TODO: this is just a temporal workwrround, proper global // TODO: this is just a temporal workwrround, proper global
// support would need custom shortcuts defined by the user. // support would need custom shortcuts defined by the user.

View File

@@ -17,15 +17,20 @@
#pragma once #pragma once
#include <QObject>
#include <QAbstractNativeEventFilter> #include <QAbstractNativeEventFilter>
#include <QObject>
class GlobalShortcutFilter : public QObject, public QAbstractNativeEventFilter { class GlobalShortcutFilter
: public QObject
, public QAbstractNativeEventFilter
{
Q_OBJECT Q_OBJECT
public: public:
explicit GlobalShortcutFilter(QObject *parent = nullptr); explicit GlobalShortcutFilter(QObject* parent = nullptr);
bool nativeEventFilter(const QByteArray &eventType, void *message, long *result); bool nativeEventFilter(const QByteArray& eventType,
void* message,
long* result);
signals: signals:
void printPressed(); void printPressed();

View File

@@ -15,32 +15,34 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "src/core/controller.h"
#include "singleapplication.h" #include "singleapplication.h"
#include "src/utils/filenamehandler.h"
#include "src/utils/confighandler.h"
#include "src/cli/commandlineparser.h" #include "src/cli/commandlineparser.h"
#include "src/utils/systemnotification.h"
#include "src/utils/pathinfo.h"
#include "src/core/capturerequest.h" #include "src/core/capturerequest.h"
#include "src/core/controller.h"
#include "src/utils/confighandler.h"
#include "src/utils/filenamehandler.h"
#include "src/utils/pathinfo.h"
#include "src/utils/systemnotification.h"
#include <QApplication> #include <QApplication>
#include <QDir>
#include <QLibraryInfo> #include <QLibraryInfo>
#include <QTranslator>
#include <QTextStream> #include <QTextStream>
#include <QTimer> #include <QTimer>
#include <QDir> #include <QTranslator>
#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX)
#include "src/core/flameshotdbusadapter.h" #include "src/core/flameshotdbusadapter.h"
#include "src/utils/dbusutils.h" #include "src/utils/dbusutils.h"
#include <QDBusMessage>
#include <QDBusConnection> #include <QDBusConnection>
#include <QDBusMessage>
#endif #endif
int main(int argc, char *argv[]) { int
main(int argc, char* argv[])
{
// required for the button serialization // required for the button serialization
// TODO: change to QVector in v1.0 // TODO: change to QVector in v1.0
qRegisterMetaTypeStreamOperators<QList<int> >("QList<int>"); qRegisterMetaTypeStreamOperators<QList<int>>("QList<int>");
qApp->setApplicationVersion(static_cast<QString>(APP_VERSION)); qApp->setApplicationVersion(static_cast<QString>(APP_VERSION));
// no arguments, just launch Flameshot // no arguments, just launch Flameshot
@@ -50,16 +52,19 @@ int main(int argc, char *argv[]) {
QTranslator translator, qtTranslator; QTranslator translator, qtTranslator;
QStringList trPaths = PathInfo::translationsPaths(); QStringList trPaths = PathInfo::translationsPaths();
for (const QString &path: trPaths) { for (const QString& path : trPaths) {
bool match = translator.load(QLocale(), bool match = translator.load(QLocale(),
QStringLiteral("Internationalization"), QStringLiteral("_"), QStringLiteral("Internationalization"),
QStringLiteral("_"),
path); path);
if (match) { if (match) {
break; break;
} }
} }
qtTranslator.load(QLocale::system(), "qt", "_", qtTranslator.load(QLocale::system(),
"qt",
"_",
QLibraryInfo::location(QLibraryInfo::TranslationsPath)); QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(&translator); app.installTranslator(&translator);
@@ -99,58 +104,60 @@ int main(int argc, char *argv[]) {
QStringLiteral("Powerful yet simple to use screenshot software.")); QStringLiteral("Powerful yet simple to use screenshot software."));
parser.setGeneralErrorMessage(QStringLiteral("See 'flameshot --help'.")); parser.setGeneralErrorMessage(QStringLiteral("See 'flameshot --help'."));
// Arguments // Arguments
CommandArgument fullArgument(QStringLiteral("full"), QStringLiteral("Capture the entire desktop.")); CommandArgument fullArgument(QStringLiteral("full"),
CommandArgument launcherArgument(QStringLiteral("launcher"), QStringLiteral("Open the capture launcher.")); QStringLiteral("Capture the entire desktop."));
CommandArgument guiArgument(QStringLiteral("gui"), QStringLiteral("Start a manual capture in GUI mode.")); CommandArgument launcherArgument(
CommandArgument configArgument(QStringLiteral("config"), QStringLiteral("Configure flameshot.")); QStringLiteral("launcher"), QStringLiteral("Open the capture launcher."));
CommandArgument screenArgument(QStringLiteral("screen"), QStringLiteral("Capture a single screen.")); CommandArgument guiArgument(
QStringLiteral("gui"),
QStringLiteral("Start a manual capture in GUI mode."));
CommandArgument configArgument(QStringLiteral("config"),
QStringLiteral("Configure flameshot."));
CommandArgument screenArgument(QStringLiteral("screen"),
QStringLiteral("Capture a single screen."));
// Options // Options
CommandOption pathOption( CommandOption pathOption(
{"p", "path"}, { "p", "path" },
QStringLiteral("Path where the capture will be saved"), QStringLiteral("Path where the capture will be saved"),
QStringLiteral("path")); QStringLiteral("path"));
CommandOption clipboardOption( CommandOption clipboardOption(
{"c", "clipboard"}, { "c", "clipboard" }, QStringLiteral("Save the capture to the clipboard"));
QStringLiteral("Save the capture to the clipboard")); CommandOption delayOption({ "d", "delay" },
CommandOption delayOption(
{"d", "delay"},
QStringLiteral("Delay time in milliseconds"), QStringLiteral("Delay time in milliseconds"),
QStringLiteral("milliseconds")); QStringLiteral("milliseconds"));
CommandOption filenameOption( CommandOption filenameOption({ "f", "filename" },
{"f", "filename"},
QStringLiteral("Set the filename pattern"), QStringLiteral("Set the filename pattern"),
QStringLiteral("pattern")); QStringLiteral("pattern"));
CommandOption trayOption( CommandOption trayOption({ "t", "trayicon" },
{"t", "trayicon"},
QStringLiteral("Enable or disable the trayicon"), QStringLiteral("Enable or disable the trayicon"),
QStringLiteral("bool")); QStringLiteral("bool"));
CommandOption autostartOption( CommandOption autostartOption(
{"a", "autostart"}, { "a", "autostart" },
QStringLiteral("Enable or disable run at startup"), QStringLiteral("Enable or disable run at startup"),
QStringLiteral("bool")); QStringLiteral("bool"));
CommandOption showHelpOption( CommandOption showHelpOption(
{"s", "showhelp"}, { "s", "showhelp" },
QStringLiteral("Show the help message in the capture mode"), QStringLiteral("Show the help message in the capture mode"),
QStringLiteral("bool")); QStringLiteral("bool"));
CommandOption mainColorOption( CommandOption mainColorOption({ "m", "maincolor" },
{"m", "maincolor"},
QStringLiteral("Define the main UI color"), QStringLiteral("Define the main UI color"),
QStringLiteral("color-code")); QStringLiteral("color-code"));
CommandOption contrastColorOption( CommandOption contrastColorOption(
{"k", "contrastcolor"}, { "k", "contrastcolor" },
QStringLiteral("Define the contrast UI color"), QStringLiteral("Define the contrast UI color"),
QStringLiteral("color-code")); QStringLiteral("color-code"));
CommandOption rawImageOption( CommandOption rawImageOption({ "r", "raw" },
{"r", "raw"},
QStringLiteral("Print raw PNG capture")); QStringLiteral("Print raw PNG capture"));
CommandOption screenNumberOption( CommandOption screenNumberOption(
{"n", "number"}, { "n", "number" },
QStringLiteral("Define the screen to capture,\ndefault: screen containing the cursor"), QStringLiteral(
QStringLiteral("Screen number"), QStringLiteral("-1")); "Define the screen to capture,\ndefault: screen containing the cursor"),
QStringLiteral("Screen number"),
QStringLiteral("-1"));
// Add checkers // Add checkers
auto colorChecker = [](const QString &colorCode) -> bool { auto colorChecker = [](const QString& colorCode) -> bool {
QColor parsedColor(colorCode); QColor parsedColor(colorCode);
return parsedColor.isValid() && parsedColor.alphaF() == 1.0; return parsedColor.isValid() && parsedColor.alphaF() == 1.0;
}; };
@@ -162,15 +169,18 @@ int main(int argc, char *argv[]) {
"- Named colors like 'blue' or 'red'\n" "- Named colors like 'blue' or 'red'\n"
"You may need to escape the '#' sign as in '\\#FFF'"; "You may need to escape the '#' sign as in '\\#FFF'";
const QString delayErr = QStringLiteral("Invalid delay, it must be higher than 0"); const QString delayErr =
const QString numberErr = QStringLiteral("Invalid screen number, it must be non negative"); QStringLiteral("Invalid delay, it must be higher than 0");
auto numericChecker = [](const QString &delayValue) -> bool { const QString numberErr =
QStringLiteral("Invalid screen number, it must be non negative");
auto numericChecker = [](const QString& delayValue) -> bool {
int value = delayValue.toInt(); int value = delayValue.toInt();
return value >= 0; return value >= 0;
}; };
const QString pathErr = QStringLiteral("Invalid path, it must be a real path in the system"); const QString pathErr =
auto pathChecker = [pathErr](const QString &pathValue) -> bool { QStringLiteral("Invalid path, it must be a real path in the system");
auto pathChecker = [pathErr](const QString& pathValue) -> bool {
bool res = QDir(pathValue).exists(); bool res = QDir(pathValue).exists();
if (!res) { if (!res) {
SystemNotification().sendMessage(QObject::tr(pathErr.toLatin1().data())); SystemNotification().sendMessage(QObject::tr(pathErr.toLatin1().data()));
@@ -178,8 +188,9 @@ int main(int argc, char *argv[]) {
return res; return res;
}; };
const QString booleanErr = QStringLiteral("Invalid value, it must be defined as 'true' or 'false'"); const QString booleanErr =
auto booleanChecker = [](const QString &value) -> bool { QStringLiteral("Invalid value, it must be defined as 'true' or 'false'");
auto booleanChecker = [](const QString& value) -> bool {
return value == QLatin1String("true") || value == QLatin1String("false"); return value == QLatin1String("true") || value == QLatin1String("false");
}; };
@@ -201,13 +212,20 @@ int main(int argc, char *argv[]) {
auto helpOption = parser.addHelpOption(); auto helpOption = parser.addHelpOption();
auto versionOption = parser.addVersionOption(); auto versionOption = parser.addVersionOption();
parser.AddOptions({ pathOption, delayOption, rawImageOption }, guiArgument); parser.AddOptions({ pathOption, delayOption, rawImageOption }, guiArgument);
parser.AddOptions({ screenNumberOption, clipboardOption, pathOption, parser.AddOptions({ screenNumberOption,
delayOption, rawImageOption }, clipboardOption,
pathOption,
delayOption,
rawImageOption },
screenArgument); screenArgument);
parser.AddOptions({ pathOption, clipboardOption, delayOption, rawImageOption }, parser.AddOptions(
fullArgument); { pathOption, clipboardOption, delayOption, rawImageOption }, fullArgument);
parser.AddOptions({ autostartOption, filenameOption, trayOption, parser.AddOptions({ autostartOption,
showHelpOption, mainColorOption, contrastColorOption }, filenameOption,
trayOption,
showHelpOption,
mainColorOption,
contrastColorOption },
configArgument); configArgument);
// Parse // Parse
if (!parser.parse(app.arguments())) { if (!parser.parse(app.arguments())) {
@@ -217,18 +235,19 @@ int main(int argc, char *argv[]) {
// PROCESS DATA // PROCESS DATA
//-------------- //--------------
if (parser.isSet(helpOption) || parser.isSet(versionOption)) { if (parser.isSet(helpOption) || parser.isSet(versionOption)) {
} } else if (parser.isSet(launcherArgument)) { // LAUNCHER
else if (parser.isSet(launcherArgument)) { // LAUNCHER QDBusMessage m =
QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"),
QStringLiteral("/"), QLatin1String(""), QStringLiteral("openLauncher")); QStringLiteral("/"),
QLatin1String(""),
QStringLiteral("openLauncher"));
QDBusConnection sessionBus = QDBusConnection::sessionBus(); QDBusConnection sessionBus = QDBusConnection::sessionBus();
if (!sessionBus.isConnected()) { if (!sessionBus.isConnected()) {
SystemNotification().sendMessage( SystemNotification().sendMessage(
QObject::tr("Unable to connect via DBus")); QObject::tr("Unable to connect via DBus"));
} }
sessionBus.call(m); sessionBus.call(m);
} } else if (parser.isSet(guiArgument)) { // GUI
else if (parser.isSet(guiArgument)) { // GUI
QString pathValue = parser.value(pathOption); QString pathValue = parser.value(pathOption);
int delay = parser.value(delayOption).toInt(); int delay = parser.value(delayOption).toInt();
bool isRaw = parser.isSet(rawImageOption); bool isRaw = parser.isSet(rawImageOption);
@@ -237,8 +256,11 @@ int main(int argc, char *argv[]) {
uint id = req.id(); uint id = req.id();
// Send message // Send message
QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), QDBusMessage m =
QStringLiteral("/"), QLatin1String(""), QStringLiteral("graphicCapture")); QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"),
QStringLiteral("/"),
QLatin1String(""),
QStringLiteral("graphicCapture"));
m << pathValue << delay << id; m << pathValue << delay << id;
QDBusConnection sessionBus = QDBusConnection::sessionBus(); QDBusConnection sessionBus = QDBusConnection::sessionBus();
dbusUtils.checkDBusConnection(sessionBus); dbusUtils.checkDBusConnection(sessionBus);
@@ -248,14 +270,12 @@ int main(int argc, char *argv[]) {
dbusUtils.connectPrintCapture(sessionBus, id); dbusUtils.connectPrintCapture(sessionBus, id);
QTimer t; QTimer t;
t.setInterval(delay + 1000 * 60 * 15); // 15 minutes timeout t.setInterval(delay + 1000 * 60 * 15); // 15 minutes timeout
QObject::connect(&t, &QTimer::timeout, qApp, QObject::connect(&t, &QTimer::timeout, qApp, &QCoreApplication::quit);
&QCoreApplication::quit);
t.start(); t.start();
// wait // wait
return app.exec(); return app.exec();
} }
} } else if (parser.isSet(fullArgument)) { // FULL
else if (parser.isSet(fullArgument)) { // FULL
QString pathValue = parser.value(pathOption); QString pathValue = parser.value(pathOption);
int delay = parser.value(delayOption).toInt(); int delay = parser.value(delayOption).toInt();
bool toClipboard = parser.isSet(clipboardOption); bool toClipboard = parser.isSet(clipboardOption);
@@ -268,7 +288,8 @@ int main(int argc, char *argv[]) {
<< pathOption.dashedNames().join(QStringLiteral(", ")) << "\n " << pathOption.dashedNames().join(QStringLiteral(", ")) << "\n "
<< rawImageOption.dashedNames().join(QStringLiteral(", ")) << "\n " << rawImageOption.dashedNames().join(QStringLiteral(", ")) << "\n "
<< clipboardOption.dashedNames().join(QStringLiteral(", ")) << "\n\n"; << clipboardOption.dashedNames().join(QStringLiteral(", ")) << "\n\n";
parser.parse(QStringList() << argv[0] << QStringLiteral("full") << QStringLiteral("-h")); parser.parse(QStringList() << argv[0] << QStringLiteral("full")
<< QStringLiteral("-h"));
goto finish; goto finish;
} }
@@ -283,8 +304,11 @@ int main(int argc, char *argv[]) {
DBusUtils dbusUtils; DBusUtils dbusUtils;
// Send message // Send message
QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), QDBusMessage m =
QStringLiteral("/"), QLatin1String(""), QStringLiteral("fullScreen")); QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"),
QStringLiteral("/"),
QLatin1String(""),
QStringLiteral("fullScreen"));
m << pathValue << toClipboard << delay << id; m << pathValue << toClipboard << delay << id;
QDBusConnection sessionBus = QDBusConnection::sessionBus(); QDBusConnection sessionBus = QDBusConnection::sessionBus();
dbusUtils.checkDBusConnection(sessionBus); dbusUtils.checkDBusConnection(sessionBus);
@@ -295,16 +319,15 @@ int main(int argc, char *argv[]) {
// timeout just in case // timeout just in case
QTimer t; QTimer t;
t.setInterval(delay + 2000); t.setInterval(delay + 2000);
QObject::connect(&t, &QTimer::timeout, qApp, QObject::connect(&t, &QTimer::timeout, qApp, &QCoreApplication::quit);
&QCoreApplication::quit);
t.start(); t.start();
// wait // wait
return app.exec(); return app.exec();
} }
} } else if (parser.isSet(screenArgument)) { // SCREEN
else if (parser.isSet(screenArgument)) { // SCREEN
QString numberStr = parser.value(screenNumberOption); QString numberStr = parser.value(screenNumberOption);
int number = numberStr.startsWith(QLatin1String("-")) ? -1 : numberStr.toInt(); int number =
numberStr.startsWith(QLatin1String("-")) ? -1 : numberStr.toInt();
QString pathValue = parser.value(pathOption); QString pathValue = parser.value(pathOption);
int delay = parser.value(delayOption).toInt(); int delay = parser.value(delayOption).toInt();
bool toClipboard = parser.isSet(clipboardOption); bool toClipboard = parser.isSet(clipboardOption);
@@ -317,12 +340,12 @@ int main(int argc, char *argv[]) {
<< pathOption.dashedNames().join(QStringLiteral(", ")) << "\n " << pathOption.dashedNames().join(QStringLiteral(", ")) << "\n "
<< rawImageOption.dashedNames().join(QStringLiteral(", ")) << "\n " << rawImageOption.dashedNames().join(QStringLiteral(", ")) << "\n "
<< clipboardOption.dashedNames().join(QStringLiteral(", ")) << "\n\n"; << clipboardOption.dashedNames().join(QStringLiteral(", ")) << "\n\n";
parser.parse(QStringList() << argv[0] << QStringLiteral("screen") << QStringLiteral("-h")); parser.parse(QStringList() << argv[0] << QStringLiteral("screen")
<< QStringLiteral("-h"));
goto finish; goto finish;
} }
CaptureRequest req(CaptureRequest::SCREEN_MODE, CaptureRequest req(CaptureRequest::SCREEN_MODE, delay, pathValue, number);
delay, pathValue, number);
if (toClipboard) { if (toClipboard) {
req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK);
} }
@@ -333,8 +356,11 @@ int main(int argc, char *argv[]) {
DBusUtils dbusUtils; DBusUtils dbusUtils;
// Send message // Send message
QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), QDBusMessage m =
QStringLiteral("/"), QLatin1String(""), QStringLiteral("captureScreen")); QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"),
QStringLiteral("/"),
QLatin1String(""),
QStringLiteral("captureScreen"));
m << number << pathValue << toClipboard << delay << id; m << number << pathValue << toClipboard << delay << id;
QDBusConnection sessionBus = QDBusConnection::sessionBus(); QDBusConnection sessionBus = QDBusConnection::sessionBus();
dbusUtils.checkDBusConnection(sessionBus); dbusUtils.checkDBusConnection(sessionBus);
@@ -345,26 +371,26 @@ int main(int argc, char *argv[]) {
// timeout just in case // timeout just in case
QTimer t; QTimer t;
t.setInterval(delay + 2000); t.setInterval(delay + 2000);
QObject::connect(&t, &QTimer::timeout, qApp, QObject::connect(&t, &QTimer::timeout, qApp, &QCoreApplication::quit);
&QCoreApplication::quit);
t.start(); t.start();
// wait // wait
return app.exec(); return app.exec();
} }
} } else if (parser.isSet(configArgument)) { // CONFIG
else if (parser.isSet(configArgument)) { // CONFIG
bool autostart = parser.isSet(autostartOption); bool autostart = parser.isSet(autostartOption);
bool filename = parser.isSet(filenameOption); bool filename = parser.isSet(filenameOption);
bool tray = parser.isSet(trayOption); bool tray = parser.isSet(trayOption);
bool help = parser.isSet(showHelpOption); bool help = parser.isSet(showHelpOption);
bool mainColor = parser.isSet(mainColorOption); bool mainColor = parser.isSet(mainColorOption);
bool contrastColor = parser.isSet(contrastColorOption); bool contrastColor = parser.isSet(contrastColorOption);
bool someFlagSet = (filename || tray || help || bool someFlagSet = (filename || tray || help || mainColor || contrastColor);
mainColor || contrastColor);
ConfigHandler config; ConfigHandler config;
if (autostart) { if (autostart) {
QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), QDBusMessage m =
QStringLiteral("/"), QLatin1String(""), QStringLiteral("autostartEnabled")); QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"),
QStringLiteral("/"),
QLatin1String(""),
QStringLiteral("autostartEnabled"));
if (parser.value(autostartOption) == QLatin1String("false")) { if (parser.value(autostartOption) == QLatin1String("false")) {
m << false; m << false;
} else if (parser.value(autostartOption) == QLatin1String("true")) { } else if (parser.value(autostartOption) == QLatin1String("true")) {
@@ -381,14 +407,17 @@ int main(int argc, char *argv[]) {
QString newFilename(parser.value(filenameOption)); QString newFilename(parser.value(filenameOption));
config.setFilenamePattern(newFilename); config.setFilenamePattern(newFilename);
FileNameHandler fh; FileNameHandler fh;
QTextStream(stdout) QTextStream(stdout) << QStringLiteral("The new pattern is '%1'\n"
<< QStringLiteral("The new pattern is '%1'\n" "Parsed pattern example: %2\n")
"Parsed pattern example: %2\n").arg(newFilename) .arg(newFilename)
.arg(fh.parsedPattern()); .arg(fh.parsedPattern());
} }
if (tray) { if (tray) {
QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), QDBusMessage m =
QStringLiteral("/"), QLatin1String(""), QStringLiteral("trayIconEnabled")); QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"),
QStringLiteral("/"),
QLatin1String(""),
QStringLiteral("trayIconEnabled"));
if (parser.value(trayOption) == QLatin1String("false")) { if (parser.value(trayOption) == QLatin1String("false")) {
m << false; m << false;
} else if (parser.value(trayOption) == QLatin1String("true")) { } else if (parser.value(trayOption) == QLatin1String("true")) {
@@ -421,8 +450,11 @@ int main(int argc, char *argv[]) {
// Open gui when no options // Open gui when no options
if (!someFlagSet) { if (!someFlagSet) {
QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), QDBusMessage m =
QStringLiteral("/"), QLatin1String(""), QStringLiteral("openConfig")); QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"),
QStringLiteral("/"),
QLatin1String(""),
QStringLiteral("openConfig"));
QDBusConnection sessionBus = QDBusConnection::sessionBus(); QDBusConnection sessionBus = QDBusConnection::sessionBus();
if (!sessionBus.isConnected()) { if (!sessionBus.isConnected()) {
SystemNotification().sendMessage( SystemNotification().sendMessage(

View File

@@ -17,55 +17,78 @@
#include "abstractactiontool.h" #include "abstractactiontool.h"
AbstractActionTool::AbstractActionTool(QObject *parent) : CaptureTool(parent) { AbstractActionTool::AbstractActionTool(QObject* parent)
: CaptureTool(parent)
{}
} bool
AbstractActionTool::isValid() const
bool AbstractActionTool::isValid() const { {
return true; return true;
} }
bool AbstractActionTool::isSelectable() const { bool
AbstractActionTool::isSelectable() const
{
return false; return false;
} }
bool AbstractActionTool::showMousePreview() const { bool
AbstractActionTool::showMousePreview() const
{
return false; return false;
} }
void AbstractActionTool::undo(QPixmap &pixmap) { void
AbstractActionTool::undo(QPixmap& pixmap)
{
Q_UNUSED(pixmap); Q_UNUSED(pixmap);
} }
void AbstractActionTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { void
AbstractActionTool::process(QPainter& painter,
const QPixmap& pixmap,
bool recordUndo)
{
Q_UNUSED(painter); Q_UNUSED(painter);
Q_UNUSED(pixmap); Q_UNUSED(pixmap);
Q_UNUSED(recordUndo); Q_UNUSED(recordUndo);
} }
void AbstractActionTool::paintMousePreview( void
QPainter &painter, const CaptureContext &context) AbstractActionTool::paintMousePreview(QPainter& painter,
const CaptureContext& context)
{ {
Q_UNUSED(painter); Q_UNUSED(painter);
Q_UNUSED(context); Q_UNUSED(context);
} }
void AbstractActionTool::drawEnd(const QPoint &p) { void
AbstractActionTool::drawEnd(const QPoint& p)
{
Q_UNUSED(p); Q_UNUSED(p);
} }
void AbstractActionTool::drawMove(const QPoint &p) { void
AbstractActionTool::drawMove(const QPoint& p)
{
Q_UNUSED(p); Q_UNUSED(p);
} }
void AbstractActionTool::drawStart(const CaptureContext &context) { void
AbstractActionTool::drawStart(const CaptureContext& context)
{
Q_UNUSED(context); Q_UNUSED(context);
} }
void AbstractActionTool::colorChanged(const QColor &c) { void
AbstractActionTool::colorChanged(const QColor& c)
{
Q_UNUSED(c); Q_UNUSED(c);
} }
void AbstractActionTool::thicknessChanged(const int th) { void
AbstractActionTool::thicknessChanged(const int th)
{
Q_UNUSED(th); Q_UNUSED(th);
} }

View File

@@ -19,23 +19,27 @@
#include "capturetool.h" #include "capturetool.h"
class AbstractActionTool : public CaptureTool { class AbstractActionTool : public CaptureTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit AbstractActionTool(QObject *parent = nullptr); explicit AbstractActionTool(QObject* parent = nullptr);
bool isValid() const override; bool isValid() const override;
bool isSelectable() const override; bool isSelectable() const override;
bool showMousePreview() const override; bool showMousePreview() const override;
void undo(QPixmap &pixmap) override; void undo(QPixmap& pixmap) override;
void process(QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; void process(QPainter& painter,
void paintMousePreview(QPainter &painter, const CaptureContext &context) override; const QPixmap& pixmap,
bool recordUndo = false) override;
void paintMousePreview(QPainter& painter,
const CaptureContext& context) override;
public slots: public slots:
void drawEnd(const QPoint &p) override; void drawEnd(const QPoint& p) override;
void drawMove(const QPoint &p) override; void drawMove(const QPoint& p) override;
void drawStart(const CaptureContext &context) override; void drawStart(const CaptureContext& context) override;
void colorChanged(const QColor &c) override; void colorChanged(const QColor& c) override;
void thicknessChanged(const int th) override; void thicknessChanged(const int th) override;
}; };

View File

@@ -17,59 +17,80 @@
#include "abstractpathtool.h" #include "abstractpathtool.h"
AbstractPathTool::AbstractPathTool(QObject *parent) : AbstractPathTool::AbstractPathTool(QObject* parent)
CaptureTool(parent), m_thickness(0), m_padding(0) : CaptureTool(parent)
, m_thickness(0)
, m_padding(0)
{}
bool
AbstractPathTool::isValid() const
{ {
}
bool AbstractPathTool::isValid() const {
return m_points.length() > 1; return m_points.length() > 1;
} }
bool AbstractPathTool::closeOnButtonPressed() const { bool
AbstractPathTool::closeOnButtonPressed() const
{
return false; return false;
} }
bool AbstractPathTool::isSelectable() const { bool
AbstractPathTool::isSelectable() const
{
return true; return true;
} }
bool AbstractPathTool::showMousePreview() const { bool
AbstractPathTool::showMousePreview() const
{
return true; return true;
} }
void AbstractPathTool::undo(QPixmap &pixmap) { void
AbstractPathTool::undo(QPixmap& pixmap)
{
QPainter p(&pixmap); QPainter p(&pixmap);
const int val = m_thickness + m_padding; const int val = m_thickness + m_padding;
QRect area = m_backupArea + QMargins(val, val, val, val); QRect area = m_backupArea + QMargins(val, val, val, val);
p.drawPixmap(area.intersected(pixmap.rect()) p.drawPixmap(area.intersected(pixmap.rect()).topLeft(), m_pixmapBackup);
.topLeft(), m_pixmapBackup);
} }
void AbstractPathTool::drawEnd(const QPoint &p) { void
AbstractPathTool::drawEnd(const QPoint& p)
{
Q_UNUSED(p); Q_UNUSED(p);
} }
void AbstractPathTool::drawMove(const QPoint &p) { void
AbstractPathTool::drawMove(const QPoint& p)
{
addPoint(p); addPoint(p);
} }
void AbstractPathTool::colorChanged(const QColor &c) { void
AbstractPathTool::colorChanged(const QColor& c)
{
m_color = c; m_color = c;
} }
void AbstractPathTool::thicknessChanged(const int th) { void
AbstractPathTool::thicknessChanged(const int th)
{
m_thickness = th; m_thickness = th;
} }
void AbstractPathTool::updateBackup(const QPixmap &pixmap) { void
AbstractPathTool::updateBackup(const QPixmap& pixmap)
{
const int val = m_thickness + m_padding; const int val = m_thickness + m_padding;
QRect area = m_backupArea.normalized() + QMargins(val, val, val, val); QRect area = m_backupArea.normalized() + QMargins(val, val, val, val);
m_pixmapBackup = pixmap.copy(area); m_pixmapBackup = pixmap.copy(area);
} }
void AbstractPathTool::addPoint(const QPoint &point) { void
AbstractPathTool::addPoint(const QPoint& point)
{
if (m_backupArea.left() > point.x()) { if (m_backupArea.left() > point.x()) {
m_backupArea.setLeft(point.x()); m_backupArea.setLeft(point.x());
} else if (m_backupArea.right() < point.x()) { } else if (m_backupArea.right() < point.x()) {

View File

@@ -19,27 +19,28 @@
#include "capturetool.h" #include "capturetool.h"
class AbstractPathTool : public CaptureTool { class AbstractPathTool : public CaptureTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit AbstractPathTool(QObject *parent = nullptr); explicit AbstractPathTool(QObject* parent = nullptr);
bool isValid() const override; bool isValid() const override;
bool closeOnButtonPressed() const override; bool closeOnButtonPressed() const override;
bool isSelectable() const override; bool isSelectable() const override;
bool showMousePreview() const override; bool showMousePreview() const override;
void undo(QPixmap &pixmap) override; void undo(QPixmap& pixmap) override;
public slots: public slots:
void drawEnd(const QPoint &p) override; void drawEnd(const QPoint& p) override;
void drawMove(const QPoint &p) override; void drawMove(const QPoint& p) override;
void colorChanged(const QColor &c) override; void colorChanged(const QColor& c) override;
void thicknessChanged(const int th) override; void thicknessChanged(const int th) override;
protected: protected:
void updateBackup(const QPixmap &pixmap); void updateBackup(const QPixmap& pixmap);
void addPoint(const QPoint &point); void addPoint(const QPoint& point);
QPixmap m_pixmapBackup; QPixmap m_pixmapBackup;
QRect m_backupArea; QRect m_backupArea;

View File

@@ -23,7 +23,8 @@ namespace {
const double ADJ_UNIT = std::atan(1.0); const double ADJ_UNIT = std::atan(1.0);
const int DIRS_NUMBER = 4; const int DIRS_NUMBER = 4;
enum UNIT { enum UNIT
{
HORIZ_DIR = 0, HORIZ_DIR = 0,
DIAG1_DIR = 1, DIAG1_DIR = 1,
VERT_DIR = 2, VERT_DIR = 2,
@@ -33,74 +34,103 @@ enum UNIT {
const double ADJ_DIAG_UNIT = 2 * ADJ_UNIT; const double ADJ_DIAG_UNIT = 2 * ADJ_UNIT;
const int DIAG_DIRS_NUMBER = 2; const int DIAG_DIRS_NUMBER = 2;
enum DIAG_UNIT { enum DIAG_UNIT
{
DIR1 = 0, DIR1 = 0,
DIR2 = 1 DIR2 = 1
}; };
} }
AbstractTwoPointTool::AbstractTwoPointTool(QObject *parent) : AbstractTwoPointTool::AbstractTwoPointTool(QObject* parent)
CaptureTool(parent), m_thickness(0), m_padding(0) : CaptureTool(parent)
, m_thickness(0)
, m_padding(0)
{}
bool
AbstractTwoPointTool::isValid() const
{ {
}
bool AbstractTwoPointTool::isValid() const {
return (m_points.first != m_points.second); return (m_points.first != m_points.second);
} }
bool AbstractTwoPointTool::closeOnButtonPressed() const { bool
AbstractTwoPointTool::closeOnButtonPressed() const
{
return false; return false;
} }
bool AbstractTwoPointTool::isSelectable() const { bool
AbstractTwoPointTool::isSelectable() const
{
return true; return true;
} }
bool AbstractTwoPointTool::showMousePreview() const { bool
AbstractTwoPointTool::showMousePreview() const
{
return true; return true;
} }
void AbstractTwoPointTool::undo(QPixmap &pixmap) { void
AbstractTwoPointTool::undo(QPixmap& pixmap)
{
QPainter p(&pixmap); QPainter p(&pixmap);
p.drawPixmap(backupRect(pixmap.rect()).topLeft(), m_pixmapBackup); p.drawPixmap(backupRect(pixmap.rect()).topLeft(), m_pixmapBackup);
} }
void AbstractTwoPointTool::drawEnd(const QPoint &p) { void
AbstractTwoPointTool::drawEnd(const QPoint& p)
{
Q_UNUSED(p); Q_UNUSED(p);
} }
void AbstractTwoPointTool::drawMove(const QPoint &p) { void
AbstractTwoPointTool::drawMove(const QPoint& p)
{
m_points.second = p; m_points.second = p;
} }
void AbstractTwoPointTool::drawMoveWithAdjustment(const QPoint &p) { void
AbstractTwoPointTool::drawMoveWithAdjustment(const QPoint& p)
{
m_points.second = m_points.first + adjustedVector(p - m_points.first); m_points.second = m_points.first + adjustedVector(p - m_points.first);
} }
void AbstractTwoPointTool::colorChanged(const QColor &c) { void
AbstractTwoPointTool::colorChanged(const QColor& c)
{
m_color = c; m_color = c;
} }
void AbstractTwoPointTool::thicknessChanged(const int th) { void
AbstractTwoPointTool::thicknessChanged(const int th)
{
m_thickness = th; m_thickness = th;
} }
void AbstractTwoPointTool::updateBackup(const QPixmap &pixmap) { void
AbstractTwoPointTool::updateBackup(const QPixmap& pixmap)
{
m_pixmapBackup = pixmap.copy(backupRect(pixmap.rect())); m_pixmapBackup = pixmap.copy(backupRect(pixmap.rect()));
} }
QRect AbstractTwoPointTool::backupRect(const QRect &limits) const { QRect
AbstractTwoPointTool::backupRect(const QRect& limits) const
{
QRect r = QRect(m_points.first, m_points.second).normalized(); QRect r = QRect(m_points.first, m_points.second).normalized();
const int val = m_thickness + m_padding; const int val = m_thickness + m_padding;
r += QMargins(val, val, val, val); r += QMargins(val, val, val, val);
return r.intersected(limits); return r.intersected(limits);
} }
QPoint AbstractTwoPointTool::adjustedVector(QPoint v) const { QPoint
AbstractTwoPointTool::adjustedVector(QPoint v) const
{
if (m_supportsOrthogonalAdj && m_supportsDiagonalAdj) { if (m_supportsOrthogonalAdj && m_supportsDiagonalAdj) {
int dir = ( static_cast<int>(round(atan2(-v.y(), v.x()) / ADJ_UNIT)) + DIRS_NUMBER ) % DIRS_NUMBER; int dir =
(static_cast<int>(round(atan2(-v.y(), v.x()) / ADJ_UNIT)) + DIRS_NUMBER) %
DIRS_NUMBER;
if (dir == UNIT::HORIZ_DIR) { if (dir == UNIT::HORIZ_DIR) {
v.setY(0); v.setY(0);
} else if (dir == UNIT::VERT_DIR) { } else if (dir == UNIT::VERT_DIR) {
@@ -117,8 +147,10 @@ QPoint AbstractTwoPointTool::adjustedVector(QPoint v) const {
v.setY(newY); v.setY(newY);
} }
} else if (m_supportsDiagonalAdj) { } else if (m_supportsDiagonalAdj) {
int dir = ( static_cast<int>(round((atan2(-v.y(), v.x()) - ADJ_DIAG_UNIT / 2) / ADJ_DIAG_UNIT)) int dir = (static_cast<int>(round(
+ DIAG_DIRS_NUMBER ) % DIAG_DIRS_NUMBER; (atan2(-v.y(), v.x()) - ADJ_DIAG_UNIT / 2) / ADJ_DIAG_UNIT)) +
DIAG_DIRS_NUMBER) %
DIAG_DIRS_NUMBER;
if (dir == DIAG_UNIT::DIR1) { if (dir == DIAG_UNIT::DIR1) {
int newX = (v.x() - v.y()) / 2; int newX = (v.x() - v.y()) / 2;
int newY = -newX; int newY = -newX;

View File

@@ -19,28 +19,29 @@
#include "capturetool.h" #include "capturetool.h"
class AbstractTwoPointTool : public CaptureTool { class AbstractTwoPointTool : public CaptureTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit AbstractTwoPointTool(QObject *parent = nullptr); explicit AbstractTwoPointTool(QObject* parent = nullptr);
bool isValid() const override; bool isValid() const override;
bool closeOnButtonPressed() const override; bool closeOnButtonPressed() const override;
bool isSelectable() const override; bool isSelectable() const override;
bool showMousePreview() const override; bool showMousePreview() const override;
void undo(QPixmap &pixmap) override; void undo(QPixmap& pixmap) override;
public slots: public slots:
void drawEnd(const QPoint &p) override; void drawEnd(const QPoint& p) override;
void drawMove(const QPoint &p) override; void drawMove(const QPoint& p) override;
void drawMoveWithAdjustment(const QPoint &p) override; void drawMoveWithAdjustment(const QPoint& p) override;
void colorChanged(const QColor &c) override; void colorChanged(const QColor& c) override;
void thicknessChanged(const int th) override; void thicknessChanged(const int th) override;
protected: protected:
void updateBackup(const QPixmap &pixmap); void updateBackup(const QPixmap& pixmap);
QRect backupRect(const QRect &limits) const; QRect backupRect(const QRect& limits) const;
QPixmap m_pixmapBackup; QPixmap m_pixmapBackup;
QPair<QPoint, QPoint> m_points; QPair<QPoint, QPoint> m_points;

View File

@@ -24,25 +24,27 @@ namespace {
const int ArrowWidth = 10; const int ArrowWidth = 10;
const int ArrowHeight = 18; const int ArrowHeight = 18;
QPainterPath getArrowHead(QPoint p1, QPoint p2, const int thickness) { QPainterPath
getArrowHead(QPoint p1, QPoint p2, const int thickness)
{
QLineF base(p1, p2); QLineF base(p1, p2);
// Create the vector for the position of the base of the arrowhead // Create the vector for the position of the base of the arrowhead
QLineF temp(QPoint(0,0), p2-p1); QLineF temp(QPoint(0, 0), p2 - p1);
int val = ArrowHeight + thickness*4; int val = ArrowHeight + thickness * 4;
if (base.length() < val) { if (base.length() < val) {
val = (base.length() + thickness*2); val = (base.length() + thickness * 2);
} }
temp.setLength(base.length() + thickness*2 - val); temp.setLength(base.length() + thickness * 2 - val);
// Move across the line up to the head // Move across the line up to the head
QPointF bottonTranslation(temp.p2()); QPointF bottonTranslation(temp.p2());
// Rotate base of the arrowhead // Rotate base of the arrowhead
base.setLength(ArrowWidth + thickness*2); base.setLength(ArrowWidth + thickness * 2);
base.setAngle(base.angle() + 90); base.setAngle(base.angle() + 90);
// Move to the correct point // Move to the correct point
QPointF temp2 = p1 - base.p2(); QPointF temp2 = p1 - base.p2();
// Center it // Center it
QPointF centerTranslation((temp2.x()/2), (temp2.y()/2)); QPointF centerTranslation((temp2.x() / 2), (temp2.y() / 2));
base.translate(bottonTranslation); base.translate(bottonTranslation);
base.translate(centerTranslation); base.translate(centerTranslation);
@@ -56,65 +58,89 @@ QPainterPath getArrowHead(QPoint p1, QPoint p2, const int thickness) {
} }
// gets a shorter line to prevent overlap in the point of the arrow // gets a shorter line to prevent overlap in the point of the arrow
QLine getShorterLine(QPoint p1, QPoint p2, const int thickness) { QLine
getShorterLine(QPoint p1, QPoint p2, const int thickness)
{
QLineF l(p1, p2); QLineF l(p1, p2);
int val = ArrowHeight + thickness*4; int val = ArrowHeight + thickness * 4;
if (l.length() < val) { if (l.length() < val) {
val = (l.length() + thickness*2); val = (l.length() + thickness * 2);
} }
l.setLength(l.length() + thickness*2 - val); l.setLength(l.length() + thickness * 2 - val);
return l.toLine(); return l.toLine();
} }
} // unnamed namespace } // unnamed namespace
ArrowTool::ArrowTool(QObject *parent) : AbstractTwoPointTool(parent) { ArrowTool::ArrowTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
m_padding = ArrowWidth / 2; m_padding = ArrowWidth / 2;
m_supportsOrthogonalAdj = true; m_supportsOrthogonalAdj = true;
m_supportsDiagonalAdj = true; m_supportsDiagonalAdj = true;
} }
QIcon ArrowTool::icon(const QColor &background, bool inEditor) const { QIcon
ArrowTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "arrow-bottom-left.svg"); return QIcon(iconPath(background) + "arrow-bottom-left.svg");
} }
QString ArrowTool::name() const { QString
ArrowTool::name() const
{
return tr("Arrow"); return tr("Arrow");
} }
QString ArrowTool::nameID() { QString
ArrowTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString ArrowTool::description() const { QString
ArrowTool::description() const
{
return tr("Set the Arrow as the paint tool"); return tr("Set the Arrow as the paint tool");
} }
CaptureTool* ArrowTool::copy(QObject *parent) { CaptureTool*
ArrowTool::copy(QObject* parent)
{
return new ArrowTool(parent); return new ArrowTool(parent);
} }
void ArrowTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { void
ArrowTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo)
{
if (recordUndo) { if (recordUndo) {
updateBackup(pixmap); updateBackup(pixmap);
} }
painter.setPen(QPen(m_color, m_thickness)); painter.setPen(QPen(m_color, m_thickness));
painter.drawLine(getShorterLine(m_points.first, m_points.second, m_thickness)); painter.drawLine(
painter.fillPath(getArrowHead(m_points.first, m_points.second, m_thickness), QBrush(m_color)); getShorterLine(m_points.first, m_points.second, m_thickness));
painter.fillPath(getArrowHead(m_points.first, m_points.second, m_thickness),
QBrush(m_color));
} }
void ArrowTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { void
ArrowTool::paintMousePreview(QPainter& painter, const CaptureContext& context)
{
painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness));
painter.drawLine(context.mousePos, context.mousePos); painter.drawLine(context.mousePos, context.mousePos);
} }
void ArrowTool::drawStart(const CaptureContext &context) { void
ArrowTool::drawStart(const CaptureContext& context)
{
m_color = context.color; m_color = context.color;
m_thickness = context.thickness + PADDING_VALUE; m_thickness = context.thickness + PADDING_VALUE;
m_points.first = context.mousePos; m_points.first = context.mousePos;
m_points.second = context.mousePos; m_points.second = context.mousePos;
} }
void ArrowTool::pressed(const CaptureContext &context) { void
ArrowTool::pressed(const CaptureContext& context)
{
Q_UNUSED(context); Q_UNUSED(context);
} }

View File

@@ -21,22 +21,25 @@
#include <QPainter> #include <QPainter>
#include <QPainterPath> #include <QPainterPath>
class ArrowTool : public AbstractTwoPointTool { class ArrowTool : public AbstractTwoPointTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit ArrowTool(QObject *parent = nullptr); explicit ArrowTool(QObject* parent = nullptr);
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
void process( void process(QPainter& painter,
QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; const QPixmap& pixmap,
void paintMousePreview(QPainter &painter, const CaptureContext &context) override; bool recordUndo = false) override;
void paintMousePreview(QPainter& painter,
const CaptureContext& context) override;
public slots: public slots:
void drawStart(const CaptureContext &context) override; void drawStart(const CaptureContext& context) override;
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
}; };

View File

@@ -23,41 +23,59 @@
#include <QImage> #include <QImage>
#include <QPainter> #include <QPainter>
BlurTool::BlurTool(QObject *parent) : AbstractTwoPointTool(parent) {} BlurTool::BlurTool(QObject* parent)
: AbstractTwoPointTool(parent)
{}
QIcon BlurTool::icon(const QColor &background, bool inEditor) const QIcon
BlurTool::icon(const QColor& background, bool inEditor) const
{ {
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "blur.svg"); return QIcon(iconPath(background) + "blur.svg");
} }
QString BlurTool::name() const { return tr("Blur"); } QString
BlurTool::name() const
{
return tr("Blur");
}
QString BlurTool::nameID() { return QLatin1String(""); } QString
BlurTool::nameID()
{
return QLatin1String("");
}
QString BlurTool::description() const QString
BlurTool::description() const
{ {
return tr("Set Blur as the paint tool"); return tr("Set Blur as the paint tool");
} }
CaptureTool *BlurTool::copy(QObject *parent) { return new BlurTool(parent); } CaptureTool*
BlurTool::copy(QObject* parent)
{
return new BlurTool(parent);
}
void write_block(QImage &image, int x_start, int y_start, int pixel_size, void
write_block(QImage& image,
int x_start,
int y_start,
int pixel_size,
QRgb block_color) QRgb block_color)
{ {
assert(x_start + pixel_size < image.width()); assert(x_start + pixel_size < image.width());
assert(y_start + pixel_size < image.height()); assert(y_start + pixel_size < image.height());
for (auto x = x_start; x < x_start + pixel_size; x++) for (auto x = x_start; x < x_start + pixel_size; x++) {
{ for (auto y = y_start; y < y_start + pixel_size; y++) {
for (auto y = y_start; y < y_start + pixel_size; y++)
{
image.setPixel(x, y, block_color); image.setPixel(x, y, block_color);
} }
} }
} }
QRgb calculate_block_averge(QImage &image, int x_start, int y_start, QRgb
int pixel_size) calculate_block_averge(QImage& image, int x_start, int y_start, int pixel_size)
{ {
assert(x_start + pixel_size < image.width()); assert(x_start + pixel_size < image.width());
assert(y_start + pixel_size < image.height()); assert(y_start + pixel_size < image.height());
@@ -66,10 +84,8 @@ QRgb calculate_block_averge(QImage &image, int x_start, int y_start,
int blue_count = 0; int blue_count = 0;
int green_count = 0; int green_count = 0;
int pixel_count = 0; int pixel_count = 0;
for (auto x = x_start; x < x_start + pixel_size; x++) for (auto x = x_start; x < x_start + pixel_size; x++) {
{ for (auto y = y_start; y < y_start + pixel_size; y++) {
for (auto y = y_start; y < y_start + pixel_size; y++)
{
auto pixel = image.pixel(x, y); auto pixel = image.pixel(x, y);
red_count += qRed(pixel); red_count += qRed(pixel);
@@ -78,51 +94,46 @@ QRgb calculate_block_averge(QImage &image, int x_start, int y_start,
pixel_count++; pixel_count++;
} }
} }
return (qRgb(red_count / pixel_count, green_count / pixel_count, return (qRgb(red_count / pixel_count,
green_count / pixel_count,
blue_count / pixel_count)); blue_count / pixel_count));
} }
void BlurTool::process(QPainter &painter, const QPixmap &pixmap, void
bool recordUndo) BlurTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo)
{ {
if (recordUndo) if (recordUndo) {
{
updateBackup(pixmap); updateBackup(pixmap);
} }
QPoint &p0 = m_points.first; QPoint& p0 = m_points.first;
QPoint &p1 = m_points.second; QPoint& p1 = m_points.second;
auto pixelRatio = pixmap.devicePixelRatio(); auto pixelRatio = pixmap.devicePixelRatio();
QRect selection = QRect(p0, p1).normalized(); QRect selection = QRect(p0, p1).normalized();
QRect selectionScaled = QRect(p0 * pixelRatio, p1 * pixelRatio).normalized(); QRect selectionScaled = QRect(p0 * pixelRatio, p1 * pixelRatio).normalized();
QPixmap *source = new QPixmap(pixmap.copy(selectionScaled)); QPixmap* source = new QPixmap(pixmap.copy(selectionScaled));
QImage original_image{source->toImage()}; QImage original_image{ source->toImage() };
QImage imageResult{source->toImage()}; QImage imageResult{ source->toImage() };
unsigned int pixel_size = m_thickness; unsigned int pixel_size = m_thickness;
if (pixel_size < 1) if (pixel_size < 1) {
{ pixel_size = 1;
pixel_size =1;
} }
const unsigned int width = source->width(); const unsigned int width = source->width();
const unsigned int height = source->height(); const unsigned int height = source->height();
// Don't start pixelating until the region is at least as big as the pixel // Don't start pixelating until the region is at least as big as the pixel
if ((width > pixel_size) && (height > pixel_size)) if ((width > pixel_size) && (height > pixel_size)) {
{ for (unsigned int x = 0; x < (width - pixel_size); x += pixel_size) {
for (unsigned int x = 0; x < (width - pixel_size); x += pixel_size) for (unsigned int y = 0; y < (height - pixel_size); y += pixel_size) {
{
for (unsigned int y = 0; y < (height - pixel_size); y += pixel_size)
{
auto block_color = auto block_color =
calculate_block_averge(original_image, x, y, pixel_size); calculate_block_averge(original_image, x, y, pixel_size);
write_block(imageResult, x, y, pixel_size, block_color); write_block(imageResult, x, y, pixel_size, block_color);
} }
} }
} }
QPixmap result{QPixmap::fromImage(imageResult)}; QPixmap result{ QPixmap::fromImage(imageResult) };
QGraphicsScene scene; QGraphicsScene scene;
scene.addPixmap(result); scene.addPixmap(result);
@@ -130,18 +141,23 @@ void BlurTool::process(QPainter &painter, const QPixmap &pixmap,
scene.render(&painter, selection, QRectF()); scene.render(&painter, selection, QRectF());
} }
void BlurTool::paintMousePreview(QPainter &painter, void
const CaptureContext &context) BlurTool::paintMousePreview(QPainter& painter, const CaptureContext& context)
{ {
Q_UNUSED(context); Q_UNUSED(context);
Q_UNUSED(painter); Q_UNUSED(painter);
} }
void BlurTool::drawStart(const CaptureContext &context) void
BlurTool::drawStart(const CaptureContext& context)
{ {
m_thickness = context.thickness; m_thickness = context.thickness;
m_points.first = context.mousePos; m_points.first = context.mousePos;
m_points.second = context.mousePos; m_points.second = context.mousePos;
} }
void BlurTool::pressed(const CaptureContext &context) { Q_UNUSED(context); } void
BlurTool::pressed(const CaptureContext& context)
{
Q_UNUSED(context);
}

View File

@@ -19,22 +19,25 @@
#include "src/tools/abstracttwopointtool.h" #include "src/tools/abstracttwopointtool.h"
class BlurTool : public AbstractTwoPointTool { class BlurTool : public AbstractTwoPointTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit BlurTool(QObject *parent = nullptr); explicit BlurTool(QObject* parent = nullptr);
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
void process( void process(QPainter& painter,
QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; const QPixmap& pixmap,
void paintMousePreview(QPainter &painter, const CaptureContext &context) override; bool recordUndo = false) override;
void paintMousePreview(QPainter& painter,
const CaptureContext& context) override;
public slots: public slots:
void drawStart(const CaptureContext &context) override; void drawStart(const CaptureContext& context) override;
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
}; };

View File

@@ -17,11 +17,12 @@
#include "capturecontext.h" #include "capturecontext.h"
QPixmap CaptureContext::selectedScreenshotArea() const { QPixmap
CaptureContext::selectedScreenshotArea() const
{
if (selection.isNull()) { if (selection.isNull()) {
return screenshot; return screenshot;
} else { } else {
return screenshot.copy(selection); return screenshot.copy(selection);
} }
} }

View File

@@ -17,12 +17,13 @@
#pragma once #pragma once
#include <QRect>
#include <QPoint>
#include <QPixmap>
#include <QPainter> #include <QPainter>
#include <QPixmap>
#include <QPoint>
#include <QRect>
struct CaptureContext { struct CaptureContext
{
// screenshot with modifications // screenshot with modifications
QPixmap screenshot; QPixmap screenshot;
// unmodified screenshot // unmodified screenshot
@@ -45,5 +46,5 @@ struct CaptureContext {
// Mode of the capture widget // Mode of the capture widget
bool fullscreen; bool fullscreen;
QPixmap selectedScreenshotArea() const ; QPixmap selectedScreenshotArea() const;
}; };

View File

@@ -23,12 +23,14 @@
#include <QIcon> #include <QIcon>
#include <QPainter> #include <QPainter>
class CaptureTool : public QObject { class CaptureTool : public QObject
{
Q_OBJECT Q_OBJECT
public: public:
// Request actions on the main widget // Request actions on the main widget
enum Request { enum Request
{
// Call close() in the editor. // Call close() in the editor.
REQ_CLOSE_GUI, REQ_CLOSE_GUI,
// Call hide() in the editor. // Call hide() in the editor.
@@ -66,7 +68,9 @@ public:
REQ_INCREMENT_CIRCLE_COUNT, REQ_INCREMENT_CIRCLE_COUNT,
}; };
explicit CaptureTool(QObject *parent = nullptr) : QObject(parent){} explicit CaptureTool(QObject* parent = nullptr)
: QObject(parent)
{}
// Returns false when the tool is in an inconsistent state and shouldn't // Returns false when the tool is in an inconsistent state and shouldn't
// be included in the tool undo/redo stack. // be included in the tool undo/redo stack.
@@ -82,8 +86,7 @@ public:
// The icon of the tool. // The icon of the tool.
// inEditor is true when the icon is requested inside the editor // inEditor is true when the icon is requested inside the editor
// and false otherwise. // and false otherwise.
virtual QIcon icon(const QColor &background, virtual QIcon icon(const QColor& background, bool inEditor) const = 0;
bool inEditor) const = 0;
// Name displayed for the tool, this could be translated with tr() // Name displayed for the tool, this could be translated with tr()
virtual QString name() const = 0; virtual QString name() const = 0;
// Codename for the tool, this hsouldn't change as it is used as ID // Codename for the tool, this hsouldn't change as it is used as ID
@@ -95,59 +98,53 @@ public:
// if the type is TYPE_WIDGET the widget is loaded in the main widget. // if the type is TYPE_WIDGET the widget is loaded in the main widget.
// If the type is TYPE_EXTERNAL_WIDGET it is created outside as an // If the type is TYPE_EXTERNAL_WIDGET it is created outside as an
// individual widget. // individual widget.
virtual QWidget* widget() { virtual QWidget* widget() { return nullptr; }
return nullptr;
}
// When the tool is selected this method is called and the widget is added // When the tool is selected this method is called and the widget is added
// to the configuration panel inside the main widget. // to the configuration panel inside the main widget.
virtual QWidget* configurationWidget() { virtual QWidget* configurationWidget() { return nullptr; }
return nullptr;
}
// Permanent configuration used in the configuration outside of the // Permanent configuration used in the configuration outside of the
// capture. // capture.
virtual QWidget* permanentConfigurationWidget() { virtual QWidget* permanentConfigurationWidget() { return nullptr; }
return nullptr;
}
// Return a copy of the tool // Return a copy of the tool
virtual CaptureTool* copy(QObject *parent = nullptr) = 0; virtual CaptureTool* copy(QObject* parent = nullptr) = 0;
// revert changes // revert changes
virtual void undo(QPixmap &pixmap) = 0; virtual void undo(QPixmap& pixmap) = 0;
// Called every time the tool has to draw // Called every time the tool has to draw
// recordUndo indicates when the tool should save the information // recordUndo indicates when the tool should save the information
// for the undo(), if the value is false calling undo() after // for the undo(), if the value is false calling undo() after
// that process should not modify revert the changes. // that process should not modify revert the changes.
virtual void process(QPainter &painter, virtual void process(QPainter& painter,
const QPixmap &pixmap, const QPixmap& pixmap,
bool recordUndo = false) = 0; bool recordUndo = false) = 0;
// When the tool is selected, this is called when the mouse moves // When the tool is selected, this is called when the mouse moves
virtual void paintMousePreview(QPainter &painter, const CaptureContext &context) = 0; virtual void paintMousePreview(QPainter& painter,
const CaptureContext& context) = 0;
signals: signals:
void requestAction(Request r); void requestAction(Request r);
protected: protected:
QString iconPath(const QColor &c) const { QString iconPath(const QColor& c) const
return ColorUtils::colorIsDark(c) ? {
PathInfo::whiteIconPath() : PathInfo::blackIconPath(); return ColorUtils::colorIsDark(c) ? PathInfo::whiteIconPath()
: PathInfo::blackIconPath();
} }
public slots: public slots:
// On mouse release. // On mouse release.
virtual void drawEnd(const QPoint &p) = 0; virtual void drawEnd(const QPoint& p) = 0;
// Mouse pressed and moving, called once a pixel. // Mouse pressed and moving, called once a pixel.
virtual void drawMove(const QPoint &p) = 0; virtual void drawMove(const QPoint& p) = 0;
// Called when drawMove is needed with an adjustment; // Called when drawMove is needed with an adjustment;
// should be overridden in case an adjustment is applicable. // should be overridden in case an adjustment is applicable.
virtual void drawMoveWithAdjustment(const QPoint &p) { virtual void drawMoveWithAdjustment(const QPoint& p) { drawMove(p); }
drawMove(p);
}
// Called when the tool is activated. // Called when the tool is activated.
virtual void drawStart(const CaptureContext &context) = 0; virtual void drawStart(const CaptureContext& context) = 0;
// Called right after pressign the button which activates the tool. // Called right after pressign the button which activates the tool.
virtual void pressed(const CaptureContext &context) = 0; virtual void pressed(const CaptureContext& context) = 0;
// Called when the color is changed in the editor. // Called when the color is changed in the editor.
virtual void colorChanged(const QColor &c) = 0; virtual void colorChanged(const QColor& c) = 0;
// Called when the thickness of the tool is updated in the editor. // Called when the thickness of the tool is updated in the editor.
virtual void thicknessChanged(const int th) = 0; virtual void thicknessChanged(const int th) = 0;
}; };

View File

@@ -22,31 +22,45 @@ namespace {
#define PADDING_VALUE 2 #define PADDING_VALUE 2
} }
CircleTool::CircleTool(QObject *parent) : AbstractTwoPointTool(parent) { CircleTool::CircleTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
m_supportsDiagonalAdj = true; m_supportsDiagonalAdj = true;
} }
QIcon CircleTool::icon(const QColor &background, bool inEditor) const { QIcon
CircleTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "circle-outline.svg"); return QIcon(iconPath(background) + "circle-outline.svg");
} }
QString CircleTool::name() const { QString
CircleTool::name() const
{
return tr("Circle"); return tr("Circle");
} }
QString CircleTool::nameID() { QString
CircleTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString CircleTool::description() const { QString
CircleTool::description() const
{
return tr("Set the Circle as the paint tool"); return tr("Set the Circle as the paint tool");
} }
CaptureTool* CircleTool::copy(QObject *parent) { CaptureTool*
CircleTool::copy(QObject* parent)
{
return new CircleTool(parent); return new CircleTool(parent);
} }
void CircleTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { void
CircleTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo)
{
if (recordUndo) { if (recordUndo) {
updateBackup(pixmap); updateBackup(pixmap);
} }
@@ -54,18 +68,24 @@ void CircleTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUn
painter.drawEllipse(QRect(m_points.first, m_points.second)); painter.drawEllipse(QRect(m_points.first, m_points.second));
} }
void CircleTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { void
CircleTool::paintMousePreview(QPainter& painter, const CaptureContext& context)
{
painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness));
painter.drawLine(context.mousePos, context.mousePos); painter.drawLine(context.mousePos, context.mousePos);
} }
void CircleTool::drawStart(const CaptureContext &context) { void
CircleTool::drawStart(const CaptureContext& context)
{
m_color = context.color; m_color = context.color;
m_thickness = context.thickness + PADDING_VALUE; m_thickness = context.thickness + PADDING_VALUE;
m_points.first = context.mousePos; m_points.first = context.mousePos;
m_points.second = context.mousePos; m_points.second = context.mousePos;
} }
void CircleTool::pressed(const CaptureContext &context) { void
CircleTool::pressed(const CaptureContext& context)
{
Q_UNUSED(context); Q_UNUSED(context);
} }

View File

@@ -19,22 +19,25 @@
#include "src/tools/abstracttwopointtool.h" #include "src/tools/abstracttwopointtool.h"
class CircleTool : public AbstractTwoPointTool { class CircleTool : public AbstractTwoPointTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit CircleTool(QObject *parent = nullptr); explicit CircleTool(QObject* parent = nullptr);
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
void process( void process(QPainter& painter,
QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; const QPixmap& pixmap,
void paintMousePreview(QPainter &painter, const CaptureContext &context) override; bool recordUndo = false) override;
void paintMousePreview(QPainter& painter,
const CaptureContext& context) override;
public slots: public slots:
void drawStart(const CaptureContext &context) override; void drawStart(const CaptureContext& context) override;
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
}; };

View File

@@ -21,55 +21,82 @@ namespace {
#define PADDING_VALUE 2 #define PADDING_VALUE 2
} }
CircleCountTool::CircleCountTool(QObject *parent) : AbstractTwoPointTool(parent) { CircleCountTool::CircleCountTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
m_count = 0; m_count = 0;
} }
QIcon CircleCountTool::icon(const QColor &background, bool inEditor) const { QIcon
CircleCountTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "circlecount-outline.svg"); return QIcon(iconPath(background) + "circlecount-outline.svg");
} }
QString CircleCountTool::name() const { QString
CircleCountTool::name() const
{
return tr("Circle Counter"); return tr("Circle Counter");
} }
QString CircleCountTool::nameID() { QString
CircleCountTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString CircleCountTool::description() const { QString
CircleCountTool::description() const
{
return tr("Add an autoincrementing counter bubble"); return tr("Add an autoincrementing counter bubble");
} }
CaptureTool* CircleCountTool::copy(QObject *parent) { CaptureTool*
CircleCountTool::copy(QObject* parent)
{
return new CircleCountTool(parent); return new CircleCountTool(parent);
} }
void CircleCountTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { void
CircleCountTool::process(QPainter& painter,
const QPixmap& pixmap,
bool recordUndo)
{
if (recordUndo) { if (recordUndo) {
updateBackup(pixmap); updateBackup(pixmap);
} }
painter.setBrush(m_color); painter.setBrush(m_color);
int bubble_size=16; int bubble_size = 16;
painter.drawEllipse(m_points.first,bubble_size,bubble_size); painter.drawEllipse(m_points.first, bubble_size, bubble_size);
painter.drawText(QRectF(m_points.first.x()-bubble_size/2, m_points.first.y()-bubble_size/2, bubble_size, bubble_size), Qt::AlignCenter, QString::number(m_count)); painter.drawText(QRectF(m_points.first.x() - bubble_size / 2,
m_points.first.y() - bubble_size / 2,
bubble_size,
bubble_size),
Qt::AlignCenter,
QString::number(m_count));
} }
void CircleCountTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { void
CircleCountTool::paintMousePreview(QPainter& painter,
const CaptureContext& context)
{
painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness));
painter.drawLine(context.mousePos, context.mousePos); painter.drawLine(context.mousePos, context.mousePos);
} }
void CircleCountTool::drawStart(const CaptureContext &context) { void
CircleCountTool::drawStart(const CaptureContext& context)
{
m_color = context.color; m_color = context.color;
m_thickness = context.thickness + PADDING_VALUE; m_thickness = context.thickness + PADDING_VALUE;
m_points.first = context.mousePos; m_points.first = context.mousePos;
m_count = context.circleCount; m_count = context.circleCount;
emit requestAction(REQ_INCREMENT_CIRCLE_COUNT); emit requestAction(REQ_INCREMENT_CIRCLE_COUNT);
} }
void CircleCountTool::pressed(const CaptureContext &context) { void
CircleCountTool::pressed(const CaptureContext& context)
{
Q_UNUSED(context); Q_UNUSED(context);
} }

View File

@@ -19,23 +19,27 @@
#include "src/tools/abstracttwopointtool.h" #include "src/tools/abstracttwopointtool.h"
class CircleCountTool : public AbstractTwoPointTool { class CircleCountTool : public AbstractTwoPointTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit CircleCountTool(QObject *parent = nullptr); explicit CircleCountTool(QObject* parent = nullptr);
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
void process( void process(QPainter& painter,
QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; const QPixmap& pixmap,
void paintMousePreview(QPainter &painter, const CaptureContext &context) override; bool recordUndo = false) override;
void paintMousePreview(QPainter& painter,
const CaptureContext& context) override;
private: private:
unsigned int m_count; unsigned int m_count;
public slots: public slots:
void drawStart(const CaptureContext &context) override; void drawStart(const CaptureContext& context) override;
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
}; };

View File

@@ -19,35 +19,49 @@
#include "src/utils/screenshotsaver.h" #include "src/utils/screenshotsaver.h"
#include <QPainter> #include <QPainter>
CopyTool::CopyTool(QObject *parent) : AbstractActionTool(parent) { CopyTool::CopyTool(QObject* parent)
: AbstractActionTool(parent)
{}
} bool
CopyTool::closeOnButtonPressed() const
bool CopyTool::closeOnButtonPressed() const { {
return true; return true;
} }
QIcon CopyTool::icon(const QColor &background, bool inEditor) const { QIcon
CopyTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "content-copy.svg"); return QIcon(iconPath(background) + "content-copy.svg");
} }
QString CopyTool::name() const { QString
CopyTool::name() const
{
return tr("Copy"); return tr("Copy");
} }
QString CopyTool::nameID() { QString
CopyTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString CopyTool::description() const { QString
CopyTool::description() const
{
return tr("Copy the selection into the clipboard"); return tr("Copy the selection into the clipboard");
} }
CaptureTool* CopyTool::copy(QObject *parent) { CaptureTool*
CopyTool::copy(QObject* parent)
{
return new CopyTool(parent); return new CopyTool(parent);
} }
void CopyTool::pressed(const CaptureContext &context) { void
CopyTool::pressed(const CaptureContext& context)
{
emit requestAction(REQ_CAPTURE_DONE_OK); emit requestAction(REQ_CAPTURE_DONE_OK);
ScreenshotSaver().saveToClipboard(context.selectedScreenshotArea()); ScreenshotSaver().saveToClipboard(context.selectedScreenshotArea());
} }

View File

@@ -19,20 +19,21 @@
#include "src/tools/abstractactiontool.h" #include "src/tools/abstractactiontool.h"
class CopyTool : public AbstractActionTool { class CopyTool : public AbstractActionTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit CopyTool(QObject *parent = nullptr); explicit CopyTool(QObject* parent = nullptr);
bool closeOnButtonPressed() const; bool closeOnButtonPressed() const;
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
public slots: public slots:
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
}; };

View File

@@ -18,35 +18,49 @@
#include "exittool.h" #include "exittool.h"
#include <QPainter> #include <QPainter>
ExitTool::ExitTool(QObject *parent) : AbstractActionTool(parent) { ExitTool::ExitTool(QObject* parent)
: AbstractActionTool(parent)
{}
} bool
ExitTool::closeOnButtonPressed() const
bool ExitTool::closeOnButtonPressed() const { {
return true; return true;
} }
QIcon ExitTool::icon(const QColor &background, bool inEditor) const { QIcon
ExitTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "close.svg"); return QIcon(iconPath(background) + "close.svg");
} }
QString ExitTool::name() const { QString
ExitTool::name() const
{
return tr("Exit"); return tr("Exit");
} }
QString ExitTool::nameID() { QString
ExitTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString ExitTool::description() const { QString
ExitTool::description() const
{
return tr("Leave the capture screen"); return tr("Leave the capture screen");
} }
CaptureTool* ExitTool::copy(QObject *parent) { CaptureTool*
ExitTool::copy(QObject* parent)
{
return new ExitTool(parent); return new ExitTool(parent);
} }
void ExitTool::pressed(const CaptureContext &context) { void
ExitTool::pressed(const CaptureContext& context)
{
Q_UNUSED(context); Q_UNUSED(context);
emit requestAction(REQ_CLOSE_GUI); emit requestAction(REQ_CLOSE_GUI);
} }

View File

@@ -19,20 +19,21 @@
#include "src/tools/abstractactiontool.h" #include "src/tools/abstractactiontool.h"
class ExitTool : public AbstractActionTool { class ExitTool : public AbstractActionTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit ExitTool(QObject *parent = nullptr); explicit ExitTool(QObject* parent = nullptr);
bool closeOnButtonPressed() const; bool closeOnButtonPressed() const;
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
public slots: public slots:
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
}; };

View File

@@ -16,33 +16,34 @@
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "imguruploader.h" #include "imguruploader.h"
#include "src/utils/confighandler.h"
#include "src/utils/filenamehandler.h" #include "src/utils/filenamehandler.h"
#include "src/utils/systemnotification.h" #include "src/utils/systemnotification.h"
#include "src/widgets/loadspinner.h"
#include "src/widgets/imagelabel.h" #include "src/widgets/imagelabel.h"
#include "src/widgets/loadspinner.h"
#include "src/widgets/notificationwidget.h" #include "src/widgets/notificationwidget.h"
#include "src/utils/confighandler.h"
#include <QApplication> #include <QApplication>
#include <QBuffer>
#include <QClipboard> #include <QClipboard>
#include <QDesktopServices> #include <QDesktopServices>
#include <QShortcut>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QDrag> #include <QDrag>
#include <QMimeData> #include <QHBoxLayout>
#include <QBuffer>
#include <QUrlQuery>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTimer>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonObject> #include <QJsonObject>
#include <QLabel>
#include <QMimeData>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPushButton>
#include <QShortcut>
#include <QTimer>
#include <QUrlQuery>
#include <QVBoxLayout>
ImgurUploader::ImgurUploader(const QPixmap &capture, QWidget *parent) : ImgurUploader::ImgurUploader(const QPixmap& capture, QWidget* parent)
QWidget(parent), m_pixmap(capture) : QWidget(parent)
, m_pixmap(capture)
{ {
setWindowTitle(tr("Upload to Imgur")); setWindowTitle(tr("Upload to Imgur"));
setWindowIcon(QIcon(":img/app/flameshot.svg")); setWindowIcon(QIcon(":img/app/flameshot.svg"));
@@ -59,7 +60,9 @@ ImgurUploader::ImgurUploader(const QPixmap &capture, QWidget *parent) :
m_vLayout->addWidget(m_infoLabel); m_vLayout->addWidget(m_infoLabel);
m_NetworkAM = new QNetworkAccessManager(this); m_NetworkAM = new QNetworkAccessManager(this);
connect(m_NetworkAM, &QNetworkAccessManager::finished, this, connect(m_NetworkAM,
&QNetworkAccessManager::finished,
this,
&ImgurUploader::handleReply); &ImgurUploader::handleReply);
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
@@ -68,15 +71,18 @@ ImgurUploader::ImgurUploader(const QPixmap &capture, QWidget *parent) :
// QTimer::singleShot(2000, this, &ImgurUploader::onUploadOk); // testing // QTimer::singleShot(2000, this, &ImgurUploader::onUploadOk); // testing
} }
void ImgurUploader::handleReply(QNetworkReply *reply) { void
ImgurUploader::handleReply(QNetworkReply* reply)
{
m_spinner->deleteLater(); m_spinner->deleteLater();
if (reply->error() == QNetworkReply::NoError) { if (reply->error() == QNetworkReply::NoError) {
QJsonDocument response = QJsonDocument::fromJson(reply->readAll()); QJsonDocument response = QJsonDocument::fromJson(reply->readAll());
QJsonObject json = response.object(); QJsonObject json = response.object();
QJsonObject data = json[QStringLiteral("data")].toObject(); QJsonObject data = json[QStringLiteral("data")].toObject();
m_imageURL.setUrl(data[QStringLiteral("link")].toString()); m_imageURL.setUrl(data[QStringLiteral("link")].toString());
m_deleteImageURL.setUrl(QStringLiteral("https://imgur.com/delete/%1").arg( m_deleteImageURL.setUrl(
data[QStringLiteral("deletehash")].toString())); QStringLiteral("https://imgur.com/delete/%1")
.arg(data[QStringLiteral("deletehash")].toString()));
if (ConfigHandler().copyAndCloseAfterUploadEnabled()) { if (ConfigHandler().copyAndCloseAfterUploadEnabled()) {
QApplication::clipboard()->setText(m_imageURL.toString()); QApplication::clipboard()->setText(m_imageURL.toString());
SystemNotification().sendMessage(QObject::tr("URL copied to clipboard.")); SystemNotification().sendMessage(QObject::tr("URL copied to clipboard."));
@@ -90,25 +96,30 @@ void ImgurUploader::handleReply(QNetworkReply *reply) {
new QShortcut(Qt::Key_Escape, this, SLOT(close())); new QShortcut(Qt::Key_Escape, this, SLOT(close()));
} }
void ImgurUploader::startDrag() { void
QMimeData *mimeData = new QMimeData; ImgurUploader::startDrag()
mimeData->setUrls(QList<QUrl> { m_imageURL }); {
QMimeData* mimeData = new QMimeData;
mimeData->setUrls(QList<QUrl>{ m_imageURL });
mimeData->setImageData(m_pixmap); mimeData->setImageData(m_pixmap);
QDrag *dragHandler = new QDrag(this); QDrag* dragHandler = new QDrag(this);
dragHandler->setMimeData(mimeData); dragHandler->setMimeData(mimeData);
dragHandler->setPixmap(m_pixmap.scaled(256, 256, Qt::KeepAspectRatioByExpanding, dragHandler->setPixmap(m_pixmap.scaled(
Qt::SmoothTransformation)); 256, 256, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
dragHandler->exec(); dragHandler->exec();
} }
void ImgurUploader::upload() { void
ImgurUploader::upload()
{
QByteArray byteArray; QByteArray byteArray;
QBuffer buffer(&byteArray); QBuffer buffer(&byteArray);
m_pixmap.save(&buffer, "PNG"); m_pixmap.save(&buffer, "PNG");
QUrlQuery urlQuery; QUrlQuery urlQuery;
urlQuery.addQueryItem(QStringLiteral("title"), QStringLiteral("flameshot_screenshot")); urlQuery.addQueryItem(QStringLiteral("title"),
QStringLiteral("flameshot_screenshot"));
QString description = FileNameHandler().parsedPattern(); QString description = FileNameHandler().parsedPattern();
urlQuery.addQueryItem(QStringLiteral("description"), description); urlQuery.addQueryItem(QStringLiteral("description"), description);
@@ -117,21 +128,26 @@ void ImgurUploader::upload() {
QNetworkRequest request(url); QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/application/x-www-form-urlencoded"); "application/application/x-www-form-urlencoded");
request.setRawHeader("Authorization", QStringLiteral("Client-ID %1").arg(IMGUR_CLIENT_ID).toUtf8()); request.setRawHeader(
"Authorization",
QStringLiteral("Client-ID %1").arg(IMGUR_CLIENT_ID).toUtf8());
m_NetworkAM->post(request, byteArray); m_NetworkAM->post(request, byteArray);
} }
void ImgurUploader::onUploadOk() { void
ImgurUploader::onUploadOk()
{
m_infoLabel->deleteLater(); m_infoLabel->deleteLater();
m_notification = new NotificationWidget(); m_notification = new NotificationWidget();
m_vLayout->addWidget(m_notification); m_vLayout->addWidget(m_notification);
ImageLabel *imageLabel = new ImageLabel(); ImageLabel* imageLabel = new ImageLabel();
imageLabel->setScreenshot(m_pixmap); imageLabel->setScreenshot(m_pixmap);
imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
connect(imageLabel, &ImageLabel::dragInitiated, this, &ImgurUploader::startDrag); connect(
imageLabel, &ImageLabel::dragInitiated, this, &ImgurUploader::startDrag);
m_vLayout->addWidget(imageLabel); m_vLayout->addWidget(imageLabel);
m_hLayout = new QHBoxLayout(); m_hLayout = new QHBoxLayout();
@@ -146,29 +162,38 @@ void ImgurUploader::onUploadOk() {
m_hLayout->addWidget(m_openDeleteUrlButton); m_hLayout->addWidget(m_openDeleteUrlButton);
m_hLayout->addWidget(m_toClipboardButton); m_hLayout->addWidget(m_toClipboardButton);
connect(m_copyUrlButton, &QPushButton::clicked, connect(
this, &ImgurUploader::copyURL); m_copyUrlButton, &QPushButton::clicked, this, &ImgurUploader::copyURL);
connect(m_openUrlButton, &QPushButton::clicked, connect(
this, &ImgurUploader::openURL); m_openUrlButton, &QPushButton::clicked, this, &ImgurUploader::openURL);
connect(m_openDeleteUrlButton, &QPushButton::clicked, connect(m_openDeleteUrlButton,
this, &ImgurUploader::openDeleteURL); &QPushButton::clicked,
connect(m_toClipboardButton, &QPushButton::clicked, this,
this, &ImgurUploader::copyImage); &ImgurUploader::openDeleteURL);
connect(m_toClipboardButton,
&QPushButton::clicked,
this,
&ImgurUploader::copyImage);
} }
void ImgurUploader::openURL() { void
ImgurUploader::openURL()
{
bool successful = QDesktopServices::openUrl(m_imageURL); bool successful = QDesktopServices::openUrl(m_imageURL);
if (!successful) { if (!successful) {
m_notification->showMessage(tr("Unable to open the URL.")); m_notification->showMessage(tr("Unable to open the URL."));
} }
} }
void ImgurUploader::copyURL() { void
ImgurUploader::copyURL()
{
QApplication::clipboard()->setText(m_imageURL.toString()); QApplication::clipboard()->setText(m_imageURL.toString());
m_notification->showMessage(tr("URL copied to clipboard.")); m_notification->showMessage(tr("URL copied to clipboard."));
} }
void ImgurUploader::openDeleteURL() void
ImgurUploader::openDeleteURL()
{ {
bool successful = QDesktopServices::openUrl(m_deleteImageURL); bool successful = QDesktopServices::openUrl(m_deleteImageURL);
if (!successful) { if (!successful) {
@@ -176,7 +201,9 @@ void ImgurUploader::openDeleteURL()
} }
} }
void ImgurUploader::copyImage() { void
ImgurUploader::copyImage()
{
QApplication::clipboard()->setPixmap(m_pixmap); QApplication::clipboard()->setPixmap(m_pixmap);
m_notification->showMessage(tr("Screenshot copied to clipboard.")); m_notification->showMessage(tr("Screenshot copied to clipboard."));
} }

View File

@@ -17,8 +17,8 @@
#pragma once #pragma once
#include <QWidget>
#include <QUrl> #include <QUrl>
#include <QWidget>
class QNetworkReply; class QNetworkReply;
class QNetworkAccessManager; class QNetworkAccessManager;
@@ -30,13 +30,14 @@ class QPushButton;
class QUrl; class QUrl;
class NotificationWidget; class NotificationWidget;
class ImgurUploader : public QWidget { class ImgurUploader : public QWidget
{
Q_OBJECT Q_OBJECT
public: public:
explicit ImgurUploader(const QPixmap &capture, QWidget *parent = nullptr); explicit ImgurUploader(const QPixmap& capture, QWidget* parent = nullptr);
private slots: private slots:
void handleReply(QNetworkReply *reply); void handleReply(QNetworkReply* reply);
void startDrag(); void startDrag();
void openURL(); void openURL();
@@ -46,21 +47,21 @@ private slots:
private: private:
QPixmap m_pixmap; QPixmap m_pixmap;
QNetworkAccessManager *m_NetworkAM; QNetworkAccessManager* m_NetworkAM;
QVBoxLayout *m_vLayout; QVBoxLayout* m_vLayout;
QHBoxLayout *m_hLayout; QHBoxLayout* m_hLayout;
// loading // loading
QLabel *m_infoLabel; QLabel* m_infoLabel;
LoadSpinner *m_spinner; LoadSpinner* m_spinner;
// uploaded // uploaded
QPushButton *m_openUrlButton; QPushButton* m_openUrlButton;
QPushButton *m_openDeleteUrlButton; QPushButton* m_openDeleteUrlButton;
QPushButton *m_copyUrlButton; QPushButton* m_copyUrlButton;
QPushButton *m_toClipboardButton; QPushButton* m_toClipboardButton;
QUrl m_imageURL; QUrl m_imageURL;
QUrl m_deleteImageURL; QUrl m_deleteImageURL;
NotificationWidget *m_notification; NotificationWidget* m_notification;
void upload(); void upload();
void onUploadOk(); void onUploadOk();

View File

@@ -19,39 +19,55 @@
#include "imguruploader.h" #include "imguruploader.h"
#include <QPainter> #include <QPainter>
ImgurUploaderTool::ImgurUploaderTool(QObject *parent) : AbstractActionTool(parent) { ImgurUploaderTool::ImgurUploaderTool(QObject* parent)
: AbstractActionTool(parent)
{}
} bool
ImgurUploaderTool::closeOnButtonPressed() const
bool ImgurUploaderTool::closeOnButtonPressed() const { {
return true; return true;
} }
QIcon ImgurUploaderTool::icon(const QColor &background, bool inEditor) const { QIcon
ImgurUploaderTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "cloud-upload.svg"); return QIcon(iconPath(background) + "cloud-upload.svg");
} }
QString ImgurUploaderTool::name() const { QString
ImgurUploaderTool::name() const
{
return tr("Image Uploader"); return tr("Image Uploader");
} }
QString ImgurUploaderTool::nameID() { QString
ImgurUploaderTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString ImgurUploaderTool::description() const { QString
ImgurUploaderTool::description() const
{
return tr("Upload the selection to Imgur"); return tr("Upload the selection to Imgur");
} }
QWidget* ImgurUploaderTool::widget() { QWidget*
ImgurUploaderTool::widget()
{
return new ImgurUploader(capture); return new ImgurUploader(capture);
} }
CaptureTool* ImgurUploaderTool::copy(QObject *parent) { CaptureTool*
ImgurUploaderTool::copy(QObject* parent)
{
return new ImgurUploaderTool(parent); return new ImgurUploaderTool(parent);
} }
void ImgurUploaderTool::pressed(const CaptureContext &context) { void
ImgurUploaderTool::pressed(const CaptureContext& context)
{
capture = context.selectedScreenshotArea(); capture = context.selectedScreenshotArea();
emit requestAction(REQ_CAPTURE_DONE_OK); emit requestAction(REQ_CAPTURE_DONE_OK);
emit requestAction(REQ_ADD_EXTERNAL_WIDGETS); emit requestAction(REQ_ADD_EXTERNAL_WIDGETS);

View File

@@ -19,24 +19,25 @@
#include "src/tools/abstractactiontool.h" #include "src/tools/abstractactiontool.h"
class ImgurUploaderTool : public AbstractActionTool { class ImgurUploaderTool : public AbstractActionTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit ImgurUploaderTool(QObject *parent = nullptr); explicit ImgurUploaderTool(QObject* parent = nullptr);
bool closeOnButtonPressed() const; bool closeOnButtonPressed() const;
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
QWidget* widget() override; QWidget* widget() override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
public slots: public slots:
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
private: private:
QPixmap capture; QPixmap capture;

View File

@@ -18,39 +18,55 @@
#include "applaunchertool.h" #include "applaunchertool.h"
#include "applauncherwidget.h" #include "applauncherwidget.h"
AppLauncher::AppLauncher(QObject *parent) : AbstractActionTool(parent) { AppLauncher::AppLauncher(QObject* parent)
: AbstractActionTool(parent)
{}
} bool
AppLauncher::closeOnButtonPressed() const
bool AppLauncher::closeOnButtonPressed() const { {
return true; return true;
} }
QIcon AppLauncher::icon(const QColor &background, bool inEditor) const { QIcon
AppLauncher::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "open_with.svg"); return QIcon(iconPath(background) + "open_with.svg");
} }
QString AppLauncher::name() const { QString
AppLauncher::name() const
{
return tr("App Launcher"); return tr("App Launcher");
} }
QString AppLauncher::nameID() { QString
AppLauncher::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString AppLauncher::description() const { QString
AppLauncher::description() const
{
return tr("Choose an app to open the capture"); return tr("Choose an app to open the capture");
} }
QWidget* AppLauncher::widget() { QWidget*
AppLauncher::widget()
{
return new AppLauncherWidget(capture); return new AppLauncherWidget(capture);
} }
CaptureTool* AppLauncher::copy(QObject *parent) { CaptureTool*
AppLauncher::copy(QObject* parent)
{
return new AppLauncher(parent); return new AppLauncher(parent);
} }
void AppLauncher::pressed(const CaptureContext &context) { void
AppLauncher::pressed(const CaptureContext& context)
{
capture = context.selectedScreenshotArea(); capture = context.selectedScreenshotArea();
emit requestAction(REQ_CAPTURE_DONE_OK); emit requestAction(REQ_CAPTURE_DONE_OK);
emit requestAction(REQ_ADD_EXTERNAL_WIDGETS); emit requestAction(REQ_ADD_EXTERNAL_WIDGETS);

View File

@@ -19,24 +19,25 @@
#include "src/tools/abstractactiontool.h" #include "src/tools/abstractactiontool.h"
class AppLauncher : public AbstractActionTool { class AppLauncher : public AbstractActionTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit AppLauncher(QObject *parent = nullptr); explicit AppLauncher(QObject* parent = nullptr);
bool closeOnButtonPressed() const; bool closeOnButtonPressed() const;
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
QWidget* widget() override; QWidget* widget() override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
public slots: public slots:
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
private: private:
QPixmap capture; QPixmap capture;

View File

@@ -16,40 +16,40 @@
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "applauncherwidget.h" #include "applauncherwidget.h"
#include "src/utils/filenamehandler.h"
#include "src/tools/launcher/launcheritemdelegate.h" #include "src/tools/launcher/launcheritemdelegate.h"
#include "src/utils/globalvalues.h"
#include "src/utils/confighandler.h" #include "src/utils/confighandler.h"
#include "src/utils/filenamehandler.h"
#include "src/utils/globalvalues.h"
#include "terminallauncher.h" #include "terminallauncher.h"
#include <QDir>
#include <QList>
#include <QProcess>
#include <QPixmap>
#include <QListView>
#include <QTabWidget>
#include <QListWidgetItem>
#include <QHBoxLayout>
#include <QCheckBox> #include <QCheckBox>
#include <QDir>
#include <QHBoxLayout>
#include <QLineEdit> #include <QLineEdit>
#include <QList>
#include <QListView>
#include <QListWidgetItem>
#include <QMessageBox> #include <QMessageBox>
#include <QPixmap>
#include <QProcess>
#include <QTabWidget>
namespace { namespace {
QMap<QString, QString> catIconNames({ QMap<QString, QString> catIconNames(
{ "Multimedia", "applications-multimedia" }, { { "Multimedia", "applications-multimedia" },
{ "Development","applications-development" }, { "Development", "applications-development" },
{ "Graphics", "applications-graphics" }, { "Graphics", "applications-graphics" },
{ "Network", "preferences-system-network" }, { "Network", "preferences-system-network" },
{ "Office", "applications-office" }, { "Office", "applications-office" },
{ "Science", "applications-science" }, { "Science", "applications-science" },
{ "Settings", "preferences-desktop" }, { "Settings", "preferences-desktop" },
{ "System", "preferences-system" }, { "System", "preferences-system" },
{ "Utility", "applications-utilities" } { "Utility", "applications-utilities" } });
});
} }
AppLauncherWidget::AppLauncherWidget(const QPixmap &p, QWidget *parent): AppLauncherWidget::AppLauncherWidget(const QPixmap& p, QWidget* parent)
QWidget(parent), m_pixmap(p) : QWidget(parent)
, m_pixmap(p)
{ {
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
setWindowIcon(QIcon(":img/app/flameshot.svg")); setWindowIcon(QIcon(":img/app/flameshot.svg"));
@@ -71,16 +71,22 @@ AppLauncherWidget::AppLauncherWidget(const QPixmap &p, QWidget *parent):
m_terminalCheckbox = new QCheckBox(tr("Launch in terminal"), this); m_terminalCheckbox = new QCheckBox(tr("Launch in terminal"), this);
m_keepOpenCheckbox = new QCheckBox(tr("Keep open after selection"), this); m_keepOpenCheckbox = new QCheckBox(tr("Keep open after selection"), this);
m_keepOpenCheckbox->setChecked(ConfigHandler().keepOpenAppLauncherValue()); m_keepOpenCheckbox->setChecked(ConfigHandler().keepOpenAppLauncherValue());
connect(m_keepOpenCheckbox, &QCheckBox::clicked, this, &AppLauncherWidget::checkboxClicked); connect(m_keepOpenCheckbox,
&QCheckBox::clicked,
this,
&AppLauncherWidget::checkboxClicked);
// search items // search items
m_lineEdit = new QLineEdit; m_lineEdit = new QLineEdit;
connect(m_lineEdit, &QLineEdit::textChanged, connect(m_lineEdit,
this, &AppLauncherWidget::searchChanged); &QLineEdit::textChanged,
this,
&AppLauncherWidget::searchChanged);
m_filterList = new QListWidget; m_filterList = new QListWidget;
m_filterList->hide(); m_filterList->hide();
configureListView(m_filterList); configureListView(m_filterList);
connect(m_filterList, &QListWidget::clicked, this, &AppLauncherWidget::launch); connect(
m_filterList, &QListWidget::clicked, this, &AppLauncherWidget::launch);
m_layout = new QVBoxLayout(this); m_layout = new QVBoxLayout(this);
m_layout->addWidget(m_filterList); m_layout->addWidget(m_filterList);
@@ -91,43 +97,51 @@ AppLauncherWidget::AppLauncherWidget(const QPixmap &p, QWidget *parent):
m_lineEdit->setFocus(); m_lineEdit->setFocus();
} }
void AppLauncherWidget::launch(const QModelIndex &index) { void
AppLauncherWidget::launch(const QModelIndex& index)
{
if (!QFileInfo(m_tempFile).isReadable()) { if (!QFileInfo(m_tempFile).isReadable()) {
m_tempFile = FileNameHandler().generateAbsolutePath(QDir::tempPath()) + ".png"; m_tempFile =
FileNameHandler().generateAbsolutePath(QDir::tempPath()) + ".png";
bool ok = m_pixmap.save(m_tempFile); bool ok = m_pixmap.save(m_tempFile);
if (!ok) { if (!ok) {
QMessageBox::about(this, tr("Error"), tr("Unable to write in") QMessageBox::about(
+ QDir::tempPath()); this, tr("Error"), tr("Unable to write in") + QDir::tempPath());
return; return;
} }
} }
QString command = index.data(Qt::UserRole).toString().replace( QString command = index.data(Qt::UserRole)
QRegExp("(\\%.)"), '"' + m_tempFile + '"'); .toString()
.replace(QRegExp("(\\%.)"), '"' + m_tempFile + '"');
QString app_name = index.data(Qt::UserRole).toString().split(" ").at(0); QString app_name = index.data(Qt::UserRole).toString().split(" ").at(0);
bool inTerminal = index.data(Qt::UserRole+1).toBool() || bool inTerminal =
m_terminalCheckbox->isChecked(); index.data(Qt::UserRole + 1).toBool() || m_terminalCheckbox->isChecked();
if (inTerminal) { if (inTerminal) {
bool ok = TerminalLauncher::launchDetached(command); bool ok = TerminalLauncher::launchDetached(command);
if (!ok) { if (!ok) {
QMessageBox::about(this, tr("Error"), QMessageBox::about(
tr("Unable to launch in terminal.")); this, tr("Error"), tr("Unable to launch in terminal."));
} }
} else { } else {
QProcess::startDetached(app_name,{m_tempFile}); QProcess::startDetached(app_name, { m_tempFile });
} }
if (!m_keepOpen) { if (!m_keepOpen) {
close(); close();
} }
} }
void AppLauncherWidget::checkboxClicked(const bool enabled) { void
AppLauncherWidget::checkboxClicked(const bool enabled)
{
m_keepOpen = enabled; m_keepOpen = enabled;
ConfigHandler().setKeepOpenAppLauncher(enabled); ConfigHandler().setKeepOpenAppLauncher(enabled);
m_keepOpenCheckbox->setChecked(enabled); m_keepOpenCheckbox->setChecked(enabled);
} }
void AppLauncherWidget::searchChanged(const QString &text) { void
AppLauncherWidget::searchChanged(const QString& text)
{
if (text.isEmpty()) { if (text.isEmpty()) {
m_filterList->hide(); m_filterList->hide();
m_tabWidget->show(); m_tabWidget->show();
@@ -139,15 +153,14 @@ void AppLauncherWidget::searchChanged(const QString &text) {
QVector<DesktopAppData> apps; QVector<DesktopAppData> apps;
for (auto const& i : catIconNames.toStdMap()) { for (auto const& i : catIconNames.toStdMap()) {
const QString &cat = i.first; const QString& cat = i.first;
if (!m_appsMap.contains(cat)) { if (!m_appsMap.contains(cat)) {
continue; continue;
} }
const QVector<DesktopAppData> &appList = m_appsMap[cat]; const QVector<DesktopAppData>& appList = m_appsMap[cat];
for (const DesktopAppData &app: appList) { for (const DesktopAppData& app : appList) {
if (!apps.contains(app) && (app.name.contains(regexp) || if (!apps.contains(app) &&
app.description.contains(regexp) )) (app.name.contains(regexp) || app.description.contains(regexp))) {
{
apps.append(app); apps.append(app);
} }
} }
@@ -156,35 +169,40 @@ void AppLauncherWidget::searchChanged(const QString &text) {
} }
} }
void AppLauncherWidget::initListWidget() { void
AppLauncherWidget::initListWidget()
{
m_tabWidget = new QTabWidget; m_tabWidget = new QTabWidget;
const int size = GlobalValues::buttonBaseSize(); const int size = GlobalValues::buttonBaseSize();
m_tabWidget->setIconSize(QSize(size, size)); m_tabWidget->setIconSize(QSize(size, size));
for (auto const& i : catIconNames.toStdMap()) { for (auto const& i : catIconNames.toStdMap()) {
const QString &cat = i.first; const QString& cat = i.first;
const QString &iconName = i.second; const QString& iconName = i.second;
if (!m_appsMap.contains(cat)) { if (!m_appsMap.contains(cat)) {
continue; continue;
} }
QListWidget *itemsWidget = new QListWidget(); QListWidget* itemsWidget = new QListWidget();
configureListView(itemsWidget); configureListView(itemsWidget);
const QVector<DesktopAppData> &appList = m_appsMap[cat]; const QVector<DesktopAppData>& appList = m_appsMap[cat];
addAppsToListWidget(itemsWidget, appList); addAppsToListWidget(itemsWidget, appList);
m_tabWidget->addTab(itemsWidget, QIcon::fromTheme(iconName), QLatin1String("")); m_tabWidget->addTab(
itemsWidget, QIcon::fromTheme(iconName), QLatin1String(""));
m_tabWidget->setTabToolTip(m_tabWidget->count(), cat); m_tabWidget->setTabToolTip(m_tabWidget->count(), cat);
if (cat == QLatin1String("Graphics")) { if (cat == QLatin1String("Graphics")) {
m_tabWidget->setCurrentIndex(m_tabWidget->count() -1); m_tabWidget->setCurrentIndex(m_tabWidget->count() - 1);
} }
} }
} }
void AppLauncherWidget::initAppMap() { void
QStringList categories({"AudioVideo", AppLauncherWidget::initAppMap()
{
QStringList categories({ "AudioVideo",
"Audio", "Audio",
"Video", "Video",
"Development", "Development",
@@ -194,16 +212,17 @@ void AppLauncherWidget::initAppMap() {
"Science", "Science",
"Settings", "Settings",
"System", "System",
"Utility"}); "Utility" });
m_appsMap = m_parser.getAppsByCategory(categories); m_appsMap = m_parser.getAppsByCategory(categories);
// Unify multimedia. // Unify multimedia.
QVector<DesktopAppData> multimediaList; QVector<DesktopAppData> multimediaList;
QStringList multimediaNames; QStringList multimediaNames;
multimediaNames << QStringLiteral("AudioVideo") << QStringLiteral("Audio") << QStringLiteral("Video"); multimediaNames << QStringLiteral("AudioVideo") << QStringLiteral("Audio")
for (const QString &name : multimediaNames) { << QStringLiteral("Video");
if(!m_appsMap.contains(name)) { for (const QString& name : multimediaNames) {
if (!m_appsMap.contains(name)) {
continue; continue;
} }
for (auto i : m_appsMap[name]) { for (auto i : m_appsMap[name]) {
@@ -216,7 +235,9 @@ void AppLauncherWidget::initAppMap() {
m_appsMap.insert(QStringLiteral("Multimedia"), multimediaList); m_appsMap.insert(QStringLiteral("Multimedia"), multimediaList);
} }
void AppLauncherWidget::configureListView(QListWidget *widget) { void
AppLauncherWidget::configureListView(QListWidget* widget)
{
widget->setItemDelegate(new LauncherItemDelegate()); widget->setItemDelegate(new LauncherItemDelegate());
widget->setViewMode(QListWidget::IconMode); widget->setViewMode(QListWidget::IconMode);
widget->setResizeMode(QListView::Adjust); widget->setResizeMode(QListView::Adjust);
@@ -224,21 +245,20 @@ void AppLauncherWidget::configureListView(QListWidget *widget) {
widget->setFlow(QListView::LeftToRight); widget->setFlow(QListView::LeftToRight);
widget->setDragEnabled(false); widget->setDragEnabled(false);
widget->setMinimumWidth(GlobalValues::buttonBaseSize() * 11); widget->setMinimumWidth(GlobalValues::buttonBaseSize() * 11);
connect(widget, &QListWidget::clicked, connect(widget, &QListWidget::clicked, this, &AppLauncherWidget::launch);
this, &AppLauncherWidget::launch);
} }
void AppLauncherWidget::addAppsToListWidget( void
QListWidget *widget, const QVector<DesktopAppData> &appList) AppLauncherWidget::addAppsToListWidget(QListWidget* widget,
const QVector<DesktopAppData>& appList)
{ {
for (const DesktopAppData &app: appList) { for (const DesktopAppData& app : appList) {
QListWidgetItem *buttonItem = new QListWidgetItem(widget); QListWidgetItem* buttonItem = new QListWidgetItem(widget);
buttonItem->setData(Qt::DecorationRole, app.icon); buttonItem->setData(Qt::DecorationRole, app.icon);
buttonItem->setData(Qt::DisplayRole, app.name); buttonItem->setData(Qt::DisplayRole, app.name);
buttonItem->setData(Qt::UserRole, app.exec); buttonItem->setData(Qt::UserRole, app.exec);
buttonItem->setData(Qt::UserRole+1, app.showInTerminal); buttonItem->setData(Qt::UserRole + 1, app.showInTerminal);
QColor foregroundColor = QColor foregroundColor = this->palette().color(QWidget::foregroundRole());
this->palette().color(QWidget::foregroundRole());
buttonItem->setForeground(foregroundColor); buttonItem->setForeground(foregroundColor);
buttonItem->setIcon(app.icon); buttonItem->setIcon(app.icon);

View File

@@ -18,8 +18,8 @@
#pragma once #pragma once
#include "src/utils/desktopfileparse.h" #include "src/utils/desktopfileparse.h"
#include <QWidget>
#include <QMap> #include <QMap>
#include <QWidget>
class QTabWidget; class QTabWidget;
class QCheckBox; class QCheckBox;
@@ -27,32 +27,33 @@ class QVBoxLayout;
class QLineEdit; class QLineEdit;
class QListWidget; class QListWidget;
class AppLauncherWidget: public QWidget { class AppLauncherWidget : public QWidget
{
Q_OBJECT Q_OBJECT
public: public:
explicit AppLauncherWidget(const QPixmap &p, QWidget *parent = nullptr); explicit AppLauncherWidget(const QPixmap& p, QWidget* parent = nullptr);
private slots: private slots:
void launch(const QModelIndex &index); void launch(const QModelIndex& index);
void checkboxClicked(const bool enabled); void checkboxClicked(const bool enabled);
void searchChanged(const QString &text); void searchChanged(const QString& text);
private: private:
void initListWidget(); void initListWidget();
void initAppMap(); void initAppMap();
void configureListView(QListWidget *widget); void configureListView(QListWidget* widget);
void addAppsToListWidget(QListWidget *widget, void addAppsToListWidget(QListWidget* widget,
const QVector<DesktopAppData> &appList); const QVector<DesktopAppData>& appList);
DesktopFileParser m_parser; DesktopFileParser m_parser;
QPixmap m_pixmap; QPixmap m_pixmap;
QString m_tempFile; QString m_tempFile;
bool m_keepOpen; bool m_keepOpen;
QMap<QString, QVector<DesktopAppData>> m_appsMap; QMap<QString, QVector<DesktopAppData>> m_appsMap;
QCheckBox *m_keepOpenCheckbox; QCheckBox* m_keepOpenCheckbox;
QCheckBox *m_terminalCheckbox; QCheckBox* m_terminalCheckbox;
QVBoxLayout *m_layout; QVBoxLayout* m_layout;
QLineEdit *m_lineEdit; QLineEdit* m_lineEdit;
QListWidget *m_filterList; QListWidget* m_filterList;
QTabWidget *m_tabWidget; QTabWidget* m_tabWidget;
}; };

View File

@@ -19,45 +19,46 @@
#include "src/utils/globalvalues.h" #include "src/utils/globalvalues.h"
#include <QPainter> #include <QPainter>
LauncherItemDelegate::LauncherItemDelegate(QObject *parent) : LauncherItemDelegate::LauncherItemDelegate(QObject* parent)
QStyledItemDelegate(parent) : QStyledItemDelegate(parent)
{ {}
}
void LauncherItemDelegate::paint( void
QPainter *painter, LauncherItemDelegate::paint(QPainter* painter,
const QStyleOptionViewItem &option, const QStyleOptionViewItem& option,
const QModelIndex &index) const const QModelIndex& index) const
{ {
const QRect &rect = option.rect; const QRect& rect = option.rect;
if (option.state & (QStyle::State_Selected | QStyle::State_MouseOver)) { if (option.state & (QStyle::State_Selected | QStyle::State_MouseOver)) {
painter->save(); painter->save();
painter->setPen(Qt::transparent); painter->setPen(Qt::transparent);
painter->setBrush(QPalette().highlight()); painter->setBrush(QPalette().highlight());
painter->drawRect(rect.x(), rect.y(), painter->drawRect(rect.x(), rect.y(), rect.width() - 1, rect.height() - 1);
rect.width() -1, rect.height() -1);
painter->restore(); painter->restore();
} }
QIcon icon = index.data(Qt::DecorationRole).value<QIcon>(); QIcon icon = index.data(Qt::DecorationRole).value<QIcon>();
const int iconSide = GlobalValues::buttonBaseSize() * 1.3; const int iconSide = GlobalValues::buttonBaseSize() * 1.3;
const int halfIcon = iconSide/2; const int halfIcon = iconSide / 2;
const int halfWidth = rect.width()/2; const int halfWidth = rect.width() / 2;
const int halfHeight = rect.height()/2; const int halfHeight = rect.height() / 2;
QSize size(iconSide, iconSide); QSize size(iconSide, iconSide);
QPixmap pixIcon = icon.pixmap(size).scaled(size, Qt::KeepAspectRatio); QPixmap pixIcon = icon.pixmap(size).scaled(size, Qt::KeepAspectRatio);
painter->drawPixmap(rect.x() + (halfWidth - halfIcon), painter->drawPixmap(rect.x() + (halfWidth - halfIcon),
rect.y()+ (halfHeight/2 - halfIcon), rect.y() + (halfHeight / 2 - halfIcon),
iconSide, iconSide, pixIcon); iconSide,
const QRect textRect(rect.x(), rect.y() + halfHeight, iconSide,
rect.width(), halfHeight); pixIcon);
painter->drawText(textRect, Qt::TextWordWrap | Qt::AlignHCenter, const QRect textRect(
rect.x(), rect.y() + halfHeight, rect.width(), halfHeight);
painter->drawText(textRect,
Qt::TextWordWrap | Qt::AlignHCenter,
index.data(Qt::DisplayRole).toString()); index.data(Qt::DisplayRole).toString());
} }
QSize LauncherItemDelegate::sizeHint( QSize
const QStyleOptionViewItem &option, LauncherItemDelegate::sizeHint(const QStyleOptionViewItem& option,
const QModelIndex &index) const const QModelIndex& index) const
{ {
Q_UNUSED(option); Q_UNUSED(option);
Q_UNUSED(index); Q_UNUSED(index);

View File

@@ -20,14 +20,16 @@
#include "src/utils/desktopfileparse.h" #include "src/utils/desktopfileparse.h"
#include <QStyledItemDelegate> #include <QStyledItemDelegate>
class LauncherItemDelegate : public QStyledItemDelegate { class LauncherItemDelegate : public QStyledItemDelegate
{
Q_OBJECT Q_OBJECT
public: public:
explicit LauncherItemDelegate(QObject *parent = nullptr); explicit LauncherItemDelegate(QObject* parent = nullptr);
void paint(QPainter *painter, void paint(QPainter* painter,
const QStyleOptionViewItem &option, const QStyleOptionViewItem& option,
const QModelIndex &index) const; const QModelIndex& index) const;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; QSize sizeHint(const QStyleOptionViewItem& option,
const QModelIndex& index) const;
}; };

View File

@@ -15,28 +15,30 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "openwithprogram.h" #include "openwithprogram.h"
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
#include "src/utils/filenamehandler.h" #include "src/utils/filenamehandler.h"
#include <QDir> #include <QDir>
#include <QMessageBox> #include <QMessageBox>
#include <windows.h>
#include <Shlobj.h> #include <Shlobj.h>
#include <windows.h>
#pragma comment(lib, "Shell32.lib") #pragma comment(lib, "Shell32.lib")
#else #else
#include "src/tools/launcher/applauncherwidget.h" #include "src/tools/launcher/applauncherwidget.h"
#endif #endif
void showOpenWithMenu(const QPixmap &capture) { void
showOpenWithMenu(const QPixmap& capture)
{
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
QString tempFile = QString tempFile =
FileNameHandler().generateAbsolutePath(QDir::tempPath()) + ".png"; FileNameHandler().generateAbsolutePath(QDir::tempPath()) + ".png";
bool ok = capture.save(tempFile); bool ok = capture.save(tempFile);
if (!ok) { if (!ok) {
QMessageBox::about(nullptr, QObject::tr("Error"), QMessageBox::about(nullptr,
QObject::tr("Error"),
QObject::tr("Unable to write in") + QDir::tempPath()); QObject::tr("Unable to write in") + QDir::tempPath());
return; return;
} }

View File

@@ -19,4 +19,5 @@
#include <QPixmap> #include <QPixmap>
void showOpenWithMenu(const QPixmap &capture); void
showOpenWithMenu(const QPixmap& capture);

View File

@@ -16,13 +16,13 @@
// along with Flameshot. If not, see <http://www.gnu.org/licenses/>. // along with Flameshot. If not, see <http://www.gnu.org/licenses/>.
#include "terminallauncher.h" #include "terminallauncher.h"
#include <QProcess>
#include <QDir> #include <QDir>
#include <QStandardPaths> #include <QProcess>
#include <QProcessEnvironment> #include <QProcessEnvironment>
#include <QStandardPaths>
namespace { namespace {
static const TerminalApp terminalApps[] = { static const TerminalApp terminalApps[] = {
{ "x-terminal-emulator", "-e" }, { "x-terminal-emulator", "-e" },
{ "xfce4-terminal", "-x" }, { "xfce4-terminal", "-x" },
{ "konsole", "-e" }, { "konsole", "-e" },
@@ -35,15 +35,18 @@ namespace {
{ "Eterm", "-e" }, { "Eterm", "-e" },
{ "rxvt", "-e" }, { "rxvt", "-e" },
{ "urxvt", "-e" }, { "urxvt", "-e" },
}; };
} }
TerminalLauncher::TerminalLauncher(QObject *parent) : QObject(parent) { TerminalLauncher::TerminalLauncher(QObject* parent)
} : QObject(parent)
{}
TerminalApp TerminalLauncher::getPreferedTerminal() { TerminalApp
TerminalLauncher::getPreferedTerminal()
{
TerminalApp res; TerminalApp res;
for (const TerminalApp &app : terminalApps) { for (const TerminalApp& app : terminalApps) {
QString path = QStandardPaths::findExecutable(app.name); QString path = QStandardPaths::findExecutable(app.name);
if (!path.isEmpty()) { if (!path.isEmpty()) {
res = app; res = app;
@@ -53,8 +56,10 @@ TerminalApp TerminalLauncher::getPreferedTerminal() {
return res; return res;
} }
bool TerminalLauncher::launchDetached(const QString &command) { bool
TerminalLauncher::launchDetached(const QString& command)
{
TerminalApp app = getPreferedTerminal(); TerminalApp app = getPreferedTerminal();
QString s = app.name + " " + app.arg + " " + command; QString s = app.name + " " + app.arg + " " + command;
return QProcess::startDetached(app.name, {app.arg,command}); return QProcess::startDetached(app.name, { app.arg, command });
} }

View File

@@ -19,17 +19,20 @@
#include <QObject> #include <QObject>
struct TerminalApp { struct TerminalApp
{
QString name; QString name;
QString arg; QString arg;
}; };
class TerminalLauncher : public QObject { class TerminalLauncher : public QObject
{
Q_OBJECT Q_OBJECT
public: public:
explicit TerminalLauncher(QObject *parent = nullptr); explicit TerminalLauncher(QObject* parent = nullptr);
static bool launchDetached(const QString& command);
static bool launchDetached(const QString &command);
private: private:
static TerminalApp getPreferedTerminal(); static TerminalApp getPreferedTerminal();
}; };

View File

@@ -24,32 +24,46 @@ namespace {
} }
LineTool::LineTool(QObject *parent) : AbstractTwoPointTool(parent) { LineTool::LineTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
m_supportsOrthogonalAdj = true; m_supportsOrthogonalAdj = true;
m_supportsDiagonalAdj = true; m_supportsDiagonalAdj = true;
} }
QIcon LineTool::icon(const QColor &background, bool inEditor) const { QIcon
LineTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "line.svg"); return QIcon(iconPath(background) + "line.svg");
} }
QString LineTool::name() const { QString
LineTool::name() const
{
return tr("Line"); return tr("Line");
} }
QString LineTool::nameID() { QString
LineTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString LineTool::description() const { QString
LineTool::description() const
{
return tr("Set the Line as the paint tool"); return tr("Set the Line as the paint tool");
} }
CaptureTool* LineTool::copy(QObject *parent) { CaptureTool*
LineTool::copy(QObject* parent)
{
return new LineTool(parent); return new LineTool(parent);
} }
void LineTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { void
LineTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo)
{
if (recordUndo) { if (recordUndo) {
updateBackup(pixmap); updateBackup(pixmap);
} }
@@ -57,18 +71,24 @@ void LineTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo
painter.drawLine(m_points.first, m_points.second); painter.drawLine(m_points.first, m_points.second);
} }
void LineTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { void
LineTool::paintMousePreview(QPainter& painter, const CaptureContext& context)
{
painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness));
painter.drawLine(context.mousePos, context.mousePos); painter.drawLine(context.mousePos, context.mousePos);
} }
void LineTool::drawStart(const CaptureContext &context) { void
LineTool::drawStart(const CaptureContext& context)
{
m_color = context.color; m_color = context.color;
m_thickness = context.thickness + PADDING_VALUE; m_thickness = context.thickness + PADDING_VALUE;
m_points.first = context.mousePos; m_points.first = context.mousePos;
m_points.second = context.mousePos; m_points.second = context.mousePos;
} }
void LineTool::pressed(const CaptureContext &context) { void
LineTool::pressed(const CaptureContext& context)
{
Q_UNUSED(context); Q_UNUSED(context);
} }

View File

@@ -19,22 +19,25 @@
#include "src/tools/abstracttwopointtool.h" #include "src/tools/abstracttwopointtool.h"
class LineTool : public AbstractTwoPointTool { class LineTool : public AbstractTwoPointTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit LineTool(QObject *parent = nullptr); explicit LineTool(QObject* parent = nullptr);
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
void process( void process(QPainter& painter,
QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; const QPixmap& pixmap,
void paintMousePreview(QPainter &painter, const CaptureContext &context) override; bool recordUndo = false) override;
void paintMousePreview(QPainter& painter,
const CaptureContext& context) override;
public slots: public slots:
void drawStart(const CaptureContext &context) override; void drawStart(const CaptureContext& context) override;
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
}; };

View File

@@ -24,32 +24,46 @@ namespace {
} }
MarkerTool::MarkerTool(QObject *parent) : AbstractTwoPointTool(parent) { MarkerTool::MarkerTool(QObject* parent)
: AbstractTwoPointTool(parent)
{
m_supportsOrthogonalAdj = true; m_supportsOrthogonalAdj = true;
m_supportsDiagonalAdj = true; m_supportsDiagonalAdj = true;
} }
QIcon MarkerTool::icon(const QColor &background, bool inEditor) const { QIcon
MarkerTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "marker.svg"); return QIcon(iconPath(background) + "marker.svg");
} }
QString MarkerTool::name() const { QString
MarkerTool::name() const
{
return tr("Marker"); return tr("Marker");
} }
QString MarkerTool::nameID() { QString
MarkerTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString MarkerTool::description() const { QString
MarkerTool::description() const
{
return tr("Set the Marker as the paint tool"); return tr("Set the Marker as the paint tool");
} }
CaptureTool* MarkerTool::copy(QObject *parent) { CaptureTool*
MarkerTool::copy(QObject* parent)
{
return new MarkerTool(parent); return new MarkerTool(parent);
} }
void MarkerTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { void
MarkerTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo)
{
if (recordUndo) { if (recordUndo) {
updateBackup(pixmap); updateBackup(pixmap);
} }
@@ -59,24 +73,32 @@ void MarkerTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUn
painter.drawLine(m_points.first, m_points.second); painter.drawLine(m_points.first, m_points.second);
} }
void MarkerTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { void
MarkerTool::paintMousePreview(QPainter& painter, const CaptureContext& context)
{
painter.setCompositionMode(QPainter::CompositionMode_Multiply); painter.setCompositionMode(QPainter::CompositionMode_Multiply);
painter.setOpacity(0.35); painter.setOpacity(0.35);
painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness));
painter.drawLine(context.mousePos, context.mousePos); painter.drawLine(context.mousePos, context.mousePos);
} }
void MarkerTool::drawStart(const CaptureContext &context) { void
MarkerTool::drawStart(const CaptureContext& context)
{
m_color = context.color; m_color = context.color;
m_thickness = context.thickness + PADDING_VALUE; m_thickness = context.thickness + PADDING_VALUE;
m_points.first = context.mousePos; m_points.first = context.mousePos;
m_points.second = context.mousePos; m_points.second = context.mousePos;
} }
void MarkerTool::pressed(const CaptureContext &context) { void
MarkerTool::pressed(const CaptureContext& context)
{
Q_UNUSED(context); Q_UNUSED(context);
} }
void MarkerTool::thicknessChanged(const int th) { void
MarkerTool::thicknessChanged(const int th)
{
m_thickness = th + PADDING_VALUE; m_thickness = th + PADDING_VALUE;
} }

View File

@@ -19,23 +19,26 @@
#include "src/tools/abstracttwopointtool.h" #include "src/tools/abstracttwopointtool.h"
class MarkerTool : public AbstractTwoPointTool { class MarkerTool : public AbstractTwoPointTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit MarkerTool(QObject *parent = nullptr); explicit MarkerTool(QObject* parent = nullptr);
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
void process( void process(QPainter& painter,
QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; const QPixmap& pixmap,
void paintMousePreview(QPainter &painter, const CaptureContext &context) override; bool recordUndo = false) override;
void paintMousePreview(QPainter& painter,
const CaptureContext& context) override;
public slots: public slots:
void drawStart(const CaptureContext &context) override; void drawStart(const CaptureContext& context) override;
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
void thicknessChanged(const int th) override; void thicknessChanged(const int th) override;
}; };

View File

@@ -18,35 +18,49 @@
#include "movetool.h" #include "movetool.h"
#include <QPainter> #include <QPainter>
MoveTool::MoveTool(QObject *parent) : AbstractActionTool(parent) { MoveTool::MoveTool(QObject* parent)
: AbstractActionTool(parent)
{}
} bool
MoveTool::closeOnButtonPressed() const
bool MoveTool::closeOnButtonPressed() const { {
return false; return false;
} }
QIcon MoveTool::icon(const QColor &background, bool inEditor) const { QIcon
MoveTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "cursor-move.svg"); return QIcon(iconPath(background) + "cursor-move.svg");
} }
QString MoveTool::name() const { QString
MoveTool::name() const
{
return tr("Move"); return tr("Move");
} }
QString MoveTool::nameID() { QString
MoveTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString MoveTool::description() const { QString
MoveTool::description() const
{
return tr("Move the selection area"); return tr("Move the selection area");
} }
CaptureTool* MoveTool::copy(QObject *parent) { CaptureTool*
MoveTool::copy(QObject* parent)
{
return new MoveTool(parent); return new MoveTool(parent);
} }
void MoveTool::pressed(const CaptureContext &context) { void
MoveTool::pressed(const CaptureContext& context)
{
Q_UNUSED(context); Q_UNUSED(context);
emit requestAction(REQ_MOVE_MODE); emit requestAction(REQ_MOVE_MODE);
} }

View File

@@ -19,20 +19,21 @@
#include "src/tools/abstractactiontool.h" #include "src/tools/abstractactiontool.h"
class MoveTool : public AbstractActionTool { class MoveTool : public AbstractActionTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit MoveTool(QObject *parent = nullptr); explicit MoveTool(QObject* parent = nullptr);
bool closeOnButtonPressed() const; bool closeOnButtonPressed() const;
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
public slots: public slots:
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
}; };

View File

@@ -18,31 +18,43 @@
#include "penciltool.h" #include "penciltool.h"
#include <QPainter> #include <QPainter>
PencilTool::PencilTool(QObject *parent) : AbstractPathTool(parent) { PencilTool::PencilTool(QObject* parent)
: AbstractPathTool(parent)
{}
} QIcon
PencilTool::icon(const QColor& background, bool inEditor) const
QIcon PencilTool::icon(const QColor &background, bool inEditor) const { {
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "pencil.svg"); return QIcon(iconPath(background) + "pencil.svg");
} }
QString PencilTool::name() const { QString
PencilTool::name() const
{
return tr("Pencil"); return tr("Pencil");
} }
QString PencilTool::nameID() { QString
PencilTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString PencilTool::description() const { QString
PencilTool::description() const
{
return tr("Set the Pencil as the paint tool"); return tr("Set the Pencil as the paint tool");
} }
CaptureTool* PencilTool::copy(QObject *parent) { CaptureTool*
PencilTool::copy(QObject* parent)
{
return new PencilTool(parent); return new PencilTool(parent);
} }
void PencilTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { void
PencilTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo)
{
if (recordUndo) { if (recordUndo) {
updateBackup(pixmap); updateBackup(pixmap);
} }
@@ -50,12 +62,16 @@ void PencilTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUn
painter.drawPolyline(m_points.data(), m_points.size()); painter.drawPolyline(m_points.data(), m_points.size());
} }
void PencilTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { void
PencilTool::paintMousePreview(QPainter& painter, const CaptureContext& context)
{
painter.setPen(QPen(context.color, context.thickness + 2)); painter.setPen(QPen(context.color, context.thickness + 2));
painter.drawLine(context.mousePos, context.mousePos); painter.drawLine(context.mousePos, context.mousePos);
} }
void PencilTool::drawStart(const CaptureContext &context) { void
PencilTool::drawStart(const CaptureContext& context)
{
m_color = context.color; m_color = context.color;
m_thickness = context.thickness + 2; m_thickness = context.thickness + 2;
m_points.append(context.mousePos); m_points.append(context.mousePos);
@@ -63,6 +79,8 @@ void PencilTool::drawStart(const CaptureContext &context) {
m_backupArea.setBottomRight(context.mousePos); m_backupArea.setBottomRight(context.mousePos);
} }
void PencilTool::pressed(const CaptureContext &context) { void
PencilTool::pressed(const CaptureContext& context)
{
Q_UNUSED(context); Q_UNUSED(context);
} }

View File

@@ -19,23 +19,26 @@
#include "src/tools/abstractpathtool.h" #include "src/tools/abstractpathtool.h"
class PencilTool : public AbstractPathTool { class PencilTool : public AbstractPathTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit PencilTool(QObject *parent = nullptr); explicit PencilTool(QObject* parent = nullptr);
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
void process( void process(QPainter& painter,
QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; const QPixmap& pixmap,
void paintMousePreview(QPainter &painter, const CaptureContext &context) override; bool recordUndo = false) override;
void paintMousePreview(QPainter& painter,
const CaptureContext& context) override;
public slots: public slots:
void drawStart(const CaptureContext &context) override; void drawStart(const CaptureContext& context) override;
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
}; };

View File

@@ -18,47 +18,62 @@
#include "pintool.h" #include "pintool.h"
#include "src/tools/pin/pinwidget.h" #include "src/tools/pin/pinwidget.h"
PinTool::PinTool(QObject *parent) : AbstractActionTool(parent) { PinTool::PinTool(QObject* parent)
: AbstractActionTool(parent)
{}
} bool
PinTool::closeOnButtonPressed() const
bool PinTool::closeOnButtonPressed() const { {
return true; return true;
} }
QIcon PinTool::icon(const QColor &background, bool inEditor) const { QIcon
PinTool::icon(const QColor& background, bool inEditor) const
{
Q_UNUSED(inEditor); Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "pin.svg"); return QIcon(iconPath(background) + "pin.svg");
} }
QString PinTool::name() const { QString
PinTool::name() const
{
return tr("Pin Tool"); return tr("Pin Tool");
} }
QString PinTool::nameID() { QString
PinTool::nameID()
{
return QLatin1String(""); return QLatin1String("");
} }
QString PinTool::description() const { QString
PinTool::description() const
{
return tr("Pin image on the desktop"); return tr("Pin image on the desktop");
} }
QWidget* PinTool::widget() { QWidget*
PinWidget *w = new PinWidget(m_pixmap); PinTool::widget()
const int &&m = w->margin(); {
PinWidget* w = new PinWidget(m_pixmap);
const int&& m = w->margin();
QRect adjusted_pos = m_geometry + QMargins(m, m, m, m); QRect adjusted_pos = m_geometry + QMargins(m, m, m, m);
w->setGeometry(adjusted_pos); w->setGeometry(adjusted_pos);
return w; return w;
} }
CaptureTool* PinTool::copy(QObject *parent) { CaptureTool*
PinTool::copy(QObject* parent)
{
return new PinTool(parent); return new PinTool(parent);
} }
void PinTool::pressed(const CaptureContext &context) { void
PinTool::pressed(const CaptureContext& context)
{
emit requestAction(REQ_CAPTURE_DONE_OK); emit requestAction(REQ_CAPTURE_DONE_OK);
m_geometry = context.selection; m_geometry = context.selection;
m_geometry.setTopLeft(m_geometry.topLeft() + context.widgetOffset); m_geometry.setTopLeft(m_geometry.topLeft() + context.widgetOffset);
m_pixmap = context.selectedScreenshotArea(); m_pixmap = context.selectedScreenshotArea();
emit requestAction(REQ_ADD_EXTERNAL_WIDGETS); emit requestAction(REQ_ADD_EXTERNAL_WIDGETS);
} }

11
src/tools/pin/pintool.h Executable file → Normal file
View File

@@ -19,24 +19,25 @@
#include "src/tools/abstractactiontool.h" #include "src/tools/abstractactiontool.h"
class PinTool : public AbstractActionTool { class PinTool : public AbstractActionTool
{
Q_OBJECT Q_OBJECT
public: public:
explicit PinTool(QObject *parent = nullptr); explicit PinTool(QObject* parent = nullptr);
bool closeOnButtonPressed() const; bool closeOnButtonPressed() const;
QIcon icon(const QColor &background, bool inEditor) const override; QIcon icon(const QColor& background, bool inEditor) const override;
QString name() const override; QString name() const override;
static QString nameID(); static QString nameID();
QString description() const override; QString description() const override;
QWidget* widget() override; QWidget* widget() override;
CaptureTool* copy(QObject *parent = nullptr) override; CaptureTool* copy(QObject* parent = nullptr) override;
public slots: public slots:
void pressed(const CaptureContext &context) override; void pressed(const CaptureContext& context) override;
private: private:
QRect m_geometry; QRect m_geometry;

Some files were not shown because too many files have changed in this diff Show More