diff --git a/commands/imagelib/effects/kpEffectBalanceCommand.h b/commands/imagelib/effects/kpEffectBalanceCommand.h --- a/commands/imagelib/effects/kpEffectBalanceCommand.h +++ b/commands/imagelib/effects/kpEffectBalanceCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,32 +24,26 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectBalanceCommand_H #define kpEffectBalanceCommand_H - #include "kpEffectCommandBase.h" #include "imagelib/kpImage.h" - class kpEffectBalanceCommand : public kpEffectCommandBase { public: // (, & are from -50 to 50) - kpEffectBalanceCommand (int channels, - int brightness, int contrast, int gamma, - bool actOnSelection, - kpCommandEnvironment *environ); + kpEffectBalanceCommand (int channels, int brightness, int contrast, int gamma, + bool actOnSelection, kpCommandEnvironment *environ); ~kpEffectBalanceCommand () override; protected: - kpImage applyEffect (const kpImage &image) override; + kpImage applyEffect(const kpImage &image) override; protected: int m_channels; int m_brightness, m_contrast, m_gamma; }; - #endif // kpEffectBalanceCommand_H diff --git a/commands/imagelib/effects/kpEffectBalanceCommand.cpp b/commands/imagelib/effects/kpEffectBalanceCommand.cpp --- a/commands/imagelib/effects/kpEffectBalanceCommand.cpp +++ b/commands/imagelib/effects/kpEffectBalanceCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -33,23 +32,22 @@ //-------------------------------------------------------------------------------- -kpEffectBalanceCommand::kpEffectBalanceCommand (int channels, - int brightness, int contrast, int gamma, - bool actOnSelection, - kpCommandEnvironment *environ) - : kpEffectCommandBase (i18n ("Balance"), actOnSelection, environ), - m_channels (channels), - m_brightness (brightness), m_contrast (contrast), m_gamma (gamma) +kpEffectBalanceCommand::kpEffectBalanceCommand (int channels, int brightness, int contrast, + int gamma, bool actOnSelection, + kpCommandEnvironment *environ) + : kpEffectCommandBase(i18n("Balance"), actOnSelection, environ) + , m_channels(channels) + , m_brightness(brightness) + , m_contrast(contrast) + , m_gamma(gamma) { } kpEffectBalanceCommand::~kpEffectBalanceCommand () = default; - // protected virtual [base kpEffectCommandBase] -kpImage kpEffectBalanceCommand::applyEffect (const kpImage &image) +kpImage kpEffectBalanceCommand::applyEffect(const kpImage &image) { - return kpEffectBalance::applyEffect (image, m_channels, - m_brightness, m_contrast, m_gamma); + return kpEffectBalance::applyEffect(image, m_channels, + m_brightness, m_contrast, m_gamma); } - diff --git a/commands/imagelib/effects/kpEffectBlurSharpenCommand.h b/commands/imagelib/effects/kpEffectBlurSharpenCommand.h --- a/commands/imagelib/effects/kpEffectBlurSharpenCommand.h +++ b/commands/imagelib/effects/kpEffectBlurSharpenCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,34 +24,28 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectBlurSharpenCommand_H #define kpEffectBlurSharpenCommand_H - #include "kpEffectCommandBase.h" #include "imagelib/effects/kpEffectBlurSharpen.h" #include "imagelib/kpImage.h" - class kpEffectBlurSharpenCommand : public kpEffectCommandBase { public: - kpEffectBlurSharpenCommand (kpEffectBlurSharpen::Type type, - int strength, - bool actOnSelection, + kpEffectBlurSharpenCommand (kpEffectBlurSharpen::Type type, int strength, bool actOnSelection, kpCommandEnvironment *environ); ~kpEffectBlurSharpenCommand () override; - static QString nameForType (kpEffectBlurSharpen::Type type); + static QString nameForType(kpEffectBlurSharpen::Type type); protected: - kpImage applyEffect (const kpImage &image) override; + kpImage applyEffect(const kpImage &image) override; protected: kpEffectBlurSharpen::Type m_type; int m_strength; }; - #endif // kpEffectBlurSharpenCommand_H diff --git a/commands/imagelib/effects/kpEffectBlurSharpenCommand.cpp b/commands/imagelib/effects/kpEffectBlurSharpenCommand.cpp --- a/commands/imagelib/effects/kpEffectBlurSharpenCommand.cpp +++ b/commands/imagelib/effects/kpEffectBlurSharpenCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,44 +24,41 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_BLUR_SHARPEN 0 - #include "kpEffectBlurSharpenCommand.h" #include //-------------------------------------------------------------------------------- kpEffectBlurSharpenCommand::kpEffectBlurSharpenCommand (kpEffectBlurSharpen::Type type, - int strength, - bool actOnSelection, - kpCommandEnvironment *environ) - : kpEffectCommandBase (kpEffectBlurSharpenCommand::nameForType (type), - actOnSelection, environ), - m_type (type), - m_strength (strength) + int strength, bool actOnSelection, + kpCommandEnvironment *environ) + : kpEffectCommandBase(kpEffectBlurSharpenCommand::nameForType(type), + actOnSelection, environ) + , m_type(type) + , m_strength(strength) { } kpEffectBlurSharpenCommand::~kpEffectBlurSharpenCommand () = default; - // public static -QString kpEffectBlurSharpenCommand::nameForType (kpEffectBlurSharpen::Type type) +QString kpEffectBlurSharpenCommand::nameForType(kpEffectBlurSharpen::Type type) { switch (type) { - case kpEffectBlurSharpen::Blur: return i18n ("Soften"); - case kpEffectBlurSharpen::Sharpen: return i18n ("Sharpen"); - default: return {}; + case kpEffectBlurSharpen::Blur: + return i18n("Soften"); + case kpEffectBlurSharpen::Sharpen: + return i18n("Sharpen"); + default: + return {}; } } - // protected virtual [base kpEffectCommandBase] -kpImage kpEffectBlurSharpenCommand::applyEffect (const kpImage &image) +kpImage kpEffectBlurSharpenCommand::applyEffect(const kpImage &image) { - return kpEffectBlurSharpen::applyEffect (image, m_type, m_strength); + return kpEffectBlurSharpen::applyEffect(image, m_type, m_strength); } - diff --git a/commands/imagelib/effects/kpEffectClearCommand.h b/commands/imagelib/effects/kpEffectClearCommand.h --- a/commands/imagelib/effects/kpEffectClearCommand.h +++ b/commands/imagelib/effects/kpEffectClearCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,38 +24,33 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectClearCommand_H #define kpEffectClearCommand_H - #include "commands/kpCommand.h" #include "imagelib/kpColor.h" #include "imagelib/kpImage.h" - class kpEffectClearCommand : public kpCommand { public: - kpEffectClearCommand (bool actOnSelection, - const kpColor &newColor, - kpCommandEnvironment *environ); + kpEffectClearCommand (bool actOnSelection, const kpColor &newColor, + kpCommandEnvironment *environ); ~kpEffectClearCommand () override; - QString name () const override; + QString name() const override; - SizeType size () const override; + SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: bool m_actOnSelection; kpColor m_newColor; kpImage *m_oldImagePtr; }; - #endif // kpEffectClearCommand_H diff --git a/commands/imagelib/effects/kpEffectClearCommand.cpp b/commands/imagelib/effects/kpEffectClearCommand.cpp --- a/commands/imagelib/effects/kpEffectClearCommand.cpp +++ b/commands/imagelib/effects/kpEffectClearCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpEffectClearCommand.h" #include "layers/selections/image/kpAbstractImageSelection.h" @@ -36,75 +34,64 @@ //-------------------------------------------------------------------------------- -kpEffectClearCommand::kpEffectClearCommand (bool actOnSelection, - const kpColor &newColor, - kpCommandEnvironment *environ) - : kpCommand (environ), - m_actOnSelection (actOnSelection), - m_newColor (newColor), - m_oldImagePtr (nullptr) +kpEffectClearCommand::kpEffectClearCommand (bool actOnSelection, const kpColor &newColor, + kpCommandEnvironment *environ) + : kpCommand(environ) + , m_actOnSelection(actOnSelection) + , m_newColor(newColor) + , m_oldImagePtr(nullptr) { } kpEffectClearCommand::~kpEffectClearCommand () { delete m_oldImagePtr; } - // public virtual [base kpCommand] -QString kpEffectClearCommand::name () const +QString kpEffectClearCommand::name() const { - QString opName = i18n ("Clear"); + QString opName = i18n("Clear"); - return (m_actOnSelection) ? i18n ("Selection: %1", opName) : opName; + return (m_actOnSelection) ? i18n("Selection: %1", opName) : opName; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpEffectClearCommand::size () const +kpCommandSize::SizeType kpEffectClearCommand::size() const { - return ImageSize (m_oldImagePtr); + return ImageSize(m_oldImagePtr); } - // public virtual [base kpCommand] -void kpEffectClearCommand::execute () +void kpEffectClearCommand::execute() { - kpDocument *doc = document (); - Q_ASSERT (doc); - - - m_oldImagePtr = new kpImage (); - *m_oldImagePtr = doc->image (m_actOnSelection); + kpDocument *doc = document(); + Q_ASSERT(doc); + m_oldImagePtr = new kpImage(); + *m_oldImagePtr = doc->image(m_actOnSelection); // REFACTOR: Would like to derive entire class from kpEffectCommandBase but // this code makes it difficult since it's not just acting on pixels // (kpAbstractImageSelection::fill() takes into account the shape of a selection). - if (m_actOnSelection) - { + if (m_actOnSelection) { // OPT: could just edit pixmap directly and signal change - kpAbstractImageSelection *sel = doc->imageSelection (); - Q_ASSERT (sel); - sel->fill (m_newColor); - } - else { - doc->fill (m_newColor); + kpAbstractImageSelection *sel = doc->imageSelection(); + Q_ASSERT(sel); + sel->fill(m_newColor); + } else { + doc->fill(m_newColor); } } // public virtual [base kpCommand] -void kpEffectClearCommand::unexecute () +void kpEffectClearCommand::unexecute() { - kpDocument *doc = document (); - Q_ASSERT (doc); - - - doc->setImage (m_actOnSelection, *m_oldImagePtr); + kpDocument *doc = document(); + Q_ASSERT(doc); + doc->setImage(m_actOnSelection, *m_oldImagePtr); delete m_oldImagePtr; m_oldImagePtr = nullptr; } - diff --git a/commands/imagelib/effects/kpEffectCommandBase.h b/commands/imagelib/effects/kpEffectCommandBase.h --- a/commands/imagelib/effects/kpEffectCommandBase.h +++ b/commands/imagelib/effects/kpEffectCommandBase.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,43 +24,40 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectCommandBase_H #define kpEffectCommandBase_H - #include #include "commands/kpCommand.h" #include "imagelib/kpImage.h" - class kpEffectCommandBase : public kpCommand { public: - kpEffectCommandBase (const QString &name, - bool actOnSelection, - kpCommandEnvironment *environ); + kpEffectCommandBase (const QString &name, bool actOnSelection, kpCommandEnvironment *environ); ~kpEffectCommandBase () override; - QString name () const override; - SizeType size () const override; + QString name() const override; + SizeType size() const override; public: - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; public: // Return true if applyEffect(applyEffect(image)) == image // to avoid storing the old image, saving memory. - virtual bool isInvertible () const { return false; } + virtual bool isInvertible() const + { + return false; + } protected: - virtual kpImage applyEffect (const kpImage &image) = 0; + virtual kpImage applyEffect(const kpImage &image) = 0; private: struct kpEffectCommandBasePrivate *d; }; - #endif // kpEffectCommandBase_H diff --git a/commands/imagelib/effects/kpEffectCommandBase.cpp b/commands/imagelib/effects/kpEffectCommandBase.cpp --- a/commands/imagelib/effects/kpEffectCommandBase.cpp +++ b/commands/imagelib/effects/kpEffectCommandBase.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpEffectCommandBase.h" #include "kpDefs.h" @@ -44,11 +42,10 @@ kpImage oldImage; }; -kpEffectCommandBase::kpEffectCommandBase (const QString &name, - bool actOnSelection, - kpCommandEnvironment *environ) - : kpCommand (environ), - d (new kpEffectCommandBasePrivate ()) +kpEffectCommandBase::kpEffectCommandBase (const QString &name, bool actOnSelection, + kpCommandEnvironment *environ) + : kpCommand(environ) + , d(new kpEffectCommandBasePrivate()) { d->name = name; d->actOnSelection = actOnSelection; @@ -59,66 +56,54 @@ delete d; } - // public virtual [base kpCommand] -QString kpEffectCommandBase::name () const +QString kpEffectCommandBase::name() const { - return (d->actOnSelection) ? i18n ("Selection: %1", d->name) : d->name; + return (d->actOnSelection) ? i18n("Selection: %1", d->name) : d->name; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpEffectCommandBase::size () const +kpCommandSize::SizeType kpEffectCommandBase::size() const { - return ImageSize (d->oldImage); + return ImageSize(d->oldImage); } - // public virtual [base kpCommand] -void kpEffectCommandBase::execute () +void kpEffectCommandBase::execute() { - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); - - kpDocument *doc = document (); - Q_ASSERT (doc); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); + kpDocument *doc = document(); + Q_ASSERT(doc); - const kpImage oldImage = doc->image (d->actOnSelection); + const kpImage oldImage = doc->image(d->actOnSelection); - if (!isInvertible ()) - { + if (!isInvertible()) { d->oldImage = oldImage; } + kpImage newImage = /*pure virtual*/ applyEffect(oldImage); - kpImage newImage = /*pure virtual*/applyEffect (oldImage); - - doc->setImage (d->actOnSelection, newImage); + doc->setImage(d->actOnSelection, newImage); } // public virtual [base kpCommand] -void kpEffectCommandBase::unexecute () +void kpEffectCommandBase::unexecute() { - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); - - kpDocument *doc = document (); - Q_ASSERT (doc); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); + kpDocument *doc = document(); + Q_ASSERT(doc); kpImage newImage; - if (!isInvertible ()) - { + if (!isInvertible()) { newImage = d->oldImage; - } - else - { - newImage = /*pure virtual*/applyEffect (doc->image (d->actOnSelection)); + } else { + newImage = /*pure virtual*/ applyEffect(doc->image(d->actOnSelection)); } - doc->setImage (d->actOnSelection, newImage); + doc->setImage(d->actOnSelection, newImage); - - d->oldImage = kpImage (); + d->oldImage = kpImage(); } - diff --git a/commands/imagelib/effects/kpEffectEmbossCommand.h b/commands/imagelib/effects/kpEffectEmbossCommand.h --- a/commands/imagelib/effects/kpEffectEmbossCommand.h +++ b/commands/imagelib/effects/kpEffectEmbossCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,29 +24,23 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectEmbossCommand_H #define kpEffectEmbossCommand_H - #include "kpEffectCommandBase.h" #include "imagelib/kpImage.h" - class kpEffectEmbossCommand : public kpEffectCommandBase { public: - kpEffectEmbossCommand (int strength, - bool actOnSelection, - kpCommandEnvironment *environ); + kpEffectEmbossCommand (int strength, bool actOnSelection, kpCommandEnvironment *environ); ~kpEffectEmbossCommand () override; protected: - kpImage applyEffect (const kpImage &image) override; + kpImage applyEffect(const kpImage &image) override; protected: int m_strength; }; - #endif // kpEffectEmbossCommand_H diff --git a/commands/imagelib/effects/kpEffectEmbossCommand.cpp b/commands/imagelib/effects/kpEffectEmbossCommand.cpp --- a/commands/imagelib/effects/kpEffectEmbossCommand.cpp +++ b/commands/imagelib/effects/kpEffectEmbossCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,31 +24,25 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_EMBOSS 0 - #include "kpEffectEmbossCommand.h" #include "imagelib/effects/kpEffectEmboss.h" #include "kpLogCategories.h" #include - -kpEffectEmbossCommand::kpEffectEmbossCommand (int strength, - bool actOnSelection, - kpCommandEnvironment *environ) - : kpEffectCommandBase (i18n ("Emboss"), actOnSelection, environ), - m_strength (strength) +kpEffectEmbossCommand::kpEffectEmbossCommand (int strength, bool actOnSelection, + kpCommandEnvironment *environ) + : kpEffectCommandBase(i18n("Emboss"), actOnSelection, environ) + , m_strength(strength) { } kpEffectEmbossCommand::~kpEffectEmbossCommand () = default; - // protected virtual [base kpEffectCommandBase] -kpImage kpEffectEmbossCommand::applyEffect (const kpImage &image) +kpImage kpEffectEmbossCommand::applyEffect(const kpImage &image) { - return kpEffectEmboss::applyEffect (image, m_strength); + return kpEffectEmboss::applyEffect(image, m_strength); } - diff --git a/commands/imagelib/effects/kpEffectFlattenCommand.h b/commands/imagelib/effects/kpEffectFlattenCommand.h --- a/commands/imagelib/effects/kpEffectFlattenCommand.h +++ b/commands/imagelib/effects/kpEffectFlattenCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,35 +24,29 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectFlattenCommand_H #define kpEffectFlattenCommand_H - #include #include "kpEffectCommandBase.h" #include "imagelib/kpImage.h" - class kpEffectFlattenCommand : public kpEffectCommandBase { public: - kpEffectFlattenCommand (const QColor &color1, const QColor &color2, - bool actOnSelection, + kpEffectFlattenCommand (const QColor &color1, const QColor &color2, bool actOnSelection, kpCommandEnvironment *environ); ~kpEffectFlattenCommand () override; - // // kpEffectCommandBase interface // protected: - kpImage applyEffect (const kpImage &image) override; + kpImage applyEffect(const kpImage &image) override; QColor m_color1, m_color2; }; - #endif // kpEffectFlattenCommand_H diff --git a/commands/imagelib/effects/kpEffectFlattenCommand.cpp b/commands/imagelib/effects/kpEffectFlattenCommand.cpp --- a/commands/imagelib/effects/kpEffectFlattenCommand.cpp +++ b/commands/imagelib/effects/kpEffectFlattenCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,37 +24,31 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_FLATTEN 0 - #include "kpEffectFlattenCommand.h" #include "imagelib/effects/kpEffectFlatten.h" #include //-------------------------------------------------------------------------------- -kpEffectFlattenCommand::kpEffectFlattenCommand (const QColor &color1, - const QColor &color2, - bool actOnSelection, - kpCommandEnvironment *environ) - : kpEffectCommandBase (i18n ("Flatten"), actOnSelection, environ), - m_color1 (color1), m_color2 (color2) +kpEffectFlattenCommand::kpEffectFlattenCommand (const QColor &color1, const QColor &color2, + bool actOnSelection, kpCommandEnvironment *environ) + : kpEffectCommandBase(i18n("Flatten"), actOnSelection, environ) + , m_color1(color1) + , m_color2(color2) { } kpEffectFlattenCommand::~kpEffectFlattenCommand () = default; - // // kpEffectFlattenCommand implements kpEffectCommandBase interface // // protected virtual [base kpEffectCommandBase] -kpImage kpEffectFlattenCommand::applyEffect (const kpImage &image) +kpImage kpEffectFlattenCommand::applyEffect(const kpImage &image) { - return kpEffectFlatten::applyEffect (image, m_color1, m_color2); + return kpEffectFlatten::applyEffect(image, m_color1, m_color2); } - - diff --git a/commands/imagelib/effects/kpEffectGrayscaleCommand.h b/commands/imagelib/effects/kpEffectGrayscaleCommand.h --- a/commands/imagelib/effects/kpEffectGrayscaleCommand.h +++ b/commands/imagelib/effects/kpEffectGrayscaleCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,33 +24,30 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectGrayscaleCommand_H #define kpEffectGrayscaleCommand_H - #include "kpEffectCommandBase.h" #include "imagelib/kpImage.h" - class kpEffectGrayscaleCommand : public kpEffectCommandBase { public: - kpEffectGrayscaleCommand (bool actOnSelection, - kpCommandEnvironment *environ); + kpEffectGrayscaleCommand (bool actOnSelection, kpCommandEnvironment *environ); ~kpEffectGrayscaleCommand () override; - // // kpEffectCommandBase interface // public: - bool isInvertible () const override { return false; } + bool isInvertible() const override + { + return false; + } protected: - kpImage applyEffect (const kpImage &image) override; + kpImage applyEffect(const kpImage &image) override; }; - #endif // kpEffectGrayscaleCommand_H diff --git a/commands/imagelib/effects/kpEffectGrayscaleCommand.cpp b/commands/imagelib/effects/kpEffectGrayscaleCommand.cpp --- a/commands/imagelib/effects/kpEffectGrayscaleCommand.cpp +++ b/commands/imagelib/effects/kpEffectGrayscaleCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,35 +24,31 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpEffectGrayscaleCommand.h" #include "imagelib/effects/kpEffectGrayscale.h" #include //-------------------------------------------------------------------------------- kpEffectGrayscaleCommand::kpEffectGrayscaleCommand ( - bool actOnSelection, - kpCommandEnvironment *environ) + bool actOnSelection, kpCommandEnvironment *environ) - : kpEffectCommandBase ( - i18n ("Reduce to Grayscale"), + : kpEffectCommandBase( + i18n("Reduce to Grayscale"), actOnSelection, environ) { } kpEffectGrayscaleCommand::~kpEffectGrayscaleCommand () = default; - // // kpEffectGrayscaleCommand implements kpEffectCommandBase interface // // protected virtual [base kpEffectCommandBase] -kpImage kpEffectGrayscaleCommand::applyEffect (const kpImage &image) +kpImage kpEffectGrayscaleCommand::applyEffect(const kpImage &image) { - return kpEffectGrayscale::applyEffect (image); + return kpEffectGrayscale::applyEffect(image); } - diff --git a/commands/imagelib/effects/kpEffectHSVCommand.h b/commands/imagelib/effects/kpEffectHSVCommand.h --- a/commands/imagelib/effects/kpEffectHSVCommand.h +++ b/commands/imagelib/effects/kpEffectHSVCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2007 Mike Gashler All rights reserved. @@ -25,27 +24,22 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectHSVCommand_H #define kpEffectHSVCommand_H - #include "kpEffectCommandBase.h" - class kpEffectHSVCommand : public kpEffectCommandBase { public: - kpEffectHSVCommand (double hue, double saturation, double value, - bool actOnSelection, - kpCommandEnvironment *environ); + kpEffectHSVCommand (double hue, double saturation, double value, bool actOnSelection, + kpCommandEnvironment *environ); protected: - kpImage applyEffect (const kpImage &image) override; + kpImage applyEffect(const kpImage &image) override; protected: double m_hue, m_saturation, m_value; }; - #endif // kpEffectHSVCommand_H diff --git a/commands/imagelib/effects/kpEffectHSVCommand.cpp b/commands/imagelib/effects/kpEffectHSVCommand.cpp --- a/commands/imagelib/effects/kpEffectHSVCommand.cpp +++ b/commands/imagelib/effects/kpEffectHSVCommand.cpp @@ -32,19 +32,20 @@ //--------------------------------------------------------------------- kpEffectHSVCommand::kpEffectHSVCommand (double hue, double saturation, double value, - bool actOnSelection, - kpCommandEnvironment *environ) - : kpEffectCommandBase (i18n ("Hue, Saturation, Value"), actOnSelection, environ), - m_hue (hue), m_saturation (saturation), m_value (value) + bool actOnSelection, kpCommandEnvironment *environ) + : kpEffectCommandBase(i18n("Hue, Saturation, Value"), actOnSelection, environ) + , m_hue(hue) + , m_saturation(saturation) + , m_value(value) { } //--------------------------------------------------------------------- // protected virtual [base kpEffectCommandBase] -kpImage kpEffectHSVCommand::applyEffect (const kpImage &image) +kpImage kpEffectHSVCommand::applyEffect(const kpImage &image) { - return kpEffectHSV::applyEffect (image, m_hue, m_saturation, m_value); + return kpEffectHSV::applyEffect(image, m_hue, m_saturation, m_value); } //--------------------------------------------------------------------- diff --git a/commands/imagelib/effects/kpEffectInvertCommand.h b/commands/imagelib/effects/kpEffectInvertCommand.h --- a/commands/imagelib/effects/kpEffectInvertCommand.h +++ b/commands/imagelib/effects/kpEffectInvertCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,39 +24,33 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectInvertCommand_H #define kpEffectInvertCommand_H - #include "kpEffectCommandBase.h" #include "imagelib/kpImage.h" - - class kpEffectInvertCommand : public kpEffectCommandBase { public: - kpEffectInvertCommand (int channels, - bool actOnSelection, - kpCommandEnvironment *environ); - kpEffectInvertCommand (bool actOnSelection, - kpCommandEnvironment *environ); + kpEffectInvertCommand (int channels, bool actOnSelection, kpCommandEnvironment *environ); + kpEffectInvertCommand (bool actOnSelection, kpCommandEnvironment *environ); ~kpEffectInvertCommand () override; - // // kpEffectCommandBase interface // public: - bool isInvertible () const override { return true; } + bool isInvertible() const override + { + return true; + } protected: - kpImage applyEffect (const kpImage &image) override; + kpImage applyEffect(const kpImage &image) override; int m_channels; }; - #endif // kpEffectInvertCommand_H diff --git a/commands/imagelib/effects/kpEffectInvertCommand.cpp b/commands/imagelib/effects/kpEffectInvertCommand.cpp --- a/commands/imagelib/effects/kpEffectInvertCommand.cpp +++ b/commands/imagelib/effects/kpEffectInvertCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,42 +24,36 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpEffectInvertCommand.h" #include "imagelib/effects/kpEffectInvert.h" #include //-------------------------------------------------------------------------------- -kpEffectInvertCommand::kpEffectInvertCommand (int channels, - bool actOnSelection, - kpCommandEnvironment *environ) - : kpEffectCommandBase (channels == kpEffectInvert::RGB ? - i18n ("Invert Colors") : i18n ("Invert"), - actOnSelection, environ), - m_channels (channels) +kpEffectInvertCommand::kpEffectInvertCommand (int channels, bool actOnSelection, + kpCommandEnvironment *environ) + : kpEffectCommandBase(channels == kpEffectInvert::RGB + ? i18n("Invert Colors") : i18n("Invert"), + actOnSelection, environ) + , m_channels(channels) { } -kpEffectInvertCommand::kpEffectInvertCommand (bool actOnSelection, - kpCommandEnvironment *environ) +kpEffectInvertCommand::kpEffectInvertCommand (bool actOnSelection, kpCommandEnvironment *environ) : kpEffectInvertCommand(kpEffectInvert::RGB, actOnSelection, environ) { } kpEffectInvertCommand::~kpEffectInvertCommand () = default; - // // kpEffectInvertCommand implements kpEffectCommandBase interface // // protected virtual [base kpEffectCommandBase] -kpImage kpEffectInvertCommand::applyEffect (const kpImage &image) +kpImage kpEffectInvertCommand::applyEffect(const kpImage &image) { - return kpEffectInvert::applyEffect (image, m_channels); + return kpEffectInvert::applyEffect(image, m_channels); } - - diff --git a/commands/imagelib/effects/kpEffectReduceColorsCommand.h b/commands/imagelib/effects/kpEffectReduceColorsCommand.h --- a/commands/imagelib/effects/kpEffectReduceColorsCommand.h +++ b/commands/imagelib/effects/kpEffectReduceColorsCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,35 +24,30 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectReduceColorsCommand_H #define kpEffectReduceColorsCommand_H - #include "kpEffectCommandBase.h" #include "imagelib/kpImage.h" - class kpEffectReduceColorsCommand : public kpEffectCommandBase { public: // depth must be 1 or 8 - kpEffectReduceColorsCommand (int depth, bool dither, - bool actOnSelection, + kpEffectReduceColorsCommand (int depth, bool dither, bool actOnSelection, kpCommandEnvironment *environ); - QString commandName (int depth, int dither) const; + QString commandName(int depth, int dither) const; // // kpEffectCommandBase interface // protected: - kpImage applyEffect (const kpImage &image) override; + kpImage applyEffect(const kpImage &image) override; int m_depth; bool m_dither; }; - #endif // kpEffectReduceColorsCommand_H diff --git a/commands/imagelib/effects/kpEffectReduceColorsCommand.cpp b/commands/imagelib/effects/kpEffectReduceColorsCommand.cpp --- a/commands/imagelib/effects/kpEffectReduceColorsCommand.cpp +++ b/commands/imagelib/effects/kpEffectReduceColorsCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,43 +24,44 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_REDUCE_COLORS 0 - #include "kpEffectReduceColorsCommand.h" #include "imagelib/effects/kpEffectReduceColors.h" #include //--------------------------------------------------------------------- kpEffectReduceColorsCommand::kpEffectReduceColorsCommand (int depth, bool dither, - bool actOnSelection, - kpCommandEnvironment *environ) - : kpEffectCommandBase (commandName (depth, dither), actOnSelection, environ), - m_depth (depth), m_dither (dither) + bool actOnSelection, + kpCommandEnvironment *environ) + : kpEffectCommandBase(commandName(depth, dither), actOnSelection, environ) + , m_depth(depth) + , m_dither(dither) { } //--------------------------------------------------------------------- // public -QString kpEffectReduceColorsCommand::commandName (int depth, int dither) const +QString kpEffectReduceColorsCommand::commandName(int depth, int dither) const { switch (depth) { - case 1: if (dither) { - return i18n ("Reduce to Monochrome (Dithered)"); + case 1: + if (dither) { + return i18n("Reduce to Monochrome (Dithered)"); } - return i18n ("Reduce to Monochrome"); + return i18n("Reduce to Monochrome"); case 8: if (dither) { - return i18n ("Reduce to 256 Color (Dithered)"); + return i18n("Reduce to 256 Color (Dithered)"); } - return i18n ("Reduce to 256 Color"); + return i18n("Reduce to 256 Color"); - default: return {}; + default: + return {}; } } @@ -72,9 +72,9 @@ // // protected virtual [base kpEffectCommandBase] -kpImage kpEffectReduceColorsCommand::applyEffect (const kpImage &image) +kpImage kpEffectReduceColorsCommand::applyEffect(const kpImage &image) { - return kpEffectReduceColors::applyEffect (image, m_depth, m_dither); + return kpEffectReduceColors::applyEffect(image, m_depth, m_dither); } //--------------------------------------------------------------------- diff --git a/commands/imagelib/effects/kpEffectToneEnhanceCommand.h b/commands/imagelib/effects/kpEffectToneEnhanceCommand.h --- a/commands/imagelib/effects/kpEffectToneEnhanceCommand.h +++ b/commands/imagelib/effects/kpEffectToneEnhanceCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2006 Mike Gashler @@ -26,28 +25,23 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectToneEnhanceCommand_H #define kpEffectToneEnhanceCommand_H - #include "kpEffectCommandBase.h" - class kpEffectToneEnhanceCommand : public kpEffectCommandBase { public: - kpEffectToneEnhanceCommand (double granularity, double amount, - bool actOnSelection, + kpEffectToneEnhanceCommand (double granularity, double amount, bool actOnSelection, kpCommandEnvironment *environ); ~kpEffectToneEnhanceCommand () override; protected: - kpImage applyEffect (const kpImage &image) override; + kpImage applyEffect(const kpImage &image) override; protected: double m_granularity, m_amount; }; - #endif // kpEffectToneEnhanceCommand_H diff --git a/commands/imagelib/effects/kpEffectToneEnhanceCommand.cpp b/commands/imagelib/effects/kpEffectToneEnhanceCommand.cpp --- a/commands/imagelib/effects/kpEffectToneEnhanceCommand.cpp +++ b/commands/imagelib/effects/kpEffectToneEnhanceCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2006 Mike Gashler @@ -26,7 +25,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpEffectToneEnhanceCommand.h" #include "imagelib/effects/kpEffectToneEnhance.h" @@ -36,19 +34,18 @@ //-------------------------------------------------------------------------------- kpEffectToneEnhanceCommand::kpEffectToneEnhanceCommand (double granularity, double amount, - bool actOnSelection, - kpCommandEnvironment *environ) - : kpEffectCommandBase (i18n ("Histogram Equalizer"), actOnSelection, environ), - m_granularity (granularity), m_amount (amount) + bool actOnSelection, + kpCommandEnvironment *environ) + : kpEffectCommandBase(i18n("Histogram Equalizer"), actOnSelection, environ) + , m_granularity(granularity) + , m_amount(amount) { } kpEffectToneEnhanceCommand::~kpEffectToneEnhanceCommand () = default; - // protected virtual [base kpEffectCommandBase] -kpImage kpEffectToneEnhanceCommand::applyEffect (const kpImage &image) +kpImage kpEffectToneEnhanceCommand::applyEffect(const kpImage &image) { - return kpEffectToneEnhance::applyEffect (image, m_granularity, m_amount); + return kpEffectToneEnhance::applyEffect(image, m_granularity, m_amount); } - diff --git a/commands/imagelib/kpDocumentMetaInfoCommand.h b/commands/imagelib/kpDocumentMetaInfoCommand.h --- a/commands/imagelib/kpDocumentMetaInfoCommand.h +++ b/commands/imagelib/kpDocumentMetaInfoCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,34 +24,29 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpDocumentMetaInfoCommand_H #define kpDocumentMetaInfoCommand_H - #include "commands/kpNamedCommand.h" - class kpDocumentMetaInfo; class kpDocumentMetaInfoCommand : public kpNamedCommand { public: - kpDocumentMetaInfoCommand (const QString &name, - const kpDocumentMetaInfo &metaInfo, - const kpDocumentMetaInfo &oldMetaInfo, - kpCommandEnvironment *environ); + kpDocumentMetaInfoCommand (const QString &name, const kpDocumentMetaInfo &metaInfo, + const kpDocumentMetaInfo &oldMetaInfo, + kpCommandEnvironment *environ); ~kpDocumentMetaInfoCommand () override; - SizeType size () const override; + SizeType size() const override; public: - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: - struct kpDocumentMetaInfoCommandPrivate * const d; + struct kpDocumentMetaInfoCommandPrivate *const d; }; - #endif // kpDocumentMetaInfoCommand_H diff --git a/commands/imagelib/kpDocumentMetaInfoCommand.cpp b/commands/imagelib/kpDocumentMetaInfoCommand.cpp --- a/commands/imagelib/kpDocumentMetaInfoCommand.cpp +++ b/commands/imagelib/kpDocumentMetaInfoCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,24 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpDocumentMetaInfoCommand.h" #include "document/kpDocument.h" #include "imagelib/kpDocumentMetaInfo.h" #include "kpDefs.h" - struct kpDocumentMetaInfoCommandPrivate { kpDocumentMetaInfo metaInfo, oldMetaInfo; }; kpDocumentMetaInfoCommand::kpDocumentMetaInfoCommand (const QString &name, - const kpDocumentMetaInfo &metaInfo, - const kpDocumentMetaInfo &oldMetaInfo, - kpCommandEnvironment *environ) + const kpDocumentMetaInfo &metaInfo, + const kpDocumentMetaInfo &oldMetaInfo, + kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - d (new kpDocumentMetaInfoCommandPrivate ()) + : kpNamedCommand(name, environ) + , d(new kpDocumentMetaInfoCommandPrivate()) { d->metaInfo = metaInfo; d->oldMetaInfo = oldMetaInfo; @@ -55,32 +52,29 @@ delete d; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpDocumentMetaInfoCommand::size () const +kpCommandSize::SizeType kpDocumentMetaInfoCommand::size() const { - return d->metaInfo.size () + d->oldMetaInfo.size (); + return d->metaInfo.size() + d->oldMetaInfo.size(); } - // public virtual [base kpCommand] -void kpDocumentMetaInfoCommand::execute () +void kpDocumentMetaInfoCommand::execute() { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - doc->setMetaInfo (d->metaInfo); - doc->setModified (); + doc->setMetaInfo(d->metaInfo); + doc->setModified(); } // public virtual [base kpCommand] -void kpDocumentMetaInfoCommand::unexecute () +void kpDocumentMetaInfoCommand::unexecute() { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); // REFACTOR: Document in kpDocument.h that kpDocument::setMetaInfo() does not mutate modified state - doc->setMetaInfo (d->oldMetaInfo); - doc->setModified (); + doc->setMetaInfo(d->oldMetaInfo); + doc->setModified(); } - diff --git a/commands/imagelib/transforms/kpTransformFlipCommand.h b/commands/imagelib/transforms/kpTransformFlipCommand.h --- a/commands/imagelib/transforms/kpTransformFlipCommand.h +++ b/commands/imagelib/transforms/kpTransformFlipCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,36 +24,31 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransformFlipCommand_H #define kpTransformFlipCommand_H - #include "commands/kpCommand.h" - class kpTransformFlipCommand : public kpCommand { public: - kpTransformFlipCommand (bool actOnSelection, - bool horiz, bool vert, - kpCommandEnvironment *environ); + kpTransformFlipCommand (bool actOnSelection, bool horiz, bool vert, + kpCommandEnvironment *environ); ~kpTransformFlipCommand () override; - QString name () const override; + QString name() const override; - SizeType size () const override; + SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: - void flip (); + void flip(); bool m_actOnSelection; bool m_horiz, m_vert; }; - #endif // kpTransformFlipCommand_H diff --git a/commands/imagelib/transforms/kpTransformFlipCommand.cpp b/commands/imagelib/transforms/kpTransformFlipCommand.cpp --- a/commands/imagelib/transforms/kpTransformFlipCommand.cpp +++ b/commands/imagelib/transforms/kpTransformFlipCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpTransformFlipCommand.h" #include @@ -41,12 +39,12 @@ //--------------------------------------------------------------------- -kpTransformFlipCommand::kpTransformFlipCommand (bool actOnSelection, - bool horiz, bool vert, - kpCommandEnvironment *environ) - : kpCommand (environ), - m_actOnSelection (actOnSelection), - m_horiz (horiz), m_vert (vert) +kpTransformFlipCommand::kpTransformFlipCommand (bool actOnSelection, bool horiz, bool vert, + kpCommandEnvironment *environ) + : kpCommand(environ) + , m_actOnSelection(actOnSelection) + , m_horiz(horiz) + , m_vert(vert) { } @@ -57,79 +55,73 @@ //--------------------------------------------------------------------- // public virtual [base kpCommand] -QString kpTransformFlipCommand::name () const +QString kpTransformFlipCommand::name() const { QString opName; - #if 1 - opName = i18n ("Flip"); + opName = i18n("Flip"); #else // re-enable when giving full descriptions for all actions - if (m_horiz && m_vert) - opName = i18n ("Flip horizontally and vertically"); - else if (m_horiz) - opName = i18n ("Flip horizontally"); - else if (m_vert) - opName = i18n ("Flip vertically"); - else - { + if (m_horiz && m_vert) { + opName = i18n("Flip horizontally and vertically"); + } else if (m_horiz) { + opName = i18n("Flip horizontally"); + } else if (m_vert) { + opName = i18n("Flip vertically"); + } else { qCCritical(kpLogCommands) << "kpTransformFlipCommand::name() not asked to flip"; return {}; } #endif - if (m_actOnSelection) { - return i18n ("Selection: %1", opName); + return i18n("Selection: %1", opName); } return opName; } //--------------------------------------------------------------------- // public virtual [base kpCommand] -kpCommandSize::SizeType kpTransformFlipCommand::size () const +kpCommandSize::SizeType kpTransformFlipCommand::size() const { return 0; } //--------------------------------------------------------------------- // public virtual [base kpCommand] -void kpTransformFlipCommand::execute () +void kpTransformFlipCommand::execute() { - flip (); + flip(); } //--------------------------------------------------------------------- // public virtual [base kpCommand] -void kpTransformFlipCommand::unexecute () +void kpTransformFlipCommand::unexecute() { - flip (); + flip(); } //--------------------------------------------------------------------- // private -void kpTransformFlipCommand::flip () +void kpTransformFlipCommand::flip() { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - QApplication::setOverrideCursor (Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); - if (m_actOnSelection) - { - Q_ASSERT (doc->imageSelection ()); - doc->imageSelection ()->flip (m_horiz, m_vert); - environ ()->somethingBelowTheCursorChanged (); - } - else - { + if (m_actOnSelection) { + Q_ASSERT(doc->imageSelection()); + doc->imageSelection()->flip(m_horiz, m_vert); + environ()->somethingBelowTheCursorChanged(); + } else { doc->setImage(doc->image().mirrored(m_horiz, m_vert)); } - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } diff --git a/commands/imagelib/transforms/kpTransformResizeScaleCommand.h b/commands/imagelib/transforms/kpTransformResizeScaleCommand.h --- a/commands/imagelib/transforms/kpTransformResizeScaleCommand.h +++ b/commands/imagelib/transforms/kpTransformResizeScaleCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,23 +24,19 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransformResizeScaleCommand_H #define kpTransformResizeScaleCommand_H - #include #include "imagelib/kpColor.h" #include "commands/kpCommand.h" #include "imagelib/kpImage.h" - class QSize; class kpAbstractSelection; - // REFACTOR: Split into multiple classes, each doing a different thing // e.g. resize, scale and smooth scale. // REFACTOR: Replace kpToolSelectionResizeScaleCommand with us. @@ -53,34 +48,32 @@ Resize, Scale, SmoothScale }; - kpTransformResizeScaleCommand (bool actOnSelection, - int newWidth, int newHeight, - Type type, - kpCommandEnvironment *environ); + kpTransformResizeScaleCommand (bool actOnSelection, int newWidth, int newHeight, Type type, + kpCommandEnvironment *environ); ~kpTransformResizeScaleCommand () override; - QString name () const override; - SizeType size () const override; + QString name() const override; + SizeType size() const override; public: - int newWidth () const; - void setNewWidth (int width); + int newWidth() const; + void setNewWidth(int width); - int newHeight () const; - void setNewHeight (int height); + int newHeight() const; + void setNewHeight(int height); - QSize newSize () const; - virtual void resize (int width, int height); + QSize newSize() const; + virtual void resize(int width, int height); public: - bool scaleSelectionWithImage () const; + bool scaleSelectionWithImage() const; private: - void scaleSelectionRegionWithDocument (); + void scaleSelectionRegionWithDocument(); public: - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; protected: bool m_actOnSelection; @@ -96,5 +89,4 @@ kpAbstractSelection *m_oldSelectionPtr; }; - #endif // kpTransformResizeScaleCommand_H diff --git a/commands/imagelib/transforms/kpTransformResizeScaleCommand.cpp b/commands/imagelib/transforms/kpTransformResizeScaleCommand.cpp --- a/commands/imagelib/transforms/kpTransformResizeScaleCommand.cpp +++ b/commands/imagelib/transforms/kpTransformResizeScaleCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_RESIZE_SCALE_COMMAND 0 #define DEBUG_KP_TOOL_RESIZE_SCALE_DIALOG 0 - #include "kpTransformResizeScaleCommand.h" #include "layers/selections/image/kpAbstractImageSelection.h" @@ -41,7 +38,6 @@ #include "layers/selections/image/kpRectangularImageSelection.h" #include "layers/selections/text/kpTextSelection.h" - #include #include #include @@ -55,432 +51,383 @@ //-------------------------------------------------------------------------------- -kpTransformResizeScaleCommand::kpTransformResizeScaleCommand (bool actOnSelection, - int newWidth, int newHeight, - Type type, - kpCommandEnvironment *environ) - : kpCommand (environ), - m_actOnSelection (actOnSelection), - m_type (type), - m_backgroundColor (environ->backgroundColor ()), - m_oldSelectionPtr (nullptr) +kpTransformResizeScaleCommand::kpTransformResizeScaleCommand (bool actOnSelection, int newWidth, + int newHeight, Type type, + kpCommandEnvironment *environ) + : kpCommand(environ) + , m_actOnSelection(actOnSelection) + , m_type(type) + , m_backgroundColor(environ->backgroundColor()) + , m_oldSelectionPtr(nullptr) { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - m_oldWidth = doc->width (m_actOnSelection); - m_oldHeight = doc->height (m_actOnSelection); + m_oldWidth = doc->width(m_actOnSelection); + m_oldHeight = doc->height(m_actOnSelection); - m_actOnTextSelection = (m_actOnSelection && - doc->textSelection ()); + m_actOnTextSelection = (m_actOnSelection + && doc->textSelection()); - resize (newWidth, newHeight); + resize(newWidth, newHeight); // If we have a selection _border_ (but not a floating selection), // then scale the selection with the document - m_scaleSelectionWithImage = (!m_actOnSelection && - (m_type == Scale || m_type == SmoothScale) && - document ()->selection () && - !document ()->selection ()->hasContent ()); + m_scaleSelectionWithImage = (!m_actOnSelection + && (m_type == Scale || m_type == SmoothScale) + && document()->selection() + && !document()->selection()->hasContent()); } kpTransformResizeScaleCommand::~kpTransformResizeScaleCommand () { delete m_oldSelectionPtr; } - // public virtual [base kpCommand] -QString kpTransformResizeScaleCommand::name () const +QString kpTransformResizeScaleCommand::name() const { - if (m_actOnSelection) - { - if (m_actOnTextSelection) - { + if (m_actOnSelection) { + if (m_actOnTextSelection) { if (m_type == Resize) { - return i18n ("Text: Resize Box"); + return i18n("Text: Resize Box"); } - } - else - { + } else { if (m_type == Scale) { - return i18n ("Selection: Scale"); + return i18n("Selection: Scale"); } if (m_type == SmoothScale) { - return i18n ("Selection: Smooth Scale"); + return i18n("Selection: Smooth Scale"); } } - } - else - { - switch (m_type) - { + } else { + switch (m_type) { case Resize: - return i18n ("Resize"); + return i18n("Resize"); case Scale: - return i18n ("Scale"); + return i18n("Scale"); case SmoothScale: - return i18n ("Smooth Scale"); + return i18n("Smooth Scale"); } } return {}; } // public virtual [base kpCommand] -kpCommandSize::SizeType kpTransformResizeScaleCommand::size () const +kpCommandSize::SizeType kpTransformResizeScaleCommand::size() const { - return ImageSize (m_oldImage) + - ImageSize (m_oldRightImage) + - ImageSize (m_oldBottomImage) + - SelectionSize (m_oldSelectionPtr); + return ImageSize(m_oldImage) + +ImageSize(m_oldRightImage) + +ImageSize(m_oldBottomImage) + +SelectionSize(m_oldSelectionPtr); } - // public -int kpTransformResizeScaleCommand::newWidth () const +int kpTransformResizeScaleCommand::newWidth() const { return m_newWidth; } // public -void kpTransformResizeScaleCommand::setNewWidth (int width) +void kpTransformResizeScaleCommand::setNewWidth(int width) { - resize (width, newHeight ()); + resize(width, newHeight()); } - // public -int kpTransformResizeScaleCommand::newHeight () const +int kpTransformResizeScaleCommand::newHeight() const { return m_newHeight; } // public -void kpTransformResizeScaleCommand::setNewHeight (int height) +void kpTransformResizeScaleCommand::setNewHeight(int height) { - resize (newWidth (), height); + resize(newWidth(), height); } - // public -QSize kpTransformResizeScaleCommand::newSize () const +QSize kpTransformResizeScaleCommand::newSize() const { - return {newWidth (), newHeight ()}; + return { + newWidth(), newHeight() + }; } // public virtual -void kpTransformResizeScaleCommand::resize (int width, int height) +void kpTransformResizeScaleCommand::resize(int width, int height) { m_newWidth = width; m_newHeight = height; - m_isLosslessScale = ((m_type == Scale) && - (m_newWidth / m_oldWidth * m_oldWidth == m_newWidth) && - (m_newHeight / m_oldHeight * m_oldHeight == m_newHeight)); + m_isLosslessScale = ((m_type == Scale) + && (m_newWidth / m_oldWidth * m_oldWidth == m_newWidth) + && (m_newHeight / m_oldHeight * m_oldHeight == m_newHeight)); } - // public -bool kpTransformResizeScaleCommand::scaleSelectionWithImage () const +bool kpTransformResizeScaleCommand::scaleSelectionWithImage() const { return m_scaleSelectionWithImage; } - // private -void kpTransformResizeScaleCommand::scaleSelectionRegionWithDocument () +void kpTransformResizeScaleCommand::scaleSelectionRegionWithDocument() { #if DEBUG_KP_TOOL_RESIZE_SCALE_COMMAND qCDebug(kpLogCommands) << "kpTransformResizeScaleCommand::scaleSelectionRegionWithDocument"; #endif - Q_ASSERT (m_oldSelectionPtr); - Q_ASSERT (!m_oldSelectionPtr->hasContent ()); - - - const double horizScale = double (m_newWidth) / double (m_oldWidth); - const double vertScale = double (m_newHeight) / double (m_oldHeight); + Q_ASSERT(m_oldSelectionPtr); + Q_ASSERT(!m_oldSelectionPtr->hasContent()); - const int newX = static_cast (m_oldSelectionPtr->x () * horizScale); - const int newY = static_cast (m_oldSelectionPtr->y () * vertScale); + const double horizScale = double(m_newWidth) / double(m_oldWidth); + const double vertScale = double(m_newHeight) / double(m_oldHeight); + const int newX = static_cast(m_oldSelectionPtr->x() * horizScale); + const int newY = static_cast(m_oldSelectionPtr->y() * vertScale); - QPolygon currentPoints = m_oldSelectionPtr->calculatePoints (); - currentPoints.translate (-currentPoints.boundingRect ().x (), - -currentPoints.boundingRect ().y ()); + QPolygon currentPoints = m_oldSelectionPtr->calculatePoints(); + currentPoints.translate(-currentPoints.boundingRect().x(), + -currentPoints.boundingRect().y()); // TODO: refactor into kpPixmapFX // TODO: Can we get to size 0x0 accidently? QTransform scaleMatrix; - scaleMatrix.scale (horizScale, vertScale); - currentPoints = scaleMatrix.map (currentPoints); - - currentPoints.translate ( - -currentPoints.boundingRect ().x () + newX, - -currentPoints.boundingRect ().y () + newY); - - auto *imageSel = dynamic_cast (m_oldSelectionPtr); - auto *textSel = dynamic_cast (m_oldSelectionPtr); - - if (imageSel) - { - document ()->setSelection ( - kpFreeFormImageSelection (currentPoints, kpImage (), - imageSel->transparency ())); - } - else if (textSel) - { - document ()->setSelection ( - kpTextSelection (currentPoints.boundingRect (), - textSel->textLines (), - textSel->textStyle ())); - } - else { - Q_ASSERT (!"Unknown selection type"); + scaleMatrix.scale(horizScale, vertScale); + currentPoints = scaleMatrix.map(currentPoints); + + currentPoints.translate( + -currentPoints.boundingRect().x() + newX, + -currentPoints.boundingRect().y() + newY); + + auto *imageSel = dynamic_cast (m_oldSelectionPtr); + auto *textSel = dynamic_cast (m_oldSelectionPtr); + + if (imageSel) { + document()->setSelection( + kpFreeFormImageSelection(currentPoints, kpImage(), + imageSel->transparency())); + } else if (textSel) { + document()->setSelection( + kpTextSelection(currentPoints.boundingRect(), + textSel->textLines(), + textSel->textStyle())); + } else { + Q_ASSERT(!"Unknown selection type"); } - - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } - // public virtual [base kpCommand] -void kpTransformResizeScaleCommand::execute () +void kpTransformResizeScaleCommand::execute() { #if DEBUG_KP_TOOL_RESIZE_SCALE_COMMAND qCDebug(kpLogCommands) << "kpTransformResizeScaleCommand::execute() type=" - << (int) m_type - << " oldWidth=" << m_oldWidth - << " oldHeight=" << m_oldHeight - << " newWidth=" << m_newWidth - << " newHeight=" << m_newHeight; + << (int)m_type + << " oldWidth=" << m_oldWidth + << " oldHeight=" << m_oldHeight + << " newWidth=" << m_newWidth + << " newHeight=" << m_newHeight; #endif - if (m_oldWidth == m_newWidth && m_oldHeight == m_newHeight) + if (m_oldWidth == m_newWidth && m_oldHeight == m_newHeight) { return; + } - if (m_type == Resize) - { - if (m_actOnSelection) - { + if (m_type == Resize) { + if (m_actOnSelection) { if (!m_actOnTextSelection) { - Q_ASSERT (!"kpTransformResizeScaleCommand::execute() resizing sel doesn't make sense"); + Q_ASSERT(!"kpTransformResizeScaleCommand::execute() resizing sel doesn't make sense"); } - QApplication::setOverrideCursor (Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); - kpTextSelection *textSel = textSelection (); - Q_ASSERT (textSel); + kpTextSelection *textSel = textSelection(); + Q_ASSERT(textSel); - kpTextSelection *newSel = textSel->resized (m_newWidth, m_newHeight); - document ()->setSelection (*newSel); + kpTextSelection *newSel = textSel->resized(m_newWidth, m_newHeight); + document()->setSelection(*newSel); delete newSel; - environ ()->somethingBelowTheCursorChanged (); - - QApplication::restoreOverrideCursor (); - } - else - { - QApplication::setOverrideCursor (Qt::WaitCursor); + environ()->somethingBelowTheCursorChanged(); + QApplication::restoreOverrideCursor(); + } else { + QApplication::setOverrideCursor(Qt::WaitCursor); - if (m_newWidth < m_oldWidth) - { - m_oldRightImage = document ()->getImageAt ( - QRect (m_newWidth, 0, - m_oldWidth - m_newWidth, m_oldHeight)); + if (m_newWidth < m_oldWidth) { + m_oldRightImage = document()->getImageAt( + QRect(m_newWidth, 0, + m_oldWidth - m_newWidth, m_oldHeight)); } - if (m_newHeight < m_oldHeight) - { - m_oldBottomImage = document ()->getImageAt ( - QRect (0, m_newHeight, - m_newWidth, m_oldHeight - m_newHeight)); + if (m_newHeight < m_oldHeight) { + m_oldBottomImage = document()->getImageAt( + QRect(0, m_newHeight, + m_newWidth, m_oldHeight - m_newHeight)); } - document ()->resize (m_newWidth, m_newHeight, m_backgroundColor); - + document()->resize(m_newWidth, m_newHeight, m_backgroundColor); - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } } // Scale - else - { - QApplication::setOverrideCursor (Qt::WaitCursor); - + else { + QApplication::setOverrideCursor(Qt::WaitCursor); - kpImage oldImage = document ()->image (m_actOnSelection); + kpImage oldImage = document()->image(m_actOnSelection); if (!m_isLosslessScale) { m_oldImage = oldImage; } - kpImage newImage = kpPixmapFX::scale (oldImage, m_newWidth, m_newHeight, - m_type == SmoothScale); - + kpImage newImage = kpPixmapFX::scale(oldImage, m_newWidth, m_newHeight, + m_type == SmoothScale); - if (!m_oldSelectionPtr && document ()->selection ()) - { + if (!m_oldSelectionPtr && document()->selection()) { // Save sel border - m_oldSelectionPtr = document ()->selection ()->clone (); - m_oldSelectionPtr->deleteContent (); + m_oldSelectionPtr = document()->selection()->clone(); + m_oldSelectionPtr->deleteContent(); } - if (m_actOnSelection) - { + if (m_actOnSelection) { if (m_actOnTextSelection) { - Q_ASSERT (!"kpTransformResizeScaleCommand::execute() scaling text sel doesn't make sense"); + Q_ASSERT( + !"kpTransformResizeScaleCommand::execute() scaling text sel doesn't make sense"); } - Q_ASSERT (m_oldSelectionPtr); - if ( !m_oldSelectionPtr ) { // make coverity happy + Q_ASSERT(m_oldSelectionPtr); + if (!m_oldSelectionPtr) { // make coverity happy return; } - QRect newRect = QRect (m_oldSelectionPtr->x (), m_oldSelectionPtr->y (), - newImage.width (), newImage.height ()); + QRect newRect = QRect(m_oldSelectionPtr->x(), m_oldSelectionPtr->y(), + newImage.width(), newImage.height()); // Not possible to retain non-rectangular selection borders on scale // (think about e.g. a 45 deg line as part of the border & 2x scale) - Q_ASSERT (dynamic_cast (m_oldSelectionPtr)); - document ()->setSelection ( - kpRectangularImageSelection (newRect, newImage, - dynamic_cast (m_oldSelectionPtr) - ->transparency ())); - - environ ()->somethingBelowTheCursorChanged (); - } - else - { - document ()->setImage (newImage); + Q_ASSERT(dynamic_cast (m_oldSelectionPtr)); + document()->setSelection( + kpRectangularImageSelection(newRect, newImage, + dynamic_cast ( + m_oldSelectionPtr) + ->transparency())); + + environ()->somethingBelowTheCursorChanged(); + } else { + document()->setImage(newImage); - if (m_scaleSelectionWithImage) - { - scaleSelectionRegionWithDocument (); + if (m_scaleSelectionWithImage) { + scaleSelectionRegionWithDocument(); } } - - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } } // public virtual [base kpCommand] -void kpTransformResizeScaleCommand::unexecute () +void kpTransformResizeScaleCommand::unexecute() { #if DEBUG_KP_TOOL_RESIZE_SCALE_COMMAND qCDebug(kpLogCommands) << "kpTransformResizeScaleCommand::unexecute() type=" - << m_type; + << m_type; #endif if (m_oldWidth == m_newWidth && m_oldHeight == m_newHeight) { return; } - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - if (m_type == Resize) - { - if (m_actOnSelection) - { + if (m_type == Resize) { + if (m_actOnSelection) { if (!m_actOnTextSelection) { - Q_ASSERT (!"kpTransformResizeScaleCommand::unexecute() resizing sel doesn't make sense"); + Q_ASSERT( + !"kpTransformResizeScaleCommand::unexecute() resizing sel doesn't make sense"); } - QApplication::setOverrideCursor (Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); - kpTextSelection *textSel = textSelection (); - Q_ASSERT (textSel); + kpTextSelection *textSel = textSelection(); + Q_ASSERT(textSel); - kpTextSelection *newSel = textSel->resized (m_oldWidth, m_oldHeight); - document ()->setSelection (*newSel); + kpTextSelection *newSel = textSel->resized(m_oldWidth, m_oldHeight); + document()->setSelection(*newSel); delete newSel; - environ ()->somethingBelowTheCursorChanged (); - - QApplication::restoreOverrideCursor (); - } - else - { - QApplication::setOverrideCursor (Qt::WaitCursor); + environ()->somethingBelowTheCursorChanged(); + QApplication::restoreOverrideCursor(); + } else { + QApplication::setOverrideCursor(Qt::WaitCursor); - kpImage newImage (m_oldWidth, m_oldHeight, QImage::Format_ARGB32_Premultiplied); + kpImage newImage(m_oldWidth, m_oldHeight, QImage::Format_ARGB32_Premultiplied); - kpPixmapFX::setPixmapAt (&newImage, QPoint (0, 0), - doc->image ()); + kpPixmapFX::setPixmapAt(&newImage, QPoint(0, 0), + doc->image()); - if (m_newWidth < m_oldWidth) - { - kpPixmapFX::setPixmapAt (&newImage, - QPoint (m_newWidth, 0), + if (m_newWidth < m_oldWidth) { + kpPixmapFX::setPixmapAt(&newImage, + QPoint(m_newWidth, 0), m_oldRightImage); } - if (m_newHeight < m_oldHeight) - { - kpPixmapFX::setPixmapAt (&newImage, - QPoint (0, m_newHeight), + if (m_newHeight < m_oldHeight) { + kpPixmapFX::setPixmapAt(&newImage, + QPoint(0, m_newHeight), m_oldBottomImage); } - doc->setImage (newImage); + doc->setImage(newImage); - - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } } // Scale - else - { - QApplication::setOverrideCursor (Qt::WaitCursor); - + else { + QApplication::setOverrideCursor(Qt::WaitCursor); kpImage oldImage; if (!m_isLosslessScale) { oldImage = m_oldImage; } else { - oldImage = kpPixmapFX::scale (doc->image (m_actOnSelection), - m_oldWidth, m_oldHeight); + oldImage = kpPixmapFX::scale(doc->image(m_actOnSelection), + m_oldWidth, m_oldHeight); } - - if (m_actOnSelection) - { + if (m_actOnSelection) { if (m_actOnTextSelection) { - Q_ASSERT (!"kpTransformResizeScaleCommand::unexecute() scaling text sel doesn't make sense"); + Q_ASSERT( + !"kpTransformResizeScaleCommand::unexecute() scaling text sel doesn't make sense"); } - Q_ASSERT (dynamic_cast (m_oldSelectionPtr)); - auto *oldImageSel = dynamic_cast (m_oldSelectionPtr); + Q_ASSERT(dynamic_cast (m_oldSelectionPtr)); + auto *oldImageSel = dynamic_cast (m_oldSelectionPtr); - kpAbstractImageSelection *oldSelection = oldImageSel->clone (); - oldSelection->setBaseImage (oldImage); - doc->setSelection (*oldSelection); + kpAbstractImageSelection *oldSelection = oldImageSel->clone(); + oldSelection->setBaseImage(oldImage); + doc->setSelection(*oldSelection); delete oldSelection; - environ ()->somethingBelowTheCursorChanged (); - } - else - { - doc->setImage (oldImage); + environ()->somethingBelowTheCursorChanged(); + } else { + doc->setImage(oldImage); - if (m_scaleSelectionWithImage) - { - doc->setSelection (*m_oldSelectionPtr); + if (m_scaleSelectionWithImage) { + doc->setSelection(*m_oldSelectionPtr); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } } - - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } } - diff --git a/commands/imagelib/transforms/kpTransformRotateCommand.h b/commands/imagelib/transforms/kpTransformRotateCommand.h --- a/commands/imagelib/transforms/kpTransformRotateCommand.h +++ b/commands/imagelib/transforms/kpTransformRotateCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,33 +24,28 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransformRotateCommand_H #define kpTransformRotateCommand_H - #include "imagelib/kpColor.h" #include "commands/kpCommand.h" #include "imagelib/kpImage.h" - class kpAbstractImageSelection; - class kpTransformRotateCommand : public kpCommand { public: - kpTransformRotateCommand (bool actOnSelection, - double angle, // 0 <= angle < 360 (clockwise) - kpCommandEnvironment *environ); + kpTransformRotateCommand (bool actOnSelection, double angle, // 0 <= angle < 360 (clockwise) + kpCommandEnvironment *environ); ~kpTransformRotateCommand () override; - QString name () const override; + QString name() const override; - SizeType size () const override; + SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: bool m_actOnSelection; @@ -64,5 +58,4 @@ kpAbstractImageSelection *m_oldSelectionPtr; }; - #endif // kpTransformRotateCommand_H diff --git a/commands/imagelib/transforms/kpTransformRotateCommand.cpp b/commands/imagelib/transforms/kpTransformRotateCommand.cpp --- a/commands/imagelib/transforms/kpTransformRotateCommand.cpp +++ b/commands/imagelib/transforms/kpTransformRotateCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_ROTATE 0 - #include "kpTransformRotateCommand.h" #include "layers/selections/image/kpAbstractImageSelection.h" @@ -48,69 +46,61 @@ //-------------------------------------------------------------------------------- -kpTransformRotateCommand::kpTransformRotateCommand (bool actOnSelection, - double angle, - kpCommandEnvironment *environ) - : kpCommand (environ), - m_actOnSelection (actOnSelection), - m_angle (angle), - m_backgroundColor (environ->backgroundColor (actOnSelection)), - m_losslessRotation (kpPixmapFX::isLosslessRotation (angle)), - m_oldSelectionPtr (nullptr) +kpTransformRotateCommand::kpTransformRotateCommand (bool actOnSelection, double angle, + kpCommandEnvironment *environ) + : kpCommand(environ) + , m_actOnSelection(actOnSelection) + , m_angle(angle) + , m_backgroundColor(environ->backgroundColor(actOnSelection)) + , m_losslessRotation(kpPixmapFX::isLosslessRotation(angle)) + , m_oldSelectionPtr(nullptr) { } kpTransformRotateCommand::~kpTransformRotateCommand () { delete m_oldSelectionPtr; } - // public virtual [base kpCommand] -QString kpTransformRotateCommand::name () const +QString kpTransformRotateCommand::name() const { - QString opName = i18n ("Rotate"); + QString opName = i18n("Rotate"); - return (m_actOnSelection) ? i18n ("Selection: %1", opName) : opName; + return (m_actOnSelection) ? i18n("Selection: %1", opName) : opName; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpTransformRotateCommand::size () const +kpCommandSize::SizeType kpTransformRotateCommand::size() const { - return ImageSize (m_oldImage) + - SelectionSize (m_oldSelectionPtr); + return ImageSize(m_oldImage) + +SelectionSize(m_oldSelectionPtr); } - // public virtual [base kpCommand] -void kpTransformRotateCommand::execute () +void kpTransformRotateCommand::execute() { - kpDocument *doc = document (); - Q_ASSERT (doc); - - - QApplication::setOverrideCursor (Qt::WaitCursor); + kpDocument *doc = document(); + Q_ASSERT(doc); + QApplication::setOverrideCursor(Qt::WaitCursor); if (!m_losslessRotation) { - m_oldImage = doc->image (m_actOnSelection); + m_oldImage = doc->image(m_actOnSelection); } - - kpImage newImage = kpPixmapFX::rotate (doc->image (m_actOnSelection), - m_angle, - m_backgroundColor); + kpImage newImage = kpPixmapFX::rotate(doc->image(m_actOnSelection), + m_angle, + m_backgroundColor); if (!m_actOnSelection) { - doc->setImage (newImage); - } - else { - kpAbstractImageSelection *sel = doc->imageSelection (); - Q_ASSERT (sel); + doc->setImage(newImage); + } else { + kpAbstractImageSelection *sel = doc->imageSelection(); + Q_ASSERT(sel); // Save old selection - m_oldSelectionPtr = sel->clone (); + m_oldSelectionPtr = sel->clone(); // Conserve memmory: // @@ -121,100 +111,88 @@ // a copy of the old image. In this case, we actually save very // little with this line (just, the computed transparency mask) since // kpImage is copy-on-write. - m_oldSelectionPtr->setBaseImage (kpImage ()); - + m_oldSelectionPtr->setBaseImage(kpImage()); // Calculate new top left (so selection rotates about center) // (the Times2 trickery is used to reduce integer division error without // resorting to the troublesome world of floating point) - QPoint oldCenterTimes2 (sel->x () * 2 + sel->width (), - sel->y () * 2 + sel->height ()); - QPoint newTopLeftTimes2 (oldCenterTimes2 - QPoint (newImage.width (), newImage.height ())); - QPoint newTopLeft (newTopLeftTimes2.x () / 2, newTopLeftTimes2.y () / 2); - + QPoint oldCenterTimes2(sel->x() * 2 + sel->width(), + sel->y() * 2 + sel->height()); + QPoint newTopLeftTimes2(oldCenterTimes2 - QPoint(newImage.width(), newImage.height())); + QPoint newTopLeft(newTopLeftTimes2.x() / 2, newTopLeftTimes2.y() / 2); // Calculate rotated points - QPolygon currentPoints = sel->calculatePoints (); - currentPoints.translate (-currentPoints.boundingRect ().x (), - -currentPoints.boundingRect ().y ()); - QTransform rotateMatrix = kpPixmapFX::rotateMatrix (doc->image (m_actOnSelection), m_angle); - currentPoints = rotateMatrix.map (currentPoints); - currentPoints.translate (-currentPoints.boundingRect ().x () + newTopLeft.x (), - -currentPoints.boundingRect ().y () + newTopLeft.y ()); - - - if (currentPoints.boundingRect ().width () == newImage.width () && - currentPoints.boundingRect ().height () == newImage.height ()) - { - doc->setSelection ( - kpFreeFormImageSelection ( + QPolygon currentPoints = sel->calculatePoints(); + currentPoints.translate(-currentPoints.boundingRect().x(), + -currentPoints.boundingRect().y()); + QTransform rotateMatrix = kpPixmapFX::rotateMatrix(doc->image(m_actOnSelection), m_angle); + currentPoints = rotateMatrix.map(currentPoints); + currentPoints.translate(-currentPoints.boundingRect().x() + newTopLeft.x(), + -currentPoints.boundingRect().y() + newTopLeft.y()); + + if (currentPoints.boundingRect().width() == newImage.width() + && currentPoints.boundingRect().height() == newImage.height()) { + doc->setSelection( + kpFreeFormImageSelection( currentPoints, newImage, - m_oldSelectionPtr->transparency ())); - } - else - { + m_oldSelectionPtr->transparency())); + } else { // TODO: fix the latter "victim of" problem in kpAbstractImageSelection by // allowing the border width & height != pixmap width & height // Or maybe autocrop? #if DEBUG_KP_TOOL_ROTATE - qCDebug(kpLogCommands) << "kpTransformRotateCommand::execute() currentPoints.boundingRect=" - << currentPoints.boundingRect () - << " newPixmap: w=" << newImage.width () - << " h=" << newImage.height () - << " (victim of rounding error and/or rotated-a-(rectangular)-pixmap-that-was-transparent-in-the-corners-making-sel-uselessly-bigger-than-needs-be)"; + qCDebug(kpLogCommands) + << + "kpTransformRotateCommand::execute() currentPoints.boundingRect=" + << currentPoints.boundingRect() + << " newPixmap: w=" << newImage.width() + << " h=" << newImage.height() + << + " (victim of rounding error and/or rotated-a-(rectangular)-pixmap-that-was-transparent-in-the-corners-making-sel-uselessly-bigger-than-needs-be)"; #endif - doc->setSelection ( - kpRectangularImageSelection ( - QRect (newTopLeft.x (), newTopLeft.y (), - newImage.width (), newImage.height ()), + doc->setSelection( + kpRectangularImageSelection( + QRect(newTopLeft.x(), newTopLeft.y(), + newImage.width(), newImage.height()), newImage, - m_oldSelectionPtr->transparency ())); + m_oldSelectionPtr->transparency())); } - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } - - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } // public virtual [base kpCommand] -void kpTransformRotateCommand::unexecute () +void kpTransformRotateCommand::unexecute() { - kpDocument *doc = document (); - Q_ASSERT (doc); - - - QApplication::setOverrideCursor (Qt::WaitCursor); + kpDocument *doc = document(); + Q_ASSERT(doc); + QApplication::setOverrideCursor(Qt::WaitCursor); kpImage oldImage; - if (!m_losslessRotation) - { + if (!m_losslessRotation) { oldImage = m_oldImage; - m_oldImage = kpImage (); - } - else - { - oldImage = kpPixmapFX::rotate (doc->image (m_actOnSelection), - 360 - m_angle, - m_backgroundColor); + m_oldImage = kpImage(); + } else { + oldImage = kpPixmapFX::rotate(doc->image(m_actOnSelection), + 360 - m_angle, + m_backgroundColor); } - if (!m_actOnSelection) { - doc->setImage (oldImage); - } - else { - m_oldSelectionPtr->setBaseImage (oldImage); - doc->setSelection (*m_oldSelectionPtr); - delete m_oldSelectionPtr; m_oldSelectionPtr = nullptr; - - environ ()->somethingBelowTheCursorChanged (); + doc->setImage(oldImage); + } else { + m_oldSelectionPtr->setBaseImage(oldImage); + doc->setSelection(*m_oldSelectionPtr); + delete m_oldSelectionPtr; + m_oldSelectionPtr = nullptr; + + environ()->somethingBelowTheCursorChanged(); } - - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } - diff --git a/commands/imagelib/transforms/kpTransformSkewCommand.h b/commands/imagelib/transforms/kpTransformSkewCommand.h --- a/commands/imagelib/transforms/kpTransformSkewCommand.h +++ b/commands/imagelib/transforms/kpTransformSkewCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,32 +24,26 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransformSkewCommand_H #define kpTransformSkewCommand_H - #include "imagelib/kpColor.h" #include "imagelib/kpImage.h" #include "commands/kpCommand.h" - - - class kpTransformSkewCommand : public kpCommand { public: - kpTransformSkewCommand (bool actOnSelection, - int hangle, int vangle, - kpCommandEnvironment *environ); + kpTransformSkewCommand (bool actOnSelection, int hangle, int vangle, + kpCommandEnvironment *environ); ~kpTransformSkewCommand () override; - QString name () const override; + QString name() const override; - SizeType size () const override; + SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: bool m_actOnSelection; @@ -61,5 +54,4 @@ kpAbstractImageSelection *m_oldSelectionPtr; }; - #endif // kpTransformSkewCommand_H diff --git a/commands/imagelib/transforms/kpTransformSkewCommand.cpp b/commands/imagelib/transforms/kpTransformSkewCommand.cpp --- a/commands/imagelib/transforms/kpTransformSkewCommand.cpp +++ b/commands/imagelib/transforms/kpTransformSkewCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SKEW 0 #define DEBUG_KP_TOOL_SKEW_DIALOG 0 - #include "kpTransformSkewCommand.h" #include "layers/selections/image/kpAbstractImageSelection.h" @@ -52,144 +49,127 @@ //-------------------------------------------------------------------------------- -kpTransformSkewCommand::kpTransformSkewCommand (bool actOnSelection, - int hangle, int vangle, - kpCommandEnvironment *environ) - : kpCommand (environ), - m_actOnSelection (actOnSelection), - m_hangle (hangle), m_vangle (vangle), - m_backgroundColor (environ->backgroundColor (actOnSelection)), - m_oldSelectionPtr (nullptr) +kpTransformSkewCommand::kpTransformSkewCommand (bool actOnSelection, int hangle, int vangle, + kpCommandEnvironment *environ) + : kpCommand(environ) + , m_actOnSelection(actOnSelection) + , m_hangle(hangle) + , m_vangle(vangle) + , m_backgroundColor(environ->backgroundColor(actOnSelection)) + , m_oldSelectionPtr(nullptr) { } kpTransformSkewCommand::~kpTransformSkewCommand () { delete m_oldSelectionPtr; } - // public virtual [base kpCommand] -QString kpTransformSkewCommand::name () const +QString kpTransformSkewCommand::name() const { - QString opName = i18n ("Skew"); + QString opName = i18n("Skew"); - return (m_actOnSelection) ? i18n ("Selection: %1", opName) : opName; + return (m_actOnSelection) ? i18n("Selection: %1", opName) : opName; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpTransformSkewCommand::size () const +kpCommandSize::SizeType kpTransformSkewCommand::size() const { - return ImageSize (m_oldImage) + - SelectionSize (m_oldSelectionPtr); + return ImageSize(m_oldImage) + +SelectionSize(m_oldSelectionPtr); } - // public virtual [base kpCommand] -void kpTransformSkewCommand::execute () +void kpTransformSkewCommand::execute() { - kpDocument *doc = document (); - Q_ASSERT (doc); - + kpDocument *doc = document(); + Q_ASSERT(doc); - QApplication::setOverrideCursor (Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); + kpImage newImage = kpPixmapFX::skew(doc->image(m_actOnSelection), + kpTransformSkewDialog::horizontalAngleForPixmapFX(m_hangle), + kpTransformSkewDialog::verticalAngleForPixmapFX(m_vangle), + m_backgroundColor); - kpImage newImage = kpPixmapFX::skew (doc->image (m_actOnSelection), - kpTransformSkewDialog::horizontalAngleForPixmapFX (m_hangle), - kpTransformSkewDialog::verticalAngleForPixmapFX (m_vangle), - m_backgroundColor); + if (!m_actOnSelection) { + m_oldImage = doc->image(m_actOnSelection); - if (!m_actOnSelection) - { - m_oldImage = doc->image (m_actOnSelection); - - doc->setImage (newImage); - } - else - { - kpAbstractImageSelection *sel = doc->imageSelection (); - Q_ASSERT (sel); + doc->setImage(newImage); + } else { + kpAbstractImageSelection *sel = doc->imageSelection(); + Q_ASSERT(sel); // Save old selection - m_oldSelectionPtr = sel->clone (); - + m_oldSelectionPtr = sel->clone(); // Calculate skewed points - QPolygon currentPoints = sel->calculatePoints (); - currentPoints.translate (-currentPoints.boundingRect ().x (), - -currentPoints.boundingRect ().y ()); - QTransform skewMatrix = kpPixmapFX::skewMatrix ( - doc->image (m_actOnSelection), - kpTransformSkewDialog::horizontalAngleForPixmapFX (m_hangle), - kpTransformSkewDialog::verticalAngleForPixmapFX (m_vangle)); - currentPoints = skewMatrix.map (currentPoints); - currentPoints.translate (-currentPoints.boundingRect ().x () + m_oldSelectionPtr->x (), - -currentPoints.boundingRect ().y () + m_oldSelectionPtr->y ()); - - - if (currentPoints.boundingRect ().width () == newImage.width () && - currentPoints.boundingRect ().height () == newImage.height ()) - { - doc->setSelection ( - kpFreeFormImageSelection ( + QPolygon currentPoints = sel->calculatePoints(); + currentPoints.translate(-currentPoints.boundingRect().x(), + -currentPoints.boundingRect().y()); + QTransform skewMatrix = kpPixmapFX::skewMatrix( + doc->image(m_actOnSelection), + kpTransformSkewDialog::horizontalAngleForPixmapFX(m_hangle), + kpTransformSkewDialog::verticalAngleForPixmapFX(m_vangle)); + currentPoints = skewMatrix.map(currentPoints); + currentPoints.translate(-currentPoints.boundingRect().x() + m_oldSelectionPtr->x(), + -currentPoints.boundingRect().y() + m_oldSelectionPtr->y()); + + if (currentPoints.boundingRect().width() == newImage.width() + && currentPoints.boundingRect().height() == newImage.height()) { + doc->setSelection( + kpFreeFormImageSelection( currentPoints, newImage, - m_oldSelectionPtr->transparency ())); - } - else - { + m_oldSelectionPtr->transparency())); + } else { // TODO: fix the latter "victim of" problem in kpAbstractImageSelection by // allowing the border width & height != pixmap width & height // Or maybe autocrop? #if DEBUG_KP_TOOL_SKEW - qCDebug(kpLogCommands) << "kpTransformSkewCommand::execute() currentPoints.boundingRect=" - << currentPoints.boundingRect () - << " newPixmap: w=" << newImage.width () - << " h=" << newImage.height () - << " (victim of rounding error and/or skewed-a-(rectangular)-pixmap-that-was-transparent-in-the-corners-making-sel-uselessly-bigger-than-needs-be))"; + qCDebug(kpLogCommands) + << + "kpTransformSkewCommand::execute() currentPoints.boundingRect=" + << currentPoints.boundingRect() + << " newPixmap: w=" << newImage.width() + << " h=" << newImage.height() + << + " (victim of rounding error and/or skewed-a-(rectangular)-pixmap-that-was-transparent-in-the-corners-making-sel-uselessly-bigger-than-needs-be))"; #endif - doc->setSelection ( - kpRectangularImageSelection ( - QRect (currentPoints.boundingRect ().x (), - currentPoints.boundingRect ().y (), - newImage.width (), - newImage.height ()), + doc->setSelection( + kpRectangularImageSelection( + QRect(currentPoints.boundingRect().x(), + currentPoints.boundingRect().y(), + newImage.width(), + newImage.height()), newImage, - m_oldSelectionPtr->transparency ())); + m_oldSelectionPtr->transparency())); } - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } - - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } // public virtual [base kpCommand] -void kpTransformSkewCommand::unexecute () +void kpTransformSkewCommand::unexecute() { - kpDocument *doc = document (); - Q_ASSERT (doc); - + kpDocument *doc = document(); + Q_ASSERT(doc); - QApplication::setOverrideCursor (Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); + if (!m_actOnSelection) { + doc->setImage(m_oldImage); + m_oldImage = kpImage(); + } else { + doc->setSelection(*m_oldSelectionPtr); + delete m_oldSelectionPtr; + m_oldSelectionPtr = nullptr; - if (!m_actOnSelection) - { - doc->setImage (m_oldImage); - m_oldImage = kpImage (); + environ()->somethingBelowTheCursorChanged(); } - else - { - doc->setSelection (*m_oldSelectionPtr); - delete m_oldSelectionPtr; m_oldSelectionPtr = nullptr; - environ ()->somethingBelowTheCursorChanged (); - } - - - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } - diff --git a/commands/kpCommand.h b/commands/kpCommand.h --- a/commands/kpCommand.h +++ b/commands/kpCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,15 +24,12 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpCommand_H #define kpCommand_H - #include "kpCommandSize.h" #undef environ // macro on win32 - class QString; class kpAbstractImageSelection; @@ -43,15 +39,14 @@ class kpTextSelection; class kpViewManager; - class kpCommand : public kpCommandSize { public: kpCommand (kpCommandEnvironment *environ); virtual ~kpCommand (); public: - virtual QString name () const = 0; + virtual QString name() const = 0; // Returns the estimated size in bytes. // @@ -65,26 +60,25 @@ // // Implement this by measuring the size of all of your fields, using // kpCommandSize. - virtual SizeType size () const = 0; + virtual SizeType size() const = 0; - virtual void execute () = 0; - virtual void unexecute () = 0; + virtual void execute() = 0; + virtual void unexecute() = 0; protected: - kpCommandEnvironment *environ () const; + kpCommandEnvironment *environ() const; // Commonly used accessors - simply forwards to environ(). - kpDocument *document () const; + kpDocument *document() const; - kpAbstractSelection *selection () const; - kpAbstractImageSelection *imageSelection () const; - kpTextSelection *textSelection () const; + kpAbstractSelection *selection() const; + kpAbstractImageSelection *imageSelection() const; + kpTextSelection *textSelection() const; - kpViewManager *viewManager () const; + kpViewManager *viewManager() const; private: - kpCommandEnvironment * const m_environ; + kpCommandEnvironment *const m_environ; }; - #endif // kpCommand_H diff --git a/commands/kpCommand.cpp b/commands/kpCommand.cpp --- a/commands/kpCommand.cpp +++ b/commands/kpCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,59 +24,51 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COMMAND_HISTORY 0 - #include "kpCommand.h" #include "environments/commands/kpCommandEnvironment.h" - kpCommand::kpCommand (kpCommandEnvironment *environ) - : m_environ (environ) + : m_environ(environ) { - Q_ASSERT (environ); + Q_ASSERT(environ); } kpCommand::~kpCommand () = default; - -kpCommandEnvironment *kpCommand::environ () const +kpCommandEnvironment *kpCommand::environ() const { return m_environ; } - // protected -kpDocument *kpCommand::document () const +kpDocument *kpCommand::document() const { - return m_environ->document (); + return m_environ->document(); } - // protected -kpAbstractSelection *kpCommand::selection () const +kpAbstractSelection *kpCommand::selection() const { - return m_environ->selection (); + return m_environ->selection(); } // protected -kpAbstractImageSelection *kpCommand::imageSelection () const +kpAbstractImageSelection *kpCommand::imageSelection() const { - return m_environ->imageSelection (); + return m_environ->imageSelection(); } // protected -kpTextSelection *kpCommand::textSelection () const +kpTextSelection *kpCommand::textSelection() const { - return m_environ->textSelection (); + return m_environ->textSelection(); } - // protected -kpViewManager *kpCommand::viewManager () const +kpViewManager *kpCommand::viewManager() const { - return m_environ->viewManager (); + return m_environ->viewManager(); } - diff --git a/commands/kpCommandHistory.h b/commands/kpCommandHistory.h --- a/commands/kpCommandHistory.h +++ b/commands/kpCommandHistory.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,17 +24,14 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpCommandHistory_H #define kpCommandHistory_H - #include "kpCommandHistoryBase.h" class kpMainWindow; class kpToolSelectionCreateCommand; - // // KolourPaint-specific command history functionality. // @@ -59,7 +55,7 @@ // class kpCommandHistory : public kpCommandHistoryBase { -Q_OBJECT + Q_OBJECT public: kpCommandHistory (bool doReadConfig, kpMainWindow *mainWindow); @@ -90,16 +86,14 @@ // // REFACTOR: Why not just override addCommand() and test if it was given a // kpToolSelectionCreateCommand? - void addCreateSelectionCommand (kpToolSelectionCreateCommand *cmd, - bool execute = true); + void addCreateSelectionCommand(kpToolSelectionCreateCommand *cmd, bool execute = true); public slots: - void undo () override; - void redo () override; + void undo() override; + void redo() override; protected: kpMainWindow *m_mainWindow; }; - #endif // kpCommandHistory_H diff --git a/commands/kpCommandHistory.cpp b/commands/kpCommandHistory.cpp --- a/commands/kpCommandHistory.cpp +++ b/commands/kpCommandHistory.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,107 +24,93 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COMMAND_HISTORY 0 - #include "kpCommandHistory.h" #include "layers/selections/kpAbstractSelection.h" #include "mainWindow/kpMainWindow.h" #include "tools/kpTool.h" #include "commands/tools/selection/kpToolSelectionCreateCommand.h" - kpCommandHistory::kpCommandHistory (bool doReadConfig, kpMainWindow *mainWindow) - : kpCommandHistoryBase (doReadConfig, mainWindow->actionCollection ()), - m_mainWindow (mainWindow) + : kpCommandHistoryBase(doReadConfig, mainWindow->actionCollection()) + , m_mainWindow(mainWindow) { } kpCommandHistory::~kpCommandHistory () = default; - -static bool NextUndoCommandIsCreateBorder (kpCommandHistory *commandHistory) +static bool NextUndoCommandIsCreateBorder(kpCommandHistory *commandHistory) { - Q_ASSERT (commandHistory); + Q_ASSERT(commandHistory); - kpCommand *cmd = commandHistory->nextUndoCommand (); + kpCommand *cmd = commandHistory->nextUndoCommand(); if (!cmd) { return false; } - auto *c = dynamic_cast (cmd); + auto *c = dynamic_cast (cmd); if (!c) { return false; } - const kpAbstractSelection *sel = c->fromSelection (); - Q_ASSERT (sel); + const kpAbstractSelection *sel = c->fromSelection(); + Q_ASSERT(sel); - return (!sel->hasContent ()); + return !sel->hasContent(); } // public -void kpCommandHistory::addCreateSelectionCommand (kpToolSelectionCreateCommand *cmd, - bool execute) +void kpCommandHistory::addCreateSelectionCommand(kpToolSelectionCreateCommand *cmd, bool execute) { - if (cmd->fromSelection ()->hasContent ()) - { - addCommand (cmd, execute); + if (cmd->fromSelection()->hasContent()) { + addCommand(cmd, execute); return; } - if (::NextUndoCommandIsCreateBorder (this)) - { - setNextUndoCommand (cmd); + if (::NextUndoCommandIsCreateBorder(this)) { + setNextUndoCommand(cmd); if (execute) { - cmd->execute (); + cmd->execute(); } - } - else { - addCommand (cmd, execute); + } else { + addCommand(cmd, execute); } } //--------------------------------------------------------------------- // public slot virtual [base KCommandHistory] -void kpCommandHistory::undo () +void kpCommandHistory::undo() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistory::undo() CALLED!"; #endif - if (m_mainWindow && m_mainWindow->toolHasBegunShape ()) - { + if (m_mainWindow && m_mainWindow->toolHasBegunShape()) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "\thas begun shape - cancel draw"; #endif - m_mainWindow->tool ()->cancelShapeInternal (); - } - else { - kpCommandHistoryBase::undo (); + m_mainWindow->tool()->cancelShapeInternal(); + } else { + kpCommandHistoryBase::undo(); } } //--------------------------------------------------------------------- // public slot virtual [base KCommandHistory] -void kpCommandHistory::redo () +void kpCommandHistory::redo() { - if (m_mainWindow && m_mainWindow->toolHasBegunShape ()) - { + if (m_mainWindow && m_mainWindow->toolHasBegunShape()) { // Not completely obvious but what else can we do? // // Ignoring the request would not be intuitive for tools like // Polygon & Polyline (where it's not always apparent to the user // that s/he's still drawing a shape even though the mouse isn't // down). - m_mainWindow->tool ()->cancelShapeInternal (); - } - else { - kpCommandHistoryBase::redo (); + m_mainWindow->tool()->cancelShapeInternal(); + } else { + kpCommandHistoryBase::redo(); } } - - diff --git a/commands/kpCommandHistoryBase.h b/commands/kpCommandHistoryBase.h --- a/commands/kpCommandHistoryBase.h +++ b/commands/kpCommandHistoryBase.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,16 +24,13 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpCommandHistoryBase_H #define kpCommandHistoryBase_H - #include #include #include - #include "commands/kpCommandSize.h" class QAction; @@ -44,7 +40,6 @@ class kpCommand; - // Clone of KCommandHistory with features required by KolourPaint but which // could also be useful for other apps: // - nextUndoCommand()/nextRedoCommand() @@ -55,72 +50,71 @@ // KCommandHistory, this is only "almost source compatible". class kpCommandHistoryBase : public QObject { -Q_OBJECT + Q_OBJECT public: kpCommandHistoryBase (bool doReadConfig, KActionCollection *ac); ~kpCommandHistoryBase () override; public: // (provided for compatibility with KCommandHistory) - int undoLimit () const; - void setUndoLimit (int limit); - + int undoLimit() const; + void setUndoLimit(int limit); - int undoMinLimit () const; - void setUndoMinLimit (int limit); + int undoMinLimit() const; + void setUndoMinLimit(int limit); - int undoMaxLimit () const; - void setUndoMaxLimit (int limit); + int undoMaxLimit() const; + void setUndoMaxLimit(int limit); - kpCommandSize::SizeType undoMaxLimitSizeLimit () const; - void setUndoMaxLimitSizeLimit (kpCommandSize::SizeType sizeLimit); + kpCommandSize::SizeType undoMaxLimitSizeLimit() const; + void setUndoMaxLimitSizeLimit(kpCommandSize::SizeType sizeLimit); public: // Read and write above config - void readConfig (); - void writeConfig (); + void readConfig(); + void writeConfig(); public: - void addCommand (kpCommand *command, bool execute = true); - void clear (); + void addCommand(kpCommand *command, bool execute = true); + void clear(); protected slots: // (same as undo() & redo() except they don't call // trimCommandListsUpdateActions()) - void undoInternal (); - void redoInternal (); + void undoInternal(); + void redoInternal(); public slots: - virtual void undo (); - virtual void redo (); + virtual void undo(); + virtual void redo(); - virtual void undoUpToNumber (QAction *which); - virtual void redoUpToNumber (QAction *which); + virtual void undoUpToNumber(QAction *which); + virtual void redoUpToNumber(QAction *which); protected: - QString undoActionText () const; - QString redoActionText () const; + QString undoActionText() const; + QString redoActionText() const; - QString undoActionToolTip () const; - QString redoActionToolTip () const; + QString undoActionToolTip() const; + QString redoActionToolTip() const; - void trimCommandListsUpdateActions (); - void trimCommandList (QLinkedList *commandList); - void trimCommandLists (); - void updateActions (); + void trimCommandListsUpdateActions(); + void trimCommandList(QLinkedList *commandList); + void trimCommandLists(); + void updateActions(); public: - kpCommand *nextUndoCommand () const; - kpCommand *nextRedoCommand () const; + kpCommand *nextUndoCommand() const; + kpCommand *nextRedoCommand() const; - void setNextUndoCommand (kpCommand *command); + void setNextUndoCommand(kpCommand *command); public slots: - virtual void documentSaved (); + virtual void documentSaved(); signals: - void documentRestored (); + void documentRestored(); protected: KToolBarPopupAction *m_actionUndo, *m_actionRedo; @@ -142,8 +136,7 @@ int m_documentRestoredPosition; private: - struct kpCommandHistoryBasePrivate * const d; + struct kpCommandHistoryBasePrivate *const d; }; - #endif // kpCommandHistoryBase_H diff --git a/commands/kpCommandHistoryBase.cpp b/commands/kpCommandHistoryBase.cpp --- a/commands/kpCommandHistoryBase.cpp +++ b/commands/kpCommandHistoryBase.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COMMAND_HISTORY 0 - #include "kpCommandHistoryBase.h" #include @@ -56,286 +53,269 @@ //--------------------------------------------------------------------- //template -static void ClearPointerList (QLinkedList *listPtr) +static void ClearPointerList(QLinkedList *listPtr) { - if (!listPtr) + if (!listPtr) { return; + } - qDeleteAll (listPtr->begin (), listPtr->end ()); + qDeleteAll(listPtr->begin(), listPtr->end()); - listPtr->clear (); + listPtr->clear(); } - struct kpCommandHistoryBasePrivate { }; - -kpCommandHistoryBase::kpCommandHistoryBase (bool doReadConfig, - KActionCollection *ac) - : d (new kpCommandHistoryBasePrivate ()) +kpCommandHistoryBase::kpCommandHistoryBase (bool doReadConfig, KActionCollection *ac) + : d(new kpCommandHistoryBasePrivate()) { - m_actionUndo = new KToolBarPopupAction(KDE::icon(QStringLiteral("edit-undo")), undoActionText (), this); - ac->addAction (KStandardAction::name (KStandardAction::Undo), m_actionUndo); - ac->setDefaultShortcuts (m_actionUndo, KStandardShortcut::shortcut (KStandardShortcut::Undo)); - connect (m_actionUndo, &KToolBarPopupAction::triggered, this, &kpCommandHistoryBase::undo); + m_actionUndo = new KToolBarPopupAction(KDE::icon(QStringLiteral("edit-undo")), + undoActionText(), this); + ac->addAction(KStandardAction::name(KStandardAction::Undo), m_actionUndo); + ac->setDefaultShortcuts(m_actionUndo, KStandardShortcut::shortcut(KStandardShortcut::Undo)); + connect(m_actionUndo, &KToolBarPopupAction::triggered, this, &kpCommandHistoryBase::undo); - m_actionRedo = new KToolBarPopupAction(KDE::icon(QStringLiteral("edit-redo")), redoActionText (), this); - ac->addAction (KStandardAction::name (KStandardAction::Redo), m_actionRedo); - ac->setDefaultShortcuts (m_actionRedo, KStandardShortcut::shortcut (KStandardShortcut::Redo)); - connect (m_actionRedo, &KToolBarPopupAction::triggered, this, &kpCommandHistoryBase::redo ); + m_actionRedo = new KToolBarPopupAction(KDE::icon(QStringLiteral("edit-redo")), + redoActionText(), this); + ac->addAction(KStandardAction::name(KStandardAction::Redo), m_actionRedo); + ac->setDefaultShortcuts(m_actionRedo, KStandardShortcut::shortcut(KStandardShortcut::Redo)); + connect(m_actionRedo, &KToolBarPopupAction::triggered, this, &kpCommandHistoryBase::redo); + m_actionUndo->setEnabled(false); + m_actionRedo->setEnabled(false); - m_actionUndo->setEnabled (false); - m_actionRedo->setEnabled (false); - - - connect (m_actionUndo->menu(), &QMenu::triggered, - this, &kpCommandHistoryBase::undoUpToNumber); - - connect (m_actionRedo->menu(), &QMenu::triggered, - this, &kpCommandHistoryBase::redoUpToNumber); + connect(m_actionUndo->menu(), &QMenu::triggered, + this, &kpCommandHistoryBase::undoUpToNumber); + connect(m_actionRedo->menu(), &QMenu::triggered, + this, &kpCommandHistoryBase::redoUpToNumber); m_undoMinLimit = 10; m_undoMaxLimit = 500; m_undoMaxLimitSizeLimit = 16 * 1048576; - m_documentRestoredPosition = 0; - if (doReadConfig) { - readConfig (); + readConfig(); } } kpCommandHistoryBase::~kpCommandHistoryBase () { - ::ClearPointerList (&m_undoCommandList); - ::ClearPointerList (&m_redoCommandList); + ::ClearPointerList(&m_undoCommandList); + ::ClearPointerList(&m_redoCommandList); delete d; } - // public -int kpCommandHistoryBase::undoLimit () const +int kpCommandHistoryBase::undoLimit() const { - return undoMinLimit (); + return undoMinLimit(); } // public -void kpCommandHistoryBase::setUndoLimit (int limit) +void kpCommandHistoryBase::setUndoLimit(int limit) { - setUndoMinLimit (limit); + setUndoMinLimit(limit); } - // public -int kpCommandHistoryBase::undoMinLimit () const +int kpCommandHistoryBase::undoMinLimit() const { return m_undoMinLimit; } // public -void kpCommandHistoryBase::setUndoMinLimit (int limit) +void kpCommandHistoryBase::setUndoMinLimit(int limit) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::setUndoMinLimit(" - << limit << ")"; + << limit << ")"; #endif - if (limit < 1 || limit > 5000/*"ought to be enough for anybody"*/) - { + if (limit < 1 || limit > 5000 /*"ought to be enough for anybody"*/) { qCCritical(kpLogCommands) << "kpCommandHistoryBase::setUndoMinLimit(" - << limit << ")"; + << limit << ")"; return; } if (limit == m_undoMinLimit) { return; } m_undoMinLimit = limit; - trimCommandListsUpdateActions (); + trimCommandListsUpdateActions(); } - // public -int kpCommandHistoryBase::undoMaxLimit () const +int kpCommandHistoryBase::undoMaxLimit() const { return m_undoMaxLimit; } // public -void kpCommandHistoryBase::setUndoMaxLimit (int limit) +void kpCommandHistoryBase::setUndoMaxLimit(int limit) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::setUndoMaxLimit(" - << limit << ")"; + << limit << ")"; #endif - if (limit < 1 || limit > 5000/*"ought to be enough for anybody"*/) - { + if (limit < 1 || limit > 5000 /*"ought to be enough for anybody"*/) { qCCritical(kpLogCommands) << "kpCommandHistoryBase::setUndoMaxLimit(" - << limit << ")"; + << limit << ")"; return; } if (limit == m_undoMaxLimit) { return; } m_undoMaxLimit = limit; - trimCommandListsUpdateActions (); + trimCommandListsUpdateActions(); } - // public -kpCommandSize::SizeType kpCommandHistoryBase::undoMaxLimitSizeLimit () const +kpCommandSize::SizeType kpCommandHistoryBase::undoMaxLimitSizeLimit() const { return m_undoMaxLimitSizeLimit; } // public -void kpCommandHistoryBase::setUndoMaxLimitSizeLimit (kpCommandSize::SizeType sizeLimit) +void kpCommandHistoryBase::setUndoMaxLimitSizeLimit(kpCommandSize::SizeType sizeLimit) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::setUndoMaxLimitSizeLimit(" - << sizeLimit << ")"; + << sizeLimit << ")"; #endif - if (sizeLimit < 0 || - sizeLimit > (500 * 1048576)/*"ought to be enough for anybody"*/) - { + if (sizeLimit < 0 + || sizeLimit > (500 * 1048576) /*"ought to be enough for anybody"*/) { qCCritical(kpLogCommands) << "kpCommandHistoryBase::setUndoMaxLimitSizeLimit(" - << sizeLimit << ")"; + << sizeLimit << ")"; return; } if (sizeLimit == m_undoMaxLimitSizeLimit) { return; } m_undoMaxLimitSizeLimit = sizeLimit; - trimCommandListsUpdateActions (); + trimCommandListsUpdateActions(); } - // public -void kpCommandHistoryBase::readConfig () +void kpCommandHistoryBase::readConfig() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::readConfig()"; #endif - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupUndoRedo); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupUndoRedo); - setUndoMinLimit (cfg.readEntry (kpSettingUndoMinLimit, undoMinLimit ())); - setUndoMaxLimit (cfg.readEntry (kpSettingUndoMaxLimit, undoMaxLimit ())); - setUndoMaxLimitSizeLimit ( - cfg.readEntry (kpSettingUndoMaxLimitSizeLimit, - undoMaxLimitSizeLimit ())); + setUndoMinLimit(cfg.readEntry(kpSettingUndoMinLimit, undoMinLimit())); + setUndoMaxLimit(cfg.readEntry(kpSettingUndoMaxLimit, undoMaxLimit())); + setUndoMaxLimitSizeLimit( + cfg.readEntry (kpSettingUndoMaxLimitSizeLimit, + undoMaxLimitSizeLimit())); - trimCommandListsUpdateActions (); + trimCommandListsUpdateActions(); } // public -void kpCommandHistoryBase::writeConfig () +void kpCommandHistoryBase::writeConfig() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::writeConfig()"; #endif - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupUndoRedo); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupUndoRedo); - cfg.writeEntry (kpSettingUndoMinLimit, undoMinLimit ()); - cfg.writeEntry (kpSettingUndoMaxLimit, undoMaxLimit ()); - cfg.writeEntry ( - kpSettingUndoMaxLimitSizeLimit, undoMaxLimitSizeLimit ()); + cfg.writeEntry(kpSettingUndoMinLimit, undoMinLimit()); + cfg.writeEntry(kpSettingUndoMaxLimit, undoMaxLimit()); + cfg.writeEntry ( + kpSettingUndoMaxLimitSizeLimit, undoMaxLimitSizeLimit()); - cfg.sync (); + cfg.sync(); } - // public -void kpCommandHistoryBase::addCommand (kpCommand *command, bool execute) +void kpCommandHistoryBase::addCommand(kpCommand *command, bool execute) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::addCommand(" - << command - << ",execute=" << execute << ")" + << command + << ",execute=" << execute << ")" #endif if (execute) { - command->execute (); + command->execute(); } - m_undoCommandList.push_front (command); - ::ClearPointerList (&m_redoCommandList); + m_undoCommandList.push_front(command); + ::ClearPointerList(&m_redoCommandList); #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "\tdocumentRestoredPosition=" << m_documentRestoredPosition; #endif - if (m_documentRestoredPosition != INT_MAX) - { + if (m_documentRestoredPosition != INT_MAX) { if (m_documentRestoredPosition > 0) { m_documentRestoredPosition = INT_MAX; - } - else { + } else { m_documentRestoredPosition--; } #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "\t\tdocumentRestoredPosition=" << m_documentRestoredPosition; #endif } - trimCommandListsUpdateActions (); + trimCommandListsUpdateActions(); } // public -void kpCommandHistoryBase::clear () +void kpCommandHistoryBase::clear() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::clear()"; #endif - ::ClearPointerList (&m_undoCommandList); - ::ClearPointerList (&m_redoCommandList); + ::ClearPointerList(&m_undoCommandList); + ::ClearPointerList(&m_redoCommandList); m_documentRestoredPosition = 0; - updateActions (); + updateActions(); } //--------------------------------------------------------------------- // protected slot -void kpCommandHistoryBase::undoInternal () +void kpCommandHistoryBase::undoInternal() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::undoInternal()"; #endif - kpCommand *undoCommand = nextUndoCommand (); + kpCommand *undoCommand = nextUndoCommand(); if (!undoCommand) { return; } - undoCommand->unexecute (); - + undoCommand->unexecute(); - m_undoCommandList.erase (m_undoCommandList.begin ()); - m_redoCommandList.push_front (undoCommand); + m_undoCommandList.erase(m_undoCommandList.begin()); + m_redoCommandList.push_front(undoCommand); #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "\tdocumentRestoredPosition=" << m_documentRestoredPosition; #endif - if (m_documentRestoredPosition != INT_MAX) - { + if (m_documentRestoredPosition != INT_MAX) { m_documentRestoredPosition++; - if (m_documentRestoredPosition == 0) - emit documentRestored (); + if (m_documentRestoredPosition == 0) { + emit documentRestored(); + } #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "\t\tdocumentRestoredPosition=" << m_documentRestoredPosition; #endif @@ -345,31 +325,29 @@ //--------------------------------------------------------------------- // protected slot -void kpCommandHistoryBase::redoInternal () +void kpCommandHistoryBase::redoInternal() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::redoInternal()"; #endif - kpCommand *redoCommand = nextRedoCommand (); + kpCommand *redoCommand = nextRedoCommand(); if (!redoCommand) { return; } - redoCommand->execute (); + redoCommand->execute(); - - m_redoCommandList.erase (m_redoCommandList.begin ()); - m_undoCommandList.push_front (redoCommand); + m_redoCommandList.erase(m_redoCommandList.begin()); + m_undoCommandList.push_front(redoCommand); #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "\tdocumentRestoredPosition=" << m_documentRestoredPosition; #endif - if (m_documentRestoredPosition != INT_MAX) - { + if (m_documentRestoredPosition != INT_MAX) { m_documentRestoredPosition--; if (m_documentRestoredPosition == 0) { - emit documentRestored (); + emit documentRestored(); } #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "\t\tdocumentRestoredPosition=" << m_documentRestoredPosition; @@ -380,176 +358,165 @@ //--------------------------------------------------------------------- // public slot virtual -void kpCommandHistoryBase::undo () +void kpCommandHistoryBase::undo() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::undo()"; #endif - undoInternal (); - trimCommandListsUpdateActions (); + undoInternal(); + trimCommandListsUpdateActions(); } //--------------------------------------------------------------------- // public slot virtual -void kpCommandHistoryBase::redo () +void kpCommandHistoryBase::redo() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::redo()"; #endif - redoInternal (); - trimCommandListsUpdateActions (); + redoInternal(); + trimCommandListsUpdateActions(); } //--------------------------------------------------------------------- // public slot virtual -void kpCommandHistoryBase::undoUpToNumber (QAction *which) +void kpCommandHistoryBase::undoUpToNumber(QAction *which) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::undoUpToNumber(" << which << ")"; #endif for (int i = 0; - i <= which->data().toInt() && !m_undoCommandList.isEmpty (); - i++) - { - undoInternal (); + i <= which->data().toInt() && !m_undoCommandList.isEmpty(); + i++) { + undoInternal(); } - trimCommandListsUpdateActions (); + trimCommandListsUpdateActions(); } // public slot virtual -void kpCommandHistoryBase::redoUpToNumber (QAction *which) +void kpCommandHistoryBase::redoUpToNumber(QAction *which) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::redoUpToNumber(" << which << ")"; #endif for (int i = 0; - i <= which->data().toInt() && !m_redoCommandList.isEmpty (); - i++) - { - redoInternal (); + i <= which->data().toInt() && !m_redoCommandList.isEmpty(); + i++) { + redoInternal(); } - trimCommandListsUpdateActions (); + trimCommandListsUpdateActions(); } - // protected -QString kpCommandHistoryBase::undoActionText () const +QString kpCommandHistoryBase::undoActionText() const { - kpCommand *undoCommand = nextUndoCommand (); + kpCommand *undoCommand = nextUndoCommand(); - return (undoCommand) ? i18n ("&Undo: %1", undoCommand->name ()) : i18n ("&Undo"); + return (undoCommand) ? i18n("&Undo: %1", undoCommand->name()) : i18n("&Undo"); } // protected -QString kpCommandHistoryBase::redoActionText () const +QString kpCommandHistoryBase::redoActionText() const { - kpCommand *redoCommand = nextRedoCommand (); + kpCommand *redoCommand = nextRedoCommand(); - return (redoCommand) ? i18n ("&Redo: %1", redoCommand->name ()) : i18n ("&Redo"); + return (redoCommand) ? i18n("&Redo: %1", redoCommand->name()) : i18n("&Redo"); } - // protected -QString kpCommandHistoryBase::undoActionToolTip () const +QString kpCommandHistoryBase::undoActionToolTip() const { - kpCommand *undoCommand = nextUndoCommand (); + kpCommand *undoCommand = nextUndoCommand(); - return (undoCommand) ? i18n ("Undo: %1", undoCommand->name ()) : i18n ("Undo"); + return (undoCommand) ? i18n("Undo: %1", undoCommand->name()) : i18n("Undo"); } // protected -QString kpCommandHistoryBase::redoActionToolTip () const +QString kpCommandHistoryBase::redoActionToolTip() const { - kpCommand *redoCommand = nextRedoCommand (); + kpCommand *redoCommand = nextRedoCommand(); - return (redoCommand) ? i18n ("Redo: %1", redoCommand->name ()) : i18n ("Redo"); + return (redoCommand) ? i18n("Redo: %1", redoCommand->name()) : i18n("Redo"); } - // protected -void kpCommandHistoryBase::trimCommandListsUpdateActions () +void kpCommandHistoryBase::trimCommandListsUpdateActions() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::trimCommandListsUpdateActions()"; #endif - trimCommandLists (); - updateActions (); + trimCommandLists(); + updateActions(); } // protected -void kpCommandHistoryBase::trimCommandList (QLinkedList *commandList) +void kpCommandHistoryBase::trimCommandList(QLinkedList *commandList) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::trimCommandList()"; - QTime timer; timer.start (); + QTime timer; + timer.start(); #endif - if (!commandList) - { + if (!commandList) { qCCritical(kpLogCommands) << "kpCommandHistoryBase::trimCommandList() passed 0 commandList"; return; } - #if DEBUG_KP_COMMAND_HISTORY - qCDebug(kpLogCommands) << "\tsize=" << commandList->size () - << " undoMinLimit=" << m_undoMinLimit - << " undoMaxLimit=" << m_undoMaxLimit - << " undoMaxLimitSizeLimit=" << m_undoMaxLimitSizeLimit; + qCDebug(kpLogCommands) << "\tsize=" << commandList->size() + << " undoMinLimit=" << m_undoMinLimit + << " undoMaxLimit=" << m_undoMaxLimit + << " undoMaxLimitSizeLimit=" << m_undoMaxLimitSizeLimit; #endif - if (static_cast (commandList->size ()) <= m_undoMinLimit) - { + if (static_cast(commandList->size()) <= m_undoMinLimit) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "\t\tsize under undoMinLimit - done"; #endif return; } - #if DEBUG_KP_COMMAND_HISTORY && 0 qCDebug(kpLogCommands) << "\tsize over undoMinLimit - iterating thru cmds:"; #endif - QLinkedList ::iterator it = commandList->begin (); + QLinkedList ::iterator it = commandList->begin(); int upto = 0; kpCommandSize::SizeType sizeSoFar = 0; - while (it != commandList->end ()) + while (it != commandList->end()) { bool advanceIt = true; - if (sizeSoFar <= m_undoMaxLimitSizeLimit) - { - sizeSoFar += (*it)->size (); + if (sizeSoFar <= m_undoMaxLimitSizeLimit) { + sizeSoFar += (*it)->size(); } #if DEBUG_KP_COMMAND_HISTORY && 0 qCDebug(kpLogCommands) << "\t\t" << upto << ":" - << " name='" << (*it)->name () - << "' size=" << (*it)->size () - << " sizeSoFar=" << sizeSoFar; + << " name='" << (*it)->name() + << "' size=" << (*it)->size() + << " sizeSoFar=" << sizeSoFar; #endif - if (upto >= m_undoMinLimit) - { - if (upto >= m_undoMaxLimit || - sizeSoFar > m_undoMaxLimitSizeLimit) - { + if (upto >= m_undoMinLimit) { + if (upto >= m_undoMaxLimit + || sizeSoFar > m_undoMaxLimitSizeLimit) { #if DEBUG_KP_COMMAND_HISTORY && 0 qCDebug(kpLogCommands) << "\t\t\tkill"; #endif delete (*it); - it = m_undoCommandList.erase (it); + it = m_undoCommandList.erase(it); advanceIt = false; } } @@ -561,170 +528,160 @@ } #if DEBUG_KP_COMMAND_HISTORY - qCDebug(kpLogCommands) << "\ttook " << timer.elapsed () << "ms"; + qCDebug(kpLogCommands) << "\ttook " << timer.elapsed() << "ms"; #endif } // protected -void kpCommandHistoryBase::trimCommandLists () +void kpCommandHistoryBase::trimCommandLists() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::trimCommandLists()"; #endif - trimCommandList (&m_undoCommandList); - trimCommandList (&m_redoCommandList); + trimCommandList(&m_undoCommandList); + trimCommandList(&m_redoCommandList); #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "\tdocumentRestoredPosition=" << m_documentRestoredPosition #endif - if (m_documentRestoredPosition != INT_MAX) - { + if (m_documentRestoredPosition != INT_MAX) { #if DEBUG_KP_COMMAND_HISTORY - qCDebug(kpLogCommands) << "\t\tundoCmdList.size=" << m_undoCommandList.size () - << " redoCmdList.size=" << m_redoCommandList.size (); + qCDebug(kpLogCommands) << "\t\tundoCmdList.size=" << m_undoCommandList.size() + << " redoCmdList.size=" << m_redoCommandList.size(); #endif - if (m_documentRestoredPosition > static_cast (m_redoCommandList.size ()) || - -m_documentRestoredPosition > static_cast (m_undoCommandList.size ())) - { + if (m_documentRestoredPosition > static_cast(m_redoCommandList.size()) + || -m_documentRestoredPosition > static_cast(m_undoCommandList.size())) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "\t\t\tinvalidate documentRestoredPosition"; #endif m_documentRestoredPosition = INT_MAX; } } } - -static void populatePopupMenu (QMenu *popupMenu, - const QString &undoOrRedo, - const QLinkedList &commandList) +static void populatePopupMenu(QMenu *popupMenu, const QString &undoOrRedo, + const QLinkedList &commandList) { if (!popupMenu) { return; } - popupMenu->clear (); + popupMenu->clear(); - QLinkedList ::const_iterator it = commandList.begin (); + QLinkedList ::const_iterator it = commandList.begin(); int i = 0; - while (i < 10 && it != commandList.end ()) + while (i < 10 && it != commandList.end()) { - QAction *action = new QAction(i18n ("%1: %2", undoOrRedo, (*it)->name ()), popupMenu); + QAction *action = new QAction(i18n("%1: %2", undoOrRedo, (*it)->name()), popupMenu); action->setData(i); - popupMenu->addAction (action); + popupMenu->addAction(action); i++; it++; } - if (it != commandList.end ()) - { + if (it != commandList.end()) { // TODO: maybe have a scrollview show all the items instead, like KOffice in KDE 3 // LOCOMPAT: should be centered text. - popupMenu->addSection (i18np ("%1 more item", "%1 more items", - commandList.size () - i)); + popupMenu->addSection(i18np("%1 more item", "%1 more items", + commandList.size() - i)); } } - // protected -void kpCommandHistoryBase::updateActions () +void kpCommandHistoryBase::updateActions() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::updateActions()"; #endif - m_actionUndo->setEnabled (static_cast (nextUndoCommand ())); + m_actionUndo->setEnabled(static_cast(nextUndoCommand())); // Don't want to keep changing toolbar text. // TODO: As a bad side-effect, the menu doesn't have "Undo: " // anymore. In any case, the KDE4 KToolBarPopupAction // sucks in menus as it forces the clicking of a submenu. IMO, // there should be no submenu in the menu. //m_actionUndo->setText (undoActionText ()); // But in icon mode, a tooltip with context is useful. - m_actionUndo->setToolTip (undoActionToolTip ()); + m_actionUndo->setToolTip(undoActionToolTip()); #if DEBUG_KP_COMMAND_HISTORY - QTime timer; timer.start (); + QTime timer; + timer.start(); #endif - populatePopupMenu (m_actionUndo->menu (), - i18n ("Undo"), - m_undoCommandList); + populatePopupMenu(m_actionUndo->menu(), + i18n("Undo"), + m_undoCommandList); #if DEBUG_KP_COMMAND_HISTORY - qCDebug(kpLogCommands) << "\tpopuplatePopupMenu undo=" << timer.elapsed () - << "ms"; + qCDebug(kpLogCommands) << "\tpopuplatePopupMenu undo=" << timer.elapsed() + << "ms"; #endif - m_actionRedo->setEnabled (static_cast (nextRedoCommand ())); + m_actionRedo->setEnabled(static_cast(nextRedoCommand())); // Don't want to keep changing toolbar text. // TODO: As a bad side-effect, the menu doesn't have "Undo: " // anymore. In any case, the KDE4 KToolBarPopupAction // sucks in menus as it forces the clicking of a submenu. IMO, // there should be no submenu in the menu. //m_actionRedo->setText (redoActionText ()); // But in icon mode, a tooltip with context is useful. - m_actionRedo->setToolTip (redoActionToolTip ()); + m_actionRedo->setToolTip(redoActionToolTip()); #if DEBUG_KP_COMMAND_HISTORY - timer.restart (); + timer.restart(); #endif - populatePopupMenu (m_actionRedo->menu (), - i18n ("Redo"), - m_redoCommandList); + populatePopupMenu(m_actionRedo->menu(), + i18n("Redo"), + m_redoCommandList); #if DEBUG_KP_COMMAND_HISTORY - qCDebug(kpLogCommands) << "\tpopuplatePopupMenu redo=" << timer.elapsed () - << "ms"; + qCDebug(kpLogCommands) << "\tpopuplatePopupMenu redo=" << timer.elapsed() + << "ms"; #endif } - // public -kpCommand *kpCommandHistoryBase::nextUndoCommand () const +kpCommand *kpCommandHistoryBase::nextUndoCommand() const { - if (m_undoCommandList.isEmpty ()) { + if (m_undoCommandList.isEmpty()) { return nullptr; } - return m_undoCommandList.first (); + return m_undoCommandList.first(); } // public -kpCommand *kpCommandHistoryBase::nextRedoCommand () const +kpCommand *kpCommandHistoryBase::nextRedoCommand() const { - if (m_redoCommandList.isEmpty ()) { + if (m_redoCommandList.isEmpty()) { return nullptr; } - return m_redoCommandList.first (); + return m_redoCommandList.first(); } - // public -void kpCommandHistoryBase::setNextUndoCommand (kpCommand *command) +void kpCommandHistoryBase::setNextUndoCommand(kpCommand *command) { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::setNextUndoCommand("<< command << ")"; #endif - if (m_undoCommandList.isEmpty ()) { + if (m_undoCommandList.isEmpty()) { return; } - delete *m_undoCommandList.begin (); - *m_undoCommandList.begin () = command; + delete *m_undoCommandList.begin(); + *m_undoCommandList.begin() = command; - trimCommandListsUpdateActions (); + trimCommandListsUpdateActions(); } - // public slot virtual -void kpCommandHistoryBase::documentSaved () +void kpCommandHistoryBase::documentSaved() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpCommandHistoryBase::documentSaved()"; #endif m_documentRestoredPosition = 0; } - - diff --git a/commands/kpCommandSize.h b/commands/kpCommandSize.h --- a/commands/kpCommandSize.h +++ b/commands/kpCommandSize.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,21 +24,17 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpCommandSize_H #define kpCommandSize_H - #include "imagelib/kpImage.h" - class QImage; class QPolygon; class QString; class kpAbstractSelection; - // // Estimates the size of the object being pointed to, in bytes. // @@ -64,24 +59,23 @@ // implementations of kpCommand::size()). typedef qlonglong SizeType; - static SizeType PixmapSize (const QImage &image); - static SizeType PixmapSize (const QImage *image); - static SizeType PixmapSize (int width, int height, int depth); + static SizeType PixmapSize(const QImage &image); + static SizeType PixmapSize(const QImage *image); + static SizeType PixmapSize(int width, int height, int depth); - static SizeType QImageSize (const QImage &image); - static SizeType QImageSize (const QImage *image); - static SizeType QImageSize (int width, int height, int depth); + static SizeType QImageSize(const QImage &image); + static SizeType QImageSize(const QImage *image); + static SizeType QImageSize(int width, int height, int depth); - static SizeType ImageSize (const kpImage &image); - static SizeType ImageSize (const kpImage *image); + static SizeType ImageSize(const kpImage &image); + static SizeType ImageSize(const kpImage *image); - static SizeType SelectionSize (const kpAbstractSelection &sel); - static SizeType SelectionSize (const kpAbstractSelection *sel); + static SizeType SelectionSize(const kpAbstractSelection &sel); + static SizeType SelectionSize(const kpAbstractSelection *sel); - static SizeType StringSize (const QString &string); + static SizeType StringSize(const QString &string); - static SizeType PolygonSize (const QPolygon &points); + static SizeType PolygonSize(const QPolygon &points); }; - #endif // kpCommandSize_H diff --git a/commands/kpCommandSize.cpp b/commands/kpCommandSize.cpp --- a/commands/kpCommandSize.cpp +++ b/commands/kpCommandSize.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,128 +24,119 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COMMAND_SIZE 0 - #include "commands/kpCommandSize.h" #include "layers/selections/kpAbstractSelection.h" #include #include #include - // public static -kpCommandSize::SizeType kpCommandSize::PixmapSize (const QImage &image) +kpCommandSize::SizeType kpCommandSize::PixmapSize(const QImage &image) { - return kpCommandSize::PixmapSize (image.width (), image.height (), image.depth ()); + return kpCommandSize::PixmapSize(image.width(), image.height(), image.depth()); } // public static -kpCommandSize::SizeType kpCommandSize::PixmapSize (const QImage *image) +kpCommandSize::SizeType kpCommandSize::PixmapSize(const QImage *image) { - return (image ? kpCommandSize::PixmapSize (*image) : 0); + return image ? kpCommandSize::PixmapSize(*image) : 0; } // public static -kpCommandSize::SizeType kpCommandSize::PixmapSize (int width, int height, int depth) +kpCommandSize::SizeType kpCommandSize::PixmapSize(int width, int height, int depth) { // handle 15bpp int roundedDepth = (depth > 8 ? (depth + 7) / 8 * 8 : depth); - kpCommandSize::SizeType ret = - static_cast (width) * height * roundedDepth / 8; + kpCommandSize::SizeType ret + = static_cast(width) * height * roundedDepth / 8; #if DEBUG_KP_COMMAND_SIZE && 0 qCDebug(kpLogCommands) << "kpCommandSize::PixmapSize() w=" << width - << " h=" << height - << " d=" << depth - << " roundedDepth=" << roundedDepth - << " ret=" << ret; + << " h=" << height + << " d=" << depth + << " roundedDepth=" << roundedDepth + << " ret=" << ret; #endif return ret; } - // public static -kpCommandSize::SizeType kpCommandSize::QImageSize (const QImage &image) +kpCommandSize::SizeType kpCommandSize::QImageSize(const QImage &image) { - return kpCommandSize::QImageSize (image.width (), image.height (), image.depth ()); + return kpCommandSize::QImageSize(image.width(), image.height(), image.depth()); } // public static -kpCommandSize::SizeType kpCommandSize::QImageSize (const QImage *image) +kpCommandSize::SizeType kpCommandSize::QImageSize(const QImage *image) { - return (image ? kpCommandSize::QImageSize (*image) : 0); + return image ? kpCommandSize::QImageSize(*image) : 0; } // public static -kpCommandSize::SizeType kpCommandSize::QImageSize (int width, int height, int depth) +kpCommandSize::SizeType kpCommandSize::QImageSize(int width, int height, int depth) { // handle 15bpp int roundedDepth = (depth > 8 ? (depth + 7) / 8 * 8 : depth); - kpCommandSize::SizeType ret = - static_cast (width) * height * roundedDepth / 8; + kpCommandSize::SizeType ret + = static_cast(width) * height * roundedDepth / 8; #if DEBUG_KP_COMMAND_SIZE && 0 qCDebug(kpLogCommands) << "kpCommandSize::QImageSize() w=" << width - << " h=" << height - << " d=" << depth - << " roundedDepth=" << roundedDepth - << " ret=" << ret; + << " h=" << height + << " d=" << depth + << " roundedDepth=" << roundedDepth + << " ret=" << ret; #endif return ret; } - // public static -kpCommandSize::SizeType kpCommandSize::ImageSize (const kpImage &image) +kpCommandSize::SizeType kpCommandSize::ImageSize(const kpImage &image) { - return kpCommandSize::PixmapSize (image); + return kpCommandSize::PixmapSize(image); } // public static -kpCommandSize::SizeType kpCommandSize::ImageSize (const kpImage *image) +kpCommandSize::SizeType kpCommandSize::ImageSize(const kpImage *image) { - return kpCommandSize::PixmapSize (image); + return kpCommandSize::PixmapSize(image); } - // public static -kpCommandSize::SizeType kpCommandSize::SelectionSize (const kpAbstractSelection &sel) +kpCommandSize::SizeType kpCommandSize::SelectionSize(const kpAbstractSelection &sel) { - return sel.size (); + return sel.size(); } // public static -kpCommandSize::SizeType kpCommandSize::SelectionSize (const kpAbstractSelection *sel) +kpCommandSize::SizeType kpCommandSize::SelectionSize(const kpAbstractSelection *sel) { - return (sel ? sel->size () : 0); + return sel ? sel->size() : 0; } - // public static -kpCommandSize::SizeType kpCommandSize::StringSize (const QString &string) +kpCommandSize::SizeType kpCommandSize::StringSize(const QString &string) { #if DEBUG_KP_COMMAND_SIZE && 1 qCDebug(kpLogCommands) << "kpCommandSize::StringSize(" << string << ")" - << " len=" << string.length () - << " sizeof(QChar)=" << sizeof (QChar); + << " len=" << string.length() + << " sizeof(QChar)=" << sizeof(QChar); #endif - return static_cast (static_cast (string.length ()) * sizeof (QChar)); + return static_cast(static_cast(string.length()) * sizeof(QChar)); } - // public static -kpCommandSize::SizeType kpCommandSize::PolygonSize (const QPolygon &points) +kpCommandSize::SizeType kpCommandSize::PolygonSize(const QPolygon &points) { #if DEBUG_KP_COMMAND_SIZE && 1 qCDebug(kpLogCommands) << "kpCommandSize::PolygonSize() points.size=" - << points.size () - << " sizeof(QPoint)=" << sizeof (QPoint); + << points.size() + << " sizeof(QPoint)=" << sizeof(QPoint); #endif - return static_cast (static_cast (points.size ()) * sizeof (QPoint)); + return static_cast(static_cast(points.size()) * sizeof(QPoint)); } - diff --git a/commands/kpMacroCommand.h b/commands/kpMacroCommand.h --- a/commands/kpMacroCommand.h +++ b/commands/kpMacroCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,45 +24,39 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpMacroCommand_H #define kpMacroCommand_H - #include "commands/kpNamedCommand.h" #include - class kpMacroCommand : public kpNamedCommand { public: kpMacroCommand (const QString &name, kpCommandEnvironment *environ); ~kpMacroCommand () override; - // // kpCommand Interface // - SizeType size () const override; - - void execute () override; - void unexecute () override; + SizeType size() const override; + void execute() override; + void unexecute() override; // // Interface // - void addCommand (kpCommand *command); + void addCommand(kpCommand *command); protected: QLinkedList m_commandList; private: - struct kpMacroCommandPrivate * const d; + struct kpMacroCommandPrivate *const d; }; - #endif // kpMacroCommand_H diff --git a/commands/kpMacroCommand.cpp b/commands/kpMacroCommand.cpp --- a/commands/kpMacroCommand.cpp +++ b/commands/kpMacroCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COMMAND_HISTORY 0 - #include "commands/kpMacroCommand.h" #include "views/manager/kpViewManager.h" @@ -42,25 +39,24 @@ { }; - kpMacroCommand::kpMacroCommand (const QString &name, kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - d (new kpMacroCommandPrivate ()) + : kpNamedCommand(name, environ) + , d(new kpMacroCommandPrivate()) { } //--------------------------------------------------------------------- kpMacroCommand::~kpMacroCommand () { - qDeleteAll (m_commandList.begin (), m_commandList.end ()); + qDeleteAll(m_commandList.begin(), m_commandList.end()); delete d; } //--------------------------------------------------------------------- // public virtual [base kpCommand] -kpCommandSize::SizeType kpMacroCommand::size () const +kpCommandSize::SizeType kpMacroCommand::size() const { #if DEBUG_KP_COMMAND_HISTORY && 0 qCDebug(kpLogCommands) << "kpMacroCommand::size()"; @@ -70,13 +66,12 @@ #if DEBUG_KP_COMMAND_HISTORY && 0 qCDebug(kpLogCommands) << "\tcalculating:"; #endif - foreach (kpCommand *cmd, m_commandList) - { + foreach (kpCommand *cmd, m_commandList) { #if DEBUG_KP_COMMAND_HISTORY && 0 qCDebug(kpLogCommands) << "\t\tcurrentSize=" << s << " + " - << cmd->name () << ".size=" << cmd->size (); + << cmd->name() << ".size=" << cmd->size(); #endif - s += cmd->size (); + s += cmd->size(); } #if DEBUG_KP_COMMAND_HISTORY && 0 @@ -88,47 +83,46 @@ //--------------------------------------------------------------------- // public virtual [base kpCommand] -void kpMacroCommand::execute () +void kpMacroCommand::execute() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpMacroCommand::execute()"; #endif viewManager()->setQueueUpdates(); - for (QLinkedList ::const_iterator it = m_commandList.begin (); - it != m_commandList.end (); - ++it) - { + for (QLinkedList ::const_iterator it = m_commandList.begin(); + it != m_commandList.end(); + ++it) { #if DEBUG_KP_COMMAND_HISTORY - qCDebug(kpLogCommands) << "\texecuting " << (*it)->name (); + qCDebug(kpLogCommands) << "\texecuting " << (*it)->name(); #endif - (*it)->execute (); + (*it)->execute(); } viewManager()->restoreQueueUpdates(); } //--------------------------------------------------------------------- // public virtual [base kpCommand] -void kpMacroCommand::unexecute () +void kpMacroCommand::unexecute() { #if DEBUG_KP_COMMAND_HISTORY qCDebug(kpLogCommands) << "kpMacroCommand::unexecute()"; #endif viewManager()->setQueueUpdates(); - QLinkedList ::const_iterator it = m_commandList.end (); + QLinkedList ::const_iterator it = m_commandList.end(); it--; - while (it != m_commandList.end ()) + while (it != m_commandList.end()) { #if DEBUG_KP_COMMAND_HISTORY - qCDebug(kpLogCommands) << "\tunexecuting " << (*it)->name (); + qCDebug(kpLogCommands) << "\tunexecuting " << (*it)->name(); #endif - (*it)->unexecute (); + (*it)->unexecute(); it--; } @@ -139,9 +133,9 @@ //--------------------------------------------------------------------- // public -void kpMacroCommand::addCommand (kpCommand *command) +void kpMacroCommand::addCommand(kpCommand *command) { - m_commandList.push_back (command); + m_commandList.push_back(command); } //--------------------------------------------------------------------- diff --git a/commands/kpNamedCommand.h b/commands/kpNamedCommand.h --- a/commands/kpNamedCommand.h +++ b/commands/kpNamedCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,22 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpNamedCommand_H #define kpNamedCommand_H - #include "commands/kpCommand.h" #include - class kpNamedCommand : public kpCommand { public: kpNamedCommand (const QString &name, kpCommandEnvironment *environ); - QString name () const override; + QString name() const override; protected: QString m_name; }; - #endif // kpNamedCommand_H diff --git a/commands/kpNamedCommand.cpp b/commands/kpNamedCommand.cpp --- a/commands/kpNamedCommand.cpp +++ b/commands/kpNamedCommand.cpp @@ -29,15 +29,15 @@ //--------------------------------------------------------------------- kpNamedCommand::kpNamedCommand (const QString &name, kpCommandEnvironment *environ) - : kpCommand (environ), - m_name (name) + : kpCommand(environ) + , m_name(name) { } //--------------------------------------------------------------------- // public virtual [base kpCommand] -QString kpNamedCommand::name () const +QString kpNamedCommand::name() const { return m_name; } diff --git a/commands/tools/flow/kpToolFlowCommand.h b/commands/tools/flow/kpToolFlowCommand.h --- a/commands/tools/flow/kpToolFlowCommand.h +++ b/commands/tools/flow/kpToolFlowCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,40 +24,35 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_FLOW_COMMAND_H #define KP_TOOL_FLOW_COMMAND_H - #include "commands/kpNamedCommand.h" - class QPoint; class QRect; - class kpToolFlowCommand : public kpNamedCommand { public: kpToolFlowCommand (const QString &name, kpCommandEnvironment *environ); ~kpToolFlowCommand () override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; // interface for kpToolFlowBase - void updateBoundingRect (const QPoint &point); - void updateBoundingRect (const QRect &rect); - void finalize (); - void cancel (); + void updateBoundingRect(const QPoint &point); + void updateBoundingRect(const QRect &rect); + void finalize(); + void cancel(); private: - void swapOldAndNew (); + void swapOldAndNew(); - struct kpToolFlowCommandPrivate * const d; + struct kpToolFlowCommandPrivate *const d; }; - #endif // KP_TOOL_FLOW_COMMAND_H diff --git a/commands/tools/flow/kpToolFlowCommand.cpp b/commands/tools/flow/kpToolFlowCommand.cpp --- a/commands/tools/flow/kpToolFlowCommand.cpp +++ b/commands/tools/flow/kpToolFlowCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_FLOW_COMMAND 0 - #include "kpToolFlowCommand.h" #include "document/kpDocument.h" @@ -39,102 +36,92 @@ #include - struct kpToolFlowCommandPrivate { kpImage image; QRect boundingRect; }; - kpToolFlowCommand::kpToolFlowCommand (const QString &name, kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - d (new kpToolFlowCommandPrivate ()) + : kpNamedCommand(name, environ) + , d(new kpToolFlowCommandPrivate()) { - d->image = document ()->image (); + d->image = document()->image(); } kpToolFlowCommand::~kpToolFlowCommand () { delete d; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolFlowCommand::size () const +kpCommandSize::SizeType kpToolFlowCommand::size() const { - return ImageSize (d->image); + return ImageSize(d->image); } - // public virtual [base kpCommand] -void kpToolFlowCommand::execute () +void kpToolFlowCommand::execute() { - swapOldAndNew (); + swapOldAndNew(); } // public virtual [base kpCommand] -void kpToolFlowCommand::unexecute () +void kpToolFlowCommand::unexecute() { - swapOldAndNew (); + swapOldAndNew(); } - // private -void kpToolFlowCommand::swapOldAndNew () +void kpToolFlowCommand::swapOldAndNew() { - if (d->boundingRect.isValid ()) - { - const kpImage oldImage = document ()->getImageAt (d->boundingRect); + if (d->boundingRect.isValid()) { + const kpImage oldImage = document()->getImageAt(d->boundingRect); - document ()->setImageAt (d->image, d->boundingRect.topLeft ()); + document()->setImageAt(d->image, d->boundingRect.topLeft()); d->image = oldImage; } } // public -void kpToolFlowCommand::updateBoundingRect (const QPoint &point) +void kpToolFlowCommand::updateBoundingRect(const QPoint &point) { - updateBoundingRect (QRect (point, point)); + updateBoundingRect(QRect(point, point)); } // public -void kpToolFlowCommand::updateBoundingRect (const QRect &rect) +void kpToolFlowCommand::updateBoundingRect(const QRect &rect) { #if DEBUG_KP_TOOL_FLOW_COMMAND & 0 qCDebug(kpLogCommands) << "kpToolFlowCommand::updateBoundingRect() existing=" - << d->boundingRect - << " plus=" - << rect; + << d->boundingRect + << " plus=" + << rect; #endif - d->boundingRect = d->boundingRect.united (rect); + d->boundingRect = d->boundingRect.united(rect); #if DEBUG_KP_TOOL_FLOW_COMMAND & 0 qCDebug(kpLogCommands) << "\tresult=" << d->boundingRect; #endif } // public -void kpToolFlowCommand::finalize () +void kpToolFlowCommand::finalize() { - if (d->boundingRect.isValid ()) - { + if (d->boundingRect.isValid()) { // Store only the needed part of doc image. - d->image = kpTool::neededPixmap (d->image, d->boundingRect); - } - else - { - d->image = kpImage (); + d->image = kpTool::neededPixmap(d->image, d->boundingRect); + } else { + d->image = kpImage(); } } // public -void kpToolFlowCommand::cancel () +void kpToolFlowCommand::cancel() { - if (d->boundingRect.isValid ()) - { - viewManager ()->setFastUpdates (); - document ()->setImageAt (d->image, d->boundingRect.topLeft ()); - viewManager ()->restoreFastUpdates (); + if (d->boundingRect.isValid()) { + viewManager()->setFastUpdates(); + document()->setImageAt(d->image, d->boundingRect.topLeft()); + viewManager()->restoreFastUpdates(); } } diff --git a/commands/tools/kpToolColorPickerCommand.h b/commands/tools/kpToolColorPickerCommand.h --- a/commands/tools/kpToolColorPickerCommand.h +++ b/commands/tools/kpToolColorPickerCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,35 +24,30 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolColorPickerCommand_H #define kpToolColorPickerCommand_H - #include "imagelib/kpColor.h" #include "commands/kpCommand.h" - class kpToolColorPickerCommand : public kpCommand { public: - kpToolColorPickerCommand (int mouseButton, - const kpColor &newColor, const kpColor &oldColor, + kpToolColorPickerCommand (int mouseButton, const kpColor &newColor, const kpColor &oldColor, kpCommandEnvironment *environ); ~kpToolColorPickerCommand () override; - QString name () const override; + QString name() const override; - SizeType size () const override; + SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: int m_mouseButton; kpColor m_newColor; kpColor m_oldColor; }; - #endif // kpToolColorPickerCommand_H diff --git a/commands/tools/kpToolColorPickerCommand.cpp b/commands/tools/kpToolColorPickerCommand.cpp --- a/commands/tools/kpToolColorPickerCommand.cpp +++ b/commands/tools/kpToolColorPickerCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,57 +24,48 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_COLOR_PICKER 0 - #include "kpToolColorPickerCommand.h" #include "environments/commands/kpCommandEnvironment.h" #include "kpDefs.h" #include - kpToolColorPickerCommand::kpToolColorPickerCommand ( - int mouseButton, - const kpColor &newColor, - const kpColor &oldColor, - kpCommandEnvironment *environ) + int mouseButton, const kpColor &newColor, const kpColor &oldColor, + kpCommandEnvironment *environ) - : kpCommand (environ), - m_mouseButton (mouseButton), - m_newColor (newColor), - m_oldColor (oldColor) + : kpCommand(environ) + , m_mouseButton(mouseButton) + , m_newColor(newColor) + , m_oldColor(oldColor) { } kpToolColorPickerCommand::~kpToolColorPickerCommand () = default; - // public virtual [base kpCommand] -QString kpToolColorPickerCommand::name () const +QString kpToolColorPickerCommand::name() const { - return i18n ("Color Picker"); + return i18n("Color Picker"); } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolColorPickerCommand::size () const +kpCommandSize::SizeType kpToolColorPickerCommand::size() const { return 0; } - // public virtual [base kpCommand] -void kpToolColorPickerCommand::execute () +void kpToolColorPickerCommand::execute() { - environ ()->setColor (m_mouseButton, m_newColor); + environ()->setColor(m_mouseButton, m_newColor); } // public virtual [base kpCommand] -void kpToolColorPickerCommand::unexecute () +void kpToolColorPickerCommand::unexecute() { - environ ()->setColor (m_mouseButton, m_oldColor); + environ()->setColor(m_mouseButton, m_oldColor); } - diff --git a/commands/tools/kpToolFloodFillCommand.h b/commands/tools/kpToolFloodFillCommand.h --- a/commands/tools/kpToolFloodFillCommand.h +++ b/commands/tools/kpToolFloodFillCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,44 +24,38 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolFloodFillCommand_H #define kpToolFloodFillCommand_H - #include "commands/kpCommand.h" #include "imagelib/kpFloodFill.h" - class kpColor; class kpCommandEnvironment; - struct kpToolFloodFillCommandPrivate; class kpToolFloodFillCommand : public kpCommand, public kpFloodFill { public: - kpToolFloodFillCommand (int x, int y, - const kpColor &color, int processedColorSimilarity, + kpToolFloodFillCommand (int x, int y, const kpColor &color, int processedColorSimilarity, kpCommandEnvironment *environ); ~kpToolFloodFillCommand () override; - QString name () const override; + QString name() const override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; // Optimization hack: filling a fresh, unmodified document does not require // reading any pixels - just set the whole document to // . - void setFillEntireImage (bool yes = true); + void setFillEntireImage(bool yes = true); - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: - kpToolFloodFillCommandPrivate * const d; + kpToolFloodFillCommandPrivate *const d; }; - #endif // kpToolFloodFillCommand_H diff --git a/commands/tools/kpToolFloodFillCommand.cpp b/commands/tools/kpToolFloodFillCommand.cpp --- a/commands/tools/kpToolFloodFillCommand.cpp +++ b/commands/tools/kpToolFloodFillCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_FLOOD_FILL 0 - #include "kpToolFloodFillCommand.h" #include "imagelib/kpColor.h" @@ -51,13 +48,13 @@ //--------------------------------------------------------------------- -kpToolFloodFillCommand::kpToolFloodFillCommand (int x, int y, - const kpColor &color, int processedColorSimilarity, - kpCommandEnvironment *environ) +kpToolFloodFillCommand::kpToolFloodFillCommand (int x, int y, const kpColor &color, + int processedColorSimilarity, + kpCommandEnvironment *environ) - : kpCommand (environ), - kpFloodFill (document ()->imagePointer (), x, y, color, processedColorSimilarity), - d (new kpToolFloodFillCommandPrivate ()) + : kpCommand(environ) + , kpFloodFill(document()->imagePointer(), x, y, color, processedColorSimilarity) + , d(new kpToolFloodFillCommandPrivate()) { d->fillEntireImage = false; } @@ -72,61 +69,54 @@ //--------------------------------------------------------------------- // public virtual [base kpCommand] -QString kpToolFloodFillCommand::name () const +QString kpToolFloodFillCommand::name() const { - return i18n ("Flood Fill"); + return i18n("Flood Fill"); } //--------------------------------------------------------------------- // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolFloodFillCommand::size () const +kpCommandSize::SizeType kpToolFloodFillCommand::size() const { - return kpFloodFill::size () + ImageSize (d->oldImage); + return kpFloodFill::size() + ImageSize(d->oldImage); } //--------------------------------------------------------------------- // public -void kpToolFloodFillCommand::setFillEntireImage (bool yes) +void kpToolFloodFillCommand::setFillEntireImage(bool yes) { d->fillEntireImage = yes; } //--------------------------------------------------------------------- // protected virtual [base kpCommand] -void kpToolFloodFillCommand::execute () +void kpToolFloodFillCommand::execute() { #if DEBUG_KP_TOOL_FLOOD_FILL && 1 qCDebug(kpLogCommands) << "kpToolFloodFillCommand::execute() fillEntireImage=" - << d->fillEntireImage; + << d->fillEntireImage; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); - + kpDocument *doc = document(); + Q_ASSERT(doc); - if (d->fillEntireImage) - { - doc->fill (kpFloodFill::color ()); - } - else - { - QRect rect = kpFloodFill::boundingRect (); - if (rect.isValid ()) - { - QApplication::setOverrideCursor (Qt::WaitCursor); + if (d->fillEntireImage) { + doc->fill(kpFloodFill::color()); + } else { + QRect rect = kpFloodFill::boundingRect(); + if (rect.isValid()) { + QApplication::setOverrideCursor(Qt::WaitCursor); { - d->oldImage = doc->getImageAt (rect); + d->oldImage = doc->getImageAt(rect); - kpFloodFill::fill (); - doc->slotContentsChanged (rect); + kpFloodFill::fill(); + doc->slotContentsChanged(rect); } - QApplication::restoreOverrideCursor (); - } - else - { + QApplication::restoreOverrideCursor(); + } else { #if DEBUG_KP_TOOL_FLOOD_FILL && 1 qCDebug(kpLogCommands) << "\tinvalid boundingRect - must be NOP case"; #endif @@ -137,31 +127,26 @@ //--------------------------------------------------------------------- // protected virtual [base kpCommand] -void kpToolFloodFillCommand::unexecute () +void kpToolFloodFillCommand::unexecute() { #if DEBUG_KP_TOOL_FLOOD_FILL && 1 qCDebug(kpLogCommands) << "kpToolFloodFillCommand::unexecute() fillEntireImage=" - << d->fillEntireImage; + << d->fillEntireImage; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); + if (d->fillEntireImage) { + doc->fill(kpFloodFill::colorToChange()); + } else { + QRect rect = kpFloodFill::boundingRect(); + if (rect.isValid()) { + doc->setImageAt(d->oldImage, rect.topLeft()); - if (d->fillEntireImage) - { - doc->fill (kpFloodFill::colorToChange ()); - } - else - { - QRect rect = kpFloodFill::boundingRect (); - if (rect.isValid ()) - { - doc->setImageAt (d->oldImage, rect.topLeft ()); - - d->oldImage = kpImage (); + d->oldImage = kpImage(); - doc->slotContentsChanged (rect); + doc->slotContentsChanged(rect); } } } diff --git a/commands/tools/polygonal/kpToolPolygonalCommand.h b/commands/tools/polygonal/kpToolPolygonalCommand.h --- a/commands/tools/polygonal/kpToolPolygonalCommand.h +++ b/commands/tools/polygonal/kpToolPolygonalCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,44 +24,36 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolPolygonalCommand_H #define kpToolPolygonalCommand_H - #include "commands/kpNamedCommand.h" #include "tools/polygonal/kpToolPolygonalBase.h" - class QPolygon; class QRect; class kpColor; - // TODO: merge with kpToolRectangularCommand due to code duplication. class kpToolPolygonalCommand : public kpNamedCommand { public: // = the bounding rectangle for including . - kpToolPolygonalCommand (const QString &name, - kpToolPolygonalBase::DrawShapeFunc drawShapeFunc, - const QPolygon &points, - const QRect &boundingRect, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor, - kpCommandEnvironment *environ); + kpToolPolygonalCommand (const QString &name, kpToolPolygonalBase::DrawShapeFunc drawShapeFunc, + const QPolygon &points, const QRect &boundingRect, + const kpColor &fcolor, int penWidth, const kpColor &bcolor, + kpCommandEnvironment *environ); ~kpToolPolygonalCommand () override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: - struct kpToolPolygonalCommandPrivate * const d; - kpToolPolygonalCommand &operator= (const kpToolPolygonalCommand &) const; + struct kpToolPolygonalCommandPrivate *const d; + kpToolPolygonalCommand &operator=(const kpToolPolygonalCommand &) const; }; - #endif // kpToolPolygonalCommand_H diff --git a/commands/tools/polygonal/kpToolPolygonalCommand.cpp b/commands/tools/polygonal/kpToolPolygonalCommand.cpp --- a/commands/tools/polygonal/kpToolPolygonalCommand.cpp +++ b/commands/tools/polygonal/kpToolPolygonalCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,18 +24,15 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_POLYGON 0 - #include "kpToolPolygonalCommand.h" #include "document/kpDocument.h" #include "kpDefs.h" #include "imagelib/kpImage.h" #include "tools/polygonal/kpToolPolygonalBase.h" - struct kpToolPolygonalCommandPrivate { kpToolPolygonalBase::DrawShapeFunc drawShapeFunc{}; @@ -52,15 +48,14 @@ }; kpToolPolygonalCommand::kpToolPolygonalCommand (const QString &name, - kpToolPolygonalBase::DrawShapeFunc drawShapeFunc, - const QPolygon &points, - const QRect &boundingRect, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor, - kpCommandEnvironment *environ) - - : kpNamedCommand (name, environ), - d (new kpToolPolygonalCommandPrivate ()) + kpToolPolygonalBase::DrawShapeFunc drawShapeFunc, + const QPolygon &points, const QRect &boundingRect, + const kpColor &fcolor, int penWidth, + const kpColor &bcolor, + kpCommandEnvironment *environ) + + : kpNamedCommand(name, environ) + , d(new kpToolPolygonalCommandPrivate()) { d->drawShapeFunc = drawShapeFunc; @@ -77,48 +72,46 @@ delete d; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolPolygonalCommand::size () const +kpCommandSize::SizeType kpToolPolygonalCommand::size() const { - return PolygonSize (d->points) + - ImageSize (d->oldImage); + return PolygonSize(d->points) + +ImageSize(d->oldImage); } // public virtual [base kpCommand] -void kpToolPolygonalCommand::execute () +void kpToolPolygonalCommand::execute() { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); // Store Undo info. - Q_ASSERT (d->oldImage.isNull ()); - d->oldImage = doc->getImageAt (d->boundingRect); + Q_ASSERT(d->oldImage.isNull()); + d->oldImage = doc->getImageAt(d->boundingRect); // Invoke shape drawing function passed in ctor. kpImage image = d->oldImage; QPolygon pointsTranslated = d->points; - pointsTranslated.translate (-d->boundingRect.x (), -d->boundingRect.y ()); + pointsTranslated.translate(-d->boundingRect.x(), -d->boundingRect.y()); - (*d->drawShapeFunc) (&image, - pointsTranslated, - d->fcolor, d->penWidth, - d->bcolor, - true/*final shape*/); + (*d->drawShapeFunc)(&image, + pointsTranslated, + d->fcolor, d->penWidth, + d->bcolor, + true /*final shape*/); - doc->setImageAt (image, d->boundingRect.topLeft ()); + doc->setImageAt(image, d->boundingRect.topLeft()); } // public virtual [base kpCommand] -void kpToolPolygonalCommand::unexecute () +void kpToolPolygonalCommand::unexecute() { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - Q_ASSERT (!d->oldImage.isNull ()); - doc->setImageAt (d->oldImage, d->boundingRect.topLeft ()); + Q_ASSERT(!d->oldImage.isNull()); + doc->setImageAt(d->oldImage, d->boundingRect.topLeft()); - d->oldImage = kpImage (); + d->oldImage = kpImage(); } - diff --git a/commands/tools/rectangular/kpToolRectangularCommand.h b/commands/tools/rectangular/kpToolRectangularCommand.h --- a/commands/tools/rectangular/kpToolRectangularCommand.h +++ b/commands/tools/rectangular/kpToolRectangularCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,38 +24,31 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_RECTANGULAR_COMMAND_H #define KP_TOOL_RECTANGULAR_COMMAND_H - #include "commands/kpNamedCommand.h" #include "tools/rectangular/kpToolRectangularBase.h" - class kpColor; - class kpToolRectangularCommand : public kpNamedCommand { public: kpToolRectangularCommand (const QString &name, - kpToolRectangularBase::DrawShapeFunc drawShapeFunc, - const QRect &rect, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor, - kpCommandEnvironment *environ); + kpToolRectangularBase::DrawShapeFunc drawShapeFunc, const QRect &rect, + const kpColor &fcolor, int penWidth, const kpColor &bcolor, + kpCommandEnvironment *environ); ~kpToolRectangularCommand () override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: - struct kpToolRectangularCommandPrivate * const d; - kpToolRectangularCommand &operator= (const kpToolRectangularCommand &) const; + struct kpToolRectangularCommandPrivate *const d; + kpToolRectangularCommand &operator=(const kpToolRectangularCommand &) const; }; - #endif // KP_TOOL_RECTANGULAR_COMMAND_H diff --git a/commands/tools/rectangular/kpToolRectangularCommand.cpp b/commands/tools/rectangular/kpToolRectangularCommand.cpp --- a/commands/tools/rectangular/kpToolRectangularCommand.cpp +++ b/commands/tools/rectangular/kpToolRectangularCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_RECTANGULAR_COMMAND 0 - #include "kpToolRectangularCommand.h" #include "imagelib/kpColor.h" @@ -44,7 +41,6 @@ #include "views/manager/kpViewManager.h" #include "kpLogCategories.h" - struct kpToolRectangularCommandPrivate { kpToolRectangularBase::DrawShapeFunc drawShapeFunc{}; @@ -59,14 +55,11 @@ }; kpToolRectangularCommand::kpToolRectangularCommand (const QString &name, - kpToolRectangularBase::DrawShapeFunc drawShapeFunc, - const QRect &rect, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor, - kpCommandEnvironment *environ) - - : kpNamedCommand (name, environ), - d (new kpToolRectangularCommandPrivate ()) + kpToolRectangularBase::DrawShapeFunc drawShapeFunc, const QRect &rect, const kpColor &fcolor, int penWidth, const kpColor &bcolor, + kpCommandEnvironment *environ) + + : kpNamedCommand(name, environ) + , d(new kpToolRectangularCommandPrivate()) { d->drawShapeFunc = drawShapeFunc; @@ -82,45 +75,42 @@ delete d; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolRectangularCommand::size () const +kpCommandSize::SizeType kpToolRectangularCommand::size() const { - return ImageSize (d->oldImage); + return ImageSize(d->oldImage); } - // public virtual [base kpCommand] -void kpToolRectangularCommand::execute () +void kpToolRectangularCommand::execute() { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); // Store Undo info. // OPT: For a pure rectangle, can do better if there is no bcolor, by only // saving 4 pixmaps corresponding to the pixels dirtied by the 4 edges. - Q_ASSERT (d->oldImage.isNull ()); - d->oldImage = doc->getImageAt (d->rect); + Q_ASSERT(d->oldImage.isNull()); + d->oldImage = doc->getImageAt(d->rect); // Invoke shape drawing function passed in ctor. kpImage image = d->oldImage; - (*d->drawShapeFunc) (&image, - 0, 0, d->rect.width (), d->rect.height (), - d->fcolor, d->penWidth, - d->bcolor); + (*d->drawShapeFunc)(&image, + 0, 0, d->rect.width(), d->rect.height(), + d->fcolor, d->penWidth, + d->bcolor); - doc->setImageAt (image, d->rect.topLeft ()); + doc->setImageAt(image, d->rect.topLeft()); } // public virtual [base kpCommand] -void kpToolRectangularCommand::unexecute () +void kpToolRectangularCommand::unexecute() { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - Q_ASSERT (!d->oldImage.isNull ()); - doc->setImageAt (d->oldImage, d->rect.topLeft ()); + Q_ASSERT(!d->oldImage.isNull()); + doc->setImageAt(d->oldImage, d->rect.topLeft()); - d->oldImage = kpImage (); + d->oldImage = kpImage(); } - diff --git a/commands/tools/selection/kpAbstractSelectionContentCommand.h b/commands/tools/selection/kpAbstractSelectionContentCommand.h --- a/commands/tools/selection/kpAbstractSelectionContentCommand.h +++ b/commands/tools/selection/kpAbstractSelectionContentCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpAbstractSelectionContentCommand_H #define kpAbstractSelectionContentCommand_H - #include "commands/kpNamedCommand.h" - // Converts a selection border to a selection with content. // This must be executed before any manipulations can be made // to a selection. @@ -52,20 +48,18 @@ public: // must be a border i.e. have no content. kpAbstractSelectionContentCommand ( - const kpAbstractSelection &originalSelBorder, - const QString &name, + const kpAbstractSelection &originalSelBorder, const QString &name, kpCommandEnvironment *environ); ~kpAbstractSelectionContentCommand () override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; // Note: Returned pointer is only valid for as long as this command is // alive. - const kpAbstractSelection *originalSelection () const; + const kpAbstractSelection *originalSelection() const; private: - struct kpAbstractSelectionContentCommandPrivate * const d; + struct kpAbstractSelectionContentCommandPrivate *const d; }; - #endif // kpAbstractSelectionContentCommand_H diff --git a/commands/tools/selection/kpAbstractSelectionContentCommand.cpp b/commands/tools/selection/kpAbstractSelectionContentCommand.cpp --- a/commands/tools/selection/kpAbstractSelectionContentCommand.cpp +++ b/commands/tools/selection/kpAbstractSelectionContentCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,45 +24,40 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpAbstractSelectionContentCommand.h" #include "layers/selections/kpAbstractSelection.h" - struct kpAbstractSelectionContentCommandPrivate { const kpAbstractSelection *orgSelBorder; }; kpAbstractSelectionContentCommand::kpAbstractSelectionContentCommand ( - const kpAbstractSelection &originalSelBorder, - const QString &name, - kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - d (new kpAbstractSelectionContentCommandPrivate ()) + const kpAbstractSelection &originalSelBorder, const QString &name, + kpCommandEnvironment *environ) + : kpNamedCommand(name, environ) + , d(new kpAbstractSelectionContentCommandPrivate()) { - Q_ASSERT (!originalSelBorder.hasContent ()); + Q_ASSERT(!originalSelBorder.hasContent()); - d->orgSelBorder = originalSelBorder.clone (); + d->orgSelBorder = originalSelBorder.clone(); } kpAbstractSelectionContentCommand::~kpAbstractSelectionContentCommand () { delete d->orgSelBorder; delete d; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpAbstractSelectionContentCommand::size () const +kpCommandSize::SizeType kpAbstractSelectionContentCommand::size() const { - return d->orgSelBorder->size (); + return d->orgSelBorder->size(); } - // public -const kpAbstractSelection *kpAbstractSelectionContentCommand::originalSelection () const +const kpAbstractSelection *kpAbstractSelectionContentCommand::originalSelection() const { return d->orgSelBorder; } diff --git a/commands/tools/selection/kpToolImageSelectionTransparencyCommand.h b/commands/tools/selection/kpToolImageSelectionTransparencyCommand.h --- a/commands/tools/selection/kpToolImageSelectionTransparencyCommand.h +++ b/commands/tools/selection/kpToolImageSelectionTransparencyCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,32 +24,28 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolImageSelectionTransparencyCommand_H #define kpToolImageSelectionTransparencyCommand_H - #include "commands/kpNamedCommand.h" #include "layers/selections/image/kpImageSelectionTransparency.h" - class kpToolImageSelectionTransparencyCommand : public kpNamedCommand { public: kpToolImageSelectionTransparencyCommand (const QString &name, - const kpImageSelectionTransparency &st, - const kpImageSelectionTransparency &oldST, - kpCommandEnvironment *environ); + const kpImageSelectionTransparency &st, + const kpImageSelectionTransparency &oldST, + kpCommandEnvironment *environ); ~kpToolImageSelectionTransparencyCommand () override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: kpImageSelectionTransparency m_st, m_oldST; }; - #endif // kpToolImageSelectionTransparencyCommand_H diff --git a/commands/tools/selection/kpToolImageSelectionTransparencyCommand.cpp b/commands/tools/selection/kpToolImageSelectionTransparencyCommand.cpp --- a/commands/tools/selection/kpToolImageSelectionTransparencyCommand.cpp +++ b/commands/tools/selection/kpToolImageSelectionTransparencyCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpToolImageSelectionTransparencyCommand.h" #include "environments/commands/kpCommandEnvironment.h" @@ -42,55 +39,50 @@ //-------------------------------------------------------------------------------- kpToolImageSelectionTransparencyCommand::kpToolImageSelectionTransparencyCommand ( - const QString &name, - const kpImageSelectionTransparency &st, - const kpImageSelectionTransparency &oldST, - kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - m_st (st), - m_oldST (oldST) + const QString &name, const kpImageSelectionTransparency &st, + const kpImageSelectionTransparency &oldST, kpCommandEnvironment *environ) + : kpNamedCommand(name, environ) + , m_st(st) + , m_oldST(oldST) { } kpToolImageSelectionTransparencyCommand::~kpToolImageSelectionTransparencyCommand () = default; - // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolImageSelectionTransparencyCommand::size () const +kpCommandSize::SizeType kpToolImageSelectionTransparencyCommand::size() const { return 0; } - // public virtual [base kpCommand] -void kpToolImageSelectionTransparencyCommand::execute () +void kpToolImageSelectionTransparencyCommand::execute() { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "kpToolImageSelectionTransparencyCommand::execute()"; #endif - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); - - environ ()->setImageSelectionTransparency (m_st, true/*force colour change*/); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); + + environ()->setImageSelectionTransparency(m_st, true /*force colour change*/); - if (imageSelection ()) { - imageSelection ()->setTransparency (m_st); + if (imageSelection()) { + imageSelection()->setTransparency(m_st); } } // public virtual [base kpCommand] -void kpToolImageSelectionTransparencyCommand::unexecute () +void kpToolImageSelectionTransparencyCommand::unexecute() { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "kpToolImageSelectionTransparencyCommand::unexecute()"; #endif - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); - - environ ()->setImageSelectionTransparency (m_oldST, true/*force colour change*/); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); - if (imageSelection ()) { - imageSelection ()->setTransparency (m_oldST); + environ()->setImageSelectionTransparency(m_oldST, true /*force colour change*/); + + if (imageSelection()) { + imageSelection()->setTransparency(m_oldST); } } - diff --git a/commands/tools/selection/kpToolSelectionCreateCommand.h b/commands/tools/selection/kpToolSelectionCreateCommand.h --- a/commands/tools/selection/kpToolSelectionCreateCommand.h +++ b/commands/tools/selection/kpToolSelectionCreateCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,38 +24,33 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolSelectionCreateCommand_H #define kpToolSelectionCreateCommand_H - #include "commands/kpNamedCommand.h" - class kpAbstractSelection; - class kpToolSelectionCreateCommand : public kpNamedCommand { public: // (if fromSelection doesn't have a pixmap, it will only recreate the region) kpToolSelectionCreateCommand (const QString &name, const kpAbstractSelection &fromSelection, kpCommandEnvironment *environ); ~kpToolSelectionCreateCommand () override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - const kpAbstractSelection *fromSelection () const; - void setFromSelection (const kpAbstractSelection &fromSelection); + const kpAbstractSelection *fromSelection() const; + void setFromSelection(const kpAbstractSelection &fromSelection); - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: kpAbstractSelection *m_fromSelection; int m_textRow, m_textCol; }; - #endif // kpToolSelectionCreateCommand_H diff --git a/commands/tools/selection/kpToolSelectionCreateCommand.cpp b/commands/tools/selection/kpToolSelectionCreateCommand.cpp --- a/commands/tools/selection/kpToolSelectionCreateCommand.cpp +++ b/commands/tools/selection/kpToolSelectionCreateCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "commands/tools/selection/kpToolSelectionCreateCommand.h" #include "layers/selections/kpAbstractSelection.h" @@ -54,108 +51,99 @@ #include #include - kpToolSelectionCreateCommand::kpToolSelectionCreateCommand (const QString &name, - const kpAbstractSelection &fromSelection, - kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - m_fromSelection (nullptr), - m_textRow (0), m_textCol (0) + const kpAbstractSelection &fromSelection, + kpCommandEnvironment *environ) + : kpNamedCommand(name, environ) + , m_fromSelection(nullptr) + , m_textRow(0) + , m_textCol(0) { - setFromSelection (fromSelection); + setFromSelection(fromSelection); } kpToolSelectionCreateCommand::~kpToolSelectionCreateCommand () { delete m_fromSelection; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolSelectionCreateCommand::size () const +kpCommandSize::SizeType kpToolSelectionCreateCommand::size() const { - return SelectionSize (m_fromSelection); + return SelectionSize(m_fromSelection); } - // public -const kpAbstractSelection *kpToolSelectionCreateCommand::fromSelection () const +const kpAbstractSelection *kpToolSelectionCreateCommand::fromSelection() const { return m_fromSelection; } // public -void kpToolSelectionCreateCommand::setFromSelection (const kpAbstractSelection &fromSelection) +void kpToolSelectionCreateCommand::setFromSelection(const kpAbstractSelection &fromSelection) { delete m_fromSelection; - m_fromSelection = fromSelection.clone (); + m_fromSelection = fromSelection.clone(); } // public virtual [base kpCommand] -void kpToolSelectionCreateCommand::execute () +void kpToolSelectionCreateCommand::execute() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogCommands) << "kpToolSelectionCreateCommand::execute()"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - if (m_fromSelection) - { + if (m_fromSelection) { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogCommands) << "\tusing fromSelection"; - qCDebug(kpLogCommands) << "\t\thave sel=" << doc->selection () << endl; + qCDebug(kpLogCommands) << "\t\thave sel=" << doc->selection() << endl; #endif - kpAbstractImageSelection *imageSel = - dynamic_cast (m_fromSelection); - kpTextSelection *textSel = - dynamic_cast (m_fromSelection); - if (imageSel) - { - if (imageSel->transparency () != environ ()->imageSelectionTransparency ()) { - environ ()->setImageSelectionTransparency (imageSel->transparency ()); + kpAbstractImageSelection *imageSel + = dynamic_cast (m_fromSelection); + kpTextSelection *textSel + = dynamic_cast (m_fromSelection); + if (imageSel) { + if (imageSel->transparency() != environ()->imageSelectionTransparency()) { + environ()->setImageSelectionTransparency(imageSel->transparency()); } - } - else if (textSel) - { - if (textSel->textStyle () != environ ()->textStyle ()) { - environ ()->setTextStyle (textSel->textStyle ()); + } else if (textSel) { + if (textSel->textStyle() != environ()->textStyle()) { + environ()->setTextStyle(textSel->textStyle()); } - } - else { - Q_ASSERT (!"Unknown selection type"); + } else { + Q_ASSERT(!"Unknown selection type"); } - viewManager ()->setTextCursorPosition (m_textRow, m_textCol); - doc->setSelection (*m_fromSelection); + viewManager()->setTextCursorPosition(m_textRow, m_textCol); + doc->setSelection(*m_fromSelection); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } } // public virtual [base kpCommand] -void kpToolSelectionCreateCommand::unexecute () +void kpToolSelectionCreateCommand::unexecute() { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - if (!doc->selection ()) - { + if (!doc->selection()) { // Was just a border that got deselected? - if (m_fromSelection && !m_fromSelection->hasContent ()) { + if (m_fromSelection && !m_fromSelection->hasContent()) { return; } - Q_ASSERT (!"kpToolSelectionCreateCommand::unexecute() without sel region"); + Q_ASSERT(!"kpToolSelectionCreateCommand::unexecute() without sel region"); return; } - m_textRow = viewManager ()->textCursorRow (); - m_textCol = viewManager ()->textCursorCol (); + m_textRow = viewManager()->textCursorRow(); + m_textCol = viewManager()->textCursorCol(); - doc->selectionDelete (); + doc->selectionDelete(); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } - diff --git a/commands/tools/selection/kpToolSelectionDestroyCommand.h b/commands/tools/selection/kpToolSelectionDestroyCommand.h --- a/commands/tools/selection/kpToolSelectionDestroyCommand.h +++ b/commands/tools/selection/kpToolSelectionDestroyCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,29 +24,25 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolSelectionDestroyCommand_H #define kpToolSelectionDestroyCommand_H - #include "imagelib/kpImage.h" #include "commands/kpNamedCommand.h" - class kpAbstractSelection; - class kpToolSelectionDestroyCommand : public kpNamedCommand { public: kpToolSelectionDestroyCommand (const QString &name, bool pushOntoDocument, kpCommandEnvironment *environ); ~kpToolSelectionDestroyCommand () override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: bool m_pushOntoDocument; @@ -57,5 +52,4 @@ int m_textRow, m_textCol; }; - #endif // kpToolSelectionDestroyCommand_H diff --git a/commands/tools/selection/kpToolSelectionDestroyCommand.cpp b/commands/tools/selection/kpToolSelectionDestroyCommand.cpp --- a/commands/tools/selection/kpToolSelectionDestroyCommand.cpp +++ b/commands/tools/selection/kpToolSelectionDestroyCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpToolSelectionDestroyCommand.h" #include "kpLogCategories.h" #include "layers/selections/kpAbstractSelection.h" @@ -42,12 +39,13 @@ //--------------------------------------------------------------------- kpToolSelectionDestroyCommand::kpToolSelectionDestroyCommand (const QString &name, - bool pushOntoDocument, - kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - m_pushOntoDocument (pushOntoDocument), - m_oldSelectionPtr (nullptr), - m_textRow(0), m_textCol(0) + bool pushOntoDocument, + kpCommandEnvironment *environ) + : kpNamedCommand(name, environ) + , m_pushOntoDocument(pushOntoDocument) + , m_oldSelectionPtr(nullptr) + , m_textRow(0) + , m_textCol(0) { } @@ -61,116 +59,107 @@ //--------------------------------------------------------------------- // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolSelectionDestroyCommand::size () const +kpCommandSize::SizeType kpToolSelectionDestroyCommand::size() const { - return ImageSize (m_oldDocImage) + - SelectionSize (m_oldSelectionPtr); + return ImageSize(m_oldDocImage) + +SelectionSize(m_oldSelectionPtr); } //--------------------------------------------------------------------- // public virtual [base kpCommand] -void kpToolSelectionDestroyCommand::execute () +void kpToolSelectionDestroyCommand::execute() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogCommands) << "kpToolSelectionDestroyCommand::execute () CALLED"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); - Q_ASSERT (doc->selection ()); + kpDocument *doc = document(); + Q_ASSERT(doc); + Q_ASSERT(doc->selection()); - m_textRow = viewManager ()->textCursorRow (); - m_textCol = viewManager ()->textCursorCol (); + m_textRow = viewManager()->textCursorRow(); + m_textCol = viewManager()->textCursorCol(); - Q_ASSERT (!m_oldSelectionPtr); - m_oldSelectionPtr = doc->selection ()->clone (); + Q_ASSERT(!m_oldSelectionPtr); + m_oldSelectionPtr = doc->selection()->clone(); - if (m_pushOntoDocument) - { - m_oldDocImage = doc->getImageAt (doc->selection ()->boundingRect ()); - doc->selectionPushOntoDocument (); - } - else { - doc->selectionDelete (); + if (m_pushOntoDocument) { + m_oldDocImage = doc->getImageAt(doc->selection()->boundingRect()); + doc->selectionPushOntoDocument(); + } else { + doc->selectionDelete(); } - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } //--------------------------------------------------------------------- // public virtual [base kpCommand] -void kpToolSelectionDestroyCommand::unexecute () +void kpToolSelectionDestroyCommand::unexecute() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogCommands) << "kpToolSelectionDestroyCommand::unexecute () CALLED"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - if (doc->selection ()) - { + if (doc->selection()) { // not error because it's possible that the user dragged out a new // region (without pulling image), and then CTRL+Z #if DEBUG_KP_TOOL_SELECTION - qCDebug(kpLogCommands) << "kpToolSelectionDestroyCommand::unexecute() already has sel region"; + qCDebug(kpLogCommands) + << "kpToolSelectionDestroyCommand::unexecute() already has sel region"; #endif - if (doc->selection ()->hasContent ()) - { - Q_ASSERT (!"kpToolSelectionDestroyCommand::unexecute() already has sel content"); + if (doc->selection()->hasContent()) { + Q_ASSERT(!"kpToolSelectionDestroyCommand::unexecute() already has sel content"); return; } } - Q_ASSERT (m_oldSelectionPtr); + Q_ASSERT(m_oldSelectionPtr); - if (m_pushOntoDocument) - { + if (m_pushOntoDocument) { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogCommands) << "\tunpush oldDocImage onto doc first"; #endif - doc->setImageAt (m_oldDocImage, m_oldSelectionPtr->topLeft ()); + doc->setImageAt(m_oldDocImage, m_oldSelectionPtr->topLeft()); } #if DEBUG_KP_TOOL_SELECTION - qCDebug(kpLogCommands) << "\tsetting selection to: rect=" << m_oldSelectionPtr->boundingRect () - << " hasContent=" << m_oldSelectionPtr->hasContent (); + qCDebug(kpLogCommands) << "\tsetting selection to: rect=" << m_oldSelectionPtr->boundingRect() + << " hasContent=" << m_oldSelectionPtr->hasContent(); #endif - kpAbstractImageSelection *imageSel = - dynamic_cast (m_oldSelectionPtr); - kpTextSelection *textSel = - dynamic_cast (m_oldSelectionPtr); - if (imageSel) - { - if (imageSel->transparency () != environ ()->imageSelectionTransparency ()) { - environ ()->setImageSelectionTransparency (imageSel->transparency ()); + kpAbstractImageSelection *imageSel + = dynamic_cast (m_oldSelectionPtr); + kpTextSelection *textSel + = dynamic_cast (m_oldSelectionPtr); + if (imageSel) { + if (imageSel->transparency() != environ()->imageSelectionTransparency()) { + environ()->setImageSelectionTransparency(imageSel->transparency()); } - if (dynamic_cast (doc->selection())) { + if (dynamic_cast (doc->selection())) { doc->selectionPushOntoDocument(); } - } - else if (textSel) - { - if (textSel->textStyle () != environ ()->textStyle ()) { - environ ()->setTextStyle (textSel->textStyle ()); + } else if (textSel) { + if (textSel->textStyle() != environ()->textStyle()) { + environ()->setTextStyle(textSel->textStyle()); } - if (dynamic_cast (doc->selection())) { + if (dynamic_cast (doc->selection())) { doc->selectionPushOntoDocument(); } - } - else { - Q_ASSERT (!"Unknown selection type"); + } else { + Q_ASSERT(!"Unknown selection type"); } - viewManager ()->setTextCursorPosition (m_textRow, m_textCol); - doc->setSelection (*m_oldSelectionPtr); + viewManager()->setTextCursorPosition(m_textRow, m_textCol); + doc->setSelection(*m_oldSelectionPtr); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); delete m_oldSelectionPtr; m_oldSelectionPtr = nullptr; } - diff --git a/commands/tools/selection/kpToolSelectionMoveCommand.h b/commands/tools/selection/kpToolSelectionMoveCommand.h --- a/commands/tools/selection/kpToolSelectionMoveCommand.h +++ b/commands/tools/selection/kpToolSelectionMoveCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,39 +24,35 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolSelectionMoveCommand_H #define kpToolSelectionMoveCommand_H - #include #include #include #include "imagelib/kpImage.h" #include "commands/kpNamedCommand.h" - class kpAbstractSelection; - class kpToolSelectionMoveCommand : public kpNamedCommand { public: kpToolSelectionMoveCommand (const QString &name, kpCommandEnvironment *environ); ~kpToolSelectionMoveCommand () override; - kpAbstractSelection *originalSelectionClone () const; + kpAbstractSelection *originalSelectionClone() const; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; - void moveTo (const QPoint &point, bool moveLater = false); - void moveTo (int x, int y, bool moveLater = false); - void copyOntoDocument (); - void finalize (); + void moveTo(const QPoint &point, bool moveLater = false); + void moveTo(int x, int y, bool moveLater = false); + void copyOntoDocument(); + void finalize(); private: QPoint m_startPoint, m_endPoint; @@ -70,5 +65,4 @@ QPolygon m_copyOntoDocumentPoints; }; - #endif // kpToolSelectionMoveCommand_H diff --git a/commands/tools/selection/kpToolSelectionMoveCommand.cpp b/commands/tools/selection/kpToolSelectionMoveCommand.cpp --- a/commands/tools/selection/kpToolSelectionMoveCommand.cpp +++ b/commands/tools/selection/kpToolSelectionMoveCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpToolSelectionMoveCommand.h" #include "layers/selections/kpAbstractSelection.h" @@ -44,176 +41,169 @@ //-------------------------------------------------------------------------------- kpToolSelectionMoveCommand::kpToolSelectionMoveCommand (const QString &name, - kpCommandEnvironment *environ) - : kpNamedCommand (name, environ) + kpCommandEnvironment *environ) + : kpNamedCommand(name, environ) { - kpDocument *doc = document (); - Q_ASSERT (doc); - Q_ASSERT (doc->selection ()); + kpDocument *doc = document(); + Q_ASSERT(doc); + Q_ASSERT(doc->selection()); - m_startPoint = m_endPoint = doc->selection ()->topLeft (); + m_startPoint = m_endPoint = doc->selection()->topLeft(); } kpToolSelectionMoveCommand::~kpToolSelectionMoveCommand () = default; - // public -kpAbstractSelection *kpToolSelectionMoveCommand::originalSelectionClone () const +kpAbstractSelection *kpToolSelectionMoveCommand::originalSelectionClone() const { - kpDocument *doc = document (); - Q_ASSERT (doc); - Q_ASSERT (doc->selection ()); + kpDocument *doc = document(); + Q_ASSERT(doc); + Q_ASSERT(doc->selection()); - kpAbstractSelection *selection = doc->selection ()->clone (); - selection->moveTo (m_startPoint); + kpAbstractSelection *selection = doc->selection()->clone(); + selection->moveTo(m_startPoint); return selection; } - // public virtual [base kpComand] -kpCommandSize::SizeType kpToolSelectionMoveCommand::size () const +kpCommandSize::SizeType kpToolSelectionMoveCommand::size() const { - return ImageSize (m_oldDocumentImage) + - PolygonSize (m_copyOntoDocumentPoints); + return ImageSize(m_oldDocumentImage) + +PolygonSize(m_copyOntoDocumentPoints); } - // public virtual [base kpCommand] -void kpToolSelectionMoveCommand::execute () +void kpToolSelectionMoveCommand::execute() { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "kpToolSelectionMoveCommand::execute()"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - kpAbstractSelection *sel = doc->selection (); + kpAbstractSelection *sel = doc->selection(); // Must have content before it can be moved. - Q_ASSERT (sel && sel->hasContent ()); + Q_ASSERT(sel && sel->hasContent()); - kpViewManager *vm = viewManager (); - Q_ASSERT (vm); + kpViewManager *vm = viewManager(); + Q_ASSERT(vm); - vm->setQueueUpdates (); + vm->setQueueUpdates(); { - for (const auto &p : m_copyOntoDocumentPoints) - { - sel->moveTo (p); - doc->selectionCopyOntoDocument (); + for (const auto &p : m_copyOntoDocumentPoints) { + sel->moveTo(p); + doc->selectionCopyOntoDocument(); } - sel->moveTo (m_endPoint); + sel->moveTo(m_endPoint); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } - vm->restoreQueueUpdates (); + vm->restoreQueueUpdates(); } // public virtual [base kpCommand] -void kpToolSelectionMoveCommand::unexecute () +void kpToolSelectionMoveCommand::unexecute() { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "kpToolSelectionMoveCommand::unexecute()"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - kpAbstractSelection *sel = doc->selection (); + kpAbstractSelection *sel = doc->selection(); // Must have content before it can be un-moved. - Q_ASSERT (sel && sel->hasContent ()); + Q_ASSERT(sel && sel->hasContent()); - kpViewManager *vm = viewManager (); - Q_ASSERT (vm); + kpViewManager *vm = viewManager(); + Q_ASSERT(vm); - vm->setQueueUpdates (); + vm->setQueueUpdates(); - if (!m_oldDocumentImage.isNull ()) { - doc->setImageAt (m_oldDocumentImage, m_documentBoundingRect.topLeft ()); + if (!m_oldDocumentImage.isNull()) { + doc->setImageAt(m_oldDocumentImage, m_documentBoundingRect.topLeft()); } #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "\tmove to startPoint=" << m_startPoint; #endif - sel->moveTo (m_startPoint); + sel->moveTo(m_startPoint); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); - vm->restoreQueueUpdates (); + vm->restoreQueueUpdates(); } // public -void kpToolSelectionMoveCommand::moveTo (const QPoint &point, bool moveLater) +void kpToolSelectionMoveCommand::moveTo(const QPoint &point, bool moveLater) { #if DEBUG_KP_TOOL_SELECTION && 0 qCDebug(kpLogCommands) << "kpToolSelectionMoveCommand::moveTo" << point - << " moveLater=" << moveLater; + << " moveLater=" << moveLater; #endif - if (!moveLater) - { - kpDocument *doc = document (); - Q_ASSERT (doc); + if (!moveLater) { + kpDocument *doc = document(); + Q_ASSERT(doc); - kpAbstractSelection *sel = doc->selection (); + kpAbstractSelection *sel = doc->selection(); // Must have content before it can be moved. - Q_ASSERT (sel && sel->hasContent ()); + Q_ASSERT(sel && sel->hasContent()); - if (point == sel->topLeft ()) { + if (point == sel->topLeft()) { return; } - sel->moveTo (point); + sel->moveTo(point); } m_endPoint = point; } // public -void kpToolSelectionMoveCommand::moveTo (int x, int y, bool moveLater) +void kpToolSelectionMoveCommand::moveTo(int x, int y, bool moveLater) { - moveTo (QPoint (x, y), moveLater); + moveTo(QPoint(x, y), moveLater); } // public -void kpToolSelectionMoveCommand::copyOntoDocument () +void kpToolSelectionMoveCommand::copyOntoDocument() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogCommands) << "kpToolSelectionMoveCommand::copyOntoDocument()"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - kpAbstractSelection *sel = doc->selection (); + kpAbstractSelection *sel = doc->selection(); // Must have content before we allow it be stamped onto the document, // to be consistent with the requirement on other selection operations. - Q_ASSERT (sel && sel->hasContent ()); + Q_ASSERT(sel && sel->hasContent()); - if (m_oldDocumentImage.isNull ()) { - m_oldDocumentImage = doc->image (); + if (m_oldDocumentImage.isNull()) { + m_oldDocumentImage = doc->image(); } - QRect selBoundingRect = sel->boundingRect (); - m_documentBoundingRect = m_documentBoundingRect.united (selBoundingRect); + QRect selBoundingRect = sel->boundingRect(); + m_documentBoundingRect = m_documentBoundingRect.united(selBoundingRect); - doc->selectionCopyOntoDocument (); + doc->selectionCopyOntoDocument(); - m_copyOntoDocumentPoints.putPoints (m_copyOntoDocumentPoints.count (), - 1, - selBoundingRect.x (), - selBoundingRect.y ()); + m_copyOntoDocumentPoints.putPoints(m_copyOntoDocumentPoints.count(), + 1, + selBoundingRect.x(), + selBoundingRect.y()); } // public -void kpToolSelectionMoveCommand::finalize () +void kpToolSelectionMoveCommand::finalize() { - if (!m_oldDocumentImage.isNull () && !m_documentBoundingRect.isNull ()) - { - m_oldDocumentImage = kpTool::neededPixmap (m_oldDocumentImage, - m_documentBoundingRect); + if (!m_oldDocumentImage.isNull() && !m_documentBoundingRect.isNull()) { + m_oldDocumentImage = kpTool::neededPixmap(m_oldDocumentImage, + m_documentBoundingRect); } } - diff --git a/commands/tools/selection/kpToolSelectionPullFromDocumentCommand.h b/commands/tools/selection/kpToolSelectionPullFromDocumentCommand.h --- a/commands/tools/selection/kpToolSelectionPullFromDocumentCommand.h +++ b/commands/tools/selection/kpToolSelectionPullFromDocumentCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,35 +24,27 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolSelectionPullFromDocumentCommand_H #define kpToolSelectionPullFromDocumentCommand_H - #include "kpAbstractSelectionContentCommand.h" #include "imagelib/kpColor.h" - class kpAbstractImageSelection; - -class kpToolSelectionPullFromDocumentCommand : - public kpAbstractSelectionContentCommand +class kpToolSelectionPullFromDocumentCommand : public kpAbstractSelectionContentCommand { public: kpToolSelectionPullFromDocumentCommand ( - const kpAbstractImageSelection &originalSelBorder, - const kpColor &backgroundColor, - const QString &name, - kpCommandEnvironment *environ); + const kpAbstractImageSelection &originalSelBorder, const kpColor &backgroundColor, + const QString &name, kpCommandEnvironment *environ); ~kpToolSelectionPullFromDocumentCommand () override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: kpColor m_backgroundColor; }; - #endif // kpToolSelectionPullFromDocumentCommand_H diff --git a/commands/tools/selection/kpToolSelectionPullFromDocumentCommand.cpp b/commands/tools/selection/kpToolSelectionPullFromDocumentCommand.cpp --- a/commands/tools/selection/kpToolSelectionPullFromDocumentCommand.cpp +++ b/commands/tools/selection/kpToolSelectionPullFromDocumentCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,50 +24,44 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpToolSelectionPullFromDocumentCommand.h" #include "layers/selections/image/kpAbstractImageSelection.h" #include "environments/commands/kpCommandEnvironment.h" #include "document/kpDocument.h" #include "views/manager/kpViewManager.h" #include "kpLogCategories.h" - kpToolSelectionPullFromDocumentCommand::kpToolSelectionPullFromDocumentCommand ( - const kpAbstractImageSelection &originalSelBorder, - const kpColor &backgroundColor, - const QString &name, - kpCommandEnvironment *environ) - : kpAbstractSelectionContentCommand (originalSelBorder, name, environ), - m_backgroundColor (backgroundColor) + const kpAbstractImageSelection &originalSelBorder, const kpColor &backgroundColor, + const QString &name, kpCommandEnvironment *environ) + : kpAbstractSelectionContentCommand(originalSelBorder, name, environ) + , m_backgroundColor(backgroundColor) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "kpToolSelectionPullFromDocumentCommand::() environ=" - << environ; + << environ; #endif } kpToolSelectionPullFromDocumentCommand::~kpToolSelectionPullFromDocumentCommand () = default; - // public virtual [base kpCommand] -void kpToolSelectionPullFromDocumentCommand::execute () +void kpToolSelectionPullFromDocumentCommand::execute() { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "kpToolSelectionPullFromDocumentCommand::execute()"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - kpViewManager *vm = viewManager (); - Q_ASSERT (vm); + kpViewManager *vm = viewManager(); + Q_ASSERT(vm); - vm->setQueueUpdates (); + vm->setQueueUpdates(); { // // Recreate border @@ -94,47 +87,43 @@ // 2. Later calls: // a) no image selection (due to deselection) // b) image selection with no content, at an arbitrary location - Q_ASSERT (!imageSelection () || !imageSelection ()->hasContent ()); + Q_ASSERT(!imageSelection() || !imageSelection()->hasContent()); const auto *originalImageSel = dynamic_cast - (originalSelection ()); + (originalSelection()); - if (originalImageSel->transparency () != - environ ()->imageSelectionTransparency ()) - { - environ ()->setImageSelectionTransparency (originalImageSel->transparency ()); + if (originalImageSel->transparency() + != environ()->imageSelectionTransparency()) { + environ()->setImageSelectionTransparency(originalImageSel->transparency()); } - doc->setSelection (*originalSelection ()); - + doc->setSelection(*originalSelection()); // // Add content // - doc->imageSelectionPullFromDocument (m_backgroundColor); + doc->imageSelectionPullFromDocument(m_backgroundColor); } - vm->restoreQueueUpdates (); + vm->restoreQueueUpdates(); } // public virtual [base kpCommand] -void kpToolSelectionPullFromDocumentCommand::unexecute () +void kpToolSelectionPullFromDocumentCommand::unexecute() { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "kpToolSelectionPullFromDocumentCommand::unexecute()"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); // Must have selection image content. - Q_ASSERT (doc->imageSelection () && doc->imageSelection ()->hasContent ()); - + Q_ASSERT(doc->imageSelection() && doc->imageSelection()->hasContent()); // We can have faith that this is the state of the selection after // execute(), rather than after the user tried to throw us off by // simply selecting another region as to do that, a destroy command // must have been used. - doc->selectionCopyOntoDocument (false/*use opaque pixmap*/); - doc->imageSelection ()->deleteContent (); + doc->selectionCopyOntoDocument(false /*use opaque pixmap*/); + doc->imageSelection()->deleteContent(); } - diff --git a/commands/tools/selection/kpToolSelectionResizeScaleCommand.h b/commands/tools/selection/kpToolSelectionResizeScaleCommand.h --- a/commands/tools/selection/kpToolSelectionResizeScaleCommand.h +++ b/commands/tools/selection/kpToolSelectionResizeScaleCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,22 +24,18 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolSelectionResizeScaleCommand_H #define kpToolSelectionResizeScaleCommand_H - #include #include #include "commands/kpNamedCommand.h" - class QTimer; class kpAbstractSelection; - // You could subclass kpToolResizeScaleCommand and/or // kpToolSelectionMoveCommand instead if want a disaster. // This is different to kpToolResizeScaleCommand in that: @@ -51,45 +46,43 @@ // // REFACTOR: Later: I take that all back. We should merge with // kpToolResizeScaleCommand to reduce code duplication. -class kpToolSelectionResizeScaleCommand : public QObject, - public kpNamedCommand +class kpToolSelectionResizeScaleCommand : public QObject, public kpNamedCommand { -Q_OBJECT + Q_OBJECT public: kpToolSelectionResizeScaleCommand (kpCommandEnvironment *environ); ~kpToolSelectionResizeScaleCommand () override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; public: - const kpAbstractSelection *originalSelection () const; + const kpAbstractSelection *originalSelection() const; - QPoint topLeft () const; - void moveTo (const QPoint &point); + QPoint topLeft() const; + void moveTo(const QPoint &point); - int width () const; - int height () const; - void resize (int width, int height, bool delayed = false); + int width() const; + int height() const; + void resize(int width, int height, bool delayed = false); // (equivalent to resize() followed by moveTo() but faster) - void resizeAndMoveTo (int width, int height, const QPoint &point, - bool delayed = false); + void resizeAndMoveTo(int width, int height, const QPoint &point, bool delayed = false); protected: - void killSmoothScaleTimer (); + void killSmoothScaleTimer(); // If , does a fast, low-quality scale and then calls itself // with unset for a smooth scale, a short time later. // If acting on a text box, is ignored. - void resizeScaleAndMove (bool delayed = false); + void resizeScaleAndMove(bool delayed = false); public: - void finalize (); + void finalize(); public: - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; protected: kpAbstractSelection *m_originalSelectionPtr; @@ -100,5 +93,4 @@ QTimer *m_smoothScaleTimer; }; - #endif // kpToolSelectionResizeScaleCommand_H diff --git a/commands/tools/selection/kpToolSelectionResizeScaleCommand.cpp b/commands/tools/selection/kpToolSelectionResizeScaleCommand.cpp --- a/commands/tools/selection/kpToolSelectionResizeScaleCommand.cpp +++ b/commands/tools/selection/kpToolSelectionResizeScaleCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpToolSelectionResizeScaleCommand.h" #include "layers/selections/kpAbstractSelection.h" @@ -49,209 +46,192 @@ //-------------------------------------------------------------------------------- kpToolSelectionResizeScaleCommand::kpToolSelectionResizeScaleCommand ( - kpCommandEnvironment *environ) - : kpNamedCommand (environ->textSelection () ? - i18n ("Text: Resize Box") : - i18n ("Selection: Smooth Scale"), - environ), - m_smoothScaleTimer (new QTimer (this)) + kpCommandEnvironment *environ) + : kpNamedCommand(environ->textSelection() + ? i18n("Text: Resize Box") + : i18n("Selection: Smooth Scale"), + environ) + , m_smoothScaleTimer(new QTimer(this)) { - m_originalSelectionPtr = selection ()->clone (); + m_originalSelectionPtr = selection()->clone(); - m_newTopLeft = selection ()->topLeft (); - m_newWidth = selection ()->width (); - m_newHeight = selection ()->height (); + m_newTopLeft = selection()->topLeft(); + m_newWidth = selection()->width(); + m_newHeight = selection()->height(); - m_smoothScaleTimer->setSingleShot (true); - connect (m_smoothScaleTimer, &QTimer::timeout, this, [this]{resizeScaleAndMove(false);}); + m_smoothScaleTimer->setSingleShot(true); + connect(m_smoothScaleTimer, &QTimer::timeout, this, [this] { + resizeScaleAndMove(false); + }); } kpToolSelectionResizeScaleCommand::~kpToolSelectionResizeScaleCommand () { delete m_originalSelectionPtr; } - // public virtual -kpCommandSize::SizeType kpToolSelectionResizeScaleCommand::size () const +kpCommandSize::SizeType kpToolSelectionResizeScaleCommand::size() const { - return SelectionSize (m_originalSelectionPtr); + return SelectionSize(m_originalSelectionPtr); } - // public -const kpAbstractSelection *kpToolSelectionResizeScaleCommand::originalSelection () const +const kpAbstractSelection *kpToolSelectionResizeScaleCommand::originalSelection() const { return m_originalSelectionPtr; } - // public -QPoint kpToolSelectionResizeScaleCommand::topLeft () const +QPoint kpToolSelectionResizeScaleCommand::topLeft() const { return m_newTopLeft; } // public -void kpToolSelectionResizeScaleCommand::moveTo (const QPoint &point) +void kpToolSelectionResizeScaleCommand::moveTo(const QPoint &point) { if (point == m_newTopLeft) { return; } m_newTopLeft = point; - selection ()->moveTo (m_newTopLeft); + selection()->moveTo(m_newTopLeft); } - // public -int kpToolSelectionResizeScaleCommand::width () const +int kpToolSelectionResizeScaleCommand::width() const { return m_newWidth; } // public -int kpToolSelectionResizeScaleCommand::height () const +int kpToolSelectionResizeScaleCommand::height() const { return m_newHeight; } // public -void kpToolSelectionResizeScaleCommand::resize (int width, int height, - bool delayed) +void kpToolSelectionResizeScaleCommand::resize(int width, int height, bool delayed) { if (width == m_newWidth && height == m_newHeight) { return; } m_newWidth = width; m_newHeight = height; - resizeScaleAndMove (delayed); + resizeScaleAndMove(delayed); } - // public -void kpToolSelectionResizeScaleCommand::resizeAndMoveTo (int width, int height, - const QPoint &point, - bool delayed) +void kpToolSelectionResizeScaleCommand::resizeAndMoveTo(int width, int height, const QPoint &point, + bool delayed) { - if (width == m_newWidth && height == m_newHeight && - point == m_newTopLeft) - { + if (width == m_newWidth && height == m_newHeight + && point == m_newTopLeft) { return; } m_newWidth = width; m_newHeight = height; m_newTopLeft = point; - resizeScaleAndMove (delayed); + resizeScaleAndMove(delayed); } - // protected -void kpToolSelectionResizeScaleCommand::killSmoothScaleTimer () +void kpToolSelectionResizeScaleCommand::killSmoothScaleTimer() { - m_smoothScaleTimer->stop (); + m_smoothScaleTimer->stop(); } - // protected -void kpToolSelectionResizeScaleCommand::resizeScaleAndMove (bool delayed) +void kpToolSelectionResizeScaleCommand::resizeScaleAndMove(bool delayed) { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogCommands) << "kpToolSelectionResizeScaleCommand::resizeScaleAndMove(delayed=" - << delayed << ")"; + << delayed << ")"; #endif - killSmoothScaleTimer (); + killSmoothScaleTimer(); kpAbstractSelection *newSelPtr = nullptr; - if (textSelection ()) - { - Q_ASSERT (dynamic_cast (m_originalSelectionPtr)); - auto *orgTextSel = dynamic_cast (m_originalSelectionPtr); - - newSelPtr = orgTextSel->resized (m_newWidth, m_newHeight); - } - else - { - Q_ASSERT (dynamic_cast (m_originalSelectionPtr)); - auto *imageSel = dynamic_cast (m_originalSelectionPtr); - - newSelPtr = new kpRectangularImageSelection ( - QRect (imageSel->x (), - imageSel->y (), - m_newWidth, - m_newHeight), - kpPixmapFX::scale (imageSel->baseImage (), - m_newWidth, m_newHeight, - !delayed/*if not delayed, smooth*/), - imageSel->transparency ()); - - if (delayed) - { + if (textSelection()) { + Q_ASSERT(dynamic_cast (m_originalSelectionPtr)); + auto *orgTextSel = dynamic_cast (m_originalSelectionPtr); + + newSelPtr = orgTextSel->resized(m_newWidth, m_newHeight); + } else { + Q_ASSERT(dynamic_cast (m_originalSelectionPtr)); + auto *imageSel = dynamic_cast (m_originalSelectionPtr); + + newSelPtr = new kpRectangularImageSelection( + QRect(imageSel->x(), + imageSel->y(), + m_newWidth, + m_newHeight), + kpPixmapFX::scale(imageSel->baseImage(), + m_newWidth, m_newHeight, + !delayed /*if not delayed, smooth*/), + imageSel->transparency()); + + if (delayed) { // Call self (once) with delayed==false in 200ms - m_smoothScaleTimer->start (200/*ms*/); + m_smoothScaleTimer->start(200 /*ms*/); } } - Q_ASSERT (newSelPtr); - newSelPtr->moveTo (m_newTopLeft); + Q_ASSERT(newSelPtr); + newSelPtr->moveTo(m_newTopLeft); - document ()->setSelection (*newSelPtr); + document()->setSelection(*newSelPtr); delete newSelPtr; } - // public -void kpToolSelectionResizeScaleCommand::finalize () +void kpToolSelectionResizeScaleCommand::finalize() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogCommands) << "kpToolSelectionResizeScaleCommand::finalize()" - << " smoothScaleTimer->isActive=" - << m_smoothScaleTimer->isActive (); + << " smoothScaleTimer->isActive=" + << m_smoothScaleTimer->isActive(); #endif // Make sure the selection contains the final image and the timer won't // fire afterwards. - if (m_smoothScaleTimer->isActive ()) - { - resizeScaleAndMove (); - Q_ASSERT (!m_smoothScaleTimer->isActive ()); + if (m_smoothScaleTimer->isActive()) { + resizeScaleAndMove(); + Q_ASSERT(!m_smoothScaleTimer->isActive()); } } - // public virtual [base kpToolResizeScaleCommand] -void kpToolSelectionResizeScaleCommand::execute () +void kpToolSelectionResizeScaleCommand::execute() { - QApplication::setOverrideCursor (Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); - killSmoothScaleTimer (); + killSmoothScaleTimer(); - resizeScaleAndMove (); + resizeScaleAndMove(); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } // public virtual [base kpToolResizeScaleCommand] -void kpToolSelectionResizeScaleCommand::unexecute () +void kpToolSelectionResizeScaleCommand::unexecute() { - QApplication::setOverrideCursor (Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); - killSmoothScaleTimer (); + killSmoothScaleTimer(); - document ()->setSelection (*m_originalSelectionPtr); + document()->setSelection(*m_originalSelectionPtr); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } - - diff --git a/commands/tools/selection/text/kpToolTextBackspaceCommand.h b/commands/tools/selection/text/kpToolTextBackspaceCommand.h --- a/commands/tools/selection/text/kpToolTextBackspaceCommand.h +++ b/commands/tools/selection/text/kpToolTextBackspaceCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_TEXT_BACKSPACE_COMMAND_H #define KP_TOOL_TEXT_BACKSPACE_COMMAND_H - #include "commands/kpNamedCommand.h" - class kpToolTextBackspaceCommand : public kpNamedCommand { public: @@ -42,23 +38,21 @@ AddBackspaceNow }; - kpToolTextBackspaceCommand (const QString &name, - int row, int col, Action action, - kpCommandEnvironment *environ); + kpToolTextBackspaceCommand (const QString &name, int row, int col, Action action, + kpCommandEnvironment *environ); ~kpToolTextBackspaceCommand () override; - void addBackspace (); + void addBackspace(); - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; protected: int m_row, m_col; int m_numBackspaces; QString m_deletedText; }; - #endif // KP_TOOL_TEXT_BACKSPACE_COMMAND_H diff --git a/commands/tools/selection/text/kpToolTextBackspaceCommand.cpp b/commands/tools/selection/text/kpToolTextBackspaceCommand.cpp --- a/commands/tools/selection/text/kpToolTextBackspaceCommand.cpp +++ b/commands/tools/selection/text/kpToolTextBackspaceCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,126 +26,113 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "kpToolTextBackspaceCommand.h" #include "layers/selections/text/kpTextSelection.h" #include "views/manager/kpViewManager.h" #include - -kpToolTextBackspaceCommand::kpToolTextBackspaceCommand (const QString &name, - int row, int col, Action action, - kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - m_row (row), m_col (col), - m_numBackspaces (0) +kpToolTextBackspaceCommand::kpToolTextBackspaceCommand (const QString &name, int row, int col, + Action action, + kpCommandEnvironment *environ) + : kpNamedCommand(name, environ) + , m_row(row) + , m_col(col) + , m_numBackspaces(0) { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); if (action == AddBackspaceNow) { - addBackspace (); + addBackspace(); } } kpToolTextBackspaceCommand::~kpToolTextBackspaceCommand () = default; - // public -void kpToolTextBackspaceCommand::addBackspace () +void kpToolTextBackspaceCommand::addBackspace() { - QList textLines = textSelection ()->textLines (); + QList textLines = textSelection()->textLines(); - if (m_col > 0) - { - m_deletedText.prepend (textLines [m_row][m_col - 1]); + if (m_col > 0) { + m_deletedText.prepend(textLines [m_row][m_col - 1]); - textLines [m_row] = textLines [m_row].left (m_col - 1) + - textLines [m_row].mid (m_col); + textLines [m_row] = textLines [m_row].left(m_col - 1) + +textLines [m_row].mid(m_col); m_col--; - } - else - { - if (m_row > 0) - { + } else { + if (m_row > 0) { int newCursorRow = m_row - 1; - int newCursorCol = textLines [newCursorRow].length (); + int newCursorCol = textLines [newCursorRow].length(); - m_deletedText.prepend ('\n'); + m_deletedText.prepend('\n'); textLines [newCursorRow] += textLines [m_row]; - textLines.erase (textLines.begin () + m_row); + textLines.erase(textLines.begin() + m_row); m_row = newCursorRow; m_col = newCursorCol; } } - textSelection ()->setTextLines (textLines); + textSelection()->setTextLines(textLines); - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); m_numBackspaces++; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolTextBackspaceCommand::size () const +kpCommandSize::SizeType kpToolTextBackspaceCommand::size() const { return static_cast - (static_cast (m_deletedText.length ()) * sizeof (QChar)); + (static_cast(m_deletedText.length()) * sizeof(QChar)); } - // public virtual [base kpCommand] -void kpToolTextBackspaceCommand::execute () +void kpToolTextBackspaceCommand::execute() { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); - m_deletedText.clear (); + m_deletedText.clear(); int oldNumBackspaces = m_numBackspaces; m_numBackspaces = 0; for (int i = 0; i < oldNumBackspaces; i++) { - addBackspace (); + addBackspace(); } } // public virtual [base kpCommand] -void kpToolTextBackspaceCommand::unexecute () +void kpToolTextBackspaceCommand::unexecute() { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); - QList textLines = textSelection ()->textLines (); + QList textLines = textSelection()->textLines(); - for (auto && i : m_deletedText) - { - if (i == '\n') - { - const QString rightHalf = textLines [m_row].mid (m_col); + for (auto &&i : m_deletedText) { + if (i == '\n') { + const QString rightHalf = textLines [m_row].mid(m_col); - textLines [m_row].truncate (m_col); - textLines.insert (textLines.begin () + m_row + 1, rightHalf); + textLines [m_row].truncate(m_col); + textLines.insert(textLines.begin() + m_row + 1, rightHalf); m_row++; m_col = 0; - } - else - { - const QString leftHalf = textLines [m_row].left (m_col); - const QString rightHalf = textLines [m_row].mid (m_col); + } else { + const QString leftHalf = textLines [m_row].left(m_col); + const QString rightHalf = textLines [m_row].mid(m_col); textLines [m_row] = leftHalf + i + rightHalf; m_col++; } } - m_deletedText.clear (); + m_deletedText.clear(); - textSelection ()->setTextLines (textLines); + textSelection()->setTextLines(textLines); - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); } - diff --git a/commands/tools/selection/text/kpToolTextChangeStyleCommand.h b/commands/tools/selection/text/kpToolTextChangeStyleCommand.h --- a/commands/tools/selection/text/kpToolTextChangeStyleCommand.h +++ b/commands/tools/selection/text/kpToolTextChangeStyleCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,31 +24,26 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_TEXT_CHANGE_STYLE_COMMAND_H #define KP_TOOL_TEXT_CHANGE_STYLE_COMMAND_H - #include "commands/kpNamedCommand.h" #include "layers/selections/text/kpTextStyle.h" - class kpToolTextChangeStyleCommand : public kpNamedCommand { public: - kpToolTextChangeStyleCommand (const QString &name, - const kpTextStyle &newTextStyle, const kpTextStyle &oldTextStyle, - kpCommandEnvironment *environ); + kpToolTextChangeStyleCommand (const QString &name, const kpTextStyle &newTextStyle, + const kpTextStyle &oldTextStyle, kpCommandEnvironment *environ); ~kpToolTextChangeStyleCommand () override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; protected: kpTextStyle m_newTextStyle, m_oldTextStyle; }; - #endif // KP_TOOL_TEXT_CHANGE_STYLE_COMMAND_H diff --git a/commands/tools/selection/text/kpToolTextChangeStyleCommand.cpp b/commands/tools/selection/text/kpToolTextChangeStyleCommand.cpp --- a/commands/tools/selection/text/kpToolTextChangeStyleCommand.cpp +++ b/commands/tools/selection/text/kpToolTextChangeStyleCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,70 +26,67 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "kpToolTextChangeStyleCommand.h" #include "environments/commands/kpCommandEnvironment.h" #include "layers/selections/text/kpTextSelection.h" #include "kpLogCategories.h" - kpToolTextChangeStyleCommand::kpToolTextChangeStyleCommand (const QString &name, - const kpTextStyle &newTextStyle, const kpTextStyle &oldTextStyle, - kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - m_newTextStyle (newTextStyle), - m_oldTextStyle (oldTextStyle) + const kpTextStyle &newTextStyle, + const kpTextStyle &oldTextStyle, + kpCommandEnvironment *environ) + : kpNamedCommand(name, environ) + , m_newTextStyle(newTextStyle) + , m_oldTextStyle(oldTextStyle) { } kpToolTextChangeStyleCommand::~kpToolTextChangeStyleCommand () = default; - // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolTextChangeStyleCommand::size () const +kpCommandSize::SizeType kpToolTextChangeStyleCommand::size() const { return 0; } - // public virtual [base kpCommand] -void kpToolTextChangeStyleCommand::execute () +void kpToolTextChangeStyleCommand::execute() { #if DEBUG_KP_TOOL_TEXT && 1 qCDebug(kpLogCommands) << "kpToolTextChangeStyleCommand::execute()" - << " font=" << m_newTextStyle.fontFamily () - << " fontSize=" << m_newTextStyle.fontSize () - << " isBold=" << m_newTextStyle.isBold () - << " isItalic=" << m_newTextStyle.isItalic () - << " isUnderline=" << m_newTextStyle.isUnderline () - << " isStrikeThru=" << m_newTextStyle.isStrikeThru (); + << " font=" << m_newTextStyle.fontFamily() + << " fontSize=" << m_newTextStyle.fontSize() + << " isBold=" << m_newTextStyle.isBold() + << " isItalic=" << m_newTextStyle.isItalic() + << " isUnderline=" << m_newTextStyle.isUnderline() + << " isStrikeThru=" << m_newTextStyle.isStrikeThru(); #endif - environ ()->setTextStyle (m_newTextStyle); + environ()->setTextStyle(m_newTextStyle); - if (textSelection ()) { - textSelection ()->setTextStyle (m_newTextStyle); + if (textSelection()) { + textSelection()->setTextStyle(m_newTextStyle); } } // public virtual [base kpCommand] -void kpToolTextChangeStyleCommand::unexecute () +void kpToolTextChangeStyleCommand::unexecute() { #if DEBUG_KP_TOOL_TEXT && 1 qCDebug(kpLogCommands) << "kpToolTextChangeStyleCommand::unexecute()" - << " font=" << m_newTextStyle.fontFamily () - << " fontSize=" << m_newTextStyle.fontSize () - << " isBold=" << m_newTextStyle.isBold () - << " isItalic=" << m_newTextStyle.isItalic () - << " isUnderline=" << m_newTextStyle.isUnderline () - << " isStrikeThru=" << m_newTextStyle.isStrikeThru (); + << " font=" << m_newTextStyle.fontFamily() + << " fontSize=" << m_newTextStyle.fontSize() + << " isBold=" << m_newTextStyle.isBold() + << " isItalic=" << m_newTextStyle.isItalic() + << " isUnderline=" << m_newTextStyle.isUnderline() + << " isStrikeThru=" << m_newTextStyle.isStrikeThru(); #endif - environ ()->setTextStyle (m_oldTextStyle); + environ()->setTextStyle(m_oldTextStyle); - if (textSelection ()) - textSelection ()->setTextStyle (m_oldTextStyle); + if (textSelection()) { + textSelection()->setTextStyle(m_oldTextStyle); + } } - diff --git a/commands/tools/selection/text/kpToolTextDeleteCommand.h b/commands/tools/selection/text/kpToolTextDeleteCommand.h --- a/commands/tools/selection/text/kpToolTextDeleteCommand.h +++ b/commands/tools/selection/text/kpToolTextDeleteCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_TEXT_DELETE_COMMAND_H #define KP_TOOL_TEXT_DELETE_COMMAND_H - #include "commands/kpNamedCommand.h" - class kpToolTextDeleteCommand : public kpNamedCommand { public: @@ -42,23 +38,21 @@ AddDeleteNow }; - kpToolTextDeleteCommand (const QString &name, - int row, int col, Action action, - kpCommandEnvironment *environ); + kpToolTextDeleteCommand (const QString &name, int row, int col, Action action, + kpCommandEnvironment *environ); ~kpToolTextDeleteCommand () override; - void addDelete (); + void addDelete(); - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; protected: int m_row, m_col; int m_numDeletes; QString m_deletedText; }; - #endif // KP_TOOL_TEXT_DELETE_COMMAND_H diff --git a/commands/tools/selection/text/kpToolTextDeleteCommand.cpp b/commands/tools/selection/text/kpToolTextDeleteCommand.cpp --- a/commands/tools/selection/text/kpToolTextDeleteCommand.cpp +++ b/commands/tools/selection/text/kpToolTextDeleteCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,114 +26,100 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "kpToolTextDeleteCommand.h" #include "layers/selections/text/kpTextSelection.h" #include "views/manager/kpViewManager.h" #include - -kpToolTextDeleteCommand::kpToolTextDeleteCommand (const QString &name, - int row, int col, Action action, - kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - m_row (row), m_col (col), - m_numDeletes (0) +kpToolTextDeleteCommand::kpToolTextDeleteCommand (const QString &name, int row, int col, + Action action, kpCommandEnvironment *environ) + : kpNamedCommand(name, environ) + , m_row(row) + , m_col(col) + , m_numDeletes(0) { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); if (action == AddDeleteNow) { - addDelete (); + addDelete(); } } kpToolTextDeleteCommand::~kpToolTextDeleteCommand () = default; - // public -void kpToolTextDeleteCommand::addDelete () +void kpToolTextDeleteCommand::addDelete() { - QList textLines = textSelection ()->textLines (); + QList textLines = textSelection()->textLines(); - if (m_col < static_cast (textLines [m_row].length ())) - { - m_deletedText.prepend (textLines [m_row][m_col]); + if (m_col < static_cast(textLines [m_row].length())) { + m_deletedText.prepend(textLines [m_row][m_col]); - textLines [m_row] = textLines [m_row].left (m_col) + - textLines [m_row].mid (m_col + 1); - } - else - { - if (m_row < static_cast (textLines.size () - 1)) - { - m_deletedText.prepend ('\n'); + textLines [m_row] = textLines [m_row].left(m_col) + +textLines [m_row].mid(m_col + 1); + } else { + if (m_row < static_cast(textLines.size() - 1)) { + m_deletedText.prepend('\n'); textLines [m_row] += textLines [m_row + 1]; - textLines.erase (textLines.begin () + m_row + 1); + textLines.erase(textLines.begin() + m_row + 1); } } - textSelection ()->setTextLines (textLines); + textSelection()->setTextLines(textLines); - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); m_numDeletes++; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolTextDeleteCommand::size () const +kpCommandSize::SizeType kpToolTextDeleteCommand::size() const { return static_cast - (static_cast (m_deletedText.length ()) * sizeof (QChar)); + (static_cast(m_deletedText.length()) * sizeof(QChar)); } - // public virtual [base kpCommand] -void kpToolTextDeleteCommand::execute () +void kpToolTextDeleteCommand::execute() { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); - m_deletedText.clear (); + m_deletedText.clear(); int oldNumDeletes = m_numDeletes; m_numDeletes = 0; for (int i = 0; i < oldNumDeletes; i++) { - addDelete (); + addDelete(); } } // public virtual [base kpCommand] -void kpToolTextDeleteCommand::unexecute () +void kpToolTextDeleteCommand::unexecute() { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); - QList textLines = textSelection ()->textLines (); + QList textLines = textSelection()->textLines(); - for (auto && i : m_deletedText) - { - if (i == '\n') - { - const QString rightHalf = textLines [m_row].mid (m_col); + for (auto &&i : m_deletedText) { + if (i == '\n') { + const QString rightHalf = textLines [m_row].mid(m_col); - textLines [m_row].truncate (m_col); - textLines.insert (textLines.begin () + m_row + 1, rightHalf); - } - else - { - const QString leftHalf = textLines [m_row].left (m_col); - const QString rightHalf = textLines [m_row].mid (m_col); + textLines [m_row].truncate(m_col); + textLines.insert(textLines.begin() + m_row + 1, rightHalf); + } else { + const QString leftHalf = textLines [m_row].left(m_col); + const QString rightHalf = textLines [m_row].mid(m_col); textLines [m_row] = leftHalf + i + rightHalf; } } - m_deletedText.clear (); + m_deletedText.clear(); - textSelection ()->setTextLines (textLines); + textSelection()->setTextLines(textLines); - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); } - diff --git a/commands/tools/selection/text/kpToolTextEnterCommand.h b/commands/tools/selection/text/kpToolTextEnterCommand.h --- a/commands/tools/selection/text/kpToolTextEnterCommand.h +++ b/commands/tools/selection/text/kpToolTextEnterCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_TEXT_ENTER_COMMAND_H #define KP_TOOL_TEXT_ENTER_COMMAND_H - #include "commands/kpNamedCommand.h" - class kpToolTextEnterCommand : public kpNamedCommand { public: @@ -42,22 +38,20 @@ AddEnterNow }; - kpToolTextEnterCommand (const QString &name, - int row, int col, Action action, - kpCommandEnvironment *environ); + kpToolTextEnterCommand (const QString &name, int row, int col, Action action, + kpCommandEnvironment *environ); ~kpToolTextEnterCommand () override; - void addEnter (); + void addEnter(); - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; protected: int m_row, m_col; int m_numEnters; }; - #endif // KP_TOOL_TEXT_ENTER_COMMAND_H diff --git a/commands/tools/selection/text/kpToolTextEnterCommand.cpp b/commands/tools/selection/text/kpToolTextEnterCommand.cpp --- a/commands/tools/selection/text/kpToolTextEnterCommand.cpp +++ b/commands/tools/selection/text/kpToolTextEnterCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,100 +26,93 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "kpToolTextEnterCommand.h" #include "layers/selections/text/kpTextSelection.h" #include "views/manager/kpViewManager.h" #include - -kpToolTextEnterCommand::kpToolTextEnterCommand (const QString &name, - int row, int col, Action action, - kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - m_row (row), m_col (col), - m_numEnters (0) +kpToolTextEnterCommand::kpToolTextEnterCommand (const QString &name, int row, int col, + Action action, kpCommandEnvironment *environ) + : kpNamedCommand(name, environ) + , m_row(row) + , m_col(col) + , m_numEnters(0) { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); if (action == AddEnterNow) { - addEnter (); + addEnter(); } } kpToolTextEnterCommand::~kpToolTextEnterCommand () = default; - // public -void kpToolTextEnterCommand::addEnter () +void kpToolTextEnterCommand::addEnter() { - QList textLines = textSelection ()->textLines (); + QList textLines = textSelection()->textLines(); - const QString rightHalf = textLines [m_row].mid (m_col); + const QString rightHalf = textLines [m_row].mid(m_col); - textLines [m_row].truncate (m_col); - textLines.insert (textLines.begin () + m_row + 1, rightHalf); + textLines [m_row].truncate(m_col); + textLines.insert(textLines.begin() + m_row + 1, rightHalf); - textSelection ()->setTextLines (textLines); + textSelection()->setTextLines(textLines); m_row++; m_col = 0; - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); m_numEnters++; } - // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolTextEnterCommand::size () const +kpCommandSize::SizeType kpToolTextEnterCommand::size() const { return 0; } - // public virtual [base kpCommand] -void kpToolTextEnterCommand::execute () +void kpToolTextEnterCommand::execute() { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); int oldNumEnters = m_numEnters; m_numEnters = 0; for (int i = 0; i < oldNumEnters; i++) { - addEnter (); + addEnter(); } } // public virtual [base kpCommand] -void kpToolTextEnterCommand::unexecute () +void kpToolTextEnterCommand::unexecute() { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); - QList textLines = textSelection ()->textLines (); + QList textLines = textSelection()->textLines(); - for (int i = 0; i < m_numEnters; i++) - { - Q_ASSERT (m_col == 0); + for (int i = 0; i < m_numEnters; i++) { + Q_ASSERT(m_col == 0); if (m_row <= 0) { break; } int newRow = m_row - 1; - int newCol = textLines [newRow].length (); + int newCol = textLines [newRow].length(); textLines [newRow] += textLines [m_row]; - textLines.erase (textLines.begin () + m_row); + textLines.erase(textLines.begin() + m_row); m_row = newRow; m_col = newCol; } - textSelection ()->setTextLines (textLines); + textSelection()->setTextLines(textLines); - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); } - diff --git a/commands/tools/selection/text/kpToolTextGiveContentCommand.h b/commands/tools/selection/text/kpToolTextGiveContentCommand.h --- a/commands/tools/selection/text/kpToolTextGiveContentCommand.h +++ b/commands/tools/selection/text/kpToolTextGiveContentCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,35 +24,28 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolTextGiveContentCommand_H #define kpToolTextGiveContentCommand_H - #include "commands/tools/selection/kpAbstractSelectionContentCommand.h" - class kpTextSelection; - // Converts a text border (no text lines) to a text selection with 1 empty // text line. This must be executed before any manipulations can be made // to a text selection. // // Text analog of kpToolSelectionPullFromDocumentCommand. -class kpToolTextGiveContentCommand : - public kpAbstractSelectionContentCommand +class kpToolTextGiveContentCommand : public kpAbstractSelectionContentCommand { public: kpToolTextGiveContentCommand ( - const kpTextSelection &originalSelBorder, - const QString &name, + const kpTextSelection &originalSelBorder, const QString &name, kpCommandEnvironment *environ); ~kpToolTextGiveContentCommand () override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; }; - #endif // kpToolTextGiveContentCommand_H diff --git a/commands/tools/selection/text/kpToolTextGiveContentCommand.cpp b/commands/tools/selection/text/kpToolTextGiveContentCommand.cpp --- a/commands/tools/selection/text/kpToolTextGiveContentCommand.cpp +++ b/commands/tools/selection/text/kpToolTextGiveContentCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,51 +24,45 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpToolTextGiveContentCommand.h" #include "environments/commands/kpCommandEnvironment.h" #include "document/kpDocument.h" #include "layers/selections/text/kpTextSelection.h" #include "views/manager/kpViewManager.h" #include "kpLogCategories.h" - kpToolTextGiveContentCommand::kpToolTextGiveContentCommand ( - const kpTextSelection &originalSelBorder, - const QString &name, - kpCommandEnvironment *environ) - : kpAbstractSelectionContentCommand (originalSelBorder, name, environ) + const kpTextSelection &originalSelBorder, const QString &name, kpCommandEnvironment *environ) + : kpAbstractSelectionContentCommand(originalSelBorder, name, environ) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "kpToolTextGiveContentCommand::() environ=" - << environ + << environ #endif } kpToolTextGiveContentCommand::~kpToolTextGiveContentCommand () = default; - // public virtual [base kpCommand] -void kpToolTextGiveContentCommand::execute () +void kpToolTextGiveContentCommand::execute() { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "kpToolTextGiveContentCommand::execute()"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - kpViewManager *vm = viewManager (); - Q_ASSERT (vm); + kpViewManager *vm = viewManager(); + Q_ASSERT(vm); // See API Doc for kpViewManager::textCursorRow() & textCursorCol(). - Q_ASSERT (vm->textCursorRow () == 0 && vm->textCursorCol () == 0); + Q_ASSERT(vm->textCursorRow() == 0 && vm->textCursorCol() == 0); - vm->setQueueUpdates (); + vm->setQueueUpdates(); { // // Recreate border @@ -95,57 +88,55 @@ // 2. Later calls: // a) no text selection (due to deselection) // b) text selection with no content, at an arbitrary location - Q_ASSERT (!textSelection () || !textSelection ()->hasContent ()); + Q_ASSERT(!textSelection() || !textSelection()->hasContent()); const auto *originalTextSel = dynamic_cast - (originalSelection ()); + (originalSelection()); - if (originalTextSel->textStyle () != environ ()->textStyle ()) { - environ ()->setTextStyle (originalTextSel->textStyle ()); + if (originalTextSel->textStyle() != environ()->textStyle()) { + environ()->setTextStyle(originalTextSel->textStyle()); } - doc->setSelection (*originalSelection ()); - + doc->setSelection(*originalSelection()); // // Add Content // QList listOfOneEmptyString; - listOfOneEmptyString.append (QString ()); - textSelection ()->setTextLines (listOfOneEmptyString); + listOfOneEmptyString.append(QString()); + textSelection()->setTextLines(listOfOneEmptyString); } - vm->restoreQueueUpdates (); + vm->restoreQueueUpdates(); // This should not have changed from the start of the method. - Q_ASSERT (vm->textCursorRow () == 0 && vm->textCursorCol () == 0); + Q_ASSERT(vm->textCursorRow() == 0 && vm->textCursorCol() == 0); } // public virtual [base kpCommand] -void kpToolTextGiveContentCommand::unexecute () +void kpToolTextGiveContentCommand::unexecute() { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogCommands) << "kpToolTextGiveContentCommand::unexecute()"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); // Must have selection text content. - Q_ASSERT (doc->textSelection () && doc->textSelection ()->hasContent ()); + Q_ASSERT(doc->textSelection() && doc->textSelection()->hasContent()); - kpViewManager *vm = viewManager (); - Q_ASSERT (vm); + kpViewManager *vm = viewManager(); + Q_ASSERT(vm); // All the commands after us have been unexecuted, so we must be back // to the state we were after our execute(). - Q_ASSERT (vm->textCursorRow () == 0 && vm->textCursorCol () == 0); + Q_ASSERT(vm->textCursorRow() == 0 && vm->textCursorCol() == 0); // We can have faith that this is the state of the selection after // execute(), rather than after the user tried to throw us off by // simply selecting another region as to do that, a destroy command // must have been used. - doc->textSelection ()->deleteContent (); + doc->textSelection()->deleteContent(); // This should not have changed from the start of the method. - Q_ASSERT (vm->textCursorRow () == 0 && vm->textCursorCol () == 0); + Q_ASSERT(vm->textCursorRow() == 0 && vm->textCursorCol() == 0); } - diff --git a/commands/tools/selection/text/kpToolTextInsertCommand.h b/commands/tools/selection/text/kpToolTextInsertCommand.h --- a/commands/tools/selection/text/kpToolTextInsertCommand.h +++ b/commands/tools/selection/text/kpToolTextInsertCommand.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,32 +24,27 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_TEXT_INSERT_COMMAND_H #define KP_TOOL_TEXT_INSERT_COMMAND_H - #include "commands/kpNamedCommand.h" - class kpToolTextInsertCommand : public kpNamedCommand { public: - kpToolTextInsertCommand (const QString &name, - int row, int col, const QString& newText, - kpCommandEnvironment *environ); + kpToolTextInsertCommand (const QString &name, int row, int col, const QString &newText, + kpCommandEnvironment *environ); - void addText (const QString &moreText); + void addText(const QString &moreText); - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; protected: int m_row, m_col; QString m_newText; }; - #endif // KP_TOOL_TEXT_INSERT_COMMAND_H diff --git a/commands/tools/selection/text/kpToolTextInsertCommand.cpp b/commands/tools/selection/text/kpToolTextInsertCommand.cpp --- a/commands/tools/selection/text/kpToolTextInsertCommand.cpp +++ b/commands/tools/selection/text/kpToolTextInsertCommand.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "kpToolTextInsertCommand.h" #include "layers/selections/text/kpTextSelection.h" @@ -37,74 +35,75 @@ //--------------------------------------------------------------------- -kpToolTextInsertCommand::kpToolTextInsertCommand (const QString &name, - int row, int col, const QString& newText, - kpCommandEnvironment *environ) - : kpNamedCommand (name, environ), - m_row (row), m_col (col) +kpToolTextInsertCommand::kpToolTextInsertCommand (const QString &name, int row, int col, + const QString &newText, + kpCommandEnvironment *environ) + : kpNamedCommand(name, environ) + , m_row(row) + , m_col(col) { - viewManager ()->setTextCursorPosition (m_row, m_col); - addText (newText); + viewManager()->setTextCursorPosition(m_row, m_col); + addText(newText); } //--------------------------------------------------------------------- // public -void kpToolTextInsertCommand::addText (const QString &moreText) +void kpToolTextInsertCommand::addText(const QString &moreText) { - if (moreText.isEmpty ()) { + if (moreText.isEmpty()) { return; } - QList textLines = textSelection ()->textLines (); - const QString leftHalf = textLines [m_row].left (m_col); - const QString rightHalf = textLines [m_row].mid (m_col); + QList textLines = textSelection()->textLines(); + const QString leftHalf = textLines [m_row].left(m_col); + const QString rightHalf = textLines [m_row].mid(m_col); textLines [m_row] = leftHalf + moreText + rightHalf; - textSelection ()->setTextLines (textLines); + textSelection()->setTextLines(textLines); m_newText += moreText; - m_col += moreText.length (); + m_col += moreText.length(); - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); } //--------------------------------------------------------------------- // public virtual [base kpCommand] -kpCommandSize::SizeType kpToolTextInsertCommand::size () const +kpCommandSize::SizeType kpToolTextInsertCommand::size() const { return static_cast - (static_cast (m_newText.length ()) * sizeof (QChar)); + (static_cast(m_newText.length()) * sizeof(QChar)); } //--------------------------------------------------------------------- // public virtual [base kpCommand] -void kpToolTextInsertCommand::execute () +void kpToolTextInsertCommand::execute() { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); QString text = m_newText; - m_newText.clear (); - addText (text); + m_newText.clear(); + addText(text); } //--------------------------------------------------------------------- // public virtual [base kpCommand] -void kpToolTextInsertCommand::unexecute () +void kpToolTextInsertCommand::unexecute() { - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); - QList textLines = textSelection ()->textLines (); - const QString leftHalf = textLines [m_row].left (m_col - m_newText.length ()); - const QString rightHalf = textLines [m_row].mid (m_col); + QList textLines = textSelection()->textLines(); + const QString leftHalf = textLines [m_row].left(m_col - m_newText.length()); + const QString rightHalf = textLines [m_row].mid(m_col); textLines [m_row] = leftHalf + rightHalf; - textSelection ()->setTextLines (textLines); + textSelection()->setTextLines(textLines); - m_col -= m_newText.length (); + m_col -= m_newText.length(); - viewManager ()->setTextCursorPosition (m_row, m_col); + viewManager()->setTextCursorPosition(m_row, m_col); } //--------------------------------------------------------------------- diff --git a/cursors/kpCursorLightCross.h b/cursors/kpCursorLightCross.h --- a/cursors/kpCursorLightCross.h +++ b/cursors/kpCursorLightCross.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,15 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_CURSOR_LIGHT_CROSS_H #define KP_CURSOR_LIGHT_CROSS_H - class QCursor; - -const QCursor *kpCursorLightCrossCreate (); - +const QCursor *kpCursorLightCrossCreate(); #endif // KP_CURSOR_LIGHT_CROSS_H diff --git a/cursors/kpCursorLightCross.cpp b/cursors/kpCursorLightCross.cpp --- a/cursors/kpCursorLightCross.cpp +++ b/cursors/kpCursorLightCross.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,24 +26,20 @@ #define DEBUG_KP_CURSOR_LIGHT_CROSS 0 - #include "kpCursorLightCross.h" #include "kpLogCategories.h" #include #include - enum PixelValue { White, Black, Transparent }; -static void setPixel (unsigned char *colorBitmap, - unsigned char *maskBitmap, - int width, - int y, int x, enum PixelValue pv) +static void setPixel(unsigned char *colorBitmap, unsigned char *maskBitmap, int width, int y, int x, + enum PixelValue pv) { const int ColorBlack = 1; const int ColorWhite = 0; @@ -54,8 +49,7 @@ int colorValue, maskValue; - switch (pv) - { + switch (pv) { case White: colorValue = ColorWhite; maskValue = MaskOpaque; @@ -81,8 +75,7 @@ } } - -const QCursor *kpCursorLightCrossCreate () +const QCursor *kpCursorLightCrossCreate() { #if DEBUG_KP_CURSOR_LIGHT_CROSS qCDebug(kpLogMisc) << "kpCursorLightCrossCreate() "; @@ -93,39 +86,37 @@ auto *colorBitmap = new unsigned char [byteSize]; auto *maskBitmap = new unsigned char [byteSize]; - memset (colorBitmap, 0, byteSize); - memset (maskBitmap, 0, byteSize); + memset(colorBitmap, 0, byteSize); + memset(maskBitmap, 0, byteSize); const int oddSide = side - 1; const int strokeLen = oddSide * 3 / 8; - for (int i = 0; i < strokeLen; i++) - { + for (int i = 0; i < strokeLen; i++) { const enum PixelValue pv = (i % 2) ? Black : White; #define X_(val) (val) #define Y_(val) (val) - #define DRAW(y,x) setPixel (colorBitmap, maskBitmap, side, (y), (x), pv) + #define DRAW(y, x) setPixel(colorBitmap, maskBitmap, side, (y), (x), pv) // horizontal - DRAW (Y_(side / 2), X_(1 + i)); - DRAW (Y_(side / 2), X_(side - 1 - i)); + DRAW(Y_(side / 2), X_(1 + i)); + DRAW(Y_(side / 2), X_(side - 1 - i)); // vertical - DRAW (Y_(1 + i), X_(side / 2)); - DRAW (Y_(side - 1 - i), X_(side / 2)); + DRAW(Y_(1 + i), X_(side / 2)); + DRAW(Y_(side - 1 - i), X_(side / 2)); #undef DRAW #undef Y_ #undef X_ } - const QSize size (side, side); - QCursor *cursor = new QCursor ( - QBitmap::fromData (size, colorBitmap, QImage::Format_MonoLSB), - QBitmap::fromData (size, maskBitmap, QImage::Format_MonoLSB)); + const QSize size(side, side); + QCursor *cursor = new QCursor( + QBitmap::fromData(size, colorBitmap, QImage::Format_MonoLSB), + QBitmap::fromData(size, maskBitmap, QImage::Format_MonoLSB)); delete [] maskBitmap; delete [] colorBitmap; return cursor; } - diff --git a/cursors/kpCursorProvider.h b/cursors/kpCursorProvider.h --- a/cursors/kpCursorProvider.h +++ b/cursors/kpCursorProvider.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,19 +24,15 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_CURSOR_PROVIDER_H #define KP_CURSOR_PROVIDER_H - class QCursor; - class kpCursorProvider { public: - static QCursor lightCross (); + static QCursor lightCross(); }; - #endif // KP_CURSOR_PROVIDER_H diff --git a/cursors/kpCursorProvider.cpp b/cursors/kpCursorProvider.cpp --- a/cursors/kpCursorProvider.cpp +++ b/cursors/kpCursorProvider.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,23 +24,20 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpCursorProvider.h" #include "kpCursorLightCross.h" #include - static const QCursor *TheLightCursor = nullptr; - // public static -QCursor kpCursorProvider::lightCross () +QCursor kpCursorProvider::lightCross() { // TODO: don't leak (although it's cleaned up on exit by OS anyway) if (!::TheLightCursor) { - ::TheLightCursor = kpCursorLightCrossCreate (); + ::TheLightCursor = kpCursorLightCrossCreate(); } return *::TheLightCursor; diff --git a/dialogs/imagelib/effects/kpEffectsDialog.h b/dialogs/imagelib/effects/kpEffectsDialog.h --- a/dialogs/imagelib/effects/kpEffectsDialog.h +++ b/dialogs/imagelib/effects/kpEffectsDialog.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_EFFECTS_DIALOG_H #define KP_EFFECTS_DIALOG_H - #include "dialogs/imagelib/transforms/kpTransformPreviewDialog.h" - class QComboBox; class QGroupBox; class QImage; @@ -42,38 +38,34 @@ class kpEffectCommandBase; class kpEffectWidgetBase; - class kpEffectsDialog : public kpTransformPreviewDialog { -Q_OBJECT + Q_OBJECT public: // Specifying is more efficient than leaving it // as 0 and then calling selectEffect() afterwards. - kpEffectsDialog (bool actOnSelection, - kpTransformDialogEnvironment *_env, - QWidget *parent, + kpEffectsDialog (bool actOnSelection, kpTransformDialogEnvironment *_env, QWidget *parent, int defaultSelectedEffect = 0); ~kpEffectsDialog () override; - bool isNoOp () const override; - kpEffectCommandBase *createCommand () const; + bool isNoOp() const override; + kpEffectCommandBase *createCommand() const; protected: - QSize newDimensions () const override; - QImage transformPixmap (const QImage &pixmap, - int targetWidth, int targetHeight) const override; + QSize newDimensions() const override; + QImage transformPixmap(const QImage &pixmap, int targetWidth, int targetHeight) const override; public: - int selectedEffect () const; + int selectedEffect() const; public slots: - void selectEffect (int which); + void selectEffect(int which); protected slots: - void slotUpdate () override; - void slotUpdateWithWaitCursor () override; + void slotUpdate() override; + void slotUpdateWithWaitCursor() override; - void slotDelayedUpdate (); + void slotDelayedUpdate(); protected: static int s_lastWidth, s_lastHeight; @@ -87,5 +79,4 @@ kpEffectWidgetBase *m_effectWidget; }; - #endif // KP_EFFECTS_DIALOG_H diff --git a/dialogs/imagelib/effects/kpEffectsDialog.cpp b/dialogs/imagelib/effects/kpEffectsDialog.cpp --- a/dialogs/imagelib/effects/kpEffectsDialog.cpp +++ b/dialogs/imagelib/effects/kpEffectsDialog.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECTS_DIALOG 0 - #include "kpEffectsDialog.h" #include "kpDefs.h" @@ -55,318 +52,292 @@ #include #include - // protected static int kpEffectsDialog::s_lastWidth = 640; int kpEffectsDialog::s_lastHeight = 620; - -kpEffectsDialog::kpEffectsDialog (bool actOnSelection, - kpTransformDialogEnvironment *_env, - QWidget *parent, - int defaultSelectedEffect) - : kpTransformPreviewDialog (kpTransformPreviewDialog::Preview, - true/*reserve top row*/, - QString()/*caption*/, - QString()/*afterActionText (no Dimensions Group Box)*/, - actOnSelection, - _env, - parent), - m_delayedUpdateTimer (new QTimer (this)), - m_effectsComboBox (nullptr), - m_settingsGroupBox (nullptr), - m_settingsLayout (nullptr), - m_effectWidget (nullptr) +kpEffectsDialog::kpEffectsDialog (bool actOnSelection, kpTransformDialogEnvironment *_env, + QWidget *parent, int defaultSelectedEffect) + : kpTransformPreviewDialog(kpTransformPreviewDialog::Preview, + true /*reserve top row*/, + QString() /*caption*/, + QString() /*afterActionText (no Dimensions Group Box)*/, + actOnSelection, + _env, + parent) + , m_delayedUpdateTimer(new QTimer(this)) + , m_effectsComboBox(nullptr) + , m_settingsGroupBox(nullptr) + , m_settingsLayout(nullptr) + , m_effectWidget(nullptr) { #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "kpEffectsDialog::kpEffectsDialog()"; #endif - const bool e = updatesEnabled (); - setUpdatesEnabled (false); - + const bool e = updatesEnabled(); + setUpdatesEnabled(false); if (actOnSelection) { - setWindowTitle (i18nc ("@title:window", "More Image Effects (Selection)")); - } - else { - setWindowTitle (i18nc ("@title:window", "More Image Effects")); + setWindowTitle(i18nc("@title:window", "More Image Effects (Selection)")); + } else { + setWindowTitle(i18nc("@title:window", "More Image Effects")); } + m_delayedUpdateTimer->setSingleShot(true); + connect(m_delayedUpdateTimer, &QTimer::timeout, + this, &kpEffectsDialog::slotUpdateWithWaitCursor); - m_delayedUpdateTimer->setSingleShot (true); - connect (m_delayedUpdateTimer, &QTimer::timeout, - this, &kpEffectsDialog::slotUpdateWithWaitCursor); + QWidget *effectContainer = new QWidget(mainWidget()); - - QWidget *effectContainer = new QWidget (mainWidget ()); - - auto *containerLayout = new QHBoxLayout (effectContainer); + auto *containerLayout = new QHBoxLayout(effectContainer); containerLayout->setContentsMargins(0, 0, 0, 0); - QLabel *label = new QLabel (i18n ("&Effect:"), effectContainer); + QLabel *label = new QLabel(i18n("&Effect:"), effectContainer); - m_effectsComboBox = new QComboBox (effectContainer); + m_effectsComboBox = new QComboBox(effectContainer); // Keep in alphabetical order. // TODO: What about translations? // sync: order in selectEffect(). - m_effectsComboBox->addItem (i18n ("Balance")); - m_effectsComboBox->addItem (i18n ("Emboss")); - m_effectsComboBox->addItem (i18n ("Flatten")); - m_effectsComboBox->addItem (i18n ("Histogram Equalizer")); - m_effectsComboBox->addItem (i18n ("Hue, Saturation, Value")); - m_effectsComboBox->addItem (i18n ("Invert")); - m_effectsComboBox->addItem (i18n ("Reduce Colors")); - m_effectsComboBox->addItem (i18n ("Soften & Sharpen")); - - containerLayout->addWidget (label); - containerLayout->addWidget (m_effectsComboBox, 1); - - label->setBuddy (m_effectsComboBox); - - addCustomWidgetToFront (effectContainer); - - - m_settingsGroupBox = new QGroupBox (mainWidget ()); - m_settingsLayout = new QVBoxLayout ( m_settingsGroupBox ); - addCustomWidgetToBack (m_settingsGroupBox); + m_effectsComboBox->addItem(i18n("Balance")); + m_effectsComboBox->addItem(i18n("Emboss")); + m_effectsComboBox->addItem(i18n("Flatten")); + m_effectsComboBox->addItem(i18n("Histogram Equalizer")); + m_effectsComboBox->addItem(i18n("Hue, Saturation, Value")); + m_effectsComboBox->addItem(i18n("Invert")); + m_effectsComboBox->addItem(i18n("Reduce Colors")); + m_effectsComboBox->addItem(i18n("Soften & Sharpen")); + containerLayout->addWidget(label); + containerLayout->addWidget(m_effectsComboBox, 1); - connect (m_effectsComboBox, static_cast(&QComboBox::activated), - this, &kpEffectsDialog::selectEffect); + label->setBuddy(m_effectsComboBox); + addCustomWidgetToFront(effectContainer); - selectEffect (defaultSelectedEffect); + m_settingsGroupBox = new QGroupBox(mainWidget()); + m_settingsLayout = new QVBoxLayout(m_settingsGroupBox); + addCustomWidgetToBack(m_settingsGroupBox); + connect(m_effectsComboBox, static_cast(&QComboBox::activated), + this, &kpEffectsDialog::selectEffect); - resize (s_lastWidth, s_lastHeight); + selectEffect(defaultSelectedEffect); + resize(s_lastWidth, s_lastHeight); #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "about to setUpdatesEnabled()"; #endif // OPT: The preview pixmap gets recalculated here and then possibly // again when QResizeEvent fires, when the dialog is shown. - setUpdatesEnabled (e); + setUpdatesEnabled(e); #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << endl - << endl - << endl; + << endl + << endl; #endif } kpEffectsDialog::~kpEffectsDialog () { - s_lastWidth = width (); - s_lastHeight = height (); + s_lastWidth = width(); + s_lastHeight = height(); } - // public virtual [base kpTransformPreviewDialog] -bool kpEffectsDialog::isNoOp () const +bool kpEffectsDialog::isNoOp() const { if (!m_effectWidget) { return true; } - return m_effectWidget->isNoOp (); + return m_effectWidget->isNoOp(); } // public -kpEffectCommandBase *kpEffectsDialog::createCommand () const +kpEffectCommandBase *kpEffectsDialog::createCommand() const { if (!m_effectWidget) { return nullptr; } - return m_effectWidget->createCommand (m_environ->commandEnvironment ()); + return m_effectWidget->createCommand(m_environ->commandEnvironment()); } - // protected virtual [base kpTransformPreviewDialog] -QSize kpEffectsDialog::newDimensions () const +QSize kpEffectsDialog::newDimensions() const { - kpDocument *doc = document (); + kpDocument *doc = document(); if (!doc) { - return {}; + return {}; } - return {doc->width (m_actOnSelection), doc->height (m_actOnSelection)}; + return { + doc->width(m_actOnSelection), doc->height(m_actOnSelection) + }; } // protected virtual [base kpTransformPreviewDialog] -QImage kpEffectsDialog::transformPixmap (const QImage &pixmap, - int targetWidth, int targetHeight) const +QImage kpEffectsDialog::transformPixmap(const QImage &pixmap, int targetWidth, + int targetHeight) const { QImage pixmapWithEffect; - if (m_effectWidget && !m_effectWidget->isNoOp ()) { - pixmapWithEffect = m_effectWidget->applyEffect (pixmap); - } - else { + if (m_effectWidget && !m_effectWidget->isNoOp()) { + pixmapWithEffect = m_effectWidget->applyEffect(pixmap); + } else { pixmapWithEffect = pixmap; } - return kpPixmapFX::scale (pixmapWithEffect, targetWidth, targetHeight); + return kpPixmapFX::scale(pixmapWithEffect, targetWidth, targetHeight); } - // public -int kpEffectsDialog::selectedEffect () const +int kpEffectsDialog::selectedEffect() const { - return m_effectsComboBox->currentIndex (); + return m_effectsComboBox->currentIndex(); } // public slot -void kpEffectsDialog::selectEffect (int which) +void kpEffectsDialog::selectEffect(int which) { #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "kpEffectsDialog::selectEffect(" << which << ")"; #endif - if (which < 0 || - which >= m_effectsComboBox->count ()) - { + if (which < 0 + || which >= m_effectsComboBox->count()) { return; } - if (which != m_effectsComboBox->currentIndex ()) { - m_effectsComboBox->setCurrentIndex (which); + if (which != m_effectsComboBox->currentIndex()) { + m_effectsComboBox->setCurrentIndex(which); } - delete m_effectWidget; m_effectWidget = nullptr; - m_settingsGroupBox->setWindowTitle(QString()); #define CREATE_EFFECT_WIDGET(name) \ - m_effectWidget = new name (m_actOnSelection, m_settingsGroupBox) + m_effectWidget = new name(m_actOnSelection, m_settingsGroupBox) // sync: order in constructor. - switch (which) - { + switch (which) { case 0: - CREATE_EFFECT_WIDGET (kpEffectBalanceWidget); + CREATE_EFFECT_WIDGET(kpEffectBalanceWidget); break; case 1: - CREATE_EFFECT_WIDGET (kpEffectEmbossWidget); + CREATE_EFFECT_WIDGET(kpEffectEmbossWidget); break; case 2: - CREATE_EFFECT_WIDGET (kpEffectFlattenWidget); + CREATE_EFFECT_WIDGET(kpEffectFlattenWidget); break; - + case 3: - CREATE_EFFECT_WIDGET (kpEffectToneEnhanceWidget); + CREATE_EFFECT_WIDGET(kpEffectToneEnhanceWidget); break; case 4: - CREATE_EFFECT_WIDGET (kpEffectHSVWidget); + CREATE_EFFECT_WIDGET(kpEffectHSVWidget); break; case 5: - CREATE_EFFECT_WIDGET (kpEffectInvertWidget); + CREATE_EFFECT_WIDGET(kpEffectInvertWidget); break; case 6: - CREATE_EFFECT_WIDGET (kpEffectReduceColorsWidget); + CREATE_EFFECT_WIDGET(kpEffectReduceColorsWidget); break; case 7: - CREATE_EFFECT_WIDGET (kpEffectBlurSharpenWidget); + CREATE_EFFECT_WIDGET(kpEffectBlurSharpenWidget); break; } #undef CREATE_EFFECT_WIDGET - - if (m_effectWidget) - { - const bool e = updatesEnabled (); - setUpdatesEnabled (false); + if (m_effectWidget) { + const bool e = updatesEnabled(); + setUpdatesEnabled(false); #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "widget exists for effect #"; #endif - m_settingsGroupBox->setTitle (m_effectWidget->caption ()); + m_settingsGroupBox->setTitle(m_effectWidget->caption()); // Show widget. // // Don't resize the whole dialog when doing this. // This seems to work magically without any extra code with Qt4. #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "addWidget"; #endif - m_settingsLayout->addWidget (m_effectWidget); + m_settingsLayout->addWidget(m_effectWidget); #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "show widget"; #endif - m_effectWidget->show (); + m_effectWidget->show(); - connect (m_effectWidget, &kpEffectWidgetBase::settingsChangedNoWaitCursor, - this, &kpEffectsDialog::slotUpdate); - connect (m_effectWidget, &kpEffectWidgetBase::settingsChanged, - this, &kpEffectsDialog::slotUpdateWithWaitCursor); - connect (m_effectWidget, &kpEffectWidgetBase::settingsChangedDelayed, - this, &kpEffectsDialog::slotDelayedUpdate); + connect(m_effectWidget, &kpEffectWidgetBase::settingsChangedNoWaitCursor, + this, &kpEffectsDialog::slotUpdate); + connect(m_effectWidget, &kpEffectWidgetBase::settingsChanged, + this, &kpEffectsDialog::slotUpdateWithWaitCursor); + connect(m_effectWidget, &kpEffectWidgetBase::settingsChangedDelayed, + this, &kpEffectsDialog::slotDelayedUpdate); #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "about to setUpdatesEnabled()"; #endif - setUpdatesEnabled (e); + setUpdatesEnabled(e); } - #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "done" - << endl - << endl - << endl; + << endl + << endl + << endl; #endif } - // protected slot virtual [base kpTransformPreviewDialog] -void kpEffectsDialog::slotUpdate () +void kpEffectsDialog::slotUpdate() { #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "kpEffectsDialog::slotUpdate()" - << " timerActive=" << m_delayedUpdateTimer->isActive () - << endl; + << " timerActive=" << m_delayedUpdateTimer->isActive() + << endl; #endif - m_delayedUpdateTimer->stop (); + m_delayedUpdateTimer->stop(); - kpTransformPreviewDialog::slotUpdate (); + kpTransformPreviewDialog::slotUpdate(); } // protected slot virtual [base kpTransformPreviewDialog] -void kpEffectsDialog::slotUpdateWithWaitCursor () +void kpEffectsDialog::slotUpdateWithWaitCursor() { #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "kpEffectsDialog::slotUpdateWithWaitCursor()" - << " timerActive=" << m_delayedUpdateTimer->isActive () - << endl; + << " timerActive=" << m_delayedUpdateTimer->isActive() + << endl; #endif - m_delayedUpdateTimer->stop (); + m_delayedUpdateTimer->stop(); - kpTransformPreviewDialog::slotUpdateWithWaitCursor (); + kpTransformPreviewDialog::slotUpdateWithWaitCursor(); } - // protected slot -void kpEffectsDialog::slotDelayedUpdate () +void kpEffectsDialog::slotDelayedUpdate() { #if DEBUG_KP_EFFECTS_DIALOG qCDebug(kpLogDialogs) << "kpEffectsDialog::slotDelayedUpdate()" - << " timerActive=" << m_delayedUpdateTimer->isActive () - << endl; + << " timerActive=" << m_delayedUpdateTimer->isActive() + << endl; #endif - m_delayedUpdateTimer->stop (); + m_delayedUpdateTimer->stop(); // (single shot) - m_delayedUpdateTimer->start (400/*ms*/); + m_delayedUpdateTimer->start(400 /*ms*/); } - - diff --git a/dialogs/imagelib/kpDocumentMetaInfoDialog.h b/dialogs/imagelib/kpDocumentMetaInfoDialog.h --- a/dialogs/imagelib/kpDocumentMetaInfoDialog.h +++ b/dialogs/imagelib/kpDocumentMetaInfoDialog.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,19 +24,15 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpDocumentMetaInfoDialog_H #define kpDocumentMetaInfoDialog_H - #include - class QTableWidgetItem; class kpDocumentMetaInfo; - // Dialog for editing document meta information (see kpDocumentMetaInfo). // It contains: // @@ -50,17 +45,16 @@ // to add new rows without pressing any pushbuttons. class kpDocumentMetaInfoDialog : public QDialog { -Q_OBJECT + Q_OBJECT public: - kpDocumentMetaInfoDialog (const kpDocumentMetaInfo *docMetaInfo, - QWidget *parent); + kpDocumentMetaInfoDialog (const kpDocumentMetaInfo *docMetaInfo, QWidget *parent); ~kpDocumentMetaInfoDialog () override; public: - bool isNoOp () const; + bool isNoOp() const; - kpDocumentMetaInfo originalMetaInfo () const; + kpDocumentMetaInfo originalMetaInfo() const; // Returns the meta information gathered from all the UI. // @@ -79,36 +73,35 @@ // // This is a slow method as it recalculates the meta information each // time it's called. - kpDocumentMetaInfo metaInfo (QString *errorMessage = nullptr) const; + kpDocumentMetaInfo metaInfo(QString *errorMessage = nullptr) const; private: - void editCell (int r, int c); - void fieldsUpdateVerticalHeader (); + void editCell(int r, int c); + void fieldsUpdateVerticalHeader(); - void fieldsAddEmptyRow (int atRow); - void fieldsAppendEmptyRow (); + void fieldsAddEmptyRow(int atRow); + void fieldsAppendEmptyRow(); - bool isFieldsRowDeleteable (int row) const; - void fieldsDeleteRow (int r); + bool isFieldsRowDeleteable(int row) const; + void fieldsDeleteRow(int r); - void enableFieldsDeleteRowButtonIfShould (); + void enableFieldsDeleteRowButtonIfShould(); private slots: - void setUIToOriginalMetaInfo (); - void slotFieldsCurrentCellChanged (int row, int col, int oldRow, int oldCol); + void setUIToOriginalMetaInfo(); + void slotFieldsCurrentCellChanged(int row, int col, int oldRow, int oldCol); // Allows the user to add a row without pressing any pushbuttons: // Appends a new, blank row when text has been added to the last row. - void slotFieldsItemChanged (QTableWidgetItem *item); + void slotFieldsItemChanged(QTableWidgetItem *item); - void slotFieldsAddRowButtonClicked (); - void slotFieldsDeleteRowButtonClicked (); + void slotFieldsAddRowButtonClicked(); + void slotFieldsDeleteRowButtonClicked(); - void accept () override; + void accept() override; private: - struct kpDocumentMetaInfoDialogPrivate * const d; + struct kpDocumentMetaInfoDialogPrivate *const d; }; - #endif // kpDocumentMetaInfoDialog_H diff --git a/dialogs/imagelib/kpDocumentMetaInfoDialog.cpp b/dialogs/imagelib/kpDocumentMetaInfoDialog.cpp --- a/dialogs/imagelib/kpDocumentMetaInfoDialog.cpp +++ b/dialogs/imagelib/kpDocumentMetaInfoDialog.cpp @@ -24,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_DOCUMENT_META_INFO_DIALOG 0 - #include "kpDocumentMetaInfoDialog.h" #include "kpDefs.h" @@ -48,7 +46,6 @@ #include #include - struct kpDocumentMetaInfoDialogPrivate { const kpDocumentMetaInfo *originalMetaInfoPtr; @@ -60,11 +57,9 @@ QPushButton *fieldsAddRowButton, *fieldsDeleteRowButton, *fieldsResetButton; }; - // (shared by all dialogs, across all main windows, in a KolourPaint instance) static int LastWidth = -1, LastHeight = -1; - // sync: You must keep DpiMinStep = 10 ^ (-DpiPrecision). // // You can increase the precision to reduce the chance of inadvertently changing @@ -84,15 +79,15 @@ static const int DpiPrecision = 3; static const double DpiMinStep = 0.001; -static const double DpiLegalMin = - kpDocumentMetaInfo::MinDotsPerMeter / KP_INCHES_PER_METER; +static const double DpiLegalMin + = kpDocumentMetaInfo::MinDotsPerMeter / KP_INCHES_PER_METER; // Out of range represents unspecified DPI. static const double DpiUnspecified = ::DpiLegalMin - ::DpiMinStep; static const double DpiInputMin = ::DpiUnspecified; -static const double DpiInputMax = - kpDocumentMetaInfo::MaxDotsPerMeter / KP_INCHES_PER_METER; +static const double DpiInputMax + = kpDocumentMetaInfo::MaxDotsPerMeter / KP_INCHES_PER_METER; // The increment the DPI spinboxes jump by when they're clicked. // @@ -105,38 +100,34 @@ // exactly the value they want. static const double DpiInputStep = 10; - // TODO: Halve groupbox layout margins in every other file since it doesn't // seem to be need in Qt4. kpDocumentMetaInfoDialog::kpDocumentMetaInfoDialog ( - const kpDocumentMetaInfo *docMetaInfo, - QWidget *parent) + const kpDocumentMetaInfo *docMetaInfo, QWidget *parent) - : QDialog (parent), - d (new kpDocumentMetaInfoDialogPrivate ()) + : QDialog(parent) + , d(new kpDocumentMetaInfoDialogPrivate()) { d->originalMetaInfoPtr = docMetaInfo; + setWindowTitle(i18nc("@title:window", "Document Properties")); + auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok + |QDialogButtonBox::Cancel, this); - setWindowTitle (i18nc ("@title:window", "Document Properties")); - auto * buttons = new QDialogButtonBox (QDialogButtonBox::Ok | - QDialogButtonBox::Cancel, this); + connect(buttons, &QDialogButtonBox::accepted, this, &kpDocumentMetaInfoDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, this, &kpDocumentMetaInfoDialog::reject); - connect (buttons, &QDialogButtonBox::accepted, this, &kpDocumentMetaInfoDialog::accept); - connect (buttons, &QDialogButtonBox::rejected, this, &kpDocumentMetaInfoDialog::reject); - - auto *baseWidget = new QWidget (this); - - auto *dialogLayout = new QVBoxLayout (this); - dialogLayout->addWidget (baseWidget); - dialogLayout->addWidget (buttons); + auto *baseWidget = new QWidget(this); + auto *dialogLayout = new QVBoxLayout(this); + dialogLayout->addWidget(baseWidget); + dialogLayout->addWidget(buttons); // // DPI Group Box // - Q_ASSERT (::DpiInputMin < ::DpiInputMax); + Q_ASSERT(::DpiInputMin < ::DpiInputMax); auto *dpiGroupBox = new QGroupBox(i18n("Dots &Per Inch (DPI)"), baseWidget); @@ -147,18 +138,17 @@ d->horizDpiInput->setDecimals(::DpiPrecision); d->horizDpiInput->setSpecialValueText(i18n("Unspecified")); - auto *dpiXLabel = new QLabel ( - i18nc ("Horizontal DPI 'x' Vertical DPI", " x "), dpiGroupBox); - dpiXLabel->setAlignment (Qt::AlignCenter); + auto *dpiXLabel = new QLabel( + i18nc("Horizontal DPI 'x' Vertical DPI", " x "), dpiGroupBox); + dpiXLabel->setAlignment(Qt::AlignCenter); d->vertDpiInput = new QDoubleSpinBox(dpiGroupBox); d->vertDpiInput->setRange(::DpiInputMin, ::DpiInputMax); d->vertDpiInput->setValue(0.0); d->vertDpiInput->setSingleStep(::DpiInputStep); d->vertDpiInput->setDecimals(::DpiPrecision); d->vertDpiInput->setSpecialValueText(i18n("Unspecified")); - auto *dpiLay = new QGridLayout(dpiGroupBox); dpiLay->addWidget(new QLabel(i18n("Horizontal:")), 0, 0, Qt::AlignHCenter); @@ -169,9 +159,8 @@ dpiLay->setRowStretch(2, 1); - - dpiGroupBox->setWhatsThis ( - i18n ( + dpiGroupBox->setWhatsThis( + i18n( "" "

Dots Per Inch (DPI) specifies the number of pixels" " of the image that should be printed inside one inch (2.54cm).

" @@ -195,14 +184,13 @@ "

Not all image formats support DPI values. If the format you" " save in does not support them, they will not be saved.

" "
" - )); - + )); // // Offset Group Box // - auto *offsetGroupBox = new QGroupBox(i18n ("O&ffset"), baseWidget); + auto *offsetGroupBox = new QGroupBox(i18n("O&ffset"), baseWidget); d->horizOffsetInput = new QSpinBox; d->horizOffsetInput->setRange(kpDocumentMetaInfo::MinOffset, kpDocumentMetaInfo::MaxOffset); @@ -217,68 +205,64 @@ offsetLay->addWidget(new QLabel(i18n("Vertical:")), 0, 1, Qt::AlignHCenter); offsetLay->addWidget(d->vertOffsetInput, 1, 1); - offsetLay->setRowStretch (2, 1); - + offsetLay->setRowStretch(2, 1); - offsetGroupBox->setWhatsThis ( - i18n ( + offsetGroupBox->setWhatsThis( + i18n( "" "

The Offset is the relative position where this image" " should be placed, compared to other images.

" "

Not all image formats support the Offset feature." " If the format you save in does not support it, the values" " specified here will not be saved.

" "
" - )); - + )); // // Fields Group Box // + auto *fieldsGroupBox = new QGroupBox(i18n("&Text Fields"), + baseWidget); - auto *fieldsGroupBox = new QGroupBox (i18n ("&Text Fields"), - baseWidget); - - d->fieldsTableWidget = new QTableWidget (fieldsGroupBox); + d->fieldsTableWidget = new QTableWidget(fieldsGroupBox); d->fieldsTableWidget->setEditTriggers(QAbstractItemView::AllEditTriggers); - connect (d->fieldsTableWidget, &QTableWidget::currentCellChanged, - this, &kpDocumentMetaInfoDialog::slotFieldsCurrentCellChanged); - - connect (d->fieldsTableWidget, &QTableWidget::itemChanged, - this, &kpDocumentMetaInfoDialog::slotFieldsItemChanged); + connect(d->fieldsTableWidget, &QTableWidget::currentCellChanged, + this, &kpDocumentMetaInfoDialog::slotFieldsCurrentCellChanged); - d->fieldsAddRowButton = new QPushButton (i18n ("&Add Row"), - fieldsGroupBox); - connect (d->fieldsAddRowButton, &QPushButton::clicked, - this, &kpDocumentMetaInfoDialog::slotFieldsAddRowButtonClicked); + connect(d->fieldsTableWidget, &QTableWidget::itemChanged, + this, &kpDocumentMetaInfoDialog::slotFieldsItemChanged); - d->fieldsDeleteRowButton = new QPushButton (i18n ("&Delete Row"), - fieldsGroupBox); - connect (d->fieldsDeleteRowButton, &QPushButton::clicked, - this, &kpDocumentMetaInfoDialog::slotFieldsDeleteRowButtonClicked); + d->fieldsAddRowButton = new QPushButton(i18n("&Add Row"), + fieldsGroupBox); + connect(d->fieldsAddRowButton, &QPushButton::clicked, + this, &kpDocumentMetaInfoDialog::slotFieldsAddRowButtonClicked); - d->fieldsResetButton = new QPushButton (i18n ("&Reset"), - fieldsGroupBox); - connect (d->fieldsResetButton, &QPushButton::clicked, - this, &kpDocumentMetaInfoDialog::setUIToOriginalMetaInfo); + d->fieldsDeleteRowButton = new QPushButton(i18n("&Delete Row"), + fieldsGroupBox); + connect(d->fieldsDeleteRowButton, &QPushButton::clicked, + this, &kpDocumentMetaInfoDialog::slotFieldsDeleteRowButtonClicked); - auto *fieldsButtonsLayout = new QHBoxLayout (); - fieldsButtonsLayout->addWidget (d->fieldsAddRowButton); - fieldsButtonsLayout->addWidget (d->fieldsDeleteRowButton); - fieldsButtonsLayout->addStretch (); - fieldsButtonsLayout->addWidget (d->fieldsResetButton); + d->fieldsResetButton = new QPushButton(i18n("&Reset"), + fieldsGroupBox); + connect(d->fieldsResetButton, &QPushButton::clicked, + this, &kpDocumentMetaInfoDialog::setUIToOriginalMetaInfo); - auto *fieldsLayout = new QVBoxLayout (fieldsGroupBox); + auto *fieldsButtonsLayout = new QHBoxLayout(); + fieldsButtonsLayout->addWidget(d->fieldsAddRowButton); + fieldsButtonsLayout->addWidget(d->fieldsDeleteRowButton); + fieldsButtonsLayout->addStretch(); + fieldsButtonsLayout->addWidget(d->fieldsResetButton); - fieldsLayout->addWidget (d->fieldsTableWidget); - fieldsLayout->addLayout (fieldsButtonsLayout); + auto *fieldsLayout = new QVBoxLayout(fieldsGroupBox); + fieldsLayout->addWidget(d->fieldsTableWidget); + fieldsLayout->addLayout(fieldsButtonsLayout); - fieldsGroupBox->setWhatsThis ( - i18n ( + fieldsGroupBox->setWhatsThis( + i18n( "" "

Text Fields provide extra information about the image." " This is probably a comment area that you can freely write any text in.

" @@ -290,212 +274,187 @@ "

Not all image formats support Text Fields. If the format" " you save in does not support them, they will not be saved.

" "
" - )); - + )); // // Global Layout // - auto *baseLayout = new QGridLayout (baseWidget); + auto *baseLayout = new QGridLayout(baseWidget); baseLayout->setContentsMargins(0, 0, 0, 0); // Col 0 - baseLayout->addWidget (dpiGroupBox, 0, 0); - baseLayout->addWidget (offsetGroupBox, 1, 0); + baseLayout->addWidget(dpiGroupBox, 0, 0); + baseLayout->addWidget(offsetGroupBox, 1, 0); // Col 1 - baseLayout->addWidget (fieldsGroupBox, 0, 1, 2/*row span*/, 1/*col span*/); - baseLayout->setColumnStretch (1, 1/*stretch*/); - + baseLayout->addWidget(fieldsGroupBox, 0, 1, 2 /*row span*/, 1 /*col span*/); + baseLayout->setColumnStretch(1, 1 /*stretch*/); // // Remaining UI Setup // - - setUIToOriginalMetaInfo (); - + setUIToOriginalMetaInfo(); if (::LastWidth > 0 && ::LastHeight > 0) { - resize (::LastWidth, ::LastHeight); + resize(::LastWidth, ::LastHeight); } } //--------------------------------------------------------------------- kpDocumentMetaInfoDialog::~kpDocumentMetaInfoDialog () { - ::LastWidth = width (); - ::LastHeight = height (); + ::LastWidth = width(); + ::LastHeight = height(); delete d; } //--------------------------------------------------------------------- // private -void kpDocumentMetaInfoDialog::editCell (int r, int c) +void kpDocumentMetaInfoDialog::editCell(int r, int c) { - d->fieldsTableWidget->setCurrentCell (r, c); - d->fieldsTableWidget->editItem (d->fieldsTableWidget->item (r, c)); + d->fieldsTableWidget->setCurrentCell(r, c); + d->fieldsTableWidget->editItem(d->fieldsTableWidget->item(r, c)); } //--------------------------------------------------------------------- // private slot -void kpDocumentMetaInfoDialog::setUIToOriginalMetaInfo () +void kpDocumentMetaInfoDialog::setUIToOriginalMetaInfo() { // Set DPI spinboxes. - d->horizDpiInput->setValue (d->originalMetaInfoPtr->dotsPerMeterX () / - KP_INCHES_PER_METER); - d->vertDpiInput->setValue (d->originalMetaInfoPtr->dotsPerMeterY () / - KP_INCHES_PER_METER); - + d->horizDpiInput->setValue(d->originalMetaInfoPtr->dotsPerMeterX() + /KP_INCHES_PER_METER); + d->vertDpiInput->setValue(d->originalMetaInfoPtr->dotsPerMeterY() + /KP_INCHES_PER_METER); // Set Offset spinboxes. - d->horizOffsetInput->setValue (d->originalMetaInfoPtr->offset ().x ()); - d->vertOffsetInput->setValue (d->originalMetaInfoPtr->offset ().y ()); - + d->horizOffsetInput->setValue(d->originalMetaInfoPtr->offset().x()); + d->vertOffsetInput->setValue(d->originalMetaInfoPtr->offset().y()); // Set Text Fields. // // Block itemChanged() signal as slotFieldsItemChanged() should not get called // when rows are half-created. - const bool b = d->fieldsTableWidget->blockSignals (true); + const bool b = d->fieldsTableWidget->blockSignals(true); { - d->fieldsTableWidget->clear (); + d->fieldsTableWidget->clear(); - d->fieldsTableWidget->setRowCount (d->originalMetaInfoPtr->textKeys ().size ()); - d->fieldsTableWidget->setColumnCount (2); + d->fieldsTableWidget->setRowCount(d->originalMetaInfoPtr->textKeys().size()); + d->fieldsTableWidget->setColumnCount(2); QStringList fieldsHeader; - fieldsHeader << i18n ("Key") << i18n ("Value"); - d->fieldsTableWidget->setHorizontalHeaderLabels (fieldsHeader); + fieldsHeader << i18n("Key") << i18n("Value"); + d->fieldsTableWidget->setHorizontalHeaderLabels(fieldsHeader); int row = 0; - for (const auto &key : d->originalMetaInfoPtr->textKeys ()) - { - d->fieldsTableWidget->setItem (row, 0/*1st col*/, - new QTableWidgetItem (key)); - d->fieldsTableWidget->setItem (row, 1/*2nd col*/, - new QTableWidgetItem (d->originalMetaInfoPtr->text (key))); + for (const auto &key : d->originalMetaInfoPtr->textKeys()) { + d->fieldsTableWidget->setItem(row, 0 /*1st col*/, + new QTableWidgetItem(key)); + d->fieldsTableWidget->setItem(row, 1 /*2nd col*/, + new QTableWidgetItem(d->originalMetaInfoPtr->text(key))); row++; } - fieldsAppendEmptyRow (); + fieldsAppendEmptyRow(); } - d->fieldsTableWidget->blockSignals (b); + d->fieldsTableWidget->blockSignals(b); + editCell(0 /*row*/, 0 /*col*/); - editCell (0/*row*/, 0/*col*/); - - - enableFieldsDeleteRowButtonIfShould (); + enableFieldsDeleteRowButtonIfShould(); } //--------------------------------------------------------------------- // public -bool kpDocumentMetaInfoDialog::isNoOp () const +bool kpDocumentMetaInfoDialog::isNoOp() const { - return (metaInfo () == *d->originalMetaInfoPtr); + return metaInfo() == *d->originalMetaInfoPtr; } //--------------------------------------------------------------------- // public -kpDocumentMetaInfo kpDocumentMetaInfoDialog::originalMetaInfo () const +kpDocumentMetaInfo kpDocumentMetaInfoDialog::originalMetaInfo() const { return *d->originalMetaInfoPtr; } // public -kpDocumentMetaInfo kpDocumentMetaInfoDialog::metaInfo ( - QString *errorMessage) const +kpDocumentMetaInfo kpDocumentMetaInfoDialog::metaInfo( + QString *errorMessage) const { - if (errorMessage) - { + if (errorMessage) { // No errors to start with. - *errorMessage = QString (); + *errorMessage = QString(); } - kpDocumentMetaInfo ret; - - if (d->horizDpiInput->value () < ::DpiLegalMin) { - ret.setDotsPerMeterX (0/*unspecified*/); - } - else { - ret.setDotsPerMeterX (qRound (d->horizDpiInput->value () * KP_INCHES_PER_METER)); + if (d->horizDpiInput->value() < ::DpiLegalMin) { + ret.setDotsPerMeterX(0 /*unspecified*/); + } else { + ret.setDotsPerMeterX(qRound(d->horizDpiInput->value() * KP_INCHES_PER_METER)); } - if (d->vertDpiInput->value () < ::DpiLegalMin) { - ret.setDotsPerMeterY (0/*unspecified*/); + if (d->vertDpiInput->value() < ::DpiLegalMin) { + ret.setDotsPerMeterY(0 /*unspecified*/); + } else { + ret.setDotsPerMeterY(qRound(d->vertDpiInput->value() * KP_INCHES_PER_METER)); } - else { - ret.setDotsPerMeterY (qRound (d->vertDpiInput->value () * KP_INCHES_PER_METER)); - } - - - ret.setOffset (QPoint (d->horizOffsetInput->value (), - d->vertOffsetInput->value ())); + ret.setOffset(QPoint(d->horizOffsetInput->value(), + d->vertOffsetInput->value())); - for (int r = 0; r < d->fieldsTableWidget->rowCount (); r++) - { - const QString key = d->fieldsTableWidget->item (r, 0)->text (); - const QString value = d->fieldsTableWidget->item (r, 1)->text (); + for (int r = 0; r < d->fieldsTableWidget->rowCount(); r++) { + const QString key = d->fieldsTableWidget->item(r, 0)->text(); + const QString value = d->fieldsTableWidget->item(r, 1)->text(); // Empty key? - if (key.isEmpty ()) - { + if (key.isEmpty()) { // Empty value too? - if (value.isEmpty ()) - { + if (value.isEmpty()) { // Ignore empty row. continue; } // Value without a key? - - if (errorMessage) - { - *errorMessage = - ki18n ("The text value \"%1\" on line %2 requires a key.") - .subs (value).subs (r + 1/*count from 1*/).toString (); + if (errorMessage) { + *errorMessage + = ki18n("The text value \"%1\" on line %2 requires a key.") + .subs(value).subs(r + 1 /*count from 1*/).toString(); // Print only 1 error message per method invocation. errorMessage = nullptr; } // Ignore. continue; - } // Duplicate key? - if (ret.textKeys ().contains (key)) - { - if (errorMessage) - { + if (ret.textKeys().contains(key)) { + if (errorMessage) { int q; - for (q = 0; q < r; q++) - { - if (d->fieldsTableWidget->item (q, 0)->text () == key) { + for (q = 0; q < r; q++) { + if (d->fieldsTableWidget->item(q, 0)->text() == key) { break; } } - Q_ASSERT (q != r); + Q_ASSERT(q != r); - *errorMessage = - ki18n ("All text keys must be unique. The text key \"%1\"" - " on lines %2 and %3 are identical.") - .subs (key) - .subs (q + 1/*count from 1*/) - .subs (r + 1/*count from 1*/) - .toString (); + *errorMessage + = ki18n("All text keys must be unique. The text key \"%1\"" + " on lines %2 and %3 are identical.") + .subs(key) + .subs(q + 1 /*count from 1*/) + .subs(r + 1 /*count from 1*/) + .toString(); // Print only 1 error message per method invocation. errorMessage = nullptr; @@ -505,89 +464,82 @@ continue; } - ret.setText (key, value); - + ret.setText(key, value); } // for (r = 0; r < table widget rows; r++) { - return ret; } - // private -void kpDocumentMetaInfoDialog::fieldsUpdateVerticalHeader () +void kpDocumentMetaInfoDialog::fieldsUpdateVerticalHeader() { QStringList vertLabels; - for (int r = 1; r <= d->fieldsTableWidget->rowCount (); r++) { - vertLabels << QString::number (r); + for (int r = 1; r <= d->fieldsTableWidget->rowCount(); r++) { + vertLabels << QString::number(r); } - d->fieldsTableWidget->setVerticalHeaderLabels (vertLabels); + d->fieldsTableWidget->setVerticalHeaderLabels(vertLabels); } - // private -void kpDocumentMetaInfoDialog::fieldsAddEmptyRow (int atRow) +void kpDocumentMetaInfoDialog::fieldsAddEmptyRow(int atRow) { // Block itemChanged() signal as slotFieldsItemChanged() should not get called // when rows are half-created. - const bool b = d->fieldsTableWidget->blockSignals (true); + const bool b = d->fieldsTableWidget->blockSignals(true); { - d->fieldsTableWidget->insertRow (atRow); + d->fieldsTableWidget->insertRow(atRow); - d->fieldsTableWidget->setItem (atRow, 0, new QTableWidgetItem (QString ())); - d->fieldsTableWidget->setItem (atRow, 1, new QTableWidgetItem (QString ())); + d->fieldsTableWidget->setItem(atRow, 0, new QTableWidgetItem(QString())); + d->fieldsTableWidget->setItem(atRow, 1, new QTableWidgetItem(QString())); } - d->fieldsTableWidget->blockSignals (b); + d->fieldsTableWidget->blockSignals(b); // Hack around Qt's failure to redraw these sometimes. - fieldsUpdateVerticalHeader (); + fieldsUpdateVerticalHeader(); - enableFieldsDeleteRowButtonIfShould (); + enableFieldsDeleteRowButtonIfShould(); } // private -void kpDocumentMetaInfoDialog::fieldsAppendEmptyRow () +void kpDocumentMetaInfoDialog::fieldsAppendEmptyRow() { - fieldsAddEmptyRow (d->fieldsTableWidget->rowCount ()); + fieldsAddEmptyRow(d->fieldsTableWidget->rowCount()); } - // private -bool kpDocumentMetaInfoDialog::isFieldsRowDeleteable (int row) const +bool kpDocumentMetaInfoDialog::isFieldsRowDeleteable(int row) const { // Can't delete no row and can't delete last (always blank) row, which // is used to make it easy for the user to add rows without pressing // the "Add" button explicitly. - return (row >= 0 && row < d->fieldsTableWidget->rowCount () - 1); + return row >= 0 && row < d->fieldsTableWidget->rowCount() - 1; } // private -void kpDocumentMetaInfoDialog::fieldsDeleteRow (int r) +void kpDocumentMetaInfoDialog::fieldsDeleteRow(int r) { #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "kpDocumentMetaInfoDialog::fieldsDeleteRow(" - << "row=" << r << ")" - << " currentRow=" << d->fieldsTableWidget->currentRow (); + << "row=" << r << ")" + << " currentRow=" << d->fieldsTableWidget->currentRow(); #endif - Q_ASSERT (isFieldsRowDeleteable (r)); + Q_ASSERT(isFieldsRowDeleteable(r)); - if (r == d->fieldsTableWidget->currentRow ()) - { + if (r == d->fieldsTableWidget->currentRow()) { // Assertion follows from previous assertion. const int newRow = r + 1; #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "\tnewRow=" << newRow; #endif - Q_ASSERT (newRow < d->fieldsTableWidget->rowCount ()); + Q_ASSERT(newRow < d->fieldsTableWidget->rowCount()); - int newCol = d->fieldsTableWidget->currentColumn (); + int newCol = d->fieldsTableWidget->currentColumn(); #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "\tnewCol=" << newCol; #endif - if (newCol != 0 && newCol != 1) - { + if (newCol != 0 && newCol != 1) { newCol = 0; #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "\t\tcorrecting to " << newCol; @@ -603,151 +555,141 @@ // // TODO: This usually results in a redraw error if the scrollbar scrolls // after deleting the 2nd last row. Qt bug. - editCell (newRow, newCol); + editCell(newRow, newCol); } + d->fieldsTableWidget->removeRow(r); - d->fieldsTableWidget->removeRow (r); + fieldsUpdateVerticalHeader(); - - fieldsUpdateVerticalHeader (); - - enableFieldsDeleteRowButtonIfShould (); + enableFieldsDeleteRowButtonIfShould(); } - // private -void kpDocumentMetaInfoDialog::enableFieldsDeleteRowButtonIfShould () +void kpDocumentMetaInfoDialog::enableFieldsDeleteRowButtonIfShould() { #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "kpDocumentMetaInfoDialog::enableFieldsDeleteRowButtonIfShould()"; #endif - const int r = d->fieldsTableWidget->currentRow (); + const int r = d->fieldsTableWidget->currentRow(); #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "\tr=" << r; #endif - d->fieldsDeleteRowButton->setEnabled (isFieldsRowDeleteable (r)); + d->fieldsDeleteRowButton->setEnabled(isFieldsRowDeleteable(r)); } - // private slot -void kpDocumentMetaInfoDialog::slotFieldsCurrentCellChanged (int row, int col, - int oldRow, int oldCol) +void kpDocumentMetaInfoDialog::slotFieldsCurrentCellChanged(int row, int col, int oldRow, + int oldCol) { #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "kpDocumentMetaInfoDialog::slotFieldsCurrentCellChanged(" - << "row=" << row << ",col=" << col - << ",oldRow=" << oldRow << ",oldCol=" << oldCol - << ")" << endl; + << "row=" << row << ",col=" << col + << ",oldRow=" << oldRow << ",oldCol=" << oldCol + << ")" << endl; #endif - (void) row; - (void) col; - (void) oldRow; - (void) oldCol; + (void)row; + (void)col; + (void)oldRow; + (void)oldCol; - enableFieldsDeleteRowButtonIfShould (); + enableFieldsDeleteRowButtonIfShould(); } //--------------------------------------------------------------------- // private slot -void kpDocumentMetaInfoDialog::slotFieldsItemChanged (QTableWidgetItem *it) +void kpDocumentMetaInfoDialog::slotFieldsItemChanged(QTableWidgetItem *it) { #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "kpDocumentMetaInfoDialog::slotFieldsItemChanged(" - << "item=" << it << ") rows=" << d->fieldsTableWidget->rowCount (); + << "item=" << it << ") rows=" << d->fieldsTableWidget->rowCount(); #endif - const int r = d->fieldsTableWidget->row (it); + const int r = d->fieldsTableWidget->row(it); #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "\tr=" << r; #endif - Q_ASSERT (r >= 0 && r < d->fieldsTableWidget->rowCount ()); + Q_ASSERT(r >= 0 && r < d->fieldsTableWidget->rowCount()); - const QString key = d->fieldsTableWidget->item (r, 0)->text (); + const QString key = d->fieldsTableWidget->item(r, 0)->text(); #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << " key='" << key << "'"; #endif - const QString value = d->fieldsTableWidget->item (r, 1)->text (); + const QString value = d->fieldsTableWidget->item(r, 1)->text(); #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << " value='" << value << "'"; #endif // At the last row? - if (r == d->fieldsTableWidget->rowCount () - 1) - { + if (r == d->fieldsTableWidget->rowCount() - 1) { // Typed some text? - if (!key.isEmpty () || !value.isEmpty ()) - { + if (!key.isEmpty() || !value.isEmpty()) { // LOTODO: If we're called due to the cell's text being finalized // as a result of the user pressing the "Add Row" button, // should this really append a row since // slotFieldsAddRowButtonClicked() button is going to add // another one? That's two rows when the user only clicked // that button once! - fieldsAppendEmptyRow (); + fieldsAppendEmptyRow(); } } } //--------------------------------------------------------------------- // private slot -void kpDocumentMetaInfoDialog::slotFieldsAddRowButtonClicked () +void kpDocumentMetaInfoDialog::slotFieldsAddRowButtonClicked() { #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "kpDocumentMetaInfoDialog::slotFieldsAddRowButtonClicked()"; #endif - const int r = d->fieldsTableWidget->currentRow (); + const int r = d->fieldsTableWidget->currentRow(); #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "\tr=" << r; #endif // (if no row is selected, r = -1) - fieldsAddEmptyRow (r + 1); + fieldsAddEmptyRow(r + 1); // Edit the key of this new row (column 0). // No one edits the value first (column 1). - editCell ((r + 1)/*row*/, 0/*col*/); + editCell((r + 1) /*row*/, 0 /*col*/); } //--------------------------------------------------------------------- // private slot -void kpDocumentMetaInfoDialog::slotFieldsDeleteRowButtonClicked () +void kpDocumentMetaInfoDialog::slotFieldsDeleteRowButtonClicked() { #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "kpDocumentMetaInfoDialog::slotFieldsDeleteRowButtonClicked()"; #endif - const int r = d->fieldsTableWidget->currentRow (); + const int r = d->fieldsTableWidget->currentRow(); #if DEBUG_KP_DOCUMENT_META_INFO_DIALOG qCDebug(kpLogDialogs) << "\tr=" << r; #endif - Q_ASSERT (isFieldsRowDeleteable (r)); - fieldsDeleteRow (r); + Q_ASSERT(isFieldsRowDeleteable(r)); + fieldsDeleteRow(r); } - // private slot virtual [base QDialog] -void kpDocumentMetaInfoDialog::accept () +void kpDocumentMetaInfoDialog::accept() { // Validate text fields. QString errorMessage; - (void) metaInfo (&errorMessage); - if (!errorMessage.isEmpty ()) - { - KMessageBox::sorry (this, errorMessage, i18nc ("@title:window", "Invalid Text Fields")); + (void)metaInfo(&errorMessage); + if (!errorMessage.isEmpty()) { + KMessageBox::sorry(this, errorMessage, i18nc("@title:window", "Invalid Text Fields")); return; } - QDialog::accept (); + QDialog::accept(); } - - diff --git a/dialogs/imagelib/transforms/kpTransformPreviewDialog.h b/dialogs/imagelib/transforms/kpTransformPreviewDialog.h --- a/dialogs/imagelib/transforms/kpTransformPreviewDialog.h +++ b/dialogs/imagelib/transforms/kpTransformPreviewDialog.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,27 +24,23 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransformPreviewDialog_H #define kpTransformPreviewDialog_H - #include #include - class QLabel; class QGridLayout; class QGroupBox; class kpDocument; class kpResizeSignallingLabel; class kpTransformDialogEnvironment; - class kpTransformPreviewDialog : public QDialog { -Q_OBJECT + Q_OBJECT public: enum Features @@ -55,69 +50,65 @@ }; // You must call slotUpdate() in your constructor - kpTransformPreviewDialog (Features features, - bool reserveTopRow, - // e.g. "Skew (Image|Selection)" - const QString &caption, - // (in the Dimensions Group Box) e.g. "After Skew:" - const QString &afterActionText, - bool actOnSelection, - kpTransformDialogEnvironment *_env, - QWidget *parent); + kpTransformPreviewDialog (Features features, bool reserveTopRow, + // e.g. "Skew (Image|Selection)" + const QString &caption, + // (in the Dimensions Group Box) e.g. "After Skew:" + const QString &afterActionText, bool actOnSelection, + kpTransformDialogEnvironment *_env, QWidget *parent); ~kpTransformPreviewDialog () override; private: - void createDimensionsGroupBox (); - void createPreviewGroupBox (); + void createDimensionsGroupBox(); + void createPreviewGroupBox(); public: - virtual bool isNoOp () const = 0; + virtual bool isNoOp() const = 0; protected: - kpDocument *document () const; + kpDocument *document() const; - QWidget *mainWidget () const; + QWidget *mainWidget() const; // All widgets must have mainWidget() as their parent - void addCustomWidgetToFront (QWidget *w); // see in ctor - void addCustomWidget (QWidget *w); - void addCustomWidgetToBack (QWidget *w) + void addCustomWidgetToFront(QWidget *w); // see in ctor + void addCustomWidget(QWidget *w); + void addCustomWidgetToBack(QWidget *w) { - addCustomWidget (w); + addCustomWidget(w); } - virtual QSize newDimensions () const = 0; - virtual QImage transformPixmap (const QImage &pixmap, - int targetWidth, int targetHeight) const = 0; + virtual QSize newDimensions() const = 0; + virtual QImage transformPixmap(const QImage &pixmap, int targetWidth, + int targetHeight) const = 0; public: // Use to avoid excessive, expensive preview pixmap label recalcuations, // during init and widget relayouts. // // Setting to true automatically calls slotUpdateWithWaitCursor(). // // WARNING: This overrides a non-virtual method in QWidget. - void setUpdatesEnabled (bool enable); + void setUpdatesEnabled(bool enable); private: - void updateDimensions (); + void updateDimensions(); public: - static double aspectScale (int newWidth, int newHeight, - int oldWidth, int oldHeight); - static int scaleDimension (int dimension, double scale, int min, int max); + static double aspectScale(int newWidth, int newHeight, int oldWidth, int oldHeight); + static int scaleDimension(int dimension, double scale, int min, int max); private: - void updateShrunkenDocumentPixmap (); + void updateShrunkenDocumentPixmap(); protected slots: - void updatePreview (); + void updatePreview(); // Call this whenever a value (e.g. an angle) changes // and the Dimensions & Preview need to be updated - virtual void slotUpdate (); + virtual void slotUpdate(); - virtual void slotUpdateWithWaitCursor (); + virtual void slotUpdateWithWaitCursor(); protected: // REFACTOR: Use d-ptr @@ -141,5 +132,4 @@ kpTransformDialogEnvironment *m_environ; }; - #endif // kpTransformPreviewDialog_H diff --git a/dialogs/imagelib/transforms/kpTransformPreviewDialog.cpp b/dialogs/imagelib/transforms/kpTransformPreviewDialog.cpp --- a/dialogs/imagelib/transforms/kpTransformPreviewDialog.cpp +++ b/dialogs/imagelib/transforms/kpTransformPreviewDialog.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TRANSFORM_PREVIEW_DIALOG 0 - #include "dialogs/imagelib/transforms/kpTransformPreviewDialog.h" #include @@ -51,302 +48,272 @@ #include "generic/widgets/kpResizeSignallingLabel.h" #include "environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.h" - -kpTransformPreviewDialog::kpTransformPreviewDialog (Features features, - bool reserveTopRow, - const QString &caption, - const QString &afterActionText, - bool actOnSelection, - kpTransformDialogEnvironment *_env, - QWidget *parent) - : QDialog (parent), - m_afterActionText (afterActionText), - m_actOnSelection (actOnSelection), - m_dimensionsGroupBox (nullptr), - m_afterTransformDimensionsLabel (nullptr), - m_previewGroupBox (nullptr), - m_previewPixmapLabel (nullptr), - m_gridLayout (nullptr), - m_environ (_env) +kpTransformPreviewDialog::kpTransformPreviewDialog (Features features, bool reserveTopRow, + const QString &caption, + const QString &afterActionText, + bool actOnSelection, + kpTransformDialogEnvironment *_env, + QWidget *parent) + : QDialog(parent) + , m_afterActionText(afterActionText) + , m_actOnSelection(actOnSelection) + , m_dimensionsGroupBox(nullptr) + , m_afterTransformDimensionsLabel(nullptr) + , m_previewGroupBox(nullptr) + , m_previewPixmapLabel(nullptr) + , m_gridLayout(nullptr) + , m_environ(_env) { - setWindowTitle (caption); - QDialogButtonBox *buttons = new QDialogButtonBox (QDialogButtonBox::Ok | - QDialogButtonBox::Cancel, this); - connect (buttons, &QDialogButtonBox::accepted, this, &kpTransformPreviewDialog::accept); - connect (buttons, &QDialogButtonBox::rejected, this, &kpTransformPreviewDialog::reject); + setWindowTitle(caption); + QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok + |QDialogButtonBox::Cancel, this); + connect(buttons, &QDialogButtonBox::accepted, this, &kpTransformPreviewDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, this, &kpTransformPreviewDialog::reject); - QWidget *baseWidget = new QWidget (this); + QWidget *baseWidget = new QWidget(this); m_mainWidget = baseWidget; - auto *dialogLayout = new QVBoxLayout (this); - dialogLayout->addWidget (baseWidget); - dialogLayout->addWidget (buttons); + auto *dialogLayout = new QVBoxLayout(this); + dialogLayout->addWidget(baseWidget); + dialogLayout->addWidget(buttons); - - if (document ()) - { - m_oldWidth = document ()->width (actOnSelection); - m_oldHeight = document ()->height (actOnSelection); - } - else - { + if (document()) { + m_oldWidth = document()->width(actOnSelection); + m_oldHeight = document()->height(actOnSelection); + } else { m_oldWidth = m_oldHeight = 1; } - if (features & Dimensions) { - createDimensionsGroupBox (); + createDimensionsGroupBox(); } if (features & Preview) { - createPreviewGroupBox (); + createPreviewGroupBox(); } - - m_gridLayout = new QGridLayout (baseWidget ); + m_gridLayout = new QGridLayout(baseWidget); m_gridLayout->setContentsMargins(0, 0, 0, 0); m_gridNumRows = reserveTopRow ? 1 : 0; - if (m_dimensionsGroupBox || m_previewGroupBox) - { - if (m_dimensionsGroupBox && m_previewGroupBox) - { - m_gridLayout->addWidget (m_dimensionsGroupBox, m_gridNumRows, 0); - m_gridLayout->addWidget (m_previewGroupBox, m_gridNumRows, 1); - - m_gridLayout->setColumnStretch (1, 1); - } - else if (m_dimensionsGroupBox) - { - m_gridLayout->addWidget (m_dimensionsGroupBox, - m_gridNumRows, 0, 1, 2); - } - else if (m_previewGroupBox) - { - m_gridLayout->addWidget (m_previewGroupBox, - m_gridNumRows, 0, 1, 2); + if (m_dimensionsGroupBox || m_previewGroupBox) { + if (m_dimensionsGroupBox && m_previewGroupBox) { + m_gridLayout->addWidget(m_dimensionsGroupBox, m_gridNumRows, 0); + m_gridLayout->addWidget(m_previewGroupBox, m_gridNumRows, 1); + + m_gridLayout->setColumnStretch(1, 1); + } else if (m_dimensionsGroupBox) { + m_gridLayout->addWidget(m_dimensionsGroupBox, + m_gridNumRows, 0, 1, 2); + } else if (m_previewGroupBox) { + m_gridLayout->addWidget(m_previewGroupBox, + m_gridNumRows, 0, 1, 2); } - m_gridLayout->setRowStretch (m_gridNumRows, 1); + m_gridLayout->setRowStretch(m_gridNumRows, 1); m_gridNumRows++; } } kpTransformPreviewDialog::~kpTransformPreviewDialog () = default; - // private -void kpTransformPreviewDialog::createDimensionsGroupBox () +void kpTransformPreviewDialog::createDimensionsGroupBox() { - m_dimensionsGroupBox = new QGroupBox (i18n ("Dimensions"), mainWidget ()); + m_dimensionsGroupBox = new QGroupBox(i18n("Dimensions"), mainWidget()); - auto *originalLabel = new QLabel (i18n ("Original:"), m_dimensionsGroupBox); + auto *originalLabel = new QLabel(i18n("Original:"), m_dimensionsGroupBox); QString originalDimensions; - if (document ()) - { - originalDimensions = i18n ("%1 x %2", - m_oldWidth, - m_oldHeight); - - // Stop the Dimensions Group Box from resizing so often - const QString minimumLengthString (QStringLiteral("100000 x 100000")); - const int padLength = minimumLengthString.length (); - for (int i = originalDimensions.length (); i < padLength; i++) { - originalDimensions += ' '; - } + if (document()) { + originalDimensions = i18n("%1 x %2", + m_oldWidth, + m_oldHeight); + + // Stop the Dimensions Group Box from resizing so often + const QString minimumLengthString(QStringLiteral("100000 x 100000")); + const int padLength = minimumLengthString.length(); + for (int i = originalDimensions.length(); i < padLength; i++) { + originalDimensions += ' '; + } } - auto *originalDimensionsLabel = new QLabel (originalDimensions, m_dimensionsGroupBox); - - auto *afterTransformLabel = new QLabel (m_afterActionText, m_dimensionsGroupBox); - m_afterTransformDimensionsLabel = new QLabel (m_dimensionsGroupBox); + auto *originalDimensionsLabel = new QLabel(originalDimensions, m_dimensionsGroupBox); + auto *afterTransformLabel = new QLabel(m_afterActionText, m_dimensionsGroupBox); + m_afterTransformDimensionsLabel = new QLabel(m_dimensionsGroupBox); - auto *dimensionsLayout = new QGridLayout (m_dimensionsGroupBox ); - dimensionsLayout->addWidget (originalLabel, 0, 0, Qt::AlignBottom); - dimensionsLayout->addWidget (originalDimensionsLabel, 0, 1, Qt::AlignBottom); - dimensionsLayout->addWidget (afterTransformLabel, 1, 0, Qt::AlignTop); - dimensionsLayout->addWidget (m_afterTransformDimensionsLabel, 1, 1, Qt::AlignTop); + auto *dimensionsLayout = new QGridLayout(m_dimensionsGroupBox); + dimensionsLayout->addWidget(originalLabel, 0, 0, Qt::AlignBottom); + dimensionsLayout->addWidget(originalDimensionsLabel, 0, 1, Qt::AlignBottom); + dimensionsLayout->addWidget(afterTransformLabel, 1, 0, Qt::AlignTop); + dimensionsLayout->addWidget(m_afterTransformDimensionsLabel, 1, 1, Qt::AlignTop); } // private -void kpTransformPreviewDialog::createPreviewGroupBox () +void kpTransformPreviewDialog::createPreviewGroupBox() { - m_previewGroupBox = new QGroupBox (i18n ("Preview"), mainWidget ()); - - m_previewPixmapLabel = new kpResizeSignallingLabel (m_previewGroupBox); - m_previewPixmapLabel->setMinimumSize (150, 110); - connect (m_previewPixmapLabel, &kpResizeSignallingLabel::resized, - this, &kpTransformPreviewDialog::updatePreview); + m_previewGroupBox = new QGroupBox(i18n("Preview"), mainWidget()); - QPushButton *updatePushButton = new QPushButton (i18n ("&Update"), - m_previewGroupBox); - connect (updatePushButton, &QPushButton::clicked, - this, &kpTransformPreviewDialog::slotUpdateWithWaitCursor); + m_previewPixmapLabel = new kpResizeSignallingLabel(m_previewGroupBox); + m_previewPixmapLabel->setMinimumSize(150, 110); + connect(m_previewPixmapLabel, &kpResizeSignallingLabel::resized, + this, &kpTransformPreviewDialog::updatePreview); + QPushButton *updatePushButton = new QPushButton(i18n("&Update"), + m_previewGroupBox); + connect(updatePushButton, &QPushButton::clicked, + this, &kpTransformPreviewDialog::slotUpdateWithWaitCursor); - auto *previewLayout = new QVBoxLayout (m_previewGroupBox); - previewLayout->addWidget (m_previewPixmapLabel, 1/*stretch*/); - previewLayout->addWidget (updatePushButton, 0/*stretch*/, Qt::AlignHCenter); + auto *previewLayout = new QVBoxLayout(m_previewGroupBox); + previewLayout->addWidget(m_previewPixmapLabel, 1 /*stretch*/); + previewLayout->addWidget(updatePushButton, 0 /*stretch*/, Qt::AlignHCenter); } - // protected -kpDocument *kpTransformPreviewDialog::document () const +kpDocument *kpTransformPreviewDialog::document() const { - return m_environ->document (); + return m_environ->document(); } // protected -QWidget *kpTransformPreviewDialog::mainWidget () const +QWidget *kpTransformPreviewDialog::mainWidget() const { return m_mainWidget; } // protected -void kpTransformPreviewDialog::addCustomWidgetToFront (QWidget *w) +void kpTransformPreviewDialog::addCustomWidgetToFront(QWidget *w) { - m_gridLayout->addWidget (w, 0, 0, 1, 2); + m_gridLayout->addWidget(w, 0, 0, 1, 2); } // protected -void kpTransformPreviewDialog::addCustomWidget (QWidget *w) +void kpTransformPreviewDialog::addCustomWidget(QWidget *w) { - m_gridLayout->addWidget (w, m_gridNumRows, 0, 1, 2); + m_gridLayout->addWidget(w, m_gridNumRows, 0, 1, 2); m_gridNumRows++; } - // public override [base QWidget] -void kpTransformPreviewDialog::setUpdatesEnabled (bool enable) +void kpTransformPreviewDialog::setUpdatesEnabled(bool enable) { - QDialog::setUpdatesEnabled (enable); + QDialog::setUpdatesEnabled(enable); if (enable) { - slotUpdateWithWaitCursor (); + slotUpdateWithWaitCursor(); } } - // private -void kpTransformPreviewDialog::updateDimensions () +void kpTransformPreviewDialog::updateDimensions() { if (!m_dimensionsGroupBox) { return; } - kpDocument *doc = document (); + kpDocument *doc = document(); if (!doc) { return; } - if (!updatesEnabled ()) - { + if (!updatesEnabled()) { #if DEBUG_KP_TRANSFORM_PREVIEW_DIALOG qCDebug(kpLogDialogs) << "updates not enabled - aborting"; #endif return; } - QSize newDim = newDimensions (); + QSize newDim = newDimensions(); #if DEBUG_KP_TRANSFORM_PREVIEW_DIALOG qCDebug(kpLogDialogs) << "kpTransformPreviewDialog::updateDimensions(): newDim=" << newDim; #endif - QString newDimString = i18n ("%1 x %2", - newDim.width (), - newDim.height ()); - m_afterTransformDimensionsLabel->setText (newDimString); + QString newDimString = i18n("%1 x %2", + newDim.width(), + newDim.height()); + m_afterTransformDimensionsLabel->setText(newDimString); } - // public static -double kpTransformPreviewDialog::aspectScale (int newWidth, int newHeight, - int oldWidth, int oldHeight) +double kpTransformPreviewDialog::aspectScale(int newWidth, int newHeight, int oldWidth, + int oldHeight) { - double widthScale = double (newWidth) / double (oldWidth); - double heightScale = double (newHeight) / double (oldHeight); + double widthScale = double(newWidth) / double(oldWidth); + double heightScale = double(newHeight) / double(oldHeight); // Keeps aspect ratio - return qMin (widthScale, heightScale); + return qMin(widthScale, heightScale); } // public static -int kpTransformPreviewDialog::scaleDimension (int dimension, double scale, int min, int max) +int kpTransformPreviewDialog::scaleDimension(int dimension, double scale, int min, int max) { - return qMax (min, - qMin (max, - qRound (dimension * scale))); + return qMax(min, + qMin(max, + qRound(dimension * scale))); } - // private -void kpTransformPreviewDialog::updateShrunkenDocumentPixmap () +void kpTransformPreviewDialog::updateShrunkenDocumentPixmap() { #if DEBUG_KP_TRANSFORM_PREVIEW_DIALOG qCDebug(kpLogDialogs) << "kpTransformPreviewDialog::updateShrunkenDocumentPixmap()" - << " shrunkenDocPixmap.size=" - << m_shrunkenDocumentPixmap.size () - << " previewPixmapLabelSizeWhenUpdatedPixmap=" - << m_previewPixmapLabelSizeWhenUpdatedPixmap - << " previewPixmapLabel.size=" - << m_previewPixmapLabel->size () - << endl; + << " shrunkenDocPixmap.size=" + << m_shrunkenDocumentPixmap.size() + << " previewPixmapLabelSizeWhenUpdatedPixmap=" + << m_previewPixmapLabelSizeWhenUpdatedPixmap + << " previewPixmapLabel.size=" + << m_previewPixmapLabel->size() + << endl; #endif if (!m_previewGroupBox) { return; } + kpDocument *doc = document(); + Q_ASSERT(doc && !doc->image().isNull()); - kpDocument *doc = document (); - Q_ASSERT (doc && !doc->image ().isNull ()); - - if (m_shrunkenDocumentPixmap.isNull () || - m_previewPixmapLabel->size () != m_previewPixmapLabelSizeWhenUpdatedPixmap) - { + if (m_shrunkenDocumentPixmap.isNull() + || m_previewPixmapLabel->size() != m_previewPixmapLabelSizeWhenUpdatedPixmap) { #if DEBUG_KP_TRANSFORM_PREVIEW_DIALOG qCDebug(kpLogDialogs) << "\tupdating shrunkenDocPixmap"; #endif // TODO: Why the need to keep aspect ratio here? // Isn't scaling the skewed result maintaining aspect enough? - double keepsAspectScale = aspectScale (m_previewPixmapLabel->width (), - m_previewPixmapLabel->height (), - m_oldWidth, - m_oldHeight); + double keepsAspectScale = aspectScale(m_previewPixmapLabel->width(), + m_previewPixmapLabel->height(), + m_oldWidth, + m_oldHeight); kpImage image; - if (m_actOnSelection) - { - kpAbstractImageSelection *sel = doc->imageSelection ()->clone (); - if (!sel->hasContent ()) { - sel->setBaseImage (doc->getSelectedBaseImage ()); + if (m_actOnSelection) { + kpAbstractImageSelection *sel = doc->imageSelection()->clone(); + if (!sel->hasContent()) { + sel->setBaseImage(doc->getSelectedBaseImage()); } - image = sel->transparentImage (); + image = sel->transparentImage(); delete sel; - } - else - { - image = doc->image (); + } else { + image = doc->image(); } - m_shrunkenDocumentPixmap = kpPixmapFX::scale ( + m_shrunkenDocumentPixmap = kpPixmapFX::scale( image, - scaleDimension (m_oldWidth, - keepsAspectScale, - 1, m_previewPixmapLabel->width ()), - scaleDimension (m_oldHeight, - keepsAspectScale, - 1, m_previewPixmapLabel->height ())); - - m_previewPixmapLabelSizeWhenUpdatedPixmap = m_previewPixmapLabel->size (); + scaleDimension(m_oldWidth, + keepsAspectScale, + 1, m_previewPixmapLabel->width()), + scaleDimension(m_oldHeight, + keepsAspectScale, + 1, m_previewPixmapLabel->height())); + + m_previewPixmapLabelSizeWhenUpdatedPixmap = m_previewPixmapLabel->size(); } } - // private -void kpTransformPreviewDialog::updatePreview () +void kpTransformPreviewDialog::updatePreview() { #if DEBUG_KP_TRANSFORM_PREVIEW_DIALOG qCDebug(kpLogDialogs) << "kpTransformPreviewDialog::updatePreview()"; @@ -356,113 +323,105 @@ return; } - - kpDocument *doc = document (); + kpDocument *doc = document(); if (!doc) { return; } - - if (!updatesEnabled ()) - { + if (!updatesEnabled()) { #if DEBUG_KP_TRANSFORM_PREVIEW_DIALOG qCDebug(kpLogDialogs) << "updates not enabled - aborting"; #endif return; } + updateShrunkenDocumentPixmap(); - updateShrunkenDocumentPixmap (); - - if (!m_shrunkenDocumentPixmap.isNull ()) - { - QSize newDim = newDimensions (); - double keepsAspectScale = aspectScale (m_previewPixmapLabel->width (), - m_previewPixmapLabel->height (), - newDim.width (), - newDim.height ()); + if (!m_shrunkenDocumentPixmap.isNull()) { + QSize newDim = newDimensions(); + double keepsAspectScale = aspectScale(m_previewPixmapLabel->width(), + m_previewPixmapLabel->height(), + newDim.width(), + newDim.height()); - int targetWidth = scaleDimension (newDim.width (), + int targetWidth = scaleDimension(newDim.width(), + keepsAspectScale, + 1, // min + m_previewPixmapLabel->width()); // max + int targetHeight = scaleDimension(newDim.height(), keepsAspectScale, - 1, // min - m_previewPixmapLabel->width ()); // max - int targetHeight = scaleDimension (newDim.height (), - keepsAspectScale, - 1, // min - m_previewPixmapLabel->height ()); // max + 1, // min + m_previewPixmapLabel->height()); // max // TODO: Some effects work directly on QImage; so could cache the // QImage so that transformPixmap() is faster - QImage transformedShrunkenDocumentPixmap = - transformPixmap (m_shrunkenDocumentPixmap, targetWidth, targetHeight); + QImage transformedShrunkenDocumentPixmap + = transformPixmap(m_shrunkenDocumentPixmap, targetWidth, targetHeight); - QImage previewPixmap (m_previewPixmapLabel->width (), - m_previewPixmapLabel->height (), QImage::Format_ARGB32_Premultiplied); + QImage previewPixmap(m_previewPixmapLabel->width(), + m_previewPixmapLabel->height(), QImage::Format_ARGB32_Premultiplied); previewPixmap.fill(QColor(Qt::transparent).rgba()); - kpPixmapFX::setPixmapAt (&previewPixmap, - (previewPixmap.width () - transformedShrunkenDocumentPixmap.width ()) / 2, - (previewPixmap.height () - transformedShrunkenDocumentPixmap.height ()) / 2, - transformedShrunkenDocumentPixmap); + kpPixmapFX::setPixmapAt(&previewPixmap, + (previewPixmap.width() - transformedShrunkenDocumentPixmap.width()) / 2, + (previewPixmap.height() - transformedShrunkenDocumentPixmap.height()) / 2, + transformedShrunkenDocumentPixmap); #if DEBUG_KP_TRANSFORM_PREVIEW_DIALOG - qCDebug(kpLogDialogs) << "kpTransformPreviewDialog::updatePreview ():" - << " shrunkenDocumentPixmap: w=" - << m_shrunkenDocumentPixmap.width () - << " h=" - << m_shrunkenDocumentPixmap.height () - << " previewPixmapLabel: w=" - << m_previewPixmapLabel->width () - << " h=" - << m_previewPixmapLabel->height () - << " transformedShrunkenDocumentPixmap: w=" - << transformedShrunkenDocumentPixmap.width () - << " h=" - << transformedShrunkenDocumentPixmap.height () - << " previewPixmap: w=" - << previewPixmap.width () - << " h=" - << previewPixmap.height () - << endl; + qCDebug(kpLogDialogs) << "kpTransformPreviewDialog::updatePreview ():" + << " shrunkenDocumentPixmap: w=" + << m_shrunkenDocumentPixmap.width() + << " h=" + << m_shrunkenDocumentPixmap.height() + << " previewPixmapLabel: w=" + << m_previewPixmapLabel->width() + << " h=" + << m_previewPixmapLabel->height() + << " transformedShrunkenDocumentPixmap: w=" + << transformedShrunkenDocumentPixmap.width() + << " h=" + << transformedShrunkenDocumentPixmap.height() + << " previewPixmap: w=" + << previewPixmap.width() + << " h=" + << previewPixmap.height() + << endl; #endif - m_previewPixmapLabel->setPixmap (QPixmap::fromImage(previewPixmap)); + m_previewPixmapLabel->setPixmap(QPixmap::fromImage(previewPixmap)); // immediate update esp. for expensive previews - m_previewPixmapLabel->repaint (); + m_previewPixmapLabel->repaint(); #if DEBUG_KP_TRANSFORM_PREVIEW_DIALOG - qCDebug(kpLogDialogs) << "\tafter QLabel::setPixmap() previewPixmapLabel: w=" - << m_previewPixmapLabel->width () - << " h=" - << m_previewPixmapLabel->height () - << endl; + qCDebug(kpLogDialogs) << "\tafter QLabel::setPixmap() previewPixmapLabel: w=" + << m_previewPixmapLabel->width() + << " h=" + << m_previewPixmapLabel->height() + << endl; #endif } } - // protected slot virtual -void kpTransformPreviewDialog::slotUpdate () +void kpTransformPreviewDialog::slotUpdate() { #if DEBUG_KP_TRANSFORM_PREVIEW_DIALOG qCDebug(kpLogDialogs) << "kpTransformPreviewDialog::slotUpdate()"; #endif - updateDimensions (); - updatePreview (); + updateDimensions(); + updatePreview(); } // protected slot virtual -void kpTransformPreviewDialog::slotUpdateWithWaitCursor () +void kpTransformPreviewDialog::slotUpdateWithWaitCursor() { #if DEBUG_KP_TRANSFORM_PREVIEW_DIALOG qCDebug(kpLogDialogs) << "kpTransformPreviewDialog::slotUpdateWithWaitCursor()"; #endif - QApplication::setOverrideCursor (Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); - slotUpdate (); + slotUpdate(); - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } - - diff --git a/dialogs/imagelib/transforms/kpTransformResizeScaleDialog.h b/dialogs/imagelib/transforms/kpTransformResizeScaleDialog.h --- a/dialogs/imagelib/transforms/kpTransformResizeScaleDialog.h +++ b/dialogs/imagelib/transforms/kpTransformResizeScaleDialog.h @@ -25,16 +25,14 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransformResizeScaleDialog_H #define kpTransformResizeScaleDialog_H #include #include "imagelib/kpColor.h" #include "commands/imagelib/transforms/kpTransformResizeScaleCommand.h" - class QCheckBox; class QComboBox; class QGroupBox; @@ -47,59 +45,58 @@ class kpTextSelection; class kpTransformDialogEnvironment; - class kpTransformResizeScaleDialog : public QDialog { -Q_OBJECT + Q_OBJECT - public: +public: kpTransformResizeScaleDialog(kpTransformDialogEnvironment *_env, QWidget *parent); enum ActOn { Image, Selection }; - int imageWidth () const; - int imageHeight () const; - bool actOnSelection () const; - kpTransformResizeScaleCommand::Type type () const; + int imageWidth() const; + int imageHeight() const; + bool actOnSelection() const; + kpTransformResizeScaleCommand::Type type() const; - bool isNoOp () const; + bool isNoOp() const; - public slots: - void slotActOnChanged (); - void slotTypeChanged (); +public slots: + void slotActOnChanged(); + void slotTypeChanged(); - void slotWidthChanged (int width); - void slotHeightChanged (int height); + void slotWidthChanged(int width); + void slotHeightChanged(int height); - void slotPercentWidthChanged (double percentWidth); - void slotPercentHeightChanged (double percentHeight); + void slotPercentWidthChanged(double percentWidth); + void slotPercentHeightChanged(double percentHeight); - private: - kpDocument *document () const; - kpAbstractSelection *selection () const; - kpTextSelection *textSelection () const; +private: + kpDocument *document() const; + kpAbstractSelection *selection() const; + kpTextSelection *textSelection() const; QWidget *createActOnBox(QWidget *baseWidget); QGroupBox *createOperationGroupBox(QWidget *baseWidget); QGroupBox *createDimensionsGroupBox(QWidget *baseWidget); - void widthFitHeightToAspectRatio (); - void heightFitWidthToAspectRatio (); + void widthFitHeightToAspectRatio(); + void heightFitWidthToAspectRatio(); - bool resizeEnabled () const; - bool scaleEnabled () const; - bool smoothScaleEnabled () const; - int originalWidth () const; - int originalHeight () const; + bool resizeEnabled() const; + bool scaleEnabled() const; + bool smoothScaleEnabled() const; + int originalWidth() const; + int originalHeight() const; - private slots: +private slots: void accept() override; void setKeepAspectRatio(bool on); - private: +private: kpTransformDialogEnvironment *m_environ; QComboBox *m_actOnCombo; @@ -118,5 +115,4 @@ kpTransformResizeScaleCommand::Type m_lastType; }; - #endif // kpTransformResizeScaleDialog_H diff --git a/dialogs/imagelib/transforms/kpTransformResizeScaleDialog.cpp b/dialogs/imagelib/transforms/kpTransformResizeScaleDialog.cpp --- a/dialogs/imagelib/transforms/kpTransformResizeScaleDialog.cpp +++ b/dialogs/imagelib/transforms/kpTransformResizeScaleDialog.cpp @@ -25,13 +25,10 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_RESIZE_SCALE_DIALOG 0 - #include "kpTransformResizeScaleDialog.h" - #include #include #include @@ -68,206 +65,198 @@ //--------------------------------------------------------------------- -#define SET_VALUE_WITHOUT_SIGNAL_EMISSION(knuminput_instance,value) \ -{ \ - knuminput_instance->blockSignals (true); \ - knuminput_instance->setValue (value); \ - knuminput_instance->blockSignals (false); \ -} +#define SET_VALUE_WITHOUT_SIGNAL_EMISSION(knuminput_instance, value) \ + { \ + knuminput_instance->blockSignals(true); \ + knuminput_instance->setValue(value); \ + knuminput_instance->blockSignals(false); \ + } #define IGNORE_KEEP_ASPECT_RATIO(cmd) \ -{ \ - m_ignoreKeepAspectRatio++; \ - cmd; \ - m_ignoreKeepAspectRatio--; \ -} + { \ + m_ignoreKeepAspectRatio++; \ + cmd; \ + m_ignoreKeepAspectRatio--; \ + } //--------------------------------------------------------------------- kpTransformResizeScaleDialog::kpTransformResizeScaleDialog ( - kpTransformDialogEnvironment *_env, QWidget *parent) - : QDialog (parent), - m_environ (_env), - m_ignoreKeepAspectRatio (0), - m_lastType(kpTransformResizeScaleCommand::Resize) + kpTransformDialogEnvironment *_env, QWidget *parent) + : QDialog(parent) + , m_environ(_env) + , m_ignoreKeepAspectRatio(0) + , m_lastType(kpTransformResizeScaleCommand::Resize) { - setWindowTitle (i18nc ("@title:window", "Resize / Scale")); - QDialogButtonBox *buttons = new QDialogButtonBox (QDialogButtonBox::Ok | - QDialogButtonBox::Cancel, this); - connect (buttons, &QDialogButtonBox::accepted, this, &kpTransformResizeScaleDialog::accept); - connect (buttons, &QDialogButtonBox::rejected, this, &kpTransformResizeScaleDialog::reject); + setWindowTitle(i18nc("@title:window", "Resize / Scale")); + QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok + |QDialogButtonBox::Cancel, this); + connect(buttons, &QDialogButtonBox::accepted, this, &kpTransformResizeScaleDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, this, &kpTransformResizeScaleDialog::reject); - QWidget *baseWidget = new QWidget (this); + QWidget *baseWidget = new QWidget(this); - auto *dialogLayout = new QVBoxLayout (this); - dialogLayout->addWidget (baseWidget); - dialogLayout->addWidget (buttons); + auto *dialogLayout = new QVBoxLayout(this); + dialogLayout->addWidget(baseWidget); + dialogLayout->addWidget(buttons); QWidget *actOnBox = createActOnBox(baseWidget); QGroupBox *operationGroupBox = createOperationGroupBox(baseWidget); QGroupBox *dimensionsGroupBox = createDimensionsGroupBox(baseWidget); - auto *baseLayout = new QVBoxLayout (baseWidget); + auto *baseLayout = new QVBoxLayout(baseWidget); baseLayout->setContentsMargins(0, 0, 0, 0); baseLayout->addWidget(actOnBox); baseLayout->addWidget(operationGroupBox); baseLayout->addWidget(dimensionsGroupBox); KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); setKeepAspectRatio(cfg.readEntry(kpSettingResizeScaleLastKeepAspect, false)); m_lastType = static_cast - (cfg.readEntry(kpSettingResizeScaleScaleType, - static_cast(kpTransformResizeScaleCommand::Resize))); + (cfg.readEntry(kpSettingResizeScaleScaleType, + static_cast(kpTransformResizeScaleCommand::Resize))); - slotActOnChanged (); + slotActOnChanged(); - m_newWidthInput->setFocus (); + m_newWidthInput->setFocus(); //enableButtonOk (!isNoOp ()); } //--------------------------------------------------------------------- // private -kpDocument *kpTransformResizeScaleDialog::document () const +kpDocument *kpTransformResizeScaleDialog::document() const { - return m_environ->document (); + return m_environ->document(); } //--------------------------------------------------------------------- // private -kpAbstractSelection *kpTransformResizeScaleDialog::selection () const +kpAbstractSelection *kpTransformResizeScaleDialog::selection() const { - Q_ASSERT (document ()); - return document ()->selection (); + Q_ASSERT(document()); + return document()->selection(); } //--------------------------------------------------------------------- // private -kpTextSelection *kpTransformResizeScaleDialog::textSelection () const +kpTextSelection *kpTransformResizeScaleDialog::textSelection() const { - Q_ASSERT (document ()); - return document ()->textSelection (); + Q_ASSERT(document()); + return document()->textSelection(); } //--------------------------------------------------------------------- // private QWidget *kpTransformResizeScaleDialog::createActOnBox(QWidget *baseWidget) { - QWidget *actOnBox = new QWidget (baseWidget); - - - auto *actOnLabel = new QLabel (i18n ("Ac&t on:"), actOnBox); - m_actOnCombo = new QComboBox (actOnBox); + QWidget *actOnBox = new QWidget(baseWidget); + auto *actOnLabel = new QLabel(i18n("Ac&t on:"), actOnBox); + m_actOnCombo = new QComboBox(actOnBox); - actOnLabel->setBuddy (m_actOnCombo); + actOnLabel->setBuddy(m_actOnCombo); - m_actOnCombo->insertItem (Image, i18n ("Entire Image")); - if (selection ()) - { - QString selName = i18n ("Selection"); + m_actOnCombo->insertItem(Image, i18n("Entire Image")); + if (selection()) { + QString selName = i18n("Selection"); - if (textSelection ()) { - selName = i18n ("Text Box"); + if (textSelection()) { + selName = i18n("Text Box"); } - m_actOnCombo->insertItem (Selection, selName); - m_actOnCombo->setCurrentIndex (Selection); - } - else - { - actOnLabel->setEnabled (false); - m_actOnCombo->setEnabled (false); + m_actOnCombo->insertItem(Selection, selName); + m_actOnCombo->setCurrentIndex(Selection); + } else { + actOnLabel->setEnabled(false); + m_actOnCombo->setEnabled(false); } - auto *lay = new QHBoxLayout (actOnBox); + auto *lay = new QHBoxLayout(actOnBox); lay->setContentsMargins(0, 0, 0, 0); - lay->addWidget (actOnLabel); - lay->addWidget (m_actOnCombo, 1); + lay->addWidget(actOnLabel); + lay->addWidget(m_actOnCombo, 1); - connect (m_actOnCombo, static_cast(&QComboBox::activated), - this, &kpTransformResizeScaleDialog::slotActOnChanged); + connect(m_actOnCombo, static_cast(&QComboBox::activated), + this, &kpTransformResizeScaleDialog::slotActOnChanged); return actOnBox; } //--------------------------------------------------------------------- -static void toolButtonSetLook (QToolButton *button, - const QString &iconName, - const QString &name) +static void toolButtonSetLook(QToolButton *button, const QString &iconName, const QString &name) { - QPixmap icon = UserIcon (iconName); - button->setIconSize (QSize (icon.width (), icon.height ())); - button->setIcon (icon); - - button->setToolButtonStyle (Qt::ToolButtonTextUnderIcon); - button->setText (name); - button->setFocusPolicy (Qt::StrongFocus); - button->setCheckable (true); + QPixmap icon = UserIcon(iconName); + button->setIconSize(QSize(icon.width(), icon.height())); + button->setIcon(icon); + + button->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + button->setText(name); + button->setFocusPolicy(Qt::StrongFocus); + button->setCheckable(true); } //--------------------------------------------------------------------- // private -QGroupBox *kpTransformResizeScaleDialog::createOperationGroupBox (QWidget *baseWidget) +QGroupBox *kpTransformResizeScaleDialog::createOperationGroupBox(QWidget *baseWidget) { - QGroupBox *operationGroupBox = new QGroupBox (i18n ("Operation"), baseWidget); + QGroupBox *operationGroupBox = new QGroupBox(i18n("Operation"), baseWidget); operationGroupBox->setWhatsThis( - i18n ("" - "
    " - "
  • Resize: The size of the picture will be" - " increased" - " by creating new areas to the right and/or bottom" - " (filled in with the background color) or" - " decreased by cutting" - " it at the right and/or bottom.
  • " - - "
  • Scale: The picture will be expanded" - " by duplicating pixels or squashed by dropping pixels.
  • " - - "
  • Smooth Scale: This is the same as" - " Scale except that it blends neighboring" - " pixels to produce a smoother looking picture.
  • " - "
" - "
")); - - m_resizeButton = new QToolButton (operationGroupBox); - toolButtonSetLook (m_resizeButton, - QStringLiteral ("resize"), - i18n ("&Resize")); - - m_scaleButton = new QToolButton (operationGroupBox); - toolButtonSetLook (m_scaleButton, - QStringLiteral ("scale"), - i18n ("&Scale")); - - m_smoothScaleButton = new QToolButton (operationGroupBox); - toolButtonSetLook (m_smoothScaleButton, - QStringLiteral ("smooth_scale"), - i18n ("S&mooth Scale")); - - auto *resizeScaleButtonGroup = new QButtonGroup (baseWidget); - resizeScaleButtonGroup->addButton (m_resizeButton); - resizeScaleButtonGroup->addButton (m_scaleButton); - resizeScaleButtonGroup->addButton (m_smoothScaleButton); - - - auto *operationLayout = new QGridLayout (operationGroupBox ); - operationLayout->addWidget (m_resizeButton, 0, 0, Qt::AlignCenter); - operationLayout->addWidget (m_scaleButton, 0, 1, Qt::AlignCenter); - operationLayout->addWidget (m_smoothScaleButton, 0, 2, Qt::AlignCenter); - - connect (m_resizeButton, &QToolButton::toggled, - this, &kpTransformResizeScaleDialog::slotTypeChanged); - connect (m_scaleButton, &QToolButton::toggled, - this, &kpTransformResizeScaleDialog::slotTypeChanged); - connect (m_smoothScaleButton, &QToolButton::toggled, - this, &kpTransformResizeScaleDialog::slotTypeChanged); + i18n("" + "
    " + "
  • Resize: The size of the picture will be" + " increased" + " by creating new areas to the right and/or bottom" + " (filled in with the background color) or" + " decreased by cutting" + " it at the right and/or bottom.
  • " + + "
  • Scale: The picture will be expanded" + " by duplicating pixels or squashed by dropping pixels.
  • " + + "
  • Smooth Scale: This is the same as" + " Scale except that it blends neighboring" + " pixels to produce a smoother looking picture.
  • " + "
" + "
")); + + m_resizeButton = new QToolButton(operationGroupBox); + toolButtonSetLook(m_resizeButton, + QStringLiteral("resize"), + i18n("&Resize")); + + m_scaleButton = new QToolButton(operationGroupBox); + toolButtonSetLook(m_scaleButton, + QStringLiteral("scale"), + i18n("&Scale")); + + m_smoothScaleButton = new QToolButton(operationGroupBox); + toolButtonSetLook(m_smoothScaleButton, + QStringLiteral("smooth_scale"), + i18n("S&mooth Scale")); + + auto *resizeScaleButtonGroup = new QButtonGroup(baseWidget); + resizeScaleButtonGroup->addButton(m_resizeButton); + resizeScaleButtonGroup->addButton(m_scaleButton); + resizeScaleButtonGroup->addButton(m_smoothScaleButton); + + auto *operationLayout = new QGridLayout(operationGroupBox); + operationLayout->addWidget(m_resizeButton, 0, 0, Qt::AlignCenter); + operationLayout->addWidget(m_scaleButton, 0, 1, Qt::AlignCenter); + operationLayout->addWidget(m_smoothScaleButton, 0, 2, Qt::AlignCenter); + + connect(m_resizeButton, &QToolButton::toggled, + this, &kpTransformResizeScaleDialog::slotTypeChanged); + connect(m_scaleButton, &QToolButton::toggled, + this, &kpTransformResizeScaleDialog::slotTypeChanged); + connect(m_smoothScaleButton, &QToolButton::toggled, + this, &kpTransformResizeScaleDialog::slotTypeChanged); return operationGroupBox; } @@ -277,93 +266,88 @@ QGroupBox *kpTransformResizeScaleDialog::createDimensionsGroupBox(QWidget *baseWidget) { - QGroupBox *dimensionsGroupBox = new QGroupBox (i18n ("Dimensions"), baseWidget); + QGroupBox *dimensionsGroupBox = new QGroupBox(i18n("Dimensions"), baseWidget); - auto *widthLabel = new QLabel (i18n ("Width:"), dimensionsGroupBox); - widthLabel->setAlignment (widthLabel->alignment () | Qt::AlignHCenter); - auto *heightLabel = new QLabel (i18n ("Height:"), dimensionsGroupBox); - heightLabel->setAlignment (heightLabel->alignment () | Qt::AlignHCenter); + auto *widthLabel = new QLabel(i18n("Width:"), dimensionsGroupBox); + widthLabel->setAlignment(widthLabel->alignment() | Qt::AlignHCenter); + auto *heightLabel = new QLabel(i18n("Height:"), dimensionsGroupBox); + heightLabel->setAlignment(heightLabel->alignment() | Qt::AlignHCenter); - auto *originalLabel = new QLabel (i18n ("Original:"), dimensionsGroupBox); + auto *originalLabel = new QLabel(i18n("Original:"), dimensionsGroupBox); m_originalWidthInput = new QSpinBox; m_originalWidthInput->setRange(1, INT_MAX); - m_originalWidthInput->setValue(document()->width(static_cast (selection()))); - auto *xLabel0 = new QLabel (i18n ("x"), dimensionsGroupBox); + m_originalWidthInput->setValue(document()->width(static_cast(selection()))); + auto *xLabel0 = new QLabel(i18n("x"), dimensionsGroupBox); m_originalHeightInput = new QSpinBox; m_originalHeightInput->setRange(1, INT_MAX); - m_originalHeightInput->setValue(document()->height(static_cast (selection()))); + m_originalHeightInput->setValue(document()->height(static_cast(selection()))); - auto *newLabel = new QLabel (i18n ("&New:"), dimensionsGroupBox); + auto *newLabel = new QLabel(i18n("&New:"), dimensionsGroupBox); m_newWidthInput = new QSpinBox; m_newWidthInput->setRange(1, INT_MAX); - auto *xLabel1 = new QLabel (i18n ("x"), dimensionsGroupBox); + auto *xLabel1 = new QLabel(i18n("x"), dimensionsGroupBox); m_newHeightInput = new QSpinBox; m_newHeightInput->setRange(1, INT_MAX); - auto *percentLabel = new QLabel (i18n ("&Percent:"), dimensionsGroupBox); + auto *percentLabel = new QLabel(i18n("&Percent:"), dimensionsGroupBox); m_percentWidthInput = new QDoubleSpinBox; m_percentWidthInput->setRange(0.01, 1000000); m_percentWidthInput->setValue(100); m_percentWidthInput->setSingleStep(1); m_percentWidthInput->setDecimals(2); m_percentWidthInput->setSuffix(i18n("%")); - auto *xLabel2 = new QLabel (i18n ("x"), dimensionsGroupBox); + auto *xLabel2 = new QLabel(i18n("x"), dimensionsGroupBox); m_percentHeightInput = new QDoubleSpinBox; m_percentHeightInput->setRange(0.01, 1000000); m_percentHeightInput->setValue(100); m_percentHeightInput->setSingleStep(1); m_percentHeightInput->setDecimals(2); m_percentHeightInput->setSuffix(i18n("%")); - m_keepAspectRatioCheckBox = new QCheckBox (i18n ("Keep &aspect ratio"), - dimensionsGroupBox); - - - m_originalWidthInput->setEnabled (false); - m_originalHeightInput->setEnabled (false); - originalLabel->setBuddy (m_originalWidthInput); - newLabel->setBuddy (m_newWidthInput); - m_percentWidthInput->setValue (100); - m_percentHeightInput->setValue (100); - percentLabel->setBuddy (m_percentWidthInput); - + m_keepAspectRatioCheckBox = new QCheckBox(i18n("Keep &aspect ratio"), + dimensionsGroupBox); - auto *dimensionsLayout = new QGridLayout (dimensionsGroupBox); - dimensionsLayout->setColumnStretch (1/*column*/, 1); - dimensionsLayout->setColumnStretch (3/*column*/, 1); - - - dimensionsLayout->addWidget (widthLabel, 0, 1); - dimensionsLayout->addWidget (heightLabel, 0, 3); + m_originalWidthInput->setEnabled(false); + m_originalHeightInput->setEnabled(false); + originalLabel->setBuddy(m_originalWidthInput); + newLabel->setBuddy(m_newWidthInput); + m_percentWidthInput->setValue(100); + m_percentHeightInput->setValue(100); + percentLabel->setBuddy(m_percentWidthInput); - dimensionsLayout->addWidget (originalLabel, 1, 0); - dimensionsLayout->addWidget (m_originalWidthInput, 1, 1); - dimensionsLayout->addWidget (xLabel0, 1, 2); - dimensionsLayout->addWidget (m_originalHeightInput, 1, 3); + auto *dimensionsLayout = new QGridLayout(dimensionsGroupBox); + dimensionsLayout->setColumnStretch(1 /*column*/, 1); + dimensionsLayout->setColumnStretch(3 /*column*/, 1); - dimensionsLayout->addWidget (newLabel, 2, 0); - dimensionsLayout->addWidget (m_newWidthInput, 2, 1); - dimensionsLayout->addWidget (xLabel1, 2, 2); - dimensionsLayout->addWidget (m_newHeightInput, 2, 3); + dimensionsLayout->addWidget(widthLabel, 0, 1); + dimensionsLayout->addWidget(heightLabel, 0, 3); - dimensionsLayout->addWidget (percentLabel, 3, 0); - dimensionsLayout->addWidget (m_percentWidthInput, 3, 1); - dimensionsLayout->addWidget (xLabel2, 3, 2); - dimensionsLayout->addWidget (m_percentHeightInput, 3, 3); + dimensionsLayout->addWidget(originalLabel, 1, 0); + dimensionsLayout->addWidget(m_originalWidthInput, 1, 1); + dimensionsLayout->addWidget(xLabel0, 1, 2); + dimensionsLayout->addWidget(m_originalHeightInput, 1, 3); - dimensionsLayout->addWidget (m_keepAspectRatioCheckBox, 4, 0, 1, 4); - dimensionsLayout->setRowStretch (4/*row*/, 1); - dimensionsLayout->setRowMinimumHeight (4/*row*/, dimensionsLayout->rowMinimumHeight (4) * 2); + dimensionsLayout->addWidget(newLabel, 2, 0); + dimensionsLayout->addWidget(m_newWidthInput, 2, 1); + dimensionsLayout->addWidget(xLabel1, 2, 2); + dimensionsLayout->addWidget(m_newHeightInput, 2, 3); + dimensionsLayout->addWidget(percentLabel, 3, 0); + dimensionsLayout->addWidget(m_percentWidthInput, 3, 1); + dimensionsLayout->addWidget(xLabel2, 3, 2); + dimensionsLayout->addWidget(m_percentHeightInput, 3, 3); + dimensionsLayout->addWidget(m_keepAspectRatioCheckBox, 4, 0, 1, 4); + dimensionsLayout->setRowStretch(4 /*row*/, 1); + dimensionsLayout->setRowMinimumHeight(4 /*row*/, dimensionsLayout->rowMinimumHeight(4) * 2); - connect (m_newWidthInput, static_cast(&QSpinBox::valueChanged), - this, &kpTransformResizeScaleDialog::slotWidthChanged); + connect(m_newWidthInput, static_cast(&QSpinBox::valueChanged), + this, &kpTransformResizeScaleDialog::slotWidthChanged); - connect (m_newHeightInput, static_cast(&QSpinBox::valueChanged), - this, &kpTransformResizeScaleDialog::slotHeightChanged); + connect(m_newHeightInput, static_cast(&QSpinBox::valueChanged), + this, &kpTransformResizeScaleDialog::slotHeightChanged); // COMPAT: KDoubleNumInput only fires valueChanged(double) once per // edit. It should either fire: @@ -376,298 +360,283 @@ // 2. Once per keystroke. // // Bug in KDoubleNumInput. - connect (m_percentWidthInput, - static_cast(&QDoubleSpinBox::valueChanged), - this, &kpTransformResizeScaleDialog::slotPercentWidthChanged); + connect(m_percentWidthInput, + static_cast(&QDoubleSpinBox::valueChanged), + this, &kpTransformResizeScaleDialog::slotPercentWidthChanged); - connect (m_percentHeightInput, - static_cast(&QDoubleSpinBox::valueChanged), - this, &kpTransformResizeScaleDialog::slotPercentHeightChanged); + connect(m_percentHeightInput, + static_cast(&QDoubleSpinBox::valueChanged), + this, &kpTransformResizeScaleDialog::slotPercentHeightChanged); - connect (m_keepAspectRatioCheckBox, &QCheckBox::toggled, - this, &kpTransformResizeScaleDialog::setKeepAspectRatio); + connect(m_keepAspectRatioCheckBox, &QCheckBox::toggled, + this, &kpTransformResizeScaleDialog::setKeepAspectRatio); return dimensionsGroupBox; } //--------------------------------------------------------------------- // private -void kpTransformResizeScaleDialog::widthFitHeightToAspectRatio () +void kpTransformResizeScaleDialog::widthFitHeightToAspectRatio() { - if (m_keepAspectRatioCheckBox->isChecked () && !m_ignoreKeepAspectRatio) - { + if (m_keepAspectRatioCheckBox->isChecked() && !m_ignoreKeepAspectRatio) { // width / height = oldWidth / oldHeight // height = width * oldHeight / oldWidth - const int newHeight = qRound (double (imageWidth ()) * double (originalHeight ()) - / double (originalWidth ())); - IGNORE_KEEP_ASPECT_RATIO (m_newHeightInput->setValue (newHeight)); + const int newHeight = qRound(double(imageWidth()) * double(originalHeight()) + / double(originalWidth())); + IGNORE_KEEP_ASPECT_RATIO(m_newHeightInput->setValue(newHeight)); } } //--------------------------------------------------------------------- // private -void kpTransformResizeScaleDialog::heightFitWidthToAspectRatio () +void kpTransformResizeScaleDialog::heightFitWidthToAspectRatio() { - if (m_keepAspectRatioCheckBox->isChecked () && !m_ignoreKeepAspectRatio) - { + if (m_keepAspectRatioCheckBox->isChecked() && !m_ignoreKeepAspectRatio) { // width / height = oldWidth / oldHeight // width = height * oldWidth / oldHeight - const int newWidth = qRound (double (imageHeight ()) * double (originalWidth ()) - / double (originalHeight ())); - IGNORE_KEEP_ASPECT_RATIO (m_newWidthInput->setValue (newWidth)); + const int newWidth = qRound(double(imageHeight()) * double(originalWidth()) + / double(originalHeight())); + IGNORE_KEEP_ASPECT_RATIO(m_newWidthInput->setValue(newWidth)); } } //--------------------------------------------------------------------- // private -bool kpTransformResizeScaleDialog::resizeEnabled () const +bool kpTransformResizeScaleDialog::resizeEnabled() const { - return (!actOnSelection () || - (actOnSelection () && textSelection ())); + return !actOnSelection() + || (actOnSelection() && textSelection()); } //--------------------------------------------------------------------- // private -bool kpTransformResizeScaleDialog::scaleEnabled () const +bool kpTransformResizeScaleDialog::scaleEnabled() const { - return (!(actOnSelection () && textSelection ())); + return !(actOnSelection() && textSelection()); } //--------------------------------------------------------------------- // private -bool kpTransformResizeScaleDialog::smoothScaleEnabled () const +bool kpTransformResizeScaleDialog::smoothScaleEnabled() const { - return scaleEnabled (); + return scaleEnabled(); } //--------------------------------------------------------------------- // public slot -void kpTransformResizeScaleDialog::slotActOnChanged () +void kpTransformResizeScaleDialog::slotActOnChanged() { #if DEBUG_KP_TOOL_RESIZE_SCALE_DIALOG && 1 qCDebug(kpLogDialogs) << "kpTransformResizeScaleDialog::slotActOnChanged()"; #endif - m_resizeButton->setEnabled (resizeEnabled ()); - m_scaleButton->setEnabled (scaleEnabled ()); - m_smoothScaleButton->setEnabled (smoothScaleEnabled ()); + m_resizeButton->setEnabled(resizeEnabled()); + m_scaleButton->setEnabled(scaleEnabled()); + m_smoothScaleButton->setEnabled(smoothScaleEnabled()); // TODO: somehow share logic with (resize|*scale)Enabled() - if (actOnSelection ()) - { - if (textSelection ()) - { - m_resizeButton->setChecked (true); - } - else - { + if (actOnSelection()) { + if (textSelection()) { + m_resizeButton->setChecked(true); + } else { if (m_lastType == kpTransformResizeScaleCommand::Scale) { - m_scaleButton->setChecked (true); - } - else { - m_smoothScaleButton->setChecked (true); + m_scaleButton->setChecked(true); + } else { + m_smoothScaleButton->setChecked(true); } } - } - else - { + } else { if (m_lastType == kpTransformResizeScaleCommand::Resize) { - m_resizeButton->setChecked (true); - } - else if (m_lastType == kpTransformResizeScaleCommand::Scale) { - m_scaleButton->setChecked (true); - } - else { - m_smoothScaleButton->setChecked (true); + m_resizeButton->setChecked(true); + } else if (m_lastType == kpTransformResizeScaleCommand::Scale) { + m_scaleButton->setChecked(true); + } else { + m_smoothScaleButton->setChecked(true); } } + m_originalWidthInput->setValue(originalWidth()); + m_originalHeightInput->setValue(originalHeight()); - m_originalWidthInput->setValue (originalWidth ()); - m_originalHeightInput->setValue (originalHeight ()); + m_newWidthInput->blockSignals(true); + m_newHeightInput->blockSignals(true); + m_newWidthInput->setMinimum(actOnSelection() + ? selection()->minimumWidth() + : 1); + m_newHeightInput->setMinimum(actOnSelection() + ? selection()->minimumHeight() + : 1); - m_newWidthInput->blockSignals (true); - m_newHeightInput->blockSignals (true); + m_newWidthInput->blockSignals(false); + m_newHeightInput->blockSignals(false); - m_newWidthInput->setMinimum (actOnSelection () ? - selection ()->minimumWidth () : - 1); - m_newHeightInput->setMinimum (actOnSelection () ? - selection ()->minimumHeight () : - 1); + IGNORE_KEEP_ASPECT_RATIO(slotPercentWidthChanged(m_percentWidthInput->value())); + IGNORE_KEEP_ASPECT_RATIO(slotPercentHeightChanged(m_percentHeightInput->value())); - m_newWidthInput->blockSignals (false); - m_newHeightInput->blockSignals (false); - - - IGNORE_KEEP_ASPECT_RATIO (slotPercentWidthChanged (m_percentWidthInput->value ())); - IGNORE_KEEP_ASPECT_RATIO (slotPercentHeightChanged (m_percentHeightInput->value ())); - - setKeepAspectRatio (m_keepAspectRatioCheckBox->isChecked ()); + setKeepAspectRatio(m_keepAspectRatioCheckBox->isChecked()); } //--------------------------------------------------------------------- // public slot -void kpTransformResizeScaleDialog::slotTypeChanged () +void kpTransformResizeScaleDialog::slotTypeChanged() { - m_lastType = type (); + m_lastType = type(); } //--------------------------------------------------------------------- // public slot -void kpTransformResizeScaleDialog::slotWidthChanged (int width) +void kpTransformResizeScaleDialog::slotWidthChanged(int width) { #if DEBUG_KP_TOOL_RESIZE_SCALE_DIALOG && 1 qCDebug(kpLogDialogs) << "kpTransformResizeScaleDialog::slotWidthChanged(" - << width << ")" << endl; + << width << ")" << endl; #endif - const double newPercentWidth = double (width) * 100 / double (originalWidth ()); + const double newPercentWidth = double(width) * 100 / double(originalWidth()); - SET_VALUE_WITHOUT_SIGNAL_EMISSION (m_percentWidthInput,newPercentWidth); + SET_VALUE_WITHOUT_SIGNAL_EMISSION(m_percentWidthInput, newPercentWidth); - widthFitHeightToAspectRatio (); + widthFitHeightToAspectRatio(); //enableButtonOk (!isNoOp ()); } //--------------------------------------------------------------------- // public slot -void kpTransformResizeScaleDialog::slotHeightChanged (int height) +void kpTransformResizeScaleDialog::slotHeightChanged(int height) { #if DEBUG_KP_TOOL_RESIZE_SCALE_DIALOG && 1 qCDebug(kpLogDialogs) << "kpTransformResizeScaleDialog::slotHeightChanged(" - << height << ")" << endl; + << height << ")" << endl; #endif - const double newPercentHeight = double (height) * 100 / double (originalHeight ()); + const double newPercentHeight = double(height) * 100 / double(originalHeight()); - SET_VALUE_WITHOUT_SIGNAL_EMISSION (m_percentHeightInput,newPercentHeight); + SET_VALUE_WITHOUT_SIGNAL_EMISSION(m_percentHeightInput, newPercentHeight); - heightFitWidthToAspectRatio (); + heightFitWidthToAspectRatio(); //enableButtonOk (!isNoOp ()); } //--------------------------------------------------------------------- // public slot -void kpTransformResizeScaleDialog::slotPercentWidthChanged (double percentWidth) +void kpTransformResizeScaleDialog::slotPercentWidthChanged(double percentWidth) { #if DEBUG_KP_TOOL_RESIZE_SCALE_DIALOG && 1 qCDebug(kpLogDialogs) << "kpTransformResizeScaleDialog::slotPercentWidthChanged(" - << percentWidth << ")"; + << percentWidth << ")"; #endif - SET_VALUE_WITHOUT_SIGNAL_EMISSION (m_newWidthInput, - qRound (percentWidth * originalWidth () / 100.0)); + SET_VALUE_WITHOUT_SIGNAL_EMISSION(m_newWidthInput, + qRound(percentWidth * originalWidth() / 100.0)); - widthFitHeightToAspectRatio (); + widthFitHeightToAspectRatio(); //enableButtonOk (!isNoOp ()); } //--------------------------------------------------------------------- // public slot -void kpTransformResizeScaleDialog::slotPercentHeightChanged (double percentHeight) +void kpTransformResizeScaleDialog::slotPercentHeightChanged(double percentHeight) { #if DEBUG_KP_TOOL_RESIZE_SCALE_DIALOG && 1 qCDebug(kpLogDialogs) << "kpTransformResizeScaleDialog::slotPercentHeightChanged(" - << percentHeight << ")"; + << percentHeight << ")"; #endif - SET_VALUE_WITHOUT_SIGNAL_EMISSION (m_newHeightInput, - qRound (percentHeight * originalHeight () / 100.0)); + SET_VALUE_WITHOUT_SIGNAL_EMISSION(m_newHeightInput, + qRound(percentHeight * originalHeight() / 100.0)); - heightFitWidthToAspectRatio (); + heightFitWidthToAspectRatio(); //enableButtonOk (!isNoOp ()); } //--------------------------------------------------------------------- // public slot -void kpTransformResizeScaleDialog::setKeepAspectRatio (bool on) +void kpTransformResizeScaleDialog::setKeepAspectRatio(bool on) { #if DEBUG_KP_TOOL_RESIZE_SCALE_DIALOG && 1 qCDebug(kpLogDialogs) << "kpTransformResizeScaleDialog::setKeepAspectRatio(" - << on << ")"; + << on << ")"; #endif - if (on != m_keepAspectRatioCheckBox->isChecked ()) { - m_keepAspectRatioCheckBox->setChecked (on); + if (on != m_keepAspectRatioCheckBox->isChecked()) { + m_keepAspectRatioCheckBox->setChecked(on); } if (on) { - widthFitHeightToAspectRatio (); + widthFitHeightToAspectRatio(); } } //--------------------------------------------------------------------- #undef IGNORE_KEEP_ASPECT_RATIO #undef SET_VALUE_WITHOUT_SIGNAL_EMISSION - //--------------------------------------------------------------------- // private -int kpTransformResizeScaleDialog::originalWidth () const +int kpTransformResizeScaleDialog::originalWidth() const { - return document ()->width (actOnSelection ()); + return document()->width(actOnSelection()); } //--------------------------------------------------------------------- // private -int kpTransformResizeScaleDialog::originalHeight () const +int kpTransformResizeScaleDialog::originalHeight() const { - return document ()->height (actOnSelection ()); + return document()->height(actOnSelection()); } //--------------------------------------------------------------------- // public -int kpTransformResizeScaleDialog::imageWidth () const +int kpTransformResizeScaleDialog::imageWidth() const { - return m_newWidthInput->value (); + return m_newWidthInput->value(); } //--------------------------------------------------------------------- // public -int kpTransformResizeScaleDialog::imageHeight () const +int kpTransformResizeScaleDialog::imageHeight() const { - return m_newHeightInput->value (); + return m_newHeightInput->value(); } //--------------------------------------------------------------------- // public -bool kpTransformResizeScaleDialog::actOnSelection () const +bool kpTransformResizeScaleDialog::actOnSelection() const { - return (m_actOnCombo->currentIndex () == Selection); + return m_actOnCombo->currentIndex() == Selection; } //--------------------------------------------------------------------- // public -kpTransformResizeScaleCommand::Type kpTransformResizeScaleDialog::type () const +kpTransformResizeScaleCommand::Type kpTransformResizeScaleDialog::type() const { - if (m_resizeButton->isChecked ()) { + if (m_resizeButton->isChecked()) { return kpTransformResizeScaleCommand::Resize; } - if (m_scaleButton->isChecked ()) { + if (m_scaleButton->isChecked()) { return kpTransformResizeScaleCommand::Scale; } @@ -677,152 +646,135 @@ //--------------------------------------------------------------------- // public -bool kpTransformResizeScaleDialog::isNoOp () const +bool kpTransformResizeScaleDialog::isNoOp() const { - return (imageWidth () == originalWidth () && - imageHeight () == originalHeight ()); + return imageWidth() == originalWidth() + && imageHeight() == originalHeight(); } //--------------------------------------------------------------------- // private slot virtual [base QDialog] -void kpTransformResizeScaleDialog::accept () +void kpTransformResizeScaleDialog::accept() { - enum { eText, eSelection, eImage } actionTarget = eText; + enum { + eText, eSelection, eImage + } actionTarget = eText; - if (actOnSelection ()) - { - if (textSelection ()) - { + if (actOnSelection()) { + if (textSelection()) { actionTarget = eText; - } - else - { + } else { actionTarget = eSelection; } - } - else - { + } else { actionTarget = eImage; } - KLocalizedString message; QString caption, continueButtonText; // Note: If eText, can't Scale nor SmoothScale. // If eSelection, can't Resize. - switch (type ()) - { + switch (type()) { default: case kpTransformResizeScaleCommand::Resize: - if (actionTarget == eText) - { - message = - ki18n ("

Resizing the text box to %1x%2" - " may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to resize the text box?

"); - - caption = i18nc ("@title:window", "Resize Text Box?"); - continueButtonText = i18n ("R&esize Text Box"); - } - else if (actionTarget == eImage) - { - message = - ki18n ("

Resizing the image to %1x%2" - " may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to resize the image?

"); - - caption = i18nc ("@title:window", "Resize Image?"); - continueButtonText = i18n ("R&esize Image"); + if (actionTarget == eText) { + message + = ki18n("

Resizing the text box to %1x%2" + " may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + + "

Are you sure you want to resize the text box?

"); + + caption = i18nc("@title:window", "Resize Text Box?"); + continueButtonText = i18n("R&esize Text Box"); + } else if (actionTarget == eImage) { + message + = ki18n("

Resizing the image to %1x%2" + " may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + + "

Are you sure you want to resize the image?

"); + + caption = i18nc("@title:window", "Resize Image?"); + continueButtonText = i18n("R&esize Image"); } break; case kpTransformResizeScaleCommand::Scale: - if (actionTarget == eImage) - { - message = - ki18n ("

Scaling the image to %1x%2" - " may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to scale the image?

"); - - caption = i18nc ("@title:window", "Scale Image?"); - continueButtonText = i18n ("Scal&e Image"); - } - else if (actionTarget == eSelection) - { - message = - ki18n ("

Scaling the selection to %1x%2" - " may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to scale the selection?

"); - - caption = i18nc ("@title:window", "Scale Selection?"); - continueButtonText = i18n ("Scal&e Selection"); + if (actionTarget == eImage) { + message + = ki18n("

Scaling the image to %1x%2" + " may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + + "

Are you sure you want to scale the image?

"); + + caption = i18nc("@title:window", "Scale Image?"); + continueButtonText = i18n("Scal&e Image"); + } else if (actionTarget == eSelection) { + message + = ki18n("

Scaling the selection to %1x%2" + " may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + + "

Are you sure you want to scale the selection?

"); + + caption = i18nc("@title:window", "Scale Selection?"); + continueButtonText = i18n("Scal&e Selection"); } break; case kpTransformResizeScaleCommand::SmoothScale: - if (actionTarget == eImage) - { - message = - ki18n ("

Smooth Scaling the image to %1x%2" - " may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to smooth scale the image?

"); - - caption = i18nc ("@title:window", "Smooth Scale Image?"); - continueButtonText = i18n ("Smooth Scal&e Image"); - } - else if (actionTarget == eSelection) - { - message = - ki18n ("

Smooth Scaling the selection to %1x%2" - " may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to smooth scale the selection?

"); - - caption = i18nc ("@title:window", "Smooth Scale Selection?"); - continueButtonText = i18n ("Smooth Scal&e Selection"); + if (actionTarget == eImage) { + message + = ki18n("

Smooth Scaling the image to %1x%2" + " may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + + "

Are you sure you want to smooth scale the image?

"); + + caption = i18nc("@title:window", "Smooth Scale Image?"); + continueButtonText = i18n("Smooth Scal&e Image"); + } else if (actionTarget == eSelection) { + message + = ki18n("

Smooth Scaling the selection to %1x%2" + " may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + + "

Are you sure you want to smooth scale the selection?

"); + + caption = i18nc("@title:window", "Smooth Scale Selection?"); + continueButtonText = i18n("Smooth Scal&e Selection"); } break; } - - if (kpTool::warnIfBigImageSize (originalWidth (), - originalHeight (), - imageWidth (), imageHeight (), - message.subs (imageWidth ()).subs (imageHeight ()).toString (), - caption, - continueButtonText, - this)) - { - QDialog::accept (); + if (kpTool::warnIfBigImageSize(originalWidth(), + originalHeight(), + imageWidth(), imageHeight(), + message.subs(imageWidth()).subs(imageHeight()).toString(), + caption, + continueButtonText, + this)) { + QDialog::accept(); } // store settings @@ -834,4 +786,3 @@ } //--------------------------------------------------------------------- - diff --git a/dialogs/imagelib/transforms/kpTransformRotateDialog.h b/dialogs/imagelib/transforms/kpTransformRotateDialog.h --- a/dialogs/imagelib/transforms/kpTransformRotateDialog.h +++ b/dialogs/imagelib/transforms/kpTransformRotateDialog.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,56 +24,50 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransformRotateDialog_H #define kpTransformRotateDialog_H - #include #include #include "imagelib/kpColor.h" #include "dialogs/imagelib/transforms/kpTransformPreviewDialog.h" - class QButtonGroup; class QRadioButton; class QSpinBox; - class kpTransformRotateDialog : public kpTransformPreviewDialog { -Q_OBJECT + Q_OBJECT public: - kpTransformRotateDialog (bool actOnSelection, - kpTransformDialogEnvironment *_env, - QWidget *parent); + kpTransformRotateDialog (bool actOnSelection, kpTransformDialogEnvironment *_env, + QWidget *parent); ~kpTransformRotateDialog () override; private: static int s_lastWidth, s_lastHeight; static bool s_lastIsClockwise; static int s_lastAngleCustom; - void createDirectionGroupBox (); - void createAngleGroupBox (); + void createDirectionGroupBox(); + void createAngleGroupBox(); public: - bool isNoOp () const override; - int angle () const; // 0 <= angle < 360 (clockwise); + bool isNoOp() const override; + int angle() const; // 0 <= angle < 360 (clockwise); private: - QSize newDimensions () const override; - QImage transformPixmap (const QImage &pixmap, - int targetWidth, int targetHeight) const override; + QSize newDimensions() const override; + QImage transformPixmap(const QImage &pixmap, int targetWidth, int targetHeight) const override; private slots: - void slotAngleCustomRadioButtonToggled (bool isChecked); - void slotUpdate () override; + void slotAngleCustomRadioButtonToggled(bool isChecked); + void slotUpdate() override; private slots: - void accept () override; + void accept() override; private: QRadioButton *m_antiClockwiseRadioButton, @@ -88,5 +81,4 @@ QSpinBox *m_angleCustomInput; }; - #endif // kpTransformRotateDialog_H diff --git a/dialogs/imagelib/transforms/kpTransformRotateDialog.cpp b/dialogs/imagelib/transforms/kpTransformRotateDialog.cpp --- a/dialogs/imagelib/transforms/kpTransformRotateDialog.cpp +++ b/dialogs/imagelib/transforms/kpTransformRotateDialog.cpp @@ -26,7 +26,6 @@ #define DEBUG_KP_TOOL_ROTATE 0 - #include "kpTransformRotateDialog.h" #include "kpDefs.h" @@ -51,272 +50,240 @@ #include #include - // private static int kpTransformRotateDialog::s_lastWidth = -1, - kpTransformRotateDialog::s_lastHeight = -1; +kpTransformRotateDialog::s_lastHeight = -1; // private static bool kpTransformRotateDialog::s_lastIsClockwise = true; int kpTransformRotateDialog::s_lastAngleCustom = 0; - kpTransformRotateDialog::kpTransformRotateDialog (bool actOnSelection, - kpTransformDialogEnvironment *_env, QWidget *parent) - : kpTransformPreviewDialog (kpTransformPreviewDialog::AllFeatures, - false/*don't reserve top row*/, - actOnSelection ? i18nc ("@title:window", "Rotate Selection") : i18nc ("@title:window", "Rotate Image"), - i18n ("After rotate:"), - actOnSelection, - _env, parent) + kpTransformDialogEnvironment *_env, + QWidget *parent) + : kpTransformPreviewDialog(kpTransformPreviewDialog::AllFeatures, + false /*don't reserve top row*/, + actOnSelection ? i18nc("@title:window", + "Rotate Selection") : i18nc("@title:window", + "Rotate Image"), + i18n("After rotate:"), + actOnSelection, + _env, parent) { s_lastAngleCustom = 0; - - createDirectionGroupBox (); - createAngleGroupBox (); - + createDirectionGroupBox(); + createAngleGroupBox(); if (s_lastWidth > 0 && s_lastHeight > 0) { - resize (s_lastWidth, s_lastHeight); + resize(s_lastWidth, s_lastHeight); } - - slotAngleCustomRadioButtonToggled (m_angleCustomRadioButton->isChecked ()); - slotUpdate (); + slotAngleCustomRadioButtonToggled(m_angleCustomRadioButton->isChecked()); + slotUpdate(); } kpTransformRotateDialog::~kpTransformRotateDialog () { - s_lastWidth = width (); - s_lastHeight = height (); + s_lastWidth = width(); + s_lastHeight = height(); } - // private -void kpTransformRotateDialog::createDirectionGroupBox () +void kpTransformRotateDialog::createDirectionGroupBox() { - auto *directionGroupBox = new QGroupBox (i18n ("Direction"), mainWidget ()); - addCustomWidget (directionGroupBox); - - - auto *antiClockwisePixmapLabel = new QLabel (directionGroupBox); - antiClockwisePixmapLabel->setPixmap (UserIcon (QStringLiteral("image_rotate_anticlockwise"))); + auto *directionGroupBox = new QGroupBox(i18n("Direction"), mainWidget()); + addCustomWidget(directionGroupBox); - auto *clockwisePixmapLabel = new QLabel (directionGroupBox); - clockwisePixmapLabel->setPixmap (UserIcon (QStringLiteral("image_rotate_clockwise"))); + auto *antiClockwisePixmapLabel = new QLabel(directionGroupBox); + antiClockwisePixmapLabel->setPixmap(UserIcon(QStringLiteral("image_rotate_anticlockwise"))); + auto *clockwisePixmapLabel = new QLabel(directionGroupBox); + clockwisePixmapLabel->setPixmap(UserIcon(QStringLiteral("image_rotate_clockwise"))); - m_antiClockwiseRadioButton = new QRadioButton (i18n ("Cou&nterclockwise"), directionGroupBox); - m_clockwiseRadioButton = new QRadioButton (i18n ("C&lockwise"), directionGroupBox); + m_antiClockwiseRadioButton = new QRadioButton(i18n("Cou&nterclockwise"), directionGroupBox); + m_clockwiseRadioButton = new QRadioButton(i18n("C&lockwise"), directionGroupBox); + m_antiClockwiseRadioButton->setChecked(!s_lastIsClockwise); + m_clockwiseRadioButton->setChecked(s_lastIsClockwise); - m_antiClockwiseRadioButton->setChecked (!s_lastIsClockwise); - m_clockwiseRadioButton->setChecked (s_lastIsClockwise); + auto *directionLayout = new QGridLayout(directionGroupBox); + directionLayout->addWidget(antiClockwisePixmapLabel, 0, 0, Qt::AlignCenter); + directionLayout->addWidget(clockwisePixmapLabel, 0, 1, Qt::AlignCenter); + directionLayout->addWidget(m_antiClockwiseRadioButton, 1, 0, Qt::AlignCenter); + directionLayout->addWidget(m_clockwiseRadioButton, 1, 1, Qt::AlignCenter); + connect(m_antiClockwiseRadioButton, &QRadioButton::toggled, + this, &kpTransformRotateDialog::slotUpdate); - auto *directionLayout = new QGridLayout (directionGroupBox ); - directionLayout->addWidget (antiClockwisePixmapLabel, 0, 0, Qt::AlignCenter); - directionLayout->addWidget (clockwisePixmapLabel, 0, 1, Qt::AlignCenter); - directionLayout->addWidget (m_antiClockwiseRadioButton, 1, 0, Qt::AlignCenter); - directionLayout->addWidget (m_clockwiseRadioButton, 1, 1, Qt::AlignCenter); - - - connect (m_antiClockwiseRadioButton, &QRadioButton::toggled, - this, &kpTransformRotateDialog::slotUpdate); - - connect (m_clockwiseRadioButton, &QRadioButton::toggled, - this, &kpTransformRotateDialog::slotUpdate); + connect(m_clockwiseRadioButton, &QRadioButton::toggled, + this, &kpTransformRotateDialog::slotUpdate); } // private -void kpTransformRotateDialog::createAngleGroupBox () +void kpTransformRotateDialog::createAngleGroupBox() { - auto *angleGroupBox = new QGroupBox (i18n ("Angle"), mainWidget ()); - addCustomWidget (angleGroupBox); + auto *angleGroupBox = new QGroupBox(i18n("Angle"), mainWidget()); + addCustomWidget(angleGroupBox); + m_angle90RadioButton = new QRadioButton(i18n("90 °rees"), angleGroupBox); + m_angle180RadioButton = new QRadioButton(i18n("180 d&egrees"), angleGroupBox); + m_angle270RadioButton = new QRadioButton(i18n("270 de&grees"), angleGroupBox); - m_angle90RadioButton = new QRadioButton (i18n ("90 °rees"), angleGroupBox); - m_angle180RadioButton = new QRadioButton (i18n ("180 d&egrees"), angleGroupBox); - m_angle270RadioButton = new QRadioButton (i18n ("270 de&grees"), angleGroupBox); - - m_angleCustomRadioButton = new QRadioButton (i18n ("C&ustom:"), angleGroupBox); + m_angleCustomRadioButton = new QRadioButton(i18n("C&ustom:"), angleGroupBox); m_angleCustomInput = new QSpinBox; m_angleCustomInput->setMinimum(-359); m_angleCustomInput->setMaximum(+359); m_angleCustomInput->setValue(s_lastAngleCustom); - auto *degreesLabel = new QLabel (i18n ("degrees"), angleGroupBox); - + auto *degreesLabel = new QLabel(i18n("degrees"), angleGroupBox); - m_angleCustomRadioButton->setChecked (true); + m_angleCustomRadioButton->setChecked(true); + auto *angleLayout = new QGridLayout(angleGroupBox); - auto *angleLayout = new QGridLayout (angleGroupBox ); + angleLayout->addWidget(m_angle90RadioButton, 0, 0, 1, 3); + angleLayout->addWidget(m_angle180RadioButton, 1, 0, 1, 3); + angleLayout->addWidget(m_angle270RadioButton, 2, 0, 1, 3); - angleLayout->addWidget (m_angle90RadioButton, 0, 0, 1, 3); - angleLayout->addWidget (m_angle180RadioButton, 1, 0, 1, 3); - angleLayout->addWidget (m_angle270RadioButton, 2, 0, 1, 3); + angleLayout->addWidget(m_angleCustomRadioButton, 3, 0); + angleLayout->addWidget(m_angleCustomInput, 3, 1); + angleLayout->addWidget(degreesLabel, 3, 2); - angleLayout->addWidget (m_angleCustomRadioButton, 3, 0); - angleLayout->addWidget (m_angleCustomInput, 3, 1); - angleLayout->addWidget (degreesLabel, 3, 2); + angleLayout->setColumnStretch(1, 2); // Stretch Custom Angle Input - angleLayout->setColumnStretch (1, 2); // Stretch Custom Angle Input + connect(m_angle90RadioButton, &QRadioButton::toggled, + this, &kpTransformRotateDialog::slotUpdate); + connect(m_angle180RadioButton, &QRadioButton::toggled, + this, &kpTransformRotateDialog::slotUpdate); + connect(m_angle270RadioButton, &QRadioButton::toggled, + this, &kpTransformRotateDialog::slotUpdate); + connect(m_angleCustomRadioButton, &QRadioButton::toggled, + this, &kpTransformRotateDialog::slotAngleCustomRadioButtonToggled); + connect(m_angleCustomRadioButton, &QRadioButton::toggled, + this, &kpTransformRotateDialog::slotUpdate); - - connect (m_angle90RadioButton, &QRadioButton::toggled, - this, &kpTransformRotateDialog::slotUpdate); - connect (m_angle180RadioButton, &QRadioButton::toggled, - this, &kpTransformRotateDialog::slotUpdate); - connect (m_angle270RadioButton, &QRadioButton::toggled, - this, &kpTransformRotateDialog::slotUpdate); - - connect (m_angleCustomRadioButton, &QRadioButton::toggled, - this, &kpTransformRotateDialog::slotAngleCustomRadioButtonToggled); - connect (m_angleCustomRadioButton, &QRadioButton::toggled, - this, &kpTransformRotateDialog::slotUpdate); - - connect (m_angleCustomInput, - static_cast(&QSpinBox::valueChanged), - this, &kpTransformRotateDialog::slotUpdate); + connect(m_angleCustomInput, + static_cast(&QSpinBox::valueChanged), + this, &kpTransformRotateDialog::slotUpdate); } - // public virtual [base kpTransformPreviewDialog] -bool kpTransformRotateDialog::isNoOp () const +bool kpTransformRotateDialog::isNoOp() const { - return (angle () == 0); + return angle() == 0; } // public -int kpTransformRotateDialog::angle () const +int kpTransformRotateDialog::angle() const { int retAngle; - - if (m_angle90RadioButton->isChecked ()) { + if (m_angle90RadioButton->isChecked()) { retAngle = 90; - } - else if (m_angle180RadioButton->isChecked ()) { + } else if (m_angle180RadioButton->isChecked()) { retAngle = 180; - } - else if (m_angle270RadioButton->isChecked ()) { + } else if (m_angle270RadioButton->isChecked()) { retAngle = 270; + } else { // if (m_angleCustomRadioButton->isChecked ()) + retAngle = m_angleCustomInput->value(); } - else { // if (m_angleCustomRadioButton->isChecked ()) - retAngle = m_angleCustomInput->value (); - } - - if (m_antiClockwiseRadioButton->isChecked ()) { + if (m_antiClockwiseRadioButton->isChecked()) { retAngle *= -1; } - if (retAngle < 0) { retAngle += ((0 - retAngle) / 360 + 1) * 360; } if (retAngle >= 360) { retAngle -= ((retAngle - 360) / 360 + 1) * 360; } - return retAngle; } - // private virtual [base kpTransformPreviewDialog] -QSize kpTransformRotateDialog::newDimensions () const +QSize kpTransformRotateDialog::newDimensions() const { - QTransform matrix = kpPixmapFX::rotateMatrix (m_oldWidth, m_oldHeight, angle ()); - QRect rect = matrix.mapRect (QRect (0, 0, m_oldWidth, m_oldHeight)); - return rect.size (); + QTransform matrix = kpPixmapFX::rotateMatrix(m_oldWidth, m_oldHeight, angle()); + QRect rect = matrix.mapRect(QRect(0, 0, m_oldWidth, m_oldHeight)); + return rect.size(); } // private virtual [base kpTransformPreviewDialog] -QImage kpTransformRotateDialog::transformPixmap (const QImage &image, - int targetWidth, int targetHeight) const +QImage kpTransformRotateDialog::transformPixmap(const QImage &image, int targetWidth, + int targetHeight) const { - return kpPixmapFX::rotate (image, angle (), - m_environ->backgroundColor (m_actOnSelection), - targetWidth, targetHeight); + return kpPixmapFX::rotate(image, angle(), + m_environ->backgroundColor(m_actOnSelection), + targetWidth, targetHeight); } - // private slot -void kpTransformRotateDialog::slotAngleCustomRadioButtonToggled (bool isChecked) +void kpTransformRotateDialog::slotAngleCustomRadioButtonToggled(bool isChecked) { - m_angleCustomInput->setEnabled (isChecked); + m_angleCustomInput->setEnabled(isChecked); if (isChecked) { m_angleCustomInput->setFocus(); } } // private slot virtual [base kpTransformPreviewDialog] -void kpTransformRotateDialog::slotUpdate () +void kpTransformRotateDialog::slotUpdate() { - s_lastIsClockwise = m_clockwiseRadioButton->isChecked (); - s_lastAngleCustom = m_angleCustomInput->value (); + s_lastIsClockwise = m_clockwiseRadioButton->isChecked(); + s_lastAngleCustom = m_angleCustomInput->value(); - kpTransformPreviewDialog::slotUpdate (); + kpTransformPreviewDialog::slotUpdate(); } - // private slot virtual [base QDialog] -void kpTransformRotateDialog::accept () +void kpTransformRotateDialog::accept() { KLocalizedString message; QString caption, continueButtonText; - if (document ()->selection ()) - { - if (!document ()->textSelection ()) - { - message = - ki18n ("

Rotating the selection to %1x%2" - " may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to rotate the selection?

"); - - caption = i18nc ("@title:window", "Rotate Selection?"); - continueButtonText = i18n ("Rotat&e Selection"); - } - } - else - { - message = - ki18n ("

Rotating the image to %1x%2" - " may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to rotate the image?

"); - - caption = i18nc ("@title:window", "Rotate Image?"); - continueButtonText = i18n ("Rotat&e Image"); - } + if (document()->selection()) { + if (!document()->textSelection()) { + message + = ki18n("

Rotating the selection to %1x%2" + " may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + "

Are you sure you want to rotate the selection?

"); - const int newWidth = newDimensions ().width (); - const int newHeight = newDimensions ().height (); + caption = i18nc("@title:window", "Rotate Selection?"); + continueButtonText = i18n("Rotat&e Selection"); + } + } else { + message + = ki18n("

Rotating the image to %1x%2" + " may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + + "

Are you sure you want to rotate the image?

"); + + caption = i18nc("@title:window", "Rotate Image?"); + continueButtonText = i18n("Rotat&e Image"); + } - if (kpTool::warnIfBigImageSize (m_oldWidth, - m_oldHeight, - newWidth, newHeight, - message.subs (newWidth).subs (newHeight).toString (), - caption, - continueButtonText, - this)) - { - QDialog::accept (); + const int newWidth = newDimensions().width(); + const int newHeight = newDimensions().height(); + + if (kpTool::warnIfBigImageSize(m_oldWidth, + m_oldHeight, + newWidth, newHeight, + message.subs(newWidth).subs(newHeight).toString(), + caption, + continueButtonText, + this)) { + QDialog::accept(); } } - - diff --git a/dialogs/imagelib/transforms/kpTransformSkewDialog.h b/dialogs/imagelib/transforms/kpTransformSkewDialog.h --- a/dialogs/imagelib/transforms/kpTransformSkewDialog.h +++ b/dialogs/imagelib/transforms/kpTransformSkewDialog.h @@ -24,60 +24,56 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransformSkewDialog_H #define kpTransformSkewDialog_H #include "kpTransformPreviewDialog.h" #include "imagelib/kpColor.h" class QSpinBox; - class kpTransformSkewDialog : public kpTransformPreviewDialog { -Q_OBJECT + Q_OBJECT public: - kpTransformSkewDialog (bool actOnSelection, - kpTransformDialogEnvironment *_env, QWidget *parent); + kpTransformSkewDialog (bool actOnSelection, kpTransformDialogEnvironment *_env, + QWidget *parent); ~kpTransformSkewDialog () override; private: static int s_lastWidth, s_lastHeight; static int s_lastHorizontalAngle, s_lastVerticalAngle; - void createAngleGroupBox (); + void createAngleGroupBox(); - QSize newDimensions () const override; - QImage transformPixmap (const QImage &image, - int targetWidth, int targetHeight) const override; + QSize newDimensions() const override; + QImage transformPixmap(const QImage &image, int targetWidth, int targetHeight) const override; - void updateLastAngles (); + void updateLastAngles(); private slots: - void slotUpdate () override; + void slotUpdate() override; public: // These are the angles the users sees in the dialog and... - int horizontalAngle () const; - int verticalAngle () const; + int horizontalAngle() const; + int verticalAngle() const; // ...these functions translate them for use in kpPixmapFX::skew(). - static int horizontalAngleForPixmapFX (int hangle); - static int verticalAngleForPixmapFX (int vangle); + static int horizontalAngleForPixmapFX(int hangle); + static int verticalAngleForPixmapFX(int vangle); - int horizontalAngleForPixmapFX () const; - int verticalAngleForPixmapFX () const; + int horizontalAngleForPixmapFX() const; + int verticalAngleForPixmapFX() const; - bool isNoOp () const override; + bool isNoOp() const override; private slots: - void accept () override; + void accept() override; private: QSpinBox *m_horizontalSkewInput, *m_verticalSkewInput; }; - #endif // kpTransformSkewDialog_H diff --git a/dialogs/imagelib/transforms/kpTransformSkewDialog.cpp b/dialogs/imagelib/transforms/kpTransformSkewDialog.cpp --- a/dialogs/imagelib/transforms/kpTransformSkewDialog.cpp +++ b/dialogs/imagelib/transforms/kpTransformSkewDialog.cpp @@ -24,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SKEW 0 #define DEBUG_KP_TOOL_SKEW_DIALOG 0 - #include "dialogs/imagelib/transforms/kpTransformSkewDialog.h" #include @@ -51,248 +49,225 @@ #include "tools/kpTool.h" #include "environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.h" - // private static int kpTransformSkewDialog::s_lastWidth = -1, - kpTransformSkewDialog::s_lastHeight = -1; +kpTransformSkewDialog::s_lastHeight = -1; // private static int kpTransformSkewDialog::s_lastHorizontalAngle = 0, - kpTransformSkewDialog::s_lastVerticalAngle = 0; - +kpTransformSkewDialog::s_lastVerticalAngle = 0; kpTransformSkewDialog::kpTransformSkewDialog (bool actOnSelection, - kpTransformDialogEnvironment *_env, QWidget *parent) - : kpTransformPreviewDialog (kpTransformPreviewDialog::AllFeatures, - false/*don't reserve top row*/, - actOnSelection ? i18nc ("@title:window", "Skew Selection") : i18nc ("@title:window", "Skew Image"), - i18n ("After skew:"), - actOnSelection, - _env, parent) + kpTransformDialogEnvironment *_env, QWidget *parent) + : kpTransformPreviewDialog(kpTransformPreviewDialog::AllFeatures, + false /*don't reserve top row*/, + actOnSelection ? i18nc("@title:window", + "Skew Selection") : i18nc("@title:window", + "Skew Image"), + i18n("After skew:"), + actOnSelection, + _env, parent) { // Too confusing - disable for now s_lastHorizontalAngle = s_lastVerticalAngle = 0; - - createAngleGroupBox (); - + createAngleGroupBox(); if (s_lastWidth > 0 && s_lastHeight > 0) { - resize (s_lastWidth, s_lastHeight); + resize(s_lastWidth, s_lastHeight); } + slotUpdate(); - slotUpdate (); - - - m_horizontalSkewInput->setFocus (); + m_horizontalSkewInput->setFocus(); } kpTransformSkewDialog::~kpTransformSkewDialog () { - s_lastWidth = width (); - s_lastHeight = height (); + s_lastWidth = width(); + s_lastHeight = height(); } - // private -void kpTransformSkewDialog::createAngleGroupBox () +void kpTransformSkewDialog::createAngleGroupBox() { - auto *angleGroupBox = new QGroupBox (i18n ("Angle"), mainWidget ()); - addCustomWidget (angleGroupBox); - + auto *angleGroupBox = new QGroupBox(i18n("Angle"), mainWidget()); + addCustomWidget(angleGroupBox); - auto *horizontalSkewPixmapLabel = new QLabel (angleGroupBox); - horizontalSkewPixmapLabel->setPixmap (UserIcon (QStringLiteral("image_skew_horizontal"))); + auto *horizontalSkewPixmapLabel = new QLabel(angleGroupBox); + horizontalSkewPixmapLabel->setPixmap(UserIcon(QStringLiteral("image_skew_horizontal"))); - auto *horizontalSkewLabel = new QLabel (i18n ("&Horizontal:"), angleGroupBox); + auto *horizontalSkewLabel = new QLabel(i18n("&Horizontal:"), angleGroupBox); m_horizontalSkewInput = new QSpinBox; m_horizontalSkewInput->setValue(s_lastHorizontalAngle); m_horizontalSkewInput->setMinimum(-89); m_horizontalSkewInput->setMaximum(+89); - auto *horizontalSkewDegreesLabel = new QLabel (i18n ("degrees"), angleGroupBox); + auto *horizontalSkewDegreesLabel = new QLabel(i18n("degrees"), angleGroupBox); + auto *verticalSkewPixmapLabel = new QLabel(angleGroupBox); + verticalSkewPixmapLabel->setPixmap(UserIcon(QStringLiteral("image_skew_vertical"))); - auto *verticalSkewPixmapLabel = new QLabel (angleGroupBox); - verticalSkewPixmapLabel->setPixmap (UserIcon (QStringLiteral("image_skew_vertical"))); - - auto *verticalSkewLabel = new QLabel (i18n ("&Vertical:"), angleGroupBox); + auto *verticalSkewLabel = new QLabel(i18n("&Vertical:"), angleGroupBox); m_verticalSkewInput = new QSpinBox; m_verticalSkewInput->setValue(s_lastVerticalAngle); m_verticalSkewInput->setMinimum(-89); m_verticalSkewInput->setMaximum(+89); - auto *verticalSkewDegreesLabel = new QLabel (i18n ("degrees"), angleGroupBox); - + auto *verticalSkewDegreesLabel = new QLabel(i18n("degrees"), angleGroupBox); - horizontalSkewLabel->setBuddy (m_horizontalSkewInput); - verticalSkewLabel->setBuddy (m_verticalSkewInput); + horizontalSkewLabel->setBuddy(m_horizontalSkewInput); + verticalSkewLabel->setBuddy(m_verticalSkewInput); + auto *angleLayout = new QGridLayout(angleGroupBox); - auto *angleLayout = new QGridLayout (angleGroupBox); + angleLayout->addWidget(horizontalSkewPixmapLabel, 0, 0); + angleLayout->addWidget(horizontalSkewLabel, 0, 1); + angleLayout->addWidget(m_horizontalSkewInput, 0, 2, Qt::AlignVCenter); + angleLayout->addWidget(horizontalSkewDegreesLabel, 0, 3); - angleLayout->addWidget (horizontalSkewPixmapLabel, 0, 0); - angleLayout->addWidget (horizontalSkewLabel, 0, 1); - angleLayout->addWidget (m_horizontalSkewInput, 0, 2, Qt::AlignVCenter); - angleLayout->addWidget (horizontalSkewDegreesLabel, 0, 3); + angleLayout->addWidget(verticalSkewPixmapLabel, 1, 0); + angleLayout->addWidget(verticalSkewLabel, 1, 1); + angleLayout->addWidget(m_verticalSkewInput, 1, 2, Qt::AlignVCenter); + angleLayout->addWidget(verticalSkewDegreesLabel, 1, 3); - angleLayout->addWidget (verticalSkewPixmapLabel, 1, 0); - angleLayout->addWidget (verticalSkewLabel, 1, 1); - angleLayout->addWidget (m_verticalSkewInput, 1, 2, Qt::AlignVCenter); - angleLayout->addWidget (verticalSkewDegreesLabel, 1, 3); + connect(m_horizontalSkewInput, + static_cast(&QSpinBox::valueChanged), + this, &kpTransformSkewDialog::slotUpdate); - - connect (m_horizontalSkewInput, - static_cast(&QSpinBox::valueChanged), - this, &kpTransformSkewDialog::slotUpdate); - - connect (m_verticalSkewInput, - static_cast(&QSpinBox::valueChanged), - this, &kpTransformSkewDialog::slotUpdate); + connect(m_verticalSkewInput, + static_cast(&QSpinBox::valueChanged), + this, &kpTransformSkewDialog::slotUpdate); } - // private virtual [base kpTransformPreviewDialog] -QSize kpTransformSkewDialog::newDimensions () const +QSize kpTransformSkewDialog::newDimensions() const { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - auto skewMatrix = kpPixmapFX::skewMatrix (doc->image (), - horizontalAngleForPixmapFX (), - verticalAngleForPixmapFX ()); - auto skewRect = skewMatrix.mapRect (doc->rect (m_actOnSelection)); + auto skewMatrix = kpPixmapFX::skewMatrix(doc->image(), + horizontalAngleForPixmapFX(), + verticalAngleForPixmapFX()); + auto skewRect = skewMatrix.mapRect(doc->rect(m_actOnSelection)); - return {skewRect.width (), skewRect.height ()}; + return { + skewRect.width(), skewRect.height() + }; } // private virtual [base kpTransformPreviewDialog] -QImage kpTransformSkewDialog::transformPixmap (const QImage &image, - int targetWidth, int targetHeight) const +QImage kpTransformSkewDialog::transformPixmap(const QImage &image, int targetWidth, + int targetHeight) const { - return kpPixmapFX::skew (image, - horizontalAngleForPixmapFX (), - verticalAngleForPixmapFX (), - m_environ->backgroundColor (m_actOnSelection), - targetWidth, - targetHeight); + return kpPixmapFX::skew(image, + horizontalAngleForPixmapFX(), + verticalAngleForPixmapFX(), + m_environ->backgroundColor(m_actOnSelection), + targetWidth, + targetHeight); } - // private -void kpTransformSkewDialog::updateLastAngles () +void kpTransformSkewDialog::updateLastAngles() { - s_lastHorizontalAngle = horizontalAngle (); - s_lastVerticalAngle = verticalAngle (); + s_lastHorizontalAngle = horizontalAngle(); + s_lastVerticalAngle = verticalAngle(); } // private slot virtual [base kpTransformPreviewDialog] -void kpTransformSkewDialog::slotUpdate () +void kpTransformSkewDialog::slotUpdate() { - updateLastAngles (); - kpTransformPreviewDialog::slotUpdate (); + updateLastAngles(); + kpTransformPreviewDialog::slotUpdate(); } - // public -int kpTransformSkewDialog::horizontalAngle () const +int kpTransformSkewDialog::horizontalAngle() const { - return m_horizontalSkewInput->value (); + return m_horizontalSkewInput->value(); } // public -int kpTransformSkewDialog::verticalAngle () const +int kpTransformSkewDialog::verticalAngle() const { - return m_verticalSkewInput->value (); + return m_verticalSkewInput->value(); } - // public static -int kpTransformSkewDialog::horizontalAngleForPixmapFX (int hangle) +int kpTransformSkewDialog::horizontalAngleForPixmapFX(int hangle) { return -hangle; } // public static -int kpTransformSkewDialog::verticalAngleForPixmapFX (int vangle) +int kpTransformSkewDialog::verticalAngleForPixmapFX(int vangle) { return -vangle; } - // public -int kpTransformSkewDialog::horizontalAngleForPixmapFX () const +int kpTransformSkewDialog::horizontalAngleForPixmapFX() const { - return kpTransformSkewDialog::horizontalAngleForPixmapFX (horizontalAngle ()); + return kpTransformSkewDialog::horizontalAngleForPixmapFX(horizontalAngle()); } // public -int kpTransformSkewDialog::verticalAngleForPixmapFX () const +int kpTransformSkewDialog::verticalAngleForPixmapFX() const { - return kpTransformSkewDialog::verticalAngleForPixmapFX (verticalAngle ()); + return kpTransformSkewDialog::verticalAngleForPixmapFX(verticalAngle()); } - // public virtual [base kpTransformPreviewDialog] -bool kpTransformSkewDialog::isNoOp () const +bool kpTransformSkewDialog::isNoOp() const { - return (horizontalAngle () == 0) && (verticalAngle () == 0); + return (horizontalAngle() == 0) && (verticalAngle() == 0); } - // private slot virtual [base QDialog] -void kpTransformSkewDialog::accept () +void kpTransformSkewDialog::accept() { KLocalizedString message; QString caption, continueButtonText; - if (document ()->selection ()) - { - if (!document ()->textSelection ()) - { - message = - ki18n ("

Skewing the selection to %1x%2" - " may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to skew the selection?

"); - - caption = i18nc ("@title:window", "Skew Selection?"); - continueButtonText = i18n ("Sk&ew Selection"); - } - } - else - { - message = - ki18n ("

Skewing the image to %1x%2" - " may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to skew the image?

"); - - caption = i18nc ("@title:window", "Skew Image?"); - continueButtonText = i18n ("Sk&ew Image"); - } + if (document()->selection()) { + if (!document()->textSelection()) { + message + = ki18n("

Skewing the selection to %1x%2" + " may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + "

Are you sure you want to skew the selection?

"); - const int newWidth = newDimensions ().width (); - const int newHeight = newDimensions ().height (); + caption = i18nc("@title:window", "Skew Selection?"); + continueButtonText = i18n("Sk&ew Selection"); + } + } else { + message + = ki18n("

Skewing the image to %1x%2" + " may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + + "

Are you sure you want to skew the image?

"); + + caption = i18nc("@title:window", "Skew Image?"); + continueButtonText = i18n("Sk&ew Image"); + } - if (kpTool::warnIfBigImageSize (m_oldWidth, - m_oldHeight, - newWidth, newHeight, - message.subs (newWidth).subs (newHeight).toString (), - caption, - continueButtonText, - this)) - { - QDialog::accept (); + const int newWidth = newDimensions().width(); + const int newHeight = newDimensions().height(); + + if (kpTool::warnIfBigImageSize(m_oldWidth, + m_oldHeight, + newWidth, newHeight, + message.subs(newWidth).subs(newHeight).toString(), + caption, + continueButtonText, + this)) { + QDialog::accept(); } } - - diff --git a/dialogs/kpColorSimilarityDialog.h b/dialogs/kpColorSimilarityDialog.h --- a/dialogs/kpColorSimilarityDialog.h +++ b/dialogs/kpColorSimilarityDialog.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,44 +24,39 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_COLOR_SIMILARITY_DIALOG_H #define KP_COLOR_SIMILARITY_DIALOG_H - #include - class QLabel; class kpIntNumInput; class kpColorSimilarityFrame; - // LOTODO: Why doesn't this dialog automatically enforce a minimum size // based on layout magic, like Image -> Resize / Scale? class kpColorSimilarityDialog : public QDialog { -Q_OBJECT + Q_OBJECT public: kpColorSimilarityDialog (QWidget *parent); ~kpColorSimilarityDialog () override; - double colorSimilarity () const; - void setColorSimilarity (double similarity); + double colorSimilarity() const; + void setColorSimilarity(double similarity); private slots: - void slotColorSimilarityValueChanged (); + void slotColorSimilarityValueChanged(); - void slotWhatIsLabelClicked (); + void slotWhatIsLabelClicked(); private: kpColorSimilarityFrame *m_colorSimilarityFrame; kpIntNumInput *m_colorSimilarityInput; QLabel *m_whatIsLabel; }; - #endif // KP_COLOR_SIMILARITY_DIALOG_H diff --git a/dialogs/kpColorSimilarityDialog.cpp b/dialogs/kpColorSimilarityDialog.cpp --- a/dialogs/kpColorSimilarityDialog.cpp +++ b/dialogs/kpColorSimilarityDialog.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpColorSimilarityDialog.h" #include "widgets/colorSimilarity/kpColorSimilarityFrame.h" @@ -42,100 +40,92 @@ #include kpColorSimilarityDialog::kpColorSimilarityDialog (QWidget *parent) - : QDialog (parent) + : QDialog(parent) { - setWindowTitle (i18nc ("@title:window", "Color Similarity")); - auto *buttons = new QDialogButtonBox (QDialogButtonBox::Ok | - QDialogButtonBox::Cancel, this); - connect (buttons, &QDialogButtonBox::accepted, this, &kpColorSimilarityDialog::accept); - connect (buttons, &QDialogButtonBox::rejected, this, &kpColorSimilarityDialog::reject); + setWindowTitle(i18nc("@title:window", "Color Similarity")); + auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok + |QDialogButtonBox::Cancel, this); + connect(buttons, &QDialogButtonBox::accepted, this, &kpColorSimilarityDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, this, &kpColorSimilarityDialog::reject); - auto *baseWidget = new QWidget (this); + auto *baseWidget = new QWidget(this); - auto *dialogLayout = new QVBoxLayout (this); - dialogLayout->addWidget (baseWidget); - dialogLayout->addWidget (buttons); + auto *dialogLayout = new QVBoxLayout(this); + dialogLayout->addWidget(baseWidget); + dialogLayout->addWidget(buttons); - auto *cubeGroupBox = new QGroupBox (i18n ("Preview"), baseWidget); + auto *cubeGroupBox = new QGroupBox(i18n("Preview"), baseWidget); m_colorSimilarityFrame = new kpColorSimilarityFrame(cubeGroupBox); - m_colorSimilarityFrame->setMinimumSize (240, 180); - - auto *updatePushButton = new QPushButton (i18n ("&Update"), cubeGroupBox); + m_colorSimilarityFrame->setMinimumSize(240, 180); + auto *updatePushButton = new QPushButton(i18n("&Update"), cubeGroupBox); - auto *cubeLayout = new QVBoxLayout (cubeGroupBox); - cubeLayout->addWidget (m_colorSimilarityFrame, 1/*stretch*/); - cubeLayout->addWidget (updatePushButton, 0/*stretch*/, Qt::AlignHCenter); + auto *cubeLayout = new QVBoxLayout(cubeGroupBox); + cubeLayout->addWidget(m_colorSimilarityFrame, 1 /*stretch*/); + cubeLayout->addWidget(updatePushButton, 0 /*stretch*/, Qt::AlignHCenter); + connect(updatePushButton, &QPushButton::clicked, + this, &kpColorSimilarityDialog::slotColorSimilarityValueChanged); - connect (updatePushButton, &QPushButton::clicked, - this, &kpColorSimilarityDialog::slotColorSimilarityValueChanged); + auto *inputGroupBox = new QGroupBox(i18n("&RGB Color Cube Distance"), + baseWidget); - - auto *inputGroupBox = new QGroupBox (i18n ("&RGB Color Cube Distance"), - baseWidget); - - m_colorSimilarityInput = new kpIntNumInput (inputGroupBox); - m_colorSimilarityInput->setRange (0, int (kpColorSimilarityHolder::MaxColorSimilarity * 100 + 0.1/*don't floor below target int*/), - 5/*step*/); - m_colorSimilarityInput->setSuffix (i18n ("%")); - m_colorSimilarityInput->setSpecialValueText (i18n ("Exact Match")); + m_colorSimilarityInput = new kpIntNumInput(inputGroupBox); + m_colorSimilarityInput->setRange(0, + int(kpColorSimilarityHolder::MaxColorSimilarity * 100 + 0.1 /*don't floor below target int*/), + 5 /*step*/); + m_colorSimilarityInput->setSuffix(i18n("%")); + m_colorSimilarityInput->setSpecialValueText(i18n("Exact Match")); // TODO: We have a good handbook section on this, which we should // somehow link to. - m_whatIsLabel = new QLabel ( - i18n ("" - "What is Color Similarity?"), + m_whatIsLabel = new QLabel( + i18n("" + "What is Color Similarity?"), inputGroupBox); - m_whatIsLabel->setAlignment (Qt::AlignHCenter); - connect (m_whatIsLabel, &QLabel::linkActivated, - this, &kpColorSimilarityDialog::slotWhatIsLabelClicked); - + m_whatIsLabel->setAlignment(Qt::AlignHCenter); + connect(m_whatIsLabel, &QLabel::linkActivated, + this, &kpColorSimilarityDialog::slotWhatIsLabelClicked); - auto *inputLayout = new QVBoxLayout (inputGroupBox); - - inputLayout->addWidget (m_colorSimilarityInput); - inputLayout->addWidget (m_whatIsLabel); + auto *inputLayout = new QVBoxLayout(inputGroupBox); + inputLayout->addWidget(m_colorSimilarityInput); + inputLayout->addWidget(m_whatIsLabel); // COMPAT: This is not firing properly when the user is typing in a // new value. - connect (m_colorSimilarityInput, &kpIntNumInput::valueChanged, - this, &kpColorSimilarityDialog::slotColorSimilarityValueChanged); - + connect(m_colorSimilarityInput, &kpIntNumInput::valueChanged, + this, &kpColorSimilarityDialog::slotColorSimilarityValueChanged); - auto *baseLayout = new QVBoxLayout (baseWidget); + auto *baseLayout = new QVBoxLayout(baseWidget); baseLayout->setContentsMargins(0, 0, 0, 0); - baseLayout->addWidget (cubeGroupBox, 1/*stretch*/); - baseLayout->addWidget (inputGroupBox); + baseLayout->addWidget(cubeGroupBox, 1 /*stretch*/); + baseLayout->addWidget(inputGroupBox); } kpColorSimilarityDialog::~kpColorSimilarityDialog () = default; - // public -double kpColorSimilarityDialog::colorSimilarity () const +double kpColorSimilarityDialog::colorSimilarity() const { - return m_colorSimilarityFrame->colorSimilarity (); + return m_colorSimilarityFrame->colorSimilarity(); } // public -void kpColorSimilarityDialog::setColorSimilarity (double similarity) +void kpColorSimilarityDialog::setColorSimilarity(double similarity) { - m_colorSimilarityInput->setValue (qRound (similarity * 100)); + m_colorSimilarityInput->setValue(qRound(similarity * 100)); } - // private slot -void kpColorSimilarityDialog::slotColorSimilarityValueChanged () +void kpColorSimilarityDialog::slotColorSimilarityValueChanged() { - m_colorSimilarityFrame->setColorSimilarity (double (m_colorSimilarityInput->value ()) / 100); + m_colorSimilarityFrame->setColorSimilarity(double(m_colorSimilarityInput->value()) / 100); } - // private slot -void kpColorSimilarityDialog::slotWhatIsLabelClicked () +void kpColorSimilarityDialog::slotWhatIsLabelClicked() { - QWhatsThis::showText(QCursor::pos(), m_colorSimilarityFrame->whatsThis(), this); + QWhatsThis::showText(QCursor::pos(), m_colorSimilarityFrame->whatsThis(), this); } diff --git a/dialogs/kpDocumentSaveOptionsPreviewDialog.h b/dialogs/kpDocumentSaveOptionsPreviewDialog.h --- a/dialogs/kpDocumentSaveOptionsPreviewDialog.h +++ b/dialogs/kpDocumentSaveOptionsPreviewDialog.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,50 +24,47 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpDocumentSaveOptionsPreviewDialog_H #define kpDocumentSaveOptionsPreviewDialog_H #include "generic/widgets/kpSubWindow.h" #include - class QCloseEvent; class QImage; class QLabel; class QMoveEvent; class QResizeEvent; class kpResizeSignallingLabel; - class kpDocumentSaveOptionsPreviewDialog : public kpSubWindow { -Q_OBJECT + Q_OBJECT public: kpDocumentSaveOptionsPreviewDialog (QWidget *parent); ~kpDocumentSaveOptionsPreviewDialog () override; - QSize preferredMinimumSize () const; + QSize preferredMinimumSize() const; protected: static const QSize s_pixmapLabelMinimumSize; signals: - void moved (); - void resized (); - void finished (); + void moved(); + void resized(); + void finished(); public slots: - void setFilePixmapAndSize (const QImage &filePixmap, qint64 fileSize); - void updatePixmapPreview (); + void setFilePixmapAndSize(const QImage &filePixmap, qint64 fileSize); + void updatePixmapPreview(); protected: - void closeEvent (QCloseEvent *e) override; - void moveEvent (QMoveEvent *e) override; - void resizeEvent (QResizeEvent *e) override; + void closeEvent(QCloseEvent *e) override; + void moveEvent(QMoveEvent *e) override; + void resizeEvent(QResizeEvent *e) override; protected: QImage *m_filePixmap; @@ -78,5 +74,4 @@ QLabel *m_fileSizeLabel; }; - #endif // kpDocumentSaveOptionsPreviewDialog_H diff --git a/dialogs/kpDocumentSaveOptionsPreviewDialog.cpp b/dialogs/kpDocumentSaveOptionsPreviewDialog.cpp --- a/dialogs/kpDocumentSaveOptionsPreviewDialog.cpp +++ b/dialogs/kpDocumentSaveOptionsPreviewDialog.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET 0 - #include "kpDocumentSaveOptionsPreviewDialog.h" #include @@ -47,186 +45,173 @@ #include "generic/widgets/kpResizeSignallingLabel.h" #include "dialogs/imagelib/transforms/kpTransformPreviewDialog.h" - // protected static -const QSize kpDocumentSaveOptionsPreviewDialog::s_pixmapLabelMinimumSize (25, 25); - +const QSize kpDocumentSaveOptionsPreviewDialog::s_pixmapLabelMinimumSize(25, 25); kpDocumentSaveOptionsPreviewDialog::kpDocumentSaveOptionsPreviewDialog ( - QWidget *parent ) - : kpSubWindow (parent), - m_filePixmap (nullptr), - m_fileSize (0) + QWidget *parent) + : kpSubWindow(parent) + , m_filePixmap(nullptr) + , m_fileSize(0) { - setWindowTitle (i18nc ("@title:window", "Save Preview")); + setWindowTitle(i18nc("@title:window", "Save Preview")); auto *baseWidget = this;//new QWidget (this); //setMainWidget (baseWidget); + auto *lay = new QGridLayout(baseWidget); - auto *lay = new QGridLayout ( baseWidget ); - - m_filePixmapLabel = new kpResizeSignallingLabel (baseWidget); - m_fileSizeLabel = new QLabel (baseWidget); - - - m_filePixmapLabel->setMinimumSize (s_pixmapLabelMinimumSize); - - - lay->addWidget (m_filePixmapLabel, 0, 0); - lay->addWidget (m_fileSizeLabel, 1, 0, Qt::AlignHCenter); + m_filePixmapLabel = new kpResizeSignallingLabel(baseWidget); + m_fileSizeLabel = new QLabel(baseWidget); + m_filePixmapLabel->setMinimumSize(s_pixmapLabelMinimumSize); - lay->setRowStretch (0, 1); + lay->addWidget(m_filePixmapLabel, 0, 0); + lay->addWidget(m_fileSizeLabel, 1, 0, Qt::AlignHCenter); + lay->setRowStretch(0, 1); - connect (m_filePixmapLabel, &kpResizeSignallingLabel::resized, - this, &kpDocumentSaveOptionsPreviewDialog::updatePixmapPreview); + connect(m_filePixmapLabel, &kpResizeSignallingLabel::resized, + this, &kpDocumentSaveOptionsPreviewDialog::updatePixmapPreview); } kpDocumentSaveOptionsPreviewDialog::~kpDocumentSaveOptionsPreviewDialog () { delete m_filePixmap; } - // public -QSize kpDocumentSaveOptionsPreviewDialog::preferredMinimumSize () const +QSize kpDocumentSaveOptionsPreviewDialog::preferredMinimumSize() const { const auto contentsWidth = 180; - const auto totalMarginsWidth = fontMetrics ().height (); + const auto totalMarginsWidth = fontMetrics().height(); - return {contentsWidth + totalMarginsWidth, contentsWidth * 3 / 4 + totalMarginsWidth}; + return { + contentsWidth + totalMarginsWidth, contentsWidth * 3 / 4 + totalMarginsWidth + }; } - // public slot -void kpDocumentSaveOptionsPreviewDialog::setFilePixmapAndSize (const QImage &pixmap, - qint64 fileSize) +void kpDocumentSaveOptionsPreviewDialog::setFilePixmapAndSize(const QImage &pixmap, qint64 fileSize) { delete m_filePixmap; - m_filePixmap = new QImage (pixmap); + m_filePixmap = new QImage(pixmap); - updatePixmapPreview (); + updatePixmapPreview(); m_fileSize = fileSize; - const kpCommandSize::SizeType pixmapSize = kpCommandSize::PixmapSize (pixmap); + const kpCommandSize::SizeType pixmapSize = kpCommandSize::PixmapSize(pixmap); // (int cast is safe as long as the file size is not more than 20 million // -- i.e. INT_MAX / 100 -- times the pixmap size) - const int percent = pixmapSize ? - qMax (1, - static_cast (static_cast (fileSize * 100 / pixmapSize))) : - 0; + const int percent = pixmapSize + ? qMax(1, + static_cast(static_cast(fileSize + * 100 + / pixmapSize))) + : 0; #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogDialogs) << "kpDocumentSaveOptionsPreviewDialog::setFilePixmapAndSize()" - << " pixmapSize=" << pixmapSize - << " fileSize=" << fileSize - << " raw fileSize/pixmapSize%=" - << (pixmapSize ? (kpCommandSize::SizeType) fileSize * 100 / pixmapSize : 0); + << " pixmapSize=" << pixmapSize + << " fileSize=" << fileSize + << " raw fileSize/pixmapSize%=" + << (pixmapSize ? (kpCommandSize::SizeType)fileSize * 100 + / pixmapSize : 0); #endif - m_fileSizeLabel->setText (i18np ("1 byte (approx. %2%)", "%1 bytes (approx. %2%)", - m_fileSize, percent)); + m_fileSizeLabel->setText(i18np("1 byte (approx. %2%)", "%1 bytes (approx. %2%)", + m_fileSize, percent)); } // public slot -void kpDocumentSaveOptionsPreviewDialog::updatePixmapPreview () +void kpDocumentSaveOptionsPreviewDialog::updatePixmapPreview() { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogDialogs) << "kpDocumentSaveOptionsPreviewDialog::updatePreviewPixmap()" - << " filePixmapLabel.size=" << m_filePixmapLabel->size () - << " filePixmap.size=" << m_filePixmap->size (); + << " filePixmapLabel.size=" << m_filePixmapLabel->size() + << " filePixmap.size=" << m_filePixmap->size(); #endif - if (m_filePixmap) - { - int maxNewWidth = qMin (m_filePixmap->width (), - m_filePixmapLabel->width ()), - maxNewHeight = qMin (m_filePixmap->height (), - m_filePixmapLabel->height ()); + if (m_filePixmap) { + int maxNewWidth = qMin(m_filePixmap->width(), + m_filePixmapLabel->width()), + maxNewHeight = qMin(m_filePixmap->height(), + m_filePixmapLabel->height()); - double keepsAspect = kpTransformPreviewDialog::aspectScale ( + double keepsAspect = kpTransformPreviewDialog::aspectScale( maxNewWidth, maxNewHeight, - m_filePixmap->width (), m_filePixmap->height ()); + m_filePixmap->width(), m_filePixmap->height()); #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogDialogs) << "\tmaxNewWidth=" << maxNewWidth - << " maxNewHeight=" << maxNewHeight - << " keepsAspect=" << keepsAspect; + << " maxNewHeight=" << maxNewHeight + << " keepsAspect=" << keepsAspect; #endif - const int newWidth = kpTransformPreviewDialog::scaleDimension ( - m_filePixmap->width (), + const int newWidth = kpTransformPreviewDialog::scaleDimension( + m_filePixmap->width(), keepsAspect, 1, maxNewWidth); - const int newHeight = kpTransformPreviewDialog::scaleDimension ( - m_filePixmap->height (), + const int newHeight = kpTransformPreviewDialog::scaleDimension( + m_filePixmap->height(), keepsAspect, 1, maxNewHeight); #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogDialogs) << "\tnewWidth=" << newWidth - << " newHeight=" << newHeight; + << " newHeight=" << newHeight; #endif - QImage transformedPixmap = - kpPixmapFX::scale (*m_filePixmap, - newWidth, newHeight); - + QImage transformedPixmap + = kpPixmapFX::scale(*m_filePixmap, + newWidth, newHeight); - QImage labelPixmap (m_filePixmapLabel->width (), - m_filePixmapLabel->height (), QImage::Format_ARGB32_Premultiplied); + QImage labelPixmap(m_filePixmapLabel->width(), + m_filePixmapLabel->height(), QImage::Format_ARGB32_Premultiplied); labelPixmap.fill(QColor(Qt::transparent).rgba()); - kpPixmapFX::setPixmapAt (&labelPixmap, - (labelPixmap.width () - transformedPixmap.width ()) / 2, - (labelPixmap.height () - transformedPixmap.height ()) / 2, - transformedPixmap); - - - m_filePixmapLabel->setPixmap (QPixmap::fromImage(labelPixmap)); - } - else - { - m_filePixmapLabel->setPixmap (QPixmap ()); + kpPixmapFX::setPixmapAt(&labelPixmap, + (labelPixmap.width() - transformedPixmap.width()) / 2, + (labelPixmap.height() - transformedPixmap.height()) / 2, + transformedPixmap); + + m_filePixmapLabel->setPixmap(QPixmap::fromImage(labelPixmap)); + } else { + m_filePixmapLabel->setPixmap(QPixmap()); } } - // protected virtual [base QWidget] -void kpDocumentSaveOptionsPreviewDialog::closeEvent (QCloseEvent *e) +void kpDocumentSaveOptionsPreviewDialog::closeEvent(QCloseEvent *e) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogDialogs) << "kpDocumentSaveOptionsPreviewDialog::closeEvent()"; #endif - QWidget::closeEvent (e); + QWidget::closeEvent(e); - emit finished (); + emit finished(); } // protected virtual [base QWidget] -void kpDocumentSaveOptionsPreviewDialog::moveEvent (QMoveEvent *e) +void kpDocumentSaveOptionsPreviewDialog::moveEvent(QMoveEvent *e) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogDialogs) << "kpDocumentSaveOptionsPreviewDialog::moveEvent()"; #endif - QWidget::moveEvent (e); + QWidget::moveEvent(e); - emit moved (); + emit moved(); } // protected virtual [base QWidget] -void kpDocumentSaveOptionsPreviewDialog::resizeEvent (QResizeEvent *e) +void kpDocumentSaveOptionsPreviewDialog::resizeEvent(QResizeEvent *e) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogDialogs) << "kpDocumentSaveOptionsPreviewDialog::resizeEvent()"; #endif - QWidget::resizeEvent (e); + QWidget::resizeEvent(e); - emit resized (); + emit resized(); } - - diff --git a/document/kpDocument.h b/document/kpDocument.h --- a/document/kpDocument.h +++ b/document/kpDocument.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_DOCUMENT_H #define KP_DOCUMENT_H - #include #include #include @@ -53,11 +50,10 @@ class kpAbstractSelection; class kpTextSelection; - // REFACTOR: rearrange method order to make sense and reflect kpDocument_*.cpp split. class kpDocument : public QObject { -Q_OBJECT + Q_OBJECT public: // REFACTOR: Hide constructor and have 2 factory methods: @@ -71,61 +67,47 @@ kpDocument (int w, int h, kpDocumentEnvironment *environ); ~kpDocument () override; - kpDocumentEnvironment *environ () const; - void setEnviron (kpDocumentEnvironment *environ); - + kpDocumentEnvironment *environ() const; + void setEnviron(kpDocumentEnvironment *environ); // // File I/O - Open // - - static QImage getPixmapFromFile (const QUrl &url, bool suppressDoesntExistDialog, - QWidget *parent, - kpDocumentSaveOptions *saveOptions = nullptr, - kpDocumentMetaInfo *metaInfo = nullptr); + static QImage getPixmapFromFile(const QUrl &url, bool suppressDoesntExistDialog, + QWidget *parent, kpDocumentSaveOptions *saveOptions = nullptr, + kpDocumentMetaInfo *metaInfo = nullptr); // REFACTOR: fix: open*() should only be called once. // Create a new kpDocument() if you want to open again. - void openNew (const QUrl &url); - bool open (const QUrl &url, bool newDocSameNameIfNotExist = false); + void openNew(const QUrl &url); + bool open(const QUrl &url, bool newDocSameNameIfNotExist = false); - static void getDataFromImage(const QImage &image, - kpDocumentSaveOptions &saveOptions, + static void getDataFromImage(const QImage &image, kpDocumentSaveOptions &saveOptions, kpDocumentMetaInfo &metaInfo); // // File I/O - Save // - static bool lossyPromptContinue (const QImage &pixmap, - const kpDocumentSaveOptions &saveOptions, - QWidget *parent); - static bool savePixmapToDevice (const QImage &pixmap, - QIODevice *device, - const kpDocumentSaveOptions &saveOptions, - const kpDocumentMetaInfo &metaInfo, - bool lossyPrompt, - QWidget *parent, - bool *userCancelled = nullptr); - static bool savePixmapToFile (const QImage &pixmap, - const QUrl &url, - const kpDocumentSaveOptions &saveOptions, - const kpDocumentMetaInfo &metaInfo, - bool overwritePrompt, - bool lossyPrompt, - QWidget *parent); - bool save (bool overwritePrompt = false, bool lossyPrompt = false); - bool saveAs (const QUrl &url, - const kpDocumentSaveOptions &saveOptions, - bool overwritePrompt = true, - bool lossyPrompt = true); - + static bool lossyPromptContinue(const QImage &pixmap, const kpDocumentSaveOptions &saveOptions, + QWidget *parent); + static bool savePixmapToDevice(const QImage &pixmap, QIODevice *device, + const kpDocumentSaveOptions &saveOptions, + const kpDocumentMetaInfo &metaInfo, bool lossyPrompt, + QWidget *parent, bool *userCancelled = nullptr); + static bool savePixmapToFile(const QImage &pixmap, const QUrl &url, + const kpDocumentSaveOptions &saveOptions, + const kpDocumentMetaInfo &metaInfo, bool overwritePrompt, + bool lossyPrompt, QWidget *parent); + bool save(bool overwritePrompt = false, bool lossyPrompt = false); + bool saveAs(const QUrl &url, const kpDocumentSaveOptions &saveOptions, + bool overwritePrompt = true, bool lossyPrompt = true); // Returns whether save() or saveAs() have ever been called and returned true - bool savedAtLeastOnceBefore () const; + bool savedAtLeastOnceBefore() const; - QUrl url () const; - void setURL (const QUrl &url, bool isFromURL); + QUrl url() const; + void setURL(const QUrl &url, bool isFromURL); // Returns whether the document's image was successfully opened from // or saved to the URL returned by url(). This is not true for a @@ -139,55 +121,53 @@ // // e.g. If the user types "kolourpaint doesnotexist.png" to start // KolourPaint, this method will return false. - bool isFromURL (bool checkURLStillExists = true) const; + bool isFromURL(bool checkURLStillExists = true) const; // (will convert: empty Url --> "Untitled") - QString prettyUrl () const; + QString prettyUrl() const; // (will convert: empty Url --> "Untitled") - QString prettyFilename () const; + QString prettyFilename() const; // (guaranteed to return valid pointer) - const kpDocumentSaveOptions *saveOptions () const; - void setSaveOptions (const kpDocumentSaveOptions &saveOptions); - - const kpDocumentMetaInfo *metaInfo () const; - void setMetaInfo (const kpDocumentMetaInfo &metaInfo); + const kpDocumentSaveOptions *saveOptions() const; + void setSaveOptions(const kpDocumentSaveOptions &saveOptions); + const kpDocumentMetaInfo *metaInfo() const; + void setMetaInfo(const kpDocumentMetaInfo &metaInfo); /* * Properties (modified, width, height, color depth...) */ - void setModified (bool yes = true); - bool isModified () const; - bool isEmpty () const; + void setModified(bool yes = true); + bool isModified() const; + bool isEmpty() const; // REFACTOR: Rename to originalWidth()? - int constructorWidth () const; // as passed to the constructor - int width (bool ofSelection = false) const; - int oldWidth () const; // only valid in a slot connected to sizeChanged() - void setWidth (int w, const kpColor &backgroundColor); + int constructorWidth() const; // as passed to the constructor + int width(bool ofSelection = false) const; + int oldWidth() const; // only valid in a slot connected to sizeChanged() + void setWidth(int w, const kpColor &backgroundColor); // REFACTOR: Rename to originalHeight()? - int constructorHeight () const; // as passed to the constructor - int height (bool ofSelection = false) const; - int oldHeight () const; // only valid in a slot connected to sizeChanged() - void setHeight (int h, const kpColor &backgroundColor); - - QRect rect (bool ofSelection = false) const; + int constructorHeight() const; // as passed to the constructor + int height(bool ofSelection = false) const; + int oldHeight() const; // only valid in a slot connected to sizeChanged() + void setHeight(int h, const kpColor &backgroundColor); + QRect rect(bool ofSelection = false) const; // // Image access // // Returns a copy of part of the document's image (not including the // selection). - kpImage getImageAt (const QRect &rect) const; + kpImage getImageAt(const QRect &rect) const; - void setImageAt (const kpImage &image, const QPoint &at); + void setImageAt(const kpImage &image, const QPoint &at); // "image(false)" returns a copy of the document's image, ignoring any // floating selection. @@ -197,23 +177,22 @@ // null if the image selection is a just a border. // // ASSUMPTION: For == true only, an image selection exists. - kpImage image (bool ofSelection = false) const; - kpImage *imagePointer () const; + kpImage image(bool ofSelection = false) const; + kpImage *imagePointer() const; - void setImage (const kpImage &image); + void setImage(const kpImage &image); // ASSUMPTION: If setting the selection's image, the selection must be // an image selection. - void setImage (bool ofSelection, const kpImage &image); - + void setImage(bool ofSelection, const kpImage &image); // // Selections // public: - kpAbstractSelection *selection () const; - kpAbstractImageSelection *imageSelection () const; - kpTextSelection *textSelection () const; + kpAbstractSelection *selection() const; + kpAbstractImageSelection *imageSelection() const; + kpTextSelection *textSelection() const; // Sets the document's selection to the given one and changes to the // matching selection tool. Tool changes occur in the following situations: @@ -241,7 +220,7 @@ // has the 's selection transparency or // for a text selection, its text style, selected. // TODO: Why can't we change it for them, if we change tool automatically for them already? - void setSelection (const kpAbstractSelection &selection); + void setSelection(const kpAbstractSelection &selection); // Returns the base image of the current image selection. If this is // null (because the selection is still a border), it extracts the @@ -251,17 +230,17 @@ // // TODO: this always returns base image - need ver that applies selection // transparency. - kpImage getSelectedBaseImage () const; + kpImage getSelectedBaseImage() const; // Sets the base image of the current image selection to the pixels // of the document marked out by the border of the selection. // // ASSUMPTION: There is an imageSelection() that is just a border // (no base image). - void imageSelectionPullFromDocument (const kpColor &backgroundColor); + void imageSelectionPullFromDocument(const kpColor &backgroundColor); // Deletes the current selection, if there is a selection(), else NOP - void selectionDelete (); + void selectionDelete(); // Stamps a copy of the selection onto the document. // @@ -271,11 +250,11 @@ // for non-image selections. // // ASSUMPTION: There is a selection() with content, else NOP - void selectionCopyOntoDocument (bool applySelTransparency = true); + void selectionCopyOntoDocument(bool applySelTransparency = true); // Same as selectionCopyOntoDocument() but deletes the selection // afterwards. - void selectionPushOntoDocument (bool applySelTransparency = true); + void selectionPushOntoDocument(bool applySelTransparency = true); // // Same as image() but returns a _copy_ of the document image @@ -294,43 +273,41 @@ // // b) with a transparent background: this makes no difference. // - kpImage imageWithSelection () const; - + kpImage imageWithSelection() const; /* * Transformations * (convenience only - you could achieve the same effect (and more) with * kpPixmapFX: these functions do not affect the selection) */ - void fill (const kpColor &color); - void resize (int w, int h, const kpColor &backgroundColor); - + void fill(const kpColor &color); + void resize(int w, int h, const kpColor &backgroundColor); public slots: // these will emit signals! - void slotContentsChanged (const QRect &rect); - void slotSizeChanged (const QSize &newSize); + void slotContentsChanged(const QRect &rect); + void slotSizeChanged(const QSize &newSize); signals: - void documentOpened (); - void documentSaved (); + void documentOpened(); + void documentSaved(); // Emitted whenever the isModified() flag changes from false to true. // This is the _only_ signal that may be emitted in addition to the others. - void documentModified (); + void documentModified(); - void contentsChanged (const QRect &rect); - void sizeChanged (int newWidth, int newHeight); // see oldWidth(), oldHeight() - void sizeChanged (const QSize &newSize); + void contentsChanged(const QRect &rect); + void sizeChanged(int newWidth, int newHeight); // see oldWidth(), oldHeight() + void sizeChanged(const QSize &newSize); - void selectionEnabled (bool on); + void selectionEnabled(bool on); // Emitted when setSelection() is given a selection such that we change // from a non-text-selection tool to the text selection tool or vice-versa. // reports whether the new selection is text (and therefore, // whether we've switched to the text tool). - void selectionIsTextChanged (bool isText); + void selectionIsTextChanged(bool isText); private: int m_constructorWidth, m_constructorHeight; @@ -355,5 +332,4 @@ struct kpDocumentPrivate *d; }; - #endif // KP_DOCUMENT_H diff --git a/document/kpDocument.cpp b/document/kpDocument.cpp --- a/document/kpDocument.cpp +++ b/document/kpDocument.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_DOCUMENT 0 - #include "kpDocument.h" #include "kpDocumentPrivate.h" @@ -46,7 +43,6 @@ #include "widgets/toolbars/kpToolToolBar.h" #include "lgpl/generic/kpUrlFormatter.h" - #include "kpLogCategories.h" #include // kdelibs4support #include @@ -64,18 +60,19 @@ //--------------------------------------------------------------------- -kpDocument::kpDocument (int w, int h, - kpDocumentEnvironment *environ) - : QObject (), - m_constructorWidth (w), m_constructorHeight (h), - m_isFromURL (false), - m_savedAtLeastOnceBefore (false), - m_saveOptions (new kpDocumentSaveOptions ()), - m_metaInfo (new kpDocumentMetaInfo ()), - m_modified (false), - m_selection (nullptr), - m_oldWidth (-1), m_oldHeight (-1), - d (new kpDocumentPrivate ()) +kpDocument::kpDocument (int w, int h, kpDocumentEnvironment *environ) + : QObject() + , m_constructorWidth(w) + , m_constructorHeight(h) + , m_isFromURL(false) + , m_savedAtLeastOnceBefore(false) + , m_saveOptions(new kpDocumentSaveOptions()) + , m_metaInfo(new kpDocumentMetaInfo()) + , m_modified(false) + , m_selection(nullptr) + , m_oldWidth(-1) + , m_oldHeight(-1) + , d(new kpDocumentPrivate()) { #if DEBUG_KP_DOCUMENT && 0 qCDebug(kpLogDocument) << "kpDocument::kpDocument (" << w << "," << h << ")"; @@ -104,48 +101,48 @@ //--------------------------------------------------------------------- // public -kpDocumentEnvironment *kpDocument::environ () const +kpDocumentEnvironment *kpDocument::environ() const { return d->environ; } //--------------------------------------------------------------------- // public -void kpDocument::setEnviron (kpDocumentEnvironment *environ) +void kpDocument::setEnviron(kpDocumentEnvironment *environ) { d->environ = environ; } //--------------------------------------------------------------------- // public -bool kpDocument::savedAtLeastOnceBefore () const +bool kpDocument::savedAtLeastOnceBefore() const { return m_savedAtLeastOnceBefore; } //--------------------------------------------------------------------- // public -QUrl kpDocument::url () const +QUrl kpDocument::url() const { return m_url; } //--------------------------------------------------------------------- // public -void kpDocument::setURL (const QUrl &url, bool isFromURL) +void kpDocument::setURL(const QUrl &url, bool isFromURL) { m_url = url; m_isFromURL = isFromURL; } //--------------------------------------------------------------------- // public -bool kpDocument::isFromURL (bool checkURLStillExists) const +bool kpDocument::isFromURL(bool checkURLStillExists) const { if (!m_isFromURL) { return false; @@ -155,55 +152,55 @@ return true; } - return (!m_url.isEmpty () && - KIO::NetAccess::exists (m_url, KIO::NetAccess::SourceSide/*open*/, - d->environ->dialogParent ())); + return !m_url.isEmpty() + && KIO::NetAccess::exists(m_url, KIO::NetAccess::SourceSide /*open*/, + d->environ->dialogParent()); } //--------------------------------------------------------------------- // public -QString kpDocument::prettyUrl () const +QString kpDocument::prettyUrl() const { - return kpUrlFormatter::PrettyUrl (m_url); + return kpUrlFormatter::PrettyUrl(m_url); } //--------------------------------------------------------------------- // public -QString kpDocument::prettyFilename () const +QString kpDocument::prettyFilename() const { - return kpUrlFormatter::PrettyFilename (m_url); + return kpUrlFormatter::PrettyFilename(m_url); } //--------------------------------------------------------------------- // public -const kpDocumentSaveOptions *kpDocument::saveOptions () const +const kpDocumentSaveOptions *kpDocument::saveOptions() const { return m_saveOptions; } //--------------------------------------------------------------------- // public -void kpDocument::setSaveOptions (const kpDocumentSaveOptions &saveOptions) +void kpDocument::setSaveOptions(const kpDocumentSaveOptions &saveOptions) { *m_saveOptions = saveOptions; } //--------------------------------------------------------------------- // public -const kpDocumentMetaInfo *kpDocument::metaInfo () const +const kpDocumentMetaInfo *kpDocument::metaInfo() const { return m_metaInfo; } //--------------------------------------------------------------------- // public -void kpDocument::setMetaInfo (const kpDocumentMetaInfo &metaInfo) +void kpDocument::setMetaInfo(const kpDocumentMetaInfo &metaInfo) { *m_metaInfo = metaInfo; } @@ -214,136 +211,134 @@ * Properties */ -void kpDocument::setModified (bool yes) +void kpDocument::setModified(bool yes) { if (yes == m_modified) { return; } m_modified = yes; if (yes) { - emit documentModified (); + emit documentModified(); } } //--------------------------------------------------------------------- -bool kpDocument::isModified () const +bool kpDocument::isModified() const { return m_modified; } //--------------------------------------------------------------------- -bool kpDocument::isEmpty () const +bool kpDocument::isEmpty() const { - return url ().isEmpty () && !isModified (); + return url().isEmpty() && !isModified(); } //--------------------------------------------------------------------- -int kpDocument::constructorWidth () const +int kpDocument::constructorWidth() const { return m_constructorWidth; } //--------------------------------------------------------------------- -int kpDocument::width (bool ofSelection) const +int kpDocument::width(bool ofSelection) const { return (ofSelection && m_selection) ? m_selection->width() : m_image->width(); } //--------------------------------------------------------------------- -int kpDocument::oldWidth () const +int kpDocument::oldWidth() const { return m_oldWidth; } //--------------------------------------------------------------------- -void kpDocument::setWidth (int w, const kpColor &backgroundColor) +void kpDocument::setWidth(int w, const kpColor &backgroundColor) { - resize (w, height (), backgroundColor); + resize(w, height(), backgroundColor); } //--------------------------------------------------------------------- -int kpDocument::constructorHeight () const +int kpDocument::constructorHeight() const { return m_constructorHeight; } //--------------------------------------------------------------------- -int kpDocument::height (bool ofSelection) const +int kpDocument::height(bool ofSelection) const { return (ofSelection && m_selection) ? m_selection->height() : m_image->height(); } //--------------------------------------------------------------------- -int kpDocument::oldHeight () const +int kpDocument::oldHeight() const { return m_oldHeight; } //--------------------------------------------------------------------- -void kpDocument::setHeight (int h, const kpColor &backgroundColor) +void kpDocument::setHeight(int h, const kpColor &backgroundColor) { - resize (width (), h, backgroundColor); + resize(width(), h, backgroundColor); } //--------------------------------------------------------------------- -QRect kpDocument::rect (bool ofSelection) const +QRect kpDocument::rect(bool ofSelection) const { return (ofSelection && m_selection) ? m_selection->boundingRect() : m_image->rect(); } //--------------------------------------------------------------------- // public -kpImage kpDocument::getImageAt (const QRect &rect) const +kpImage kpDocument::getImageAt(const QRect &rect) const { - return kpPixmapFX::getPixmapAt (*m_image, rect); + return kpPixmapFX::getPixmapAt(*m_image, rect); } //--------------------------------------------------------------------- // public -void kpDocument::setImageAt (const kpImage &image, const QPoint &at) +void kpDocument::setImageAt(const kpImage &image, const QPoint &at) { #if DEBUG_KP_DOCUMENT && 0 qCDebug(kpLogDocument) << "kpDocument::setImageAt (image (w=" - << image.width () - << ",h=" << image.height () - << "), x=" << at.x () - << ",y=" << at.y (); + << image.width() + << ",h=" << image.height() + << "), x=" << at.x() + << ",y=" << at.y(); #endif - kpPixmapFX::setPixmapAt (m_image, at, image); - slotContentsChanged (QRect (at.x (), at.y (), image.width (), image.height ())); + kpPixmapFX::setPixmapAt(m_image, at, image); + slotContentsChanged(QRect(at.x(), at.y(), image.width(), image.height())); } //--------------------------------------------------------------------- // public -kpImage kpDocument::image (bool ofSelection) const +kpImage kpDocument::image(bool ofSelection) const { kpImage ret; - if (ofSelection) - { - kpAbstractImageSelection *imageSel = imageSelection (); - Q_ASSERT (imageSel); + if (ofSelection) { + kpAbstractImageSelection *imageSel = imageSelection(); + Q_ASSERT(imageSel); - ret = imageSel->baseImage (); - } - else { + ret = imageSel->baseImage(); + } else { ret = *m_image; } @@ -353,103 +348,97 @@ //--------------------------------------------------------------------- // public -kpImage *kpDocument::imagePointer () const +kpImage *kpDocument::imagePointer() const { return m_image; } //--------------------------------------------------------------------- // public -void kpDocument::setImage (const kpImage &image) +void kpDocument::setImage(const kpImage &image) { - m_oldWidth = width (); - m_oldHeight = height (); + m_oldWidth = width(); + m_oldHeight = height(); *m_image = image; - if (m_oldWidth == width () && m_oldHeight == height ()) { - slotContentsChanged (image.rect ()); - } - else { - slotSizeChanged (QSize (width (), height ())); + if (m_oldWidth == width() && m_oldHeight == height()) { + slotContentsChanged(image.rect()); + } else { + slotSizeChanged(QSize(width(), height())); } } //--------------------------------------------------------------------- // public -void kpDocument::setImage (bool ofSelection, const kpImage &image) +void kpDocument::setImage(bool ofSelection, const kpImage &image) { - if (ofSelection) - { - kpAbstractImageSelection *imageSel = imageSelection (); + if (ofSelection) { + kpAbstractImageSelection *imageSel = imageSelection(); // Have to have an image selection in order to set its pixmap. - Q_ASSERT (imageSel); + Q_ASSERT(imageSel); - imageSel->setBaseImage (image); - } - else { - setImage (image); + imageSel->setBaseImage(image); + } else { + setImage(image); } } //--------------------------------------------------------------------- -void kpDocument::fill (const kpColor &color) +void kpDocument::fill(const kpColor &color) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "kpDocument::fill ()"; #endif m_image->fill(color.toQRgb()); - slotContentsChanged (m_image->rect ()); + slotContentsChanged(m_image->rect()); } //--------------------------------------------------------------------- -void kpDocument::resize (int w, int h, const kpColor &backgroundColor) +void kpDocument::resize(int w, int h, const kpColor &backgroundColor) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "kpDocument::resize (" << w << "," << h << ")"; #endif - m_oldWidth = width (); - m_oldHeight = height (); + m_oldWidth = width(); + m_oldHeight = height(); #if DEBUG_KP_DOCUMENT && 1 qCDebug(kpLogDocument) << "\toldWidth=" << m_oldWidth - << " oldHeight=" << m_oldHeight; + << " oldHeight=" << m_oldHeight; #endif if (w == m_oldWidth && h == m_oldHeight) { return; } - kpPixmapFX::resize (m_image, w, h, backgroundColor); + kpPixmapFX::resize(m_image, w, h, backgroundColor); - slotSizeChanged (QSize (width (), height ())); + slotSizeChanged(QSize(width(), height())); } //--------------------------------------------------------------------- -void kpDocument::slotContentsChanged (const QRect &rect) +void kpDocument::slotContentsChanged(const QRect &rect) { - setModified (); - emit contentsChanged (rect); + setModified(); + emit contentsChanged(rect); } //--------------------------------------------------------------------- -void kpDocument::slotSizeChanged (const QSize &newSize) +void kpDocument::slotSizeChanged(const QSize &newSize) { - setModified (); - emit sizeChanged (newSize.width(), newSize.height()); - emit sizeChanged (newSize); + setModified(); + emit sizeChanged(newSize.width(), newSize.height()); + emit sizeChanged(newSize); } //--------------------------------------------------------------------- - - - diff --git a/document/kpDocumentPrivate.h b/document/kpDocumentPrivate.h --- a/document/kpDocumentPrivate.h +++ b/document/kpDocumentPrivate.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,23 +24,19 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpDocumentPrivate_H #define kpDocumentPrivate_H - class kpDocumentEnvironment; - struct kpDocumentPrivate { kpDocumentPrivate () - : environ(nullptr) + : environ(nullptr) { } kpDocumentEnvironment *environ; }; - #endif // kpDocumentPrivate_H diff --git a/document/kpDocumentSaveOptions.h b/document/kpDocumentSaveOptions.h --- a/document/kpDocumentSaveOptions.h +++ b/document/kpDocumentSaveOptions.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,99 +24,86 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_DOCUMENT_SAVE_OPTIONS_H #define KP_DOCUMENT_SAVE_OPTIONS_H - class QImage; class QString; class KConfigGroup; - class kpDocumentSaveOptions { public: kpDocumentSaveOptions (); kpDocumentSaveOptions (const kpDocumentSaveOptions &rhs); kpDocumentSaveOptions (const QString &mimeType, int colorDepth, bool dither, int quality); virtual ~kpDocumentSaveOptions (); - bool operator== (const kpDocumentSaveOptions &rhs) const; - bool operator!= (const kpDocumentSaveOptions &rhs) const; - - kpDocumentSaveOptions &operator= (const kpDocumentSaveOptions &rhs); - - - void printDebug (const QString &prefix) const; - + bool operator==(const kpDocumentSaveOptions &rhs) const; + bool operator!=(const kpDocumentSaveOptions &rhs) const; - QString mimeType () const; - void setMimeType (const QString &mimeType); + kpDocumentSaveOptions &operator=(const kpDocumentSaveOptions &rhs); - static QString invalidMimeType (); - static bool mimeTypeIsInvalid (const QString &mimeType); - bool mimeTypeIsInvalid () const; + void printDebug(const QString &prefix) const; + QString mimeType() const; + void setMimeType(const QString &mimeType); - int colorDepth () const; - void setColorDepth (int depth); + static QString invalidMimeType(); + static bool mimeTypeIsInvalid(const QString &mimeType); + bool mimeTypeIsInvalid() const; - static int invalidColorDepth (); - static bool colorDepthIsInvalid (int colorDepth); - bool colorDepthIsInvalid () const; + int colorDepth() const; + void setColorDepth(int depth); + static int invalidColorDepth(); + static bool colorDepthIsInvalid(int colorDepth); + bool colorDepthIsInvalid() const; - bool dither () const; - void setDither (bool dither); + bool dither() const; + void setDither(bool dither); - static int initialDither (); + static int initialDither(); + int quality() const; + void setQuality(int quality); - int quality () const; - void setQuality (int quality); - - static int invalidQuality (); - static bool qualityIsInvalid (int quality); - bool qualityIsInvalid () const; - + static int invalidQuality(); + static bool qualityIsInvalid(int quality); + bool qualityIsInvalid() const; // (All assume that 's group has been set) // (None of them call KConfigBase::reparseConfig() nor KConfigBase::sync()) - static QString defaultMimeType (const KConfigGroup &config); - static void saveDefaultMimeType (KConfigGroup &config, const QString &mimeType); + static QString defaultMimeType(const KConfigGroup &config); + static void saveDefaultMimeType(KConfigGroup &config, const QString &mimeType); - static int defaultColorDepth (const KConfigGroup &config); - static void saveDefaultColorDepth (KConfigGroup &config, int colorDepth); + static int defaultColorDepth(const KConfigGroup &config); + static void saveDefaultColorDepth(KConfigGroup &config, int colorDepth); - static int defaultDither (const KConfigGroup &config); - static void saveDefaultDither (KConfigGroup &config, bool dither); + static int defaultDither(const KConfigGroup &config); + static void saveDefaultDither(KConfigGroup &config, bool dither); - static int defaultQuality (const KConfigGroup &config); - static void saveDefaultQuality (KConfigGroup &config, int quality); + static int defaultQuality(const KConfigGroup &config); + static void saveDefaultQuality(KConfigGroup &config, int quality); - - static kpDocumentSaveOptions defaultDocumentSaveOptions (const KConfigGroup &config); + static kpDocumentSaveOptions defaultDocumentSaveOptions(const KConfigGroup &config); // (returns true if it encountered a difference (and saved it to )) - static bool saveDefaultDifferences (KConfigGroup &config, - const kpDocumentSaveOptions &oldDocInfo, - const kpDocumentSaveOptions &newDocInfo); - + static bool saveDefaultDifferences(KConfigGroup &config, + const kpDocumentSaveOptions &oldDocInfo, + const kpDocumentSaveOptions &newDocInfo); public: // (purely for informational purposes - not enforced by this class) - static int mimeTypeMaximumColorDepth (const QString &mimeType); - int mimeTypeMaximumColorDepth () const; + static int mimeTypeMaximumColorDepth(const QString &mimeType); + int mimeTypeMaximumColorDepth() const; + static bool mimeTypeHasConfigurableColorDepth(const QString &mimeType); + bool mimeTypeHasConfigurableColorDepth() const; - static bool mimeTypeHasConfigurableColorDepth (const QString &mimeType); - bool mimeTypeHasConfigurableColorDepth () const; - - static bool mimeTypeHasConfigurableQuality (const QString &mimeType); - bool mimeTypeHasConfigurableQuality () const; - + static bool mimeTypeHasConfigurableQuality(const QString &mimeType); + bool mimeTypeHasConfigurableQuality() const; // TODO: checking for mask loss due to format e.g. BMP enum LossyType @@ -136,15 +122,13 @@ // Returns whether saving with these options will result in // loss of information. Returned value is the bitwise OR of // LossType enum possiblities. - int isLossyForSaving (const QImage &image) const; - + int isLossyForSaving(const QImage &image) const; private: // There is no need to maintain binary compatibility at this stage. // The d-pointer is just so that you can experiment without recompiling // the kitchen sink. class kpDocumentSaveOptionsPrivate *d; }; - #endif // KP_DOCUMENT_SAVE_OPTIONS_H diff --git a/document/kpDocumentSaveOptions.cpp b/document/kpDocumentSaveOptions.cpp --- a/document/kpDocumentSaveOptions.cpp +++ b/document/kpDocumentSaveOptions.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_DOCUMENT_SAVE_OPTIONS 0 - #include "kpDocumentSaveOptions.h" #include "kpDefs.h" @@ -55,29 +53,30 @@ //--------------------------------------------------------------------- kpDocumentSaveOptions::kpDocumentSaveOptions () - : d (new kpDocumentSaveOptionsPrivate ()) + : d(new kpDocumentSaveOptionsPrivate()) { - d->m_mimeType = invalidMimeType (); - d->m_colorDepth = invalidColorDepth (); - d->m_dither = initialDither (); - d->m_quality = invalidQuality (); + d->m_mimeType = invalidMimeType(); + d->m_colorDepth = invalidColorDepth(); + d->m_dither = initialDither(); + d->m_quality = invalidQuality(); } //--------------------------------------------------------------------- kpDocumentSaveOptions::kpDocumentSaveOptions (const kpDocumentSaveOptions &rhs) - : d (new kpDocumentSaveOptionsPrivate ()) + : d(new kpDocumentSaveOptionsPrivate()) { - d->m_mimeType = rhs.mimeType (); - d->m_colorDepth = rhs.colorDepth (); - d->m_dither = rhs.dither (); - d->m_quality = rhs.quality (); + d->m_mimeType = rhs.mimeType(); + d->m_colorDepth = rhs.colorDepth(); + d->m_dither = rhs.dither(); + d->m_quality = rhs.quality(); } //--------------------------------------------------------------------- -kpDocumentSaveOptions::kpDocumentSaveOptions (const QString &mimeType, int colorDepth, bool dither, int quality) - : d (new kpDocumentSaveOptionsPrivate ()) +kpDocumentSaveOptions::kpDocumentSaveOptions (const QString &mimeType, int colorDepth, bool dither, + int quality) + : d(new kpDocumentSaveOptionsPrivate()) { d->m_mimeType = mimeType; d->m_colorDepth = colorDepth; @@ -94,207 +93,192 @@ //--------------------------------------------------------------------- - // public -bool kpDocumentSaveOptions::operator== (const kpDocumentSaveOptions &rhs) const +bool kpDocumentSaveOptions::operator==(const kpDocumentSaveOptions &rhs) const { - return (mimeType () == rhs.mimeType () && - colorDepth () == rhs.colorDepth () && - dither () == rhs.dither () && - quality () == rhs.quality ()); + return mimeType() == rhs.mimeType() + && colorDepth() == rhs.colorDepth() + && dither() == rhs.dither() + && quality() == rhs.quality(); } //--------------------------------------------------------------------- // public -bool kpDocumentSaveOptions::operator!= (const kpDocumentSaveOptions &rhs) const +bool kpDocumentSaveOptions::operator!=(const kpDocumentSaveOptions &rhs) const { return !(*this == rhs); } //--------------------------------------------------------------------- - // public -kpDocumentSaveOptions &kpDocumentSaveOptions::operator= (const kpDocumentSaveOptions &rhs) +kpDocumentSaveOptions &kpDocumentSaveOptions::operator=(const kpDocumentSaveOptions &rhs) { - setMimeType (rhs.mimeType ()); - setColorDepth (rhs.colorDepth ()); - setDither (rhs.dither ()); - setQuality (rhs.quality ()); + setMimeType(rhs.mimeType()); + setColorDepth(rhs.colorDepth()); + setDither(rhs.dither()); + setQuality(rhs.quality()); return *this; } //--------------------------------------------------------------------- - // public -void kpDocumentSaveOptions::printDebug (const QString &prefix) const +void kpDocumentSaveOptions::printDebug(const QString &prefix) const { - const QString usedPrefix = !prefix.isEmpty () ? - prefix + QLatin1String (": ") : - QString(); + const QString usedPrefix = !prefix.isEmpty() + ? prefix + QLatin1String(": ") + : QString(); qCDebug(kpLogDocument) << usedPrefix - << "mimeType=" << mimeType () - << " colorDepth=" << colorDepth () - << " dither=" << dither () - << " quality=" << quality (); + << "mimeType=" << mimeType() + << " colorDepth=" << colorDepth() + << " dither=" << dither() + << " quality=" << quality(); } //--------------------------------------------------------------------- - // public -QString kpDocumentSaveOptions::mimeType () const +QString kpDocumentSaveOptions::mimeType() const { return d->m_mimeType; } //--------------------------------------------------------------------- // public -void kpDocumentSaveOptions::setMimeType (const QString &mimeType) +void kpDocumentSaveOptions::setMimeType(const QString &mimeType) { d->m_mimeType = mimeType; } //--------------------------------------------------------------------- - // public static -QString kpDocumentSaveOptions::invalidMimeType () +QString kpDocumentSaveOptions::invalidMimeType() { return {}; } //--------------------------------------------------------------------- // public static -bool kpDocumentSaveOptions::mimeTypeIsInvalid (const QString &mimeType) +bool kpDocumentSaveOptions::mimeTypeIsInvalid(const QString &mimeType) { - return (mimeType == invalidMimeType ()); + return mimeType == invalidMimeType(); } //--------------------------------------------------------------------- // public -bool kpDocumentSaveOptions::mimeTypeIsInvalid () const +bool kpDocumentSaveOptions::mimeTypeIsInvalid() const { - return mimeTypeIsInvalid (mimeType ()); + return mimeTypeIsInvalid(mimeType()); } //--------------------------------------------------------------------- - // public -int kpDocumentSaveOptions::colorDepth () const +int kpDocumentSaveOptions::colorDepth() const { return d->m_colorDepth; } // public -void kpDocumentSaveOptions::setColorDepth (int depth) +void kpDocumentSaveOptions::setColorDepth(int depth) { d->m_colorDepth = depth; } - // public static -int kpDocumentSaveOptions::invalidColorDepth () +int kpDocumentSaveOptions::invalidColorDepth() { return -1; } // public static -bool kpDocumentSaveOptions::colorDepthIsInvalid (int colorDepth) +bool kpDocumentSaveOptions::colorDepthIsInvalid(int colorDepth) { - return (colorDepth != 1 && colorDepth != 8 && colorDepth != 32); + return colorDepth != 1 && colorDepth != 8 && colorDepth != 32; } // public -bool kpDocumentSaveOptions::colorDepthIsInvalid () const +bool kpDocumentSaveOptions::colorDepthIsInvalid() const { - return colorDepthIsInvalid (colorDepth ()); + return colorDepthIsInvalid(colorDepth()); } - // public -bool kpDocumentSaveOptions::dither () const +bool kpDocumentSaveOptions::dither() const { return d->m_dither; } // public -void kpDocumentSaveOptions::setDither (bool dither) +void kpDocumentSaveOptions::setDither(bool dither) { d->m_dither = dither; } - // public static -int kpDocumentSaveOptions::initialDither () +int kpDocumentSaveOptions::initialDither() { return false; // to avoid accidental double dithering } - // public -int kpDocumentSaveOptions::quality () const +int kpDocumentSaveOptions::quality() const { return d->m_quality; } // public -void kpDocumentSaveOptions::setQuality (int quality) +void kpDocumentSaveOptions::setQuality(int quality) { d->m_quality = quality; } - // public static -int kpDocumentSaveOptions::invalidQuality () +int kpDocumentSaveOptions::invalidQuality() { return -2; } // public static -bool kpDocumentSaveOptions::qualityIsInvalid (int quality) +bool kpDocumentSaveOptions::qualityIsInvalid(int quality) { - return (quality < -1 || quality > 100); + return quality < -1 || quality > 100; } // public -bool kpDocumentSaveOptions::qualityIsInvalid () const +bool kpDocumentSaveOptions::qualityIsInvalid() const { - return qualityIsInvalid (quality ()); + return qualityIsInvalid(quality()); } - // public static -QString kpDocumentSaveOptions::defaultMimeType (const KConfigGroup &config) +QString kpDocumentSaveOptions::defaultMimeType(const KConfigGroup &config) { - return config.readEntry (kpSettingForcedMimeType, - QStringLiteral ("image/png")); + return config.readEntry(kpSettingForcedMimeType, + QStringLiteral("image/png")); } // public static -void kpDocumentSaveOptions::saveDefaultMimeType (KConfigGroup &config, - const QString &mimeType) +void kpDocumentSaveOptions::saveDefaultMimeType(KConfigGroup &config, const QString &mimeType) { - config.writeEntry (kpSettingForcedMimeType, mimeType); + config.writeEntry(kpSettingForcedMimeType, mimeType); } - // public static -int kpDocumentSaveOptions::defaultColorDepth (const KConfigGroup &config) +int kpDocumentSaveOptions::defaultColorDepth(const KConfigGroup &config) { - int colorDepth = - config.readEntry (kpSettingForcedColorDepth, -1); + int colorDepth + = config.readEntry(kpSettingForcedColorDepth, -1); - if (colorDepthIsInvalid (colorDepth)) - { + if (colorDepthIsInvalid(colorDepth)) { // (not screen depth, in case of transparency) colorDepth = 32; } @@ -305,147 +289,135 @@ //--------------------------------------------------------------------- // public static -void kpDocumentSaveOptions::saveDefaultColorDepth (KConfigGroup &config, int colorDepth) +void kpDocumentSaveOptions::saveDefaultColorDepth(KConfigGroup &config, int colorDepth) { - config.writeEntry (kpSettingForcedColorDepth, colorDepth); + config.writeEntry(kpSettingForcedColorDepth, colorDepth); } //--------------------------------------------------------------------- - // public static -int kpDocumentSaveOptions::defaultDither (const KConfigGroup &config) +int kpDocumentSaveOptions::defaultDither(const KConfigGroup &config) { - return config.readEntry (kpSettingForcedDither, initialDither ()); + return config.readEntry(kpSettingForcedDither, initialDither()); } //--------------------------------------------------------------------- // public static -void kpDocumentSaveOptions::saveDefaultDither (KConfigGroup &config, bool dither) +void kpDocumentSaveOptions::saveDefaultDither(KConfigGroup &config, bool dither) { - config.writeEntry (kpSettingForcedDither, dither); + config.writeEntry(kpSettingForcedDither, dither); } //--------------------------------------------------------------------- - // public static -int kpDocumentSaveOptions::defaultQuality (const KConfigGroup &config) +int kpDocumentSaveOptions::defaultQuality(const KConfigGroup &config) { - int val = config.readEntry (kpSettingForcedQuality, -1); + int val = config.readEntry(kpSettingForcedQuality, -1); - return qualityIsInvalid (val) ? -1 : val; + return qualityIsInvalid(val) ? -1 : val; } //--------------------------------------------------------------------- // public static -void kpDocumentSaveOptions::saveDefaultQuality (KConfigGroup &config, int quality) +void kpDocumentSaveOptions::saveDefaultQuality(KConfigGroup &config, int quality) { - config.writeEntry (kpSettingForcedQuality, quality); + config.writeEntry(kpSettingForcedQuality, quality); } //--------------------------------------------------------------------- - // public static -kpDocumentSaveOptions kpDocumentSaveOptions::defaultDocumentSaveOptions (const KConfigGroup &config) +kpDocumentSaveOptions kpDocumentSaveOptions::defaultDocumentSaveOptions(const KConfigGroup &config) { kpDocumentSaveOptions saveOptions; - saveOptions.setMimeType (defaultMimeType (config)); - saveOptions.setColorDepth (defaultColorDepth (config)); - saveOptions.setDither (defaultDither (config)); - saveOptions.setQuality (defaultQuality (config)); + saveOptions.setMimeType(defaultMimeType(config)); + saveOptions.setColorDepth(defaultColorDepth(config)); + saveOptions.setDither(defaultDither(config)); + saveOptions.setQuality(defaultQuality(config)); #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS - saveOptions.printDebug ("kpDocumentSaveOptions::defaultDocumentSaveOptions()"); + saveOptions.printDebug("kpDocumentSaveOptions::defaultDocumentSaveOptions()"); #endif return saveOptions; } //--------------------------------------------------------------------- // public static -bool kpDocumentSaveOptions::saveDefaultDifferences (KConfigGroup &config, - const kpDocumentSaveOptions &oldDocInfo, - const kpDocumentSaveOptions &newDocInfo) +bool kpDocumentSaveOptions::saveDefaultDifferences(KConfigGroup &config, + const kpDocumentSaveOptions &oldDocInfo, + const kpDocumentSaveOptions &newDocInfo) { bool savedSomething = false; #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS qCDebug(kpLogDocument) << "kpDocumentSaveOptions::saveDefaultDifferences()"; - oldDocInfo.printDebug ("\told"); - newDocInfo.printDebug ("\tnew"); + oldDocInfo.printDebug("\told"); + newDocInfo.printDebug("\tnew"); #endif - if (newDocInfo.mimeType () != oldDocInfo.mimeType ()) - { - saveDefaultMimeType (config, newDocInfo.mimeType ()); + if (newDocInfo.mimeType() != oldDocInfo.mimeType()) { + saveDefaultMimeType(config, newDocInfo.mimeType()); savedSomething = true; } - if (newDocInfo.colorDepth () != oldDocInfo.colorDepth ()) - { - saveDefaultColorDepth (config, newDocInfo.colorDepth ()); + if (newDocInfo.colorDepth() != oldDocInfo.colorDepth()) { + saveDefaultColorDepth(config, newDocInfo.colorDepth()); savedSomething = true; } - if (newDocInfo.dither () != oldDocInfo.dither ()) - { - saveDefaultDither (config, newDocInfo.dither ()); + if (newDocInfo.dither() != oldDocInfo.dither()) { + saveDefaultDither(config, newDocInfo.dither()); savedSomething = true; } - if (newDocInfo.quality () != oldDocInfo.quality ()) - { - saveDefaultQuality (config, newDocInfo.quality ()); + if (newDocInfo.quality() != oldDocInfo.quality()) { + saveDefaultQuality(config, newDocInfo.quality()); savedSomething = true; } return savedSomething; } //--------------------------------------------------------------------- - -static QStringList mimeTypesSupportingProperty (const QString &property, - const QStringList &defaultMimeTypesWithPropertyList) +static QStringList mimeTypesSupportingProperty(const QString &property, + const QStringList &defaultMimeTypesWithPropertyList) { QStringList mimeTypeList; - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupMimeTypeProperties); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupMimeTypeProperties); - if (cfg.hasKey (property)) - { - mimeTypeList = cfg.readEntry (property, QStringList ()); - } - else - { + if (cfg.hasKey(property)) { + mimeTypeList = cfg.readEntry(property, QStringList()); + } else { mimeTypeList = defaultMimeTypesWithPropertyList; - cfg.writeEntry (property, mimeTypeList); - cfg.sync (); + cfg.writeEntry(property, mimeTypeList); + cfg.sync(); } return mimeTypeList; } //--------------------------------------------------------------------- -static bool mimeTypeSupportsProperty (const QString &mimeType, - const QString &property, const QStringList &defaultMimeTypesWithPropertyList) +static bool mimeTypeSupportsProperty(const QString &mimeType, const QString &property, + const QStringList &defaultMimeTypesWithPropertyList) { - const auto mimeTypeList = mimeTypesSupportingProperty ( + const auto mimeTypeList = mimeTypesSupportingProperty( property, defaultMimeTypesWithPropertyList); - return mimeTypeList.contains (mimeType); + return mimeTypeList.contains(mimeType); } //--------------------------------------------------------------------- - // SYNC: update mime info // // Only care about writable mimetypes. @@ -488,35 +460,31 @@ // mimetype with all depths and read each one back. See what // kpDocument thinks the depth is when it gets QImage to read it. - // public static -int kpDocumentSaveOptions::mimeTypeMaximumColorDepth (const QString &mimeType) +int kpDocumentSaveOptions::mimeTypeMaximumColorDepth(const QString &mimeType) { QStringList defaultList; // SYNC: update mime info here // Grayscale actually (unenforced since depth not set to configurable) - defaultList << QStringLiteral ("image/x-eps:32"); + defaultList << QStringLiteral("image/x-eps:32"); - defaultList << QStringLiteral ("image/x-portable-bitmap:1"); + defaultList << QStringLiteral("image/x-portable-bitmap:1"); // Grayscale actually (unenforced since depth not set to configurable) - defaultList << QStringLiteral ("image/x-portable-graymap:8"); + defaultList << QStringLiteral("image/x-portable-graymap:8"); - defaultList << QStringLiteral ("image/x-xbitmap:1"); + defaultList << QStringLiteral("image/x-xbitmap:1"); - const auto mimeTypeList = mimeTypesSupportingProperty ( + const auto mimeTypeList = mimeTypesSupportingProperty( kpSettingMimeTypeMaximumColorDepth, defaultList); - const QString mimeTypeColon = mimeType + QLatin1String (":"); - for (const auto & it : mimeTypeList) - { - if (it.startsWith (mimeTypeColon)) - { - int number = it.midRef (mimeTypeColon.length ()).toInt (); - if (!colorDepthIsInvalid (number)) - { + const QString mimeTypeColon = mimeType + QLatin1String(":"); + for (const auto &it : mimeTypeList) { + if (it.startsWith(mimeTypeColon)) { + int number = it.midRef(mimeTypeColon.length()).toInt(); + if (!colorDepthIsInvalid(number)) { return number; } } @@ -528,91 +496,88 @@ //--------------------------------------------------------------------- // public -int kpDocumentSaveOptions::mimeTypeMaximumColorDepth () const +int kpDocumentSaveOptions::mimeTypeMaximumColorDepth() const { - return mimeTypeMaximumColorDepth (mimeType ()); + return mimeTypeMaximumColorDepth(mimeType()); } //--------------------------------------------------------------------- // public static -bool kpDocumentSaveOptions::mimeTypeHasConfigurableColorDepth (const QString &mimeType) +bool kpDocumentSaveOptions::mimeTypeHasConfigurableColorDepth(const QString &mimeType) { QStringList defaultMimeTypes; // SYNC: update mime info here - defaultMimeTypes << QStringLiteral ("image/png"); - defaultMimeTypes << QStringLiteral ("image/bmp"); - defaultMimeTypes << QStringLiteral ("image/x-pcx"); + defaultMimeTypes << QStringLiteral("image/png"); + defaultMimeTypes << QStringLiteral("image/bmp"); + defaultMimeTypes << QStringLiteral("image/x-pcx"); // TODO: Only 1, 24 not 8; Qt only sees 32 but "file" cmd realizes // it's either 1 or 24. - defaultMimeTypes << QStringLiteral ("image/x-rgb"); + defaultMimeTypes << QStringLiteral("image/x-rgb"); // TODO: Only 8 and 24 - no 1. - defaultMimeTypes << QStringLiteral ("image/x-xpixmap"); + defaultMimeTypes << QStringLiteral("image/x-xpixmap"); - return mimeTypeSupportsProperty (mimeType, - kpSettingMimeTypeHasConfigurableColorDepth, - defaultMimeTypes); + return mimeTypeSupportsProperty(mimeType, + kpSettingMimeTypeHasConfigurableColorDepth, + defaultMimeTypes); } //--------------------------------------------------------------------- // public -bool kpDocumentSaveOptions::mimeTypeHasConfigurableColorDepth () const +bool kpDocumentSaveOptions::mimeTypeHasConfigurableColorDepth() const { - return mimeTypeHasConfigurableColorDepth (mimeType ()); + return mimeTypeHasConfigurableColorDepth(mimeType()); } //--------------------------------------------------------------------- // public static -bool kpDocumentSaveOptions::mimeTypeHasConfigurableQuality (const QString &mimeType) +bool kpDocumentSaveOptions::mimeTypeHasConfigurableQuality(const QString &mimeType) { QStringList defaultMimeTypes; // SYNC: update mime info here - defaultMimeTypes << QStringLiteral ("image/jp2"); - defaultMimeTypes << QStringLiteral ("image/jpeg"); - defaultMimeTypes << QStringLiteral ("image/x-webp"); + defaultMimeTypes << QStringLiteral("image/jp2"); + defaultMimeTypes << QStringLiteral("image/jpeg"); + defaultMimeTypes << QStringLiteral("image/x-webp"); - return mimeTypeSupportsProperty (mimeType, - kpSettingMimeTypeHasConfigurableQuality, - defaultMimeTypes); + return mimeTypeSupportsProperty(mimeType, + kpSettingMimeTypeHasConfigurableQuality, + defaultMimeTypes); } //--------------------------------------------------------------------- // public -bool kpDocumentSaveOptions::mimeTypeHasConfigurableQuality () const +bool kpDocumentSaveOptions::mimeTypeHasConfigurableQuality() const { - return mimeTypeHasConfigurableQuality (mimeType ()); + return mimeTypeHasConfigurableQuality(mimeType()); } //--------------------------------------------------------------------- // public -int kpDocumentSaveOptions::isLossyForSaving (const QImage &image) const +int kpDocumentSaveOptions::isLossyForSaving(const QImage &image) const { auto ret = 0; - if (mimeTypeMaximumColorDepth () < image.depth ()) - { + if (mimeTypeMaximumColorDepth() < image.depth()) { ret |= MimeTypeMaximumColorDepthLow; } - if (mimeTypeHasConfigurableColorDepth () && - !colorDepthIsInvalid () /*REFACTOR: guarantee it is valid*/ && - ((colorDepth () < image.depth ()) || - (colorDepth () < 32 && image.hasAlphaChannel()))) - { + if (mimeTypeHasConfigurableColorDepth() + && !colorDepthIsInvalid() /*REFACTOR: guarantee it is valid*/ + && ((colorDepth() < image.depth()) + || (colorDepth() < 32 && image.hasAlphaChannel()))) { ret |= ColorDepthLow; } - if (mimeTypeHasConfigurableQuality () && - !qualityIsInvalid ()) - { + if (mimeTypeHasConfigurableQuality() + && !qualityIsInvalid()) { ret |= Quality; } diff --git a/document/kpDocument_Open.cpp b/document/kpDocument_Open.cpp --- a/document/kpDocument_Open.cpp +++ b/document/kpDocument_Open.cpp @@ -24,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_DOCUMENT 0 - #include "kpDocument.h" #include "kpDocumentPrivate.h" @@ -43,7 +41,6 @@ #include "lgpl/generic/kpUrlFormatter.h" #include "views/manager/kpViewManager.h" - #include #include #include @@ -56,55 +53,51 @@ //--------------------------------------------------------------------- -void kpDocument::getDataFromImage(const QImage &image, - kpDocumentSaveOptions &saveOptions, +void kpDocument::getDataFromImage(const QImage &image, kpDocumentSaveOptions &saveOptions, kpDocumentMetaInfo &metaInfo) { - saveOptions.setColorDepth(image.depth()); - saveOptions.setDither(false); // avoid double dithering when saving + saveOptions.setColorDepth(image.depth()); + saveOptions.setDither(false); // avoid double dithering when saving - metaInfo.setDotsPerMeterX(image.dotsPerMeterX()); - metaInfo.setDotsPerMeterY(image.dotsPerMeterY()); - metaInfo.setOffset(image.offset()); + metaInfo.setDotsPerMeterX(image.dotsPerMeterX()); + metaInfo.setDotsPerMeterY(image.dotsPerMeterY()); + metaInfo.setOffset(image.offset()); - QStringList keys = image.textKeys(); - for (int i = 0; i < keys.count(); i++) { - metaInfo.setText(keys[i], image.text(keys[i])); - } + QStringList keys = image.textKeys(); + for (int i = 0; i < keys.count(); i++) { + metaInfo.setText(keys[i], image.text(keys[i])); + } } //--------------------------------------------------------------------- // public static QImage kpDocument::getPixmapFromFile(const QUrl &url, bool suppressDoesntExistDialog, - QWidget *parent, - kpDocumentSaveOptions *saveOptions, + QWidget *parent, kpDocumentSaveOptions *saveOptions, kpDocumentMetaInfo *metaInfo) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "kpDocument::getPixmapFromFile(" << url << "," << parent << ")"; #endif if (saveOptions) { - *saveOptions = kpDocumentSaveOptions (); + *saveOptions = kpDocumentSaveOptions(); } if (metaInfo) { - *metaInfo = kpDocumentMetaInfo (); + *metaInfo = kpDocumentMetaInfo(); } QString tempFile; - if (url.isEmpty () || !KIO::NetAccess::download (url, tempFile, parent)) - { - if (!suppressDoesntExistDialog) - { + if (url.isEmpty() || !KIO::NetAccess::download(url, tempFile, parent)) { + if (!suppressDoesntExistDialog) { // TODO: Use "Cannot" instead of "Could not" in all dialogs in KolourPaint. // Or at least choose one consistently. // // TODO: Have captions for all dialogs in KolourPaint. - KMessageBox::sorry (parent, - i18n ("Could not open \"%1\".", - kpUrlFormatter::PrettyFilename (url))); + KMessageBox::sorry(parent, + i18n("Could not open \"%1\".", + kpUrlFormatter::PrettyFilename(url))); } return {}; @@ -120,7 +113,7 @@ #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\ttempFile=" << tempFile; qCDebug(kpLogDocument) << "\tmimetype=" << mimeType.name(); - qCDebug(kpLogDocument) << "\tsrc=" << url.path (); + qCDebug(kpLogDocument) << "\tsrc=" << url.path(); #endif QImageReader reader(tempFile); @@ -131,113 +124,106 @@ KIO::NetAccess::removeTempFile(tempFile); - if (image.isNull ()) - { - KMessageBox::sorry (parent, - i18n ("Could not open \"%1\" - unsupported image format.\n" - "The file may be corrupt.", - kpUrlFormatter::PrettyFilename (url))); + if (image.isNull()) { + KMessageBox::sorry(parent, + i18n("Could not open \"%1\" - unsupported image format.\n" + "The file may be corrupt.", + kpUrlFormatter::PrettyFilename(url))); return {}; } #if DEBUG_KP_DOCUMENT - qCDebug(kpLogDocument) << "\tpixmap: depth=" << image.depth () - << " hasAlphaChannel=" << image.hasAlphaChannel (); + qCDebug(kpLogDocument) << "\tpixmap: depth=" << image.depth() + << " hasAlphaChannel=" << image.hasAlphaChannel(); #endif - if ( saveOptions && metaInfo ) { + if (saveOptions && metaInfo) { getDataFromImage(image, *saveOptions, *metaInfo); } // make sure we always have Format_ARGB32_Premultiplied as this is the fastest to draw on // and Qt can not draw onto Format_Indexed8 (Qt-4.7) - if ( image.format() != QImage::Format_ARGB32_Premultiplied ) { - image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); + if (image.format() != QImage::Format_ARGB32_Premultiplied) { + image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); } return image; } //--------------------------------------------------------------------- -void kpDocument::openNew (const QUrl &url) +void kpDocument::openNew(const QUrl &url) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "kpDocument::openNew (" << url << ")"; #endif m_image->fill(QColor(Qt::white).rgb()); - setURL (url, false/*not from url*/); + setURL(url, false /*not from url*/); - *m_saveOptions = kpDocumentSaveOptions (); + *m_saveOptions = kpDocumentSaveOptions(); - if ( !url.isEmpty() ) - { - // guess the mimetype from url's filename extension. - // - // That way "kolourpaint doesnotexist.bmp" automatically - // selects the BMP file format when the save dialog comes up for - // the first time. + if (!url.isEmpty()) { + // guess the mimetype from url's filename extension. + // + // That way "kolourpaint doesnotexist.bmp" automatically + // selects the BMP file format when the save dialog comes up for + // the first time. - QMimeDatabase mimeDb; - m_saveOptions->setMimeType(mimeDb.mimeTypeForUrl(url).name()); + QMimeDatabase mimeDb; + m_saveOptions->setMimeType(mimeDb.mimeTypeForUrl(url).name()); } - *m_metaInfo = kpDocumentMetaInfo (); + *m_metaInfo = kpDocumentMetaInfo(); m_modified = false; - emit documentOpened (); + emit documentOpened(); } //--------------------------------------------------------------------- -bool kpDocument::open (const QUrl &url, bool newDocSameNameIfNotExist) +bool kpDocument::open(const QUrl &url, bool newDocSameNameIfNotExist) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "kpDocument::open (" << url << ")"; #endif kpDocumentSaveOptions newSaveOptions; kpDocumentMetaInfo newMetaInfo; - QImage newPixmap = kpDocument::getPixmapFromFile (url, - newDocSameNameIfNotExist/*suppress "doesn't exist" dialog*/, - d->environ->dialogParent (), - &newSaveOptions, - &newMetaInfo); - - if (!newPixmap.isNull ()) - { + QImage newPixmap = kpDocument::getPixmapFromFile(url, + newDocSameNameIfNotExist /*suppress "doesn't exist" dialog*/, + d->environ->dialogParent(), + &newSaveOptions, + &newMetaInfo); + + if (!newPixmap.isNull()) { delete m_image; - m_image = new kpImage (newPixmap); + m_image = new kpImage(newPixmap); - setURL (url, true/*is from url*/); + setURL(url, true /*is from url*/); *m_saveOptions = newSaveOptions; *m_metaInfo = newMetaInfo; m_modified = false; - emit documentOpened (); + emit documentOpened(); return true; } - if (newDocSameNameIfNotExist) - { - if (!url.isEmpty () && - // not just a permission error? - !KIO::NetAccess::exists (url, KIO::NetAccess::SourceSide/*open*/, d->environ->dialogParent ())) - { - openNew (url); - } - else - { - openNew (QUrl ()); + if (newDocSameNameIfNotExist) { + if (!url.isEmpty() + &&// not just a permission error? + !KIO::NetAccess::exists(url, KIO::NetAccess::SourceSide /*open*/, + d->environ->dialogParent())) { + openNew(url); + } else { + openNew(QUrl()); } return true; } return false; - } //--------------------------------------------------------------------- diff --git a/document/kpDocument_Save.cpp b/document/kpDocument_Save.cpp --- a/document/kpDocument_Save.cpp +++ b/document/kpDocument_Save.cpp @@ -24,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_DOCUMENT 0 - #include "kpDocument.h" #include "kpDocumentPrivate.h" - #include #include #include @@ -65,94 +62,90 @@ #include "lgpl/generic/kpUrlFormatter.h" #include "views/manager/kpViewManager.h" - -bool kpDocument::save (bool overwritePrompt, bool lossyPrompt) +bool kpDocument::save(bool overwritePrompt, bool lossyPrompt) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "kpDocument::save(" - << "overwritePrompt=" << overwritePrompt - << ",lossyPrompt=" << lossyPrompt - << ") url=" << m_url - << " savedAtLeastOnceBefore=" << savedAtLeastOnceBefore (); + << "overwritePrompt=" << overwritePrompt + << ",lossyPrompt=" << lossyPrompt + << ") url=" << m_url + << " savedAtLeastOnceBefore=" << savedAtLeastOnceBefore(); #endif // TODO: check feels weak - if (m_url.isEmpty () || m_saveOptions->mimeType ().isEmpty ()) - { - KMessageBox::detailedError (d->environ->dialogParent (), - i18n ("Could not save image - insufficient information."), - i18n ("URL: %1\n" - "Mimetype: %2", - prettyUrl (), - m_saveOptions->mimeType ().isEmpty () ? - i18n ("") : - m_saveOptions->mimeType ()), - i18nc ("@title:window", "Internal Error")); + if (m_url.isEmpty() || m_saveOptions->mimeType().isEmpty()) { + KMessageBox::detailedError(d->environ->dialogParent(), + i18n("Could not save image - insufficient information."), + i18n("URL: %1\n" + "Mimetype: %2", + prettyUrl(), + m_saveOptions->mimeType().isEmpty() + ? i18n("") + : m_saveOptions->mimeType()), + i18nc("@title:window", "Internal Error")); return false; } - return saveAs (m_url, *m_saveOptions, - overwritePrompt, - lossyPrompt); + return saveAs(m_url, *m_saveOptions, + overwritePrompt, + lossyPrompt); } //--------------------------------------------------------------------- // public static -bool kpDocument::lossyPromptContinue (const QImage &pixmap, - const kpDocumentSaveOptions &saveOptions, - QWidget *parent) +bool kpDocument::lossyPromptContinue(const QImage &pixmap, const kpDocumentSaveOptions &saveOptions, + QWidget *parent) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "kpDocument::lossyPromptContinue()"; #endif #define QUIT_IF_CANCEL(messageBoxCommand) \ -{ \ - if (messageBoxCommand != KMessageBox::Continue) \ - { \ - return false; \ - } \ -} + { \ + if (messageBoxCommand != KMessageBox::Continue) \ + { \ + return false; \ + } \ + } - const int lossyType = saveOptions.isLossyForSaving (pixmap); - if (lossyType & (kpDocumentSaveOptions::MimeTypeMaximumColorDepthLow | - kpDocumentSaveOptions::Quality)) - { + const int lossyType = saveOptions.isLossyForSaving(pixmap); + if (lossyType & (kpDocumentSaveOptions::MimeTypeMaximumColorDepthLow + |kpDocumentSaveOptions::Quality)) { QMimeDatabase db; - QUIT_IF_CANCEL ( - KMessageBox::warningContinueCancel (parent, - i18n ("

The %1 format may not be able" - " to preserve all of the image's color information.

" - - "

Are you sure you want to save in this format?

", - db.mimeTypeForName(saveOptions.mimeType()).comment()), - // TODO: caption misleading for lossless formats that have - // low maximum colour depth - i18nc ("@title:window", "Lossy File Format"), - KStandardGuiItem::save (), - KStandardGuiItem::cancel(), - QLatin1String ("SaveInLossyMimeTypeDontAskAgain"))); - } - else if (lossyType & kpDocumentSaveOptions::ColorDepthLow) - { - QUIT_IF_CANCEL ( - KMessageBox::warningContinueCancel (parent, - i18n ("

Saving the image at the low color depth of %1-bit" - " may result in the loss of color information." - - // TODO: It looks like 8-bit QImage's now support alpha. - // Update kpDocumentSaveOptions::isLossyForSaving() - // and change "might" to "will". - " Any transparency might also be removed.

" - - "

Are you sure you want to save at this color depth?

", - saveOptions.colorDepth ()), - i18nc ("@title:window", "Low Color Depth"), - KStandardGuiItem::save (), - KStandardGuiItem::cancel(), - QLatin1String ("SaveAtLowColorDepthDontAskAgain"))); + QUIT_IF_CANCEL( + KMessageBox::warningContinueCancel(parent, + i18n("

The %1 format may not be able" + " to preserve all of the image's color information.

" + + "

Are you sure you want to save in this format?

", + db.mimeTypeForName(saveOptions.mimeType()). + comment()), + // TODO: caption misleading for lossless formats that have + // low maximum colour depth + i18nc("@title:window", "Lossy File Format"), + KStandardGuiItem::save(), + KStandardGuiItem::cancel(), + QLatin1String("SaveInLossyMimeTypeDontAskAgain"))); + } else if (lossyType & kpDocumentSaveOptions::ColorDepthLow) { + QUIT_IF_CANCEL( + KMessageBox::warningContinueCancel(parent, + i18n( + "

Saving the image at the low color depth of %1-bit" + " may result in the loss of color information." + + // TODO: It looks like 8-bit QImage's now support alpha. + // Update kpDocumentSaveOptions::isLossyForSaving() + // and change "might" to "will". + " Any transparency might also be removed.

" + + "

Are you sure you want to save at this color depth?

", + saveOptions.colorDepth()), + i18nc("@title:window", "Low Color Depth"), + KStandardGuiItem::save(), + KStandardGuiItem::cancel(), + QLatin1String("SaveAtLowColorDepthDontAskAgain"))); } #undef QUIT_IF_CANCEL @@ -162,36 +155,32 @@ //--------------------------------------------------------------------- // public static -bool kpDocument::savePixmapToDevice (const QImage &image, - QIODevice *device, - const kpDocumentSaveOptions &saveOptions, - const kpDocumentMetaInfo &metaInfo, - bool lossyPrompt, - QWidget *parent, - bool *userCancelled) +bool kpDocument::savePixmapToDevice(const QImage &image, QIODevice *device, + const kpDocumentSaveOptions &saveOptions, + const kpDocumentMetaInfo &metaInfo, bool lossyPrompt, + QWidget *parent, bool *userCancelled) { if (userCancelled) { *userCancelled = false; } - QStringList types = KImageIO::typeForMime (saveOptions.mimeType ()); + QStringList types = KImageIO::typeForMime(saveOptions.mimeType()); #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\ttypes=" << types; #endif - if (types.isEmpty ()) { + if (types.isEmpty()) { return false; } // It's safe to arbitrarily choose the 0th type as any type in the list // should invoke the same KImageIO image loader. const QString type = types [0]; #if DEBUG_KP_DOCUMENT - qCDebug(kpLogDocument) << "\tmimeType=" << saveOptions.mimeType () - << " type=" << type; + qCDebug(kpLogDocument) << "\tmimeType=" << saveOptions.mimeType() + << " type=" << type; #endif - if (lossyPrompt && !lossyPromptContinue (image, saveOptions, parent)) - { + if (lossyPrompt && !lossyPromptContinue(image, saveOptions, parent)) { if (userCancelled) { *userCancelled = true; } @@ -202,307 +191,281 @@ return false; } - // TODO: fix dup with kpDocumentSaveOptions::isLossyForSaving() - const bool useSaveOptionsColorDepth = - (saveOptions.mimeTypeHasConfigurableColorDepth () && - !saveOptions.colorDepthIsInvalid ()); - const bool useSaveOptionsQuality = - (saveOptions.mimeTypeHasConfigurableQuality () && - !saveOptions.qualityIsInvalid ()); - + const bool useSaveOptionsColorDepth + = (saveOptions.mimeTypeHasConfigurableColorDepth() + && !saveOptions.colorDepthIsInvalid()); + const bool useSaveOptionsQuality + = (saveOptions.mimeTypeHasConfigurableQuality() + && !saveOptions.qualityIsInvalid()); // // Reduce colors if required // #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\tuseSaveOptionsColorDepth=" << useSaveOptionsColorDepth - << "current image depth=" << image.depth () - << "save options depth=" << saveOptions.colorDepth (); + << "current image depth=" << image.depth() + << "save options depth=" << saveOptions.colorDepth(); #endif QImage imageToSave(image); - if (useSaveOptionsColorDepth && - imageToSave.depth () != saveOptions.colorDepth ()) - { + if (useSaveOptionsColorDepth + && imageToSave.depth() != saveOptions.colorDepth()) { // TODO: I think this erases the mask! // // I suspect this doesn't matter since this is only called to // reduce color depth and QImage's with depth < 32 don't // support masks anyway. // // Later: I think the mask is preserved for 8-bit since Qt4 // seems to support it for QImage. - imageToSave = kpEffectReduceColors::convertImageDepth (imageToSave, - saveOptions.colorDepth (), - saveOptions.dither ()); + imageToSave = kpEffectReduceColors::convertImageDepth(imageToSave, + saveOptions.colorDepth(), + saveOptions.dither()); } - // // Write Meta Info // - imageToSave.setDotsPerMeterX (metaInfo.dotsPerMeterX ()); - imageToSave.setDotsPerMeterY (metaInfo.dotsPerMeterY ()); - imageToSave.setOffset (metaInfo.offset ()); + imageToSave.setDotsPerMeterX(metaInfo.dotsPerMeterX()); + imageToSave.setDotsPerMeterY(metaInfo.dotsPerMeterY()); + imageToSave.setOffset(metaInfo.offset()); - QList keyList = metaInfo.textKeys (); - for (QList ::const_iterator it = keyList.constBegin (); - it != keyList.constEnd (); - ++it) - { - imageToSave.setText (*it, metaInfo.text (*it)); + QList keyList = metaInfo.textKeys(); + for (QList ::const_iterator it = keyList.constBegin(); + it != keyList.constEnd(); + ++it) { + imageToSave.setText(*it, metaInfo.text(*it)); } - // // Save at required quality // int quality = -1; // default if (useSaveOptionsQuality) { - quality = saveOptions.quality (); + quality = saveOptions.quality(); } #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\tsaving"; #endif - if (!imageToSave.save (device, type.toLatin1 (), quality)) - { + if (!imageToSave.save(device, type.toLatin1(), quality)) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\tQImage::save() returned false"; #endif return false; } - #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\tsave OK"; #endif return true; } //--------------------------------------------------------------------- -static void CouldNotCreateTemporaryFileDialog (QWidget *parent) +static void CouldNotCreateTemporaryFileDialog(QWidget *parent) { - KMessageBox::error (parent, - i18n ("Could not save image - unable to create temporary file.")); + KMessageBox::error(parent, + i18n("Could not save image - unable to create temporary file.")); } //--------------------------------------------------------------------- -static void CouldNotSaveDialog (const QUrl &url, QWidget *parent) +static void CouldNotSaveDialog(const QUrl &url, QWidget *parent) { // TODO: use file.errorString() - KMessageBox::error (parent, - i18n ("Could not save as \"%1\".", - kpUrlFormatter::PrettyFilename (url))); + KMessageBox::error(parent, + i18n("Could not save as \"%1\".", + kpUrlFormatter::PrettyFilename(url))); } //--------------------------------------------------------------------- // public static -bool kpDocument::savePixmapToFile (const QImage &pixmap, - const QUrl &url, - const kpDocumentSaveOptions &saveOptions, - const kpDocumentMetaInfo &metaInfo, - bool overwritePrompt, - bool lossyPrompt, - QWidget *parent) +bool kpDocument::savePixmapToFile(const QImage &pixmap, const QUrl &url, + const kpDocumentSaveOptions &saveOptions, + const kpDocumentMetaInfo &metaInfo, bool overwritePrompt, + bool lossyPrompt, QWidget *parent) { // TODO: Use KIO::NetAccess:mostLocalURL() for accessing home:/ (and other // such local URLs) for efficiency and because only local writes // are atomic. #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "kpDocument::savePixmapToFile (" - << url - << ",overwritePrompt=" << overwritePrompt - << ",lossyPrompt=" << lossyPrompt - << ")"; - saveOptions.printDebug (QLatin1String ("\tsaveOptions")); - metaInfo.printDebug (QLatin1String ("\tmetaInfo")); + << url + << ",overwritePrompt=" << overwritePrompt + << ",lossyPrompt=" << lossyPrompt + << ")"; + saveOptions.printDebug(QLatin1String("\tsaveOptions")); + metaInfo.printDebug(QLatin1String("\tmetaInfo")); #endif - if (overwritePrompt && - KIO::NetAccess::exists (url, KIO::NetAccess::DestinationSide/*write*/, parent)) - { - int result = KMessageBox::warningContinueCancel (parent, - i18n ("A document called \"%1\" already exists.\n" - "Do you want to overwrite it?", - kpUrlFormatter::PrettyFilename (url)), - QString(), - KStandardGuiItem::overwrite ()); - - if (result != KMessageBox::Continue) - { + if (overwritePrompt + && KIO::NetAccess::exists(url, KIO::NetAccess::DestinationSide /*write*/, parent)) { + int result = KMessageBox::warningContinueCancel(parent, + i18n( + "A document called \"%1\" already exists.\n" + "Do you want to overwrite it?", + kpUrlFormatter::PrettyFilename(url)), + QString(), + KStandardGuiItem::overwrite()); + + if (result != KMessageBox::Continue) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\tuser doesn't want to overwrite"; #endif return false; } } - - if (lossyPrompt && !lossyPromptContinue (pixmap, saveOptions, parent)) - { + if (lossyPrompt && !lossyPromptContinue(pixmap, saveOptions, parent)) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\treturning false because of lossyPrompt"; #endif return false; } - // Local file? - if (url.isLocalFile ()) - { - const QString filename = url.toLocalFile (); + if (url.isLocalFile()) { + const QString filename = url.toLocalFile(); // sync: All failure exit paths _must_ call QSaveFile::cancelWriting() or // else, the QSaveFile destructor will overwrite the file, // , despite the failure. - QSaveFile atomicFileWriter (filename); + QSaveFile atomicFileWriter(filename); { - if (!atomicFileWriter.open (QIODevice::WriteOnly)) - { + if (!atomicFileWriter.open(QIODevice::WriteOnly)) { // We probably don't need this as has not been // opened. - atomicFileWriter.cancelWriting (); + atomicFileWriter.cancelWriting(); #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\treturning false because could not open QSaveFile" - << " error=" << atomicFileWriter.error () << endl; + << " error=" << atomicFileWriter.error() << endl; #endif - ::CouldNotCreateTemporaryFileDialog (parent); + ::CouldNotCreateTemporaryFileDialog(parent); return false; } // Write to local temporary file. - if (!savePixmapToDevice (pixmap, &atomicFileWriter, - saveOptions, metaInfo, - false/*no lossy prompt*/, - parent)) - { - atomicFileWriter.cancelWriting (); + if (!savePixmapToDevice(pixmap, &atomicFileWriter, + saveOptions, metaInfo, + false /*no lossy prompt*/, + parent)) { + atomicFileWriter.cancelWriting(); #if DEBUG_KP_DOCUMENT - qCDebug(kpLogDocument) << "\treturning false because could not save pixmap to device" - << endl; + qCDebug(kpLogDocument) + << + "\treturning false because could not save pixmap to device" + << endl; #endif - ::CouldNotSaveDialog (url, parent); + ::CouldNotSaveDialog(url, parent); return false; } // Atomically overwrite local file with the temporary file // we saved to. - if (!atomicFileWriter.commit ()) - { - atomicFileWriter.cancelWriting (); + if (!atomicFileWriter.commit()) { + atomicFileWriter.cancelWriting(); #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\tcould not close QSaveFile"; #endif - ::CouldNotSaveDialog (url, parent); + ::CouldNotSaveDialog(url, parent); return false; } } // sync QSaveFile.cancelWriting() } // Remote file? - else - { + else { // Create temporary file that is deleted when the variable goes // out of scope. QTemporaryFile tempFile; - if (!tempFile.open ()) - { + if (!tempFile.open()) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\treturning false because could not open tempFile"; #endif - ::CouldNotCreateTemporaryFileDialog (parent); + ::CouldNotCreateTemporaryFileDialog(parent); return false; } // Write to local temporary file. - if (!savePixmapToDevice (pixmap, &tempFile, - saveOptions, metaInfo, - false/*no lossy prompt*/, - parent)) - { + if (!savePixmapToDevice(pixmap, &tempFile, + saveOptions, metaInfo, + false /*no lossy prompt*/, + parent)) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\treturning false because could not save pixmap to device" - << endl; + << endl; #endif - ::CouldNotSaveDialog (url, parent); + ::CouldNotSaveDialog(url, parent); return false; } // Collect name of temporary file now, as QTemporaryFile::fileName() // stops working after close() is called. - const QString tempFileName = tempFile.fileName (); + const QString tempFileName = tempFile.fileName(); #if DEBUG_KP_DOCUMENT - qCDebug(kpLogDocument) << "\ttempFileName='" << tempFileName << "'"; + qCDebug(kpLogDocument) << "\ttempFileName='" << tempFileName << "'"; #endif - Q_ASSERT (!tempFileName.isEmpty ()); + Q_ASSERT(!tempFileName.isEmpty()); - tempFile.close (); - if (tempFile.error () != QFile::NoError) - { + tempFile.close(); + if (tempFile.error() != QFile::NoError) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\treturning false because could not close"; #endif - ::CouldNotSaveDialog (url, parent); + ::CouldNotSaveDialog(url, parent); return false; } // Copy local temporary file to overwrite remote. // TODO: No one seems to know how to do this atomically // [http://lists.kde.org/?l=kde-core-devel&m=117845162728484&w=2]. // At least, fish:// (ssh) is definitely not atomic. - if (!KIO::NetAccess::upload (tempFileName, url, parent)) - { + if (!KIO::NetAccess::upload(tempFileName, url, parent)) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "\treturning false because could not upload"; #endif - KMessageBox::error (parent, - i18n ("Could not save image - failed to upload.")); + KMessageBox::error(parent, + i18n("Could not save image - failed to upload.")); return false; } } - return true; } //--------------------------------------------------------------------- -bool kpDocument::saveAs (const QUrl &url, - const kpDocumentSaveOptions &saveOptions, - bool overwritePrompt, - bool lossyPrompt) +bool kpDocument::saveAs(const QUrl &url, const kpDocumentSaveOptions &saveOptions, + bool overwritePrompt, bool lossyPrompt) { #if DEBUG_KP_DOCUMENT qCDebug(kpLogDocument) << "kpDocument::saveAs (" << url << "," - << saveOptions.mimeType () << ")" << endl; + << saveOptions.mimeType() << ")" << endl; #endif - if (kpDocument::savePixmapToFile (imageWithSelection (), - url, - saveOptions, *metaInfo (), - overwritePrompt, - lossyPrompt, - d->environ->dialogParent ())) - { - setURL (url, true/*is from url*/); + if (kpDocument::savePixmapToFile(imageWithSelection(), + url, + saveOptions, *metaInfo(), + overwritePrompt, + lossyPrompt, + d->environ->dialogParent())) { + setURL(url, true /*is from url*/); *m_saveOptions = saveOptions; m_modified = false; m_savedAtLeastOnceBefore = true; - emit documentSaved (); + emit documentSaved(); return true; } diff --git a/document/kpDocument_Selection.cpp b/document/kpDocument_Selection.cpp --- a/document/kpDocument_Selection.cpp +++ b/document/kpDocument_Selection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_DOCUMENT 0 - #include "kpDocument.h" #include "kpDocumentPrivate.h" - #include #include #include @@ -47,111 +43,102 @@ #include "layers/selections/image/kpAbstractImageSelection.h" #include "layers/selections/text/kpTextSelection.h" - // public -kpAbstractSelection *kpDocument::selection () const +kpAbstractSelection *kpDocument::selection() const { return m_selection; } //--------------------------------------------------------------------- // public -kpAbstractImageSelection *kpDocument::imageSelection () const +kpAbstractImageSelection *kpDocument::imageSelection() const { - return dynamic_cast (m_selection); + return dynamic_cast (m_selection); } //--------------------------------------------------------------------- // public -kpTextSelection *kpDocument::textSelection () const +kpTextSelection *kpDocument::textSelection() const { - return dynamic_cast (m_selection); + return dynamic_cast (m_selection); } //--------------------------------------------------------------------- // public -void kpDocument::setSelection (const kpAbstractSelection &selection) +void kpDocument::setSelection(const kpAbstractSelection &selection) { #if DEBUG_KP_DOCUMENT && 1 qCDebug(kpLogDocument) << "kpDocument::setSelection() sel boundingRect=" - << selection.boundingRect (); + << selection.boundingRect(); #endif - d->environ->setQueueViewUpdates (); + d->environ->setQueueViewUpdates(); { - const bool hadSelection = static_cast (m_selection); + const bool hadSelection = static_cast(m_selection); auto *oldSelection = m_selection; - // (must be called before giving the document a new selection, to // avoid a potential mess where switchToCompatibleTool() ends // the current selection tool, killing the new selection) bool isTextChanged = false; - d->environ->switchToCompatibleTool (selection, &isTextChanged); - Q_ASSERT (m_selection == oldSelection); - + d->environ->switchToCompatibleTool(selection, &isTextChanged); + Q_ASSERT(m_selection == oldSelection); - m_selection = selection.clone (); + m_selection = selection.clone(); // There's no need to uninitialize the old selection // (e.g. call disconnect()) since we delete it later. - connect (m_selection, &kpAbstractSelection::changed, - this, &kpDocument::slotContentsChanged); - + connect(m_selection, &kpAbstractSelection::changed, + this, &kpDocument::slotContentsChanged); // // Now all kpDocument state has been set. // We can _only_ change the environment after that, as the environment // may access the document. Exception is above with // switchToCompatibleTool(). // - d->environ->assertMatchingUIState (selection); - + d->environ->assertMatchingUIState(selection); // // Now all kpDocument and environment state has been set. // We can _only_ fire signals after that, as the signal receivers (the // "wider environment") may access the document and the environment. // #if DEBUG_KP_DOCUMENT && 1 - qCDebug(kpLogDocument) << "\tcheck sel " << (int *) m_selection - << " boundingRect=" << m_selection->boundingRect (); + qCDebug(kpLogDocument) << "\tcheck sel " << (int *)m_selection + << " boundingRect=" << m_selection->boundingRect(); #endif - if (oldSelection) - { - if (oldSelection->hasContent ()) { - slotContentsChanged (oldSelection->boundingRect ()); - } - else { - emit contentsChanged (oldSelection->boundingRect ()); + if (oldSelection) { + if (oldSelection->hasContent()) { + slotContentsChanged(oldSelection->boundingRect()); + } else { + emit contentsChanged(oldSelection->boundingRect()); } delete oldSelection; oldSelection = nullptr; } - if (m_selection->hasContent ()) { - slotContentsChanged (m_selection->boundingRect ()); + if (m_selection->hasContent()) { + slotContentsChanged(m_selection->boundingRect()); + } else { + emit contentsChanged(m_selection->boundingRect()); } - else { - emit contentsChanged (m_selection->boundingRect ()); - } - if (!hadSelection) { - emit selectionEnabled (true); + emit selectionEnabled(true); } if (isTextChanged) { - emit selectionIsTextChanged (textSelection ()); + emit selectionIsTextChanged(textSelection()); } } - d->environ->restoreQueueViewUpdates (); + d->environ->restoreQueueViewUpdates(); #if DEBUG_KP_DOCUMENT && 1 qCDebug(kpLogDocument) << "\tkpDocument::setSelection() ended"; @@ -161,61 +148,57 @@ //--------------------------------------------------------------------- // public -kpImage kpDocument::getSelectedBaseImage () const +kpImage kpDocument::getSelectedBaseImage() const { - auto *imageSel = imageSelection (); - Q_ASSERT (imageSel); + auto *imageSel = imageSelection(); + Q_ASSERT(imageSel); // Easy if we already have it :) - const auto image = imageSel->baseImage (); - if (!image.isNull ()) { + const auto image = imageSel->baseImage(); + if (!image.isNull()) { return image; } - - const auto boundingRect = imageSel->boundingRect (); - Q_ASSERT (boundingRect.isValid ()); + const auto boundingRect = imageSel->boundingRect(); + Q_ASSERT(boundingRect.isValid()); // OPT: This is very slow. Image / More Effects ... calls us twice // unnecessarily. - return imageSel->givenImageMaskedByShape (getImageAt (boundingRect)); + return imageSel->givenImageMaskedByShape(getImageAt(boundingRect)); } //--------------------------------------------------------------------- // public -void kpDocument::imageSelectionPullFromDocument (const kpColor &backgroundColor) +void kpDocument::imageSelectionPullFromDocument(const kpColor &backgroundColor) { - auto *imageSel = imageSelection (); - Q_ASSERT (imageSel); + auto *imageSel = imageSelection(); + Q_ASSERT(imageSel); // Should not already have an image or we would not be pulling. - Q_ASSERT (!imageSel->hasContent ()); + Q_ASSERT(!imageSel->hasContent()); - const auto boundingRect = imageSel->boundingRect (); - Q_ASSERT (boundingRect.isValid ()); + const auto boundingRect = imageSel->boundingRect(); + Q_ASSERT(boundingRect.isValid()); // // Get selection image from document // - auto selectedImage = getSelectedBaseImage (); + auto selectedImage = getSelectedBaseImage(); - d->environ->setQueueViewUpdates (); + d->environ->setQueueViewUpdates(); - imageSel->setBaseImage (selectedImage); + imageSel->setBaseImage(selectedImage); // // Fill opaque bits of the hole in the document // #if !defined (QT_NO_DEBUG) && !defined (NDEBUG) - if (imageSel->transparency ().isTransparent ()) - { - Q_ASSERT (backgroundColor == imageSel->transparency ().transparentColor ()); - } - else - { + if (imageSel->transparency().isTransparent()) { + Q_ASSERT(backgroundColor == imageSel->transparency().transparentColor()); + } else { // If this method is begin called by a tool, the assert does not // have to hold since transparentColor() might not be defined in Opaque // Mode. @@ -239,84 +222,78 @@ painter.drawImage(boundingRect.topLeft(), eraseImage); slotContentsChanged(boundingRect); - d->environ->restoreQueueViewUpdates (); + d->environ->restoreQueueViewUpdates(); } //--------------------------------------------------------------------- // public -void kpDocument::selectionDelete () +void kpDocument::selectionDelete() { - if ( !m_selection ) { + if (!m_selection) { return; } - const auto boundingRect = m_selection->boundingRect (); - Q_ASSERT (boundingRect.isValid ()); + const auto boundingRect = m_selection->boundingRect(); + Q_ASSERT(boundingRect.isValid()); - const auto selectionHadContent = m_selection->hasContent (); + const auto selectionHadContent = m_selection->hasContent(); delete m_selection; m_selection = nullptr; - // HACK to prevent document from being modified when // user cancels dragging out a new selection // REFACTOR: Extract this out into a method. if (selectionHadContent) { - slotContentsChanged (boundingRect); - } - else { - emit contentsChanged (boundingRect); + slotContentsChanged(boundingRect); + } else { + emit contentsChanged(boundingRect); } - emit selectionEnabled (false); + emit selectionEnabled(false); } //--------------------------------------------------------------------- // public -void kpDocument::selectionCopyOntoDocument (bool applySelTransparency) +void kpDocument::selectionCopyOntoDocument(bool applySelTransparency) { // Empty selection, just doing nothing - if ( !m_selection || !m_selection->hasContent() ) { + if (!m_selection || !m_selection->hasContent()) { return; } - const QRect boundingRect = m_selection->boundingRect (); - Q_ASSERT (boundingRect.isValid ()); + const QRect boundingRect = m_selection->boundingRect(); + Q_ASSERT(boundingRect.isValid()); - if (imageSelection ()) - { + if (imageSelection()) { if (applySelTransparency) { - imageSelection ()->paint (m_image, rect ()); - } - else { - imageSelection ()->paintWithBaseImage (m_image, rect ()); + imageSelection()->paint(m_image, rect()); + } else { + imageSelection()->paintWithBaseImage(m_image, rect()); } - } - else - { + } else { // (for antialiasing with background) - m_selection->paint (m_image, rect ()); + m_selection->paint(m_image, rect()); } - slotContentsChanged (boundingRect); + slotContentsChanged(boundingRect); } //--------------------------------------------------------------------- // public -void kpDocument::selectionPushOntoDocument (bool applySelTransparency) +void kpDocument::selectionPushOntoDocument(bool applySelTransparency) { - selectionCopyOntoDocument (applySelTransparency); - selectionDelete (); + selectionCopyOntoDocument(applySelTransparency); + selectionDelete(); } //--------------------------------------------------------------------- // public -kpImage kpDocument::imageWithSelection () const +kpImage kpDocument::imageWithSelection() const { #if DEBUG_KP_DOCUMENT && 1 qCDebug(kpLogDocument) << "kpDocument::imageWithSelection()"; @@ -326,20 +303,17 @@ // // It need not have any content because e.g. a text box with an opaque // background, but no content, is still visually there. - if (m_selection) - { + if (m_selection) { #if DEBUG_KP_DOCUMENT && 1 - qCDebug(kpLogDocument) << "\tselection @ " << m_selection->boundingRect (); + qCDebug(kpLogDocument) << "\tselection @ " << m_selection->boundingRect(); #endif kpImage output = *m_image; // (this is a NOP for image selections without content) - m_selection->paint (&output, rect ()); + m_selection->paint(&output, rect()); return output; - } - else - { + } else { #if DEBUG_KP_DOCUMENT && 1 qCDebug(kpLogDocument) << "\tno selection"; #endif diff --git a/environments/commands/kpCommandEnvironment.h b/environments/commands/kpCommandEnvironment.h --- a/environments/commands/kpCommandEnvironment.h +++ b/environments/commands/kpCommandEnvironment.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,55 +24,45 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpCommandEnvironment_H #define kpCommandEnvironment_H - #include "environments/kpEnvironmentBase.h" - class kpMainWindow; class kpImageSelectionTransparency; class kpTextStyle; - // Facade for kpCommand clients. class kpCommandEnvironment : public kpEnvironmentBase { -Q_OBJECT + Q_OBJECT public: // Note: Our interface must never publicly leak or any other // classes we are trying to hide as that would defeat the point of // the facade. kpCommandEnvironment (kpMainWindow *mainWindow); ~kpCommandEnvironment () override; - - void somethingBelowTheCursorChanged () const; - + void somethingBelowTheCursorChanged() const; // Sets the foreground and background drawing colors in the UI. - void setColor (int which, const kpColor &color) const; - + void setColor(int which, const kpColor &color) const; // // Selections // - kpImageSelectionTransparency imageSelectionTransparency () const; - void setImageSelectionTransparency (const kpImageSelectionTransparency &transparency, - bool forceColorChange = false); - - kpTextStyle textStyle () const; - void setTextStyle (const kpTextStyle &textStyle); + kpImageSelectionTransparency imageSelectionTransparency() const; + void setImageSelectionTransparency(const kpImageSelectionTransparency &transparency, + bool forceColorChange = false); + kpTextStyle textStyle() const; + void setTextStyle(const kpTextStyle &textStyle); private: - struct kpCommandEnvironmentPrivate * const d; + struct kpCommandEnvironmentPrivate *const d; }; - #endif // kpCommandEnvironment_H - diff --git a/environments/commands/kpCommandEnvironment.cpp b/environments/commands/kpCommandEnvironment.cpp --- a/environments/commands/kpCommandEnvironment.cpp +++ b/environments/commands/kpCommandEnvironment.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "environments/commands/kpCommandEnvironment.h" #include "widgets/toolbars/kpColorToolBar.h" @@ -35,68 +33,60 @@ #include "layers/selections/text/kpTextStyle.h" #include "tools/kpTool.h" - struct kpCommandEnvironmentPrivate { }; kpCommandEnvironment::kpCommandEnvironment (kpMainWindow *mainWindow) - : kpEnvironmentBase (mainWindow), - d (new kpCommandEnvironmentPrivate ()) + : kpEnvironmentBase(mainWindow) + , d(new kpCommandEnvironmentPrivate()) { } kpCommandEnvironment::~kpCommandEnvironment () { delete d; } - // public -void kpCommandEnvironment::setColor (int which, const kpColor &color) const +void kpCommandEnvironment::setColor(int which, const kpColor &color) const { - kpColorToolBar *toolBar = mainWindow ()->colorToolBar (); - Q_ASSERT (toolBar); + kpColorToolBar *toolBar = mainWindow()->colorToolBar(); + Q_ASSERT(toolBar); - toolBar->setColor (which, color); + toolBar->setColor(which, color); } - // public -void kpCommandEnvironment::somethingBelowTheCursorChanged () const +void kpCommandEnvironment::somethingBelowTheCursorChanged() const { - kpTool *tool = mainWindow ()->tool (); - Q_ASSERT (tool); + kpTool *tool = mainWindow()->tool(); + Q_ASSERT(tool); - tool->somethingBelowTheCursorChanged (); + tool->somethingBelowTheCursorChanged(); } - // public -kpImageSelectionTransparency kpCommandEnvironment::imageSelectionTransparency () const +kpImageSelectionTransparency kpCommandEnvironment::imageSelectionTransparency() const { - return mainWindow ()->imageSelectionTransparency (); + return mainWindow()->imageSelectionTransparency(); } // public -void kpCommandEnvironment::setImageSelectionTransparency ( - const kpImageSelectionTransparency &transparency, - bool forceColorChange) +void kpCommandEnvironment::setImageSelectionTransparency( + const kpImageSelectionTransparency &transparency, bool forceColorChange) { - mainWindow ()->setImageSelectionTransparency (transparency, forceColorChange); + mainWindow()->setImageSelectionTransparency(transparency, forceColorChange); } - // public -kpTextStyle kpCommandEnvironment::textStyle () const +kpTextStyle kpCommandEnvironment::textStyle() const { - return mainWindow ()->textStyle (); + return mainWindow()->textStyle(); } // public -void kpCommandEnvironment::setTextStyle (const kpTextStyle &textStyle) +void kpCommandEnvironment::setTextStyle(const kpTextStyle &textStyle) { - mainWindow ()->setTextStyle (textStyle); + mainWindow()->setTextStyle(textStyle); } - - diff --git a/environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.h b/environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.h --- a/environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.h +++ b/environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,28 +24,21 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransformDialogEnvironment_H #define kpTransformDialogEnvironment_H - #include "environments/kpEnvironmentBase.h" - - - // Facade for kpTransformDialog* clients. class kpTransformDialogEnvironment : public kpEnvironmentBase { -Q_OBJECT + Q_OBJECT public: // Note: Our interface must never publicly leak or any other // classes we are trying to hide as that would defeat the point of // the facade. kpTransformDialogEnvironment (kpMainWindow *mainWindow); }; - #endif // kpTransformDialogEnvironment_H - diff --git a/environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.cpp b/environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.cpp --- a/environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.cpp +++ b/environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,18 +24,15 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "environments/dialogs/imagelib/transforms/kpTransformDialogEnvironment.h" #include "mainWindow/kpMainWindow.h" - //--------------------------------------------------------------------- kpTransformDialogEnvironment::kpTransformDialogEnvironment(kpMainWindow *mainWindow) : kpEnvironmentBase(mainWindow) { } //--------------------------------------------------------------------- - diff --git a/environments/document/kpDocumentEnvironment.h b/environments/document/kpDocumentEnvironment.h --- a/environments/document/kpDocumentEnvironment.h +++ b/environments/document/kpDocumentEnvironment.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,47 +24,39 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpDocumentEnvironment_H #define kpDocumentEnvironment_H - #include "environments/kpEnvironmentBase.h" - class QWidget; class kpAbstractSelection; - // Facade for kpDocument clients. class kpDocumentEnvironment : public kpEnvironmentBase { -Q_OBJECT + Q_OBJECT public: // Note: Our interface must never publicly leak or any other // classes we are trying to hide as that would defeat the point of // the facade. kpDocumentEnvironment (kpMainWindow *mainWindow); ~kpDocumentEnvironment () override; + QWidget *dialogParent() const; - QWidget *dialogParent () const; - - void setQueueViewUpdates () const; - void restoreQueueViewUpdates () const; - - void switchToCompatibleTool (const kpAbstractSelection &selection, - // REFACTOR: This is horrible API and terribly named. - bool *isTextChanged) const; - void assertMatchingUIState (const kpAbstractSelection &selection) const; + void setQueueViewUpdates() const; + void restoreQueueViewUpdates() const; + void switchToCompatibleTool(const kpAbstractSelection &selection, + // REFACTOR: This is horrible API and terribly named. + bool *isTextChanged) const; + void assertMatchingUIState(const kpAbstractSelection &selection) const; private: - struct kpDocumentEnvironmentPrivate * const d; + struct kpDocumentEnvironmentPrivate *const d; }; - #endif // kpDocumentEnvironment_H - diff --git a/environments/document/kpDocumentEnvironment.cpp b/environments/document/kpDocumentEnvironment.cpp --- a/environments/document/kpDocumentEnvironment.cpp +++ b/environments/document/kpDocumentEnvironment.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_DOCUMENT_ENVIRONMENT 0 - #include "environments/document/kpDocumentEnvironment.h" #include "kpLogCategories.h" @@ -47,67 +44,65 @@ #endif #include "views/manager/kpViewManager.h" - struct kpDocumentEnvironmentPrivate { }; kpDocumentEnvironment::kpDocumentEnvironment (kpMainWindow *mainWindow) - : kpEnvironmentBase (mainWindow), - d (new kpDocumentEnvironmentPrivate ()) + : kpEnvironmentBase(mainWindow) + , d(new kpDocumentEnvironmentPrivate()) { } kpDocumentEnvironment::~kpDocumentEnvironment () { delete d; } - // public -QWidget *kpDocumentEnvironment::dialogParent () const +QWidget *kpDocumentEnvironment::dialogParent() const { - return mainWindow (); + return mainWindow(); } - -static kpViewManager *ViewManager (kpMainWindow *mw) +static kpViewManager *ViewManager(kpMainWindow *mw) { - return mw->viewManager (); + return mw->viewManager(); } // public -void kpDocumentEnvironment::setQueueViewUpdates () const +void kpDocumentEnvironment::setQueueViewUpdates() const { - ::ViewManager (mainWindow ())->setQueueUpdates (); + ::ViewManager(mainWindow())->setQueueUpdates(); } // public -void kpDocumentEnvironment::restoreQueueViewUpdates () const +void kpDocumentEnvironment::restoreQueueViewUpdates() const { - ::ViewManager (mainWindow ())->restoreQueueUpdates (); + ::ViewManager(mainWindow())->restoreQueueUpdates(); } //--------------------------------------------------------------------- // public -void kpDocumentEnvironment::switchToCompatibleTool (const kpAbstractSelection &selection, - bool *isTextChanged) const +void kpDocumentEnvironment::switchToCompatibleTool(const kpAbstractSelection &selection, + bool *isTextChanged) const { #if DEBUG_KP_DOCUMENT_ENVIRONMENT qCDebug(kpLogEnvironments) << "kpDocumentEnvironment::switchToCompatibleTool(" - << &selection << ")" - << " mainwindow.tool=" - << (mainWindow ()->tool () ? mainWindow ()->tool ()->objectName () : nullptr) - << " mainWindow.toolIsTextTool=" << mainWindow ()->toolIsTextTool () - << " current selection=" - << document ()->selection () - << " new selection is text=" - << dynamic_cast (&selection); + << &selection << ")" + << " mainwindow.tool=" + << (mainWindow()->tool() ? mainWindow()->tool()->objectName() : + nullptr) + << " mainWindow.toolIsTextTool=" << mainWindow()->toolIsTextTool() + << " current selection=" + << document()->selection() + << " new selection is text=" + << dynamic_cast (&selection); #endif - *isTextChanged = (mainWindow ()->toolIsTextTool () != - (dynamic_cast (&selection) != nullptr)); + *isTextChanged = (mainWindow()->toolIsTextTool() + != (dynamic_cast (&selection) != nullptr)); // We don't change the Selection Tool if the new selection's // shape is merely different to the current tool's (e.g. rectangular @@ -121,91 +116,77 @@ // a differently shaped tool, the borders drawn after the paste would // be using a new shape rather than the shape before the paste. This // could get irritating so we don't do the switch. - if (!mainWindow ()->toolIsASelectionTool () || *isTextChanged) - { + if (!mainWindow()->toolIsASelectionTool() || *isTextChanged) { // See kpDocument::setSelection() APIDoc for this assumption. - Q_ASSERT (!document ()->selection ()); + Q_ASSERT(!document()->selection()); // Switch to the appropriately shaped selection tool // _before_ we change the selection // (all selection tool's ::end() functions nuke the current selection) - if (dynamic_cast (&selection)) - { + if (dynamic_cast (&selection)) { #if DEBUG_KP_DOCUMENT_ENVIRONMENT qCDebug(kpLogEnvironments) << "\tswitch to rect selection tool"; #endif - mainWindow ()->slotToolRectSelection (); - } - else if (dynamic_cast (&selection)) - { + mainWindow()->slotToolRectSelection(); + } else if (dynamic_cast (&selection)) { #if DEBUG_KP_DOCUMENT_ENVIRONMENT qCDebug(kpLogEnvironments) << "\tswitch to elliptical selection tool"; #endif - mainWindow ()->slotToolEllipticalSelection (); - } - else if (dynamic_cast (&selection)) - { + mainWindow()->slotToolEllipticalSelection(); + } else if (dynamic_cast (&selection)) { #if DEBUG_KP_DOCUMENT_ENVIRONMENT qCDebug(kpLogEnvironments) << "\tswitch to free form selection tool"; #endif - mainWindow ()->slotToolFreeFormSelection (); - } - else if (dynamic_cast (&selection)) - { + mainWindow()->slotToolFreeFormSelection(); + } else if (dynamic_cast (&selection)) { #if DEBUG_KP_DOCUMENT_ENVIRONMENT qCDebug(kpLogEnvironments) << "\tswitch to text selection tool"; #endif - mainWindow ()->slotToolText (); - } - else { - Q_ASSERT (!"Unknown selection type"); + mainWindow()->slotToolText(); + } else { + Q_ASSERT(!"Unknown selection type"); } } #if DEBUG_KP_DOCUMENT_ENVIRONMENT - qCDebug(kpLogEnvironments) << "kpDocumentEnvironment::switchToCompatibleTool(" << &selection << ") finished"; + qCDebug(kpLogEnvironments) << "kpDocumentEnvironment::switchToCompatibleTool(" << &selection + << ") finished"; #endif } //--------------------------------------------------------------------- // public -void kpDocumentEnvironment::assertMatchingUIState (const kpAbstractSelection &selection) const +void kpDocumentEnvironment::assertMatchingUIState(const kpAbstractSelection &selection) const { // Trap and try to recover from bugs. // TODO: See kpDocument::setSelection() API comment and determine best fix. - const auto *imageSelection = dynamic_cast (&selection); - const auto *textSelection = dynamic_cast (&selection); - - if (imageSelection) - { - if (imageSelection->transparency () != mainWindow ()->imageSelectionTransparency ()) - { - qCCritical(kpLogEnvironments) << "kpDocument::setSelection() sel's transparency differs " - "from mainWindow's transparency - setting mainWindow's transparency " - "to sel"; - - qCCritical(kpLogEnvironments) << "\tisOpaque: sel=" << imageSelection->transparency ().isOpaque () - << " mainWindow=" << mainWindow ()->imageSelectionTransparency ().isOpaque (); - - mainWindow ()->setImageSelectionTransparency (imageSelection->transparency ()); + const auto *imageSelection = dynamic_cast (&selection); + const auto *textSelection = dynamic_cast (&selection); + + if (imageSelection) { + if (imageSelection->transparency() != mainWindow()->imageSelectionTransparency()) { + qCCritical(kpLogEnvironments) + << "kpDocument::setSelection() sel's transparency differs " + "from mainWindow's transparency - setting mainWindow's transparency " + "to sel"; + + qCCritical(kpLogEnvironments) << "\tisOpaque: sel=" + << imageSelection->transparency().isOpaque() + << " mainWindow=" + << mainWindow()->imageSelectionTransparency().isOpaque(); + + mainWindow()->setImageSelectionTransparency(imageSelection->transparency()); } - } - else if (textSelection) - { - if (textSelection->textStyle () != mainWindow ()->textStyle ()) - { + } else if (textSelection) { + if (textSelection->textStyle() != mainWindow()->textStyle()) { qCCritical(kpLogEnvironments) << "kpDocument::setSelection() sel's textStyle differs " - "from mainWindow's textStyle - setting mainWindow's textStyle " - "to sel"; + "from mainWindow's textStyle - setting mainWindow's textStyle " + "to sel"; - mainWindow ()->setTextStyle (textSelection->textStyle ()); + mainWindow()->setTextStyle(textSelection->textStyle()); } - } - else - { - Q_ASSERT (!"Unknown selection type"); + } else { + Q_ASSERT(!"Unknown selection type"); } } - - diff --git a/environments/kpEnvironmentBase.h b/environments/kpEnvironmentBase.h --- a/environments/kpEnvironmentBase.h +++ b/environments/kpEnvironmentBase.h @@ -1,4 +1,3 @@ - // LOREFACTOR: The files in this folder duplicate too much code. // Use mixin multiple inheritance to get around this. // @@ -33,14 +32,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEnvironmentBase_H #define kpEnvironmentBase_H - #include - class kpAbstractImageSelection; class kpAbstractSelection; class kpColor; @@ -50,7 +46,6 @@ class kpTextSelection; class kpViewManager; - // Abstract facade bridging kpMainWindow and other suppliers (e.g. kpTool, // kpToolToolBar, kpColorToolBar) to clients. // @@ -64,7 +59,7 @@ // a new class. class kpEnvironmentBase : public QObject { -Q_OBJECT + Q_OBJECT // (must derive from) protected: @@ -75,25 +70,23 @@ ~kpEnvironmentBase () override; public: - kpDocument *document () const; + kpDocument *document() const; - kpAbstractSelection *selection () const; - kpAbstractImageSelection *imageSelection () const; - kpTextSelection *textSelection () const; + kpAbstractSelection *selection() const; + kpAbstractImageSelection *imageSelection() const; + kpTextSelection *textSelection() const; - kpViewManager *viewManager () const; + kpViewManager *viewManager() const; - kpCommandEnvironment *commandEnvironment () const; + kpCommandEnvironment *commandEnvironment() const; - kpColor backgroundColor (bool ofSelection = false) const; + kpColor backgroundColor(bool ofSelection = false) const; protected: - kpMainWindow *mainWindow () const; + kpMainWindow *mainWindow() const; private: - struct kpEnvironmentBasePrivate * const d; + struct kpEnvironmentBasePrivate *const d; }; - #endif // kpEnvironmentBase_H - diff --git a/environments/kpEnvironmentBase.cpp b/environments/kpEnvironmentBase.cpp --- a/environments/kpEnvironmentBase.cpp +++ b/environments/kpEnvironmentBase.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,24 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "environments/kpEnvironmentBase.h" #include "widgets/toolbars/kpColorToolBar.h" #include "document/kpDocument.h" #include "mainWindow/kpMainWindow.h" #include "layers/selections/text/kpTextStyle.h" #include "tools/kpTool.h" - struct kpEnvironmentBasePrivate { kpMainWindow *mainWindow; }; kpEnvironmentBase::kpEnvironmentBase (kpMainWindow *mainWindow) - : QObject (mainWindow), - d (new kpEnvironmentBasePrivate ()) + : QObject(mainWindow) + , d(new kpEnvironmentBasePrivate()) { - Q_ASSERT (mainWindow); + Q_ASSERT(mainWindow); d->mainWindow = mainWindow; } @@ -54,67 +51,59 @@ delete d; } - // public -kpDocument *kpEnvironmentBase::document () const +kpDocument *kpEnvironmentBase::document() const { - return d->mainWindow->document (); + return d->mainWindow->document(); } - // public -kpAbstractSelection *kpEnvironmentBase::selection () const +kpAbstractSelection *kpEnvironmentBase::selection() const { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - return doc->selection (); + return doc->selection(); } // public -kpAbstractImageSelection *kpEnvironmentBase::imageSelection () const +kpAbstractImageSelection *kpEnvironmentBase::imageSelection() const { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - return doc->imageSelection (); + return doc->imageSelection(); } // public -kpTextSelection *kpEnvironmentBase::textSelection () const +kpTextSelection *kpEnvironmentBase::textSelection() const { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - return doc->textSelection (); + return doc->textSelection(); } - // public -kpViewManager *kpEnvironmentBase::viewManager () const +kpViewManager *kpEnvironmentBase::viewManager() const { - return mainWindow ()->viewManager (); + return mainWindow()->viewManager(); } - // public -kpCommandEnvironment *kpEnvironmentBase::commandEnvironment () const +kpCommandEnvironment *kpEnvironmentBase::commandEnvironment() const { - return mainWindow ()->commandEnvironment (); + return mainWindow()->commandEnvironment(); } - // public -kpColor kpEnvironmentBase::backgroundColor (bool ofSelection) const +kpColor kpEnvironmentBase::backgroundColor(bool ofSelection) const { - return d->mainWindow->backgroundColor (ofSelection); + return d->mainWindow->backgroundColor(ofSelection); } - // protected -kpMainWindow *kpEnvironmentBase::mainWindow () const +kpMainWindow *kpEnvironmentBase::mainWindow() const { return d->mainWindow; } - - diff --git a/environments/tools/kpToolEnvironment.h b/environments/tools/kpToolEnvironment.h --- a/environments/tools/kpToolEnvironment.h +++ b/environments/tools/kpToolEnvironment.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolEnvironment_H #define kpToolEnvironment_H - #include "environments/kpEnvironmentBase.h" - class QActionGroup; class QPoint; class QRect; @@ -44,40 +40,38 @@ class kpCommandHistory; class kpToolToolBar; - // Facade for kpTool clients. class kpToolEnvironment : public kpEnvironmentBase { -Q_OBJECT + Q_OBJECT public: // Note: Our interface must never publicly leak or any other // classes we are trying to hide as that would defeat the point of // the facade. kpToolEnvironment (kpMainWindow *mainWindow); ~kpToolEnvironment () override; + KActionCollection *actionCollection() const; - KActionCollection *actionCollection () const; + kpCommandHistory *commandHistory() const; - kpCommandHistory *commandHistory () const; + QActionGroup *toolsActionGroup() const; + kpToolToolBar *toolToolBar() const; + void hideAllToolWidgets() const; + bool selectPreviousTool() const; - QActionGroup *toolsActionGroup () const; - kpToolToolBar *toolToolBar () const; - void hideAllToolWidgets () const; - bool selectPreviousTool () const; - - kpColor color (int which) const; - double colorSimilarity () const; - int processedColorSimilarity () const; + kpColor color(int which) const; + double colorSimilarity() const; + int processedColorSimilarity() const; // (only valid in kpTool::slotForegroundColorChanged()) - kpColor oldForegroundColor () const; + kpColor oldForegroundColor() const; // (only valid in kpTool::slotBackgroundColorChanged()) - kpColor oldBackgroundColor () const; + kpColor oldBackgroundColor() const; // (only valid in kpTool::slotColorSimilarityChanged()) - double oldColorSimilarity () const; + double oldColorSimilarity() const; // Flashes the Color Similarity Tool Bar Item to highlight to the user, // the existence of the Color Similarity feature. @@ -129,35 +123,31 @@ // // We flash in tools but not commands as else it would be very distracting // Undo/Redo - this flashing in the tools is distracting enough already :) - void flashColorSimilarityToolBarItem () const; + void flashColorSimilarityToolBarItem() const; - void setColor (int which, const kpColor &color) const; + void setColor(int which, const kpColor &color) const; - void deleteSelection () const; - void pasteTextAt (const QString &text, const QPoint &point, - // Allow tiny adjustment of so that mouse - // pointer is not exactly on top of the topLeft of - // any new text selection (so that it doesn't look - // weird by being on top of a resize handle just after - // a paste). - bool allowNewTextSelectionPointShift = false) const; + void deleteSelection() const; + void pasteTextAt(const QString &text, const QPoint &point, + // Allow tiny adjustment of so that mouse + // pointer is not exactly on top of the topLeft of + // any new text selection (so that it doesn't look + // weird by being on top of a resize handle just after + // a paste). + bool allowNewTextSelectionPointShift = false) const; - void zoomIn (bool centerUnderCursor = false) const; - void zoomOut (bool centerUnderCursor = false) const; + void zoomIn(bool centerUnderCursor = false) const; + void zoomOut(bool centerUnderCursor = false) const; - void zoomToRect (const QRect &normalizedDocRect, - bool accountForGrips, - bool careAboutWidth, bool careAboutHeight) const; + void zoomToRect(const QRect &normalizedDocRect, bool accountForGrips, bool careAboutWidth, + bool careAboutHeight) const; - void fitToPage () const; + void fitToPage() const; static bool drawAntiAliased; - private: - struct kpToolEnvironmentPrivate * const d; + struct kpToolEnvironmentPrivate *const d; }; - #endif // kpToolEnvironment_H - diff --git a/environments/tools/kpToolEnvironment.cpp b/environments/tools/kpToolEnvironment.cpp --- a/environments/tools/kpToolEnvironment.cpp +++ b/environments/tools/kpToolEnvironment.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpToolEnvironment.h" #include "imagelib/kpColor.h" @@ -50,168 +48,157 @@ }; kpToolEnvironment::kpToolEnvironment (kpMainWindow *mainWindow) - : kpEnvironmentBase (mainWindow), - d (new kpToolEnvironmentPrivate ()) + : kpEnvironmentBase(mainWindow) + , d(new kpToolEnvironmentPrivate()) { } kpToolEnvironment::~kpToolEnvironment () { delete d; } - // public -KActionCollection *kpToolEnvironment::actionCollection () const +KActionCollection *kpToolEnvironment::actionCollection() const { - return mainWindow ()->actionCollection (); + return mainWindow()->actionCollection(); } // public -kpCommandHistory *kpToolEnvironment::commandHistory () const +kpCommandHistory *kpToolEnvironment::commandHistory() const { - return mainWindow ()->commandHistory (); + return mainWindow()->commandHistory(); } - // public -QActionGroup *kpToolEnvironment::toolsActionGroup () const +QActionGroup *kpToolEnvironment::toolsActionGroup() const { - return mainWindow ()->toolsActionGroup (); + return mainWindow()->toolsActionGroup(); } // public -kpToolToolBar *kpToolEnvironment::toolToolBar () const +kpToolToolBar *kpToolEnvironment::toolToolBar() const { - return mainWindow ()->toolToolBar (); + return mainWindow()->toolToolBar(); } // public -void kpToolEnvironment::hideAllToolWidgets () const +void kpToolEnvironment::hideAllToolWidgets() const { - toolToolBar ()->hideAllToolWidgets (); + toolToolBar()->hideAllToolWidgets(); } // public -bool kpToolEnvironment::selectPreviousTool () const +bool kpToolEnvironment::selectPreviousTool() const { - kpToolToolBar *tb = toolToolBar (); + kpToolToolBar *tb = toolToolBar(); // (don't end up with no tool selected) - if (!tb->previousTool ()) { + if (!tb->previousTool()) { return false; } // endInternal() will be called by kpMainWindow (thanks to this line) // so we won't have the view anymore // TODO: Update comment. - tb->selectPreviousTool (); + tb->selectPreviousTool(); return true; } - -static kpColorToolBar *ColorToolBar (kpMainWindow *mw) +static kpColorToolBar *ColorToolBar(kpMainWindow *mw) { - return mw->colorToolBar (); + return mw->colorToolBar(); } // public -kpColor kpToolEnvironment::color (int which) const +kpColor kpToolEnvironment::color(int which) const { - return ::ColorToolBar (mainWindow ())->color (which); + return ::ColorToolBar(mainWindow())->color(which); } // public -double kpToolEnvironment::colorSimilarity () const +double kpToolEnvironment::colorSimilarity() const { - return ::ColorToolBar (mainWindow ())->colorSimilarity (); + return ::ColorToolBar(mainWindow())->colorSimilarity(); } // public -int kpToolEnvironment::processedColorSimilarity () const +int kpToolEnvironment::processedColorSimilarity() const { - return ::ColorToolBar (mainWindow ())->processedColorSimilarity (); + return ::ColorToolBar(mainWindow())->processedColorSimilarity(); } // public -kpColor kpToolEnvironment::oldForegroundColor () const +kpColor kpToolEnvironment::oldForegroundColor() const { - return ::ColorToolBar (mainWindow ())->oldForegroundColor (); + return ::ColorToolBar(mainWindow())->oldForegroundColor(); } // public -kpColor kpToolEnvironment::oldBackgroundColor () const +kpColor kpToolEnvironment::oldBackgroundColor() const { - return ::ColorToolBar (mainWindow ())->oldBackgroundColor (); + return ::ColorToolBar(mainWindow())->oldBackgroundColor(); } // public -double kpToolEnvironment::oldColorSimilarity () const +double kpToolEnvironment::oldColorSimilarity() const { - return ::ColorToolBar (mainWindow ())->oldColorSimilarity (); + return ::ColorToolBar(mainWindow())->oldColorSimilarity(); } - // public -void kpToolEnvironment::flashColorSimilarityToolBarItem () const +void kpToolEnvironment::flashColorSimilarityToolBarItem() const { - ::ColorToolBar (mainWindow ())->flashColorSimilarityToolBarItem (); + ::ColorToolBar(mainWindow())->flashColorSimilarityToolBarItem(); } - // public -void kpToolEnvironment::setColor (int which, const kpColor &color) const +void kpToolEnvironment::setColor(int which, const kpColor &color) const { - kpColorToolBar *toolBar = mainWindow ()->colorToolBar (); - Q_ASSERT (toolBar); + kpColorToolBar *toolBar = mainWindow()->colorToolBar(); + Q_ASSERT(toolBar); - toolBar->setColor (which, color); + toolBar->setColor(which, color); } - // public -void kpToolEnvironment::deleteSelection () const +void kpToolEnvironment::deleteSelection() const { - mainWindow ()->slotDelete (); + mainWindow()->slotDelete(); } // public -void kpToolEnvironment::pasteTextAt (const QString &text, const QPoint &point, - bool allowNewTextSelectionPointShift) const +void kpToolEnvironment::pasteTextAt(const QString &text, const QPoint &point, + bool allowNewTextSelectionPointShift) const { - mainWindow ()->pasteTextAt (text, point, allowNewTextSelectionPointShift); + mainWindow()->pasteTextAt(text, point, allowNewTextSelectionPointShift); } - // public -void kpToolEnvironment::zoomIn (bool centerUnderCursor) const +void kpToolEnvironment::zoomIn(bool centerUnderCursor) const { - mainWindow ()->zoomIn (centerUnderCursor); + mainWindow()->zoomIn(centerUnderCursor); } // public -void kpToolEnvironment::zoomOut (bool centerUnderCursor) const +void kpToolEnvironment::zoomOut(bool centerUnderCursor) const { - mainWindow ()->zoomOut (centerUnderCursor); + mainWindow()->zoomOut(centerUnderCursor); } - // public -void kpToolEnvironment::zoomToRect ( - const QRect &normalizedDocRect, - bool accountForGrips, - bool careAboutWidth, bool careAboutHeight) const +void kpToolEnvironment::zoomToRect( + const QRect &normalizedDocRect, bool accountForGrips, bool careAboutWidth, + bool careAboutHeight) const { - mainWindow ()->zoomToRect ( + mainWindow()->zoomToRect( normalizedDocRect, accountForGrips, careAboutWidth, careAboutHeight); } // public -void kpToolEnvironment::fitToPage () const +void kpToolEnvironment::fitToPage() const { - mainWindow ()->slotFitToPage (); + mainWindow()->slotFitToPage(); } - - diff --git a/environments/tools/selection/kpToolSelectionEnvironment.h b/environments/tools/selection/kpToolSelectionEnvironment.h --- a/environments/tools/selection/kpToolSelectionEnvironment.h +++ b/environments/tools/selection/kpToolSelectionEnvironment.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,48 +24,42 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolSelectionEnvironment_H #define kpToolSelectionEnvironment_H - #include "environments/tools/kpToolEnvironment.h" - class QMenu; class kpImageSelectionTransparency; class kpTextStyle; - // Facade for kpToolSelection clients. class kpToolSelectionEnvironment : public kpToolEnvironment { -Q_OBJECT + Q_OBJECT public: // Note: Our interface must never publicly leak or any other // classes we are trying to hide as that would defeat the point of // the facade. kpToolSelectionEnvironment (kpMainWindow *mainWindow); ~kpToolSelectionEnvironment () override; - kpImageSelectionTransparency imageSelectionTransparency () const; - int settingImageSelectionTransparency () const; + kpImageSelectionTransparency imageSelectionTransparency() const; + int settingImageSelectionTransparency() const; - void deselectSelection () const; + void deselectSelection() const; - QMenu *selectionToolRMBMenu () const; + QMenu *selectionToolRMBMenu() const; - void enableTextToolBarActions (bool enable = true) const; + void enableTextToolBarActions(bool enable = true) const; - kpTextStyle textStyle () const; - int settingTextStyle () const; + kpTextStyle textStyle() const; + int settingTextStyle() const; private: - struct kpToolSelectionEnvironmentPrivate * const d; + struct kpToolSelectionEnvironmentPrivate *const d; }; - #endif // kpToolSelectionEnvironment_H - diff --git a/environments/tools/selection/kpToolSelectionEnvironment.cpp b/environments/tools/selection/kpToolSelectionEnvironment.cpp --- a/environments/tools/selection/kpToolSelectionEnvironment.cpp +++ b/environments/tools/selection/kpToolSelectionEnvironment.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,72 +24,65 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpToolSelectionEnvironment.h" #include "mainWindow/kpMainWindow.h" #include "layers/selections/image/kpImageSelectionTransparency.h" #include "layers/selections/text/kpTextStyle.h" - struct kpToolSelectionEnvironmentPrivate { }; kpToolSelectionEnvironment::kpToolSelectionEnvironment (kpMainWindow *mainWindow) - : kpToolEnvironment (mainWindow), - d (new kpToolSelectionEnvironmentPrivate ()) + : kpToolEnvironment(mainWindow) + , d(new kpToolSelectionEnvironmentPrivate()) { } kpToolSelectionEnvironment::~kpToolSelectionEnvironment () { delete d; } - // public -kpImageSelectionTransparency kpToolSelectionEnvironment::imageSelectionTransparency () const +kpImageSelectionTransparency kpToolSelectionEnvironment::imageSelectionTransparency() const { - return mainWindow ()->imageSelectionTransparency (); + return mainWindow()->imageSelectionTransparency(); } // public -int kpToolSelectionEnvironment::settingImageSelectionTransparency () const +int kpToolSelectionEnvironment::settingImageSelectionTransparency() const { - return mainWindow ()->settingImageSelectionTransparency (); + return mainWindow()->settingImageSelectionTransparency(); } - // public -void kpToolSelectionEnvironment::deselectSelection () const +void kpToolSelectionEnvironment::deselectSelection() const { - mainWindow ()->slotDeselect (); + mainWindow()->slotDeselect(); } // public -QMenu *kpToolSelectionEnvironment::selectionToolRMBMenu () const +QMenu *kpToolSelectionEnvironment::selectionToolRMBMenu() const { - return mainWindow ()->selectionToolRMBMenu (); + return mainWindow()->selectionToolRMBMenu(); } - // public -void kpToolSelectionEnvironment::enableTextToolBarActions (bool enable) const +void kpToolSelectionEnvironment::enableTextToolBarActions(bool enable) const { - mainWindow ()->enableTextToolBarActions (enable); + mainWindow()->enableTextToolBarActions(enable); } // public -kpTextStyle kpToolSelectionEnvironment::textStyle () const +kpTextStyle kpToolSelectionEnvironment::textStyle() const { - return mainWindow ()->textStyle (); + return mainWindow()->textStyle(); } // public -int kpToolSelectionEnvironment::settingTextStyle () const +int kpToolSelectionEnvironment::settingTextStyle() const { - return mainWindow ()->settingTextStyle (); + return mainWindow()->settingTextStyle(); } - - diff --git a/generic/kpSetOverrideCursorSaver.h b/generic/kpSetOverrideCursorSaver.h --- a/generic/kpSetOverrideCursorSaver.h +++ b/generic/kpSetOverrideCursorSaver.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpSetOverrideCursorSaver_H #define kpSetOverrideCursorSaver_H - class QCursor; - // // A less error-prone way of setting the override cursor, compared to // the QApplication::{set,restore}OverrideCursor() pair. @@ -103,5 +99,4 @@ ~kpSetOverrideCursorSaver (); }; - #endif // kpSetOverrideCursorSaver_H diff --git a/generic/kpSetOverrideCursorSaver.cpp b/generic/kpSetOverrideCursorSaver.cpp --- a/generic/kpSetOverrideCursorSaver.cpp +++ b/generic/kpSetOverrideCursorSaver.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,19 +24,16 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "generic/kpSetOverrideCursorSaver.h" #include - kpSetOverrideCursorSaver::kpSetOverrideCursorSaver (const QCursor &cursor) { - QApplication::setOverrideCursor (cursor); + QApplication::setOverrideCursor(cursor); } kpSetOverrideCursorSaver::~kpSetOverrideCursorSaver () { - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } - diff --git a/generic/kpWidgetMapper.h b/generic/kpWidgetMapper.h --- a/generic/kpWidgetMapper.h +++ b/generic/kpWidgetMapper.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,24 +24,19 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_WIDGET_MAPPER_H #define KP_WIDGET_MAPPER_H - class QWidget; class QPoint; class QRect; +namespace kpWidgetMapper { +QPoint fromGlobal(const QWidget *widget, const QPoint &point); +QRect fromGlobal(const QWidget *widget, const QRect &rect); -namespace kpWidgetMapper -{ - QPoint fromGlobal (const QWidget *widget, const QPoint &point); - QRect fromGlobal (const QWidget *widget, const QRect &rect); - - QPoint toGlobal (const QWidget *widget, const QPoint &point); - QRect toGlobal (const QWidget *widget, const QRect &rect); +QPoint toGlobal(const QWidget *widget, const QPoint &point); +QRect toGlobal(const QWidget *widget, const QRect &rect); } - #endif // KP_WIDGET_MAPPER_H diff --git a/generic/kpWidgetMapper.cpp b/generic/kpWidgetMapper.cpp --- a/generic/kpWidgetMapper.cpp +++ b/generic/kpWidgetMapper.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,56 +24,52 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpWidgetMapper.h" #include #include #include - -namespace kpWidgetMapper -{ - - -QPoint fromGlobal (const QWidget *widget, const QPoint &point) +namespace kpWidgetMapper { +QPoint fromGlobal(const QWidget *widget, const QPoint &point) { if (!widget) { return point; } - return widget->mapFromGlobal (point); + return widget->mapFromGlobal(point); } -QRect fromGlobal (const QWidget *widget, const QRect &rect) +QRect fromGlobal(const QWidget *widget, const QRect &rect) { - if (!widget || !rect.isValid ()) { + if (!widget || !rect.isValid()) { return rect; } - auto topLeft = fromGlobal (widget, rect.topLeft ()); - return {topLeft.x (), topLeft.y (), rect.width (), rect.height ()}; + auto topLeft = fromGlobal(widget, rect.topLeft()); + return { + topLeft.x(), topLeft.y(), rect.width(), rect.height() + }; } - -QPoint toGlobal (const QWidget *widget, const QPoint &point) +QPoint toGlobal(const QWidget *widget, const QPoint &point) { if (!widget) { return point; } - return widget->mapToGlobal (point); + return widget->mapToGlobal(point); } -QRect toGlobal (const QWidget *widget, const QRect &rect) +QRect toGlobal(const QWidget *widget, const QRect &rect) { - if (!widget || !rect.isValid ()) { + if (!widget || !rect.isValid()) { return rect; } - auto topLeft = toGlobal (widget, rect.topLeft ()); - return {topLeft.x (), topLeft.y (), rect.width (), rect.height ()}; + auto topLeft = toGlobal(widget, rect.topLeft()); + return { + topLeft.x(), topLeft.y(), rect.width(), rect.height() + }; } - - } // namespace kpWidgetMapper diff --git a/generic/widgets/kpResizeSignallingLabel.h b/generic/widgets/kpResizeSignallingLabel.h --- a/generic/widgets/kpResizeSignallingLabel.h +++ b/generic/widgets/kpResizeSignallingLabel.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,32 +24,27 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_RESIZE_SIGNALLING_LABEL_H #define KP_RESIZE_SIGNALLING_LABEL_H - #include - class QResizeEvent; - class kpResizeSignallingLabel : public QLabel { -Q_OBJECT + Q_OBJECT public: kpResizeSignallingLabel (const QString &string, QWidget *parent); kpResizeSignallingLabel (QWidget *parent); ~kpResizeSignallingLabel () override; signals: - void resized (); + void resized(); protected: - void resizeEvent (QResizeEvent *e) override; + void resizeEvent(QResizeEvent *e) override; }; - #endif // KP_RESIZE_SIGNALLING_LABEL_H diff --git a/generic/widgets/kpResizeSignallingLabel.cpp b/generic/widgets/kpResizeSignallingLabel.cpp --- a/generic/widgets/kpResizeSignallingLabel.cpp +++ b/generic/widgets/kpResizeSignallingLabel.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,41 +24,34 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_RESIZE_SIGNALLING_LABEL 0 - #include "generic/widgets/kpResizeSignallingLabel.h" #include #include "kpLogCategories.h" - -kpResizeSignallingLabel::kpResizeSignallingLabel (const QString &string, - QWidget *parent ) - : QLabel (string, parent) +kpResizeSignallingLabel::kpResizeSignallingLabel (const QString &string, QWidget *parent) + : QLabel(string, parent) { } -kpResizeSignallingLabel::kpResizeSignallingLabel (QWidget *parent ) - : QLabel (parent) +kpResizeSignallingLabel::kpResizeSignallingLabel (QWidget *parent) + : QLabel(parent) { } kpResizeSignallingLabel::~kpResizeSignallingLabel () = default; - // protected virtual [base QLabel] -void kpResizeSignallingLabel::resizeEvent (QResizeEvent *e) +void kpResizeSignallingLabel::resizeEvent(QResizeEvent *e) { #if DEBUG_KP_RESIZE_SIGNALLING_LABEL - qCDebug(kpLogMisc) << "kpResizeSignallingLabel::resizeEvent() newSize=" << e->size () - << " oldSize=" << e->oldSize (); + qCDebug(kpLogMisc) << "kpResizeSignallingLabel::resizeEvent() newSize=" << e->size() + << " oldSize=" << e->oldSize(); #endif - QLabel::resizeEvent (e); + QLabel::resizeEvent(e); - emit resized (); + emit resized(); } - - diff --git a/generic/widgets/kpSubWindow.h b/generic/widgets/kpSubWindow.h --- a/generic/widgets/kpSubWindow.h +++ b/generic/widgets/kpSubWindow.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpSubWindow_H #define kpSubWindow_H - #include // @@ -49,9 +46,8 @@ // class kpSubWindow : public QDialog { - public: +public: kpSubWindow(QWidget *parent); }; - #endif // kpSubWindow_H diff --git a/generic/widgets/kpSubWindow.cpp b/generic/widgets/kpSubWindow.cpp --- a/generic/widgets/kpSubWindow.cpp +++ b/generic/widgets/kpSubWindow.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpSubWindow.h" - kpSubWindow::kpSubWindow (QWidget *parent) - : QDialog (parent) + : QDialog(parent) { } diff --git a/imagelib/effects/blitz.h b/imagelib/effects/blitz.h --- a/imagelib/effects/blitz.h +++ b/imagelib/effects/blitz.h @@ -31,12 +31,11 @@ #include -namespace Blitz -{ - QImage blur(QImage &img, int radius); - QImage gaussianSharpen(QImage &img, float radius, float sigma); - QImage emboss(QImage &img, float radius, float sigma); - QImage &flatten(QImage &img, const QColor &ca, const QColor &cb); -}; +namespace Blitz { +QImage blur(QImage &img, int radius); +QImage gaussianSharpen(QImage &img, float radius, float sigma); +QImage emboss(QImage &img, float radius, float sigma); +QImage &flatten(QImage &img, const QColor &ca, const QColor &cb); +} #endif diff --git a/imagelib/effects/blitz.cpp b/imagelib/effects/blitz.cpp --- a/imagelib/effects/blitz.cpp +++ b/imagelib/effects/blitz.cpp @@ -1,6 +1,6 @@ // functions taken from qimageblitz (no longer maintained) -/* +/* Copyright (C) 1998, 1999, 2001, 2002, 2004, 2005, 2007 Daniel M. Duley (C) 2004 Zack Rusin @@ -71,18 +71,18 @@ #define M_EPSILON 1.0e-6 #define CONVOLVE_ACC(weight, pixel) \ - r+=((weight))*(qRed((pixel))); g+=((weight))*(qGreen((pixel))); \ - b+=((weight))*(qBlue((pixel))); + r += ((weight))*(qRed((pixel))); g += ((weight))*(qGreen((pixel))); \ + b += ((weight))*(qBlue((pixel))); //-------------------------------------------------------------------------------- inline QRgb convertFromPremult(QRgb p) { int alpha = qAlpha(p); - return(!alpha ? 0 : qRgba(255*qRed(p)/alpha, + return !alpha ? 0 : qRgba(255*qRed(p)/alpha, 255*qGreen(p)/alpha, 255*qBlue(p)/alpha, - alpha)); + alpha); } //-------------------------------------------------------------------------------- @@ -98,7 +98,7 @@ p = (p + ((p >> 8) & 0xff) + 0x80); p &= 0xff00; p |= t | (a << 24); - return(p); + return p; } //-------------------------------------------------------------------------------- @@ -121,11 +121,10 @@ quint32 red, green, blue, alpha; } HistogramListItem; - bool equalize(QImage &img) { - if(img.isNull()) { - return(false); + if (img.isNull()) { + return false; } HistogramListItem *histogram; @@ -136,10 +135,10 @@ QRgb pixel, *dest; unsigned char r, g, b; - if(img.depth() < 32){ - img = img.convertToFormat(img.hasAlphaChannel() ? - QImage::Format_ARGB32 : - QImage::Format_RGB32); + if (img.depth() < 32) { + img = img.convertToFormat(img.hasAlphaChannel() + ? QImage::Format_ARGB32 + : QImage::Format_RGB32); } count = img.width()*img.height(); @@ -151,17 +150,16 @@ memset(histogram, 0, 256*sizeof(HistogramListItem)); dest = (QRgb *)img.bits(); - if(img.format() == QImage::Format_ARGB32_Premultiplied){ - for(i=0; i < count; ++i, ++dest){ + if (img.format() == QImage::Format_ARGB32_Premultiplied) { + for (i = 0; i < count; ++i, ++dest) { pixel = convertFromPremult(*dest); histogram[qRed(pixel)].red++; histogram[qGreen(pixel)].green++; histogram[qBlue(pixel)].blue++; histogram[qAlpha(pixel)].alpha++; } - } - else{ - for(i=0; i < count; ++i){ + } else { + for (i = 0; i < count; ++i) { pixel = *dest++; histogram[qRed(pixel)].red++; histogram[qGreen(pixel)].green++; @@ -172,7 +170,7 @@ // integrate the histogram to get the equalization map memset(&intensity, 0, sizeof(IntegerPixel)); - for(i=0; i < 256; ++i){ + for (i = 0; i < 256; ++i) { intensity.red += histogram[i].red; intensity.green += histogram[i].green; intensity.blue += histogram[i].blue; @@ -182,66 +180,65 @@ low = map[0]; high = map[255]; memset(equalize_map, 0, 256*sizeof(CharPixel)); - for(i=0; i < 256; ++i){ - if(high.red != low.red) { + for (i = 0; i < 256; ++i) { + if (high.red != low.red) { equalize_map[i].red = static_cast - ((255*(map[i].red-low.red))/(high.red-low.red)); + ((255*(map[i].red-low.red))/(high.red-low.red)); } - if(high.green != low.green) { + if (high.green != low.green) { equalize_map[i].green = static_cast - ((255*(map[i].green-low.green))/(high.green-low.green)); + ((255*(map[i].green-low.green))/(high.green-low.green)); } - if(high.blue != low.blue) { + if (high.blue != low.blue) { equalize_map[i].blue = static_cast - ((255*(map[i].blue-low.blue))/(high.blue-low.blue)); + ((255*(map[i].blue-low.blue))/(high.blue-low.blue)); } } // stretch the histogram and write dest = (QRgb *)img.bits(); - if(img.format() == QImage::Format_ARGB32_Premultiplied){ - for(i=0; i < count; ++i, ++dest){ + if (img.format() == QImage::Format_ARGB32_Premultiplied) { + for (i = 0; i < count; ++i, ++dest) { pixel = convertFromPremult(*dest); - r = static_cast ((low.red != high.red) ? - equalize_map[qRed(pixel)].red : qRed(pixel)); + r = static_cast((low.red != high.red) + ? equalize_map[qRed(pixel)].red : qRed(pixel)); - g = static_cast ((low.green != high.green) ? - equalize_map[qGreen(pixel)].green : qGreen(pixel)); + g = static_cast((low.green != high.green) + ? equalize_map[qGreen(pixel)].green : qGreen(pixel)); - b = static_cast ((low.blue != high.blue) ? - equalize_map[qBlue(pixel)].blue : qBlue(pixel)); + b = static_cast((low.blue != high.blue) + ? equalize_map[qBlue(pixel)].blue : qBlue(pixel)); *dest = convertToPremult(qRgba(r, g, b, qAlpha(pixel))); } - } - else{ - for(i=0; i < count; ++i){ + } else { + for (i = 0; i < count; ++i) { pixel = *dest; - r = static_cast ((low.red != high.red) ? - equalize_map[qRed(pixel)].red : qRed(pixel)); + r = static_cast((low.red != high.red) + ? equalize_map[qRed(pixel)].red : qRed(pixel)); - g = static_cast ((low.green != high.green) ? - equalize_map[qGreen(pixel)].green : qGreen(pixel)); + g = static_cast((low.green != high.green) + ? equalize_map[qGreen(pixel)].green : qGreen(pixel)); - b = static_cast ((low.blue != high.blue) ? - equalize_map[qBlue(pixel)].blue : qBlue(pixel)); + b = static_cast((low.blue != high.blue) + ? equalize_map[qBlue(pixel)].blue : qBlue(pixel)); *dest++ = qRgba(r, g, b, qAlpha(pixel)); } } delete[] histogram; delete[] map; delete[] equalize_map; - return(true); + return true; } //-------------------------------------------------------------------------------- QImage Blitz::blur(QImage &img, int radius) { if (img.isNull()) { - return (img); + return img; } if (img.depth() < 8) { @@ -256,16 +253,17 @@ auto width = img.width(); auto height = img.height(); - QImage buffer(width, height, img.hasAlphaChannel() ? QImage::Format_ARGB32 : QImage::Format_RGB32); + QImage buffer(width, height, + img.hasAlphaChannel() ? QImage::Format_ARGB32 : QImage::Format_RGB32); const auto img_format = img.format(); int *as = new int[width]; int *rs = new int[width]; int *gs = new int[width]; int *bs = new int[width]; - QRgb *p1 , *p2; + QRgb *p1, *p2; for (auto y = 0; y < height; ++y) { auto my = y - radius; @@ -280,16 +278,16 @@ mh = height - my; } - p1 = (QRgb*)buffer.scanLine(y); + p1 = (QRgb *)buffer.scanLine(y); memset(as, 0, static_cast(width) * sizeof(int)); memset(rs, 0, static_cast(width) * sizeof(int)); memset(gs, 0, static_cast(width) * sizeof(int)); memset(bs, 0, static_cast(width) * sizeof(int)); - switch (img_format) { - case QImage::Format_ARGB32_Premultiplied: { + case QImage::Format_ARGB32_Premultiplied: + { QRgb pixel; for (auto i = 0; i < mh; i++) { p2 = (QRgb *)img.scanLine(i + my); @@ -305,7 +303,8 @@ break; } - case QImage::Format_Indexed8: { + case QImage::Format_Indexed8: + { QRgb pixel; unsigned char *ptr; for (auto i = 0; i < mh; ++i) { @@ -322,7 +321,7 @@ break; } - default: { + default: for (auto i = 0; i < mh; ++i) { p2 = (QRgb *)img.scanLine(i + my); for (auto j = 0; j < width; j++) { @@ -335,7 +334,6 @@ } break; } - } for (auto i = 0; i < width; ++i) { auto a{0}; @@ -378,7 +376,7 @@ delete[] gs; delete[] bs; - return (buffer); + return buffer; } //-------------------------------------------------------------------------------- @@ -391,28 +389,28 @@ float sigmaSQ2PI = static_cast(M_SQ2PI) * sigma; int max = quality ? 65535 : 255; - if(sigma == 0.0f){ + if (sigma == 0.0f) { qWarning("Blitz::defaultConvolveMatrixSize(): Zero sigma is invalid!"); - return(5); + return 5; } - if(radius > 0.0f) { - return(static_cast(2.0f * std::ceil(radius) + 1.0f)); + if (radius > 0.0f) { + return static_cast(2.0f * std::ceil(radius) + 1.0f); } matrix_size = 5; - do{ + do { normalize = 0.0; - for(i=(-matrix_size/2); i <= (matrix_size/2); ++i) { - normalize += std::exp(-(static_cast (i*i))/sigma2) / sigmaSQ2PI; + for (i = (-matrix_size/2); i <= (matrix_size/2); ++i) { + normalize += std::exp(-(static_cast(i*i))/sigma2) / sigmaSQ2PI; } i = matrix_size/2; - value = std::exp(-(static_cast (i*i))/sigma2) / sigmaSQ2PI / normalize; + value = std::exp(-(static_cast(i*i))/sigma2) / sigmaSQ2PI / normalize; matrix_size += 2; - } while(static_cast(max*value) > 0); + } while (static_cast(max*value) > 0); - matrix_size-=4; - return(matrix_size); + matrix_size -= 4; + return matrix_size; } //-------------------------------------------------------------------------------- @@ -424,41 +422,40 @@ QRgb *dest, *src, *s, **scanblock; float *m, *normalize_matrix, normalize; - if(!(matrix_size % 2)){ + if (!(matrix_size % 2)) { qWarning("Blitz::convolve(): kernel width must be an odd number!"); - return(img); + return img; } w = img.width(); h = img.height(); - if(w < 3 || h < 3){ + if (w < 3 || h < 3) { qWarning("Blitz::convolve(): Image is too small!"); - return(img); + return img; } - if(img.format() == QImage::Format_ARGB32_Premultiplied) { + if (img.format() == QImage::Format_ARGB32_Premultiplied) { img = img.convertToFormat(QImage::Format_ARGB32); - } - else if(img.depth() < 32){ - img = img.convertToFormat(img.hasAlphaChannel() ? - QImage::Format_ARGB32 : - QImage::Format_RGB32); + } else if (img.depth() < 32) { + img = img.convertToFormat(img.hasAlphaChannel() + ? QImage::Format_ARGB32 + : QImage::Format_RGB32); } QImage buffer(w, h, img.format()); - scanblock = new QRgb* [matrix_size]; + scanblock = new QRgb * [matrix_size]; normalize_matrix = new float[matrix_size*matrix_size]; // create normalized matrix normalize = 0.0; - for(i=0; i < matrix_size*matrix_size; ++i) { + for (i = 0; i < matrix_size*matrix_size; ++i) { normalize += matrix[i]; } - if(std::abs(normalize) <= static_cast (M_EPSILON)) { + if (std::abs(normalize) <= static_cast(M_EPSILON)) { normalize = 1.0f; } normalize = 1.0f/normalize; - for(i=0; i < matrix_size*matrix_size; ++i){ + for (i = 0; i < matrix_size*matrix_size; ++i) { normalize_matrix[i] = normalize*matrix[i]; } @@ -472,203 +469,206 @@ // float r, g, b; - for(y=0; y < h; ++y){ + for (y = 0; y < h; ++y) { src = (QRgb *)img.scanLine(y); dest = (QRgb *)buffer.scanLine(y); // Read in scanlines to pixel neighborhood. If the scanline is outside // the image use the top or bottom edge. - for(x=y-edge, i=0; x <= y+edge; ++i, ++x){ + for (x = y-edge, i = 0; x <= y+edge; ++i, ++x) { scanblock[i] = (QRgb *) - img.scanLine((x < 0) ? 0 : (x > h-1) ? h-1 : x); + img.scanLine((x < 0) ? 0 : (x > h-1) ? h-1 : x); } // Now we are about to start processing scanlines. First handle the // part where the pixel neighborhood extends off the left edge. - for(x=0; x-edge < 0 ; ++x){ + for (x = 0; x-edge < 0; ++x) { r = g = b = 0.0; m = normalize_matrix; - for(matrix_y = 0; matrix_y < matrix_size; ++matrix_y){ + for (matrix_y = 0; matrix_y < matrix_size; ++matrix_y) { s = scanblock[matrix_y]; matrix_x = -edge; - while(x+matrix_x < 0){ + while (x+matrix_x < 0) { CONVOLVE_ACC(*m, *s); - ++matrix_x; ++m; + ++matrix_x; + ++m; } - while(matrix_x <= edge){ + while (matrix_x <= edge) { CONVOLVE_ACC(*m, *s); - ++matrix_x; ++m; ++s; + ++matrix_x; + ++m; + ++s; } } r = r < 0.0f ? 0.0f : r > 255.0f ? 255.0f : r + 0.5f; g = g < 0.0f ? 0.0f : g > 255.0f ? 255.0f : g + 0.5f; b = b < 0.0f ? 0.0f : b > 255.0f ? 255.0f : b + 0.5f; - *dest++ = qRgba(static_cast (r), static_cast (g), - static_cast (b), qAlpha(*src++)); + *dest++ = qRgba(static_cast(r), static_cast(g), + static_cast(b), qAlpha(*src++)); } // Okay, now process the middle part where the entire neighborhood // is on the image. - for(; x+edge < w; ++x){ + for (; x+edge < w; ++x) { m = normalize_matrix; r = g = b = 0.0; - for(matrix_y = 0; matrix_y < matrix_size; ++matrix_y){ + for (matrix_y = 0; matrix_y < matrix_size; ++matrix_y) { s = scanblock[matrix_y] + (x-edge); - for(matrix_x = -edge; matrix_x <= edge; ++matrix_x, ++m, ++s){ + for (matrix_x = -edge; matrix_x <= edge; ++matrix_x, ++m, ++s) { CONVOLVE_ACC(*m, *s); } } r = r < 0.0f ? 0.0f : r > 255.0f ? 255.0f : r + 0.5f; g = g < 0.0f ? 0.0f : g > 255.0f ? 255.0f : g + 0.5f; b = b < 0.0f ? 0.0f : b > 255.0f ? 255.0f : b + 0.5f; - *dest++ = qRgba(static_cast (r), static_cast (g), - static_cast (b), qAlpha(*src++)); + *dest++ = qRgba(static_cast(r), static_cast(g), + static_cast(b), qAlpha(*src++)); } // Finally process the right part where the neighborhood extends off // the right edge of the image - for(; x < w; ++x){ + for (; x < w; ++x) { r = g = b = 0.0; m = normalize_matrix; - for(matrix_y = 0; matrix_y < matrix_size; ++matrix_y){ + for (matrix_y = 0; matrix_y < matrix_size; ++matrix_y) { s = scanblock[matrix_y]; s += x-edge; matrix_x = -edge; - while(x+matrix_x < w){ + while (x+matrix_x < w) { CONVOLVE_ACC(*m, *s); ++matrix_x; ++m; ++s; } --s; - while(matrix_x <= edge){ + while (matrix_x <= edge) { CONVOLVE_ACC(*m, *s); ++matrix_x; ++m; } } r = r < 0.0f ? 0.0f : r > 255.0f ? 255.0f : r + 0.5f; g = g < 0.0f ? 0.0f : g > 255.0f ? 255.0f : g + 0.5f; b = b < 0.0f ? 0.0f : b > 255.0f ? 255.0f : b + 0.5f; - *dest++ = qRgba(static_cast (r), static_cast (g), - static_cast (b), qAlpha(*src++)); + *dest++ = qRgba(static_cast(r), static_cast(g), + static_cast(b), qAlpha(*src++)); } } } delete[] scanblock; delete[] normalize_matrix; - return(buffer); + return buffer; } //-------------------------------------------------------------------------------- QImage Blitz::gaussianSharpen(QImage &img, float radius, float sigma) { - if(sigma == 0.0f){ + if (sigma == 0.0f) { qWarning("Blitz::gaussianSharpen(): Zero sigma is invalid!"); - return(img); + return img; } int matrix_size = defaultConvolveMatrixSize(radius, sigma, true); int len = matrix_size*matrix_size; float alpha, *matrix = new float[len]; float sigma2 = sigma*sigma*2.0f; - float sigmaPI2 = 2.0f*static_cast (M_PI)*sigma*sigma; + float sigmaPI2 = 2.0f*static_cast(M_PI)*sigma*sigma; int half = matrix_size/2; - int x, y, i=0, j=half; - float normalize=0.0; - for(y=(-half); y <= half; ++y, --j){ - for(x=(-half); x <= half; ++x, ++i){ - alpha = std::exp(-(static_cast (x*x+y*y))/sigma2); + int x, y, i = 0, j = half; + float normalize = 0.0; + for (y = (-half); y <= half; ++y, --j) { + for (x = (-half); x <= half; ++x, ++i) { + alpha = std::exp(-(static_cast(x*x+y*y))/sigma2); matrix[i] = alpha/sigmaPI2; normalize += matrix[i]; } } - matrix[i/2]=(-2.0f)*normalize; + matrix[i/2] = (-2.0f)*normalize; QImage result(convolve(img, matrix_size, matrix)); delete[] matrix; - return(result); + return result; } //-------------------------------------------------------------------------------- QImage Blitz::emboss(QImage &img, float radius, float sigma) { - if(sigma == 0.0f){ + if (sigma == 0.0f) { qWarning("Blitz::emboss(): Zero sigma is invalid!"); - return(img); + return img; } int matrix_size = defaultConvolveMatrixSize(radius, sigma, true); int len = matrix_size*matrix_size; float alpha, *matrix = new float[len]; float sigma2 = sigma*sigma*2.0f; - float sigmaPI2 = 2.0f*static_cast (M_PI)*sigma*sigma; + float sigmaPI2 = 2.0f*static_cast(M_PI)*sigma*sigma; int half = matrix_size/2; - int x, y, i=0, j=half; - for(y=(-half); y <= half; ++y, --j){ - for(x=(-half); x <= half; ++x, ++i){ - alpha = std::exp(-(static_cast (x*x+y*y))/sigma2); - matrix[i]=((x < 0) || (y < 0) ? -8.0f : 8.0f)*alpha/sigmaPI2; - if(x == j) { - matrix[i]=0.0; + int x, y, i = 0, j = half; + for (y = (-half); y <= half; ++y, --j) { + for (x = (-half); x <= half; ++x, ++i) { + alpha = std::exp(-(static_cast(x*x+y*y))/sigma2); + matrix[i] = ((x < 0) || (y < 0) ? -8.0f : 8.0f)*alpha/sigmaPI2; + if (x == j) { + matrix[i] = 0.0; } } } QImage result(convolve(img, matrix_size, matrix)); delete[] matrix; equalize(result); - return(result); + return result; } //-------------------------------------------------------------------------------- -QImage& Blitz::flatten(QImage &img, const QColor &ca, const QColor &cb) +QImage &Blitz::flatten(QImage &img, const QColor &ca, const QColor &cb) { - if(img.isNull()) { - return(img); + if (img.isNull()) { + return img; } - if(img.depth() == 1) { + if (img.depth() == 1) { img.setColor(0, ca.rgb()); img.setColor(1, cb.rgb()); - return(img); + return img; } - int r1 = ca.red(); int r2 = cb.red(); - int g1 = ca.green(); int g2 = cb.green(); - int b1 = ca.blue(); int b2 = cb.blue(); + int r1 = ca.red(); + int r2 = cb.red(); + int g1 = ca.green(); + int g2 = cb.green(); + int b1 = ca.blue(); + int b2 = cb.blue(); int min = 0, max = 255; QRgb *data, *end; QVector cTable; - if(img.format() == QImage::Format_Indexed8){ + if (img.format() == QImage::Format_Indexed8) { cTable = img.colorTable(); - data = static_cast (cTable.data()); + data = static_cast(cTable.data()); end = data + img.colorCount(); - - } - else{ + } else { data = (unsigned int *)img.scanLine(0); end = data + (img.width()*img.height()); } // get minimum and maximum graylevel QRgb *ptr = data; int mean; - if(img.format() != QImage::Format_ARGB32_Premultiplied){ - while(ptr != end){ + if (img.format() != QImage::Format_ARGB32_Premultiplied) { + while (ptr != end) { mean = (qRed(*ptr) + qGreen(*ptr) + qBlue(*ptr)) / 3; min = qMin(min, mean); max = qMax(max, mean); ++ptr; } - } - else{ + } else { QRgb pixel; - while(ptr != end){ + while (ptr != end) { pixel = convertFromPremult(*ptr); mean = (qRed(pixel) + qGreen(pixel) + qBlue(pixel)) / 3; min = qMin(min, mean); @@ -678,38 +678,37 @@ } // conversion factors - float sr = (static_cast (r2 - r1) / (max - min)); - float sg = (static_cast (g2 - g1) / (max - min)); - float sb = (static_cast (b2 - b1) / (max - min)); + float sr = (static_cast(r2 - r1) / (max - min)); + float sg = (static_cast(g2 - g1) / (max - min)); + float sb = (static_cast(b2 - b1) / (max - min)); - if(img.format() != QImage::Format_ARGB32_Premultiplied){ - while(data != end){ + if (img.format() != QImage::Format_ARGB32_Premultiplied) { + while (data != end) { mean = (qRed(*data) + qGreen(*data) + qBlue(*data)) / 3; - *data = qRgba(static_cast (sr * (mean - min) + r1 + 0.5f), - static_cast (sg * (mean - min) + g1 + 0.5f), - static_cast (sb * (mean - min) + b1 + 0.5f), + *data = qRgba(static_cast(sr * (mean - min) + r1 + 0.5f), + static_cast(sg * (mean - min) + g1 + 0.5f), + static_cast(sb * (mean - min) + b1 + 0.5f), qAlpha(*data)); ++data; } - } - else{ + } else { QRgb pixel; - while(data != end){ + while (data != end) { pixel = convertFromPremult(*data); mean = (qRed(pixel) + qGreen(pixel) + qBlue(pixel)) / 3; - *data = - convertToPremult(qRgba(static_cast (sr * (mean - min) + r1 + 0.5f), - static_cast (sg * (mean - min) + g1 + 0.5f), - static_cast (sb * (mean - min) + b1 + 0.5f), - qAlpha(*data))); + *data + = convertToPremult(qRgba(static_cast(sr * (mean - min) + r1 + 0.5f), + static_cast(sg * (mean - min) + g1 + 0.5f), + static_cast(sb * (mean - min) + b1 + 0.5f), + qAlpha(*data))); ++data; } } - if(img.format() == QImage::Format_Indexed8) { + if (img.format() == QImage::Format_Indexed8) { img.setColorTable(cTable); } - return(img); + return img; } //-------------------------------------------------------------------------------- diff --git a/imagelib/effects/kpEffectBalance.h b/imagelib/effects/kpEffectBalance.h --- a/imagelib/effects/kpEffectBalance.h +++ b/imagelib/effects/kpEffectBalance.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectBalance_H #define kpEffectBalance_H - #include "imagelib/kpImage.h" - class kpEffectBalance { public: @@ -44,10 +40,8 @@ }; // (, & are from -50 to 50) - static kpImage applyEffect (const kpImage &image, - int channels, - int brightness, int contrast, int gamma); + static kpImage applyEffect(const kpImage &image, int channels, int brightness, int contrast, + int gamma); }; - #endif // kpEffectBalance_H diff --git a/imagelib/effects/kpEffectBalance.cpp b/imagelib/effects/kpEffectBalance.cpp --- a/imagelib/effects/kpEffectBalance.cpp +++ b/imagelib/effects/kpEffectBalance.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_BALANCE 0 - #include "kpEffectBalance.h" #include @@ -39,13 +36,11 @@ #include "pixmapfx/kpPixmapFX.h" - #if DEBUG_KP_EFFECT_BALANCE #include #endif - -static inline int between0And255 (int val) +static inline int between0And255(int val) { if (val < 0) { return 0; @@ -58,153 +53,133 @@ return val; } - -static inline int brightness (int base, int strength) +static inline int brightness(int base, int strength) { - return between0And255 (base + strength * 255 / 50); + return between0And255(base + strength * 255 / 50); } -static inline int contrast (int base, int strength) +static inline int contrast(int base, int strength) { - return between0And255 ((base - 127) * (strength + 50) / 50 + 127); + return between0And255((base - 127) * (strength + 50) / 50 + 127); } -static inline int gamma (int base, int strength) +static inline int gamma(int base, int strength) { - return between0And255 (qRound (255.0 * std::pow (base / 255.0, 1.0 / std::pow (10., strength / 50.0)))); + return between0And255(qRound(255.0 + * std::pow(base / 255.0, 1.0 / std::pow(10., strength / 50.0)))); } - -static inline int brightnessContrastGamma (int base, - int newBrightness, - int newContrast, - int newGamma) +static inline int brightnessContrastGamma(int base, int newBrightness, int newContrast, + int newGamma) { - return gamma (contrast (brightness (base, newBrightness), - newContrast), - newGamma); + return gamma(contrast(brightness(base, newBrightness), + newContrast), + newGamma); } -static inline QRgb brightnessContrastGammaForRGB (QRgb rgb, - int channels, - int brightness, int contrast, int gamma) +static inline QRgb brightnessContrastGammaForRGB(QRgb rgb, int channels, int brightness, + int contrast, int gamma) { - int red = qRed (rgb); - int green = qGreen (rgb); - int blue = qBlue (rgb); + int red = qRed(rgb); + int green = qGreen(rgb); + int blue = qBlue(rgb); if (channels & kpEffectBalance::Red) { - red = brightnessContrastGamma (red, brightness, contrast, gamma); + red = brightnessContrastGamma(red, brightness, contrast, gamma); } if (channels & kpEffectBalance::Green) { - green = brightnessContrastGamma (green, brightness, contrast, gamma); + green = brightnessContrastGamma(green, brightness, contrast, gamma); } if (channels & kpEffectBalance::Blue) { - blue = brightnessContrastGamma (blue, brightness, contrast, gamma); + blue = brightnessContrastGamma(blue, brightness, contrast, gamma); } - - return qRgba (red, green, blue, qAlpha (rgb)); + return qRgba(red, green, blue, qAlpha(rgb)); } - // public static -kpImage kpEffectBalance::applyEffect (const kpImage &image, - int channels, - int brightness, int contrast, int gamma) +kpImage kpEffectBalance::applyEffect(const kpImage &image, int channels, int brightness, + int contrast, int gamma) { #if DEBUG_KP_EFFECT_BALANCE qCDebug(kpLogImagelib) << "kpEffectBalance::applyEffect(" - << "channels=" << channels - << ",brightness=" << brightness - << ",contrast=" << contrast - << ",gamma=" << gamma - << ")"; - QTime timer; timer.start (); + << "channels=" << channels + << ",brightness=" << brightness + << ",contrast=" << contrast + << ",gamma=" << gamma + << ")"; + QTime timer; + timer.start(); #endif QImage qimage = image; #if DEBUG_KP_EFFECT_BALANCE - qCDebug(kpLogImagelib) << "\tconvertToImage=" << timer.restart (); + qCDebug(kpLogImagelib) << "\tconvertToImage=" << timer.restart(); #endif - quint8 transformRed [256], - transformGreen [256], - transformBlue [256]; + transformGreen [256], + transformBlue [256]; - for (int i = 0; i < 256; i++) - { - auto applied = static_cast (brightnessContrastGamma (i, brightness, contrast, gamma)); + for (int i = 0; i < 256; i++) { + auto applied = static_cast(brightnessContrastGamma(i, brightness, contrast, gamma)); if (channels & kpEffectBalance::Red) { transformRed [i] = applied; - } - else { - transformRed [i] = static_cast (i); + } else { + transformRed [i] = static_cast(i); } if (channels & kpEffectBalance::Green) { transformGreen [i] = applied; - } - else { - transformGreen [i] = static_cast (i); + } else { + transformGreen [i] = static_cast(i); } if (channels & kpEffectBalance::Blue) { transformBlue [i] = applied; - } - else { - transformBlue [i] = static_cast (i); + } else { + transformBlue [i] = static_cast(i); } } #if DEBUG_KP_EFFECT_BALANCE - qCDebug(kpLogImagelib) << "\tbuild lookup=" << timer.restart (); + qCDebug(kpLogImagelib) << "\tbuild lookup=" << timer.restart(); #endif - - if (qimage.depth () > 8) - { - for (int y = 0; y < qimage.height (); y++) - { - for (int x = 0; x < qimage.width (); x++) - { - const QRgb rgb = qimage.pixel (x, y); - - const auto red = static_cast (qRed (rgb)); - const auto green = static_cast (qGreen (rgb)); - const auto blue = static_cast (qBlue (rgb)); - const auto alpha = static_cast (qAlpha (rgb)); - - qimage.setPixel (x, y, - qRgba (transformRed [red], - transformGreen [green], - transformBlue [blue], - alpha)); + if (qimage.depth() > 8) { + for (int y = 0; y < qimage.height(); y++) { + for (int x = 0; x < qimage.width(); x++) { + const QRgb rgb = qimage.pixel(x, y); + + const auto red = static_cast(qRed(rgb)); + const auto green = static_cast(qGreen(rgb)); + const auto blue = static_cast(qBlue(rgb)); + const auto alpha = static_cast(qAlpha(rgb)); + + qimage.setPixel(x, y, + qRgba(transformRed [red], + transformGreen [green], + transformBlue [blue], + alpha)); } } - } - else - { - for (int i = 0; i < qimage.colorCount (); i++) - { - const QRgb rgb = qimage.color (i); - - const auto red = static_cast (qRed (rgb)); - const auto green = static_cast (qGreen (rgb)); - const auto blue = static_cast (qBlue (rgb)); - const auto alpha = static_cast (qAlpha (rgb)); - - qimage.setColor (i, - qRgba (transformRed [red], - transformGreen [green], - transformBlue [blue], - alpha)); + } else { + for (int i = 0; i < qimage.colorCount(); i++) { + const QRgb rgb = qimage.color(i); + + const auto red = static_cast(qRed(rgb)); + const auto green = static_cast(qGreen(rgb)); + const auto blue = static_cast(qBlue(rgb)); + const auto alpha = static_cast(qAlpha(rgb)); + + qimage.setColor(i, + qRgba(transformRed [red], + transformGreen [green], + transformBlue [blue], + alpha)); } - } return qimage; } - diff --git a/imagelib/effects/kpEffectBlurSharpen.h b/imagelib/effects/kpEffectBlurSharpen.h --- a/imagelib/effects/kpEffectBlurSharpen.h +++ b/imagelib/effects/kpEffectBlurSharpen.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectBlurSharpen_H #define kpEffectBlurSharpen_H - #include "imagelib/kpImage.h" - class kpEffectBlurSharpen { public: @@ -49,9 +45,7 @@ // = strength of the effect // (must be between MinStrength and MaxStrength inclusive) - static kpImage applyEffect (const kpImage &image, - Type type, int strength); + static kpImage applyEffect(const kpImage &image, Type type, int strength); }; - #endif // kpEffectBlurSharpen_H diff --git a/imagelib/effects/kpEffectBlurSharpen.cpp b/imagelib/effects/kpEffectBlurSharpen.cpp --- a/imagelib/effects/kpEffectBlurSharpen.cpp +++ b/imagelib/effects/kpEffectBlurSharpen.cpp @@ -24,23 +24,19 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_BLUR_SHARPEN 0 - #include "kpEffectBlurSharpen.h" #include "blitz.h" #include "kpLogCategories.h" #include "pixmapfx/kpPixmapFX.h" - #if DEBUG_KP_EFFECT_BLUR_SHARPEN #include #endif - //--------------------------------------------------------------------- // @@ -58,7 +54,6 @@ // // - static QImage BlurQImage(const QImage &qimage, int strength) { if (strength == 0) { @@ -73,104 +68,99 @@ const double RadiusMin = 1; const double RadiusMax = 10; - const double radius = RadiusMin + - (strength - 1) * - (RadiusMax - RadiusMin) / - (kpEffectBlurSharpen::MaxStrength - 1); + const double radius = RadiusMin + +(strength - 1) + *(RadiusMax - RadiusMin) + /(kpEffectBlurSharpen::MaxStrength - 1); #if DEBUG_KP_EFFECT_BLUR_SHARPEN qCDebug(kpLogImagelib) << "kpEffectBlurSharpen.cpp:BlurQImage(strength=" << strength << ")" - << " radius=" << radius; + << " radius=" << radius; #endif QImage img(qimage); return Blitz::blur(img, qRound(radius)); } //--------------------------------------------------------------------- -static QImage SharpenQImage (const QImage &qimage_, int strength) +static QImage SharpenQImage(const QImage &qimage_, int strength) { QImage qimage = qimage_; if (strength == 0) { return qimage; } - // The numbers that follow were picked by experimentation to try to get // an effect linearly proportional to and at the same time, // be fast enough. // // I still have no idea what "radius" and "sigma" mean. const double RadiusMin = 0.1; const double RadiusMax = 2.5; - const double radius = RadiusMin + - (strength - 1) * - (RadiusMax - RadiusMin) / - (kpEffectBlurSharpen::MaxStrength - 1); + const double radius = RadiusMin + +(strength - 1) + *(RadiusMax - RadiusMin) + /(kpEffectBlurSharpen::MaxStrength - 1); const double SigmaMin = 0.5; const double SigmaMax = 3.0; - const double sigma = SigmaMin + - (strength - 1) * - (SigmaMax - SigmaMin) / - (kpEffectBlurSharpen::MaxStrength - 1); + const double sigma = SigmaMin + +(strength - 1) + *(SigmaMax - SigmaMin) + /(kpEffectBlurSharpen::MaxStrength - 1); const double RepeatMin = 1; const double RepeatMax = 2; - const double repeat = qRound (RepeatMin + - (strength - 1) * - (RepeatMax - RepeatMin) / - (kpEffectBlurSharpen::MaxStrength - 1)); - + const double repeat = qRound(RepeatMin + +(strength - 1) + *(RepeatMax - RepeatMin) + /(kpEffectBlurSharpen::MaxStrength - 1)); #if DEBUG_KP_EFFECT_BLUR_SHARPEN qCDebug(kpLogImagelib) << "kpEffectBlurSharpen.cpp:SharpenQImage(strength=" << strength << ")" - << " radius=" << radius - << " sigma=" << sigma - << " repeat=" << repeat; + << " radius=" << radius + << " sigma=" << sigma + << " repeat=" << repeat; #endif - - for (int i = 0; i < repeat; i++) - { + for (int i = 0; i < repeat; i++) { #if DEBUG_KP_EFFECT_BLUR_SHARPEN - QTime timer; timer.start (); + QTime timer; + timer.start(); #endif - qimage = Blitz::gaussianSharpen (qimage, static_cast (radius), - static_cast (sigma)); + qimage = Blitz::gaussianSharpen(qimage, static_cast(radius), + static_cast(sigma)); #if DEBUG_KP_EFFECT_BLUR_SHARPEN - qCDebug(kpLogImagelib) << "\titeration #" + QString::number (i) - << ": " + QString::number (timer.elapsed ()) << "ms"; + qCDebug(kpLogImagelib) << "\titeration #" + QString::number(i) + << ": " + QString::number(timer.elapsed()) << "ms"; #endif } - return qimage; } //--------------------------------------------------------------------- // public static -kpImage kpEffectBlurSharpen::applyEffect (const kpImage &image, - Type type, int strength) +kpImage kpEffectBlurSharpen::applyEffect(const kpImage &image, Type type, int strength) { #if DEBUG_KP_EFFECT_BLUR_SHARPEN - qCDebug(kpLogImagelib) << "kpEffectBlurSharpen::applyEffect(image.rect=" << image.rect () - << ",type=" << int (type) - << ",strength=" << strength - << ")"; + qCDebug(kpLogImagelib) << "kpEffectBlurSharpen::applyEffect(image.rect=" << image.rect() + << ",type=" << int(type) + << ",strength=" << strength + << ")"; #endif - Q_ASSERT (strength >= MinStrength && strength <= MaxStrength); + Q_ASSERT(strength >= MinStrength && strength <= MaxStrength); if (type == Blur) { - return ::BlurQImage (image, strength); + return ::BlurQImage(image, strength); } if (type == Sharpen) { - return ::SharpenQImage (image, strength); + return ::SharpenQImage(image, strength); } if (type == MakeConfidential) { diff --git a/imagelib/effects/kpEffectEmboss.h b/imagelib/effects/kpEffectEmboss.h --- a/imagelib/effects/kpEffectEmboss.h +++ b/imagelib/effects/kpEffectEmboss.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectEmboss_H #define kpEffectEmboss_H - #include "imagelib/kpImage.h" - class kpEffectEmboss { public: @@ -45,8 +41,7 @@ // (must be between MinStrength and MaxStrength inclusive) // // Currently, all non-zero strengths are the same. - static kpImage applyEffect (const kpImage &image, int strength); + static kpImage applyEffect(const kpImage &image, int strength); }; - #endif // kpEffectEmboss_H diff --git a/imagelib/effects/kpEffectEmboss.cpp b/imagelib/effects/kpEffectEmboss.cpp --- a/imagelib/effects/kpEffectEmboss.cpp +++ b/imagelib/effects/kpEffectEmboss.cpp @@ -24,26 +24,22 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_EMBOSS 0 - #include "kpEffectEmboss.h" #include "blitz.h" #include "kpLogCategories.h" #include "pixmapfx/kpPixmapFX.h" - -static QImage EmbossQImage (const QImage &qimage_, int strength) +static QImage EmbossQImage(const QImage &qimage_, int strength) { QImage qimage = qimage_; if (strength == 0) { return qimage; } - // The numbers that follow were picked by experimentation to try to get // an effect linearly proportional to and at the same time, // be fast enough. @@ -56,26 +52,22 @@ const auto repeat = 1; - - for (int i = 0; i < repeat; i++) - { - qimage = Blitz::emboss (qimage, radius, sigma); + for (int i = 0; i < repeat; i++) { + qimage = Blitz::emboss(qimage, radius, sigma); } - return qimage; } - // public static -kpImage kpEffectEmboss::applyEffect (const kpImage &image, int strength) +kpImage kpEffectEmboss::applyEffect(const kpImage &image, int strength) { #if DEBUG_KP_EFFECT_EMBOSS qCDebug(kpLogImagelib) << "kpEffectEmboss::applyEffect(strength=" << strength << ")" - << endl; + << endl; #endif - Q_ASSERT (strength >= MinStrength && strength <= MaxStrength); + Q_ASSERT(strength >= MinStrength && strength <= MaxStrength); - return ::EmbossQImage (image, strength); + return ::EmbossQImage(image, strength); } diff --git a/imagelib/effects/kpEffectFlatten.h b/imagelib/effects/kpEffectFlatten.h --- a/imagelib/effects/kpEffectFlatten.h +++ b/imagelib/effects/kpEffectFlatten.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,23 +24,17 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectFlatten_H #define kpEffectFlatten_H - class QColor; class QImage; - class kpEffectFlatten { public: - static void applyEffect (QImage *destImagePtr, - const QColor &color1, const QColor &color2); - static QImage applyEffect (const QImage &img, - const QColor &color1, const QColor &color2); + static void applyEffect(QImage *destImagePtr, const QColor &color1, const QColor &color2); + static QImage applyEffect(const QImage &img, const QColor &color1, const QColor &color2); }; - #endif // kpEffectFlatten_H diff --git a/imagelib/effects/kpEffectFlatten.cpp b/imagelib/effects/kpEffectFlatten.cpp --- a/imagelib/effects/kpEffectFlatten.cpp +++ b/imagelib/effects/kpEffectFlatten.cpp @@ -30,24 +30,22 @@ //-------------------------------------------------------------------------------- // public static -void kpEffectFlatten::applyEffect (QImage *destImagePtr, - const QColor &color1, const QColor &color2) +void kpEffectFlatten::applyEffect(QImage *destImagePtr, const QColor &color1, const QColor &color2) { if (!destImagePtr) { return; } - Blitz::flatten (*destImagePtr/*ref*/, color1, color2); + Blitz::flatten(*destImagePtr /*ref*/, color1, color2); } //-------------------------------------------------------------------------------- // public static -QImage kpEffectFlatten::applyEffect (const QImage &img, - const QColor &color1, const QColor &color2) +QImage kpEffectFlatten::applyEffect(const QImage &img, const QColor &color1, const QColor &color2) { QImage retImage = img; - applyEffect (&retImage, color1, color2); + applyEffect(&retImage, color1, color2); return retImage; } diff --git a/imagelib/effects/kpEffectGrayscale.h b/imagelib/effects/kpEffectGrayscale.h --- a/imagelib/effects/kpEffectGrayscale.h +++ b/imagelib/effects/kpEffectGrayscale.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,23 +24,19 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectGrayscale_H #define kpEffectGrayscale_H - #include "imagelib/kpImage.h" - // // Converts the image to grayscale. // class kpEffectGrayscale { public: - static kpImage applyEffect (const kpImage &image); + static kpImage applyEffect(const kpImage &image); }; - #endif // kpEffectGrayscale_H diff --git a/imagelib/effects/kpEffectGrayscale.cpp b/imagelib/effects/kpEffectGrayscale.cpp --- a/imagelib/effects/kpEffectGrayscale.cpp +++ b/imagelib/effects/kpEffectGrayscale.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,49 +24,40 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_PIXMAP_FX 0 - #include "kpEffectGrayscale.h" #include "pixmapfx/kpPixmapFX.h" - -static QRgb toGray (QRgb rgb) +static QRgb toGray(QRgb rgb) { // naive way that doesn't preserve brightness // int gray = (qRed (rgb) + qGreen (rgb) + qBlue (rgb)) / 3; // over-exaggerates red & blue // int gray = qGray (rgb); - int gray = (212671 * qRed (rgb) + 715160 * qGreen (rgb) + 72169 * qBlue (rgb)) / 1000000; - return qRgba (gray, gray, gray, qAlpha (rgb)); + int gray = (212671 * qRed(rgb) + 715160 * qGreen(rgb) + 72169 * qBlue(rgb)) / 1000000; + return qRgba(gray, gray, gray, qAlpha(rgb)); } - // public static -kpImage kpEffectGrayscale::applyEffect (const kpImage &image) +kpImage kpEffectGrayscale::applyEffect(const kpImage &image) { kpImage qimage(image); - + // TODO: Why not just write to the kpImage directly? - if (qimage.depth () > 8) - { - for (int y = 0; y < qimage.height (); y++) - { - for (int x = 0; x < qimage.width (); x++) - { - qimage.setPixel (x, y, toGray (qimage.pixel (x, y))); + if (qimage.depth() > 8) { + for (int y = 0; y < qimage.height(); y++) { + for (int x = 0; x < qimage.width(); x++) { + qimage.setPixel(x, y, toGray(qimage.pixel(x, y))); } } - } - else - { + } else { // 1- & 8- bit images use a color table - for (int i = 0; i < qimage.colorCount (); i++) { - qimage.setColor (i, toGray (qimage.color (i))); + for (int i = 0; i < qimage.colorCount(); i++) { + qimage.setColor(i, toGray(qimage.color(i))); } } diff --git a/imagelib/effects/kpEffectHSV.h b/imagelib/effects/kpEffectHSV.h --- a/imagelib/effects/kpEffectHSV.h +++ b/imagelib/effects/kpEffectHSV.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2007 Mike Gashler All rights reserved. @@ -25,20 +24,15 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectHSV_H #define kpEffectHSV_H - #include "imagelib/kpImage.h" - class kpEffectHSV { public: - static kpImage applyEffect (const kpImage &image, - double hue, double saturation, double value); + static kpImage applyEffect(const kpImage &image, double hue, double saturation, double value); }; - #endif // kpEffectHSV_H diff --git a/imagelib/effects/kpEffectHSV.cpp b/imagelib/effects/kpEffectHSV.cpp --- a/imagelib/effects/kpEffectHSV.cpp +++ b/imagelib/effects/kpEffectHSV.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2007 Mike Gashler All rights reserved. @@ -38,152 +37,134 @@ #include "pixmapfx/kpPixmapFX.h" - -static void ColorToHSV(unsigned int c, float* pHue, float* pSaturation, float* pValue) +static void ColorToHSV(unsigned int c, float *pHue, float *pSaturation, float *pValue) { int r = qRed(c); int g = qGreen(c); int b = qBlue(c); int min{}; - if(b >= g && b >= r) - { + if (b >= g && b >= r) { // Blue min = qMin(r, g); - if(b != min) - { - *pHue = static_cast (r - g) / ((b - min) * 6) + static_cast (2) / 3; - *pSaturation = 1.0f - static_cast (min) / static_cast (b); - } - else - { + if (b != min) { + *pHue = static_cast(r - g) / ((b - min) * 6) + static_cast(2) / 3; + *pSaturation = 1.0f - static_cast(min) / static_cast(b); + } else { *pHue = 0; *pSaturation = 0; } - *pValue = static_cast (b) / 255; - } - else if(g >= r) - { + *pValue = static_cast(b) / 255; + } else if (g >= r) { // Green min = qMin(b, r); - if(g != min) - { - *pHue = static_cast (b - r) / ((g - min) * 6) + static_cast (1) / 3; - *pSaturation = 1.0f - static_cast (min) / static_cast (g); - } - else - { + if (g != min) { + *pHue = static_cast(b - r) / ((g - min) * 6) + static_cast(1) / 3; + *pSaturation = 1.0f - static_cast(min) / static_cast(g); + } else { *pHue = 0; *pSaturation = 0; } - *pValue = static_cast (g) / 255; - } - else - { + *pValue = static_cast(g) / 255; + } else { // Red min = qMin(g, b); - if(r != min) - { - *pHue = static_cast (g - b) / ((r - min) * 6); - if(*pHue < 0) { + if (r != min) { + *pHue = static_cast(g - b) / ((r - min) * 6); + if (*pHue < 0) { (*pHue) += 1.0f; } - *pSaturation = 1.0f - static_cast (min) / static_cast (r); - } - else - { + *pSaturation = 1.0f - static_cast(min) / static_cast(r); + } else { *pHue = 0; *pSaturation = 0; } - *pValue = static_cast (r) / 255; + *pValue = static_cast(r) / 255; } } static unsigned int HSVToColor(int alpha, float hue, float saturation, float value) { hue *= 5.999999f; - int h = static_cast (hue); + int h = static_cast(hue); float f = hue - h; float p = value * (1.0 - saturation); float q = value * (1.0 - ((h & 1) == 0 ? 1.0 - f : f) * saturation); - switch(h) - { - case 0: return qRgba(static_cast (value * 255.999999), - static_cast (q * 255.999999), - static_cast (p * 255.999999), alpha); - - case 1: return qRgba(static_cast (q * 255.999999), - static_cast (value * 255.999999), - static_cast (p * 255.999999), alpha); - - case 2: return qRgba(static_cast (p * 255.999999), - static_cast (value * 255.999999), - static_cast (q * 255.999999), alpha); - - case 3: return qRgba(static_cast (p * 255.999999), - static_cast (q * 255.999999), - static_cast (value * 255.999999), alpha); - - case 4: return qRgba(static_cast (q * 255.999999), - static_cast (p * 255.999999), - static_cast (value * 255.999999), alpha); - - case 5: return qRgba(static_cast (value * 255.999999), - static_cast (p * 255.999999), - static_cast (q * 255.999999), alpha); + switch (h) { + case 0: + return qRgba(static_cast(value * 255.999999), + static_cast(q * 255.999999), + static_cast(p * 255.999999), alpha); + + case 1: + return qRgba(static_cast(q * 255.999999), + static_cast(value * 255.999999), + static_cast(p * 255.999999), alpha); + + case 2: + return qRgba(static_cast(p * 255.999999), + static_cast(value * 255.999999), + static_cast(q * 255.999999), alpha); + + case 3: + return qRgba(static_cast(p * 255.999999), + static_cast(q * 255.999999), + static_cast(value * 255.999999), alpha); + + case 4: + return qRgba(static_cast(q * 255.999999), + static_cast(p * 255.999999), + static_cast(value * 255.999999), alpha); + + case 5: + return qRgba(static_cast(value * 255.999999), + static_cast(p * 255.999999), + static_cast(q * 255.999999), alpha); } return qRgba(0, 0, 0, alpha); } -static QRgb AdjustHSVInternal (QRgb pix, double hueDiv360, double saturation, double value) +static QRgb AdjustHSVInternal(QRgb pix, double hueDiv360, double saturation, double value) { float h, s, v; ::ColorToHSV(pix, &h, &s, &v); - + const int alpha = qAlpha(pix); - h += static_cast (hueDiv360); + h += static_cast(hueDiv360); h -= std::floor(h); - s = qMax(0.0f, qMin(static_cast(1), s + static_cast (saturation))); + s = qMax(0.0f, qMin(static_cast(1), s + static_cast(saturation))); - v = qMax(0.0f, qMin(static_cast(1), v + static_cast (value))); + v = qMax(0.0f, qMin(static_cast(1), v + static_cast(value))); return ::HSVToColor(alpha, h, s, v); } -static void AdjustHSV (QImage* pImage, double hue, double saturation, double value) +static void AdjustHSV(QImage *pImage, double hue, double saturation, double value) { hue /= 360; - if (pImage->depth () > 8) - { - for (int y = 0; y < pImage->height (); y++) - { - for (int x = 0; x < pImage->width (); x++) - { - QRgb pix = pImage->pixel (x, y); - pix = ::AdjustHSVInternal (pix, hue, saturation, value); - pImage->setPixel (x, y, pix); + if (pImage->depth() > 8) { + for (int y = 0; y < pImage->height(); y++) { + for (int x = 0; x < pImage->width(); x++) { + QRgb pix = pImage->pixel(x, y); + pix = ::AdjustHSVInternal(pix, hue, saturation, value); + pImage->setPixel(x, y, pix); } } - } - else - { - for (int i = 0; i < pImage->colorCount (); i++) - { - QRgb pix = pImage->color (i); - pix = ::AdjustHSVInternal (pix, hue, saturation, value); - pImage->setColor (i, pix); + } else { + for (int i = 0; i < pImage->colorCount(); i++) { + QRgb pix = pImage->color(i); + pix = ::AdjustHSVInternal(pix, hue, saturation, value); + pImage->setColor(i, pix); } } } // public static -kpImage kpEffectHSV::applyEffect (const kpImage &image, - double hue, double saturation, double value) +kpImage kpEffectHSV::applyEffect(const kpImage &image, double hue, double saturation, double value) { QImage qimage(image); - ::AdjustHSV (&qimage, hue, saturation, value); + ::AdjustHSV(&qimage, hue, saturation, value); return qimage; } - diff --git a/imagelib/effects/kpEffectInvert.h b/imagelib/effects/kpEffectInvert.h --- a/imagelib/effects/kpEffectInvert.h +++ b/imagelib/effects/kpEffectInvert.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectInvert_H #define kpEffectInvert_H - class QImage; - class kpEffectInvert { public: @@ -54,9 +50,8 @@ // 2. never inverts the Alpha Buffer // - static void applyEffect (QImage *destImagePtr, int channels = RGB); - static QImage applyEffect (const QImage &img, int channels = RGB); + static void applyEffect(QImage *destImagePtr, int channels = RGB); + static QImage applyEffect(const QImage &img, int channels = RGB); }; - #endif // kpEffectInvert_H diff --git a/imagelib/effects/kpEffectInvert.cpp b/imagelib/effects/kpEffectInvert.cpp --- a/imagelib/effects/kpEffectInvert.cpp +++ b/imagelib/effects/kpEffectInvert.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,65 +24,53 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_INVERT 0 - #include "kpEffectInvert.h" #include #include "kpLogCategories.h" #include "pixmapfx/kpPixmapFX.h" - // public static -void kpEffectInvert::applyEffect (QImage *destImagePtr, int channels) +void kpEffectInvert::applyEffect(QImage *destImagePtr, int channels) { - if (channels == kpEffectInvert::RGB) - { - destImagePtr->invertPixels (); + if (channels == kpEffectInvert::RGB) { + destImagePtr->invertPixels(); return; } - QRgb mask = qRgba ((channels & Red) ? 0xFF : 0, - (channels & Green) ? 0xFF : 0, - (channels & Blue) ? 0xFF : 0, - 0/*don't invert alpha*/); + QRgb mask = qRgba((channels & Red) ? 0xFF : 0, + (channels & Green) ? 0xFF : 0, + (channels & Blue) ? 0xFF : 0, + 0 /*don't invert alpha*/); #if DEBUG_KP_EFFECT_INVERT qCDebug(kpLogImagelib) << "kpEffectInvert::applyEffect(channels=" << channels - << ") mask=" << (int *) mask; + << ") mask=" << (int *)mask; #endif - if (destImagePtr->depth () > 8) - { + if (destImagePtr->depth() > 8) { // Above version works for Qt 3.2 at least. // But this version will always work (slower, though) and supports // inverting particular channels. - for (int y = 0; y < destImagePtr->height (); y++) - { - for (int x = 0; x < destImagePtr->width (); x++) - { - destImagePtr->setPixel (x, y, destImagePtr->pixel (x, y) ^ mask); + for (int y = 0; y < destImagePtr->height(); y++) { + for (int x = 0; x < destImagePtr->width(); x++) { + destImagePtr->setPixel(x, y, destImagePtr->pixel(x, y) ^ mask); } } - } - else - { - for (int i = 0; i < destImagePtr->colorCount (); i++) - { - destImagePtr->setColor (i, destImagePtr->color (i) ^ mask); + } else { + for (int i = 0; i < destImagePtr->colorCount(); i++) { + destImagePtr->setColor(i, destImagePtr->color(i) ^ mask); } } } // public static -QImage kpEffectInvert::applyEffect (const QImage &img, int channels) +QImage kpEffectInvert::applyEffect(const QImage &img, int channels) { QImage retImage = img; - applyEffect (&retImage, channels); + applyEffect(&retImage, channels); return retImage; } - - diff --git a/imagelib/effects/kpEffectReduceColors.h b/imagelib/effects/kpEffectReduceColors.h --- a/imagelib/effects/kpEffectReduceColors.h +++ b/imagelib/effects/kpEffectReduceColors.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectReduceColors_H #define kpEffectReduceColors_H @@ -38,14 +36,13 @@ // TODO: Why isn't applyEffect() for the public API sufficient? // Ans: See TODO in kpDocument_Save.cpp. Maybe we should rename // this method? - // + // // Also, this can increase the image depth while applyEffect() // will not. - static QImage convertImageDepth (const QImage &image, int depth, bool dither); + static QImage convertImageDepth(const QImage &image, int depth, bool dither); - static void applyEffect (QImage *destPixmapPtr, int depth, bool dither); - static QImage applyEffect (const QImage &pm, int depth, bool dither); + static void applyEffect(QImage *destPixmapPtr, int depth, bool dither); + static QImage applyEffect(const QImage &pm, int depth, bool dither); }; - #endif // kpEffectReduceColors_H diff --git a/imagelib/effects/kpEffectReduceColors.cpp b/imagelib/effects/kpEffectReduceColors.cpp --- a/imagelib/effects/kpEffectReduceColors.cpp +++ b/imagelib/effects/kpEffectReduceColors.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2011 Martin Koller @@ -26,21 +25,18 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_REDUCE_COLORS 0 - #include "imagelib/effects/kpEffectReduceColors.h" #include "kpLogCategories.h" //--------------------------------------------------------------------- -static QImage::Format DepthToFormat (int depth) +static QImage::Format DepthToFormat(int depth) { // These values are QImage's supported depths. - switch (depth) - { + switch (depth) { case 1: // (can be MSB instead, I suppose) return QImage::Format_MonoLSB; @@ -58,109 +54,97 @@ return QImage::Format_ARGB32_Premultiplied; default: - Q_ASSERT (!"unknown depth"); + Q_ASSERT(!"unknown depth"); return QImage::Format_Invalid; } } //--------------------------------------------------------------------- // public static -QImage kpEffectReduceColors::convertImageDepth (const QImage &image, int depth, bool dither) +QImage kpEffectReduceColors::convertImageDepth(const QImage &image, int depth, bool dither) { #if DEBUG_KP_EFFECT_REDUCE_COLORS - qCDebug(kpLogImagelib) << "kpeffectreducecolors.cpp:ConvertImageDepth() changing image (w=" << image.width () - << ",h=" << image.height () - << ") depth from " << image.depth () - << " to " << depth - << " (dither=" << dither << ")" - << endl; + qCDebug(kpLogImagelib) << "kpeffectreducecolors.cpp:ConvertImageDepth() changing image (w=" + << image.width() + << ",h=" << image.height() + << ") depth from " << image.depth() + << " to " << depth + << " (dither=" << dither << ")" + << endl; #endif - if (image.isNull ()) { + if (image.isNull()) { return image; } - if (depth == image.depth ()) { + if (depth == image.depth()) { return image; } - #if DEBUG_KP_EFFECT_REDUCE_COLORS && 0 - for (int y = 0; y < image.height (); y++) - { - for (int x = 0; x < image.width (); x++) - { - fprintf (stderr, " %08X", image.pixel (x, y)); + for (int y = 0; y < image.height(); y++) { + for (int x = 0; x < image.width(); x++) { + fprintf(stderr, " %08X", image.pixel(x, y)); } - fprintf (stderr, "\n"); + fprintf(stderr, "\n"); } #endif - // Hack around Qt's braindead QImage::convertToFormat(QImage::Format_MonoLSB, ...) // (with dithering off) which produces pathetic results with an image that // only has 2 colors - sometimes it just gives a completely black // result (try yellow and white as input). Instead, we simply preserve // the 2 colours. // // One use case is resaving a "color monochrome" image (<= 2 colors but // not necessarily black & white). - if (depth == 1 && !dither) - { + if (depth == 1 && !dither) { #if DEBUG_KP_EFFECT_REDUCE_COLORS qCDebug(kpLogImagelib) << "\tinvoking convert-to-depth 1 hack"; #endif QRgb color0 = 0, color1 = 0; bool color0Valid = false, color1Valid = false; bool moreThan2Colors = false; - QImage monoImage (image.width (), image.height (), QImage::Format_MonoLSB); - monoImage.setColorCount (2); + QImage monoImage(image.width(), image.height(), QImage::Format_MonoLSB); + monoImage.setColorCount(2); #if DEBUG_KP_EFFECT_REDUCE_COLORS - qCDebug(kpLogImagelib) << "\t\tinitialising output image w=" << monoImage.width () - << ",h=" << monoImage.height () - << ",d=" << monoImage.depth (); + qCDebug(kpLogImagelib) << "\t\tinitialising output image w=" << monoImage.width() + << ",h=" << monoImage.height() + << ",d=" << monoImage.depth(); #endif - for (int y = 0; y < image.height (); y++) - { - for (int x = 0; x < image.width (); x++) - { + for (int y = 0; y < image.height(); y++) { + for (int x = 0; x < image.width(); x++) { // (this can be transparent) - QRgb imagePixel = image.pixel (x, y); + QRgb imagePixel = image.pixel(x, y); if (color0Valid && imagePixel == color0) { - monoImage.setPixel (x, y, 0); - } - else if (color1Valid && imagePixel == color1) { - monoImage.setPixel (x, y, 1); - } - else if (!color0Valid) { + monoImage.setPixel(x, y, 0); + } else if (color1Valid && imagePixel == color1) { + monoImage.setPixel(x, y, 1); + } else if (!color0Valid) { color0 = imagePixel; color0Valid = true; - monoImage.setPixel (x, y, 0); + monoImage.setPixel(x, y, 0); #if DEBUG_KP_EFFECT_REDUCE_COLORS - qCDebug(kpLogImagelib) << "\t\t\tcolor0=" << (int *) color0 - << " at x=" << x << ",y=" << y; + qCDebug(kpLogImagelib) << "\t\t\tcolor0=" << (int *)color0 + << " at x=" << x << ",y=" << y; #endif - } - else if (!color1Valid) - { + } else if (!color1Valid) { color1 = imagePixel; color1Valid = true; - monoImage.setPixel (x, y, 1); + monoImage.setPixel(x, y, 1); #if DEBUG_KP_EFFECT_REDUCE_COLORS - qCDebug(kpLogImagelib) << "\t\t\tcolor1=" << (int *) color1 - << " at x=" << x << ",y=" << y; + qCDebug(kpLogImagelib) << "\t\t\tcolor1=" << (int *)color1 + << " at x=" << x << ",y=" << y; #endif - } - else - { + } else { #if DEBUG_KP_EFFECT_REDUCE_COLORS - qCDebug(kpLogImagelib) << "\t\t\timagePixel=" << (int *) imagePixel - << " at x=" << x << ",y=" << y - << " moreThan2Colors - abort hack"; + qCDebug(kpLogImagelib) << "\t\t\timagePixel=" << (int *)imagePixel + << " at x=" << x << ",y=" << y + << " moreThan2Colors - abort hack"; #endif moreThan2Colors = true; @@ -170,35 +154,32 @@ } } } - exit_loop: +exit_loop: - if (!moreThan2Colors) - { - monoImage.setColor (0, color0Valid ? color0 : 0xFFFFFF); - monoImage.setColor (1, color1Valid ? color1 : 0x000000); + if (!moreThan2Colors) { + monoImage.setColor(0, color0Valid ? color0 : 0xFFFFFF); + monoImage.setColor(1, color1Valid ? color1 : 0x000000); return monoImage; } } - QImage retImage = image.convertToFormat (::DepthToFormat (depth), - Qt::AutoColor | - (dither ? Qt::DiffuseDither : Qt::ThresholdDither) | - Qt::ThresholdAlphaDither | - (dither ? Qt::PreferDither : Qt::AvoidDither)); + QImage retImage = image.convertToFormat(::DepthToFormat(depth), + Qt::AutoColor + |(dither ? Qt::DiffuseDither : Qt::ThresholdDither) + |Qt::ThresholdAlphaDither + |(dither ? Qt::PreferDither : Qt::AvoidDither)); #if DEBUG_KP_EFFECT_REDUCE_COLORS - qCDebug(kpLogImagelib) << "\tformat: before=" << image.format () - << "after=" << retImage.format (); + qCDebug(kpLogImagelib) << "\tformat: before=" << image.format() + << "after=" << retImage.format(); #endif #if DEBUG_KP_EFFECT_REDUCE_COLORS && 0 qCDebug(kpLogImagelib) << "After colour reduction:"; - for (int y = 0; y < image.height (); y++) - { - for (int x = 0; x < image.width (); x++) - { - fprintf (stderr, " %08X", image.pixel (x, y)); + for (int y = 0; y < image.height(); y++) { + for (int x = 0; x < image.width(); x++) { + fprintf(stderr, " %08X", image.pixel(x, y)); } - fprintf (stderr, "\n"); + fprintf(stderr, "\n"); } #endif @@ -208,7 +189,7 @@ //--------------------------------------------------------------------- // public static -void kpEffectReduceColors::applyEffect (QImage *destPtr, int depth, bool dither) +void kpEffectReduceColors::applyEffect(QImage *destPtr, int depth, bool dither) { if (!destPtr) { return; @@ -230,10 +211,10 @@ //--------------------------------------------------------------------- -QImage kpEffectReduceColors::applyEffect (const QImage &pm, int depth, bool dither) +QImage kpEffectReduceColors::applyEffect(const QImage &pm, int depth, bool dither) { QImage ret = pm; - applyEffect (&ret, depth, dither); + applyEffect(&ret, depth, dither); return ret; } diff --git a/imagelib/effects/kpEffectToneEnhance.h b/imagelib/effects/kpEffectToneEnhance.h --- a/imagelib/effects/kpEffectToneEnhance.h +++ b/imagelib/effects/kpEffectToneEnhance.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2006 Mike Gashler @@ -26,14 +25,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectToneEnhance_H #define kpEffectToneEnhance_H - #include "imagelib/kpImage.h" - // // Histogram Equalizer effect. // @@ -53,9 +49,7 @@ class kpEffectToneEnhance { public: - static kpImage applyEffect (const kpImage &image, - double granularity, double amount); + static kpImage applyEffect(const kpImage &image, double granularity, double amount); }; - #endif // kpEffectToneEnhance_H diff --git a/imagelib/effects/kpEffectToneEnhance.cpp b/imagelib/effects/kpEffectToneEnhance.cpp --- a/imagelib/effects/kpEffectToneEnhance.cpp +++ b/imagelib/effects/kpEffectToneEnhance.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2006 Mike Gashler @@ -26,7 +25,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - // TODO: Clarence's code review #include "kpEffectToneEnhance.h" @@ -37,7 +35,6 @@ #include "pixmapfx/kpPixmapFX.h" - #define RED_WEIGHT 77 #define GREEN_WEIGHT 150 #define BLUE_WEIGHT 29 @@ -52,138 +49,145 @@ inline unsigned int ComputeTone(unsigned int color) { - return RED_WEIGHT * static_cast (qRed(color)) + - GREEN_WEIGHT * static_cast (qGreen(color)) + - BLUE_WEIGHT * static_cast (qBlue(color)); + return RED_WEIGHT * static_cast(qRed(color)) + +GREEN_WEIGHT * static_cast(qGreen(color)) + +BLUE_WEIGHT * static_cast(qBlue(color)); } //--------------------------------------------------------------------- -inline unsigned int AdjustTone(unsigned int color, unsigned int oldTone, unsigned int newTone, double amount) +inline unsigned int AdjustTone(unsigned int color, unsigned int oldTone, unsigned int newTone, + double amount) { - return qRgba( - qMax(0, qMin(255, static_cast (amount * qRed(color) * newTone / oldTone + (1.0 - amount) * qRed(color)))), - qMax(0, qMin(255, static_cast (amount * qGreen(color) * newTone / oldTone + (1.0 - amount) * qGreen(color)))), - qMax(0, qMin(255, static_cast (amount * qBlue(color) * newTone / oldTone + (1.0 - amount) * qBlue(color)))), - qAlpha(color) - ); + return qRgba( + qMax(0, + qMin(255, + static_cast(amount * qRed(color) * newTone / oldTone + (1.0 - amount) + * qRed(color)))), + qMax(0, + qMin(255, + static_cast(amount * qGreen(color) * newTone / oldTone + (1.0 - amount) + * qGreen(color)))), + qMax(0, + qMin(255, + static_cast(amount * qBlue(color) * newTone / oldTone + (1.0 - amount) + * qBlue(color)))), + qAlpha(color) + ); } //--------------------------------------------------------------------- class kpEffectToneEnhanceApplier { - public: +public: kpEffectToneEnhanceApplier (); ~kpEffectToneEnhanceApplier (); - void BalanceImageTone(QImage* pImage, double granularity, double amount); + void BalanceImageTone(QImage *pImage, double granularity, double amount); - protected: +protected: int m_nToneMapGranularity, m_areaWid, m_areaHgt; unsigned int m_nComputedWid, m_nComputedHgt; // LOTODO: Use less error-prone QTL containers instead. - unsigned int* m_pHistogram; - unsigned int** m_pToneMaps; + unsigned int *m_pHistogram; + unsigned int **m_pToneMaps; void DeleteToneMaps(); - unsigned int* MakeToneMap(QImage* pImage, int x, int y, int nGranularity); - void ComputeToneMaps(QImage* pImage, int nGranularity); - unsigned int InterpolateNewTone(QImage* pImage, unsigned int oldTone, int x, int y, int nGranularity); + unsigned int *MakeToneMap(QImage *pImage, int x, int y, int nGranularity); + void ComputeToneMaps(QImage *pImage, int nGranularity); + unsigned int InterpolateNewTone(QImage *pImage, unsigned int oldTone, int x, int y, + int nGranularity); }; //--------------------------------------------------------------------- kpEffectToneEnhanceApplier::kpEffectToneEnhanceApplier () { - m_nToneMapGranularity = 0; - m_areaWid = 0; - m_areaHgt = 0; - m_nComputedWid = 0; - m_nComputedHgt = 0; - m_pHistogram = new unsigned int[TONE_MAP_SIZE]; - m_pToneMaps = nullptr; + m_nToneMapGranularity = 0; + m_areaWid = 0; + m_areaHgt = 0; + m_nComputedWid = 0; + m_nComputedHgt = 0; + m_pHistogram = new unsigned int[TONE_MAP_SIZE]; + m_pToneMaps = nullptr; } //--------------------------------------------------------------------- kpEffectToneEnhanceApplier::~kpEffectToneEnhanceApplier () { - DeleteToneMaps(); - delete[] m_pHistogram; + DeleteToneMaps(); + delete[] m_pHistogram; } //--------------------------------------------------------------------- // protected void kpEffectToneEnhanceApplier::DeleteToneMaps() { - int nToneMaps = m_nToneMapGranularity * m_nToneMapGranularity; - for(int i = 0; i < nToneMaps; i++) { - delete[] m_pToneMaps[i]; - } - delete[] m_pToneMaps; - m_pToneMaps = nullptr; - m_nToneMapGranularity = 0; + int nToneMaps = m_nToneMapGranularity * m_nToneMapGranularity; + for (int i = 0; i < nToneMaps; i++) { + delete[] m_pToneMaps[i]; + } + delete[] m_pToneMaps; + m_pToneMaps = nullptr; + m_nToneMapGranularity = 0; } //--------------------------------------------------------------------- // protected -unsigned int* kpEffectToneEnhanceApplier::MakeToneMap(QImage* pImage, int u, int v, int nGranularity) +unsigned int *kpEffectToneEnhanceApplier::MakeToneMap(QImage *pImage, int u, int v, + int nGranularity) { // Compute the region to make the tone map for int xx, yy; - if(nGranularity > 1) - { + if (nGranularity > 1) { xx = u * (pImage->width() - 1) / (nGranularity - 1) - m_areaWid / 2; - if(xx < 0) { + if (xx < 0) { xx = 0; - } - else if(xx + m_areaWid > pImage->width()) { + } else if (xx + m_areaWid > pImage->width()) { xx = pImage->width() - m_areaWid; } yy = v * (pImage->width() - 1) / (nGranularity - 1) - m_areaHgt / 2; - if(yy < 0) { + if (yy < 0) { yy = 0; - } - else if(yy + m_areaHgt > pImage->height()) { + } else if (yy + m_areaHgt > pImage->height()) { yy = pImage->height() - m_areaHgt; } - } - else - { + } else { xx = 0; yy = 0; } - // Make a tone histogram for the region - memset(m_pHistogram, '\0', sizeof(unsigned int) * TONE_MAP_SIZE); - int x, y; - unsigned int tone; - for(y = 0; y < m_areaHgt; y++) - { - for(x = 0; x < m_areaWid; x++) - { - tone = ComputeTone(pImage->pixel(xx + x, yy + y)); - m_pHistogram[tone >> TONE_DROP_BITS]++; + // Make a tone histogram for the region + memset(m_pHistogram, '\0', sizeof(unsigned int) * TONE_MAP_SIZE); + int x, y; + unsigned int tone; + for (y = 0; y < m_areaHgt; y++) { + for (x = 0; x < m_areaWid; x++) { + tone = ComputeTone(pImage->pixel(xx + x, yy + y)); + m_pHistogram[tone >> TONE_DROP_BITS]++; + } } - } - // Forward sum the tone histogram - int i{}; - for(i = 1; i < TONE_MAP_SIZE; i++) { - m_pHistogram[i] += m_pHistogram[i - 1]; - } + // Forward sum the tone histogram + int i{}; + for (i = 1; i < TONE_MAP_SIZE; i++) { + m_pHistogram[i] += m_pHistogram[i - 1]; + } - // Compute the forward contribution to the tone map - auto total = m_pHistogram[i - 1]; - auto *pToneMap = new unsigned int[TONE_MAP_SIZE]; - for(i = 0; i < TONE_MAP_SIZE; i++) { - pToneMap[i] = static_cast (static_cast (m_pHistogram[i] * MAX_TONE_VALUE / total)); - } + // Compute the forward contribution to the tone map + auto total = m_pHistogram[i - 1]; + auto *pToneMap = new unsigned int[TONE_MAP_SIZE]; + for (i = 0; i < TONE_MAP_SIZE; i++) { + pToneMap[i] + = static_cast(static_cast(m_pHistogram[i] * MAX_TONE_VALUE + / total)); + } /* // Undo the forward sum and reverse sum the tone histogram m_pHistogram[TONE_MAP_SIZE - 1] -= m_pHistogram[TONE_MAP_SIZE - 2]; @@ -194,115 +198,116 @@ } m_pHistogram[0] += m_pHistogram[1]; */ - return pToneMap; + return pToneMap; } //--------------------------------------------------------------------- // protected -void kpEffectToneEnhanceApplier::ComputeToneMaps(QImage* pImage, int nGranularity) +void kpEffectToneEnhanceApplier::ComputeToneMaps(QImage *pImage, int nGranularity) { - if(nGranularity == m_nToneMapGranularity && pImage->width() == - static_cast (m_nComputedWid) && pImage->height() == static_cast (m_nComputedHgt)) - { - return; // We've already computed tone maps for this granularity - } - DeleteToneMaps(); - m_pToneMaps = new unsigned int*[nGranularity * nGranularity]; - m_nToneMapGranularity = nGranularity; - m_nComputedWid = static_cast (pImage->width()); - m_nComputedHgt = static_cast (pImage->height()); - int u, v; - for(v = 0; v < nGranularity; v++) - { - for(u = 0; u < nGranularity; u++) { - m_pToneMaps[nGranularity * v + u] = MakeToneMap(pImage, u, v, nGranularity); - } - } + if (nGranularity == m_nToneMapGranularity && pImage->width() + == static_cast(m_nComputedWid) + && pImage->height() == static_cast(m_nComputedHgt)) { + return; // We've already computed tone maps for this granularity + } + DeleteToneMaps(); + m_pToneMaps = new unsigned int *[nGranularity * nGranularity]; + m_nToneMapGranularity = nGranularity; + m_nComputedWid = static_cast(pImage->width()); + m_nComputedHgt = static_cast(pImage->height()); + int u, v; + for (v = 0; v < nGranularity; v++) { + for (u = 0; u < nGranularity; u++) { + m_pToneMaps[nGranularity * v + u] = MakeToneMap(pImage, u, v, nGranularity); + } + } } //--------------------------------------------------------------------- // protected -unsigned int kpEffectToneEnhanceApplier::InterpolateNewTone(QImage* pImage, unsigned int oldTone, int x, int y, int nGranularity) +unsigned int kpEffectToneEnhanceApplier::InterpolateNewTone(QImage *pImage, unsigned int oldTone, + int x, int y, int nGranularity) { - oldTone = (oldTone >> TONE_DROP_BITS); - if(m_nToneMapGranularity <= 1) { - return m_pToneMaps[0][oldTone]; - } - auto u = x * (nGranularity - 1) / pImage->width(); - auto v = y * (nGranularity - 1) / pImage->height(); - auto x1y1 = m_pToneMaps[m_nToneMapGranularity * v + u][oldTone]; - auto x2y1 = m_pToneMaps[m_nToneMapGranularity * v + u + 1][oldTone]; - auto x1y2 = m_pToneMaps[m_nToneMapGranularity * (v + 1) + u][oldTone]; - auto x2y2 = m_pToneMaps[m_nToneMapGranularity * (v + 1) + u + 1][oldTone]; - auto hFac = x - (u * (pImage->width() - 1) / (nGranularity - 1)); - if(hFac > m_areaWid) { - hFac = m_areaWid; - } - unsigned int y1 = (x1y1 * (static_cast (m_areaWid) - static_cast (hFac)) - + x2y1 * static_cast (hFac)) / static_cast (m_areaWid); - - unsigned int y2 = (x1y2 * (static_cast (m_areaWid) - static_cast (hFac)) - + x2y2 * static_cast (hFac)) / static_cast (m_areaWid); - - int vFac = y - (v * (pImage->height() - 1) / (nGranularity - 1)); - if(vFac > m_areaHgt) { - vFac = m_areaHgt; - } - return (y1 * (static_cast (m_areaHgt) - static_cast (vFac)) - + y2 * static_cast (vFac)) / static_cast (m_areaHgt); + oldTone = (oldTone >> TONE_DROP_BITS); + if (m_nToneMapGranularity <= 1) { + return m_pToneMaps[0][oldTone]; + } + auto u = x * (nGranularity - 1) / pImage->width(); + auto v = y * (nGranularity - 1) / pImage->height(); + auto x1y1 = m_pToneMaps[m_nToneMapGranularity * v + u][oldTone]; + auto x2y1 = m_pToneMaps[m_nToneMapGranularity * v + u + 1][oldTone]; + auto x1y2 = m_pToneMaps[m_nToneMapGranularity * (v + 1) + u][oldTone]; + auto x2y2 = m_pToneMaps[m_nToneMapGranularity * (v + 1) + u + 1][oldTone]; + auto hFac = x - (u * (pImage->width() - 1) / (nGranularity - 1)); + if (hFac > m_areaWid) { + hFac = m_areaWid; + } + unsigned int y1 + = (x1y1 * (static_cast(m_areaWid) - static_cast(hFac)) + + x2y1 * static_cast(hFac)) + / static_cast(m_areaWid); + + unsigned int y2 + = (x1y2 * (static_cast(m_areaWid) - static_cast(hFac)) + + x2y2 * static_cast(hFac)) + / static_cast(m_areaWid); + + int vFac = y - (v * (pImage->height() - 1) / (nGranularity - 1)); + if (vFac > m_areaHgt) { + vFac = m_areaHgt; + } + return (y1 * (static_cast(m_areaHgt) - static_cast(vFac)) + + y2 * static_cast(vFac)) / static_cast(m_areaHgt); } //--------------------------------------------------------------------- // public -void kpEffectToneEnhanceApplier::BalanceImageTone(QImage* pImage, double granularity, double amount) +void kpEffectToneEnhanceApplier::BalanceImageTone(QImage *pImage, double granularity, double amount) { - if(pImage->width() < MIN_IMAGE_DIM || pImage->height() < MIN_IMAGE_DIM) { + if (pImage->width() < MIN_IMAGE_DIM || pImage->height() < MIN_IMAGE_DIM) { return; // the image is not big enough to perform this operation } - int nGranularity = static_cast (granularity * (MAX_GRANULARITY - 2)) + 1; - m_areaWid = pImage->width() / nGranularity; - if(m_areaWid < MIN_IMAGE_DIM) { - m_areaWid = MIN_IMAGE_DIM; - } - m_areaHgt = pImage->height() / nGranularity; - if(m_areaHgt < MIN_IMAGE_DIM) { - m_areaHgt = MIN_IMAGE_DIM; - } - ComputeToneMaps(pImage, nGranularity); - int x, y; - unsigned int oldTone, newTone, col; - for(y = 0; y < pImage->height(); y++) - { - for(x = 0; x < pImage->width(); x++) - { - col = pImage->pixel(x, y); - oldTone = ComputeTone(col); - newTone = InterpolateNewTone(pImage, oldTone, x, y, nGranularity); - pImage->setPixel(x, y, AdjustTone(col, oldTone, newTone, amount)); - } - } + int nGranularity = static_cast(granularity * (MAX_GRANULARITY - 2)) + 1; + m_areaWid = pImage->width() / nGranularity; + if (m_areaWid < MIN_IMAGE_DIM) { + m_areaWid = MIN_IMAGE_DIM; + } + m_areaHgt = pImage->height() / nGranularity; + if (m_areaHgt < MIN_IMAGE_DIM) { + m_areaHgt = MIN_IMAGE_DIM; + } + ComputeToneMaps(pImage, nGranularity); + int x, y; + unsigned int oldTone, newTone, col; + for (y = 0; y < pImage->height(); y++) { + for (x = 0; x < pImage->width(); x++) { + col = pImage->pixel(x, y); + oldTone = ComputeTone(col); + newTone = InterpolateNewTone(pImage, oldTone, x, y, nGranularity); + pImage->setPixel(x, y, AdjustTone(col, oldTone, newTone, amount)); + } + } } //--------------------------------------------------------------------- // public static -kpImage kpEffectToneEnhance::applyEffect (const kpImage &image, - double granularity, double amount) +kpImage kpEffectToneEnhance::applyEffect(const kpImage &image, double granularity, double amount) { - if (amount == 0.0) { - return image; - } + if (amount == 0.0) { + return image; + } - QImage qimage(image); + QImage qimage(image); - // OPT: Cache the calculated values? - kpEffectToneEnhanceApplier applier; - applier.BalanceImageTone (&qimage, granularity, amount); + // OPT: Cache the calculated values? + kpEffectToneEnhanceApplier applier; + applier.BalanceImageTone(&qimage, granularity, amount); - return qimage; + return qimage; } //--------------------------------------------------------------------- diff --git a/imagelib/kpColor.h b/imagelib/kpColor.h --- a/imagelib/kpColor.h +++ b/imagelib/kpColor.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,17 +24,13 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_COLOR_H #define KP_COLOR_H - #include - class QDataStream; - // // kpColor is an object-oriented abstraction of QRgb, for document image data. // In the future, other color models such as @@ -58,99 +53,91 @@ kpColor (int red, int green, int blue, bool isTransparent = false); kpColor (const QRgb &rgba); kpColor (const kpColor &rhs); - friend QDataStream &operator<< (QDataStream &stream, const kpColor &color); - friend QDataStream &operator>> (QDataStream &stream, kpColor &color); - kpColor &operator= (const kpColor &rhs); - bool operator== (const kpColor &rhs) const; - bool operator!= (const kpColor &rhs) const; - + friend QDataStream &operator<<(QDataStream &stream, const kpColor &color); + friend QDataStream &operator>>(QDataStream &stream, kpColor &color); + kpColor &operator=(const kpColor &rhs); + bool operator==(const kpColor &rhs) const; + bool operator!=(const kpColor &rhs) const; // // Constants // public: // "lhs.isSimilarTo (rhs, kpColor::Exact)" is exactly the same as calling // "lhs == rhs". static const int Exact; - + static const kpColor Invalid; static const kpColor Transparent; - // // Primary Colors + B&W // - + static const kpColor Red, Green, Blue; static const kpColor Black, White; - // // Full-brightness Colors // static const kpColor Yellow, Purple, Aqua; - // // Mixed Colors // - + static const kpColor Gray, LightGray, Orange; - // // Pastel Colors // static const kpColor Pink, LightGreen, LightBlue, Tan; - // // Dark Colors // - + static const kpColor DarkRed; // (identical) static const kpColor DarkOrange, Brown; static const kpColor DarkYellow, DarkGreen, DarkAqua, DarkBlue, - DarkPurple, DarkGray; - + DarkPurple, DarkGray; public: - static int processSimilarity (double colorSimilarity); + static int processSimilarity(double colorSimilarity); // Usage: isSimilarTo (rhs, kpColor::processSimilarity (.1)) checks for // Color Similarity within 10% - bool isSimilarTo (const kpColor &rhs, int processedSimilarity) const; + bool isSimilarTo(const kpColor &rhs, int processedSimilarity) const; - bool isValid () const; + bool isValid() const; - int red () const; - int green () const; - int blue () const; - int alpha () const; - bool isTransparent () const; + int red() const; + int green() const; + int blue() const; + int alpha() const; + bool isTransparent() const; // Cast operators will most likely result in careless conversions so // use explicit functions instead: - QRgb toQRgb () const; + QRgb toQRgb() const; - QColor toQColor () const; + QColor toQColor() const; private: // Catch accidental call to "const QRgb &rgba" (unsigned int) ctor // by e.g. "kpColor(Qt::black)" (Qt::black is an enum element that can cast // to "unsigned int"). kpColor (Qt::GlobalColor color); - + bool m_rgbaIsValid; QRgb m_rgba; mutable bool m_colorCacheIsValid; mutable QColor m_colorCache; }; - #endif // KP_COLOR_H diff --git a/imagelib/kpColor.cpp b/imagelib/kpColor.cpp --- a/imagelib/kpColor.cpp +++ b/imagelib/kpColor.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COLOR 0 - #include "kpColor.h" #include @@ -38,57 +35,57 @@ //--------------------------------------------------------------------- kpColor::kpColor() - : m_rgbaIsValid(false), - m_rgba(0), - m_colorCacheIsValid(false) + : m_rgbaIsValid(false) + , m_rgba(0) + , m_colorCacheIsValid(false) { } //--------------------------------------------------------------------- kpColor::kpColor (int red, int green, int blue, bool isTransparent) - : m_rgba(0), m_colorCacheIsValid(false) + : m_rgba(0) + , m_colorCacheIsValid(false) { #if DEBUG_KP_COLOR qCDebug(kpLogImagelib) << "kpColor::(r=" << red << ",g=" << green << ",b=" << blue - << ",isTrans=" << isTransparent << ")"; + << ",isTrans=" << isTransparent << ")"; #endif - if (red < 0 || red > 255 || - green < 0 || green > 255 || - blue < 0 || blue > 255) - { + if (red < 0 || red > 255 + || green < 0 || green > 255 + || blue < 0 || blue > 255) { qCCritical(kpLogImagelib) << "kpColor::(r=" << red - << ",g=" << green - << ",b=" << blue - << ",t=" << isTransparent - << ") passed out of range values"; + << ",g=" << green + << ",b=" << blue + << ",t=" << isTransparent + << ") passed out of range values"; m_rgbaIsValid = false; return; } - m_rgba = qRgba (red, green, blue, isTransparent ? 0 : 255/*opaque*/); + m_rgba = qRgba(red, green, blue, isTransparent ? 0 : 255 /*opaque*/); m_rgbaIsValid = true; } //--------------------------------------------------------------------- kpColor::kpColor (const QRgb &rgba) - : m_colorCacheIsValid (false) + : m_colorCacheIsValid(false) { #if DEBUG_KP_COLOR - qCDebug(kpLogImagelib) << "kpColor::(rgba=" << (int *) rgba << ")"; + qCDebug(kpLogImagelib) << "kpColor::(rgba=" << (int *)rgba << ")"; #endif m_rgba = rgba; m_rgbaIsValid = true; } //--------------------------------------------------------------------- kpColor::kpColor (const kpColor &rhs) - : m_rgbaIsValid (rhs.m_rgbaIsValid), - m_rgba (rhs.m_rgba), - m_colorCacheIsValid (rhs.m_colorCacheIsValid), - m_colorCache (rhs.m_colorCache) + : m_rgbaIsValid(rhs.m_rgbaIsValid) + , m_rgba(rhs.m_rgba) + , m_colorCacheIsValid(rhs.m_colorCacheIsValid) + , m_colorCache(rhs.m_colorCache) { #if DEBUG_KP_COLOR qCDebug(kpLogImagelib) << "kpColor::()"; @@ -98,31 +95,31 @@ //--------------------------------------------------------------------- // friend -QDataStream &operator<< (QDataStream &stream, const kpColor &color) +QDataStream &operator<<(QDataStream &stream, const kpColor &color) { - stream << int (color.m_rgbaIsValid) << int (color.m_rgba); + stream << int(color.m_rgbaIsValid) << int(color.m_rgba); return stream; } //--------------------------------------------------------------------- // friend -QDataStream &operator>> (QDataStream &stream, kpColor &color) +QDataStream &operator>>(QDataStream &stream, kpColor &color) { int a, b; stream >> a >> b; color.m_rgbaIsValid = a; - color.m_rgba = static_cast (b); + color.m_rgba = static_cast(b); color.m_colorCacheIsValid = false; return stream; } //--------------------------------------------------------------------- -kpColor &kpColor::operator= (const kpColor &rhs) +kpColor &kpColor::operator=(const kpColor &rhs) { // (as soon as you add a ptr, you won't be complaining to me that this // method was unnecessary :)) @@ -139,53 +136,51 @@ return *this; } -bool kpColor::operator== (const kpColor &rhs) const +bool kpColor::operator==(const kpColor &rhs) const { - return isSimilarTo (rhs, kpColor::Exact); + return isSimilarTo(rhs, kpColor::Exact); } -bool kpColor::operator!= (const kpColor &rhs) const +bool kpColor::operator!=(const kpColor &rhs) const { return !(*this == rhs); } //--------------------------------------------------------------------- - -template -inline dtype square (dtype val) +template +inline dtype square(dtype val) { return val * val; } //--------------------------------------------------------------------- // public static -int kpColor::processSimilarity (double colorSimilarity) +int kpColor::processSimilarity(double colorSimilarity) { // sqrt (dr ^ 2 + dg ^ 2 + db ^ 2) <= colorSimilarity * sqrt (255 ^ 2 * 3) // dr ^ 2 + dg ^ 2 + db ^ 2 <= (colorSimilarity ^ 2) * (255 ^ 2 * 3) - return int (square (colorSimilarity) * (square (255) * 3)); + return int(square(colorSimilarity) * (square(255) * 3)); } //--------------------------------------------------------------------- -bool kpColor::isSimilarTo (const kpColor &rhs, int processedSimilarity) const +bool kpColor::isSimilarTo(const kpColor &rhs, int processedSimilarity) const { // Are we the same? if (this == &rhs) { return true; } - // Do we dither in terms of validity? - if (isValid () != rhs.isValid ()) { + if (isValid() != rhs.isValid()) { return false; } // Are both of us invalid? - if (!isValid ()) { + if (!isValid()) { return true; } @@ -199,93 +194,86 @@ return false; } - - return (square (qRed (m_rgba) - qRed (rhs.m_rgba)) + - square (qGreen (m_rgba) - qGreen (rhs.m_rgba)) + - square (qBlue (m_rgba) - qBlue (rhs.m_rgba)) - <= processedSimilarity); - + return square(qRed(m_rgba) - qRed(rhs.m_rgba)) + +square(qGreen(m_rgba) - qGreen(rhs.m_rgba)) + +square(qBlue(m_rgba) - qBlue(rhs.m_rgba)) + <= processedSimilarity; } //--------------------------------------------------------------------- // public -bool kpColor::isValid () const +bool kpColor::isValid() const { return m_rgbaIsValid; } //--------------------------------------------------------------------- // public -int kpColor::red () const +int kpColor::red() const { - if (!m_rgbaIsValid) - { + if (!m_rgbaIsValid) { qCCritical(kpLogImagelib) << "kpColor::red() called with invalid kpColor"; return 0; } - return qRed (m_rgba); + return qRed(m_rgba); } //--------------------------------------------------------------------- // public -int kpColor::green () const +int kpColor::green() const { - if (!m_rgbaIsValid) - { + if (!m_rgbaIsValid) { qCCritical(kpLogImagelib) << "kpColor::green() called with invalid kpColor"; return 0; } - return qGreen (m_rgba); + return qGreen(m_rgba); } //--------------------------------------------------------------------- // public -int kpColor::blue () const +int kpColor::blue() const { - if (!m_rgbaIsValid) - { + if (!m_rgbaIsValid) { qCCritical(kpLogImagelib) << "kpColor::blue() called with invalid kpColor"; return 0; } - return qBlue (m_rgba); + return qBlue(m_rgba); } //--------------------------------------------------------------------- // public -int kpColor::alpha () const +int kpColor::alpha() const { - if (!m_rgbaIsValid) - { + if (!m_rgbaIsValid) { qCCritical(kpLogImagelib) << "kpColor::alpha() called with invalid kpColor"; return 0; } - return qAlpha (m_rgba); + return qAlpha(m_rgba); } //--------------------------------------------------------------------- // public -bool kpColor::isTransparent () const +bool kpColor::isTransparent() const { - return (alpha () == 0); + return alpha() == 0; } //--------------------------------------------------------------------- // public -QRgb kpColor::toQRgb () const +QRgb kpColor::toQRgb() const { - if (!m_rgbaIsValid) - { + if (!m_rgbaIsValid) { qCCritical(kpLogImagelib) << "kpColor::toQRgb() called with invalid kpColor"; return 0; } @@ -296,10 +284,9 @@ //--------------------------------------------------------------------- // public -QColor kpColor::toQColor () const +QColor kpColor::toQColor() const { - if (!m_rgbaIsValid) - { + if (!m_rgbaIsValid) { qCCritical(kpLogImagelib) << "kpColor::toQColor() called with invalid kpColor"; return Qt::black; } diff --git a/imagelib/kpColor_Constants.cpp b/imagelib/kpColor_Constants.cpp --- a/imagelib/kpColor_Constants.cpp +++ b/imagelib/kpColor_Constants.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,24 +24,20 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COLOR 0 - #include "kpColor.h" - -static inline int RoundUp2 (int val) +static inline int RoundUp2(int val) { return val % 2 ? val + 1 : val; } -static inline int Bound0_255 (int val) +static inline int Bound0_255(int val) { - return qBound (0, val, 255); + return qBound(0, val, 255); } - enum { BlendDark = 25, @@ -52,66 +47,61 @@ }; // Adds the 2 given colors together and then multiplies by the given . -static inline kpColor Blend (const kpColor &a, const kpColor &b, - int percent = ::BlendNormal) +static inline kpColor Blend(const kpColor &a, const kpColor &b, int percent = ::BlendNormal) { - return kpColor (::Bound0_255 (::RoundUp2 (a.red () + b.red ()) * percent / 100), - ::Bound0_255 (::RoundUp2 (a.green () + b.green ()) * percent / 100), - ::Bound0_255 (::RoundUp2 (a.blue () + b.blue ()) * percent / 100)); + return kpColor(::Bound0_255(::RoundUp2(a.red() + b.red()) * percent / 100), + ::Bound0_255(::RoundUp2(a.green() + b.green()) * percent / 100), + ::Bound0_255(::RoundUp2(a.blue() + b.blue()) * percent / 100)); } -static inline kpColor Add (const kpColor &a, const kpColor &b) +static inline kpColor Add(const kpColor &a, const kpColor &b) { - return ::Blend (a, b, ::BlendAdd); + return ::Blend(a, b, ::BlendAdd); } - // (intentionally _not_ an HSV darkener) -static inline kpColor Dark (const kpColor &color) +static inline kpColor Dark(const kpColor &color) { - return ::Blend (color, kpColor::Black); + return ::Blend(color, kpColor::Black); } - // public static const int kpColor::Exact = 0; // public static const kpColor kpColor::Invalid; // LOTODO: what's wrong with explicitly specifying () constructor? -const kpColor kpColor::Transparent (0, 0, 0, true/*isTransparent*/); - +const kpColor kpColor::Transparent(0, 0, 0, true /*isTransparent*/); // // Make our own colors in case weird ones like "Qt::cyan" // (turquoise) get changed by Qt. // +const kpColor kpColor::Red(255, 0, 0); +const kpColor kpColor::Green(0, 255, 0); +const kpColor kpColor::Blue(0, 0, 255); +const kpColor kpColor::Black(0, 0, 0); +const kpColor kpColor::White(255, 255, 255); -const kpColor kpColor::Red (255, 0, 0); -const kpColor kpColor::Green (0, 255, 0); -const kpColor kpColor::Blue (0, 0, 255); -const kpColor kpColor::Black (0, 0, 0); -const kpColor kpColor::White (255, 255, 255); - -const kpColor kpColor::Yellow = ::Add (kpColor::Red, kpColor::Green); -const kpColor kpColor::Purple = ::Add (kpColor::Red, kpColor::Blue); -const kpColor kpColor::Aqua = ::Add (kpColor::Green, kpColor::Blue); +const kpColor kpColor::Yellow = ::Add(kpColor::Red, kpColor::Green); +const kpColor kpColor::Purple = ::Add(kpColor::Red, kpColor::Blue); +const kpColor kpColor::Aqua = ::Add(kpColor::Green, kpColor::Blue); -const kpColor kpColor::Gray = ::Blend (kpColor::Black, kpColor::White); -const kpColor kpColor::LightGray = ::Blend (kpColor::Gray, kpColor::White); -const kpColor kpColor::Orange = ::Blend (kpColor::Red, kpColor::Yellow); +const kpColor kpColor::Gray = ::Blend(kpColor::Black, kpColor::White); +const kpColor kpColor::LightGray = ::Blend(kpColor::Gray, kpColor::White); +const kpColor kpColor::Orange = ::Blend(kpColor::Red, kpColor::Yellow); -const kpColor kpColor::Pink = ::Blend (kpColor::Red, kpColor::White); -const kpColor kpColor::LightGreen = ::Blend (kpColor::Green, kpColor::White); -const kpColor kpColor::LightBlue = ::Blend (kpColor::Blue, kpColor::White); -const kpColor kpColor::Tan = ::Blend (kpColor::Yellow, kpColor::White); +const kpColor kpColor::Pink = ::Blend(kpColor::Red, kpColor::White); +const kpColor kpColor::LightGreen = ::Blend(kpColor::Green, kpColor::White); +const kpColor kpColor::LightBlue = ::Blend(kpColor::Blue, kpColor::White); +const kpColor kpColor::Tan = ::Blend(kpColor::Yellow, kpColor::White); -const kpColor kpColor::DarkRed = ::Dark (kpColor::Red); -const kpColor kpColor::DarkOrange = ::Dark (kpColor::Orange); +const kpColor kpColor::DarkRed = ::Dark(kpColor::Red); +const kpColor kpColor::DarkOrange = ::Dark(kpColor::Orange); const kpColor kpColor::Brown = kpColor::DarkOrange; -const kpColor kpColor::DarkYellow = ::Dark (kpColor::Yellow); -const kpColor kpColor::DarkGreen = ::Dark (kpColor::Green); -const kpColor kpColor::DarkAqua = ::Dark (kpColor::Aqua); -const kpColor kpColor::DarkBlue = ::Dark (kpColor::Blue); -const kpColor kpColor::DarkPurple = ::Dark (kpColor::Purple); -const kpColor kpColor::DarkGray = ::Dark (kpColor::Gray); +const kpColor kpColor::DarkYellow = ::Dark(kpColor::Yellow); +const kpColor kpColor::DarkGreen = ::Dark(kpColor::Green); +const kpColor kpColor::DarkAqua = ::Dark(kpColor::Aqua); +const kpColor kpColor::DarkBlue = ::Dark(kpColor::Blue); +const kpColor kpColor::DarkPurple = ::Dark(kpColor::Purple); +const kpColor kpColor::DarkGray = ::Dark(kpColor::Gray); diff --git a/imagelib/kpDocumentMetaInfo.h b/imagelib/kpDocumentMetaInfo.h --- a/imagelib/kpDocumentMetaInfo.h +++ b/imagelib/kpDocumentMetaInfo.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,83 +24,71 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_DOCUMENT_META_INFO_H #define KP_DOCUMENT_META_INFO_H - #include #include #include #include #include "commands/kpCommandSize.h" - class QPoint; - class kpDocumentMetaInfo { public: kpDocumentMetaInfo (); kpDocumentMetaInfo (const kpDocumentMetaInfo &rhs); virtual ~kpDocumentMetaInfo (); - bool operator== (const kpDocumentMetaInfo &rhs) const; - bool operator!= (const kpDocumentMetaInfo &rhs) const; - - kpDocumentMetaInfo &operator= (const kpDocumentMetaInfo &rhs); - + bool operator==(const kpDocumentMetaInfo &rhs) const; + bool operator!=(const kpDocumentMetaInfo &rhs) const; - void printDebug (const QString &prefix) const; + kpDocumentMetaInfo &operator=(const kpDocumentMetaInfo &rhs); + void printDebug(const QString &prefix) const; - kpCommandSize::SizeType size () const; - + kpCommandSize::SizeType size() const; // // Constants (enforced by methods) // static const int MinDotsPerMeter, MaxDotsPerMeter; static const int MinOffset, MaxOffset; - // See QImage documentation // is 0 if the resolution is unspecified. // Else, these methods automatically bound to be between // MinDotsPerMeter ... MaxDotsPerMeter inclusive. - int dotsPerMeterX () const; - void setDotsPerMeterX (int val); + int dotsPerMeterX() const; + void setDotsPerMeterX(int val); // is 0 if the resolution is unspecified. // Else, these methods automatically bound to be between // MinDotsPerMeter ... MaxDotsPerMeter inclusive. - int dotsPerMeterY () const; - void setDotsPerMeterY (int val); - + int dotsPerMeterY() const; + void setDotsPerMeterY(int val); // These methods automatically bound each of X and Y to be between // MinOffset and MaxOffset inclusive. - QPoint offset () const; - void setOffset (const QPoint &point); + QPoint offset() const; + void setOffset(const QPoint &point); - - QMap textMap () const; - QList textKeys () const; + QMap textMap() const; + QList textKeys() const; // (if is empty, it returns an empty string) - QString text (const QString &key) const; + QString text(const QString &key) const; // (if is empty, the operation is ignored) - void setText (const QString &key, const QString &value); - + void setText(const QString &key, const QString &value); private: struct kpDocumentMetaInfoPrivate *d; }; - #endif // KP_DOCUMENT_META_INFO_H diff --git a/imagelib/kpDocumentMetaInfo.cpp b/imagelib/kpDocumentMetaInfo.cpp --- a/imagelib/kpDocumentMetaInfo.cpp +++ b/imagelib/kpDocumentMetaInfo.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpDocumentMetaInfo.h" #include @@ -37,23 +35,22 @@ #include "kpDefs.h" - // // Constants which "ought to be enough for anybody" // LOTODO: Maybe there are some QImage constants somewhere? // // public static // (round up to guarantee at least 1 dot per inch) -const int kpDocumentMetaInfo::MinDotsPerMeter = - int (std::ceil (1/*single dot per inch - a very low DPI*/ * KP_INCHES_PER_METER) + 0.1); +const int kpDocumentMetaInfo::MinDotsPerMeter + = int(std::ceil(1 /*single dot per inch - a very low DPI*/ * KP_INCHES_PER_METER) + 0.1); -const int kpDocumentMetaInfo::MaxDotsPerMeter = - int ((600 * 100)/*a lot of DPI*/ * KP_INCHES_PER_METER); +const int kpDocumentMetaInfo::MaxDotsPerMeter + = int((600 * 100) /*a lot of DPI*/ * KP_INCHES_PER_METER); // public static -const int kpDocumentMetaInfo::MaxOffset = (4000/*big image*/ * 100)/*a very big image*/; +const int kpDocumentMetaInfo::MaxOffset = (4000 /*big image*/ * 100) /*a very big image*/; const int kpDocumentMetaInfo::MinOffset = -kpDocumentMetaInfo::MaxOffset; //--------------------------------------------------------------------- @@ -70,22 +67,22 @@ // public kpDocumentMetaInfo::kpDocumentMetaInfo () - : d (new kpDocumentMetaInfoPrivate ()) + : d(new kpDocumentMetaInfoPrivate()) { d->m_dotsPerMeterX = 0; d->m_dotsPerMeterY = 0; - d->m_offset = QPoint (0, 0); + d->m_offset = QPoint(0, 0); } //--------------------------------------------------------------------- kpDocumentMetaInfo::kpDocumentMetaInfo (const kpDocumentMetaInfo &rhs) - : d (new kpDocumentMetaInfoPrivate ()) + : d(new kpDocumentMetaInfoPrivate()) { - d->m_dotsPerMeterX = rhs.dotsPerMeterX (); - d->m_dotsPerMeterY = rhs.dotsPerMeterY (); - d->m_offset = rhs.offset (); - d->m_textMap = rhs.textMap (); + d->m_dotsPerMeterX = rhs.dotsPerMeterX(); + d->m_dotsPerMeterY = rhs.dotsPerMeterY(); + d->m_offset = rhs.offset(); + d->m_textMap = rhs.textMap(); } //--------------------------------------------------------------------- @@ -99,75 +96,73 @@ //--------------------------------------------------------------------- // public -bool kpDocumentMetaInfo::operator== (const kpDocumentMetaInfo &rhs) const +bool kpDocumentMetaInfo::operator==(const kpDocumentMetaInfo &rhs) const { - return (d->m_dotsPerMeterX == rhs.d->m_dotsPerMeterX && - d->m_dotsPerMeterY == rhs.d->m_dotsPerMeterY && - d->m_offset == rhs.d->m_offset && - d->m_textMap == rhs.d->m_textMap); + return d->m_dotsPerMeterX == rhs.d->m_dotsPerMeterX + && d->m_dotsPerMeterY == rhs.d->m_dotsPerMeterY + && d->m_offset == rhs.d->m_offset + && d->m_textMap == rhs.d->m_textMap; } //--------------------------------------------------------------------- // public -bool kpDocumentMetaInfo::operator!= (const kpDocumentMetaInfo &rhs) const +bool kpDocumentMetaInfo::operator!=(const kpDocumentMetaInfo &rhs) const { return !(*this == rhs); } //--------------------------------------------------------------------- // public -kpDocumentMetaInfo &kpDocumentMetaInfo::operator= (const kpDocumentMetaInfo &rhs) +kpDocumentMetaInfo &kpDocumentMetaInfo::operator=(const kpDocumentMetaInfo &rhs) { if (this == &rhs) { return *this; } - d->m_dotsPerMeterX = rhs.dotsPerMeterX (); - d->m_dotsPerMeterY = rhs.dotsPerMeterY (); - d->m_offset = rhs.offset (); - d->m_textMap = rhs.textMap (); + d->m_dotsPerMeterX = rhs.dotsPerMeterX(); + d->m_dotsPerMeterY = rhs.dotsPerMeterY(); + d->m_offset = rhs.offset(); + d->m_textMap = rhs.textMap(); return *this; } //--------------------------------------------------------------------- // public -void kpDocumentMetaInfo::printDebug (const QString &prefix) const +void kpDocumentMetaInfo::printDebug(const QString &prefix) const { const QString usedPrefix = !prefix.isEmpty() ? QString(prefix + QLatin1String(":")) : QString(); qCDebug(kpLogImagelib) << usedPrefix; - qCDebug(kpLogImagelib) << "dotsPerMeter X=" << dotsPerMeterX () - << " Y=" << dotsPerMeterY () - << " offset=" << offset (); + qCDebug(kpLogImagelib) << "dotsPerMeter X=" << dotsPerMeterX() + << " Y=" << dotsPerMeterY() + << " offset=" << offset(); - QList keyList = textKeys (); - for (QList ::const_iterator it = keyList.constBegin (); - it != keyList.constEnd (); - ++it) - { + QList keyList = textKeys(); + for (QList ::const_iterator it = keyList.constBegin(); + it != keyList.constEnd(); + ++it) { qCDebug(kpLogImagelib) << "key=" << (*it) - << " text=" << text (*it); + << " text=" << text(*it); } qCDebug(kpLogImagelib) << usedPrefix << "ENDS"; } //--------------------------------------------------------------------- // public -kpCommandSize::SizeType kpDocumentMetaInfo::size () const +kpCommandSize::SizeType kpDocumentMetaInfo::size() const { kpCommandSize::SizeType ret = 0; - for (const auto &key : d->m_textMap.keys ()) - { - ret += kpCommandSize::StringSize (key) + - kpCommandSize::StringSize (d->m_textMap [key]); + for (const auto &key : d->m_textMap.keys()) { + ret += kpCommandSize::StringSize(key) + +kpCommandSize::StringSize(d->m_textMap [key]); } // We don't know what the QMap size overhead is so overestimate the size @@ -179,90 +174,88 @@ //--------------------------------------------------------------------- // public -int kpDocumentMetaInfo::dotsPerMeterX () const +int kpDocumentMetaInfo::dotsPerMeterX() const { return d->m_dotsPerMeterX; } //--------------------------------------------------------------------- // public -void kpDocumentMetaInfo::setDotsPerMeterX (int val) +void kpDocumentMetaInfo::setDotsPerMeterX(int val) { // Unspecified resolution? - if (val == 0) - { + if (val == 0) { d->m_dotsPerMeterX = 0; return; } - d->m_dotsPerMeterX = qBound (MinDotsPerMeter, val, MaxDotsPerMeter); + d->m_dotsPerMeterX = qBound(MinDotsPerMeter, val, MaxDotsPerMeter); } //--------------------------------------------------------------------- // public -int kpDocumentMetaInfo::dotsPerMeterY () const +int kpDocumentMetaInfo::dotsPerMeterY() const { return d->m_dotsPerMeterY; } //--------------------------------------------------------------------- // public -void kpDocumentMetaInfo::setDotsPerMeterY (int val) +void kpDocumentMetaInfo::setDotsPerMeterY(int val) { // Unspecified resolution? - if (val == 0) - { + if (val == 0) { d->m_dotsPerMeterY = 0; return; } - d->m_dotsPerMeterY = qBound (MinDotsPerMeter, val, MaxDotsPerMeter); + d->m_dotsPerMeterY = qBound(MinDotsPerMeter, val, MaxDotsPerMeter); } //--------------------------------------------------------------------- // public -QPoint kpDocumentMetaInfo::offset () const +QPoint kpDocumentMetaInfo::offset() const { return d->m_offset; } //--------------------------------------------------------------------- // public -void kpDocumentMetaInfo::setOffset (const QPoint &point) +void kpDocumentMetaInfo::setOffset(const QPoint &point) { - const int x = qBound (MinOffset, point.x (), MaxOffset); - const int y = qBound (MinOffset, point.y (), MaxOffset); + const int x = qBound(MinOffset, point.x(), MaxOffset); + const int y = qBound(MinOffset, point.y(), MaxOffset); - d->m_offset = QPoint (x, y); + d->m_offset = QPoint(x, y); } //--------------------------------------------------------------------- // public -QMap kpDocumentMetaInfo::textMap () const +QMap kpDocumentMetaInfo::textMap() const { return d->m_textMap; } //--------------------------------------------------------------------- // public -QList kpDocumentMetaInfo::textKeys () const +QList kpDocumentMetaInfo::textKeys() const { - return d->m_textMap.keys (); + return d->m_textMap.keys(); } //--------------------------------------------------------------------- // public -QString kpDocumentMetaInfo::text (const QString &key) const +QString kpDocumentMetaInfo::text(const QString &key) const { - if (key.isEmpty ()) { + if (key.isEmpty()) { return {}; } @@ -272,9 +265,9 @@ //--------------------------------------------------------------------- // public -void kpDocumentMetaInfo::setText (const QString &key, const QString &value) +void kpDocumentMetaInfo::setText(const QString &key, const QString &value) { - if (key.isEmpty ()) { + if (key.isEmpty()) { return; } diff --git a/imagelib/kpFloodFill.h b/imagelib/kpFloodFill.h --- a/imagelib/kpFloodFill.h +++ b/imagelib/kpFloodFill.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,56 +24,46 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_FLOOD_FILL_H #define KP_FLOOD_FILL_H - #include "kpImage.h" #include "commands/kpCommandSize.h" - class kpColor; class kpFillLine; - struct kpFloodFillPrivate; class kpFloodFill { public: - kpFloodFill (kpImage *image, int x, int y, - const kpColor &color, - int processedColorSimilarity); + kpFloodFill (kpImage *image, int x, int y, const kpColor &color, int processedColorSimilarity); ~kpFloodFill (); - // // Spits back constructor arguments. // public: - kpColor color () const; - int processedColorSimilarity () const; - + kpColor color() const; + int processedColorSimilarity() const; public: // Used for calculating the size of a command in the command history. - kpCommandSize::SizeType size () const; - + kpCommandSize::SizeType size() const; // // Step 1: Determines the colour that will be changed to color(). // // Very fast. // public: - void prepareColorToChange (); + void prepareColorToChange(); // (may invoke prepareColorToChange()). - kpColor colorToChange (); - + kpColor colorToChange(); // // Step 2: Determines the scanlines / pixels that will be changed to color(). @@ -86,25 +75,24 @@ // private: - kpColor pixelColor (int x, int y, bool *beenHere = nullptr) const; - bool shouldGoTo (int x, int y) const; + kpColor pixelColor(int x, int y, bool *beenHere = nullptr) const; + bool shouldGoTo(int x, int y) const; // Finds the minimum x value at a certain line to be filled. - int findMinX (int y, int x) const; + int findMinX(int y, int x) const; // Finds the maximum x value at a certain line to be filled. - int findMaxX (int y, int x) const; + int findMaxX(int y, int x) const; - void addLine (int y, int x1, int x2); - void findAndAddLines (const kpFillLine &fillLine, int dy); + void addLine(int y, int x1, int x2); + void findAndAddLines(const kpFillLine &fillLine, int dy); public: // (may invoke Step 1's prepareColorToChange()) - void prepare (); + void prepare(); // (may invoke prepare()) - QRect boundingRect (); - + QRect boundingRect(); // // Step 3: Draws the lines identified in Step 2 in color(). @@ -117,12 +105,10 @@ public: // (may invoke Step 2's prepare()) - void fill (); - + void fill(); private: - kpFloodFillPrivate * const d; + kpFloodFillPrivate *const d; }; - #endif // KP_FLOOD_FILL_H diff --git a/imagelib/kpFloodFill.cpp b/imagelib/kpFloodFill.cpp --- a/imagelib/kpFloodFill.cpp +++ b/imagelib/kpFloodFill.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_FLOOD_FILL 0 - #include "kpFloodFill.h" #include @@ -51,23 +48,25 @@ { public: kpFillLine (int y = -1, int x1 = -1, int x2 = -1) - : m_y (y), m_x1 (x1), m_x2 (x2) + : m_y(y) + , m_x1(x1) + , m_x2(x2) { } - static kpCommandSize::SizeType size () + static kpCommandSize::SizeType size() { - return sizeof (kpFillLine); + return sizeof(kpFillLine); } int m_y, m_x1, m_x2; }; //--------------------------------------------------------------------- -static kpCommandSize::SizeType FillLinesListSize (const QLinkedList &fillLines) +static kpCommandSize::SizeType FillLinesListSize(const QLinkedList &fillLines) { - return (fillLines.size () * kpFillLine::size ()); + return fillLines.size() * kpFillLine::size(); } //--------------------------------------------------------------------- @@ -83,14 +82,12 @@ kpColor color; int processedColorSimilarity{}; - // // Set by Step 1. // kpColor colorToChange; - // // Set by Step 2. // @@ -105,9 +102,9 @@ //--------------------------------------------------------------------- -kpFloodFill::kpFloodFill (kpImage *image, int x, int y, - const kpColor &color, int processedColorSimilarity) - : d (new kpFloodFillPrivate ()) +kpFloodFill::kpFloodFill (kpImage *image, int x, int y, const kpColor &color, + int processedColorSimilarity) + : d(new kpFloodFillPrivate()) { d->imagePtr = image; d->x = x; @@ -128,57 +125,56 @@ //--------------------------------------------------------------------- // public -kpColor kpFloodFill::color () const +kpColor kpFloodFill::color() const { return d->color; } //--------------------------------------------------------------------- // public -int kpFloodFill::processedColorSimilarity () const +int kpFloodFill::processedColorSimilarity() const { return d->processedColorSimilarity; } //--------------------------------------------------------------------- // public -kpCommandSize::SizeType kpFloodFill::size () const +kpCommandSize::SizeType kpFloodFill::size() const { kpCommandSize::SizeType fillLinesCacheSize = 0; - for (const auto &linesList : d->fillLinesCache) - { - fillLinesCacheSize += ::FillLinesListSize (linesList); + for (const auto &linesList : d->fillLinesCache) { + fillLinesCacheSize += ::FillLinesListSize(linesList); } - return ::FillLinesListSize(d->fillLines) + - kpCommandSize::QImageSize(d->imagePtr) + - fillLinesCacheSize; + return ::FillLinesListSize(d->fillLines) + +kpCommandSize::QImageSize(d->imagePtr) + +fillLinesCacheSize; } //--------------------------------------------------------------------- // public -void kpFloodFill::prepareColorToChange () +void kpFloodFill::prepareColorToChange() { - if (d->colorToChange.isValid ()) { + if (d->colorToChange.isValid()) { return; } #if DEBUG_KP_FLOOD_FILL && 1 qCDebug(kpLogImagelib) << "kpFloodFill::prepareColorToChange()"; #endif - d->colorToChange = kpPixmapFX::getColorAtPixel (*d->imagePtr, QPoint (d->x, d->y)); + d->colorToChange = kpPixmapFX::getColorAtPixel(*d->imagePtr, QPoint(d->x, d->y)); } //--------------------------------------------------------------------- // public -kpColor kpFloodFill::colorToChange () +kpColor kpFloodFill::colorToChange() { - prepareColorToChange (); + prepareColorToChange(); return d->colorToChange; } @@ -188,116 +184,108 @@ // Derived from the zSprite2 Graphics Engine // private -kpColor kpFloodFill::pixelColor (int x, int y, bool *beenHere) const +kpColor kpFloodFill::pixelColor(int x, int y, bool *beenHere) const { if (beenHere) { *beenHere = false; } - Q_ASSERT (y >= 0 && y < static_cast (d->fillLinesCache.count ())); + Q_ASSERT(y >= 0 && y < static_cast(d->fillLinesCache.count())); - for (const auto &line : d->fillLinesCache [y]) - { - if (x >= line.m_x1 && x <= line.m_x2) - { + for (const auto &line : d->fillLinesCache [y]) { + if (x >= line.m_x1 && x <= line.m_x2) { if (beenHere) { *beenHere = true; } return d->color; } } - return kpPixmapFX::getColorAtPixel (*(d->imagePtr), QPoint (x, y)); + return kpPixmapFX::getColorAtPixel(*(d->imagePtr), QPoint(x, y)); } //--------------------------------------------------------------------- // private -bool kpFloodFill::shouldGoTo (int x, int y) const +bool kpFloodFill::shouldGoTo(int x, int y) const { bool beenThere; - const kpColor col = pixelColor (x, y, &beenThere); + const kpColor col = pixelColor(x, y, &beenThere); - return (!beenThere && col.isSimilarTo (d->colorToChange, d->processedColorSimilarity)); + return !beenThere && col.isSimilarTo(d->colorToChange, d->processedColorSimilarity); } //--------------------------------------------------------------------- // private -int kpFloodFill::findMinX (int y, int x) const +int kpFloodFill::findMinX(int y, int x) const { - for (;;) - { + for (;;) { if (x < 0) { return 0; } - if (shouldGoTo (x, y)) { + if (shouldGoTo(x, y)) { x--; - } - else { + } else { return x + 1; } } } //--------------------------------------------------------------------- // private -int kpFloodFill::findMaxX (int y, int x) const +int kpFloodFill::findMaxX(int y, int x) const { - for (;;) - { - if (x > d->imagePtr->width () - 1) { - return d->imagePtr->width () - 1; + for (;;) { + if (x > d->imagePtr->width() - 1) { + return d->imagePtr->width() - 1; } - if (shouldGoTo (x, y)) { + if (shouldGoTo(x, y)) { x++; - } - else { + } else { return x - 1; } } } //--------------------------------------------------------------------- // private -void kpFloodFill::addLine (int y, int x1, int x2) +void kpFloodFill::addLine(int y, int x1, int x2) { #if DEBUG_KP_FLOOD_FILL && 0 qCDebug(kpLogImagelib) << "kpFillCommand::fillAddLine (" - << y << "," << x1 << "," << x2 << ")" << endl; + << y << "," << x1 << "," << x2 << ")" << endl; #endif - d->fillLines.append (kpFillLine (y, x1, x2)); - d->fillLinesCache [y].append ( - kpFillLine (y/*OPT: can determine from array index*/, x1, x2)); - d->boundingRect = d->boundingRect.united (QRect (QPoint (x1, y), QPoint (x2, y))); + d->fillLines.append(kpFillLine(y, x1, x2)); + d->fillLinesCache [y].append( + kpFillLine(y /*OPT: can determine from array index*/, x1, x2)); + d->boundingRect = d->boundingRect.united(QRect(QPoint(x1, y), QPoint(x2, y))); } //--------------------------------------------------------------------- // private -void kpFloodFill::findAndAddLines (const kpFillLine &fillLine, int dy) +void kpFloodFill::findAndAddLines(const kpFillLine &fillLine, int dy) { // out of bounds? - if (fillLine.m_y + dy < 0 || fillLine.m_y + dy >= d->imagePtr->height ()) { + if (fillLine.m_y + dy < 0 || fillLine.m_y + dy >= d->imagePtr->height()) { return; } - for (int xnow = fillLine.m_x1; xnow <= fillLine.m_x2; xnow++) - { + for (int xnow = fillLine.m_x1; xnow <= fillLine.m_x2; xnow++) { // At current position, right colour? - if (shouldGoTo (xnow, fillLine.m_y + dy)) - { + if (shouldGoTo(xnow, fillLine.m_y + dy)) { // Find minimum and maximum x values - int minxnow = findMinX (fillLine.m_y + dy, xnow); - int maxxnow = findMaxX (fillLine.m_y + dy, xnow); + int minxnow = findMinX(fillLine.m_y + dy, xnow); + int maxxnow = findMaxX(fillLine.m_y + dy, xnow); // Draw line - addLine (fillLine.m_y + dy, minxnow, maxxnow); + addLine(fillLine.m_y + dy, minxnow, maxxnow); // Move x pointer xnow = maxxnow; @@ -308,7 +296,7 @@ //--------------------------------------------------------------------- // public -void kpFloodFill::prepare () +void kpFloodFill::prepare() { if (d->prepared) { return; @@ -318,18 +306,16 @@ qCDebug(kpLogImagelib) << "kpFloodFill::prepare()"; #endif - prepareColorToChange (); - - d->boundingRect = QRect (); + prepareColorToChange(); + d->boundingRect = QRect(); #if DEBUG_KP_FLOOD_FILL && 1 qCDebug(kpLogImagelib) << "\tperforming NOP check"; #endif // get the color we need to replace - if (d->processedColorSimilarity == 0 && d->color == d->colorToChange) - { + if (d->processedColorSimilarity == 0 && d->color == d->colorToChange) { // need to do absolutely nothing (this is a significant optimization // for people who randomly click a lot over already-filled areas) d->prepared = true; // sync with all "return true"'s @@ -341,26 +327,25 @@ #endif // ready cache - for (int i = 0; i < d->imagePtr->height (); i++) { - d->fillLinesCache.append (QLinkedList ()); + for (int i = 0; i < d->imagePtr->height(); i++) { + d->fillLinesCache.append(QLinkedList ()); } #if DEBUG_KP_FLOOD_FILL && 1 qCDebug(kpLogImagelib) << "\tcreating fill lines"; #endif // draw initial line - addLine (d->y, findMinX (d->y, d->x), findMaxX (d->y, d->x)); + addLine(d->y, findMinX(d->y, d->x), findMaxX(d->y, d->x)); - for (QLinkedList ::ConstIterator it = d->fillLines.begin (); - it != d->fillLines.end (); - ++it) - { + for (QLinkedList ::ConstIterator it = d->fillLines.begin(); + it != d->fillLines.end(); + ++it) { #if DEBUG_KP_FLOOD_FILL && 0 qCDebug(kpLogImagelib) << "Expanding from y=" << (*it).m_y - << " x1=" << (*it).m_x1 - << " x2=" << (*it).m_x2 - << endl; + << " x1=" << (*it).m_x1 + << " x2=" << (*it).m_x2 + << endl; #endif // @@ -372,26 +357,26 @@ // "foreach" for this loop as that makes a copy of the linked // list at the start and won't see new lines. // - findAndAddLines (*it, -1); - findAndAddLines (*it, +1); + findAndAddLines(*it, -1); + findAndAddLines(*it, +1); } #if DEBUG_KP_FLOOD_FILL && 1 qCDebug(kpLogImagelib) << "\tfinalising memory usage"; #endif // finalize memory usage - d->fillLinesCache.clear (); + d->fillLinesCache.clear(); d->prepared = true; // sync with all "return true"'s } //--------------------------------------------------------------------- // public -QRect kpFloodFill::boundingRect () +QRect kpFloodFill::boundingRect() { - prepare (); + prepare(); return d->boundingRect; } @@ -408,20 +393,18 @@ // by definition, flood fill with a fully transparent color erases the pixels // and sets them to be fully transparent - if ( d->color.isTransparent() ) { - painter.setCompositionMode(QPainter::CompositionMode_Clear); + if (d->color.isTransparent()) { + painter.setCompositionMode(QPainter::CompositionMode_Clear); } painter.setPen(d->color.toQColor()); - for (const auto &l : d->fillLines) - { - if ( l.m_x1 == l.m_x2 ) { - painter.drawPoint(l.m_x1, l.m_y); - } - else { - painter.drawLine(l.m_x1, l.m_y, l.m_x2, l.m_y); - } + for (const auto &l : d->fillLines) { + if (l.m_x1 == l.m_x2) { + painter.drawPoint(l.m_x1, l.m_y); + } else { + painter.drawLine(l.m_x1, l.m_y, l.m_x2, l.m_y); + } } QApplication::restoreOverrideCursor(); diff --git a/imagelib/kpImage.h b/imagelib/kpImage.h --- a/imagelib/kpImage.h +++ b/imagelib/kpImage.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_IMAGE_H #define KP_IMAGE_H - #include typedef QImage kpImage; - #endif // KP_IMAGE_H diff --git a/imagelib/kpPainter.h b/imagelib/kpPainter.h --- a/imagelib/kpPainter.h +++ b/imagelib/kpPainter.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,17 +24,12 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_PAINTER_H #define KP_PAINTER_H - #include "kpColor.h" #include "kpImage.h" - - - // // Stateless painter with sane semantics that works on kpImage's i.e. it // works on document - not view - data. If you find that you need state, @@ -56,16 +50,16 @@ public: // helper to make a correct QRect out of 2 QPoints regardless of their relative position // to each other - static QRect normalizedRect(const QPoint& p1, const QPoint& p2) + static QRect normalizedRect(const QPoint &p1, const QPoint &p2) { - return QRect(qMin(p1.x(), p2.x()), qMin(p1.y(), p2.y()), - qAbs(p2.x() - p1.x()) + 1, qAbs(p2.y() - p1.y()) + 1); + return QRect(qMin(p1.x(), p2.x()), qMin(p1.y(), p2.y()), + qAbs(p2.x() - p1.x()) + 1, qAbs(p2.y() - p1.y()) + 1); } // Returns whether the given points are cardinally adjacent (i.e. one point // is exactly 1 pixel north, east, south or west of the other). Equal // points are not cardinally adjacent. - static bool pointsAreCardinallyAdjacent (const QPoint &p, const QPoint &q); + static bool pointsAreCardinallyAdjacent(const QPoint &p, const QPoint &q); // Returns a list of points representing a straight line from // to inclusive, using Bresenham's line algorithm. Each point @@ -92,14 +86,11 @@ // a point at 'c'. // // ASSUMPTION: is between 0.0 and 1.0 inclusive. - static QList interpolatePoints (const QPoint &startPoint, - const QPoint &endPoint, - bool cardinalAdjacency = false, - double probability = 1.0); + static QList interpolatePoints(const QPoint &startPoint, const QPoint &endPoint, + bool cardinalAdjacency = false, + double probability = 1.0); - static void fillRect (kpImage *image, - int x, int y, int width, int height, - const kpColor &color); + static void fillRect(kpImage *image, int x, int y, int width, int height, const kpColor &color); // Replaces all pixels of on the line // from (x1,y1) to (x2,y2) of , with a pen of with @@ -110,28 +101,20 @@ // those corners. // // Returns the dirty rectangle. - static QRect washLine (kpImage *image, - int x1, int y1, int x2, int y2, - const kpColor &color, int penWidth, int penHeight, - const kpColor &colorToReplace, - int processedColorSimilarity); + static QRect washLine(kpImage *image, int x1, int y1, int x2, int y2, const kpColor &color, + int penWidth, int penHeight, const kpColor &colorToReplace, + int processedColorSimilarity); - static QRect washRect (kpImage *image, - int x, int y, int width, int height, - const kpColor &color, - const kpColor &colorToReplace, - int processedColorSimilarity); + static QRect washRect(kpImage *image, int x, int y, int width, int height, const kpColor &color, + const kpColor &colorToReplace, int processedColorSimilarity); // For each point in , sprays a random pattern of 10 dots of , // each within a circle of diameter , onto . // // ASSUMPTION: spraycanSize > 0. // TODO: I think this diameter is 1 or 2 off. - static void sprayPoints (kpImage *image, - const QList &points, - const kpColor &color, - int spraycanSize); + static void sprayPoints(kpImage *image, const QList &points, const kpColor &color, + int spraycanSize); }; - #endif // KP_PAINTER_H diff --git a/imagelib/kpPainter.cpp b/imagelib/kpPainter.cpp --- a/imagelib/kpPainter.cpp +++ b/imagelib/kpPainter.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_PAINTER 0 - #include "kpPainter.h" #include "kpImage.h" @@ -47,59 +44,56 @@ //--------------------------------------------------------------------- // public static -bool kpPainter::pointsAreCardinallyAdjacent (const QPoint &p, const QPoint &q) +bool kpPainter::pointsAreCardinallyAdjacent(const QPoint &p, const QPoint &q) { - int dx = qAbs (p.x () - q.x ()); - int dy = qAbs (p.y () - q.y ()); + int dx = qAbs(p.x() - q.x()); + int dy = qAbs(p.y() - q.y()); - return (dx + dy == 1); + return dx + dy == 1; } //--------------------------------------------------------------------- // Returns a random integer from 0 to 999 inclusive. -static int RandomNumberFrom0to999 () +static int RandomNumberFrom0to999() { - return (KRandom::random () % 1000); + return KRandom::random() % 1000; } //--------------------------------------------------------------------- // public static -QList kpPainter::interpolatePoints (const QPoint &startPoint, - const QPoint &endPoint, - bool cardinalAdjacency, - double probability) +QList kpPainter::interpolatePoints(const QPoint &startPoint, const QPoint &endPoint, + bool cardinalAdjacency, double probability) { #if DEBUG_KP_PAINTER qCDebug(kpLogImagelib) << "CALL(startPoint=" << startPoint - << ",endPoint=" << endPoint << ")"; + << ",endPoint=" << endPoint << ")"; #endif QList ret; - Q_ASSERT (probability >= 0.0 && probability <= 1.0); - const int probabilityTimes1000 = qRound (probability * 1000); -#define SHOULD_DRAW() (probabilityTimes1000 == 1000/*avoid ::RandomNumberFrom0to999() call*/ || \ - ::RandomNumberFrom0to999 () < probabilityTimes1000) - + Q_ASSERT(probability >= 0.0 && probability <= 1.0); + const int probabilityTimes1000 = qRound(probability * 1000); +#define SHOULD_DRAW() (probabilityTimes1000 == 1000/*avoid ::RandomNumberFrom0to999() call*/ \ + || ::RandomNumberFrom0to999() < probabilityTimes1000) // Derived from the zSprite2 Graphics Engine. // "MODIFIED" comment shows deviation from zSprite2 and Bresenham's line // algorithm. - const int x1 = startPoint.x (), - y1 = startPoint.y (), - x2 = endPoint.x (), - y2 = endPoint.y (); + const int x1 = startPoint.x(), + y1 = startPoint.y(), + x2 = endPoint.x(), + y2 = endPoint.y(); // Difference of x and y values const int dx = x2 - x1; const int dy = y2 - y1; // Absolute values of differences - const int ix = qAbs (dx); - const int iy = qAbs (dy); + const int ix = qAbs(dx); + const int iy = qAbs(dy); // Larger of the x and y differences const int inc = ix > iy ? ix : iy; @@ -111,63 +105,55 @@ int x = 0; int y = 0; - if (SHOULD_DRAW ()) { - ret.append (QPoint (plotx, ploty)); + if (SHOULD_DRAW()) { + ret.append(QPoint(plotx, ploty)); } - - for (int i = 0; i <= inc; i++) - { + for (int i = 0; i <= inc; i++) { // oldplotx is equally as valid but would look different // (but nobody will notice which one it is) const int oldploty = ploty; int plot = 0; x += ix; y += iy; - if (x > inc) - { + if (x > inc) { plot++; x -= inc; if (dx < 0) { plotx--; - } - else { + } else { plotx++; } } - if (y > inc) - { + if (y > inc) { plot++; y -= inc; if (dy < 0) { ploty--; - } - else { + } else { ploty++; } } - if (plot) - { - if (cardinalAdjacency && plot == 2) - { + if (plot) { + if (cardinalAdjacency && plot == 2) { // MODIFIED: Every point is // horizontally or vertically adjacent to another point (if there // is more than 1 point, of course). This is in contrast to the // ordinary line algorithm which can create diagonal adjacencies. - if (SHOULD_DRAW ()) { - ret.append (QPoint (plotx, oldploty)); + if (SHOULD_DRAW()) { + ret.append(QPoint(plotx, oldploty)); } } - if (SHOULD_DRAW ()) { - ret.append (QPoint (plotx, ploty)); + if (SHOULD_DRAW()) { + ret.append(QPoint(plotx, ploty)); } } } @@ -180,100 +166,92 @@ //--------------------------------------------------------------------- // public static -void kpPainter::fillRect (kpImage *image, - int x, int y, int width, int height, - const kpColor &color) +void kpPainter::fillRect(kpImage *image, int x, int y, int width, int height, const kpColor &color) { - kpPixmapFX::fillRect (image, x, y, width, height, color); + kpPixmapFX::fillRect(image, x, y, width, height, color); } //--------------------------------------------------------------------- - // are operating on the original image // (the original image is not passed to this function). // // = subset of the original image containing all the pixels in // // = the rectangle, relative to the painters, whose pixels we // want to change -static bool ReadableImageWashRect (QPainter *rgbPainter, - const QImage &image, - const kpColor &colorToReplace, - const QRect &imageRect, const QRect &drawRect, - int processedColorSimilarity) +static bool ReadableImageWashRect(QPainter *rgbPainter, const QImage &image, + const kpColor &colorToReplace, const QRect &imageRect, + const QRect &drawRect, int processedColorSimilarity) { bool didSomething = false; #if DEBUG_KP_PAINTER && 0 qCDebug(kpLogImagelib) << "kppixmapfx.cpp:WashRect(imageRect=" << imageRect - << ",drawRect=" << drawRect - << ")" << endl; + << ",drawRect=" << drawRect + << ")" << endl; #endif // If you're going to pass painter pointers, those painters had better be // active (i.e. QPainter::begin() has been called). - Q_ASSERT (!rgbPainter || rgbPainter->isActive ()); + Q_ASSERT(!rgbPainter || rgbPainter->isActive()); // make use of scanline coherence #define FLUSH_LINE() \ -{ \ - if (rgbPainter) { \ - if (startDrawX == x - 1) \ - rgbPainter->drawPoint (startDrawX + imageRect.x (), \ - y + imageRect.y ()); \ - else \ - rgbPainter->drawLine (startDrawX + imageRect.x (), \ - y + imageRect.y (), \ - x - 1 + imageRect.x (), \ - y + imageRect.y ()); \ - } \ - didSomething = true; \ - startDrawX = -1; \ -} + { \ + if (rgbPainter) { \ + if (startDrawX == x - 1) { \ + rgbPainter->drawPoint(startDrawX + imageRect.x(), \ + y + imageRect.y());} \ + else { \ + rgbPainter->drawLine(startDrawX + imageRect.x(), \ + y + imageRect.y(), \ + x - 1 + imageRect.x(), \ + y + imageRect.y());} \ + } \ + didSomething = true; \ + startDrawX = -1; \ + } - const int maxY = drawRect.bottom () - imageRect.top (); + const int maxY = drawRect.bottom() - imageRect.top(); - const int minX = drawRect.left () - imageRect.left (); - const int maxX = drawRect.right () - imageRect.left (); + const int minX = drawRect.left() - imageRect.left(); + const int maxX = drawRect.right() - imageRect.left(); - for (int y = drawRect.top () - imageRect.top (); + for (int y = drawRect.top() - imageRect.top(); y <= maxY; - y++) - { + y++) { int startDrawX = -1; int x; // for FLUSH_LINE() - for (x = minX; x <= maxX; x++) - { + for (x = minX; x <= maxX; x++) { #if DEBUG_KP_PAINTER && 0 - fprintf (stderr, "y=%i x=%i colorAtPixel=%08X colorToReplace=%08X ... ", - y, x, - kpPixmapFX::getColorAtPixel (image, QPoint (x, y)).toQRgb (), - colorToReplace.toQRgb ()); + fprintf(stderr, "y=%i x=%i colorAtPixel=%08X colorToReplace=%08X ... ", + y, x, + kpPixmapFX::getColorAtPixel(image, QPoint(x, y)).toQRgb(), + colorToReplace.toQRgb()); #endif - if (kpPixmapFX::getColorAtPixel (image, QPoint (x, y)).isSimilarTo (colorToReplace, processedColorSimilarity)) + if (kpPixmapFX::getColorAtPixel(image, QPoint(x, y)).isSimilarTo(colorToReplace, + processedColorSimilarity)) { #if DEBUG_KP_PAINTER && 0 - fprintf (stderr, "similar\n"); + fprintf(stderr, "similar\n"); #endif if (startDrawX < 0) { startDrawX = x; } - } - else - { + } else { #if DEBUG_KP_PAINTER && 0 - fprintf (stderr, "different\n"); + fprintf(stderr, "different\n"); #endif if (startDrawX >= 0) { - FLUSH_LINE (); + FLUSH_LINE(); } } } if (startDrawX >= 0) { - FLUSH_LINE (); + FLUSH_LINE(); } } @@ -298,222 +276,203 @@ //--------------------------------------------------------------------- -static QRect Wash (kpImage *image, - const QPoint &startPoint, const QPoint &endPoint, - const kpColor &color, int penWidth, int penHeight, - const kpColor &colorToReplace, - int processedColorSimilarity, - QRect (*drawFunc) (QPainter * /*rgbPainter*/, void * /*data*/)) +static QRect Wash(kpImage *image, const QPoint &startPoint, const QPoint &endPoint, + const kpColor &color, int penWidth, int penHeight, const kpColor &colorToReplace, + int processedColorSimilarity, QRect (*drawFunc)(QPainter * /*rgbPainter*/, + void * /*data*/)) { WashPack pack; - pack.startPoint = startPoint; pack.endPoint = endPoint; + pack.startPoint = startPoint; + pack.endPoint = endPoint; pack.color = color; - pack.penWidth = penWidth; pack.penHeight = penHeight; + pack.penWidth = penWidth; + pack.penHeight = penHeight; pack.colorToReplace = colorToReplace; pack.processedColorSimilarity = processedColorSimilarity; - // Get the rectangle that bounds the changes and the pixmap for that // rectangle. const QRect normalizedRect = kpPainter::normalizedRect(pack.startPoint, pack.endPoint); - pack.readableImageRect = kpTool::neededRect (normalizedRect, - qMax (pack.penWidth, pack.penHeight)); + pack.readableImageRect = kpTool::neededRect(normalizedRect, + qMax(pack.penWidth, pack.penHeight)); #if DEBUG_KP_PAINTER qCDebug(kpLogImagelib) << "kppainter.cpp:Wash() startPoint=" << startPoint - << " endPoint=" << endPoint - << " --> normalizedRect=" << normalizedRect - << " readableImageRect=" << pack.readableImageRect - << endl; + << " endPoint=" << endPoint + << " --> normalizedRect=" << normalizedRect + << " readableImageRect=" << pack.readableImageRect + << endl; #endif - pack.readableImage = kpPixmapFX::getPixmapAt (*image, pack.readableImageRect); + pack.readableImage = kpPixmapFX::getPixmapAt(*image, pack.readableImageRect); QPainter painter(image); return (*drawFunc)(&painter, &pack); } //--------------------------------------------------------------------- -void WashHelperSetup (QPainter *rgbPainter, const WashPack *pack) +void WashHelperSetup(QPainter *rgbPainter, const WashPack *pack) { // Set the drawing colors for the painters. if (rgbPainter) { - rgbPainter->setPen (pack->color.toQColor()); + rgbPainter->setPen(pack->color.toQColor()); } } //--------------------------------------------------------------------- -static QRect WashLineHelper (QPainter *rgbPainter, void *data) +static QRect WashLineHelper(QPainter *rgbPainter, void *data) { #if DEBUG_KP_PAINTER && 0 - qCDebug(kpLogImagelib) << "Washing pixmap (w=" << rect.width () - << ",h=" << rect.height () << ")" << endl; + qCDebug(kpLogImagelib) << "Washing pixmap (w=" << rect.width() + << ",h=" << rect.height() << ")" << endl; QTime timer; int convAndWashTime; #endif - auto *pack = static_cast (data); + auto *pack = static_cast (data); // Setup painters. - ::WashHelperSetup (rgbPainter, pack); - + ::WashHelperSetup(rgbPainter, pack); bool didSomething = false; - QList points = kpPainter::interpolatePoints (pack->startPoint, pack->endPoint); - for (QList ::const_iterator pit = points.constBegin (); - pit != points.constEnd (); - ++pit) - { + QList points = kpPainter::interpolatePoints(pack->startPoint, pack->endPoint); + for (QList ::const_iterator pit = points.constBegin(); + pit != points.constEnd(); + ++pit) { // OPT: This may be reading and possibly writing pixels that were // visited on a previous iteration, since the pen is usually // bigger than 1 pixel. Maybe we could use QRegion to determine // all the non-intersecting regions and only wash each region once. // // Profiling needs to be done as QRegion is known to be a CPU hog. - if (::ReadableImageWashRect (rgbPainter, - pack->readableImage, - pack->colorToReplace, - pack->readableImageRect, - kpToolFlowBase::hotRectForMousePointAndBrushWidthHeight ( - *pit, pack->penWidth, pack->penHeight), - pack->processedColorSimilarity)) - { + if (::ReadableImageWashRect(rgbPainter, + pack->readableImage, + pack->colorToReplace, + pack->readableImageRect, + kpToolFlowBase::hotRectForMousePointAndBrushWidthHeight( + *pit, pack->penWidth, pack->penHeight), + pack->processedColorSimilarity)) { didSomething = true; } } - #if DEBUG_KP_PAINTER && 0 - int ms = timer.restart (); + int ms = timer.restart(); qCDebug(kpLogImagelib) << "\ttried to wash: " << ms << "ms" - << " (" << (ms ? (rect.width () * rect.height () / ms) : -1234) - << " pixels/ms)" - << endl; + << " (" << (ms ? (rect.width() * rect.height() / ms) : -1234) + << " pixels/ms)" + << endl; convAndWashTime += ms; #endif - // TODO: Rectangle may be too big. Use QRect::united() incrementally? // Efficiency? - return didSomething ? pack->readableImageRect : QRect (); + return didSomething ? pack->readableImageRect : QRect(); } //--------------------------------------------------------------------- // public static -QRect kpPainter::washLine (kpImage *image, - int x1, int y1, int x2, int y2, - const kpColor &color, int penWidth, int penHeight, - const kpColor &colorToReplace, - int processedColorSimilarity) +QRect kpPainter::washLine(kpImage *image, int x1, int y1, int x2, int y2, const kpColor &color, + int penWidth, int penHeight, const kpColor &colorToReplace, + int processedColorSimilarity) { - return ::Wash (image, - QPoint (x1, y1), QPoint (x2, y2), - color, penWidth, penHeight, - colorToReplace, - processedColorSimilarity, - &::WashLineHelper); + return ::Wash(image, + QPoint(x1, y1), QPoint(x2, y2), + color, penWidth, penHeight, + colorToReplace, + processedColorSimilarity, + &::WashLineHelper); } //--------------------------------------------------------------------- -static QRect WashRectHelper (QPainter *rgbPainter, void *data) +static QRect WashRectHelper(QPainter *rgbPainter, void *data) { - auto *pack = static_cast (data); + auto *pack = static_cast (data); #if DEBUG_KP_PAINTER && 0 - qCDebug(kpLogImagelib) << "Washing pixmap (w=" << rect.width () - << ",h=" << rect.height () << ")" << endl; + qCDebug(kpLogImagelib) << "Washing pixmap (w=" << rect.width() + << ",h=" << rect.height() << ")" << endl; QTime timer; int convAndWashTime; #endif // Setup painters. - ::WashHelperSetup (rgbPainter, pack); - + ::WashHelperSetup(rgbPainter, pack); - const QRect drawRect (pack->startPoint, pack->endPoint); + const QRect drawRect(pack->startPoint, pack->endPoint); bool didSomething = false; - if (::ReadableImageWashRect (rgbPainter, - pack->readableImage, - pack->colorToReplace, - pack->readableImageRect, - drawRect, - pack->processedColorSimilarity)) - { + if (::ReadableImageWashRect(rgbPainter, + pack->readableImage, + pack->colorToReplace, + pack->readableImageRect, + drawRect, + pack->processedColorSimilarity)) { didSomething = true; } - #if DEBUG_KP_PAINTER && 0 - int ms = timer.restart (); + int ms = timer.restart(); qCDebug(kpLogImagelib) << "\ttried to wash: " << ms << "ms" - << " (" << (ms ? (rect.width () * rect.height () / ms) : -1234) - << " pixels/ms)" - << endl; + << " (" << (ms ? (rect.width() * rect.height() / ms) : -1234) + << " pixels/ms)" + << endl; convAndWashTime += ms; #endif - - return didSomething ? drawRect : QRect (); + return didSomething ? drawRect : QRect(); } //--------------------------------------------------------------------- // public static -QRect kpPainter::washRect (kpImage *image, - int x, int y, int width, int height, - const kpColor &color, - const kpColor &colorToReplace, - int processedColorSimilarity) +QRect kpPainter::washRect(kpImage *image, int x, int y, int width, int height, const kpColor &color, + const kpColor &colorToReplace, int processedColorSimilarity) { - return ::Wash (image, - QPoint (x, y), QPoint (x + width - 1, y + height - 1), - color, 1/*pen width*/, 1/*pen height*/, - colorToReplace, - processedColorSimilarity, - &::WashRectHelper); + return ::Wash(image, + QPoint(x, y), QPoint(x + width - 1, y + height - 1), + color, 1 /*pen width*/, 1 /*pen height*/, + colorToReplace, + processedColorSimilarity, + &::WashRectHelper); } //--------------------------------------------------------------------- // public static -void kpPainter::sprayPoints (kpImage *image, - const QList &points, - const kpColor &color, - int spraycanSize) +void kpPainter::sprayPoints(kpImage *image, const QList &points, const kpColor &color, + int spraycanSize) { #if DEBUG_KP_PAINTER qCDebug(kpLogImagelib) << "kpPainter::sprayPoints()"; #endif - Q_ASSERT (spraycanSize > 0); + Q_ASSERT(spraycanSize > 0); QPainter painter(image); const int radius = spraycanSize / 2; // Set the drawing colors for the painters. painter.setPen(color.toQColor()); - for (const auto &p : points) - { - for (int i = 0; i < 10; i++) - { - const int dx = (KRandom::random () % spraycanSize) - radius; - const int dy = (KRandom::random () % spraycanSize) - radius; + for (const auto &p : points) { + for (int i = 0; i < 10; i++) { + const int dx = (KRandom::random() % spraycanSize) - radius; + const int dy = (KRandom::random() % spraycanSize) - radius; // Make it look circular. // TODO: Can be done better by doing a random vector angle & length // but would sin and cos be too slow? if ((dx * dx) + (dy * dy) > (radius * radius)) { continue; } - const QPoint p2 (p.x () + dx, p.y () + dy); + const QPoint p2(p.x() + dx, p.y() + dy); painter.drawPoint(p2); } diff --git a/imagelib/transforms/kpTransformAutoCrop.h b/imagelib/transforms/kpTransformAutoCrop.h --- a/imagelib/transforms/kpTransformAutoCrop.h +++ b/imagelib/transforms/kpTransformAutoCrop.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,31 +24,26 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TRANSFORM_AUTO_CROP_H #define KP_TRANSFORM_AUTO_CROP_H - #include "commands/kpNamedCommand.h" - class QRect; //class kpImage; class kpMainWindow; class kpTransformAutoCropBorder; - // REFACTOR: This should be moved into /commands/ class kpTransformAutoCropCommand : public kpNamedCommand { public: - kpTransformAutoCropCommand (bool actOnSelection, - const kpTransformAutoCropBorder &leftBorder, - const kpTransformAutoCropBorder &rightBorder, - const kpTransformAutoCropBorder &topBorder, - const kpTransformAutoCropBorder &botBorder, - kpCommandEnvironment *environ); + kpTransformAutoCropCommand (bool actOnSelection, const kpTransformAutoCropBorder &leftBorder, + const kpTransformAutoCropBorder &rightBorder, + const kpTransformAutoCropBorder &topBorder, + const kpTransformAutoCropBorder &botBorder, + kpCommandEnvironment *environ); ~kpTransformAutoCropCommand () override; enum NameOptions @@ -60,26 +54,24 @@ static QString text(bool actOnSelection, int options); - SizeType size () const override; + SizeType size() const override; private: - void getUndoImage (const kpTransformAutoCropBorder &border, kpImage **image); - void getUndoImages (); - void deleteUndoImages (); + void getUndoImage(const kpTransformAutoCropBorder &border, kpImage **image); + void getUndoImages(); + void deleteUndoImages(); public: - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; private: - QRect contentsRect () const; + QRect contentsRect() const; struct kpTransformAutoCropCommandPrivate *d; }; - // (returns true on success (even if it did nothing) or false on error) -bool kpTransformAutoCrop (kpMainWindow *mainWindow); - +bool kpTransformAutoCrop(kpMainWindow *mainWindow); #endif // KP_TRANSFORM_AUTO_CROP_H diff --git a/imagelib/transforms/kpTransformAutoCrop.cpp b/imagelib/transforms/kpTransformAutoCrop.cpp --- a/imagelib/transforms/kpTransformAutoCrop.cpp +++ b/imagelib/transforms/kpTransformAutoCrop.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -43,7 +42,6 @@ #define DEBUG_KP_TOOL_AUTO_CROP 0 - #include "kpTransformAutoCrop.h" #include "layers/selections/image/kpAbstractImageSelection.h" @@ -75,25 +73,25 @@ // afterwards. kpTransformAutoCropBorder (const kpImage *imagePtr = nullptr, int processedColorSimilarity = 0); - kpCommandSize::SizeType size () const; + kpCommandSize::SizeType size() const; - const kpImage *image () const; - int processedColorSimilarity () const; - QRect rect () const; - int left () const; - int right () const; - int top () const; - int bottom () const; - kpColor referenceColor () const; - kpColor averageColor () const; - bool isSingleColor () const; + const kpImage *image() const; + int processedColorSimilarity() const; + QRect rect() const; + int left() const; + int right() const; + int top() const; + int bottom() const; + kpColor referenceColor() const; + kpColor averageColor() const; + bool isSingleColor() const; // (returns true on success (even if no rect) or false on error) - bool calculate (int isX, int dir); + bool calculate(int isX, int dir); - bool fillsEntireImage () const; - bool exists () const; - void invalidate (); + bool fillsEntireImage() const; + bool exists() const; + void invalidate(); private: const kpImage *m_imagePtr; @@ -106,223 +104,216 @@ }; kpTransformAutoCropBorder::kpTransformAutoCropBorder (const kpImage *imagePtr, - int processedColorSimilarity) - : m_imagePtr (imagePtr), - m_processedColorSimilarity (processedColorSimilarity) + int processedColorSimilarity) + : m_imagePtr(imagePtr) + , m_processedColorSimilarity(processedColorSimilarity) { - invalidate (); + invalidate(); } - // public -kpCommandSize::SizeType kpTransformAutoCropBorder::size () const +kpCommandSize::SizeType kpTransformAutoCropBorder::size() const { - return sizeof (kpTransformAutoCropBorder); + return sizeof(kpTransformAutoCropBorder); } - // public -const kpImage *kpTransformAutoCropBorder::image () const +const kpImage *kpTransformAutoCropBorder::image() const { return m_imagePtr; } // public -int kpTransformAutoCropBorder::processedColorSimilarity () const +int kpTransformAutoCropBorder::processedColorSimilarity() const { return m_processedColorSimilarity; } // public -QRect kpTransformAutoCropBorder::rect () const +QRect kpTransformAutoCropBorder::rect() const { return m_rect; } // public -int kpTransformAutoCropBorder::left () const +int kpTransformAutoCropBorder::left() const { - return m_rect.left (); + return m_rect.left(); } // public -int kpTransformAutoCropBorder::right () const +int kpTransformAutoCropBorder::right() const { - return m_rect.right (); + return m_rect.right(); } // public -int kpTransformAutoCropBorder::top () const +int kpTransformAutoCropBorder::top() const { - return m_rect.top (); + return m_rect.top(); } // public -int kpTransformAutoCropBorder::bottom () const +int kpTransformAutoCropBorder::bottom() const { - return m_rect.bottom (); + return m_rect.bottom(); } // public -kpColor kpTransformAutoCropBorder::referenceColor () const +kpColor kpTransformAutoCropBorder::referenceColor() const { return m_referenceColor; } // public -kpColor kpTransformAutoCropBorder::averageColor () const +kpColor kpTransformAutoCropBorder::averageColor() const { - if (!m_rect.isValid ()) + if (!m_rect.isValid()) { return kpColor::Invalid; + } - if (m_referenceColor.isTransparent ()) + if (m_referenceColor.isTransparent()) { return kpColor::Transparent; + } - if (m_processedColorSimilarity == 0) + if (m_processedColorSimilarity == 0) { return m_referenceColor; + } - int numPixels = (m_rect.width () * m_rect.height ()); - Q_ASSERT (numPixels > 0); - - return kpColor (m_redSum / numPixels, m_greenSum / numPixels, m_blueSum / numPixels); + int numPixels = (m_rect.width() * m_rect.height()); + Q_ASSERT(numPixels > 0); + return kpColor(m_redSum / numPixels, m_greenSum / numPixels, m_blueSum / numPixels); } //--------------------------------------------------------------------- -bool kpTransformAutoCropBorder::isSingleColor () const +bool kpTransformAutoCropBorder::isSingleColor() const { return m_isSingleColor; } //--------------------------------------------------------------------- // public -bool kpTransformAutoCropBorder::calculate (int isX, int dir) +bool kpTransformAutoCropBorder::calculate(int isX, int dir) { #if DEBUG_KP_TOOL_AUTO_CROP && 1 qCDebug(kpLogImagelib) << "kpTransformAutoCropBorder::calculate() CALLED!"; #endif - int maxX = m_imagePtr->width () - 1; - int maxY = m_imagePtr->height () - 1; + int maxX = m_imagePtr->width() - 1; + int maxY = m_imagePtr->height() - 1; QImage qimage = *m_imagePtr; - Q_ASSERT (!qimage.isNull ()); + Q_ASSERT(!qimage.isNull()); // (sync both branches) - if (isX) - { + if (isX) { int numCols = 0; int startX = (dir > 0) ? 0 : maxX; - kpColor col = kpPixmapFX::getColorAtPixel (qimage, startX, 0); + kpColor col = kpPixmapFX::getColorAtPixel(qimage, startX, 0); for (int x = startX; x >= 0 && x <= maxX; - x += dir) - { + x += dir) { int y; - for (y = 0; y <= maxY; y++) - { - if (!kpPixmapFX::getColorAtPixel (qimage, x, y).isSimilarTo (col, m_processedColorSimilarity)) + for (y = 0; y <= maxY; y++) { + if (!kpPixmapFX::getColorAtPixel(qimage, x, y).isSimilarTo(col, + m_processedColorSimilarity)) + { break; + } } - if (y <= maxY) + if (y <= maxY) { break; - else + } else { numCols++; + } } - if (numCols) - { - m_rect = - kpPainter::normalizedRect(QPoint(startX, 0), - QPoint(startX + (numCols - 1) * dir, maxY)); + if (numCols) { + m_rect + = kpPainter::normalizedRect(QPoint(startX, 0), + QPoint(startX + (numCols - 1) * dir, maxY)); m_referenceColor = col; } - } - else - { + } else { int numRows = 0; int startY = (dir > 0) ? 0 : maxY; - kpColor col = kpPixmapFX::getColorAtPixel (qimage, 0, startY); + kpColor col = kpPixmapFX::getColorAtPixel(qimage, 0, startY); for (int y = startY; y >= 0 && y <= maxY; - y += dir) - { + y += dir) { int x; - for (x = 0; x <= maxX; x++) - { - if (!kpPixmapFX::getColorAtPixel (qimage, x, y).isSimilarTo (col, m_processedColorSimilarity)) + for (x = 0; x <= maxX; x++) { + if (!kpPixmapFX::getColorAtPixel(qimage, x, y).isSimilarTo(col, + m_processedColorSimilarity)) + { break; + } } - if (x <= maxX) + if (x <= maxX) { break; - else + } else { numRows++; + } } - if (numRows) - { + if (numRows) { m_rect = kpPainter::normalizedRect(QPoint(0, startY), - QPoint(maxX, startY + (numRows - 1) * dir)); + QPoint(maxX, startY + (numRows - 1) * dir)); m_referenceColor = col; } } - - if (m_rect.isValid ()) - { + if (m_rect.isValid()) { m_isSingleColor = true; - if (m_processedColorSimilarity != 0) - { - for (int y = m_rect.top (); y <= m_rect.bottom (); y++) - { - for (int x = m_rect.left (); x <= m_rect.right (); x++) - { - kpColor colAtPixel = kpPixmapFX::getColorAtPixel (qimage, x, y); + if (m_processedColorSimilarity != 0) { + for (int y = m_rect.top(); y <= m_rect.bottom(); y++) { + for (int x = m_rect.left(); x <= m_rect.right(); x++) { + kpColor colAtPixel = kpPixmapFX::getColorAtPixel(qimage, x, y); - if (m_isSingleColor && colAtPixel != m_referenceColor) + if (m_isSingleColor && colAtPixel != m_referenceColor) { m_isSingleColor = false; + } - m_redSum += colAtPixel.red (); - m_greenSum += colAtPixel.green (); - m_blueSum += colAtPixel.blue (); + m_redSum += colAtPixel.red(); + m_greenSum += colAtPixel.green(); + m_blueSum += colAtPixel.blue(); } } } } - return true; } // public -bool kpTransformAutoCropBorder::fillsEntireImage () const +bool kpTransformAutoCropBorder::fillsEntireImage() const { - return (m_rect == m_imagePtr->rect ()); + return m_rect == m_imagePtr->rect(); } // public -bool kpTransformAutoCropBorder::exists () const +bool kpTransformAutoCropBorder::exists() const { // (will use in an addition so make sure returns 1 or 0) - return (m_rect.isValid () ? 1 : 0); + return m_rect.isValid() ? 1 : 0; } // public -void kpTransformAutoCropBorder::invalidate () +void kpTransformAutoCropBorder::invalidate() { - m_rect = QRect (); + m_rect = QRect(); m_referenceColor = kpColor::Invalid; m_redSum = m_greenSum = m_blueSum = 0; m_isSingleColor = false; } - struct kpTransformAutoCropCommandPrivate { bool actOnSelection{}; @@ -336,13 +327,11 @@ // REFACTOR: Move to /commands/ kpTransformAutoCropCommand::kpTransformAutoCropCommand (bool actOnSelection, - const kpTransformAutoCropBorder &leftBorder, - const kpTransformAutoCropBorder &rightBorder, - const kpTransformAutoCropBorder &topBorder, - const kpTransformAutoCropBorder &botBorder, - kpCommandEnvironment *environ) - : kpNamedCommand(text(actOnSelection, DontShowAccel), environ), - d (new kpTransformAutoCropCommandPrivate ()) + const kpTransformAutoCropBorder &leftBorder, + const kpTransformAutoCropBorder &rightBorder, const kpTransformAutoCropBorder &topBorder, const kpTransformAutoCropBorder &botBorder, + kpCommandEnvironment *environ) + : kpNamedCommand(text(actOnSelection, DontShowAccel), environ) + , d(new kpTransformAutoCropCommandPrivate()) { d->actOnSelection = actOnSelection; d->leftBorder = leftBorder; @@ -354,20 +343,20 @@ d->topImage = nullptr; d->botImage = nullptr; - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - d->oldWidth = doc->width (d->actOnSelection); - d->oldHeight = doc->height (d->actOnSelection); + d->oldWidth = doc->width(d->actOnSelection); + d->oldHeight = doc->height(d->actOnSelection); d->oldSelectionPtr = nullptr; } //--------------------------------------------------------------------- kpTransformAutoCropCommand::~kpTransformAutoCropCommand () { - deleteUndoImages (); + deleteUndoImages(); delete d->oldSelectionPtr; delete d; @@ -378,150 +367,146 @@ QString kpTransformAutoCropCommand::text(bool actOnSelection, int options) { - if (actOnSelection) - { + if (actOnSelection) { if (options & kpTransformAutoCropCommand::ShowAccel) { - return i18n ("Remove Internal B&order"); + return i18n("Remove Internal B&order"); } - return i18n ("Remove Internal Border"); + return i18n("Remove Internal Border"); } - if (options & kpTransformAutoCropCommand::ShowAccel) - return i18n ("Autocr&op"); + if (options & kpTransformAutoCropCommand::ShowAccel) { + return i18n("Autocr&op"); + } - return i18n ("Autocrop"); + return i18n("Autocrop"); } //--------------------------------------------------------------------- // public virtual [base kpCommand] -kpCommandSize::SizeType kpTransformAutoCropCommand::size () const +kpCommandSize::SizeType kpTransformAutoCropCommand::size() const { - return d->leftBorder.size () + - d->rightBorder.size () + - d->topBorder.size () + - d->botBorder.size () + - ImageSize (d->leftImage) + - ImageSize (d->rightImage) + - ImageSize (d->topImage) + - ImageSize (d->botImage) + - SelectionSize (d->oldSelectionPtr); + return d->leftBorder.size() + +d->rightBorder.size() + +d->topBorder.size() + +d->botBorder.size() + +ImageSize(d->leftImage) + +ImageSize(d->rightImage) + +ImageSize(d->topImage) + +ImageSize(d->botImage) + +SelectionSize(d->oldSelectionPtr); } //--------------------------------------------------------------------- // private -void kpTransformAutoCropCommand::getUndoImage (const kpTransformAutoCropBorder &border, kpImage **image) +void kpTransformAutoCropCommand::getUndoImage(const kpTransformAutoCropBorder &border, + kpImage **image) { - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); #if DEBUG_KP_TOOL_AUTO_CROP && 1 qCDebug(kpLogImagelib) << "kpTransformAutoCropCommand::getUndoImage()"; qCDebug(kpLogImagelib) << "\timage=" << image - << " border: rect=" << border.rect () - << " isSingleColor=" << border.isSingleColor (); + << " border: rect=" << border.rect() + << " isSingleColor=" << border.isSingleColor(); #endif - if (image && border.exists () && !border.isSingleColor ()) - { - if (*image) - { + if (image && border.exists() && !border.isSingleColor()) { + if (*image) { #if DEBUG_KP_TOOL_AUTO_CROP && 1 qCDebug(kpLogImagelib) << "\talready have *image - delete it"; #endif delete *image; } - *image = new kpImage ( - kpPixmapFX::getPixmapAt (doc->image (d->actOnSelection), - border.rect ())); + *image = new kpImage( + kpPixmapFX::getPixmapAt(doc->image(d->actOnSelection), + border.rect())); } } - // private -void kpTransformAutoCropCommand::getUndoImages () +void kpTransformAutoCropCommand::getUndoImages() { - getUndoImage (d->leftBorder, &d->leftImage); - getUndoImage (d->rightBorder, &d->rightImage); - getUndoImage (d->topBorder, &d->topImage); - getUndoImage (d->botBorder, &d->botImage); + getUndoImage(d->leftBorder, &d->leftImage); + getUndoImage(d->rightBorder, &d->rightImage); + getUndoImage(d->topBorder, &d->topImage); + getUndoImage(d->botBorder, &d->botImage); } // private -void kpTransformAutoCropCommand::deleteUndoImages () +void kpTransformAutoCropCommand::deleteUndoImages() { #if DEBUG_KP_TOOL_AUTO_CROP && 1 qCDebug(kpLogImagelib) << "kpTransformAutoCropCommand::deleteUndoImages()"; #endif - delete d->leftImage; d->leftImage = nullptr; - delete d->rightImage; d->rightImage = nullptr; - delete d->topImage; d->topImage = nullptr; - delete d->botImage; d->botImage = nullptr; + delete d->leftImage; + d->leftImage = nullptr; + delete d->rightImage; + d->rightImage = nullptr; + delete d->topImage; + d->topImage = nullptr; + delete d->botImage; + d->botImage = nullptr; } - // public virtual [base kpCommand] -void kpTransformAutoCropCommand::execute () +void kpTransformAutoCropCommand::execute() { - if (!d->contentsRect.isValid ()) { - d->contentsRect = contentsRect (); + if (!d->contentsRect.isValid()) { + d->contentsRect = contentsRect(); } + getUndoImages(); - getUndoImages (); - - - kpDocument *doc = document (); - Q_ASSERT (doc); - - - kpImage imageWithoutBorder = - kpTool::neededPixmap (doc->image (d->actOnSelection), - d->contentsRect); + kpDocument *doc = document(); + Q_ASSERT(doc); + kpImage imageWithoutBorder + = kpTool::neededPixmap(doc->image(d->actOnSelection), + d->contentsRect); if (!d->actOnSelection) { - doc->setImage (imageWithoutBorder); - } - else { - d->oldSelectionPtr = doc->imageSelection ()->clone (); - d->oldSelectionPtr->setBaseImage (kpImage ()); + doc->setImage(imageWithoutBorder); + } else { + d->oldSelectionPtr = doc->imageSelection()->clone(); + d->oldSelectionPtr->setBaseImage(kpImage()); // d->contentsRect is relative to the top of the sel // while sel is relative to the top of the doc QRect rect = d->contentsRect; - rect.translate (d->oldSelectionPtr->x (), d->oldSelectionPtr->y ()); + rect.translate(d->oldSelectionPtr->x(), d->oldSelectionPtr->y()); - kpRectangularImageSelection sel ( + kpRectangularImageSelection sel( rect, imageWithoutBorder, - d->oldSelectionPtr->transparency ()); + d->oldSelectionPtr->transparency()); - doc->setSelection (sel); + doc->setSelection(sel); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } } // public virtual [base kpCommand] -void kpTransformAutoCropCommand::unexecute () +void kpTransformAutoCropCommand::unexecute() { #if DEBUG_KP_TOOL_AUTO_CROP && 1 qCDebug(kpLogImagelib) << "kpTransformAutoCropCommand::unexecute()"; #endif - kpDocument *doc = document (); - Q_ASSERT (doc); + kpDocument *doc = document(); + Q_ASSERT(doc); - kpImage image (d->oldWidth, d->oldHeight, QImage::Format_ARGB32_Premultiplied); + kpImage image(d->oldWidth, d->oldHeight, QImage::Format_ARGB32_Premultiplied); // restore the position of the center image - kpPixmapFX::setPixmapAt (&image, d->contentsRect, - doc->image (d->actOnSelection)); + kpPixmapFX::setPixmapAt(&image, d->contentsRect, + doc->image(d->actOnSelection)); // draw the borders @@ -540,173 +525,177 @@ }; const kpImage **p = images; - for (const kpTransformAutoCropBorder **b = borders; *b; b++, p++) - { - if (!(*b)->exists ()) { + for (const kpTransformAutoCropBorder **b = borders; *b; b++, p++) { + if (!(*b)->exists()) { continue; } - if ((*b)->isSingleColor ()) - { - kpColor col = (*b)->referenceColor (); + if ((*b)->isSingleColor()) { + kpColor col = (*b)->referenceColor(); #if DEBUG_KP_TOOL_AUTO_CROP && 1 - qCDebug(kpLogImagelib) << "\tdrawing border " << (*b)->rect () - << " rgb=" << (int *) col.toQRgb () /* %X hack */; + qCDebug(kpLogImagelib) << "\tdrawing border " << (*b)->rect() + << " rgb=" << (int *)col.toQRgb() /* %X hack */; #endif - const QRect r = (*b)->rect (); - kpPainter::fillRect (&image, - r.x (), r.y (), r.width (), r.height (), - col); - } - else - { + const QRect r = (*b)->rect(); + kpPainter::fillRect(&image, + r.x(), r.y(), r.width(), r.height(), + col); + } else { #if DEBUG_KP_TOOL_AUTO_CROP && 1 - qCDebug(kpLogImagelib) << "\trestoring border image " << (*b)->rect (); + qCDebug(kpLogImagelib) << "\trestoring border image " << (*b)->rect(); #endif - if (*p) - { + if (*p) { // REFACTOR: Add equivalent method to kpPainter and use. - kpPixmapFX::setPixmapAt (&image, (*b)->rect (), **p); + kpPixmapFX::setPixmapAt(&image, (*b)->rect(), **p); } } } - if (!d->actOnSelection) { - doc->setImage (image); - } - else - { - d->oldSelectionPtr->setBaseImage (image); + doc->setImage(image); + } else { + d->oldSelectionPtr->setBaseImage(image); - doc->setSelection (*d->oldSelectionPtr); - delete d->oldSelectionPtr; d->oldSelectionPtr = nullptr; + doc->setSelection(*d->oldSelectionPtr); + delete d->oldSelectionPtr; + d->oldSelectionPtr = nullptr; - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } - - deleteUndoImages (); + deleteUndoImages(); } - // private -QRect kpTransformAutoCropCommand::contentsRect () const +QRect kpTransformAutoCropCommand::contentsRect() const { - const kpImage image = document ()->image (d->actOnSelection); - - QPoint topLeft (d->leftBorder.exists () ? - d->leftBorder.rect ().right () + 1 : - 0, - d->topBorder.exists () ? - d->topBorder.rect ().bottom () + 1 : - 0); - QPoint botRight (d->rightBorder.exists () ? - d->rightBorder.rect ().left () - 1 : - image.width () - 1, - d->botBorder.exists () ? - d->botBorder.rect ().top () - 1 : - image.height () - 1); - - return {topLeft, botRight}; + const kpImage image = document()->image(d->actOnSelection); + + QPoint topLeft(d->leftBorder.exists() + ? d->leftBorder.rect().right() + 1 + : 0, + d->topBorder.exists() + ? d->topBorder.rect().bottom() + 1 + : 0); + QPoint botRight(d->rightBorder.exists() + ? d->rightBorder.rect().left() - 1 + : image.width() - 1, + d->botBorder.exists() + ? d->botBorder.rect().top() - 1 + : image.height() - 1); + + return { + topLeft, botRight + }; } - -static void ShowNothingToAutocropMessage (kpMainWindow *mainWindow, bool actOnSelection) +static void ShowNothingToAutocropMessage(kpMainWindow *mainWindow, bool actOnSelection) { - kpSetOverrideCursorSaver cursorSaver (Qt::ArrowCursor); - - if (actOnSelection) - { - KMessageBox::information (mainWindow, - i18n ("KolourPaint cannot remove the selection's internal border as it" - " could not be located."), - i18nc ("@title:window", "Cannot Remove Internal Border"), - QStringLiteral("NothingToAutoCrop")); - } - else - { - KMessageBox::information (mainWindow, - i18n ("KolourPaint cannot automatically crop the image as its" - " border could not be located."), - i18nc ("@title:window", "Cannot Autocrop"), - QStringLiteral("NothingToAutoCrop")); + kpSetOverrideCursorSaver cursorSaver(Qt::ArrowCursor); + + if (actOnSelection) { + KMessageBox::information(mainWindow, + i18n( + "KolourPaint cannot remove the selection's internal border as it" + " could not be located."), + i18nc("@title:window", "Cannot Remove Internal Border"), + QStringLiteral("NothingToAutoCrop")); + } else { + KMessageBox::information(mainWindow, + i18n("KolourPaint cannot automatically crop the image as its" + " border could not be located."), + i18nc("@title:window", "Cannot Autocrop"), + QStringLiteral("NothingToAutoCrop")); } } -bool kpTransformAutoCrop (kpMainWindow *mainWindow) +bool kpTransformAutoCrop(kpMainWindow *mainWindow) { #if DEBUG_KP_TOOL_AUTO_CROP qCDebug(kpLogImagelib) << "kpTransformAutoCrop() CALLED!"; #endif - Q_ASSERT (mainWindow); - kpDocument *doc = mainWindow->document (); - Q_ASSERT (doc); + Q_ASSERT(mainWindow); + kpDocument *doc = mainWindow->document(); + Q_ASSERT(doc); // OPT: if already pulled selection image, no need to do it again here - kpImage image = doc->selection () ? doc->getSelectedBaseImage () : doc->image (); - Q_ASSERT (!image.isNull ()); + kpImage image = doc->selection() ? doc->getSelectedBaseImage() : doc->image(); + Q_ASSERT(!image.isNull()); - kpViewManager *vm = mainWindow->viewManager (); - Q_ASSERT (vm); + kpViewManager *vm = mainWindow->viewManager(); + Q_ASSERT(vm); - int processedColorSimilarity = mainWindow->colorToolBar ()->processedColorSimilarity (); - kpTransformAutoCropBorder leftBorder (&image, processedColorSimilarity), - rightBorder (&image, processedColorSimilarity), - topBorder (&image, processedColorSimilarity), - botBorder (&image, processedColorSimilarity); + int processedColorSimilarity = mainWindow->colorToolBar()->processedColorSimilarity(); + kpTransformAutoCropBorder leftBorder(&image, processedColorSimilarity), + rightBorder(&image, processedColorSimilarity), + topBorder(&image, processedColorSimilarity), + botBorder(&image, processedColorSimilarity); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); - - mainWindow->colorToolBar ()->flashColorSimilarityToolBarItem (); + mainWindow->colorToolBar()->flashColorSimilarityToolBarItem(); // TODO: With Colour Similarity, a lot of weird (and wonderful) things can // happen resulting in a huge number of code paths. Needs refactoring // and regression testing. // // TODO: e.g. When the top fills entire rect but bot doesn't we could // invalidate top and continue autocrop. int numRegions = 0; - if (!leftBorder.calculate (true/*x*/, +1/*going right*/) || - leftBorder.fillsEntireImage () || - !rightBorder.calculate (true/*x*/, -1/*going left*/) || - rightBorder.fillsEntireImage () || - !topBorder.calculate (false/*y*/, +1/*going down*/) || - topBorder.fillsEntireImage () || - !botBorder.calculate (false/*y*/, -1/*going up*/) || - botBorder.fillsEntireImage () || - ((numRegions = leftBorder.exists () + - rightBorder.exists () + - topBorder.exists () + - botBorder.exists ()) == 0)) - { + if (!leftBorder.calculate(true /*x*/, +1 /*going right*/) + || leftBorder.fillsEntireImage() + || !rightBorder.calculate(true /*x*/, -1 /*going left*/) + || rightBorder.fillsEntireImage() + || !topBorder.calculate(false /*y*/, +1 /*going down*/) + || topBorder.fillsEntireImage() + || !botBorder.calculate(false /*y*/, -1 /*going up*/) + || botBorder.fillsEntireImage() + || ((numRegions = leftBorder.exists() + +rightBorder.exists() + +topBorder.exists() + +botBorder.exists()) == 0)) { #if DEBUG_KP_TOOL_AUTO_CROP - qCDebug(kpLogImagelib) << "\tcan't find border; leftBorder.rect=" << leftBorder.rect () - << " rightBorder.rect=" << rightBorder.rect () - << " topBorder.rect=" << topBorder.rect () - << " botBorder.rect=" << botBorder.rect (); + qCDebug(kpLogImagelib) << "\tcan't find border; leftBorder.rect=" << leftBorder.rect() + << " rightBorder.rect=" << rightBorder.rect() + << " topBorder.rect=" << topBorder.rect() + << " botBorder.rect=" << botBorder.rect(); #endif - ::ShowNothingToAutocropMessage (mainWindow, static_cast (doc->selection ())); + ::ShowNothingToAutocropMessage(mainWindow, static_cast(doc->selection())); return false; } #if DEBUG_KP_TOOL_AUTO_CROP qCDebug(kpLogImagelib) << "\tnumRegions=" << numRegions; - qCDebug(kpLogImagelib) << "\t\tleft=" << leftBorder.rect () - << " refCol=" << (leftBorder.exists () ? (int *) leftBorder.referenceColor ().toQRgb () : nullptr) - << " avgCol=" << (leftBorder.exists () ? (int *) leftBorder.averageColor ().toQRgb () : nullptr); - qCDebug(kpLogImagelib) << "\t\tright=" << rightBorder.rect () - << " refCol=" << (rightBorder.exists () ? (int *) rightBorder.referenceColor ().toQRgb () : nullptr) - << " avgCol=" << (rightBorder.exists () ? (int *) rightBorder.averageColor ().toQRgb () : nullptr); - qCDebug(kpLogImagelib) << "\t\ttop=" << topBorder.rect () - << " refCol=" << (topBorder.exists () ? (int *) topBorder.referenceColor ().toQRgb () : nullptr) - << " avgCol=" << (topBorder.exists () ? (int *) topBorder.averageColor ().toQRgb () : nullptr); - qCDebug(kpLogImagelib) << "\t\tbot=" << botBorder.rect () - << " refCol=" << (botBorder.exists () ? (int *) botBorder.referenceColor ().toQRgb () : nullptr) - << " avgCol=" << (botBorder.exists () ? (int *) botBorder.averageColor ().toQRgb () : nullptr); + qCDebug(kpLogImagelib) << "\t\tleft=" << leftBorder.rect() + << " refCol=" + << (leftBorder.exists() ? (int *)leftBorder.referenceColor().toQRgb() : + nullptr) + << " avgCol=" + << (leftBorder.exists() ? (int *)leftBorder.averageColor().toQRgb() : + nullptr); + qCDebug(kpLogImagelib) << "\t\tright=" << rightBorder.rect() + << " refCol=" + << (rightBorder.exists() ? (int *)rightBorder.referenceColor().toQRgb() : + nullptr) + << " avgCol=" + << (rightBorder.exists() ? (int *)rightBorder.averageColor().toQRgb() : + nullptr); + qCDebug(kpLogImagelib) << "\t\ttop=" << topBorder.rect() + << " refCol=" + << (topBorder.exists() ? (int *)topBorder.referenceColor().toQRgb() : + nullptr) + << " avgCol=" + << (topBorder.exists() ? (int *)topBorder.averageColor().toQRgb() : + nullptr); + qCDebug(kpLogImagelib) << "\t\tbot=" << botBorder.rect() + << " refCol=" + << (botBorder.exists() ? (int *)botBorder.referenceColor().toQRgb() : + nullptr) + << " avgCol=" + << (botBorder.exists() ? (int *)botBorder.averageColor().toQRgb() : + nullptr); #endif // In case e.g. the user pastes a solid, coloured-in rectangle, @@ -716,41 +705,36 @@ // // We also kill if they kiss or even overlap. - if (leftBorder.exists () && rightBorder.exists ()) - { - const kpColor leftCol = leftBorder.averageColor (); - const kpColor rightCol = rightBorder.averageColor (); + if (leftBorder.exists() && rightBorder.exists()) { + const kpColor leftCol = leftBorder.averageColor(); + const kpColor rightCol = rightBorder.averageColor(); - if ((numRegions == 2 && !leftCol.isSimilarTo (rightCol, processedColorSimilarity)) || - leftBorder.right () >= rightBorder.left () - 1) // kissing or overlapping - { + if ((numRegions == 2 && !leftCol.isSimilarTo(rightCol, processedColorSimilarity)) + || leftBorder.right() >= rightBorder.left() - 1) { // kissing or overlapping #if DEBUG_KP_TOOL_AUTO_CROP qCDebug(kpLogImagelib) << "\tignoring left border"; #endif - leftBorder.invalidate (); + leftBorder.invalidate(); } } - if (topBorder.exists () && botBorder.exists ()) - { - const kpColor topCol = topBorder.averageColor (); - const kpColor botCol = botBorder.averageColor (); + if (topBorder.exists() && botBorder.exists()) { + const kpColor topCol = topBorder.averageColor(); + const kpColor botCol = botBorder.averageColor(); - if ((numRegions == 2 && !topCol.isSimilarTo (botCol, processedColorSimilarity)) || - topBorder.bottom () >= botBorder.top () - 1) // kissing or overlapping - { + if ((numRegions == 2 && !topCol.isSimilarTo(botCol, processedColorSimilarity)) + || topBorder.bottom() >= botBorder.top() - 1) { // kissing or overlapping #if DEBUG_KP_TOOL_AUTO_CROP qCDebug(kpLogImagelib) << "\tignoring top border"; #endif - topBorder.invalidate (); + topBorder.invalidate(); } } - - mainWindow->addImageOrSelectionCommand ( - new kpTransformAutoCropCommand (static_cast (doc->selection ()), - leftBorder, rightBorder, topBorder, botBorder, mainWindow->commandEnvironment ())); - + mainWindow->addImageOrSelectionCommand( + new kpTransformAutoCropCommand(static_cast(doc->selection()), + leftBorder, rightBorder, topBorder, botBorder, + mainWindow->commandEnvironment())); return true; } diff --git a/imagelib/transforms/kpTransformCrop.h b/imagelib/transforms/kpTransformCrop.h --- a/imagelib/transforms/kpTransformCrop.h +++ b/imagelib/transforms/kpTransformCrop.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TRANSFORM_CROP_H #define KP_TRANSFORM_CROP_H - class kpMainWindow; - // // ASSUMPTION: There is a current selection. // @@ -77,7 +73,6 @@ // For user convenience, this border is created by a undoable // create-selection-border command added to the undo history. // -void kpTransformCrop (kpMainWindow *mainWindow); - +void kpTransformCrop(kpMainWindow *mainWindow); #endif // KP_TRANSFORM_CROP_H diff --git a/imagelib/transforms/kpTransformCrop.cpp b/imagelib/transforms/kpTransformCrop.cpp --- a/imagelib/transforms/kpTransformCrop.cpp +++ b/imagelib/transforms/kpTransformCrop.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_CROP 0 - #include "kpTransformCrop.h" #include "kpTransformCropPrivate.h" @@ -41,37 +38,32 @@ #include - -void kpTransformCrop (kpMainWindow *mainWindow) +void kpTransformCrop(kpMainWindow *mainWindow) { - kpDocument *doc = mainWindow->document (); - Q_ASSERT (doc); + kpDocument *doc = mainWindow->document(); + Q_ASSERT(doc); - kpAbstractSelection *sel = doc->selection (); - Q_ASSERT (sel); + kpAbstractSelection *sel = doc->selection(); + Q_ASSERT(sel); + kpCommand *resizeDocCommand + = new kpTransformResizeScaleCommand( + false /*act on doc, not sel*/, + sel->width(), sel->height(), + kpTransformResizeScaleCommand::Resize, + mainWindow->commandEnvironment()); - kpCommand *resizeDocCommand = - new kpTransformResizeScaleCommand ( - false/*act on doc, not sel*/, - sel->width (), sel->height (), - kpTransformResizeScaleCommand::Resize, - mainWindow->commandEnvironment ()); - - - auto *textSel = dynamic_cast (sel); - auto *imageSel = dynamic_cast (sel); + auto *textSel = dynamic_cast (sel); + auto *imageSel = dynamic_cast (sel); // It's either a text selection or an image selection, but cannot be // neither or both. - Q_ASSERT (!!textSel != !!imageSel); + Q_ASSERT(!!textSel != !!imageSel); if (textSel) { - ::kpTransformCrop_TextSelection (mainWindow, i18n ("Set as Image"), resizeDocCommand); - } - else if (imageSel) { - ::kpTransformCrop_ImageSelection (mainWindow, i18n ("Set as Image"), resizeDocCommand); - } - else { - Q_ASSERT (!"unreachable"); + ::kpTransformCrop_TextSelection(mainWindow, i18n("Set as Image"), resizeDocCommand); + } else if (imageSel) { + ::kpTransformCrop_ImageSelection(mainWindow, i18n("Set as Image"), resizeDocCommand); + } else { + Q_ASSERT(!"unreachable"); } } diff --git a/imagelib/transforms/kpTransformCropPrivate.h b/imagelib/transforms/kpTransformCropPrivate.h --- a/imagelib/transforms/kpTransformCropPrivate.h +++ b/imagelib/transforms/kpTransformCropPrivate.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,25 +24,21 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransformCropPrivate_H #define kpTransformCropPrivate_H - class QString; class kpCommand; class kpMainWindow; - // Adds a kpMacroCommand, with name , to the command history. // // The first subcommand of this kpMacroCommand should be // which resizes the document to the size of the selection. -void kpTransformCrop_TextSelection (kpMainWindow *mainWindow, - const QString &commandName, kpCommand *resizeDocCommand); -void kpTransformCrop_ImageSelection (kpMainWindow *mainWindow, - const QString &commandName, kpCommand *resizeDocCommand); - +void kpTransformCrop_TextSelection(kpMainWindow *mainWindow, const QString &commandName, + kpCommand *resizeDocCommand); +void kpTransformCrop_ImageSelection(kpMainWindow *mainWindow, const QString &commandName, + kpCommand *resizeDocCommand); #endif // kpTransformCropPrivate_H diff --git a/imagelib/transforms/kpTransformCrop_ImageSelection.cpp b/imagelib/transforms/kpTransformCrop_ImageSelection.cpp --- a/imagelib/transforms/kpTransformCrop_ImageSelection.cpp +++ b/imagelib/transforms/kpTransformCrop_ImageSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_CROP 0 - #include "kpTransformCrop.h" #include "kpTransformCropPrivate.h" @@ -43,7 +40,6 @@ #include "commands/tools/selection/kpToolSelectionCreateCommand.h" #include "views/manager/kpViewManager.h" - // See the "image selection" part of the kpTransformCrop() API Doc. // // REFACTOR: Move into commands/ @@ -54,43 +50,45 @@ ~SetDocumentToSelectionImageCommand () override; /* (uninteresting child of macro cmd) */ - QString name () const override { return {}; } + QString name() const override + { + return {}; + } - kpCommandSize::SizeType size () const override + kpCommandSize::SizeType size() const override { - return ImageSize (m_oldImage) + - SelectionSize (m_fromSelectionPtr) + - ImageSize (m_imageIfFromSelectionDoesntHaveOne); + return ImageSize(m_oldImage) + +SelectionSize(m_fromSelectionPtr) + +ImageSize(m_imageIfFromSelectionDoesntHaveOne); } // ASSUMPTION: Document has been resized to be the same size as the // selection. - void execute () override; - void unexecute () override; + void execute() override; + void unexecute() override; protected: kpColor m_backgroundColor; kpImage m_oldImage; kpAbstractImageSelection *m_fromSelectionPtr; kpImage m_imageIfFromSelectionDoesntHaveOne; }; - -SetDocumentToSelectionImageCommand::SetDocumentToSelectionImageCommand (kpCommandEnvironment *environ) - : kpCommand (environ), - m_backgroundColor (environ->backgroundColor ()), - m_fromSelectionPtr ( - dynamic_cast ( - environ->document ()->selection ()->clone ())) +SetDocumentToSelectionImageCommand::SetDocumentToSelectionImageCommand ( + kpCommandEnvironment *environ) + : kpCommand(environ) + , m_backgroundColor(environ->backgroundColor()) + , m_fromSelectionPtr( + dynamic_cast ( + environ->document()->selection()->clone())) { - Q_ASSERT (m_fromSelectionPtr); + Q_ASSERT(m_fromSelectionPtr); - if ( m_fromSelectionPtr ) // make coverity happy - { - m_imageIfFromSelectionDoesntHaveOne = - m_fromSelectionPtr->hasContent () ? - kpImage () : - document ()->getSelectedBaseImage (); + if (m_fromSelectionPtr) { // make coverity happy + m_imageIfFromSelectionDoesntHaveOne + = m_fromSelectionPtr->hasContent() + ? kpImage() + : document()->getSelectedBaseImage(); } } @@ -104,21 +102,20 @@ //--------------------------------------------------------------------- // public virtual [base kpCommand] -void SetDocumentToSelectionImageCommand::execute () +void SetDocumentToSelectionImageCommand::execute() { #if DEBUG_KP_TOOL_CROP qCDebug(kpLogImagelib) << "SetDocumentToSelectionImageCommand::execute()"; #endif - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { // kpTransformCrop_ImageSelection's has // executed, resizing the document to be the size of the selection // bounding rectangle. - Q_ASSERT (document ()->width () == m_fromSelectionPtr->width ()); - Q_ASSERT (document ()->height () == m_fromSelectionPtr->height ()); - m_oldImage = document ()->image (); - + Q_ASSERT(document()->width() == m_fromSelectionPtr->width()); + Q_ASSERT(document()->height() == m_fromSelectionPtr->height()); + m_oldImage = document()->image(); // // e.g. original elliptical selection: @@ -139,119 +136,111 @@ // any transparent pixels. // - QImage newDocImage(document()->width(), document()->height(), QImage::Format_ARGB32_Premultiplied); + QImage newDocImage(document()->width(), + document()->height(), QImage::Format_ARGB32_Premultiplied); newDocImage.fill(m_backgroundColor.toQRgb()); #if DEBUG_KP_TOOL_CROP - qCDebug(kpLogImagelib) << "\tsel: rect=" << m_fromSelectionPtr->boundingRect () - << " pm=" << m_fromSelectionPtr->hasContent (); + qCDebug(kpLogImagelib) << "\tsel: rect=" << m_fromSelectionPtr->boundingRect() + << " pm=" << m_fromSelectionPtr->hasContent(); #endif QImage setTransparentImage; - if (m_fromSelectionPtr->hasContent ()) - { - setTransparentImage = m_fromSelectionPtr->transparentImage (); + if (m_fromSelectionPtr->hasContent()) { + setTransparentImage = m_fromSelectionPtr->transparentImage(); #if DEBUG_KP_TOOL_CROP qCDebug(kpLogImagelib) << "\thave pixmap; rect=" - << setTransparentImage.rect (); + << setTransparentImage.rect(); #endif - } - else - { + } else { setTransparentImage = m_imageIfFromSelectionDoesntHaveOne; #if DEBUG_KP_TOOL_CROP qCDebug(kpLogImagelib) << "\tno pixmap in sel - get it; rect=" - << setTransparentImage.rect (); + << setTransparentImage.rect(); #endif } - kpPixmapFX::paintPixmapAt (&newDocImage, - QPoint (0, 0), - setTransparentImage); - - - document ()->setImageAt (newDocImage, QPoint (0, 0)); - document ()->selectionDelete (); + kpPixmapFX::paintPixmapAt(&newDocImage, + QPoint(0, 0), + setTransparentImage); + document()->setImageAt(newDocImage, QPoint(0, 0)); + document()->selectionDelete(); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } - viewManager ()->restoreQueueUpdates (); + viewManager()->restoreQueueUpdates(); } //--------------------------------------------------------------------- // public virtual [base kpCommand] -void SetDocumentToSelectionImageCommand::unexecute () +void SetDocumentToSelectionImageCommand::unexecute() { #if DEBUG_KP_TOOL_CROP qCDebug(kpLogImagelib) << "SetDocumentToSelectionImageCommand::unexecute()"; #endif - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { - document ()->setImageAt (m_oldImage, QPoint (0, 0)); - m_oldImage = kpImage (); + document()->setImageAt(m_oldImage, QPoint(0, 0)); + m_oldImage = kpImage(); #if DEBUG_KP_TOOL_CROP - qCDebug(kpLogImagelib) << "\tsel: rect=" << m_fromSelectionPtr->boundingRect () - << " pm=" << m_fromSelectionPtr->hasContent (); + qCDebug(kpLogImagelib) << "\tsel: rect=" << m_fromSelectionPtr->boundingRect() + << " pm=" << m_fromSelectionPtr->hasContent(); #endif - document ()->setSelection (*m_fromSelectionPtr); + document()->setSelection(*m_fromSelectionPtr); - environ ()->somethingBelowTheCursorChanged (); + environ()->somethingBelowTheCursorChanged(); } - viewManager ()->restoreQueueUpdates (); + viewManager()->restoreQueueUpdates(); } //--------------------------------------------------------------------- - -void kpTransformCrop_ImageSelection (kpMainWindow *mainWindow, - const QString &commandName, kpCommand *resizeDocCommand) +void kpTransformCrop_ImageSelection(kpMainWindow *mainWindow, const QString &commandName, + kpCommand *resizeDocCommand) { // Save starting selection, minus the border. - auto *borderImageSel = dynamic_cast ( - mainWindow->document ()->selection ()->clone ()); + auto *borderImageSel = dynamic_cast ( + mainWindow->document()->selection()->clone()); - Q_ASSERT (borderImageSel); + Q_ASSERT(borderImageSel); - if ( !borderImageSel ) { // make coverity happy + if (!borderImageSel) { // make coverity happy return; } // (only interested in border) - borderImageSel->deleteContent (); - borderImageSel->moveTo (QPoint (0, 0)); + borderImageSel->deleteContent(); + borderImageSel->moveTo(QPoint(0, 0)); - auto *environ = mainWindow->commandEnvironment (); - auto *macroCmd = new kpMacroCommand (commandName, environ); + auto *environ = mainWindow->commandEnvironment(); + auto *macroCmd = new kpMacroCommand(commandName, environ); // (must resize doc _before_ SetDocumentToSelectionImageCommand in case // doc needs to gets bigger - else selection image may not fit) - macroCmd->addCommand (resizeDocCommand); + macroCmd->addCommand(resizeDocCommand); #if DEBUG_KP_TOOL_CROP qCDebug(kpLogImagelib) << "\tis pixmap sel"; qCDebug(kpLogImagelib) << "\tcreating SetImage cmd"; #endif - macroCmd->addCommand (new SetDocumentToSelectionImageCommand (environ)); - + macroCmd->addCommand(new SetDocumentToSelectionImageCommand(environ)); - mainWindow->addImageOrSelectionCommand ( + mainWindow->addImageOrSelectionCommand( macroCmd, - true/*add create cmd*/, - false/*don't add pull cmd*/); - + true /*add create cmd*/, + false /*don't add pull cmd*/); // Add selection border back for convenience. - mainWindow->commandHistory ()->addCommand ( - new kpToolSelectionCreateCommand ( - i18n ("Selection: Create"), + mainWindow->commandHistory()->addCommand( + new kpToolSelectionCreateCommand( + i18n("Selection: Create"), *borderImageSel, - mainWindow->commandEnvironment ())); - + mainWindow->commandEnvironment())); delete borderImageSel; } diff --git a/imagelib/transforms/kpTransformCrop_TextSelection.cpp b/imagelib/transforms/kpTransformCrop_TextSelection.cpp --- a/imagelib/transforms/kpTransformCrop_TextSelection.cpp +++ b/imagelib/transforms/kpTransformCrop_TextSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,50 +26,46 @@ #define DEBUG_KP_TOOL_CROP 0 - #include "kpTransformCrop.h" #include "kpTransformCropPrivate.h" #include "commands/imagelib/effects/kpEffectClearCommand.h" #include "commands/kpMacroCommand.h" #include "mainWindow/kpMainWindow.h" #include "commands/tools/selection/kpToolSelectionMoveCommand.h" - -void kpTransformCrop_TextSelection (kpMainWindow *mainWindow, - const QString &commandName, kpCommand *resizeDocCommand) +void kpTransformCrop_TextSelection(kpMainWindow *mainWindow, const QString &commandName, + kpCommand *resizeDocCommand) { - kpCommandEnvironment *environ = mainWindow->commandEnvironment (); + kpCommandEnvironment *environ = mainWindow->commandEnvironment(); + auto *macroCmd = new kpMacroCommand(commandName, environ); - auto *macroCmd = new kpMacroCommand (commandName, environ); - - macroCmd->addCommand (resizeDocCommand); + macroCmd->addCommand(resizeDocCommand); #if DEBUG_KP_TOOL_CROP qCDebug(kpLogImagelib) << "\tisText"; qCDebug(kpLogImagelib) << "\tclearing doc with trans cmd"; #endif - macroCmd->addCommand ( - new kpEffectClearCommand ( - false/*act on doc*/, + macroCmd->addCommand( + new kpEffectClearCommand( + false /*act on doc*/, kpColor::Transparent, environ)); #if DEBUG_KP_TOOL_CROP qCDebug(kpLogImagelib) << "\tmoving sel to (0,0) cmd"; #endif - kpToolSelectionMoveCommand *moveCmd = - new kpToolSelectionMoveCommand ( - QString()/*uninteresting child of macro cmd*/, - environ); - moveCmd->moveTo (QPoint (0, 0), true/*move on exec, not now*/); - moveCmd->finalize (); - macroCmd->addCommand (moveCmd); - - - mainWindow->addImageOrSelectionCommand ( + kpToolSelectionMoveCommand *moveCmd + = new kpToolSelectionMoveCommand( + QString() /*uninteresting child of macro cmd*/, + environ); + moveCmd->moveTo(QPoint(0, 0), true /*move on exec, not now*/); + moveCmd->finalize(); + macroCmd->addCommand(moveCmd); + + mainWindow->addImageOrSelectionCommand( macroCmd, - true/*add create cmd*/, - true/*add create content cmd*/); + true /*add create cmd*/, + true /*add create content cmd*/); } diff --git a/kolourpaint.cpp b/kolourpaint.cpp --- a/kolourpaint.cpp +++ b/kolourpaint.cpp @@ -25,7 +25,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include #include "kpVersion.h" @@ -39,86 +38,94 @@ int main(int argc, char *argv []) { - QApplication app(argc, argv); - QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); - - KLocalizedString::setApplicationDomain("kolourpaint"); - - KAboutData aboutData - ( - QStringLiteral("kolourpaint"), - i18n("KolourPaint"), - QStringLiteral(KOLOURPAINT_VERSION_STRING), - i18n("Paint Program by KDE"), - KAboutLicense::Custom, - QString(), // copyright statement - see license instead - QString(), // other text - QStringLiteral("http://www.kolourpaint.org/") // home page - ); - - // (this is _not_ the same as KAboutLicense::BSD) - aboutData.setLicenseText(i18n(kpLicenseText)); - aboutData.setDesktopFileName(QStringLiteral("org.kde.kolourpaint")); - - // Please add yourself here if you feel you're missing. - // SYNC: with AUTHORS - - aboutData.addAuthor(i18n("Clarence Dang"), i18n("Project Founder"), QStringLiteral("dang@kde.org")); - - aboutData.addAuthor(i18n("Thurston Dang"), i18n("Chief Investigator"), - QStringLiteral("thurston_dang@users.sourceforge.net")); - - aboutData.addAuthor(i18n("Martin Koller"), i18n("Scanning Support, Alpha Support, Current Maintainer"), - QStringLiteral("kollix@aon.at")); - - aboutData.addAuthor(i18n("Kristof Borrey"), i18n("Icons"), QStringLiteral("borrey@kde.org")); - aboutData.addAuthor(i18n("Tasuku Suzuki"), i18n("InputMethod Support"), QStringLiteral("stasuku@gmail.com")); - aboutData.addAuthor(i18n("Kazuki Ohta"), i18n("InputMethod Support"), QStringLiteral("mover@hct.zaq.ne.jp")); - aboutData.addAuthor(i18n("Nuno Pinheiro"), i18n("Icons"), QStringLiteral("nf.pinheiro@gmail.com")); - aboutData.addAuthor(i18n("Danny Allen"), i18n("Icons"), QStringLiteral("dannya40uk@yahoo.co.uk")); - aboutData.addAuthor(i18n("Mike Gashler"), i18n("Image Effects"), QStringLiteral("gashlerm@yahoo.com")); - - aboutData.addAuthor(i18n("Laurent Montel"), i18n("KDE 4 Porting"), QStringLiteral("montel@kde.org")); - aboutData.addAuthor(i18n("Christoph Feck"), i18n("KF 5 Porting"), QStringLiteral("cfeck@kde.org")); - - aboutData.addCredit(i18n("Thanks to the many others who have helped to make this program possible.")); - - QCommandLineParser cmdLine; - KAboutData::setApplicationData(aboutData); - QApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("kolourpaint"), QApplication::windowIcon())); - cmdLine.addVersionOption(); - cmdLine.addHelpOption(); - cmdLine.addPositionalArgument(QStringLiteral("files"), i18n("Image files to open, optionally"), QStringLiteral("[files...]")); - - aboutData.setupCommandLine(&cmdLine); - cmdLine.process(app); - aboutData.processCommandLine(&cmdLine); - - if ( app.isSessionRestored() ) - { - // Creates a kpMainWindow using the default constructor and then - // calls kpMainWindow::readProperties(). - RESTORE(kpMainWindow) - } - else - { - kpMainWindow *mainWindow; - QStringList args = cmdLine.positionalArguments(); - - if ( args.count() >= 1 ) - { - for (int i = 0; i < args.count(); i++) - { - mainWindow = new kpMainWindow(QUrl::fromUserInput(args[i], QDir::currentPath(), QUrl::AssumeLocalFile)); - mainWindow->show(); - } - } - else - { - mainWindow = new kpMainWindow(); - mainWindow->show(); + QApplication app(argc, argv); + QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + + KLocalizedString::setApplicationDomain("kolourpaint"); + + KAboutData aboutData + ( + QStringLiteral("kolourpaint"), + i18n("KolourPaint"), + QStringLiteral(KOLOURPAINT_VERSION_STRING), + i18n("Paint Program by KDE"), + KAboutLicense::Custom, + QString(), // copyright statement - see license instead + QString(), // other text + QStringLiteral("http://www.kolourpaint.org/") // home page + ); + + // (this is _not_ the same as KAboutLicense::BSD) + aboutData.setLicenseText(i18n(kpLicenseText)); + aboutData.setDesktopFileName(QStringLiteral("org.kde.kolourpaint")); + + // Please add yourself here if you feel you're missing. + // SYNC: with AUTHORS + + aboutData.addAuthor(i18n("Clarence Dang"), i18n("Project Founder"), + QStringLiteral("dang@kde.org")); + + aboutData.addAuthor(i18n("Thurston Dang"), i18n("Chief Investigator"), + QStringLiteral("thurston_dang@users.sourceforge.net")); + + aboutData.addAuthor(i18n("Martin Koller"), + i18n("Scanning Support, Alpha Support, Current Maintainer"), + QStringLiteral("kollix@aon.at")); + + aboutData.addAuthor(i18n("Kristof Borrey"), i18n("Icons"), QStringLiteral("borrey@kde.org")); + aboutData.addAuthor(i18n("Tasuku Suzuki"), i18n("InputMethod Support"), + QStringLiteral("stasuku@gmail.com")); + aboutData.addAuthor(i18n("Kazuki Ohta"), i18n("InputMethod Support"), + QStringLiteral("mover@hct.zaq.ne.jp")); + aboutData.addAuthor(i18n("Nuno Pinheiro"), i18n("Icons"), QStringLiteral( + "nf.pinheiro@gmail.com")); + aboutData.addAuthor(i18n("Danny Allen"), i18n("Icons"), + QStringLiteral("dannya40uk@yahoo.co.uk")); + aboutData.addAuthor(i18n("Mike Gashler"), i18n("Image Effects"), + QStringLiteral("gashlerm@yahoo.com")); + + aboutData.addAuthor(i18n("Laurent Montel"), i18n("KDE 4 Porting"), + QStringLiteral("montel@kde.org")); + aboutData.addAuthor(i18n("Christoph Feck"), i18n("KF 5 Porting"), QStringLiteral( + "cfeck@kde.org")); + + aboutData.addCredit(i18n( + "Thanks to the many others who have helped to make this program possible.")); + + QCommandLineParser cmdLine; + KAboutData::setApplicationData(aboutData); + QApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("kolourpaint"), + QApplication::windowIcon())); + cmdLine.addVersionOption(); + cmdLine.addHelpOption(); + cmdLine.addPositionalArgument(QStringLiteral("files"), i18n( + "Image files to open, optionally"), + QStringLiteral("[files...]")); + + aboutData.setupCommandLine(&cmdLine); + cmdLine.process(app); + aboutData.processCommandLine(&cmdLine); + + if (app.isSessionRestored()) { + // Creates a kpMainWindow using the default constructor and then + // calls kpMainWindow::readProperties(). + RESTORE(kpMainWindow) + } else { + kpMainWindow *mainWindow; + QStringList args = cmdLine.positionalArguments(); + + if (args.count() >= 1) { + for (int i = 0; i < args.count(); i++) { + mainWindow + = new kpMainWindow(QUrl::fromUserInput(args[i], QDir::currentPath(), + QUrl::AssumeLocalFile)); + mainWindow->show(); + } + } else { + mainWindow = new kpMainWindow(); + mainWindow->show(); + } } - } - return QApplication::exec(); + return QApplication::exec(); } diff --git a/kpDefs.h b/kpDefs.h --- a/kpDefs.h +++ b/kpDefs.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,33 +24,27 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_DEFS_H #define KP_DEFS_H - #include #include #include #include #include - // approx. 2896x2896x32bpp or 3344x3344x24bpp (TODO: 24==32?) or 4096*4096x16bpp #define KP_BIG_IMAGE_SIZE (32 * 1048576) - -#define KP_INVALID_POINT QPoint (INT_MIN / 8, INT_MIN / 8) +#define KP_INVALID_POINT QPoint(INT_MIN / 8, INT_MIN / 8) #define KP_INVALID_WIDTH (INT_MIN / 8) #define KP_INVALID_HEIGHT (INT_MIN / 8) -#define KP_INVALID_SIZE QSize (INT_MIN / 8, INT_MIN / 8) - +#define KP_INVALID_SIZE QSize(INT_MIN / 8, INT_MIN / 8) #define KP_INCHES_PER_METER (100 / 2.54) #define KP_MILLIMETERS_PER_INCH 25.4 - // // Settings // @@ -86,59 +79,50 @@ #define kpSettingMimeTypeHasConfigurableColorDepth "Configurable Color Depth" #define kpSettingMimeTypeHasConfigurableQuality "Configurable Quality Setting" - #define kpSettingsGroupUndoRedo "Undo/Redo Settings" #define kpSettingUndoMinLimit "Min Limit" #define kpSettingUndoMaxLimit "Max Limit" #define kpSettingUndoMaxLimitSizeLimit "Max Limit Size Limit" - #define kpSettingsGroupThumbnail "Thumbnail Settings" #define kpSettingThumbnailShown "Shown" #define kpSettingThumbnailGeometry "Geometry" #define kpSettingThumbnailZoomed "Zoomed" #define kpSettingThumbnailShowRectangle "ShowRectangle" - #define kpSettingsGroupPreviewSave "Save Preview Settings" #define kpSettingPreviewSaveGeometry "Geometry" #define kpSettingPreviewSaveUpdateDelay "Update Delay" - #define kpSettingsGroupTools "Tool Settings" #define kpSettingLastTool "Last Used Tool" #define kpSettingToolBoxIconSize "Tool Box Icon Size" - #define kpSettingsGroupText "Text Settings" #define kpSettingFontFamily "Font Family" #define kpSettingFontSize "Font Size" #define kpSettingBold "Bold" #define kpSettingItalic "Italic" #define kpSettingUnderline "Underline" #define kpSettingStrikeThru "Strike Thru" - #define kpSettingsGroupFlattenEffect "Flatten Effect Settings" #define kpSettingFlattenEffectColor1 "Color1" #define kpSettingFlattenEffectColor2 "Color2" - // // Session Restore Setting // // URL of the document in the main window. // // This key only exists if the document does. If it exists, it can be empty. // The URL need not point to a file that exists e.g. "kolourpaint doesnotexist.png". -#define kpSessionSettingDocumentUrl QString::fromLatin1 ("Session Document Url") +#define kpSessionSettingDocumentUrl QString::fromLatin1("Session Document Url") // The size of a document which is not from a URL e.g. "kolourpaint doesnotexist.png". // This key does not exist for documents from URLs. -#define kpSessionSettingNotFromUrlDocumentSize QString::fromLatin1 ("Session Not-From-Url Document Size") - +#define kpSessionSettingNotFromUrlDocumentSize QString::fromLatin1( \ + "Session Not-From-Url Document Size") #endif // KP_DEFS_H - - diff --git a/kpLogCategories.h b/kpLogCategories.h --- a/kpLogCategories.h +++ b/kpLogCategories.h @@ -43,4 +43,3 @@ Q_DECLARE_LOGGING_CATEGORY(kpLogImagelib) #endif - diff --git a/kpLogCategories.cpp b/kpLogCategories.cpp --- a/kpLogCategories.cpp +++ b/kpLogCategories.cpp @@ -26,16 +26,15 @@ #include "kpLogCategories.h" -Q_LOGGING_CATEGORY(kpLogMisc, "kp.misc") -Q_LOGGING_CATEGORY(kpLogDialogs, "kp.dialogs") -Q_LOGGING_CATEGORY(kpLogCommands, "kp.commands") -Q_LOGGING_CATEGORY(kpLogDocument, "kp.document") -Q_LOGGING_CATEGORY(kpLogTools, "kp.tools") -Q_LOGGING_CATEGORY(kpLogViews, "kp.views") -Q_LOGGING_CATEGORY(kpLogEnvironments, "kp.environments") -Q_LOGGING_CATEGORY(kpLogPixmapfx, "kp.pixmapfx") -Q_LOGGING_CATEGORY(kpLogWidgets, "kp.widgets") -Q_LOGGING_CATEGORY(kpLogMainWindow, "kp.mainwindow") -Q_LOGGING_CATEGORY(kpLogLayers, "kp.layers") -Q_LOGGING_CATEGORY(kpLogImagelib, "kp.imagelib") - +Q_LOGGING_CATEGORY(kpLogMisc, "kp.misc") +Q_LOGGING_CATEGORY(kpLogDialogs, "kp.dialogs") +Q_LOGGING_CATEGORY(kpLogCommands, "kp.commands") +Q_LOGGING_CATEGORY(kpLogDocument, "kp.document") +Q_LOGGING_CATEGORY(kpLogTools, "kp.tools") +Q_LOGGING_CATEGORY(kpLogViews, "kp.views") +Q_LOGGING_CATEGORY(kpLogEnvironments, "kp.environments") +Q_LOGGING_CATEGORY(kpLogPixmapfx, "kp.pixmapfx") +Q_LOGGING_CATEGORY(kpLogWidgets, "kp.widgets") +Q_LOGGING_CATEGORY(kpLogMainWindow, "kp.mainwindow") +Q_LOGGING_CATEGORY(kpLogLayers, "kp.layers") +Q_LOGGING_CATEGORY(kpLogImagelib, "kp.imagelib") diff --git a/kpThumbnail.h b/kpThumbnail.h --- a/kpThumbnail.h +++ b/kpThumbnail.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,52 +24,47 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_THUMBNAIL_H #define KP_THUMBNAIL_H - #include "generic/widgets/kpSubWindow.h" - class QMoveEvent; class QResizeEvent; class kpMainWindow; class kpThumbnailView; - struct kpThumbnailPrivate; class kpThumbnail : public kpSubWindow { -Q_OBJECT + Q_OBJECT public: kpThumbnail (kpMainWindow *parent); ~kpThumbnail () override; public: - kpThumbnailView *view () const; - void setView (kpThumbnailView *view); + kpThumbnailView *view() const; + void setView(kpThumbnailView *view); public slots: - void updateCaption (); + void updateCaption(); protected slots: - void slotViewDestroyed (); + void slotViewDestroyed(); protected: - void resizeEvent (QResizeEvent *e) override; - void moveEvent (QMoveEvent *e) override; - void closeEvent (QCloseEvent *e) override; + void resizeEvent(QResizeEvent *e) override; + void moveEvent(QMoveEvent *e) override; + void closeEvent(QCloseEvent *e) override; signals: - void windowClosed (); + void windowClosed(); private: - kpThumbnailPrivate * const d; + kpThumbnailPrivate *const d; }; - #endif // KP_THUMBNAIL_H diff --git a/kpThumbnail.cpp b/kpThumbnail.cpp --- a/kpThumbnail.cpp +++ b/kpThumbnail.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_THUMBNAIL 0 - #include "kpThumbnail.h" #include "kpDefs.h" @@ -43,45 +40,41 @@ #include #include - struct kpThumbnailPrivate { kpMainWindow *mainWindow; kpThumbnailView *view; QHBoxLayout *lay; }; kpThumbnail::kpThumbnail (kpMainWindow *parent) - : kpSubWindow (parent), - d (new kpThumbnailPrivate ()) + : kpSubWindow(parent) + , d(new kpThumbnailPrivate()) { - Q_ASSERT (parent); + Q_ASSERT(parent); d->mainWindow = parent; d->view = nullptr; - d->lay = new QHBoxLayout (this); + d->lay = new QHBoxLayout(this); + setMinimumSize(64, 64); - setMinimumSize (64, 64); - - - updateCaption (); + updateCaption(); } kpThumbnail::~kpThumbnail () { delete d; } - // public -kpThumbnailView *kpThumbnail::view () const +kpThumbnailView *kpThumbnail::view() const { return d->view; } // public -void kpThumbnail::setView (kpThumbnailView *view) +void kpThumbnail::setView(kpThumbnailView *view) { #if DEBUG_KP_THUMBNAIL qCDebug(kpLogMisc) << "kpThumbnail::setView(" << view << ")"; @@ -91,93 +84,84 @@ return; } + if (d->view) { + disconnect(d->view, &kpThumbnailView::destroyed, + this, &kpThumbnail::slotViewDestroyed); - if (d->view) - { - disconnect (d->view, &kpThumbnailView::destroyed, - this, &kpThumbnail::slotViewDestroyed); - - disconnect (d->view, &kpThumbnailView::zoomLevelChanged, - this, &kpThumbnail::updateCaption); + disconnect(d->view, &kpThumbnailView::zoomLevelChanged, + this, &kpThumbnail::updateCaption); - d->lay->removeWidget (d->view); + d->lay->removeWidget(d->view); } d->view = view; - if (d->view) - { - connect (d->view, &kpThumbnailView::destroyed, - this, &kpThumbnail::slotViewDestroyed); + if (d->view) { + connect(d->view, &kpThumbnailView::destroyed, + this, &kpThumbnail::slotViewDestroyed); - connect (d->view, &kpThumbnailView::zoomLevelChanged, - this, &kpThumbnail::updateCaption); + connect(d->view, &kpThumbnailView::zoomLevelChanged, + this, &kpThumbnail::updateCaption); - Q_ASSERT (d->view->parent () == this); - d->lay->addWidget (d->view, Qt::AlignCenter); - - d->view->show (); + Q_ASSERT(d->view->parent() == this); + d->lay->addWidget(d->view, Qt::AlignCenter); + + d->view->show(); } - - updateCaption (); -} + updateCaption(); +} // public slot -void kpThumbnail::updateCaption () +void kpThumbnail::updateCaption() { - setWindowTitle (view () ? view ()->caption () : i18nc ("@title:window", "Thumbnail")); + setWindowTitle(view() ? view()->caption() : i18nc("@title:window", "Thumbnail")); } - // protected slot -void kpThumbnail::slotViewDestroyed () +void kpThumbnail::slotViewDestroyed() { #if DEBUG_KP_THUMBNAIL qCDebug(kpLogMisc) << "kpThumbnail::slotViewDestroyed()"; #endif d->view = nullptr; - updateCaption (); + updateCaption(); } - // protected virtual [base QWidget] -void kpThumbnail::resizeEvent (QResizeEvent *e) +void kpThumbnail::resizeEvent(QResizeEvent *e) { #if DEBUG_KP_THUMBNAIL - qCDebug(kpLogMisc) << "kpThumbnail::resizeEvent(" << width () - << "," << height () << ")"; + qCDebug(kpLogMisc) << "kpThumbnail::resizeEvent(" << width() + << "," << height() << ")"; #endif - QWidget::resizeEvent (e); + QWidget::resizeEvent(e); // updateVariableZoom (); TODO: is below a good idea since this commented out? - if (d->mainWindow) - { - d->mainWindow->notifyThumbnailGeometryChanged (); + if (d->mainWindow) { + d->mainWindow->notifyThumbnailGeometryChanged(); - if (d->mainWindow->tool ()) { - d->mainWindow->tool ()->somethingBelowTheCursorChanged (); + if (d->mainWindow->tool()) { + d->mainWindow->tool()->somethingBelowTheCursorChanged(); } } } // protected virtual [base QWidget] -void kpThumbnail::moveEvent (QMoveEvent * /*e*/) +void kpThumbnail::moveEvent(QMoveEvent * /*e*/) { if (d->mainWindow) { - d->mainWindow->notifyThumbnailGeometryChanged (); + d->mainWindow->notifyThumbnailGeometryChanged(); } } // protected virtual [base QWidget] -void kpThumbnail::closeEvent (QCloseEvent *e) +void kpThumbnail::closeEvent(QCloseEvent *e) { - QWidget::closeEvent (e); + QWidget::closeEvent(e); - emit windowClosed (); + emit windowClosed(); } - - diff --git a/kpViewScrollableContainer.h b/kpViewScrollableContainer.h --- a/kpViewScrollableContainer.h +++ b/kpViewScrollableContainer.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,17 +24,14 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_VIEW_SCROLLABLE_CONTAINER_H #define KP_VIEW_SCROLLABLE_CONTAINER_H - #include #include #include #include - class QCursor; class QEvent; class QKeyEvent; @@ -47,13 +43,12 @@ class kpView; class kpOverlay; - //--------------------------------------------------------------------- // REFACTOR: refactor by sharing iface's with kpTool class kpGrip : public QWidget { -Q_OBJECT + Q_OBJECT public: enum GripType @@ -64,47 +59,47 @@ kpGrip (GripType type, QWidget *parent); - GripType type () const; + GripType type() const; - static QCursor cursorForType (GripType type); + static QCursor cursorForType(GripType type); bool containsCursor(); - bool isDrawing () const; + bool isDrawing() const; static const int Size; signals: - void beganDraw (); - void continuedDraw (int viewDX, int viewDY, bool dueToDragScroll); - void cancelledDraw (); - void endedDraw (int viewDX, int viewDY); + void beganDraw(); + void continuedDraw(int viewDX, int viewDY, bool dueToDragScroll); + void cancelledDraw(); + void endedDraw(int viewDX, int viewDY); - void statusMessageChanged (const QString &string); + void statusMessageChanged(const QString &string); - void releasedAllButtons (); + void releasedAllButtons(); public: - QString haventBegunDrawUserMessage () const; + QString haventBegunDrawUserMessage() const; - QString userMessage () const; - void setUserMessage (const QString &message); + QString userMessage() const; + void setUserMessage(const QString &message); protected: - void cancel (); + void cancel(); protected: - void keyReleaseEvent (QKeyEvent *e) override; - void mousePressEvent (QMouseEvent *e) override; + void keyReleaseEvent(QKeyEvent *e) override; + void mousePressEvent(QMouseEvent *e) override; public: - QPoint viewDeltaPoint () const; - void mouseMovedTo (const QPoint &point, bool dueToDragScroll); + QPoint viewDeltaPoint() const; + void mouseMovedTo(const QPoint &point, bool dueToDragScroll); protected: - void mouseMoveEvent (QMouseEvent *e) override; - void mouseReleaseEvent (QMouseEvent *e) override; + void mouseMoveEvent(QMouseEvent *e) override; + void mouseReleaseEvent(QMouseEvent *e) override; - void enterEvent (QEvent *e) override; - void leaveEvent (QEvent *e) override; + void enterEvent(QEvent *e) override; + void leaveEvent(QEvent *e) override; protected: GripType m_type; @@ -117,84 +112,82 @@ class kpViewScrollableContainer : public QScrollArea { -Q_OBJECT + Q_OBJECT public: kpViewScrollableContainer(QWidget *parent); - QSize newDocSize () const; - bool haveMovedFromOriginalDocSize () const; - QString statusMessage () const; - void clearStatusMessage (); + QSize newDocSize() const; + bool haveMovedFromOriginalDocSize() const; + QString statusMessage() const; + void clearStatusMessage(); - kpView *view () const; - void setView (kpView *view); + kpView *view() const; + void setView(kpView *view); void drawResizeLines(); // public only for kpOverlay signals: void contentsMoved(); - void beganDocResize (); - void continuedDocResize (const QSize &size); - void cancelledDocResize (); - void endedDocResize (const QSize &size); + void beganDocResize(); + void continuedDocResize(const QSize &size); + void cancelledDocResize(); + void endedDocResize(const QSize &size); // (string.isEmpty() if kpViewScrollableContainer has nothing to say) - void statusMessageChanged (const QString &string); + void statusMessageChanged(const QString &string); - void resized (); + void resized(); public slots: - void recalculateStatusMessage (); + void recalculateStatusMessage(); - void updateGrips (); + void updateGrips(); // TODO: Why the need for view's zoomLevel? We have the view() anyway. - bool beginDragScroll (int zoomLevel, - bool *didSomething); - bool beginDragScroll (int zoomLevel); - bool endDragScroll (); + bool beginDragScroll(int zoomLevel, bool *didSomething); + bool beginDragScroll(int zoomLevel); + bool endDragScroll(); private: - void connectGripSignals (kpGrip *grip); + void connectGripSignals(kpGrip *grip); - QSize newDocSize (int viewDX, int viewDY) const; + QSize newDocSize(int viewDX, int viewDY) const; - void calculateDocResizingGrip (); - kpGrip *docResizingGrip () const; + void calculateDocResizingGrip(); + kpGrip *docResizingGrip() const; - int bottomResizeLineWidth () const; - int rightResizeLineWidth () const; + int bottomResizeLineWidth() const; + int rightResizeLineWidth() const; - QRect bottomResizeLineRect () const; - QRect rightResizeLineRect () const; - QRect bottomRightResizeLineRect () const; + QRect bottomResizeLineRect() const; + QRect rightResizeLineRect() const; + QRect bottomRightResizeLineRect() const; - QRect mapViewToViewport (const QRect &viewRect); + QRect mapViewToViewport(const QRect &viewRect); - void updateResizeLines (int viewX, int viewY, - int viewDX, int viewDY); + void updateResizeLines(int viewX, int viewY, int viewDX, int viewDY); - void disconnectViewSignals (); - void connectViewSignals (); + void disconnectViewSignals(); + void connectViewSignals(); - QRect noDragScrollRect () const; + QRect noDragScrollRect() const; void wheelEvent(QWheelEvent *e) override; void resizeEvent(QResizeEvent *e) override; private slots: - void slotGripBeganDraw (); - void slotGripContinuedDraw (int viewDX, int viewDY, bool dueToScrollView); - void slotGripCancelledDraw (); - void slotGripEndedDraw (int viewDX, int viewDY); + void slotGripBeganDraw(); + void slotGripContinuedDraw(int viewDX, int viewDY, bool dueToScrollView); + void slotGripCancelledDraw(); + void slotGripEndedDraw(int viewDX, int viewDY); - void slotGripStatusMessageChanged (const QString &string); + void slotGripStatusMessageChanged(const QString &string); - void slotContentsMoved (); - void slotViewDestroyed (); - bool slotDragScroll (bool *didSomething = nullptr); + void slotContentsMoved(); + void slotViewDestroyed(); + bool slotDragScroll(bool *didSomething = nullptr); private: kpView *m_view; diff --git a/kpViewScrollableContainer.cpp b/kpViewScrollableContainer.cpp --- a/kpViewScrollableContainer.cpp +++ b/kpViewScrollableContainer.cpp @@ -64,20 +64,20 @@ class kpOverlay : public QWidget { - public: +public: kpOverlay(QWidget *parent, kpViewScrollableContainer *container) - : QWidget(parent), m_container(container) + : QWidget(parent) + , m_container(container) { } void paintEvent(QPaintEvent *) override { - m_container->drawResizeLines(); + m_container->drawResizeLines(); } - private: +private: kpViewScrollableContainer *m_container; - }; //--------------------------------------------------------------------- @@ -87,11 +87,11 @@ //--------------------------------------------------------------------- kpGrip::kpGrip (GripType type, QWidget *parent) - : QWidget(parent), - m_type (type), - m_startPoint (KP_INVALID_POINT), - m_currentPoint (KP_INVALID_POINT), - m_shouldReleaseMouseButtons (false) + : QWidget(parent) + , m_type(type) + , m_startPoint(KP_INVALID_POINT) + , m_currentPoint(KP_INVALID_POINT) + , m_shouldReleaseMouseButtons(false) { setCursor(cursorForType(m_type)); @@ -106,18 +106,17 @@ //--------------------------------------------------------------------- // public -kpGrip::GripType kpGrip::type () const +kpGrip::GripType kpGrip::type() const { return m_type; } //--------------------------------------------------------------------- // public static -QCursor kpGrip::cursorForType (GripType type) +QCursor kpGrip::cursorForType(GripType type) { - switch (type) - { + switch (type) { case kpGrip::Bottom: return Qt::SizeVerCursor; @@ -136,52 +135,52 @@ // public bool kpGrip::containsCursor() { - return isVisible() && - QRect(mapToGlobal(rect().topLeft()), - mapToGlobal(rect().bottomRight())).contains(QCursor::pos()); + return isVisible() + && QRect(mapToGlobal(rect().topLeft()), + mapToGlobal(rect().bottomRight())).contains(QCursor::pos()); } //--------------------------------------------------------------------- // public -bool kpGrip::isDrawing () const +bool kpGrip::isDrawing() const { - return (m_startPoint != KP_INVALID_POINT); + return m_startPoint != KP_INVALID_POINT; } //--------------------------------------------------------------------- // public -QString kpGrip::haventBegunDrawUserMessage () const +QString kpGrip::haventBegunDrawUserMessage() const { - return i18n ("Left drag the handle to resize the image."); + return i18n("Left drag the handle to resize the image."); } //--------------------------------------------------------------------- // public -QString kpGrip::userMessage () const +QString kpGrip::userMessage() const { return m_userMessage; } //--------------------------------------------------------------------- // public -void kpGrip::setUserMessage (const QString &message) +void kpGrip::setUserMessage(const QString &message) { // Don't do NOP checking here since another grip might have changed // the message so an apparent NOP for this grip is not a NOP in the // global sense (kpViewScrollableContainer::slotGripStatusMessageChanged()). m_userMessage = message; - emit statusMessageChanged (message); + emit statusMessageChanged(message); } //--------------------------------------------------------------------- // protected -void kpGrip::cancel () +void kpGrip::cancel() { #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER qCDebug(kpLogMisc) << "kpGrip::cancel()"; @@ -193,175 +192,167 @@ m_startPoint = KP_INVALID_POINT; m_currentPoint = KP_INVALID_POINT; - setUserMessage (i18n ("Resize Image: Let go of all the mouse buttons.")); - setCursor (Qt::ArrowCursor); + setUserMessage(i18n("Resize Image: Let go of all the mouse buttons.")); + setCursor(Qt::ArrowCursor); m_shouldReleaseMouseButtons = true; - releaseKeyboard (); - emit cancelledDraw (); + releaseKeyboard(); + emit cancelledDraw(); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpGrip::keyReleaseEvent (QKeyEvent *e) +void kpGrip::keyReleaseEvent(QKeyEvent *e) { - if (m_startPoint != KP_INVALID_POINT && - e->key () == Qt::Key_Escape) - { - cancel (); + if (m_startPoint != KP_INVALID_POINT + && e->key() == Qt::Key_Escape) { + cancel(); } } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpGrip::mousePressEvent (QMouseEvent *e) +void kpGrip::mousePressEvent(QMouseEvent *e) { - if (m_startPoint == KP_INVALID_POINT && - (e->buttons () & Qt::MouseButtonMask) == Qt::LeftButton) - { - m_startPoint = e->pos (); - m_currentPoint = e->pos (); - emit beganDraw (); - grabKeyboard (); - - setUserMessage (i18n ("Resize Image: Right click to cancel.")); - setCursor (cursorForType (m_type)); - } - else - { + if (m_startPoint == KP_INVALID_POINT + && (e->buttons() & Qt::MouseButtonMask) == Qt::LeftButton) { + m_startPoint = e->pos(); + m_currentPoint = e->pos(); + emit beganDraw(); + grabKeyboard(); + + setUserMessage(i18n("Resize Image: Right click to cancel.")); + setCursor(cursorForType(m_type)); + } else { if (m_startPoint != KP_INVALID_POINT) { - cancel (); + cancel(); } } } //--------------------------------------------------------------------- // public -QPoint kpGrip::viewDeltaPoint () const +QPoint kpGrip::viewDeltaPoint() const { if (m_startPoint == KP_INVALID_POINT) { return KP_INVALID_POINT; } - const QPoint point = mapFromGlobal (QCursor::pos ()); + const QPoint point = mapFromGlobal(QCursor::pos()); // TODO: this is getting out of sync with m_currentPoint - return {(m_type & kpGrip::Right) ? point.x () - m_startPoint.x () : 0, - (m_type & kpGrip::Bottom) ? point.y () - m_startPoint.y () : 0}; - + return { + (m_type &kpGrip::Right) ? point.x() - m_startPoint.x() : 0, + (m_type &kpGrip::Bottom) ? point.y() - m_startPoint.y() : 0 + }; } //--------------------------------------------------------------------- // public -void kpGrip::mouseMovedTo (const QPoint &point, bool dueToDragScroll) +void kpGrip::mouseMovedTo(const QPoint &point, bool dueToDragScroll) { if (m_startPoint == KP_INVALID_POINT) { return; } m_currentPoint = point; - emit continuedDraw (((m_type & kpGrip::Right) ? point.x () - m_startPoint.x () : 0), - ((m_type & kpGrip::Bottom) ? point.y () - m_startPoint.y () : 0), - dueToDragScroll); + emit continuedDraw(((m_type &kpGrip::Right) ? point.x() - m_startPoint.x() : 0), + ((m_type &kpGrip::Bottom) ? point.y() - m_startPoint.y() : 0), + dueToDragScroll); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpGrip::mouseMoveEvent (QMouseEvent *e) +void kpGrip::mouseMoveEvent(QMouseEvent *e) { #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER qCDebug(kpLogMisc) << "kpGrip::mouseMoveEvent() m_startPoint=" << m_startPoint - << " stateAfter: buttons=" << (int *) (int) e->buttons (); + << " stateAfter: buttons=" << (int *)(int)e->buttons(); #endif - if (m_startPoint == KP_INVALID_POINT) - { - if ((e->buttons () & Qt::MouseButtonMask) == 0) { - setUserMessage (haventBegunDrawUserMessage ()); + if (m_startPoint == KP_INVALID_POINT) { + if ((e->buttons() & Qt::MouseButtonMask) == 0) { + setUserMessage(haventBegunDrawUserMessage()); } return; } - mouseMovedTo (e->pos (), false/*not due to drag scroll*/); + mouseMovedTo(e->pos(), false /*not due to drag scroll*/); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpGrip::mouseReleaseEvent (QMouseEvent *e) +void kpGrip::mouseReleaseEvent(QMouseEvent *e) { #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER qCDebug(kpLogMisc) << "kpGrip::mouseReleaseEvent() m_startPoint=" << m_startPoint - << " stateAfter: buttons=" << (int *) (int) e->buttons (); + << " stateAfter: buttons=" << (int *)(int)e->buttons(); #endif - if (m_startPoint != KP_INVALID_POINT) - { - const int dx = m_currentPoint.x () - m_startPoint.x (), - dy = m_currentPoint.y () - m_startPoint.y (); + if (m_startPoint != KP_INVALID_POINT) { + const int dx = m_currentPoint.x() - m_startPoint.x(), + dy = m_currentPoint.y() - m_startPoint.y(); m_currentPoint = KP_INVALID_POINT; m_startPoint = KP_INVALID_POINT; - releaseKeyboard (); - emit endedDraw ((m_type & kpGrip::Right) ? dx : 0, - (m_type & kpGrip::Bottom) ? dy : 0); + releaseKeyboard(); + emit endedDraw((m_type &kpGrip::Right) ? dx : 0, + (m_type &kpGrip::Bottom) ? dy : 0); } - if ((e->buttons () & Qt::MouseButtonMask) == 0) - { + if ((e->buttons() & Qt::MouseButtonMask) == 0) { m_shouldReleaseMouseButtons = false; setUserMessage(QString()); - setCursor (cursorForType (m_type)); + setCursor(cursorForType(m_type)); - releaseKeyboard (); - emit releasedAllButtons (); + releaseKeyboard(); + emit releasedAllButtons(); } } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpGrip::enterEvent (QEvent * /*e*/) +void kpGrip::enterEvent(QEvent * /*e*/) { #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER qCDebug(kpLogMisc) << "kpGrip::enterEvent()" - << " m_startPoint=" << m_startPoint - << " shouldReleaseMouseButtons=" - << m_shouldReleaseMouseButtons; + << " m_startPoint=" << m_startPoint + << " shouldReleaseMouseButtons=" + << m_shouldReleaseMouseButtons; #endif - if (m_startPoint == KP_INVALID_POINT && - !m_shouldReleaseMouseButtons) - { + if (m_startPoint == KP_INVALID_POINT + && !m_shouldReleaseMouseButtons) { #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER qCDebug(kpLogMisc) << "\tsending message"; #endif - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpGrip::leaveEvent (QEvent * /*e*/) +void kpGrip::leaveEvent(QEvent * /*e*/) { #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER qCDebug(kpLogMisc) << "kpGrip::leaveEvent()" - << " m_startPoint=" << m_startPoint - << " shouldReleaseMouseButtons=" - << m_shouldReleaseMouseButtons; + << " m_startPoint=" << m_startPoint + << " shouldReleaseMouseButtons=" + << m_shouldReleaseMouseButtons; #endif - if (m_startPoint == KP_INVALID_POINT && - !m_shouldReleaseMouseButtons) - { + if (m_startPoint == KP_INVALID_POINT + && !m_shouldReleaseMouseButtons) { setUserMessage(QString()); } } @@ -372,16 +363,18 @@ // TODO: Are we checking for m_view == 0 often enough? Also an issue in KDE 3. kpViewScrollableContainer::kpViewScrollableContainer(QWidget *parent) - : QScrollArea(parent), - m_view(nullptr), m_overlay(new kpOverlay(viewport(), this)), - m_docResizingGrip (nullptr), - m_dragScrollTimer (new QTimer (this)), - m_zoomLevel (100), - m_scrollTimerRunOnce (false), - m_resizeRoundedLastViewX (-1), m_resizeRoundedLastViewY (-1), - m_resizeRoundedLastViewDX (0), m_resizeRoundedLastViewDY (0), - m_haveMovedFromOriginalDocSize (false) - + : QScrollArea(parent) + , m_view(nullptr) + , m_overlay(new kpOverlay(viewport(), this)) + , m_docResizingGrip(nullptr) + , m_dragScrollTimer(new QTimer(this)) + , m_zoomLevel(100) + , m_scrollTimerRunOnce(false) + , m_resizeRoundedLastViewX(-1) + , m_resizeRoundedLastViewY(-1) + , m_resizeRoundedLastViewDX(0) + , m_resizeRoundedLastViewDY(0) + , m_haveMovedFromOriginalDocSize(false) { // the base widget holding the documents view plus the resize grips setWidget(new QWidget(viewport())); @@ -394,80 +387,81 @@ m_rightGrip->setObjectName(QStringLiteral("Right Grip")); m_bottomRightGrip->setObjectName(QStringLiteral("BottomRight Grip")); - m_bottomGrip->hide (); - connectGripSignals (m_bottomGrip); - - m_rightGrip->hide (); - connectGripSignals (m_rightGrip); + m_bottomGrip->hide(); + connectGripSignals(m_bottomGrip); - m_bottomRightGrip->hide (); - connectGripSignals (m_bottomRightGrip); + m_rightGrip->hide(); + connectGripSignals(m_rightGrip); + m_bottomRightGrip->hide(); + connectGripSignals(m_bottomRightGrip); - connect (horizontalScrollBar(), &QScrollBar::valueChanged, - this, &kpViewScrollableContainer::slotContentsMoved); + connect(horizontalScrollBar(), &QScrollBar::valueChanged, + this, &kpViewScrollableContainer::slotContentsMoved); - connect (verticalScrollBar(), &QScrollBar::valueChanged, - this, &kpViewScrollableContainer::slotContentsMoved); + connect(verticalScrollBar(), &QScrollBar::valueChanged, + this, &kpViewScrollableContainer::slotContentsMoved); - connect (m_dragScrollTimer, &QTimer::timeout, this, [this]{slotDragScroll();}); + connect(m_dragScrollTimer, &QTimer::timeout, this, [this] { + slotDragScroll(); + }); m_overlay->hide(); } //--------------------------------------------------------------------- // protected -void kpViewScrollableContainer::connectGripSignals (kpGrip *grip) +void kpViewScrollableContainer::connectGripSignals(kpGrip *grip) { - connect (grip, &kpGrip::beganDraw, - this, &kpViewScrollableContainer::slotGripBeganDraw); + connect(grip, &kpGrip::beganDraw, + this, &kpViewScrollableContainer::slotGripBeganDraw); - connect (grip, &kpGrip::continuedDraw, - this, &kpViewScrollableContainer::slotGripContinuedDraw); + connect(grip, &kpGrip::continuedDraw, + this, &kpViewScrollableContainer::slotGripContinuedDraw); - connect (grip, &kpGrip::cancelledDraw, - this, &kpViewScrollableContainer::slotGripCancelledDraw); + connect(grip, &kpGrip::cancelledDraw, + this, &kpViewScrollableContainer::slotGripCancelledDraw); - connect (grip, &kpGrip::endedDraw, - this, &kpViewScrollableContainer::slotGripEndedDraw); + connect(grip, &kpGrip::endedDraw, + this, &kpViewScrollableContainer::slotGripEndedDraw); - connect (grip, &kpGrip::statusMessageChanged, - this, &kpViewScrollableContainer::slotGripStatusMessageChanged); + connect(grip, &kpGrip::statusMessageChanged, + this, &kpViewScrollableContainer::slotGripStatusMessageChanged); - connect (grip, &kpGrip::releasedAllButtons, - this, &kpViewScrollableContainer::recalculateStatusMessage); + connect(grip, &kpGrip::releasedAllButtons, + this, &kpViewScrollableContainer::recalculateStatusMessage); } //--------------------------------------------------------------------- // public -QSize kpViewScrollableContainer::newDocSize () const +QSize kpViewScrollableContainer::newDocSize() const { - return newDocSize (m_resizeRoundedLastViewDX, - m_resizeRoundedLastViewDY); + return newDocSize(m_resizeRoundedLastViewDX, + m_resizeRoundedLastViewDY); } //--------------------------------------------------------------------- // public -bool kpViewScrollableContainer::haveMovedFromOriginalDocSize () const +bool kpViewScrollableContainer::haveMovedFromOriginalDocSize() const { return m_haveMovedFromOriginalDocSize; } //--------------------------------------------------------------------- // public -QString kpViewScrollableContainer::statusMessage () const +QString kpViewScrollableContainer::statusMessage() const { return m_gripStatusMessage; } //--------------------------------------------------------------------- // public -void kpViewScrollableContainer::clearStatusMessage () +void kpViewScrollableContainer::clearStatusMessage() { #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER && 1 qCDebug(kpLogMisc) << "kpViewScrollableContainer::clearStatusMessage()"; @@ -480,230 +474,227 @@ //--------------------------------------------------------------------- // protected -QSize kpViewScrollableContainer::newDocSize (int viewDX, int viewDY) const +QSize kpViewScrollableContainer::newDocSize(int viewDX, int viewDY) const { if (!m_view) { return {}; } - if (!docResizingGrip ()) { + if (!docResizingGrip()) { return {}; } - const int docX = static_cast (m_view->transformViewToDocX (m_view->width () + viewDX)); - const int docY = static_cast (m_view->transformViewToDocY (m_view->height () + viewDY)); + const int docX = static_cast(m_view->transformViewToDocX(m_view->width() + viewDX)); + const int docY = static_cast(m_view->transformViewToDocY(m_view->height() + viewDY)); - return {qMax (1, docX), qMax (1, docY)}; + return { + qMax(1, docX), qMax(1, docY) + }; } //--------------------------------------------------------------------- // protected -void kpViewScrollableContainer::calculateDocResizingGrip () +void kpViewScrollableContainer::calculateDocResizingGrip() { - if (m_bottomRightGrip->isDrawing ()) { + if (m_bottomRightGrip->isDrawing()) { m_docResizingGrip = m_bottomRightGrip; - } - else if (m_bottomGrip->isDrawing ()) { + } else if (m_bottomGrip->isDrawing()) { m_docResizingGrip = m_bottomGrip; - } - else if (m_rightGrip->isDrawing ()) { + } else if (m_rightGrip->isDrawing()) { m_docResizingGrip = m_rightGrip; - } - else { + } else { m_docResizingGrip = nullptr; } } //--------------------------------------------------------------------- // protected -kpGrip *kpViewScrollableContainer::docResizingGrip () const +kpGrip *kpViewScrollableContainer::docResizingGrip() const { return m_docResizingGrip; } //--------------------------------------------------------------------- // protected -int kpViewScrollableContainer::bottomResizeLineWidth () const +int kpViewScrollableContainer::bottomResizeLineWidth() const { - if (!docResizingGrip ()) { + if (!docResizingGrip()) { return -1; } if (!m_view) { return -1; } - if (docResizingGrip ()->type () & kpGrip::Bottom) { - return qMax (m_view->zoomLevelY () / 100, 1); + if (docResizingGrip()->type() & kpGrip::Bottom) { + return qMax(m_view->zoomLevelY() / 100, 1); } return 1; } //--------------------------------------------------------------------- // protected -int kpViewScrollableContainer::rightResizeLineWidth () const +int kpViewScrollableContainer::rightResizeLineWidth() const { - if (!docResizingGrip ()) { + if (!docResizingGrip()) { return -1; } if (!m_view) { return -1; } - if (docResizingGrip ()->type () & kpGrip::Right) { - return qMax (m_view->zoomLevelX () / 100, 1); + if (docResizingGrip()->type() & kpGrip::Right) { + return qMax(m_view->zoomLevelX() / 100, 1); } return 1; } //--------------------------------------------------------------------- // protected -QRect kpViewScrollableContainer::bottomResizeLineRect () const +QRect kpViewScrollableContainer::bottomResizeLineRect() const { if (m_resizeRoundedLastViewX < 0 || m_resizeRoundedLastViewY < 0) { - return {}; + return {}; } - QRect visibleArea = QRect(QPoint(horizontalScrollBar()->value(),verticalScrollBar()->value()), viewport()->size()); + QRect visibleArea = QRect(QPoint(horizontalScrollBar()->value(), + verticalScrollBar()->value()), viewport()->size()); - return QRect (QPoint (0, - m_resizeRoundedLastViewY), - QPoint (m_resizeRoundedLastViewX - 1, - m_resizeRoundedLastViewY + bottomResizeLineWidth () - 1)).intersected(visibleArea); + return QRect(QPoint(0, + m_resizeRoundedLastViewY), + QPoint(m_resizeRoundedLastViewX - 1, + m_resizeRoundedLastViewY + bottomResizeLineWidth() - 1)).intersected( + visibleArea); } //--------------------------------------------------------------------- // protected -QRect kpViewScrollableContainer::rightResizeLineRect () const +QRect kpViewScrollableContainer::rightResizeLineRect() const { if (m_resizeRoundedLastViewX < 0 || m_resizeRoundedLastViewY < 0) { - return {}; + return {}; } - QRect visibleArea = QRect(QPoint(horizontalScrollBar()->value(),verticalScrollBar()->value()), viewport()->size()); + QRect visibleArea = QRect(QPoint(horizontalScrollBar()->value(), + verticalScrollBar()->value()), viewport()->size()); - return QRect (QPoint (m_resizeRoundedLastViewX, - 0), - QPoint (m_resizeRoundedLastViewX + rightResizeLineWidth () - 1, - m_resizeRoundedLastViewY - 1)).intersected(visibleArea); + return QRect(QPoint(m_resizeRoundedLastViewX, + 0), + QPoint(m_resizeRoundedLastViewX + rightResizeLineWidth() - 1, + m_resizeRoundedLastViewY - 1)).intersected(visibleArea); } //--------------------------------------------------------------------- // protected -QRect kpViewScrollableContainer::bottomRightResizeLineRect () const +QRect kpViewScrollableContainer::bottomRightResizeLineRect() const { if (m_resizeRoundedLastViewX < 0 || m_resizeRoundedLastViewY < 0) { - return {}; + return {}; } - QRect visibleArea = QRect(QPoint(horizontalScrollBar()->value(),verticalScrollBar()->value()), viewport()->size()); + QRect visibleArea = QRect(QPoint(horizontalScrollBar()->value(), + verticalScrollBar()->value()), viewport()->size()); - return QRect (QPoint (m_resizeRoundedLastViewX, - m_resizeRoundedLastViewY), - QPoint (m_resizeRoundedLastViewX + rightResizeLineWidth () - 1, - m_resizeRoundedLastViewY + bottomResizeLineWidth () - 1)).intersected(visibleArea); + return QRect(QPoint(m_resizeRoundedLastViewX, + m_resizeRoundedLastViewY), + QPoint(m_resizeRoundedLastViewX + rightResizeLineWidth() - 1, + m_resizeRoundedLastViewY + bottomResizeLineWidth() - 1)).intersected( + visibleArea); } //--------------------------------------------------------------------- // private -QRect kpViewScrollableContainer::mapViewToViewport (const QRect &viewRect) +QRect kpViewScrollableContainer::mapViewToViewport(const QRect &viewRect) { - if (!viewRect.isValid ()) { + if (!viewRect.isValid()) { return {}; } QRect ret = viewRect; - ret.translate (-horizontalScrollBar()->value() - viewport()->x(), -verticalScrollBar()->value() - viewport()->y()); + ret.translate(-horizontalScrollBar()->value() - viewport()->x(), + -verticalScrollBar()->value() - viewport()->y()); return ret; } //--------------------------------------------------------------------- -void kpViewScrollableContainer::drawResizeLines () +void kpViewScrollableContainer::drawResizeLines() { - static const char *stipple[] = - { - "8 8 2 1", - ". c #000000", - "# c #ffffff", - "....####", - "....####", - "....####", - "....####", - "####....", - "####....", - "####....", - "####...." - }; - - QPainter p(m_overlay); - p.setBackground(QPixmap(stipple)); - - const QRect rightRect = rightResizeLineRect(); - if ( rightRect.isValid() ) - { - QRect rect = mapViewToViewport(rightRect); - p.setBrushOrigin(rect.x(), rect.y()); - p.eraseRect(rect); - } - - const QRect bottomRect = bottomResizeLineRect(); - if ( bottomRect.isValid() ) - { - QRect rect = mapViewToViewport(bottomRect); - p.setBrushOrigin(rect.x(), rect.y()); - p.eraseRect(rect); - } - - const QRect bottomRightRect = bottomRightResizeLineRect (); - if ( bottomRightRect.isValid() ) - { - QRect rect = mapViewToViewport(bottomRightRect); - p.setBrushOrigin(rect.x(), rect.y()); - p.eraseRect(rect); - } + static const char *stipple[] = + { + "8 8 2 1", + ". c #000000", + "# c #ffffff", + "....####", + "....####", + "....####", + "....####", + "####....", + "####....", + "####....", + "####...." + }; + + QPainter p(m_overlay); + p.setBackground(QPixmap(stipple)); + + const QRect rightRect = rightResizeLineRect(); + if (rightRect.isValid()) { + QRect rect = mapViewToViewport(rightRect); + p.setBrushOrigin(rect.x(), rect.y()); + p.eraseRect(rect); + } + + const QRect bottomRect = bottomResizeLineRect(); + if (bottomRect.isValid()) { + QRect rect = mapViewToViewport(bottomRect); + p.setBrushOrigin(rect.x(), rect.y()); + p.eraseRect(rect); + } + + const QRect bottomRightRect = bottomRightResizeLineRect(); + if (bottomRightRect.isValid()) { + QRect rect = mapViewToViewport(bottomRightRect); + p.setBrushOrigin(rect.x(), rect.y()); + p.eraseRect(rect); + } } //--------------------------------------------------------------------- // protected -void kpViewScrollableContainer::updateResizeLines (int viewX, int viewY, - int viewDX, int viewDY) +void kpViewScrollableContainer::updateResizeLines(int viewX, int viewY, int viewDX, int viewDY) { #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER && 0 qCDebug(kpLogMisc) << "kpViewScrollableContainer::updateResizeLines(" - << viewX << "," << viewY << ")" - << " oldViewX=" << m_resizeRoundedLastViewX - << " oldViewY=" << m_resizeRoundedLastViewY - << " viewDX=" << viewDX - << " viewDY=" << viewDY; + << viewX << "," << viewY << ")" + << " oldViewX=" << m_resizeRoundedLastViewX + << " oldViewY=" << m_resizeRoundedLastViewY + << " viewDX=" << viewDX + << " viewDY=" << viewDY; #endif + if (viewX >= 0 && viewY >= 0) { + m_resizeRoundedLastViewX + = static_cast(m_view->transformDocToViewX(m_view->transformViewToDocX(viewX))); - if (viewX >= 0 && viewY >= 0) - { - m_resizeRoundedLastViewX = - static_cast (m_view->transformDocToViewX (m_view->transformViewToDocX (viewX))); - - m_resizeRoundedLastViewY = - static_cast (m_view->transformDocToViewY (m_view->transformViewToDocY (viewY))); + m_resizeRoundedLastViewY + = static_cast(m_view->transformDocToViewY(m_view->transformViewToDocY(viewY))); m_resizeRoundedLastViewDX = viewDX; m_resizeRoundedLastViewDY = viewDY; - } - else - { + } else { m_resizeRoundedLastViewX = -1; m_resizeRoundedLastViewY = -1; @@ -717,7 +708,7 @@ //--------------------------------------------------------------------- // protected slot -void kpViewScrollableContainer::slotGripBeganDraw () +void kpViewScrollableContainer::slotGripBeganDraw() { if (!m_view) { return; @@ -728,174 +719,166 @@ m_overlay->show(); m_overlay->raise(); // make it top-most - calculateDocResizingGrip (); + calculateDocResizingGrip(); m_haveMovedFromOriginalDocSize = false; - updateResizeLines (m_view->width (), m_view->height (), - 0/*viewDX*/, 0/*viewDY*/); + updateResizeLines(m_view->width(), m_view->height(), + 0 /*viewDX*/, 0 /*viewDY*/); - emit beganDocResize (); + emit beganDocResize(); } //--------------------------------------------------------------------- // protected slot -void kpViewScrollableContainer::slotGripContinuedDraw (int inViewDX, int inViewDY, - bool dueToDragScroll) +void kpViewScrollableContainer::slotGripContinuedDraw(int inViewDX, int inViewDY, + bool dueToDragScroll) { int viewDX = inViewDX, viewDY = inViewDY; #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER qCDebug(kpLogMisc) << "kpViewScrollableContainer::slotGripContinuedDraw(" - << viewDX << "," << viewDY << ") size=" - << newDocSize (viewDX, viewDY) - << " dueToDragScroll=" << dueToDragScroll; + << viewDX << "," << viewDY << ") size=" + << newDocSize(viewDX, viewDY) + << " dueToDragScroll=" << dueToDragScroll; #endif if (!m_view) { return; } - if (!dueToDragScroll && - beginDragScroll(m_view->zoomLevelX ())) - { - const QPoint newViewDeltaPoint = docResizingGrip ()->viewDeltaPoint (); - viewDX = newViewDeltaPoint.x (); - viewDY = newViewDeltaPoint.y (); + if (!dueToDragScroll + && beginDragScroll(m_view->zoomLevelX())) { + const QPoint newViewDeltaPoint = docResizingGrip()->viewDeltaPoint(); + viewDX = newViewDeltaPoint.x(); + viewDY = newViewDeltaPoint.y(); #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER qCDebug(kpLogMisc) << "\tdrag scrolled - new view delta point=" - << newViewDeltaPoint; + << newViewDeltaPoint; #endif } m_haveMovedFromOriginalDocSize = true; - updateResizeLines (qMax (1, qMax (m_view->width () + viewDX, static_cast (m_view->transformDocToViewX (1)))), - qMax (1, qMax (m_view->height () + viewDY, static_cast (m_view->transformDocToViewY (1)))), - viewDX, viewDY); + updateResizeLines(qMax(1, + qMax(m_view->width() + viewDX, + static_cast(m_view->transformDocToViewX(1)))), + qMax(1, + qMax(m_view->height() + viewDY, + static_cast(m_view->transformDocToViewY(1)))), + viewDX, viewDY); - emit continuedDocResize (newDocSize ()); + emit continuedDocResize(newDocSize()); } //--------------------------------------------------------------------- // protected slot -void kpViewScrollableContainer::slotGripCancelledDraw () +void kpViewScrollableContainer::slotGripCancelledDraw() { m_haveMovedFromOriginalDocSize = false; - updateResizeLines (-1, -1, 0, 0); + updateResizeLines(-1, -1, 0, 0); - calculateDocResizingGrip (); + calculateDocResizingGrip(); - emit cancelledDocResize (); + emit cancelledDocResize(); - endDragScroll (); + endDragScroll(); m_overlay->hide(); } //--------------------------------------------------------------------- // protected slot -void kpViewScrollableContainer::slotGripEndedDraw (int viewDX, int viewDY) +void kpViewScrollableContainer::slotGripEndedDraw(int viewDX, int viewDY) { #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER qCDebug(kpLogMisc) << "kpViewScrollableContainer::slotGripEndedDraw(" - << viewDX << "," << viewDY << ") size=" - << newDocSize (viewDX, viewDY); + << viewDX << "," << viewDY << ") size=" + << newDocSize(viewDX, viewDY); #endif if (!m_view) { return; } - const QSize newSize = newDocSize (viewDX, viewDY); + const QSize newSize = newDocSize(viewDX, viewDY); m_haveMovedFromOriginalDocSize = false; // must erase lines before view size changes - updateResizeLines (-1, -1, 0, 0); + updateResizeLines(-1, -1, 0, 0); - calculateDocResizingGrip (); + calculateDocResizingGrip(); - emit endedDocResize (newSize); + emit endedDocResize(newSize); - endDragScroll (); + endDragScroll(); m_overlay->hide(); } //--------------------------------------------------------------------- // protected slot -void kpViewScrollableContainer::slotGripStatusMessageChanged (const QString &string) +void kpViewScrollableContainer::slotGripStatusMessageChanged(const QString &string) { if (string == m_gripStatusMessage) { return; } m_gripStatusMessage = string; - emit statusMessageChanged (string); + emit statusMessageChanged(string); } //--------------------------------------------------------------------- // public slot -void kpViewScrollableContainer::recalculateStatusMessage () +void kpViewScrollableContainer::recalculateStatusMessage() { #if DEBUG_KP_VIEW_SCROLLABLE_CONTAINER qCDebug(kpLogMisc) << "kpViewScrollabelContainer::recalculateStatusMessage()"; - qCDebug(kpLogMisc) << "\tQCursor::pos=" << QCursor::pos () - << " global visibleRect=" - << kpWidgetMapper::toGlobal (this, - QRect(0, 0, viewport->width(), viewport->height())); + qCDebug(kpLogMisc) << "\tQCursor::pos=" << QCursor::pos() + << " global visibleRect=" + << kpWidgetMapper::toGlobal(this, + QRect(0, 0, viewport->width(), viewport->height())); #endif // HACK: After dragging to a new size, handles move so that they are now // under the mouse pointer but no mouseMoveEvent() is generated for // any grip. This also handles the case of canceling over any // grip. // - if (kpWidgetMapper::toGlobal (this, - QRect(0, 0, viewport()->width(), viewport()->height())) - .contains (QCursor::pos ())) - { - if ( m_bottomRightGrip->containsCursor() ) - { - m_bottomRightGrip->setUserMessage (i18n ("Left drag the handle to resize the image.")); - } - else if ( m_bottomGrip->containsCursor() ) - { - m_bottomGrip->setUserMessage (i18n ("Left drag the handle to resize the image.")); + if (kpWidgetMapper::toGlobal(this, + QRect(0, 0, viewport()->width(), viewport()->height())) + .contains(QCursor::pos())) { + if (m_bottomRightGrip->containsCursor()) { + m_bottomRightGrip->setUserMessage(i18n("Left drag the handle to resize the image.")); + } else if (m_bottomGrip->containsCursor()) { + m_bottomGrip->setUserMessage(i18n("Left drag the handle to resize the image.")); + } else if (m_rightGrip->containsCursor()) { + m_rightGrip->setUserMessage(i18n("Left drag the handle to resize the image.")); + } else { + clearStatusMessage(); } - else if ( m_rightGrip->containsCursor() ) - { - m_rightGrip->setUserMessage (i18n ("Left drag the handle to resize the image.")); - } - else - { - clearStatusMessage (); - } - } - else - { - clearStatusMessage (); + } else { + clearStatusMessage(); } } //--------------------------------------------------------------------- // protected slot -void kpViewScrollableContainer::slotContentsMoved () +void kpViewScrollableContainer::slotContentsMoved() { - kpGrip *grip = docResizingGrip (); - if (grip) - { - grip->mouseMovedTo (grip->mapFromGlobal (QCursor::pos ()), - true/*moved due to drag scroll*/); + kpGrip *grip = docResizingGrip(); + if (grip) { + grip->mouseMovedTo(grip->mapFromGlobal(QCursor::pos()), + true /*moved due to drag scroll*/); } m_overlay->move(viewport()->pos()); @@ -907,101 +890,97 @@ //--------------------------------------------------------------------- // protected -void kpViewScrollableContainer::disconnectViewSignals () +void kpViewScrollableContainer::disconnectViewSignals() { - disconnect (m_view, - static_cast(&kpView::sizeChanged), - this, &kpViewScrollableContainer::updateGrips); + disconnect(m_view, + static_cast(&kpView::sizeChanged), + this, &kpViewScrollableContainer::updateGrips); - disconnect (m_view, &kpView::destroyed, - this, &kpViewScrollableContainer::slotViewDestroyed); + disconnect(m_view, &kpView::destroyed, + this, &kpViewScrollableContainer::slotViewDestroyed); } //--------------------------------------------------------------------- // protected -void kpViewScrollableContainer::connectViewSignals () +void kpViewScrollableContainer::connectViewSignals() { - connect (m_view, - static_cast(&kpView::sizeChanged), - this, &kpViewScrollableContainer::updateGrips); + connect(m_view, + static_cast(&kpView::sizeChanged), + this, &kpViewScrollableContainer::updateGrips); - connect (m_view, &kpView::destroyed, - this, &kpViewScrollableContainer::slotViewDestroyed); + connect(m_view, &kpView::destroyed, + this, &kpViewScrollableContainer::slotViewDestroyed); } //--------------------------------------------------------------------- // public -kpView *kpViewScrollableContainer::view () const +kpView *kpViewScrollableContainer::view() const { return m_view; } //--------------------------------------------------------------------- // public -void kpViewScrollableContainer::setView (kpView *view) +void kpViewScrollableContainer::setView(kpView *view) { if (m_view == view) { return; } - if (m_view) - { - disconnectViewSignals (); + if (m_view) { + disconnectViewSignals(); } m_view = view; - if ( m_view ) - { - m_view->setParent(widget()); - m_view->show(); + if (m_view) { + m_view->setParent(widget()); + m_view->show(); } - updateGrips (); + updateGrips(); - if (m_view) - { - connectViewSignals (); + if (m_view) { + connectViewSignals(); } } //--------------------------------------------------------------------- // public slot -void kpViewScrollableContainer::updateGrips () +void kpViewScrollableContainer::updateGrips() { - if (m_view) - { - widget()->resize(m_view->size() + m_bottomRightGrip->size()); + if (m_view) { + widget()->resize(m_view->size() + m_bottomRightGrip->size()); - // to make the grip more easily "touchable" make it as high as the view - m_rightGrip->setFixedHeight(m_view->height()); - m_rightGrip->move(m_view->width(), 0); + // to make the grip more easily "touchable" make it as high as the view + m_rightGrip->setFixedHeight(m_view->height()); + m_rightGrip->move(m_view->width(), 0); - // to make the grip more easily "touchable" make it as wide as the view - m_bottomGrip->setFixedWidth(m_view->width()); - m_bottomGrip->move(0, m_view->height ()); + // to make the grip more easily "touchable" make it as wide as the view + m_bottomGrip->setFixedWidth(m_view->width()); + m_bottomGrip->move(0, m_view->height()); - m_bottomRightGrip->move(m_view->width(), m_view->height()); + m_bottomRightGrip->move(m_view->width(), m_view->height()); } - m_bottomGrip->setHidden (m_view == nullptr); - m_rightGrip->setHidden (m_view == nullptr); - m_bottomRightGrip->setHidden (m_view == nullptr); + m_bottomGrip->setHidden(m_view == nullptr); + m_rightGrip->setHidden(m_view == nullptr); + m_bottomRightGrip->setHidden(m_view == nullptr); - recalculateStatusMessage (); + recalculateStatusMessage(); } //--------------------------------------------------------------------- // protected slot -void kpViewScrollableContainer::slotViewDestroyed () +void kpViewScrollableContainer::slotViewDestroyed() { m_view = nullptr; - updateGrips (); + updateGrips(); } //--------------------------------------------------------------------- @@ -1015,31 +994,26 @@ m_zoomLevel = zoomLevel; - const QPoint p = mapFromGlobal (QCursor::pos ()); + const QPoint p = mapFromGlobal(QCursor::pos()); bool stopDragScroll = true; bool scrolled = false; - if (!noDragScrollRect ().contains (p)) - { - if (m_dragScrollTimer->isActive ()) - { - if (m_scrollTimerRunOnce) - { - scrolled = slotDragScroll (); + if (!noDragScrollRect().contains(p)) { + if (m_dragScrollTimer->isActive()) { + if (m_scrollTimerRunOnce) { + scrolled = slotDragScroll(); } - } - else - { + } else { m_scrollTimerRunOnce = false; - m_dragScrollTimer->start (DragScrollInitialInterval); + m_dragScrollTimer->start(DragScrollInitialInterval); } stopDragScroll = false; } if (stopDragScroll) { - m_dragScrollTimer->stop (); + m_dragScrollTimer->stop(); } if (didSomething) { @@ -1055,26 +1029,25 @@ bool kpViewScrollableContainer::beginDragScroll(int zoomLevel) { return beginDragScroll(zoomLevel, - nullptr/*don't want scrolled notification*/); + nullptr /*don't want scrolled notification*/); } //--------------------------------------------------------------------- // public slot -bool kpViewScrollableContainer::endDragScroll () +bool kpViewScrollableContainer::endDragScroll() { - if (m_dragScrollTimer->isActive ()) - { - m_dragScrollTimer->stop (); + if (m_dragScrollTimer->isActive()) { + m_dragScrollTimer->stop(); return true; } return false; } //--------------------------------------------------------------------- -static int distanceFromRectToMultiplier (int dist) +static int distanceFromRectToMultiplier(int dist) { if (dist < 0) { return 0; @@ -1094,71 +1067,62 @@ //--------------------------------------------------------------------- // protected slot -bool kpViewScrollableContainer::slotDragScroll (bool *didSomething) +bool kpViewScrollableContainer::slotDragScroll(bool *didSomething) { bool scrolled = false; if (didSomething) { *didSomething = false; } - - const QRect rect = noDragScrollRect (); - const QPoint pos = mapFromGlobal (QCursor::pos ()); + const QRect rect = noDragScrollRect(); + const QPoint pos = mapFromGlobal(QCursor::pos()); int dx = 0, dy = 0; int dxMultiplier = 0, dyMultiplier = 0; - if (pos.x () < rect.left ()) - { + if (pos.x() < rect.left()) { dx = -DragScrollNumPixels; - dxMultiplier = distanceFromRectToMultiplier (rect.left () - pos.x ()); - } - else if (pos.x () > rect.right ()) - { + dxMultiplier = distanceFromRectToMultiplier(rect.left() - pos.x()); + } else if (pos.x() > rect.right()) { dx = +DragScrollNumPixels; - dxMultiplier = distanceFromRectToMultiplier (pos.x () - rect.right ()); + dxMultiplier = distanceFromRectToMultiplier(pos.x() - rect.right()); } - if (pos.y () < rect.top ()) - { + if (pos.y() < rect.top()) { dy = -DragScrollNumPixels; - dyMultiplier = distanceFromRectToMultiplier (rect.top () - pos.y ()); - } - else if (pos.y () > rect.bottom ()) - { + dyMultiplier = distanceFromRectToMultiplier(rect.top() - pos.y()); + } else if (pos.y() > rect.bottom()) { dy = +DragScrollNumPixels; - dyMultiplier = distanceFromRectToMultiplier (pos.y () - rect.bottom ()); + dyMultiplier = distanceFromRectToMultiplier(pos.y() - rect.bottom()); } dx *= dxMultiplier;// * qMax (1, m_zoomLevel / 100); dy *= dyMultiplier;// * qMax (1, m_zoomLevel / 100); - if (dx || dy) - { - const int oldContentsX = horizontalScrollBar()->value (), - oldContentsY = verticalScrollBar()->value (); + if (dx || dy) { + const int oldContentsX = horizontalScrollBar()->value(), + oldContentsY = verticalScrollBar()->value(); horizontalScrollBar()->setValue(oldContentsX + dx); verticalScrollBar()->setValue(oldContentsY + dy); - scrolled = (oldContentsX != horizontalScrollBar()->value () || - oldContentsY != verticalScrollBar()->value ()); + scrolled = (oldContentsX != horizontalScrollBar()->value() + || oldContentsY != verticalScrollBar()->value()); - if (scrolled) - { - QRegion region = QRect (horizontalScrollBar()->value (), verticalScrollBar()->value (), - viewport()->width(), viewport()->height()); - region -= QRect (oldContentsX, oldContentsY, - viewport()->width(), viewport()->height()); + if (scrolled) { + QRegion region = QRect(horizontalScrollBar()->value(), verticalScrollBar()->value(), + viewport()->width(), viewport()->height()); + region -= QRect(oldContentsX, oldContentsY, + viewport()->width(), viewport()->height()); // Repaint newly exposed region immediately to reduce tearing // of scrollView. - m_view->repaint (region); + m_view->repaint(region); } } - m_dragScrollTimer->start (DragScrollInterval); + m_dragScrollTimer->start(DragScrollInterval); m_scrollTimerRunOnce = true; if (didSomething) { @@ -1168,41 +1132,41 @@ return scrolled; } - //--------------------------------------------------------------------- // protected virtual -void kpViewScrollableContainer::wheelEvent (QWheelEvent *e) +void kpViewScrollableContainer::wheelEvent(QWheelEvent *e) { - e->ignore (); + e->ignore(); if (m_view) { - m_view->wheelEvent (e); + m_view->wheelEvent(e); } - if ( !e->isAccepted() ) { + if (!e->isAccepted()) { QScrollArea::wheelEvent(e); } } //--------------------------------------------------------------------------------- -QRect kpViewScrollableContainer::noDragScrollRect () const +QRect kpViewScrollableContainer::noDragScrollRect() const { - return {DragScrollLeftTopMargin, DragScrollLeftTopMargin, - width () - DragScrollLeftTopMargin - DragScrollRightBottomMargin, - height () - DragScrollLeftTopMargin - DragScrollRightBottomMargin}; + return { + DragScrollLeftTopMargin, DragScrollLeftTopMargin, + width() - DragScrollLeftTopMargin - DragScrollRightBottomMargin, + height() - DragScrollLeftTopMargin - DragScrollRightBottomMargin + }; } //--------------------------------------------------------------------- // protected virtual [base QScrollView] -void kpViewScrollableContainer::resizeEvent (QResizeEvent *e) +void kpViewScrollableContainer::resizeEvent(QResizeEvent *e) { - QScrollArea::resizeEvent (e); + QScrollArea::resizeEvent(e); - emit resized (); + emit resized(); } //--------------------------------------------------------------------- - diff --git a/layers/selections/image/kpAbstractImageSelection.h b/layers/selections/image/kpAbstractImageSelection.h --- a/layers/selections/image/kpAbstractImageSelection.h +++ b/layers/selections/image/kpAbstractImageSelection.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,16 +24,13 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpAbstractImageSelection_H #define kpAbstractImageSelection_H - #include "kpImageSelectionTransparency.h" #include "layers/selections/kpAbstractSelection.h" #include "imagelib/kpImage.h" - // // An abstract selection with optional image content and background // subtraction. If there is image content, it is known as a "floating @@ -63,61 +59,57 @@ // class kpAbstractImageSelection : public kpAbstractSelection { -Q_OBJECT + Q_OBJECT // // Initialization // protected: // (Call these in subclass constructors) - kpAbstractImageSelection (const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + kpAbstractImageSelection (const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); kpAbstractImageSelection (const QRect &rect, - const kpImage &baseImage = kpImage (), - const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + const kpImage &baseImage = kpImage(), const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); - kpAbstractImageSelection (const QRect &rect, - const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + kpAbstractImageSelection (const QRect &rect, const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); // (Call this in subclass implementations of operator=) - kpAbstractImageSelection &operator= (const kpAbstractImageSelection &rhs); + kpAbstractImageSelection &operator=(const kpAbstractImageSelection &rhs); public: // (Covariant return-type specialization of superclass pure virtual method) - kpAbstractImageSelection *clone () const override = 0; + kpAbstractImageSelection *clone() const override = 0; ~kpAbstractImageSelection () override; - // // Marshalling // public: // You must override this if you have extra serializable fields. // Remember to call this base implementation before your code. - bool readFromStream (QDataStream &stream) override; + bool readFromStream(QDataStream &stream) override; // You must override this if you have extra serializable fields. // Remember to call this base implementation before your code. - void writeToStream (QDataStream &stream) const override; - + void writeToStream(QDataStream &stream) const override; // // General Queries // public: - QString name () const override; + QString name() const override; // You must override this, if you have extra fields that take a // non-constant amount of space, and add the size returned by this // implementation. - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; // Same as virtual size() (it even calls it) but subtracts the size of the // baseImage(). @@ -137,17 +129,15 @@ // started removing the old kpSelection::setPixmap(QPixmap()) // (now kpAbstractImageSelection::setBaseImage(kpImage()) or // kpAbstractImageSelection::deleteContent()) space saving hack. - kpCommandSize::SizeType sizeWithoutImage () const; - + kpCommandSize::SizeType sizeWithoutImage() const; // // Dimensions // public: - int minimumWidth () const override; - int minimumHeight () const override; - + int minimumWidth() const override; + int minimumHeight() const override; // // Shape Mask @@ -171,7 +161,7 @@ // shapeRegion(). // // TODO: Try to get rid of this method since it's slow. - virtual QBitmap shapeBitmap (bool nullForRectangular = false) const; + virtual QBitmap shapeBitmap(bool nullForRectangular = false) const; // Returns the region corresponding to the shape of the selection // e.g. elliptical region for an elliptical selection. @@ -182,85 +172,79 @@ // shapeRegion(). // // OPT: QRegion is probably incredibly slow - cache - virtual QRegion shapeRegion () const = 0; + virtual QRegion shapeRegion() const = 0; // Returns the given with the pixels outside of the selection's // shape set to transparent. // // Very slow. // // ASSUMPTION: The image has the same dimensions as the selection. - kpImage givenImageMaskedByShape (const kpImage &image) const; - + kpImage givenImageMaskedByShape(const kpImage &image) const; // // Content - Base Image // public: // Returns whether there's a non-null base image. - bool hasContent () const override; + bool hasContent() const override; - void deleteContent () override; + void deleteContent() override; public: - kpImage baseImage () const; - void setBaseImage (const kpImage &baseImage); - + kpImage baseImage() const; + void setBaseImage(const kpImage &baseImage); // // Background Subtraction // public: - kpImageSelectionTransparency transparency () const; + kpImageSelectionTransparency transparency() const; // Returns whether or not the selection changed due to setting the // transparency info. If is set, // it will try harder to return false (although the check is // expensive). - bool setTransparency (const kpImageSelectionTransparency &transparency, - bool checkTransparentPixmapChanged = false); + bool setTransparency(const kpImageSelectionTransparency &transparency, + bool checkTransparentPixmapChanged = false); private: // Updates the selection transparency (a.k.a. background subtraction) mask // so that transparentImage() will work. // // Called when the base image or selection transparency changes. - void recalculateTransparencyMaskCache (); + void recalculateTransparencyMaskCache(); public: // Returns baseImage() after applying kpImageSelectionTransparency - kpImage transparentImage () const; - + kpImage transparentImage() const; // // Mutation - Effects // public: // Overwrites the base image with the selection's shape (e.g. ellipse) // filled in with . See shapeBitmap(). - void fill (const kpColor &color); - - virtual void flip (bool horiz, bool vert); + void fill(const kpColor &color); + virtual void flip(bool horiz, bool vert); // // Rendering // public: // (using transparent image) - void paint (QImage *destPixmap, const QRect &docRect) const override; + void paint(QImage *destPixmap, const QRect &docRect) const override; // (using base image) - void paintWithBaseImage (QImage *destPixmap, const QRect &docRect) const; - + void paintWithBaseImage(QImage *destPixmap, const QRect &docRect) const; private: - struct kpAbstractImageSelectionPrivate * const d; + struct kpAbstractImageSelectionPrivate *const d; }; - #endif // kpAbstractImageSelection_H diff --git a/layers/selections/image/kpAbstractImageSelection.cpp b/layers/selections/image/kpAbstractImageSelection.cpp --- a/layers/selections/image/kpAbstractImageSelection.cpp +++ b/layers/selections/image/kpAbstractImageSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION 0 - #include "layers/selections/image/kpAbstractImageSelection.h" #include @@ -42,17 +39,16 @@ // In other words, this is the precondition for .setBaseImage(width () && - baseImage.height () == sel->height ()); + return baseImage.width() == sel->width() + && baseImage.height() == sel->height(); } //--------------------------------------------------------------------- @@ -72,47 +68,46 @@ // protected kpAbstractImageSelection::kpAbstractImageSelection ( - const kpImageSelectionTransparency &transparency) - : kpAbstractSelection (), - d (new kpAbstractImageSelectionPrivate ()) + const kpImageSelectionTransparency &transparency) + : kpAbstractSelection() + , d(new kpAbstractImageSelectionPrivate()) { - setTransparency (transparency); + setTransparency(transparency); } //--------------------------------------------------------------------- // protected -kpAbstractImageSelection::kpAbstractImageSelection (const QRect &rect, - const kpImage &baseImage, - const kpImageSelectionTransparency &transparency) - : kpAbstractSelection (rect), - d (new kpAbstractImageSelectionPrivate ()) +kpAbstractImageSelection::kpAbstractImageSelection (const QRect &rect, const kpImage &baseImage, + const kpImageSelectionTransparency &transparency) + : kpAbstractSelection(rect) + , d(new kpAbstractImageSelectionPrivate()) { // This also checks that and have compatible // relative dimensions. - setBaseImage (baseImage); + setBaseImage(baseImage); - setTransparency (transparency); + setTransparency(transparency); } //--------------------------------------------------------------------- // protected kpAbstractImageSelection::kpAbstractImageSelection (const QRect &rect, - const kpImageSelectionTransparency &transparency) - : kpAbstractSelection (rect), - d (new kpAbstractImageSelectionPrivate ()) + const kpImageSelectionTransparency &transparency) + : kpAbstractSelection(rect) + , d(new kpAbstractImageSelectionPrivate()) { - setTransparency (transparency); + setTransparency(transparency); } //--------------------------------------------------------------------- // protected -kpAbstractImageSelection &kpAbstractImageSelection::operator= ( - const kpAbstractImageSelection &rhs) +kpAbstractImageSelection &kpAbstractImageSelection::operator=( + const kpAbstractImageSelection &rhs) { - kpAbstractSelection::operator= (rhs); + kpAbstractSelection::operator=(rhs); d->baseImage = rhs.d->baseImage; @@ -133,35 +128,33 @@ //--------------------------------------------------------------------- // public virtual [base kpAbstractSelection] -bool kpAbstractImageSelection::readFromStream (QDataStream &stream) +bool kpAbstractImageSelection::readFromStream(QDataStream &stream) { - if (!kpAbstractSelection::readFromStream (stream )) { + if (!kpAbstractSelection::readFromStream(stream)) { return false; } QImage qimage; stream >> qimage; #if DEBUG_KP_SELECTION && 1 - qCDebug(kpLogLayers) << "\timage: w=" << qimage.width () << " h=" << qimage.height () - << " depth=" << qimage.depth (); + qCDebug(kpLogLayers) << "\timage: w=" << qimage.width() << " h=" << qimage.height() + << " depth=" << qimage.depth(); #endif - if (!qimage.isNull ()) - { + if (!qimage.isNull()) { // Image size does not match the selection's dimensions? // This call only accesses our superclass' fields, which have already // been read in. - if (!::CanSetBaseImageTo (this, qimage)) - { + if (!::CanSetBaseImageTo(this, qimage)) { return false; } d->baseImage = qimage; } // (was just a selection border in the clipboard, even though KolourPaint's // GUI doesn't allow you to copy such a thing into the clipboard) else { - d->baseImage = kpImage (); + d->baseImage = kpImage(); } // TODO: Reset transparency mask? @@ -175,124 +168,121 @@ //--------------------------------------------------------------------- // public virtual [base kpAbstractSelection] -void kpAbstractImageSelection::writeToStream (QDataStream &stream) const +void kpAbstractImageSelection::writeToStream(QDataStream &stream) const { - kpAbstractSelection::writeToStream (stream); + kpAbstractSelection::writeToStream(stream); - if (!d->baseImage.isNull ()) - { + if (!d->baseImage.isNull()) { const QImage image = d->baseImage; #if DEBUG_KP_SELECTION && 1 - qCDebug(kpLogLayers) << "\twrote image rect=" << image.rect (); + qCDebug(kpLogLayers) << "\twrote image rect=" << image.rect(); #endif stream << image; - } - else - { + } else { #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "\twrote no image because no pixmap"; #endif - stream << QImage (); + stream << QImage(); } } //--------------------------------------------------------------------- // public virtual [kpAbstractSelection] -QString kpAbstractImageSelection::name () const +QString kpAbstractImageSelection::name() const { - return i18n ("Selection"); + return i18n("Selection"); } //--------------------------------------------------------------------- // public virtual [base kpAbstractSelection] -kpCommandSize::SizeType kpAbstractImageSelection::size () const +kpCommandSize::SizeType kpAbstractImageSelection::size() const { - return kpAbstractSelection::size () + - kpCommandSize::ImageSize (d->baseImage) + - (d->transparencyMaskCache.width() * d->transparencyMaskCache.height()) / 8; + return kpAbstractSelection::size() + +kpCommandSize::ImageSize(d->baseImage) + +(d->transparencyMaskCache.width() * d->transparencyMaskCache.height()) / 8; } //--------------------------------------------------------------------- // public -kpCommandSize::SizeType kpAbstractImageSelection::sizeWithoutImage () const +kpCommandSize::SizeType kpAbstractImageSelection::sizeWithoutImage() const { - return (size () - kpCommandSize::ImageSize (d->baseImage)); + return size() - kpCommandSize::ImageSize(d->baseImage); } //--------------------------------------------------------------------- // public virtual [kpAbstractSelection] -int kpAbstractImageSelection::minimumWidth () const +int kpAbstractImageSelection::minimumWidth() const { return 1; } //--------------------------------------------------------------------- // public virtual [kpAbstractSelection] -int kpAbstractImageSelection::minimumHeight () const +int kpAbstractImageSelection::minimumHeight() const { return 1; } //--------------------------------------------------------------------- // public virtual -QBitmap kpAbstractImageSelection::shapeBitmap (bool nullForRectangular) const +QBitmap kpAbstractImageSelection::shapeBitmap(bool nullForRectangular) const { - (void) nullForRectangular; + (void)nullForRectangular; - Q_ASSERT (boundingRect ().isValid ()); + Q_ASSERT(boundingRect().isValid()); - QBitmap maskBitmap (width (), height ()); - maskBitmap.fill (Qt::color0/*transparent*/); + QBitmap maskBitmap(width(), height()); + maskBitmap.fill(Qt::color0 /*transparent*/); { QPainter painter(&maskBitmap); - painter.setPen (Qt::color1/*opaque*/); - painter.setBrush (Qt::color1/*opaque*/); + painter.setPen(Qt::color1 /*opaque*/); + painter.setBrush(Qt::color1 /*opaque*/); - QPolygon points = calculatePoints (); - points.translate (-x (), -y ()); + QPolygon points = calculatePoints(); + points.translate(-x(), -y()); // Unlike QPainter::drawRect(), this draws the points literally // without being 1 pixel wider and higher. This requires a QPen // or it will draw 1 pixel narrower and shorter. - painter.drawPolygon (points, Qt::OddEvenFill); + painter.drawPolygon(points, Qt::OddEvenFill); } return maskBitmap; } //--------------------------------------------------------------------- // public -kpImage kpAbstractImageSelection::givenImageMaskedByShape (const kpImage &image) const +kpImage kpAbstractImageSelection::givenImageMaskedByShape(const kpImage &image) const { #if DEBUG_KP_SELECTION qCDebug(kpLogLayers) << "kpAbstractImageSelection::givenImageMaskedByShape() boundingRect=" - << boundingRect () << endl; + << boundingRect() << endl; #endif - Q_ASSERT (image.width () == width () && image.height () == height ()); + Q_ASSERT(image.width() == width() && image.height() == height()); - if (isRectangular ()) { + if (isRectangular()) { return image; } - const QRegion mRegion = shapeRegion ().translated (-topLeft ()); + const QRegion mRegion = shapeRegion().translated(-topLeft()); #if DEBUG_KP_SELECTION - qCDebug(kpLogLayers) << "\tshapeRegion=" << shapeRegion () - << " [rect=" << shapeRegion ().boundingRect () << "]" - << " calculatePoints=" << calculatePoints () - << " [rect=" << calculatePoints ().boundingRect () << "]" - << endl; + qCDebug(kpLogLayers) << "\tshapeRegion=" << shapeRegion() + << " [rect=" << shapeRegion().boundingRect() << "]" + << " calculatePoints=" << calculatePoints() + << " [rect=" << calculatePoints().boundingRect() << "]" + << endl; #endif - kpImage retImage(width (), height (), QImage::Format_ARGB32_Premultiplied); + kpImage retImage(width(), height(), QImage::Format_ARGB32_Premultiplied); retImage.fill(0); // transparent QPainter painter(&retImage); @@ -306,62 +296,60 @@ //--------------------------------------------------------------------- // public virtual [kpAbstractSelection] -bool kpAbstractImageSelection::hasContent () const +bool kpAbstractImageSelection::hasContent() const { - return !d->baseImage.isNull (); + return !d->baseImage.isNull(); } //--------------------------------------------------------------------- // public virtual [kpAbstractSelection] -void kpAbstractImageSelection::deleteContent () +void kpAbstractImageSelection::deleteContent() { - if (!hasContent ()) { + if (!hasContent()) { return; } - setBaseImage (kpImage ()); + setBaseImage(kpImage()); } //--------------------------------------------------------------------- - // public -kpImage kpAbstractImageSelection::baseImage () const +kpImage kpAbstractImageSelection::baseImage() const { return d->baseImage; } //--------------------------------------------------------------------- // public -void kpAbstractImageSelection::setBaseImage (const kpImage &baseImage) +void kpAbstractImageSelection::setBaseImage(const kpImage &baseImage) { - Q_ASSERT (::CanSetBaseImageTo (this, baseImage)); + Q_ASSERT(::CanSetBaseImageTo(this, baseImage)); // qt doc: the image format must be set to Format_ARGB32Premultiplied or Format_ARGB32 // for the composition modes to have any effect d->baseImage = baseImage.convertToFormat(QImage::Format_ARGB32_Premultiplied); - recalculateTransparencyMaskCache (); + recalculateTransparencyMaskCache(); - emit changed (boundingRect ()); + emit changed(boundingRect()); } //--------------------------------------------------------------------- // public -kpImageSelectionTransparency kpAbstractImageSelection::transparency () const +kpImageSelectionTransparency kpAbstractImageSelection::transparency() const { return d->transparency; } //--------------------------------------------------------------------- // public -bool kpAbstractImageSelection::setTransparency ( - const kpImageSelectionTransparency &transparency, - bool checkTransparentPixmapChanged) +bool kpAbstractImageSelection::setTransparency( + const kpImageSelectionTransparency &transparency, bool checkTransparentPixmapChanged) { if (d->transparency == transparency) { return false; @@ -372,35 +360,30 @@ bool haveChanged = true; QBitmap oldTransparencyMaskCache = d->transparencyMaskCache; - recalculateTransparencyMaskCache (); + recalculateTransparencyMaskCache(); - if ( oldTransparencyMaskCache.size() == d->transparencyMaskCache.size() ) - { - if (d->transparencyMaskCache.isNull ()) - { + if (oldTransparencyMaskCache.size() == d->transparencyMaskCache.size()) { + if (d->transparencyMaskCache.isNull()) { #if DEBUG_KP_SELECTION qCDebug(kpLogLayers) << "\tboth old and new pixmaps are null - nothing changed"; #endif haveChanged = false; - } - else if (checkTransparentPixmapChanged) - { + } else if (checkTransparentPixmapChanged) { QImage oldTransparencyMaskImage = oldTransparencyMaskCache.toImage(); QImage newTransparencyMaskImage = d->transparencyMaskCache.toImage(); bool changed = false; - for (int y = 0; y < oldTransparencyMaskImage.height () && !changed; y++) - { - for (int x = 0; x < oldTransparencyMaskImage.width () && !changed; x++) - { - if (kpPixmapFX::getColorAtPixel (oldTransparencyMaskImage, x, y) != - kpPixmapFX::getColorAtPixel (newTransparencyMaskImage, x, y)) - { + for (int y = 0; y < oldTransparencyMaskImage.height() && !changed; y++) { + for (int x = 0; x < oldTransparencyMaskImage.width() && !changed; x++) { + if (kpPixmapFX::getColorAtPixel(oldTransparencyMaskImage, x, y) + != kpPixmapFX::getColorAtPixel(newTransparencyMaskImage, x, y)) { #if DEBUG_KP_SELECTION - qCDebug(kpLogLayers) << "\tdiffer at " << QPoint (x, y) - << " old=" << kpPixmapFX::getColorAtPixel (oldTransparencyMaskImage, x, y).toQRgb () - << " new=" << kpPixmapFX::getColorAtPixel (newTransparencyMaskImage, x, y).toQRgb () - << endl; + qCDebug(kpLogLayers) << "\tdiffer at " << QPoint(x, y) + << " old=" << kpPixmapFX::getColorAtPixel( + oldTransparencyMaskImage, x, y).toQRgb() + << " new=" << kpPixmapFX::getColorAtPixel( + newTransparencyMaskImage, x, y).toQRgb() + << endl; #endif changed = true; break; @@ -414,176 +397,158 @@ } } - if (haveChanged) { - emit changed (boundingRect ()); + emit changed(boundingRect()); } return haveChanged; } //--------------------------------------------------------------------- // private -void kpAbstractImageSelection::recalculateTransparencyMaskCache () +void kpAbstractImageSelection::recalculateTransparencyMaskCache() { #if DEBUG_KP_SELECTION qCDebug(kpLogLayers) << "kpAbstractImageSelection::recalculateTransparencyMaskCache()"; #endif - if (d->baseImage.isNull ()) - { + if (d->baseImage.isNull()) { #if DEBUG_KP_SELECTION qCDebug(kpLogLayers) << "\tno image - no need for transparency mask"; #endif - d->transparencyMaskCache = QBitmap (); + d->transparencyMaskCache = QBitmap(); return; } - if (d->transparency.isOpaque ()) - { + if (d->transparency.isOpaque()) { #if DEBUG_KP_SELECTION qCDebug(kpLogLayers) << "\topaque - no need for transparency mask"; #endif - d->transparencyMaskCache = QBitmap (); + d->transparencyMaskCache = QBitmap(); return; } d->transparencyMaskCache = QBitmap(d->baseImage.size()); - QPainter transparencyMaskPainter (&d->transparencyMaskCache); + QPainter transparencyMaskPainter(&d->transparencyMaskCache); bool hasTransparent = false; - for (int y = 0; y < d->baseImage.height (); y++) - { - for (int x = 0; x < d->baseImage.width (); x++) - { - const kpColor pixelCol = kpPixmapFX::getColorAtPixel (d->baseImage, x, y); - if (pixelCol == kpColor::Transparent || - pixelCol.isSimilarTo (d->transparency.transparentColor (), - d->transparency.processedColorSimilarity ())) - { - transparencyMaskPainter.setPen (Qt::color1/*transparent*/); + for (int y = 0; y < d->baseImage.height(); y++) { + for (int x = 0; x < d->baseImage.width(); x++) { + const kpColor pixelCol = kpPixmapFX::getColorAtPixel(d->baseImage, x, y); + if (pixelCol == kpColor::Transparent + || pixelCol.isSimilarTo(d->transparency.transparentColor(), + d->transparency.processedColorSimilarity())) { + transparencyMaskPainter.setPen(Qt::color1 /*transparent*/); hasTransparent = true; - } - else - { - transparencyMaskPainter.setPen (Qt::color0/*opaque*/); + } else { + transparencyMaskPainter.setPen(Qt::color0 /*opaque*/); } - transparencyMaskPainter.drawPoint (x, y); + transparencyMaskPainter.drawPoint(x, y); } } - transparencyMaskPainter.end (); + transparencyMaskPainter.end(); - if (!hasTransparent) - { + if (!hasTransparent) { #if DEBUG_KP_SELECTION qCDebug(kpLogLayers) << "\tcolour useless - completely opaque"; #endif - d->transparencyMaskCache = QBitmap (); + d->transparencyMaskCache = QBitmap(); return; } } //--------------------------------------------------------------------- // public -kpImage kpAbstractImageSelection::transparentImage () const +kpImage kpAbstractImageSelection::transparentImage() const { - kpImage image = baseImage (); + kpImage image = baseImage(); - if (!d->transparencyMaskCache.isNull ()) - { - QPainter painter(&image); - painter.setCompositionMode(QPainter::CompositionMode_Clear); - painter.drawPixmap(0, 0, d->transparencyMaskCache); + if (!d->transparencyMaskCache.isNull()) { + QPainter painter(&image); + painter.setCompositionMode(QPainter::CompositionMode_Clear); + painter.drawPixmap(0, 0, d->transparencyMaskCache); } return image; } //--------------------------------------------------------------------- // public -void kpAbstractImageSelection::fill (const kpColor &color) +void kpAbstractImageSelection::fill(const kpColor &color) { QImage newImage(width(), height(), QImage::Format_ARGB32_Premultiplied); newImage.fill(color.toQRgb()); // LOTODO: Maybe disable Image/Clear menu item if transparent color - if ( !color.isTransparent() ) - { - QPainter painter(&newImage); - painter.setCompositionMode(QPainter::CompositionMode_Clear); - painter.drawPixmap(0, 0, shapeBitmap()); + if (!color.isTransparent()) { + QPainter painter(&newImage); + painter.setCompositionMode(QPainter::CompositionMode_Clear); + painter.drawPixmap(0, 0, shapeBitmap()); } - setBaseImage (newImage); + setBaseImage(newImage); } //--------------------------------------------------------------------- // public virtual -void kpAbstractImageSelection::flip (bool horiz, bool vert) +void kpAbstractImageSelection::flip(bool horiz, bool vert) { #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "kpAbstractImageSelection::flip(horiz=" << horiz - << ",vert=" << vert << ")"; + << ",vert=" << vert << ")"; #endif - if (!d->baseImage.isNull ()) - { + if (!d->baseImage.isNull()) { #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "\thave pixmap - flipping that"; #endif d->baseImage = d->baseImage.mirrored(horiz, vert); } - if (!d->transparencyMaskCache.isNull ()) - { + if (!d->transparencyMaskCache.isNull()) { #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "\thave transparency mask - flipping that"; #endif QImage image = d->transparencyMaskCache.toImage().mirrored(horiz, vert); d->transparencyMaskCache = QBitmap::fromImage(image); } - emit changed (boundingRect ()); + emit changed(boundingRect()); } //--------------------------------------------------------------------- -static void Paint (const kpAbstractImageSelection *sel, const kpImage &srcImage, - QImage *destImage, const QRect &docRect) +static void Paint(const kpAbstractImageSelection *sel, const kpImage &srcImage, QImage *destImage, + const QRect &docRect) { - if (!srcImage.isNull ()) - { - kpPixmapFX::paintPixmapAt (destImage, - sel->topLeft () - docRect.topLeft (), - srcImage); + if (!srcImage.isNull()) { + kpPixmapFX::paintPixmapAt(destImage, + sel->topLeft() - docRect.topLeft(), + srcImage); } } //--------------------------------------------------------------------- // public virtual [kpAbstractSelection] -void kpAbstractImageSelection::paint (QImage *destImage, - const QRect &docRect) const +void kpAbstractImageSelection::paint(QImage *destImage, const QRect &docRect) const { - ::Paint (this, transparentImage (), destImage, docRect); + ::Paint(this, transparentImage(), destImage, docRect); } //--------------------------------------------------------------------- // public -void kpAbstractImageSelection::paintWithBaseImage (QImage *destImage, - const QRect &docRect) const +void kpAbstractImageSelection::paintWithBaseImage(QImage *destImage, const QRect &docRect) const { - ::Paint (this, baseImage (), destImage, docRect); + ::Paint(this, baseImage(), destImage, docRect); } //--------------------------------------------------------------------- - - diff --git a/layers/selections/image/kpEllipticalImageSelection.h b/layers/selections/image/kpEllipticalImageSelection.h --- a/layers/selections/image/kpEllipticalImageSelection.h +++ b/layers/selections/image/kpEllipticalImageSelection.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,94 +24,80 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEllipticalImageSelection_H #define kpEllipticalImageSelection_H - #include "layers/selections/image/kpAbstractImageSelection.h" - class kpEllipticalImageSelection : public kpAbstractImageSelection { -Q_OBJECT + Q_OBJECT public: - kpEllipticalImageSelection (const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + kpEllipticalImageSelection (const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); kpEllipticalImageSelection (const QRect &rect, - const kpImage &baseImage = kpImage (), - const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + const kpImage &baseImage = kpImage(), const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); - kpEllipticalImageSelection (const QRect &rect, - const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + kpEllipticalImageSelection (const QRect &rect, const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); kpEllipticalImageSelection (const kpEllipticalImageSelection &rhs); - kpEllipticalImageSelection &operator= (const kpEllipticalImageSelection &rhs); + kpEllipticalImageSelection &operator=(const kpEllipticalImageSelection &rhs); - kpEllipticalImageSelection *clone () const override; + kpEllipticalImageSelection *clone() const override; ~kpEllipticalImageSelection () override; - // // Marshalling // public: static const int SerialID = 1; - int serialID () const override; - + int serialID() const override; // // General Queries // public: - bool isRectangular () const override; - + bool isRectangular() const override; // // Position & Dimensions // public: - QPolygon calculatePoints () const override; - + QPolygon calculatePoints() const override; // // Shape Mask // public: - QRegion shapeRegion () const override; - + QRegion shapeRegion() const override; // // Point Testing // public: - bool contains (const QPoint &point) const override; - + bool contains(const QPoint &point) const override; // // Rendering // public: - void paintBorder (QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const override; - + void paintBorder(QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const override; private: - struct kpEllipticalImageSelectionPrivate * const d; + struct kpEllipticalImageSelectionPrivate *const d; }; - - #endif // kpEllipticalImageSelection_H diff --git a/layers/selections/image/kpEllipticalImageSelection.cpp b/layers/selections/image/kpEllipticalImageSelection.cpp --- a/layers/selections/image/kpEllipticalImageSelection.cpp +++ b/layers/selections/image/kpEllipticalImageSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,61 +24,56 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION 0 - #include "layers/selections/image/kpEllipticalImageSelection.h" #include #include - struct kpEllipticalImageSelectionPrivate { }; - kpEllipticalImageSelection::kpEllipticalImageSelection ( - const kpImageSelectionTransparency &transparency) - : kpAbstractImageSelection (transparency), - d (new kpEllipticalImageSelectionPrivate ()) + const kpImageSelectionTransparency &transparency) + : kpAbstractImageSelection(transparency) + , d(new kpEllipticalImageSelectionPrivate()) { } -kpEllipticalImageSelection::kpEllipticalImageSelection (const QRect &rect, - const kpImage &baseImage, - const kpImageSelectionTransparency &transparency) - : kpAbstractImageSelection (rect, baseImage, transparency), - d (new kpEllipticalImageSelectionPrivate ()) +kpEllipticalImageSelection::kpEllipticalImageSelection (const QRect &rect, const kpImage &baseImage, + const kpImageSelectionTransparency &transparency) + : kpAbstractImageSelection(rect, baseImage, transparency) + , d(new kpEllipticalImageSelectionPrivate()) { } kpEllipticalImageSelection::kpEllipticalImageSelection (const QRect &rect, - const kpImageSelectionTransparency &transparency) - : kpAbstractImageSelection (rect, transparency), - d (new kpEllipticalImageSelectionPrivate ()) + const kpImageSelectionTransparency &transparency) + : kpAbstractImageSelection(rect, transparency) + , d(new kpEllipticalImageSelectionPrivate()) { } kpEllipticalImageSelection::kpEllipticalImageSelection (const kpEllipticalImageSelection &rhs) - : kpAbstractImageSelection (), - d (new kpEllipticalImageSelectionPrivate ()) + : kpAbstractImageSelection() + , d(new kpEllipticalImageSelectionPrivate()) { *this = rhs; } -kpEllipticalImageSelection &kpEllipticalImageSelection::operator= ( - const kpEllipticalImageSelection &rhs) +kpEllipticalImageSelection &kpEllipticalImageSelection::operator=( + const kpEllipticalImageSelection &rhs) { - kpAbstractImageSelection::operator= (rhs); + kpAbstractImageSelection::operator=(rhs); return *this; } -kpEllipticalImageSelection *kpEllipticalImageSelection::clone () const +kpEllipticalImageSelection *kpEllipticalImageSelection::clone() const { - kpEllipticalImageSelection *sel = new kpEllipticalImageSelection (); + kpEllipticalImageSelection *sel = new kpEllipticalImageSelection(); *sel = *this; return sel; } @@ -92,93 +86,84 @@ //--------------------------------------------------------------------- // public virtual [kpAbstractSelection] -int kpEllipticalImageSelection::serialID () const +int kpEllipticalImageSelection::serialID() const { return SerialID; } //--------------------------------------------------------------------- // public virtual [kpAbstractSelection] -bool kpEllipticalImageSelection::isRectangular () const +bool kpEllipticalImageSelection::isRectangular() const { return false; } //--------------------------------------------------------------------- // public virtual [kpAbstractSelection] -QPolygon kpEllipticalImageSelection::calculatePoints () const +QPolygon kpEllipticalImageSelection::calculatePoints() const { - Q_ASSERT (boundingRect ().isValid ()); + Q_ASSERT(boundingRect().isValid()); - if (width () == 1 && height () == 1) - { + if (width() == 1 && height() == 1) { QPolygon ret; - ret.append (topLeft ()); + ret.append(topLeft()); return ret; } QPainterPath path; - if (width () == 1 || height () == 1) - { - path.moveTo (x (), y ()); + if (width() == 1 || height() == 1) { + path.moveTo(x(), y()); // This does not work when the width _and_ height are 1 since lineTo() // would not move at all. This is why we have a separate case for that // at the top of the method. - path.lineTo (x () + width () - 1, y () + height () - 1); - } - else - { + path.lineTo(x() + width() - 1, y() + height() - 1); + } else { // The adjusting is to fight QPainterPath::addEllipse() making // the ellipse 1 pixel higher and wider than specified. - path.addEllipse (boundingRect ().adjusted (0, 0, -1, -1)); + path.addEllipse(boundingRect().adjusted(0, 0, -1, -1)); } - const QList polygons = path.toSubpathPolygons (); - Q_ASSERT (polygons.size () == 1); + const QList polygons = path.toSubpathPolygons(); + Q_ASSERT(polygons.size() == 1); - const QPolygonF& firstPolygonF = polygons.first (); - return firstPolygonF.toPolygon (); + const QPolygonF &firstPolygonF = polygons.first(); + return firstPolygonF.toPolygon(); } //--------------------------------------------------------------------- - // protected virtual [kpAbstractImageSelection] -QRegion kpEllipticalImageSelection::shapeRegion () const +QRegion kpEllipticalImageSelection::shapeRegion() const { QRegion reg(calculatePoints()); return reg; } //--------------------------------------------------------------------- - // public virtual [kpAbstractSelection] -bool kpEllipticalImageSelection::contains (const QPoint &point) const +bool kpEllipticalImageSelection::contains(const QPoint &point) const { - if (!boundingRect ().contains (point)) { + if (!boundingRect().contains(point)) { return false; } - return shapeRegion ().contains (point); + return shapeRegion().contains(point); } //--------------------------------------------------------------------- - // public virtual [kpAbstractSelection] -void kpEllipticalImageSelection::paintBorder (QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const +void kpEllipticalImageSelection::paintBorder(QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const { - if ( !boundingRect().isValid() ) { - return; + if (!boundingRect().isValid()) { + return; } - paintPolygonalBorder (calculatePoints (), - destPixmap, docRect, - selectionFinished); + paintPolygonalBorder(calculatePoints(), + destPixmap, docRect, + selectionFinished); } - - diff --git a/layers/selections/image/kpFreeFormImageSelection.h b/layers/selections/image/kpFreeFormImageSelection.h --- a/layers/selections/image/kpFreeFormImageSelection.h +++ b/layers/selections/image/kpFreeFormImageSelection.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,85 +24,76 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpFreeFormImageSelection_H #define kpFreeFormImageSelection_H - #include "layers/selections/image/kpAbstractImageSelection.h" - class kpFreeFormImageSelection : public kpAbstractImageSelection { -Q_OBJECT + Q_OBJECT public: - kpFreeFormImageSelection (const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + kpFreeFormImageSelection (const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); kpFreeFormImageSelection (const QPolygon &points, - const kpImage &baseImage = kpImage (), - const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + const kpImage &baseImage = kpImage(), const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); - kpFreeFormImageSelection (const QPolygon &points, - const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + kpFreeFormImageSelection (const QPolygon &points, const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); kpFreeFormImageSelection (const kpFreeFormImageSelection &rhs); - kpFreeFormImageSelection &operator= (const kpFreeFormImageSelection &rhs); + kpFreeFormImageSelection &operator=(const kpFreeFormImageSelection &rhs); - kpFreeFormImageSelection *clone () const override; + kpFreeFormImageSelection *clone() const override; ~kpFreeFormImageSelection () override; - // // Marshalling // public: static const int SerialID = 2; - int serialID () const override; + int serialID() const override; - bool readFromStream (QDataStream &stream) override; - - void writeToStream (QDataStream &stream) const override; + bool readFromStream(QDataStream &stream) override; + void writeToStream(QDataStream &stream) const override; // // General Queries // public: - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; - bool isRectangular () const override; + bool isRectangular() const override; // (as passed to the constructor) - QPolygon originalPoints () const; - + QPolygon originalPoints() const; // // Cardinally Adjacent Points // protected: - void recalculateCardinallyAdjacentPoints (); + void recalculateCardinallyAdjacentPoints(); public: // Returns the originalPoints() interpolated to be cardinally adjacent. - QPolygon cardinallyAdjacentPoints () const; + QPolygon cardinallyAdjacentPoints() const; // Returns cardinallyAdjacentPoints() but with extra points interpolated // from the last point to the first point (the original points are // thought of as a polygon where the first and last points are connected, // rather than as a string of points). // // As used by the shape mask methods. - QPolygon cardinallyAdjacentPointsLoop () const; - + QPolygon cardinallyAdjacentPointsLoop() const; // // Position & Dimensions @@ -113,47 +103,41 @@ // Implements kpAbstractSelection interface - same as // cardinallyAdjacentPointsLoop (). // This implementation is fast. - QPolygon calculatePoints () const override; - + QPolygon calculatePoints() const override; // // Shape Mask // public: - QRegion shapeRegion () const override; - + QRegion shapeRegion() const override; // // Point Testing // public: - bool contains (const QPoint &point) const override; - + bool contains(const QPoint &point) const override; // // Mutation // public: - void moveBy (int dx, int dy) override; - - void flip (bool horiz, bool vert) override; + void moveBy(int dx, int dy) override; + void flip(bool horiz, bool vert) override; // // Rendering // public: - void paintBorder (QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const override; - + void paintBorder(QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const override; private: - struct kpFreeFormImageSelectionPrivate * const d; + struct kpFreeFormImageSelectionPrivate *const d; }; - #endif // kpFreeFormImageSelection_H diff --git a/layers/selections/image/kpFreeFormImageSelection.cpp b/layers/selections/image/kpFreeFormImageSelection.cpp --- a/layers/selections/image/kpFreeFormImageSelection.cpp +++ b/layers/selections/image/kpFreeFormImageSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,17 +24,14 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION 0 - #include "layers/selections/image/kpFreeFormImageSelection.h" #include "kpLogCategories.h" #include "imagelib/kpPainter.h" - struct kpFreeFormImageSelectionPrivate { QPolygon orgPoints; @@ -65,43 +61,42 @@ QPolygon cardPointsCache, cardPointsLoopCache; }; - kpFreeFormImageSelection::kpFreeFormImageSelection ( - const kpImageSelectionTransparency &transparency) - : kpAbstractImageSelection (transparency), - d (new kpFreeFormImageSelectionPrivate ()) + const kpImageSelectionTransparency &transparency) + : kpAbstractImageSelection(transparency) + , d(new kpFreeFormImageSelectionPrivate()) { } kpFreeFormImageSelection::kpFreeFormImageSelection (const QPolygon &points, - const kpImage &baseImage, - const kpImageSelectionTransparency &transparency) - : kpAbstractImageSelection (points.boundingRect (), baseImage, transparency), - d (new kpFreeFormImageSelectionPrivate ()) + const kpImage &baseImage, + const kpImageSelectionTransparency &transparency) + : kpAbstractImageSelection(points.boundingRect(), baseImage, transparency) + , d(new kpFreeFormImageSelectionPrivate()) { d->orgPoints = points; - recalculateCardinallyAdjacentPoints (); + recalculateCardinallyAdjacentPoints(); } kpFreeFormImageSelection::kpFreeFormImageSelection (const QPolygon &points, - const kpImageSelectionTransparency &transparency) - : kpAbstractImageSelection (points.boundingRect (), transparency), - d (new kpFreeFormImageSelectionPrivate ()) + const kpImageSelectionTransparency &transparency) + : kpAbstractImageSelection(points.boundingRect(), transparency) + , d(new kpFreeFormImageSelectionPrivate()) { d->orgPoints = points; - recalculateCardinallyAdjacentPoints (); + recalculateCardinallyAdjacentPoints(); } kpFreeFormImageSelection::kpFreeFormImageSelection (const kpFreeFormImageSelection &rhs) - : kpAbstractImageSelection (), - d (new kpFreeFormImageSelectionPrivate ()) + : kpAbstractImageSelection() + , d(new kpFreeFormImageSelectionPrivate()) { *this = rhs; } -kpFreeFormImageSelection &kpFreeFormImageSelection::operator= (const kpFreeFormImageSelection &rhs) +kpFreeFormImageSelection &kpFreeFormImageSelection::operator=(const kpFreeFormImageSelection &rhs) { - kpAbstractImageSelection::operator= (rhs); + kpAbstractImageSelection::operator=(rhs); d->orgPoints = rhs.d->orgPoints; d->cardPointsCache = rhs.d->cardPointsCache; @@ -111,9 +106,9 @@ } // public virtual [kpAbstractSelection] -kpFreeFormImageSelection *kpFreeFormImageSelection::clone () const +kpFreeFormImageSelection *kpFreeFormImageSelection::clone() const { - kpFreeFormImageSelection *sel = new kpFreeFormImageSelection (); + kpFreeFormImageSelection *sel = new kpFreeFormImageSelection(); *sel = *this; return sel; } @@ -123,105 +118,97 @@ delete d; } - // public virtual [kpAbstractSelection] -int kpFreeFormImageSelection::serialID () const +int kpFreeFormImageSelection::serialID() const { return SerialID; } // public virtual [base kpAbstractImageSelection] -bool kpFreeFormImageSelection::readFromStream (QDataStream &stream) +bool kpFreeFormImageSelection::readFromStream(QDataStream &stream) { - if (!kpAbstractImageSelection::readFromStream (stream)) { + if (!kpAbstractImageSelection::readFromStream(stream)) { return false; } stream >> d->orgPoints; - recalculateCardinallyAdjacentPoints (); + recalculateCardinallyAdjacentPoints(); return true; } // public virtual [base kpAbstractImageSelection] -void kpFreeFormImageSelection::writeToStream (QDataStream &stream) const +void kpFreeFormImageSelection::writeToStream(QDataStream &stream) const { - kpAbstractImageSelection::writeToStream (stream); + kpAbstractImageSelection::writeToStream(stream); stream << d->orgPoints; } - // public virtual [base kpAbstractImageSelection] -kpCommandSize::SizeType kpFreeFormImageSelection::size () const +kpCommandSize::SizeType kpFreeFormImageSelection::size() const { - return kpAbstractImageSelection::size () + - (kpCommandSize::PolygonSize (d->orgPoints) + - kpCommandSize::PolygonSize (d->cardPointsCache) + - kpCommandSize::PolygonSize (d->cardPointsLoopCache)); + return kpAbstractImageSelection::size() + +(kpCommandSize::PolygonSize(d->orgPoints) + +kpCommandSize::PolygonSize(d->cardPointsCache) + +kpCommandSize::PolygonSize(d->cardPointsLoopCache)); } // public virtual [kpAbstractSelection] -bool kpFreeFormImageSelection::isRectangular () const +bool kpFreeFormImageSelection::isRectangular() const { return false; } // public -QPolygon kpFreeFormImageSelection::originalPoints () const +QPolygon kpFreeFormImageSelection::originalPoints() const { return d->orgPoints; } - -static QPolygon RecalculateCardinallyAdjacentPoints (const QPolygon &points) +static QPolygon RecalculateCardinallyAdjacentPoints(const QPolygon &points) { #if DEBUG_KP_SELECTION qCDebug(kpLogLayers) << "kpFreeFormImageSelection.cpp:RecalculateCardinallyAdjacentPoints()"; qCDebug(kpLogLayers) << "\tpoints=" << points; #endif // Filter out duplicates. QPolygon noDups; - for (const auto &p : points) - { - if (!noDups.isEmpty () && p == noDups.last ()) { + for (const auto &p : points) { + if (!noDups.isEmpty() && p == noDups.last()) { continue; } - noDups.append (p); + noDups.append(p); } #if DEBUG_KP_SELECTION qCDebug(kpLogLayers) << "\twithout dups=" << noDups; #endif // Interpolate to ensure cardinal adjacency. QPolygon cardPoints; - for (const auto &p : noDups) - { - if (!cardPoints.isEmpty () && - !kpPainter::pointsAreCardinallyAdjacent (p, cardPoints.last ())) - { - const QPoint lastPoint = cardPoints.last (); - - QList interpPoints = kpPainter::interpolatePoints ( + for (const auto &p : noDups) { + if (!cardPoints.isEmpty() + && !kpPainter::pointsAreCardinallyAdjacent(p, cardPoints.last())) { + const QPoint lastPoint = cardPoints.last(); + + QList interpPoints = kpPainter::interpolatePoints( lastPoint, p, - true/*cardinal adjacency*/); + true /*cardinal adjacency*/); - Q_ASSERT (interpPoints.size () >= 2); - Q_ASSERT (interpPoints [0] == lastPoint); - Q_ASSERT (interpPoints.last () == p); + Q_ASSERT(interpPoints.size() >= 2); + Q_ASSERT(interpPoints [0] == lastPoint); + Q_ASSERT(interpPoints.last() == p); - for (int i = 1/*skip already existing point*/; - i < interpPoints.size (); - i++) - { - cardPoints.append (interpPoints [i]); + for (int i = 1 /*skip already existing point*/; + i < interpPoints.size(); + i++) { + cardPoints.append(interpPoints [i]); } - } - else { - cardPoints.append (p); + } else { + cardPoints.append(p); } } #if DEBUG_KP_SELECTION @@ -232,46 +219,43 @@ } // protected -void kpFreeFormImageSelection::recalculateCardinallyAdjacentPoints () +void kpFreeFormImageSelection::recalculateCardinallyAdjacentPoints() { - d->cardPointsCache = ::RecalculateCardinallyAdjacentPoints (d->orgPoints); - + d->cardPointsCache = ::RecalculateCardinallyAdjacentPoints(d->orgPoints); QPolygon pointsLoop = d->cardPointsCache; - if (!pointsLoop.isEmpty ()) { - pointsLoop.append (pointsLoop.first ()); + if (!pointsLoop.isEmpty()) { + pointsLoop.append(pointsLoop.first()); } // OPT: We know this method only needs to act on the last 2 points of // "pointLoop", since the previous points are definitely cardinally // adjacent. - d->cardPointsLoopCache = ::RecalculateCardinallyAdjacentPoints (pointsLoop); + d->cardPointsLoopCache = ::RecalculateCardinallyAdjacentPoints(pointsLoop); } // public -QPolygon kpFreeFormImageSelection::cardinallyAdjacentPoints () const +QPolygon kpFreeFormImageSelection::cardinallyAdjacentPoints() const { return d->cardPointsCache; } // public -QPolygon kpFreeFormImageSelection::cardinallyAdjacentPointsLoop () const +QPolygon kpFreeFormImageSelection::cardinallyAdjacentPointsLoop() const { return d->cardPointsLoopCache; } - // public virtual [kpAbstractSelection] -QPolygon kpFreeFormImageSelection::calculatePoints () const +QPolygon kpFreeFormImageSelection::calculatePoints() const { return d->cardPointsLoopCache; } - // protected virtual [kpAbstractSelection] -QRegion kpFreeFormImageSelection::shapeRegion () const +QRegion kpFreeFormImageSelection::shapeRegion() const { - const QRegion region = QRegion (d->cardPointsLoopCache, Qt::OddEvenFill); + const QRegion region = QRegion(d->cardPointsLoopCache, Qt::OddEvenFill); // In Qt4, while QPainter::drawRect() gives you rectangles 1 pixel // wider and higher, QRegion(QPolygon) gives you regions 1 pixel @@ -293,102 +277,94 @@ // is dodgy. Also, this would guarantee that shapeBitmap() and shapeRegion() // are consistent and we wouldn't need cardinally adjacent points either // (d->cardPointsCache and d->cardPointsLoopCache). - const QRegion regionX = region.translated (1, 0); - const QRegion regionY = region.translated (0, 1); - const QRegion regionXY = region.translated (1, 1); + const QRegion regionX = region.translated(1, 0); + const QRegion regionY = region.translated(0, 1); + const QRegion regionXY = region.translated(1, 1); - return region.united (regionX).united (regionY).united (regionXY); + return region.united(regionX).united(regionY).united(regionXY); } - // public virtual [kpAbstractSelection] -bool kpFreeFormImageSelection::contains (const QPoint &point) const +bool kpFreeFormImageSelection::contains(const QPoint &point) const { - if (!boundingRect ().contains (point)) { + if (!boundingRect().contains(point)) { return false; } // We can't use the baseImage() (when non-null) and get the transparency of // the pixel at , instead of this region test, as the pixel may be // transparent but still within the border. - return shapeRegion ().contains (point); + return shapeRegion().contains(point); } - // public virtual [base kpAbstractSelection] -void kpFreeFormImageSelection::moveBy (int dx, int dy) +void kpFreeFormImageSelection::moveBy(int dx, int dy) { - d->orgPoints.translate (dx, dy); + d->orgPoints.translate(dx, dy); - d->cardPointsCache.translate (dx, dy); - d->cardPointsLoopCache.translate (dx, dy); + d->cardPointsCache.translate(dx, dy); + d->cardPointsLoopCache.translate(dx, dy); // Call base last since it fires the changed() signal and we only // want that to fire at the very end of this method, after all // the selection state has been changed. - kpAbstractImageSelection::moveBy (dx, dy); + kpAbstractImageSelection::moveBy(dx, dy); } //--------------------------------------------------------------------- -static void FlipPoints (QPolygon *points, - bool horiz, bool vert, - const QRect &oldRect) +static void FlipPoints(QPolygon *points, bool horiz, bool vert, const QRect &oldRect) { - points->translate (-oldRect.x (), -oldRect.y ()); + points->translate(-oldRect.x(), -oldRect.y()); - const QTransform matrix (horiz ? -1 : +1, // m11 - 0, // m12 - 0, // m21 - vert ? -1 : +1, // m22 - horiz ? (oldRect.width() - 1) : 0, // dx - vert ? (oldRect.height() - 1) : 0); // dy + const QTransform matrix(horiz ? -1 : +1, // m11 + 0, // m12 + 0, // m21 + vert ? -1 : +1, // m22 + horiz ? (oldRect.width() - 1) : 0, // dx + vert ? (oldRect.height() - 1) : 0); // dy #if !defined (QT_NO_DEBUG) && !defined (NDEBUG) QPolygon oldPoints = *points; #endif - *points = matrix.map (*points); + *points = matrix.map(*points); #if !defined (QT_NO_DEBUG) && !defined (NDEBUG) // Sanity check: flipping the points twice gives us the original points. - Q_ASSERT (oldPoints == matrix.map (*points)); + Q_ASSERT(oldPoints == matrix.map(*points)); #endif - points->translate (oldRect.x (), oldRect.y ()); + points->translate(oldRect.x(), oldRect.y()); } //--------------------------------------------------------------------- // public virtual [base kpAbstractImageSelection] -void kpFreeFormImageSelection::flip (bool horiz, bool vert) +void kpFreeFormImageSelection::flip(bool horiz, bool vert) { - ::FlipPoints (&d->orgPoints, horiz, vert, boundingRect ()); - - ::FlipPoints (&d->cardPointsCache, horiz, vert, boundingRect ()); - ::FlipPoints (&d->cardPointsLoopCache, horiz, vert, boundingRect ()); + ::FlipPoints(&d->orgPoints, horiz, vert, boundingRect()); + ::FlipPoints(&d->cardPointsCache, horiz, vert, boundingRect()); + ::FlipPoints(&d->cardPointsLoopCache, horiz, vert, boundingRect()); // Call base last since it fires the changed() signal and we only // want that to fire at the very end of this method, after all // the selection state has been changed. - kpAbstractImageSelection::flip (horiz, vert); + kpAbstractImageSelection::flip(horiz, vert); } //--------------------------------------------------------------------- // public virtual [kpAbstractSelection] -void kpFreeFormImageSelection::paintBorder (QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const +void kpFreeFormImageSelection::paintBorder(QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const { if (selectionFinished) { - paintPolygonalBorder (cardinallyAdjacentPointsLoop (), - destPixmap, docRect, selectionFinished); - } - else { - paintPolygonalBorder (cardinallyAdjacentPoints (), - destPixmap, docRect, selectionFinished); + paintPolygonalBorder(cardinallyAdjacentPointsLoop(), + destPixmap, docRect, selectionFinished); + } else { + paintPolygonalBorder(cardinallyAdjacentPoints(), + destPixmap, docRect, selectionFinished); } } - - diff --git a/layers/selections/image/kpImageSelectionTransparency.h b/layers/selections/image/kpImageSelectionTransparency.h --- a/layers/selections/image/kpImageSelectionTransparency.h +++ b/layers/selections/image/kpImageSelectionTransparency.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_IMAGE_SELECTION_TRANSPARENCY_H #define KP_IMAGE_SELECTION_TRANSPARENCY_H - #include "imagelib/kpColor.h" - // This does not apply to the Text Tool. Use kpTextStyle for that. class kpImageSelectionTransparency { @@ -49,34 +45,34 @@ // // It is a similar case with , although // must be in-range (see kpColorSimilarityHolder). - kpImageSelectionTransparency (bool isOpaque, const kpColor &transparentColor, double colorSimilarity); + kpImageSelectionTransparency (bool isOpaque, const kpColor &transparentColor, + double colorSimilarity); // Returns whether they are visually equivalent. // This is the same as a memcmp() except that if they are both opaque, // this function will return true regardless of the transparentColor's. - bool operator== (const kpImageSelectionTransparency &rhs) const; - bool operator!= (const kpImageSelectionTransparency &rhs) const; + bool operator==(const kpImageSelectionTransparency &rhs) const; + bool operator!=(const kpImageSelectionTransparency &rhs) const; ~kpImageSelectionTransparency (); - bool isOpaque () const; - bool isTransparent () const; - void setOpaque (bool yes = true); - void setTransparent (bool yes = true); + bool isOpaque() const; + bool isTransparent() const; + void setOpaque(bool yes = true); + void setTransparent(bool yes = true); // If isOpaque(), transparentColor() is generally not called because // the transparent color would have no effect. - kpColor transparentColor () const; - void setTransparentColor (const kpColor &transparentColor); + kpColor transparentColor() const; + void setTransparentColor(const kpColor &transparentColor); - double colorSimilarity () const; - void setColorSimilarity (double colorSimilarity); - int processedColorSimilarity () const; + double colorSimilarity() const; + void setColorSimilarity(double colorSimilarity); + int processedColorSimilarity() const; private: bool m_isOpaque; kpColor m_transparentColor; double m_colorSimilarity; int m_processedColorSimilarity; }; - #endif // KP_IMAGE_SELECTION_TRANSPARENCY_H diff --git a/layers/selections/image/kpImageSelectionTransparency.cpp b/layers/selections/image/kpImageSelectionTransparency.cpp --- a/layers/selections/image/kpImageSelectionTransparency.cpp +++ b/layers/selections/image/kpImageSelectionTransparency.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,87 +24,84 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION_TRANSPARENCY 0 - #include "layers/selections/image/kpImageSelectionTransparency.h" #include "kpLogCategories.h" #include "imagelib/kpColor.h" #include "widgets/colorSimilarity/kpColorSimilarityHolder.h" - //--------------------------------------------------------------------- kpImageSelectionTransparency::kpImageSelectionTransparency () - : m_isOpaque (true) + : m_isOpaque(true) { - setColorSimilarity (0); + setColorSimilarity(0); } //--------------------------------------------------------------------- -kpImageSelectionTransparency::kpImageSelectionTransparency (const kpColor &transparentColor, double colorSimilarity) - : m_isOpaque (false), - m_transparentColor (transparentColor) +kpImageSelectionTransparency::kpImageSelectionTransparency (const kpColor &transparentColor, + double colorSimilarity) + : m_isOpaque(false) + , m_transparentColor(transparentColor) { - setColorSimilarity (colorSimilarity); + setColorSimilarity(colorSimilarity); } //--------------------------------------------------------------------- -kpImageSelectionTransparency::kpImageSelectionTransparency (bool isOpaque, const kpColor &transparentColor, - double colorSimilarity) - : m_isOpaque (isOpaque), - m_transparentColor (transparentColor) +kpImageSelectionTransparency::kpImageSelectionTransparency (bool isOpaque, + const kpColor &transparentColor, + double colorSimilarity) + : m_isOpaque(isOpaque) + , m_transparentColor(transparentColor) { - setColorSimilarity (colorSimilarity); + setColorSimilarity(colorSimilarity); } //--------------------------------------------------------------------- -bool kpImageSelectionTransparency::operator== (const kpImageSelectionTransparency &rhs) const +bool kpImageSelectionTransparency::operator==(const kpImageSelectionTransparency &rhs) const { #if DEBUG_KP_SELECTION_TRANSPARENCY && 0 qCDebug(kpLogLayers) << "kpImageSelectionTransparency::operator==()"; #endif - - if (m_isOpaque != rhs.m_isOpaque) - { + + if (m_isOpaque != rhs.m_isOpaque) { #if DEBUG_KP_SELECTION_TRANSPARENCY && 0 qCDebug(kpLogLayers) << "\tdifferent opacity: lhs=" << m_isOpaque - << " rhs=" << rhs.m_isOpaque - << endl; + << " rhs=" << rhs.m_isOpaque + << endl; #endif return false; } - if (m_isOpaque) - { + if (m_isOpaque) { #if DEBUG_KP_SELECTION_TRANSPARENCY && 0 qCDebug(kpLogLayers) << "\tboth opaque - eq"; #endif return true; } #if DEBUG_KP_SELECTION_TRANSPARENCY && 0 - qCDebug(kpLogLayers) << "\tcolours: lhs=" << (int *) m_transparentColor.toQRgb () - << " rhs=" << (int *) rhs.m_transparentColor.toQRgb () - << endl; + qCDebug(kpLogLayers) << "\tcolours: lhs=" << (int *)m_transparentColor.toQRgb() + << " rhs=" << (int *)rhs.m_transparentColor.toQRgb() + << endl; qCDebug(kpLogLayers) << "\tcolour similarity: lhs=" << m_colorSimilarity - << " rhs=" << rhs.m_colorSimilarity - << endl; + << " rhs=" << rhs.m_colorSimilarity + << endl; #endif - - return (m_transparentColor == rhs.m_transparentColor && - m_colorSimilarity == rhs.m_colorSimilarity); + + return m_transparentColor == rhs.m_transparentColor + && m_colorSimilarity == rhs.m_colorSimilarity; } //--------------------------------------------------------------------- -bool kpImageSelectionTransparency::operator!= (const kpImageSelectionTransparency &rhs) const +bool kpImageSelectionTransparency::operator!=(const kpImageSelectionTransparency &rhs) const { return !(*this == rhs); } @@ -117,69 +113,66 @@ //--------------------------------------------------------------------- // public -bool kpImageSelectionTransparency::isOpaque () const +bool kpImageSelectionTransparency::isOpaque() const { return m_isOpaque; } //--------------------------------------------------------------------- // public -bool kpImageSelectionTransparency::isTransparent () const +bool kpImageSelectionTransparency::isTransparent() const { - return !isOpaque (); + return !isOpaque(); } //--------------------------------------------------------------------- // public -void kpImageSelectionTransparency::setOpaque (bool yes) +void kpImageSelectionTransparency::setOpaque(bool yes) { m_isOpaque = yes; } //--------------------------------------------------------------------- // public -void kpImageSelectionTransparency::setTransparent (bool yes) +void kpImageSelectionTransparency::setTransparent(bool yes) { - setOpaque (!yes); + setOpaque(!yes); } //--------------------------------------------------------------------- - // public -kpColor kpImageSelectionTransparency::transparentColor () const +kpColor kpImageSelectionTransparency::transparentColor() const { - if (m_isOpaque) - { + if (m_isOpaque) { // There are legitimate uses for this so no qCCritical(kpLogLayers) qCDebug(kpLogLayers) << "kpImageSelectionTransparency::transparentColor() " - "getting transparent color even though opaque"; + "getting transparent color even though opaque"; } return m_transparentColor; } //--------------------------------------------------------------------- // public -void kpImageSelectionTransparency::setTransparentColor (const kpColor &transparentColor) +void kpImageSelectionTransparency::setTransparentColor(const kpColor &transparentColor) { m_transparentColor = transparentColor; } //--------------------------------------------------------------------- - // public -double kpImageSelectionTransparency::colorSimilarity () const +double kpImageSelectionTransparency::colorSimilarity() const { - if (m_colorSimilarity < 0 || - m_colorSimilarity > kpColorSimilarityHolder::MaxColorSimilarity) - { - qCCritical(kpLogLayers) << "kpImageSelectionTransparency::colorSimilarity() invalid colorSimilarity"; + if (m_colorSimilarity < 0 + || m_colorSimilarity > kpColorSimilarityHolder::MaxColorSimilarity) { + qCCritical(kpLogLayers) + << "kpImageSelectionTransparency::colorSimilarity() invalid colorSimilarity"; return 0; } @@ -189,16 +182,16 @@ //--------------------------------------------------------------------- // pubulic -void kpImageSelectionTransparency::setColorSimilarity (double colorSimilarity) +void kpImageSelectionTransparency::setColorSimilarity(double colorSimilarity) { m_colorSimilarity = colorSimilarity; - m_processedColorSimilarity = kpColor::processSimilarity (colorSimilarity); + m_processedColorSimilarity = kpColor::processSimilarity(colorSimilarity); } //--------------------------------------------------------------------- // public -int kpImageSelectionTransparency::processedColorSimilarity () const +int kpImageSelectionTransparency::processedColorSimilarity() const { return m_processedColorSimilarity; } diff --git a/layers/selections/image/kpRectangularImageSelection.h b/layers/selections/image/kpRectangularImageSelection.h --- a/layers/selections/image/kpRectangularImageSelection.h +++ b/layers/selections/image/kpRectangularImageSelection.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,95 +24,82 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpRectangularImageSelection_H #define kpRectangularImageSelection_H - #include "layers/selections/image/kpAbstractImageSelection.h" - class kpRectangularImageSelection : public kpAbstractImageSelection { -Q_OBJECT + Q_OBJECT public: - kpRectangularImageSelection (const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + kpRectangularImageSelection (const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); kpRectangularImageSelection (const QRect &rect, - const kpImage &baseImage = kpImage (), - const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + const kpImage &baseImage = kpImage(), const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); - kpRectangularImageSelection (const QRect &rect, - const kpImageSelectionTransparency &transparency = - kpImageSelectionTransparency ()); + kpRectangularImageSelection (const QRect &rect, const kpImageSelectionTransparency &transparency + = kpImageSelectionTransparency()); kpRectangularImageSelection (const kpRectangularImageSelection &rhs); - kpRectangularImageSelection &operator= (const kpRectangularImageSelection &rhs); + kpRectangularImageSelection &operator=(const kpRectangularImageSelection &rhs); - kpRectangularImageSelection *clone () const override; + kpRectangularImageSelection *clone() const override; ~kpRectangularImageSelection () override; - // // Marshalling // public: static const int SerialID = 0; - int serialID () const override; - + int serialID() const override; // // General Queries // public: - bool isRectangular () const override; - + bool isRectangular() const override; // // Position & Dimensions // public: - QPolygon calculatePoints () const override; - + QPolygon calculatePoints() const override; // // Shape Mask // public: - QBitmap shapeBitmap (bool nullForRectangular = false) const override; - - QRegion shapeRegion () const override; + QBitmap shapeBitmap(bool nullForRectangular = false) const override; + QRegion shapeRegion() const override; // // Point Testing // public: - bool contains (const QPoint &point) const override; - + bool contains(const QPoint &point) const override; // // Rendering // public: - void paintBorder (QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const override; - + void paintBorder(QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const override; private: - struct kpRectangularImageSelectionPrivate * const d; + struct kpRectangularImageSelectionPrivate *const d; }; - #endif // kpRectangularImageSelection_H diff --git a/layers/selections/image/kpRectangularImageSelection.cpp b/layers/selections/image/kpRectangularImageSelection.cpp --- a/layers/selections/image/kpRectangularImageSelection.cpp +++ b/layers/selections/image/kpRectangularImageSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,61 +24,57 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION 0 - #include "layers/selections/image/kpRectangularImageSelection.h" #include #include - struct kpRectangularImageSelectionPrivate { }; - kpRectangularImageSelection::kpRectangularImageSelection ( - const kpImageSelectionTransparency &transparency) - : kpAbstractImageSelection (transparency), - d (new kpRectangularImageSelectionPrivate ()) + const kpImageSelectionTransparency &transparency) + : kpAbstractImageSelection(transparency) + , d(new kpRectangularImageSelectionPrivate()) { } kpRectangularImageSelection::kpRectangularImageSelection (const QRect &rect, - const kpImage &baseImage, - const kpImageSelectionTransparency &transparency) - : kpAbstractImageSelection (rect, baseImage, transparency), - d (new kpRectangularImageSelectionPrivate ()) + const kpImage &baseImage, + const kpImageSelectionTransparency &transparency) + : kpAbstractImageSelection(rect, baseImage, transparency) + , d(new kpRectangularImageSelectionPrivate()) { } kpRectangularImageSelection::kpRectangularImageSelection (const QRect &rect, - const kpImageSelectionTransparency &transparency) - : kpAbstractImageSelection (rect, transparency), - d (new kpRectangularImageSelectionPrivate ()) + const kpImageSelectionTransparency &transparency) + : kpAbstractImageSelection(rect, transparency) + , d(new kpRectangularImageSelectionPrivate()) { } kpRectangularImageSelection::kpRectangularImageSelection (const kpRectangularImageSelection &rhs) - : kpAbstractImageSelection (), - d (new kpRectangularImageSelectionPrivate ()) + : kpAbstractImageSelection() + , d(new kpRectangularImageSelectionPrivate()) { *this = rhs; } -kpRectangularImageSelection &kpRectangularImageSelection::operator= ( - const kpRectangularImageSelection &rhs) +kpRectangularImageSelection &kpRectangularImageSelection::operator=( + const kpRectangularImageSelection &rhs) { - kpAbstractImageSelection::operator= (rhs); + kpAbstractImageSelection::operator=(rhs); return *this; } -kpRectangularImageSelection *kpRectangularImageSelection::clone () const +kpRectangularImageSelection *kpRectangularImageSelection::clone() const { - kpRectangularImageSelection *sel = new kpRectangularImageSelection (); + kpRectangularImageSelection *sel = new kpRectangularImageSelection(); *sel = *this; return sel; } @@ -89,61 +84,53 @@ delete d; } - // public virtual [kpAbstractSelection] -int kpRectangularImageSelection::serialID () const +int kpRectangularImageSelection::serialID() const { return SerialID; } - // public virtual [kpAbstractSelection] -bool kpRectangularImageSelection::isRectangular () const +bool kpRectangularImageSelection::isRectangular() const { return true; } - // public virtual [kpAbstractSelection] -QPolygon kpRectangularImageSelection::calculatePoints () const +QPolygon kpRectangularImageSelection::calculatePoints() const { - return kpAbstractImageSelection::CalculatePointsForRectangle (boundingRect ()); + return kpAbstractImageSelection::CalculatePointsForRectangle(boundingRect()); } - // public virtual [base kpAbstractImageSelection] -QBitmap kpRectangularImageSelection::shapeBitmap (bool nullForRectangular) const +QBitmap kpRectangularImageSelection::shapeBitmap(bool nullForRectangular) const { - Q_ASSERT (boundingRect ().isValid ()); + Q_ASSERT(boundingRect().isValid()); if (nullForRectangular) { return {}; } - QBitmap maskBitmap (width (), height ()); - maskBitmap.fill (Qt::color1/*opaque*/); + QBitmap maskBitmap(width(), height()); + maskBitmap.fill(Qt::color1 /*opaque*/); return maskBitmap; } // public virtual [kpAbstractImageSelection] -QRegion kpRectangularImageSelection::shapeRegion () const +QRegion kpRectangularImageSelection::shapeRegion() const { - return QRegion (boundingRect (), QRegion::Rectangle); + return QRegion(boundingRect(), QRegion::Rectangle); } - // public virtual [kpAbstractSelection] -bool kpRectangularImageSelection::contains (const QPoint &point) const +bool kpRectangularImageSelection::contains(const QPoint &point) const { - return boundingRect ().contains (point); + return boundingRect().contains(point); } - // public virtual [kpAbstractSelection] -void kpRectangularImageSelection::paintBorder (QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const +void kpRectangularImageSelection::paintBorder(QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const { - paintRectangularBorder (destPixmap, docRect, selectionFinished); + paintRectangularBorder(destPixmap, docRect, selectionFinished); } - - diff --git a/layers/selections/kpAbstractSelection.h b/layers/selections/kpAbstractSelection.h --- a/layers/selections/kpAbstractSelection.h +++ b/layers/selections/kpAbstractSelection.h @@ -1,4 +1,3 @@ - // OPT: The selection classes should use copy-on-write. /* @@ -27,24 +26,20 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KPABSTRACTSELECTION_H #define KPABSTRACTSELECTION_H - #include #include "commands/kpCommandSize.h" #include "pixmapfx/kpPixmapFX.h" - class QImage; class QPolygon; class QPoint; class QRect; class QSize; - // // Abstract base class for selections. // @@ -65,7 +60,7 @@ // class kpAbstractSelection : public QObject { -Q_OBJECT + Q_OBJECT // // Initialization @@ -77,23 +72,22 @@ kpAbstractSelection (const QRect &rect); // (Call this in subclass implementations of operator=) - kpAbstractSelection &operator= (const kpAbstractSelection &rhs); + kpAbstractSelection &operator=(const kpAbstractSelection &rhs); public: // To implement, create an instance of your type and then call your // implementation of operator=(). - virtual kpAbstractSelection *clone () const = 0; + virtual kpAbstractSelection *clone() const = 0; ~kpAbstractSelection () override; - // // Marshalling // public: // Returns a unique ID for this type of selection, use for marshalling. - virtual int serialID () const = 0; + virtual int serialID() const = 0; // This is called after your object has been created with the default // constructor. @@ -104,80 +98,76 @@ // // You must override this. Remember to call this base implementation // before your code. - virtual bool readFromStream (QDataStream &stream); + virtual bool readFromStream(QDataStream &stream); // Marshalls the object into the . This is called by // operator<<() so the serialID() has already been written into the // . // // You must override this. Remember to call this base implementation // before your code. - virtual void writeToStream (QDataStream &stream) const; + virtual void writeToStream(QDataStream &stream) const; // Writes the serialID() of the to the and then // calls writeToStream() to do the remaining marshalling. // // (kpSelectionFactory::FromStream() is the ">>" replacement) - friend QDataStream &operator<< (QDataStream &stream, - const kpAbstractSelection &selection); - + friend QDataStream &operator<<(QDataStream &stream, const kpAbstractSelection &selection); // // General Queries // public: // Returns e.g. i18n ("Selection") or i18n ("Text"). - virtual QString name () const = 0; + virtual QString name() const = 0; // Returns the memory usage of the selection (like kpCommand's), // _not_ its dimensions. // // You must override this and add the size returned by this implementation. - virtual kpCommandSize::SizeType size () const; + virtual kpCommandSize::SizeType size() const; public: // e.g. return false for an elliptical selection. - virtual bool isRectangular () const = 0; - + virtual bool isRectangular() const = 0; // // Position & Dimensions // public: // Returns the minimum allowed dimensions of your selection type. // Usually this is 1x1 pixels by pixels. - virtual int minimumWidth () const = 0; - virtual int minimumHeight () const = 0; - QSize minimumSize () const; + virtual int minimumWidth() const = 0; + virtual int minimumHeight() const = 0; + QSize minimumSize() const; public: // (in document coordinates) - int x () const; - int y () const; - QPoint topLeft () const; + int x() const; + int y() const; + QPoint topLeft() const; public: // (in document coordinates) // Returns the width of the bounding rectangle. - int width () const; + int width() const; // Returns the height of the bounding rectangle. - int height () const; + int height() const; // Returns the bounding rectangle. - QRect boundingRect () const; + QRect boundingRect() const; public: // Use this to implement calculatePoints() for rectangular selections. - static QPolygon CalculatePointsForRectangle (const QRect &rect); + static QPolygon CalculatePointsForRectangle(const QRect &rect); // Returns the border. This may be recalculated for every call so // may be slow. - virtual QPolygon calculatePoints () const = 0; - + virtual QPolygon calculatePoints() const = 0; // // Point Testing @@ -189,37 +179,34 @@ // // (for non-rectangular selections, may return false even if // kpView::onSelectionResizeHandle()) - virtual bool contains (const QPoint &point) const = 0; - bool contains (int x, int y) const; - + virtual bool contains(const QPoint &point) const = 0; + bool contains(int x, int y) const; // // Content // public: // i.e. Has an image or text - not just a border. - virtual bool hasContent () const = 0; + virtual bool hasContent() const = 0; // Deletes the content, changing the selection back into a border. // If the selection has no content, it does nothing. - virtual void deleteContent () = 0; - + virtual void deleteContent() = 0; // // Mutation - Movement // public: // (You only need to override this if you store your own border // coordinates) - virtual void moveBy (int dx, int dy); + virtual void moveBy(int dx, int dy); // (These call moveBy() so if you only reimplement moveBy(), that should // be sufficient) - void moveTo (int dx, int dy); - void moveTo (const QPoint &topLeftPoint); - + void moveTo(int dx, int dy); + void moveTo(const QPoint &topLeftPoint); // // Rendering @@ -237,42 +224,37 @@ // However, there is no need to do any explicit clipping to , // since any drawing outside the bounds of is discarded. // However, you may choose to clip for whatever reason e.g. performance. - virtual void paint (QImage *destPixmap, const QRect &docRect) const = 0; - + virtual void paint(QImage *destPixmap, const QRect &docRect) const = 0; protected: // Use this to implement paintBorder() for rectangular selections. - void paintRectangularBorder (QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const; + void paintRectangularBorder(QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const; // Use this to implement paintBorder() for non-rectangular selections // (this calls calculatePoints()). // // If , this also draws a bounding rectangular box. - void paintPolygonalBorder (const QPolygon &points, - QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const; + void paintPolygonalBorder(const QPolygon &points, QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const; public: // Renders the selection border on top of <*destPixmap>. // // is the same as for paint(). // // If is false, the user is still dragging out the // selection border so it may be drawn differently. - virtual void paintBorder (QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const = 0; - + virtual void paintBorder(QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const = 0; signals: // Signals that a view update is required in the document region , // due to the selection changing. - void changed (const QRect &docRect); - + void changed(const QRect &docRect); private: - struct kpAbstractSelectionPrivate * const d; + struct kpAbstractSelectionPrivate *const d; }; - #endif // KPABSTRACTSELECTION_H diff --git a/layers/selections/kpAbstractSelection.cpp b/layers/selections/kpAbstractSelection.cpp --- a/layers/selections/kpAbstractSelection.cpp +++ b/layers/selections/kpAbstractSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION 0 - #include "layers/selections/kpAbstractSelection.h" #include @@ -41,25 +38,24 @@ QRect rect; }; - // protected kpAbstractSelection::kpAbstractSelection () - : QObject (), - d (new kpAbstractSelectionPrivate ()) + : QObject() + , d(new kpAbstractSelectionPrivate()) { - d->rect = QRect (); + d->rect = QRect(); } // protected kpAbstractSelection::kpAbstractSelection (const QRect &rect) - : QObject (), - d (new kpAbstractSelectionPrivate ()) + : QObject() + , d(new kpAbstractSelectionPrivate()) { d->rect = rect; } // protected -kpAbstractSelection &kpAbstractSelection::operator= (const kpAbstractSelection &rhs) +kpAbstractSelection &kpAbstractSelection::operator=(const kpAbstractSelection &rhs) { if (this == &rhs) { return *this; @@ -76,125 +72,120 @@ delete d; } - // public virtual -bool kpAbstractSelection::readFromStream (QDataStream &stream) +bool kpAbstractSelection::readFromStream(QDataStream &stream) { stream >> d->rect; return true; } // public virtual -void kpAbstractSelection::writeToStream (QDataStream &stream) const +void kpAbstractSelection::writeToStream(QDataStream &stream) const { stream << d->rect; } // friend -QDataStream &operator<< (QDataStream &stream, const kpAbstractSelection &selection) +QDataStream &operator<<(QDataStream &stream, const kpAbstractSelection &selection) { #if DEBUG_KP_SELECTION && 1 - qCDebug(kpLogLayers) << "kpAbstractSelection::operator<<(sel: rect=" << - selection.boundingRect (); + qCDebug(kpLogLayers) << "kpAbstractSelection::operator<<(sel: rect=" + <rect.x (); + return d->rect.x(); } // public -int kpAbstractSelection::y () const +int kpAbstractSelection::y() const { - return d->rect.y (); + return d->rect.y(); } // public -QPoint kpAbstractSelection::topLeft () const +QPoint kpAbstractSelection::topLeft() const { - return d->rect.topLeft (); + return d->rect.topLeft(); } - // public -int kpAbstractSelection::width () const +int kpAbstractSelection::width() const { - return boundingRect ().width (); + return boundingRect().width(); } // public -int kpAbstractSelection::height () const +int kpAbstractSelection::height() const { - return boundingRect ().height (); + return boundingRect().height(); } // public -QRect kpAbstractSelection::boundingRect () const +QRect kpAbstractSelection::boundingRect() const { return d->rect; } // public static -QPolygon kpAbstractSelection::CalculatePointsForRectangle (const QRect &rect) +QPolygon kpAbstractSelection::CalculatePointsForRectangle(const QRect &rect) { QPolygon points; // OPT: not space optimal - current code adds duplicate corner points. // top - for (int x = 0; x < rect.width (); x++) { - points.append (QPoint (rect.x () + x, rect.top ())); + for (int x = 0; x < rect.width(); x++) { + points.append(QPoint(rect.x() + x, rect.top())); } // right - for (int y = 0; y < rect.height (); y++) { - points.append (QPoint (rect.right (), rect.y () + y)); + for (int y = 0; y < rect.height(); y++) { + points.append(QPoint(rect.right(), rect.y() + y)); } // bottom - for (int x = rect.width () - 1; x >= 0; x--) { - points.append (QPoint (rect.x () + x, rect.bottom ())); + for (int x = rect.width() - 1; x >= 0; x--) { + points.append(QPoint(rect.x() + x, rect.bottom())); } // left - for (int y = rect.height () - 1; y >= 0; y--) { - points.append (QPoint (rect.left (), rect.y () + y)); + for (int y = rect.height() - 1; y >= 0; y--) { + points.append(QPoint(rect.left(), rect.y() + y)); } return points; } - // public -bool kpAbstractSelection::contains (int x, int y) const +bool kpAbstractSelection::contains(int x, int y) const { - return contains (QPoint (x, y)); + return contains(QPoint(x, y)); } - // public virtual -void kpAbstractSelection::moveBy (int dx, int dy) +void kpAbstractSelection::moveBy(int dx, int dy) { #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "kpAbstractSelection::moveBy(" << dx << "," << dy << ")"; @@ -204,112 +195,105 @@ return; } - QRect oldRect = boundingRect (); + QRect oldRect = boundingRect(); #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "\toldRect=" << oldRect; #endif - d->rect.translate (dx, dy); + d->rect.translate(dx, dy); #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "\tnewRect=" << d->rect; #endif - emit changed (oldRect); - emit changed (boundingRect ()); + emit changed(oldRect); + emit changed(boundingRect()); } // public -void kpAbstractSelection::moveTo (int dx, int dy) +void kpAbstractSelection::moveTo(int dx, int dy) { - moveTo (QPoint (dx, dy)); + moveTo(QPoint(dx, dy)); } // public -void kpAbstractSelection::moveTo (const QPoint &topLeftPoint) +void kpAbstractSelection::moveTo(const QPoint &topLeftPoint) { #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "kpAbstractSelection::moveTo(" << topLeftPoint << ")"; #endif - QRect oldBoundingRect = boundingRect (); + QRect oldBoundingRect = boundingRect(); #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "\toldBoundingRect=" << oldBoundingRect; #endif - if (topLeftPoint == oldBoundingRect.topLeft ()) { + if (topLeftPoint == oldBoundingRect.topLeft()) { return; } - QPoint delta (topLeftPoint - oldBoundingRect.topLeft ()); - moveBy (delta.x (), delta.y ()); + QPoint delta(topLeftPoint - oldBoundingRect.topLeft()); + moveBy(delta.x(), delta.y()); } //--------------------------------------------------------------------- // protected -void kpAbstractSelection::paintRectangularBorder (QImage *destPixmap, - const QRect &docRect, - bool selectionFinished) const +void kpAbstractSelection::paintRectangularBorder(QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const { - (void) selectionFinished; + (void)selectionFinished; #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "kpAbstractSelection::paintRectangularBorder() boundingRect=" - << boundingRect (); + << boundingRect(); #endif #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "\tselection border = rectangle"; - qCDebug(kpLogLayers) << "\t\tx=" << boundingRect ().x () - docRect.x () - << " y=" << boundingRect ().y () - docRect.y () - << " w=" << boundingRect ().width () - << " h=" << boundingRect ().height (); + qCDebug(kpLogLayers) << "\t\tx=" << boundingRect().x() - docRect.x() + << " y=" << boundingRect().y() - docRect.y() + << " w=" << boundingRect().width() + << " h=" << boundingRect().height(); #endif kpPixmapFX::drawStippleRect(destPixmap, - boundingRect ().x () - docRect.x (), - boundingRect ().y () - docRect.y (), - boundingRect ().width (), - boundingRect ().height (), - kpColor::Blue, - kpColor::Yellow); + boundingRect().x() - docRect.x(), + boundingRect().y() - docRect.y(), + boundingRect().width(), + boundingRect().height(), + kpColor::Blue, + kpColor::Yellow); } //--------------------------------------------------------------------- // protected -void kpAbstractSelection::paintPolygonalBorder (const QPolygon &points, - QImage *destPixmap, - const QRect &docRect, - bool selectionFinished) const +void kpAbstractSelection::paintPolygonalBorder(const QPolygon &points, QImage *destPixmap, + const QRect &docRect, bool selectionFinished) const { #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "kpAbstractSelection::paintPolygonalBorder() boundingRect=" - << boundingRect (); + << boundingRect(); #endif QPolygon pointsTranslated = points; - pointsTranslated.translate (-docRect.x (), -docRect.y ()); - - if ( !selectionFinished ) - { - kpPixmapFX::drawPolyline(destPixmap, - pointsTranslated, kpColor::Blue, 1/*pen width*/, kpColor::Yellow); - } - else - { - kpPixmapFX::drawPolygon(destPixmap, - pointsTranslated, - kpColor::Blue, 1/*pen width*/, - kpColor::Invalid/*no background*/, - true/*is final*/, - kpColor::Yellow); - - kpPixmapFX::drawStippleRect(destPixmap, - boundingRect ().x () - docRect.x (), - boundingRect ().y () - docRect.y (), - boundingRect ().width (), - boundingRect ().height (), - kpColor::LightGray, - kpColor::DarkGray); + pointsTranslated.translate(-docRect.x(), -docRect.y()); + + if (!selectionFinished) { + kpPixmapFX::drawPolyline(destPixmap, + pointsTranslated, kpColor::Blue, 1 /*pen width*/, kpColor::Yellow); + } else { + kpPixmapFX::drawPolygon(destPixmap, + pointsTranslated, + kpColor::Blue, 1 /*pen width*/, + kpColor::Invalid /*no background*/, + true /*is final*/, + kpColor::Yellow); + + kpPixmapFX::drawStippleRect(destPixmap, + boundingRect().x() - docRect.x(), + boundingRect().y() - docRect.y(), + boundingRect().width(), + boundingRect().height(), + kpColor::LightGray, + kpColor::DarkGray); } } - diff --git a/layers/selections/kpSelectionDrag.h b/layers/selections/kpSelectionDrag.h --- a/layers/selections/kpSelectionDrag.h +++ b/layers/selections/kpSelectionDrag.h @@ -24,29 +24,26 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_SELECTION_DRAG_H #define KP_SELECTION_DRAG_H #include class kpAbstractImageSelection; - class kpSelectionDrag : public QMimeData { - Q_OBJECT + Q_OBJECT - public: - static const char * const SelectionMimeType; +public: + static const char *const SelectionMimeType; // ASSUMPTION: has content (is not just a border). kpSelectionDrag(const kpAbstractImageSelection &sel); - public: +public: static bool canDecode(const QMimeData *mimeData); static kpAbstractImageSelection *decode(const QMimeData *mimeData); }; - #endif // KP_SELECTION_DRAG_H diff --git a/layers/selections/kpSelectionDrag.cpp b/layers/selections/kpSelectionDrag.cpp --- a/layers/selections/kpSelectionDrag.cpp +++ b/layers/selections/kpSelectionDrag.cpp @@ -25,10 +25,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION_DRAG 0 - #include "kpSelectionDrag.h" #include @@ -44,42 +42,40 @@ //--------------------------------------------------------------------- // public static -const char * const kpSelectionDrag::SelectionMimeType = - "application/x-kolourpaint-selection-400"; +const char *const kpSelectionDrag::SelectionMimeType + = "application/x-kolourpaint-selection-400"; //--------------------------------------------------------------------- kpSelectionDrag::kpSelectionDrag (const kpAbstractImageSelection &sel) { #if DEBUG_KP_SELECTION_DRAG && 1 - qCDebug(kpLogLayers) << "kpSelectionDrag() w=" << sel.width () - << " h=" << sel.height (); + qCDebug(kpLogLayers) << "kpSelectionDrag() w=" << sel.width() + << " h=" << sel.height(); #endif - Q_ASSERT (sel.hasContent ()); + Q_ASSERT(sel.hasContent()); // Store as selection. QByteArray ba; { - QDataStream stream (&ba, QIODevice::WriteOnly); + QDataStream stream(&ba, QIODevice::WriteOnly); stream << sel; } - setData (kpSelectionDrag::SelectionMimeType, ba); + setData(kpSelectionDrag::SelectionMimeType, ba); // Store as image (so that QMimeData::hasImage()) works). // OPT: an awful waste of memory storing image in both selection and QImage - const QImage image = sel.baseImage (); + const QImage image = sel.baseImage(); #if DEBUG_KP_SELECTION_DRAG && 1 - qCDebug(kpLogLayers) << "\timage: w=" << image.width () - << " h=" << image.height (); + qCDebug(kpLogLayers) << "\timage: w=" << image.width() + << " h=" << image.height(); #endif - if (image.isNull ()) - { + if (image.isNull()) { // TODO: proper error handling. qCCritical(kpLogLayers) << "kpSelectionDrag::setSelection() could not convert to image"; - } - else { - setImageData (image); + } else { + setImageData(image); } } @@ -92,13 +88,13 @@ #if DEBUG_KP_SELECTION_DRAG qCDebug(kpLogLayers) << "kpSelectionDrag::canDecode()" - << "hasSel=" << mimeData->hasFormat(kpSelectionDrag::SelectionMimeType) - << "hasImage=" << mimeData->hasImage(); + << "hasSel=" << mimeData->hasFormat(kpSelectionDrag::SelectionMimeType) + << "hasImage=" << mimeData->hasImage(); #endif // mimeData->hasImage() would not check if the data is a valid image - return mimeData->hasFormat(kpSelectionDrag::SelectionMimeType) || - !qvariant_cast(mimeData->imageData()).isNull(); + return mimeData->hasFormat(kpSelectionDrag::SelectionMimeType) + || !qvariant_cast(mimeData->imageData()).isNull(); } //--------------------------------------------------------------------- @@ -109,57 +105,50 @@ #if DEBUG_KP_SELECTION_DRAG qCDebug(kpLogLayers) << "kpSelectionDrag::decode(kpAbstractSelection)"; #endif - Q_ASSERT (mimeData); + Q_ASSERT(mimeData); - if (mimeData->hasFormat (kpSelectionDrag::SelectionMimeType)) - { + if (mimeData->hasFormat(kpSelectionDrag::SelectionMimeType)) { #if DEBUG_KP_SELECTION_DRAG qCDebug(kpLogLayers) << "\tmimeSource hasFormat selection - just return it in QByteArray"; #endif - QByteArray data = mimeData->data (kpSelectionDrag::SelectionMimeType); - QDataStream stream (&data, QIODevice::ReadOnly); + QByteArray data = mimeData->data(kpSelectionDrag::SelectionMimeType); + QDataStream stream(&data, QIODevice::ReadOnly); - return kpSelectionFactory::FromStream (stream); + return kpSelectionFactory::FromStream(stream); } - #if DEBUG_KP_SELECTION_DRAG qCDebug(kpLogLayers) << "\tmimeSource doesn't provide selection - try image"; #endif - QImage image = qvariant_cast (mimeData->imageData ()); - if (!image.isNull ()) - { + QImage image = qvariant_cast (mimeData->imageData()); + if (!image.isNull()) { #if DEBUG_KP_SELECTION_DRAG - qCDebug(kpLogLayers) << "\tok w=" << image.width () << " h=" << image.height (); + qCDebug(kpLogLayers) << "\tok w=" << image.width() << " h=" << image.height(); #endif - return new kpRectangularImageSelection ( - QRect (0, 0, image.width (), image.height ()), image); + return new kpRectangularImageSelection( + QRect(0, 0, image.width(), image.height()), image); } - if ( mimeData->hasUrls() ) // no image, check for path to local image file - { + if (mimeData->hasUrls()) { // no image, check for path to local image file QList urls = mimeData->urls(); - if ( urls.count() && urls[0].isLocalFile() ) - { + if (urls.count() && urls[0].isLocalFile()) { image.load(urls[0].toLocalFile()); - if ( !image.isNull() ) - { + if (!image.isNull()) { return new kpRectangularImageSelection( - QRect(0, 0, image.width(), image.height()), image); + QRect(0, 0, image.width(), image.height()), image); } } } #if DEBUG_KP_SELECTION_DRAG - qCDebug(kpLogLayers) << "kpSelectionDrag::decode(kpAbstractSelection) mimeSource had no sel " - "and could not decode to image"; + qCDebug(kpLogLayers) << "kpSelectionDrag::decode(kpAbstractSelection) mimeSource had no sel " + "and could not decode to image"; #endif - return nullptr; - + return nullptr; } //--------------------------------------------------------------------- diff --git a/layers/selections/kpSelectionFactory.h b/layers/selections/kpSelectionFactory.h --- a/layers/selections/kpSelectionFactory.h +++ b/layers/selections/kpSelectionFactory.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,24 +24,19 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpSelectionFactory_H #define kpSelectionFactory_H - #include "pixmapfx/kpPixmapFX.h" - class QDataStream; class kpAbstractImageSelection; - class kpSelectionFactory { public: - static kpAbstractImageSelection *FromStream (QDataStream &stream); + static kpAbstractImageSelection *FromStream(QDataStream &stream); }; - #endif // kpSelectionFactory_H diff --git a/layers/selections/kpSelectionFactory.cpp b/layers/selections/kpSelectionFactory.cpp --- a/layers/selections/kpSelectionFactory.cpp +++ b/layers/selections/kpSelectionFactory.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION 0 - #include "kpSelectionFactory.h" #include @@ -42,7 +39,7 @@ // public static // TODO: KolourPaint has not been tested against invalid or malicious // clipboard data [Bug #28]. -kpAbstractImageSelection *kpSelectionFactory::FromStream (QDataStream &stream) +kpAbstractImageSelection *kpSelectionFactory::FromStream(QDataStream &stream) { #if DEBUG_KP_SELECTION && 1 qCDebug(kpLogLayers) << "kpSelectionFactory::FromStream()"; @@ -60,29 +57,26 @@ // not selections, since copying text formatting over the clipboard doesn't // seem compelling. kpAbstractImageSelection *imageSel = nullptr; - switch (serialID) - { + switch (serialID) { case kpRectangularImageSelection::SerialID: - imageSel = new kpRectangularImageSelection (); + imageSel = new kpRectangularImageSelection(); break; case kpEllipticalImageSelection::SerialID: - imageSel = new kpEllipticalImageSelection (); + imageSel = new kpEllipticalImageSelection(); break; case kpFreeFormImageSelection::SerialID: - imageSel = new kpFreeFormImageSelection (); + imageSel = new kpFreeFormImageSelection(); break; } // Unknown selection type? - if (imageSel == nullptr) - { + if (imageSel == nullptr) { return nullptr; } - if (!imageSel->readFromStream (stream)) - { + if (!imageSel->readFromStream(stream)) { delete imageSel; return nullptr; } diff --git a/layers/selections/text/kpPreeditText.h b/layers/selections/text/kpPreeditText.h --- a/layers/selections/text/kpPreeditText.h +++ b/layers/selections/text/kpPreeditText.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2010 Tasuku Suzuki All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpPreeditText_H #define kpPreeditText_H @@ -39,18 +37,18 @@ kpPreeditText (); kpPreeditText (const QInputMethodEvent *event); - bool isEmpty () const; + bool isEmpty() const; - const QString &preeditString () const; - int cursorPosition () const; - bool cursorVisible () const; - const QColor &cursorColor () const; - int selectionStart () const; - int selectionLength () const; - const QList &textFormatList () const; + const QString &preeditString() const; + int cursorPosition() const; + bool cursorVisible() const; + const QColor &cursorColor() const; + int selectionStart() const; + int selectionLength() const; + const QList &textFormatList() const; - const QPoint &position () const; - void setPosition (const QPoint &position); + const QPoint &position() const; + void setPosition(const QPoint &position); private: QString m_preeditString; diff --git a/layers/selections/text/kpPreeditText.cpp b/layers/selections/text/kpPreeditText.cpp --- a/layers/selections/text/kpPreeditText.cpp +++ b/layers/selections/text/kpPreeditText.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2010 Tasuku Suzuki All rights reserved. @@ -29,39 +28,41 @@ //--------------------------------------------------------------------- -bool attributeLessThan (const QInputMethodEvent::Attribute &a1, const QInputMethodEvent::Attribute &a2) +bool attributeLessThan(const QInputMethodEvent::Attribute &a1, + const QInputMethodEvent::Attribute &a2) { return a1.start < a2.start; } //--------------------------------------------------------------------- kpPreeditText::kpPreeditText () - : m_cursorPosition (0), m_cursorColor (Qt::transparent), - m_selectionStart (0), m_selectionLength (0), - m_position (-1, -1) + : m_cursorPosition(0) + , m_cursorColor(Qt::transparent) + , m_selectionStart(0) + , m_selectionLength(0) + , m_position(-1, -1) { } //--------------------------------------------------------------------- kpPreeditText::kpPreeditText (const QInputMethodEvent *event) - : m_cursorPosition (0), m_cursorColor (Qt::transparent), - m_selectionStart (0), m_selectionLength (0), - m_position (-1, -1) + : m_cursorPosition(0) + , m_cursorColor(Qt::transparent) + , m_selectionStart(0) + , m_selectionLength(0) + , m_position(-1, -1) { - m_preeditString = event->preeditString (); - for (const auto &attr : event->attributes ()) - { - switch (attr.type) - { + m_preeditString = event->preeditString(); + for (const auto &attr : event->attributes()) { + switch (attr.type) { case QInputMethodEvent::TextFormat: - m_textFormatList.append (attr); + m_textFormatList.append(attr); break; case QInputMethodEvent::Cursor: m_cursorPosition = attr.start; - if (attr.length > 0) - { + if (attr.length > 0) { m_cursorColor = attr.value.value (); } break; @@ -73,68 +74,68 @@ break; } } - qSort (m_textFormatList.begin (), m_textFormatList.end (), attributeLessThan); + qSort(m_textFormatList.begin(), m_textFormatList.end(), attributeLessThan); } //--------------------------------------------------------------------- -bool kpPreeditText::isEmpty () const +bool kpPreeditText::isEmpty() const { - return m_preeditString.isEmpty (); + return m_preeditString.isEmpty(); } //--------------------------------------------------------------------- -const QString &kpPreeditText::preeditString () const +const QString &kpPreeditText::preeditString() const { return m_preeditString; } //--------------------------------------------------------------------- -int kpPreeditText::cursorPosition () const +int kpPreeditText::cursorPosition() const { return m_cursorPosition; } //--------------------------------------------------------------------- -const QColor &kpPreeditText::cursorColor () const +const QColor &kpPreeditText::cursorColor() const { return m_cursorColor; } //--------------------------------------------------------------------- -int kpPreeditText::selectionStart () const +int kpPreeditText::selectionStart() const { return m_selectionStart; } //--------------------------------------------------------------------- -int kpPreeditText::selectionLength () const +int kpPreeditText::selectionLength() const { return m_selectionLength; } //--------------------------------------------------------------------- -const QList &kpPreeditText::textFormatList () const +const QList &kpPreeditText::textFormatList() const { return m_textFormatList; } //--------------------------------------------------------------------- -const QPoint &kpPreeditText::position () const +const QPoint &kpPreeditText::position() const { return m_position; } //--------------------------------------------------------------------- -void kpPreeditText::setPosition (const QPoint &position) +void kpPreeditText::setPosition(const QPoint &position) { m_position = position; } diff --git a/layers/selections/text/kpTextSelection.h b/layers/selections/text/kpTextSelection.h --- a/layers/selections/text/kpTextSelection.h +++ b/layers/selections/text/kpTextSelection.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTextSelection_H #define kpTextSelection_H - #include "layers/selections/kpAbstractSelection.h" #include "imagelib/kpImage.h" #include "layers/selections/text/kpTextStyle.h" @@ -89,54 +86,50 @@ // class kpTextSelection : public kpAbstractSelection { -Q_OBJECT + Q_OBJECT // // Initialization // public: - kpTextSelection (const QRect &rect = QRect (), - const kpTextStyle &textStyle = kpTextStyle ()); + kpTextSelection (const QRect &rect = QRect(), const kpTextStyle &textStyle = kpTextStyle()); kpTextSelection (const QRect &rect, const QList &textLines, - const kpTextStyle &textStyle); + const kpTextStyle &textStyle); kpTextSelection (const kpTextSelection &rhs); - kpTextSelection &operator= (const kpTextSelection &rhs); + kpTextSelection &operator=(const kpTextSelection &rhs); - kpTextSelection *clone () const override; + kpTextSelection *clone() const override; // Returns a copy of the text selection but with new dimensions // x . - kpTextSelection *resized (int newWidth, int newHeight) const; + kpTextSelection *resized(int newWidth, int newHeight) const; ~kpTextSelection () override; - // // Marshalling // public: - int serialID () const override; + int serialID() const override; - bool readFromStream (QDataStream &stream) override; - - void writeToStream (QDataStream &stream) const override; + bool readFromStream(QDataStream &stream) override; + void writeToStream(QDataStream &stream) const override; // // General Queries // public: - QString name () const override; + QString name() const override; - kpCommandSize::SizeType size () const override; + kpCommandSize::SizeType size() const override; public: - bool isRectangular () const override; - + bool isRectangular() const override; // // Position & Dimensions @@ -148,89 +141,85 @@ // // This leaves enough room for the border on all 4 sides and also a // text area big enough to fit a character in an extremely small font. - static int MinimumWidthForTextStyle (const kpTextStyle &textStyle); - static int MinimumHeightForTextStyle (const kpTextStyle &textStyle); - static QSize MinimumSizeForTextStyle (const kpTextStyle &textStyle); + static int MinimumWidthForTextStyle(const kpTextStyle &textStyle); + static int MinimumHeightForTextStyle(const kpTextStyle &textStyle); + static QSize MinimumSizeForTextStyle(const kpTextStyle &textStyle); // REFACTOR: Enforce in kpTextSelection, not just in kpToolSelection & // when pasting (in kpMainWindow). // // Otherwise, if enforcement fails, e.g. textAreaRect() will // not work. - int minimumWidth () const override; - int minimumHeight () const override; + int minimumWidth() const override; + int minimumHeight() const override; public: // Returns the suggested minimum size that a textbox should be if it is of // the given . // // This leaves enough room for the border on all 4 sides and also for // a small line of the text in the given text style. - static int PreferredMinimumWidthForTextStyle (const kpTextStyle &textStyle); - static int PreferredMinimumHeightForTextStyle (const kpTextStyle &textStyle); - static QSize PreferredMinimumSizeForTextStyle (const kpTextStyle &textStyle); + static int PreferredMinimumWidthForTextStyle(const kpTextStyle &textStyle); + static int PreferredMinimumHeightForTextStyle(const kpTextStyle &textStyle); + static QSize PreferredMinimumSizeForTextStyle(const kpTextStyle &textStyle); public: // Returns the size of the text border. Constant. - static int TextBorderSize (); + static int TextBorderSize(); // Returns the rectangle that text lines are drawn on top of. // This will be a sub-rectangle of boundingRect() and is therefore, // in document coordinates like everything else in this class. - QRect textAreaRect () const; + QRect textAreaRect() const; public: - QPolygon calculatePoints () const override; - + QPolygon calculatePoints() const override; // // Point Testing // public: - bool contains (const QPoint &point) const override; + bool contains(const QPoint &point) const override; public: - bool pointIsInTextBorderArea (const QPoint &point) const; - bool pointIsInTextArea (const QPoint &point) const; - + bool pointIsInTextBorderArea(const QPoint &point) const; + bool pointIsInTextArea(const QPoint &point) const; // // Content // public: // (see class header comment) - bool hasContent () const override; + bool hasContent() const override; - void deleteContent () override; + void deleteContent() override; public: - QList textLines () const; - void setTextLines (const QList &textLines); + QList textLines() const; + void setTextLines(const QList &textLines); - static QString TextForTextLines (const QList &textLines); + static QString TextForTextLines(const QList &textLines); // Returns textLines() as one long newline-separated string. // If the last text line is not empty, there is no trailing newline. - QString text () const; - + QString text() const; // // Text Style // public: - kpTextStyle textStyle () const; - void setTextStyle (const kpTextStyle &textStyle); - + kpTextStyle textStyle() const; + void setTextStyle(const kpTextStyle &textStyle); // // Preedit Text // public: - kpPreeditText preeditText () const; - void setPreeditText (const kpPreeditText &preeditText); + kpPreeditText preeditText() const; + void setPreeditText(const kpPreeditText &preeditText); // // Cursor @@ -245,31 +234,31 @@ // row/column (in textLines()) for the point. // // If the given point is not in the text area, it returns -1. - int closestTextRowForPoint (const QPoint &point) const; - int closestTextColForPoint (const QPoint &point) const; + int closestTextRowForPoint(const QPoint &point) const; + int closestTextColForPoint(const QPoint &point) const; // Given a valid row and column in textLines(), returns the top-left // point of where the text cursor should be rendered. // TODO: Code is not symmetric to closestTest{Row,Col}ForPoint() // [look at the Y/row value calculations] // // If the row and column is not inside textLines(), it returns // KP_INVALID_POINT. - QPoint pointForTextRowCol (int row, int col) const; - + QPoint pointForTextRowCol(int row, int col) const; // // Rendering // private: - void drawPreeditString(QPainter &painter, int &x, int y, const kpPreeditText &preeditText) const; + void drawPreeditString(QPainter &painter, int &x, int y, + const kpPreeditText &preeditText) const; public: void paint(QImage *destPixmap, const QRect &docRect) const override; void paintBorder(QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const override; + bool selectionFinished) const override; public: // Returns an image that contains the painted text (without a border). @@ -283,12 +272,10 @@ // like stamping this text selection onto the document image (the latter // is achieved via kpDocument::selectionPushOntoDocument(), antialiases // and is more correct). - kpImage approximateImage () const; - + kpImage approximateImage() const; private: - struct kpTextSelectionPrivate * const d; + struct kpTextSelectionPrivate *const d; }; - #endif // kpTextSelection_H diff --git a/layers/selections/text/kpTextSelection.cpp b/layers/selections/text/kpTextSelection.cpp --- a/layers/selections/text/kpTextSelection.cpp +++ b/layers/selections/text/kpTextSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2010 Tasuku Suzuki @@ -26,10 +25,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION 0 - #include "kpTextSelection.h" #include "kpTextSelectionPrivate.h" @@ -41,39 +38,36 @@ #include #include - // public -kpTextSelection::kpTextSelection (const QRect &rect, - const kpTextStyle &textStyle) - : kpAbstractSelection (rect), - d (new kpTextSelectionPrivate ()) +kpTextSelection::kpTextSelection (const QRect &rect, const kpTextStyle &textStyle) + : kpAbstractSelection(rect) + , d(new kpTextSelectionPrivate()) { d->textStyle = textStyle; } // public -kpTextSelection::kpTextSelection (const QRect &rect, - const QList &textLines, - const kpTextStyle &textStyle) - : kpAbstractSelection (rect), - d (new kpTextSelectionPrivate ()) +kpTextSelection::kpTextSelection (const QRect &rect, const QList &textLines, + const kpTextStyle &textStyle) + : kpAbstractSelection(rect) + , d(new kpTextSelectionPrivate()) { d->textLines = textLines; d->textStyle = textStyle; } // public kpTextSelection::kpTextSelection (const kpTextSelection &rhs) - : kpAbstractSelection (), - d (new kpTextSelectionPrivate ()) + : kpAbstractSelection() + , d(new kpTextSelectionPrivate()) { *this = rhs; } // public -kpTextSelection &kpTextSelection::operator= (const kpTextSelection &rhs) +kpTextSelection &kpTextSelection::operator=(const kpTextSelection &rhs) { - kpAbstractSelection::operator= (rhs); + kpAbstractSelection::operator=(rhs); d->textLines = rhs.d->textLines; d->textStyle = rhs.d->textStyle; @@ -83,265 +77,254 @@ } // public virtual [base kpAbstractSelection] -kpTextSelection *kpTextSelection::clone () const +kpTextSelection *kpTextSelection::clone() const { - kpTextSelection *sel = new kpTextSelection (); + kpTextSelection *sel = new kpTextSelection(); *sel = *this; return sel; } // public -kpTextSelection *kpTextSelection::resized (int newWidth, int newHeight) const +kpTextSelection *kpTextSelection::resized(int newWidth, int newHeight) const { - return new kpTextSelection (QRect (x (), y (), newWidth, newHeight), - d->textLines, - d->textStyle); + return new kpTextSelection(QRect(x(), y(), newWidth, newHeight), + d->textLines, + d->textStyle); } // public kpTextSelection::~kpTextSelection () { delete d; } - // public virtual [kpAbstractSelection] -int kpTextSelection::serialID () const +int kpTextSelection::serialID() const { - Q_ASSERT (!"Marshalling not supported"); + Q_ASSERT(!"Marshalling not supported"); return -1; } // public virtual [base kpAbstractSelection] -bool kpTextSelection::readFromStream (QDataStream &stream) +bool kpTextSelection::readFromStream(QDataStream &stream) { - (void) stream; + (void)stream; - Q_ASSERT (!"Marshalling not supported"); + Q_ASSERT(!"Marshalling not supported"); return false; } // public virtual [base kpAbstractSelection] -void kpTextSelection::writeToStream (QDataStream &stream) const +void kpTextSelection::writeToStream(QDataStream &stream) const { - (void) stream; + (void)stream; - Q_ASSERT (!"Marshalling not supported"); + Q_ASSERT(!"Marshalling not supported"); } - // public virtual [kpAbstractSelection] -QString kpTextSelection::name () const +QString kpTextSelection::name() const { - return i18n ("Text"); + return i18n("Text"); } - // public virtual [base kpAbstractSelection] -kpCommandSize::SizeType kpTextSelection::size () const +kpCommandSize::SizeType kpTextSelection::size() const { - return kpAbstractSelection::size () + - kpCommandSize::StringSize (text ()); + return kpAbstractSelection::size() + +kpCommandSize::StringSize(text()); } - // public virtual [kpAbstractSelection] -bool kpTextSelection::isRectangular () const +bool kpTextSelection::isRectangular() const { return true; } - // public static -int kpTextSelection::MinimumWidthForTextStyle (const kpTextStyle &) +int kpTextSelection::MinimumWidthForTextStyle(const kpTextStyle &) { - return (kpTextSelection::TextBorderSize () * 2 + 5); + return kpTextSelection::TextBorderSize() * 2 + 5; } // public static -int kpTextSelection::MinimumHeightForTextStyle (const kpTextStyle &) +int kpTextSelection::MinimumHeightForTextStyle(const kpTextStyle &) { - return (kpTextSelection::TextBorderSize () * 2 + 5); + return kpTextSelection::TextBorderSize() * 2 + 5; } // public static -QSize kpTextSelection::MinimumSizeForTextStyle (const kpTextStyle &textStyle) +QSize kpTextSelection::MinimumSizeForTextStyle(const kpTextStyle &textStyle) { - return {kpTextSelection::MinimumWidthForTextStyle (textStyle), - kpTextSelection::MinimumHeightForTextStyle (textStyle)}; + return { + kpTextSelection::MinimumWidthForTextStyle(textStyle), + kpTextSelection::MinimumHeightForTextStyle(textStyle) + }; } - // public virtual [kpAbstractSelection] -int kpTextSelection::minimumWidth () const +int kpTextSelection::minimumWidth() const { - return kpTextSelection::MinimumWidthForTextStyle (textStyle ()); + return kpTextSelection::MinimumWidthForTextStyle(textStyle()); } // public virtual [kpAbstractSelection] -int kpTextSelection::minimumHeight () const +int kpTextSelection::minimumHeight() const { - return kpTextSelection::MinimumHeightForTextStyle (textStyle ()); + return kpTextSelection::MinimumHeightForTextStyle(textStyle()); } - // public static -int kpTextSelection::PreferredMinimumWidthForTextStyle (const kpTextStyle &textStyle) +int kpTextSelection::PreferredMinimumWidthForTextStyle(const kpTextStyle &textStyle) { - const int about15CharsWidth = - textStyle.fontMetrics ().width ( - QStringLiteral ("1234567890abcde")); + const int about15CharsWidth + = textStyle.fontMetrics().width( + QStringLiteral("1234567890abcde")); - const int preferredMinWidth = - qMax (150, - kpTextSelection::TextBorderSize () * 2 + about15CharsWidth); + const int preferredMinWidth + = qMax(150, + kpTextSelection::TextBorderSize() * 2 + about15CharsWidth); - return qMax (kpTextSelection::MinimumWidthForTextStyle (textStyle), - qMin (250, preferredMinWidth)); + return qMax(kpTextSelection::MinimumWidthForTextStyle(textStyle), + qMin(250, preferredMinWidth)); } // public static -int kpTextSelection::PreferredMinimumHeightForTextStyle (const kpTextStyle &textStyle) +int kpTextSelection::PreferredMinimumHeightForTextStyle(const kpTextStyle &textStyle) { - const int preferredMinHeight = - kpTextSelection::TextBorderSize () * 2 + textStyle.fontMetrics ().height (); + const int preferredMinHeight + = kpTextSelection::TextBorderSize() * 2 + textStyle.fontMetrics().height(); - return qMax (kpTextSelection::MinimumHeightForTextStyle (textStyle), - qMin (150, preferredMinHeight)); + return qMax(kpTextSelection::MinimumHeightForTextStyle(textStyle), + qMin(150, preferredMinHeight)); } // public static -QSize kpTextSelection::PreferredMinimumSizeForTextStyle (const kpTextStyle &textStyle) +QSize kpTextSelection::PreferredMinimumSizeForTextStyle(const kpTextStyle &textStyle) { - return {kpTextSelection::PreferredMinimumWidthForTextStyle (textStyle), - kpTextSelection::PreferredMinimumHeightForTextStyle (textStyle)}; + return { + kpTextSelection::PreferredMinimumWidthForTextStyle(textStyle), + kpTextSelection::PreferredMinimumHeightForTextStyle(textStyle) + }; } - // public static -int kpTextSelection::TextBorderSize () +int kpTextSelection::TextBorderSize() { return 1; } // public -QRect kpTextSelection::textAreaRect () const +QRect kpTextSelection::textAreaRect() const { - return {x () + kpTextSelection::TextBorderSize (), - y () + kpTextSelection::TextBorderSize (), - width () - kpTextSelection::TextBorderSize () * 2, - height () - kpTextSelection::TextBorderSize () * 2}; + return { + x() + kpTextSelection::TextBorderSize(), + y() + kpTextSelection::TextBorderSize(), + width() - kpTextSelection::TextBorderSize() * 2, + height() - kpTextSelection::TextBorderSize() * 2 + }; } - // public virtual [kpAbstractSelection] -QPolygon kpTextSelection::calculatePoints () const +QPolygon kpTextSelection::calculatePoints() const { - return kpAbstractSelection::CalculatePointsForRectangle (boundingRect ()); + return kpAbstractSelection::CalculatePointsForRectangle(boundingRect()); } - // public virtual [kpAbstractSelection] -bool kpTextSelection::contains (const QPoint &point) const +bool kpTextSelection::contains(const QPoint &point) const { - return boundingRect ().contains (point); + return boundingRect().contains(point); } - // public -bool kpTextSelection::pointIsInTextBorderArea (const QPoint &point) const +bool kpTextSelection::pointIsInTextBorderArea(const QPoint &point) const { - return (boundingRect ().contains (point) && !pointIsInTextArea (point)); + return boundingRect().contains(point) && !pointIsInTextArea(point); } // public -bool kpTextSelection::pointIsInTextArea (const QPoint &point) const +bool kpTextSelection::pointIsInTextArea(const QPoint &point) const { - return textAreaRect ().contains (point); + return textAreaRect().contains(point); } - // public virtual [kpAbstractSelection] -bool kpTextSelection::hasContent () const +bool kpTextSelection::hasContent() const { - return !d->textLines.isEmpty (); + return !d->textLines.isEmpty(); } // public virtual [kpAbstractSelection] -void kpTextSelection::deleteContent () +void kpTextSelection::deleteContent() { - if (!hasContent ()) { + if (!hasContent()) { return; } - setTextLines (QList ()); + setTextLines(QList ()); } - // public -QList kpTextSelection::textLines () const +QList kpTextSelection::textLines() const { return d->textLines; } // public -void kpTextSelection::setTextLines (const QList &textLines_) +void kpTextSelection::setTextLines(const QList &textLines_) { d->textLines = textLines_; - emit changed (boundingRect ()); + emit changed(boundingRect()); } - // public static -QString kpTextSelection::TextForTextLines (const QList &textLines) +QString kpTextSelection::TextForTextLines(const QList &textLines) { - if (textLines.isEmpty ()) { + if (textLines.isEmpty()) { return {}; } QString bigString = textLines [0]; - for (QList ::const_iterator it = textLines.begin () + 1; - it != textLines.end (); - ++it) - { - bigString += QLatin1String ("\n"); + for (QList ::const_iterator it = textLines.begin() + 1; + it != textLines.end(); + ++it) { + bigString += QLatin1String("\n"); bigString += (*it); } return bigString; } // public -QString kpTextSelection::text () const +QString kpTextSelection::text() const { - return kpTextSelection::TextForTextLines (d->textLines); + return kpTextSelection::TextForTextLines(d->textLines); } - // public -kpTextStyle kpTextSelection::textStyle () const +kpTextStyle kpTextSelection::textStyle() const { return d->textStyle; } // public -void kpTextSelection::setTextStyle (const kpTextStyle &textStyle) +void kpTextSelection::setTextStyle(const kpTextStyle &textStyle) { d->textStyle = textStyle; - emit changed (boundingRect ()); + emit changed(boundingRect()); } -kpPreeditText kpTextSelection::preeditText () const +kpPreeditText kpTextSelection::preeditText() const { return d->preeditText; } -void kpTextSelection::setPreeditText (const kpPreeditText &preeditText) +void kpTextSelection::setPreeditText(const kpPreeditText &preeditText) { d->preeditText = preeditText; - emit changed (boundingRect ()); + emit changed(boundingRect()); } - diff --git a/layers/selections/text/kpTextSelectionPrivate.h b/layers/selections/text/kpTextSelectionPrivate.h --- a/layers/selections/text/kpTextSelectionPrivate.h +++ b/layers/selections/text/kpTextSelectionPrivate.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTextSelectionPrivate_H #define kpTextSelectionPrivate_H - #include #include "imagelib/kpImage.h" @@ -43,5 +40,4 @@ kpPreeditText preeditText; }; - #endif // kpTextSelectionPrivate_H diff --git a/layers/selections/text/kpTextSelection_Cursor.cpp b/layers/selections/text/kpTextSelection_Cursor.cpp --- a/layers/selections/text/kpTextSelection_Cursor.cpp +++ b/layers/selections/text/kpTextSelection_Cursor.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2010 Tasuku Suzuki @@ -26,10 +25,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION 0 - #include "kpTextSelection.h" #include "kpTextSelectionPrivate.h" @@ -42,88 +39,85 @@ #include #include - // public -int kpTextSelection::closestTextRowForPoint (const QPoint &point) const +int kpTextSelection::closestTextRowForPoint(const QPoint &point) const { - if (!pointIsInTextArea (point)) { + if (!pointIsInTextArea(point)) { return -1; } - const QFontMetrics fontMetrics (d->textStyle.fontMetrics ()); + const QFontMetrics fontMetrics(d->textStyle.fontMetrics()); - int row = (point.y () - textAreaRect ().y ()) / - fontMetrics.lineSpacing (); - if (row >= static_cast (d->textLines.size ())) { - row = d->textLines.size () - 1; + int row = (point.y() - textAreaRect().y()) + /fontMetrics.lineSpacing(); + if (row >= static_cast(d->textLines.size())) { + row = d->textLines.size() - 1; } return row; } // public -int kpTextSelection::closestTextColForPoint (const QPoint &point) const +int kpTextSelection::closestTextColForPoint(const QPoint &point) const { - int row = closestTextRowForPoint (point); - if (row < 0 || row >= static_cast (d->textLines.size ())) { + int row = closestTextRowForPoint(point); + if (row < 0 || row >= static_cast(d->textLines.size())) { return -1; } - const int localX = point.x () - textAreaRect ().x (); + const int localX = point.x() - textAreaRect().x(); - const QFontMetrics fontMetrics (d->textStyle.fontMetrics ()); + const QFontMetrics fontMetrics(d->textStyle.fontMetrics()); // (should be 0 but call just in case) - int charLocalLeft = fontMetrics.width (d->textLines [row], 0); + int charLocalLeft = fontMetrics.width(d->textLines [row], 0); // OPT: binary search or guess location then move - for (int col = 0; col < static_cast (d->textLines [row].length ()); col++) - { + for (int col = 0; col < static_cast(d->textLines [row].length()); col++) { // OPT: fontMetrics::charWidth() might be faster - const int nextCharLocalLeft = fontMetrics.width (d->textLines [row], col + 1); + const int nextCharLocalLeft = fontMetrics.width(d->textLines [row], col + 1); if (localX <= (charLocalLeft + nextCharLocalLeft) / 2) { return col; } charLocalLeft = nextCharLocalLeft; } - return d->textLines [row].length ()/*past end of line*/; + return d->textLines [row].length() /*past end of line*/; } //--------------------------------------------------------------------- // public -QPoint kpTextSelection::pointForTextRowCol (int row, int col) const +QPoint kpTextSelection::pointForTextRowCol(int row, int col) const { kpPreeditText preeditText = d->preeditText; - if ((row < 0 || col < 0) || - (preeditText.isEmpty () && - (row >= static_cast (d->textLines.size ()) || col > static_cast (d->textLines [row].length ())))) - { + if ((row < 0 || col < 0) + || (preeditText.isEmpty() + && (row >= static_cast(d->textLines.size()) + || col > static_cast(d->textLines [row].length())))) { #if DEBUG_KP_SELECTION && 1 - qCDebug(kpLogLayers) << "kpTextSelection::pointForTextRowCol(" - << row << "," - << col << ") out of range" - << " textLines='" - << text () - << "'"; + qCDebug(kpLogLayers) << "kpTextSelection::pointForTextRowCol(" + << row << "," + << col << ") out of range" + << " textLines='" + << text() + << "'"; #endif return KP_INVALID_POINT; } - const QFontMetrics fontMetrics (d->textStyle.fontMetrics ()); + const QFontMetrics fontMetrics(d->textStyle.fontMetrics()); - QString line = (d->textLines.count () > row) ? d->textLines[row] : QString (); - if (row == preeditText.position ().y ()) - { - line.insert (preeditText.position ().x (), preeditText.preeditString ()); + QString line = (d->textLines.count() > row) ? d->textLines[row] : QString(); + if (row == preeditText.position().y()) { + line.insert(preeditText.position().x(), preeditText.preeditString()); } - const int x = fontMetrics.width (line.left (col)); - const int y = row * fontMetrics.height () + - (row >= 1 ? row * fontMetrics.leading () : 0); + const int x = fontMetrics.width(line.left(col)); + const int y = row * fontMetrics.height() + +(row >= 1 ? row * fontMetrics.leading() : 0); - return textAreaRect ().topLeft () + QPoint (x, y); + return textAreaRect().topLeft() + QPoint(x, y); } //--------------------------------------------------------------------- diff --git a/layers/selections/text/kpTextSelection_Paint.cpp b/layers/selections/text/kpTextSelection_Paint.cpp --- a/layers/selections/text/kpTextSelection_Paint.cpp +++ b/layers/selections/text/kpTextSelection_Paint.cpp @@ -1,4 +1,3 @@ - // REFACTOR: Move into kpPainter /* @@ -28,10 +27,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_SELECTION 0 - #include "kpTextSelection.h" #include "kpTextSelectionPrivate.h" @@ -49,65 +46,62 @@ //--------------------------------------------------------------------- -void kpTextSelection::drawPreeditString(QPainter &painter, int &x, int y, const kpPreeditText &preeditText) const +void kpTextSelection::drawPreeditString(QPainter &painter, int &x, int y, + const kpPreeditText &preeditText) const { int i = 0; - const QString& preeditString = preeditText.preeditString (); + const QString &preeditString = preeditText.preeditString(); QString str; - for (const auto &attr : preeditText.textFormatList ()) - { + for (const auto &attr : preeditText.textFormatList()) { int start = attr.start; int length = attr.length; - QTextCharFormat format = qvariant_cast (attr.value).toCharFormat (); + QTextCharFormat format = qvariant_cast(attr.value).toCharFormat(); - if (i > start) - { + if (i > start) { length = length - i + start; start = i; } if (length <= 0) { continue; } - if (i < start) - { - str = preeditString.mid (i, start - i); - painter.drawText (x, y, str); - x += painter.fontMetrics ().width (str); + if (i < start) { + str = preeditString.mid(i, start - i); + painter.drawText(x, y, str); + x += painter.fontMetrics().width(str); } painter.save(); - str = preeditString.mid (start, length); - int width = painter.fontMetrics().width (str); - if (format.background ().color () != Qt::black) - { - painter.save (); - painter.setPen (format.background ().color ()); - painter.setBrush (format.background()); - painter.drawRect (x, y - painter.fontMetrics ().ascent (), width, painter.fontMetrics ().height ()); - painter.restore (); + str = preeditString.mid(start, length); + int width = painter.fontMetrics().width(str); + if (format.background().color() != Qt::black) { + painter.save(); + painter.setPen(format.background().color()); + painter.setBrush(format.background()); + painter.drawRect(x, y - painter.fontMetrics().ascent(), width, + painter.fontMetrics().height()); + painter.restore(); } - if (format.foreground ().color () != Qt::black) - { - painter.setBrush (format.foreground ()); - painter.setPen (format.foreground ().color ()); + if (format.foreground().color() != Qt::black) { + painter.setBrush(format.foreground()); + painter.setPen(format.foreground().color()); } - if (format.underlineStyle ()) - { - painter.drawLine (x, y + painter.fontMetrics ().descent (), x + width, y + painter.fontMetrics ().descent ()); + if (format.underlineStyle()) { + painter.drawLine(x, + y + painter.fontMetrics().descent(), x + width, + y + painter.fontMetrics().descent()); } - painter.drawText (x, y, str); + painter.drawText(x, y, str); x += width; - painter.restore (); + painter.restore(); i = start + length; } - if (i < preeditString.length ()) - { - str = preeditString.mid (i); - painter.drawText (x, y, str); - x += painter.fontMetrics ().width (str); + if (i < preeditString.length()) { + str = preeditString.mid(i); + painter.drawText(x, y, str); + x += painter.fontMetrics().width(str); } } @@ -118,156 +112,144 @@ { #if DEBUG_KP_SELECTION qCDebug(kpLogLayers) << "kpTextSelection::paint() textStyle: fcol=" - << (int *) d->textStyle.foregroundColor ().toQRgb () - << " bcol=" - << (int *) d->textStyle.backgroundColor ().toQRgb (); + << (int *)d->textStyle.foregroundColor().toQRgb() + << " bcol=" + << (int *)d->textStyle.backgroundColor().toQRgb(); #endif // Drawing text is slow so if the text box will be rendered completely // outside of , don't bother rendering it at all. - const QRect modifyingRect = docRect.intersected (boundingRect ()); - if (modifyingRect.isEmpty ()) { + const QRect modifyingRect = docRect.intersected(boundingRect()); + if (modifyingRect.isEmpty()) { return; } - // Is the text box completely invisible? - if (textStyle ().foregroundColor ().isTransparent () && - textStyle ().backgroundColor ().isTransparent ()) - { + if (textStyle().foregroundColor().isTransparent() + && textStyle().backgroundColor().isTransparent()) { return; } kpImage floatImage(modifyingRect.size(), QImage::Format_ARGB32_Premultiplied); floatImage.fill(0); QRect theWholeAreaRect, theTextAreaRect; - theWholeAreaRect = boundingRect ().translated (-modifyingRect.topLeft ()); - theTextAreaRect = textAreaRect ().translated (-modifyingRect.topLeft ()); + theWholeAreaRect = boundingRect().translated(-modifyingRect.topLeft()); + theTextAreaRect = textAreaRect().translated(-modifyingRect.topLeft()); QList theTextLines = textLines(); kpTextStyle theTextStyle = textStyle(); - const QFontMetrics fontMetrics (theTextStyle.font ()); + const QFontMetrics fontMetrics(theTextStyle.font()); #if DEBUG_KP_SELECTION qCDebug(kpLogLayers) << "kpTextSelection_Paint.cpp:DrawTextHelper"; - qCDebug(kpLogLayers) << "\theight=" << fontMetrics.height () - << " leading=" << fontMetrics.leading () - << " ascent=" << fontMetrics.ascent () - << " descent=" << fontMetrics.descent () - << " lineSpacing=" << fontMetrics.lineSpacing (); + qCDebug(kpLogLayers) << "\theight=" << fontMetrics.height() + << " leading=" << fontMetrics.leading() + << " ascent=" << fontMetrics.ascent() + << " descent=" << fontMetrics.descent() + << " lineSpacing=" << fontMetrics.lineSpacing(); #endif QPainter painter(&floatImage); // Fill in the background using the transparent/opaque tool setting - if ( theTextStyle.isBackgroundTransparent() ) { - painter.fillRect(theWholeAreaRect, Qt::transparent); - } - else { - painter.fillRect(theWholeAreaRect, theTextStyle.backgroundColor().toQColor()); + if (theTextStyle.isBackgroundTransparent()) { + painter.fillRect(theWholeAreaRect, Qt::transparent); + } else { + painter.fillRect(theWholeAreaRect, theTextStyle.backgroundColor().toQColor()); } painter.setClipRect(theWholeAreaRect); painter.setPen(theTextStyle.foregroundColor().toQColor()); painter.setFont(theTextStyle.font()); - if ( theTextStyle.foregroundColor().toQColor().alpha() < 255 ) - { - // if the foreground color has an alpha channel, we want to - // see through the background, so we first need to punch holes - // into the background where the text is - painter.setCompositionMode(QPainter::CompositionMode_Clear); - - int baseLine = theTextAreaRect.y () + fontMetrics.ascent (); - for (const auto &str : theTextLines) - { - painter.drawText (theTextAreaRect.x (), baseLine, str); - baseLine += fontMetrics.lineSpacing (); - - // if the next textline would already be below the visible text area, stop drawing - if ( (baseLine - fontMetrics.ascent()) > (theTextAreaRect.y() + theTextAreaRect.height()) ) { - break; - } - } - // the next text drawing will now blend the text foreground color with - // what is really below the text background - painter.setCompositionMode(QPainter::CompositionMode_SourceOver); + if (theTextStyle.foregroundColor().toQColor().alpha() < 255) { + // if the foreground color has an alpha channel, we want to + // see through the background, so we first need to punch holes + // into the background where the text is + painter.setCompositionMode(QPainter::CompositionMode_Clear); + + int baseLine = theTextAreaRect.y() + fontMetrics.ascent(); + for (const auto &str : theTextLines) { + painter.drawText(theTextAreaRect.x(), baseLine, str); + baseLine += fontMetrics.lineSpacing(); + + // if the next textline would already be below the visible text area, stop drawing + if ((baseLine - fontMetrics.ascent()) + > (theTextAreaRect.y() + theTextAreaRect.height())) { + break; + } + } + // the next text drawing will now blend the text foreground color with + // what is really below the text background + painter.setCompositionMode(QPainter::CompositionMode_SourceOver); } // Draw a line at a time instead of using QPainter::drawText(QRect,...). // Else, the line heights become >QFontMetrics::height() if you type Chinese // characters (!) and then the cursor gets out of sync. - int baseLine = theTextAreaRect.y () + fontMetrics.ascent (); + int baseLine = theTextAreaRect.y() + fontMetrics.ascent(); kpPreeditText thePreeditText = preeditText(); - if ( theTextLines.isEmpty() ) - { - if ( ! thePreeditText.isEmpty() ) - { + if (theTextLines.isEmpty()) { + if (!thePreeditText.isEmpty()) { int x = theTextAreaRect.x(); drawPreeditString(painter, x, baseLine, thePreeditText); } - } - else - { + } else { int i = 0; int row = thePreeditText.position().y(); int col = thePreeditText.position().x(); - for (const auto &str : theTextLines) - { - if (row == i && !thePreeditText.isEmpty()) - { + for (const auto &str : theTextLines) { + if (row == i && !thePreeditText.isEmpty()) { QString left = str.left(col); QString right = str.mid(col); int x = theTextAreaRect.x(); painter.drawText(x, baseLine, left); x += fontMetrics.width(left); drawPreeditString(painter, x, baseLine, thePreeditText); painter.drawText(x, baseLine, right); - } - else - { - painter.drawText(theTextAreaRect.x (), baseLine, str); + } else { + painter.drawText(theTextAreaRect.x(), baseLine, str); } baseLine += fontMetrics.lineSpacing(); i++; // if the next textline would already be below the visible text area, stop drawing - if ( (baseLine - fontMetrics.ascent()) > (theTextAreaRect.y() + theTextAreaRect.height()) ) { - break; + if ((baseLine - fontMetrics.ascent()) + > (theTextAreaRect.y() + theTextAreaRect.height())) { + break; } } } // ... convert that into "painting" transparent pixels on top of // the document. - kpPixmapFX::paintPixmapAt (destPixmap, - modifyingRect.topLeft () - docRect.topLeft (), - floatImage); + kpPixmapFX::paintPixmapAt(destPixmap, + modifyingRect.topLeft() - docRect.topLeft(), + floatImage); } //--------------------------------------------------------------------- - // public virtual [kpAbstractSelection] -void kpTextSelection::paintBorder (QImage *destPixmap, const QRect &docRect, - bool selectionFinished) const +void kpTextSelection::paintBorder(QImage *destPixmap, const QRect &docRect, + bool selectionFinished) const { - paintRectangularBorder (destPixmap, docRect, selectionFinished); + paintRectangularBorder(destPixmap, docRect, selectionFinished); } //--------------------------------------------------------------------- // public -kpImage kpTextSelection::approximateImage () const +kpImage kpTextSelection::approximateImage() const { - kpImage retImage (width (), height (), QImage::Format_ARGB32_Premultiplied); + kpImage retImage(width(), height(), QImage::Format_ARGB32_Premultiplied); retImage.fill(0); - paint (&retImage, boundingRect ()); + paint(&retImage, boundingRect()); return retImage; } diff --git a/layers/selections/text/kpTextStyle.h b/layers/selections/text/kpTextStyle.h --- a/layers/selections/text/kpTextStyle.h +++ b/layers/selections/text/kpTextStyle.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,75 +24,64 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TEXT_STYLE_H #define KP_TEXT_STYLE_H - #include #include "imagelib/kpColor.h" - class QDataStream; class QFont; class QFontMetrics; - class kpTextStyle { public: kpTextStyle (); - kpTextStyle (const QString &fontFamily, - int fontSize, - bool isBold, bool isItalic, - bool isUnderline, bool isStrikeThru, - const kpColor &fcolor, - const kpColor &bcolor, + kpTextStyle (const QString &fontFamily, int fontSize, bool isBold, bool isItalic, + bool isUnderline, bool isStrikeThru, const kpColor &fcolor, const kpColor &bcolor, bool isBackgroundOpaque); ~kpTextStyle (); + friend QDataStream &operator<<(QDataStream &stream, const kpTextStyle &textStyle); + friend QDataStream &operator>>(QDataStream &stream, kpTextStyle &textStyle); + bool operator==(const kpTextStyle &rhs) const; + bool operator!=(const kpTextStyle &rhs) const; - friend QDataStream &operator<< (QDataStream &stream, const kpTextStyle &textStyle); - friend QDataStream &operator>> (QDataStream &stream, kpTextStyle &textStyle); - bool operator== (const kpTextStyle &rhs) const; - bool operator!= (const kpTextStyle &rhs) const; + QString fontFamily() const; + void setFontFamily(const QString &f); + int fontSize() const; + void setFontSize(int s); - QString fontFamily () const; - void setFontFamily (const QString &f); + bool isBold() const; + void setBold(bool yes = true); - int fontSize () const; - void setFontSize (int s); + bool isItalic() const; + void setItalic(bool yes = true); - bool isBold () const; - void setBold (bool yes = true); + bool isUnderline() const; + void setUnderline(bool yes = true); - bool isItalic () const; - void setItalic (bool yes = true); + bool isStrikeThru() const; + void setStrikeThru(bool yes = true); - bool isUnderline () const; - void setUnderline (bool yes = true); - - bool isStrikeThru () const; - void setStrikeThru (bool yes = true); - - kpColor foregroundColor () const; - void setForegroundColor (const kpColor &fcolor); + kpColor foregroundColor() const; + void setForegroundColor(const kpColor &fcolor); // Note: This is the _input_ backgroundColor - kpColor backgroundColor () const; - void setBackgroundColor (const kpColor &bcolor); + kpColor backgroundColor() const; + void setBackgroundColor(const kpColor &bcolor); - bool isBackgroundOpaque () const; - void setBackgroundOpaque (bool yes = true); + bool isBackgroundOpaque() const; + void setBackgroundOpaque(bool yes = true); - bool isBackgroundTransparent () const; - void setBackgroundTransparent (bool yes = true); + bool isBackgroundTransparent() const; + void setBackgroundTransparent(bool yes = true); - - QFont font () const; - QFontMetrics fontMetrics () const; + QFont font() const; + QFontMetrics fontMetrics() const; private: QString m_fontFamily; @@ -103,5 +91,4 @@ bool m_isBackgroundOpaque; }; - #endif // KP_TEXT_STYLE_H diff --git a/layers/selections/text/kpTextStyle.cpp b/layers/selections/text/kpTextStyle.cpp --- a/layers/selections/text/kpTextStyle.cpp +++ b/layers/selections/text/kpTextStyle.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,58 +24,57 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "layers/selections/text/kpTextStyle.h" #include #include #include - kpTextStyle::kpTextStyle () - : m_fontSize (0), - m_isBold (false), m_isItalic (false), - m_isUnderline (false), m_isStrikeThru (false), - m_isBackgroundOpaque (true) + : m_fontSize(0) + , m_isBold(false) + , m_isItalic(false) + , m_isUnderline(false) + , m_isStrikeThru(false) + , m_isBackgroundOpaque(true) { } -kpTextStyle::kpTextStyle (const QString &fontFamily, - int fontSize, - bool isBold, bool isItalic, - bool isUnderline, bool isStrikeThru, - const kpColor &fcolor, const kpColor &bcolor, - bool isBackgroundOpaque) - : m_fontFamily (fontFamily), - m_fontSize (fontSize), - m_isBold (isBold), m_isItalic (isItalic), - m_isUnderline (isUnderline), m_isStrikeThru (isStrikeThru), - m_foregroundColor (fcolor), m_backgroundColor (bcolor), - m_isBackgroundOpaque (isBackgroundOpaque) +kpTextStyle::kpTextStyle (const QString &fontFamily, int fontSize, bool isBold, bool isItalic, + bool isUnderline, bool isStrikeThru, const kpColor &fcolor, + const kpColor &bcolor, bool isBackgroundOpaque) + : m_fontFamily(fontFamily) + , m_fontSize(fontSize) + , m_isBold(isBold) + , m_isItalic(isItalic) + , m_isUnderline(isUnderline) + , m_isStrikeThru(isStrikeThru) + , m_foregroundColor(fcolor) + , m_backgroundColor(bcolor) + , m_isBackgroundOpaque(isBackgroundOpaque) { } kpTextStyle::~kpTextStyle () = default; - // friend -QDataStream &operator<< (QDataStream &stream, const kpTextStyle &textStyle) +QDataStream &operator<<(QDataStream &stream, const kpTextStyle &textStyle) { stream << textStyle.m_fontFamily; stream << textStyle.m_fontSize; - stream << int (textStyle.m_isBold) << int (textStyle.m_isItalic) - << int (textStyle.m_isUnderline) << int (textStyle.m_isStrikeThru); + stream << int(textStyle.m_isBold) << int(textStyle.m_isItalic) + << int(textStyle.m_isUnderline) << int(textStyle.m_isStrikeThru); stream << textStyle.m_foregroundColor << textStyle.m_backgroundColor; - stream << int (textStyle.m_isBackgroundOpaque); + stream << int(textStyle.m_isBackgroundOpaque); return stream; } // friend -QDataStream &operator>> (QDataStream &stream, kpTextStyle &textStyle) +QDataStream &operator>>(QDataStream &stream, kpTextStyle &textStyle) { stream >> textStyle.m_fontFamily; stream >> textStyle.m_fontSize; @@ -98,170 +96,159 @@ } // public -bool kpTextStyle::operator== (const kpTextStyle &rhs) const +bool kpTextStyle::operator==(const kpTextStyle &rhs) const { - return (m_fontFamily == rhs.m_fontFamily && - m_fontSize == rhs.m_fontSize && - m_isBold == rhs.m_isBold && - m_isItalic == rhs.m_isItalic && - m_isUnderline == rhs.m_isUnderline && - m_isStrikeThru == rhs.m_isStrikeThru && - m_foregroundColor == rhs.m_foregroundColor && - m_backgroundColor == rhs.m_backgroundColor && - m_isBackgroundOpaque == rhs.m_isBackgroundOpaque); + return m_fontFamily == rhs.m_fontFamily + && m_fontSize == rhs.m_fontSize + && m_isBold == rhs.m_isBold + && m_isItalic == rhs.m_isItalic + && m_isUnderline == rhs.m_isUnderline + && m_isStrikeThru == rhs.m_isStrikeThru + && m_foregroundColor == rhs.m_foregroundColor + && m_backgroundColor == rhs.m_backgroundColor + && m_isBackgroundOpaque == rhs.m_isBackgroundOpaque; } // public -bool kpTextStyle::operator!= (const kpTextStyle &rhs) const +bool kpTextStyle::operator!=(const kpTextStyle &rhs) const { return !(*this == rhs); } - // public -QString kpTextStyle::fontFamily () const +QString kpTextStyle::fontFamily() const { return m_fontFamily; } // public -void kpTextStyle::setFontFamily (const QString &f) +void kpTextStyle::setFontFamily(const QString &f) { m_fontFamily = f; } - // public -int kpTextStyle::fontSize () const +int kpTextStyle::fontSize() const { return m_fontSize; } // public -void kpTextStyle::setFontSize (int s) +void kpTextStyle::setFontSize(int s) { m_fontSize = s; } - // public -bool kpTextStyle::isBold () const +bool kpTextStyle::isBold() const { return m_isBold; } // public -void kpTextStyle::setBold (bool yes) +void kpTextStyle::setBold(bool yes) { m_isBold = yes; } - // public -bool kpTextStyle::isItalic () const +bool kpTextStyle::isItalic() const { return m_isItalic; } // public -void kpTextStyle::setItalic (bool yes) +void kpTextStyle::setItalic(bool yes) { m_isItalic = yes; } - // public -bool kpTextStyle::isUnderline () const +bool kpTextStyle::isUnderline() const { return m_isUnderline; } // public -void kpTextStyle::setUnderline (bool yes) +void kpTextStyle::setUnderline(bool yes) { m_isUnderline = yes; } - // public -bool kpTextStyle::isStrikeThru () const +bool kpTextStyle::isStrikeThru() const { return m_isStrikeThru; } // public -void kpTextStyle::setStrikeThru (bool yes) +void kpTextStyle::setStrikeThru(bool yes) { m_isStrikeThru = yes; } - // public -kpColor kpTextStyle::foregroundColor () const +kpColor kpTextStyle::foregroundColor() const { return m_foregroundColor; } // public -void kpTextStyle::setForegroundColor (const kpColor &fcolor) +void kpTextStyle::setForegroundColor(const kpColor &fcolor) { m_foregroundColor = fcolor; } - // public -kpColor kpTextStyle::backgroundColor () const +kpColor kpTextStyle::backgroundColor() const { return m_backgroundColor; } // public -void kpTextStyle::setBackgroundColor (const kpColor &bcolor) +void kpTextStyle::setBackgroundColor(const kpColor &bcolor) { m_backgroundColor = bcolor; } - // public -bool kpTextStyle::isBackgroundOpaque () const +bool kpTextStyle::isBackgroundOpaque() const { return m_isBackgroundOpaque; } // public -void kpTextStyle::setBackgroundOpaque (bool yes) +void kpTextStyle::setBackgroundOpaque(bool yes) { m_isBackgroundOpaque = yes; } - // public -bool kpTextStyle::isBackgroundTransparent () const +bool kpTextStyle::isBackgroundTransparent() const { return !m_isBackgroundOpaque; } // public -void kpTextStyle::setBackgroundTransparent (bool yes) +void kpTextStyle::setBackgroundTransparent(bool yes) { m_isBackgroundOpaque = !yes; } - // public -QFont kpTextStyle::font () const +QFont kpTextStyle::font() const { - QFont fnt (m_fontFamily, m_fontSize); - fnt.setBold (m_isBold); - fnt.setItalic (m_isItalic); - fnt.setUnderline (m_isUnderline); - fnt.setStrikeOut (m_isStrikeThru); + QFont fnt(m_fontFamily, m_fontSize); + fnt.setBold(m_isBold); + fnt.setItalic(m_isItalic); + fnt.setUnderline(m_isUnderline); + fnt.setStrikeOut(m_isStrikeThru); return fnt; } // public -QFontMetrics kpTextStyle::fontMetrics () const +QFontMetrics kpTextStyle::fontMetrics() const { - return QFontMetrics (font ()); + return QFontMetrics(font()); } diff --git a/layers/tempImage/kpTempImage.h b/layers/tempImage/kpTempImage.h --- a/layers/tempImage/kpTempImage.h +++ b/layers/tempImage/kpTempImage.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,19 +26,15 @@ // REFACTOR: maybe make us and kpAbstractSelection share a new kpLayer base? - #ifndef kpTempImage_H #define kpTempImage_H - #include #include "imagelib/kpImage.h" - class kpViewManager; - class kpTempImage { public: @@ -52,9 +47,8 @@ }; // REFACTOR: Function pointers imply a need for a proper class hierarchy. - typedef void (*UserFunctionType) (kpImage * /*destImage*/, - const QPoint & /*topLeft*/, - void * /*userData*/); + typedef void (*UserFunctionType)(kpImage * /*destImage*/, const QPoint & /*topLeft*/, + void * /*userData*/); /* * Specifies that its visibility is dependent on whether or @@ -66,34 +60,32 @@ * the claimed rectangle. */ kpTempImage (bool isBrush, RenderMode renderMode, const QPoint &topLeft, const kpImage &image); - kpTempImage (bool isBrush, const QPoint &topLeft, - UserFunctionType userFunction, void *userData, - int width, int height); + kpTempImage (bool isBrush, const QPoint &topLeft, UserFunctionType userFunction, void *userData, + int width, int height); kpTempImage (const kpTempImage &rhs); - kpTempImage &operator= (const kpTempImage &rhs); - - bool isBrush () const; - RenderMode renderMode () const; - QPoint topLeft () const; - kpImage image () const; - UserFunctionType userFunction () const; - void *userData () const; + kpTempImage &operator=(const kpTempImage &rhs); - bool isVisible (const kpViewManager *vm) const; - QRect rect () const; - int width () const; - int height () const; + bool isBrush() const; + RenderMode renderMode() const; + QPoint topLeft() const; + kpImage image() const; + UserFunctionType userFunction() const; + void *userData() const; + bool isVisible(const kpViewManager *vm) const; + QRect rect() const; + int width() const; + int height() const; // Returns whether a call to paint() may add a mask to <*destImage>. - bool paintMayAddMask () const; + bool paintMayAddMask() const; /* * Draws itself onto <*destImage>, given that <*destImage> represents * the unzoomed of the kpDocument. You should check for * visibility before calling this function. */ - void paint (kpImage *destImage, const QRect &docRect) const; + void paint(kpImage *destImage, const QRect &docRect) const; private: bool m_isBrush; @@ -106,5 +98,4 @@ void *m_userData; }; - #endif // kpTempImage_H diff --git a/layers/tempImage/kpTempImage.cpp b/layers/tempImage/kpTempImage.cpp --- a/layers/tempImage/kpTempImage.cpp +++ b/layers/tempImage/kpTempImage.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "layers/tempImage/kpTempImage.h" #include "pixmapfx/kpPixmapFX.h" @@ -35,51 +33,53 @@ //--------------------------------------------------------------------- -kpTempImage::kpTempImage (bool isBrush, RenderMode renderMode, - const QPoint &topLeft, const kpImage &image) - : m_isBrush (isBrush), - m_renderMode (renderMode), - m_topLeft (topLeft), - m_image (image), - m_width (image.width ()), m_height (image.height ()), - m_userFunction (nullptr), - m_userData (nullptr) +kpTempImage::kpTempImage (bool isBrush, RenderMode renderMode, const QPoint &topLeft, + const kpImage &image) + : m_isBrush(isBrush) + , m_renderMode(renderMode) + , m_topLeft(topLeft) + , m_image(image) + , m_width(image.width()) + , m_height(image.height()) + , m_userFunction(nullptr) + , m_userData(nullptr) { // Use below constructor for that. - Q_ASSERT (renderMode != UserFunction); + Q_ASSERT(renderMode != UserFunction); } //--------------------------------------------------------------------- -kpTempImage::kpTempImage (bool isBrush, const QPoint &topLeft, - UserFunctionType userFunction, void *userData, - int width, int height) - : m_isBrush (isBrush), - m_renderMode (UserFunction), - m_topLeft (topLeft), - m_width (width), m_height (height), - m_userFunction (userFunction), - m_userData (userData) +kpTempImage::kpTempImage (bool isBrush, const QPoint &topLeft, UserFunctionType userFunction, + void *userData, int width, int height) + : m_isBrush(isBrush) + , m_renderMode(UserFunction) + , m_topLeft(topLeft) + , m_width(width) + , m_height(height) + , m_userFunction(userFunction) + , m_userData(userData) { - Q_ASSERT (m_userFunction); + Q_ASSERT(m_userFunction); } //--------------------------------------------------------------------- kpTempImage::kpTempImage (const kpTempImage &rhs) - : m_isBrush (rhs.m_isBrush), - m_renderMode (rhs.m_renderMode), - m_topLeft (rhs.m_topLeft), - m_image (rhs.m_image), - m_width (rhs.m_width), m_height (rhs.m_height), - m_userFunction (rhs.m_userFunction), - m_userData (rhs.m_userData) + : m_isBrush(rhs.m_isBrush) + , m_renderMode(rhs.m_renderMode) + , m_topLeft(rhs.m_topLeft) + , m_image(rhs.m_image) + , m_width(rhs.m_width) + , m_height(rhs.m_height) + , m_userFunction(rhs.m_userFunction) + , m_userData(rhs.m_userData) { } //--------------------------------------------------------------------- -kpTempImage &kpTempImage::operator= (const kpTempImage &rhs) +kpTempImage &kpTempImage::operator=(const kpTempImage &rhs) { if (this == &rhs) { return *this; @@ -100,118 +100,113 @@ //--------------------------------------------------------------------- // public -bool kpTempImage::isBrush () const +bool kpTempImage::isBrush() const { return m_isBrush; } //--------------------------------------------------------------------- // public -kpTempImage::RenderMode kpTempImage::renderMode () const +kpTempImage::RenderMode kpTempImage::renderMode() const { return m_renderMode; } //--------------------------------------------------------------------- // public -QPoint kpTempImage::topLeft () const +QPoint kpTempImage::topLeft() const { return m_topLeft; } //--------------------------------------------------------------------- // public -kpImage kpTempImage::image () const +kpImage kpTempImage::image() const { return m_image; } //--------------------------------------------------------------------- // public -kpTempImage::UserFunctionType kpTempImage::userFunction () const +kpTempImage::UserFunctionType kpTempImage::userFunction() const { return m_userFunction; } //--------------------------------------------------------------------- // public -void *kpTempImage::userData () const +void *kpTempImage::userData() const { return m_userData; } //--------------------------------------------------------------------- // public -bool kpTempImage::isVisible (const kpViewManager *vm) const +bool kpTempImage::isVisible(const kpViewManager *vm) const { - return m_isBrush ? static_cast (vm->viewUnderCursor ()) : true; + return m_isBrush ? static_cast(vm->viewUnderCursor()) : true; } //--------------------------------------------------------------------- // public -QRect kpTempImage::rect () const +QRect kpTempImage::rect() const { - return {m_topLeft.x (), m_topLeft.y (), m_width, m_height}; + return { + m_topLeft.x(), m_topLeft.y(), m_width, m_height + }; } //--------------------------------------------------------------------- // public -int kpTempImage::width () const +int kpTempImage::width() const { return m_width; } //--------------------------------------------------------------------- // public -int kpTempImage::height () const +int kpTempImage::height() const { return m_height; } //--------------------------------------------------------------------- // public -bool kpTempImage::paintMayAddMask () const +bool kpTempImage::paintMayAddMask() const { - return (m_renderMode == SetImage || - m_renderMode == UserFunction); + return m_renderMode == SetImage + || m_renderMode == UserFunction; } //--------------------------------------------------------------------- // public -void kpTempImage::paint (kpImage *destImage, const QRect &docRect) const +void kpTempImage::paint(kpImage *destImage, const QRect &docRect) const { - const QPoint REL_TOP_LEFT = m_topLeft - docRect.topLeft (); + const QPoint REL_TOP_LEFT = m_topLeft - docRect.topLeft(); - switch (m_renderMode) - { - case SetImage: - { + switch (m_renderMode) { + case SetImage: kpPixmapFX::setPixmapAt(destImage, REL_TOP_LEFT, m_image); break; - } - case PaintImage: - { + case PaintImage: kpPixmapFX::paintPixmapAt(destImage, REL_TOP_LEFT, m_image); break; - } - case UserFunction: - { + case UserFunction: m_userFunction(destImage, REL_TOP_LEFT, m_userData); break; - } } } diff --git a/lgpl/generic/kpColorCollection.h b/lgpl/generic/kpColorCollection.h --- a/lgpl/generic/kpColorCollection.h +++ b/lgpl/generic/kpColorCollection.h @@ -1,4 +1,3 @@ - // SYNC: Periodically merge in changes from: // // trunk/KDE/kdelibs/kdeui/colors/kcolorcollection.{h,cpp} @@ -58,207 +57,202 @@ class KOLOURPAINT_LGPL_EXPORT kpColorCollection { public: - /** - * Query which KDE color collections are installed. - * - * @return A list with installed color collection names. - */ - static QStringList installedCollections(); - - /** - * kpColorCollection constructor - * - * argument removed for KolourPaint. - * Use openKDE() instead, which also has error handling. - **/ - explicit kpColorCollection(); - - /** - * kpColorCollection copy constructor. - **/ - kpColorCollection(const kpColorCollection &); - - /** - * kpColorCollection destructor. - **/ - ~kpColorCollection(); - - /** - * kpColorCollection assignment operator - **/ - kpColorCollection& operator=( const kpColorCollection &); - - // On failure, this prints an error dialog and returns false. - // On success, it sets the name() to an empty string and returns true. - // - // Added for KolourPaint. - bool open(const QUrl &url, QWidget *parent); - - // Same as open() but is given the name of a KDE palette, not a filename. - // - // @param name The name of collection as returned by installedCollections(). - // name() is set to this. - // - // Added for KolourPaint. - bool openKDE(const QString &name, QWidget *parent); - - // On failure, this prints an error dialog and returns false. - // If the user cancels any presented overwrite dialog, it also returns false. - // On success, it returns true. - // - // The file can be overwritten without displaying any warning dialog, if - // is set to false. - // - // name() is set to an empty string. - // - // Added for KolourPaint. - bool saveAs(const QUrl &url, bool showOverwritePrompt, QWidget *parent) const; - - /** - * Save the collection to the KDE-local store - * (usually $HOME/.kde/share/config/colors) using name(). - * - * @return 'true' if successful - * - * Renamed from save() for KolourPaint. - **/ - bool saveKDE(QWidget *parent) const; - - /** - * Get the description of the collection. - * @return the description of the collection. - **/ - QString description() const; - - /** - * Set the description of the collection. - * @param desc the new description - **/ - void setDescription(const QString &desc); - - /** - * Get the name of the collection. - * @return the name of the collection - **/ - QString name() const; - - /** - * Set the name of the collection. - * @param name the name of the collection - **/ - void setName(const QString &name); - - /** - * Used to specify whether a collection may be edited. - * @see editable() - * @see setEditable() - */ - enum Editable { Yes, ///< Collection may be edited - No, ///< Collection may not be edited - Ask ///< Ask user before editing - }; - - /** - * Returns whether the collection may be edited. - * @return the state of the collection - **/ - Editable editable() const; - - /** - * Change whether the collection may be edited. - * @param editable the state of the collection - **/ - void setEditable(Editable editable); - - /** - * Return the number of colors in the collection. - * @return the number of colors - **/ - int count() const; - - /** - * Adds invalid colors or removes colors so that there will be @p newCount - * colors in the color collection. - * - * @param target number of colors - * - * Added for KolourPaint. - */ - void resize(int newCount); - - /** - * Find color by index. - * @param index the index of the desired color - * @return The @p index -th color of the collection, null if not found. - **/ - QColor color(int index) const; - - /** - * Find index by @p color. - * @param color the color to find - * @return The index of the color in the collection or -1 if the - * color is not found. - **/ - int findColor(const QColor &color) const; - - /** - * Find color name by @p index. - * @param index the index of the color - * @return The name of the @p index -th color. - * Note that not all collections have named the colors. Null is - * returned if the color does not exist or has no name. - **/ - QString name(int index) const; - - /** - * Find color name by @p color. - * @return The name of color according to this collection. - * Note that not all collections have named the colors. - * Note also that each collection can give the same color - * a different name. - **/ - QString name(const QColor &color) const; - - /** - * Add a color. - * @param newColor The color to add. - * @param newColorName The name of the color, null to remove - * the name. - * @return The index of the added color. - **/ - int addColor(const QColor &newColor, - const QString &newColorName = QString()); - - /** - * Change a color. - * @param index Index of the color to change - * @param newColor The new color. - * @param newColorName The new color name, null to remove - * the name. - * @return The index of the new color or -1 if the color couldn't - * be changed. - **/ - int changeColor(int index, - const QColor &newColor, - const QString &newColorName = QString()); - - /** - * Change a color. - * @param oldColor The original color - * @param newColor The new color. - * @param newColorName The new color name, null to remove - * the name. - * @return The index of the new color or -1 if the color couldn't - * be changed. - **/ - int changeColor(const QColor &oldColor, - const QColor &newColor, - const QString &newColorName = QString()); + /** + * Query which KDE color collections are installed. + * + * @return A list with installed color collection names. + */ + static QStringList installedCollections(); + + /** + * kpColorCollection constructor + * + * argument removed for KolourPaint. + * Use openKDE() instead, which also has error handling. + **/ + explicit kpColorCollection(); + + /** + * kpColorCollection copy constructor. + **/ + kpColorCollection(const kpColorCollection &); + + /** + * kpColorCollection destructor. + **/ + ~kpColorCollection(); + + /** + * kpColorCollection assignment operator + **/ + kpColorCollection &operator=(const kpColorCollection &); + + // On failure, this prints an error dialog and returns false. + // On success, it sets the name() to an empty string and returns true. + // + // Added for KolourPaint. + bool open(const QUrl &url, QWidget *parent); + + // Same as open() but is given the name of a KDE palette, not a filename. + // + // @param name The name of collection as returned by installedCollections(). + // name() is set to this. + // + // Added for KolourPaint. + bool openKDE(const QString &name, QWidget *parent); + + // On failure, this prints an error dialog and returns false. + // If the user cancels any presented overwrite dialog, it also returns false. + // On success, it returns true. + // + // The file can be overwritten without displaying any warning dialog, if + // is set to false. + // + // name() is set to an empty string. + // + // Added for KolourPaint. + bool saveAs(const QUrl &url, bool showOverwritePrompt, QWidget *parent) const; + + /** + * Save the collection to the KDE-local store + * (usually $HOME/.kde/share/config/colors) using name(). + * + * @return 'true' if successful + * + * Renamed from save() for KolourPaint. + **/ + bool saveKDE(QWidget *parent) const; + + /** + * Get the description of the collection. + * @return the description of the collection. + **/ + QString description() const; + + /** + * Set the description of the collection. + * @param desc the new description + **/ + void setDescription(const QString &desc); + + /** + * Get the name of the collection. + * @return the name of the collection + **/ + QString name() const; + + /** + * Set the name of the collection. + * @param name the name of the collection + **/ + void setName(const QString &name); + + /** + * Used to specify whether a collection may be edited. + * @see editable() + * @see setEditable() + */ + enum Editable { + Yes, ///< Collection may be edited + No, ///< Collection may not be edited + Ask ///< Ask user before editing + }; + + /** + * Returns whether the collection may be edited. + * @return the state of the collection + **/ + Editable editable() const; + + /** + * Change whether the collection may be edited. + * @param editable the state of the collection + **/ + void setEditable(Editable editable); + + /** + * Return the number of colors in the collection. + * @return the number of colors + **/ + int count() const; + + /** + * Adds invalid colors or removes colors so that there will be @p newCount + * colors in the color collection. + * + * @param target number of colors + * + * Added for KolourPaint. + */ + void resize(int newCount); + + /** + * Find color by index. + * @param index the index of the desired color + * @return The @p index -th color of the collection, null if not found. + **/ + QColor color(int index) const; + + /** + * Find index by @p color. + * @param color the color to find + * @return The index of the color in the collection or -1 if the + * color is not found. + **/ + int findColor(const QColor &color) const; + + /** + * Find color name by @p index. + * @param index the index of the color + * @return The name of the @p index -th color. + * Note that not all collections have named the colors. Null is + * returned if the color does not exist or has no name. + **/ + QString name(int index) const; + + /** + * Find color name by @p color. + * @return The name of color according to this collection. + * Note that not all collections have named the colors. + * Note also that each collection can give the same color + * a different name. + **/ + QString name(const QColor &color) const; + + /** + * Add a color. + * @param newColor The color to add. + * @param newColorName The name of the color, null to remove + * the name. + * @return The index of the added color. + **/ + int addColor(const QColor &newColor, const QString &newColorName = QString()); + + /** + * Change a color. + * @param index Index of the color to change + * @param newColor The new color. + * @param newColorName The new color name, null to remove + * the name. + * @return The index of the new color or -1 if the color couldn't + * be changed. + **/ + int changeColor(int index, const QColor &newColor, const QString &newColorName = QString()); + + /** + * Change a color. + * @param oldColor The original color + * @param newColor The new color. + * @param newColorName The new color name, null to remove + * the name. + * @return The index of the new color or -1 if the color couldn't + * be changed. + **/ + int changeColor(const QColor &oldColor, const QColor &newColor, + const QString &newColorName = QString()); private: - class kpColorCollectionPrivate *d; + class kpColorCollectionPrivate *d; }; - #endif // kpColorCollection_H - diff --git a/lgpl/generic/kpColorCollection.cpp b/lgpl/generic/kpColorCollection.cpp --- a/lgpl/generic/kpColorCollection.cpp +++ b/lgpl/generic/kpColorCollection.cpp @@ -1,4 +1,3 @@ - // REFACT0R: Remote open/save file logic is duplicated in kpDocument. // HITODO: Test when remote file support in KDE 4 stabilizes @@ -47,7 +46,10 @@ struct ColorNode { ColorNode(const QColor &c, const QString &n) - : color(c), name(n) {} + : color(c) + , name(n) + { + } QColor color; QString name; @@ -60,44 +62,49 @@ { public: kpColorCollectionPrivate(); - kpColorCollectionPrivate(const kpColorCollectionPrivate&); + kpColorCollectionPrivate(const kpColorCollectionPrivate &); QList colorList; QString name; QString desc; kpColorCollection::Editable editable; }; kpColorCollectionPrivate::kpColorCollectionPrivate() - : editable(kpColorCollection::Yes) + : editable(kpColorCollection::Yes) { } -kpColorCollectionPrivate::kpColorCollectionPrivate(const kpColorCollectionPrivate& p) - : colorList(p.colorList), name(p.name), desc(p.desc), editable(p.editable) +kpColorCollectionPrivate::kpColorCollectionPrivate(const kpColorCollectionPrivate &p) + : colorList(p.colorList) + , name(p.name) + , desc(p.desc) + , editable(p.editable) { } + //END kpColorCollectionPrivate //--------------------------------------------------------------------- QStringList kpColorCollection::installedCollections() { - QStringList paletteList; + QStringList paletteList; - QStringList paths = QStandardPaths::locateAll(QStandardPaths::GenericConfigLocation, QStringLiteral("colors"), - QStandardPaths::LocateDirectory); - for (const auto &path : paths) { - paletteList.append(QDir(path).entryList(QStringList(), QDir::Files)); - } + QStringList paths = QStandardPaths::locateAll(QStandardPaths::GenericConfigLocation, QStringLiteral( + "colors"), + QStandardPaths::LocateDirectory); + for (const auto &path : paths) { + paletteList.append(QDir(path).entryList(QStringList(), QDir::Files)); + } - return paletteList; + return paletteList; } kpColorCollection::kpColorCollection() { - d = new kpColorCollectionPrivate(); + d = new kpColorCollectionPrivate(); } kpColorCollection::kpColorCollection(const kpColorCollection &p) @@ -107,303 +114,287 @@ kpColorCollection::~kpColorCollection() { - // Need auto-save? + // Need auto-save? delete d; } -static void CouldNotOpenDialog (const QUrl &url, QWidget *parent) +static void CouldNotOpenDialog(const QUrl &url, QWidget *parent) { - KMessageBox::sorry (parent, - i18n ("Could not open color palette \"%1\".", - kpUrlFormatter::PrettyFilename (url))); + KMessageBox::sorry(parent, + i18n("Could not open color palette \"%1\".", + kpUrlFormatter::PrettyFilename(url))); } // TODO: Set d->editable? bool kpColorCollection::open(const QUrl &url, QWidget *parent) { - QString tempPaletteFilePath; - if (url.isEmpty () || !KIO::NetAccess::download (url, tempPaletteFilePath, parent)) - { + QString tempPaletteFilePath; + if (url.isEmpty() || !KIO::NetAccess::download(url, tempPaletteFilePath, parent)) { #if DEBUG_KP_COLOR_COLLECTION - qCDebug(kpLogMisc) << "\tcould not download"; + qCDebug(kpLogMisc) << "\tcould not download"; #endif - ::CouldNotOpenDialog (url, parent); - return false; - } + ::CouldNotOpenDialog(url, parent); + return false; + } - // sync: remember to "KIO::NetAccess::removeTempFile (tempPaletteFilePath)" in all exit paths + // sync: remember to "KIO::NetAccess::removeTempFile (tempPaletteFilePath)" in all exit paths - QFile paletteFile(tempPaletteFilePath); - if (!paletteFile.exists() || - !paletteFile.open(QIODevice::ReadOnly)) - { + QFile paletteFile(tempPaletteFilePath); + if (!paletteFile.exists() + || !paletteFile.open(QIODevice::ReadOnly)) { #if DEBUG_KP_COLOR_COLLECTION - qCDebug(kpLogMisc) << "\tcould not open qfile"; + qCDebug(kpLogMisc) << "\tcould not open qfile"; #endif - KIO::NetAccess::removeTempFile (tempPaletteFilePath); - ::CouldNotOpenDialog (url, parent); - return false; - } - - // Read first line - // Expected "GIMP Palette" - QString line = QString::fromLocal8Bit(paletteFile.readLine()); - if (line.indexOf(QLatin1String(" Palette")) == -1) - { - KIO::NetAccess::removeTempFile (tempPaletteFilePath); - KMessageBox::sorry (parent, - i18n ("Could not open color palette \"%1\" - unsupported format.\n" - "The file may be corrupt.", - kpUrlFormatter::PrettyFilename (url))); - return false; - } - - QList newColorList; - QString newDesc; - - while( !paletteFile.atEnd() ) - { - line = QString::fromLocal8Bit(paletteFile.readLine()); - if (line[0] == '#') - { - // This is a comment line - line = line.mid(1); // Strip '#' - line = line.trimmed(); // Strip remaining white space.. - if (!line.isEmpty()) - { - newDesc += line+'\n'; // Add comment to description - } - } - else - { - // This is a color line, hopefully - line = line.trimmed(); - if (line.isEmpty()) continue; - int r, g, b; - int pos = 0; - if (sscanf(line.toLatin1(), "%d %d %d%n", &r, &g, &b, &pos) >= 3) - { - r = qBound(0, r, 255); - g = qBound(0, g, 255); - b = qBound(0, b, 255); - QString name = line.mid(pos).trimmed(); - newColorList.append(ColorNode(QColor(r, g, b), name)); + KIO::NetAccess::removeTempFile(tempPaletteFilePath); + ::CouldNotOpenDialog(url, parent); + return false; + } + + // Read first line + // Expected "GIMP Palette" + QString line = QString::fromLocal8Bit(paletteFile.readLine()); + if (line.indexOf(QLatin1String(" Palette")) == -1) { + KIO::NetAccess::removeTempFile(tempPaletteFilePath); + KMessageBox::sorry(parent, + i18n("Could not open color palette \"%1\" - unsupported format.\n" + "The file may be corrupt.", + kpUrlFormatter::PrettyFilename(url))); + return false; + } + + QList newColorList; + QString newDesc; + + while (!paletteFile.atEnd()) + { + line = QString::fromLocal8Bit(paletteFile.readLine()); + if (line[0] == '#') { + // This is a comment line + line = line.mid(1); // Strip '#' + line = line.trimmed(); // Strip remaining white space.. + if (!line.isEmpty()) { + newDesc += line+'\n'; // Add comment to description + } + } else { + // This is a color line, hopefully + line = line.trimmed(); + if (line.isEmpty()) { + continue; + } + int r, g, b; + int pos = 0; + if (sscanf(line.toLatin1(), "%d %d %d%n", &r, &g, &b, &pos) >= 3) { + r = qBound(0, r, 255); + g = qBound(0, g, 255); + b = qBound(0, b, 255); + QString name = line.mid(pos).trimmed(); + newColorList.append(ColorNode(QColor(r, g, b), name)); + } } - } - } + } - d->colorList = newColorList; - d->name.clear (); - d->desc = newDesc; + d->colorList = newColorList; + d->name.clear(); + d->desc = newDesc; - KIO::NetAccess::removeTempFile (tempPaletteFilePath); - return true; + KIO::NetAccess::removeTempFile(tempPaletteFilePath); + return true; } -static void CouldNotOpenKDEDialog (const QString &name, QWidget *parent) +static void CouldNotOpenKDEDialog(const QString &name, QWidget *parent) { - KMessageBox::sorry (parent, - i18n ("Could not open KDE color palette \"%1\".", name)); + KMessageBox::sorry(parent, + i18n("Could not open KDE color palette \"%1\".", name)); } bool kpColorCollection::openKDE(const QString &name, QWidget *parent) { #if DEBUG_KP_COLOR_COLLECTION - qCDebug(kpLogMisc) << "name=" << name; + qCDebug(kpLogMisc) << "name=" << name; #endif - if (name.isEmpty()) - { + if (name.isEmpty()) { #if DEBUG_KP_COLOR_COLLECTION - qCDebug(kpLogMisc) << "name.isEmpty"; + qCDebug(kpLogMisc) << "name.isEmpty"; #endif - ::CouldNotOpenKDEDialog (name, parent); - return false; - } - - QString filename = QStandardPaths::locate(QStandardPaths::GenericConfigLocation, - "colors/" + name); - if (filename.isEmpty()) - { + ::CouldNotOpenKDEDialog(name, parent); + return false; + } + + QString filename = QStandardPaths::locate(QStandardPaths::GenericConfigLocation, + "colors/" + name); + if (filename.isEmpty()) { #if DEBUG_KP_COLOR_COLLECTION - qCDebug(kpLogMisc) << "could not find file"; + qCDebug(kpLogMisc) << "could not find file"; #endif - ::CouldNotOpenKDEDialog (name, parent); - return false; - } + ::CouldNotOpenKDEDialog(name, parent); + return false; + } - // (this will pop up an error dialog on failure) - if (!open (QUrl::fromLocalFile (filename), parent)) - { + // (this will pop up an error dialog on failure) + if (!open(QUrl::fromLocalFile(filename), parent)) { #if DEBUG_KP_COLOR_COLLECTION - qCDebug(kpLogMisc) << "could not open"; + qCDebug(kpLogMisc) << "could not open"; #endif - return false; - } + return false; + } - d->name = name; + d->name = name; #if DEBUG_KP_COLOR_COLLECTION - qCDebug(kpLogMisc) << "opened"; + qCDebug(kpLogMisc) << "opened"; #endif - return true; + return true; } -static void CouldNotSaveDialog (const QUrl &url, QWidget *parent) +static void CouldNotSaveDialog(const QUrl &url, QWidget *parent) { // TODO: use file.errorString() - KMessageBox::error (parent, - i18n ("Could not save color palette as \"%1\".", - kpUrlFormatter::PrettyFilename (url))); + KMessageBox::error(parent, + i18n("Could not save color palette as \"%1\".", + kpUrlFormatter::PrettyFilename(url))); } -static void SaveToFile (kpColorCollectionPrivate *d, QIODevice *device) +static void SaveToFile(kpColorCollectionPrivate *d, QIODevice *device) { - // HITODO: QTextStream can fail but does not report errors. - // Bug in KColorCollection too. - QTextStream str (device); + // HITODO: QTextStream can fail but does not report errors. + // Bug in KColorCollection too. + QTextStream str(device); - QString description = d->desc.trimmed(); - description = '#'+description.split( '\n', QString::KeepEmptyParts).join(QLatin1String("\n#")); + QString description = d->desc.trimmed(); + description = '#'+description.split('\n', QString::KeepEmptyParts).join(QLatin1String("\n#")); - str << "KDE RGB Palette\n"; - str << description << "\n"; - for (const auto &node : d->colorList) - { - // Added for KolourPaint. - if(!node.color.isValid ()) - continue; + str << "KDE RGB Palette\n"; + str << description << "\n"; + for (const auto &node : d->colorList) { + // Added for KolourPaint. + if (!node.color.isValid()) { + continue; + } - int r,g,b; - node.color.getRgb(&r, &g, &b); - str << r << " " << g << " " << b << " " << node.name << "\n"; - } + int r, g, b; + node.color.getRgb(&r, &g, &b); + str << r << " " << g << " " << b << " " << node.name << "\n"; + } - str.flush(); + str.flush(); } bool -kpColorCollection::saveAs(const QUrl &url, bool showOverwritePrompt, - QWidget *parent) const -{ - if (showOverwritePrompt && - KIO::NetAccess::exists (url, KIO::NetAccess::DestinationSide/*write*/, parent)) - { - int result = KMessageBox::warningContinueCancel (parent, - i18n ("A color palette called \"%1\" already exists.\n" - "Do you want to overwrite it?", - kpUrlFormatter::PrettyFilename (url)), - QString (), - KStandardGuiItem::overwrite ()); - if (result != KMessageBox::Continue) - return false; - } - - if (url.isLocalFile ()) - { - const QString filename = url.toLocalFile (); +kpColorCollection::saveAs(const QUrl &url, bool showOverwritePrompt, QWidget *parent) const +{ + if (showOverwritePrompt + && KIO::NetAccess::exists(url, KIO::NetAccess::DestinationSide /*write*/, parent)) { + int result = KMessageBox::warningContinueCancel(parent, + i18n( + "A color palette called \"%1\" already exists.\n" + "Do you want to overwrite it?", + kpUrlFormatter::PrettyFilename(url)), + QString(), + KStandardGuiItem::overwrite()); + if (result != KMessageBox::Continue) { + return false; + } + } + + if (url.isLocalFile()) { + const QString filename = url.toLocalFile(); // sync: All failure exit paths _must_ call QSaveFile::cancelWriting() or // else, the QSaveFile destructor will overwrite the file, // , despite the failure. - QSaveFile atomicFileWriter (filename); + QSaveFile atomicFileWriter(filename); { - if (!atomicFileWriter.open (QIODevice::WriteOnly)) - { + if (!atomicFileWriter.open(QIODevice::WriteOnly)) { // We probably don't need this as has not been // opened. - atomicFileWriter.cancelWriting (); + atomicFileWriter.cancelWriting(); #if DEBUG_KP_COLOR_COLLECTION qCDebug(kpLogMisc) << "\treturning false because could not open QSaveFile" - << " error=" << atomicFileWriter.error (); + << " error=" << atomicFileWriter.error(); #endif - ::CouldNotSaveDialog (url, parent); + ::CouldNotSaveDialog(url, parent); return false; } // Write to local temporary file. - ::SaveToFile (d, &atomicFileWriter); + ::SaveToFile(d, &atomicFileWriter); // Atomically overwrite local file with the temporary file // we saved to. - if (!atomicFileWriter.commit ()) - { - atomicFileWriter.cancelWriting (); + if (!atomicFileWriter.commit()) { + atomicFileWriter.cancelWriting(); #if DEBUG_KP_COLOR_COLLECTION qCDebug(kpLogMisc) << "\tcould not close QSaveFile"; #endif - ::CouldNotSaveDialog (url, parent); + ::CouldNotSaveDialog(url, parent); return false; } } // sync QSaveFile.cancelWriting() } // Remote file? - else - { + else { // Create temporary file that is deleted when the variable goes // out of scope. QTemporaryFile tempFile; - if (!tempFile.open ()) - { + if (!tempFile.open()) { #if DEBUG_KP_COLOR_COLLECTION qCDebug(kpLogMisc) << "\treturning false because could not open tempFile"; #endif - ::CouldNotSaveDialog (url, parent); + ::CouldNotSaveDialog(url, parent); return false; } // Write to local temporary file. - ::SaveToFile (d, &tempFile); + ::SaveToFile(d, &tempFile); // Collect name of temporary file now, as QTemporaryFile::fileName() // stops working after close() is called. - const QString tempFileName = tempFile.fileName (); + const QString tempFileName = tempFile.fileName(); #if DEBUG_KP_COLOR_COLLECTION - qCDebug(kpLogMisc) << "\ttempFileName='" << tempFileName << "'"; + qCDebug(kpLogMisc) << "\ttempFileName='" << tempFileName << "'"; #endif - Q_ASSERT (!tempFileName.isEmpty ()); + Q_ASSERT(!tempFileName.isEmpty()); - tempFile.close (); - if (tempFile.error () != QFile::NoError) - { + tempFile.close(); + if (tempFile.error() != QFile::NoError) { #if DEBUG_KP_COLOR_COLLECTION qCDebug(kpLogMisc) << "\treturning false because could not close"; #endif - ::CouldNotSaveDialog (url, parent); + ::CouldNotSaveDialog(url, parent); return false; } // Copy local temporary file to overwrite remote. // TODO: No one seems to know how to do this atomically // [http://lists.kde.org/?l=kde-core-devel&m=117845162728484&w=2]. // At least, fish:// (ssh) is definitely not atomic. - if (!KIO::NetAccess::upload (tempFileName, url, parent)) - { + if (!KIO::NetAccess::upload(tempFileName, url, parent)) { #if DEBUG_KP_COLOR_COLLECTION qCDebug(kpLogMisc) << "\treturning false because could not upload"; #endif - ::CouldNotSaveDialog (url, parent); + ::CouldNotSaveDialog(url, parent); return false; } } - d->name.clear (); - return true; + d->name.clear(); + return true; } bool kpColorCollection::saveKDE(QWidget *parent) const { - const QString name = d->name; - QString filename = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) - + "colors/" + name; - const bool ret = saveAs (QUrl::fromLocalFile (filename), false/*no overwite prompt*/, parent); - // (d->name is wiped by saveAs()). - d->name = name; - return ret; + const QString name = d->name; + QString filename = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + + "colors/" + name; + const bool ret = saveAs(QUrl::fromLocalFile(filename), false /*no overwite prompt*/, parent); + // (d->name is wiped by saveAs()). + d->name = name; + return ret; } QString kpColorCollection::description() const @@ -438,65 +429,66 @@ int kpColorCollection::count() const { - return (int) d->colorList.count(); + return (int)d->colorList.count(); } void kpColorCollection::resize(int newCount) { - if (newCount == count()) + if (newCount == count()) { return; - else if (newCount < count()) - { + } else if (newCount < count()) { d->colorList.erase(d->colorList.begin() + newCount, d->colorList.end()); - } - else if (newCount > count()) - { - while(newCount > count()) - { - const int ret = addColor(QColor(), QString()/*color name*/); - Q_ASSERT(ret == count() - 1); - } + } else if (newCount > count()) { + while (newCount > count()) + { + const int ret = addColor(QColor(), QString() /*color name*/); + Q_ASSERT(ret == count() - 1); + } } } -kpColorCollection& -kpColorCollection::operator=( const kpColorCollection &p) +kpColorCollection & +kpColorCollection::operator=(const kpColorCollection &p) { - if (&p == this) return *this; + if (&p == this) { + return *this; + } d->colorList = p.d->colorList; d->name = p.d->name; d->desc = p.d->desc; d->editable = p.d->editable; - return *this; + return *this; } QColor kpColorCollection::color(int index) const { - if ((index < 0) || (index >= count())) - return {}; + if ((index < 0) || (index >= count())) { + return {}; + } return d->colorList[index].color; } int kpColorCollection::findColor(const QColor &color) const { - for (int i = 0; i < d->colorList.size(); ++i) - { - if (d->colorList[i].color == color) - return i; - } - return -1; + for (int i = 0; i < d->colorList.size(); ++i) { + if (d->colorList[i].color == color) { + return i; + } + } + return -1; } QString kpColorCollection::name(int index) const { - if ((index < 0) || (index >= count())) - return {}; + if ((index < 0) || (index >= count())) { + return {}; + } - return d->colorList[index].name; + return d->colorList[index].name; } QString kpColorCollection::name(const QColor &color) const @@ -512,24 +504,21 @@ } int -kpColorCollection::changeColor(int index, - const QColor &newColor, - const QString &newColorName) +kpColorCollection::changeColor(int index, const QColor &newColor, const QString &newColorName) { - if ((index < 0) || (index >= count())) - return -1; + if ((index < 0) || (index >= count())) { + return -1; + } - ColorNode& node = d->colorList[index]; - node.color = newColor; - node.name = newColorName; + ColorNode &node = d->colorList[index]; + node.color = newColor; + node.name = newColorName; - return index; + return index; } -int kpColorCollection::changeColor(const QColor &oldColor, - const QColor &newColor, - const QString &newColorName) +int kpColorCollection::changeColor(const QColor &oldColor, const QColor &newColor, + const QString &newColorName) { - return changeColor( findColor(oldColor), newColor, newColorName); + return changeColor(findColor(oldColor), newColor, newColorName); } - diff --git a/lgpl/generic/kpUrlFormatter.h b/lgpl/generic/kpUrlFormatter.h --- a/lgpl/generic/kpUrlFormatter.h +++ b/lgpl/generic/kpUrlFormatter.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,33 +24,28 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - // // This class is in the lpgl/ folder because other code in the folder needs // to access it. But it is not under the LPGL. // - #ifndef kpUrlFormatter_H #define kpUrlFormatter_H #include - class QString; class QUrl; - class KOLOURPAINT_LGPL_EXPORT kpUrlFormatter { public: // (will convert: empty Url --> "Untitled") - static QString PrettyUrl (const QUrl &url); + static QString PrettyUrl(const QUrl &url); // (will convert: empty Url --> "Untitled") - static QString PrettyFilename (const QUrl &url); + static QString PrettyFilename(const QUrl &url); }; - #endif // kpUrlFormatter_H diff --git a/lgpl/generic/kpUrlFormatter.cpp b/lgpl/generic/kpUrlFormatter.cpp --- a/lgpl/generic/kpUrlFormatter.cpp +++ b/lgpl/generic/kpUrlFormatter.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,41 +24,37 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpUrlFormatter.h" #include #include //--------------------------------------------------------------------- // public static -QString kpUrlFormatter::PrettyUrl (const QUrl &url) +QString kpUrlFormatter::PrettyUrl(const QUrl &url) { - if (url.isEmpty ()) - { - return i18n ("Untitled"); + if (url.isEmpty()) { + return i18n("Untitled"); } - return url.url (QUrl::PreferLocalFile); + return url.url(QUrl::PreferLocalFile); } //--------------------------------------------------------------------- // public static -QString kpUrlFormatter::PrettyFilename (const QUrl &url) +QString kpUrlFormatter::PrettyFilename(const QUrl &url) { - if (url.isEmpty ()) - { - return i18n ("Untitled"); + if (url.isEmpty()) { + return i18n("Untitled"); } - if (url.fileName ().isEmpty ()) - { - return kpUrlFormatter::PrettyUrl (url); // better than the name "" + if (url.fileName().isEmpty()) { + return kpUrlFormatter::PrettyUrl(url); // better than the name "" } - return url.fileName (); + return url.fileName(); } //--------------------------------------------------------------------- diff --git a/lgpl/generic/widgets/kpColorCellsBase.h b/lgpl/generic/widgets/kpColorCellsBase.h --- a/lgpl/generic/widgets/kpColorCellsBase.h +++ b/lgpl/generic/widgets/kpColorCellsBase.h @@ -1,4 +1,3 @@ - // SYNC: Periodically merge in changes from: // // trunk/KDE/kdelibs/kdeui/colors/kcolordialog.{h,cpp} @@ -66,120 +65,120 @@ */ class KOLOURPAINT_LGPL_EXPORT kpColorCellsBase : public QTableWidget { - Q_OBJECT + Q_OBJECT public: - /** - * Constructs a new table of color cells, consisting of - * @p rows * @p columns colors. - * - * @param parent The parent of the new widget - * @param rows The number of rows in the table - * @param columns The number of columns in the table - * - * Specifying and was made optional for KolourPaint. - */ - kpColorCellsBase( QWidget *parent, int rows = 0, int columns = 0 ); - ~kpColorCellsBase() override; + /** + * Constructs a new table of color cells, consisting of + * @p rows * @p columns colors. + * + * @param parent The parent of the new widget + * @param rows The number of rows in the table + * @param columns The number of columns in the table + * + * Specifying and was made optional for KolourPaint. + */ + kpColorCellsBase(QWidget *parent, int rows = 0, int columns = 0); + ~kpColorCellsBase() override; private: - /** Added for KolourPaint. */ - void invalidateAllColors (); + /** Added for KolourPaint. */ + void invalidateAllColors(); public: - /** Added for KolourPaint. - WARNING: These are not virtual in QTableWidget. - */ - void clear (); - void clearContents (); - - /** Added for KolourPaint. */ - void setRowColumnCounts (int rows, int columns); - - /** Added for KolourPaint. - WARNING: These are not virtual in QTableWidget. - */ - void setColumnCount (int columns); - void setRowCount (int rows); - - /** Sets the color in the given index in the table. - - The following behavior change was added for KolourPaint: - - If is not valid, the cell widget at is deleted. - */ - void setColor( int index, const QColor &col ); - /** Returns the color at a given index in the table. - If a cell widget does not exist at , the invalid color is - returned. - */ - QColor color( int index ) const; - /** Returns the total number of color cells in the table */ - int count() const; - - void setShading(bool shade); - void setAcceptDrags(bool acceptDrags); - - /** Whether component cells should resize with the entire widget. - Default is true. - - Added for KolourPaint. - */ - void setCellsResizable(bool yes); - - /** Sets the currently selected cell to @p index */ - void setSelected(int index); - /** Returns the index of the cell which is currently selected */ - int selectedIndex() const; + /** Added for KolourPaint. + WARNING: These are not virtual in QTableWidget. + */ + void clear(); + void clearContents(); + + /** Added for KolourPaint. */ + void setRowColumnCounts(int rows, int columns); + + /** Added for KolourPaint. + WARNING: These are not virtual in QTableWidget. + */ + void setColumnCount(int columns); + void setRowCount(int rows); + + /** Sets the color in the given index in the table. + + The following behavior change was added for KolourPaint: + + If is not valid, the cell widget at is deleted. + */ + void setColor(int index, const QColor &col); + /** Returns the color at a given index in the table. + If a cell widget does not exist at , the invalid color is + returned. + */ + QColor color(int index) const; + /** Returns the total number of color cells in the table */ + int count() const; + + void setShading(bool shade); + void setAcceptDrags(bool acceptDrags); + + /** Whether component cells should resize with the entire widget. + Default is true. + + Added for KolourPaint. + */ + void setCellsResizable(bool yes); + + /** Sets the currently selected cell to @p index */ + void setSelected(int index); + /** Returns the index of the cell which is currently selected */ + int selectedIndex() const; Q_SIGNALS: - /** Emitted when a color is selected in the table */ - void colorSelected( int index , const QColor& color ); - /** Emitted with the above. + /** Emitted when a color is selected in the table */ + void colorSelected(int index, const QColor &color); + /** Emitted with the above. - Added for KolourPaint. - */ - void colorSelectedWhitButton( int index , const QColor& color, Qt::MouseButton button ); + Added for KolourPaint. + */ + void colorSelectedWhitButton(int index, const QColor &color, Qt::MouseButton button); - /** Emitted when a color in the table is double-clicked */ - void colorDoubleClicked( int index , const QColor& color ); + /** Emitted when a color in the table is double-clicked */ + void colorDoubleClicked(int index, const QColor &color); - /** Emitted when setColor() is called. - This includes when a color is dropped onto the table, via drag-and-drop. + /** Emitted when setColor() is called. + This includes when a color is dropped onto the table, via drag-and-drop. - Added for KolourPaint. - */ - void colorChanged( int index , const QColor& color ); + Added for KolourPaint. + */ + void colorChanged(int index, const QColor &color); protected: - /** Grays out the cells, when the object is disabled. - Added for KolourPaint. - */ - void changeEvent( QEvent* event ) override; - - // the three methods below are used to ensure equal column widths and row heights - // for all cells and to update the widths/heights when the widget is resized - int sizeHintForColumn(int column) const override; - int sizeHintForRow(int column) const override; - void resizeEvent( QResizeEvent* event ) override; - - void mouseReleaseEvent( QMouseEvent * ) override; - void mousePressEvent( QMouseEvent * ) override; - void mouseMoveEvent( QMouseEvent * ) override; - void dragEnterEvent( QDragEnterEvent * ) override; - void dragMoveEvent( QDragMoveEvent * ) override; - void dropEvent( QDropEvent *) override; - void mouseDoubleClickEvent( QMouseEvent * ) override; - - /** was added for KolourPaint. */ - int positionToCell(const QPoint &pos, bool ignoreBorders=false, - bool allowEmptyCell=false) const; + /** Grays out the cells, when the object is disabled. + Added for KolourPaint. + */ + void changeEvent(QEvent *event) override; + + // the three methods below are used to ensure equal column widths and row heights + // for all cells and to update the widths/heights when the widget is resized + int sizeHintForColumn(int column) const override; + int sizeHintForRow(int column) const override; + void resizeEvent(QResizeEvent *event) override; + + void mouseReleaseEvent(QMouseEvent *) override; + void mousePressEvent(QMouseEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + void dragEnterEvent(QDragEnterEvent *) override; + void dragMoveEvent(QDragMoveEvent *) override; + void dropEvent(QDropEvent *) override; + void mouseDoubleClickEvent(QMouseEvent *) override; + + /** was added for KolourPaint. */ + int positionToCell(const QPoint &pos, bool ignoreBorders = false, + bool allowEmptyCell = false) const; private: - class kpColorCellsBasePrivate; - friend class kpColorCellsBasePrivate; - kpColorCellsBasePrivate *const d; + class kpColorCellsBasePrivate; + friend class kpColorCellsBasePrivate; + kpColorCellsBasePrivate *const d; - Q_DISABLE_COPY(kpColorCellsBase) + Q_DISABLE_COPY(kpColorCellsBase) }; -#endif // kpColorCellsBase_H +#endif // kpColorCellsBase_H diff --git a/lgpl/generic/widgets/kpColorCellsBase.cpp b/lgpl/generic/widgets/kpColorCellsBase.cpp --- a/lgpl/generic/widgets/kpColorCellsBase.cpp +++ b/lgpl/generic/widgets/kpColorCellsBase.cpp @@ -1,4 +1,3 @@ - /* This file is part of the KDE libraries Copyright (C) 1997 Martin Jones (mjones@kde.org) Copyright (C) 2007 Roberto Raggi (roberto@kdevelop.org) @@ -39,11 +38,10 @@ #include - class kpColorCellsBase::kpColorCellsBasePrivate { public: - kpColorCellsBasePrivate(kpColorCellsBase *q): q(q) + kpColorCellsBasePrivate(kpColorCellsBase *q) : q(q) { colors = nullptr; inMouse = false; @@ -70,22 +68,23 @@ QColor *colors; QPoint mousePos; - int selected; + int selected; bool shade; bool acceptDrags; bool cellsResizable; bool inMouse; }; -kpColorCellsBase::kpColorCellsBase( QWidget *parent, int rows, int cols ) - : QTableWidget( parent ), d(new kpColorCellsBasePrivate(this)) +kpColorCellsBase::kpColorCellsBase(QWidget *parent, int rows, int cols) + : QTableWidget(parent) + , d(new kpColorCellsBasePrivate(this)) { setItemDelegate(new QItemDelegate(this)); setFrameShape(QFrame::NoFrame); d->shade = true; - setRowCount( rows ); - setColumnCount( cols ); + setRowCount(rows); + setColumnCount(cols); verticalHeader()->setMinimumSectionSize(16); verticalHeader()->hide(); @@ -98,12 +97,12 @@ d->inMouse = false; // Drag'n'Drop - setAcceptDrops( true); + setAcceptDrops(true); - setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - viewport()->setBackgroundRole( QPalette::Window ); - setBackgroundRole( QPalette::Window ); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + viewport()->setBackgroundRole(QPalette::Window); + setBackgroundRole(QPalette::Window); } kpColorCellsBase::~kpColorCellsBase() @@ -113,58 +112,63 @@ delete d; } -void kpColorCellsBase::invalidateAllColors () +void kpColorCellsBase::invalidateAllColors() { - for (int r = 0; r < rowCount (); r++) - for (int c = 0; c < columnCount (); c++) - d->colors [r * columnCount () + c] = QColor (); + for (int r = 0; r < rowCount(); r++) { + for (int c = 0; c < columnCount(); c++) { + d->colors [r * columnCount() + c] = QColor(); + } + } } void kpColorCellsBase::clear() { - invalidateAllColors (); - QTableWidget::clear (); + invalidateAllColors(); + QTableWidget::clear(); } void kpColorCellsBase::clearContents() { - invalidateAllColors (); - QTableWidget::clearContents (); + invalidateAllColors(); + QTableWidget::clearContents(); } -void kpColorCellsBase::setRowColumnCounts (int rows, int columns) +void kpColorCellsBase::setRowColumnCounts(int rows, int columns) { - const int oldRows = rowCount (), oldCols = columnCount (); + const int oldRows = rowCount(), oldCols = columnCount(); const int newRows = rows, newCols = columns; #if DEBUG_KP_COLOR_CELLS_BASE qCDebug(kpLogMisc) << "oldRows=" << oldRows << "oldCols=" << oldCols - << "newRows=" << newRows << "newCols=" << newCols; + << "newRows=" << newRows << "newCols=" << newCols; #endif - if (oldRows == newRows && oldCols == newCols) + if (oldRows == newRows && oldCols == newCols) { return; + } - QTableWidget::setColumnCount (newCols); - QTableWidget::setRowCount (newRows); + QTableWidget::setColumnCount(newCols); + QTableWidget::setRowCount(newRows); QColor *oldColors = d->colors; d->colors = new QColor [newRows * newCols]; - for (int r = 0; r < qMin (oldRows, newRows); r++) - for (int c = 0; c < qMin (oldCols, newCols); c++) + for (int r = 0; r < qMin(oldRows, newRows); r++) { + for (int c = 0; c < qMin(oldCols, newCols); c++) { d->colors [r * newCols + c] = oldColors [r * oldCols + c]; + } + } delete [] oldColors; } -void kpColorCellsBase::setColumnCount (int newColumns) +void kpColorCellsBase::setColumnCount(int newColumns) { - setRowColumnCounts (rowCount (), newColumns); + setRowColumnCounts(rowCount(), newColumns); } -void kpColorCellsBase::setRowCount (int newRows) +void kpColorCellsBase::setRowCount(int newRows) { - setRowColumnCounts (newRows, columnCount ()); + setRowColumnCounts(newRows, columnCount()); } QColor kpColorCellsBase::color(int index) const @@ -194,7 +198,7 @@ void kpColorCellsBase::setSelected(int index) { - Q_ASSERT( index >= 0 && index < count() ); + Q_ASSERT(index >= 0 && index < count()); d->selected = index; } @@ -206,236 +210,233 @@ //--------------------------------------------------------------------- -static void TableWidgetItemSetColor (QTableWidgetItem *tableItem, const QColor &color) +static void TableWidgetItemSetColor(QTableWidgetItem *tableItem, const QColor &color) { - Q_ASSERT (tableItem); + Q_ASSERT(tableItem); QImage image(16, 16, QImage::Format_ARGB32_Premultiplied); QPainter painter(&image); const int StippleSize = 4; QColor useColor; - for (int dy = 0; dy < 16; dy += StippleSize) - { - for (int dx = 0; dx < 16; dx += StippleSize) - { + for (int dy = 0; dy < 16; dy += StippleSize) { + for (int dx = 0; dx < 16; dx += StippleSize) { const bool parity = ((dy + dx) / StippleSize) % 2; - if (!parity) + if (!parity) { useColor = Qt::white; - else + } else { useColor = Qt::lightGray; + } painter.fillRect(dx, dy, StippleSize, StippleSize, useColor); } } painter.fillRect(image.rect(), color); painter.end(); - tableItem->setData(Qt::BackgroundRole , QBrush(image)); + tableItem->setData(Qt::BackgroundRole, QBrush(image)); } //--------------------------------------------------------------------- -void kpColorCellsBase::setColor( int column, const QColor &colorIn ) +void kpColorCellsBase::setColor(int column, const QColor &colorIn) { const int tableRow = column / columnCount(); const int tableColumn = column % columnCount(); - Q_ASSERT( tableRow >= 0 && tableRow < rowCount() ); - Q_ASSERT( tableColumn >= 0 && tableColumn < columnCount() ); + Q_ASSERT(tableRow >= 0 && tableRow < rowCount()); + Q_ASSERT(tableColumn >= 0 && tableColumn < columnCount()); QColor color = colorIn; d->colors[column] = color; - QTableWidgetItem* tableItem = item(tableRow,tableColumn); + QTableWidgetItem *tableItem = item(tableRow, tableColumn); - if (color.isValid ()) - { - if ( tableItem == nullptr ) { + if (color.isValid()) { + if (tableItem == nullptr) { tableItem = new QTableWidgetItem(); - setItem(tableRow,tableColumn,tableItem); + setItem(tableRow, tableColumn, tableItem); } - if (isEnabled ()) - ::TableWidgetItemSetColor (tableItem, color); - } - else - { + if (isEnabled()) { + ::TableWidgetItemSetColor(tableItem, color); + } + } else { delete tableItem; } - emit colorChanged (column, color); + emit colorChanged(column, color); } -void kpColorCellsBase::changeEvent( QEvent* event ) +void kpColorCellsBase::changeEvent(QEvent *event) { - QTableWidget::changeEvent (event); + QTableWidget::changeEvent(event); - if (event->type () != QEvent::EnabledChange) + if (event->type() != QEvent::EnabledChange) { return; + } - for (int r = 0; r < rowCount (); r++) - { - for (int c = 0; c < columnCount (); c++) - { - const int index = r * columnCount () + c; + for (int r = 0; r < rowCount(); r++) { + for (int c = 0; c < columnCount(); c++) { + const int index = r * columnCount() + c; - QTableWidgetItem* tableItem = item(r, c); + QTableWidgetItem *tableItem = item(r, c); // See API Doc for this invariant. - Q_ASSERT (!!tableItem == d->colors [index].isValid ()); + Q_ASSERT(!!tableItem == d->colors [index].isValid()); - if (!tableItem) + if (!tableItem) { continue; - + } QColor color; - if (isEnabled ()) + if (isEnabled()) { color = d->colors [index]; - else - color = palette ().color (backgroundRole ()); + } else { + color = palette().color(backgroundRole()); + } - ::TableWidgetItemSetColor (tableItem, color); + ::TableWidgetItemSetColor(tableItem, color); } } } /*void kpColorCellsBase::paintCell( QPainter *painter, int row, int col ) { painter->setRenderHint( QPainter::Antialiasing , true ); - QBrush brush; - int w = 1; - - if (shade) - { - qDrawShadePanel( painter, 1, 1, cellWidth()-2, - cellHeight()-2, palette(), true, 1, &brush ); - w = 2; - } - QColor color = colors[ row * numCols() + col ]; - if (!color.isValid()) - { - if (!shade) return; - color = palette().color(backgroundRole()); - } - - const QRect colorRect( w, w, cellWidth()-w*2, cellHeight()-w*2 ); - painter->fillRect( colorRect, color ); - - if ( row * numCols() + col == selected ) { - painter->setPen( qGray(color.rgb())>=127 ? Qt::black : Qt::white ); - painter->drawLine( colorRect.topLeft(), colorRect.bottomRight() ); - painter->drawLine( colorRect.topRight(), colorRect.bottomLeft() ); - } + QBrush brush; + int w = 1; + + if (shade) + { + qDrawShadePanel( painter, 1, 1, cellWidth()-2, + cellHeight()-2, palette(), true, 1, &brush ); + w = 2; + } + QColor color = colors[ row * numCols() + col ]; + if (!color.isValid()) + { + if (!shade) return; + color = palette().color(backgroundRole()); + } + + const QRect colorRect( w, w, cellWidth()-w*2, cellHeight()-w*2 ); + painter->fillRect( colorRect, color ); + + if ( row * numCols() + col == selected ) { + painter->setPen( qGray(color.rgb())>=127 ? Qt::black : Qt::white ); + painter->drawLine( colorRect.topLeft(), colorRect.bottomRight() ); + painter->drawLine( colorRect.topRight(), colorRect.bottomLeft() ); + } }*/ -void kpColorCellsBase::resizeEvent( QResizeEvent* e ) +void kpColorCellsBase::resizeEvent(QResizeEvent *e) { - if (d->cellsResizable) - { + if (d->cellsResizable) { // According to the Qt doc: // If you need to set the width of a given column to a fixed value, call // QHeaderView::resizeSection() on the table's {horizontal,vertical} // header. // Therefore we iterate over each row and column and set the header section // size, as the sizeHint does indeed appear to be ignored in favor of a // minimum size that is larger than what we want. - for ( int index = 0 ; index < columnCount() ; index++ ) - horizontalHeader()->resizeSection( index, sizeHintForColumn(index) ); - for ( int index = 0 ; index < rowCount() ; index++ ) - verticalHeader()->resizeSection( index, sizeHintForRow(index) ); - } - else - { + for (int index = 0; index < columnCount(); index++) { + horizontalHeader()->resizeSection(index, sizeHintForColumn(index)); + } + for (int index = 0; index < rowCount(); index++) { + verticalHeader()->resizeSection(index, sizeHintForRow(index)); + } + } else { // Update scrollbars if they're forced on by a subclass. // TODO: Should the d->cellsResizable path (from kdelibs) do this as well? - QTableWidget::resizeEvent (e); + QTableWidget::resizeEvent(e); } } int kpColorCellsBase::sizeHintForColumn(int /*column*/) const { // TODO: Should it be "(width() - frameWidth() * 2) / columnCount()"? - return width() / columnCount() ; + return width() / columnCount(); } int kpColorCellsBase::sizeHintForRow(int /*row*/) const { // TODO: Should be "(height() - frameWidth() * 2) / rowCount()"? - return height() / rowCount() ; + return height() / rowCount(); } -void kpColorCellsBase::mousePressEvent( QMouseEvent *e ) +void kpColorCellsBase::mousePressEvent(QMouseEvent *e) { d->inMouse = true; d->mousePos = e->pos(); } - int kpColorCellsBase::positionToCell(const QPoint &pos, bool ignoreBorders, - bool allowEmptyCell) const + bool allowEmptyCell) const { //TODO ignoreBorders not yet handled - Q_UNUSED( ignoreBorders ) + Q_UNUSED(ignoreBorders) - const int r = indexAt (pos).row (), c = indexAt (pos).column (); + const int r = indexAt(pos).row(), c = indexAt(pos).column(); #if DEBUG_KP_COLOR_CELLS_BASE qCDebug(kpLogMisc) << "r=" << r << "c=" << c; #endif - if (r == -1 || c == -1) - return -1; + if (r == -1 || c == -1) { + return -1; + } - if (!allowEmptyCell && !itemAt(pos)) + if (!allowEmptyCell && !itemAt(pos)) { return -1; + } const int cell = r * columnCount() + c; - /*if (!ignoreBorders) - { - int border = 2; - int x = pos.x() - col * cellWidth(); - int y = pos.y() - row * cellHeight(); - if ( (x < border) || (x > cellWidth()-border) || - (y < border) || (y > cellHeight()-border)) - return -1; - }*/ + /*if (!ignoreBorders) + { + int border = 2; + int x = pos.x() - col * cellWidth(); + int y = pos.y() - row * cellHeight(); + if ( (x < border) || (x > cellWidth()-border) || + (y < border) || (y > cellHeight()-border)) + return -1; + }*/ return cell; } - -void kpColorCellsBase::mouseMoveEvent( QMouseEvent *e ) +void kpColorCellsBase::mouseMoveEvent(QMouseEvent *e) { - if( !(e->buttons() & Qt::LeftButton)) return; + if (!(e->buttons() & Qt::LeftButton)) { + return; + } - if(d->inMouse) { + if (d->inMouse) { int delay = QApplication::startDragDistance(); - if(e->x() > d->mousePos.x()+delay || e->x() < d->mousePos.x()-delay || - e->y() > d->mousePos.y()+delay || e->y() < d->mousePos.y()-delay){ + if (e->x() > d->mousePos.x()+delay || e->x() < d->mousePos.x()-delay + || e->y() > d->mousePos.y()+delay || e->y() < d->mousePos.y()-delay) { // Drag color object int cell = positionToCell(d->mousePos); - if (cell != -1) - { + if (cell != -1) { #if DEBUG_KP_COLOR_CELLS_BASE - qCDebug(kpLogMisc) << "beginning drag from cell=" << cell - << "color: isValid=" << d->colors [cell].isValid () - << " rgba=" << (int *) d->colors [cell].rgba(); + qCDebug(kpLogMisc) << "beginning drag from cell=" << cell + << "color: isValid=" << d->colors [cell].isValid() + << " rgba=" << (int *)d->colors [cell].rgba(); #endif - Q_ASSERT (d->colors[cell].isValid()); - KColorMimeData::createDrag(d->colors[cell], this)->start(Qt::CopyAction | Qt::MoveAction); + Q_ASSERT(d->colors[cell].isValid()); + KColorMimeData::createDrag(d->colors[cell], this)->start( + Qt::CopyAction | Qt::MoveAction); #if DEBUG_KP_COLOR_CELLS_BASE - qCDebug(kpLogMisc) << "finished drag"; + qCDebug(kpLogMisc) << "finished drag"; #endif } } } } - // LOTODO: I'm not quite clear on how the drop actions logic is supposed // to be done e.g.: // @@ -446,118 +447,121 @@ // // Nevertheless, it appears to work -- probably because we restrict // the non-Qt-default move/swap action to be intrawidget. -static void SetDropAction (QWidget *self, QDropEvent *event) -{ - // TODO: Would be nice to default to CopyAction if the destination cell - // is null. - if (event->source () == self && (event->keyboardModifiers () & Qt::ControlModifier) == 0) - event->setDropAction(Qt::MoveAction); - else - event->setDropAction(Qt::CopyAction); +static void SetDropAction(QWidget *self, QDropEvent *event) +{ + // TODO: Would be nice to default to CopyAction if the destination cell + // is null. + if (event->source() == self && (event->keyboardModifiers() & Qt::ControlModifier) == 0) { + event->setDropAction(Qt::MoveAction); + } else { + event->setDropAction(Qt::CopyAction); + } } -void kpColorCellsBase::dragEnterEvent( QDragEnterEvent *event) +void kpColorCellsBase::dragEnterEvent(QDragEnterEvent *event) { #if DEBUG_KP_COLOR_CELLS_BASE - qCDebug(kpLogMisc) << "kpColorCellsBase::dragEnterEvent() acceptDrags=" - << d->acceptDrags - << " canDecode=" << KColorMimeData::canDecode(event->mimeData()); + qCDebug(kpLogMisc) << "kpColorCellsBase::dragEnterEvent() acceptDrags=" + << d->acceptDrags + << " canDecode=" << KColorMimeData::canDecode(event->mimeData()); #endif - event->setAccepted( d->acceptDrags && KColorMimeData::canDecode( event->mimeData())); - if (event->isAccepted ()) - ::SetDropAction (this, event); + event->setAccepted(d->acceptDrags && KColorMimeData::canDecode(event->mimeData())); + if (event->isAccepted()) { + ::SetDropAction(this, event); + } } // Reimplemented to override QTableWidget's override. Else dropping doesn't work. -void kpColorCellsBase::dragMoveEvent (QDragMoveEvent *event) +void kpColorCellsBase::dragMoveEvent(QDragMoveEvent *event) { #if DEBUG_KP_COLOR_CELLS_BASE - qCDebug(kpLogMisc) << "kpColorCellsBase::dragMoveEvent() acceptDrags=" - << d->acceptDrags - << " canDecode=" << KColorMimeData::canDecode(event->mimeData()); + qCDebug(kpLogMisc) << "kpColorCellsBase::dragMoveEvent() acceptDrags=" + << d->acceptDrags + << " canDecode=" << KColorMimeData::canDecode(event->mimeData()); #endif - // TODO: Disallow drag that isn't onto a cell. - event->setAccepted( d->acceptDrags && KColorMimeData::canDecode( event->mimeData())); - if (event->isAccepted ()) - ::SetDropAction (this, event); + // TODO: Disallow drag that isn't onto a cell. + event->setAccepted(d->acceptDrags && KColorMimeData::canDecode(event->mimeData())); + if (event->isAccepted()) { + ::SetDropAction(this, event); + } } -void kpColorCellsBase::dropEvent( QDropEvent *event) +void kpColorCellsBase::dropEvent(QDropEvent *event) { - QColor c=KColorMimeData::fromMimeData(event->mimeData()); + QColor c = KColorMimeData::fromMimeData(event->mimeData()); - const int dragSourceCell = event->source () == this ? - positionToCell (d->mousePos, true) : - -1; + const int dragSourceCell = event->source() == this + ? positionToCell(d->mousePos, true) + : -1; #if DEBUG_KP_COLOR_CELLS_BASE - qCDebug(kpLogMisc) << "kpColorCellsBase::dropEvent()" - << "color: rgba=" << (const int *) c.rgba () << "isValid=" << c.isValid() - << "source=" << event->source () << "dragSourceCell=" << dragSourceCell; + qCDebug(kpLogMisc) << "kpColorCellsBase::dropEvent()" + << "color: rgba=" << (const int *)c.rgba() << "isValid=" << c.isValid() + << "source=" << event->source() << "dragSourceCell=" << dragSourceCell; #endif - if( c.isValid()) { - ::SetDropAction (this, event); + if (c.isValid()) { + ::SetDropAction(this, event); - int cell = positionToCell(event->pos(), true, true/*allow empty cell*/); + int cell = positionToCell(event->pos(), true, true /*allow empty cell*/); #if DEBUG_KP_COLOR_CELLS_BASE - qCDebug(kpLogMisc) << "\tcell=" << cell; + qCDebug(kpLogMisc) << "\tcell=" << cell; #endif - // TODO: I believe kdelibs forgets to do this. - if (cell == -1) - return; + // TODO: I believe kdelibs forgets to do this. + if (cell == -1) { + return; + } - // Avoid NOP. - if (cell == dragSourceCell) - return; + // Avoid NOP. + if (cell == dragSourceCell) { + return; + } - QColor destOldColor = d->colors [cell]; - setColor(cell,c); + QColor destOldColor = d->colors [cell]; + setColor(cell, c); #if DEBUG_KP_COLOR_CELLS_BASE - qCDebug(kpLogMisc) << "\tdropAction=" << event->dropAction () - << "destOldColor.rgba=" << (const int *) destOldColor.rgba (); + qCDebug(kpLogMisc) << "\tdropAction=" << event->dropAction() + << "destOldColor.rgba=" << (const int *)destOldColor.rgba(); #endif - if (event->dropAction () == Qt::MoveAction && dragSourceCell != -1) { - setColor(dragSourceCell, destOldColor); - } - } + if (event->dropAction() == Qt::MoveAction && dragSourceCell != -1) { + setColor(dragSourceCell, destOldColor); + } + } } -void kpColorCellsBase::mouseReleaseEvent( QMouseEvent *e ) +void kpColorCellsBase::mouseReleaseEvent(QMouseEvent *e) { - int cell = positionToCell(d->mousePos); + int cell = positionToCell(d->mousePos); int currentCell = positionToCell(e->pos()); - // If we release the mouse in another cell and we don't have - // a drag we should ignore this event. - if (currentCell != cell) - cell = -1; + // If we release the mouse in another cell and we don't have + // a drag we should ignore this event. + if (currentCell != cell) { + cell = -1; + } - if ( (cell != -1) && (d->selected != cell) ) - { - d->selected = cell; + if ((cell != -1) && (d->selected != cell)) { + d->selected = cell; const int newRow = cell/columnCount(); const int newColumn = cell%columnCount(); clearSelection(); // we do not want old violet selected cells - item(newRow,newColumn)->setSelected(true); + item(newRow, newColumn)->setSelected(true); } d->inMouse = false; - if (cell != -1) - { - emit colorSelected( cell , color(cell) ); - emit colorSelectedWhitButton( cell , color(cell), e->button() ); + if (cell != -1) { + emit colorSelected(cell, color(cell)); + emit colorSelectedWhitButton(cell, color(cell), e->button()); } } -void kpColorCellsBase::mouseDoubleClickEvent( QMouseEvent * /*e*/ ) +void kpColorCellsBase::mouseDoubleClickEvent(QMouseEvent * /*e*/) { - int cell = positionToCell(d->mousePos, false, true/*allow empty cell*/); + int cell = positionToCell(d->mousePos, false, true /*allow empty cell*/); - if (cell != -1) - emit colorDoubleClicked( cell , color(cell) ); + if (cell != -1) { + emit colorDoubleClicked(cell, color(cell)); + } } - - diff --git a/mainWindow/kpMainWindow.h b/mainWindow/kpMainWindow.h --- a/mainWindow/kpMainWindow.h +++ b/mainWindow/kpMainWindow.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,20 +24,17 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_MAIN_WINDOW_H #define KP_MAIN_WINDOW_H - #include #include #include "kpDefs.h" #include "pixmapfx/kpPixmapFX.h" #include "imagelib/kpImage.h" - class QAction; class QActionGroup; class QDragEnterEvent; @@ -76,7 +72,7 @@ class kpMainWindow : public KXmlGuiWindow { -Q_OBJECT + Q_OBJECT public: // Opens a new window with a blank document. @@ -94,75 +90,74 @@ void finalizeGUI(KXMLGUIClient *client) override; private: - void readGeneralSettings (); - void readThumbnailSettings (); + void readGeneralSettings(); + void readThumbnailSettings(); - void init (); + void init(); // (only called for restoring a previous session e.g. starting KDE with // a previously saved session; it's not called on normal KolourPaint // startup) - void readProperties (const KConfigGroup &configGroup) override; + void readProperties(const KConfigGroup &configGroup) override; // (only called for saving the current session e.g. logging out of KDE // with the KolourPaint window open; it's not called on normal KolourPaint // exit) - void saveProperties (KConfigGroup &configGroup) override; + void saveProperties(KConfigGroup &configGroup) override; public: ~kpMainWindow () override; public: - kpDocument *document () const; - kpDocumentEnvironment *documentEnvironment (); - kpViewManager *viewManager () const; - kpColorToolBar *colorToolBar () const; - kpColorCells *colorCells () const; - kpToolToolBar *toolToolBar () const; - kpCommandHistory *commandHistory () const; - kpCommandEnvironment *commandEnvironment (); + kpDocument *document() const; + kpDocumentEnvironment *documentEnvironment(); + kpViewManager *viewManager() const; + kpColorToolBar *colorToolBar() const; + kpColorCells *colorCells() const; + kpToolToolBar *toolToolBar() const; + kpCommandHistory *commandHistory() const; + kpCommandEnvironment *commandEnvironment(); private: - void setupActions (); - void enableDocumentActions (bool enable = true); + void setupActions(); + void enableDocumentActions(bool enable = true); - void setDocument (kpDocument *newDoc); + void setDocument(kpDocument *newDoc); - void dragEnterEvent (QDragEnterEvent *e) override; - void dropEvent (QDropEvent *e) override; - void moveEvent (QMoveEvent *e) override; + void dragEnterEvent(QDragEnterEvent *e) override; + void dropEvent(QDropEvent *e) override; + void moveEvent(QMoveEvent *e) override; private slots: - void slotScrollViewAfterScroll (); - void slotUpdateCaption (); - void slotDocumentRestored (); - + void slotScrollViewAfterScroll(); + void slotUpdateCaption(); + void slotDocumentRestored(); // // Tools // private: - kpToolSelectionEnvironment *toolSelectionEnvironment (); - kpToolEnvironment *toolEnvironment (); + kpToolSelectionEnvironment *toolSelectionEnvironment(); + kpToolEnvironment *toolEnvironment(); - void setupToolActions (); - void createToolBox (); - void enableToolsDocumentActions (bool enable = true); + void setupToolActions(); + void createToolBox(); + void enableToolsDocumentActions(bool enable = true); private slots: - void updateToolOptionPrevNextActionsEnabled (); - void updateActionDrawOpaqueChecked (); + void updateToolOptionPrevNextActionsEnabled(); + void updateActionDrawOpaqueChecked(); private: - void updateActionDrawOpaqueEnabled (); + void updateActionDrawOpaqueEnabled(); public: - QActionGroup *toolsActionGroup (); + QActionGroup *toolsActionGroup(); - kpTool *tool () const; + kpTool *tool() const; - bool toolHasBegunShape () const; - bool toolIsASelectionTool (bool includingTextTool = true) const; - bool toolIsTextTool () const; + bool toolHasBegunShape() const; + bool toolIsASelectionTool(bool includingTextTool = true) const; + bool toolIsTextTool() const; private: // Ends the current shape. If there is no shape currently being drawn, @@ -213,10 +208,10 @@ // // TODO: Help / KolourPaint Handbook does not call this. I'm sure there // are a few other actions that don't call this but should. - void toolEndShape (); + void toolEndShape(); public: - kpImageSelectionTransparency imageSelectionTransparency () const; + kpImageSelectionTransparency imageSelectionTransparency() const; // The drawing background color is set to .transparentColor() // if the is in Transparent mode or if // is true (not the default). [x] @@ -241,43 +236,41 @@ // // The other fields of are copied into the main window // as expected. - void setImageSelectionTransparency (const kpImageSelectionTransparency &transparency, - bool forceColorChange = false); - int settingImageSelectionTransparency () const; + void setImageSelectionTransparency(const kpImageSelectionTransparency &transparency, + bool forceColorChange = false); + int settingImageSelectionTransparency() const; private slots: - void slotToolSelected (kpTool *tool); + void slotToolSelected(kpTool *tool); private: - void readLastTool (); - int toolNumber () const; - void saveLastTool (); + void readLastTool(); + int toolNumber() const; + void saveLastTool(); private: - bool maybeDragScrollingMainView () const; + bool maybeDragScrollingMainView() const; private slots: - bool slotDragScroll (const QPoint &docPoint, - const QPoint &docLastPoint, - int zoomLevel, - bool *didSomething); - bool slotEndDragScroll (); + bool slotDragScroll(const QPoint &docPoint, const QPoint &docLastPoint, int zoomLevel, + bool *didSomething); + bool slotEndDragScroll(); private slots: - void slotBeganDocResize (); - void slotContinuedDocResize (const QSize &size); - void slotCancelledDocResize (); - void slotEndedDocResize (const QSize &size); + void slotBeganDocResize(); + void slotContinuedDocResize(const QSize &size); + void slotCancelledDocResize(); + void slotEndedDocResize(const QSize &size); - void slotDocResizeMessageChanged (const QString &string); + void slotDocResizeMessageChanged(const QString &string); private slots: - void slotActionPrevToolOptionGroup1 (); - void slotActionNextToolOptionGroup1 (); - void slotActionPrevToolOptionGroup2 (); - void slotActionNextToolOptionGroup2 (); + void slotActionPrevToolOptionGroup1(); + void slotActionNextToolOptionGroup1(); + void slotActionPrevToolOptionGroup2(); + void slotActionNextToolOptionGroup2(); - void slotActionDrawOpaqueToggled (); - void slotActionDrawColorSimilarity (); + void slotActionDrawOpaqueToggled(); + void slotActionDrawColorSimilarity(); public slots: void slotToolRectSelection(); @@ -290,26 +283,25 @@ // private: - void setupFileMenuActions (); - void enableFileMenuDocumentActions (bool enable = true); + void setupFileMenuActions(); + void enableFileMenuDocumentActions(bool enable = true); - void addRecentURL (const QUrl &url); + void addRecentURL(const QUrl &url); private slots: - void slotNew (); + void slotNew(); private: - QSize defaultDocSize () const; - void saveDefaultDocSize (const QSize &size); + QSize defaultDocSize() const; + void saveDefaultDocSize(const QSize &size); private: - bool shouldOpen (); - void setDocumentChoosingWindow (kpDocument *doc); + bool shouldOpen(); + void setDocumentChoosingWindow(kpDocument *doc); private: - kpDocument *openInternal (const QUrl &url, - const QSize &fallbackDocSize, - bool newDocSameNameIfNotExist); + kpDocument *openInternal(const QUrl &url, const QSize &fallbackDocSize, + bool newDocSameNameIfNotExist); // Same as above except that it: // // 1. Assumes a default fallback document size. @@ -321,310 +313,293 @@ // to a user open request e.g. File / Open or "kolourpaint doesexist.png". // It should not be used for session restore - in that case, it does not // make sense to bubble the Recent Files list. - bool open (const QUrl &url, bool newDocSameNameIfNotExist = false); + bool open(const QUrl &url, bool newDocSameNameIfNotExist = false); - QList askForOpenURLs(const QString &caption, - bool allowMultipleURLs = true); + QList askForOpenURLs(const QString &caption, bool allowMultipleURLs = true); private slots: - void slotOpen (); - void slotOpenRecent (const QUrl &url); + void slotOpen(); + void slotOpenRecent(const QUrl &url); void slotRecentListCleared(); #if HAVE_KSANE - void slotScan (); - void slotScanned (const QImage &image, int); + void slotScan(); + void slotScanned(const QImage &image, int); #endif // HAVE_KSANE void slotScreenshot(); void slotMakeScreenshot(); - void slotProperties (); + void slotProperties(); - bool save (bool localOnly = false); - bool slotSave (); + bool save(bool localOnly = false); + bool slotSave(); private: - QUrl askForSaveURL (const QString &caption, - const QString &startURL, - const kpImage &imageToBeSaved, - const kpDocumentSaveOptions &startSaveOptions, - const kpDocumentMetaInfo &docMetaInfo, - const QString &forcedSaveOptionsGroup, - bool localOnly, - kpDocumentSaveOptions *chosenSaveOptions, - bool isSavingForFirstTime, - bool *allowOverwritePrompt, - bool *allowLossyPrompt); + QUrl askForSaveURL(const QString &caption, const QString &startURL, + const kpImage &imageToBeSaved, const kpDocumentSaveOptions &startSaveOptions, + const kpDocumentMetaInfo &docMetaInfo, const QString &forcedSaveOptionsGroup, + bool localOnly, kpDocumentSaveOptions *chosenSaveOptions, + bool isSavingForFirstTime, bool *allowOverwritePrompt, + bool *allowLossyPrompt); private slots: - bool saveAs (bool localOnly = false); - bool slotSaveAs (); + bool saveAs(bool localOnly = false); + bool slotSaveAs(); - bool slotExport (); + bool slotExport(); - void slotEnableReload (); - bool slotReload (); + void slotEnableReload(); + bool slotReload(); void sendPreviewToPrinter(QPrinter *printer); private: - void sendDocumentNameToPrinter (QPrinter *printer); + void sendDocumentNameToPrinter(QPrinter *printer); void sendImageToPrinter(QPrinter *printer, bool showPrinterSetupDialog); private slots: - void slotPrint (); - void slotPrintPreview (); - - void slotMail (); + void slotPrint(); + void slotPrintPreview(); - bool queryCloseDocument (); - bool queryClose () override; + void slotMail(); - void slotClose (); - void slotQuit (); + bool queryCloseDocument(); + bool queryClose() override; + void slotClose(); + void slotQuit(); // // Edit Menu // private: - void setupEditMenuActions (); - void enableEditMenuDocumentActions (bool enable = true); + void setupEditMenuActions(); + void enableEditMenuDocumentActions(bool enable = true); public: - QMenu *selectionToolRMBMenu (); + QMenu *selectionToolRMBMenu(); private slots: - void slotCut (); - void slotCopy (); - void slotEnablePaste (); + void slotCut(); + void slotCopy(); + void slotEnablePaste(); private: - QRect calcUsefulPasteRect (int imageWidth, int imageHeight); + QRect calcUsefulPasteRect(int imageWidth, int imageHeight); // (it is possible to paste a selection border i.e. a selection with no content) - void paste (const kpAbstractSelection &sel, - bool forceTopLeft = false); + void paste(const kpAbstractSelection &sel, bool forceTopLeft = false); public: // ( is ignored if is empty) - void pasteText (const QString &text, - bool forceNewTextSelection = false, - const QPoint &newTextSelectionTopLeft = KP_INVALID_POINT); - void pasteTextAt (const QString &text, const QPoint &point, - // Allow tiny adjustment of so that mouse - // pointer is not exactly on top of the topLeft of - // any new text selection (so that it doesn't look - // weird by being on top of a resize handle just after - // a paste). - bool allowNewTextSelectionPointShift = false); + void pasteText(const QString &text, bool forceNewTextSelection = false, + const QPoint &newTextSelectionTopLeft = KP_INVALID_POINT); + void pasteTextAt(const QString &text, const QPoint &point, + // Allow tiny adjustment of so that mouse + // pointer is not exactly on top of the topLeft of + // any new text selection (so that it doesn't look + // weird by being on top of a resize handle just after + // a paste). + bool allowNewTextSelectionPointShift = false); public slots: - void slotPaste (); + void slotPaste(); private slots: - void slotPasteInNewWindow (); + void slotPasteInNewWindow(); public slots: - void slotDelete (); + void slotDelete(); - void slotSelectAll (); + void slotSelectAll(); private: - void addDeselectFirstCommand (kpCommand *cmd); + void addDeselectFirstCommand(kpCommand *cmd); public slots: - void slotDeselect (); + void slotDeselect(); private slots: - void slotCopyToFile (); - void slotPasteFromFile (); - + void slotCopyToFile(); + void slotPasteFromFile(); // // View Menu // private: - void setupViewMenuActions (); + void setupViewMenuActions(); - bool viewMenuDocumentActionsEnabled () const; - void enableViewMenuDocumentActions (bool enable = true); - void actionShowGridUpdate (); - void updateMainViewGrid (); - QRect mapToGlobal (const QRect &rect) const; - QRect mapFromGlobal (const QRect &rect) const; + bool viewMenuDocumentActionsEnabled() const; + void enableViewMenuDocumentActions(bool enable = true); + void actionShowGridUpdate(); + void updateMainViewGrid(); + QRect mapToGlobal(const QRect &rect) const; + QRect mapFromGlobal(const QRect &rect) const; private slots: - void slotShowGridToggled (); - + void slotShowGridToggled(); // // View Menu - Zoom // private: - void setupViewMenuZoomActions (); - void enableViewMenuZoomDocumentActions (bool enable); + void setupViewMenuZoomActions(); + void enableViewMenuZoomDocumentActions(bool enable); - void sendZoomListToActionZoom (); + void sendZoomListToActionZoom(); - void zoomToPre (int zoomLevel); - void zoomToPost (); + void zoomToPre(int zoomLevel); + void zoomToPost(); public: - void zoomTo (int zoomLevel, bool centerUnderCursor = false); - void zoomToRect (const QRect &normalizedDocRect, - bool accountForGrips, - bool careAboutWidth, bool careAboutHeight); + void zoomTo(int zoomLevel, bool centerUnderCursor = false); + void zoomToRect(const QRect &normalizedDocRect, bool accountForGrips, bool careAboutWidth, + bool careAboutHeight); public slots: - void slotActualSize (); - void slotFitToPage (); - void slotFitToWidth (); - void slotFitToHeight (); + void slotActualSize(); + void slotFitToPage(); + void slotFitToWidth(); + void slotFitToHeight(); public: - void zoomIn (bool centerUnderCursor = false); - void zoomOut (bool centerUnderCursor = false); + void zoomIn(bool centerUnderCursor = false); + void zoomOut(bool centerUnderCursor = false); public slots: - void slotZoomIn (); - void slotZoomOut (); + void slotZoomIn(); + void slotZoomOut(); private: - void zoomAccordingToZoomAction (bool centerUnderCursor = false); + void zoomAccordingToZoomAction(bool centerUnderCursor = false); private slots: - void slotZoom (); - + void slotZoom(); // // View Menu - Thumbnail // private: - void setupViewMenuThumbnailActions (); - void enableViewMenuThumbnailDocumentActions (bool enable); + void setupViewMenuThumbnailActions(); + void enableViewMenuThumbnailDocumentActions(bool enable); private slots: - void slotDestroyThumbnail (); - void slotDestroyThumbnailInitatedByUser (); - void slotCreateThumbnail (); + void slotDestroyThumbnail(); + void slotDestroyThumbnailInitatedByUser(); + void slotCreateThumbnail(); public: - void notifyThumbnailGeometryChanged (); + void notifyThumbnailGeometryChanged(); private slots: - void slotSaveThumbnailGeometry (); - void slotShowThumbnailToggled (); - void updateThumbnailZoomed (); - void slotZoomedThumbnailToggled (); - void slotThumbnailShowRectangleToggled (); + void slotSaveThumbnailGeometry(); + void slotShowThumbnailToggled(); + void updateThumbnailZoomed(); + void slotZoomedThumbnailToggled(); + void slotThumbnailShowRectangleToggled(); private: - void enableViewZoomedThumbnail (bool enable = true); - void enableViewShowThumbnailRectangle (bool enable = true); - void enableThumbnailOptionActions (bool enable = true); - void createThumbnailView (); - void destroyThumbnailView (); - void updateThumbnail (); - + void enableViewZoomedThumbnail(bool enable = true); + void enableViewShowThumbnailRectangle(bool enable = true); + void enableThumbnailOptionActions(bool enable = true); + void createThumbnailView(); + void destroyThumbnailView(); + void updateThumbnail(); // // Image Menu // private: - kpTransformDialogEnvironment *transformDialogEnvironment (); + kpTransformDialogEnvironment *transformDialogEnvironment(); - bool isSelectionActive () const; - bool isTextSelection () const; + bool isSelectionActive() const; + bool isTextSelection() const; - QString autoCropText () const; + QString autoCropText() const; - void setupImageMenuActions (); - void enableImageMenuDocumentActions (bool enable = true); + void setupImageMenuActions(); + void enableImageMenuDocumentActions(bool enable = true); private slots: - void slotImageMenuUpdateDueToSelection (); + void slotImageMenuUpdateDueToSelection(); public: - kpColor backgroundColor (bool ofSelection = false) const; - void addImageOrSelectionCommand (kpCommand *cmd, - bool addSelCreateCmdIfSelAvail = true, - bool addSelContentCmdIfSelAvail = true); + kpColor backgroundColor(bool ofSelection = false) const; + void addImageOrSelectionCommand(kpCommand *cmd, bool addSelCreateCmdIfSelAvail = true, + bool addSelContentCmdIfSelAvail = true); public slots: - void slotCrop (); + void slotCrop(); private slots: - void slotResizeScale (); - void slotAutoCrop (); - void slotFlip (); - void slotMirror (); - - void slotRotate (); - void slotRotate270 (); - void slotRotate90 (); - - void slotSkew (); - void slotConvertToBlackAndWhite (); - void slotConvertToGrayscale (); - void slotInvertColors (); - void slotClear (); + void slotResizeScale(); + void slotAutoCrop(); + void slotFlip(); + void slotMirror(); + + void slotRotate(); + void slotRotate270(); + void slotRotate90(); + + void slotSkew(); + void slotConvertToBlackAndWhite(); + void slotConvertToGrayscale(); + void slotInvertColors(); + void slotClear(); void slotMakeConfidential(); - void slotMoreEffects (); - + void slotMoreEffects(); // // Colors Menu // private: - void setupColorsMenuActions (); - void createColorBox (); - void enableColorsMenuDocumentActions (bool enable); + void setupColorsMenuActions(); + void createColorBox(); + void enableColorsMenuDocumentActions(bool enable); private slots: - void slotUpdateColorsDeleteRowActionEnabled (); + void slotUpdateColorsDeleteRowActionEnabled(); private: - void deselectActionColorsKDE (); + void deselectActionColorsKDE(); - bool queryCloseColors (); + bool queryCloseColors(); private: - void openDefaultColors (); + void openDefaultColors(); private slots: - void slotColorsDefault (); + void slotColorsDefault(); private: - bool openKDEColors (const QString &name); + bool openKDEColors(const QString &name); private slots: - void slotColorsKDE (); + void slotColorsKDE(); private: - bool openColors (const QUrl &url); + bool openColors(const QUrl &url); private slots: - void slotColorsOpen (); - - void slotColorsReload (); + void slotColorsOpen(); - bool slotColorsSave (); - bool slotColorsSaveAs (); + void slotColorsReload(); - void slotColorsAppendRow (); - void slotColorsDeleteRow (); + bool slotColorsSave(); + bool slotColorsSaveAs(); + void slotColorsAppendRow(); + void slotColorsDeleteRow(); // // Settings Menu // private: - void setupSettingsMenuActions (); - void enableSettingsMenuDocumentActions (bool enable = true); + void setupSettingsMenuActions(); + void enableSettingsMenuDocumentActions(bool enable = true); private slots: - void slotFullScreen (); + void slotFullScreen(); - void slotEnableSettingsShowPath (); - void slotShowPathToggled (); + void slotEnableSettingsShowPath(); + void slotShowPathToggled(); void slotDrawAntiAliasedToggled(bool on); - void slotKeyBindings (); + void slotKeyBindings(); // // Status Bar @@ -640,50 +615,49 @@ StatusBarItemZoom }; - void addPermanentStatusBarItem (int id, int maxTextLen); - void createStatusBar (); + void addPermanentStatusBarItem(int id, int maxTextLen); + void createStatusBar(); - void setStatusBarDocDepth (int depth = 0); + void setStatusBarDocDepth(int depth = 0); private slots: - void setStatusBarMessage (const QString &message = QString()); - void setStatusBarShapePoints (const QPoint &startPoint = KP_INVALID_POINT, - const QPoint &endPoint = KP_INVALID_POINT); - void setStatusBarShapeSize (const QSize &size = KP_INVALID_SIZE); - void setStatusBarDocSize (const QSize &size = KP_INVALID_SIZE); - void setStatusBarZoom (int zoom = 0); - - void recalculateStatusBarMessage (); - void recalculateStatusBarShape (); + void setStatusBarMessage(const QString &message = QString()); + void setStatusBarShapePoints(const QPoint &startPoint = KP_INVALID_POINT, + const QPoint &endPoint = KP_INVALID_POINT); + void setStatusBarShapeSize(const QSize &size = KP_INVALID_SIZE); + void setStatusBarDocSize(const QSize &size = KP_INVALID_SIZE); + void setStatusBarZoom(int zoom = 0); - void recalculateStatusBar (); + void recalculateStatusBarMessage(); + void recalculateStatusBarShape(); + void recalculateStatusBar(); // // Text ToolBar // private: - void setupTextToolBarActions (); - void readAndApplyTextSettings (); + void setupTextToolBarActions(); + void readAndApplyTextSettings(); public: - void enableTextToolBarActions (bool enable = true); + void enableTextToolBarActions(bool enable = true); private slots: - void slotTextFontFamilyChanged (); - void slotTextFontSizeChanged (); - void slotTextBoldChanged (); - void slotTextItalicChanged (); - void slotTextUnderlineChanged (); - void slotTextStrikeThruChanged (); + void slotTextFontFamilyChanged(); + void slotTextFontSizeChanged(); + void slotTextBoldChanged(); + void slotTextItalicChanged(); + void slotTextUnderlineChanged(); + void slotTextStrikeThruChanged(); public: - KToolBar *textToolBar (); - bool isTextStyleBackgroundOpaque () const; - kpTextStyle textStyle () const; - void setTextStyle (const kpTextStyle &textStyle_); - int settingTextStyle () const; + KToolBar *textToolBar(); + bool isTextStyleBackgroundOpaque() const; + kpTextStyle textStyle() const; + void setTextStyle(const kpTextStyle &textStyle_); + int settingTextStyle() const; private: struct kpMainWindowPrivate *d; diff --git a/mainWindow/kpMainWindow.cpp b/mainWindow/kpMainWindow.cpp --- a/mainWindow/kpMainWindow.cpp +++ b/mainWindow/kpMainWindow.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpMainWindow.h" #include "kpMainWindowPrivate.h" @@ -59,170 +57,163 @@ #include "kpLogCategories.h" - //--------------------------------------------------------------------- kpMainWindow::kpMainWindow () - : KXmlGuiWindow (nullptr/*parent*/) + : KXmlGuiWindow(nullptr /*parent*/) { - init (); - open (QUrl (), true/*create an empty doc*/); + init(); + open(QUrl(), true /*create an empty doc*/); d->isFullyConstructed = true; } //--------------------------------------------------------------------- kpMainWindow::kpMainWindow (const QUrl &url) - : KXmlGuiWindow (nullptr/*parent*/) + : KXmlGuiWindow(nullptr /*parent*/) { - init (); - open (url, true/*create an empty doc with the same url if url !exist*/); + init(); + open(url, true /*create an empty doc with the same url if url !exist*/); d->isFullyConstructed = true; } //--------------------------------------------------------------------- kpMainWindow::kpMainWindow (kpDocument *newDoc) - : KXmlGuiWindow (nullptr/*parent*/) + : KXmlGuiWindow(nullptr /*parent*/) { - init (); - setDocument (newDoc); + init(); + setDocument(newDoc); d->isFullyConstructed = true; } //--------------------------------------------------------------------- - // TODO: Move into appropriate kpMainWindow_*.cpp or another class // private -void kpMainWindow::readGeneralSettings () +void kpMainWindow::readGeneralSettings() { #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tkpMainWindow(" << objectName () << ")::readGeneralSettings()"; + qCDebug(kpLogMainWindow) << "\tkpMainWindow(" << objectName() << ")::readGeneralSettings()"; #endif - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupGeneral); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); - d->configFirstTime = cfg.readEntry (kpSettingFirstTime, true); - d->configShowGrid = cfg.readEntry (kpSettingShowGrid, false); - d->configShowPath = cfg.readEntry (kpSettingShowPath, false); - d->moreEffectsDialogLastEffect = cfg.readEntry (kpSettingMoreEffectsLastEffect, 0); + d->configFirstTime = cfg.readEntry(kpSettingFirstTime, true); + d->configShowGrid = cfg.readEntry(kpSettingShowGrid, false); + d->configShowPath = cfg.readEntry(kpSettingShowPath, false); + d->moreEffectsDialogLastEffect = cfg.readEntry(kpSettingMoreEffectsLastEffect, 0); kpToolEnvironment::drawAntiAliased = cfg.readEntry(kpSettingDrawAntiAliased, true); - if (cfg.hasKey (kpSettingOpenImagesInSameWindow)) - { - d->configOpenImagesInSameWindow = cfg.readEntry (kpSettingOpenImagesInSameWindow, false); - } - else - { + if (cfg.hasKey(kpSettingOpenImagesInSameWindow)) { + d->configOpenImagesInSameWindow = cfg.readEntry(kpSettingOpenImagesInSameWindow, false); + } else { d->configOpenImagesInSameWindow = false; #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tconfigOpenImagesInSameWindow: first time" - << " - writing default: " << d->configOpenImagesInSameWindow; + << " - writing default: " << d->configOpenImagesInSameWindow; #endif // TODO: More hidden options have to write themselves out on startup, // not on use, to be discoverable (e.g. printing centered on page). - cfg.writeEntry (kpSettingOpenImagesInSameWindow, - d->configOpenImagesInSameWindow); - cfg.sync (); + cfg.writeEntry(kpSettingOpenImagesInSameWindow, + d->configOpenImagesInSameWindow); + cfg.sync(); } - d->configPrintImageCenteredOnPage = cfg.readEntry (kpSettingPrintImageCenteredOnPage, true); - + d->configPrintImageCenteredOnPage = cfg.readEntry(kpSettingPrintImageCenteredOnPage, true); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tGeneral Settings: firstTime=" << d->configFirstTime - << " showGrid=" << d->configShowGrid - << " showPath=" << d->configShowPath - << " moreEffectsDialogLastEffect=" << d->moreEffectsDialogLastEffect - << " openImagesInSameWindow=" << d->configOpenImagesInSameWindow - << " printImageCenteredOnPage=" << d->configPrintImageCenteredOnPage; + << " showGrid=" << d->configShowGrid + << " showPath=" << d->configShowPath + << " moreEffectsDialogLastEffect=" << d->moreEffectsDialogLastEffect + << " openImagesInSameWindow=" << d->configOpenImagesInSameWindow + << " printImageCenteredOnPage=" << d->configPrintImageCenteredOnPage; #endif } //--------------------------------------------------------------------- // private -void kpMainWindow::readThumbnailSettings () +void kpMainWindow::readThumbnailSettings() { #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tkpMainWindow(" << objectName () << ")::readThumbnailSettings()"; + qCDebug(kpLogMainWindow) << "\tkpMainWindow(" << objectName() << ")::readThumbnailSettings()"; #endif - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupThumbnail); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupThumbnail); - d->configThumbnailShown = cfg.readEntry (kpSettingThumbnailShown, false); - d->configThumbnailGeometry = cfg.readEntry (kpSettingThumbnailGeometry, QRect ()); - d->configZoomedThumbnail = cfg.readEntry (kpSettingThumbnailZoomed, true); - d->configThumbnailShowRectangle = cfg.readEntry (kpSettingThumbnailShowRectangle, true); + d->configThumbnailShown = cfg.readEntry(kpSettingThumbnailShown, false); + d->configThumbnailGeometry = cfg.readEntry(kpSettingThumbnailGeometry, QRect()); + d->configZoomedThumbnail = cfg.readEntry(kpSettingThumbnailZoomed, true); + d->configThumbnailShowRectangle = cfg.readEntry(kpSettingThumbnailShowRectangle, true); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tThumbnail Settings: shown=" << d->configThumbnailShown - << " geometry=" << d->configThumbnailGeometry - << " zoomed=" << d->configZoomedThumbnail - << " showRectangle=" << d->configThumbnailShowRectangle; + << " geometry=" << d->configThumbnailGeometry + << " zoomed=" << d->configZoomedThumbnail + << " showRectangle=" << d->configThumbnailShowRectangle; #endif } //--------------------------------------------------------------------- void kpMainWindow::finalizeGUI(KXMLGUIClient *client) { - if ( client == this ) - { - const QList menuToHide = findChildren(QStringLiteral("toolToolBarHiddenMenu")); - // should only contain one but... - for (auto *menu : menuToHide) - { - menu->menuAction()->setVisible(false); + if (client == this) { + const QList menuToHide + = findChildren(QStringLiteral("toolToolBarHiddenMenu")); + // should only contain one but... + for (auto *menu : menuToHide) { + menu->menuAction()->setVisible(false); + } } - } } //--------------------------------------------------------------------- // private -void kpMainWindow::init () +void kpMainWindow::init() { #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "kpMainWindow(" << objectName () << ")::init()"; - QTime totalTime; totalTime.start (); + qCDebug(kpLogMainWindow) << "kpMainWindow(" << objectName() << ")::init()"; + QTime totalTime; + totalTime.start(); #endif d = new kpMainWindowPrivate; // // set mainwindow properties // - setMinimumSize (320, 260); - setAcceptDrops (true); + setMinimumSize(320, 260); + setAcceptDrops(true); // // read config // // KConfig::readEntry() does not actually reread from disk, hence doesn't // realize what other processes have done e.g. Settings / Show Path - KSharedConfig::openConfig ()->reparseConfiguration (); + KSharedConfig::openConfig()->reparseConfiguration(); - readGeneralSettings (); - readThumbnailSettings (); + readGeneralSettings(); + readThumbnailSettings(); // // create GUI // - setupActions (); - createStatusBar (); - createGUI (); - - createColorBox (); - createToolBox (); + setupActions(); + createStatusBar(); + createGUI(); + createColorBox(); + createToolBox(); // Let the Tool Box take all the vertical space, since it can be quite // tall with all its tool option widgets. This also avoids occasional @@ -235,143 +226,134 @@ addDockWidget(Qt::BottomDockWidgetArea, d->colorToolBar, Qt::Horizontal); - d->scrollView = new kpViewScrollableContainer (this); - d->scrollView->setObjectName ( QStringLiteral("scrollView" )); + d->scrollView = new kpViewScrollableContainer(this); + d->scrollView->setObjectName(QStringLiteral("scrollView")); - connect (d->scrollView, &kpViewScrollableContainer::beganDocResize, - this, &kpMainWindow::slotBeganDocResize); + connect(d->scrollView, &kpViewScrollableContainer::beganDocResize, + this, &kpMainWindow::slotBeganDocResize); - connect (d->scrollView, &kpViewScrollableContainer::continuedDocResize, - this, &kpMainWindow::slotContinuedDocResize); + connect(d->scrollView, &kpViewScrollableContainer::continuedDocResize, + this, &kpMainWindow::slotContinuedDocResize); - connect (d->scrollView, &kpViewScrollableContainer::cancelledDocResize, - this, &kpMainWindow::slotCancelledDocResize); + connect(d->scrollView, &kpViewScrollableContainer::cancelledDocResize, + this, &kpMainWindow::slotCancelledDocResize); - connect (d->scrollView, &kpViewScrollableContainer::endedDocResize, - this, &kpMainWindow::slotEndedDocResize); + connect(d->scrollView, &kpViewScrollableContainer::endedDocResize, + this, &kpMainWindow::slotEndedDocResize); - connect (d->scrollView, &kpViewScrollableContainer::statusMessageChanged, - this, &kpMainWindow::slotDocResizeMessageChanged); + connect(d->scrollView, &kpViewScrollableContainer::statusMessageChanged, + this, &kpMainWindow::slotDocResizeMessageChanged); - connect (d->scrollView, &kpViewScrollableContainer::contentsMoved, - this, &kpMainWindow::slotScrollViewAfterScroll); + connect(d->scrollView, &kpViewScrollableContainer::contentsMoved, + this, &kpMainWindow::slotScrollViewAfterScroll); - setCentralWidget (d->scrollView); + setCentralWidget(d->scrollView); // // set initial pos/size of GUI // - setAutoSaveSettings (); + setAutoSaveSettings(); // our non-XMLGUI tools-toolbar will get initially the toolButtonStyle as // all other toolbars, but we want to show only icons for the tools by default // (have to do this _after_ setAutoSaveSettings as that applies the default settings) - if (d->configFirstTime) - { - d->toolToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); + if (d->configFirstTime) { + d->toolToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); - KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); - cfg.writeEntry(kpSettingFirstTime, d->configFirstTime = false); - cfg.sync(); + cfg.writeEntry(kpSettingFirstTime, d->configFirstTime = false); + cfg.sync(); } - #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tall done in " << totalTime.elapsed () << "msec"; + qCDebug(kpLogMainWindow) << "\tall done in " << totalTime.elapsed() << "msec"; #endif } //--------------------------------------------------------------------- // private virtual [base KMainWindow] -void kpMainWindow::readProperties (const KConfigGroup &configGroup) +void kpMainWindow::readProperties(const KConfigGroup &configGroup) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow<" << this << ">::readProperties()"; #endif // No document at all? - if (!configGroup.hasKey (kpSessionSettingDocumentUrl)) - { + if (!configGroup.hasKey(kpSessionSettingDocumentUrl)) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tno url - no document"; #endif - setDocument (nullptr); + setDocument(nullptr); } // Have a document. - else - { - const QUrl url = QUrl (configGroup.readEntry (kpSessionSettingDocumentUrl, - QString ())); + else { + const QUrl url = QUrl(configGroup.readEntry(kpSessionSettingDocumentUrl, + QString())); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\turl=" << url; #endif - const QSize notFromURLDocSize = - configGroup.readEntry (kpSessionSettingNotFromUrlDocumentSize, - QSize ()); + const QSize notFromURLDocSize + = configGroup.readEntry(kpSessionSettingNotFromUrlDocumentSize, + QSize()); // Is from URL? - if (notFromURLDocSize.isEmpty ()) - { + if (notFromURLDocSize.isEmpty()) { // If this fails, the empty document that kpMainWindow::kpMainWindow() // created is left untouched. - openInternal (url, defaultDocSize (), - false/*show error message if url !exist*/); + openInternal(url, defaultDocSize(), + false /*show error message if url !exist*/); } // Not from URL? - else - { + else { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tnot from url; doc size=" << notFromURLDocSize; #endif // Either we have an empty URL or we have a "kolourpaint doesnotexist.png" // URL. Regarding the latter case, if a file now actually exists at that // URL, we do open it - ignoring notFromURLDocSize - to avoid putting // the user in a situation where he might accidentally overwrite an // existing file. - openInternal (url, notFromURLDocSize, - true/*create an empty doc with the same url if url !exist*/); + openInternal(url, notFromURLDocSize, + true /*create an empty doc with the same url if url !exist*/); } } - } //--------------------------------------------------------------------- // private virtual [base KMainWindow] // WARNING: KMainWindow API Doc says "No user interaction is allowed // in this function!" -void kpMainWindow::saveProperties (KConfigGroup &configGroup) +void kpMainWindow::saveProperties(KConfigGroup &configGroup) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow<" << this << ">::saveProperties()"; #endif // No document at all? - if (!d->document) - { + if (!d->document) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tno url - no document"; #endif } // Have a document. - else - { + else { // Save URL in all cases: // // a) d->document->isFromURL() // b) !d->document->isFromURL() [save size in this case] // i) No URL // ii) URL (from "kolourpaint doesnotexist.png") - const QUrl url = d->document->url (); + const QUrl url = d->document->url(); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\turl=" << url; #endif - configGroup.writeEntry (kpSessionSettingDocumentUrl, url.url ()); + configGroup.writeEntry(kpSessionSettingDocumentUrl, url.url()); // Not from URL e.g. "kolourpaint doesnotexist.png"? // @@ -381,162 +363,161 @@ // it to be from a URL, so when we session restore, we pop up a // "cannot find file" dialog, instead of silently creating a new, // blank document. - if (!d->document->isFromURL (false/*don't bother checking exists*/)) - { + if (!d->document->isFromURL(false /*don't bother checking exists*/)) { // If we don't have a URL either: // // a) it was not modified - so we can use either width() or // constructorWidth() (they'll be equal). // b) the changes were discarded so we use the initial width, // constructorWidth(). // // Similarly for height() and constructorHeight(). - const QSize docSize (d->document->constructorWidth (), - d->document->constructorHeight ()); + const QSize docSize(d->document->constructorWidth(), + d->document->constructorHeight()); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tnot from url; doc size=" << docSize; #endif - configGroup.writeEntry (kpSessionSettingNotFromUrlDocumentSize, docSize); + configGroup.writeEntry(kpSessionSettingNotFromUrlDocumentSize, docSize); } } } //--------------------------------------------------------------------- - kpMainWindow::~kpMainWindow () { d->isFullyConstructed = false; // Get the kpTool to finish up. This makes sure that the kpTool destructor // will not need to access any other class (that might be deleted before // the destructor is called by the QObject child-deletion mechanism). - if (tool ()) { - tool ()->endInternal (); + if (tool()) { + tool()->endInternal(); } // Delete document & views. // Note: This will disconnects signals from the current kpTool, so kpTool // must not be destructed yet. - setDocument (nullptr); + setDocument(nullptr); - delete d->commandHistory; d->commandHistory = nullptr; - delete d->scrollView; d->scrollView = nullptr; + delete d->commandHistory; + d->commandHistory = nullptr; + delete d->scrollView; + d->scrollView = nullptr; - delete d; d = nullptr; + delete d; + d = nullptr; } //--------------------------------------------------------------------- - // public -kpDocument *kpMainWindow::document () const +kpDocument *kpMainWindow::document() const { return d->document; } //--------------------------------------------------------------------- // public -kpDocumentEnvironment *kpMainWindow::documentEnvironment () +kpDocumentEnvironment *kpMainWindow::documentEnvironment() { if (!d->documentEnvironment) { - d->documentEnvironment = new kpDocumentEnvironment (this); + d->documentEnvironment = new kpDocumentEnvironment(this); } return d->documentEnvironment; } //--------------------------------------------------------------------- // public -kpViewManager *kpMainWindow::viewManager () const +kpViewManager *kpMainWindow::viewManager() const { return d->viewManager; } //--------------------------------------------------------------------- // public -kpColorToolBar *kpMainWindow::colorToolBar () const +kpColorToolBar *kpMainWindow::colorToolBar() const { return d->colorToolBar; } //--------------------------------------------------------------------- // public -kpColorCells *kpMainWindow::colorCells () const +kpColorCells *kpMainWindow::colorCells() const { - return d->colorToolBar ? d->colorToolBar->colorCells () : nullptr; + return d->colorToolBar ? d->colorToolBar->colorCells() : nullptr; } //--------------------------------------------------------------------- // public -kpToolToolBar *kpMainWindow::toolToolBar () const +kpToolToolBar *kpMainWindow::toolToolBar() const { return d->toolToolBar; } //--------------------------------------------------------------------- // public -kpCommandHistory *kpMainWindow::commandHistory () const +kpCommandHistory *kpMainWindow::commandHistory() const { return d->commandHistory; } //--------------------------------------------------------------------- -kpCommandEnvironment *kpMainWindow::commandEnvironment () +kpCommandEnvironment *kpMainWindow::commandEnvironment() { if (!d->commandEnvironment) { - d->commandEnvironment = new kpCommandEnvironment (this); + d->commandEnvironment = new kpCommandEnvironment(this); } return d->commandEnvironment; } //--------------------------------------------------------------------- // private -void kpMainWindow::setupActions () +void kpMainWindow::setupActions() { - setupFileMenuActions (); - setupEditMenuActions (); - setupViewMenuActions (); - setupImageMenuActions (); - setupColorsMenuActions (); - setupSettingsMenuActions (); - - setupTextToolBarActions (); - setupToolActions (); + setupFileMenuActions(); + setupEditMenuActions(); + setupViewMenuActions(); + setupImageMenuActions(); + setupColorsMenuActions(); + setupSettingsMenuActions(); + + setupTextToolBarActions(); + setupToolActions(); } //--------------------------------------------------------------------- // private -void kpMainWindow::enableDocumentActions (bool enable) +void kpMainWindow::enableDocumentActions(bool enable) { - enableFileMenuDocumentActions (enable); - enableEditMenuDocumentActions (enable); - enableViewMenuDocumentActions (enable); - enableImageMenuDocumentActions (enable); - enableColorsMenuDocumentActions (enable); - enableSettingsMenuDocumentActions (enable); + enableFileMenuDocumentActions(enable); + enableEditMenuDocumentActions(enable); + enableViewMenuDocumentActions(enable); + enableImageMenuDocumentActions(enable); + enableColorsMenuDocumentActions(enable); + enableSettingsMenuDocumentActions(enable); } //--------------------------------------------------------------------- // private -void kpMainWindow::setDocument (kpDocument *newDoc) +void kpMainWindow::setDocument(kpDocument *newDoc) { //qCDebug(kpLogMainWindow) << newDoc; // is it a close operation? - if (!newDoc) - { + if (!newDoc) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tdisabling actions"; #endif @@ -550,34 +531,35 @@ // We just have to make sure that signals from the Color // Box aren't fired and received unexpectedly when there's // no document. - Q_ASSERT (d->colorToolBar); - d->colorToolBar->setEnabled (false); + Q_ASSERT(d->colorToolBar); + d->colorToolBar->setEnabled(false); - enableTextToolBarActions (false); + enableTextToolBarActions(false); } // Always disable the tools. // If we decide to open a new document/mainView we want // kpTool::begin() to be called again e.g. in case it sets the cursor. // kpViewManager won't do this because we nuke it to avoid stale state. - enableToolsDocumentActions (false); + enableToolsDocumentActions(false); - if (!newDoc) - { - enableDocumentActions (false); + if (!newDoc) { + enableDocumentActions(false); } - delete d->mainView; d->mainView = nullptr; - slotDestroyThumbnail (); + delete d->mainView; + d->mainView = nullptr; + slotDestroyThumbnail(); // viewManager will die and so will the selection - d->actionCopy->setEnabled (false); - d->actionCut->setEnabled (false); - d->actionDelete->setEnabled (false); - d->actionDeselect->setEnabled (false); - d->actionCopyToFile->setEnabled (false); + d->actionCopy->setEnabled(false); + d->actionCut->setEnabled(false); + d->actionDelete->setEnabled(false); + d->actionDeselect->setEnabled(false); + d->actionCopyToFile->setEnabled(false); - delete d->viewManager; d->viewManager = nullptr; + delete d->viewManager; + d->viewManager = nullptr; #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tdestroying document"; @@ -587,153 +569,147 @@ delete d->document; d->document = newDoc; - - if (!d->lastCopyToURL.isEmpty ()) - { + if (!d->lastCopyToURL.isEmpty()) { // remove file name from path - QString path = d->lastCopyToURL.path (); - path = path.left (path.lastIndexOf (QLatin1Char ('/')) + 1); - d->lastCopyToURL.setPath (path); + QString path = d->lastCopyToURL.path(); + path = path.left(path.lastIndexOf(QLatin1Char('/')) + 1); + d->lastCopyToURL.setPath(path); } d->copyToFirstTime = true; - if (!d->lastExportURL.isEmpty ()) - { - QString path = d->lastExportURL.path (); - path = path.left (path.lastIndexOf (QLatin1Char ('/')) + 1); - d->lastExportURL.setPath (path); + if (!d->lastExportURL.isEmpty()) { + QString path = d->lastExportURL.path(); + path = path.left(path.lastIndexOf(QLatin1Char('/')) + 1); + d->lastExportURL.setPath(path); } d->exportFirstTime = true; - // not a close operation? - if (d->document) - { + if (d->document) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\treparenting doc that may have been created into a" - << " different mainWindiow"; + << " different mainWindiow"; #endif - d->document->setEnviron (documentEnvironment ()); + d->document->setEnviron(documentEnvironment()); - d->viewManager = new kpViewManager (this); + d->viewManager = new kpViewManager(this); - d->mainView = new kpZoomedView (d->document, d->toolToolBar, d->viewManager, - nullptr/*buddyView*/, + d->mainView = new kpZoomedView(d->document, d->toolToolBar, d->viewManager, + nullptr /*buddyView*/, d->scrollView, - d->scrollView->viewport ()); - d->mainView->setObjectName ( QStringLiteral("mainView" )); + d->scrollView->viewport()); + d->mainView->setObjectName(QStringLiteral("mainView")); - d->viewManager->registerView (d->mainView); - d->scrollView->setView (d->mainView); - d->mainView->show (); + d->viewManager->registerView(d->mainView); + d->scrollView->setView(d->mainView); + d->mainView->show(); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\thooking up document signals"; #endif // Copy/Cut/Deselect/Delete - connect (d->document, &kpDocument::selectionEnabled, - d->actionCut, &QAction::setEnabled); + connect(d->document, &kpDocument::selectionEnabled, + d->actionCut, &QAction::setEnabled); - connect (d->document, &kpDocument::selectionEnabled, - d->actionCopy, &QAction::setEnabled); + connect(d->document, &kpDocument::selectionEnabled, + d->actionCopy, &QAction::setEnabled); - connect (d->document, &kpDocument::selectionEnabled, - d->actionDelete, &QAction::setEnabled); + connect(d->document, &kpDocument::selectionEnabled, + d->actionDelete, &QAction::setEnabled); - connect (d->document, &kpDocument::selectionEnabled, - d->actionDeselect, &QAction::setEnabled); + connect(d->document, &kpDocument::selectionEnabled, + d->actionDeselect, &QAction::setEnabled); - connect (d->document, &kpDocument::selectionEnabled, - d->actionCopyToFile, &QAction::setEnabled); + connect(d->document, &kpDocument::selectionEnabled, + d->actionCopyToFile, &QAction::setEnabled); // this code won't actually enable any actions at this stage // (fresh document) but better safe than sorry - d->actionCopy->setEnabled (d->document->selection ()); - d->actionCut->setEnabled (d->document->selection ()); - d->actionDeselect->setEnabled (d->document->selection ()); - d->actionDelete->setEnabled (d->document->selection ()); - d->actionCopyToFile->setEnabled (d->document->selection ()); + d->actionCopy->setEnabled(d->document->selection()); + d->actionCut->setEnabled(d->document->selection()); + d->actionDeselect->setEnabled(d->document->selection()); + d->actionDelete->setEnabled(d->document->selection()); + d->actionCopyToFile->setEnabled(d->document->selection()); - connect (d->document, &kpDocument::selectionEnabled, - this, &kpMainWindow::slotImageMenuUpdateDueToSelection); + connect(d->document, &kpDocument::selectionEnabled, + this, &kpMainWindow::slotImageMenuUpdateDueToSelection); - connect (d->document, &kpDocument::selectionIsTextChanged, - this, &kpMainWindow::slotImageMenuUpdateDueToSelection); + connect(d->document, &kpDocument::selectionIsTextChanged, + this, &kpMainWindow::slotImageMenuUpdateDueToSelection); // Status bar - connect (d->document, &kpDocument::documentOpened, - this, &kpMainWindow::recalculateStatusBar); + connect(d->document, &kpDocument::documentOpened, + this, &kpMainWindow::recalculateStatusBar); - connect (d->document, SIGNAL (sizeChanged(QSize)), - this, SLOT (setStatusBarDocSize(QSize))); + connect(d->document, SIGNAL(sizeChanged(QSize)), + this, SLOT(setStatusBarDocSize(QSize))); // Caption (url, modified) - connect (d->document, &kpDocument::documentModified, - this, &kpMainWindow::slotUpdateCaption); + connect(d->document, &kpDocument::documentModified, + this, &kpMainWindow::slotUpdateCaption); - connect (d->document, &kpDocument::documentOpened, - this, &kpMainWindow::slotUpdateCaption); + connect(d->document, &kpDocument::documentOpened, + this, &kpMainWindow::slotUpdateCaption); - connect (d->document, &kpDocument::documentSaved, - this, &kpMainWindow::slotUpdateCaption); + connect(d->document, &kpDocument::documentSaved, + this, &kpMainWindow::slotUpdateCaption); // File/Reload action only available with non-empty URL - connect (d->document, &kpDocument::documentSaved, - this, &kpMainWindow::slotEnableReload); + connect(d->document, &kpDocument::documentSaved, + this, &kpMainWindow::slotEnableReload); - connect (d->document, &kpDocument::documentSaved, - this, &kpMainWindow::slotEnableSettingsShowPath); + connect(d->document, &kpDocument::documentSaved, + this, &kpMainWindow::slotEnableSettingsShowPath); // Command history - Q_ASSERT (d->commandHistory); - connect (d->commandHistory, &kpCommandHistory::documentRestored, - this, &kpMainWindow::slotDocumentRestored); // caption "!modified" + Q_ASSERT(d->commandHistory); + connect(d->commandHistory, &kpCommandHistory::documentRestored, + this, &kpMainWindow::slotDocumentRestored); // caption "!modified" - connect (d->document, &kpDocument::documentSaved, - d->commandHistory, &kpCommandHistory::documentSaved); + connect(d->document, &kpDocument::documentSaved, + d->commandHistory, &kpCommandHistory::documentSaved); // Sync document -> views - connect (d->document, &kpDocument::contentsChanged, - d->viewManager, &kpViewManager::updateViews); + connect(d->document, &kpDocument::contentsChanged, + d->viewManager, &kpViewManager::updateViews); - connect (d->document, static_cast(&kpDocument::sizeChanged), - d->viewManager, &kpViewManager::adjustViewsToEnvironment); + connect(d->document, static_cast(&kpDocument::sizeChanged), + d->viewManager, &kpViewManager::adjustViewsToEnvironment); - connect (d->document, - static_cast(&kpDocument::sizeChanged), - d->viewManager, &kpViewManager::adjustViewsToEnvironment); + connect(d->document, + static_cast(&kpDocument::sizeChanged), + d->viewManager, &kpViewManager::adjustViewsToEnvironment); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tenabling actions"; #endif // sync with the bit marked "sync" above - Q_ASSERT (d->colorToolBar); - d->colorToolBar->setEnabled (true); - + Q_ASSERT(d->colorToolBar); + d->colorToolBar->setEnabled(true); // Hide the text toolbar - it will be shown by kpToolText::begin() - enableTextToolBarActions (false); + enableTextToolBarActions(false); - enableToolsDocumentActions (true); + enableToolsDocumentActions(true); - enableDocumentActions (true); + enableDocumentActions(true); } #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tupdating mainWindow elements"; #endif - slotImageMenuUpdateDueToSelection (); - recalculateStatusBar (); - slotUpdateCaption (); // Untitled to start with - slotEnableReload (); - slotEnableSettingsShowPath (); + slotImageMenuUpdateDueToSelection(); + recalculateStatusBar(); + slotUpdateCaption(); // Untitled to start with + slotEnableReload(); + slotEnableSettingsShowPath(); if (d->commandHistory) { - d->commandHistory->clear (); + d->commandHistory->clear(); } #if DEBUG_KP_MAIN_WINDOW @@ -744,114 +720,103 @@ //--------------------------------------------------------------------- // private virtual [base QWidget] -void kpMainWindow::dragEnterEvent (QDragEnterEvent *e) +void kpMainWindow::dragEnterEvent(QDragEnterEvent *e) { // It's faster to test for QMimeData::hasText() first due to the // lazy evaluation of the '||' operator. - e->setAccepted (e->mimeData ()->hasText () || - e->mimeData ()->hasUrls () || - kpSelectionDrag::canDecode (e->mimeData ())); + e->setAccepted(e->mimeData()->hasText() + || e->mimeData()->hasUrls() + || kpSelectionDrag::canDecode(e->mimeData())); } //--------------------------------------------------------------------- // private virtual [base QWidget] -void kpMainWindow::dropEvent (QDropEvent *e) +void kpMainWindow::dropEvent(QDropEvent *e) { #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "kpMainWindow::dropEvent" << e->pos (); + qCDebug(kpLogMainWindow) << "kpMainWindow::dropEvent" << e->pos(); #endif QList urls; - kpAbstractImageSelection *sel = kpSelectionDrag::decode (e->mimeData ()); - if (sel) - { + kpAbstractImageSelection *sel = kpSelectionDrag::decode(e->mimeData()); + if (sel) { // TODO: How do you actually drop a selection or ordinary images on // the clipboard)? Will this code path _ever_ execute? - sel->setTransparency (imageSelectionTransparency ()); + sel->setTransparency(imageSelectionTransparency()); // TODO: drop at point like with QTextDrag below? - paste (*sel); + paste(*sel); delete sel; - } - else if (!(urls = e->mimeData ()->urls ()).isEmpty ()) - { + } else if (!(urls = e->mimeData()->urls()).isEmpty()) { // LOTODO: kpSetOverrideCursorSaver cursorSaver (Qt::waitCursor); // // However, you would need to prefix all possible error/warning // dialogs that might be called, with Qt::arrowCursor e.g. in // kpDocument and probably a lot more places. - for (const auto &u : urls) - open (u); - } - else if (e->mimeData ()->hasText ()) - { - const QString text = e->mimeData ()->text (); + for (const auto &u : urls) { + open(u); + } + } else if (e->mimeData()->hasText()) { + const QString text = e->mimeData()->text(); QPoint selTopLeft = KP_INVALID_POINT; - const QPoint globalPos = QWidget::mapToGlobal (e->pos ()); + const QPoint globalPos = QWidget::mapToGlobal(e->pos()); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tpos toGlobal=" << globalPos; #endif kpView *view = nullptr; - if (d->viewManager) - { - view = d->viewManager->viewUnderCursor (); + if (d->viewManager) { + view = d->viewManager->viewUnderCursor(); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tviewUnderCursor=" << view; #endif - if (!view) - { + if (!view) { // HACK: see kpViewManager::setViewUnderCursor() to see why // it's not reliable #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tattempting to discover view"; - if (d->mainView && d->scrollView) - { + if (d->mainView && d->scrollView) { qCDebug(kpLogMainWindow) << "\t\t\tmainView->globalRect=" - << kpWidgetMapper::toGlobal (d->mainView, d->mainView->rect ()) - << " scrollView->globalRect=" - << kpWidgetMapper::toGlobal (d->scrollView, - QRect (0, 0, - d->scrollView->viewport()->width (), - d->scrollView->viewport()->height ())); + << kpWidgetMapper::toGlobal(d->mainView, + d->mainView->rect()) + << " scrollView->globalRect=" + << kpWidgetMapper::toGlobal(d->scrollView, + QRect(0, 0, + d->scrollView->viewport()->width(), + d->scrollView->viewport()->height())); } #endif - if (d->thumbnailView && - kpWidgetMapper::toGlobal (d->thumbnailView, d->thumbnailView->rect ()) - .contains (globalPos)) - { + if (d->thumbnailView + && kpWidgetMapper::toGlobal(d->thumbnailView, d->thumbnailView->rect()) + .contains(globalPos)) { // TODO: Code will never get executed. // Thumbnail doesn't accept drops. view = d->thumbnailView; - } - else if (d->mainView && - kpWidgetMapper::toGlobal (d->mainView, d->mainView->rect ()) - .contains (globalPos) && - d->scrollView && - kpWidgetMapper::toGlobal (d->scrollView, - QRect (0, 0, - d->scrollView->viewport()->width (), - d->scrollView->viewport()->height ())) - .contains (globalPos)) - { + } else if (d->mainView + && kpWidgetMapper::toGlobal(d->mainView, d->mainView->rect()) + .contains(globalPos) + && d->scrollView + && kpWidgetMapper::toGlobal(d->scrollView, + QRect(0, 0, + d->scrollView->viewport()->width(), + d->scrollView->viewport()->height())) + .contains(globalPos)) { view = d->mainView; } } } - if (view) - { - const QPoint viewPos = view->mapFromGlobal (globalPos); - const QPoint docPoint = view->transformViewToDoc (viewPos); + if (view) { + const QPoint viewPos = view->mapFromGlobal(globalPos); + const QPoint docPoint = view->transformViewToDoc(viewPos); // viewUnderCursor() is hacky and can return a view when we aren't // over one thanks to drags. - if (d->document && d->document->rect ().contains (docPoint)) - { + if (d->document && d->document->rect().contains(docPoint)) { selTopLeft = docPoint; // TODO: In terms of doc pixels, would be inconsistent behaviour @@ -861,65 +826,59 @@ } } - pasteText (text, true/*force new text selection*/, selTopLeft); + pasteText(text, true /*force new text selection*/, selTopLeft); } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotScrollViewAfterScroll () +void kpMainWindow::slotScrollViewAfterScroll() { // OPT: Why can't this be moved into kpViewScrollableContainer::slotDragScroll(), // grouping all drag-scroll-related repaints, which would potentially avoid // double repainting? - if (tool ()) - { - tool ()->somethingBelowTheCursorChanged (); + if (tool()) { + tool()->somethingBelowTheCursorChanged(); } } //--------------------------------------------------------------------- // private virtual [base QWidget] -void kpMainWindow::moveEvent (QMoveEvent * /*e*/) +void kpMainWindow::moveEvent(QMoveEvent * /*e*/) { - if (d->thumbnail) - { + if (d->thumbnail) { // Disabled because it lags too far behind the mainWindow // d->thumbnail->move (d->thumbnail->pos () + (e->pos () - e->oldPos ())); - notifyThumbnailGeometryChanged (); + notifyThumbnailGeometryChanged(); } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotUpdateCaption () +void kpMainWindow::slotUpdateCaption() { - if (d->document) - { - setCaption (d->configShowPath ? d->document->prettyUrl () - : d->document->prettyFilename (), - d->document->isModified ()); - } - else - { - setCaption (QString(), false); + if (d->document) { + setCaption(d->configShowPath ? d->document->prettyUrl() + : d->document->prettyFilename(), + d->document->isModified()); + } else { + setCaption(QString(), false); } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotDocumentRestored () +void kpMainWindow::slotDocumentRestored() { if (d->document) { - d->document->setModified (false); + d->document->setModified(false); } - slotUpdateCaption (); + slotUpdateCaption(); } //--------------------------------------------------------------------- - diff --git a/mainWindow/kpMainWindowPrivate.h b/mainWindow/kpMainWindowPrivate.h --- a/mainWindow/kpMainWindowPrivate.h +++ b/mainWindow/kpMainWindowPrivate.h @@ -25,17 +25,13 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpMainWindowPrivate_H #define kpMainWindowPrivate_H - #define DEBUG_KP_MAIN_WINDOW 0 - #include "document/kpDocumentSaveOptions.h" - class QAction; class QActionGroup; class QLabel; @@ -64,382 +60,352 @@ class kpToolText; class SaneDialog; - struct kpMainWindowPrivate { - kpMainWindowPrivate () - : isFullyConstructed(false), - scrollView(nullptr), - mainView(nullptr), - thumbnail(nullptr), - thumbnailView(nullptr), - document(nullptr), - viewManager(nullptr), - colorToolBar(nullptr), - toolToolBar(nullptr), - commandHistory(nullptr), - - configFirstTime(false), - configShowGrid(false), - configShowPath(false), - configThumbnailShown(false), - configZoomedThumbnail(false), - - documentEnvironment(nullptr), - commandEnvironment(nullptr), - - // Tools - - toolSelectionEnvironment(nullptr), - toolsActionGroup(nullptr), - - toolSpraycan(nullptr), - toolBrush(nullptr), - toolColorEraser(nullptr), - toolColorPicker(nullptr), - toolCurve(nullptr), - toolEllipse(nullptr), - toolEllipticalSelection(nullptr), - toolEraser(nullptr), - toolFloodFill(nullptr), - toolFreeFormSelection(nullptr), - toolLine(nullptr), - toolPen(nullptr), - toolPolygon(nullptr), - toolPolyline(nullptr), - toolRectangle(nullptr), - toolRectSelection(nullptr), - toolRoundedRectangle(nullptr), - toolZoom(nullptr), - toolText(nullptr), - - lastToolNumber(0), - toolActionsEnabled(false), - actionPrevToolOptionGroup1(nullptr), - actionNextToolOptionGroup1(nullptr), - actionPrevToolOptionGroup2(nullptr), - actionNextToolOptionGroup2(nullptr), - - settingImageSelectionTransparency(0), - - docResizeWidth(0), - docResizeHeight(0), - docResizeToBeCompleted(false), - - configOpenImagesInSameWindow(false), - configPrintImageCenteredOnPage(false), - - actionNew(nullptr), - actionOpen(nullptr), - actionOpenRecent(nullptr), - actionScan(nullptr), - actionScreenshot(nullptr), - actionProperties(nullptr), - actionSave(nullptr), - actionSaveAs(nullptr), - actionExport(nullptr), - actionReload(nullptr), - actionPrint(nullptr), - actionPrintPreview(nullptr), - actionMail(nullptr), - actionClose(nullptr), - actionQuit(nullptr), - - scanDialog(nullptr), - - exportFirstTime(false), - - // Edit Menu - - editMenuDocumentActionsEnabled(false), - - actionUndo(nullptr), - actionRedo(nullptr), - actionCut(nullptr), - actionCopy(nullptr), - actionPaste(nullptr), - actionPasteInNewWindow(nullptr), - actionDelete(nullptr), - actionSelectAll(nullptr), - actionDeselect(nullptr), - actionCopyToFile(nullptr), - actionPasteFromFile(nullptr), - - copyToFirstTime(false), - - // View Menu - - configThumbnailShowRectangle(false), - actionShowThumbnailRectangle(nullptr), - - viewMenuDocumentActionsEnabled(false), - - actionActualSize(nullptr), - actionFitToPage(nullptr), - actionFitToWidth(nullptr), - actionFitToHeight(nullptr), - actionZoomIn(nullptr), - actionZoomOut(nullptr), - actionZoom(nullptr), - actionShowGrid(nullptr), - actionShowThumbnail(nullptr), - actionZoomedThumbnail(nullptr), - - thumbnailSaveConfigTimer(nullptr), - - // Image Menu - - transformDialogEnvironment(nullptr), - - imageMenuDocumentActionsEnabled(false), - - actionResizeScale(nullptr), - actionCrop(nullptr), - actionAutoCrop(nullptr), - actionFlip(nullptr), - actionMirror(nullptr), - actionRotate(nullptr), - actionRotateLeft(nullptr), - actionRotateRight(nullptr), - actionSkew(nullptr), - actionConvertToBlackAndWhite(nullptr), - actionConvertToGrayscale(nullptr), - actionBlur(nullptr), - actionMoreEffects(nullptr), - actionInvertColors(nullptr), - actionClear(nullptr), - - actionDrawOpaque(nullptr), - actionDrawColorSimilarity(nullptr), - - moreEffectsDialogLastEffect(0), - - // Colors Menu - - colorMenuDocumentActionsEnabled(false), - - actionColorsDefault(nullptr), - actionColorsKDE(nullptr), - actionColorsOpen(nullptr), - actionColorsReload(nullptr), - actionColorsSave(nullptr), - actionColorsSaveAs(nullptr), - actionColorsAppendRow(nullptr), - actionColorsDeleteRow(nullptr), - - // Settings Menu - - actionShowPath(nullptr), - actionKeyBindings(nullptr), - actionConfigureToolbars(nullptr), - actionConfigure(nullptr), - actionFullScreen(nullptr), - - // Status Bar - - statusBarCreated(false), - statusBarMessageLabel(nullptr), - statusBarShapeLastPointsInitialised(false), - statusBarShapeLastSizeInitialised(false), - - // Text ToolBar - - actionTextFontFamily(nullptr), - actionTextFontSize(nullptr), - actionTextBold(nullptr), - actionTextItalic(nullptr), - actionTextUnderline(nullptr), - actionTextStrikeThru(nullptr), - settingTextStyle(0), - textOldFontSize(0) - { - } - - bool isFullyConstructed; - - kpViewScrollableContainer *scrollView; - kpZoomedView *mainView; - kpThumbnail *thumbnail; - kpThumbnailView *thumbnailView; - kpDocument *document; - kpViewManager *viewManager; - kpColorToolBar *colorToolBar; - kpToolToolBar *toolToolBar; - kpCommandHistory *commandHistory; - - bool configFirstTime; - bool configShowGrid; - bool configShowPath; - - bool configThumbnailShown; - QRect configThumbnailGeometry; - bool configZoomedThumbnail; - - kpDocumentEnvironment *documentEnvironment; - kpCommandEnvironment *commandEnvironment; - - // - // Tools - // - - kpToolSelectionEnvironment *toolSelectionEnvironment; - QActionGroup *toolsActionGroup; - - kpTool *toolSpraycan, *toolBrush, - *toolColorEraser, *toolColorPicker, - *toolCurve, *toolEllipse, - *toolEllipticalSelection, *toolEraser, - *toolFloodFill, *toolFreeFormSelection, - *toolLine, *toolPen, *toolPolygon, - *toolPolyline, *toolRectangle, *toolRectSelection, - *toolRoundedRectangle, *toolZoom; - kpToolText *toolText; - - QList tools; - int lastToolNumber; - - bool toolActionsEnabled; - QAction *actionPrevToolOptionGroup1, - *actionNextToolOptionGroup1, - *actionPrevToolOptionGroup2, - *actionNextToolOptionGroup2; - - int settingImageSelectionTransparency; - - int docResizeWidth, docResizeHeight; - bool docResizeToBeCompleted; + kpMainWindowPrivate () + : isFullyConstructed(false) + , scrollView(nullptr) + , mainView(nullptr) + , thumbnail(nullptr) + , thumbnailView(nullptr) + , document(nullptr) + , viewManager(nullptr) + , colorToolBar(nullptr) + , toolToolBar(nullptr) + , commandHistory(nullptr) + , configFirstTime(false) + , configShowGrid(false) + , configShowPath(false) + , configThumbnailShown(false) + , configZoomedThumbnail(false) + , documentEnvironment(nullptr) + , commandEnvironment(nullptr) + ,// Tools + + toolSelectionEnvironment(nullptr) + , toolsActionGroup(nullptr) + , toolSpraycan(nullptr) + , toolBrush(nullptr) + , toolColorEraser(nullptr) + , toolColorPicker(nullptr) + , toolCurve(nullptr) + , toolEllipse(nullptr) + , toolEllipticalSelection(nullptr) + , toolEraser(nullptr) + , toolFloodFill(nullptr) + , toolFreeFormSelection(nullptr) + , toolLine(nullptr) + , toolPen(nullptr) + , toolPolygon(nullptr) + , toolPolyline(nullptr) + , toolRectangle(nullptr) + , toolRectSelection(nullptr) + , toolRoundedRectangle(nullptr) + , toolZoom(nullptr) + , toolText(nullptr) + , lastToolNumber(0) + , toolActionsEnabled(false) + , actionPrevToolOptionGroup1(nullptr) + , actionNextToolOptionGroup1(nullptr) + , actionPrevToolOptionGroup2(nullptr) + , actionNextToolOptionGroup2(nullptr) + , settingImageSelectionTransparency(0) + , docResizeWidth(0) + , docResizeHeight(0) + , docResizeToBeCompleted(false) + , configOpenImagesInSameWindow(false) + , configPrintImageCenteredOnPage(false) + , actionNew(nullptr) + , actionOpen(nullptr) + , actionOpenRecent(nullptr) + , actionScan(nullptr) + , actionScreenshot(nullptr) + , actionProperties(nullptr) + , actionSave(nullptr) + , actionSaveAs(nullptr) + , actionExport(nullptr) + , actionReload(nullptr) + , actionPrint(nullptr) + , actionPrintPreview(nullptr) + , actionMail(nullptr) + , actionClose(nullptr) + , actionQuit(nullptr) + , scanDialog(nullptr) + , exportFirstTime(false) + ,// Edit Menu + + editMenuDocumentActionsEnabled(false) + , actionUndo(nullptr) + , actionRedo(nullptr) + , actionCut(nullptr) + , actionCopy(nullptr) + , actionPaste(nullptr) + , actionPasteInNewWindow(nullptr) + , actionDelete(nullptr) + , actionSelectAll(nullptr) + , actionDeselect(nullptr) + , actionCopyToFile(nullptr) + , actionPasteFromFile(nullptr) + , copyToFirstTime(false) + ,// View Menu + + configThumbnailShowRectangle(false) + , actionShowThumbnailRectangle(nullptr) + , viewMenuDocumentActionsEnabled(false) + , actionActualSize(nullptr) + , actionFitToPage(nullptr) + , actionFitToWidth(nullptr) + , actionFitToHeight(nullptr) + , actionZoomIn(nullptr) + , actionZoomOut(nullptr) + , actionZoom(nullptr) + , actionShowGrid(nullptr) + , actionShowThumbnail(nullptr) + , actionZoomedThumbnail(nullptr) + , thumbnailSaveConfigTimer(nullptr) + ,// Image Menu + + transformDialogEnvironment(nullptr) + , imageMenuDocumentActionsEnabled(false) + , actionResizeScale(nullptr) + , actionCrop(nullptr) + , actionAutoCrop(nullptr) + , actionFlip(nullptr) + , actionMirror(nullptr) + , actionRotate(nullptr) + , actionRotateLeft(nullptr) + , actionRotateRight(nullptr) + , actionSkew(nullptr) + , actionConvertToBlackAndWhite(nullptr) + , actionConvertToGrayscale(nullptr) + , actionBlur(nullptr) + , actionMoreEffects(nullptr) + , actionInvertColors(nullptr) + , actionClear(nullptr) + , actionDrawOpaque(nullptr) + , actionDrawColorSimilarity(nullptr) + , moreEffectsDialogLastEffect(0) + ,// Colors Menu + + colorMenuDocumentActionsEnabled(false) + , actionColorsDefault(nullptr) + , actionColorsKDE(nullptr) + , actionColorsOpen(nullptr) + , actionColorsReload(nullptr) + , actionColorsSave(nullptr) + , actionColorsSaveAs(nullptr) + , actionColorsAppendRow(nullptr) + , actionColorsDeleteRow(nullptr) + ,// Settings Menu + + actionShowPath(nullptr) + , actionKeyBindings(nullptr) + , actionConfigureToolbars(nullptr) + , actionConfigure(nullptr) + , actionFullScreen(nullptr) + ,// Status Bar + + statusBarCreated(false) + , statusBarMessageLabel(nullptr) + , statusBarShapeLastPointsInitialised(false) + , statusBarShapeLastSizeInitialised(false) + ,// Text ToolBar + + actionTextFontFamily(nullptr) + , actionTextFontSize(nullptr) + , actionTextBold(nullptr) + , actionTextItalic(nullptr) + , actionTextUnderline(nullptr) + , actionTextStrikeThru(nullptr) + , settingTextStyle(0) + , textOldFontSize(0) + { + } + + bool isFullyConstructed; + + kpViewScrollableContainer *scrollView; + kpZoomedView *mainView; + kpThumbnail *thumbnail; + kpThumbnailView *thumbnailView; + kpDocument *document; + kpViewManager *viewManager; + kpColorToolBar *colorToolBar; + kpToolToolBar *toolToolBar; + kpCommandHistory *commandHistory; + + bool configFirstTime; + bool configShowGrid; + bool configShowPath; + + bool configThumbnailShown; + QRect configThumbnailGeometry; + bool configZoomedThumbnail; + + kpDocumentEnvironment *documentEnvironment; + kpCommandEnvironment *commandEnvironment; + + // + // Tools + // + + kpToolSelectionEnvironment *toolSelectionEnvironment; + QActionGroup *toolsActionGroup; + + kpTool *toolSpraycan, *toolBrush, + *toolColorEraser, *toolColorPicker, + *toolCurve, *toolEllipse, + *toolEllipticalSelection, *toolEraser, + *toolFloodFill, *toolFreeFormSelection, + *toolLine, *toolPen, *toolPolygon, + *toolPolyline, *toolRectangle, *toolRectSelection, + *toolRoundedRectangle, *toolZoom; + kpToolText *toolText; + + QList tools; + int lastToolNumber; + + bool toolActionsEnabled; + QAction *actionPrevToolOptionGroup1, + *actionNextToolOptionGroup1, + *actionPrevToolOptionGroup2, + *actionNextToolOptionGroup2; + + int settingImageSelectionTransparency; + + int docResizeWidth, docResizeHeight; + bool docResizeToBeCompleted; + + // + // File Menu + // + + bool configOpenImagesInSameWindow, configPrintImageCenteredOnPage; + + QAction *actionNew, *actionOpen; + KRecentFilesAction *actionOpenRecent; + QAction *actionScan, *actionScreenshot, *actionProperties, + *actionSave, *actionSaveAs, *actionExport, + *actionReload, + *actionPrint, *actionPrintPreview, + *actionMail, + *actionClose, *actionQuit; + + SaneDialog *scanDialog; + + QUrl lastExportURL; + kpDocumentSaveOptions lastExportSaveOptions; + bool exportFirstTime; + + // + // Edit Menu + // + + bool editMenuDocumentActionsEnabled; + + QAction *actionUndo, *actionRedo, + *actionCut, *actionCopy, + *actionPaste, *actionPasteInNewWindow, + *actionDelete, + *actionSelectAll, *actionDeselect, + *actionCopyToFile, *actionPasteFromFile; + + QUrl lastCopyToURL; + kpDocumentSaveOptions lastCopyToSaveOptions; + bool copyToFirstTime; + + // + // View Menu + // + + bool configThumbnailShowRectangle; + KToggleAction *actionShowThumbnailRectangle; - // - // File Menu - // - - bool configOpenImagesInSameWindow, configPrintImageCenteredOnPage; - - QAction *actionNew, *actionOpen; - KRecentFilesAction *actionOpenRecent; - QAction *actionScan, *actionScreenshot, *actionProperties, - *actionSave, *actionSaveAs, *actionExport, - *actionReload, - *actionPrint, *actionPrintPreview, - *actionMail, - *actionClose, *actionQuit; - - SaneDialog *scanDialog; - - QUrl lastExportURL; - kpDocumentSaveOptions lastExportSaveOptions; - bool exportFirstTime; - - // - // Edit Menu - // - - bool editMenuDocumentActionsEnabled; - - QAction *actionUndo, *actionRedo, - *actionCut, *actionCopy, - *actionPaste, *actionPasteInNewWindow, - *actionDelete, - *actionSelectAll, *actionDeselect, - *actionCopyToFile, *actionPasteFromFile; - - QUrl lastCopyToURL; - kpDocumentSaveOptions lastCopyToSaveOptions; - bool copyToFirstTime; - - // - // View Menu - // - - bool configThumbnailShowRectangle; - KToggleAction *actionShowThumbnailRectangle; + bool viewMenuDocumentActionsEnabled; + + QAction *actionActualSize, + *actionFitToPage, *actionFitToWidth, *actionFitToHeight, + *actionZoomIn, *actionZoomOut; + KSelectAction *actionZoom; + KToggleAction *actionShowGrid, + *actionShowThumbnail, *actionZoomedThumbnail; - bool viewMenuDocumentActionsEnabled; - - QAction *actionActualSize, - *actionFitToPage, *actionFitToWidth, *actionFitToHeight, - *actionZoomIn, *actionZoomOut; - KSelectAction *actionZoom; - KToggleAction *actionShowGrid, - *actionShowThumbnail, *actionZoomedThumbnail; + QList zoomList; - QList zoomList; + QTimer *thumbnailSaveConfigTimer; - QTimer *thumbnailSaveConfigTimer; + // + // Image Menu + // - // - // Image Menu - // + kpTransformDialogEnvironment *transformDialogEnvironment; - kpTransformDialogEnvironment *transformDialogEnvironment; + bool imageMenuDocumentActionsEnabled; - bool imageMenuDocumentActionsEnabled; + QAction *actionResizeScale, + *actionCrop, *actionAutoCrop, + *actionFlip, *actionMirror, + *actionRotate, *actionRotateLeft, *actionRotateRight, + *actionSkew, + *actionConvertToBlackAndWhite, *actionConvertToGrayscale, + *actionBlur, *actionMoreEffects, + *actionInvertColors, *actionClear; - QAction *actionResizeScale, - *actionCrop, *actionAutoCrop, - *actionFlip, *actionMirror, - *actionRotate, *actionRotateLeft, *actionRotateRight, - *actionSkew, - *actionConvertToBlackAndWhite, *actionConvertToGrayscale, - *actionBlur, *actionMoreEffects, - *actionInvertColors, *actionClear; + // Implemented in kpMainWindow_Tools.cpp, not kpImageWindow_Image.cpp + // since they're really setting tool options. + KToggleAction *actionDrawOpaque; + QAction *actionDrawColorSimilarity; - // Implemented in kpMainWindow_Tools.cpp, not kpImageWindow_Image.cpp - // since they're really setting tool options. - KToggleAction *actionDrawOpaque; - QAction *actionDrawColorSimilarity; + int moreEffectsDialogLastEffect; - int moreEffectsDialogLastEffect; + // + // Colors Menu + // - // - // Colors Menu - // + bool colorMenuDocumentActionsEnabled; - bool colorMenuDocumentActionsEnabled; + QAction *actionColorsDefault; + KSelectAction *actionColorsKDE; + QAction *actionColorsOpen, *actionColorsReload; - QAction *actionColorsDefault; - KSelectAction *actionColorsKDE; - QAction *actionColorsOpen, *actionColorsReload; + QAction *actionColorsSave, *actionColorsSaveAs; - QAction *actionColorsSave, *actionColorsSaveAs; + QAction *actionColorsAppendRow; + QAction *actionColorsDeleteRow; - QAction *actionColorsAppendRow; - QAction *actionColorsDeleteRow; + // + // Settings Menu + // - // - // Settings Menu - // + KToggleAction *actionShowPath; + QAction *actionKeyBindings, *actionConfigureToolbars, *actionConfigure; + KToggleFullScreenAction *actionFullScreen; - KToggleAction *actionShowPath; - QAction *actionKeyBindings, *actionConfigureToolbars, *actionConfigure; - KToggleFullScreenAction *actionFullScreen; + // + // Status Bar + // - // - // Status Bar - // + bool statusBarCreated; + KSqueezedTextLabel *statusBarMessageLabel; + QList statusBarLabels; - bool statusBarCreated; - KSqueezedTextLabel *statusBarMessageLabel; - QList statusBarLabels; + bool statusBarShapeLastPointsInitialised; + QPoint statusBarShapeLastStartPoint, statusBarShapeLastEndPoint; + bool statusBarShapeLastSizeInitialised; + QSize statusBarShapeLastSize; - bool statusBarShapeLastPointsInitialised; - QPoint statusBarShapeLastStartPoint, statusBarShapeLastEndPoint; - bool statusBarShapeLastSizeInitialised; - QSize statusBarShapeLastSize; + // + // Text ToolBar + // - // - // Text ToolBar - // + KFontAction *actionTextFontFamily; + KFontSizeAction *actionTextFontSize; + KToggleAction *actionTextBold, *actionTextItalic, + *actionTextUnderline, *actionTextStrikeThru; - KFontAction *actionTextFontFamily; - KFontSizeAction *actionTextFontSize; - KToggleAction *actionTextBold, *actionTextItalic, - *actionTextUnderline, *actionTextStrikeThru; - - int settingTextStyle; - QString textOldFontFamily; - int textOldFontSize; + int settingTextStyle; + QString textOldFontFamily; + int textOldFontSize; }; - #endif // kpMainWindowPrivate_H diff --git a/mainWindow/kpMainWindow_Colors.cpp b/mainWindow/kpMainWindow_Colors.cpp --- a/mainWindow/kpMainWindow_Colors.cpp +++ b/mainWindow/kpMainWindow_Colors.cpp @@ -24,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpMainWindow.h" #include "kpMainWindowPrivate.h" @@ -44,120 +43,117 @@ //--------------------------------------------------------------------- -static QStringList KDEColorCollectionNames () +static QStringList KDEColorCollectionNames() { - return kpColorCollection::installedCollections (); + return kpColorCollection::installedCollections(); } //--------------------------------------------------------------------- // private -void kpMainWindow::setupColorsMenuActions () +void kpMainWindow::setupColorsMenuActions() { - KActionCollection *ac = actionCollection (); - + KActionCollection *ac = actionCollection(); - d->actionColorsDefault = ac->addAction (QStringLiteral("colors_default")); - d->actionColorsDefault->setText (i18n ("Use KolourPaint Defaults")); - connect (d->actionColorsDefault, &QAction::triggered, - this, &kpMainWindow::slotColorsDefault); + d->actionColorsDefault = ac->addAction(QStringLiteral("colors_default")); + d->actionColorsDefault->setText(i18n("Use KolourPaint Defaults")); + connect(d->actionColorsDefault, &QAction::triggered, + this, &kpMainWindow::slotColorsDefault); - d->actionColorsKDE = ac->add (QStringLiteral("colors_kde")); - d->actionColorsKDE->setText (i18nc ("@item:inmenu colors", "Use KDE's")); + d->actionColorsKDE = ac->add (QStringLiteral("colors_kde")); + d->actionColorsKDE->setText(i18nc("@item:inmenu colors", "Use KDE's")); // TODO: Will this slot be called spuriously if there are no colors // installed? - connect (d->actionColorsKDE, - static_cast(&KSelectAction::triggered), - this, &kpMainWindow::slotColorsKDE); + connect(d->actionColorsKDE, + static_cast(&KSelectAction::triggered), + this, &kpMainWindow::slotColorsKDE); - for (const auto &colName : ::KDEColorCollectionNames ()) { - d->actionColorsKDE->addAction (colName); + for (const auto &colName : ::KDEColorCollectionNames()) { + d->actionColorsKDE->addAction(colName); } - d->actionColorsOpen = ac->addAction (QStringLiteral("colors_open")); - d->actionColorsOpen->setText (i18nc ("@item:inmenu colors", "&Open...")); - connect (d->actionColorsOpen, &QAction::triggered, this, &kpMainWindow::slotColorsOpen); + d->actionColorsOpen = ac->addAction(QStringLiteral("colors_open")); + d->actionColorsOpen->setText(i18nc("@item:inmenu colors", "&Open...")); + connect(d->actionColorsOpen, &QAction::triggered, this, &kpMainWindow::slotColorsOpen); - d->actionColorsReload = ac->addAction (QStringLiteral("colors_reload")); - d->actionColorsReload->setText (i18nc ("@item:inmenu colors", "Reloa&d")); - connect (d->actionColorsReload, &QAction::triggered, - this, &kpMainWindow::slotColorsReload); + d->actionColorsReload = ac->addAction(QStringLiteral("colors_reload")); + d->actionColorsReload->setText(i18nc("@item:inmenu colors", "Reloa&d")); + connect(d->actionColorsReload, &QAction::triggered, + this, &kpMainWindow::slotColorsReload); - d->actionColorsSave = ac->addAction (QStringLiteral("colors_save")); - d->actionColorsSave->setText (i18nc ("@item:inmenu colors", "&Save")); - connect (d->actionColorsSave, &QAction::triggered, - this, &kpMainWindow::slotColorsSave); + d->actionColorsSave = ac->addAction(QStringLiteral("colors_save")); + d->actionColorsSave->setText(i18nc("@item:inmenu colors", "&Save")); + connect(d->actionColorsSave, &QAction::triggered, + this, &kpMainWindow::slotColorsSave); - d->actionColorsSaveAs = ac->addAction (QStringLiteral("colors_save_as")); - d->actionColorsSaveAs->setText (i18nc ("@item:inmenu colors", "Save &As...")); - connect (d->actionColorsSaveAs, &QAction::triggered, - this, &kpMainWindow::slotColorsSaveAs); + d->actionColorsSaveAs = ac->addAction(QStringLiteral("colors_save_as")); + d->actionColorsSaveAs->setText(i18nc("@item:inmenu colors", "Save &As...")); + connect(d->actionColorsSaveAs, &QAction::triggered, + this, &kpMainWindow::slotColorsSaveAs); - d->actionColorsAppendRow = ac->addAction (QStringLiteral("colors_append_row")); - d->actionColorsAppendRow->setText (i18nc ("@item:inmenu colors", "Add Row")); - connect (d->actionColorsAppendRow, &QAction::triggered, - this, &kpMainWindow::slotColorsAppendRow); + d->actionColorsAppendRow = ac->addAction(QStringLiteral("colors_append_row")); + d->actionColorsAppendRow->setText(i18nc("@item:inmenu colors", "Add Row")); + connect(d->actionColorsAppendRow, &QAction::triggered, + this, &kpMainWindow::slotColorsAppendRow); - d->actionColorsDeleteRow = ac->addAction (QStringLiteral("colors_delete_row")); - d->actionColorsDeleteRow->setText (i18nc ("@item:inmenu colors", "Delete Last Row")); - connect (d->actionColorsDeleteRow, &QAction::triggered, - this, &kpMainWindow::slotColorsDeleteRow); + d->actionColorsDeleteRow = ac->addAction(QStringLiteral("colors_delete_row")); + d->actionColorsDeleteRow->setText(i18nc("@item:inmenu colors", "Delete Last Row")); + connect(d->actionColorsDeleteRow, &QAction::triggered, + this, &kpMainWindow::slotColorsDeleteRow); - - enableColorsMenuDocumentActions (false); + enableColorsMenuDocumentActions(false); } //--------------------------------------------------------------------- // private -void kpMainWindow::createColorBox () +void kpMainWindow::createColorBox() { - d->colorToolBar = new kpColorToolBar (i18n ("Color Box"), this); + d->colorToolBar = new kpColorToolBar(i18n("Color Box"), this); // (needed for QMainWindow::saveState()) - d->colorToolBar->setObjectName ( QStringLiteral("Color Box" )); + d->colorToolBar->setObjectName(QStringLiteral("Color Box")); - connect (colorCells (), &kpColorCells::rowCountChanged, - this, &kpMainWindow::slotUpdateColorsDeleteRowActionEnabled); + connect(colorCells(), &kpColorCells::rowCountChanged, + this, &kpMainWindow::slotUpdateColorsDeleteRowActionEnabled); } //--------------------------------------------------------------------- // private -void kpMainWindow::enableColorsMenuDocumentActions (bool enable) +void kpMainWindow::enableColorsMenuDocumentActions(bool enable) { - d->actionColorsDefault->setEnabled (enable); - d->actionColorsKDE->setEnabled (enable); - d->actionColorsOpen->setEnabled (enable); - d->actionColorsReload->setEnabled (enable); + d->actionColorsDefault->setEnabled(enable); + d->actionColorsKDE->setEnabled(enable); + d->actionColorsOpen->setEnabled(enable); + d->actionColorsReload->setEnabled(enable); - d->actionColorsSave->setEnabled (enable); - d->actionColorsSaveAs->setEnabled (enable); + d->actionColorsSave->setEnabled(enable); + d->actionColorsSaveAs->setEnabled(enable); - d->actionColorsAppendRow->setEnabled (enable); + d->actionColorsAppendRow->setEnabled(enable); d->colorMenuDocumentActionsEnabled = enable; - slotUpdateColorsDeleteRowActionEnabled (); + slotUpdateColorsDeleteRowActionEnabled(); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotUpdateColorsDeleteRowActionEnabled () +void kpMainWindow::slotUpdateColorsDeleteRowActionEnabled() { // Currently, this is always enabled since kpColorCells guarantees that // there will be at least one row of cells (which might all be of the // invalid color). // // But this method is left here for future extensibility. - d->actionColorsDeleteRow->setEnabled ( - d->colorMenuDocumentActionsEnabled && (colorCells ()->rowCount () > 0)); + d->actionColorsDeleteRow->setEnabled( + d->colorMenuDocumentActionsEnabled && (colorCells()->rowCount() > 0)); } //--------------------------------------------------------------------- - // Used in 2 situations: // // 1. User opens a color without using the "Use KDE's" submenu. @@ -169,66 +165,64 @@ // this hack. // // private -void kpMainWindow::deselectActionColorsKDE () +void kpMainWindow::deselectActionColorsKDE() { - d->actionColorsKDE->setCurrentItem (-1); + d->actionColorsKDE->setCurrentItem(-1); } //--------------------------------------------------------------------- - // private -bool kpMainWindow::queryCloseColors () +bool kpMainWindow::queryCloseColors() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::queryCloseColors() colorCells.modified=" - << colorCells ()->isModified (); + << colorCells()->isModified(); #endif - toolEndShape (); + toolEndShape(); - if (!colorCells ()->isModified ()) { + if (!colorCells()->isModified()) { return true; // ok to close } int result = KMessageBox::Cancel; - - if (!colorCells ()->url ().isEmpty ()) - { - result = KMessageBox::warningYesNoCancel (this, - i18n ("The color palette \"%1\" has been modified.\n" - "Do you want to save it?", - kpUrlFormatter::PrettyFilename (colorCells ()->url ())), - QString ()/*caption*/, - KStandardGuiItem::save (), KStandardGuiItem::discard ()); - } - else - { - const QString name = colorCells ()->colorCollection ()->name (); - if (!name.isEmpty ()) - { - result = KMessageBox::warningYesNoCancel (this, - i18n ("The KDE color palette \"%1\" has been modified.\n" - "Do you want to save it to a file?", - name), - QString ()/*caption*/, - KStandardGuiItem::save (), KStandardGuiItem::discard ()); - } - else - { - result = KMessageBox::warningYesNoCancel (this, - i18n ("The default color palette has been modified.\n" - "Do you want to save it to a file?"), - QString ()/*caption*/, - KStandardGuiItem::save (), KStandardGuiItem::discard ()); + if (!colorCells()->url().isEmpty()) { + result = KMessageBox::warningYesNoCancel(this, + i18n( + "The color palette \"%1\" has been modified.\n" + "Do you want to save it?", + kpUrlFormatter::PrettyFilename(colorCells()-> + url())), + QString() /*caption*/, + KStandardGuiItem::save(), + KStandardGuiItem::discard()); + } else { + const QString name = colorCells()->colorCollection()->name(); + if (!name.isEmpty()) { + result = KMessageBox::warningYesNoCancel(this, + i18n( + "The KDE color palette \"%1\" has been modified.\n" + "Do you want to save it to a file?", + name), + QString() /*caption*/, + KStandardGuiItem::save(), + KStandardGuiItem::discard()); + } else { + result = KMessageBox::warningYesNoCancel(this, + i18n( + "The default color palette has been modified.\n" + "Do you want to save it to a file?"), + QString() /*caption*/, + KStandardGuiItem::save(), + KStandardGuiItem::discard()); } } - switch (result) - { + switch (result) { case KMessageBox::Yes: - return slotColorsSave (); // close only if save succeeds + return slotColorsSave(); // close only if save succeeds case KMessageBox::No: return true; // close without saving default: @@ -238,51 +232,47 @@ //--------------------------------------------------------------------- - // private -void kpMainWindow::openDefaultColors () +void kpMainWindow::openDefaultColors() { - colorCells ()->setColorCollection ( - kpColorCells::DefaultColorCollection ()); + colorCells()->setColorCollection( + kpColorCells::DefaultColorCollection()); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotColorsDefault () +void kpMainWindow::slotColorsDefault() { // Call just in case. - toolEndShape (); + toolEndShape(); - if (!queryCloseColors ()) { + if (!queryCloseColors()) { return; } - openDefaultColors (); + openDefaultColors(); - deselectActionColorsKDE (); + deselectActionColorsKDE(); } //--------------------------------------------------------------------- // private -bool kpMainWindow::openKDEColors (const QString &name) +bool kpMainWindow::openKDEColors(const QString &name) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::openKDEColors(" << name << ")"; #endif kpColorCollection colorCol; - if (colorCol.openKDE (name, this)) - { + if (colorCol.openKDE(name, this)) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "opened"; #endif - colorCells ()->setColorCollection (colorCol); + colorCells()->setColorCollection(colorCol); return true; - } - else - { + } else { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "failed to open"; #endif @@ -293,175 +283,163 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotColorsKDE () +void kpMainWindow::slotColorsKDE() { // Call in case an error dialog appears. - toolEndShape (); + toolEndShape(); - const int curItem = d->actionColorsKDE->currentItem (); + const int curItem = d->actionColorsKDE->currentItem(); - if (!queryCloseColors ()) - { - deselectActionColorsKDE (); + if (!queryCloseColors()) { + deselectActionColorsKDE(); return; } // queryCloseColors() calls slotColorSave(), which can call // slotColorSaveAs(), which can call deselectActionColorsKDE(). - d->actionColorsKDE->setCurrentItem (curItem); + d->actionColorsKDE->setCurrentItem(curItem); - const QStringList colNames = ::KDEColorCollectionNames (); - const int selected = d->actionColorsKDE->currentItem (); - Q_ASSERT (selected >= 0 && selected < colNames.size ()); + const QStringList colNames = ::KDEColorCollectionNames(); + const int selected = d->actionColorsKDE->currentItem(); + Q_ASSERT(selected >= 0 && selected < colNames.size()); - if (!openKDEColors (colNames [selected])) { - deselectActionColorsKDE (); + if (!openKDEColors(colNames [selected])) { + deselectActionColorsKDE(); } } //--------------------------------------------------------------------- // private -bool kpMainWindow::openColors (const QUrl &url) +bool kpMainWindow::openColors(const QUrl &url) { - return colorCells ()->openColorCollection (url); + return colorCells()->openColorCollection(url); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotColorsOpen () +void kpMainWindow::slotColorsOpen() { // Call due to dialog. - toolEndShape (); + toolEndShape(); QFileDialog fd(this); - fd.setDirectoryUrl(colorCells ()->url()); - fd.setWindowTitle(i18nc ("@title:window", "Open Color Palette")); + fd.setDirectoryUrl(colorCells()->url()); + fd.setWindowTitle(i18nc("@title:window", "Open Color Palette")); - if (fd.exec ()) - { - if (!queryCloseColors ()) { + if (fd.exec()) { + if (!queryCloseColors()) { return; } QList selected = fd.selectedUrls(); - if ( selected.count() && openColors(selected[0]) ) { - deselectActionColorsKDE(); + if (selected.count() && openColors(selected[0])) { + deselectActionColorsKDE(); } } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotColorsReload () +void kpMainWindow::slotColorsReload() { - toolEndShape (); + toolEndShape(); - if (colorCells ()->isModified ()) - { + if (colorCells()->isModified()) { int result = KMessageBox::Cancel; - if (!colorCells ()->url ().isEmpty ()) - { - result = KMessageBox::warningContinueCancel (this, - i18n ("The color palette \"%1\" has been modified.\n" - "Reloading will lose all changes since you last saved it.\n" - "Are you sure?", - kpUrlFormatter::PrettyFilename (colorCells ()->url ())), - QString ()/*caption*/, - KGuiItem(i18n ("&Reload"))); - } - else - { - const QString name = colorCells ()->colorCollection ()->name (); - if (!name.isEmpty ()) - { - result = KMessageBox::warningContinueCancel (this, - i18n ("The KDE color palette \"%1\" has been modified.\n" - "Reloading will lose all changes.\n" - "Are you sure?", - colorCells ()->colorCollection ()->name ()), - QString ()/*caption*/, - KGuiItem (i18n ("&Reload"))); - } - else - { - result = KMessageBox::warningContinueCancel (this, - i18n ("The default color palette has been modified.\n" - "Reloading will lose all changes.\n" - "Are you sure?"), - QString ()/*caption*/, - KGuiItem (i18n ("&Reload"))); + if (!colorCells()->url().isEmpty()) { + result = KMessageBox::warningContinueCancel(this, + i18n( + "The color palette \"%1\" has been modified.\n" + "Reloading will lose all changes since you last saved it.\n" + "Are you sure?", + kpUrlFormatter::PrettyFilename( + colorCells()->url())), + QString() /*caption*/, + KGuiItem(i18n("&Reload"))); + } else { + const QString name = colorCells()->colorCollection()->name(); + if (!name.isEmpty()) { + result = KMessageBox::warningContinueCancel(this, + i18n( + "The KDE color palette \"%1\" has been modified.\n" + "Reloading will lose all changes.\n" + "Are you sure?", + colorCells()->colorCollection()-> + name()), + QString() /*caption*/, + KGuiItem(i18n("&Reload"))); + } else { + result = KMessageBox::warningContinueCancel(this, + i18n( + "The default color palette has been modified.\n" + "Reloading will lose all changes.\n" + "Are you sure?"), + QString() /*caption*/, + KGuiItem(i18n("&Reload"))); } } #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "result=" << result - << "vs KMessageBox::Continue" << KMessageBox::Continue; + << "vs KMessageBox::Continue" << KMessageBox::Continue; #endif if (result != KMessageBox::Continue) { return; } } - - if (!colorCells ()->url ().isEmpty ()) - { - openColors (colorCells ()->url ()); - } - else - { - const QString name = colorCells ()->colorCollection ()->name (); - if (!name.isEmpty ()) { - openKDEColors (name); - } - else { - openDefaultColors (); + if (!colorCells()->url().isEmpty()) { + openColors(colorCells()->url()); + } else { + const QString name = colorCells()->colorCollection()->name(); + if (!name.isEmpty()) { + openKDEColors(name); + } else { + openDefaultColors(); } } } //--------------------------------------------------------------------- - // private slot -bool kpMainWindow::slotColorsSave () +bool kpMainWindow::slotColorsSave() { // Call due to dialog. - toolEndShape (); + toolEndShape(); - if (colorCells ()->url ().isEmpty ()) - { - return slotColorsSaveAs (); + if (colorCells()->url().isEmpty()) { + return slotColorsSaveAs(); } - return colorCells ()->saveColorCollection (); + return colorCells()->saveColorCollection(); } //--------------------------------------------------------------------- // private slot -bool kpMainWindow::slotColorsSaveAs () +bool kpMainWindow::slotColorsSaveAs() { // Call due to dialog. - toolEndShape (); + toolEndShape(); QFileDialog fd(this); - fd.setDirectoryUrl(colorCells ()->url()); + fd.setDirectoryUrl(colorCells()->url()); fd.setWindowTitle(i18n("Save Color Palette As")); fd.setAcceptMode(QFileDialog::AcceptSave); - if (fd.exec ()) - { + if (fd.exec()) { QList selected = fd.selectedUrls(); - if ( !selected.count() || !colorCells ()->saveColorCollectionAs(selected[0]) ) { - return false; + if (!selected.count() || !colorCells()->saveColorCollectionAs(selected[0])) { + return false; } // We're definitely using our own color collection now. - deselectActionColorsKDE (); + deselectActionColorsKDE(); return true; } @@ -472,23 +450,23 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotColorsAppendRow () +void kpMainWindow::slotColorsAppendRow() { // Call just in case. - toolEndShape (); + toolEndShape(); - kpColorCells *colorCells = d->colorToolBar->colorCells (); - colorCells->appendRow (); + kpColorCells *colorCells = d->colorToolBar->colorCells(); + colorCells->appendRow(); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotColorsDeleteRow () +void kpMainWindow::slotColorsDeleteRow() { // Call just in case. - toolEndShape (); + toolEndShape(); - kpColorCells *colorCells = d->colorToolBar->colorCells (); - colorCells->deleteLastRow (); + kpColorCells *colorCells = d->colorToolBar->colorCells(); + colorCells->deleteLastRow(); } diff --git a/mainWindow/kpMainWindow_Edit.cpp b/mainWindow/kpMainWindow_Edit.cpp --- a/mainWindow/kpMainWindow_Edit.cpp +++ b/mainWindow/kpMainWindow_Edit.cpp @@ -25,7 +25,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpMainWindow.h" #include "kpMainWindowPrivate.h" @@ -73,73 +72,68 @@ //--------------------------------------------------------------------- // private -void kpMainWindow::setupEditMenuActions () +void kpMainWindow::setupEditMenuActions() { - KActionCollection *ac = actionCollection (); - + KActionCollection *ac = actionCollection(); // Undo/Redo // CONFIG: Need GUI for config history size. - d->commandHistory = new kpCommandHistory (true/*read config*/, this); + d->commandHistory = new kpCommandHistory(true /*read config*/, this); - if (d->configFirstTime) - { + if (d->configFirstTime) { // (so that cfg-file-editing user can modify in the meantime) - d->commandHistory->writeConfig (); + d->commandHistory->writeConfig(); } - - d->actionCut = KStandardAction::cut (this, SLOT (slotCut()), ac); - d->actionCopy = KStandardAction::copy (this, SLOT (slotCopy()), ac); - d->actionPaste = KStandardAction::paste (this, SLOT (slotPaste()), ac); - d->actionPasteInNewWindow = ac->addAction (QStringLiteral("edit_paste_in_new_window")); - d->actionPasteInNewWindow->setText (i18n ("Paste in &New Window")); - connect (d->actionPasteInNewWindow, &QAction::triggered, - this, &kpMainWindow::slotPasteInNewWindow); - ac->setDefaultShortcut (d->actionPasteInNewWindow, Qt::CTRL + Qt::SHIFT + Qt::Key_V); + d->actionCut = KStandardAction::cut(this, SLOT(slotCut()), ac); + d->actionCopy = KStandardAction::copy(this, SLOT(slotCopy()), ac); + d->actionPaste = KStandardAction::paste(this, SLOT(slotPaste()), ac); + d->actionPasteInNewWindow = ac->addAction(QStringLiteral("edit_paste_in_new_window")); + d->actionPasteInNewWindow->setText(i18n("Paste in &New Window")); + connect(d->actionPasteInNewWindow, &QAction::triggered, + this, &kpMainWindow::slotPasteInNewWindow); + ac->setDefaultShortcut(d->actionPasteInNewWindow, Qt::CTRL + Qt::SHIFT + Qt::Key_V); //d->actionDelete = KStandardAction::clear (this, SLOT (slotDelete()), ac); - d->actionDelete = ac->addAction (QStringLiteral("edit_clear")); - d->actionDelete->setText (i18n ("&Delete Selection")); - connect (d->actionDelete, &QAction::triggered, this, &kpMainWindow::slotDelete); + d->actionDelete = ac->addAction(QStringLiteral("edit_clear")); + d->actionDelete->setText(i18n("&Delete Selection")); + connect(d->actionDelete, &QAction::triggered, this, &kpMainWindow::slotDelete); - d->actionSelectAll = KStandardAction::selectAll (this, SLOT (slotSelectAll()), ac); - d->actionDeselect = KStandardAction::deselect (this, SLOT (slotDeselect()), ac); + d->actionSelectAll = KStandardAction::selectAll(this, SLOT(slotSelectAll()), ac); + d->actionDeselect = KStandardAction::deselect(this, SLOT(slotDeselect()), ac); + d->actionCopyToFile = ac->addAction(QStringLiteral("edit_copy_to_file")); + d->actionCopyToFile->setText(i18n("C&opy to File...")); + connect(d->actionCopyToFile, &QAction::triggered, this, &kpMainWindow::slotCopyToFile); - d->actionCopyToFile = ac->addAction (QStringLiteral("edit_copy_to_file")); - d->actionCopyToFile->setText (i18n ("C&opy to File...")); - connect (d->actionCopyToFile, &QAction::triggered, this, &kpMainWindow::slotCopyToFile); - - d->actionPasteFromFile = ac->addAction (QStringLiteral("edit_paste_from_file")); - d->actionPasteFromFile->setText (i18n ("Paste &From File...")); - connect (d->actionPasteFromFile, &QAction::triggered, this, &kpMainWindow::slotPasteFromFile); - + d->actionPasteFromFile = ac->addAction(QStringLiteral("edit_paste_from_file")); + d->actionPasteFromFile->setText(i18n("Paste &From File...")); + connect(d->actionPasteFromFile, &QAction::triggered, this, &kpMainWindow::slotPasteFromFile); d->editMenuDocumentActionsEnabled = false; - enableEditMenuDocumentActions (false); + enableEditMenuDocumentActions(false); // Paste should always be enabled, as long as there is something to paste // (independent of whether we have a document or not) - connect (QApplication::clipboard(), &QClipboard::dataChanged, - this, &kpMainWindow::slotEnablePaste); + connect(QApplication::clipboard(), &QClipboard::dataChanged, + this, &kpMainWindow::slotEnablePaste); - slotEnablePaste (); + slotEnablePaste(); } //--------------------------------------------------------------------- // private -void kpMainWindow::enableEditMenuDocumentActions (bool enable) +void kpMainWindow::enableEditMenuDocumentActions(bool enable) { // d->actionCut // d->actionCopy // d->actionPaste // d->actionPasteInNewWindow // d->actionDelete - d->actionSelectAll->setEnabled (enable); + d->actionSelectAll->setEnabled(enable); // d->actionDeselect d->editMenuDocumentActionsEnabled = enable; @@ -149,69 +143,68 @@ // Unlike d->actionPaste, we disable this if there is no document. // This is because "File / Open" would do the same thing, if there is // no document. - d->actionPasteFromFile->setEnabled (enable); + d->actionPasteFromFile->setEnabled(enable); } //--------------------------------------------------------------------- // public -QMenu *kpMainWindow::selectionToolRMBMenu () +QMenu *kpMainWindow::selectionToolRMBMenu() { - return qobject_cast (guiFactory ()->container (QStringLiteral("selectionToolRMBMenu"), this)); + return qobject_cast (guiFactory()->container(QStringLiteral("selectionToolRMBMenu"), + this)); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotCut () +void kpMainWindow::slotCut() { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::slotCut() CALLED"; #endif - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); - Q_ASSERT (d->document && d->document->selection ()); + Q_ASSERT(d->document && d->document->selection()); - toolEndShape (); + toolEndShape(); - slotCopy (); - slotDelete (); + slotCopy(); + slotDelete(); } //--------------------------------------------------------------------- -static QMimeData *NewTextMimeData (const QString &text) +static QMimeData *NewTextMimeData(const QString &text) { - auto *md = new QMimeData (); - md->setText (text); + auto *md = new QMimeData(); + md->setText(text); return md; } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotCopy () +void kpMainWindow::slotCopy() { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::slotCopy() CALLED"; #endif - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); - Q_ASSERT (d->document && d->document->selection ()); + Q_ASSERT(d->document && d->document->selection()); - toolEndShape (); + toolEndShape(); - kpAbstractSelection *sel = d->document->selection ()->clone (); + kpAbstractSelection *sel = d->document->selection()->clone(); - if (dynamic_cast (sel)) - { - auto *textSel = dynamic_cast (sel); - if (!textSel->text ().isEmpty ()) - { - QApplication::clipboard ()->setMimeData ( - ::NewTextMimeData (textSel->text ()), + if (dynamic_cast (sel)) { + auto *textSel = dynamic_cast (sel); + if (!textSel->text().isEmpty()) { + QApplication::clipboard()->setMimeData( + ::NewTextMimeData(textSel->text()), QClipboard::Clipboard); // SYNC: Normally, users highlight text and press CTRL+C. @@ -231,49 +224,45 @@ // Once we change KolourPaint to support highlighted text // and CTRL+C to copy only the highlighted text, delete // this code. - QApplication::clipboard ()->setMimeData ( - ::NewTextMimeData (textSel->text ()), + QApplication::clipboard()->setMimeData( + ::NewTextMimeData(textSel->text()), QClipboard::Selection); } - } - else if (dynamic_cast (sel)) - { - auto *imageSel = dynamic_cast (sel); + } else if (dynamic_cast (sel)) { + auto *imageSel = dynamic_cast (sel); // Transparency doesn't get sent across the aether so nuke it now // so that transparency mask doesn't get needlessly recalculated // if we ever call sel.setBaseImage(). - imageSel->setTransparency (kpImageSelectionTransparency ()); + imageSel->setTransparency(kpImageSelectionTransparency()); kpImage rawImage; - if (imageSel->hasContent ()) { - rawImage = imageSel->baseImage (); - } - else { - rawImage = d->document->getSelectedBaseImage (); + if (imageSel->hasContent()) { + rawImage = imageSel->baseImage(); + } else { + rawImage = d->document->getSelectedBaseImage(); } - imageSel->setBaseImage ( rawImage ); + imageSel->setBaseImage(rawImage); - QApplication::clipboard ()->setMimeData ( - new kpSelectionDrag (*imageSel), + QApplication::clipboard()->setMimeData( + new kpSelectionDrag(*imageSel), QClipboard::Clipboard); - } - else { - Q_ASSERT (!"Unknown selection type"); + } else { + Q_ASSERT(!"Unknown selection type"); } delete sel; } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotEnablePaste () +void kpMainWindow::slotEnablePaste() { - const QMimeData *md = - QApplication::clipboard()->mimeData(QClipboard::Clipboard); + const QMimeData *md + = QApplication::clipboard()->mimeData(QClipboard::Clipboard); // It's faster to test for QMimeData::hasText() first due to the // lazy evaluation of the '||' operator. @@ -286,34 +275,36 @@ //--------------------------------------------------------------------- // private -QRect kpMainWindow::calcUsefulPasteRect (int imageWidth, int imageHeight) +QRect kpMainWindow::calcUsefulPasteRect(int imageWidth, int imageHeight) { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::calcUsefulPasteRect(" - << imageWidth << "," << imageHeight - << ")"; + << imageWidth << "," << imageHeight + << ")"; #endif - Q_ASSERT (d->document); + Q_ASSERT(d->document); // TODO: 1st choice is to paste sel near but not overlapping last deselect point - if (d->mainView && d->scrollView) - { - const QPoint viewTopLeft (d->scrollView->horizontalScrollBar()->value (), - d->scrollView->verticalScrollBar()->value ()); + if (d->mainView && d->scrollView) { + const QPoint viewTopLeft(d->scrollView->horizontalScrollBar()->value(), + d->scrollView->verticalScrollBar()->value()); - const QPoint docTopLeft = d->mainView->transformViewToDoc (viewTopLeft); + const QPoint docTopLeft = d->mainView->transformViewToDoc(viewTopLeft); - if ((docTopLeft.x () + imageWidth <= d->document->width () && - docTopLeft.y () + imageHeight <= d->document->height ()) || - imageWidth <= docTopLeft.x () || - imageHeight <= docTopLeft.y ()) - { - return {docTopLeft.x (), docTopLeft.y (), imageWidth, imageHeight}; + if ((docTopLeft.x() + imageWidth <= d->document->width() + && docTopLeft.y() + imageHeight <= d->document->height()) + || imageWidth <= docTopLeft.x() + || imageHeight <= docTopLeft.y()) { + return { + docTopLeft.x(), docTopLeft.y(), imageWidth, imageHeight + }; } } - return {0, 0, imageWidth, imageHeight}; + return { + 0, 0, imageWidth, imageHeight + }; } //--------------------------------------------------------------------- @@ -325,265 +316,244 @@ qCDebug(kpLogMainWindow) << "kpMainWindow::paste(forceTopLeft=" << forceTopLeft << ")"; #endif - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); - toolEndShape (); + toolEndShape(); // // Make sure we've got a document (esp. with File/Close) // - if (!d->document) - { - auto *newDoc = new kpDocument ( - sel.width (), sel.height (), documentEnvironment ()); + if (!d->document) { + auto *newDoc = new kpDocument( + sel.width(), sel.height(), documentEnvironment()); // will also create viewManager - setDocument (newDoc); + setDocument(newDoc); } // // Paste as new selection // - const auto *imageSel = dynamic_cast (&sel); + const auto *imageSel = dynamic_cast (&sel); - if (imageSel && imageSel->hasContent () && imageSel->transparency ().isTransparent ()) - { - d->colorToolBar->flashColorSimilarityToolBarItem (); + if (imageSel && imageSel->hasContent() && imageSel->transparency().isTransparent()) { + d->colorToolBar->flashColorSimilarityToolBarItem(); } - kpAbstractSelection *selInUsefulPos = sel.clone (); + kpAbstractSelection *selInUsefulPos = sel.clone(); if (!forceTopLeft) { - selInUsefulPos->moveTo (calcUsefulPasteRect (sel.width (), sel.height ()).topLeft ()); + selInUsefulPos->moveTo(calcUsefulPasteRect(sel.width(), sel.height()).topLeft()); } // TODO: Should use kpCommandHistory::addCreateSelectionCommand(), // as well, to really support pasting selection borders. - addDeselectFirstCommand (new kpToolSelectionCreateCommand ( - dynamic_cast (selInUsefulPos) ? - i18n ("Text: Create Box") : - i18n ("Selection: Create"), - *selInUsefulPos, - commandEnvironment ())); + addDeselectFirstCommand(new kpToolSelectionCreateCommand( + dynamic_cast (selInUsefulPos) + ? i18n("Text: Create Box") + : i18n("Selection: Create"), + *selInUsefulPos, + commandEnvironment())); delete selInUsefulPos; - #if DEBUG_KP_MAIN_WINDOW && 1 - qCDebug(kpLogMainWindow) << "sel.size=" << QSize (sel.width (), sel.height ()) - << " document.size=" - << QSize (d->document->width (), d->document->height ()); + qCDebug(kpLogMainWindow) << "sel.size=" << QSize(sel.width(), sel.height()) + << " document.size=" + << QSize(d->document->width(), d->document->height()); #endif // If the selection is bigger than the document, automatically // resize the document (with the option of Undo'ing) to fit // the selection. // // No annoying dialog necessary. // - if (sel.width () > d->document->width () || - sel.height () > d->document->height ()) - { - d->commandHistory->addCommand ( - new kpTransformResizeScaleCommand ( - false/*act on doc, not sel*/, - qMax (sel.width (), d->document->width ()), - qMax (sel.height (), d->document->height ()), + if (sel.width() > d->document->width() + || sel.height() > d->document->height()) { + d->commandHistory->addCommand( + new kpTransformResizeScaleCommand( + false /*act on doc, not sel*/, + qMax(sel.width(), d->document->width()), + qMax(sel.height(), d->document->height()), kpTransformResizeScaleCommand::Resize, - commandEnvironment ())); + commandEnvironment())); } } //--------------------------------------------------------------------- // public -void kpMainWindow::pasteText (const QString &text, - bool forceNewTextSelection, - const QPoint &newTextSelectionTopLeft) +void kpMainWindow::pasteText(const QString &text, bool forceNewTextSelection, + const QPoint &newTextSelectionTopLeft) { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::pasteText(" << text - << ",forceNewTextSelection=" << forceNewTextSelection - << ",newTextSelectionTopLeft=" << newTextSelectionTopLeft - << ")"; + << ",forceNewTextSelection=" << forceNewTextSelection + << ",newTextSelectionTopLeft=" << newTextSelectionTopLeft + << ")"; #endif - if ( text.isEmpty() ) { + if (text.isEmpty()) { return; } - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); - toolEndShape (); + toolEndShape(); QStringList textLines = text.split('\n'); - if (!forceNewTextSelection && - d->document && d->document->textSelection () && - d->commandHistory && d->viewManager) - { + if (!forceNewTextSelection + && d->document && d->document->textSelection() + && d->commandHistory && d->viewManager) { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "\treusing existing Text Selection"; #endif d->viewManager->setQueueUpdates(); - kpTextSelection *textSel = d->document->textSelection (); - if (!textSel->hasContent ()) - { + kpTextSelection *textSel = d->document->textSelection(); + if (!textSel->hasContent()) { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "\t\tneeds content"; #endif - commandHistory ()->addCreateSelectionCommand ( - new kpToolSelectionCreateCommand ( - i18n ("Text: Create Box"), + commandHistory()->addCreateSelectionCommand( + new kpToolSelectionCreateCommand( + i18n("Text: Create Box"), *textSel, - commandEnvironment ()), - false/*no exec*/); + commandEnvironment()), + false /*no exec*/); } - kpMacroCommand *macroCmd = new kpMacroCommand (i18n ("Text: Paste"), - commandEnvironment ()); + kpMacroCommand *macroCmd = new kpMacroCommand(i18n("Text: Paste"), + commandEnvironment()); // (yes, this is the same check as the previous "if") - if (!textSel->hasContent ()) - { - kpCommand *giveContentCmd = new kpToolTextGiveContentCommand ( + if (!textSel->hasContent()) { + kpCommand *giveContentCmd = new kpToolTextGiveContentCommand( *textSel, - QString ()/*uninteresting child of macro cmd*/, - commandEnvironment ()); - giveContentCmd->execute (); + QString() /*uninteresting child of macro cmd*/, + commandEnvironment()); + giveContentCmd->execute(); - macroCmd->addCommand (giveContentCmd); + macroCmd->addCommand(giveContentCmd); } - for (int i = 0; i < static_cast (textLines.size ()); i++) - { - if (i > 0) - { - macroCmd->addCommand ( - new kpToolTextEnterCommand ( - QString()/*uninteresting child of macroCmd*/, - d->viewManager->textCursorRow (), - d->viewManager->textCursorCol (), + for (int i = 0; i < static_cast(textLines.size()); i++) { + if (i > 0) { + macroCmd->addCommand( + new kpToolTextEnterCommand( + QString() /*uninteresting child of macroCmd*/, + d->viewManager->textCursorRow(), + d->viewManager->textCursorCol(), kpToolTextEnterCommand::AddEnterNow, - commandEnvironment ())); + commandEnvironment())); } - macroCmd->addCommand ( - new kpToolTextInsertCommand ( - QString()/*uninteresting child of macroCmd*/, - d->viewManager->textCursorRow (), - d->viewManager->textCursorCol (), + macroCmd->addCommand( + new kpToolTextInsertCommand( + QString() /*uninteresting child of macroCmd*/, + d->viewManager->textCursorRow(), + d->viewManager->textCursorCol(), textLines [i], - commandEnvironment ())); + commandEnvironment())); } - d->commandHistory->addCommand (macroCmd, false/*no exec*/); + d->commandHistory->addCommand(macroCmd, false /*no exec*/); d->viewManager->restoreQueueUpdates(); - } - else - { + } else { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "\tcreating Text Selection"; #endif - const kpTextStyle ts = textStyle (); - const QFontMetrics fontMetrics = ts.fontMetrics (); + const kpTextStyle ts = textStyle(); + const QFontMetrics fontMetrics = ts.fontMetrics(); - int height = textLines.size () * fontMetrics.height (); - if (textLines.size () >= 1) { - height += (textLines.size () - 1) * fontMetrics.leading (); + int height = textLines.size() * fontMetrics.height(); + if (textLines.size() >= 1) { + height += (textLines.size() - 1) * fontMetrics.leading(); } int width = 0; - for (QList ::const_iterator it = textLines.constBegin (); - it != textLines.constEnd (); - ++it) - { - const int w = fontMetrics.width (*it); + for (QList ::const_iterator it = textLines.constBegin(); + it != textLines.constEnd(); + ++it) { + const int w = fontMetrics.width(*it); if (w > width) { width = w; } } // limit the size to avoid memory overflow - width = qMin(qMax(QApplication::desktop()->width(), d->document ? d->document->width() : 0), width); - height = qMin(qMax(QApplication::desktop()->height(), d->document ? d->document->height() : 0), height); - - const int selWidth = qMax (kpTextSelection::MinimumWidthForTextStyle (ts), - width + kpTextSelection::TextBorderSize () * 2); - const int selHeight = qMax (kpTextSelection::MinimumHeightForTextStyle (ts), - height + kpTextSelection::TextBorderSize () * 2); - kpTextSelection newTextSel (QRect (0, 0, selWidth, selHeight), - textLines, - ts); - - if (newTextSelectionTopLeft != KP_INVALID_POINT) - { - newTextSel.moveTo (newTextSelectionTopLeft); - paste (newTextSel, true/*force topLeft*/); - } - else - { - paste (newTextSel); + width = qMin(qMax(QApplication::desktop()->width(), + d->document ? d->document->width() : 0), width); + height + = qMin(qMax(QApplication::desktop()->height(), + d->document ? d->document->height() : 0), height); + + const int selWidth = qMax(kpTextSelection::MinimumWidthForTextStyle(ts), + width + kpTextSelection::TextBorderSize() * 2); + const int selHeight = qMax(kpTextSelection::MinimumHeightForTextStyle(ts), + height + kpTextSelection::TextBorderSize() * 2); + kpTextSelection newTextSel(QRect(0, 0, selWidth, selHeight), + textLines, + ts); + + if (newTextSelectionTopLeft != KP_INVALID_POINT) { + newTextSel.moveTo(newTextSelectionTopLeft); + paste(newTextSel, true /*force topLeft*/); + } else { + paste(newTextSel); } } } //--------------------------------------------------------------------- // public -void kpMainWindow::pasteTextAt (const QString &text, const QPoint &point, - bool allowNewTextSelectionPointShift) +void kpMainWindow::pasteTextAt(const QString &text, const QPoint &point, + bool allowNewTextSelectionPointShift) { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::pasteTextAt(" << text - << ",point=" << point - << ",allowNewTextSelectionPointShift=" - << allowNewTextSelectionPointShift - << ")"; + << ",point=" << point + << ",allowNewTextSelectionPointShift=" + << allowNewTextSelectionPointShift + << ")"; #endif - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); - - toolEndShape (); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); + toolEndShape(); - if (d->document && - d->document->textSelection () && - d->document->textSelection ()->pointIsInTextArea (point)) - { - kpTextSelection *textSel = d->document->textSelection (); + if (d->document + && d->document->textSelection() + && d->document->textSelection()->pointIsInTextArea(point)) { + kpTextSelection *textSel = d->document->textSelection(); int row, col; - if (textSel->hasContent ()) - { - row = textSel->closestTextRowForPoint (point); - col = textSel->closestTextColForPoint (point); - } - else - { + if (textSel->hasContent()) { + row = textSel->closestTextRowForPoint(point); + col = textSel->closestTextColForPoint(point); + } else { row = col = 0; } - d->viewManager->setTextCursorPosition (row, col); + d->viewManager->setTextCursorPosition(row, col); - pasteText (text); - } - else - { + pasteText(text); + } else { QPoint pointToUse = point; - if (allowNewTextSelectionPointShift) - { + if (allowNewTextSelectionPointShift) { // TODO: In terms of doc pixels, would be inconsistent behaviour // based on zoomLevel of view. // pointToUse -= QPoint (-view->selectionResizeHandleAtomicSize (), // -view->selectionResizeHandleAtomicSize ()); } - pasteText (text, true/*force new text selection*/, pointToUse); + pasteText(text, true /*force new text selection*/, pointToUse); } } @@ -599,292 +569,264 @@ const QMimeData *mimeData = QApplication::clipboard()->mimeData(QClipboard::Clipboard); kpAbstractImageSelection *sel = kpSelectionDrag::decode(mimeData); - if ( sel ) - { + if (sel) { sel->setTransparency(imageSelectionTransparency()); paste(*sel); delete sel; - } - else if ( mimeData->hasText() ) - { + } else if (mimeData->hasText()) { pasteText(mimeData->text()); - } - else - { + } else { kpSetOverrideCursorSaver cursorSaver(Qt::ArrowCursor); KMessageBox::sorry(this, - i18n("KolourPaint cannot paste the contents of" - " the clipboard as it has an unknown format."), - i18n("Cannot Paste")); + i18n("KolourPaint cannot paste the contents of" + " the clipboard as it has an unknown format."), + i18n("Cannot Paste")); } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotPasteInNewWindow () +void kpMainWindow::slotPasteInNewWindow() { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::slotPasteInNewWindow() CALLED"; #endif - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); - toolEndShape (); + toolEndShape(); // // Pasting must ensure that: // // Requirement 1. the document is the same size as the image to be pasted. // Requirement 2. transparent pixels in the image must remain as transparent. // - auto *win = new kpMainWindow (nullptr/*no document*/); - win->show (); + auto *win = new kpMainWindow(nullptr /*no document*/); + win->show(); // Make "Edit / Paste in New Window" always paste white pixels as white. // Don't let selection transparency get in the way and paste them as // transparent. - kpImageSelectionTransparency transparency = win->imageSelectionTransparency (); - if (transparency.isTransparent ()) - { + kpImageSelectionTransparency transparency = win->imageSelectionTransparency(); + if (transparency.isTransparent()) { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "\tchanging image selection transparency to opaque"; #endif - transparency.setOpaque (); + transparency.setOpaque(); // Since we are setting selection transparency programmatically // -- as opposed to in response to user input -- this will not // affect the selection transparency tool option widget's "last used" // config setting. - win->setImageSelectionTransparency (transparency); + win->setImageSelectionTransparency(transparency); } // (this handles Requirement 1. above) - win->slotPaste (); + win->slotPaste(); // if slotPaste could not decode clipboard data, no document was created - if ( win->document() ) - { - // (this handles Requirement 2. above; - // slotDeselect() is not enough unless the document is filled with the - // transparent color in advance) - win->slotCrop(); + if (win->document()) { + // (this handles Requirement 2. above; + // slotDeselect() is not enough unless the document is filled with the + // transparent color in advance) + win->slotCrop(); } } //--------------------------------------------------------------------- // public slot -void kpMainWindow::slotDelete () +void kpMainWindow::slotDelete() { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::slotDelete() CALLED"; #endif - if (!d->actionDelete->isEnabled ()) - { + if (!d->actionDelete->isEnabled()) { #if DEBUG_KP_MAIN_WINDOW && 1 - qCDebug(kpLogMainWindow) << "\taction not enabled - was probably called from kpTool::keyPressEvent()"; + qCDebug(kpLogMainWindow) + << "\taction not enabled - was probably called from kpTool::keyPressEvent()"; #endif return; } - Q_ASSERT (d->document && d->document->selection ()); + Q_ASSERT(d->document && d->document->selection()); - toolEndShape (); + toolEndShape(); - addImageOrSelectionCommand (new kpToolSelectionDestroyCommand ( - d->document->textSelection () ? - i18n ("Text: Delete Box") : // not to be confused with i18n ("Text: Delete") - i18n ("Selection: Delete"), - false/*no push onto doc*/, - commandEnvironment ())); + addImageOrSelectionCommand(new kpToolSelectionDestroyCommand( + d->document->textSelection() + ? i18n("Text: Delete Box") // not to be confused with i18n ("Text: Delete") + : i18n("Selection: Delete"), + false /*no push onto doc*/, + commandEnvironment())); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotSelectAll () +void kpMainWindow::slotSelectAll() { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::slotSelectAll() CALLED"; #endif - Q_ASSERT (d->document); + Q_ASSERT(d->document); - toolEndShape (); + toolEndShape(); - if (d->document->selection ()) { - slotDeselect (); + if (d->document->selection()) { + slotDeselect(); } // just the border - don't actually pull image from doc yet - d->document->setSelection ( - kpRectangularImageSelection (d->document->rect (), - imageSelectionTransparency ())); + d->document->setSelection( + kpRectangularImageSelection(d->document->rect(), + imageSelectionTransparency())); - if (tool ()) { - tool ()->somethingBelowTheCursorChanged (); + if (tool()) { + tool()->somethingBelowTheCursorChanged(); } } //--------------------------------------------------------------------- // private -void kpMainWindow::addDeselectFirstCommand (kpCommand *cmd) +void kpMainWindow::addDeselectFirstCommand(kpCommand *cmd) { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::addDeselectFirstCommand(" - << cmd - << ")"; + << cmd + << ")"; #endif - - kpAbstractSelection *sel = d->document->selection (); + kpAbstractSelection *sel = d->document->selection(); #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "\tsel=" << sel; #endif - if (sel) - { + if (sel) { // if you just dragged out something with no action then // forget the drag - if (!sel->hasContent ()) - { + if (!sel->hasContent()) { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "\tjust a fresh border - was nop - delete"; #endif - d->document->selectionDelete (); - if (tool ()) { - tool ()->somethingBelowTheCursorChanged (); + d->document->selectionDelete(); + if (tool()) { + tool()->somethingBelowTheCursorChanged(); } if (cmd) { - d->commandHistory->addCommand (cmd); + d->commandHistory->addCommand(cmd); } - } - else - { + } else { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "\treal selection with image - push onto doc cmd"; #endif - kpCommand *deselectCommand = new kpToolSelectionDestroyCommand ( - dynamic_cast (sel) ? - i18n ("Text: Finish") : - i18n ("Selection: Deselect"), - true/*push onto document*/, - commandEnvironment ()); - - if (cmd) - { - kpMacroCommand *macroCmd = new kpMacroCommand (cmd->name (), - commandEnvironment ()); - macroCmd->addCommand (deselectCommand); - macroCmd->addCommand (cmd); - d->commandHistory->addCommand (macroCmd); - } - else { - d->commandHistory->addCommand (deselectCommand); + kpCommand *deselectCommand = new kpToolSelectionDestroyCommand( + dynamic_cast (sel) + ? i18n("Text: Finish") + : i18n("Selection: Deselect"), + true /*push onto document*/, + commandEnvironment()); + + if (cmd) { + kpMacroCommand *macroCmd = new kpMacroCommand(cmd->name(), + commandEnvironment()); + macroCmd->addCommand(deselectCommand); + macroCmd->addCommand(cmd); + d->commandHistory->addCommand(macroCmd); + } else { + d->commandHistory->addCommand(deselectCommand); } } - } - else - { + } else { if (cmd) { - d->commandHistory->addCommand (cmd); + d->commandHistory->addCommand(cmd); } } } //--------------------------------------------------------------------- // public slot -void kpMainWindow::slotDeselect () +void kpMainWindow::slotDeselect() { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::slotDeselect() CALLED"; #endif - Q_ASSERT (d->document && d->document->selection ()); + Q_ASSERT(d->document && d->document->selection()); - toolEndShape (); + toolEndShape(); - addDeselectFirstCommand (nullptr); + addDeselectFirstCommand(nullptr); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotCopyToFile () +void kpMainWindow::slotCopyToFile() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotCopyToFile()"; #endif - toolEndShape (); - + toolEndShape(); - if (!d->document->selection ()) { + if (!d->document->selection()) { return; } kpImage imageToSave; - if (d->document->imageSelection ()) - { - kpAbstractImageSelection *imageSel = d->document->imageSelection (); - if (!imageSel->hasContent ()) - { + if (d->document->imageSelection()) { + kpAbstractImageSelection *imageSel = d->document->imageSelection(); + if (!imageSel->hasContent()) { // Not a floating selection - user has just selected a region; // haven't pulled it off yet so probably don't expect and can't // visualize selection transparency so give opaque, not transparent // image. - imageToSave = d->document->getSelectedBaseImage (); + imageToSave = d->document->getSelectedBaseImage(); + } else { + imageToSave = imageSel->transparentImage(); } - else { - imageToSave = imageSel->transparentImage (); - } - } - else if (d->document->textSelection ()) - { - imageToSave = d->document->textSelection ()->approximateImage (); - } - else { - Q_ASSERT (!"Unknown selection type"); + } else if (d->document->textSelection()) { + imageToSave = d->document->textSelection()->approximateImage(); + } else { + Q_ASSERT(!"Unknown selection type"); } - kpDocumentSaveOptions chosenSaveOptions; bool allowOverwritePrompt, allowLossyPrompt; - QUrl chosenURL = askForSaveURL (i18nc ("@title:window", "Copy to File"), - d->lastCopyToURL.url (), - imageToSave, - d->lastCopyToSaveOptions, - kpDocumentMetaInfo (), - kpSettingsGroupEditCopyTo, - false/*allow remote files*/, - &chosenSaveOptions, - d->copyToFirstTime, - &allowOverwritePrompt, - &allowLossyPrompt); - - if (chosenURL.isEmpty ()) { + QUrl chosenURL = askForSaveURL(i18nc("@title:window", "Copy to File"), + d->lastCopyToURL.url(), + imageToSave, + d->lastCopyToSaveOptions, + kpDocumentMetaInfo(), + kpSettingsGroupEditCopyTo, + false /*allow remote files*/, + &chosenSaveOptions, + d->copyToFirstTime, + &allowOverwritePrompt, + &allowLossyPrompt); + + if (chosenURL.isEmpty()) { return; } - - if (!kpDocument::savePixmapToFile (imageToSave, - chosenURL, - chosenSaveOptions, kpDocumentMetaInfo (), - allowOverwritePrompt, - allowLossyPrompt, - this)) - { + if (!kpDocument::savePixmapToFile(imageToSave, + chosenURL, + chosenSaveOptions, kpDocumentMetaInfo(), + allowOverwritePrompt, + allowLossyPrompt, + this)) { return; } - - addRecentURL (chosenURL); - + addRecentURL(chosenURL); d->lastCopyToURL = chosenURL; d->lastCopyToSaveOptions = chosenSaveOptions; @@ -895,38 +837,37 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotPasteFromFile () +void kpMainWindow::slotPasteFromFile() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotPasteFromFile()"; #endif - toolEndShape (); - + toolEndShape(); - QList urls = askForOpenURLs(i18nc ("@title:window", "Paste From File"), - false/*only 1 URL*/); + QList urls = askForOpenURLs(i18nc("@title:window", "Paste From File"), + false /*only 1 URL*/); - if (urls.count () != 1) { + if (urls.count() != 1) { return; } - QUrl url = urls.first (); + QUrl url = urls.first(); - kpImage image = kpDocument::getPixmapFromFile (url, - false/*show error message if doesn't exist*/, - this); + kpImage image = kpDocument::getPixmapFromFile(url, + false /*show error message if doesn't exist*/, + this); - if (image.isNull ()) { + if (image.isNull()) { return; } - addRecentURL (url); + addRecentURL(url); - paste (kpRectangularImageSelection ( - QRect (0, 0, image.width (), image.height ()), - image, - imageSelectionTransparency ())); + paste(kpRectangularImageSelection( + QRect(0, 0, image.width(), image.height()), + image, + imageSelectionTransparency())); } //--------------------------------------------------------------------- diff --git a/mainWindow/kpMainWindow_File.cpp b/mainWindow/kpMainWindow_File.cpp --- a/mainWindow/kpMainWindow_File.cpp +++ b/mainWindow/kpMainWindow_File.cpp @@ -26,7 +26,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpMainWindow.h" #include "kpMainWindowPrivate.h" @@ -84,104 +83,105 @@ #endif // HAVE_KSANE // private -void kpMainWindow::setupFileMenuActions () +void kpMainWindow::setupFileMenuActions() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::setupFileMenuActions()"; #endif - KActionCollection *ac = actionCollection (); + KActionCollection *ac = actionCollection(); - d->actionNew = KStandardAction::openNew (this, SLOT (slotNew()), ac); - d->actionOpen = KStandardAction::open (this, SLOT (slotOpen()), ac); + d->actionNew = KStandardAction::openNew(this, SLOT(slotNew()), ac); + d->actionOpen = KStandardAction::open(this, SLOT(slotOpen()), ac); d->actionOpenRecent = KStandardAction::openRecent(this, &kpMainWindow::slotOpenRecent, ac); - connect(d->actionOpenRecent, &KRecentFilesAction::recentListCleared, this, &kpMainWindow::slotRecentListCleared); - d->actionOpenRecent->loadEntries (KSharedConfig::openConfig ()->group (kpSettingsGroupRecentFiles)); + connect(d->actionOpenRecent, &KRecentFilesAction::recentListCleared, this, + &kpMainWindow::slotRecentListCleared); + d->actionOpenRecent->loadEntries(KSharedConfig::openConfig()->group(kpSettingsGroupRecentFiles)); #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\trecent URLs=" << d->actionOpenRecent->items (); + qCDebug(kpLogMainWindow) << "\trecent URLs=" << d->actionOpenRecent->items(); #endif - d->actionSave = KStandardAction::save (this, SLOT (slotSave()), ac); - d->actionSaveAs = KStandardAction::saveAs (this, SLOT (slotSaveAs()), ac); + d->actionSave = KStandardAction::save(this, SLOT(slotSave()), ac); + d->actionSaveAs = KStandardAction::saveAs(this, SLOT(slotSaveAs()), ac); d->actionExport = ac->addAction(QStringLiteral("file_export")); - d->actionExport->setText (i18n ("E&xport...")); + d->actionExport->setText(i18n("E&xport...")); d->actionExport->setIcon(KDE::icon(QStringLiteral("document-export"))); - connect (d->actionExport, &QAction::triggered, this, &kpMainWindow::slotExport); + connect(d->actionExport, &QAction::triggered, this, &kpMainWindow::slotExport); d->actionScan = ac->addAction(QStringLiteral("file_scan")); - d->actionScan->setText(i18n ("Scan...")); + d->actionScan->setText(i18n("Scan...")); d->actionScan->setIcon(SmallIcon("scanner")); #if HAVE_KSANE - connect (d->actionScan, &QAction::triggered, this, &kpMainWindow::slotScan); + connect(d->actionScan, &QAction::triggered, this, &kpMainWindow::slotScan); #else d->actionScan->setEnabled(false); #endif // HAVE_KSANE d->actionScreenshot = ac->addAction(QStringLiteral("file_screenshot")); d->actionScreenshot->setText(i18n("Acquire Screenshot")); - connect (d->actionScreenshot, &QAction::triggered, this, &kpMainWindow::slotScreenshot); + connect(d->actionScreenshot, &QAction::triggered, this, &kpMainWindow::slotScreenshot); - d->actionProperties = ac->addAction (QStringLiteral("file_properties")); - d->actionProperties->setText (i18n ("Properties")); + d->actionProperties = ac->addAction(QStringLiteral("file_properties")); + d->actionProperties->setText(i18n("Properties")); d->actionProperties->setIcon(KDE::icon(QStringLiteral("document-properties"))); - connect (d->actionProperties, &QAction::triggered, this, &kpMainWindow::slotProperties); + connect(d->actionProperties, &QAction::triggered, this, &kpMainWindow::slotProperties); //d->actionRevert = KStandardAction::revert (this, SLOT (slotRevert()), ac); - d->actionReload = ac->addAction (QStringLiteral("file_revert")); - d->actionReload->setText (i18n ("Reloa&d")); + d->actionReload = ac->addAction(QStringLiteral("file_revert")); + d->actionReload->setText(i18n("Reloa&d")); d->actionReload->setIcon(KDE::icon(QStringLiteral("view-refresh"))); - connect (d->actionReload, &QAction::triggered, this, &kpMainWindow::slotReload); - ac->setDefaultShortcuts (d->actionReload, KStandardShortcut::reload ()); - slotEnableReload (); + connect(d->actionReload, &QAction::triggered, this, &kpMainWindow::slotReload); + ac->setDefaultShortcuts(d->actionReload, KStandardShortcut::reload()); + slotEnableReload(); - d->actionPrint = KStandardAction::print (this, SLOT (slotPrint()), ac); - d->actionPrintPreview = KStandardAction::printPreview (this, SLOT (slotPrintPreview()), ac); + d->actionPrint = KStandardAction::print(this, SLOT(slotPrint()), ac); + d->actionPrintPreview = KStandardAction::printPreview(this, SLOT(slotPrintPreview()), ac); - d->actionMail = KStandardAction::mail (this, SLOT (slotMail()), ac); + d->actionMail = KStandardAction::mail(this, SLOT(slotMail()), ac); - d->actionClose = KStandardAction::close (this, SLOT (slotClose()), ac); - d->actionQuit = KStandardAction::quit (this, SLOT (slotQuit()), ac); + d->actionClose = KStandardAction::close(this, SLOT(slotClose()), ac); + d->actionQuit = KStandardAction::quit(this, SLOT(slotQuit()), ac); d->scanDialog = nullptr; - enableFileMenuDocumentActions (false); + enableFileMenuDocumentActions(false); } //--------------------------------------------------------------------- // private -void kpMainWindow::enableFileMenuDocumentActions (bool enable) +void kpMainWindow::enableFileMenuDocumentActions(bool enable) { // d->actionNew // d->actionOpen // d->actionOpenRecent - d->actionSave->setEnabled (enable); - d->actionSaveAs->setEnabled (enable); + d->actionSave->setEnabled(enable); + d->actionSaveAs->setEnabled(enable); - d->actionExport->setEnabled (enable); + d->actionExport->setEnabled(enable); // d->actionScan - d->actionProperties->setEnabled (enable); + d->actionProperties->setEnabled(enable); // d->actionReload - d->actionPrint->setEnabled (enable); - d->actionPrintPreview->setEnabled (enable); + d->actionPrint->setEnabled(enable); + d->actionPrintPreview->setEnabled(enable); - d->actionMail->setEnabled (enable); + d->actionMail->setEnabled(enable); - d->actionClose->setEnabled (enable); + d->actionClose->setEnabled(enable); // d->actionQuit->setEnabled (enable); } //--------------------------------------------------------------------- // private -void kpMainWindow::addRecentURL (const QUrl &url_) +void kpMainWindow::addRecentURL(const QUrl &url_) { // HACK: KRecentFilesAction::loadEntries() clears the KRecentFilesAction::d->urls // map. @@ -198,150 +198,137 @@ #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::addRecentURL(" << url << ")"; #endif - if (url.isEmpty ()) + if (url.isEmpty()) { return; - + } KSharedConfig::Ptr cfg = KSharedConfig::openConfig(); // KConfig::readEntry() does not actually reread from disk, hence doesn't // realize what other processes have done e.g. Settings / Show Path - cfg->reparseConfiguration (); + cfg->reparseConfiguration(); #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\trecent URLs=" << d->actionOpenRecent->items (); + qCDebug(kpLogMainWindow) << "\trecent URLs=" << d->actionOpenRecent->items(); #endif // HACK: Something might have changed interprocess. // If we could PROPAGATE: interprocess, then this wouldn't be required. - d->actionOpenRecent->loadEntries (cfg->group (kpSettingsGroupRecentFiles)); + d->actionOpenRecent->loadEntries(cfg->group(kpSettingsGroupRecentFiles)); #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tafter loading config=" << d->actionOpenRecent->items (); + qCDebug(kpLogMainWindow) << "\tafter loading config=" << d->actionOpenRecent->items(); #endif - d->actionOpenRecent->addUrl (url); + d->actionOpenRecent->addUrl(url); - d->actionOpenRecent->saveEntries (cfg->group (kpSettingsGroupRecentFiles)); - cfg->sync (); + d->actionOpenRecent->saveEntries(cfg->group(kpSettingsGroupRecentFiles)); + cfg->sync(); #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tnew recent URLs=" << d->actionOpenRecent->items (); + qCDebug(kpLogMainWindow) << "\tnew recent URLs=" << d->actionOpenRecent->items(); #endif - // TODO: PROPAGATE: interprocess // TODO: Is this loop safe since a KMainWindow later along in the list, // could be closed as the code in the body almost certainly re-enters // the event loop? Problem for KDE 3 as well, I think. - for (auto *kmw : KMainWindow::memberList ()) - { - Q_ASSERT (dynamic_cast (kmw)); - auto *mw = dynamic_cast (kmw); + for (auto *kmw : KMainWindow::memberList()) { + Q_ASSERT(dynamic_cast (kmw)); + auto *mw = dynamic_cast (kmw); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tmw=" << mw; #endif - if (mw != this) - { + if (mw != this) { // WARNING: Do not use KRecentFilesAction::setItems() // - it does not work since only its superclass, // KSelectAction, implements setItems() and can't // update KRecentFilesAction's URL list. // Avoid URL memory leak in KRecentFilesAction::loadEntries(). - mw->d->actionOpenRecent->clear (); + mw->d->actionOpenRecent->clear(); - mw->d->actionOpenRecent->loadEntries (cfg->group (kpSettingsGroupRecentFiles)); + mw->d->actionOpenRecent->loadEntries(cfg->group(kpSettingsGroupRecentFiles)); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\t\tcheck recent URLs=" - << mw->d->actionOpenRecent->items (); + << mw->d->actionOpenRecent->items(); #endif } } } //--------------------------------------------------------------------- - // private slot // TODO: Disable action if // (d->configOpenImagesInSameWindow && d->document && d->document->isEmpty()) // as it does nothing if this is true. -void kpMainWindow::slotNew () +void kpMainWindow::slotNew() { - toolEndShape (); + toolEndShape(); - if (d->document && !d->configOpenImagesInSameWindow) - { + if (d->document && !d->configOpenImagesInSameWindow) { // A document -- empty or otherwise -- is open. // Force open a new window. In contrast, open() might not open // a new window in this case. - auto *win = new kpMainWindow (); - win->show (); - } - else - { - open (QUrl (), true/*create an empty doc*/); + auto *win = new kpMainWindow(); + win->show(); + } else { + open(QUrl(), true /*create an empty doc*/); } } //--------------------------------------------------------------------- - // private -QSize kpMainWindow::defaultDocSize () const +QSize kpMainWindow::defaultDocSize() const { // KConfig::readEntry() does not actually reread from disk, hence doesn't // realize what other processes have done e.g. Settings / Show Path - KSharedConfig::openConfig ()->reparseConfiguration (); + KSharedConfig::openConfig()->reparseConfiguration(); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupGeneral); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); - QSize docSize = cfg.readEntry (kpSettingLastDocSize, QSize ()); + QSize docSize = cfg.readEntry(kpSettingLastDocSize, QSize()); - if (docSize.isEmpty ()) - { - docSize = QSize (400, 300); - } - else - { + if (docSize.isEmpty()) { + docSize = QSize(400, 300); + } else { // Don't get too big or you'll thrash (or even lock up) the computer // just by opening a window - docSize = QSize (qMin (2048, docSize.width ()), - qMin (2048, docSize.height ())); + docSize = QSize(qMin(2048, docSize.width()), + qMin(2048, docSize.height())); } return docSize; } //--------------------------------------------------------------------- // private -void kpMainWindow::saveDefaultDocSize (const QSize &size) +void kpMainWindow::saveDefaultDocSize(const QSize &size) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tCONFIG: saving Last Doc Size = " << size; #endif - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupGeneral); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); - cfg.writeEntry (kpSettingLastDocSize, size); - cfg.sync (); + cfg.writeEntry(kpSettingLastDocSize, size); + cfg.sync(); } //--------------------------------------------------------------------- // private -bool kpMainWindow::shouldOpen () +bool kpMainWindow::shouldOpen() { - if (d->configOpenImagesInSameWindow) - { + if (d->configOpenImagesInSameWindow) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\topenImagesInSameWindow"; #endif // (this brings up a dialog and might save the current doc) - if (!queryCloseDocument ()) - { + if (!queryCloseDocument()) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tqueryCloseDocument() aborts open"; #endif @@ -355,41 +342,37 @@ //--------------------------------------------------------------------- // private -void kpMainWindow::setDocumentChoosingWindow (kpDocument *doc) +void kpMainWindow::setDocumentChoosingWindow(kpDocument *doc) { // Want new window? - if (d->document && !d->document->isEmpty () && - !d->configOpenImagesInSameWindow) - { + if (d->document && !d->document->isEmpty() + && !d->configOpenImagesInSameWindow) { // Send doc to new window. - auto *win = new kpMainWindow (doc); - win->show (); - } - else - { + auto *win = new kpMainWindow(doc); + win->show(); + } else { // (sets up views, doc signals) - setDocument (doc); + setDocument(doc); } } //--------------------------------------------------------------------- // private -kpDocument *kpMainWindow::openInternal (const QUrl &url, - const QSize &fallbackDocSize, - bool newDocSameNameIfNotExist) +kpDocument *kpMainWindow::openInternal(const QUrl &url, const QSize &fallbackDocSize, + bool newDocSameNameIfNotExist) { // If using OpenImagesInSameWindow mode, ask whether to close the // current document. - if (!shouldOpen ()) + if (!shouldOpen()) { return nullptr; + } // Create/open doc. - auto *newDoc = new kpDocument (fallbackDocSize.width (), - fallbackDocSize.height (), documentEnvironment ()); + auto *newDoc = new kpDocument(fallbackDocSize.width(), + fallbackDocSize.height(), documentEnvironment()); - if (!newDoc->open (url, newDocSameNameIfNotExist)) - { + if (!newDoc->open(url, newDocSameNameIfNotExist)) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\topen failed"; #endif @@ -401,29 +384,29 @@ qCDebug(kpLogMainWindow) << "\topen OK"; #endif // Send document to current or new window. - setDocumentChoosingWindow (newDoc); + setDocumentChoosingWindow(newDoc); return newDoc; } //--------------------------------------------------------------------- // private -bool kpMainWindow::open (const QUrl &url, bool newDocSameNameIfNotExist) +bool kpMainWindow::open(const QUrl &url, bool newDocSameNameIfNotExist) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::open(" << url - << ",newDocSameNameIfNotExist=" << newDocSameNameIfNotExist - << ")"; + << ",newDocSameNameIfNotExist=" << newDocSameNameIfNotExist + << ")"; #endif - kpDocument *newDoc = openInternal (url, - defaultDocSize (), - newDocSameNameIfNotExist); - if (newDoc) - { - if (newDoc->isFromURL (false/*don't bother checking exists*/)) - addRecentURL (url); + kpDocument *newDoc = openInternal(url, + defaultDocSize(), + newDocSameNameIfNotExist); + if (newDoc) { + if (newDoc->isFromURL(false /*don't bother checking exists*/)) { + addRecentURL(url); + } return true; } @@ -435,76 +418,73 @@ // private QList kpMainWindow::askForOpenURLs(const QString &caption, bool allowMultipleURLs) { - QMimeDatabase db; - QStringList filterList; - QString filter; - for (const auto &type : QImageReader::supportedMimeTypes()) - { - if ( !filter.isEmpty() ) { - filter += QLatin1Char(' '); - } + QMimeDatabase db; + QStringList filterList; + QString filter; + for (const auto &type : QImageReader::supportedMimeTypes()) { + if (!filter.isEmpty()) { + filter += QLatin1Char(' '); + } - QMimeType mime(db.mimeTypeForName(QString::fromLatin1(type))); - if ( mime.isValid() ) - { - QString glob = mime.globPatterns().join(QLatin1Char(' ')); + QMimeType mime(db.mimeTypeForName(QString::fromLatin1(type))); + if (mime.isValid()) { + QString glob = mime.globPatterns().join(QLatin1Char(' ')); - filter += glob; + filter += glob; - // I want to show the mime comment AND the file glob pattern, - // but to avoid that the "All Supported Files" entry shows ALL glob patterns, - // I must add the pattern here a second time so that QFileDialog::HideNameFilterDetails - // can hide the first pattern and I still see the second one - filterList << mime.comment() + QStringLiteral(" (%1)(%2)").arg(glob).arg(glob); + // I want to show the mime comment AND the file glob pattern, + // but to avoid that the "All Supported Files" entry shows ALL glob patterns, + // I must add the pattern here a second time so that QFileDialog::HideNameFilterDetails + // can hide the first pattern and I still see the second one + filterList << mime.comment() + QStringLiteral(" (%1)(%2)").arg(glob).arg(glob); + } } - } - filterList.prepend(i18n("All Supported Files (%1)", filter)); + filterList.prepend(i18n("All Supported Files (%1)", filter)); - QFileDialog fd(this); - fd.setNameFilters(filterList); - fd.setOption(QFileDialog::HideNameFilterDetails); - fd.setWindowTitle(caption); + QFileDialog fd(this); + fd.setNameFilters(filterList); + fd.setOption(QFileDialog::HideNameFilterDetails); + fd.setWindowTitle(caption); - if ( allowMultipleURLs ) { - fd.setFileMode(QFileDialog::ExistingFiles); - } + if (allowMultipleURLs) { + fd.setFileMode(QFileDialog::ExistingFiles); + } - if ( fd.exec() ) { - return fd.selectedUrls(); - } + if (fd.exec()) { + return fd.selectedUrls(); + } - return {}; + return {}; } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotOpen () +void kpMainWindow::slotOpen() { - toolEndShape (); + toolEndShape(); const QList urls = askForOpenURLs(i18nc("@title:window", "Open Image")); - for (const auto & url : urls) - { - open (url); + for (const auto &url : urls) { + open(url); } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotOpenRecent (const QUrl &url) +void kpMainWindow::slotOpenRecent(const QUrl &url) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotOpenRecent(" << url << ")"; - qCDebug(kpLogMainWindow) << "\titems=" << d->actionOpenRecent->items (); + qCDebug(kpLogMainWindow) << "\titems=" << d->actionOpenRecent->items(); #endif - toolEndShape (); + toolEndShape(); - open (url); + open(url); // If the open is successful, addRecentURL() would have bubbled up the // URL in the File / Open Recent action. As a side effect, the URL is @@ -516,49 +496,46 @@ // // 2. because it has not been opened. // - d->actionOpenRecent->setCurrentItem (-1); + d->actionOpenRecent->setCurrentItem(-1); } //--------------------------------------------------------------------- void kpMainWindow::slotRecentListCleared() { - d->actionOpenRecent->saveEntries(KSharedConfig::openConfig()->group(kpSettingsGroupRecentFiles)); + d->actionOpenRecent->saveEntries(KSharedConfig::openConfig()->group(kpSettingsGroupRecentFiles)); } //--------------------------------------------------------------------- #if HAVE_KSANE // private slot -void kpMainWindow::slotScan () +void kpMainWindow::slotScan() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotScan() scanDialog=" << d->scanDialog; #endif - toolEndShape (); + toolEndShape(); - if (!d->scanDialog) - { + if (!d->scanDialog) { // Create scan dialog d->scanDialog = new SaneDialog(this); // No scanning support (kdegraphics/libkscan) installed? - if (!d->scanDialog) - { - KMessageBox::sorry (this, - i18n("Failed to open scanning dialog."), - i18nc("@title:window", "Scanning Failed")); + if (!d->scanDialog) { + KMessageBox::sorry(this, + i18n("Failed to open scanning dialog."), + i18nc("@title:window", "Scanning Failed")); return; } #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tcreated scanDialog=" << d->scanDialog; #endif - connect (d->scanDialog, &SaneDialog::finalImage, this, &kpMainWindow::slotScanned); + connect(d->scanDialog, &SaneDialog::finalImage, this, &kpMainWindow::slotScanned); } - // If using OpenImagesInSameWindow mode, ask whether to close the // current document. // @@ -573,19 +550,17 @@ // scan dialogs are shown. We don't do this between KScanDialog::setup() // and KScanDialog::exec() as it could be confusing alternating between // scanning and KolourPaint dialogs. - if (!shouldOpen ()) { + if (!shouldOpen()) { return; } - #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tcalling setup"; #endif // Bring up dialog to select scan device. // If there is no scanner, we find that this does not bring up a dialog // but still returns true. - if (d->scanDialog->setup ()) - { + if (d->scanDialog->setup()) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tOK - showing dialog"; #endif @@ -596,10 +571,8 @@ // // We use exec() to make sure it's modal. show() seems to work too // but better safe than sorry. - d->scanDialog->exec (); - } - else - { + d->scanDialog->exec(); + } else { // Have never seen this code path execute even if "Cancel" is pressed. #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tFAIL"; @@ -610,10 +583,10 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotScanned (const QImage &image, int) +void kpMainWindow::slotScanned(const QImage &image, int) { #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "kpMainWindow::slotScanned() image.rect=" << image.rect (); + qCDebug(kpLogMainWindow) << "kpMainWindow::slotScanned() image.rect=" << image.rect(); #endif #if DEBUG_KP_MAIN_WINDOW @@ -627,12 +600,11 @@ // // 2. We don't want to return from this method but forget to close // the dialog. So do it before anything else. - d->scanDialog->hide (); + d->scanDialog->hide(); // (just in case there's some drawing between slotScan() exiting and // us being called) - toolEndShape (); - + toolEndShape(); // TODO: Maybe this code should be moved into kpdocument.cpp - // since it resembles the responsibilities of kpDocument::open(). @@ -643,115 +615,112 @@ kpDocument::getDataFromImage(image, saveOptions, metaInfo); // Create document from image and meta info. - auto *doc = new kpDocument (image.width (), image.height (), documentEnvironment ()); - doc->setImage (image); - doc->setSaveOptions (saveOptions); - doc->setMetaInfo (metaInfo); + auto *doc = new kpDocument(image.width(), image.height(), documentEnvironment()); + doc->setImage(image); + doc->setSaveOptions(saveOptions); + doc->setMetaInfo(metaInfo); // Send document to current or new window. - setDocumentChoosingWindow (doc); + setDocumentChoosingWindow(doc); } + #endif // HAVE_KSANE //--------------------------------------------------------------------- void kpMainWindow::slotScreenshot() { - toolEndShape(); - - auto *dialog = new QDialog(this); - auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | - QDialogButtonBox::Cancel, dialog); - connect (buttons, &QDialogButtonBox::accepted, dialog, &QDialog::accept); - connect (buttons, &QDialogButtonBox::rejected, dialog, &QDialog::reject); - - auto *label = new QLabel(i18n("Snapshot Delay")); - auto *seconds = new KPluralHandlingSpinBox; - seconds->setRange(0, 99); - seconds->setSuffix(ki18np(" second", " seconds")); - seconds->setSpecialValueText(i18n("No delay")); - - auto *hideWindow = new QCheckBox(i18n("Hide Main Window")); - hideWindow->setChecked(true); - - auto *vbox = new QVBoxLayout(dialog); - vbox->addWidget(label); - vbox->addWidget(seconds); - vbox->addWidget(hideWindow); - vbox->addWidget(buttons); - - if ( dialog->exec() == QDialog::Rejected ) - { - delete dialog; - return; - } + toolEndShape(); + + auto *dialog = new QDialog(this); + auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok + |QDialogButtonBox::Cancel, dialog); + connect(buttons, &QDialogButtonBox::accepted, dialog, &QDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, dialog, &QDialog::reject); + + auto *label = new QLabel(i18n("Snapshot Delay")); + auto *seconds = new KPluralHandlingSpinBox; + seconds->setRange(0, 99); + seconds->setSuffix(ki18np(" second", " seconds")); + seconds->setSpecialValueText(i18n("No delay")); + + auto *hideWindow = new QCheckBox(i18n("Hide Main Window")); + hideWindow->setChecked(true); + + auto *vbox = new QVBoxLayout(dialog); + vbox->addWidget(label); + vbox->addWidget(seconds); + vbox->addWidget(hideWindow); + vbox->addWidget(buttons); + + if (dialog->exec() == QDialog::Rejected) { + delete dialog; + return; + } - if ( hideWindow->isChecked() ) { - hide(); - } + if (hideWindow->isChecked()) { + hide(); + } - // at least 1 seconds to make sure the window is hidden and the hide effect already stopped - QTimer::singleShot((seconds->value() + 1) * 1000, this, &kpMainWindow::slotMakeScreenshot); + // at least 1 seconds to make sure the window is hidden and the hide effect already stopped + QTimer::singleShot((seconds->value() + 1) * 1000, this, &kpMainWindow::slotMakeScreenshot); - delete dialog; + delete dialog; } //--------------------------------------------------------------------- void kpMainWindow::slotMakeScreenshot() { - QCoreApplication::processEvents(); - QPixmap pixmap = QGuiApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId()); + QCoreApplication::processEvents(); + QPixmap pixmap = QGuiApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId()); - auto *doc = new kpDocument(pixmap.width(), pixmap.height(), documentEnvironment()); - doc->setImage(pixmap.toImage()); + auto *doc = new kpDocument(pixmap.width(), pixmap.height(), documentEnvironment()); + doc->setImage(pixmap.toImage()); - // Send document to current or new window. - setDocumentChoosingWindow(doc); + // Send document to current or new window. + setDocumentChoosingWindow(doc); - show(); // in case we hid the mainwindow, show it again + show(); // in case we hid the mainwindow, show it again } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotProperties () +void kpMainWindow::slotProperties() { - toolEndShape (); + toolEndShape(); - kpDocumentMetaInfoDialog dialog (document ()->metaInfo (), this); + kpDocumentMetaInfoDialog dialog(document()->metaInfo(), this); - if (dialog.exec () && !dialog.isNoOp ()) - { - commandHistory ()->addCommand ( - new kpDocumentMetaInfoCommand ( - i18n ("Document Properties"), - dialog.metaInfo ()/*new*/, *document ()->metaInfo ()/*old*/, - commandEnvironment ())); + if (dialog.exec() && !dialog.isNoOp()) { + commandHistory()->addCommand( + new kpDocumentMetaInfoCommand( + i18n("Document Properties"), + dialog.metaInfo() /*new*/, *document()->metaInfo() /*old*/, + commandEnvironment())); } } //--------------------------------------------------------------------- // private slot -bool kpMainWindow::save (bool localOnly) +bool kpMainWindow::save(bool localOnly) { - if (d->document->url ().isEmpty () || - !QImageWriter::supportedMimeTypes() - .contains(d->document->saveOptions ()->mimeType().toLatin1()) || - // SYNC: kpDocument::getPixmapFromFile() can't determine quality - // from file so it has been set initially to an invalid value. - (d->document->saveOptions ()->mimeTypeHasConfigurableQuality () && - d->document->saveOptions ()->qualityIsInvalid ()) || - (localOnly && !d->document->url ().isLocalFile ())) - { - return saveAs (localOnly); + if (d->document->url().isEmpty() + || !QImageWriter::supportedMimeTypes() + .contains(d->document->saveOptions()->mimeType().toLatin1()) + ||// SYNC: kpDocument::getPixmapFromFile() can't determine quality + // from file so it has been set initially to an invalid value. + (d->document->saveOptions()->mimeTypeHasConfigurableQuality() + && d->document->saveOptions()->qualityIsInvalid()) + || (localOnly && !d->document->url().isLocalFile())) { + return saveAs(localOnly); } - if (d->document->save (false/*no overwrite prompt*/, - !d->document->savedAtLeastOnceBefore ()/*lossy prompt*/)) - { - addRecentURL (d->document->url ()); + if (d->document->save(false /*no overwrite prompt*/, + !d->document->savedAtLeastOnceBefore() /*lossy prompt*/)) { + addRecentURL(d->document->url()); return true; } @@ -761,31 +730,28 @@ //--------------------------------------------------------------------- // private slot -bool kpMainWindow::slotSave () +bool kpMainWindow::slotSave() { - toolEndShape (); + toolEndShape(); - return save (); + return save(); } //--------------------------------------------------------------------- // private -QUrl kpMainWindow::askForSaveURL (const QString &caption, - const QString &startURL, - const kpImage &imageToBeSaved, - const kpDocumentSaveOptions &startSaveOptions, - const kpDocumentMetaInfo &docMetaInfo, - const QString &forcedSaveOptionsGroup, - bool localOnly, - kpDocumentSaveOptions *chosenSaveOptions, - bool isSavingForFirstTime, - bool *allowOverwritePrompt, - bool *allowLossyPrompt) +QUrl kpMainWindow::askForSaveURL(const QString &caption, const QString &startURL, + const kpImage &imageToBeSaved, + const kpDocumentSaveOptions &startSaveOptions, + const kpDocumentMetaInfo &docMetaInfo, + const QString &forcedSaveOptionsGroup, bool localOnly, + kpDocumentSaveOptions *chosenSaveOptions, + bool isSavingForFirstTime, bool *allowOverwritePrompt, + bool *allowLossyPrompt) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::askForURL() startURL=" << startURL; - startSaveOptions.printDebug ("\tstartSaveOptions"); + startSaveOptions.printDebug("\tstartSaveOptions"); #endif bool reparsedConfiguration = false; @@ -796,15 +762,14 @@ #define SETUP_READ_CFG() \ if (!reparsedConfiguration) \ { \ - KSharedConfig::openConfig ()->reparseConfiguration (); \ + KSharedConfig::openConfig()->reparseConfiguration(); \ reparsedConfiguration = true; \ } \ \ - KConfigGroup cfg (KSharedConfig::openConfig (), forcedSaveOptionsGroup); - + KConfigGroup cfg(KSharedConfig::openConfig(), forcedSaveOptionsGroup); if (chosenSaveOptions) { - *chosenSaveOptions = kpDocumentSaveOptions (); + *chosenSaveOptions = kpDocumentSaveOptions(); } if (allowOverwritePrompt) { @@ -815,147 +780,132 @@ *allowLossyPrompt = true; // play it safe for now } - kpDocumentSaveOptions fdSaveOptions = startSaveOptions; QStringList mimeTypes; for (const auto &type : QImageWriter::supportedMimeTypes()) { - mimeTypes << QString::fromLatin1(type); + mimeTypes << QString::fromLatin1(type); } #if DEBUG_KP_MAIN_WINDOW QStringList sortedMimeTypes = mimeTypes; - sortedMimeTypes.sort (); + sortedMimeTypes.sort(); qCDebug(kpLogMainWindow) << "\tmimeTypes=" << mimeTypes - << "\tsortedMimeTypes=" << sortedMimeTypes; + << "\tsortedMimeTypes=" << sortedMimeTypes; #endif - if (mimeTypes.isEmpty ()) - { + if (mimeTypes.isEmpty()) { qCCritical(kpLogMainWindow) << "No output mimetypes!"; return {}; } -#define MIME_TYPE_IS_VALID() (!fdSaveOptions.mimeTypeIsInvalid () && \ - mimeTypes.contains (fdSaveOptions.mimeType ())) - if (!MIME_TYPE_IS_VALID ()) - { +#define MIME_TYPE_IS_VALID() (!fdSaveOptions.mimeTypeIsInvalid() \ + && mimeTypes.contains(fdSaveOptions.mimeType())) + if (!MIME_TYPE_IS_VALID()) { #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tmimeType=" << fdSaveOptions.mimeType () - << " not valid, get default"; + qCDebug(kpLogMainWindow) << "\tmimeType=" << fdSaveOptions.mimeType() + << " not valid, get default"; #endif - SETUP_READ_CFG (); + SETUP_READ_CFG(); - fdSaveOptions.setMimeType (kpDocumentSaveOptions::defaultMimeType (cfg)); + fdSaveOptions.setMimeType(kpDocumentSaveOptions::defaultMimeType(cfg)); - - if (!MIME_TYPE_IS_VALID ()) - { + if (!MIME_TYPE_IS_VALID()) { #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tmimeType=" << fdSaveOptions.mimeType () - << " not valid, get hardcoded"; + qCDebug(kpLogMainWindow) << "\tmimeType=" << fdSaveOptions.mimeType() + << " not valid, get hardcoded"; #endif if (mimeTypes.contains(QLatin1String("image/png"))) { - fdSaveOptions.setMimeType (QStringLiteral("image/png")); - } - else if (mimeTypes.contains(QLatin1String("image/bmp"))) { - fdSaveOptions.setMimeType (QStringLiteral("image/bmp")); - } - else { - fdSaveOptions.setMimeType (mimeTypes.first ()); + fdSaveOptions.setMimeType(QStringLiteral("image/png")); + } else if (mimeTypes.contains(QLatin1String("image/bmp"))) { + fdSaveOptions.setMimeType(QStringLiteral("image/bmp")); + } else { + fdSaveOptions.setMimeType(mimeTypes.first()); } } } #undef MIME_TYPE_IS_VALID - if (fdSaveOptions.colorDepthIsInvalid ()) - { - SETUP_READ_CFG (); + if (fdSaveOptions.colorDepthIsInvalid()) { + SETUP_READ_CFG(); - fdSaveOptions.setColorDepth (kpDocumentSaveOptions::defaultColorDepth (cfg)); - fdSaveOptions.setDither (kpDocumentSaveOptions::defaultDither (cfg)); + fdSaveOptions.setColorDepth(kpDocumentSaveOptions::defaultColorDepth(cfg)); + fdSaveOptions.setDither(kpDocumentSaveOptions::defaultDither(cfg)); } - if (fdSaveOptions.qualityIsInvalid ()) - { - SETUP_READ_CFG (); + if (fdSaveOptions.qualityIsInvalid()) { + SETUP_READ_CFG(); - fdSaveOptions.setQuality (kpDocumentSaveOptions::defaultQuality (cfg)); + fdSaveOptions.setQuality(kpDocumentSaveOptions::defaultQuality(cfg)); } #if DEBUG_KP_MAIN_WINDOW - fdSaveOptions.printDebug ("\tcorrected saveOptions passed to fileDialog"); + fdSaveOptions.printDebug("\tcorrected saveOptions passed to fileDialog"); #endif - auto *saveOptionsWidget = - new kpDocumentSaveOptionsWidget (imageToBeSaved, - fdSaveOptions, - docMetaInfo, - this); - - KFileDialog fd (QUrl (startURL), QString(), this, - saveOptionsWidget); - saveOptionsWidget->setVisualParent (&fd); - fd.setWindowTitle (caption); - fd.setOperationMode (KFileDialog::Saving); - fd.setMimeFilter (mimeTypes, fdSaveOptions.mimeType ()); + auto *saveOptionsWidget + = new kpDocumentSaveOptionsWidget(imageToBeSaved, + fdSaveOptions, + docMetaInfo, + this); + + KFileDialog fd(QUrl(startURL), QString(), this, + saveOptionsWidget); + saveOptionsWidget->setVisualParent(&fd); + fd.setWindowTitle(caption); + fd.setOperationMode(KFileDialog::Saving); + fd.setMimeFilter(mimeTypes, fdSaveOptions.mimeType()); if (localOnly) { - fd.setMode (KFile::File | KFile::LocalOnly); + fd.setMode(KFile::File | KFile::LocalOnly); } - connect (&fd, &KFileDialog::filterChanged, - saveOptionsWidget, &kpDocumentSaveOptionsWidget::setMimeType); + connect(&fd, &KFileDialog::filterChanged, + saveOptionsWidget, &kpDocumentSaveOptionsWidget::setMimeType); - if ( fd.exec() == QDialog::Accepted ) - { - kpDocumentSaveOptions newSaveOptions = saveOptionsWidget->documentSaveOptions (); + if (fd.exec() == QDialog::Accepted) { + kpDocumentSaveOptions newSaveOptions = saveOptionsWidget->documentSaveOptions(); #if DEBUG_KP_MAIN_WINDOW - newSaveOptions.printDebug ("\tnewSaveOptions"); + newSaveOptions.printDebug("\tnewSaveOptions"); #endif - KConfigGroup cfg (KSharedConfig::openConfig (), forcedSaveOptionsGroup); + KConfigGroup cfg(KSharedConfig::openConfig(), forcedSaveOptionsGroup); // Save options user forced - probably want to use them in future - kpDocumentSaveOptions::saveDefaultDifferences (cfg, - fdSaveOptions, newSaveOptions); - cfg.sync (); - + kpDocumentSaveOptions::saveDefaultDifferences(cfg, + fdSaveOptions, newSaveOptions); + cfg.sync(); if (chosenSaveOptions) { *chosenSaveOptions = newSaveOptions; } - - bool shouldAllowOverwritePrompt = - (fd.selectedUrl () != QUrl (startURL) || - newSaveOptions.mimeType () != startSaveOptions.mimeType ()); - if (allowOverwritePrompt) - { + bool shouldAllowOverwritePrompt + = (fd.selectedUrl() != QUrl(startURL) + || newSaveOptions.mimeType() != startSaveOptions.mimeType()); + if (allowOverwritePrompt) { *allowOverwritePrompt = shouldAllowOverwritePrompt; #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tallowOverwritePrompt=" << *allowOverwritePrompt; #endif } - if (allowLossyPrompt) - { + if (allowLossyPrompt) { // SYNC: kpDocumentSaveOptions elements - everything except quality // (one quality setting is "just as lossy" as another so no // need to continually warn due to quality change) - *allowLossyPrompt = - (isSavingForFirstTime || - shouldAllowOverwritePrompt || - newSaveOptions.mimeType () != startSaveOptions.mimeType () || - newSaveOptions.colorDepth () != startSaveOptions.colorDepth () || - newSaveOptions.dither () != startSaveOptions.dither ()); + *allowLossyPrompt + = (isSavingForFirstTime + || shouldAllowOverwritePrompt + || newSaveOptions.mimeType() != startSaveOptions.mimeType() + || newSaveOptions.colorDepth() != startSaveOptions.colorDepth() + || newSaveOptions.dither() != startSaveOptions.dither()); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tallowLossyPrompt=" << *allowLossyPrompt; #endif } - #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tselectedUrl=" << fd.selectedUrl (); + qCDebug(kpLogMainWindow) << "\tselectedUrl=" << fd.selectedUrl(); #endif - return fd.selectedUrl (); + return fd.selectedUrl(); } return {}; @@ -965,89 +915,82 @@ //--------------------------------------------------------------------- // private slot -bool kpMainWindow::saveAs (bool localOnly) +bool kpMainWindow::saveAs(bool localOnly) { kpDocumentSaveOptions chosenSaveOptions; bool allowOverwritePrompt, allowLossyPrompt; - QUrl chosenURL = askForSaveURL (i18nc ("@title:window", "Save Image As"), - d->document->url ().url (), - d->document->imageWithSelection (), - *d->document->saveOptions (), - *d->document->metaInfo (), - kpSettingsGroupFileSaveAs, - localOnly, - &chosenSaveOptions, - !d->document->savedAtLeastOnceBefore (), - &allowOverwritePrompt, - &allowLossyPrompt); - - - if (chosenURL.isEmpty ()) { + QUrl chosenURL = askForSaveURL(i18nc("@title:window", "Save Image As"), + d->document->url().url(), + d->document->imageWithSelection(), + *d->document->saveOptions(), + *d->document->metaInfo(), + kpSettingsGroupFileSaveAs, + localOnly, + &chosenSaveOptions, + !d->document->savedAtLeastOnceBefore(), + &allowOverwritePrompt, + &allowLossyPrompt); + + if (chosenURL.isEmpty()) { return false; } - - if (!d->document->saveAs (chosenURL, chosenSaveOptions, + if (!d->document->saveAs(chosenURL, chosenSaveOptions, allowOverwritePrompt, - allowLossyPrompt)) - { + allowLossyPrompt)) { return false; } - - addRecentURL (chosenURL); + addRecentURL(chosenURL); return true; } //--------------------------------------------------------------------- // private slot -bool kpMainWindow::slotSaveAs () +bool kpMainWindow::slotSaveAs() { - toolEndShape (); + toolEndShape(); - return saveAs (); + return saveAs(); } //--------------------------------------------------------------------- // private slot -bool kpMainWindow::slotExport () +bool kpMainWindow::slotExport() { - toolEndShape (); + toolEndShape(); kpDocumentSaveOptions chosenSaveOptions; bool allowOverwritePrompt, allowLossyPrompt; - QUrl chosenURL = askForSaveURL (i18nc ("@title:window", "Export"), - d->lastExportURL.url (), - d->document->imageWithSelection (), - d->lastExportSaveOptions, - *d->document->metaInfo (), - kpSettingsGroupFileExport, - false/*allow remote files*/, - &chosenSaveOptions, - d->exportFirstTime, - &allowOverwritePrompt, - &allowLossyPrompt); - - - if (chosenURL.isEmpty ()) { + QUrl chosenURL = askForSaveURL(i18nc("@title:window", "Export"), + d->lastExportURL.url(), + d->document->imageWithSelection(), + d->lastExportSaveOptions, + *d->document->metaInfo(), + kpSettingsGroupFileExport, + false /*allow remote files*/, + &chosenSaveOptions, + d->exportFirstTime, + &allowOverwritePrompt, + &allowLossyPrompt); + + if (chosenURL.isEmpty()) { return false; } - if (!kpDocument::savePixmapToFile (d->document->imageWithSelection (), - chosenURL, - chosenSaveOptions, *d->document->metaInfo (), - allowOverwritePrompt, - allowLossyPrompt, - this)) - { + if (!kpDocument::savePixmapToFile(d->document->imageWithSelection(), + chosenURL, + chosenSaveOptions, *d->document->metaInfo(), + allowOverwritePrompt, + allowLossyPrompt, + this)) { return false; } - - addRecentURL (chosenURL); + addRecentURL(chosenURL); d->lastExportURL = chosenURL; d->lastExportSaveOptions = chosenSaveOptions; @@ -1060,150 +1003,137 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotEnableReload () +void kpMainWindow::slotEnableReload() { - d->actionReload->setEnabled (d->document); + d->actionReload->setEnabled(d->document); } //--------------------------------------------------------------------- // private slot -bool kpMainWindow::slotReload () +bool kpMainWindow::slotReload() { - toolEndShape (); + toolEndShape(); - Q_ASSERT (d->document); + Q_ASSERT(d->document); + QUrl oldURL = d->document->url(); - QUrl oldURL = d->document->url (); - - - if (d->document->isModified ()) - { + if (d->document->isModified()) { int result = KMessageBox::Cancel; - if (d->document->isFromURL (false/*don't bother checking exists*/) && !oldURL.isEmpty ()) - { - result = KMessageBox::warningContinueCancel (this, - i18n ("The document \"%1\" has been modified.\n" - "Reloading will lose all changes since you last saved it.\n" - "Are you sure?", - d->document->prettyFilename ()), - QString()/*caption*/, - KGuiItem(i18n ("&Reload"))); - } - else - { - result = KMessageBox::warningContinueCancel (this, - i18n ("The document \"%1\" has been modified.\n" - "Reloading will lose all changes.\n" - "Are you sure?", - d->document->prettyFilename ()), - QString()/*caption*/, - KGuiItem(i18n ("&Reload"))); + if (d->document->isFromURL(false /*don't bother checking exists*/) && !oldURL.isEmpty()) { + result = KMessageBox::warningContinueCancel(this, + i18n( + "The document \"%1\" has been modified.\n" + "Reloading will lose all changes since you last saved it.\n" + "Are you sure?", + d->document->prettyFilename()), + QString() /*caption*/, + KGuiItem(i18n("&Reload"))); + } else { + result = KMessageBox::warningContinueCancel(this, + i18n( + "The document \"%1\" has been modified.\n" + "Reloading will lose all changes.\n" + "Are you sure?", + d->document->prettyFilename()), + QString() /*caption*/, + KGuiItem(i18n("&Reload"))); } if (result != KMessageBox::Continue) { return false; } } - kpDocument *doc = nullptr; // If it's _supposed to_ come from a URL or it exists - if (d->document->isFromURL (false/*don't bother checking exists*/) || - (!oldURL.isEmpty () && KIO::NetAccess::exists (oldURL, KIO::NetAccess::SourceSide/*open*/, this))) - { + if (d->document->isFromURL(false /*don't bother checking exists*/) + || (!oldURL.isEmpty() + && KIO::NetAccess::exists(oldURL, KIO::NetAccess::SourceSide /*open*/, this))) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotReload() reloading from disk!"; #endif - doc = new kpDocument (1, 1, documentEnvironment ()); - if (!doc->open (oldURL)) - { - delete doc; doc = nullptr; + doc = new kpDocument(1, 1, documentEnvironment()); + if (!doc->open(oldURL)) { + delete doc; + doc = nullptr; return false; } - addRecentURL (oldURL); - } - else - { + addRecentURL(oldURL); + } else { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotReload() create doc"; #endif - doc = new kpDocument (d->document->constructorWidth (), - d->document->constructorHeight (), - documentEnvironment ()); - doc->setURL (oldURL, false/*not from URL*/); + doc = new kpDocument(d->document->constructorWidth(), + d->document->constructorHeight(), + documentEnvironment()); + doc->setURL(oldURL, false /*not from URL*/); } - - setDocument (doc); + setDocument(doc); return true; } - // private -void kpMainWindow::sendDocumentNameToPrinter (QPrinter *printer) +void kpMainWindow::sendDocumentNameToPrinter(QPrinter *printer) { - QUrl url = d->document->url (); - if (!url.isEmpty ()) - { + QUrl url = d->document->url(); + if (!url.isEmpty()) { int dot; - QString fileName = url.fileName (); - dot = fileName.lastIndexOf ('.'); + QString fileName = url.fileName(); + dot = fileName.lastIndexOf('.'); // file.ext but not .hidden-file? if (dot > 0) { - fileName.truncate (dot); + fileName.truncate(dot); } #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::sendDocumentNameToPrinter() fileName=" - << fileName - << " dir=" - << url.path(); + << fileName + << " dir=" + << url.path(); #endif - printer->setDocName (fileName); + printer->setDocName(fileName); } } //-------------------------------------------------------------------------------- void kpMainWindow::sendPreviewToPrinter(QPrinter *printer) { - sendImageToPrinter(printer, false); + sendImageToPrinter(printer, false); } //-------------------------------------------------------------------------------- // private -void kpMainWindow::sendImageToPrinter (QPrinter *printer, - bool showPrinterSetupDialog) +void kpMainWindow::sendImageToPrinter(QPrinter *printer, bool showPrinterSetupDialog) { // Get image to be printed. - kpImage image = d->document->imageWithSelection (); - + kpImage image = d->document->imageWithSelection(); // Get image DPI. - auto imageDotsPerMeterX = double (d->document->metaInfo ()->dotsPerMeterX ()); - auto imageDotsPerMeterY = double (d->document->metaInfo ()->dotsPerMeterY ()); + auto imageDotsPerMeterX = double(d->document->metaInfo()->dotsPerMeterX()); + auto imageDotsPerMeterY = double(d->document->metaInfo()->dotsPerMeterY()); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::sendImageToPrinter() image:" - << " width=" << image.width () - << " height=" << image.height () - << " dotsPerMeterX=" << imageDotsPerMeterX - << " dotsPerMeterY=" << imageDotsPerMeterY; + << " width=" << image.width() + << " height=" << image.height() + << " dotsPerMeterX=" << imageDotsPerMeterX + << " dotsPerMeterY=" << imageDotsPerMeterY; #endif // Image DPI invalid (e.g. new image, could not read from file // or Qt3 doesn't implement DPI for JPEG)? - if (imageDotsPerMeterX <= 0 || imageDotsPerMeterY <= 0) - { + if (imageDotsPerMeterX <= 0 || imageDotsPerMeterY <= 0) { // Even if just one DPI dimension is invalid, mutate both DPI // dimensions as we have no information about the intended // aspect ratio anyway (and other dimension likely to be invalid). @@ -1227,132 +1157,124 @@ // TODO: mysteriously, someone else is setting this to 96dpi always. QPixmap arbitraryScreenElement(1, 1); const QPaintDevice *screenDevice = &arbitraryScreenElement; - const auto dpiX = screenDevice->logicalDpiX (); - const auto dpiY = screenDevice->logicalDpiY (); + const auto dpiX = screenDevice->logicalDpiX(); + const auto dpiY = screenDevice->logicalDpiY(); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tusing screen dpi: x=" << dpiX << " y=" << dpiY; #endif imageDotsPerMeterX = dpiX * KP_INCHES_PER_METER; imageDotsPerMeterY = dpiY * KP_INCHES_PER_METER; } - // Get page size (excluding margins). // Coordinate (0,0) is the X here: // mmmmm // mX m // m m m = margin // m m // mmmmm - const auto printerWidthMM = printer->widthMM (); - const auto printerHeightMM = printer->heightMM (); + const auto printerWidthMM = printer->widthMM(); + const auto printerHeightMM = printer->heightMM(); auto dpiX = imageDotsPerMeterX / KP_INCHES_PER_METER; auto dpiY = imageDotsPerMeterY / KP_INCHES_PER_METER; #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tprinter: widthMM=" << printerWidthMM - << " heightMM=" << printerHeightMM; + << " heightMM=" << printerHeightMM; qCDebug(kpLogMainWindow) << "\timage: dpiX=" << dpiX << " dpiY=" << dpiY; #endif - // // If image doesn't fit on page at intended DPI, change the DPI. // - const auto scaleDpiX = - (image.width () / (printerWidthMM / KP_MILLIMETERS_PER_INCH)) / dpiX; - const auto scaleDpiY = - (image.height () / (printerHeightMM / KP_MILLIMETERS_PER_INCH)) / dpiY; - const auto scaleDpi = qMax (scaleDpiX, scaleDpiY); + const auto scaleDpiX + = (image.width() / (printerWidthMM / KP_MILLIMETERS_PER_INCH)) / dpiX; + const auto scaleDpiY + = (image.height() / (printerHeightMM / KP_MILLIMETERS_PER_INCH)) / dpiY; + const auto scaleDpi = qMax(scaleDpiX, scaleDpiY); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tscaleDpi: x=" << scaleDpiX << " y=" << scaleDpiY - << " --> scale at " << scaleDpi << " to fit?"; + << " --> scale at " << scaleDpi << " to fit?"; #endif // Need to increase resolution to fit page? - if (scaleDpi > 1.0) - { + if (scaleDpi > 1.0) { dpiX *= scaleDpi; dpiY *= scaleDpi; #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\t\tto fit page, scaled to:" - << " dpiX=" << dpiX << " dpiY=" << dpiY; + << " dpiX=" << dpiX << " dpiY=" << dpiY; #endif } - // Make sure DPIs are equal as that's all QPrinter::setResolution() // supports. We do this in such a way that we only ever stretch an // image, to avoid losing information. Don't antialias as the printer // will do that to translate our DPI to its physical resolution and // double-antialiasing looks bad. - if (dpiX > dpiY) - { + if (dpiX > dpiY) { #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tdpiX > dpiY; stretching image height to equalise DPIs to dpiX=" - << dpiX; + qCDebug(kpLogMainWindow) + << + "\tdpiX > dpiY; stretching image height to equalise DPIs to dpiX=" + << dpiX; #endif - kpPixmapFX::scale (&image, - image.width (), - qMax (1, qRound (image.height () * dpiX / dpiY)), - false/*don't antialias*/); + kpPixmapFX::scale(&image, + image.width(), + qMax(1, qRound(image.height() * dpiX / dpiY)), + false /*don't antialias*/); dpiY = dpiX; - } - else if (dpiY > dpiX) - { + } else if (dpiY > dpiX) { #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tdpiY > dpiX; stretching image width to equalise DPIs to dpiY=" - << dpiY; + qCDebug(kpLogMainWindow) + << + "\tdpiY > dpiX; stretching image width to equalise DPIs to dpiY=" + << dpiY; #endif - kpPixmapFX::scale (&image, - qMax (1, qRound (image.width () * dpiY / dpiX)), - image.height (), - false/*don't antialias*/); + kpPixmapFX::scale(&image, + qMax(1, qRound(image.width() * dpiY / dpiX)), + image.height(), + false /*don't antialias*/); dpiX = dpiY; } - Q_ASSERT (dpiX == dpiY); - + Q_ASSERT(dpiX == dpiY); // QPrinter::setResolution() has to be called before QPrinter::setup(). - printer->setResolution (qMax (1, qRound (dpiX))); - + printer->setResolution(qMax(1, qRound(dpiX))); - sendDocumentNameToPrinter (printer); + sendDocumentNameToPrinter(printer); + if (showPrinterSetupDialog) { + auto *optionsPage = new kpPrintDialogPage(this); + optionsPage->setPrintImageCenteredOnPage(d->configPrintImageCenteredOnPage); - if (showPrinterSetupDialog) - { - auto *optionsPage = new kpPrintDialogPage (this); - optionsPage->setPrintImageCenteredOnPage (d->configPrintImageCenteredOnPage); - - QPrintDialog *printDialog = - KdePrint::createPrintDialog ( - printer, - QList () << optionsPage, + QPrintDialog *printDialog + = KdePrint::createPrintDialog( + printer, + QList () << optionsPage, this); - printDialog->setWindowTitle (i18nc ("@title:window", "Print Image")); + printDialog->setWindowTitle(i18nc("@title:window", "Print Image")); // Display dialog. - const bool wantToPrint = printDialog->exec (); + const bool wantToPrint = printDialog->exec(); - if (optionsPage->printImageCenteredOnPage () != - d->configPrintImageCenteredOnPage) - { + if (optionsPage->printImageCenteredOnPage() + != d->configPrintImageCenteredOnPage) { // Save config option even if the dialog was cancelled. - d->configPrintImageCenteredOnPage = optionsPage->printImageCenteredOnPage (); + d->configPrintImageCenteredOnPage = optionsPage->printImageCenteredOnPage(); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupGeneral); - cfg.writeEntry (kpSettingPrintImageCenteredOnPage, + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); + cfg.writeEntry(kpSettingPrintImageCenteredOnPage, d->configPrintImageCenteredOnPage); - cfg.sync (); + cfg.sync(); } delete printDialog; @@ -1362,18 +1284,16 @@ } } - // Send image to printer. QPainter painter; painter.begin(printer); double originX = 0, originY = 0; // Center image on page? - if (d->configPrintImageCenteredOnPage) - { - originX = (printer->width() - image.width ()) / 2; - originY = (printer->height() - image.height ()) / 2; + if (d->configPrintImageCenteredOnPage) { + originX = (printer->width() - image.width()) / 2; + originY = (printer->height() - image.height()) / 2; } painter.drawImage(qRound(originX), qRound(originY), image); @@ -1383,92 +1303,89 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotPrint () +void kpMainWindow::slotPrint() { - toolEndShape (); + toolEndShape(); QPrinter printer; - sendImageToPrinter (&printer, true/*showPrinterSetupDialog*/); + sendImageToPrinter(&printer, true /*showPrinterSetupDialog*/); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotPrintPreview () +void kpMainWindow::slotPrintPreview() { - toolEndShape (); + toolEndShape(); QPrintPreviewDialog printPreview(this); - connect(&printPreview, &QPrintPreviewDialog::paintRequested, this, &kpMainWindow::sendPreviewToPrinter); + connect(&printPreview, &QPrintPreviewDialog::paintRequested, this, + &kpMainWindow::sendPreviewToPrinter); - printPreview.exec (); + printPreview.exec(); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotMail () +void kpMainWindow::slotMail() { - toolEndShape (); - - if (d->document->url ().isEmpty ()/*no name*/ || - !d->document->isFromURL () || - d->document->isModified ()/*needs to be saved*/) - { - int result = KMessageBox::questionYesNo (this, - i18n ("You must save this image before sending it.\n" - "Do you want to save it?"), - QString(), - KStandardGuiItem::save (), KStandardGuiItem::cancel ()); - - if (result == KMessageBox::Yes) - { - if (!save ()) - { + toolEndShape(); + + if (d->document->url().isEmpty() /*no name*/ + || !d->document->isFromURL() + || d->document->isModified() /*needs to be saved*/) { + int result = KMessageBox::questionYesNo(this, + i18n("You must save this image before sending it.\n" + "Do you want to save it?"), + QString(), + KStandardGuiItem::save(), + KStandardGuiItem::cancel()); + + if (result == KMessageBox::Yes) { + if (!save()) { // save failed or aborted - don't email return; } - } - else - { + } else { // don't want to save - don't email return; } } - KToolInvocation::invokeMailer ( - QString()/*to*/, - QString()/*cc*/, - QString()/*bcc*/, - d->document->prettyFilename()/*subject*/, - QString()/*body*/, - QString()/*messageFile*/, - QStringList(d->document->url().url())/*attachments*/); + KToolInvocation::invokeMailer( + QString() /*to*/, + QString() /*cc*/, + QString() /*bcc*/, + d->document->prettyFilename() /*subject*/, + QString() /*body*/, + QString() /*messageFile*/, + QStringList(d->document->url().url()) /*attachments*/); } //--------------------------------------------------------------------- // private -bool kpMainWindow::queryCloseDocument () +bool kpMainWindow::queryCloseDocument() { - toolEndShape (); + toolEndShape(); - if (!d->document || !d->document->isModified ()) { + if (!d->document || !d->document->isModified()) { return true; // ok to close current doc } - int result = KMessageBox::warningYesNoCancel (this, - i18n ("The document \"%1\" has been modified.\n" - "Do you want to save it?", - d->document->prettyFilename ()), - QString()/*caption*/, - KStandardGuiItem::save (), KStandardGuiItem::discard ()); + int result = KMessageBox::warningYesNoCancel(this, + i18n("The document \"%1\" has been modified.\n" + "Do you want to save it?", + d->document->prettyFilename()), + QString() /*caption*/, + KStandardGuiItem::save(), + KStandardGuiItem::discard()); - switch (result) - { + switch (result) { case KMessageBox::Yes: - return slotSave (); // close only if save succeeds + return slotSave(); // close only if save succeeds case KMessageBox::No: return true; // close without saving default: @@ -1479,18 +1396,18 @@ //--------------------------------------------------------------------- // private virtual [base KMainWindow] -bool kpMainWindow::queryClose () +bool kpMainWindow::queryClose() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::queryClose()"; #endif - toolEndShape (); + toolEndShape(); - if (!queryCloseDocument ()) { + if (!queryCloseDocument()) { return false; } - if (!queryCloseColors ()) { + if (!queryCloseColors()) { return false; } @@ -1500,25 +1417,25 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotClose () +void kpMainWindow::slotClose() { - toolEndShape (); + toolEndShape(); - if (!queryCloseDocument ()) { + if (!queryCloseDocument()) { return; } - setDocument (nullptr); + setDocument(nullptr); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotQuit () +void kpMainWindow::slotQuit() { - toolEndShape (); + toolEndShape(); - close (); // will call queryClose() + close(); // will call queryClose() } //--------------------------------------------------------------------- diff --git a/mainWindow/kpMainWindow_Image.cpp b/mainWindow/kpMainWindow_Image.cpp --- a/mainWindow/kpMainWindow_Image.cpp +++ b/mainWindow/kpMainWindow_Image.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "mainWindow/kpMainWindow.h" #include "kpMainWindowPrivate.h" @@ -70,378 +68,357 @@ #include #include - //--------------------------------------------------------------------- // private -kpTransformDialogEnvironment *kpMainWindow::transformDialogEnvironment () +kpTransformDialogEnvironment *kpMainWindow::transformDialogEnvironment() { - if (!d->transformDialogEnvironment) - d->transformDialogEnvironment = new kpTransformDialogEnvironment (this); + if (!d->transformDialogEnvironment) { + d->transformDialogEnvironment = new kpTransformDialogEnvironment(this); + } return d->transformDialogEnvironment; } //--------------------------------------------------------------------- // private -bool kpMainWindow::isSelectionActive () const +bool kpMainWindow::isSelectionActive() const { - return (d->document ? bool (d->document->selection ()) : false); + return d->document ? bool(d->document->selection()) : false; } //--------------------------------------------------------------------- // private -bool kpMainWindow::isTextSelection () const +bool kpMainWindow::isTextSelection() const { - return (d->document && d->document->textSelection ()); + return d->document && d->document->textSelection(); } //--------------------------------------------------------------------- // private -QString kpMainWindow::autoCropText () const +QString kpMainWindow::autoCropText() const { return kpTransformAutoCropCommand::text(isSelectionActive(), kpTransformAutoCropCommand::ShowAccel); } //--------------------------------------------------------------------- // private -void kpMainWindow::setupImageMenuActions () +void kpMainWindow::setupImageMenuActions() { - KActionCollection *ac = actionCollection (); + KActionCollection *ac = actionCollection(); - d->actionResizeScale = ac->addAction (QStringLiteral("image_resize_scale")); - d->actionResizeScale->setText (i18n ("R&esize / Scale...")); - connect (d->actionResizeScale, &QAction::triggered, this, &kpMainWindow::slotResizeScale); + d->actionResizeScale = ac->addAction(QStringLiteral("image_resize_scale")); + d->actionResizeScale->setText(i18n("R&esize / Scale...")); + connect(d->actionResizeScale, &QAction::triggered, this, &kpMainWindow::slotResizeScale); - ac->setDefaultShortcut (d->actionResizeScale, Qt::CTRL + Qt::Key_E); + ac->setDefaultShortcut(d->actionResizeScale, Qt::CTRL + Qt::Key_E); - d->actionCrop = ac->addAction (QStringLiteral("image_crop")); - d->actionCrop->setText (i18n ("Se&t as Image (Crop)")); - connect (d->actionCrop, &QAction::triggered, this, &kpMainWindow::slotCrop); - ac->setDefaultShortcut (d->actionCrop, Qt::CTRL + Qt::Key_T); + d->actionCrop = ac->addAction(QStringLiteral("image_crop")); + d->actionCrop->setText(i18n("Se&t as Image (Crop)")); + connect(d->actionCrop, &QAction::triggered, this, &kpMainWindow::slotCrop); + ac->setDefaultShortcut(d->actionCrop, Qt::CTRL + Qt::Key_T); - d->actionAutoCrop = ac->addAction (QStringLiteral("image_auto_crop")); - d->actionAutoCrop->setText (autoCropText ()); - connect (d->actionAutoCrop, &QAction::triggered, this, &kpMainWindow::slotAutoCrop); - ac->setDefaultShortcut (d->actionAutoCrop, Qt::CTRL + Qt::Key_U); + d->actionAutoCrop = ac->addAction(QStringLiteral("image_auto_crop")); + d->actionAutoCrop->setText(autoCropText()); + connect(d->actionAutoCrop, &QAction::triggered, this, &kpMainWindow::slotAutoCrop); + ac->setDefaultShortcut(d->actionAutoCrop, Qt::CTRL + Qt::Key_U); - d->actionFlip = ac->addAction (QStringLiteral("image_flip")); - d->actionFlip->setText (i18n ("&Flip (upside down)")); - connect (d->actionFlip, &QAction::triggered, this, &kpMainWindow::slotFlip); - ac->setDefaultShortcut (d->actionFlip, Qt::CTRL + Qt::Key_F); + d->actionFlip = ac->addAction(QStringLiteral("image_flip")); + d->actionFlip->setText(i18n("&Flip (upside down)")); + connect(d->actionFlip, &QAction::triggered, this, &kpMainWindow::slotFlip); + ac->setDefaultShortcut(d->actionFlip, Qt::CTRL + Qt::Key_F); - d->actionMirror = ac->addAction (QStringLiteral("image_mirror")); - d->actionMirror->setText (i18n ("Mirror (horizontally)")); - connect (d->actionMirror, &QAction::triggered, this, &kpMainWindow::slotMirror); + d->actionMirror = ac->addAction(QStringLiteral("image_mirror")); + d->actionMirror->setText(i18n("Mirror (horizontally)")); + connect(d->actionMirror, &QAction::triggered, this, &kpMainWindow::slotMirror); //ac->setDefaultShortcut (d->actionMirror, Qt::CTRL + Qt::Key_M); - d->actionRotate = ac->addAction (QStringLiteral("image_rotate")); - d->actionRotate->setText (i18n ("&Rotate...")); + d->actionRotate = ac->addAction(QStringLiteral("image_rotate")); + d->actionRotate->setText(i18n("&Rotate...")); d->actionRotate->setIcon(KDE::icon(QStringLiteral("transform-rotate"))); - connect (d->actionRotate, &QAction::triggered, this, &kpMainWindow::slotRotate); - ac->setDefaultShortcut (d->actionRotate, Qt::CTRL + Qt::Key_R); + connect(d->actionRotate, &QAction::triggered, this, &kpMainWindow::slotRotate); + ac->setDefaultShortcut(d->actionRotate, Qt::CTRL + Qt::Key_R); - d->actionRotateLeft = ac->addAction (QStringLiteral("image_rotate_270deg")); - d->actionRotateLeft->setText (i18n ("Rotate &Left")); + d->actionRotateLeft = ac->addAction(QStringLiteral("image_rotate_270deg")); + d->actionRotateLeft->setText(i18n("Rotate &Left")); d->actionRotateLeft->setIcon(KDE::icon(QStringLiteral("object-rotate-left"))); - connect (d->actionRotateLeft, &QAction::triggered, this, &kpMainWindow::slotRotate270); - ac->setDefaultShortcut (d->actionRotateLeft, Qt::CTRL + Qt::SHIFT + Qt::Key_Left); + connect(d->actionRotateLeft, &QAction::triggered, this, &kpMainWindow::slotRotate270); + ac->setDefaultShortcut(d->actionRotateLeft, Qt::CTRL + Qt::SHIFT + Qt::Key_Left); - d->actionRotateRight = ac->addAction (QStringLiteral("image_rotate_90deg")); - d->actionRotateRight->setText (i18n ("Rotate Righ&t")); + d->actionRotateRight = ac->addAction(QStringLiteral("image_rotate_90deg")); + d->actionRotateRight->setText(i18n("Rotate Righ&t")); d->actionRotateRight->setIcon(KDE::icon(QStringLiteral("object-rotate-right"))); - connect (d->actionRotateRight, &QAction::triggered, this, &kpMainWindow::slotRotate90); - ac->setDefaultShortcut (d->actionRotateRight, Qt::CTRL + Qt::SHIFT + Qt::Key_Right); - - d->actionSkew = ac->addAction (QStringLiteral("image_skew")); - d->actionSkew->setText (i18n ("S&kew...")); - connect (d->actionSkew, &QAction::triggered, this, &kpMainWindow::slotSkew); - ac->setDefaultShortcut (d->actionSkew, Qt::CTRL + Qt::Key_K); - - d->actionConvertToBlackAndWhite = ac->addAction (QStringLiteral("image_convert_to_black_and_white")); - d->actionConvertToBlackAndWhite->setText (i18n ("Reduce to Mo&nochrome (Dithered)")); - connect (d->actionConvertToBlackAndWhite, &QAction::triggered, - this, &kpMainWindow::slotConvertToBlackAndWhite); - - d->actionConvertToGrayscale = ac->addAction (QStringLiteral("image_convert_to_grayscale")); - d->actionConvertToGrayscale->setText (i18n ("Reduce to &Grayscale")); - connect (d->actionConvertToGrayscale, &QAction::triggered, this, &kpMainWindow::slotConvertToGrayscale); - - d->actionInvertColors = ac->addAction (QStringLiteral("image_invert_colors")); - d->actionInvertColors->setText (i18n ("&Invert Colors")); - connect (d->actionInvertColors, &QAction::triggered, this, &kpMainWindow::slotInvertColors); - ac->setDefaultShortcut (d->actionInvertColors, Qt::CTRL + Qt::Key_I); - - d->actionClear = ac->addAction (QStringLiteral("image_clear")); - d->actionClear->setText (i18n ("C&lear")); - connect (d->actionClear, &QAction::triggered, this, &kpMainWindow::slotClear); - ac->setDefaultShortcut (d->actionClear, Qt::CTRL + Qt::SHIFT + Qt::Key_N); + connect(d->actionRotateRight, &QAction::triggered, this, &kpMainWindow::slotRotate90); + ac->setDefaultShortcut(d->actionRotateRight, Qt::CTRL + Qt::SHIFT + Qt::Key_Right); + + d->actionSkew = ac->addAction(QStringLiteral("image_skew")); + d->actionSkew->setText(i18n("S&kew...")); + connect(d->actionSkew, &QAction::triggered, this, &kpMainWindow::slotSkew); + ac->setDefaultShortcut(d->actionSkew, Qt::CTRL + Qt::Key_K); + + d->actionConvertToBlackAndWhite + = ac->addAction(QStringLiteral("image_convert_to_black_and_white")); + d->actionConvertToBlackAndWhite->setText(i18n("Reduce to Mo&nochrome (Dithered)")); + connect(d->actionConvertToBlackAndWhite, &QAction::triggered, + this, &kpMainWindow::slotConvertToBlackAndWhite); + + d->actionConvertToGrayscale = ac->addAction(QStringLiteral("image_convert_to_grayscale")); + d->actionConvertToGrayscale->setText(i18n("Reduce to &Grayscale")); + connect(d->actionConvertToGrayscale, &QAction::triggered, this, + &kpMainWindow::slotConvertToGrayscale); + + d->actionInvertColors = ac->addAction(QStringLiteral("image_invert_colors")); + d->actionInvertColors->setText(i18n("&Invert Colors")); + connect(d->actionInvertColors, &QAction::triggered, this, &kpMainWindow::slotInvertColors); + ac->setDefaultShortcut(d->actionInvertColors, Qt::CTRL + Qt::Key_I); + + d->actionClear = ac->addAction(QStringLiteral("image_clear")); + d->actionClear->setText(i18n("C&lear")); + connect(d->actionClear, &QAction::triggered, this, &kpMainWindow::slotClear); + ac->setDefaultShortcut(d->actionClear, Qt::CTRL + Qt::SHIFT + Qt::Key_N); d->actionBlur = ac->addAction(QStringLiteral("image_make_confidential")); d->actionBlur->setText(i18n("Make Confidential")); connect(d->actionBlur, &QAction::triggered, this, &kpMainWindow::slotMakeConfidential); - d->actionMoreEffects = ac->addAction (QStringLiteral("image_more_effects")); - d->actionMoreEffects->setText (i18n ("&More Effects...")); - connect (d->actionMoreEffects, &QAction::triggered, this, &kpMainWindow::slotMoreEffects); - ac->setDefaultShortcut (d->actionMoreEffects, Qt::CTRL + Qt::Key_M); + d->actionMoreEffects = ac->addAction(QStringLiteral("image_more_effects")); + d->actionMoreEffects->setText(i18n("&More Effects...")); + connect(d->actionMoreEffects, &QAction::triggered, this, &kpMainWindow::slotMoreEffects); + ac->setDefaultShortcut(d->actionMoreEffects, Qt::CTRL + Qt::Key_M); - - enableImageMenuDocumentActions (false); + enableImageMenuDocumentActions(false); } //--------------------------------------------------------------------- // private -void kpMainWindow::enableImageMenuDocumentActions (bool enable) +void kpMainWindow::enableImageMenuDocumentActions(bool enable) { - d->actionResizeScale->setEnabled (enable); - d->actionCrop->setEnabled (enable); - d->actionAutoCrop->setEnabled (enable); - d->actionFlip->setEnabled (enable); - d->actionMirror->setEnabled (enable); - d->actionRotate->setEnabled (enable); - d->actionRotateLeft->setEnabled (enable); - d->actionRotateRight->setEnabled (enable); - d->actionSkew->setEnabled (enable); - d->actionConvertToBlackAndWhite->setEnabled (enable); - d->actionConvertToGrayscale->setEnabled (enable); - d->actionInvertColors->setEnabled (enable); - d->actionClear->setEnabled (enable); - d->actionBlur->setEnabled (enable); - d->actionMoreEffects->setEnabled (enable); + d->actionResizeScale->setEnabled(enable); + d->actionCrop->setEnabled(enable); + d->actionAutoCrop->setEnabled(enable); + d->actionFlip->setEnabled(enable); + d->actionMirror->setEnabled(enable); + d->actionRotate->setEnabled(enable); + d->actionRotateLeft->setEnabled(enable); + d->actionRotateRight->setEnabled(enable); + d->actionSkew->setEnabled(enable); + d->actionConvertToBlackAndWhite->setEnabled(enable); + d->actionConvertToGrayscale->setEnabled(enable); + d->actionInvertColors->setEnabled(enable); + d->actionClear->setEnabled(enable); + d->actionBlur->setEnabled(enable); + d->actionMoreEffects->setEnabled(enable); d->imageMenuDocumentActionsEnabled = enable; } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotImageMenuUpdateDueToSelection () +void kpMainWindow::slotImageMenuUpdateDueToSelection() { // SYNC: kolourpaintui.rc - const QString MenuBarItemTextImage = i18nc ( + const QString MenuBarItemTextImage = i18nc( "Image/Selection Menu caption - make sure the translation has" " the same accel as the Select&ion translation", "&Image"); - const QString MenuBarItemTextSelection = i18nc ( + const QString MenuBarItemTextSelection = i18nc( "Image/Selection Menu caption - make sure that translation has" " the same accel as the &Image translation", "Select&ion"); - Q_ASSERT (menuBar ()); - for (auto *action : menuBar ()->actions ()) - { - if (action->text () == MenuBarItemTextImage || - action->text () == MenuBarItemTextSelection) - { - if (isSelectionActive ()) { - action->setText (MenuBarItemTextSelection); - } - else { - action->setText (MenuBarItemTextImage); + Q_ASSERT(menuBar()); + for (auto *action : menuBar()->actions()) { + if (action->text() == MenuBarItemTextImage + || action->text() == MenuBarItemTextSelection) { + if (isSelectionActive()) { + action->setText(MenuBarItemTextSelection); + } else { + action->setText(MenuBarItemTextImage); } break; } } - - d->actionResizeScale->setEnabled (d->imageMenuDocumentActionsEnabled); - d->actionCrop->setEnabled (d->imageMenuDocumentActionsEnabled && - isSelectionActive ()); - - const bool enable = (d->imageMenuDocumentActionsEnabled && !isTextSelection ()); - d->actionAutoCrop->setText (autoCropText ()); - d->actionAutoCrop->setEnabled (enable); - d->actionFlip->setEnabled (enable); - d->actionMirror->setEnabled (enable); - d->actionRotate->setEnabled (enable); - d->actionRotateLeft->setEnabled (enable); - d->actionRotateRight->setEnabled (enable); - d->actionSkew->setEnabled (enable); - d->actionConvertToBlackAndWhite->setEnabled (enable); - d->actionConvertToGrayscale->setEnabled (enable); - d->actionInvertColors->setEnabled (enable); - d->actionClear->setEnabled (enable); - d->actionBlur->setEnabled (enable); - d->actionMoreEffects->setEnabled (enable); + d->actionResizeScale->setEnabled(d->imageMenuDocumentActionsEnabled); + d->actionCrop->setEnabled(d->imageMenuDocumentActionsEnabled + && isSelectionActive()); + + const bool enable = (d->imageMenuDocumentActionsEnabled && !isTextSelection()); + d->actionAutoCrop->setText(autoCropText()); + d->actionAutoCrop->setEnabled(enable); + d->actionFlip->setEnabled(enable); + d->actionMirror->setEnabled(enable); + d->actionRotate->setEnabled(enable); + d->actionRotateLeft->setEnabled(enable); + d->actionRotateRight->setEnabled(enable); + d->actionSkew->setEnabled(enable); + d->actionConvertToBlackAndWhite->setEnabled(enable); + d->actionConvertToGrayscale->setEnabled(enable); + d->actionInvertColors->setEnabled(enable); + d->actionClear->setEnabled(enable); + d->actionBlur->setEnabled(enable); + d->actionMoreEffects->setEnabled(enable); } //--------------------------------------------------------------------- // public -kpColor kpMainWindow::backgroundColor (bool ofSelection) const +kpColor kpMainWindow::backgroundColor(bool ofSelection) const { if (ofSelection) { return kpColor::Transparent; } - Q_ASSERT (d->colorToolBar); - return d->colorToolBar->backgroundColor (); + Q_ASSERT(d->colorToolBar); + return d->colorToolBar->backgroundColor(); } //--------------------------------------------------------------------- // public // REFACTOR: sync: Code dup with kpAbstractSelectionTool::addNeedingContentCommand(). -void kpMainWindow::addImageOrSelectionCommand (kpCommand *cmd, - bool addSelCreateCmdIfSelAvail, - bool addSelContentCmdIfSelAvail) +void kpMainWindow::addImageOrSelectionCommand(kpCommand *cmd, bool addSelCreateCmdIfSelAvail, + bool addSelContentCmdIfSelAvail) { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::addImageOrSelectionCommand()" - << " addSelCreateCmdIfSelAvail=" << addSelCreateCmdIfSelAvail - << " addSelContentCmdIfSelAvail=" << addSelContentCmdIfSelAvail; + << " addSelCreateCmdIfSelAvail=" << addSelCreateCmdIfSelAvail + << " addSelContentCmdIfSelAvail=" << addSelContentCmdIfSelAvail; #endif - Q_ASSERT (d->document); - + Q_ASSERT(d->document); if (d->viewManager) { - d->viewManager->setQueueUpdates (); + d->viewManager->setQueueUpdates(); } - - kpAbstractSelection *sel = d->document->selection (); + kpAbstractSelection *sel = d->document->selection(); #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "\timage sel=" << sel - << " sel->hasContent=" << (sel ? sel->hasContent () : 0); + << " sel->hasContent=" << (sel ? sel->hasContent() : 0); #endif - if (addSelCreateCmdIfSelAvail && sel && !sel->hasContent ()) - { + if (addSelCreateCmdIfSelAvail && sel && !sel->hasContent()) { QString createCmdName; - if (dynamic_cast (sel)) { - createCmdName = i18n ("Selection: Create"); - } - else if (dynamic_cast (sel)) { - createCmdName = i18n ("Text: Create Box"); - } - else { - Q_ASSERT (!"Unknown selection type"); + if (dynamic_cast (sel)) { + createCmdName = i18n("Selection: Create"); + } else if (dynamic_cast (sel)) { + createCmdName = i18n("Text: Create Box"); + } else { + Q_ASSERT(!"Unknown selection type"); } // create selection region - commandHistory ()->addCreateSelectionCommand ( - new kpToolSelectionCreateCommand ( + commandHistory()->addCreateSelectionCommand( + new kpToolSelectionCreateCommand( createCmdName, *sel, - commandEnvironment ()), - false/*no exec - user already dragged out sel*/); + commandEnvironment()), + false /*no exec - user already dragged out sel*/); } + if (addSelContentCmdIfSelAvail && sel && !sel->hasContent()) { + auto *imageSel = dynamic_cast (sel); + auto *textSel = dynamic_cast (sel); - if (addSelContentCmdIfSelAvail && sel && !sel->hasContent ()) - { - auto *imageSel = dynamic_cast (sel); - auto *textSel = dynamic_cast (sel); - - if (imageSel && imageSel->transparency ().isTransparent ()) { - d->colorToolBar->flashColorSimilarityToolBarItem (); + if (imageSel && imageSel->transparency().isTransparent()) { + d->colorToolBar->flashColorSimilarityToolBarItem(); } - kpMacroCommand *macroCmd = new kpMacroCommand (cmd->name (), - commandEnvironment ()); + kpMacroCommand *macroCmd = new kpMacroCommand(cmd->name(), + commandEnvironment()); - if (imageSel) - { - macroCmd->addCommand ( - new kpToolSelectionPullFromDocumentCommand ( + if (imageSel) { + macroCmd->addCommand( + new kpToolSelectionPullFromDocumentCommand( *imageSel, - backgroundColor (), - QString()/*uninteresting child of macro cmd*/, - commandEnvironment ())); - } - else if (textSel) - { - macroCmd->addCommand ( - new kpToolTextGiveContentCommand ( + backgroundColor(), + QString() /*uninteresting child of macro cmd*/, + commandEnvironment())); + } else if (textSel) { + macroCmd->addCommand( + new kpToolTextGiveContentCommand( *textSel, - QString()/*uninteresting child of macro cmd*/, - commandEnvironment ())); - } - else { - Q_ASSERT (!"Unknown selection type"); + QString() /*uninteresting child of macro cmd*/, + commandEnvironment())); + } else { + Q_ASSERT(!"Unknown selection type"); } - macroCmd->addCommand (cmd); + macroCmd->addCommand(cmd); - d->commandHistory->addCommand (macroCmd); + d->commandHistory->addCommand(macroCmd); + } else { + d->commandHistory->addCommand(cmd); } - else - { - d->commandHistory->addCommand (cmd); - } - if (d->viewManager) { - d->viewManager->restoreQueueUpdates (); + d->viewManager->restoreQueueUpdates(); } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotResizeScale () +void kpMainWindow::slotResizeScale() { - toolEndShape (); + toolEndShape(); kpTransformResizeScaleDialog dialog(transformDialogEnvironment(), this); - if (dialog.exec () && !dialog.isNoOp ()) - { - auto *cmd = new kpTransformResizeScaleCommand ( - dialog.actOnSelection (), - dialog.imageWidth (), dialog.imageHeight (), - dialog.type (), - commandEnvironment ()); + if (dialog.exec() && !dialog.isNoOp()) { + auto *cmd = new kpTransformResizeScaleCommand( + dialog.actOnSelection(), + dialog.imageWidth(), dialog.imageHeight(), + dialog.type(), + commandEnvironment()); - bool addSelCreateCommand = (dialog.actOnSelection () || - cmd->scaleSelectionWithImage ()); - bool addSelContentCommand = dialog.actOnSelection (); + bool addSelCreateCommand = (dialog.actOnSelection() + || cmd->scaleSelectionWithImage()); + bool addSelContentCommand = dialog.actOnSelection(); - addImageOrSelectionCommand ( + addImageOrSelectionCommand( cmd, addSelCreateCommand, addSelContentCommand); // Resized document? - if (!dialog.actOnSelection () && - dialog.type () == kpTransformResizeScaleCommand::Resize) - { + if (!dialog.actOnSelection() + && dialog.type() == kpTransformResizeScaleCommand::Resize) { // TODO: this should be the responsibility of kpDocument - saveDefaultDocSize (QSize (dialog.imageWidth (), dialog.imageHeight ())); + saveDefaultDocSize(QSize(dialog.imageWidth(), dialog.imageHeight())); } } } //--------------------------------------------------------------------- // public slot -void kpMainWindow::slotCrop () +void kpMainWindow::slotCrop() { - toolEndShape (); - - Q_ASSERT (d->document && d->document->selection ()); + toolEndShape(); + Q_ASSERT(d->document && d->document->selection()); - ::kpTransformCrop (this); + ::kpTransformCrop(this); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotAutoCrop () +void kpMainWindow::slotAutoCrop() { - toolEndShape (); + toolEndShape(); - ::kpTransformAutoCrop (this); + ::kpTransformAutoCrop(this); } //--------------------------------------------------------------------- @@ -471,115 +448,112 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotRotate () +void kpMainWindow::slotRotate() { - toolEndShape (); + toolEndShape(); - kpTransformRotateDialog dialog (static_cast (d->document->selection ()), - transformDialogEnvironment (), this); + kpTransformRotateDialog dialog(static_cast(d->document->selection()), + transformDialogEnvironment(), this); - if (dialog.exec () && !dialog.isNoOp ()) - { - addImageOrSelectionCommand ( - new kpTransformRotateCommand (d->document->selection (), - dialog.angle (), - commandEnvironment ())); + if (dialog.exec() && !dialog.isNoOp()) { + addImageOrSelectionCommand( + new kpTransformRotateCommand(d->document->selection(), + dialog.angle(), + commandEnvironment())); } } // private slot -void kpMainWindow::slotRotate270 () +void kpMainWindow::slotRotate270() { - toolEndShape (); + toolEndShape(); // TODO: Special command name instead of just "Rotate"? - addImageOrSelectionCommand ( - new kpTransformRotateCommand ( - d->document->selection (), + addImageOrSelectionCommand( + new kpTransformRotateCommand( + d->document->selection(), 270, - commandEnvironment ())); + commandEnvironment())); } // private slot -void kpMainWindow::slotRotate90 () +void kpMainWindow::slotRotate90() { - toolEndShape (); + toolEndShape(); // TODO: Special command name instead of just "Rotate"? - addImageOrSelectionCommand ( - new kpTransformRotateCommand ( - d->document->selection (), + addImageOrSelectionCommand( + new kpTransformRotateCommand( + d->document->selection(), 90, - commandEnvironment ())); + commandEnvironment())); } - // private slot -void kpMainWindow::slotSkew () +void kpMainWindow::slotSkew() { - toolEndShape (); + toolEndShape(); - kpTransformSkewDialog dialog (static_cast (d->document->selection ()), - transformDialogEnvironment (), this); + kpTransformSkewDialog dialog(static_cast(d->document->selection()), + transformDialogEnvironment(), this); - if (dialog.exec () && !dialog.isNoOp ()) - { - addImageOrSelectionCommand ( - new kpTransformSkewCommand (d->document->selection (), - dialog.horizontalAngle (), dialog.verticalAngle (), - commandEnvironment ())); + if (dialog.exec() && !dialog.isNoOp()) { + addImageOrSelectionCommand( + new kpTransformSkewCommand(d->document->selection(), + dialog.horizontalAngle(), dialog.verticalAngle(), + commandEnvironment())); } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotConvertToBlackAndWhite () +void kpMainWindow::slotConvertToBlackAndWhite() { - toolEndShape (); + toolEndShape(); - addImageOrSelectionCommand ( - new kpEffectReduceColorsCommand (1/*depth*/, true/*dither*/, - d->document->selection (), - commandEnvironment ())); + addImageOrSelectionCommand( + new kpEffectReduceColorsCommand(1 /*depth*/, true /*dither*/, + d->document->selection(), + commandEnvironment())); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotConvertToGrayscale () +void kpMainWindow::slotConvertToGrayscale() { - toolEndShape (); + toolEndShape(); - addImageOrSelectionCommand ( - new kpEffectGrayscaleCommand (d->document->selection (), - commandEnvironment ())); + addImageOrSelectionCommand( + new kpEffectGrayscaleCommand(d->document->selection(), + commandEnvironment())); } //-------------------------------------------------------------------------------- // private slot -void kpMainWindow::slotInvertColors () +void kpMainWindow::slotInvertColors() { - toolEndShape (); + toolEndShape(); - addImageOrSelectionCommand ( - new kpEffectInvertCommand (d->document->selection (), - commandEnvironment ())); + addImageOrSelectionCommand( + new kpEffectInvertCommand(d->document->selection(), + commandEnvironment())); } //-------------------------------------------------------------------------------- // private slot -void kpMainWindow::slotClear () +void kpMainWindow::slotClear() { - toolEndShape (); + toolEndShape(); - addImageOrSelectionCommand ( - new kpEffectClearCommand ( - d->document->selection (), - backgroundColor (), - commandEnvironment ())); + addImageOrSelectionCommand( + new kpEffectClearCommand( + d->document->selection(), + backgroundColor(), + commandEnvironment())); } //-------------------------------------------------------------------------------- @@ -589,36 +563,34 @@ toolEndShape(); addImageOrSelectionCommand( - new kpEffectBlurSharpenCommand(kpEffectBlurSharpen::MakeConfidential, kpEffectBlurSharpen::MaxStrength, + new kpEffectBlurSharpenCommand(kpEffectBlurSharpen::MakeConfidential, + kpEffectBlurSharpen::MaxStrength, d->document->selection(), commandEnvironment())); } //-------------------------------------------------------------------------------- // private slot -void kpMainWindow::slotMoreEffects () +void kpMainWindow::slotMoreEffects() { - toolEndShape (); + toolEndShape(); - kpEffectsDialog dialog (static_cast (d->document->selection ()), - transformDialogEnvironment (), this, - d->moreEffectsDialogLastEffect); + kpEffectsDialog dialog(static_cast(d->document->selection()), + transformDialogEnvironment(), this, + d->moreEffectsDialogLastEffect); - if (dialog.exec () && !dialog.isNoOp ()) - { - addImageOrSelectionCommand (dialog.createCommand ()); + if (dialog.exec() && !dialog.isNoOp()) { + addImageOrSelectionCommand(dialog.createCommand()); } + if (d->moreEffectsDialogLastEffect != dialog.selectedEffect()) { + d->moreEffectsDialogLastEffect = dialog.selectedEffect(); - if (d->moreEffectsDialogLastEffect != dialog.selectedEffect ()) - { - d->moreEffectsDialogLastEffect = dialog.selectedEffect (); - - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupGeneral); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); - cfg.writeEntry (kpSettingMoreEffectsLastEffect, - d->moreEffectsDialogLastEffect); - cfg.sync (); + cfg.writeEntry(kpSettingMoreEffectsLastEffect, + d->moreEffectsDialogLastEffect); + cfg.sync(); } } diff --git a/mainWindow/kpMainWindow_Settings.cpp b/mainWindow/kpMainWindow_Settings.cpp --- a/mainWindow/kpMainWindow_Settings.cpp +++ b/mainWindow/kpMainWindow_Settings.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "mainWindow/kpMainWindow.h" #include "kpMainWindowPrivate.h" #include "kpLogCategories.h" @@ -47,87 +45,83 @@ //--------------------------------------------------------------------- // private -void kpMainWindow::setupSettingsMenuActions () +void kpMainWindow::setupSettingsMenuActions() { - KActionCollection *ac = actionCollection (); - + KActionCollection *ac = actionCollection(); // Settings/Toolbars |> %s - setStandardToolBarMenuEnabled (true); + setStandardToolBarMenuEnabled(true); // Settings/Show Statusbar - createStandardStatusBarAction (); - + createStandardStatusBarAction(); - d->actionFullScreen = KStandardAction::fullScreen (this, SLOT (slotFullScreen()), - this/*window*/, ac); + d->actionFullScreen = KStandardAction::fullScreen(this, SLOT(slotFullScreen()), + this /*window*/, ac); - - d->actionShowPath = ac->add (QStringLiteral("settings_show_path")); - d->actionShowPath->setText (i18n ("Show &Path")); - connect (d->actionShowPath, &QAction::triggered, this, &kpMainWindow::slotShowPathToggled); - slotEnableSettingsShowPath (); + d->actionShowPath = ac->add(QStringLiteral("settings_show_path")); + d->actionShowPath->setText(i18n("Show &Path")); + connect(d->actionShowPath, &QAction::triggered, this, &kpMainWindow::slotShowPathToggled); + slotEnableSettingsShowPath(); auto *action = ac->add(QStringLiteral("settings_draw_antialiased")); action->setText(i18n("Draw Anti-Aliased")); action->setChecked(kpToolEnvironment::drawAntiAliased); - connect (action, &KToggleAction::triggered, this, &kpMainWindow::slotDrawAntiAliasedToggled); + connect(action, &KToggleAction::triggered, this, &kpMainWindow::slotDrawAntiAliasedToggled); - d->actionKeyBindings = KStandardAction::keyBindings (this, SLOT (slotKeyBindings()), ac); + d->actionKeyBindings = KStandardAction::keyBindings(this, SLOT(slotKeyBindings()), ac); KStandardAction::configureToolbars(this, SLOT(configureToolbars()), actionCollection()); - enableSettingsMenuDocumentActions (false); + enableSettingsMenuDocumentActions(false); } //--------------------------------------------------------------------- // private -void kpMainWindow::enableSettingsMenuDocumentActions (bool /*enable*/) +void kpMainWindow::enableSettingsMenuDocumentActions(bool /*enable*/) { } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotFullScreen () +void kpMainWindow::slotFullScreen() { - KToggleFullScreenAction::setFullScreen( this, d->actionFullScreen->isChecked ()); + KToggleFullScreenAction::setFullScreen(this, d->actionFullScreen->isChecked()); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotEnableSettingsShowPath () +void kpMainWindow::slotEnableSettingsShowPath() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotEnableSettingsShowPath()"; #endif - const bool enable = (d->document && !d->document->url ().isEmpty ()); + const bool enable = (d->document && !d->document->url().isEmpty()); - d->actionShowPath->setEnabled (enable); - d->actionShowPath->setChecked (enable && d->configShowPath); + d->actionShowPath->setEnabled(enable); + d->actionShowPath->setChecked(enable && d->configShowPath); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotShowPathToggled () +void kpMainWindow::slotShowPathToggled() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotShowPathToggled()"; #endif - d->configShowPath = d->actionShowPath->isChecked (); - - slotUpdateCaption (); + d->configShowPath = d->actionShowPath->isChecked(); + slotUpdateCaption(); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupGeneral); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); - cfg.writeEntry (kpSettingShowPath, d->configShowPath); - cfg.sync (); + cfg.writeEntry(kpSettingShowPath, d->configShowPath); + cfg.sync(); } //--------------------------------------------------------------------- @@ -145,14 +139,13 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotKeyBindings () +void kpMainWindow::slotKeyBindings() { - toolEndShape (); + toolEndShape(); - if (KShortcutsDialog::configure (actionCollection (), - KShortcutsEditor::LetterShortcutsAllowed, - this)) - { + if (KShortcutsDialog::configure(actionCollection(), + KShortcutsEditor::LetterShortcutsAllowed, + this)) { // TODO: PROPAGATE: thru mainWindow's and interprocess } } diff --git a/mainWindow/kpMainWindow_StatusBar.cpp b/mainWindow/kpMainWindow_StatusBar.cpp --- a/mainWindow/kpMainWindow_StatusBar.cpp +++ b/mainWindow/kpMainWindow_StatusBar.cpp @@ -27,7 +27,6 @@ #define DEBUG_STATUS_BAR (DEBUG_KP_MAIN_WINDOW && 0) - #include "mainWindow/kpMainWindow.h" #include "kpMainWindowPrivate.h" @@ -49,29 +48,29 @@ //--------------------------------------------------------------------- // private -void kpMainWindow::addPermanentStatusBarItem (int id, int maxTextLen) +void kpMainWindow::addPermanentStatusBarItem(int id, int maxTextLen) { - QStatusBar *sb = statusBar (); + QStatusBar *sb = statusBar(); - QLabel *label = new QLabel (sb); - label->setAlignment (Qt::AlignCenter); - label->setFixedHeight (label->fontMetrics ().height () + 2); - int maxWidth = label->fontMetrics ().width (QLatin1Char ('8')) * maxTextLen; + QLabel *label = new QLabel(sb); + label->setAlignment(Qt::AlignCenter); + label->setFixedHeight(label->fontMetrics().height() + 2); + int maxWidth = label->fontMetrics().width(QLatin1Char('8')) * maxTextLen; // add some margins - maxWidth += label->fontMetrics ().height (); - label->setFixedWidth (maxWidth); + maxWidth += label->fontMetrics().height(); + label->setFixedWidth(maxWidth); // Permanent --> place on the right - sb->addPermanentWidget (label); + sb->addPermanentWidget(label); - d->statusBarLabels.append (label); - Q_ASSERT (d->statusBarLabels.at(id) == label); + d->statusBarLabels.append(label); + Q_ASSERT(d->statusBarLabels.at(id) == label); } //--------------------------------------------------------------------- // private -void kpMainWindow::createStatusBar () +void kpMainWindow::createStatusBar() { QStatusBar *sb = statusBar(); @@ -82,20 +81,20 @@ // this is done to have the same height as the other labels in status bar; done like in kstatusbar.cpp d->statusBarMessageLabel->setFixedHeight(d->statusBarMessageLabel->fontMetrics().height() + 2); d->statusBarMessageLabel->setTextElideMode(Qt::ElideRight); // this is the reason why we explicitly set a widget - sb->addWidget(d->statusBarMessageLabel, 1/*stretch*/); + sb->addWidget(d->statusBarMessageLabel, 1 /*stretch*/); - addPermanentStatusBarItem (StatusBarItemShapePoints, - (maxDimenLength + 1/*,*/ + maxDimenLength) * 2 + 3/* - */); - addPermanentStatusBarItem (StatusBarItemShapeSize, - (1/*+/-*/ + maxDimenLength) * 2 + 1/*x*/); + addPermanentStatusBarItem(StatusBarItemShapePoints, + (maxDimenLength + 1 /*,*/ + maxDimenLength) * 2 + 3 /* - */); + addPermanentStatusBarItem(StatusBarItemShapeSize, + (1 /*+/-*/ + maxDimenLength) * 2 + 1 /*x*/); QString numSample = i18n("%1 x %2", 5000, 5000); // localized string; can e.g. be "5 000" addPermanentStatusBarItem(StatusBarItemDocSize, numSample.length()); - addPermanentStatusBarItem(StatusBarItemDocDepth, 5/*XXbpp*/); + addPermanentStatusBarItem(StatusBarItemDocDepth, 5 /*XXbpp*/); - addPermanentStatusBarItem (StatusBarItemZoom, - 5/*1600%*/); + addPermanentStatusBarItem(StatusBarItemZoom, + 5 /*1600%*/); d->statusBarShapeLastPointsInitialised = false; d->statusBarShapeLastSizeInitialised = false; @@ -105,65 +104,58 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::setStatusBarMessage (const QString &message) +void kpMainWindow::setStatusBarMessage(const QString &message) { #if DEBUG_STATUS_BAR && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::setStatusBarMessage(" - << message - << ") ok=" << d->statusBarCreated; + << message + << ") ok=" << d->statusBarCreated; #endif if (!d->statusBarCreated) { return; } - d->statusBarMessageLabel->setText (message); + d->statusBarMessageLabel->setText(message); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::setStatusBarShapePoints (const QPoint &startPoint, - const QPoint &endPoint) +void kpMainWindow::setStatusBarShapePoints(const QPoint &startPoint, const QPoint &endPoint) { #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "kpMainWindow::setStatusBarShapePoints(" - << startPoint << "," << endPoint - << ") ok=" << d->statusBarCreated; + << startPoint << "," << endPoint + << ") ok=" << d->statusBarCreated; #endif if (!d->statusBarCreated) { return; } - if (d->statusBarShapeLastPointsInitialised && - startPoint == d->statusBarShapeLastStartPoint && - endPoint == d->statusBarShapeLastEndPoint) - { + if (d->statusBarShapeLastPointsInitialised + && startPoint == d->statusBarShapeLastStartPoint + && endPoint == d->statusBarShapeLastEndPoint) { #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "\tNOP"; #endif return; } - QLabel *statusBarLabel = d->statusBarLabels.at (StatusBarItemShapePoints); - if (startPoint == KP_INVALID_POINT) - { - statusBarLabel->setText (QString()); - } - else if (endPoint == KP_INVALID_POINT) - { - statusBarLabel->setText (i18n ("%1,%2", - startPoint.x (), - startPoint.y ())); - } - else - { - statusBarLabel->setText (i18n ("%1,%2 - %3,%4", - startPoint.x (), - startPoint.y (), - endPoint.x (), - endPoint.y ())); + QLabel *statusBarLabel = d->statusBarLabels.at(StatusBarItemShapePoints); + if (startPoint == KP_INVALID_POINT) { + statusBarLabel->setText(QString()); + } else if (endPoint == KP_INVALID_POINT) { + statusBarLabel->setText(i18n("%1,%2", + startPoint.x(), + startPoint.y())); + } else { + statusBarLabel->setText(i18n("%1,%2 - %3,%4", + startPoint.x(), + startPoint.y(), + endPoint.x(), + endPoint.y())); } d->statusBarShapeLastStartPoint = startPoint; @@ -174,37 +166,33 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::setStatusBarShapeSize (const QSize &size) +void kpMainWindow::setStatusBarShapeSize(const QSize &size) { #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "kpMainWindow::setStatusBarShapeSize(" - << size - << ") ok=" << d->statusBarCreated; + << size + << ") ok=" << d->statusBarCreated; #endif if (!d->statusBarCreated) { return; } - if (d->statusBarShapeLastSizeInitialised && - size == d->statusBarShapeLastSize) - { + if (d->statusBarShapeLastSizeInitialised + && size == d->statusBarShapeLastSize) { #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "\tNOP"; #endif return; } - QLabel *statusBarLabel = d->statusBarLabels.at (StatusBarItemShapeSize); - if (size == KP_INVALID_SIZE) - { - statusBarLabel->setText (QString()); - } - else - { - statusBarLabel->setText (i18n ("%1x%2", - size.width (), - size.height ())); + QLabel *statusBarLabel = d->statusBarLabels.at(StatusBarItemShapeSize); + if (size == KP_INVALID_SIZE) { + statusBarLabel->setText(QString()); + } else { + statusBarLabel->setText(i18n("%1x%2", + size.width(), + size.height())); } d->statusBarShapeLastSize = size; @@ -214,226 +202,196 @@ //--------------------------------------------------------------------- // private slot -void kpMainWindow::setStatusBarDocSize (const QSize &size) +void kpMainWindow::setStatusBarDocSize(const QSize &size) { #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "kpMainWindow::setStatusBarDocSize(" - << size - << ") ok=" << d->statusBarCreated; + << size + << ") ok=" << d->statusBarCreated; #endif if (!d->statusBarCreated) { return; } - QLabel *statusBarLabel = d->statusBarLabels.at (StatusBarItemDocSize); - if (size == KP_INVALID_SIZE) - { - statusBarLabel->setText (QString()); - } - else - { - statusBarLabel->setText (i18n ("%1 x %2", - size.width (), - size.height ())); + QLabel *statusBarLabel = d->statusBarLabels.at(StatusBarItemDocSize); + if (size == KP_INVALID_SIZE) { + statusBarLabel->setText(QString()); + } else { + statusBarLabel->setText(i18n("%1 x %2", + size.width(), + size.height())); } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::setStatusBarDocDepth (int depth) +void kpMainWindow::setStatusBarDocDepth(int depth) { #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "kpMainWindow::setStatusBarDocDepth(" - << depth - << ") ok=" << d->statusBarCreated; + << depth + << ") ok=" << d->statusBarCreated; #endif if (!d->statusBarCreated) { return; } - QLabel *statusBarLabel = d->statusBarLabels.at (StatusBarItemDocDepth); - if (depth <= 0) - { - statusBarLabel->setText (QString()); - } - else - { - statusBarLabel->setText (i18n ("%1bpp", depth)); + QLabel *statusBarLabel = d->statusBarLabels.at(StatusBarItemDocDepth); + if (depth <= 0) { + statusBarLabel->setText(QString()); + } else { + statusBarLabel->setText(i18n("%1bpp", depth)); } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::setStatusBarZoom (int zoom) +void kpMainWindow::setStatusBarZoom(int zoom) { #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "kpMainWindow::setStatusBarZoom(" - << zoom - << ") ok=" << d->statusBarCreated; + << zoom + << ") ok=" << d->statusBarCreated; #endif if (!d->statusBarCreated) { return; } - QLabel *statusBarLabel = d->statusBarLabels.at (StatusBarItemZoom); - if (zoom <= 0) - { - statusBarLabel->setText (QString()); - } - else - { - statusBarLabel->setText (i18n ("%1%", zoom)); + QLabel *statusBarLabel = d->statusBarLabels.at(StatusBarItemZoom); + if (zoom <= 0) { + statusBarLabel->setText(QString()); + } else { + statusBarLabel->setText(i18n("%1%", zoom)); } } //--------------------------------------------------------------------- -void kpMainWindow::recalculateStatusBarMessage () +void kpMainWindow::recalculateStatusBarMessage() { #if DEBUG_STATUS_BAR && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::recalculateStatusBarMessage()"; #endif - QString scrollViewMessage = d->scrollView->statusMessage (); + QString scrollViewMessage = d->scrollView->statusMessage(); #if DEBUG_STATUS_BAR && 1 qCDebug(kpLogMainWindow) << "\tscrollViewMessage=" << scrollViewMessage; - qCDebug(kpLogMainWindow) << "\tresizing doc? " << !d->scrollView->newDocSize ().isEmpty (); + qCDebug(kpLogMainWindow) << "\tresizing doc? " << !d->scrollView->newDocSize().isEmpty(); qCDebug(kpLogMainWindow) << "\tviewUnderCursor? " - << (d->viewManager && d->viewManager->viewUnderCursor ()); + << (d->viewManager && d->viewManager->viewUnderCursor()); #endif // HACK: To work around kpViewScrollableContainer's unreliable // status messages (which in turn is due to Qt not updating // QWidget::underMouse() on drags and we needing to hack around it) - if (!scrollViewMessage.isEmpty () && - d->scrollView->newDocSize ().isEmpty () && - d->viewManager && d->viewManager->viewUnderCursor ()) - { + if (!scrollViewMessage.isEmpty() + && d->scrollView->newDocSize().isEmpty() + && d->viewManager && d->viewManager->viewUnderCursor()) { #if DEBUG_STATUS_BAR && 1 - qCDebug(kpLogMainWindow) << "\t\tnot resizing & viewUnderCursor - message is wrong - clearing"; + qCDebug(kpLogMainWindow) + << "\t\tnot resizing & viewUnderCursor - message is wrong - clearing"; #endif - d->scrollView->blockSignals (true); - d->scrollView->clearStatusMessage (); - d->scrollView->blockSignals (false); + d->scrollView->blockSignals(true); + d->scrollView->clearStatusMessage(); + d->scrollView->blockSignals(false); - scrollViewMessage.clear (); + scrollViewMessage.clear(); #if DEBUG_STATUS_BAR && 1 qCDebug(kpLogMainWindow) << "\t\t\tdone"; #endif } - if (!scrollViewMessage.isEmpty ()) - { - setStatusBarMessage (scrollViewMessage); - } - else - { - const kpTool *t = tool (); - if (t) - { - setStatusBarMessage (t->userMessage ()); - } - else - { - setStatusBarMessage (); + if (!scrollViewMessage.isEmpty()) { + setStatusBarMessage(scrollViewMessage); + } else { + const kpTool *t = tool(); + if (t) { + setStatusBarMessage(t->userMessage()); + } else { + setStatusBarMessage(); } } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::recalculateStatusBarShape () +void kpMainWindow::recalculateStatusBarShape() { #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "kpMainWindow::recalculateStatusBarShape()"; #endif - QSize docResizeTo = d->scrollView->newDocSize (); + QSize docResizeTo = d->scrollView->newDocSize(); #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "\tdocResizeTo=" << docResizeTo; #endif - if (docResizeTo.isValid ()) - { - const QPoint startPoint (d->document->width (), d->document->height ()); + if (docResizeTo.isValid()) { + const QPoint startPoint(d->document->width(), d->document->height()); #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "\thavedMovedFromOrgSize=" - << d->scrollView->haveMovedFromOriginalDocSize (); + << d->scrollView->haveMovedFromOriginalDocSize(); #endif - if (!d->scrollView->haveMovedFromOriginalDocSize ()) - { - setStatusBarShapePoints (startPoint); - setStatusBarShapeSize (); + if (!d->scrollView->haveMovedFromOriginalDocSize()) { + setStatusBarShapePoints(startPoint); + setStatusBarShapeSize(); + } else { + const int newWidth = docResizeTo.width(); + const int newHeight = docResizeTo.height(); + + setStatusBarShapePoints(startPoint, QPoint(newWidth, newHeight)); + const QPoint sizeAsPoint(QPoint(newWidth, newHeight) - startPoint); + setStatusBarShapeSize(QSize(sizeAsPoint.x(), sizeAsPoint.y())); } - else - { - const int newWidth = docResizeTo.width (); - const int newHeight = docResizeTo.height (); - - setStatusBarShapePoints (startPoint, QPoint (newWidth, newHeight)); - const QPoint sizeAsPoint (QPoint (newWidth, newHeight) - startPoint); - setStatusBarShapeSize (QSize (sizeAsPoint.x (), sizeAsPoint.y ())); - } - } - else - { - const kpTool *t = tool (); + } else { + const kpTool *t = tool(); #if DEBUG_STATUS_BAR && 0 qCDebug(kpLogMainWindow) << "\ttool=" << t; #endif - if (t) - { - setStatusBarShapePoints (t->userShapeStartPoint (), - t->userShapeEndPoint ()); - setStatusBarShapeSize (t->userShapeSize ()); - } - else - { - setStatusBarShapePoints (); - setStatusBarShapeSize (); + if (t) { + setStatusBarShapePoints(t->userShapeStartPoint(), + t->userShapeEndPoint()); + setStatusBarShapeSize(t->userShapeSize()); + } else { + setStatusBarShapePoints(); + setStatusBarShapeSize(); } } } //--------------------------------------------------------------------- // private slot -void kpMainWindow::recalculateStatusBar () +void kpMainWindow::recalculateStatusBar() { #if DEBUG_STATUS_BAR && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::recalculateStatusBar() ok=" - << d->statusBarCreated; + << d->statusBarCreated; #endif if (!d->statusBarCreated) { return; } - recalculateStatusBarMessage (); - recalculateStatusBarShape (); + recalculateStatusBarMessage(); + recalculateStatusBarShape(); - if (d->document) - { - setStatusBarDocSize (QSize (d->document->width (), d->document->height ())); - setStatusBarDocDepth (d->document->image ().depth ()); - } - else - { - setStatusBarDocSize (); - setStatusBarDocDepth (); + if (d->document) { + setStatusBarDocSize(QSize(d->document->width(), d->document->height())); + setStatusBarDocDepth(d->document->image().depth()); + } else { + setStatusBarDocSize(); + setStatusBarDocDepth(); } - if (d->mainView) - { - setStatusBarZoom (d->mainView->zoomLevelX ()); - } - else - { - setStatusBarZoom (); + if (d->mainView) { + setStatusBarZoom(d->mainView->zoomLevelX()); + } else { + setStatusBarZoom(); } } diff --git a/mainWindow/kpMainWindow_Text.cpp b/mainWindow/kpMainWindow_Text.cpp --- a/mainWindow/kpMainWindow_Text.cpp +++ b/mainWindow/kpMainWindow_Text.cpp @@ -24,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "mainWindow/kpMainWindow.h" #include "kpMainWindowPrivate.h" @@ -47,390 +46,359 @@ #include "widgets/toolbars/options/kpToolWidgetOpaqueOrTransparent.h" #include "views/kpZoomedView.h" - // private -void kpMainWindow::setupTextToolBarActions () +void kpMainWindow::setupTextToolBarActions() { - KActionCollection *ac = actionCollection (); + KActionCollection *ac = actionCollection(); - d->actionTextFontFamily = ac->add (QStringLiteral("text_font_family")); - d->actionTextFontFamily->setText (i18n ("Font Family")); - connect (d->actionTextFontFamily, - static_cast(&KFontAction::triggered), - this, &kpMainWindow::slotTextFontFamilyChanged); + d->actionTextFontFamily = ac->add(QStringLiteral("text_font_family")); + d->actionTextFontFamily->setText(i18n("Font Family")); + connect(d->actionTextFontFamily, + static_cast(&KFontAction::triggered), + this, &kpMainWindow::slotTextFontFamilyChanged); - d->actionTextFontSize = ac->add (QStringLiteral("text_font_size")); - d->actionTextFontSize->setText (i18n ("Font Size")); - connect (d->actionTextFontSize, - static_cast(&KFontSizeAction::triggered), - this, &kpMainWindow::slotTextFontSizeChanged); + d->actionTextFontSize = ac->add(QStringLiteral("text_font_size")); + d->actionTextFontSize->setText(i18n("Font Size")); + connect(d->actionTextFontSize, + static_cast(&KFontSizeAction::triggered), + this, &kpMainWindow::slotTextFontSizeChanged); - d->actionTextBold = ac->add (QStringLiteral("text_bold")); + d->actionTextBold = ac->add(QStringLiteral("text_bold")); d->actionTextBold->setIcon(KDE::icon(QStringLiteral("format-text-bold"))); - d->actionTextBold->setText (i18n ("Bold")); - connect (d->actionTextBold, &KToggleAction::triggered, - this, &kpMainWindow::slotTextBoldChanged); - - d->actionTextItalic = ac->add (QStringLiteral("text_italic")); - d->actionTextItalic->setIcon (KDE::icon(QStringLiteral("format-text-italic"))); - d->actionTextItalic->setText (i18n ("Italic")); - connect (d->actionTextItalic, &KToggleAction::triggered, - this, &kpMainWindow::slotTextItalicChanged); - - d->actionTextUnderline = ac->add (QStringLiteral("text_underline")); - d->actionTextUnderline->setIcon (KDE::icon(QStringLiteral("format-text-underline"))); - d->actionTextUnderline->setText (i18n ("Underline")); - connect (d->actionTextUnderline, &KToggleAction::triggered, - this, &kpMainWindow::slotTextUnderlineChanged); - - d->actionTextStrikeThru = ac->add (QStringLiteral("text_strike_thru")); + d->actionTextBold->setText(i18n("Bold")); + connect(d->actionTextBold, &KToggleAction::triggered, + this, &kpMainWindow::slotTextBoldChanged); + + d->actionTextItalic = ac->add(QStringLiteral("text_italic")); + d->actionTextItalic->setIcon(KDE::icon(QStringLiteral("format-text-italic"))); + d->actionTextItalic->setText(i18n("Italic")); + connect(d->actionTextItalic, &KToggleAction::triggered, + this, &kpMainWindow::slotTextItalicChanged); + + d->actionTextUnderline = ac->add(QStringLiteral("text_underline")); + d->actionTextUnderline->setIcon(KDE::icon(QStringLiteral("format-text-underline"))); + d->actionTextUnderline->setText(i18n("Underline")); + connect(d->actionTextUnderline, &KToggleAction::triggered, + this, &kpMainWindow::slotTextUnderlineChanged); + + d->actionTextStrikeThru = ac->add(QStringLiteral("text_strike_thru")); d->actionTextStrikeThru->setIcon(KDE::icon(QStringLiteral("format-text-strikethrough"))); - d->actionTextStrikeThru->setText (i18n ("Strike Through")); - connect (d->actionTextStrikeThru, &KToggleAction::triggered, - this, &kpMainWindow::slotTextStrikeThruChanged); - - - readAndApplyTextSettings (); + d->actionTextStrikeThru->setText(i18n("Strike Through")); + connect(d->actionTextStrikeThru, &KToggleAction::triggered, + this, &kpMainWindow::slotTextStrikeThruChanged); + readAndApplyTextSettings(); - enableTextToolBarActions (false); + enableTextToolBarActions(false); } // private -void kpMainWindow::readAndApplyTextSettings () +void kpMainWindow::readAndApplyTextSettings() { - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupText); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupText); - const QString font (cfg.readEntry (kpSettingFontFamily, QStringLiteral ("Times"))); - d->actionTextFontFamily->setFont (font); + const QString font(cfg.readEntry(kpSettingFontFamily, QStringLiteral("Times"))); + d->actionTextFontFamily->setFont(font); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "asked setFont to set to=" << font - << "- got back=" << d->actionTextFontFamily->font (); + << "- got back=" << d->actionTextFontFamily->font(); #endif - d->actionTextFontSize->setFontSize (cfg.readEntry (kpSettingFontSize, 14)); - d->actionTextBold->setChecked (cfg.readEntry (kpSettingBold, false)); - d->actionTextItalic->setChecked (cfg.readEntry (kpSettingItalic, false)); - d->actionTextUnderline->setChecked (cfg.readEntry (kpSettingUnderline, false)); - d->actionTextStrikeThru->setChecked (cfg.readEntry (kpSettingStrikeThru, false)); - - d->textOldFontFamily = d->actionTextFontFamily->font (); - d->textOldFontSize = d->actionTextFontSize->fontSize (); + d->actionTextFontSize->setFontSize(cfg.readEntry(kpSettingFontSize, 14)); + d->actionTextBold->setChecked(cfg.readEntry(kpSettingBold, false)); + d->actionTextItalic->setChecked(cfg.readEntry(kpSettingItalic, false)); + d->actionTextUnderline->setChecked(cfg.readEntry(kpSettingUnderline, false)); + d->actionTextStrikeThru->setChecked(cfg.readEntry(kpSettingStrikeThru, false)); + + d->textOldFontFamily = d->actionTextFontFamily->font(); + d->textOldFontSize = d->actionTextFontSize->fontSize(); } - // public -void kpMainWindow::enableTextToolBarActions (bool enable) +void kpMainWindow::enableTextToolBarActions(bool enable) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::enableTextToolBarActions(" << enable << ")"; #endif - d->actionTextFontFamily->setEnabled (enable); - d->actionTextFontSize->setEnabled (enable); - d->actionTextBold->setEnabled (enable); - d->actionTextItalic->setEnabled (enable); - d->actionTextUnderline->setEnabled (enable); - d->actionTextStrikeThru->setEnabled (enable); + d->actionTextFontFamily->setEnabled(enable); + d->actionTextFontSize->setEnabled(enable); + d->actionTextBold->setEnabled(enable); + d->actionTextItalic->setEnabled(enable); + d->actionTextUnderline->setEnabled(enable); + d->actionTextStrikeThru->setEnabled(enable); - if (textToolBar ()) - { + if (textToolBar()) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\thave toolbar - setShown"; #endif // COMPAT: KDE4 does not place the Text Tool Bar in a new row, underneath // the Main Tool Bar, if there isn't enough room. This makes // accessing the Text Tool Bar's buttons difficult. - textToolBar ()->setVisible (enable); + textToolBar()->setVisible(enable); } } - // private slot -void kpMainWindow::slotTextFontFamilyChanged () +void kpMainWindow::slotTextFontFamilyChanged() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotTextFontFamilyChanged() alive=" - << d->isFullyConstructed - << "fontFamily=" - << d->actionTextFontFamily->font () - << "action.currentItem=" - << d->actionTextFontFamily->currentItem (); + << d->isFullyConstructed + << "fontFamily=" + << d->actionTextFontFamily->font() + << "action.currentItem=" + << d->actionTextFontFamily->currentItem(); #endif if (!d->isFullyConstructed) { return; } - if (d->toolText && d->toolText->hasBegun ()) - { - toolEndShape (); - d->toolText->slotFontFamilyChanged (d->actionTextFontFamily->font (), + if (d->toolText && d->toolText->hasBegun()) { + toolEndShape(); + d->toolText->slotFontFamilyChanged(d->actionTextFontFamily->font(), d->textOldFontFamily); } // Since editable KSelectAction's steal focus from view, switch back to mainView // TODO: back to the last view if (d->mainView) { - d->mainView->setFocus (); + d->mainView->setFocus(); } - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupText); - cfg.writeEntry (kpSettingFontFamily, d->actionTextFontFamily->font ()); - cfg.sync (); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupText); + cfg.writeEntry(kpSettingFontFamily, d->actionTextFontFamily->font()); + cfg.sync(); - d->textOldFontFamily = d->actionTextFontFamily->font (); + d->textOldFontFamily = d->actionTextFontFamily->font(); } // private slot -void kpMainWindow::slotTextFontSizeChanged () +void kpMainWindow::slotTextFontSizeChanged() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotTextFontSizeChanged() alive=" - << d->isFullyConstructed - << " fontSize=" - << d->actionTextFontSize->fontSize (); + << d->isFullyConstructed + << " fontSize=" + << d->actionTextFontSize->fontSize(); #endif if (!d->isFullyConstructed) { return; } - if (d->toolText && d->toolText->hasBegun ()) - { - toolEndShape (); - d->toolText->slotFontSizeChanged (d->actionTextFontSize->fontSize (), + if (d->toolText && d->toolText->hasBegun()) { + toolEndShape(); + d->toolText->slotFontSizeChanged(d->actionTextFontSize->fontSize(), d->textOldFontSize); } // Since editable KSelectAction's steal focus from view, switch back to mainView // TODO: back to the last view if (d->mainView) { - d->mainView->setFocus (); + d->mainView->setFocus(); } - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupText); - cfg.writeEntry (kpSettingFontSize, d->actionTextFontSize->fontSize ()); - cfg.sync (); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupText); + cfg.writeEntry(kpSettingFontSize, d->actionTextFontSize->fontSize()); + cfg.sync(); - d->textOldFontSize = d->actionTextFontSize->fontSize (); + d->textOldFontSize = d->actionTextFontSize->fontSize(); } // private slot -void kpMainWindow::slotTextBoldChanged () +void kpMainWindow::slotTextBoldChanged() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotTextFontBoldChanged() alive=" - << d->isFullyConstructed - << " bold=" - << d->actionTextBold->isChecked (); + << d->isFullyConstructed + << " bold=" + << d->actionTextBold->isChecked(); #endif if (!d->isFullyConstructed) { return; } - if (d->toolText && d->toolText->hasBegun ()) - { - toolEndShape (); - d->toolText->slotBoldChanged (d->actionTextBold->isChecked ()); + if (d->toolText && d->toolText->hasBegun()) { + toolEndShape(); + d->toolText->slotBoldChanged(d->actionTextBold->isChecked()); } - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupText); - cfg.writeEntry (kpSettingBold, d->actionTextBold->isChecked ()); - cfg.sync (); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupText); + cfg.writeEntry(kpSettingBold, d->actionTextBold->isChecked()); + cfg.sync(); } // private slot -void kpMainWindow::slotTextItalicChanged () +void kpMainWindow::slotTextItalicChanged() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotTextFontItalicChanged() alive=" - << d->isFullyConstructed - << " bold=" - << d->actionTextItalic->isChecked (); + << d->isFullyConstructed + << " bold=" + << d->actionTextItalic->isChecked(); #endif if (!d->isFullyConstructed) { return; } - if (d->toolText && d->toolText->hasBegun ()) - { - toolEndShape (); - d->toolText->slotItalicChanged (d->actionTextItalic->isChecked ()); + if (d->toolText && d->toolText->hasBegun()) { + toolEndShape(); + d->toolText->slotItalicChanged(d->actionTextItalic->isChecked()); } - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupText); - cfg.writeEntry (kpSettingItalic, d->actionTextItalic->isChecked ()); - cfg.sync (); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupText); + cfg.writeEntry(kpSettingItalic, d->actionTextItalic->isChecked()); + cfg.sync(); } // private slot -void kpMainWindow::slotTextUnderlineChanged () +void kpMainWindow::slotTextUnderlineChanged() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotTextFontUnderlineChanged() alive=" - << d->isFullyConstructed - << " underline=" - << d->actionTextUnderline->isChecked (); + << d->isFullyConstructed + << " underline=" + << d->actionTextUnderline->isChecked(); #endif if (!d->isFullyConstructed) { return; } - if (d->toolText && d->toolText->hasBegun ()) - { - toolEndShape (); - d->toolText->slotUnderlineChanged (d->actionTextUnderline->isChecked ()); + if (d->toolText && d->toolText->hasBegun()) { + toolEndShape(); + d->toolText->slotUnderlineChanged(d->actionTextUnderline->isChecked()); } - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupText); - cfg.writeEntry (kpSettingUnderline, d->actionTextUnderline->isChecked ()); - cfg.sync (); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupText); + cfg.writeEntry(kpSettingUnderline, d->actionTextUnderline->isChecked()); + cfg.sync(); } // private slot -void kpMainWindow::slotTextStrikeThruChanged () +void kpMainWindow::slotTextStrikeThruChanged() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotTextStrikeThruChanged() alive=" - << d->isFullyConstructed - << " strikeThru=" - << d->actionTextStrikeThru->isChecked (); + << d->isFullyConstructed + << " strikeThru=" + << d->actionTextStrikeThru->isChecked(); #endif if (!d->isFullyConstructed) { return; } - if (d->toolText && d->toolText->hasBegun ()) - { - toolEndShape (); - d->toolText->slotStrikeThruChanged (d->actionTextStrikeThru->isChecked ()); + if (d->toolText && d->toolText->hasBegun()) { + toolEndShape(); + d->toolText->slotStrikeThruChanged(d->actionTextStrikeThru->isChecked()); } - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupText); - cfg.writeEntry (kpSettingStrikeThru, d->actionTextStrikeThru->isChecked ()); - cfg.sync (); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupText); + cfg.writeEntry(kpSettingStrikeThru, d->actionTextStrikeThru->isChecked()); + cfg.sync(); } - // public -KToolBar *kpMainWindow::textToolBar () +KToolBar *kpMainWindow::textToolBar() { - return toolBar (QStringLiteral("textToolBar")); + return toolBar(QStringLiteral("textToolBar")); } -bool kpMainWindow::isTextStyleBackgroundOpaque () const +bool kpMainWindow::isTextStyleBackgroundOpaque() const { - if (d->toolToolBar) - { - kpToolWidgetOpaqueOrTransparent *oot = - d->toolToolBar->toolWidgetOpaqueOrTransparent (); - - if (oot) - { - return oot->isOpaque (); + if (d->toolToolBar) { + kpToolWidgetOpaqueOrTransparent *oot + = d->toolToolBar->toolWidgetOpaqueOrTransparent(); + + if (oot) { + return oot->isOpaque(); } } return true; } // public -kpTextStyle kpMainWindow::textStyle () const +kpTextStyle kpMainWindow::textStyle() const { - return kpTextStyle (d->actionTextFontFamily->font (), - d->actionTextFontSize->fontSize (), - d->actionTextBold->isChecked (), - d->actionTextItalic->isChecked (), - d->actionTextUnderline->isChecked (), - d->actionTextStrikeThru->isChecked (), - d->colorToolBar ? d->colorToolBar->foregroundColor () : kpColor::Invalid, - d->colorToolBar ? d->colorToolBar->backgroundColor () : kpColor::Invalid, - isTextStyleBackgroundOpaque ()); + return kpTextStyle(d->actionTextFontFamily->font(), + d->actionTextFontSize->fontSize(), + d->actionTextBold->isChecked(), + d->actionTextItalic->isChecked(), + d->actionTextUnderline->isChecked(), + d->actionTextStrikeThru->isChecked(), + d->colorToolBar ? d->colorToolBar->foregroundColor() : kpColor::Invalid, + d->colorToolBar ? d->colorToolBar->backgroundColor() : kpColor::Invalid, + isTextStyleBackgroundOpaque()); } // public -void kpMainWindow::setTextStyle (const kpTextStyle &textStyle_) +void kpMainWindow::setTextStyle(const kpTextStyle &textStyle_) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::setTextStyle()"; #endif d->settingTextStyle++; - - if (textStyle_.fontFamily () != d->actionTextFontFamily->font ()) - { - d->actionTextFontFamily->setFont (textStyle_.fontFamily ()); - slotTextFontFamilyChanged (); + if (textStyle_.fontFamily() != d->actionTextFontFamily->font()) { + d->actionTextFontFamily->setFont(textStyle_.fontFamily()); + slotTextFontFamilyChanged(); } - if (textStyle_.fontSize () != d->actionTextFontSize->fontSize ()) - { - d->actionTextFontSize->setFontSize (textStyle_.fontSize ()); - slotTextFontSizeChanged (); + if (textStyle_.fontSize() != d->actionTextFontSize->fontSize()) { + d->actionTextFontSize->setFontSize(textStyle_.fontSize()); + slotTextFontSizeChanged(); } - if (textStyle_.isBold () != d->actionTextBold->isChecked ()) - { - d->actionTextBold->setChecked (textStyle_.isBold ()); - slotTextBoldChanged (); + if (textStyle_.isBold() != d->actionTextBold->isChecked()) { + d->actionTextBold->setChecked(textStyle_.isBold()); + slotTextBoldChanged(); } - if (textStyle_.isItalic () != d->actionTextItalic->isChecked ()) - { - d->actionTextItalic->setChecked (textStyle_.isItalic ()); - slotTextItalicChanged (); + if (textStyle_.isItalic() != d->actionTextItalic->isChecked()) { + d->actionTextItalic->setChecked(textStyle_.isItalic()); + slotTextItalicChanged(); } - if (textStyle_.isUnderline () != d->actionTextUnderline->isChecked ()) - { - d->actionTextUnderline->setChecked (textStyle_.isUnderline ()); - slotTextUnderlineChanged (); + if (textStyle_.isUnderline() != d->actionTextUnderline->isChecked()) { + d->actionTextUnderline->setChecked(textStyle_.isUnderline()); + slotTextUnderlineChanged(); } - if (textStyle_.isStrikeThru () != d->actionTextStrikeThru->isChecked ()) - { - d->actionTextStrikeThru->setChecked (textStyle_.isStrikeThru ()); - slotTextStrikeThruChanged (); + if (textStyle_.isStrikeThru() != d->actionTextStrikeThru->isChecked()) { + d->actionTextStrikeThru->setChecked(textStyle_.isStrikeThru()); + slotTextStrikeThruChanged(); } - - if (textStyle_.foregroundColor () != d->colorToolBar->foregroundColor ()) - { - d->colorToolBar->setForegroundColor (textStyle_.foregroundColor ()); + if (textStyle_.foregroundColor() != d->colorToolBar->foregroundColor()) { + d->colorToolBar->setForegroundColor(textStyle_.foregroundColor()); } - if (textStyle_.backgroundColor () != d->colorToolBar->backgroundColor ()) - { - d->colorToolBar->setBackgroundColor (textStyle_.backgroundColor ()); + if (textStyle_.backgroundColor() != d->colorToolBar->backgroundColor()) { + d->colorToolBar->setBackgroundColor(textStyle_.backgroundColor()); } + if (textStyle_.isBackgroundOpaque() != isTextStyleBackgroundOpaque()) { + if (d->toolToolBar) { + kpToolWidgetOpaqueOrTransparent *oot + = d->toolToolBar->toolWidgetOpaqueOrTransparent(); - if (textStyle_.isBackgroundOpaque () != isTextStyleBackgroundOpaque ()) - { - if (d->toolToolBar) - { - kpToolWidgetOpaqueOrTransparent *oot = - d->toolToolBar->toolWidgetOpaqueOrTransparent (); - - if (oot) - { - oot->setOpaque (textStyle_.isBackgroundOpaque ()); + if (oot) { + oot->setOpaque(textStyle_.isBackgroundOpaque()); } } } - d->settingTextStyle--; } // public -int kpMainWindow::settingTextStyle () const +int kpMainWindow::settingTextStyle() const { return d->settingTextStyle; } - diff --git a/mainWindow/kpMainWindow_Tools.cpp b/mainWindow/kpMainWindow_Tools.cpp --- a/mainWindow/kpMainWindow_Tools.cpp +++ b/mainWindow/kpMainWindow_Tools.cpp @@ -25,7 +25,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "mainWindow/kpMainWindow.h" #include "kpMainWindowPrivate.h" @@ -73,233 +72,222 @@ //--------------------------------------------------------------------- // private -kpToolSelectionEnvironment *kpMainWindow::toolSelectionEnvironment () +kpToolSelectionEnvironment *kpMainWindow::toolSelectionEnvironment() { if (!d->toolSelectionEnvironment) { - d->toolSelectionEnvironment = new kpToolSelectionEnvironment (this); + d->toolSelectionEnvironment = new kpToolSelectionEnvironment(this); } return d->toolSelectionEnvironment; } //--------------------------------------------------------------------- // private -kpToolEnvironment *kpMainWindow::toolEnvironment () +kpToolEnvironment *kpMainWindow::toolEnvironment() { // It's fine to return a more complex environment than required. - return toolSelectionEnvironment (); + return toolSelectionEnvironment(); } //--------------------------------------------------------------------- // private -void kpMainWindow::setupToolActions () +void kpMainWindow::setupToolActions() { - kpToolSelectionEnvironment *toolSelEnv = toolSelectionEnvironment (); - kpToolEnvironment *toolEnv = toolEnvironment (); - - d->tools.append (d->toolFreeFormSelection = new kpToolFreeFormSelection (toolSelEnv, this)); - d->tools.append (d->toolRectSelection = new kpToolRectSelection (toolSelEnv, this)); + kpToolSelectionEnvironment *toolSelEnv = toolSelectionEnvironment(); + kpToolEnvironment *toolEnv = toolEnvironment(); - d->tools.append (d->toolEllipticalSelection = new kpToolEllipticalSelection (toolSelEnv, this)); - d->tools.append (d->toolText = new kpToolText (toolSelEnv, this)); + d->tools.append(d->toolFreeFormSelection = new kpToolFreeFormSelection(toolSelEnv, this)); + d->tools.append(d->toolRectSelection = new kpToolRectSelection(toolSelEnv, this)); - d->tools.append (d->toolLine = new kpToolLine (toolEnv, this)); - d->tools.append (d->toolPen = new kpToolPen (toolEnv, this)); + d->tools.append(d->toolEllipticalSelection = new kpToolEllipticalSelection(toolSelEnv, this)); + d->tools.append(d->toolText = new kpToolText(toolSelEnv, this)); - d->tools.append (d->toolEraser = new kpToolEraser (toolEnv, this)); - d->tools.append (d->toolBrush = new kpToolBrush (toolEnv, this)); + d->tools.append(d->toolLine = new kpToolLine(toolEnv, this)); + d->tools.append(d->toolPen = new kpToolPen(toolEnv, this)); - d->tools.append (d->toolFloodFill = new kpToolFloodFill (toolEnv, this)); - d->tools.append (d->toolColorPicker = new kpToolColorPicker (toolEnv, this)); + d->tools.append(d->toolEraser = new kpToolEraser(toolEnv, this)); + d->tools.append(d->toolBrush = new kpToolBrush(toolEnv, this)); - d->tools.append (d->toolColorEraser = new kpToolColorEraser (toolEnv, this)); - d->tools.append (d->toolSpraycan = new kpToolSpraycan (toolEnv, this)); + d->tools.append(d->toolFloodFill = new kpToolFloodFill(toolEnv, this)); + d->tools.append(d->toolColorPicker = new kpToolColorPicker(toolEnv, this)); - d->tools.append (d->toolRoundedRectangle = new kpToolRoundedRectangle (toolEnv, this)); - d->tools.append (d->toolRectangle = new kpToolRectangle (toolEnv, this)); + d->tools.append(d->toolColorEraser = new kpToolColorEraser(toolEnv, this)); + d->tools.append(d->toolSpraycan = new kpToolSpraycan(toolEnv, this)); - d->tools.append (d->toolPolygon = new kpToolPolygon (toolEnv, this)); - d->tools.append (d->toolEllipse = new kpToolEllipse (toolEnv, this)); + d->tools.append(d->toolRoundedRectangle = new kpToolRoundedRectangle(toolEnv, this)); + d->tools.append(d->toolRectangle = new kpToolRectangle(toolEnv, this)); - d->tools.append (d->toolPolyline = new kpToolPolyline (toolEnv, this)); - d->tools.append (d->toolCurve = new kpToolCurve (toolEnv, this)); + d->tools.append(d->toolPolygon = new kpToolPolygon(toolEnv, this)); + d->tools.append(d->toolEllipse = new kpToolEllipse(toolEnv, this)); - d->tools.append (d->toolZoom = new kpToolZoom (toolEnv, this)); + d->tools.append(d->toolPolyline = new kpToolPolyline(toolEnv, this)); + d->tools.append(d->toolCurve = new kpToolCurve(toolEnv, this)); + d->tools.append(d->toolZoom = new kpToolZoom(toolEnv, this)); - KActionCollection *ac = actionCollection (); + KActionCollection *ac = actionCollection(); - d->actionPrevToolOptionGroup1 = ac->addAction (QStringLiteral("prev_tool_option_group_1")); - d->actionPrevToolOptionGroup1->setText (i18n ("Previous Tool Option (Group #1)")); - ac->setDefaultShortcuts (d->actionPrevToolOptionGroup1, kpTool::shortcutForKey (Qt::Key_1)); - connect (d->actionPrevToolOptionGroup1, &QAction::triggered, - this, &kpMainWindow::slotActionPrevToolOptionGroup1); + d->actionPrevToolOptionGroup1 = ac->addAction(QStringLiteral("prev_tool_option_group_1")); + d->actionPrevToolOptionGroup1->setText(i18n("Previous Tool Option (Group #1)")); + ac->setDefaultShortcuts(d->actionPrevToolOptionGroup1, kpTool::shortcutForKey(Qt::Key_1)); + connect(d->actionPrevToolOptionGroup1, &QAction::triggered, + this, &kpMainWindow::slotActionPrevToolOptionGroup1); - d->actionNextToolOptionGroup1 = ac->addAction (QStringLiteral("next_tool_option_group_1")); - d->actionNextToolOptionGroup1->setText (i18n ("Next Tool Option (Group #1)")); - ac->setDefaultShortcuts (d->actionNextToolOptionGroup1, kpTool::shortcutForKey (Qt::Key_2)); - connect (d->actionNextToolOptionGroup1, &QAction::triggered, - this, &kpMainWindow::slotActionNextToolOptionGroup1); + d->actionNextToolOptionGroup1 = ac->addAction(QStringLiteral("next_tool_option_group_1")); + d->actionNextToolOptionGroup1->setText(i18n("Next Tool Option (Group #1)")); + ac->setDefaultShortcuts(d->actionNextToolOptionGroup1, kpTool::shortcutForKey(Qt::Key_2)); + connect(d->actionNextToolOptionGroup1, &QAction::triggered, + this, &kpMainWindow::slotActionNextToolOptionGroup1); - d->actionPrevToolOptionGroup2 = ac->addAction (QStringLiteral("prev_tool_option_group_2")); - d->actionPrevToolOptionGroup2->setText (i18n ("Previous Tool Option (Group #2)")); - ac->setDefaultShortcuts (d->actionPrevToolOptionGroup2, kpTool::shortcutForKey (Qt::Key_3)); - connect (d->actionPrevToolOptionGroup2, &QAction::triggered, - this, &kpMainWindow::slotActionPrevToolOptionGroup2); - - d->actionNextToolOptionGroup2 = ac->addAction (QStringLiteral("next_tool_option_group_2")); - d->actionNextToolOptionGroup2->setText (i18n ("Next Tool Option (Group #2)")); - ac->setDefaultShortcuts (d->actionNextToolOptionGroup2, kpTool::shortcutForKey (Qt::Key_4)); - connect (d->actionNextToolOptionGroup2, &QAction::triggered, - this, &kpMainWindow::slotActionNextToolOptionGroup2); + d->actionPrevToolOptionGroup2 = ac->addAction(QStringLiteral("prev_tool_option_group_2")); + d->actionPrevToolOptionGroup2->setText(i18n("Previous Tool Option (Group #2)")); + ac->setDefaultShortcuts(d->actionPrevToolOptionGroup2, kpTool::shortcutForKey(Qt::Key_3)); + connect(d->actionPrevToolOptionGroup2, &QAction::triggered, + this, &kpMainWindow::slotActionPrevToolOptionGroup2); + d->actionNextToolOptionGroup2 = ac->addAction(QStringLiteral("next_tool_option_group_2")); + d->actionNextToolOptionGroup2->setText(i18n("Next Tool Option (Group #2)")); + ac->setDefaultShortcuts(d->actionNextToolOptionGroup2, kpTool::shortcutForKey(Qt::Key_4)); + connect(d->actionNextToolOptionGroup2, &QAction::triggered, + this, &kpMainWindow::slotActionNextToolOptionGroup2); // // Implemented in this file (kpMainWindow_Tools.cpp), not // kpImageWindow_Image.cpp since they're really setting tool options. // - d->actionDrawOpaque = ac->add (QStringLiteral("image_draw_opaque")); - d->actionDrawOpaque->setText (i18n ("&Draw Opaque")); - connect (d->actionDrawOpaque, &QAction::triggered, - this, &kpMainWindow::slotActionDrawOpaqueToggled); + d->actionDrawOpaque = ac->add (QStringLiteral("image_draw_opaque")); + d->actionDrawOpaque->setText(i18n("&Draw Opaque")); + connect(d->actionDrawOpaque, &QAction::triggered, + this, &kpMainWindow::slotActionDrawOpaqueToggled); - d->actionDrawColorSimilarity = ac->addAction (QStringLiteral("image_draw_color_similarity")); - d->actionDrawColorSimilarity->setText (i18n ("Draw With Color Similarity...")); - connect (d->actionDrawColorSimilarity, &QAction::triggered, - this, &kpMainWindow::slotActionDrawColorSimilarity); + d->actionDrawColorSimilarity = ac->addAction(QStringLiteral("image_draw_color_similarity")); + d->actionDrawColorSimilarity->setText(i18n("Draw With Color Similarity...")); + connect(d->actionDrawColorSimilarity, &QAction::triggered, + this, &kpMainWindow::slotActionDrawColorSimilarity); } //--------------------------------------------------------------------- // private -void kpMainWindow::createToolBox () +void kpMainWindow::createToolBox() { - d->toolToolBar = new kpToolToolBar(QStringLiteral("Tool Box"), 2/*columns/rows*/, this); + d->toolToolBar = new kpToolToolBar(QStringLiteral("Tool Box"), 2 /*columns/rows*/, this); d->toolToolBar->setWindowTitle(i18n("Tool Box")); - connect (d->toolToolBar, &kpToolToolBar::sigToolSelected, - this, &kpMainWindow::slotToolSelected); + connect(d->toolToolBar, &kpToolToolBar::sigToolSelected, + this, &kpMainWindow::slotToolSelected); - connect (d->toolToolBar, &kpToolToolBar::toolWidgetOptionSelected, - this, &kpMainWindow::updateToolOptionPrevNextActionsEnabled); + connect(d->toolToolBar, &kpToolToolBar::toolWidgetOptionSelected, + this, &kpMainWindow::updateToolOptionPrevNextActionsEnabled); - connect (d->toolToolBar->toolWidgetOpaqueOrTransparent(), - &kpToolWidgetOpaqueOrTransparent::isOpaqueChanged, - this, &kpMainWindow::updateActionDrawOpaqueChecked); + connect(d->toolToolBar->toolWidgetOpaqueOrTransparent(), + &kpToolWidgetOpaqueOrTransparent::isOpaqueChanged, + this, &kpMainWindow::updateActionDrawOpaqueChecked); - updateActionDrawOpaqueChecked (); + updateActionDrawOpaqueChecked(); for (auto *tool : d->tools) { - d->toolToolBar->registerTool(tool); + d->toolToolBar->registerTool(tool); } // (from config file) - readLastTool (); + readLastTool(); } //--------------------------------------------------------------------- // private -void kpMainWindow::enableToolsDocumentActions (bool enable) +void kpMainWindow::enableToolsDocumentActions(bool enable) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::enableToolsDocumentsAction(" << enable << ")"; #endif d->toolActionsEnabled = enable; - if (enable && !d->toolToolBar->isEnabled ()) - { - kpTool *previousTool = d->toolToolBar->previousTool (); + if (enable && !d->toolToolBar->isEnabled()) { + kpTool *previousTool = d->toolToolBar->previousTool(); // select tool for enabled Tool Box if (previousTool) { - d->toolToolBar->selectPreviousTool (); - } - else - { - if (d->lastToolNumber >= 0 && d->lastToolNumber < d->tools.count ()) { - d->toolToolBar->selectTool (d->tools.at (d->lastToolNumber)); - } - else { - d->toolToolBar->selectTool (d->toolPen); + d->toolToolBar->selectPreviousTool(); + } else { + if (d->lastToolNumber >= 0 && d->lastToolNumber < d->tools.count()) { + d->toolToolBar->selectTool(d->tools.at(d->lastToolNumber)); + } else { + d->toolToolBar->selectTool(d->toolPen); } } - } - else if (!enable && d->toolToolBar->isEnabled ()) - { + } else if (!enable && d->toolToolBar->isEnabled()) { // don't have a disabled Tool Box with a checked Tool - d->toolToolBar->selectTool (nullptr); + d->toolToolBar->selectTool(nullptr); } + d->toolToolBar->setEnabled(enable); - d->toolToolBar->setEnabled (enable); - - - for (auto *tool : d->tools) - { - kpToolAction *action = tool->action(); - if (!enable && action->isChecked()) { - action->setChecked(false); - } + for (auto *tool : d->tools) { + kpToolAction *action = tool->action(); + if (!enable && action->isChecked()) { + action->setChecked(false); + } - action->setEnabled(enable); + action->setEnabled(enable); } - - updateToolOptionPrevNextActionsEnabled (); - updateActionDrawOpaqueEnabled (); + updateToolOptionPrevNextActionsEnabled(); + updateActionDrawOpaqueEnabled(); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::updateToolOptionPrevNextActionsEnabled () +void kpMainWindow::updateToolOptionPrevNextActionsEnabled() { const bool enable = d->toolActionsEnabled; + d->actionPrevToolOptionGroup1->setEnabled(enable + && d->toolToolBar->shownToolWidget(0) + && d->toolToolBar->shownToolWidget( + 0)->hasPreviousOption()); + d->actionNextToolOptionGroup1->setEnabled(enable + && d->toolToolBar->shownToolWidget(0) + && d->toolToolBar->shownToolWidget(0)->hasNextOption()); - d->actionPrevToolOptionGroup1->setEnabled (enable && - d->toolToolBar->shownToolWidget (0) && - d->toolToolBar->shownToolWidget (0)->hasPreviousOption ()); - d->actionNextToolOptionGroup1->setEnabled (enable && - d->toolToolBar->shownToolWidget (0) && - d->toolToolBar->shownToolWidget (0)->hasNextOption ()); - - d->actionPrevToolOptionGroup2->setEnabled (enable && - d->toolToolBar->shownToolWidget (1) && - d->toolToolBar->shownToolWidget (1)->hasPreviousOption ()); - d->actionNextToolOptionGroup2->setEnabled (enable && - d->toolToolBar->shownToolWidget (1) && - d->toolToolBar->shownToolWidget (1)->hasNextOption ()); + d->actionPrevToolOptionGroup2->setEnabled(enable + && d->toolToolBar->shownToolWidget(1) + && d->toolToolBar->shownToolWidget( + 1)->hasPreviousOption()); + d->actionNextToolOptionGroup2->setEnabled(enable + && d->toolToolBar->shownToolWidget(1) + && d->toolToolBar->shownToolWidget(1)->hasNextOption()); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::updateActionDrawOpaqueChecked () +void kpMainWindow::updateActionDrawOpaqueChecked() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::updateActionDrawOpaqueChecked()"; #endif - const bool drawOpaque = - (d->toolToolBar->toolWidgetOpaqueOrTransparent ()->selectedRow () == 0); + const bool drawOpaque + = (d->toolToolBar->toolWidgetOpaqueOrTransparent()->selectedRow() == 0); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tdrawOpaque=" << drawOpaque; #endif - d->actionDrawOpaque->setChecked (drawOpaque); + d->actionDrawOpaque->setChecked(drawOpaque); } //--------------------------------------------------------------------- // private -void kpMainWindow::updateActionDrawOpaqueEnabled () +void kpMainWindow::updateActionDrawOpaqueEnabled() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::updateActionDrawOpaqueEnabled()"; @@ -309,229 +297,226 @@ #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tenable=" << enable - << " tool=" << (tool () ? tool ()->objectName () : nullptr) - << " (is selection=" << toolIsASelectionTool () << ")"; + << " tool=" << (tool() ? tool()->objectName() : nullptr) + << " (is selection=" << toolIsASelectionTool() << ")"; #endif - d->actionDrawOpaque->setEnabled (enable && toolIsASelectionTool ()); + d->actionDrawOpaque->setEnabled(enable && toolIsASelectionTool()); } //--------------------------------------------------------------------- // public -QActionGroup *kpMainWindow::toolsActionGroup () +QActionGroup *kpMainWindow::toolsActionGroup() { if (!d->toolsActionGroup) { - d->toolsActionGroup = new QActionGroup (this); + d->toolsActionGroup = new QActionGroup(this); } return d->toolsActionGroup; } //--------------------------------------------------------------------- // public -kpTool *kpMainWindow::tool () const +kpTool *kpMainWindow::tool() const { - return d->toolToolBar ? d->toolToolBar->tool () : nullptr; + return d->toolToolBar ? d->toolToolBar->tool() : nullptr; } //--------------------------------------------------------------------- // public -bool kpMainWindow::toolHasBegunShape () const +bool kpMainWindow::toolHasBegunShape() const { - kpTool *currentTool = tool (); - return (currentTool && currentTool->hasBegunShape ()); + kpTool *currentTool = tool(); + return currentTool && currentTool->hasBegunShape(); } //--------------------------------------------------------------------- // public -bool kpMainWindow::toolIsASelectionTool (bool includingTextTool) const +bool kpMainWindow::toolIsASelectionTool(bool includingTextTool) const { - kpTool *currentTool = tool (); + kpTool *currentTool = tool(); - return ((currentTool == d->toolFreeFormSelection) || - (currentTool == d->toolRectSelection) || - (currentTool == d->toolEllipticalSelection) || - (currentTool == d->toolText && includingTextTool)); + return (currentTool == d->toolFreeFormSelection) + || (currentTool == d->toolRectSelection) + || (currentTool == d->toolEllipticalSelection) + || (currentTool == d->toolText && includingTextTool); } //--------------------------------------------------------------------- // public -bool kpMainWindow::toolIsTextTool () const +bool kpMainWindow::toolIsTextTool() const { - return (tool () == d->toolText); + return tool() == d->toolText; } //--------------------------------------------------------------------- - // private -void kpMainWindow::toolEndShape () +void kpMainWindow::toolEndShape() { - if (toolHasBegunShape ()) { - tool ()->endShapeInternal (); + if (toolHasBegunShape()) { + tool()->endShapeInternal(); } } //--------------------------------------------------------------------- // public -kpImageSelectionTransparency kpMainWindow::imageSelectionTransparency () const +kpImageSelectionTransparency kpMainWindow::imageSelectionTransparency() const { - kpToolWidgetOpaqueOrTransparent *oot = d->toolToolBar->toolWidgetOpaqueOrTransparent (); - Q_ASSERT (oot); + kpToolWidgetOpaqueOrTransparent *oot = d->toolToolBar->toolWidgetOpaqueOrTransparent(); + Q_ASSERT(oot); - return kpImageSelectionTransparency (oot->isOpaque (), backgroundColor (), d->colorToolBar->colorSimilarity ()); + return kpImageSelectionTransparency(oot->isOpaque(), + backgroundColor(), d->colorToolBar->colorSimilarity()); } //--------------------------------------------------------------------- // public -void kpMainWindow::setImageSelectionTransparency (const kpImageSelectionTransparency &transparency, bool forceColorChange) +void kpMainWindow::setImageSelectionTransparency(const kpImageSelectionTransparency &transparency, + bool forceColorChange) { #if DEBUG_KP_MAIN_WINDOW && 1 - qCDebug(kpLogMainWindow) << "kpMainWindow::setImageSelectionTransparency() isOpaque=" << transparency.isOpaque () - << " color=" << (transparency.transparentColor ().isValid () ? (int *) transparency.transparentColor ().toQRgb () : nullptr) - << " forceColorChange=" << forceColorChange; + qCDebug(kpLogMainWindow) << "kpMainWindow::setImageSelectionTransparency() isOpaque=" + << transparency.isOpaque() + << " color=" + << (transparency.transparentColor().isValid() ? (int *)transparency. + transparentColor().toQRgb() + : nullptr) + << " forceColorChange=" << forceColorChange; #endif - kpToolWidgetOpaqueOrTransparent *oot = d->toolToolBar->toolWidgetOpaqueOrTransparent (); - Q_ASSERT (oot); + kpToolWidgetOpaqueOrTransparent *oot = d->toolToolBar->toolWidgetOpaqueOrTransparent(); + Q_ASSERT(oot); d->settingImageSelectionTransparency++; - oot->setOpaque (transparency.isOpaque ()); - if (transparency.isTransparent () || forceColorChange) - { - d->colorToolBar->setColor (1, transparency.transparentColor ()); - d->colorToolBar->setColorSimilarity (transparency.colorSimilarity ()); + oot->setOpaque(transparency.isOpaque()); + if (transparency.isTransparent() || forceColorChange) { + d->colorToolBar->setColor(1, transparency.transparentColor()); + d->colorToolBar->setColorSimilarity(transparency.colorSimilarity()); } d->settingImageSelectionTransparency--; } //--------------------------------------------------------------------- // public -int kpMainWindow::settingImageSelectionTransparency () const +int kpMainWindow::settingImageSelectionTransparency() const { return d->settingImageSelectionTransparency; } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotToolSelected (kpTool *tool) +void kpMainWindow::slotToolSelected(kpTool *tool) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotToolSelected (" << tool << ")"; #endif - kpTool *previousTool = d->toolToolBar ? d->toolToolBar->previousTool () : nullptr; - - if (previousTool) - { - disconnect (previousTool, &kpTool::movedAndAboutToDraw, - this, &kpMainWindow::slotDragScroll); - - disconnect (previousTool, &kpTool::endedDraw, - this, &kpMainWindow::slotEndDragScroll); + kpTool *previousTool = d->toolToolBar ? d->toolToolBar->previousTool() : nullptr; - disconnect (previousTool, &kpTool::cancelledShape, - this, &kpMainWindow::slotEndDragScroll); + if (previousTool) { + disconnect(previousTool, &kpTool::movedAndAboutToDraw, + this, &kpMainWindow::slotDragScroll); - disconnect (previousTool, &kpTool::userMessageChanged, - this, &kpMainWindow::recalculateStatusBarMessage); + disconnect(previousTool, &kpTool::endedDraw, + this, &kpMainWindow::slotEndDragScroll); - disconnect (previousTool, &kpTool::userShapePointsChanged, - this, &kpMainWindow::recalculateStatusBarShape); + disconnect(previousTool, &kpTool::cancelledShape, + this, &kpMainWindow::slotEndDragScroll); - disconnect (previousTool, &kpTool::userShapeSizeChanged, - this, &kpMainWindow::recalculateStatusBarShape); + disconnect(previousTool, &kpTool::userMessageChanged, + this, &kpMainWindow::recalculateStatusBarMessage); + disconnect(previousTool, &kpTool::userShapePointsChanged, + this, &kpMainWindow::recalculateStatusBarShape); - disconnect (d->colorToolBar, &kpColorToolBar::colorsSwapped, - previousTool, &kpTool::slotColorsSwappedInternal); + disconnect(previousTool, &kpTool::userShapeSizeChanged, + this, &kpMainWindow::recalculateStatusBarShape); - disconnect (d->colorToolBar, &kpColorToolBar::foregroundColorChanged, - previousTool, &kpTool::slotForegroundColorChangedInternal); + disconnect(d->colorToolBar, &kpColorToolBar::colorsSwapped, + previousTool, &kpTool::slotColorsSwappedInternal); - disconnect (d->colorToolBar, &kpColorToolBar::backgroundColorChanged, - previousTool, &kpTool::slotBackgroundColorChangedInternal); + disconnect(d->colorToolBar, &kpColorToolBar::foregroundColorChanged, + previousTool, &kpTool::slotForegroundColorChangedInternal); + disconnect(d->colorToolBar, &kpColorToolBar::backgroundColorChanged, + previousTool, &kpTool::slotBackgroundColorChangedInternal); - disconnect (d->colorToolBar, &kpColorToolBar::colorSimilarityChanged, - previousTool, &kpTool::slotColorSimilarityChangedInternal); + disconnect(d->colorToolBar, &kpColorToolBar::colorSimilarityChanged, + previousTool, &kpTool::slotColorSimilarityChangedInternal); } - if (tool) - { - connect (tool, &kpTool::movedAndAboutToDraw, - this, &kpMainWindow::slotDragScroll); + if (tool) { + connect(tool, &kpTool::movedAndAboutToDraw, + this, &kpMainWindow::slotDragScroll); - connect (tool, &kpTool::endedDraw, - this, &kpMainWindow::slotEndDragScroll); + connect(tool, &kpTool::endedDraw, + this, &kpMainWindow::slotEndDragScroll); - connect (tool, &kpTool::cancelledShape, - this, &kpMainWindow::slotEndDragScroll); + connect(tool, &kpTool::cancelledShape, + this, &kpMainWindow::slotEndDragScroll); - connect (tool, &kpTool::userMessageChanged, - this, &kpMainWindow::recalculateStatusBarMessage); + connect(tool, &kpTool::userMessageChanged, + this, &kpMainWindow::recalculateStatusBarMessage); - connect (tool, &kpTool::userShapePointsChanged, - this, &kpMainWindow::recalculateStatusBarShape); + connect(tool, &kpTool::userShapePointsChanged, + this, &kpMainWindow::recalculateStatusBarShape); - connect (tool, &kpTool::userShapeSizeChanged, - this, &kpMainWindow::recalculateStatusBarShape); + connect(tool, &kpTool::userShapeSizeChanged, + this, &kpMainWindow::recalculateStatusBarShape); - recalculateStatusBar (); + recalculateStatusBar(); + connect(d->colorToolBar, &kpColorToolBar::colorsSwapped, + tool, &kpTool::slotColorsSwappedInternal); - connect (d->colorToolBar, &kpColorToolBar::colorsSwapped, - tool, &kpTool::slotColorsSwappedInternal); + connect(d->colorToolBar, &kpColorToolBar::foregroundColorChanged, + tool, &kpTool::slotForegroundColorChangedInternal); - connect (d->colorToolBar, &kpColorToolBar::foregroundColorChanged, - tool, &kpTool::slotForegroundColorChangedInternal); + connect(d->colorToolBar, &kpColorToolBar::backgroundColorChanged, + tool, &kpTool::slotBackgroundColorChangedInternal); - connect (d->colorToolBar, &kpColorToolBar::backgroundColorChanged, - tool, &kpTool::slotBackgroundColorChangedInternal); + connect(d->colorToolBar, &kpColorToolBar::colorSimilarityChanged, + tool, &kpTool::slotColorSimilarityChangedInternal); - connect (d->colorToolBar, &kpColorToolBar::colorSimilarityChanged, - tool, &kpTool::slotColorSimilarityChangedInternal); - - - saveLastTool (); + saveLastTool(); } - updateToolOptionPrevNextActionsEnabled (); - updateActionDrawOpaqueEnabled (); + updateToolOptionPrevNextActionsEnabled(); + updateActionDrawOpaqueEnabled(); } //--------------------------------------------------------------------- // private -void kpMainWindow::readLastTool () +void kpMainWindow::readLastTool() { - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupTools); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupTools); - d->lastToolNumber = cfg.readEntry (kpSettingLastTool, -1); + d->lastToolNumber = cfg.readEntry(kpSettingLastTool, -1); } //--------------------------------------------------------------------- // private -int kpMainWindow::toolNumber () const +int kpMainWindow::toolNumber() const { int number = 0; - for (QList ::const_iterator it = d->tools.constBegin (); - it != d->tools.constEnd (); - ++it) - { - if (*it == tool ()) { + for (QList ::const_iterator it = d->tools.constBegin(); + it != d->tools.constEnd(); + ++it) { + if (*it == tool()) { return number; } @@ -544,47 +529,43 @@ //--------------------------------------------------------------------- // private -void kpMainWindow::saveLastTool () +void kpMainWindow::saveLastTool() { - int number = toolNumber (); - if (number < 0 || number >= d->tools.count ()) { + int number = toolNumber(); + if (number < 0 || number >= d->tools.count()) { return; } + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupTools); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupTools); - - cfg.writeEntry (kpSettingLastTool, number); - cfg.sync (); + cfg.writeEntry(kpSettingLastTool, number); + cfg.sync(); } //--------------------------------------------------------------------- // private -bool kpMainWindow::maybeDragScrollingMainView () const +bool kpMainWindow::maybeDragScrollingMainView() const { - return (tool () && d->mainView && - tool ()->viewUnderStartPoint () == d->mainView); + return tool() && d->mainView + && tool()->viewUnderStartPoint() == d->mainView; } //--------------------------------------------------------------------- // private slot -bool kpMainWindow::slotDragScroll (const QPoint &docPoint, - const QPoint &docLastPoint, - int zoomLevel, - bool *scrolled) +bool kpMainWindow::slotDragScroll(const QPoint &docPoint, const QPoint &docLastPoint, int zoomLevel, + bool *scrolled) { - Q_UNUSED(docPoint) - Q_UNUSED(docLastPoint) + Q_UNUSED(docPoint) + Q_UNUSED(docLastPoint) #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotDragScroll() maybeDragScrolling=" - << maybeDragScrollingMainView (); + << maybeDragScrollingMainView(); #endif - if (maybeDragScrollingMainView ()) - { + if (maybeDragScrollingMainView()) { return d->scrollView->beginDragScroll(zoomLevel, scrolled); } @@ -594,241 +575,231 @@ //--------------------------------------------------------------------- // private slot -bool kpMainWindow::slotEndDragScroll () +bool kpMainWindow::slotEndDragScroll() { // (harmless if haven't started drag scroll) - return d->scrollView->endDragScroll (); + return d->scrollView->endDragScroll(); } //--------------------------------------------------------------------- - // private slot -void kpMainWindow::slotBeganDocResize () +void kpMainWindow::slotBeganDocResize() { - toolEndShape (); + toolEndShape(); - recalculateStatusBarShape (); + recalculateStatusBarShape(); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotContinuedDocResize (const QSize &) +void kpMainWindow::slotContinuedDocResize(const QSize &) { - recalculateStatusBarShape (); + recalculateStatusBarShape(); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotCancelledDocResize () +void kpMainWindow::slotCancelledDocResize() { - recalculateStatusBar (); + recalculateStatusBar(); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotEndedDocResize (const QSize &size) +void kpMainWindow::slotEndedDocResize(const QSize &size) { #define DOC_RESIZE_COMPLETED() \ -{ \ - d->docResizeToBeCompleted = false; \ - recalculateStatusBar (); \ -} + { \ + d->docResizeToBeCompleted = false; \ + recalculateStatusBar(); \ + } // Prevent statusbar updates d->docResizeToBeCompleted = true; - d->docResizeWidth = (size.width () > 0 ? size.width () : 1); - d->docResizeHeight = (size.height () > 0 ? size.height () : 1); + d->docResizeWidth = (size.width() > 0 ? size.width() : 1); + d->docResizeHeight = (size.height() > 0 ? size.height() : 1); - if (d->docResizeWidth == d->document->width () && - d->docResizeHeight == d->document->height ()) - { - DOC_RESIZE_COMPLETED (); + if (d->docResizeWidth == d->document->width() + && d->docResizeHeight == d->document->height()) { + DOC_RESIZE_COMPLETED(); return; } - // Blank status to avoid confusion if dialog comes up - setStatusBarMessage (); - setStatusBarShapePoints (); - setStatusBarShapeSize (); - - - if (kpTool::warnIfBigImageSize (d->document->width (), - d->document->height (), - d->docResizeWidth, d->docResizeHeight, - i18n ("

Resizing the image to" - " %1x%2 may take a substantial amount of memory." - " This can reduce system" - " responsiveness and cause other application resource" - " problems.

" - - "

Are you sure you want to resize the" - " image?

", - d->docResizeWidth, - d->docResizeHeight), - i18nc ("@title:window", "Resize Image?"), - i18n ("R&esize Image"), - this)) - { - d->commandHistory->addCommand ( - new kpTransformResizeScaleCommand ( - false/*doc, not sel*/, + setStatusBarMessage(); + setStatusBarShapePoints(); + setStatusBarShapeSize(); + + if (kpTool::warnIfBigImageSize(d->document->width(), + d->document->height(), + d->docResizeWidth, d->docResizeHeight, + i18n("

Resizing the image to" + " %1x%2 may take a substantial amount of memory." + " This can reduce system" + " responsiveness and cause other application resource" + " problems.

" + + "

Are you sure you want to resize the" + " image?

", + d->docResizeWidth, + d->docResizeHeight), + i18nc("@title:window", "Resize Image?"), + i18n("R&esize Image"), + this)) { + d->commandHistory->addCommand( + new kpTransformResizeScaleCommand( + false /*doc, not sel*/, d->docResizeWidth, d->docResizeHeight, kpTransformResizeScaleCommand::Resize, - commandEnvironment ())); + commandEnvironment())); - saveDefaultDocSize (QSize (d->docResizeWidth, d->docResizeHeight)); + saveDefaultDocSize(QSize(d->docResizeWidth, d->docResizeHeight)); } - - DOC_RESIZE_COMPLETED (); + DOC_RESIZE_COMPLETED(); #undef DOC_RESIZE_COMPLETED } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotDocResizeMessageChanged (const QString &string) +void kpMainWindow::slotDocResizeMessageChanged(const QString &string) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotDocResizeMessageChanged(" << string - << ") docResizeToBeCompleted=" << d->docResizeToBeCompleted; + << ") docResizeToBeCompleted=" << d->docResizeToBeCompleted; #else - (void) string; + (void)string; #endif if (d->docResizeToBeCompleted) { return; } - recalculateStatusBarMessage (); + recalculateStatusBarMessage(); } //--------------------------------------------------------------------- - // private slot -void kpMainWindow::slotActionPrevToolOptionGroup1 () +void kpMainWindow::slotActionPrevToolOptionGroup1() { - if (!d->toolToolBar->shownToolWidget (0)) { + if (!d->toolToolBar->shownToolWidget(0)) { return; } // We don't call toolEndShape() here because we want #23 in the file BUGS // to later work. - d->toolToolBar->shownToolWidget (0)->selectPreviousOption (); - updateToolOptionPrevNextActionsEnabled (); + d->toolToolBar->shownToolWidget(0)->selectPreviousOption(); + updateToolOptionPrevNextActionsEnabled(); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotActionNextToolOptionGroup1 () +void kpMainWindow::slotActionNextToolOptionGroup1() { - if (!d->toolToolBar->shownToolWidget (0)) { + if (!d->toolToolBar->shownToolWidget(0)) { return; } // We don't call toolEndShape() here because we want #23 in the file BUGS // to later work. - d->toolToolBar->shownToolWidget (0)->selectNextOption (); - updateToolOptionPrevNextActionsEnabled (); + d->toolToolBar->shownToolWidget(0)->selectNextOption(); + updateToolOptionPrevNextActionsEnabled(); } //--------------------------------------------------------------------- - // private slot -void kpMainWindow::slotActionPrevToolOptionGroup2 () +void kpMainWindow::slotActionPrevToolOptionGroup2() { - if (!d->toolToolBar->shownToolWidget (1)) { + if (!d->toolToolBar->shownToolWidget(1)) { return; } // We don't call toolEndShape() here because we want #23 in the file BUGS // to later work. - d->toolToolBar->shownToolWidget (1)->selectPreviousOption (); - updateToolOptionPrevNextActionsEnabled (); + d->toolToolBar->shownToolWidget(1)->selectPreviousOption(); + updateToolOptionPrevNextActionsEnabled(); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotActionNextToolOptionGroup2 () +void kpMainWindow::slotActionNextToolOptionGroup2() { - if (!d->toolToolBar->shownToolWidget (1)) { + if (!d->toolToolBar->shownToolWidget(1)) { return; } // We don't call toolEndShape() here because we want #23 in the file BUGS // to later work. - d->toolToolBar->shownToolWidget (1)->selectNextOption (); - updateToolOptionPrevNextActionsEnabled (); + d->toolToolBar->shownToolWidget(1)->selectNextOption(); + updateToolOptionPrevNextActionsEnabled(); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotActionDrawOpaqueToggled () +void kpMainWindow::slotActionDrawOpaqueToggled() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotActionDrawOpaqueToggled()"; #endif - toolEndShape (); + toolEndShape(); // TODO: How does this differ to setImageSelectionTransparency()? // ("kpToolWidgetBase::" is to access one overload shadowed by the override // of the other overload) - d->toolToolBar->toolWidgetOpaqueOrTransparent ()->kpToolWidgetBase::setSelected ( - (d->actionDrawOpaque->isChecked () ? - 0/*row 0 = opaque*/ : - 1/*row 1 = transparent*/), - 0/*column*/); + d->toolToolBar->toolWidgetOpaqueOrTransparent()->kpToolWidgetBase::setSelected( + (d->actionDrawOpaque->isChecked() + ? 0 /*row 0 = opaque*/ + : 1 /*row 1 = transparent*/), + 0 /*column*/); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotActionDrawColorSimilarity () +void kpMainWindow::slotActionDrawColorSimilarity() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotActionDrawColorSimilarity()"; #endif - toolEndShape (); + toolEndShape(); - d->colorToolBar->openColorSimilarityDialog (); + d->colorToolBar->openColorSimilarityDialog(); } //--------------------------------------------------------------------- - // public slots #define SLOT_TOOL(toolName) \ -void kpMainWindow::slotTool##toolName () \ -{ \ - if (!d->toolToolBar) \ - return; \ + void kpMainWindow::slotTool ## toolName() \ + { \ + if (!d->toolToolBar) { \ + return;} \ \ - if (tool () == d->tool##toolName) \ - return; \ + if (tool() == d->tool ## toolName) { \ + return;} \ \ - d->toolToolBar->selectTool (d->tool##toolName); \ -} - + d->toolToolBar->selectTool(d->tool ## toolName); \ + } -SLOT_TOOL (RectSelection) -SLOT_TOOL (EllipticalSelection) -SLOT_TOOL (FreeFormSelection) -SLOT_TOOL (Text) +SLOT_TOOL(RectSelection) +SLOT_TOOL(EllipticalSelection) +SLOT_TOOL(FreeFormSelection) +SLOT_TOOL(Text) diff --git a/mainWindow/kpMainWindow_View.cpp b/mainWindow/kpMainWindow_View.cpp --- a/mainWindow/kpMainWindow_View.cpp +++ b/mainWindow/kpMainWindow_View.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "mainWindow/kpMainWindow.h" #include "kpMainWindowPrivate.h" #include "kpLogCategories.h" @@ -48,116 +46,110 @@ #include "views/kpZoomedView.h" #include "views/kpZoomedThumbnailView.h" - // private -void kpMainWindow::setupViewMenuActions () +void kpMainWindow::setupViewMenuActions() { - KActionCollection *ac = actionCollection (); + KActionCollection *ac = actionCollection(); /*d->actionFullScreen = KStandardAction::fullScreen (0, 0, ac); d->actionFullScreen->setEnabled (false);*/ + setupViewMenuZoomActions(); - setupViewMenuZoomActions (); - - - d->actionShowGrid = ac->add (QStringLiteral("view_show_grid")); - d->actionShowGrid->setText (i18n ("Show &Grid")); - ac->setDefaultShortcut (d->actionShowGrid, Qt::CTRL + Qt::Key_G); + d->actionShowGrid = ac->add (QStringLiteral("view_show_grid")); + d->actionShowGrid->setText(i18n("Show &Grid")); + ac->setDefaultShortcut(d->actionShowGrid, Qt::CTRL + Qt::Key_G); //d->actionShowGrid->setCheckedState (KGuiItem(i18n ("Hide &Grid"))); - connect (d->actionShowGrid, &KToggleAction::triggered, - this, &kpMainWindow::slotShowGridToggled); - + connect(d->actionShowGrid, &KToggleAction::triggered, + this, &kpMainWindow::slotShowGridToggled); - setupViewMenuThumbnailActions (); + setupViewMenuThumbnailActions(); - - enableViewMenuDocumentActions (false); + enableViewMenuDocumentActions(false); } //--------------------------------------------------------------------- // private -bool kpMainWindow::viewMenuDocumentActionsEnabled () const +bool kpMainWindow::viewMenuDocumentActionsEnabled() const { return d->viewMenuDocumentActionsEnabled; } //--------------------------------------------------------------------- // private -void kpMainWindow::enableViewMenuDocumentActions (bool enable) +void kpMainWindow::enableViewMenuDocumentActions(bool enable) { d->viewMenuDocumentActionsEnabled = enable; + enableViewMenuZoomDocumentActions(enable); - enableViewMenuZoomDocumentActions (enable); - - actionShowGridUpdate (); + actionShowGridUpdate(); - enableViewMenuThumbnailDocumentActions (enable); + enableViewMenuThumbnailDocumentActions(enable); } //--------------------------------------------------------------------- // private -void kpMainWindow::actionShowGridUpdate () +void kpMainWindow::actionShowGridUpdate() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::actionShowGridUpdate()"; #endif - const bool enable = (viewMenuDocumentActionsEnabled () && - d->mainView && d->mainView->canShowGrid ()); + const bool enable = (viewMenuDocumentActionsEnabled() + && d->mainView && d->mainView->canShowGrid()); - d->actionShowGrid->setEnabled (enable); - d->actionShowGrid->setChecked (enable && d->configShowGrid); + d->actionShowGrid->setEnabled(enable); + d->actionShowGrid->setChecked(enable && d->configShowGrid); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotShowGridToggled () +void kpMainWindow::slotShowGridToggled() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotActionShowGridToggled()"; #endif - updateMainViewGrid (); + updateMainViewGrid(); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupGeneral); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); - cfg.writeEntry (kpSettingShowGrid, d->configShowGrid = d->actionShowGrid->isChecked ()); - cfg.sync (); + cfg.writeEntry(kpSettingShowGrid, d->configShowGrid = d->actionShowGrid->isChecked()); + cfg.sync(); } //--------------------------------------------------------------------- // private -void kpMainWindow::updateMainViewGrid () +void kpMainWindow::updateMainViewGrid() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::updateMainViewGrid ()"; #endif if (d->mainView) { - d->mainView->showGrid (d->actionShowGrid->isChecked ()); + d->mainView->showGrid(d->actionShowGrid->isChecked()); } } //--------------------------------------------------------------------- // private -QRect kpMainWindow::mapToGlobal (const QRect &rect) const +QRect kpMainWindow::mapToGlobal(const QRect &rect) const { - return kpWidgetMapper::toGlobal (this, rect); + return kpWidgetMapper::toGlobal(this, rect); } //--------------------------------------------------------------------- // private -QRect kpMainWindow::mapFromGlobal (const QRect &rect) const +QRect kpMainWindow::mapFromGlobal(const QRect &rect) const { - return kpWidgetMapper::fromGlobal (this, rect); + return kpWidgetMapper::fromGlobal(this, rect); } //--------------------------------------------------------------------- diff --git a/mainWindow/kpMainWindow_View_Thumbnail.cpp b/mainWindow/kpMainWindow_View_Thumbnail.cpp --- a/mainWindow/kpMainWindow_View_Thumbnail.cpp +++ b/mainWindow/kpMainWindow_View_Thumbnail.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "mainWindow/kpMainWindow.h" #include "kpMainWindowPrivate.h" #include "kpLogCategories.h" @@ -50,105 +48,103 @@ #include "views/kpZoomedView.h" #include "views/kpZoomedThumbnailView.h" - // private -void kpMainWindow::setupViewMenuThumbnailActions () +void kpMainWindow::setupViewMenuThumbnailActions() { d->thumbnailSaveConfigTimer = nullptr; - KActionCollection *ac = actionCollection (); - + KActionCollection *ac = actionCollection(); - d->actionShowThumbnail = ac->add (QStringLiteral("view_show_thumbnail")); - d->actionShowThumbnail->setText (i18n ("Show T&humbnail")); + d->actionShowThumbnail = ac->add (QStringLiteral("view_show_thumbnail")); + d->actionShowThumbnail->setText(i18n("Show T&humbnail")); // TODO: This doesn't work when the thumbnail has focus. // Testcase: Press CTRL+H twice on a fresh KolourPaint. // The second CTRL+H doesn't close the thumbnail. - ac->setDefaultShortcut (d->actionShowThumbnail, Qt::CTRL + Qt::Key_H); + ac->setDefaultShortcut(d->actionShowThumbnail, Qt::CTRL + Qt::Key_H); //d->actionShowThumbnail->setCheckedState (KGuiItem(i18n ("Hide T&humbnail"))); - connect (d->actionShowThumbnail, &KToggleAction::triggered, - this, &kpMainWindow::slotShowThumbnailToggled); + connect(d->actionShowThumbnail, &KToggleAction::triggered, + this, &kpMainWindow::slotShowThumbnailToggled); // Please do not use setCheckedState() here - it wouldn't make sense - d->actionZoomedThumbnail = ac->add (QStringLiteral("view_zoomed_thumbnail")); - d->actionZoomedThumbnail->setText (i18n ("Zoo&med Thumbnail Mode")); - connect (d->actionZoomedThumbnail, &KToggleAction::triggered, - this, &kpMainWindow::slotZoomedThumbnailToggled); + d->actionZoomedThumbnail = ac->add (QStringLiteral("view_zoomed_thumbnail")); + d->actionZoomedThumbnail->setText(i18n("Zoo&med Thumbnail Mode")); + connect(d->actionZoomedThumbnail, &KToggleAction::triggered, + this, &kpMainWindow::slotZoomedThumbnailToggled); // For consistency with the above action, don't use setCheckedState() // // Also, don't use "Show Thumbnail Rectangle" because if entire doc // can be seen in scrollView, checking option won't "Show" anything // since rect _surrounds_ entire doc (hence, won't be rendered). - d->actionShowThumbnailRectangle = ac->add (QStringLiteral("view_show_thumbnail_rectangle")); - d->actionShowThumbnailRectangle->setText (i18n ("Enable Thumbnail &Rectangle")); - connect (d->actionShowThumbnailRectangle, &KToggleAction::triggered, - this, &kpMainWindow::slotThumbnailShowRectangleToggled); + d->actionShowThumbnailRectangle + = ac->add (QStringLiteral("view_show_thumbnail_rectangle")); + d->actionShowThumbnailRectangle->setText(i18n("Enable Thumbnail &Rectangle")); + connect(d->actionShowThumbnailRectangle, &KToggleAction::triggered, + this, &kpMainWindow::slotThumbnailShowRectangleToggled); } // private -void kpMainWindow::enableViewMenuThumbnailDocumentActions (bool enable) +void kpMainWindow::enableViewMenuThumbnailDocumentActions(bool enable) { - d->actionShowThumbnail->setEnabled (enable); - enableThumbnailOptionActions (enable); + d->actionShowThumbnail->setEnabled(enable); + enableThumbnailOptionActions(enable); } // private slot -void kpMainWindow::slotDestroyThumbnail () +void kpMainWindow::slotDestroyThumbnail() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotDestroyThumbnail()"; #endif - d->actionShowThumbnail->setChecked (false); - enableThumbnailOptionActions (false); - updateThumbnail (); + d->actionShowThumbnail->setChecked(false); + enableThumbnailOptionActions(false); + updateThumbnail(); } // private slot -void kpMainWindow::slotDestroyThumbnailInitatedByUser () +void kpMainWindow::slotDestroyThumbnailInitatedByUser() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotDestroyThumbnailInitiatedByUser()"; #endif - d->actionShowThumbnail->setChecked (false); - slotShowThumbnailToggled (); + d->actionShowThumbnail->setChecked(false); + slotShowThumbnailToggled(); } // private slot -void kpMainWindow::slotCreateThumbnail () +void kpMainWindow::slotCreateThumbnail() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotCreateThumbnail()"; #endif - d->actionShowThumbnail->setChecked (true); - enableThumbnailOptionActions (true); - updateThumbnail (); + d->actionShowThumbnail->setChecked(true); + enableThumbnailOptionActions(true); + updateThumbnail(); } // public -void kpMainWindow::notifyThumbnailGeometryChanged () +void kpMainWindow::notifyThumbnailGeometryChanged() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::notifyThumbnailGeometryChanged()"; #endif - if (!d->thumbnailSaveConfigTimer) - { - d->thumbnailSaveConfigTimer = new QTimer (this); - d->thumbnailSaveConfigTimer->setSingleShot (true); - connect (d->thumbnailSaveConfigTimer, &QTimer::timeout, - this, &kpMainWindow::slotSaveThumbnailGeometry); + if (!d->thumbnailSaveConfigTimer) { + d->thumbnailSaveConfigTimer = new QTimer(this); + d->thumbnailSaveConfigTimer->setSingleShot(true); + connect(d->thumbnailSaveConfigTimer, &QTimer::timeout, + this, &kpMainWindow::slotSaveThumbnailGeometry); } // (single shot) - d->thumbnailSaveConfigTimer->start (500/*msec*/); + d->thumbnailSaveConfigTimer->start(500 /*msec*/); } // private slot -void kpMainWindow::slotSaveThumbnailGeometry () +void kpMainWindow::slotSaveThumbnailGeometry() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::saveThumbnailGeometry()"; @@ -158,234 +154,222 @@ return; } - QRect rect (d->thumbnail->x (), d->thumbnail->y (), - d->thumbnail->width (), d->thumbnail->height ()); + QRect rect(d->thumbnail->x(), d->thumbnail->y(), + d->thumbnail->width(), d->thumbnail->height()); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tthumbnail relative geometry=" << rect; #endif - d->configThumbnailGeometry = mapFromGlobal (rect); + d->configThumbnailGeometry = mapFromGlobal(rect); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tCONFIG: saving thumbnail geometry " - << d->configThumbnailGeometry; + << d->configThumbnailGeometry; #endif - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupThumbnail); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupThumbnail); - cfg.writeEntry (kpSettingThumbnailGeometry, d->configThumbnailGeometry); - cfg.sync (); + cfg.writeEntry(kpSettingThumbnailGeometry, d->configThumbnailGeometry); + cfg.sync(); } // private slot -void kpMainWindow::slotShowThumbnailToggled () +void kpMainWindow::slotShowThumbnailToggled() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotShowThumbnailToggled()"; #endif - d->configThumbnailShown = d->actionShowThumbnail->isChecked (); + d->configThumbnailShown = d->actionShowThumbnail->isChecked(); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupThumbnail); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupThumbnail); - cfg.writeEntry (kpSettingThumbnailShown, d->configThumbnailShown); - cfg.sync (); + cfg.writeEntry(kpSettingThumbnailShown, d->configThumbnailShown); + cfg.sync(); - - enableThumbnailOptionActions (d->actionShowThumbnail->isChecked ()); - updateThumbnail (); + enableThumbnailOptionActions(d->actionShowThumbnail->isChecked()); + updateThumbnail(); } // private slot -void kpMainWindow::updateThumbnailZoomed () +void kpMainWindow::updateThumbnailZoomed() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::updateThumbnailZoomed() zoomed=" - << d->actionZoomedThumbnail->isChecked (); + << d->actionZoomedThumbnail->isChecked(); #endif if (!d->thumbnailView) { return; } - destroyThumbnailView (); - createThumbnailView (); + destroyThumbnailView(); + createThumbnailView(); } // private slot -void kpMainWindow::slotZoomedThumbnailToggled () +void kpMainWindow::slotZoomedThumbnailToggled() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotZoomedThumbnailToggled()"; #endif - d->configZoomedThumbnail = d->actionZoomedThumbnail->isChecked (); - - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupThumbnail); + d->configZoomedThumbnail = d->actionZoomedThumbnail->isChecked(); - cfg.writeEntry (kpSettingThumbnailZoomed, d->configZoomedThumbnail); - cfg.sync (); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupThumbnail); + cfg.writeEntry(kpSettingThumbnailZoomed, d->configZoomedThumbnail); + cfg.sync(); - updateThumbnailZoomed (); + updateThumbnailZoomed(); } // private slot -void kpMainWindow::slotThumbnailShowRectangleToggled () +void kpMainWindow::slotThumbnailShowRectangleToggled() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotThumbnailShowRectangleToggled()"; #endif - d->configThumbnailShowRectangle = d->actionShowThumbnailRectangle->isChecked (); + d->configThumbnailShowRectangle = d->actionShowThumbnailRectangle->isChecked(); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupThumbnail); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupThumbnail); - cfg.writeEntry (kpSettingThumbnailShowRectangle, d->configThumbnailShowRectangle); - cfg.sync (); + cfg.writeEntry(kpSettingThumbnailShowRectangle, d->configThumbnailShowRectangle); + cfg.sync(); - - if (d->thumbnailView) - { - d->thumbnailView->showBuddyViewScrollableContainerRectangle ( - d->actionShowThumbnailRectangle->isChecked ()); + if (d->thumbnailView) { + d->thumbnailView->showBuddyViewScrollableContainerRectangle( + d->actionShowThumbnailRectangle->isChecked()); } } // private -void kpMainWindow::enableViewZoomedThumbnail (bool enable) +void kpMainWindow::enableViewZoomedThumbnail(bool enable) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::enableSettingsViewZoomedThumbnail()"; #endif - d->actionZoomedThumbnail->setEnabled (enable && - d->actionShowThumbnail->isChecked ()); + d->actionZoomedThumbnail->setEnabled(enable + && d->actionShowThumbnail->isChecked()); // Note: Don't uncheck if disabled - being able to see the zoomed state // before turning on the thumbnail can be useful. - d->actionZoomedThumbnail->setChecked (d->configZoomedThumbnail); + d->actionZoomedThumbnail->setChecked(d->configZoomedThumbnail); } // private -void kpMainWindow::enableViewShowThumbnailRectangle (bool enable) +void kpMainWindow::enableViewShowThumbnailRectangle(bool enable) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::enableViewShowThumbnailRectangle()"; #endif - d->actionShowThumbnailRectangle->setEnabled (enable && - d->actionShowThumbnail->isChecked ()); + d->actionShowThumbnailRectangle->setEnabled(enable + && d->actionShowThumbnail->isChecked()); // Note: Don't uncheck if disabled for consistency with // enableViewZoomedThumbnail() - d->actionShowThumbnailRectangle->setChecked ( + d->actionShowThumbnailRectangle->setChecked( d->configThumbnailShowRectangle); } // private -void kpMainWindow::enableThumbnailOptionActions (bool enable) +void kpMainWindow::enableThumbnailOptionActions(bool enable) { - enableViewZoomedThumbnail (enable); - enableViewShowThumbnailRectangle (enable); + enableViewZoomedThumbnail(enable); + enableViewShowThumbnailRectangle(enable); } - // private -void kpMainWindow::createThumbnailView () +void kpMainWindow::createThumbnailView() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tcreating new kpView:"; #endif - if (d->thumbnailView) - { + if (d->thumbnailView) { qCDebug(kpLogMainWindow) << "kpMainWindow::createThumbnailView() had to destroy view"; - destroyThumbnailView (); + destroyThumbnailView(); } - if (d->actionZoomedThumbnail->isChecked ()) - { - d->thumbnailView = new kpZoomedThumbnailView ( + if (d->actionZoomedThumbnail->isChecked()) { + d->thumbnailView = new kpZoomedThumbnailView( d->document, d->toolToolBar, d->viewManager, d->mainView, - nullptr/*scrollableContainer*/, + nullptr /*scrollableContainer*/, d->thumbnail); - d->thumbnailView->setObjectName ( QStringLiteral("thumbnailView" )); - } - else - { - d->thumbnailView = new kpUnzoomedThumbnailView ( + d->thumbnailView->setObjectName(QStringLiteral("thumbnailView")); + } else { + d->thumbnailView = new kpUnzoomedThumbnailView( d->document, d->toolToolBar, d->viewManager, d->mainView, - nullptr/*scrollableContainer*/, + nullptr /*scrollableContainer*/, d->thumbnail); - d->thumbnailView->setObjectName ( QStringLiteral("thumbnailView" )); + d->thumbnailView->setObjectName(QStringLiteral("thumbnailView")); } - d->thumbnailView->showBuddyViewScrollableContainerRectangle ( - d->actionShowThumbnailRectangle->isChecked ()); - + d->thumbnailView->showBuddyViewScrollableContainerRectangle( + d->actionShowThumbnailRectangle->isChecked()); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tgive kpThumbnail the kpView:"; #endif if (d->thumbnail) { - d->thumbnail->setView (d->thumbnailView); - } - else { + d->thumbnail->setView(d->thumbnailView); + } else { qCCritical(kpLogMainWindow) << "kpMainWindow::createThumbnailView() no thumbnail"; } #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tregistering the kpView:"; #endif if (d->viewManager) { - d->viewManager->registerView (d->thumbnailView); + d->viewManager->registerView(d->thumbnailView); } } // private -void kpMainWindow::destroyThumbnailView () +void kpMainWindow::destroyThumbnailView() { if (!d->thumbnailView) { return; } if (d->viewManager) { - d->viewManager->unregisterView (d->thumbnailView); + d->viewManager->unregisterView(d->thumbnailView); } if (d->thumbnail) { - d->thumbnail->setView (nullptr); + d->thumbnail->setView(nullptr); } - d->thumbnailView->deleteLater (); d->thumbnailView = nullptr; + d->thumbnailView->deleteLater(); + d->thumbnailView = nullptr; } - // private -void kpMainWindow::updateThumbnail () +void kpMainWindow::updateThumbnail() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::updateThumbnail()"; #endif - bool enable = d->actionShowThumbnail->isChecked (); + bool enable = d->actionShowThumbnail->isChecked(); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tthumbnail=" - << bool (d->thumbnail) - << " action_isChecked=" - << enable; + << bool(d->thumbnail) + << " action_isChecked=" + << enable; #endif - if (bool (d->thumbnail) == enable) { + if (bool(d->thumbnail) == enable) { return; } - if (!d->thumbnail) - { + if (!d->thumbnail) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tcreating thumbnail"; #endif @@ -397,83 +381,77 @@ qCDebug(kpLogMainWindow) << "\t\tlast used geometry=" << thumbnailGeometry; #endif - d->thumbnail = new kpThumbnail (this); + d->thumbnail = new kpThumbnail(this); - createThumbnailView (); + createThumbnailView(); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tmoving thumbnail to right place"; #endif - if (!thumbnailGeometry.isEmpty () && - QRect (0, 0, width (), height ()).intersects (thumbnailGeometry)) - { - const QRect geometry = mapToGlobal (thumbnailGeometry); - d->thumbnail->resize (geometry.size ()); - d->thumbnail->move (geometry.topLeft ()); - } - else - { - if (d->scrollView) - { + if (!thumbnailGeometry.isEmpty() + && QRect(0, 0, width(), height()).intersects(thumbnailGeometry)) { + const QRect geometry = mapToGlobal(thumbnailGeometry); + d->thumbnail->resize(geometry.size()); + d->thumbnail->move(geometry.topLeft()); + } else { + if (d->scrollView) { const int margin = 20; const int initialWidth = 160, initialHeight = 120; - QRect geometryRect (width () - initialWidth - margin * 2, - d->scrollView->y () + margin, - initialWidth, - initialHeight); + QRect geometryRect(width() - initialWidth - margin * 2, + d->scrollView->y() + margin, + initialWidth, + initialHeight); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tcreating geometry=" << geometryRect; #endif - geometryRect = mapToGlobal (geometryRect); + geometryRect = mapToGlobal(geometryRect); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tmap to global=" << geometryRect; #endif - d->thumbnail->resize (geometryRect.size ()); - d->thumbnail->move (geometryRect.topLeft ()); + d->thumbnail->resize(geometryRect.size()); + d->thumbnail->move(geometryRect.topLeft()); } } #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tshowing thumbnail"; #endif - d->thumbnail->show (); + d->thumbnail->show(); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tconnecting signal thumbnail::windowClosed to destroy slot"; #endif - connect (d->thumbnail, &kpThumbnail::windowClosed, - this, &kpMainWindow::slotDestroyThumbnailInitatedByUser); + connect(d->thumbnail, &kpThumbnail::windowClosed, + this, &kpMainWindow::slotDestroyThumbnailInitatedByUser); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tDONE"; #endif - } - else - { + } else { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tdestroying thumbnail d->thumbnail=" - << d->thumbnail; + << d->thumbnail; #endif - if (d->thumbnailSaveConfigTimer && d->thumbnailSaveConfigTimer->isActive ()) - { - d->thumbnailSaveConfigTimer->stop (); - slotSaveThumbnailGeometry (); + if (d->thumbnailSaveConfigTimer && d->thumbnailSaveConfigTimer->isActive()) { + d->thumbnailSaveConfigTimer->stop(); + slotSaveThumbnailGeometry(); } // Must be done before hiding the thumbnail to avoid triggering // this signal - re-entering this code. - disconnect (d->thumbnail, &kpThumbnail::windowClosed, - this, &kpMainWindow::slotDestroyThumbnailInitatedByUser); + disconnect(d->thumbnail, &kpThumbnail::windowClosed, + this, &kpMainWindow::slotDestroyThumbnailInitatedByUser); // Avoid change/flicker of caption due to view delete // (destroyThumbnailView()) - d->thumbnail->hide (); + d->thumbnail->hide(); - destroyThumbnailView (); + destroyThumbnailView(); - d->thumbnail->deleteLater (); d->thumbnail = nullptr; + d->thumbnail->deleteLater(); + d->thumbnail = nullptr; } } diff --git a/mainWindow/kpMainWindow_View_Zoom.cpp b/mainWindow/kpMainWindow_View_Zoom.cpp --- a/mainWindow/kpMainWindow_View_Zoom.cpp +++ b/mainWindow/kpMainWindow_View_Zoom.cpp @@ -26,7 +26,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "mainWindow/kpMainWindow.h" #include "kpMainWindowPrivate.h" #include "kpLogCategories.h" @@ -51,7 +50,7 @@ #include "views/kpZoomedView.h" #include "views/kpZoomedThumbnailView.h" -static int ZoomLevelFromString (const QString &stringIn) +static int ZoomLevelFromString(const QString &stringIn) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow_View.cpp:ZoomLevelFromString(" << stringIn << ")"; @@ -62,14 +61,14 @@ // 1. kdelibs adds accelerators to actions' text directly // 2. ',' is automatically added to change "1000%" to "1,000%" QString string = stringIn; - string.remove (QRegExp ("[^0-9]")); + string.remove(QRegExp("[^0-9]")); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\twithout non-digits='" << string << "'"; #endif // Convert zoom level to number. bool ok = false; - int zoomLevel = string.toInt (&ok); + int zoomLevel = string.toInt(&ok); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tzoomLevel=" << zoomLevel; #endif @@ -83,199 +82,194 @@ //--------------------------------------------------------------------- -static QString ZoomLevelToString (int zoomLevel) +static QString ZoomLevelToString(int zoomLevel) { - return i18n ("%1%", zoomLevel); + return i18n("%1%", zoomLevel); } //--------------------------------------------------------------------- // private -void kpMainWindow::setupViewMenuZoomActions () +void kpMainWindow::setupViewMenuZoomActions() { - KActionCollection *ac = actionCollection (); - - - d->actionActualSize = KStandardAction::actualSize (this, SLOT (slotActualSize()), ac); - d->actionFitToPage = KStandardAction::fitToPage (this, SLOT (slotFitToPage()), ac); - d->actionFitToWidth = KStandardAction::fitToWidth (this, SLOT (slotFitToWidth()), ac); - d->actionFitToHeight = KStandardAction::fitToHeight (this, SLOT (slotFitToHeight()), ac); + KActionCollection *ac = actionCollection(); + d->actionActualSize = KStandardAction::actualSize(this, SLOT(slotActualSize()), ac); + d->actionFitToPage = KStandardAction::fitToPage(this, SLOT(slotFitToPage()), ac); + d->actionFitToWidth = KStandardAction::fitToWidth(this, SLOT(slotFitToWidth()), ac); + d->actionFitToHeight = KStandardAction::fitToHeight(this, SLOT(slotFitToHeight()), ac); - d->actionZoomIn = KStandardAction::zoomIn (this, SLOT (slotZoomIn()), ac); - d->actionZoomOut = KStandardAction::zoomOut (this, SLOT (slotZoomOut()), ac); + d->actionZoomIn = KStandardAction::zoomIn(this, SLOT(slotZoomIn()), ac); + d->actionZoomOut = KStandardAction::zoomOut(this, SLOT(slotZoomOut()), ac); - - d->actionZoom = ac->add (QStringLiteral("view_zoom_to")); - d->actionZoom->setText (i18n ("&Zoom")); - connect (d->actionZoom, - static_cast(&KSelectAction::triggered), - this, &kpMainWindow::slotZoom); - d->actionZoom->setEditable (true); + d->actionZoom = ac->add (QStringLiteral("view_zoom_to")); + d->actionZoom->setText(i18n("&Zoom")); + connect(d->actionZoom, + static_cast(&KSelectAction::triggered), + this, &kpMainWindow::slotZoom); + d->actionZoom->setEditable(true); // create the zoom list for the 1st call to zoomTo() below - d->zoomList.append (10); d->zoomList.append (25); d->zoomList.append (33); - d->zoomList.append (50); d->zoomList.append (67); d->zoomList.append (75); - d->zoomList.append (100); - d->zoomList.append (200); d->zoomList.append (300); - d->zoomList.append (400); d->zoomList.append (600); d->zoomList.append (800); - d->zoomList.append (1000); d->zoomList.append (1200); d->zoomList.append (1600); + d->zoomList.append(10); + d->zoomList.append(25); + d->zoomList.append(33); + d->zoomList.append(50); + d->zoomList.append(67); + d->zoomList.append(75); + d->zoomList.append(100); + d->zoomList.append(200); + d->zoomList.append(300); + d->zoomList.append(400); + d->zoomList.append(600); + d->zoomList.append(800); + d->zoomList.append(1000); + d->zoomList.append(1200); + d->zoomList.append(1600); } //--------------------------------------------------------------------- // private -void kpMainWindow::enableViewMenuZoomDocumentActions (bool enable) +void kpMainWindow::enableViewMenuZoomDocumentActions(bool enable) { - d->actionActualSize->setEnabled (enable); - d->actionFitToPage->setEnabled (enable); - d->actionFitToWidth->setEnabled (enable); - d->actionFitToHeight->setEnabled (enable); - - d->actionZoomIn->setEnabled (enable); - d->actionZoomOut->setEnabled (enable); - d->actionZoom->setEnabled (enable); + d->actionActualSize->setEnabled(enable); + d->actionFitToPage->setEnabled(enable); + d->actionFitToWidth->setEnabled(enable); + d->actionFitToHeight->setEnabled(enable); + d->actionZoomIn->setEnabled(enable); + d->actionZoomOut->setEnabled(enable); + d->actionZoom->setEnabled(enable); // TODO: for the time being, assume that we start at zoom 100% // with no grid // This function is only called when a new document is created // or an existing document is closed. So the following will // always be correct: - zoomTo (100); + zoomTo(100); } //--------------------------------------------------------------------- // private -void kpMainWindow::sendZoomListToActionZoom () +void kpMainWindow::sendZoomListToActionZoom() { QStringList items; - const QList ::ConstIterator zoomListEnd (d->zoomList.end ()); - for (QList ::ConstIterator it = d->zoomList.constBegin (); + const QList ::ConstIterator zoomListEnd(d->zoomList.end()); + for (QList ::ConstIterator it = d->zoomList.constBegin(); it != zoomListEnd; - ++it) - { - items << ::ZoomLevelToString (*it); + ++it) { + items << ::ZoomLevelToString(*it); } // Work around a KDE bug - KSelectAction::setItems() enables the action. // David Faure said it won't be fixed because it's a feature used by // KRecentFilesAction. - bool e = d->actionZoom->isEnabled (); - d->actionZoom->setItems (items); - if (e != d->actionZoom->isEnabled ()) { - d->actionZoom->setEnabled (e); + bool e = d->actionZoom->isEnabled(); + d->actionZoom->setItems(items); + if (e != d->actionZoom->isEnabled()) { + d->actionZoom->setEnabled(e); } } //--------------------------------------------------------------------- // private -void kpMainWindow::zoomToPre (int zoomLevel) +void kpMainWindow::zoomToPre(int zoomLevel) { // We're called quite early in the init process and/or when there might // not be a document or a view so we have a lot of "if (ptr)" guards. #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::zoomToPre(" << zoomLevel << ")"; #endif - zoomLevel = qBound (kpView::MinZoomLevel, zoomLevel, kpView::MaxZoomLevel); + zoomLevel = qBound(kpView::MinZoomLevel, zoomLevel, kpView::MaxZoomLevel); int index = 0; - QList ::Iterator it = d->zoomList.begin (); + QList ::Iterator it = d->zoomList.begin(); - while (index < d->zoomList.count () && zoomLevel > *it) + while (index < d->zoomList.count() && zoomLevel > *it) { it++; index++; } if (zoomLevel != *it) { - d->zoomList.insert (it, zoomLevel); + d->zoomList.insert(it, zoomLevel); } // OPT: We get called twice on startup. sendZoomListToActionZoom() is very slow. - sendZoomListToActionZoom (); + sendZoomListToActionZoom(); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tsetCurrentItem(" << index << ")"; #endif - d->actionZoom->setCurrentItem (index); + d->actionZoom->setCurrentItem(index); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tcurrentItem=" - << d->actionZoom->currentItem () - << " action=" - << d->actionZoom->action (d->actionZoom->currentItem ()) - << " checkedAction" - << d->actionZoom->selectableActionGroup ()->checkedAction (); + << d->actionZoom->currentItem() + << " action=" + << d->actionZoom->action(d->actionZoom->currentItem()) + << " checkedAction" + << d->actionZoom->selectableActionGroup()->checkedAction(); #endif + if (viewMenuDocumentActionsEnabled()) { + d->actionActualSize->setEnabled(zoomLevel != 100); - if (viewMenuDocumentActionsEnabled ()) - { - d->actionActualSize->setEnabled (zoomLevel != 100); - - d->actionZoomIn->setEnabled (d->actionZoom->currentItem () < d->zoomList.count () - 1); - d->actionZoomOut->setEnabled (d->actionZoom->currentItem () > 0); + d->actionZoomIn->setEnabled(d->actionZoom->currentItem() < d->zoomList.count() - 1); + d->actionZoomOut->setEnabled(d->actionZoom->currentItem() > 0); } - // TODO: Is this actually needed? if (d->viewManager) { - d->viewManager->setQueueUpdates (); + d->viewManager->setQueueUpdates(); } - if (d->scrollView) - { - d->scrollView->setUpdatesEnabled (false); + if (d->scrollView) { + d->scrollView->setUpdatesEnabled(false); } } //--------------------------------------------------------------------- // private -void kpMainWindow::zoomToPost () +void kpMainWindow::zoomToPost() { #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::zoomToPost()"; #endif - if (d->mainView) - { - actionShowGridUpdate (); - updateMainViewGrid (); + if (d->mainView) { + actionShowGridUpdate(); + updateMainViewGrid(); // Since Zoom Level KSelectAction on ToolBar grabs focus after changing // Zoom, switch back to the Main View. // TODO: back to the last view - d->mainView->setFocus (); - + d->mainView->setFocus(); } - // The view magnified and moved beneath the cursor - if (tool ()) { - tool ()->somethingBelowTheCursorChanged (); + if (tool()) { + tool()->somethingBelowTheCursorChanged(); } - - if (d->scrollView) - { + if (d->scrollView) { // TODO: setUpdatesEnabled() should really return to old value // - not necessarily "true" - d->scrollView->setUpdatesEnabled (true); + d->scrollView->setUpdatesEnabled(true); } - if (d->viewManager && d->viewManager->queueUpdates ()/*just in case*/) { - d->viewManager->restoreQueueUpdates (); + if (d->viewManager && d->viewManager->queueUpdates() /*just in case*/) { + d->viewManager->restoreQueueUpdates(); } - setStatusBarZoom (d->mainView ? d->mainView->zoomLevelX () : 0); + setStatusBarZoom(d->mainView ? d->mainView->zoomLevelX() : 0); #if DEBUG_KP_MAIN_WINDOW && 1 qCDebug(kpLogMainWindow) << "kpMainWindow::zoomToPost() done"; @@ -285,23 +279,22 @@ //--------------------------------------------------------------------- // private -void kpMainWindow::zoomTo (int zoomLevel, bool centerUnderCursor) +void kpMainWindow::zoomTo(int zoomLevel, bool centerUnderCursor) { - zoomToPre (zoomLevel); + zoomToPre(zoomLevel); - - if (d->scrollView && d->mainView) - { + if (d->scrollView && d->mainView) { #if DEBUG_KP_MAIN_WINDOW && 1 - qCDebug(kpLogMainWindow) << "\tscrollView contentsX=" << d->scrollView->horizontalScrollBar()->value () - << " contentsY=" << d->scrollView->verticalScrollBar()->value () - << " contentsWidth=" << d->scrollView->widget()->width () - << " contentsHeight=" << d->scrollView->widget()->height () - << " visibleWidth=" << d->scrollView->viewport()->width () - << " visibleHeight=" << d->scrollView->viewport()->height () - << " oldZoomX=" << d->mainView->zoomLevelX () - << " oldZoomY=" << d->mainView->zoomLevelY () - << " newZoom=" << zoomLevel; + qCDebug(kpLogMainWindow) << "\tscrollView contentsX=" + << d->scrollView->horizontalScrollBar()->value() + << " contentsY=" << d->scrollView->verticalScrollBar()->value() + << " contentsWidth=" << d->scrollView->widget()->width() + << " contentsHeight=" << d->scrollView->widget()->height() + << " visibleWidth=" << d->scrollView->viewport()->width() + << " visibleHeight=" << d->scrollView->viewport()->height() + << " oldZoomX=" << d->mainView->zoomLevelX() + << " oldZoomY=" << d->mainView->zoomLevelY() + << " newZoom=" << zoomLevel; #endif // TODO: when changing from no scrollbars to scrollbars, Qt lies about @@ -319,80 +312,76 @@ bool targetDocAvail = false; double targetDocX = -1, targetDocY = -1; - if (centerUnderCursor && - d->viewManager && d->viewManager->viewUnderCursor ()) - { - kpView *const vuc = d->viewManager->viewUnderCursor (); - QPoint viewPoint = vuc->mouseViewPoint (); + if (centerUnderCursor + && d->viewManager && d->viewManager->viewUnderCursor()) { + kpView *const vuc = d->viewManager->viewUnderCursor(); + QPoint viewPoint = vuc->mouseViewPoint(); // vuc->transformViewToDoc() returns QPoint which only has int // accuracy so we do X and Y manually. - targetDocX = vuc->transformViewToDocX (viewPoint.x ()); - targetDocY = vuc->transformViewToDocY (viewPoint.y ()); + targetDocX = vuc->transformViewToDocX(viewPoint.x()); + targetDocY = vuc->transformViewToDocY(viewPoint.y()); targetDocAvail = true; if (vuc != d->mainView) { - viewPoint = vuc->transformViewToOtherView (viewPoint, d->mainView); + viewPoint = vuc->transformViewToOtherView(viewPoint, d->mainView); } - viewX = viewPoint.x (); - viewY = viewPoint.y (); - } - else - { - viewX = d->scrollView->horizontalScrollBar()->value () + - qMin (d->mainView->width (), - d->scrollView->viewport()->width ()) / 2; - viewY = d->scrollView->verticalScrollBar()->value () + - qMin (d->mainView->height (), - d->scrollView->viewport()->height ()) / 2; + viewX = viewPoint.x(); + viewY = viewPoint.y(); + } else { + viewX = d->scrollView->horizontalScrollBar()->value() + +qMin(d->mainView->width(), + d->scrollView->viewport()->width()) / 2; + viewY = d->scrollView->verticalScrollBar()->value() + +qMin(d->mainView->height(), + d->scrollView->viewport()->height()) / 2; } - - int newCenterX = viewX * zoomLevel / d->mainView->zoomLevelX (); - int newCenterY = viewY * zoomLevel / d->mainView->zoomLevelY (); + int newCenterX = viewX * zoomLevel / d->mainView->zoomLevelX(); + int newCenterY = viewY * zoomLevel / d->mainView->zoomLevelY(); // Do the zoom. - d->mainView->setZoomLevel (zoomLevel, zoomLevel); + d->mainView->setZoomLevel(zoomLevel, zoomLevel); #if DEBUG_KP_MAIN_WINDOW && 1 - qCDebug(kpLogMainWindow) << "\tvisibleWidth=" << d->scrollView->viewport()->width () - << " visibleHeight=" << d->scrollView->viewport()->height (); + qCDebug(kpLogMainWindow) << "\tvisibleWidth=" << d->scrollView->viewport()->width() + << " visibleHeight=" << d->scrollView->viewport()->height(); qCDebug(kpLogMainWindow) << "\tnewCenterX=" << newCenterX - << " newCenterY=" << newCenterY; + << " newCenterY=" << newCenterY; #endif - d->scrollView->horizontalScrollBar()->setValue(newCenterX - (d->scrollView->viewport()->width() / 2)); - d->scrollView->verticalScrollBar()->setValue(newCenterY - (d->scrollView->viewport()->height() / 2)); + d->scrollView->horizontalScrollBar()->setValue(newCenterX + - (d->scrollView->viewport()->width() / 2)); + d->scrollView->verticalScrollBar()->setValue(newCenterY + - (d->scrollView->viewport()->height() / 2)); - if (centerUnderCursor && - targetDocAvail && - d->viewManager && d->viewManager->viewUnderCursor ()) - { + if (centerUnderCursor + && targetDocAvail + && d->viewManager && d->viewManager->viewUnderCursor()) { // Move the mouse cursor so that it is still above the same // document pixel as before the zoom. - kpView *const vuc = d->viewManager->viewUnderCursor (); + kpView *const vuc = d->viewManager->viewUnderCursor(); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tcenterUnderCursor: reposition cursor; viewUnderCursor=" - << vuc->objectName (); + << vuc->objectName(); #endif - const auto viewX = vuc->transformDocToViewX (targetDocX); - const auto viewY = vuc->transformDocToViewY (targetDocY); + const auto viewX = vuc->transformDocToViewX(targetDocX); + const auto viewY = vuc->transformDocToViewY(targetDocY); // Rounding error from zooming in and out :( // TODO: do everything in terms of tool doc points in type "double". - const QPoint viewPoint (static_cast (viewX), static_cast (viewY)); + const QPoint viewPoint(static_cast(viewX), static_cast(viewY)); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tdoc: (" << targetDocX << "," << targetDocY << ")" - << " viewUnderCursor: (" << viewX << "," << viewY << ")"; + << " viewUnderCursor: (" << viewX << "," << viewY << ")"; #endif - if (vuc->visibleRegion ().contains (viewPoint)) - { - const QPoint globalPoint = - kpWidgetMapper::toGlobal (vuc, viewPoint); + if (vuc->visibleRegion().contains(viewPoint)) { + const QPoint globalPoint + = kpWidgetMapper::toGlobal(vuc, viewPoint); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\tglobalPoint=" << globalPoint; #endif @@ -404,7 +393,7 @@ // and in some stage of flash and window quits. // // Or if using kpView::setCursor() and change tool. - QCursor::setPos (globalPoint); + QCursor::setPos(globalPoint); } // e.g. Zoom to 200%, scroll mainView to bottom-right. // Unzoomed Thumbnail shows top-left portion of bottom-right of @@ -419,8 +408,7 @@ // // Unzoomed Thumbnail no longer contains the point we zoomed out // on top of. - else - { + else { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\t\twon't move cursor - would get outside view"; #endif @@ -431,43 +419,45 @@ } #if DEBUG_KP_MAIN_WINDOW && 1 - qCDebug(kpLogMainWindow) << "\t\tcheck (contentsX=" << d->scrollView->horizontalScrollBar()->value () - << ",contentsY=" << d->scrollView->verticalScrollBar()->value () - << ")"; + qCDebug(kpLogMainWindow) << "\t\tcheck (contentsX=" + << d->scrollView->horizontalScrollBar()->value() + << ",contentsY=" << d->scrollView->verticalScrollBar()->value() + << ")"; #endif } - - zoomToPost (); + zoomToPost(); } //--------------------------------------------------------------------- // private -void kpMainWindow::zoomToRect (const QRect &normalizedDocRect, - bool accountForGrips, - bool careAboutWidth, bool careAboutHeight) +void kpMainWindow::zoomToRect(const QRect &normalizedDocRect, bool accountForGrips, + bool careAboutWidth, bool careAboutHeight) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::zoomToRect(normalizedDocRect=" - << normalizedDocRect - << ",accountForGrips=" << accountForGrips - << ",careAboutWidth=" << careAboutWidth - << ",careAboutHeight=" << careAboutHeight - << ")"; + << normalizedDocRect + << ",accountForGrips=" << accountForGrips + << ",careAboutWidth=" << careAboutWidth + << ",careAboutHeight=" << careAboutHeight + << ")"; #endif // You can't care about nothing. - Q_ASSERT (careAboutWidth || careAboutHeight); + Q_ASSERT(careAboutWidth || careAboutHeight); // The size of the scroll view minus the current or future scrollbars. const QSize usableScrollArea - (d->scrollView->maximumViewportSize().width() - d->scrollView->verticalScrollBar()->sizeHint().width(), - d->scrollView->maximumViewportSize().height() - d->scrollView->horizontalScrollBar()->sizeHint().height()); + ( + d->scrollView->maximumViewportSize().width() - d->scrollView->verticalScrollBar()->sizeHint().width(), + d->scrollView->maximumViewportSize().height() + - d->scrollView->horizontalScrollBar()->sizeHint().height()); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "size=" << d->scrollView->maximumViewportSize() - << "scrollbar w=" << d->scrollView->verticalScrollBar()->sizeHint().width() - << "usableSize=" << usableScrollArea; + << "scrollbar w=" + << d->scrollView->verticalScrollBar()->sizeHint().width() + << "usableSize=" << usableScrollArea; #endif // Handle rounding error, mis-estimating the scroll view size and // cosmic rays. We do this because we really don't want unnecessary @@ -478,216 +468,215 @@ const int slack = 0; // The grip and slack are in view coordinates but are never zoomed. - const int viewWidth = - usableScrollArea.width () - - (accountForGrips ? kpGrip::Size : 0) - - slack; - const int viewHeight = - usableScrollArea.height () - - (accountForGrips ? kpGrip::Size : 0) - - slack; + const int viewWidth + = usableScrollArea.width() + -(accountForGrips ? kpGrip::Size : 0) + -slack; + const int viewHeight + = usableScrollArea.height() + -(accountForGrips ? kpGrip::Size : 0) + -slack; // We want the selected document rectangle to fill the scroll view. // // The integer arithmetic rounds down, rather than to the nearest zoom // level, as rounding down guarantees that the view, at the zoom level, // will fit inside x . - const int zoomX = - careAboutWidth ? - qMax (1, viewWidth * 100 / normalizedDocRect.width ()) : - INT_MAX; - const int zoomY = - careAboutHeight ? - qMax (1, viewHeight * 100 / normalizedDocRect.height ()) : - INT_MAX; + const int zoomX + = careAboutWidth + ? qMax(1, viewWidth * 100 / normalizedDocRect.width()) + : INT_MAX; + const int zoomY + = careAboutHeight + ? qMax(1, viewHeight * 100 / normalizedDocRect.height()) + : INT_MAX; // Since kpView only supports identical horizontal and vertical zooms, // choose the one that will show the greatest amount of document // content. - const int zoomLevel = qMin (zoomX, zoomY); + const int zoomLevel = qMin(zoomX, zoomY); #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "\tzoomX=" << zoomX - << " zoomY=" << zoomY - << " -> zoomLevel=" << zoomLevel; + << " zoomY=" << zoomY + << " -> zoomLevel=" << zoomLevel; << " -> zoomLevel=" << zoomLevel << endl; #endif - zoomToPre (zoomLevel); + zoomToPre(zoomLevel); { - d->mainView->setZoomLevel (zoomLevel, zoomLevel); + d->mainView->setZoomLevel(zoomLevel, zoomLevel); - const QPoint viewPoint = - d->mainView->transformDocToView (normalizedDocRect.topLeft ()); + const QPoint viewPoint + = d->mainView->transformDocToView(normalizedDocRect.topLeft()); d->scrollView->horizontalScrollBar()->setValue(viewPoint.x()); d->scrollView->verticalScrollBar()->setValue(viewPoint.y()); } - zoomToPost (); + zoomToPost(); } //--------------------------------------------------------------------- // public slot -void kpMainWindow::slotActualSize () +void kpMainWindow::slotActualSize() { - zoomTo (100); + zoomTo(100); } //--------------------------------------------------------------------- // public slot -void kpMainWindow::slotFitToPage () +void kpMainWindow::slotFitToPage() { - if ( d->document ) - { - zoomToRect ( - d->document->rect (), - true/*account for grips*/, - true/*care about width*/, true/*care about height*/); - } + if (d->document) { + zoomToRect( + d->document->rect(), + true /*account for grips*/, + true /*care about width*/, true /*care about height*/); + } } //--------------------------------------------------------------------- // public slot -void kpMainWindow::slotFitToWidth () +void kpMainWindow::slotFitToWidth() { - if ( d->document ) - { - const QRect docRect ( - 0/*x*/, - static_cast (d->mainView->transformViewToDocY (d->scrollView->verticalScrollBar()->value ()))/*maintain y*/, - d->document->width (), - 1/*don't care about height*/); - zoomToRect ( - docRect, - true/*account for grips*/, - true/*care about width*/, false/*don't care about height*/); - } + if (d->document) { + const QRect docRect( + 0 /*x*/, + static_cast(d->mainView->transformViewToDocY( + d->scrollView->verticalScrollBar()->value())) /*maintain y*/, + d->document->width(), + 1 /*don't care about height*/); + zoomToRect( + docRect, + true /*account for grips*/, + true /*care about width*/, false /*don't care about height*/); + } } //--------------------------------------------------------------------- // public slot -void kpMainWindow::slotFitToHeight () +void kpMainWindow::slotFitToHeight() { - if ( d->document ) - { - const QRect docRect ( - static_cast (d->mainView->transformViewToDocX (d->scrollView->horizontalScrollBar()->value ()))/*maintain x*/, - 0/*y*/, - 1/*don't care about width*/, - d->document->height ()); - zoomToRect ( - docRect, - true/*account for grips*/, - false/*don't care about width*/, true/*care about height*/); - } + if (d->document) { + const QRect docRect( + static_cast(d->mainView->transformViewToDocX( + d->scrollView->horizontalScrollBar()->value())) /*maintain x*/, + 0 /*y*/, + 1 /*don't care about width*/, + d->document->height()); + zoomToRect( + docRect, + true /*account for grips*/, + false /*don't care about width*/, true /*care about height*/); + } } //--------------------------------------------------------------------- // public -void kpMainWindow::zoomIn (bool centerUnderCursor) +void kpMainWindow::zoomIn(bool centerUnderCursor) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::zoomIn(centerUnderCursor=" - << centerUnderCursor << ") currentItem=" - << d->actionZoom->currentItem (); + << centerUnderCursor << ") currentItem=" + << d->actionZoom->currentItem(); #endif - const int targetItem = d->actionZoom->currentItem () + 1; + const int targetItem = d->actionZoom->currentItem() + 1; - if (targetItem >= static_cast (d->zoomList.count ())) { + if (targetItem >= static_cast(d->zoomList.count())) { return; } - d->actionZoom->setCurrentItem (targetItem); + d->actionZoom->setCurrentItem(targetItem); #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tnew currentItem=" << d->actionZoom->currentItem (); + qCDebug(kpLogMainWindow) << "\tnew currentItem=" << d->actionZoom->currentItem(); #endif - zoomAccordingToZoomAction (centerUnderCursor); + zoomAccordingToZoomAction(centerUnderCursor); } //--------------------------------------------------------------------- // public -void kpMainWindow::zoomOut (bool centerUnderCursor) +void kpMainWindow::zoomOut(bool centerUnderCursor) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::zoomOut(centerUnderCursor=" - << centerUnderCursor << ") currentItem=" - << d->actionZoom->currentItem (); + << centerUnderCursor << ") currentItem=" + << d->actionZoom->currentItem(); #endif - const int targetItem = d->actionZoom->currentItem () - 1; + const int targetItem = d->actionZoom->currentItem() - 1; if (targetItem < 0) { return; } - d->actionZoom->setCurrentItem (targetItem); + d->actionZoom->setCurrentItem(targetItem); #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "\tnew currentItem=" << d->actionZoom->currentItem (); + qCDebug(kpLogMainWindow) << "\tnew currentItem=" << d->actionZoom->currentItem(); #endif - zoomAccordingToZoomAction (centerUnderCursor); + zoomAccordingToZoomAction(centerUnderCursor); } //--------------------------------------------------------------------- // public slot -void kpMainWindow::slotZoomIn () +void kpMainWindow::slotZoomIn() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotZoomIn ()"; #endif - zoomIn (false/*don't center under cursor*/); + zoomIn(false /*don't center under cursor*/); } //--------------------------------------------------------------------- // public slot -void kpMainWindow::slotZoomOut () +void kpMainWindow::slotZoomOut() { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::slotZoomOut ()"; #endif - zoomOut (false/*don't center under cursor*/); + zoomOut(false /*don't center under cursor*/); } //--------------------------------------------------------------------- // public -void kpMainWindow::zoomAccordingToZoomAction (bool centerUnderCursor) +void kpMainWindow::zoomAccordingToZoomAction(bool centerUnderCursor) { #if DEBUG_KP_MAIN_WINDOW qCDebug(kpLogMainWindow) << "kpMainWindow::zoomAccordingToZoomAction(centerUnderCursor=" - << centerUnderCursor - << ") currentItem=" << d->actionZoom->currentItem () - << " currentText=" << d->actionZoom->currentText (); + << centerUnderCursor + << ") currentItem=" << d->actionZoom->currentItem() + << " currentText=" << d->actionZoom->currentText(); #endif // This might be a new zoom level the user has typed in. - zoomTo (::ZoomLevelFromString (d->actionZoom->currentText ()), - centerUnderCursor); + zoomTo(::ZoomLevelFromString(d->actionZoom->currentText()), + centerUnderCursor); } //--------------------------------------------------------------------- // private slot -void kpMainWindow::slotZoom () +void kpMainWindow::slotZoom() { #if DEBUG_KP_MAIN_WINDOW - qCDebug(kpLogMainWindow) << "kpMainWindow::slotZoom () index=" << d->actionZoom->currentItem () - << " text='" << d->actionZoom->currentText () << "'"; + qCDebug(kpLogMainWindow) << "kpMainWindow::slotZoom () index=" << d->actionZoom->currentItem() + << " text='" << d->actionZoom->currentText() << "'"; #endif - zoomAccordingToZoomAction (false/*don't center under cursor*/); + zoomAccordingToZoomAction(false /*don't center under cursor*/); } //--------------------------------------------------------------------- diff --git a/pixmapfx/kpPixmapFX.h b/pixmapfx/kpPixmapFX.h --- a/pixmapfx/kpPixmapFX.h +++ b/pixmapfx/kpPixmapFX.h @@ -1,4 +1,3 @@ - // REFACTOR: Split this class into one for each distinct functionality category // (e.g. effects, mask operations)? @@ -28,19 +27,16 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_PIXMAP_FX_H #define KP_PIXMAP_FX_H - #include #include #include #include "imagelib/kpColor.h" - class QColor; class QImage; class QTransform; @@ -50,9 +46,6 @@ class QPolygon; class QRect; - - - // // QPixmap (view) Manipulation. // @@ -73,45 +66,40 @@ // // Returns the pixel and mask data found at the in . // - static QImage getPixmapAt (const QImage &pm, const QRect &rect); + static QImage getPixmapAt(const QImage &pm, const QRect &rect); // // Sets the pixel and mask data at in <*destPixmapPtr> // to . Neither 's width nor height are allowed // to be bigger than 's (you can't copy more than you have). // On the other hand, you can copy less than the size of // - no scaling is done. // - static void setPixmapAt (QImage *destPixmapPtr, const QRect &destRect, - const QImage &srcPixmap); + static void setPixmapAt(QImage *destPixmapPtr, const QRect &destRect, const QImage &srcPixmap); // // Sets the pixel and mask data at the rectangle in <*destPixmapPtr>, // with the top-left and dimensions , // to . // - static void setPixmapAt (QImage *destPixmapPtr, const QPoint &destAt, - const QImage &srcPixmap); - static void setPixmapAt (QImage *destPixmapPtr, int destX, int destY, - const QImage &srcPixmap); + static void setPixmapAt(QImage *destPixmapPtr, const QPoint &destAt, const QImage &srcPixmap); + static void setPixmapAt(QImage *destPixmapPtr, int destX, int destY, const QImage &srcPixmap); // // Draws on top of <*destPixmapPtr> at . // The mask of <*destPixmapPtr> is adjusted so that all opaque // pixels in will be opaque in <*destPixmapPtr>. // - static void paintPixmapAt (QImage *destPixmapPtr, const QPoint &destAt, - const QImage &srcPixmap); - static void paintPixmapAt (QImage *destPixmapPtr, int destX, int destY, - const QImage &srcPixmap); + static void paintPixmapAt(QImage *destPixmapPtr, const QPoint &destAt, const QImage &srcPixmap); + static void paintPixmapAt(QImage *destPixmapPtr, int destX, int destY, const QImage &srcPixmap); // // Returns the colour of the pixel at in . // If the pixel is transparent, a value is returned such that // kpTool::isColorTransparent() will return true. // - static kpColor getColorAtPixel (const QImage &pm, const QPoint &at); - static kpColor getColorAtPixel (const QImage &pm, int x, int y); + static kpColor getColorAtPixel(const QImage &pm, const QPoint &at); + static kpColor getColorAtPixel(const QImage &pm, int x, int y); // // Transforms @@ -123,18 +111,15 @@ // Resizes an image to the given width and height, // filling any new areas with . // - static void resize (QImage *destPtr, int w, int h, - const kpColor &backgroundColor); - static QImage resize (const QImage &pm, int w, int h, - const kpColor &backgroundColor); + static void resize(QImage *destPtr, int w, int h, const kpColor &backgroundColor); + static QImage resize(const QImage &pm, int w, int h, const kpColor &backgroundColor); // // Scales an image to the given width and height. // If is true, a smooth scale will be used. // - static void scale (QImage *destPtr, int w, int h, bool pretty = false); - static QImage scale (const QImage &pm, int w, int h, bool pretty = false); - + static void scale(QImage *destPtr, int w, int h, bool pretty = false); + static QImage scale(const QImage &pm, int w, int h, bool pretty = false); // The minimum difference between 2 angles (in degrees) such that they are // considered different. This gives you at least enough precision to @@ -144,7 +129,6 @@ // Currently used for skew & rotate operations. static const double AngleInDegreesEpsilon; - // // Skews an image. // @@ -157,15 +141,13 @@ // Using & to generate preview pixmaps is // significantly more efficient than skewing and then scaling yourself. // - static QTransform skewMatrix (int width, int height, double hangle, double vangle); - static QTransform skewMatrix (const QImage &pixmap, double hangle, double vangle); + static QTransform skewMatrix(int width, int height, double hangle, double vangle); + static QTransform skewMatrix(const QImage &pixmap, double hangle, double vangle); - static void skew (QImage *destPixmapPtr, double hangle, double vangle, - const kpColor &backgroundColor, - int targetWidth = -1, int targetHeight = -1); - static QImage skew (const QImage &pm, double hangle, double vangle, - const kpColor &backgroundColor, - int targetWidth = -1, int targetHeight = -1); + static void skew(QImage *destPixmapPtr, double hangle, double vangle, + const kpColor &backgroundColor, int targetWidth = -1, int targetHeight = -1); + static QImage skew(const QImage &pm, double hangle, double vangle, + const kpColor &backgroundColor, int targetWidth = -1, int targetHeight = -1); // // Rotates an image. @@ -178,17 +160,15 @@ // Using & to generate preview pixmaps is // significantly more efficient than rotating and then scaling yourself. // - static QTransform rotateMatrix (int width, int height, double angle); - static QTransform rotateMatrix (const QImage &pixmap, double angle); + static QTransform rotateMatrix(int width, int height, double angle); + static QTransform rotateMatrix(const QImage &pixmap, double angle); - static bool isLosslessRotation (double angle); + static bool isLosslessRotation(double angle); - static void rotate (QImage *destPixmapPtr, double angle, - const kpColor &backgroundColor, - int targetWidth = -1, int targetHeight = -1); - static QImage rotate (const QImage &pm, double angle, - const kpColor &backgroundColor, - int targetWidth = -1, int targetHeight = -1); + static void rotate(QImage *destPixmapPtr, double angle, const kpColor &backgroundColor, + int targetWidth = -1, int targetHeight = -1); + static QImage rotate(const QImage &pm, double angle, const kpColor &backgroundColor, + int targetWidth = -1, int targetHeight = -1); // // Drawing Shapes @@ -199,13 +179,13 @@ // Returns a pen suitable for drawing a rectangle with 90 degree // corners ("MiterJoin"). This is necessary since Qt4 defaults to // "BevelJoin". is passed straight to QPen without modification. - static QPen QPainterDrawRectPen (const QColor &color, int qtWidth); + static QPen QPainterDrawRectPen(const QColor &color, int qtWidth); // Returns a pen suitable for drawing lines / polylines / polygons / // curves with rounded corners. This is necessary since Qt4 defaults // to square corners ("SquareCap") and "BevelJoin". // is passed straight to QPen without modification. - static QPen QPainterDrawLinePen (const QColor &color, int qtWidth); + static QPen QPainterDrawLinePen(const QColor &color, int qtWidth); static bool Only1PixelInPointArray(const QPolygon &points); @@ -216,34 +196,23 @@ // // If is valid, it draws a stippled line alternating // between long strips of and short strips of . - static void drawPolyline (QImage *image, - const QPolygon &points, - const kpColor &color, int penWidth, - const kpColor &stippleColor = kpColor::Invalid); + static void drawPolyline(QImage *image, const QPolygon &points, const kpColor &color, + int penWidth, const kpColor &stippleColor = kpColor::Invalid); // = shape completed else drawing but haven't finalised. // If not , the edge that would form the closure, if the // shape were finalised now, is highlighted specially. // // Odd-even fill. - static void drawPolygon (QImage *image, - const QPolygon &points, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor = kpColor::Invalid, - bool isFinal = true, - const kpColor &fStippleColor = kpColor::Invalid); - - static void fillRect (QImage *image, - int x, int y, int width, int height, - const kpColor &color, - const kpColor &stippleColor = kpColor::Invalid); - - static void drawStippleRect(QImage *image, - int x, int y, int width, int height, - const kpColor &fcolor, - const kpColor &fStippleColor); + static void drawPolygon(QImage *image, const QPolygon &points, const kpColor &fcolor, + int penWidth, const kpColor &bcolor = kpColor::Invalid, + bool isFinal = true, const kpColor &fStippleColor = kpColor::Invalid); -}; + static void fillRect(QImage *image, int x, int y, int width, int height, const kpColor &color, + const kpColor &stippleColor = kpColor::Invalid); + static void drawStippleRect(QImage *image, int x, int y, int width, int height, + const kpColor &fcolor, const kpColor &fStippleColor); +}; #endif // KP_PIXMAP_FX_H diff --git a/pixmapfx/kpPixmapFX_DrawShapes.cpp b/pixmapfx/kpPixmapFX_DrawShapes.cpp --- a/pixmapfx/kpPixmapFX_DrawShapes.cpp +++ b/pixmapfx/kpPixmapFX_DrawShapes.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,13 +24,10 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_PIXMAP_FX 0 - #include "kpPixmapFX.h" - #include #include #include @@ -47,14 +43,13 @@ //--------------------------------------------------------------------- // Returns whether there is only 1 distinct point in . -bool kpPixmapFX::Only1PixelInPointArray (const QPolygon &points) +bool kpPixmapFX::Only1PixelInPointArray(const QPolygon &points) { - if (points.count () == 0) { + if (points.count() == 0) { return false; } - for (int i = 1; i < static_cast (points.count ()); i++) - { + for (int i = 1; i < static_cast(points.count()); i++) { if (points [i] != points [0]) { return false; } @@ -83,14 +78,12 @@ // # // # // -static int WidthToQPenWidth (int width, bool drawingEllipse = false) +static int WidthToQPenWidth(int width, bool drawingEllipse = false) { - if (width == 1) - { + if (width == 1) { // 3x10 ellipse with Qt width 0 looks like rectangle. // Therefore, do not apply this 1 -> 0 transformations for ellipses. - if (!drawingEllipse) - { + if (!drawingEllipse) { // Closer to looking width 1, for lines at least. return 0; } @@ -101,75 +94,67 @@ //--------------------------------------------------------------------- -static void QPainterSetPenWithStipple (QPainter *p, - const kpColor &fColor, - int penWidth, - const kpColor &fStippleColor = kpColor::Invalid, - bool isEllipseLike = false) +static void QPainterSetPenWithStipple(QPainter *p, const kpColor &fColor, int penWidth, + const kpColor &fStippleColor = kpColor::Invalid, + bool isEllipseLike = false) { - if (!fStippleColor.isValid ()) - { - p->setPen ( - kpPixmapFX::QPainterDrawLinePen ( + if (!fStippleColor.isValid()) { + p->setPen( + kpPixmapFX::QPainterDrawLinePen( fColor.toQColor(), - ::WidthToQPenWidth (penWidth, isEllipseLike))); - } - else - { - QPen usePen = kpPixmapFX::QPainterDrawLinePen ( + ::WidthToQPenWidth(penWidth, isEllipseLike))); + } else { + QPen usePen = kpPixmapFX::QPainterDrawLinePen( fColor.toQColor(), - ::WidthToQPenWidth (penWidth, isEllipseLike)); - usePen.setStyle (Qt::DashLine); - p->setPen (usePen); + ::WidthToQPenWidth(penWidth, isEllipseLike)); + usePen.setStyle(Qt::DashLine); + p->setPen(usePen); - p->setBackground (fStippleColor.toQColor()); - p->setBackgroundMode (Qt::OpaqueMode); + p->setBackground(fStippleColor.toQColor()); + p->setBackgroundMode(Qt::OpaqueMode); } } //--------------------------------------------------------------------- // public static -QPen kpPixmapFX::QPainterDrawRectPen (const QColor &color, int qtWidth) +QPen kpPixmapFX::QPainterDrawRectPen(const QColor &color, int qtWidth) { - return QPen (color, qtWidth, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin); + return QPen(color, qtWidth, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin); } //--------------------------------------------------------------------- // public static -QPen kpPixmapFX::QPainterDrawLinePen (const QColor &color, int qtWidth) +QPen kpPixmapFX::QPainterDrawLinePen(const QColor &color, int qtWidth) { - return QPen (color, qtWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); + return QPen(color, qtWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); } //--------------------------------------------------------------------- // // drawPolyline() / drawLine() // // public static -void kpPixmapFX::drawPolyline (QImage *image, - const QPolygon &points, - const kpColor &color, int penWidth, - const kpColor &stippleColor) +void kpPixmapFX::drawPolyline(QImage *image, const QPolygon &points, const kpColor &color, + int penWidth, const kpColor &stippleColor) { QPainter painter(image); ::QPainterSetPenWithStipple(&painter, - color, penWidth, - stippleColor); - + color, penWidth, + stippleColor); + // Qt bug: single point doesn't show up depending on penWidth. - if (Only1PixelInPointArray(points)) - { + if (Only1PixelInPointArray(points)) { #if DEBUG_KP_PIXMAP_FX qCDebug(kpLogPixmapfx) << "\tinvoking single point hack"; #endif painter.drawPoint(points[0]); return; } - + painter.drawPolyline(points); } @@ -179,30 +164,26 @@ // // public static -void kpPixmapFX::drawPolygon (QImage *image, - const QPolygon &points, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor, - bool isFinal, - const kpColor &fStippleColor) +void kpPixmapFX::drawPolygon(QImage *image, const QPolygon &points, const kpColor &fcolor, + int penWidth, const kpColor &bcolor, bool isFinal, + const kpColor &fStippleColor) { QPainter p(image); - ::QPainterSetPenWithStipple (&p, - fcolor, penWidth, - fStippleColor); + ::QPainterSetPenWithStipple(&p, + fcolor, penWidth, + fStippleColor); - if (bcolor.isValid ()) { - p.setBrush (QBrush (bcolor.toQColor())); + if (bcolor.isValid()) { + p.setBrush(QBrush(bcolor.toQColor())); } // HACK: seems to be needed if set_Pen_(Qt::color0) else fills with Qt::color0. else { - p.setBrush (Qt::NoBrush); + p.setBrush(Qt::NoBrush); } // Qt bug: single point doesn't show up depending on penWidth. - if (Only1PixelInPointArray (points)) - { + if (Only1PixelInPointArray(points)) { #if DEBUG_KP_PIXMAP_FX qCDebug(kpLogPixmapfx) << "\tinvoking single point hack"; #endif @@ -213,12 +194,12 @@ // TODO: why aren't the ends rounded? p.drawPolygon(points, Qt::OddEvenFill); - if ( isFinal ) { - return; + if (isFinal) { + return; } - if ( points.count() <= 2 ) { - return; + if (points.count() <= 2) { + return; } p.setCompositionMode(QPainter::RasterOp_SourceXorDestination); @@ -229,57 +210,46 @@ //--------------------------------------------------------------------- // public static -void kpPixmapFX::fillRect (QImage *image, - int x, int y, int width, int height, - const kpColor &color, - const kpColor &stippleColor) +void kpPixmapFX::fillRect(QImage *image, int x, int y, int width, int height, const kpColor &color, + const kpColor &stippleColor) { QPainter painter(image); - if (!stippleColor.isValid ()) - { - painter.fillRect (x, y, width, height, color.toQColor()); - } - else - { + if (!stippleColor.isValid()) { + painter.fillRect(x, y, width, height, color.toQColor()); + } else { const int StippleSize = 4; - painter.setClipRect (x, y, width, height); + painter.setClipRect(x, y, width, height); - for (int dy = 0; dy < height; dy += StippleSize) - { - for (int dx = 0; dx < width; dx += StippleSize) - { + for (int dy = 0; dy < height; dy += StippleSize) { + for (int dx = 0; dx < width; dx += StippleSize) { const bool parity = ((dy + dx) / StippleSize) % 2; kpColor useColor; if (!parity) { useColor = color; - } - else { + } else { useColor = stippleColor; } - - painter.fillRect (x + dx, y + dy, StippleSize, StippleSize, useColor.toQColor()); + + painter.fillRect(x + dx, y + dy, StippleSize, StippleSize, useColor.toQColor()); } } - } } //--------------------------------------------------------------------- -void kpPixmapFX::drawStippleRect(QImage *image, - int x, int y, int width, int height, - const kpColor &fColor, - const kpColor &fStippleColor) +void kpPixmapFX::drawStippleRect(QImage *image, int x, int y, int width, int height, + const kpColor &fColor, const kpColor &fStippleColor) { - QPainter painter(image); + QPainter painter(image); - painter.setPen(QPen(fColor.toQColor(), 1, Qt::DashLine)); - painter.setBackground(fStippleColor.toQColor()); - painter.setBackgroundMode(Qt::OpaqueMode); - painter.drawRect(x, y, width - 1, height - 1); + painter.setPen(QPen(fColor.toQColor(), 1, Qt::DashLine)); + painter.setBackground(fStippleColor.toQColor()); + painter.setBackgroundMode(Qt::OpaqueMode); + painter.drawRect(x, y, width - 1, height - 1); } //--------------------------------------------------------------------- diff --git a/pixmapfx/kpPixmapFX_GetSetPixmapParts.cpp b/pixmapfx/kpPixmapFX_GetSetPixmapParts.cpp --- a/pixmapfx/kpPixmapFX_GetSetPixmapParts.cpp +++ b/pixmapfx/kpPixmapFX_GetSetPixmapParts.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,13 +24,10 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_PIXMAP_FX 0 - #include "kpPixmapFX.h" - #include #include #include @@ -44,32 +40,31 @@ //--------------------------------------------------------------------- // public static -QImage kpPixmapFX::getPixmapAt (const QImage &image, const QRect &rect) +QImage kpPixmapFX::getPixmapAt(const QImage &image, const QRect &rect) { - return image.copy(rect); + return image.copy(rect); } //--------------------------------------------------------------------- // public static -void kpPixmapFX::setPixmapAt(QImage *destPtr, const QRect &destRect, - const QImage &src) +void kpPixmapFX::setPixmapAt(QImage *destPtr, const QRect &destRect, const QImage &src) { #if DEBUG_KP_PIXMAP_FX && 1 qCDebug(kpLogPixmapfx) << "kpPixmapFX::setPixmapAt(destPixmap->rect=" - << destPtr->rect () - << ",destRect=" - << destRect - << ",src.rect=" - << src.rect () - << ")"; + << destPtr->rect() + << ",destRect=" + << destRect + << ",src.rect=" + << src.rect() + << ")"; #endif - Q_ASSERT (destPtr); + Q_ASSERT(destPtr); // You cannot copy more than what you have. - Q_ASSERT (destRect.width () <= src.width () && - destRect.height () <= src.height ()); + Q_ASSERT(destRect.width() <= src.width() + && destRect.height() <= src.height()); QPainter painter(destPtr); // destination shall be source only @@ -80,29 +75,26 @@ //--------------------------------------------------------------------- // public static -void kpPixmapFX::setPixmapAt (QImage *destPtr, const QPoint &destAt, - const QImage &src) +void kpPixmapFX::setPixmapAt(QImage *destPtr, const QPoint &destAt, const QImage &src) { - kpPixmapFX::setPixmapAt (destPtr, - QRect (destAt.x (), destAt.y (), - src.width (), src.height ()), - src); + kpPixmapFX::setPixmapAt(destPtr, + QRect(destAt.x(), destAt.y(), + src.width(), src.height()), + src); } //--------------------------------------------------------------------- // public static -void kpPixmapFX::setPixmapAt (QImage *destPtr, int destX, int destY, - const QImage &src) +void kpPixmapFX::setPixmapAt(QImage *destPtr, int destX, int destY, const QImage &src) { - kpPixmapFX::setPixmapAt (destPtr, QPoint (destX, destY), src); + kpPixmapFX::setPixmapAt(destPtr, QPoint(destX, destY), src); } //--------------------------------------------------------------------- // public static -void kpPixmapFX::paintPixmapAt (QImage *destPtr, const QPoint &destAt, - const QImage &src) +void kpPixmapFX::paintPixmapAt(QImage *destPtr, const QPoint &destAt, const QImage &src) { // draw image with SourceOver composition mode QPainter painter(destPtr); @@ -112,31 +104,30 @@ //--------------------------------------------------------------------- // public static -void kpPixmapFX::paintPixmapAt (QImage *destPtr, int destX, int destY, - const QImage &src) +void kpPixmapFX::paintPixmapAt(QImage *destPtr, int destX, int destY, const QImage &src) { - kpPixmapFX::paintPixmapAt(destPtr, QPoint (destX, destY), src); + kpPixmapFX::paintPixmapAt(destPtr, QPoint(destX, destY), src); } //--------------------------------------------------------------------- // public static -kpColor kpPixmapFX::getColorAtPixel (const QImage &img, const QPoint &at) +kpColor kpPixmapFX::getColorAtPixel(const QImage &img, const QPoint &at) { - if (!img.valid (at.x (), at.y ())) { + if (!img.valid(at.x(), at.y())) { return kpColor::Invalid; } QRgb rgba = img.pixel(at); - return kpColor (rgba); + return kpColor(rgba); } //--------------------------------------------------------------------- // public static -kpColor kpPixmapFX::getColorAtPixel (const QImage &img, int x, int y) +kpColor kpPixmapFX::getColorAtPixel(const QImage &img, int x, int y) { - return kpPixmapFX::getColorAtPixel (img, QPoint (x, y)); + return kpPixmapFX::getColorAtPixel(img, QPoint(x, y)); } //--------------------------------------------------------------------- diff --git a/pixmapfx/kpPixmapFX_Transforms.cpp b/pixmapfx/kpPixmapFX_Transforms.cpp --- a/pixmapfx/kpPixmapFX_Transforms.cpp +++ b/pixmapfx/kpPixmapFX_Transforms.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_PIXMAP_FX 0 - #include "kpPixmapFX.h" #include @@ -47,8 +44,7 @@ //--------------------------------------------------------------------- // public static -void kpPixmapFX::resize (QImage *destPtr, int w, int h, - const kpColor &backgroundColor) +void kpPixmapFX::resize(QImage *destPtr, int w, int h, const kpColor &backgroundColor) { #if DEBUG_KP_PIXMAP_FX && 1 qCDebug(kpLogPixmapfx) << "kpPixmapFX::resize()"; @@ -58,18 +54,18 @@ return; } - const int oldWidth = destPtr->width (); - const int oldHeight = destPtr->height (); + const int oldWidth = destPtr->width(); + const int oldHeight = destPtr->height(); if (w == oldWidth && h == oldHeight) { return; } - QImage newImage (w, h, QImage::Format_ARGB32_Premultiplied); + QImage newImage(w, h, QImage::Format_ARGB32_Premultiplied); // Would have new undefined areas? if (w > oldWidth || h > oldHeight) { - newImage.fill (backgroundColor.toQRgb ()); + newImage.fill(backgroundColor.toQRgb()); } // Copy over old pixmap. @@ -85,40 +81,39 @@ //--------------------------------------------------------------------- // public static -QImage kpPixmapFX::resize (const QImage &image, int w, int h, - const kpColor &backgroundColor) +QImage kpPixmapFX::resize(const QImage &image, int w, int h, const kpColor &backgroundColor) { QImage ret = image; - kpPixmapFX::resize (&ret, w, h, backgroundColor); + kpPixmapFX::resize(&ret, w, h, backgroundColor); return ret; } //--------------------------------------------------------------------- // public static -void kpPixmapFX::scale (QImage *destPtr, int w, int h, bool pretty) +void kpPixmapFX::scale(QImage *destPtr, int w, int h, bool pretty) { if (!destPtr) { return; } - *destPtr = kpPixmapFX::scale (*destPtr, w, h, pretty); + *destPtr = kpPixmapFX::scale(*destPtr, w, h, pretty); } //--------------------------------------------------------------------- // public static -QImage kpPixmapFX::scale (const QImage &image, int w, int h, bool pretty) +QImage kpPixmapFX::scale(const QImage &image, int w, int h, bool pretty) { #if DEBUG_KP_PIXMAP_FX && 0 - qCDebug(kpLogPixmapfx) << "kpPixmapFX::scale(oldRect=" << image.rect () - << ",w=" << w - << ",h=" << h - << ",pretty=" << pretty - << ")"; + qCDebug(kpLogPixmapfx) << "kpPixmapFX::scale(oldRect=" << image.rect() + << ",w=" << w + << ",h=" << h + << ",pretty=" << pretty + << ")"; #endif - if (w == image.width () && h == image.height ()) { + if (w == image.width() && h == image.height()) { return image; } @@ -129,37 +124,35 @@ //--------------------------------------------------------------------- // public static -const double kpPixmapFX::AngleInDegreesEpsilon = - qRadiansToDegrees (std::tan (1.0 / 10000.0)) - / (2.0/*max error allowed*/ * 2.0/*for good measure*/); - +const double kpPixmapFX::AngleInDegreesEpsilon + = qRadiansToDegrees(std::tan(1.0 / 10000.0)) + / (2.0 /*max error allowed*/ * 2.0 /*for good measure*/); -static void MatrixDebug (const QString& matrixName, const QTransform &matrix, - int srcPixmapWidth = -1, int srcPixmapHeight = -1) +static void MatrixDebug(const QString &matrixName, const QTransform &matrix, + int srcPixmapWidth = -1, int srcPixmapHeight = -1) { #if DEBUG_KP_PIXMAP_FX const int w = srcPixmapWidth, h = srcPixmapHeight; qCDebug(kpLogPixmapfx) << matrixName << "=" << matrix; // Sometimes this precision lets us see unexpected rounding errors. - fprintf (stderr, "m11=%.24f m12=%.24f m21=%.24f m22=%.24f dx=%.24f dy=%.24f\n", - matrix.m11 (), matrix.m12 (), - matrix.m21 (), matrix.m22 (), - matrix.dx (), matrix.dy ()); - if (w > 0 && h > 0) - { - qCDebug(kpLogPixmapfx) << "(0,0) ->" << matrix.map (QPoint (0, 0)); - qCDebug(kpLogPixmapfx) << "(w-1,0) ->" << matrix.map (QPoint (w - 1, 0)); - qCDebug(kpLogPixmapfx) << "(0,h-1) ->" << matrix.map (QPoint (0, h - 1)); - qCDebug(kpLogPixmapfx) << "(w-1,h-1) ->" << matrix.map (QPoint (w - 1, h - 1)); + fprintf(stderr, "m11=%.24f m12=%.24f m21=%.24f m22=%.24f dx=%.24f dy=%.24f\n", + matrix.m11(), matrix.m12(), + matrix.m21(), matrix.m22(), + matrix.dx(), matrix.dy()); + if (w > 0 && h > 0) { + qCDebug(kpLogPixmapfx) << "(0,0) ->" << matrix.map(QPoint(0, 0)); + qCDebug(kpLogPixmapfx) << "(w-1,0) ->" << matrix.map(QPoint(w - 1, 0)); + qCDebug(kpLogPixmapfx) << "(0,h-1) ->" << matrix.map(QPoint(0, h - 1)); + qCDebug(kpLogPixmapfx) << "(w-1,h-1) ->" << matrix.map(QPoint(w - 1, h - 1)); } #else - Q_UNUSED (matrixName); - Q_UNUSED (matrix); - Q_UNUSED (srcPixmapWidth); - Q_UNUSED (srcPixmapHeight); + Q_UNUSED(matrixName); + Q_UNUSED(matrix); + Q_UNUSED(srcPixmapWidth); + Q_UNUSED(srcPixmapHeight); #endif // DEBUG_KP_PIXMAP_FX } @@ -180,34 +173,34 @@ // the output is the same as QPixmap::trueMatrix(): is one off // (dy=27 instead of 26). // SYNC: I bet this is a Qt4 bug. -static QTransform MatrixWithZeroOrigin (const QTransform &matrix, int width, int height) +static QTransform MatrixWithZeroOrigin(const QTransform &matrix, int width, int height) { #if DEBUG_KP_PIXMAP_FX qCDebug(kpLogPixmapfx) << "matrixWithZeroOrigin(w=" << width << ",h=" << height << ")"; - qCDebug(kpLogPixmapfx) << "\tmatrix: m11=" << matrix.m11 () - << "m12=" << matrix.m12 () - << "m21=" << matrix.m21 () - << "m22=" << matrix.m22 () - << "dx=" << matrix.dx () - << "dy=" << matrix.dy (); + qCDebug(kpLogPixmapfx) << "\tmatrix: m11=" << matrix.m11() + << "m12=" << matrix.m12() + << "m21=" << matrix.m21() + << "m22=" << matrix.m22() + << "dx=" << matrix.dx() + << "dy=" << matrix.dy(); #endif - QRect mappedRect = matrix.mapRect (QRect (0, 0, width, height)); + QRect mappedRect = matrix.mapRect(QRect(0, 0, width, height)); #if DEBUG_KP_PIXMAP_FX qCDebug(kpLogPixmapfx) << "\tmappedRect=" << mappedRect; #endif - QTransform translatedMatrix ( - matrix.m11 (), matrix.m12 (), - matrix.m21 (), matrix.m22 (), - matrix.dx () - mappedRect.left (), matrix.dy () - mappedRect.top ()); + QTransform translatedMatrix( + matrix.m11(), matrix.m12(), + matrix.m21(), matrix.m22(), + matrix.dx() - mappedRect.left(), matrix.dy() - mappedRect.top()); #if DEBUG_KP_PIXMAP_FX qCDebug(kpLogPixmapfx) << "\treturning" << translatedMatrix; - qCDebug(kpLogPixmapfx) << "(0,0) ->" << translatedMatrix.map (QPoint (0, 0)); - qCDebug(kpLogPixmapfx) << "(w-1,0) ->" << translatedMatrix.map (QPoint (width - 1, 0)); - qCDebug(kpLogPixmapfx) << "(0,h-1) ->" << translatedMatrix.map (QPoint (0, height - 1)); - qCDebug(kpLogPixmapfx) << "(w-1,h-1) ->" << translatedMatrix.map (QPoint (width - 1, height - 1)); + qCDebug(kpLogPixmapfx) << "(0,0) ->" << translatedMatrix.map(QPoint(0, 0)); + qCDebug(kpLogPixmapfx) << "(w-1,0) ->" << translatedMatrix.map(QPoint(width - 1, 0)); + qCDebug(kpLogPixmapfx) << "(0,h-1) ->" << translatedMatrix.map(QPoint(0, height - 1)); + qCDebug(kpLogPixmapfx) << "(w-1,h-1) ->" << translatedMatrix.map(QPoint(width - 1, height - 1)); #endif return translatedMatrix; @@ -225,32 +218,32 @@ // that follow. But it was worth a try and might still help us given the // sometimes excessive aliasing QPainter::draw{Pixmap,Image}() gives us, when // QPainter::SmoothPixmapTransform is disabled. -static double TrueMatrixFixInts (double x) +static double TrueMatrixFixInts(double x) { - if (std::fabs (x - qRound (x)) < TrueMatrixEpsilon) { - return qRound (x); + if (std::fabs(x - qRound(x)) < TrueMatrixEpsilon) { + return qRound(x); } return x; } //--------------------------------------------------------------------- -static QTransform TrueMatrix (const QTransform &matrix, int srcPixmapWidth, int srcPixmapHeight) +static QTransform TrueMatrix(const QTransform &matrix, int srcPixmapWidth, int srcPixmapHeight) { - ::MatrixDebug (QStringLiteral("TrueMatrix(): org"), matrix); + ::MatrixDebug(QStringLiteral("TrueMatrix(): org"), matrix); - const QTransform truMat = QPixmap::trueMatrix (matrix, srcPixmapWidth, srcPixmapHeight); - ::MatrixDebug (QStringLiteral("TrueMatrix(): passed through QPixmap::trueMatrix()"), truMat); + const QTransform truMat = QPixmap::trueMatrix(matrix, srcPixmapWidth, srcPixmapHeight); + ::MatrixDebug(QStringLiteral("TrueMatrix(): passed through QPixmap::trueMatrix()"), truMat); - const QTransform retMat ( - ::TrueMatrixFixInts (truMat.m11 ()), - ::TrueMatrixFixInts (truMat.m12 ()), - ::TrueMatrixFixInts (truMat.m21 ()), - ::TrueMatrixFixInts (truMat.m22 ()), - ::TrueMatrixFixInts (truMat.dx ()), - ::TrueMatrixFixInts (truMat.dy ())); - ::MatrixDebug (QStringLiteral("TrueMatrix(): fixed ints"), retMat); + const QTransform retMat( + ::TrueMatrixFixInts(truMat.m11()), + ::TrueMatrixFixInts(truMat.m12()), + ::TrueMatrixFixInts(truMat.m21()), + ::TrueMatrixFixInts(truMat.m22()), + ::TrueMatrixFixInts(truMat.dx()), + ::TrueMatrixFixInts(truMat.dy())); + ::MatrixDebug(QStringLiteral("TrueMatrix(): fixed ints"), retMat); return retMat; } @@ -268,106 +261,105 @@ // // Use and to specify the intended output size // of the pixmap. -1 if don't care. -static QImage TransformPixmap (const QImage &pm, const QTransform &transformMatrix_, - const kpColor &backgroundColor, - int targetWidth, int targetHeight) +static QImage TransformPixmap(const QImage &pm, const QTransform &transformMatrix_, + const kpColor &backgroundColor, int targetWidth, int targetHeight) { QTransform transformMatrix = transformMatrix_; #if DEBUG_KP_PIXMAP_FX && 1 - qCDebug(kpLogPixmapfx) << "kppixmapfx.cpp: TransformPixmap(pm.size=" << pm.size () - << ",targetWidth=" << targetWidth - << ",targetHeight=" << targetHeight - << ")"; + qCDebug(kpLogPixmapfx) << "kppixmapfx.cpp: TransformPixmap(pm.size=" << pm.size() + << ",targetWidth=" << targetWidth + << ",targetHeight=" << targetHeight + << ")"; #endif - QRect newRect = transformMatrix.mapRect (pm.rect ()); + QRect newRect = transformMatrix.mapRect(pm.rect()); #if DEBUG_KP_PIXMAP_FX && 1 qCDebug(kpLogPixmapfx) << "\tmappedRect=" << newRect; #endif QTransform scaleMatrix; - if (targetWidth > 0 && targetWidth != newRect.width ()) - { + if (targetWidth > 0 && targetWidth != newRect.width()) { #if DEBUG_KP_PIXMAP_FX && 1 qCDebug(kpLogPixmapfx) << "\tadjusting for targetWidth"; #endif - scaleMatrix.scale (double (targetWidth) / double (newRect.width ()), 1); + scaleMatrix.scale(double(targetWidth) / double(newRect.width()), 1); } - if (targetHeight > 0 && targetHeight != newRect.height ()) - { + if (targetHeight > 0 && targetHeight != newRect.height()) { #if DEBUG_KP_PIXMAP_FX && 1 qCDebug(kpLogPixmapfx) << "\tadjusting for targetHeight"; #endif - scaleMatrix.scale (1, double (targetHeight) / double (newRect.height ())); + scaleMatrix.scale(1, double(targetHeight) / double(newRect.height())); } - if (!scaleMatrix.isIdentity ()) - { + if (!scaleMatrix.isIdentity()) { #if DEBUG_KP_PIXMAP_FX && 1 // TODO: What is going on here??? Why isn't matrix * working properly? QTransform wrongMatrix = transformMatrix * scaleMatrix; QTransform oldHat = transformMatrix; - if (targetWidth > 0 && targetWidth != newRect.width ()) { - oldHat.scale (double (targetWidth) / double (newRect.width ()), 1); + if (targetWidth > 0 && targetWidth != newRect.width()) { + oldHat.scale(double(targetWidth) / double(newRect.width()), 1); } - if (targetHeight > 0 && targetHeight != newRect.height ()) { - oldHat.scale (1, double (targetHeight) / double (newRect.height ())); + if (targetHeight > 0 && targetHeight != newRect.height()) { + oldHat.scale(1, double(targetHeight) / double(newRect.height())); } QTransform altHat = transformMatrix; - altHat.scale ((targetWidth > 0 && targetWidth != newRect.width ()) ? double (targetWidth) / double (newRect.width ()) : 1, - (targetHeight > 0 && targetHeight != newRect.height ()) ? double (targetHeight) / double (newRect.height ()) : 1); + altHat.scale( + (targetWidth > 0 + && targetWidth != newRect.width()) ? double(targetWidth) / double(newRect.width()) : 1, + (targetHeight > 0 + && targetHeight + != newRect.height()) ? double(targetHeight) / double(newRect.height()) : 1); QTransform correctMatrix = scaleMatrix * transformMatrix; - qCDebug(kpLogPixmapfx) << "\tsupposedlyWrongMatrix: m11=" << wrongMatrix.m11 () // <<<---- this is the correct matrix??? - << " m12=" << wrongMatrix.m12 () - << " m21=" << wrongMatrix.m21 () - << " m22=" << wrongMatrix.m22 () - << " dx=" << wrongMatrix.dx () - << " dy=" << wrongMatrix.dy () - << " rect=" << wrongMatrix.mapRect (pm.rect ()) - << "\n" - << "\ti_used_to_use_thisMatrix: m11=" << oldHat.m11 () - << " m12=" << oldHat.m12 () - << " m21=" << oldHat.m21 () - << " m22=" << oldHat.m22 () - << " dx=" << oldHat.dx () - << " dy=" << oldHat.dy () - << " rect=" << oldHat.mapRect (pm.rect ()) - << "\n" - << "\tabove but scaled at the same time: m11=" << altHat.m11 () - << " m12=" << altHat.m12 () - << " m21=" << altHat.m21 () - << " m22=" << altHat.m22 () - << " dx=" << altHat.dx () - << " dy=" << altHat.dy () - << " rect=" << altHat.mapRect (pm.rect ()) - << "\n" - << "\tsupposedlyCorrectMatrix: m11=" << correctMatrix.m11 () - << " m12=" << correctMatrix.m12 () - << " m21=" << correctMatrix.m21 () - << " m22=" << correctMatrix.m22 () - << " dx=" << correctMatrix.dx () - << " dy=" << correctMatrix.dy () - << " rect=" << correctMatrix.mapRect (pm.rect ()); + qCDebug(kpLogPixmapfx) << "\tsupposedlyWrongMatrix: m11=" << wrongMatrix.m11() // <<<---- this is the correct matrix??? + << " m12=" << wrongMatrix.m12() + << " m21=" << wrongMatrix.m21() + << " m22=" << wrongMatrix.m22() + << " dx=" << wrongMatrix.dx() + << " dy=" << wrongMatrix.dy() + << " rect=" << wrongMatrix.mapRect(pm.rect()) + << "\n" + << "\ti_used_to_use_thisMatrix: m11=" << oldHat.m11() + << " m12=" << oldHat.m12() + << " m21=" << oldHat.m21() + << " m22=" << oldHat.m22() + << " dx=" << oldHat.dx() + << " dy=" << oldHat.dy() + << " rect=" << oldHat.mapRect(pm.rect()) + << "\n" + << "\tabove but scaled at the same time: m11=" << altHat.m11() + << " m12=" << altHat.m12() + << " m21=" << altHat.m21() + << " m22=" << altHat.m22() + << " dx=" << altHat.dx() + << " dy=" << altHat.dy() + << " rect=" << altHat.mapRect(pm.rect()) + << "\n" + << "\tsupposedlyCorrectMatrix: m11=" << correctMatrix.m11() + << " m12=" << correctMatrix.m12() + << " m21=" << correctMatrix.m21() + << " m22=" << correctMatrix.m22() + << " dx=" << correctMatrix.dx() + << " dy=" << correctMatrix.dy() + << " rect=" << correctMatrix.mapRect(pm.rect()); #endif transformMatrix = transformMatrix * scaleMatrix; - newRect = transformMatrix.mapRect (pm.rect ()); + newRect = transformMatrix.mapRect(pm.rect()); #if DEBUG_KP_PIXMAP_FX && 1 qCDebug(kpLogPixmapfx) << "\tnewRect after targetWidth,targetHeight adjust=" << newRect; #endif } - - ::MatrixDebug (QStringLiteral("TransformPixmap(): before trueMatrix"), transformMatrix, - pm.width (), pm.height ()); + ::MatrixDebug(QStringLiteral("TransformPixmap(): before trueMatrix"), transformMatrix, + pm.width(), pm.height()); #if DEBUG_KP_PIXMAP_FX && 1 QMatrix oldMatrix = transformMatrix; #endif @@ -391,67 +383,62 @@ // Also, if you skew a rectangular selection, the skewed selection // border does not line up with the skewed image data. // TODO: do we need to pass through this new matrix? - transformMatrix = ::TrueMatrix (transformMatrix, - pm.width (), pm.height ()); + transformMatrix = ::TrueMatrix(transformMatrix, + pm.width(), pm.height()); #if DEBUG_KP_PIXMAP_FX && 1 qCDebug(kpLogPixmapfx) << "trueMatrix changed matrix?" << (oldMatrix == transformMatrix); #endif - ::MatrixDebug (QStringLiteral("TransformPixmap(): after trueMatrix"), transformMatrix, - pm.width (), pm.height ()); + ::MatrixDebug(QStringLiteral("TransformPixmap(): after trueMatrix"), transformMatrix, + pm.width(), pm.height()); + QImage newQImage(targetWidth > 0 ? targetWidth : newRect.width(), + targetHeight > 0 ? targetHeight : newRect.height(), + QImage::Format_ARGB32_Premultiplied); - QImage newQImage (targetWidth > 0 ? targetWidth : newRect.width (), - targetHeight > 0 ? targetHeight : newRect.height (), - QImage::Format_ARGB32_Premultiplied); - - if ((targetWidth > 0 && targetWidth != newRect.width ()) || - (targetHeight > 0 && targetHeight != newRect.height ())) - { + if ((targetWidth > 0 && targetWidth != newRect.width()) + || (targetHeight > 0 && targetHeight != newRect.height())) { #if DEBUG_KP_PIXMAP_FX && 1 - qCDebug(kpLogPixmapfx) << "kppixmapfx.cpp: TransformPixmap(pm.size=" << pm.size () - << ",targetWidth=" << targetWidth - << ",targetHeight=" << targetHeight - << ") newRect=" << newRect - << " (you are a victim of rounding error)"; + qCDebug(kpLogPixmapfx) << "kppixmapfx.cpp: TransformPixmap(pm.size=" << pm.size() + << ",targetWidth=" << targetWidth + << ",targetHeight=" << targetHeight + << ") newRect=" << newRect + << " (you are a victim of rounding error)"; #endif } - #if DEBUG_KP_PIXMAP_FX && 0 - qCDebug(kpLogPixmapfx) << "\ttranslate top=" << painter.xForm (QPoint (0, 0)); - qCDebug(kpLogPixmapfx) << "\tmatrix: m11=" << painter.worldMatrix ().m11 () - << " m12=" << painter.worldMatrix ().m12 () - << " m21=" << painter.worldMatrix ().m21 () - << " m22=" << painter.worldMatrix ().m22 () - << " dx=" << painter.worldMatrix ().dx () - << " dy=" << painter.worldMatrix ().dy () - << endl; + qCDebug(kpLogPixmapfx) << "\ttranslate top=" << painter.xForm(QPoint(0, 0)); + qCDebug(kpLogPixmapfx) << "\tmatrix: m11=" << painter.worldMatrix().m11() + << " m12=" << painter.worldMatrix().m12() + << " m21=" << painter.worldMatrix().m21() + << " m22=" << painter.worldMatrix().m22() + << " dx=" << painter.worldMatrix().dx() + << " dy=" << painter.worldMatrix().dy() + << endl; #endif - // Note: Do _not_ use "p.setRenderHints (QPainter::SmoothPixmapTransform);" // as the user does not want their image to get blurier every // time they e.g. rotate it (especially important for multiples // of 90 degrees but also true for every other angle). Being a // pixel-based program, we generally like to preserve RGB values // and avoid unnecessary blurs -- in the worst case, we'd rather // drop pixels, than blur. - QPainter p (&newQImage); + QPainter p(&newQImage); { // Make sure transparent pixels are drawn into the destination image. - p.setCompositionMode (QPainter::CompositionMode_Source); + p.setCompositionMode(QPainter::CompositionMode_Source); // Fill the entire new image with the background color. - if (backgroundColor.isValid ()) - { - p.fillRect (newQImage.rect (), backgroundColor.toQColor ()); + if (backgroundColor.isValid()) { + p.fillRect(newQImage.rect(), backgroundColor.toQColor()); } - p.setWorldTransform (transformMatrix); - p.drawImage (QPoint (0, 0), pm); + p.setWorldTransform(transformMatrix); + p.drawImage(QPoint(0, 0), pm); } - p.end (); + p.end(); #if DEBUG_KP_PIXMAP_FX && 1 qCDebug(kpLogPixmapfx) << "Done"; @@ -463,15 +450,13 @@ //--------------------------------------------------------------------- // public static -QTransform kpPixmapFX::skewMatrix (int width, int height, double hangle, double vangle) +QTransform kpPixmapFX::skewMatrix(int width, int height, double hangle, double vangle) { - if (std::fabs (hangle - 0) < kpPixmapFX::AngleInDegreesEpsilon && - std::fabs (vangle - 0) < kpPixmapFX::AngleInDegreesEpsilon) - { - return {}; + if (std::fabs(hangle - 0) < kpPixmapFX::AngleInDegreesEpsilon + && std::fabs(vangle - 0) < kpPixmapFX::AngleInDegreesEpsilon) { + return {}; } - /* Diagram for completeness :) * * |---------- w ----------| @@ -503,104 +488,96 @@ //QTransform matrix (1, tan (KP_DEGREES_TO_RADIANS (vangle)), tan (KP_DEGREES_TO_RADIANS (hangle)), 1, 0, 0); // I think this is clearer than above :) QTransform matrix; - matrix.shear (std::tan (qDegreesToRadians (hangle)), - std::tan (qDegreesToRadians (vangle))); + matrix.shear(std::tan(qDegreesToRadians(hangle)), + std::tan(qDegreesToRadians(vangle))); - return ::MatrixWithZeroOrigin (matrix, width, height); + return ::MatrixWithZeroOrigin(matrix, width, height); } //--------------------------------------------------------------------- // public static -QTransform kpPixmapFX::skewMatrix (const QImage &pixmap, double hangle, double vangle) +QTransform kpPixmapFX::skewMatrix(const QImage &pixmap, double hangle, double vangle) { - return kpPixmapFX::skewMatrix (pixmap.width (), pixmap.height (), hangle, vangle); + return kpPixmapFX::skewMatrix(pixmap.width(), pixmap.height(), hangle, vangle); } //--------------------------------------------------------------------- - // public static -void kpPixmapFX::skew (QImage *destPtr, double hangle, double vangle, - const kpColor &backgroundColor, - int targetWidth, int targetHeight) +void kpPixmapFX::skew(QImage *destPtr, double hangle, double vangle, const kpColor &backgroundColor, + int targetWidth, int targetHeight) { if (!destPtr) { return; } - *destPtr = kpPixmapFX::skew (*destPtr, hangle, vangle, - backgroundColor, - targetWidth, targetHeight); + *destPtr = kpPixmapFX::skew(*destPtr, hangle, vangle, + backgroundColor, + targetWidth, targetHeight); } //--------------------------------------------------------------------- // public static -QImage kpPixmapFX::skew (const QImage &pm, double hangle, double vangle, - const kpColor &backgroundColor, - int targetWidth, int targetHeight) +QImage kpPixmapFX::skew(const QImage &pm, double hangle, double vangle, + const kpColor &backgroundColor, int targetWidth, int targetHeight) { #if DEBUG_KP_PIXMAP_FX - qCDebug(kpLogPixmapfx) << "kpPixmapFX::skew() pm.width=" << pm.width () - << " pm.height=" << pm.height () - << " hangle=" << hangle - << " vangle=" << vangle - << " targetWidth=" << targetWidth - << " targetHeight=" << targetHeight; + qCDebug(kpLogPixmapfx) << "kpPixmapFX::skew() pm.width=" << pm.width() + << " pm.height=" << pm.height() + << " hangle=" << hangle + << " vangle=" << vangle + << " targetWidth=" << targetWidth + << " targetHeight=" << targetHeight; #endif - if (std::fabs (hangle - 0) < kpPixmapFX::AngleInDegreesEpsilon && - std::fabs (vangle - 0) < kpPixmapFX::AngleInDegreesEpsilon && - (targetWidth <= 0 && targetHeight <= 0)/*don't want to scale?*/) - { + if (std::fabs(hangle - 0) < kpPixmapFX::AngleInDegreesEpsilon + && std::fabs(vangle - 0) < kpPixmapFX::AngleInDegreesEpsilon + && (targetWidth <= 0 && targetHeight <= 0) /*don't want to scale?*/) { return pm; } - if (std::fabs (hangle) > 90 - kpPixmapFX::AngleInDegreesEpsilon || - std::fabs (vangle) > 90 - kpPixmapFX::AngleInDegreesEpsilon) - { - qCCritical(kpLogPixmapfx) << "kpPixmapFX::skew() passed hangle and/or vangle out of range (-90 < x < 90)"; + if (std::fabs(hangle) > 90 - kpPixmapFX::AngleInDegreesEpsilon + || std::fabs(vangle) > 90 - kpPixmapFX::AngleInDegreesEpsilon) { + qCCritical(kpLogPixmapfx) + << "kpPixmapFX::skew() passed hangle and/or vangle out of range (-90 < x < 90)"; return pm; } + QTransform matrix = skewMatrix(pm, hangle, vangle); - QTransform matrix = skewMatrix (pm, hangle, vangle); - - return ::TransformPixmap (pm, matrix, backgroundColor, targetWidth, targetHeight); + return ::TransformPixmap(pm, matrix, backgroundColor, targetWidth, targetHeight); } //--------------------------------------------------------------------- - // public static -QTransform kpPixmapFX::rotateMatrix (int width, int height, double angle) +QTransform kpPixmapFX::rotateMatrix(int width, int height, double angle) { - if (std::fabs (angle - 0) < kpPixmapFX::AngleInDegreesEpsilon) - { - return {}; + if (std::fabs(angle - 0) < kpPixmapFX::AngleInDegreesEpsilon) { + return {}; } QTransform matrix; - matrix.translate (width / 2, height / 2); - matrix.rotate (angle); + matrix.translate(width / 2, height / 2); + matrix.rotate(angle); - return ::MatrixWithZeroOrigin (matrix, width, height); + return ::MatrixWithZeroOrigin(matrix, width, height); } //--------------------------------------------------------------------- // public static -QTransform kpPixmapFX::rotateMatrix (const QImage &pixmap, double angle) +QTransform kpPixmapFX::rotateMatrix(const QImage &pixmap, double angle) { - return kpPixmapFX::rotateMatrix (pixmap.width (), pixmap.height (), angle); + return kpPixmapFX::rotateMatrix(pixmap.width(), pixmap.height(), angle); } //--------------------------------------------------------------------- - // public static -bool kpPixmapFX::isLosslessRotation (double angle) +bool kpPixmapFX::isLosslessRotation(double angle) { const double angleIn = angle; @@ -610,60 +587,54 @@ } // Remove multiples of 90 to make sure 0 <= angle <= 90 - angle -= (static_cast (angle)) / 90 * 90; + angle -= (static_cast(angle)) / 90 * 90; // "Impossible" situation? - if (angle < 0 || angle > 90) - { + if (angle < 0 || angle > 90) { qCCritical(kpLogPixmapfx) << "kpPixmapFX::isLosslessRotation(" << angleIn - << ") result=" << angle; + << ") result=" << angle; return false; // better safe than sorry } - const bool ret = (angle < kpPixmapFX::AngleInDegreesEpsilon || - 90 - angle < kpPixmapFX::AngleInDegreesEpsilon); + const bool ret = (angle < kpPixmapFX::AngleInDegreesEpsilon + || 90 - angle < kpPixmapFX::AngleInDegreesEpsilon); #if DEBUG_KP_PIXMAP_FX qCDebug(kpLogPixmapfx) << "kpPixmapFX::isLosslessRotation(" << angleIn << ")" - << " residual angle=" << angle - << " returning " << ret; + << " residual angle=" << angle + << " returning " << ret; #endif return ret; } //--------------------------------------------------------------------- - // public static -void kpPixmapFX::rotate (QImage *destPtr, double angle, - const kpColor &backgroundColor, - int targetWidth, int targetHeight) +void kpPixmapFX::rotate(QImage *destPtr, double angle, const kpColor &backgroundColor, + int targetWidth, int targetHeight) { if (!destPtr) { return; } - *destPtr = kpPixmapFX::rotate (*destPtr, angle, - backgroundColor, - targetWidth, targetHeight); + *destPtr = kpPixmapFX::rotate(*destPtr, angle, + backgroundColor, + targetWidth, targetHeight); } //--------------------------------------------------------------------- // public static -QImage kpPixmapFX::rotate (const QImage &pm, double angle, - const kpColor &backgroundColor, - int targetWidth, int targetHeight) +QImage kpPixmapFX::rotate(const QImage &pm, double angle, const kpColor &backgroundColor, + int targetWidth, int targetHeight) { - if (std::fabs (angle - 0) < kpPixmapFX::AngleInDegreesEpsilon && - (targetWidth <= 0 && targetHeight <= 0)/*don't want to scale?*/) - { + if (std::fabs(angle - 0) < kpPixmapFX::AngleInDegreesEpsilon + && (targetWidth <= 0 && targetHeight <= 0) /*don't want to scale?*/) { return pm; } + QTransform matrix = rotateMatrix(pm, angle); - QTransform matrix = rotateMatrix (pm, angle); - - return ::TransformPixmap (pm, matrix, backgroundColor, targetWidth, targetHeight); + return ::TransformPixmap(pm, matrix, backgroundColor, targetWidth, targetHeight); } //--------------------------------------------------------------------- diff --git a/scan/sanedialog.cpp b/scan/sanedialog.cpp --- a/scan/sanedialog.cpp +++ b/scan/sanedialog.cpp @@ -37,25 +37,24 @@ SaneDialog::SaneDialog(QWidget *parent) : KPageDialog(parent) { - setFaceType(static_cast (Plain)); + setFaceType(static_cast(Plain)); setWindowTitle(i18nc("@title:window", "Acquire Image")); buttonBox()->setStandardButtons(QDialogButtonBox::Close); buttonBox()->button(QDialogButtonBox::Close)->setDefault(true); - m_ksanew = new KSaneIface::KSaneWidget(this); addPage(m_ksanew, QString()); - connect (m_ksanew, &KSaneIface::KSaneWidget::imageReady, - this, &SaneDialog::imageReady); + connect(m_ksanew, &KSaneIface::KSaneWidget::imageReady, + this, &SaneDialog::imageReady); m_openDev = QString(); } bool SaneDialog::setup() { - if(!m_ksanew) { + if (!m_ksanew) { // new failed return false; } @@ -65,7 +64,7 @@ // need to select a scanner m_openDev = m_ksanew->selectDevice(nullptr); if (m_openDev.isEmpty()) { - // either no scanner was found or then cancel was pressed. + // either no scanner was found or then cancel was pressed. return false; } if (!m_ksanew->openDevice(m_openDev)) { @@ -87,7 +86,7 @@ } } - return true; + return true; } SaneDialog::~SaneDialog() @@ -110,7 +109,8 @@ void SaneDialog::imageReady(QByteArray &data, int w, int h, int bpl, int f) { /* copy the image data into img */ - QImage img = m_ksanew->toQImage(data, w, h, bpl, static_cast (f)); + QImage img + = m_ksanew->toQImage(data, w, h, bpl, static_cast(f)); emit finalImage(img, nextId()); } diff --git a/tools/flow/kpToolBrush.h b/tools/flow/kpToolBrush.h --- a/tools/flow/kpToolBrush.h +++ b/tools/flow/kpToolBrush.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,25 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_BRUSH_H #define KP_TOOL_BRUSH_H - #include "kpToolFlowPixmapBase.h" - // Brush = draws pixmaps, "interpolates" by "sweeping" pixmaps along a line (interesting brushes) class kpToolBrush : public kpToolFlowPixmapBase { -Q_OBJECT + Q_OBJECT public: kpToolBrush (kpToolEnvironment *environ, QObject *parent); protected: - QString haventBegunDrawUserMessage () const override; - bool haveDiverseBrushes () const override { return true; } + QString haventBegunDrawUserMessage() const override; + bool haveDiverseBrushes() const override + { + return true; + } }; - #endif // KP_TOOL_BRUSH_H diff --git a/tools/flow/kpToolBrush.cpp b/tools/flow/kpToolBrush.cpp --- a/tools/flow/kpToolBrush.cpp +++ b/tools/flow/kpToolBrush.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -32,25 +31,23 @@ //--------------------------------------------------------------------- kpToolBrush::kpToolBrush (kpToolEnvironment *environ, QObject *parent) - : kpToolFlowPixmapBase (i18n ("Brush"), - i18n ("Draw using brushes of different shapes and sizes"), - Qt::Key_B, - environ, parent, QStringLiteral("tool_brush")) + : kpToolFlowPixmapBase(i18n("Brush"), + i18n("Draw using brushes of different shapes and sizes"), + Qt::Key_B, + environ, parent, QStringLiteral("tool_brush")) { } //--------------------------------------------------------------------- // protected virtual [base kpToolFlowBase] -QString kpToolBrush::haventBegunDrawUserMessage () const +QString kpToolBrush::haventBegunDrawUserMessage() const { - return i18n ("Click to draw dots or drag to draw strokes."); + return i18n("Click to draw dots or drag to draw strokes."); } //--------------------------------------------------------------------- // See the our corresponding .h for brush selection. // Logic is in kpToolFlowPixmapBase. - - diff --git a/tools/flow/kpToolColorEraser.h b/tools/flow/kpToolColorEraser.h --- a/tools/flow/kpToolColorEraser.h +++ b/tools/flow/kpToolColorEraser.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,41 +24,40 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_COLOR_ERASER_H #define KP_TOOL_COLOR_ERASER_H - #include "kpToolFlowBase.h" - // Color Eraser = Brush that replaces/washes the foreground color with the background color class kpToolColorEraser : public kpToolFlowBase { -Q_OBJECT + Q_OBJECT public: kpToolColorEraser (kpToolEnvironment *environ, QObject *parent); ~kpToolColorEraser () override; - public: - void globalDraw () override; - + void globalDraw() override; protected: - QString haventBegunDrawUserMessage () const override; + QString haventBegunDrawUserMessage() const override; - bool drawShouldProceed (const QPoint &thisPoint, - const QPoint &lastPoint, - const QRect &normalizedRect) override; + bool drawShouldProceed(const QPoint &thisPoint, const QPoint &lastPoint, + const QRect &normalizedRect) override; - bool haveSquareBrushes () const override { return true; } - bool colorsAreSwapped () const override { return true; } + bool haveSquareBrushes() const override + { + return true; + } + bool colorsAreSwapped() const override + { + return true; + } - QRect drawLine (const QPoint &thisPoint, const QPoint &lastPoint) override; + QRect drawLine(const QPoint &thisPoint, const QPoint &lastPoint) override; }; - #endif // KP_TOOL_COLOR_ERASER_H diff --git a/tools/flow/kpToolColorEraser.cpp b/tools/flow/kpToolColorEraser.cpp --- a/tools/flow/kpToolColorEraser.cpp +++ b/tools/flow/kpToolColorEraser.cpp @@ -24,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_COLOR_ERASER 0 #include "kpToolColorEraser.h" @@ -46,11 +45,11 @@ //-------------------------------------------------------------------------------- kpToolColorEraser::kpToolColorEraser (kpToolEnvironment *environ, QObject *parent) - : kpToolFlowBase (i18n ("Color Eraser"), - i18n ("Replaces pixels of the foreground color with the background color"), - Qt::Key_O, - environ, parent, - QStringLiteral("tool_color_eraser")) + : kpToolFlowBase(i18n("Color Eraser"), + i18n("Replaces pixels of the foreground color with the background color"), + Qt::Key_O, + environ, parent, + QStringLiteral("tool_color_eraser")) { } @@ -61,100 +60,95 @@ //-------------------------------------------------------------------------------- // public virtual [base kpTool] -void kpToolColorEraser::globalDraw () +void kpToolColorEraser::globalDraw() { #if DEBUG_KP_TOOL_COLOR_ERASER qCDebug(kpLogTools) << "kpToolColorEraser::globalDraw()"; #endif - if (!drawShouldProceed (QPoint ()/*unused*/, QPoint ()/*unused*/, QRect ()/*unused*/)) { + if (!drawShouldProceed(QPoint() /*unused*/, QPoint() /*unused*/, QRect() /*unused*/)) { return; } - QApplication::setOverrideCursor (Qt::WaitCursor); - - environ ()->flashColorSimilarityToolBarItem (); + QApplication::setOverrideCursor(Qt::WaitCursor); - kpToolFlowCommand *cmd = new kpToolFlowCommand ( - i18n ("Color Eraser"), environ ()->commandEnvironment ()); + environ()->flashColorSimilarityToolBarItem(); - const QRect dirtyRect = kpPainter::washRect (document ()->imagePointer (), - 0, 0, document ()->width (), document ()->height (), - backgroundColor ()/*color to draw in*/, - foregroundColor ()/*color to replace*/, - processedColorSimilarity ()); + kpToolFlowCommand *cmd = new kpToolFlowCommand( + i18n("Color Eraser"), environ()->commandEnvironment()); - if (!dirtyRect.isEmpty ()) - { - document ()->slotContentsChanged (dirtyRect); + const QRect dirtyRect = kpPainter::washRect(document()->imagePointer(), + 0, 0, document()->width(), document()->height(), + backgroundColor() /*color to draw in*/, + foregroundColor() /*color to replace*/, + processedColorSimilarity()); + if (!dirtyRect.isEmpty()) { + document()->slotContentsChanged(dirtyRect); - cmd->updateBoundingRect (dirtyRect); - cmd->finalize (); + cmd->updateBoundingRect(dirtyRect); + cmd->finalize(); - commandHistory ()->addCommand (cmd, false /* don't exec */); + commandHistory()->addCommand(cmd, false /* don't exec */); // don't delete - it's up to the commandHistory cmd = nullptr; - } - else - { + } else { #if DEBUG_KP_TOOL_COLOR_ERASER qCDebug(kpLogTools) << "\tisNOP"; #endif delete cmd; cmd = nullptr; } - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } //-------------------------------------------------------------------------------- -QString kpToolColorEraser::haventBegunDrawUserMessage () const +QString kpToolColorEraser::haventBegunDrawUserMessage() const { - return i18n ("Click or drag to erase pixels of the foreground color."); + return i18n("Click or drag to erase pixels of the foreground color."); } //-------------------------------------------------------------------------------- -bool kpToolColorEraser::drawShouldProceed (const QPoint & /*thisPoint*/, - const QPoint & /*lastPoint*/, - const QRect & /*normalizedRect*/) +bool kpToolColorEraser::drawShouldProceed(const QPoint & /*thisPoint*/, + const QPoint & /*lastPoint*/, + const QRect & /*normalizedRect*/) { - return !(foregroundColor () == backgroundColor () && - processedColorSimilarity () == 0); + return !(foregroundColor() == backgroundColor() + && processedColorSimilarity() == 0); } //-------------------------------------------------------------------------------- -QRect kpToolColorEraser::drawLine (const QPoint &thisPoint, const QPoint &lastPoint) +QRect kpToolColorEraser::drawLine(const QPoint &thisPoint, const QPoint &lastPoint) { #if DEBUG_KP_TOOL_COLOR_ERASER qCDebug(kpLogTools) << "kpToolColorEraser::drawLine(thisPoint=" << thisPoint - << ",lastPoint=" << lastPoint << ")"; + << ",lastPoint=" << lastPoint << ")"; #endif - environ ()->flashColorSimilarityToolBarItem (); + environ()->flashColorSimilarityToolBarItem(); - const QRect dirtyRect = kpPainter::washLine (document ()->imagePointer (), - lastPoint.x (), lastPoint.y (), - thisPoint.x (), thisPoint.y (), - color (mouseButton ())/*color to draw in*/, - brushWidth (), brushHeight (), - color (1 - mouseButton ())/*color to replace*/, - processedColorSimilarity ()); + const QRect dirtyRect = kpPainter::washLine(document()->imagePointer(), + lastPoint.x(), lastPoint.y(), + thisPoint.x(), thisPoint.y(), + color(mouseButton()) /*color to draw in*/, + brushWidth(), brushHeight(), + color(1 - mouseButton()) /*color to replace*/, + processedColorSimilarity()); #if DEBUG_KP_TOOL_COLOR_ERASER qCDebug(kpLogTools) << "\tdirtyRect=" << dirtyRect; #endif - if (!dirtyRect.isEmpty ()) - { - document ()->slotContentsChanged (dirtyRect); + if (!dirtyRect.isEmpty()) { + document()->slotContentsChanged(dirtyRect); return dirtyRect; } - return {}; + return {}; } //-------------------------------------------------------------------------------- diff --git a/tools/flow/kpToolEraser.h b/tools/flow/kpToolEraser.h --- a/tools/flow/kpToolEraser.h +++ b/tools/flow/kpToolEraser.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,31 +24,33 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_ERASER_H #define KP_TOOL_ERASER_H - #include "kpToolFlowPixmapBase.h" - // Eraser = Brush but with foreground & background colors swapped (a few square brushes) class kpToolEraser : public kpToolFlowPixmapBase { -Q_OBJECT + Q_OBJECT public: kpToolEraser (kpToolEnvironment *environ, QObject *parent); - void globalDraw () override; - + void globalDraw() override; protected: - QString haventBegunDrawUserMessage () const override; + QString haventBegunDrawUserMessage() const override; - bool haveSquareBrushes () const override { return true; } - bool colorsAreSwapped () const override { return true; } -}; + bool haveSquareBrushes() const override + { + return true; + } + bool colorsAreSwapped() const override + { + return true; + } +}; #endif // KP_TOOL_ERASER_H diff --git a/tools/flow/kpToolEraser.cpp b/tools/flow/kpToolEraser.cpp --- a/tools/flow/kpToolEraser.cpp +++ b/tools/flow/kpToolEraser.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_ERASER 0 #include "kpToolEraser.h" @@ -39,41 +37,39 @@ //--------------------------------------------------------------------- kpToolEraser::kpToolEraser (kpToolEnvironment *environ, QObject *parent) - : kpToolFlowPixmapBase (i18n ("Eraser"), - i18n ("Lets you rub out mistakes"), - Qt::Key_A, - environ, parent, QStringLiteral("tool_eraser")) + : kpToolFlowPixmapBase(i18n("Eraser"), + i18n("Lets you rub out mistakes"), + Qt::Key_A, + environ, parent, QStringLiteral("tool_eraser")) { } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpToolEraser::globalDraw () +void kpToolEraser::globalDraw() { #if DEBUG_KP_TOOL_ERASER qCDebug(kpLogTools) << "kpToolEraser::globalDraw()"; #endif - commandHistory ()->addCommand ( - new kpEffectClearCommand ( - false/*act on doc, not sel*/, - backgroundColor (), - environ ()->commandEnvironment ())); + commandHistory()->addCommand( + new kpEffectClearCommand( + false /*act on doc, not sel*/, + backgroundColor(), + environ()->commandEnvironment())); } //--------------------------------------------------------------------- // protected virtual [base kpToolFlowBase] -QString kpToolEraser::haventBegunDrawUserMessage () const +QString kpToolEraser::haventBegunDrawUserMessage() const { - return i18n ("Click or drag to erase."); + return i18n("Click or drag to erase."); } //--------------------------------------------------------------------- // See the our corresponding .h for brush selection. // Logic is in kpToolFlowPixmapBase. - - diff --git a/tools/flow/kpToolFlowBase.h b/tools/flow/kpToolFlowBase.h --- a/tools/flow/kpToolFlowBase.h +++ b/tools/flow/kpToolFlowBase.h @@ -1,4 +1,3 @@ - /* Copyright(c) 2003-2007 Clarence Dang All rights reserved. @@ -25,31 +24,26 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_FLOW_BASE_H #define KP_TOOL_FLOW_BASE_H - #include #include "layers/tempImage/kpTempImage.h" #include "tools/kpTool.h" - class QPoint; class QString; class kpColor; class kpToolFlowCommand; - class kpToolFlowBase : public kpTool { - Q_OBJECT + Q_OBJECT - public: - kpToolFlowBase(const QString &text, const QString &description, - int key, +public: + kpToolFlowBase(const QString &text, const QString &description, int key, kpToolEnvironment *environ, QObject *parent, const QString &name); ~kpToolFlowBase() override; @@ -59,8 +53,7 @@ // up being the midpoint of the returned rectangle(subject to integer // precision). static QRect hotRectForMousePointAndBrushWidthHeight( - const QPoint &mousePoint, - int brushWidth, int brushHeight); + const QPoint &mousePoint, int brushWidth, int brushHeight); void begin() override; void end() override; @@ -73,23 +66,40 @@ virtual QRect drawPoint(const QPoint &point); virtual QRect drawLine(const QPoint &thisPoint, const QPoint &lastPoint) = 0; - virtual bool drawShouldProceed(const QPoint & /*thisPoint*/, const QPoint & /*lastPoint*/, const QRect & /*normalizedRect*/) { return true; } - void draw(const QPoint &thisPoint, const QPoint &lastPoint, const QRect &normalizedRect) override; + virtual bool drawShouldProceed(const QPoint & /*thisPoint*/, const QPoint & /*lastPoint*/, + const QRect & /*normalizedRect*/) + { + return true; + } + + void draw(const QPoint &thisPoint, const QPoint &lastPoint, + const QRect &normalizedRect) override; void cancelShape() override; void releasedAllButtons() override; void endDraw(const QPoint &, const QRect &) override; - protected: +protected: virtual QString haventBegunDrawUserMessage() const = 0; - virtual bool haveSquareBrushes() const { return false; } - virtual bool haveDiverseBrushes() const { return false; } + virtual bool haveSquareBrushes() const + { + return false; + } + + virtual bool haveDiverseBrushes() const + { + return false; + } + bool haveAnyBrushes() const { - return(haveSquareBrushes() || haveDiverseBrushes()); + return haveSquareBrushes() || haveDiverseBrushes(); } - virtual bool colorsAreSwapped() const { return false; } + virtual bool colorsAreSwapped() const + { + return false; + } kpTempImage::UserFunctionType brushDrawFunction() const; void *brushDrawFunctionData() const; @@ -103,18 +113,17 @@ virtual kpColor color(int which); QRect hotRect() const; - protected slots: +protected slots: void updateBrushAndCursor(); void slotForegroundColorChanged(const kpColor &col) override; void slotBackgroundColorChanged(const kpColor &col) override; - private: +private: void clearBrushCursorData(); - private: +private: struct kpToolFlowBasePrivate *d; }; - #endif // KP_TOOL_FLOW_BASE_H diff --git a/tools/flow/kpToolFlowBase.cpp b/tools/flow/kpToolFlowBase.cpp --- a/tools/flow/kpToolFlowBase.cpp +++ b/tools/flow/kpToolFlowBase.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_FLOW_BASE 0 #include "kpToolFlowBase.h" @@ -61,45 +59,42 @@ kpToolWidgetBrush *toolWidgetBrush{}; kpToolWidgetEraserSize *toolWidgetEraserSize{}; - // // Cursor and Brush Data // (must be zero if unused) // - kpTempImage::UserFunctionType brushDrawFunc{}, cursorDrawFunc{}; + kpTempImage::UserFunctionType brushDrawFunc{}, cursorDrawFunc{}; - // Can't use union since package types contain fields requiring - // constructors. - kpToolWidgetBrush::DrawPackage brushDrawPackageForMouseButton [2]; - kpToolWidgetEraserSize::DrawPackage eraserDrawPackageForMouseButton [2]; + // Can't use union since package types contain fields requiring + // constructors. + kpToolWidgetBrush::DrawPackage brushDrawPackageForMouseButton [2]; + kpToolWidgetEraserSize::DrawPackage eraserDrawPackageForMouseButton [2]; - // Each element points to one of the above (both elements from the same - // array). - void *drawPackageForMouseButton [2]{}; + // Each element points to one of the above (both elements from the same + // array). + void *drawPackageForMouseButton [2]{}; - int brushWidth{}, brushHeight{}; - int cursorWidth{}, cursorHeight{}; - - bool brushIsDiagonalLine{}; + int brushWidth{}, brushHeight{}; + int cursorWidth{}, cursorHeight{}; + bool brushIsDiagonalLine{}; kpToolFlowCommand *currentCommand{}; }; //--------------------------------------------------------------------- -kpToolFlowBase::kpToolFlowBase (const QString &text, const QString &description, - int key, - kpToolEnvironment *environ, QObject *parent, const QString &name) +kpToolFlowBase::kpToolFlowBase (const QString &text, const QString &description, int key, + kpToolEnvironment *environ, QObject *parent, const QString &name) - : kpTool (text, description, key, environ, parent, name), - d (new kpToolFlowBasePrivate ()) + : kpTool(text, description, key, environ, parent, name) + , d(new kpToolFlowBasePrivate()) { d->toolWidgetBrush = nullptr; d->toolWidgetEraserSize = nullptr; - clearBrushCursorData (); + clearBrushCursorData(); d->currentCommand = nullptr; } @@ -114,20 +109,20 @@ //--------------------------------------------------------------------- // private -void kpToolFlowBase::clearBrushCursorData () +void kpToolFlowBase::clearBrushCursorData() { d->brushDrawFunc = d->cursorDrawFunc = nullptr; - memset (&d->brushDrawPackageForMouseButton, - 0, - sizeof (d->brushDrawPackageForMouseButton)); - memset (&d->eraserDrawPackageForMouseButton, - 0, - sizeof (d->eraserDrawPackageForMouseButton)); + memset(&d->brushDrawPackageForMouseButton, + 0, + sizeof(d->brushDrawPackageForMouseButton)); + memset(&d->eraserDrawPackageForMouseButton, + 0, + sizeof(d->eraserDrawPackageForMouseButton)); - memset (&d->drawPackageForMouseButton, - 0, - sizeof (d->drawPackageForMouseButton)); + memset(&d->drawPackageForMouseButton, + 0, + sizeof(d->drawPackageForMouseButton)); d->brushWidth = d->brushHeight = 0; d->cursorWidth = d->cursorHeight = 0; @@ -138,334 +133,318 @@ //--------------------------------------------------------------------- // virtual -void kpToolFlowBase::begin () +void kpToolFlowBase::begin() { - kpToolToolBar *tb = toolToolBar (); - Q_ASSERT (tb); + kpToolToolBar *tb = toolToolBar(); + Q_ASSERT(tb); // TODO: Bad smell. Mutually exclusive. Use inheritance. - if (haveSquareBrushes ()) - { - d->toolWidgetEraserSize = tb->toolWidgetEraserSize (); - connect (d->toolWidgetEraserSize, &kpToolWidgetEraserSize::eraserSizeChanged, - this, &kpToolFlowBase::updateBrushAndCursor); - d->toolWidgetEraserSize->show (); + if (haveSquareBrushes()) { + d->toolWidgetEraserSize = tb->toolWidgetEraserSize(); + connect(d->toolWidgetEraserSize, &kpToolWidgetEraserSize::eraserSizeChanged, + this, &kpToolFlowBase::updateBrushAndCursor); + d->toolWidgetEraserSize->show(); - updateBrushAndCursor (); + updateBrushAndCursor(); - viewManager ()->setCursor (kpCursorProvider::lightCross ()); - } - else if (haveDiverseBrushes ()) - { - d->toolWidgetBrush = tb->toolWidgetBrush (); - connect (d->toolWidgetBrush, &kpToolWidgetBrush::brushChanged, - this, &kpToolFlowBase::updateBrushAndCursor); - d->toolWidgetBrush->show (); + viewManager()->setCursor(kpCursorProvider::lightCross()); + } else if (haveDiverseBrushes()) { + d->toolWidgetBrush = tb->toolWidgetBrush(); + connect(d->toolWidgetBrush, &kpToolWidgetBrush::brushChanged, + this, &kpToolFlowBase::updateBrushAndCursor); + d->toolWidgetBrush->show(); - updateBrushAndCursor (); + updateBrushAndCursor(); - viewManager ()->setCursor (kpCursorProvider::lightCross ()); + viewManager()->setCursor(kpCursorProvider::lightCross()); } - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- // virtual -void kpToolFlowBase::end () +void kpToolFlowBase::end() { - if (d->toolWidgetEraserSize) - { - disconnect (d->toolWidgetEraserSize, &kpToolWidgetEraserSize::eraserSizeChanged, - this, &kpToolFlowBase::updateBrushAndCursor); + if (d->toolWidgetEraserSize) { + disconnect(d->toolWidgetEraserSize, &kpToolWidgetEraserSize::eraserSizeChanged, + this, &kpToolFlowBase::updateBrushAndCursor); d->toolWidgetEraserSize = nullptr; - } - else if (d->toolWidgetBrush) - { - disconnect (d->toolWidgetBrush, &kpToolWidgetBrush::brushChanged, - this, &kpToolFlowBase::updateBrushAndCursor); + } else if (d->toolWidgetBrush) { + disconnect(d->toolWidgetBrush, &kpToolWidgetBrush::brushChanged, + this, &kpToolFlowBase::updateBrushAndCursor); d->toolWidgetBrush = nullptr; } - kpViewManager *vm = viewManager (); - Q_ASSERT (vm); + kpViewManager *vm = viewManager(); + Q_ASSERT(vm); - if (vm->tempImage () && vm->tempImage ()->isBrush ()) { - vm->invalidateTempImage (); + if (vm->tempImage() && vm->tempImage()->isBrush()) { + vm->invalidateTempImage(); } - if (haveAnyBrushes ()) { - vm->unsetCursor (); + if (haveAnyBrushes()) { + vm->unsetCursor(); } - clearBrushCursorData (); + clearBrushCursorData(); } //--------------------------------------------------------------------- // virtual -void kpToolFlowBase::beginDraw () +void kpToolFlowBase::beginDraw() { - d->currentCommand = new kpToolFlowCommand (text (), environ ()->commandEnvironment ()); + d->currentCommand = new kpToolFlowCommand(text(), environ()->commandEnvironment()); // We normally show the brush cursor in the foreground colour but if the // user starts drawing in the background color, we don't want to leave // the brush cursor in the foreground colour -- just hide it in all cases // to avoid confusion. - viewManager ()->invalidateTempImage (); + viewManager()->invalidateTempImage(); - setUserMessage (cancelUserMessage ()); + setUserMessage(cancelUserMessage()); } //--------------------------------------------------------------------- // virtual -void kpToolFlowBase::hover (const QPoint &point) +void kpToolFlowBase::hover(const QPoint &point) { #if DEBUG_KP_TOOL_FLOW_BASE && 0 qCDebug(kpLogTools) << "kpToolFlowBase::hover(" << point << ")" - << " hasBegun=" << hasBegun () - << " hasBegunDraw=" << hasBegunDraw () - << " cursorPixmap.isNull=" << m_cursorPixmap.isNull () - << endl; + << " hasBegun=" << hasBegun() + << " hasBegunDraw=" << hasBegunDraw() + << " cursorPixmap.isNull=" << m_cursorPixmap.isNull() + << endl; #endif - if (point != KP_INVALID_POINT && d->cursorDrawFunc) - { - viewManager ()->setFastUpdates (); + if (point != KP_INVALID_POINT && d->cursorDrawFunc) { + viewManager()->setFastUpdates(); - viewManager ()->setTempImage ( - kpTempImage (true/*brush*/, - hotRect ().topLeft (), - d->cursorDrawFunc, d->drawPackageForMouseButton [0/*left button*/], - d->cursorWidth, d->cursorHeight)); + viewManager()->setTempImage( + kpTempImage(true /*brush*/, + hotRect().topLeft(), + d->cursorDrawFunc, d->drawPackageForMouseButton [0 /*left button*/], + d->cursorWidth, d->cursorHeight)); - viewManager ()->restoreFastUpdates (); + viewManager()->restoreFastUpdates(); } - setUserShapePoints (point); + setUserShapePoints(point); } //--------------------------------------------------------------------- // virtual -QRect kpToolFlowBase::drawPoint (const QPoint &point) +QRect kpToolFlowBase::drawPoint(const QPoint &point) { - return drawLine (point, point); + return drawLine(point, point); } //--------------------------------------------------------------------- // virtual -void kpToolFlowBase::draw (const QPoint &thisPoint, const QPoint &lastPoint, const QRect &normalizedRect) +void kpToolFlowBase::draw(const QPoint &thisPoint, const QPoint &lastPoint, + const QRect &normalizedRect) { - if (!/*virtual*/drawShouldProceed (thisPoint, lastPoint, normalizedRect)) { + if (!/*virtual*/ drawShouldProceed(thisPoint, lastPoint, normalizedRect)) { return; } // sync: remember to restoreFastUpdates() in all exit paths - viewManager ()->setFastUpdates (); + viewManager()->setFastUpdates(); QRect dirtyRect; // TODO: I'm beginning to wonder this drawPoint() "optimization" actually // optimises. Is it worth the complexity? Hence drawPoint() impl above. - if (d->brushIsDiagonalLine ? - currentPointCardinallyNextToLast () : - currentPointNextToLast ()) - { - dirtyRect = drawPoint (thisPoint); + if (d->brushIsDiagonalLine + ? currentPointCardinallyNextToLast() + : currentPointNextToLast()) { + dirtyRect = drawPoint(thisPoint); } // in reality, the system is too slow to give us all the MouseMove events // so we "interpolate" the missing points :) - else - { - dirtyRect = drawLine (thisPoint, lastPoint); + else { + dirtyRect = drawLine(thisPoint, lastPoint); } - d->currentCommand->updateBoundingRect (dirtyRect); + d->currentCommand->updateBoundingRect(dirtyRect); - viewManager ()->restoreFastUpdates (); - setUserShapePoints (thisPoint); + viewManager()->restoreFastUpdates(); + setUserShapePoints(thisPoint); } //--------------------------------------------------------------------- // virtual -void kpToolFlowBase::cancelShape () +void kpToolFlowBase::cancelShape() { - d->currentCommand->finalize (); - d->currentCommand->cancel (); + d->currentCommand->finalize(); + d->currentCommand->cancel(); delete d->currentCommand; d->currentCommand = nullptr; - updateBrushAndCursor (); + updateBrushAndCursor(); - setUserMessage (i18n ("Let go of all the mouse buttons.")); + setUserMessage(i18n("Let go of all the mouse buttons.")); } //--------------------------------------------------------------------- -void kpToolFlowBase::releasedAllButtons () +void kpToolFlowBase::releasedAllButtons() { - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- // virtual -void kpToolFlowBase::endDraw (const QPoint &, const QRect &) +void kpToolFlowBase::endDraw(const QPoint &, const QRect &) { - d->currentCommand->finalize (); - environ ()->commandHistory ()->addCommand (d->currentCommand, - false/*don't exec*/); + d->currentCommand->finalize(); + environ()->commandHistory()->addCommand(d->currentCommand, + false /*don't exec*/); // don't delete - it's up to the commandHistory d->currentCommand = nullptr; - updateBrushAndCursor (); + updateBrushAndCursor(); - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- // TODO: maybe the base should be virtual? -kpColor kpToolFlowBase::color (int which) +kpColor kpToolFlowBase::color(int which) { #if DEBUG_KP_TOOL_FLOW_BASE && 0 qCDebug(kpLogTools) << "kpToolFlowBase::color (" << which << ")"; #endif // Pen & Brush - if (!colorsAreSwapped ()) { - return kpTool::color (which); + if (!colorsAreSwapped()) { + return kpTool::color(which); } // only the (Color) Eraser uses the opposite color - return kpTool::color (which ? 0 : 1); // don't trust !0 == 1 + return kpTool::color(which ? 0 : 1); // don't trust !0 == 1 } //--------------------------------------------------------------------- // protected -kpTempImage::UserFunctionType kpToolFlowBase::brushDrawFunction () const +kpTempImage::UserFunctionType kpToolFlowBase::brushDrawFunction() const { return d->brushDrawFunc; } //--------------------------------------------------------------------- // protected -void *kpToolFlowBase::brushDrawFunctionData () const +void *kpToolFlowBase::brushDrawFunctionData() const { - return d->drawPackageForMouseButton [mouseButton ()]; + return d->drawPackageForMouseButton [mouseButton()]; } - // protected -int kpToolFlowBase::brushWidth () const +int kpToolFlowBase::brushWidth() const { return d->brushWidth; } // protected -int kpToolFlowBase::brushHeight () const +int kpToolFlowBase::brushHeight() const { return d->brushHeight; } // protected -bool kpToolFlowBase::brushIsDiagonalLine () const +bool kpToolFlowBase::brushIsDiagonalLine() const { return d->brushIsDiagonalLine; } - // protected -kpToolFlowCommand *kpToolFlowBase::currentCommand () const +kpToolFlowCommand *kpToolFlowBase::currentCommand() const { return d->currentCommand; } //--------------------------------------------------------------------- // protected slot -void kpToolFlowBase::updateBrushAndCursor () +void kpToolFlowBase::updateBrushAndCursor() { #if DEBUG_KP_TOOL_FLOW_BASE && 1 qCDebug(kpLogTools) << "kpToolFlowBase::updateBrushAndCursor()"; #endif - if (haveSquareBrushes ()) - { - d->brushDrawFunc = d->toolWidgetEraserSize->drawFunction (); - d->cursorDrawFunc = d->toolWidgetEraserSize->drawCursorFunction (); + if (haveSquareBrushes()) { + d->brushDrawFunc = d->toolWidgetEraserSize->drawFunction(); + d->cursorDrawFunc = d->toolWidgetEraserSize->drawCursorFunction(); - for (int i = 0; i < 2; i++) - { - d->drawPackageForMouseButton [i] = - &(d->eraserDrawPackageForMouseButton [i] = - d->toolWidgetEraserSize->drawFunctionData (color (i))); + for (int i = 0; i < 2; i++) { + d->drawPackageForMouseButton [i] + = &(d->eraserDrawPackageForMouseButton [i] + = d->toolWidgetEraserSize->drawFunctionData(color(i))); } - d->brushWidth = d->brushHeight = - d->cursorWidth = d->cursorHeight = - d->toolWidgetEraserSize->eraserSize (); + d->brushWidth = d->brushHeight + = d->cursorWidth = d->cursorHeight + = d->toolWidgetEraserSize->eraserSize(); d->brushIsDiagonalLine = false; - } - else if (haveDiverseBrushes ()) - { - d->brushDrawFunc = d->cursorDrawFunc = d->toolWidgetBrush->drawFunction (); - - for (int i = 0; i < 2; i++) - { - d->drawPackageForMouseButton [i] = - &(d->brushDrawPackageForMouseButton [i] = - d->toolWidgetBrush->drawFunctionData (color (i))); + } else if (haveDiverseBrushes()) { + d->brushDrawFunc = d->cursorDrawFunc = d->toolWidgetBrush->drawFunction(); + + for (int i = 0; i < 2; i++) { + d->drawPackageForMouseButton [i] + = &(d->brushDrawPackageForMouseButton [i] + = d->toolWidgetBrush->drawFunctionData(color(i))); } - d->brushWidth = d->brushHeight = - d->cursorWidth = d->cursorHeight = - d->toolWidgetBrush->brushSize (); + d->brushWidth = d->brushHeight + = d->cursorWidth = d->cursorHeight + = d->toolWidgetBrush->brushSize(); - d->brushIsDiagonalLine = d->toolWidgetBrush->brushIsDiagonalLine (); + d->brushIsDiagonalLine = d->toolWidgetBrush->brushIsDiagonalLine(); } - hover (hasBegun () ? currentPoint () : calculateCurrentPoint ()); + hover(hasBegun() ? currentPoint() : calculateCurrentPoint()); } //--------------------------------------------------------------------- // virtual private slot -void kpToolFlowBase::slotForegroundColorChanged (const kpColor & /*col*/) +void kpToolFlowBase::slotForegroundColorChanged(const kpColor & /*col*/) { #if DEBUG_KP_TOOL_FLOW_BASE qCDebug(kpLogTools) << "kpToolFlowBase::slotForegroundColorChanged()"; #endif - updateBrushAndCursor (); + updateBrushAndCursor(); } //--------------------------------------------------------------------- // virtual private slot -void kpToolFlowBase::slotBackgroundColorChanged (const kpColor & /*col*/) +void kpToolFlowBase::slotBackgroundColorChanged(const kpColor & /*col*/) { #if DEBUG_KP_TOOL_FLOW_BASE qCDebug(kpLogTools) << "kpToolFlowBase::slotBackgroundColorChanged()"; #endif - updateBrushAndCursor (); + updateBrushAndCursor(); } //--------------------------------------------------------------------- // public static -QRect kpToolFlowBase::hotRectForMousePointAndBrushWidthHeight ( - const QPoint &mousePoint, - int brushWidth, int brushHeight) +QRect kpToolFlowBase::hotRectForMousePointAndBrushWidthHeight( + const QPoint &mousePoint, int brushWidth, int brushHeight) { /* * e.g. @@ -475,19 +454,20 @@ * | * Center */ - return {mousePoint.x () - brushWidth / 2, - mousePoint.y () - brushHeight / 2, - brushWidth, brushHeight}; + return { + mousePoint.x() - brushWidth / 2, + mousePoint.y() - brushHeight / 2, + brushWidth, brushHeight + }; } //--------------------------------------------------------------------- // protected -QRect kpToolFlowBase::hotRect () const +QRect kpToolFlowBase::hotRect() const { - return hotRectForMousePointAndBrushWidthHeight (currentPoint (), - d->brushWidth, d->brushHeight); + return hotRectForMousePointAndBrushWidthHeight(currentPoint(), + d->brushWidth, d->brushHeight); } //--------------------------------------------------------------------- - diff --git a/tools/flow/kpToolFlowPixmapBase.h b/tools/flow/kpToolFlowPixmapBase.h --- a/tools/flow/kpToolFlowPixmapBase.h +++ b/tools/flow/kpToolFlowPixmapBase.h @@ -1,4 +1,3 @@ - // REFACTOR: Rename to kpAbstractFlowImageTool, and use kpImage instead of QPixmap /* @@ -27,32 +26,27 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_FLOW_PIXMAP_BASE_H #define KP_TOOL_FLOW_PIXMAP_BASE_H - #include "kpToolFlowBase.h" - /** * @short Abstract base call for all continuous tools that draw pixmaps * (e.g. Brush, Eraser). * * @author Clarence Dang */ class kpToolFlowPixmapBase : public kpToolFlowBase { -Q_OBJECT + Q_OBJECT public: - kpToolFlowPixmapBase (const QString &text, const QString &description, - int key, - kpToolEnvironment *environ, QObject *parent, const QString &name); + kpToolFlowPixmapBase (const QString &text, const QString &description, int key, + kpToolEnvironment *environ, QObject *parent, const QString &name); protected: - QRect drawLine (const QPoint &thisPoint, const QPoint &lastPoint) override; + QRect drawLine(const QPoint &thisPoint, const QPoint &lastPoint) override; }; - #endif // KP_TOOL_FLOW_PIXMAP_BASE_H diff --git a/tools/flow/kpToolFlowPixmapBase.cpp b/tools/flow/kpToolFlowPixmapBase.cpp --- a/tools/flow/kpToolFlowPixmapBase.cpp +++ b/tools/flow/kpToolFlowPixmapBase.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpToolFlowPixmapBase.h" #include "imagelib/kpColor.h" @@ -39,32 +37,30 @@ //--------------------------------------------------------------------- kpToolFlowPixmapBase::kpToolFlowPixmapBase (const QString &text, const QString &description, - int key, - kpToolEnvironment *environ, QObject *parent, const QString &name) - : kpToolFlowBase (text, description, key, environ, parent, name) + int key, kpToolEnvironment *environ, QObject *parent, + const QString &name) + : kpToolFlowBase(text, description, key, environ, parent, name) { } //--------------------------------------------------------------------- -QRect kpToolFlowPixmapBase::drawLine (const QPoint &thisPoint, const QPoint &lastPoint) +QRect kpToolFlowPixmapBase::drawLine(const QPoint &thisPoint, const QPoint &lastPoint) { QRect docRect = kpPainter::normalizedRect(thisPoint, lastPoint); - docRect = neededRect (docRect, qMax (brushWidth (), brushHeight ())); - kpImage image = document ()->getImageAt (docRect); - + docRect = neededRect(docRect, qMax(brushWidth(), brushHeight())); + kpImage image = document()->getImageAt(docRect); - QList points = kpPainter::interpolatePoints (lastPoint, thisPoint, - brushIsDiagonalLine ()); + QList points = kpPainter::interpolatePoints(lastPoint, thisPoint, + brushIsDiagonalLine()); - for (QList ::const_iterator pit = points.constBegin (); - pit != points.constEnd (); - ++pit) - { - const QPoint point = - hotRectForMousePointAndBrushWidthHeight ( - (*pit), brushWidth (), brushHeight ()) - .topLeft () - docRect.topLeft (); + for (QList ::const_iterator pit = points.constBegin(); + pit != points.constEnd(); + ++pit) { + const QPoint point + = hotRectForMousePointAndBrushWidthHeight( + (*pit), brushWidth(), brushHeight()) + .topLeft() - docRect.topLeft(); // OPT: This may be redrawing pixels that were drawn on a previous // iteration, since the brush is usually bigger than 1 pixel. @@ -74,13 +70,11 @@ // Try this at least for the easy case of the Eraser, which has // square, simply-filled brushes. Profiling needs to be done as // QRegion is known to be a CPU hog. - brushDrawFunction () (&image, point, brushDrawFunctionData ()); + brushDrawFunction() (&image, point, brushDrawFunctionData()); } - - document ()->setImageAt (image, docRect.topLeft ()); + document()->setImageAt(image, docRect.topLeft()); return docRect; } //--------------------------------------------------------------------- - diff --git a/tools/flow/kpToolPen.h b/tools/flow/kpToolPen.h --- a/tools/flow/kpToolPen.h +++ b/tools/flow/kpToolPen.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,22 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_PEN_H #define KP_TOOL_PEN_H - #include "kpToolFlowBase.h" - // Pen = draws pixels, "interpolates" by "sweeping" pixels along a line (no brushes) class kpToolPen : public kpToolFlowBase { -Q_OBJECT + Q_OBJECT public: kpToolPen (kpToolEnvironment *environ, QObject *parent); protected: - QString haventBegunDrawUserMessage () const override; - QRect drawLine (const QPoint &thisPoint, const QPoint &lastPoint) override; + QString haventBegunDrawUserMessage() const override; + QRect drawLine(const QPoint &thisPoint, const QPoint &lastPoint) override; }; - #endif // KP_TOOL_PEN_H diff --git a/tools/flow/kpToolPen.cpp b/tools/flow/kpToolPen.cpp --- a/tools/flow/kpToolPen.cpp +++ b/tools/flow/kpToolPen.cpp @@ -25,7 +25,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpToolPen.h" #include "imagelib/kpColor.h" @@ -43,42 +42,42 @@ //--------------------------------------------------------------------- kpToolPen::kpToolPen (kpToolEnvironment *environ, QObject *parent) - : kpToolFlowBase (i18n ("Pen"), i18n ("Draws dots and freehand strokes"), - Qt::Key_P, - environ, parent, QStringLiteral("tool_pen")) + : kpToolFlowBase(i18n("Pen"), i18n("Draws dots and freehand strokes"), + Qt::Key_P, + environ, parent, QStringLiteral("tool_pen")) { } //--------------------------------------------------------------------- // protected virtual [base kpToolFlowBase] -QString kpToolPen::haventBegunDrawUserMessage () const +QString kpToolPen::haventBegunDrawUserMessage() const { - return i18n ("Click to draw dots or drag to draw strokes."); + return i18n("Click to draw dots or drag to draw strokes."); } //--------------------------------------------------------------------- // protected virtual [base kpToolFlowBase] -QRect kpToolPen::drawLine (const QPoint &thisPoint, const QPoint &lastPoint) +QRect kpToolPen::drawLine(const QPoint &thisPoint, const QPoint &lastPoint) { - QRect docRect = kpPainter::normalizedRect(thisPoint, lastPoint); - docRect = neededRect (docRect, 1/*pen width*/); - kpImage image = document ()->getImageAt (docRect); + QRect docRect = kpPainter::normalizedRect(thisPoint, lastPoint); + docRect = neededRect(docRect, 1 /*pen width*/); + kpImage image = document()->getImageAt(docRect); - const QPoint sp = lastPoint - docRect.topLeft (), - ep = thisPoint - docRect.topLeft (); + const QPoint sp = lastPoint - docRect.topLeft(), + ep = thisPoint - docRect.topLeft(); - QPainter painter(&image); + QPainter painter(&image); - // never use AA - it does not look good for the usually very short lines - //painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); + // never use AA - it does not look good for the usually very short lines + //painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); - painter.setPen(color(mouseButton()).toQColor()); - painter.drawLine(sp, ep); + painter.setPen(color(mouseButton()).toQColor()); + painter.drawLine(sp, ep); - document ()->setImageAt (image, docRect.topLeft ()); - return docRect; + document()->setImageAt(image, docRect.topLeft()); + return docRect; } //-------------------------------------------------------------------------------- diff --git a/tools/flow/kpToolSpraycan.h b/tools/flow/kpToolSpraycan.h --- a/tools/flow/kpToolSpraycan.h +++ b/tools/flow/kpToolSpraycan.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,66 +24,55 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_SPRAYCAN_H #define KP_TOOL_SPRAYCAN_H - #include "kpToolFlowBase.h" - class QPoint; class QRect; class QString; class QTimer; class kpToolWidgetSpraycanSize; - class kpToolSpraycan : public kpToolFlowBase { -Q_OBJECT + Q_OBJECT public: kpToolSpraycan (kpToolEnvironment *environ, QObject *parent); protected: - QString haventBegunDrawUserMessage () const override; - + QString haventBegunDrawUserMessage() const override; public: - void begin () override; - void end () override; - + void begin() override; + void end() override; public: - void beginDraw () override; + void beginDraw() override; protected: // (ASSUMPTION: is between 0.0 and 1.0 inclusive) - QRect drawLineWithProbability (const QPoint &thisPoint, - const QPoint &lastPoint, - double probability); + QRect drawLineWithProbability(const QPoint &thisPoint, const QPoint &lastPoint, + double probability); public: - QRect drawPoint (const QPoint &point) override; - QRect drawLine (const QPoint &thisPoint, const QPoint &lastPoint) override; - void cancelShape () override; - void endDraw (const QPoint &thisPoint, - const QRect &normalizedRect) override; + QRect drawPoint(const QPoint &point) override; + QRect drawLine(const QPoint &thisPoint, const QPoint &lastPoint) override; + void cancelShape() override; + void endDraw(const QPoint &thisPoint, const QRect &normalizedRect) override; protected slots: - void timeoutDraw (); - + void timeoutDraw(); protected: - int spraycanSize () const; + int spraycanSize() const; protected slots: - void slotSpraycanSizeChanged (int size); - + void slotSpraycanSizeChanged(int size); protected: QTimer *m_timer; kpToolWidgetSpraycanSize *m_toolWidgetSpraycanSize; }; - #endif // KP_TOOL_SPRAYCAN_H diff --git a/tools/flow/kpToolSpraycan.cpp b/tools/flow/kpToolSpraycan.cpp --- a/tools/flow/kpToolSpraycan.cpp +++ b/tools/flow/kpToolSpraycan.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SPRAYCAN 0 #include "kpToolSpraycan.h" @@ -53,207 +51,193 @@ //--------------------------------------------------------------------- kpToolSpraycan::kpToolSpraycan (kpToolEnvironment *environ, QObject *parent) - : kpToolFlowBase (i18n ("Spraycan"), i18n ("Sprays graffiti"), - Qt::Key_Y, - environ, parent, QStringLiteral("tool_spraycan")), - m_toolWidgetSpraycanSize(nullptr) + : kpToolFlowBase(i18n("Spraycan"), i18n("Sprays graffiti"), + Qt::Key_Y, + environ, parent, QStringLiteral("tool_spraycan")) + , m_toolWidgetSpraycanSize(nullptr) { - m_timer = new QTimer (this); - m_timer->setInterval (25/*ms*/); - connect (m_timer, &QTimer::timeout, this, &kpToolSpraycan::timeoutDraw); + m_timer = new QTimer(this); + m_timer->setInterval(25 /*ms*/); + connect(m_timer, &QTimer::timeout, this, &kpToolSpraycan::timeoutDraw); } //--------------------------------------------------------------------- // protected virtual [base kpToolFlowBase] -QString kpToolSpraycan::haventBegunDrawUserMessage () const +QString kpToolSpraycan::haventBegunDrawUserMessage() const { - return i18n ("Click or drag to spray graffiti."); + return i18n("Click or drag to spray graffiti."); } //--------------------------------------------------------------------- // public virtual [base kpToolFlowBase] -void kpToolSpraycan::begin () +void kpToolSpraycan::begin() { - kpToolToolBar *tb = toolToolBar (); - Q_ASSERT (tb); + kpToolToolBar *tb = toolToolBar(); + Q_ASSERT(tb); - m_toolWidgetSpraycanSize = tb->toolWidgetSpraycanSize (); - connect (m_toolWidgetSpraycanSize, &kpToolWidgetSpraycanSize::spraycanSizeChanged, - this, &kpToolSpraycan::slotSpraycanSizeChanged); - m_toolWidgetSpraycanSize->show (); + m_toolWidgetSpraycanSize = tb->toolWidgetSpraycanSize(); + connect(m_toolWidgetSpraycanSize, &kpToolWidgetSpraycanSize::spraycanSizeChanged, + this, &kpToolSpraycan::slotSpraycanSizeChanged); + m_toolWidgetSpraycanSize->show(); - kpToolFlowBase::begin (); + kpToolFlowBase::begin(); } // public virtual [base kpToolFlowBase] -void kpToolSpraycan::end () +void kpToolSpraycan::end() { - kpToolFlowBase::end (); + kpToolFlowBase::end(); - disconnect (m_toolWidgetSpraycanSize, &kpToolWidgetSpraycanSize::spraycanSizeChanged, - this, &kpToolSpraycan::slotSpraycanSizeChanged); + disconnect(m_toolWidgetSpraycanSize, &kpToolWidgetSpraycanSize::spraycanSizeChanged, + this, &kpToolSpraycan::slotSpraycanSizeChanged); m_toolWidgetSpraycanSize = nullptr; } - // public virtual [base kpToolFlowBase] -void kpToolSpraycan::beginDraw () +void kpToolSpraycan::beginDraw() { #if DEBUG_KP_TOOL_SPRAYCAN qCDebug(kpLogTools) << "kpToolSpraycan::beginDraw()"; #endif - kpToolFlowBase::beginDraw (); + kpToolFlowBase::beginDraw(); // We draw even if the user doesn't move the mouse. // We still timeout-draw even if the user _does_ move the mouse. - m_timer->start (); + m_timer->start(); } - // protected -QRect kpToolSpraycan::drawLineWithProbability (const QPoint &thisPoint, - const QPoint &lastPoint, - double probability) +QRect kpToolSpraycan::drawLineWithProbability(const QPoint &thisPoint, const QPoint &lastPoint, + double probability) { #if DEBUG_KP_TOOL_SPRAYCAN qCDebug(kpLogTools) << "CALL(thisPoint=" << thisPoint - << ",lastPoint=" << lastPoint - << ")"; + << ",lastPoint=" << lastPoint + << ")"; #endif - QList docPoints = kpPainter::interpolatePoints (lastPoint, thisPoint, - false/*no need for cardinally adjacency points*/, - probability); + QList docPoints = kpPainter::interpolatePoints(lastPoint, thisPoint, + false /*no need for cardinally adjacency points*/, + probability); #if DEBUG_KP_TOOL_SPRAYCAN qCDebug(kpLogTools) << "\tdocPoints=" << docPoints; #endif - // By chance no points to draw? - if (docPoints.empty ()) { - return {}; + if (docPoints.empty()) { + return {}; } - // For efficiency, only get image after NOP check above. QRect docRect = kpPainter::normalizedRect(thisPoint, lastPoint); - docRect = neededRect (docRect, spraycanSize ()); - kpImage image = document ()->getImageAt (docRect); - + docRect = neededRect(docRect, spraycanSize()); + kpImage image = document()->getImageAt(docRect); // Spray at each point, onto the image. // // Note in passing: Unlike other tools such as the Brush, drawing // over the same point does result in a different // appearance. QList imagePoints; - for (const auto &dp : docPoints) - imagePoints.append (dp - docRect.topLeft ()); - - kpPainter::sprayPoints (&image, - imagePoints, - color (mouseButton ()), - spraycanSize ()); - + for (const auto &dp : docPoints) { + imagePoints.append(dp - docRect.topLeft()); + } - viewManager ()->setFastUpdates (); - document ()->setImageAt (image, docRect.topLeft ()); - viewManager ()->restoreFastUpdates (); + kpPainter::sprayPoints(&image, + imagePoints, + color(mouseButton()), + spraycanSize()); + viewManager()->setFastUpdates(); + document()->setImageAt(image, docRect.topLeft()); + viewManager()->restoreFastUpdates(); return docRect; } // public virtual [base kpToolFlowBase] -QRect kpToolSpraycan::drawPoint (const QPoint &point) +QRect kpToolSpraycan::drawPoint(const QPoint &point) { #if DEBUG_KP_TOOL_SPRAYCAN qCDebug(kpLogTools) << "kpToolSpraycan::drawPoint" << point - << " lastPoint=" << lastPoint (); + << " lastPoint=" << lastPoint(); #endif // If this is the first in the flow or if the user is moving the spray, // make the spray line continuous. - if (point != lastPoint ()) - { + if (point != lastPoint()) { // Draw at this single point without delay. - return drawLineWithProbability (point, point, - 1.0/*100% chance of drawing*/); + return drawLineWithProbability(point, point, + 1.0 /*100% chance of drawing*/); } - return {}; + return {}; } // public virtual [base kpToolFlowBase] -QRect kpToolSpraycan::drawLine (const QPoint &thisPoint, const QPoint &lastPoint) +QRect kpToolSpraycan::drawLine(const QPoint &thisPoint, const QPoint &lastPoint) { #if DEBUG_KP_TOOL_SPRAYCAN qCDebug(kpLogTools) << "CALL(thisPoint=" << thisPoint << ",lastPoint=" << lastPoint; #endif // Draw only every so often in response to movement. - return drawLineWithProbability (thisPoint, lastPoint, - 0.05/*less dense: select 5% of adjacent pixels - not all*/); + return drawLineWithProbability(thisPoint, lastPoint, + 0.05 /*less dense: select 5% of adjacent pixels - not all*/); } // protected slot -void kpToolSpraycan::timeoutDraw () +void kpToolSpraycan::timeoutDraw() { #if DEBUG_KP_TOOL_SPRAYCAN qCDebug(kpLogTools) << "kpToolSpraycan::timeoutDraw()"; #endif // Draw at this single point without delay. - const QRect drawnRect = drawLineWithProbability (currentPoint (), currentPoint (), - 1.0/*100% chance of drawing*/); + const QRect drawnRect = drawLineWithProbability(currentPoint(), currentPoint(), + 1.0 /*100% chance of drawing*/); // kpToolFlowBase() does this after calling drawPoint() and drawLine() so // we need to do it too. - currentCommand ()->updateBoundingRect (drawnRect); + currentCommand()->updateBoundingRect(drawnRect); } - // public virtual [base kpToolFlowBase] -void kpToolSpraycan::cancelShape () +void kpToolSpraycan::cancelShape() { #if DEBUG_KP_TOOL_SPRAYCAN qCDebug(kpLogTools) << "kpToolSpraycan::cancelShape()"; #endif - m_timer->stop (); - kpToolFlowBase::cancelShape (); + m_timer->stop(); + kpToolFlowBase::cancelShape(); } // public virtual [base kpToolFlowBase] -void kpToolSpraycan::endDraw (const QPoint &thisPoint, - const QRect &normalizedRect) +void kpToolSpraycan::endDraw(const QPoint &thisPoint, const QRect &normalizedRect) { #if DEBUG_KP_TOOL_SPRAYCAN qCDebug(kpLogTools) << "kpToolSpraycan::endDraw(thisPoint=" << thisPoint - << ")"; + << ")"; #endif - m_timer->stop (); - kpToolFlowBase::endDraw (thisPoint, normalizedRect); + m_timer->stop(); + kpToolFlowBase::endDraw(thisPoint, normalizedRect); } - // protected -int kpToolSpraycan::spraycanSize () const +int kpToolSpraycan::spraycanSize() const { - return m_toolWidgetSpraycanSize->spraycanSize (); + return m_toolWidgetSpraycanSize->spraycanSize(); } // protected slot -void kpToolSpraycan::slotSpraycanSizeChanged (int size) +void kpToolSpraycan::slotSpraycanSizeChanged(int size) { - (void) size; + (void)size; } - - - diff --git a/tools/kpTool.h b/tools/kpTool.h --- a/tools/kpTool.h +++ b/tools/kpTool.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_H #define KP_TOOL_H - #include #include #include @@ -42,7 +39,6 @@ #undef environ // macro on win32 #endif - class QFocusEvent; class QInputMethodEvent; class QKeyEvent; @@ -59,14 +55,13 @@ class kpToolEnvironment; class kpToolToolBar; - struct kpToolPrivate; // Base class for all tools. // REFACTOR: rearrange method order to make sense and reflect kpTool_*.cpp split. class kpTool : public QObject { -Q_OBJECT + Q_OBJECT public: // = user-visible name of the tool e.g. "Color Picker" @@ -77,28 +72,27 @@ // = internal QObject name (not user-visible) e.g. "tool_color_picker" // used for fetching the icon(), the name of the action() and // debug printing. - kpTool (const QString &text, const QString &description, - int key, - kpToolEnvironment *environ, + kpTool (const QString &text, const QString &description, int key, kpToolEnvironment *environ, QObject *parent, const QString &name); ~kpTool () override; - kpToolAction *action () const; + kpToolAction *action() const; - QString text () const; + QString text() const; - static QString toolTipForTextAndShortcut (const QString &text, const QList &shortcut); - QString toolTip () const; + static QString toolTipForTextAndShortcut(const QString &text, + const QList &shortcut); + QString toolTip() const; // Given a single , returns a shortcut with // (disabled when the user is editing text) and as an alternate, // +. - static QList shortcutForKey (int key); + static QList shortcutForKey(int key); - static QRect neededRect (const QRect &rect, int lineWidth); - static QImage neededPixmap (const QImage &image, const QRect &boundingRect); + static QRect neededRect(const QRect &rect, int lineWidth); + static QImage neededPixmap(const QImage &image, const QRect &boundingRect); - bool hasCurrentPoint () const; + bool hasCurrentPoint() const; // Returns the position of the cursor relative to the topleft point of // the current view (viewUnderStartPoint() or viewUnderCursor() otherwise). // @@ -115,11 +109,11 @@ // // Keep in mind that if viewUnderStartPoint(), this can return coordinates // outside of the document/view. - QPoint calculateCurrentPoint (bool zoomToDoc = true) const; + QPoint calculateCurrentPoint(bool zoomToDoc = true) const; private: // Only called by ctor to create action(). - void initAction (); + void initAction(); signals: void actionToolTipChanged(); @@ -135,73 +129,72 @@ // can then update the position of the Brush Cursor. The Selection // Tool can update the real cursor. The Line Tool can update the current // line. The statubar gets correct coordinates. etc. etc. - void somethingBelowTheCursorChanged (); + void somethingBelowTheCursorChanged(); private: // Same as above except that you claim you know better than currentPoint() - void somethingBelowTheCursorChanged (const QPoint ¤tPoint_, - const QPoint ¤tViewPoint_); + void somethingBelowTheCursorChanged(const QPoint ¤tPoint_, + const QPoint ¤tViewPoint_); protected: - int mouseButton () const; + int mouseButton() const; - bool shiftPressed () const; - bool controlPressed () const; - bool altPressed () const; + bool shiftPressed() const; + bool controlPressed() const; + bool altPressed() const; - QPoint startPoint () const; + QPoint startPoint() const; - QPoint currentPoint () const; - QPoint currentViewPoint () const; + QPoint currentPoint() const; + QPoint currentViewPoint() const; - QRect normalizedRect () const; + QRect normalizedRect() const; - QPoint lastPoint () const; + QPoint lastPoint() const; public: // for kpMainWindow - kpView *viewUnderStartPoint () const; + kpView *viewUnderStartPoint() const; protected: - kpView *viewUnderCursor () const; + kpView *viewUnderCursor() const; public: // Called when the tool is selected. - virtual void begin (); + virtual void begin(); // Called when the tool is deselected. - virtual void end (); + virtual void end(); // Returns true after begin() has been called but returns false after end() // after end() has been called. - bool hasBegun () const; + bool hasBegun() const; - bool hasBegunDraw () const; + bool hasBegunDraw() const; - virtual bool hasBegunShape () const; + virtual bool hasBegunShape() const; // Called when user double-left-clicks on a tool in the Tool Box. - virtual void globalDraw (); + virtual void globalDraw(); // Called when the user clicks on a tool in the Tool Box even though it's // already the current tool (used by the selection tools to deselect). - virtual void reselect (); + virtual void reselect(); signals: // emitted after beginDraw() has been called - void beganDraw (const QPoint &point); + void beganDraw(const QPoint &point); // Emitted just before draw() is called in mouseMoveEvent(). Slots // connected to this signal should return in whether the // mouse pos may have changed. Used by drag scrolling. - void movedAndAboutToDraw (const QPoint ¤tPoint, const QPoint &lastPoint, - int zoomLevel, - bool *scrolled); + void movedAndAboutToDraw(const QPoint ¤tPoint, const QPoint &lastPoint, int zoomLevel, + bool *scrolled); // emitted after endDraw() has been called - void endedDraw (const QPoint &point); + void endedDraw(const QPoint &point); // emitted after cancelShape() has been called - void cancelledShape (const QPoint &point); + void cancelledShape(const QPoint &point); signals: // User clicked on the tool's action - i.e. select this tool @@ -213,95 +206,115 @@ // different times) // REFACTOR: Misleadingly named as it's also called in cancelShapeInternal(). // And it seems to be called in endShapeInternal() as well? - virtual bool returnToPreviousToolAfterEndDraw () const { return false; } + virtual bool returnToPreviousToolAfterEndDraw() const + { + return false; + } + + virtual bool careAboutModifierState() const + { + return false; + } - virtual bool careAboutModifierState () const { return false; } - virtual bool careAboutColorsSwapped () const { return false; } + virtual bool careAboutColorsSwapped() const + { + return false; + } - virtual void beginDraw (); + virtual void beginDraw(); // mouse move without button pressed // (only m_currentPoint & m_currentViewPoint is defined) - virtual void hover (const QPoint &point); + virtual void hover(const QPoint &point); // this is useful for "instant" tools like the Pen & Eraser - virtual void draw (const QPoint &thisPoint, const QPoint &lastPoint, - const QRect &normalizedRect); + virtual void draw(const QPoint &thisPoint, const QPoint &lastPoint, + const QRect &normalizedRect); private: - void drawInternal (); + void drawInternal(); protected: // (m_mouseButton will not change from beginDraw()) - virtual void cancelShape (); - virtual void releasedAllButtons (); + virtual void cancelShape(); + virtual void releasedAllButtons(); - virtual void endDraw (const QPoint &thisPoint, const QRect &normalizedRect); + virtual void endDraw(const QPoint &thisPoint, const QRect &normalizedRect); // TODO: I think reimplementations of this should be calling this base // implementation, so that endDraw() happens before the custom // endShape() logic of the reimplementation. - virtual void endShape (const QPoint &thisPoint = QPoint (), - const QRect &normalizedRect = QRect ()) + virtual void endShape(const QPoint &thisPoint = QPoint(), const QRect &normalizedRect = QRect()) { - endDraw (thisPoint, normalizedRect); + endDraw(thisPoint, normalizedRect); } - kpDocument *document () const; - kpViewManager *viewManager () const; - kpToolToolBar *toolToolBar () const; - kpCommandHistory *commandHistory () const; - kpToolEnvironment *environ () const; + kpDocument *document() const; + kpViewManager *viewManager() const; + kpToolToolBar *toolToolBar() const; + kpCommandHistory *commandHistory() const; + kpToolEnvironment *environ() const; - kpColor color (int which) const; + kpColor color(int which) const; - kpColor foregroundColor () const; - kpColor backgroundColor () const; + kpColor foregroundColor() const; + kpColor backgroundColor() const; - double colorSimilarity () const; - int processedColorSimilarity () const; + double colorSimilarity() const; + int processedColorSimilarity() const; public slots: - void slotColorsSwappedInternal (const kpColor &newForegroundColor, - const kpColor &newBackgroundColor); - void slotForegroundColorChangedInternal (const kpColor &color); - void slotBackgroundColorChangedInternal (const kpColor &color); - void slotColorSimilarityChangedInternal (double similarity, int processedSimilarity); + void slotColorsSwappedInternal(const kpColor &newForegroundColor, + const kpColor &newBackgroundColor); + void slotForegroundColorChangedInternal(const kpColor &color); + void slotBackgroundColorChangedInternal(const kpColor &color); + void slotColorSimilarityChangedInternal(double similarity, int processedSimilarity); protected slots: // TODO: there is no reason why these should be slots - virtual void slotColorsSwapped (const kpColor & /*newForegroundColor*/, const kpColor & /*newBackgroundColor*/) {} - virtual void slotForegroundColorChanged (const kpColor & /*color*/) {} - virtual void slotBackgroundColorChanged (const kpColor & /*color*/) {} - virtual void slotColorSimilarityChanged (double /*similarity*/, int /*processedSimilarity*/) {} + virtual void slotColorsSwapped(const kpColor & /*newForegroundColor*/, + const kpColor & /*newBackgroundColor*/) + { + } + + virtual void slotForegroundColorChanged(const kpColor & /*color*/) + { + } + + virtual void slotBackgroundColorChanged(const kpColor & /*color*/) + { + } + + virtual void slotColorSimilarityChanged(double /*similarity*/, int /*processedSimilarity*/) + { + } protected: // (only valid in slots connected to the respective signals above) - kpColor oldForegroundColor () const; - kpColor oldBackgroundColor () const; - double oldColorSimilarity () const; + kpColor oldForegroundColor() const; + kpColor oldBackgroundColor() const; + double oldColorSimilarity() const; protected: // returns true if m_currentPoint <= 1 pixel away from m_lastPoint // or if there was no lastPoint - bool currentPointNextToLast () const; // (includes diagonal adjacency) - bool currentPointCardinallyNextToLast () const; // (only cardinally adjacent i.e. horiz & vert; no diag) + bool currentPointNextToLast() const; // (includes diagonal adjacency) + bool currentPointCardinallyNextToLast() const; // (only cardinally adjacent i.e. horiz & vert; no diag) // TODO: We should rename these. // These are accessed from kpTool logic and our friends, kpCommandHistory, // kpMainWindow, kpToolToolBar and kpView. public: - void beginInternal (); - void endInternal (); + void beginInternal(); + void endInternal(); - void beginDrawInternal (); - void endDrawInternal (const QPoint &thisPoint, const QRect &normalizedRect, - bool wantEndShape = false); - void cancelShapeInternal (); + void beginDrawInternal(); + void endDrawInternal(const QPoint &thisPoint, const QRect &normalizedRect, + bool wantEndShape = false); + void cancelShapeInternal(); // TODO: Who is actually calling endShapeInternal()? // Tools seem to call endShape() directly. - void endShapeInternal (const QPoint &thisPoint = QPoint (), - const QRect &normalizedRect = QRect ()); - + void endShapeInternal(const QPoint &thisPoint = QPoint(), + const QRect &normalizedRect = QRect()); // // Mouse Events @@ -314,43 +327,43 @@ // If you're reimplementing any of these, you probably don't know what // you're doing - reimplement begin(),beginDraw(),draw(),cancelShape(), // endDraw() etc. instead. - virtual void mousePressEvent (QMouseEvent *e); - virtual void mouseMoveEvent (QMouseEvent *e); - virtual void mouseReleaseEvent (QMouseEvent *e); - - virtual void wheelEvent (QWheelEvent *e); + virtual void mousePressEvent(QMouseEvent *e); + virtual void mouseMoveEvent(QMouseEvent *e); + virtual void mouseReleaseEvent(QMouseEvent *e); + virtual void wheelEvent(QWheelEvent *e); // // Keyboard Events // protected: - void seeIfAndHandleModifierKey (QKeyEvent *e); + void seeIfAndHandleModifierKey(QKeyEvent *e); - void arrowKeyPressDirection (const QKeyEvent *e, int *dx, int *dy); - void seeIfAndHandleArrowKeyPress (QKeyEvent *e); + void arrowKeyPressDirection(const QKeyEvent *e, int *dx, int *dy); + void seeIfAndHandleArrowKeyPress(QKeyEvent *e); - bool isDrawKey (int key); - void seeIfAndHandleBeginDrawKeyPress (QKeyEvent *e); - void seeIfAndHandleEndDrawKeyPress (QKeyEvent *e); + bool isDrawKey(int key); + void seeIfAndHandleBeginDrawKeyPress(QKeyEvent *e); + void seeIfAndHandleEndDrawKeyPress(QKeyEvent *e); public: - virtual void keyPressEvent (QKeyEvent *e); - virtual void keyReleaseEvent (QKeyEvent *e); + virtual void keyPressEvent(QKeyEvent *e); + virtual void keyReleaseEvent(QKeyEvent *e); - virtual void inputMethodEvent (QInputMethodEvent *) {} + virtual void inputMethodEvent(QInputMethodEvent *) + { + } private: - void keyUpdateModifierState (QKeyEvent *e); - void notifyModifierStateChanged (); + void keyUpdateModifierState(QKeyEvent *e); + void notifyModifierStateChanged(); protected: - virtual void setShiftPressed (bool pressed); - virtual void setControlPressed (bool pressed); - - virtual void setAltPressed (bool pressed); + virtual void setShiftPressed(bool pressed); + virtual void setControlPressed(bool pressed); + virtual void setAltPressed(bool pressed); // // Other Events - 1. View Events @@ -364,64 +377,61 @@ // REFACTOR: rename mousePressEvent() -> viewMousePressEvent() etc. // to remind us that events are coming from the view - the tool // is not a visible object. - virtual bool viewEvent (QEvent *e); + virtual bool viewEvent(QEvent *e); public: - virtual void focusInEvent (QFocusEvent *e); - virtual void focusOutEvent (QFocusEvent *e); + virtual void focusInEvent(QFocusEvent *e); + virtual void focusOutEvent(QFocusEvent *e); public: - virtual void enterEvent (QEvent *e); - virtual void leaveEvent (QEvent *e); - + virtual void enterEvent(QEvent *e); + virtual void leaveEvent(QEvent *e); // // Other Events - 2. Non-view Events // REFACTOR: Group methods under this. // protected: // 0 = left, 1 = right, -1 = other (none, left+right, mid) - static int mouseButton (Qt::MouseButtons mouseButtons); + static int mouseButton(Qt::MouseButtons mouseButtons); public: - static int calculateLength (int start, int end); + static int calculateLength(int start, int end); // // User Notifications (Status Bar) // public: // Returns "(Left|Right) click to cancel." where Left or Right is chosen // depending on which one is the _opposite_ of - static QString cancelUserMessage (int mouseButton); - QString cancelUserMessage () const; + static QString cancelUserMessage(int mouseButton); + QString cancelUserMessage() const; - QString userMessage () const; + QString userMessage() const; // WARNING: setUserMessage() will store a message different to , // in unspecified ways (e.g. the name of the tool, followed // by a colon and a space, will be prepended). userMessage() // will return this different string. - void setUserMessage (const QString &userMessage = QString ()); + void setUserMessage(const QString &userMessage = QString()); - QPoint userShapeStartPoint () const; - QPoint userShapeEndPoint () const; - void setUserShapePoints (const QPoint &startPoint = KP_INVALID_POINT, - const QPoint &endPoint = KP_INVALID_POINT, - bool setSize = true); + QPoint userShapeStartPoint() const; + QPoint userShapeEndPoint() const; + void setUserShapePoints(const QPoint &startPoint = KP_INVALID_POINT, + const QPoint &endPoint = KP_INVALID_POINT, bool setSize = true); - QSize userShapeSize () const; - int userShapeWidth () const; - int userShapeHeight () const; - void setUserShapeSize (const QSize &size = KP_INVALID_SIZE); - void setUserShapeSize (int width, int height); + QSize userShapeSize() const; + int userShapeWidth() const; + int userShapeHeight() const; + void setUserShapeSize(const QSize &size = KP_INVALID_SIZE); + void setUserShapeSize(int width, int height); signals: - void userMessageChanged (const QString &userMessage); - void userShapePointsChanged (const QPoint &startPoint = KP_INVALID_POINT, - const QPoint &endPoint = KP_INVALID_POINT); - void userShapeSizeChanged (const QSize &size); - + void userMessageChanged(const QString &userMessage); + void userShapePointsChanged(const QPoint &startPoint = KP_INVALID_POINT, + const QPoint &endPoint = KP_INVALID_POINT); + void userShapeSizeChanged(const QSize &size); public: // Call this before the user tries to cause the document or selection @@ -449,16 +459,12 @@ // " (image|selection)?

"); // caption = i18n ("Rotate (Image|Selection)?"); // continueButtonText = i18n ("Rotat&e (Image|Selection)"); - static bool warnIfBigImageSize (int oldWidth, int oldHeight, - int newWidth, int newHeight, - const QString &text, - const QString &caption, - const QString &continueButtonText, - QWidget *parent); + static bool warnIfBigImageSize(int oldWidth, int oldHeight, int newWidth, int newHeight, + const QString &text, const QString &caption, + const QString &continueButtonText, QWidget *parent); private: kpToolPrivate *d; }; - #endif // KP_TOOL_H diff --git a/tools/kpTool.cpp b/tools/kpTool.cpp --- a/tools/kpTool.cpp +++ b/tools/kpTool.cpp @@ -51,12 +51,10 @@ //--------------------------------------------------------------------- -kpTool::kpTool(const QString &text, const QString &description, - int key, - kpToolEnvironment *environ, +kpTool::kpTool(const QString &text, const QString &description, int key, kpToolEnvironment *environ, QObject *parent, const QString &name) - : QObject(parent), - d(new kpToolPrivate()) + : QObject(parent) + , d(new kpToolPrivate()) { d->key = key; d->action = nullptr; @@ -85,7 +83,7 @@ { // before destructing, stop using the tool if (d->began) { - endInternal (); + endInternal(); } delete d->action; @@ -96,168 +94,165 @@ //--------------------------------------------------------------------- // private -void kpTool::initAction () +void kpTool::initAction() { - KActionCollection *ac = d->environ->actionCollection (); - Q_ASSERT (ac); + KActionCollection *ac = d->environ->actionCollection(); + Q_ASSERT(ac); d->action = new kpToolAction(text(), objectName(), shortcutForKey(d->key), this, SIGNAL(actionActivated()), ac, objectName()); // Make tools mutually exclusive by placing them in the same group. - d->action->setActionGroup(d->environ->toolsActionGroup ()); + d->action->setActionGroup(d->environ->toolsActionGroup()); d->action->setWhatsThis(d->description); - connect (d->action, &kpToolAction::changed, this, &kpTool::actionToolTipChanged); + connect(d->action, &kpToolAction::changed, this, &kpTool::actionToolTipChanged); } //--------------------------------------------------------------------- // public -QString kpTool::text () const +QString kpTool::text() const { return d->text; } //--------------------------------------------------------------------- -static bool KeyIsText (int key) +static bool KeyIsText(int key) { // TODO: should work like !QKeyEvent::text().isEmpty() - return !(static_cast (key) & (Qt::KeyboardModifierMask ^ Qt::ShiftModifier)); + return !(static_cast(key) & (Qt::KeyboardModifierMask ^ Qt::ShiftModifier)); } //--------------------------------------------------------------------- // public static -QString kpTool::toolTipForTextAndShortcut (const QString &text, - const QList &shortcut) +QString kpTool::toolTipForTextAndShortcut(const QString &text, const QList &shortcut) { - for(const auto &seq : shortcut) - { - if (seq.count () == 1 && ::KeyIsText (seq [0])) { - return i18nc (" ()", "%1 (%2)", text, seq.toString ().toUpper ()); + for (const auto &seq : shortcut) { + if (seq.count() == 1 && ::KeyIsText(seq [0])) { + return i18nc(" ()", "%1 (%2)", text, + seq.toString().toUpper()); } } return text; } //--------------------------------------------------------------------- -QString kpTool::toolTip () const +QString kpTool::toolTip() const { return toolTipForTextAndShortcut(d->text, d->action->shortcuts()); } //--------------------------------------------------------------------- // public static -QList kpTool::shortcutForKey (int key) +QList kpTool::shortcutForKey(int key) { QList shortcut; - if (key) - { - shortcut.append (QKeySequence (key)); + if (key) { + shortcut.append(QKeySequence(key)); // (CTRL+, ALT+, CTRL+ALT+, CTRL+SHIFT+ // all clash with global KDE shortcuts) - shortcut.append (QKeySequence (static_cast(Qt::ALT) + static_cast(Qt::SHIFT) + key)); + shortcut.append(QKeySequence(static_cast(Qt::ALT) + static_cast(Qt::SHIFT) + + key)); } return shortcut; } //--------------------------------------------------------------------- // public -kpToolAction *kpTool::action () const +kpToolAction *kpTool::action() const { return d->action; } //--------------------------------------------------------------------- -kpDocument *kpTool::document () const +kpDocument *kpTool::document() const { - return d->environ->document (); + return d->environ->document(); } //--------------------------------------------------------------------- -kpViewManager *kpTool::viewManager () const +kpViewManager *kpTool::viewManager() const { - return d->environ->viewManager (); + return d->environ->viewManager(); } //--------------------------------------------------------------------- -kpToolToolBar *kpTool::toolToolBar () const +kpToolToolBar *kpTool::toolToolBar() const { - return d->environ->toolToolBar (); + return d->environ->toolToolBar(); } //--------------------------------------------------------------------- -kpColor kpTool::color (int which) const +kpColor kpTool::color(int which) const { - return d->environ->color (which); + return d->environ->color(which); } //--------------------------------------------------------------------- -kpColor kpTool::foregroundColor () const +kpColor kpTool::foregroundColor() const { - return color (0); + return color(0); } //--------------------------------------------------------------------- -kpColor kpTool::backgroundColor () const +kpColor kpTool::backgroundColor() const { - return color (1); + return color(1); } //--------------------------------------------------------------------- // TODO: Some of these might not be common enough. // Just put in kpToolEnvironment? -double kpTool::colorSimilarity () const +double kpTool::colorSimilarity() const { - return d->environ->colorSimilarity (); + return d->environ->colorSimilarity(); } -int kpTool::processedColorSimilarity () const +int kpTool::processedColorSimilarity() const { - return d->environ->processedColorSimilarity (); + return d->environ->processedColorSimilarity(); } - -kpColor kpTool::oldForegroundColor () const +kpColor kpTool::oldForegroundColor() const { - return d->environ->oldForegroundColor (); + return d->environ->oldForegroundColor(); } -kpColor kpTool::oldBackgroundColor () const +kpColor kpTool::oldBackgroundColor() const { - return d->environ->oldBackgroundColor (); + return d->environ->oldBackgroundColor(); } -double kpTool::oldColorSimilarity () const +double kpTool::oldColorSimilarity() const { - return d->environ->oldColorSimilarity (); + return d->environ->oldColorSimilarity(); } -kpCommandHistory *kpTool::commandHistory () const +kpCommandHistory *kpTool::commandHistory() const { - return d->environ->commandHistory (); + return d->environ->commandHistory(); } - -kpToolEnvironment *kpTool::environ () const +kpToolEnvironment *kpTool::environ() const { return d->environ; } diff --git a/tools/kpToolAction.h b/tools/kpToolAction.h --- a/tools/kpToolAction.h +++ b/tools/kpToolAction.h @@ -25,7 +25,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_ACTION_H #define KP_TOOL_ACTION_H @@ -37,17 +36,15 @@ class kpToolAction : public KToggleAction { - Q_OBJECT + Q_OBJECT - public: - kpToolAction(const QString &text, - const QString &pic, const QList &shortcut, - const QObject *receiver, const char *slot, - KActionCollection *ac, const QString &name); +public: + kpToolAction(const QString &text, const QString &pic, const QList &shortcut, + const QObject *receiver, const char *slot, KActionCollection *ac, + const QString &name); - private slots: +private slots: void updateToolTip(); }; - #endif // KP_TOOL_ACTION_H diff --git a/tools/kpToolAction.cpp b/tools/kpToolAction.cpp --- a/tools/kpToolAction.cpp +++ b/tools/kpToolAction.cpp @@ -33,39 +33,36 @@ //--------------------------------------------------------------------- -kpToolAction::kpToolAction(const QString &text, - const QString &pic, const QList &shortcut, - const QObject *receiver, const char *slot, - KActionCollection *ac, const QString &name) +kpToolAction::kpToolAction(const QString &text, const QString &pic, + const QList &shortcut, const QObject *receiver, + const char *slot, KActionCollection *ac, const QString &name) : KToggleAction(KDE::icon(pic), text, ac) { - ac->setDefaultShortcuts(this, shortcut); + ac->setDefaultShortcuts(this, shortcut); + if (receiver && slot) { + connect(this, SIGNAL(triggered(bool)), receiver, slot); + } - if ( receiver && slot ) { - connect (this, SIGNAL(triggered(bool)), receiver, slot); - } + updateToolTip(); + connect(this, &kpToolAction::changed, this, &kpToolAction::updateToolTip); - updateToolTip(); - connect (this, &kpToolAction::changed, this, &kpToolAction::updateToolTip); - - ac->addAction(name, this); + ac->addAction(name, this); } //--------------------------------------------------------------------- // protected void kpToolAction::updateToolTip() { - const QString newToolTip = - kpTool::toolTipForTextAndShortcut(text(), shortcuts()).remove(QLatin1Char('&')); + const QString newToolTip + = kpTool::toolTipForTextAndShortcut(text(), shortcuts()).remove(QLatin1Char('&')); - if ( newToolTip == toolTip() ) { - return; - } + if (newToolTip == toolTip()) { + return; + } - setToolTip(newToolTip); + setToolTip(newToolTip); } //--------------------------------------------------------------------- - diff --git a/tools/kpToolColorPicker.h b/tools/kpToolColorPicker.h --- a/tools/kpToolColorPicker.h +++ b/tools/kpToolColorPicker.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,47 +24,45 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_COLOR_PICKER_H #define KP_TOOL_COLOR_PICKER_H - #include "imagelib/kpColor.h" #include "tools/kpTool.h" - class QPoint; class QRect; - class kpToolColorPicker : public kpTool { -Q_OBJECT + Q_OBJECT public: kpToolColorPicker (kpToolEnvironment *environ, QObject *parent); ~kpToolColorPicker () override; // generally the user goes to pick a color but wants to return to using // his/her previous drawing tool - bool returnToPreviousToolAfterEndDraw () const override { return true; } + bool returnToPreviousToolAfterEndDraw() const override + { + return true; + } private: - kpColor colorAtPixel (const QPoint &p); + kpColor colorAtPixel(const QPoint &p); - QString haventBegunDrawUserMessage () const; + QString haventBegunDrawUserMessage() const; public: - void begin () override; - void beginDraw () override; - void draw (const QPoint &thisPoint, const QPoint &, const QRect &) override; - void cancelShape () override; - void releasedAllButtons () override; - void endDraw (const QPoint &thisPoint, const QRect &) override; + void begin() override; + void beginDraw() override; + void draw(const QPoint &thisPoint, const QPoint &, const QRect &) override; + void cancelShape() override; + void releasedAllButtons() override; + void endDraw(const QPoint &thisPoint, const QRect &) override; private: kpColor m_oldColor; }; - #endif // KP_TOOL_COLOR_PICKER_H diff --git a/tools/kpToolColorPicker.cpp b/tools/kpToolColorPicker.cpp --- a/tools/kpToolColorPicker.cpp +++ b/tools/kpToolColorPicker.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_COLOR_PICKER 0 - #include "kpToolColorPicker.h" #include "kpLogCategories.h" #include "widgets/toolbars/kpColorToolBar.h" @@ -42,96 +39,84 @@ #include kpToolColorPicker::kpToolColorPicker (kpToolEnvironment *environ, QObject *parent) - : kpTool (i18n ("Color Picker"), i18n ("Lets you select a color from the image"), - Qt::Key_C, - environ, parent, QStringLiteral("tool_color_picker")) + : kpTool(i18n("Color Picker"), i18n("Lets you select a color from the image"), + Qt::Key_C, + environ, parent, QStringLiteral("tool_color_picker")) { } kpToolColorPicker::~kpToolColorPicker () = default; - // private -kpColor kpToolColorPicker::colorAtPixel (const QPoint &p) +kpColor kpToolColorPicker::colorAtPixel(const QPoint &p) { #if DEBUG_KP_TOOL_COLOR_PICKER && 0 qCDebug(kpLogTools) << "kpToolColorPicker::colorAtPixel" << p; #endif - return kpPixmapFX::getColorAtPixel (document ()->image (), p); + return kpPixmapFX::getColorAtPixel(document()->image(), p); } - // private -QString kpToolColorPicker::haventBegunDrawUserMessage () const +QString kpToolColorPicker::haventBegunDrawUserMessage() const { - return i18n ("Click to select a color."); + return i18n("Click to select a color."); } - // public virtual [base kpTool] -void kpToolColorPicker::begin () +void kpToolColorPicker::begin() { - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } // public virtual [base kpTool] -void kpToolColorPicker::beginDraw () +void kpToolColorPicker::beginDraw() { - m_oldColor = color (mouseButton ()); + m_oldColor = color(mouseButton()); - setUserMessage (cancelUserMessage ()); + setUserMessage(cancelUserMessage()); } // public virtual [base kpTool] -void kpToolColorPicker::draw (const QPoint &thisPoint, const QPoint &, const QRect &) +void kpToolColorPicker::draw(const QPoint &thisPoint, const QPoint &, const QRect &) { - const kpColor color = colorAtPixel (thisPoint); - - if (color.isValid ()) - { - environ ()->setColor (mouseButton (), color); - setUserShapePoints (thisPoint); - } - else - { - environ ()->setColor (mouseButton (), m_oldColor); - setUserShapePoints (); + const kpColor color = colorAtPixel(thisPoint); + + if (color.isValid()) { + environ()->setColor(mouseButton(), color); + setUserShapePoints(thisPoint); + } else { + environ()->setColor(mouseButton(), m_oldColor); + setUserShapePoints(); } } // public virtual [base kpTool] -void kpToolColorPicker::cancelShape () +void kpToolColorPicker::cancelShape() { - environ ()->setColor (mouseButton (), m_oldColor); + environ()->setColor(mouseButton(), m_oldColor); - setUserMessage (i18n ("Let go of all the mouse buttons.")); + setUserMessage(i18n("Let go of all the mouse buttons.")); } // public virtual [base kpTool] -void kpToolColorPicker::releasedAllButtons () +void kpToolColorPicker::releasedAllButtons() { - setUserMessage (haventBegunDrawUserMessage ()); - + setUserMessage(haventBegunDrawUserMessage()); } // public virtual [base kpTool] -void kpToolColorPicker::endDraw (const QPoint &thisPoint, const QRect &) +void kpToolColorPicker::endDraw(const QPoint &thisPoint, const QRect &) { - const kpColor color = colorAtPixel (thisPoint); + const kpColor color = colorAtPixel(thisPoint); - if (color.isValid ()) - { - auto *cmd = new kpToolColorPickerCommand ( mouseButton (), color, m_oldColor, - environ ()->commandEnvironment ()); + if (color.isValid()) { + auto *cmd = new kpToolColorPickerCommand(mouseButton(), color, m_oldColor, + environ()->commandEnvironment()); - environ ()->commandHistory ()->addCommand (cmd, false/*no exec*/); - setUserMessage (haventBegunDrawUserMessage ()); - } - else - { - cancelShape (); + environ()->commandHistory()->addCommand(cmd, false /*no exec*/); + setUserMessage(haventBegunDrawUserMessage()); + } else { + cancelShape(); } } - - diff --git a/tools/kpToolFloodFill.h b/tools/kpToolFloodFill.h --- a/tools/kpToolFloodFill.h +++ b/tools/kpToolFloodFill.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,36 +24,32 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_FLOOD_FILL_H #define KP_TOOL_FLOOD_FILL_H - #include "tools/kpTool.h" - class kpToolFloodFill : public kpTool { -Q_OBJECT + Q_OBJECT public: kpToolFloodFill (kpToolEnvironment *environ, QObject *parent); ~kpToolFloodFill () override; private: - QString haventBegunDrawUserMessage () const; + QString haventBegunDrawUserMessage() const; public: - void begin () override; - void beginDraw () override; - void draw (const QPoint &thisPoint, const QPoint &, const QRect &) override; - void cancelShape () override; - void releasedAllButtons () override; - void endDraw (const QPoint &, const QRect &) override; + void begin() override; + void beginDraw() override; + void draw(const QPoint &thisPoint, const QPoint &, const QRect &) override; + void cancelShape() override; + void releasedAllButtons() override; + void endDraw(const QPoint &, const QRect &) override; private: - struct kpToolFloodFillPrivate * const d; + struct kpToolFloodFillPrivate *const d; }; - #endif // KP_TOOL_FLOOD_FILL_H diff --git a/tools/kpToolFloodFill.cpp b/tools/kpToolFloodFill.cpp --- a/tools/kpToolFloodFill.cpp +++ b/tools/kpToolFloodFill.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_FLOOD_FILL 0 - #include "kpToolFloodFill.h" #include "commands/kpCommandHistory.h" @@ -52,10 +49,10 @@ //--------------------------------------------------------------------- kpToolFloodFill::kpToolFloodFill (kpToolEnvironment *environ, QObject *parent) - : kpTool (i18n ("Flood Fill"), i18n ("Fills regions in the image"), - Qt::Key_F, - environ, parent, QStringLiteral("tool_flood_fill")), - d (new kpToolFloodFillPrivate ()) + : kpTool(i18n("Flood Fill"), i18n("Fills regions in the image"), + Qt::Key_F, + environ, parent, QStringLiteral("tool_flood_fill")) + , d(new kpToolFloodFillPrivate()) { d->currentCommand = nullptr; } @@ -70,100 +67,98 @@ //--------------------------------------------------------------------- // private -QString kpToolFloodFill::haventBegunDrawUserMessage () const +QString kpToolFloodFill::haventBegunDrawUserMessage() const { - return i18n ("Click to fill a region."); + return i18n("Click to fill a region."); } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpToolFloodFill::begin () +void kpToolFloodFill::begin() { - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpToolFloodFill::beginDraw () +void kpToolFloodFill::beginDraw() { #if DEBUG_KP_TOOL_FLOOD_FILL && 1 qCDebug(kpLogTools) << "kpToolFloodFill::beginDraw()"; #endif - QApplication::setOverrideCursor (Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); { - environ ()->flashColorSimilarityToolBarItem (); + environ()->flashColorSimilarityToolBarItem(); // Flood Fill is an expensive CPU operation so we only fill at a // mouse click (beginDraw ()), not on mouse move (virtually draw()) - d->currentCommand = new kpToolFloodFillCommand ( - currentPoint ().x (), currentPoint ().y (), - color (mouseButton ()), processedColorSimilarity (), - environ ()->commandEnvironment ()); + d->currentCommand = new kpToolFloodFillCommand( + currentPoint().x(), currentPoint().y(), + color(mouseButton()), processedColorSimilarity(), + environ()->commandEnvironment()); #if DEBUG_KP_TOOL_FLOOD_FILL && 1 qCDebug(kpLogTools) << "\tperforming new-doc-corner-case check"; #endif - if (document ()->url ().isEmpty () && !document ()->isModified ()) - { + if (document()->url().isEmpty() && !document()->isModified()) { // Collect the colour that gets changed before we change the pixels // (execute() below). Needed in unexecute(). - d->currentCommand->prepareColorToChange (); + d->currentCommand->prepareColorToChange(); - d->currentCommand->setFillEntireImage (); + d->currentCommand->setFillEntireImage(); } - d->currentCommand->execute (); + d->currentCommand->execute(); } - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); - setUserMessage (cancelUserMessage ()); + setUserMessage(cancelUserMessage()); } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpToolFloodFill::draw (const QPoint &thisPoint, const QPoint &, const QRect &) +void kpToolFloodFill::draw(const QPoint &thisPoint, const QPoint &, const QRect &) { - setUserShapePoints (thisPoint); + setUserShapePoints(thisPoint); } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpToolFloodFill::cancelShape () +void kpToolFloodFill::cancelShape() { - d->currentCommand->unexecute (); + d->currentCommand->unexecute(); delete d->currentCommand; d->currentCommand = nullptr; - setUserMessage (i18n ("Let go of all the mouse buttons.")); + setUserMessage(i18n("Let go of all the mouse buttons.")); } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpToolFloodFill::releasedAllButtons () +void kpToolFloodFill::releasedAllButtons() { - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpToolFloodFill::endDraw (const QPoint &, const QRect &) +void kpToolFloodFill::endDraw(const QPoint &, const QRect &) { - environ ()->commandHistory ()->addCommand (d->currentCommand, - false/*no exec - we already did it up there*/); + environ()->commandHistory()->addCommand(d->currentCommand, + false /*no exec - we already did it up there*/); // Don't delete - it just got added to the history. d->currentCommand = nullptr; - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- - diff --git a/tools/kpToolPrivate.h b/tools/kpToolPrivate.h --- a/tools/kpToolPrivate.h +++ b/tools/kpToolPrivate.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolPrivate_H #define kpToolPrivate_H - #include #include @@ -42,7 +39,6 @@ class kpToolAction; class kpToolEnvironment; - struct kpToolPrivate { // Initialisation / properties. @@ -63,7 +59,6 @@ kpView *viewUnderStartPoint; - // Set to 2 when the user swaps the foreground and background color. // // When nonzero, it suppresses the foreground and background "color changed" @@ -79,5 +74,4 @@ kpToolEnvironment *environ; }; - #endif // kpToolPrivate_H diff --git a/tools/kpToolZoom.h b/tools/kpToolZoom.h --- a/tools/kpToolZoom.h +++ b/tools/kpToolZoom.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,42 +24,38 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_ZOOM_H #define KP_TOOL_ZOOM_H - #include "tools/kpTool.h" - class kpToolZoom : public kpTool { -Q_OBJECT + Q_OBJECT public: kpToolZoom (kpToolEnvironment *environ, QWidget *parent); ~kpToolZoom () override; - bool returnToPreviousToolAfterEndDraw () const override; + bool returnToPreviousToolAfterEndDraw() const override; private: - QString haventBegunDrawUserMessage () const; + QString haventBegunDrawUserMessage() const; public: - void begin () override; - void end () override; + void begin() override; + void end() override; - void globalDraw () override; + void globalDraw() override; - void beginDraw () override; - void draw (const QPoint &thisPoint, const QPoint &, const QRect &) override; - void cancelShape () override; - void releasedAllButtons () override; - void endDraw (const QPoint &thisPoint, const QRect &) override; + void beginDraw() override; + void draw(const QPoint &thisPoint, const QPoint &, const QRect &) override; + void cancelShape() override; + void releasedAllButtons() override; + void endDraw(const QPoint &thisPoint, const QRect &) override; private: struct kpToolZoomPrivate *d; }; - #endif // KP_TOOL_ZOOM_H diff --git a/tools/kpToolZoom.cpp b/tools/kpToolZoom.cpp --- a/tools/kpToolZoom.cpp +++ b/tools/kpToolZoom.cpp @@ -24,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_ZOOM 0 - #include "kpToolZoom.h" #include "kpDefs.h" @@ -52,33 +50,31 @@ QRect normalizedRect; }; -static void DrawZoomRect (kpImage *destImage, - const QPoint &topLeft, - void *userData) +static void DrawZoomRect(kpImage *destImage, const QPoint &topLeft, void *userData) { - auto *pack = static_cast (userData); + auto *pack = static_cast (userData); kpPixmapFX::drawStippleRect(destImage, - topLeft.x (), topLeft.y (), pack->normalizedRect.width (), pack->normalizedRect.height (), - kpColor::Yellow, - kpColor::Green); + topLeft.x(), topLeft.y(), + pack->normalizedRect.width(), pack->normalizedRect.height(), + kpColor::Yellow, + kpColor::Green); } - struct kpToolZoomPrivate { bool dragHasBegun{}, dragCompleted{}; DrawZoomRectPackage drawPackage; }; kpToolZoom::kpToolZoom (kpToolEnvironment *environ, QWidget *parent) - : kpTool (i18n ("Zoom"), i18n ("Zooms in and out of the image"), - Qt::Key_Z, - environ, parent, QStringLiteral("tool_zoom")), - d (new kpToolZoomPrivate ()) + : kpTool(i18n("Zoom"), i18n("Zooms in and out of the image"), + Qt::Key_Z, + environ, parent, QStringLiteral("tool_zoom")) + , d(new kpToolZoomPrivate()) { - // different from objectName() - action()->setIcon(KDE::icon(QStringLiteral("zoom-original"))); + // different from objectName() + action()->setIcon(KDE::icon(QStringLiteral("zoom-original"))); } //--------------------------------------------------------------------- @@ -91,7 +87,7 @@ //--------------------------------------------------------------------- // public virtual [base kpTool] -bool kpToolZoom::returnToPreviousToolAfterEndDraw () const +bool kpToolZoom::returnToPreviousToolAfterEndDraw() const { // If the user clicks to zoom in or out, s/he generally wants to click // some more to get the exact zoom level wanted. @@ -112,144 +108,133 @@ return d->dragCompleted; } - // private -QString kpToolZoom::haventBegunDrawUserMessage () const +QString kpToolZoom::haventBegunDrawUserMessage() const { - return i18n ("Click to zoom in/out or left drag to zoom into a specific area."); + return i18n("Click to zoom in/out or left drag to zoom into a specific area."); } - // public virtual [base kpTool] -void kpToolZoom::begin () +void kpToolZoom::begin() { - viewManager ()->setCursor (Qt::CrossCursor); + viewManager()->setCursor(Qt::CrossCursor); - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } // public virtual [base kpTool] -void kpToolZoom::end () +void kpToolZoom::end() { - viewManager ()->unsetCursor (); + viewManager()->unsetCursor(); } - // public virtual [base kpTool] -void kpToolZoom::globalDraw () +void kpToolZoom::globalDraw() { #if DEBUG_KP_TOOL_ZOOM qCDebug(kpLogTools) << "CALL"; #endif - environ ()->fitToPage (); + environ()->fitToPage(); } - // public virtual [base kpTool] -void kpToolZoom::beginDraw () +void kpToolZoom::beginDraw() { d->dragHasBegun = false; d->dragCompleted = false; - setUserMessage (cancelUserMessage ()); + setUserMessage(cancelUserMessage()); } // public virtual [base kpTool] -void kpToolZoom::draw (const QPoint &thisPoint, const QPoint &, const QRect &normalizedRect) +void kpToolZoom::draw(const QPoint &thisPoint, const QPoint &, const QRect &normalizedRect) { #if DEBUG_KP_TOOL_ZOOM - qCDebug(kpLogTools) << "kpToomZoom::draw() currentPoint=" << currentPoint () - << " lastPoint=" << lastPoint () - << endl; + qCDebug(kpLogTools) << "kpToomZoom::draw() currentPoint=" << currentPoint() + << " lastPoint=" << lastPoint() + << endl; #endif // TODO: Need accidental drag detection from selection tool (when dragging // out new selection) - if (!d->dragHasBegun) - { - if (thisPoint == startPoint ()) { + if (!d->dragHasBegun) { + if (thisPoint == startPoint()) { return; } // Left mouse drags select an area to zoom into. // However, it wouldn't make sense to select an area to "zoom out of" // (using the right mouse button). Therefore, make RMB drags do the // same as RMB clicks i.e. a simple zoom out, with no "area" to worry // about. - if (mouseButton () == 1/*RMB*/) { + if (mouseButton() == 1 /*RMB*/) { return; } d->dragHasBegun = true; } - d->drawPackage.normalizedRect = normalizedRect; - kpTempImage newTempImage (false/*always display*/, - normalizedRect.topLeft (), - &::DrawZoomRect, &d->drawPackage, - normalizedRect.width (), normalizedRect.height ()); + kpTempImage newTempImage(false /*always display*/, + normalizedRect.topLeft(), + &::DrawZoomRect, &d->drawPackage, + normalizedRect.width(), normalizedRect.height()); - viewManager ()->setFastUpdates (); + viewManager()->setFastUpdates(); { - viewManager ()->setTempImage (newTempImage); + viewManager()->setTempImage(newTempImage); } - viewManager ()->restoreFastUpdates (); + viewManager()->restoreFastUpdates(); } // public virtual [base kpTool] -void kpToolZoom::cancelShape () +void kpToolZoom::cancelShape() { - viewManager ()->invalidateTempImage (); + viewManager()->invalidateTempImage(); // LOREFACTOR: A lot of tools use this - push up to kpTool? - setUserMessage (i18n ("Let go of all the mouse buttons.")); + setUserMessage(i18n("Let go of all the mouse buttons.")); } // public virtual [base kpTool] -void kpToolZoom::releasedAllButtons () +void kpToolZoom::releasedAllButtons() { - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } // public virtual [base kpTool] -void kpToolZoom::endDraw (const QPoint &, const QRect &normalizedRect) +void kpToolZoom::endDraw(const QPoint &, const QRect &normalizedRect) { #if DEBUG_KP_TOOL_ZOOM qCDebug(kpLogTools) << "kpToolZoom::endDraw(rect=" << normalizedRect << ")" - << " dragHasBegun=" << d->dragHasBegun << endl; + << " dragHasBegun=" << d->dragHasBegun << endl; #endif // TODO: This cursor doesn't stay on for long enough because zooming uses // event loop tricks. - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); - viewManager ()->invalidateTempImage (); + viewManager()->invalidateTempImage(); // Click? - if (!d->dragHasBegun) - { - if (mouseButton () == 0/*LMB*/) { - environ ()->zoomIn (true/*center under cursor*/); - } - else { - environ ()->zoomOut (false/*don't center under cursor - as is + if (!d->dragHasBegun) { + if (mouseButton() == 0 /*LMB*/) { + environ()->zoomIn(true /*center under cursor*/); + } else { + environ()->zoomOut(false/*don't center under cursor - as is confusing behaviour when zooming out*/); } } // Drag? - else if (normalizedRect.isValid()) - { - environ ()->zoomToRect ( + else if (normalizedRect.isValid()) { + environ()->zoomToRect( normalizedRect, - false/*don't account for grips*/, - true/*care about width*/, true/*care about height*/); + false /*don't account for grips*/, + true /*care about width*/, true /*care about height*/); d->dragCompleted = true; } } - - diff --git a/tools/kpTool_Drawing.cpp b/tools/kpTool_Drawing.cpp --- a/tools/kpTool_Drawing.cpp +++ b/tools/kpTool_Drawing.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -29,10 +28,8 @@ // Tool methods for drawing shapes (subclasses reimplement most of these). // - #define DEBUG_KP_TOOL 0 - #include "tools/kpTool.h" #include "kpToolPrivate.h" @@ -50,46 +47,45 @@ //--------------------------------------------------------------------- // protected -int kpTool::mouseButton () const +int kpTool::mouseButton() const { return d->mouseButton; } //--------------------------------------------------------------------- // protected -bool kpTool::shiftPressed () const +bool kpTool::shiftPressed() const { return d->shiftPressed; } //--------------------------------------------------------------------- // protected -bool kpTool::controlPressed () const +bool kpTool::controlPressed() const { return d->controlPressed; } //--------------------------------------------------------------------- // protected -bool kpTool::altPressed () const +bool kpTool::altPressed() const { return d->altPressed; } - // protected -QPoint kpTool::startPoint () const +QPoint kpTool::startPoint() const { return d->startPoint; } //--------------------------------------------------------------------- // protected -QPoint kpTool::currentPoint () const +QPoint kpTool::currentPoint() const { // TODO: Q_ASSERT (hasBegun()) and similar in other accessors. // We currently violate these kinds of invariants. @@ -99,75 +95,73 @@ //--------------------------------------------------------------------- // protected -QPoint kpTool::currentViewPoint () const +QPoint kpTool::currentViewPoint() const { return d->currentViewPoint; } //--------------------------------------------------------------------- // protected -QRect kpTool::normalizedRect () const +QRect kpTool::normalizedRect() const { return kpPainter::normalizedRect(d->startPoint, d->currentPoint); } //--------------------------------------------------------------------- // protected -QPoint kpTool::lastPoint () const +QPoint kpTool::lastPoint() const { return d->lastPoint; } //--------------------------------------------------------------------- // protected -kpView *kpTool::viewUnderStartPoint () const +kpView *kpTool::viewUnderStartPoint() const { return d->viewUnderStartPoint; } //--------------------------------------------------------------------- // protected -kpView *kpTool::viewUnderCursor () const +kpView *kpTool::viewUnderCursor() const { - kpViewManager *vm = viewManager (); - return vm ? vm->viewUnderCursor () : nullptr; + kpViewManager *vm = viewManager(); + return vm ? vm->viewUnderCursor() : nullptr; } //--------------------------------------------------------------------- -void kpTool::beginInternal () +void kpTool::beginInternal() { #if DEBUG_KP_TOOL qCDebug(kpLogTools) << "kpTool::beginInternal()"; #endif - if (!d->began) - { + if (!d->began) { // clear leftover statusbar messages - setUserMessage (); - d->currentPoint = calculateCurrentPoint (); - d->currentViewPoint = calculateCurrentPoint (false/*view point*/); - setUserShapePoints (d->currentPoint); + setUserMessage(); + d->currentPoint = calculateCurrentPoint(); + d->currentViewPoint = calculateCurrentPoint(false /*view point*/); + setUserShapePoints(d->currentPoint); // TODO: Audit all the code in this file - states like "d->began" & // "d->beganDraw" should be set before calling user func. // Also, d->currentPoint should be more frequently initialised. // call user virtual func - begin (); + begin(); // we've starting using the tool... d->began = true; // but we haven't started drawing with it d->beganDraw = false; - - uint keyState = QApplication::keyboardModifiers (); + uint keyState = QApplication::keyboardModifiers(); d->shiftPressed = (keyState & Qt::ShiftModifier); d->controlPressed = (keyState & Qt::ControlModifier); @@ -181,36 +175,35 @@ //--------------------------------------------------------------------- -void kpTool::endInternal () +void kpTool::endInternal() { - if (d->began) - { + if (d->began) { // before we can stop using the tool, we must stop the current drawing operation (if any) - if (hasBegunShape ()) { - endShapeInternal (d->currentPoint, normalizedRect ()); + if (hasBegunShape()) { + endShapeInternal(d->currentPoint, normalizedRect()); } // call user virtual func - end (); + end(); // clear leftover statusbar messages - setUserMessage (); - setUserShapePoints (calculateCurrentPoint ()); + setUserMessage(); + setUserShapePoints(calculateCurrentPoint()); // we've stopped using the tool... d->began = false; // and so we can't be drawing with it d->beganDraw = false; - d->environ->hideAllToolWidgets (); + d->environ->hideAllToolWidgets(); } } //--------------------------------------------------------------------- // virtual -void kpTool::begin () +void kpTool::begin() { #if DEBUG_KP_TOOL qCDebug(kpLogTools) << "kpTool::begin() base implementation"; @@ -220,203 +213,197 @@ //--------------------------------------------------------------------- // virtual -void kpTool::end () +void kpTool::end() { #if DEBUG_KP_TOOL qCDebug(kpLogTools) << "kpTool::end() base implementation"; #endif } //--------------------------------------------------------------------- - -bool kpTool::hasBegun () const { return d->began; } +bool kpTool::hasBegun() const +{ + return d->began; +} //--------------------------------------------------------------------- -bool kpTool::hasBegunDraw () const { return d->beganDraw; } +bool kpTool::hasBegunDraw() const +{ + return d->beganDraw; +} //--------------------------------------------------------------------- // virtual -bool kpTool::hasBegunShape () const { return hasBegunDraw (); } +bool kpTool::hasBegunShape() const +{ + return hasBegunDraw(); +} //--------------------------------------------------------------------- - -void kpTool::beginDrawInternal () +void kpTool::beginDrawInternal() { - if (!d->beganDraw) - { - beginDraw (); + if (!d->beganDraw) { + beginDraw(); d->beganDraw = true; - emit beganDraw (d->currentPoint); + emit beganDraw(d->currentPoint); } } //--------------------------------------------------------------------- // virtual -void kpTool::beginDraw () +void kpTool::beginDraw() { } //--------------------------------------------------------------------- // virtual -void kpTool::hover (const QPoint &point) +void kpTool::hover(const QPoint &point) { #if DEBUG_KP_TOOL qCDebug(kpLogTools) << "kpTool::hover" << point - << " base implementation"; + << " base implementation"; #endif - setUserShapePoints (point); + setUserShapePoints(point); } //--------------------------------------------------------------------- // virtual -void kpTool::globalDraw () +void kpTool::globalDraw() { } //--------------------------------------------------------------------- // virtual -void kpTool::reselect () +void kpTool::reselect() { #if DEBUG_KP_TOOL qCDebug(kpLogTools) << "kpTool::reselect() base implementation"; #endif } //--------------------------------------------------------------------- - // virtual -void kpTool::draw (const QPoint &, const QPoint &, const QRect &) +void kpTool::draw(const QPoint &, const QPoint &, const QRect &) { } //--------------------------------------------------------------------- // private -void kpTool::drawInternal () +void kpTool::drawInternal() { - draw (d->currentPoint, d->lastPoint, normalizedRect ()); + draw(d->currentPoint, d->lastPoint, normalizedRect()); } //--------------------------------------------------------------------- - // also called by kpView -void kpTool::cancelShapeInternal () +void kpTool::cancelShapeInternal() { - if (hasBegunShape ()) - { + if (hasBegunShape()) { d->beganDraw = false; - cancelShape (); + cancelShape(); d->viewUnderStartPoint = nullptr; - emit cancelledShape (viewUnderCursor () ? d->currentPoint : KP_INVALID_POINT); + emit cancelledShape(viewUnderCursor() ? d->currentPoint : KP_INVALID_POINT); - if (viewUnderCursor ()) { - hover (d->currentPoint); - } - else - { + if (viewUnderCursor()) { + hover(d->currentPoint); + } else { d->currentPoint = KP_INVALID_POINT; d->currentViewPoint = KP_INVALID_POINT; - hover (d->currentPoint); + hover(d->currentPoint); } - if (returnToPreviousToolAfterEndDraw ()) - { - d->environ->selectPreviousTool (); + if (returnToPreviousToolAfterEndDraw()) { + d->environ->selectPreviousTool(); } } } //--------------------------------------------------------------------- // virtual -void kpTool::cancelShape () +void kpTool::cancelShape() { - qCWarning(kpLogTools) << "Tool cannot cancel operation!" ; + qCWarning(kpLogTools) << "Tool cannot cancel operation!"; } //--------------------------------------------------------------------- -void kpTool::releasedAllButtons () +void kpTool::releasedAllButtons() { } //--------------------------------------------------------------------- -void kpTool::endDrawInternal (const QPoint &thisPoint, const QRect &normalizedRect, - bool wantEndShape) +void kpTool::endDrawInternal(const QPoint &thisPoint, const QRect &normalizedRect, + bool wantEndShape) { #if DEBUG_KP_TOOL && 1 qCDebug(kpLogTools) << "kpTool::endDrawInternal() wantEndShape=" << wantEndShape; #endif - if (wantEndShape && !hasBegunShape ()) { + if (wantEndShape && !hasBegunShape()) { return; } - if (!wantEndShape && !hasBegunDraw ()) { + if (!wantEndShape && !hasBegunDraw()) { return; } d->beganDraw = false; - if (wantEndShape) - { + if (wantEndShape) { #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "\tcalling endShape()"; #endif - endShape (thisPoint, normalizedRect); - } - else - { + endShape(thisPoint, normalizedRect); + } else { #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "\tcalling endDraw()"; #endif - endDraw (thisPoint, normalizedRect); + endDraw(thisPoint, normalizedRect); } d->viewUnderStartPoint = nullptr; - emit endedDraw (d->currentPoint); - if (viewUnderCursor ()) { - hover (d->currentPoint); - } - else - { + emit endedDraw(d->currentPoint); + if (viewUnderCursor()) { + hover(d->currentPoint); + } else { d->currentPoint = KP_INVALID_POINT; d->currentViewPoint = KP_INVALID_POINT; - hover (d->currentPoint); + hover(d->currentPoint); } - if (returnToPreviousToolAfterEndDraw ()) - { - d->environ->selectPreviousTool (); + if (returnToPreviousToolAfterEndDraw()) { + d->environ->selectPreviousTool(); } } //--------------------------------------------------------------------- // private -void kpTool::endShapeInternal (const QPoint &thisPoint, const QRect &normalizedRect) +void kpTool::endShapeInternal(const QPoint &thisPoint, const QRect &normalizedRect) { - endDrawInternal (thisPoint, normalizedRect, true/*end shape*/); + endDrawInternal(thisPoint, normalizedRect, true /*end shape*/); } //--------------------------------------------------------------------- // virtual -void kpTool::endDraw (const QPoint &, const QRect &) +void kpTool::endDraw(const QPoint &, const QRect &) { } diff --git a/tools/kpTool_KeyboardEvents.cpp b/tools/kpTool_KeyboardEvents.cpp --- a/tools/kpTool_KeyboardEvents.cpp +++ b/tools/kpTool_KeyboardEvents.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -29,10 +28,8 @@ // Tool reaction to view keyboard input. // - #define DEBUG_KP_TOOL 0 - // TODO: reduce number of includes #include "tools/kpTool.h" #include "kpToolPrivate.h" @@ -60,54 +57,72 @@ //--------------------------------------------------------------------- -void kpTool::seeIfAndHandleModifierKey (QKeyEvent *e) +void kpTool::seeIfAndHandleModifierKey(QKeyEvent *e) { - switch (e->key ()) - { + switch (e->key()) { case 0: case Qt::Key_unknown: #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "kpTool::seeIfAndHandleModifierKey() picked up unknown key!"; #endif - // HACK: around Qt bug: if you hold a modifier before you start the - // program and then release it over the view, - // Qt reports it as the release of an unknown key - // Qt4 update: I don't think this happens anymore... - // --- fall thru and update all modifiers --- + // HACK: around Qt bug: if you hold a modifier before you start the + // program and then release it over the view, + // Qt reports it as the release of an unknown key + // Qt4 update: I don't think this happens anymore... + // --- fall thru and update all modifiers --- case Qt::Key_Alt: case Qt::Key_Shift: case Qt::Key_Control: #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "kpTool::setIfAndHandleModifierKey() accepting"; #endif - keyUpdateModifierState (e); + keyUpdateModifierState(e); - e->accept (); + e->accept(); break; } } //--------------------------------------------------------------------- // Returns in and the direction the arrow key "e->key()" is // pointing in or (0,0) if it's not a recognised arrow key. -void kpTool::arrowKeyPressDirection (const QKeyEvent *e, int *dx, int *dy) +void kpTool::arrowKeyPressDirection(const QKeyEvent *e, int *dx, int *dy) { int dxLocal = 0, dyLocal = 0; - switch (e->key ()) - { - case Qt::Key_Home: dxLocal = -1; dyLocal = -1; break; - case Qt::Key_Up: dyLocal = -1; break; - case Qt::Key_PageUp: dxLocal = +1; dyLocal = -1; break; + switch (e->key()) { + case Qt::Key_Home: + dxLocal = -1; + dyLocal = -1; + break; + case Qt::Key_Up: + dyLocal = -1; + break; + case Qt::Key_PageUp: + dxLocal = +1; + dyLocal = -1; + break; - case Qt::Key_Left: dxLocal = -1; break; - case Qt::Key_Right: dxLocal = +1; break; + case Qt::Key_Left: + dxLocal = -1; + break; + case Qt::Key_Right: + dxLocal = +1; + break; - case Qt::Key_End: dxLocal = -1; dyLocal = +1; break; - case Qt::Key_Down: dyLocal = +1; break; - case Qt::Key_PageDown: dxLocal = +1; dyLocal = +1; break; + case Qt::Key_End: + dxLocal = -1; + dyLocal = +1; + break; + case Qt::Key_Down: + dyLocal = +1; + break; + case Qt::Key_PageDown: + dxLocal = +1; + dyLocal = +1; + break; } if (dx) { @@ -120,312 +135,293 @@ //--------------------------------------------------------------------- -void kpTool::seeIfAndHandleArrowKeyPress (QKeyEvent *e) +void kpTool::seeIfAndHandleArrowKeyPress(QKeyEvent *e) { int dx, dy; - arrowKeyPressDirection (e, &dx, &dy); + arrowKeyPressDirection(e, &dx, &dy); if (dx == 0 && dy == 0) { return; } - - kpView * const view = viewUnderCursor (); + kpView *const view = viewUnderCursor(); if (!view) { return; } - - const QPoint oldPoint = view->mapFromGlobal (QCursor::pos ()); + const QPoint oldPoint = view->mapFromGlobal(QCursor::pos()); #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "\toldPoint=" << oldPoint - << " dx=" << dx << " dy=" << dy << endl; + << " dx=" << dx << " dy=" << dy << endl; #endif + const int viewIncX = (dx ? qMax(1, view->zoomLevelX() / 100) * dx : 0); + const int viewIncY = (dy ? qMax(1, view->zoomLevelY() / 100) * dy : 0); - const int viewIncX = (dx ? qMax (1, view->zoomLevelX () / 100) * dx : 0); - const int viewIncY = (dy ? qMax (1, view->zoomLevelY () / 100) * dy : 0); - - int newViewX = oldPoint.x () + viewIncX; - int newViewY = oldPoint.y () + viewIncY; - + int newViewX = oldPoint.x() + viewIncX; + int newViewY = oldPoint.y() + viewIncY; #if DEBUG_KP_TOOL && 0 - qCDebug(kpLogTools) << "\tnewPoint=" << QPoint (newViewX, newViewY); + qCDebug(kpLogTools) << "\tnewPoint=" << QPoint(newViewX, newViewY); #endif // Make sure we really moved at least one doc point (needed due to // rounding error). - if (view->transformViewToDoc (QPoint (newViewX, newViewY)) == - view->transformViewToDoc (oldPoint)) - { + if (view->transformViewToDoc(QPoint(newViewX, newViewY)) + == view->transformViewToDoc(oldPoint)) { newViewX += viewIncX; newViewY += viewIncY; #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "\tneed adjust for doc - newPoint=" - << QPoint (newViewX, newViewY) << endl; + << QPoint(newViewX, newViewY) << endl; #endif } - // TODO: visible width/height (e.g. with scrollbars) - const int x = qMin (qMax (newViewX, 0), view->width () - 1); - const int y = qMin (qMax (newViewY, 0), view->height () - 1); + const int x = qMin(qMax(newViewX, 0), view->width() - 1); + const int y = qMin(qMax(newViewY, 0), view->height() - 1); // QCursor::setPos conveniently causes mouseMoveEvents - QCursor::setPos (view->mapToGlobal (QPoint (x, y))); - e->accept (); + QCursor::setPos(view->mapToGlobal(QPoint(x, y))); + e->accept(); } //--------------------------------------------------------------------- -bool kpTool::isDrawKey (int key) +bool kpTool::isDrawKey(int key) { - return (key == Qt::Key_Enter || - key == Qt::Key_Return || - key == Qt::Key_Insert || - key == Qt::Key_Clear/*Numpad 5 Key*/ || - key == Qt::Key_L); + return key == Qt::Key_Enter + || key == Qt::Key_Return + || key == Qt::Key_Insert + || key == Qt::Key_Clear/*Numpad 5 Key*/ + || key == Qt::Key_L; } //--------------------------------------------------------------------- -void kpTool::seeIfAndHandleBeginDrawKeyPress (QKeyEvent *e) +void kpTool::seeIfAndHandleBeginDrawKeyPress(QKeyEvent *e) { - if (e->isAutoRepeat ()) { + if (e->isAutoRepeat()) { return; } - if (!isDrawKey (e->key ())) { + if (!isDrawKey(e->key())) { return; } #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "kpTool::seeIfAndHandleBeginDrawKeyPress() accept"; #endif - // TODO: wrong for dragging lines outside of view (for e.g.) - kpView * const view = viewUnderCursor (); + kpView *const view = viewUnderCursor(); if (!view) { return; } - // TODO: what about the modifiers? - QMouseEvent me (QEvent::MouseButtonPress, - view->mapFromGlobal (QCursor::pos ()), - Qt::LeftButton, - Qt::LeftButton/*button state after event*/, - Qt::NoModifier); - mousePressEvent (&me); - e->accept (); + QMouseEvent me(QEvent::MouseButtonPress, + view->mapFromGlobal(QCursor::pos()), + Qt::LeftButton, + Qt::LeftButton /*button state after event*/, + Qt::NoModifier); + mousePressEvent(&me); + e->accept(); } -void kpTool::seeIfAndHandleEndDrawKeyPress (QKeyEvent *e) +void kpTool::seeIfAndHandleEndDrawKeyPress(QKeyEvent *e) { #if DEBUG_KP_TOOL && 0 - qCDebug(kpLogTools) << "kpTool::setIfAndHandleEndDrawKeyPress() key=" << e->key () - << " isAutoRepeat=" << e->isAutoRepeat () - << " isDrawKey=" << isDrawKey (e->key ()) - << " view=" << viewUnderCursor () - << endl; + qCDebug(kpLogTools) << "kpTool::setIfAndHandleEndDrawKeyPress() key=" << e->key() + << " isAutoRepeat=" << e->isAutoRepeat() + << " isDrawKey=" << isDrawKey(e->key()) + << " view=" << viewUnderCursor() + << endl; #endif - if (e->isAutoRepeat ()) { + if (e->isAutoRepeat()) { return; } - if (!isDrawKey (e->key ())) { + if (!isDrawKey(e->key())) { return; } #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "kpTool::seeIfAndHandleEndDrawKeyPress() accept"; #endif - - kpView * const view = viewUnderCursor (); + kpView *const view = viewUnderCursor(); if (!view) { return; } - // TODO: what about the modifiers? - QMouseEvent me (QEvent::MouseButtonRelease, - view->mapFromGlobal (QCursor::pos ()), - Qt::LeftButton, - Qt::NoButton/*button state after event*/, - Qt::NoModifier); - mouseReleaseEvent (&me); - - e->accept (); + QMouseEvent me(QEvent::MouseButtonRelease, + view->mapFromGlobal(QCursor::pos()), + Qt::LeftButton, + Qt::NoButton /*button state after event*/, + Qt::NoModifier); + mouseReleaseEvent(&me); + + e->accept(); } //--------------------------------------------------------------------- -void kpTool::keyPressEvent (QKeyEvent *e) +void kpTool::keyPressEvent(QKeyEvent *e) { #if DEBUG_KP_TOOL && 0 - qCDebug(kpLogTools) << "kpTool::keyPressEvent() key=" << (int *) e->key () - << " stateAfter: modifiers=" << (int *) (int) e->modifiers () - << " isAutoRep=" << e->isAutoRepeat (); + qCDebug(kpLogTools) << "kpTool::keyPressEvent() key=" << (int *)e->key() + << " stateAfter: modifiers=" << (int *)(int)e->modifiers() + << " isAutoRep=" << e->isAutoRepeat(); #endif - e->ignore (); - + e->ignore(); - seeIfAndHandleModifierKey (e); - if (e->isAccepted ()) { + seeIfAndHandleModifierKey(e); + if (e->isAccepted()) { return; } - seeIfAndHandleArrowKeyPress (e); - if (e->isAccepted ()) { + seeIfAndHandleArrowKeyPress(e); + if (e->isAccepted()) { return; } - seeIfAndHandleBeginDrawKeyPress (e); - if (e->isAccepted ()) { + seeIfAndHandleBeginDrawKeyPress(e); + if (e->isAccepted()) { return; } - - switch (e->key ()) - { + switch (e->key()) { case Qt::Key_Delete: - d->environ->deleteSelection (); + d->environ->deleteSelection(); break; case Qt::Key_Escape: - if (hasBegunDraw ()) - { - cancelShapeInternal (); - e->accept (); + if (hasBegunDraw()) { + cancelShapeInternal(); + e->accept(); } break; } } //--------------------------------------------------------------------- -void kpTool::keyReleaseEvent (QKeyEvent *e) +void kpTool::keyReleaseEvent(QKeyEvent *e) { #if DEBUG_KP_TOOL && 0 - qCDebug(kpLogTools) << "kpTool::keyReleaseEvent() key=" << (int *) e->key () - << " stateAfter: modifiers=" << (int *) (int) e->modifiers () - << " isAutoRep=" << e->isAutoRepeat (); + qCDebug(kpLogTools) << "kpTool::keyReleaseEvent() key=" << (int *)e->key() + << " stateAfter: modifiers=" << (int *)(int)e->modifiers() + << " isAutoRep=" << e->isAutoRepeat(); #endif - e->ignore (); + e->ignore(); - seeIfAndHandleModifierKey (e); - if (e->isAccepted ()) { + seeIfAndHandleModifierKey(e); + if (e->isAccepted()) { return; } - seeIfAndHandleEndDrawKeyPress (e); - if (e->isAccepted ()) { + seeIfAndHandleEndDrawKeyPress(e); + if (e->isAccepted()) { return; } } //--------------------------------------------------------------------- // private -void kpTool::keyUpdateModifierState (QKeyEvent *e) +void kpTool::keyUpdateModifierState(QKeyEvent *e) { #if DEBUG_KP_TOOL && 0 - qCDebug(kpLogTools) << "kpTool::keyUpdateModifierState() e->key=" << (int *) e->key (); + qCDebug(kpLogTools) << "kpTool::keyUpdateModifierState() e->key=" << (int *)e->key(); qCDebug(kpLogTools) << "\tshift=" - << (e->modifiers () & Qt::ShiftModifier) - << " control=" - << (e->modifiers () & Qt::ControlModifier) - << " alt=" - << (e->modifiers () & Qt::AltModifier) - << endl; + << (e->modifiers() & Qt::ShiftModifier) + << " control=" + << (e->modifiers() & Qt::ControlModifier) + << " alt=" + << (e->modifiers() & Qt::AltModifier) + << endl; #endif - if (e->key () & (Qt::Key_Alt | Qt::Key_Shift | Qt::Key_Control)) - { + if (e->key() & (Qt::Key_Alt | Qt::Key_Shift | Qt::Key_Control)) { #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "\t\tmodifier changed - use e's claims"; #endif - setShiftPressed (e->modifiers () & Qt::ShiftModifier); - setControlPressed (e->modifiers () & Qt::ControlModifier); - setAltPressed (e->modifiers () & Qt::AltModifier); + setShiftPressed(e->modifiers() & Qt::ShiftModifier); + setControlPressed(e->modifiers() & Qt::ControlModifier); + setAltPressed(e->modifiers() & Qt::AltModifier); } // See seeIfAndHandleModifierKey() for why this code path exists. - else - { + else { #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "\t\tmodifiers not changed - figure out the truth"; #endif - const Qt::KeyboardModifiers keyState = QApplication::keyboardModifiers (); + const Qt::KeyboardModifiers keyState = QApplication::keyboardModifiers(); - setShiftPressed (keyState & Qt::ShiftModifier); - setControlPressed (keyState & Qt::ControlModifier); - setAltPressed (keyState & Qt::AltModifier); + setShiftPressed(keyState & Qt::ShiftModifier); + setControlPressed(keyState & Qt::ControlModifier); + setAltPressed(keyState & Qt::AltModifier); } } //--------------------------------------------------------------------- -void kpTool::notifyModifierStateChanged () +void kpTool::notifyModifierStateChanged() { - if (careAboutModifierState ()) - { + if (careAboutModifierState()) { if (d->beganDraw) { - draw (d->currentPoint, d->lastPoint, normalizedRect ()); - } - else - { - d->currentPoint = calculateCurrentPoint (); - d->currentViewPoint = calculateCurrentPoint (false/*view point*/); - hover (d->currentPoint); + draw(d->currentPoint, d->lastPoint, normalizedRect()); + } else { + d->currentPoint = calculateCurrentPoint(); + d->currentViewPoint = calculateCurrentPoint(false /*view point*/); + hover(d->currentPoint); } } } //--------------------------------------------------------------------- -void kpTool::setShiftPressed (bool pressed) +void kpTool::setShiftPressed(bool pressed) { if (pressed == d->shiftPressed) { return; } d->shiftPressed = pressed; - notifyModifierStateChanged (); + notifyModifierStateChanged(); } //--------------------------------------------------------------------- -void kpTool::setControlPressed (bool pressed) +void kpTool::setControlPressed(bool pressed) { if (pressed == d->controlPressed) { return; } d->controlPressed = pressed; - notifyModifierStateChanged (); + notifyModifierStateChanged(); } //--------------------------------------------------------------------- -void kpTool::setAltPressed (bool pressed) +void kpTool::setAltPressed(bool pressed) { if (pressed == d->altPressed) { return; } d->altPressed = pressed; - notifyModifierStateChanged (); + notifyModifierStateChanged(); } //--------------------------------------------------------------------- diff --git a/tools/kpTool_MouseEvents.cpp b/tools/kpTool_MouseEvents.cpp --- a/tools/kpTool_MouseEvents.cpp +++ b/tools/kpTool_MouseEvents.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -57,102 +56,96 @@ // It is somewhat hard to reproduce so the best way is to position the // mouse close to an edge of the view. If you do it right, no mouseMoveEvent // is generated at _all_, until you move it back into the view. -void kpTool::mousePressEvent (QMouseEvent *e) +void kpTool::mousePressEvent(QMouseEvent *e) { #if DEBUG_KP_TOOL && 1 - qCDebug(kpLogTools) << "kpTool::mousePressEvent pos=" << e->pos () - << " button=" << (int) e->button () - << " stateAfter: buttons=" << (int *) (int) e->buttons () - << " modifiers=" << (int *) (int) e->modifiers () - << " beganDraw=" << d->beganDraw << endl; + qCDebug(kpLogTools) << "kpTool::mousePressEvent pos=" << e->pos() + << " button=" << (int)e->button() + << " stateAfter: buttons=" << (int *)(int)e->buttons() + << " modifiers=" << (int *)(int)e->modifiers() + << " beganDraw=" << d->beganDraw << endl; #endif - if (e->button () == Qt::MidButton) - { - const QString text = QApplication::clipboard ()->text (QClipboard::Selection); + if (e->button() == Qt::MidButton) { + const QString text = QApplication::clipboard()->text(QClipboard::Selection); #if DEBUG_KP_TOOL && 1 qCDebug(kpLogTools) << "\tMMB pasteText='" << text << "'"; #endif - if (!text.isEmpty ()) - { - if (hasBegunShape ()) - { + if (!text.isEmpty()) { + if (hasBegunShape()) { #if DEBUG_KP_TOOL && 1 qCDebug(kpLogTools) << "\t\thasBegunShape - end"; #endif - endShapeInternal (d->currentPoint, normalizedRect ()); + endShapeInternal(d->currentPoint, normalizedRect()); } - if (viewUnderCursor ()) - { - d->environ->pasteTextAt (text, - viewUnderCursor ()->transformViewToDoc (e->pos ()), - true/*adjust topLeft so that cursor isn't + if (viewUnderCursor()) { + d->environ->pasteTextAt(text, + viewUnderCursor()->transformViewToDoc(e->pos()), + true/*adjust topLeft so that cursor isn't on top of resize handle*/); } return; } } - int mb = mouseButton (e->buttons ()); + int mb = mouseButton(e->buttons()); #if DEBUG_KP_TOOL && 1 qCDebug(kpLogTools) << "\tmb=" << mb << " d->beganDraw=" << d->beganDraw; #endif - if (mb == -1 && !d->beganDraw) - { + if (mb == -1 && !d->beganDraw) { // Ignore mouse press. return; } - if (d->beganDraw) - { - if (mb == -1 || mb != d->mouseButton) - { + if (d->beganDraw) { + if (mb == -1 || mb != d->mouseButton) { #if DEBUG_KP_TOOL && 1 - qCDebug(kpLogTools) << "\tCancelling operation as " << mb << " == -1 or != " << d->mouseButton; + qCDebug(kpLogTools) << "\tCancelling operation as " << mb << " == -1 or != " + << d->mouseButton; #endif - kpView *view = viewUnderStartPoint (); - Q_ASSERT (view); + kpView *view = viewUnderStartPoint(); + Q_ASSERT(view); // if we get a mousePressEvent when we're drawing, then the other // mouse button must have been pressed - d->currentPoint = view->transformViewToDoc (e->pos ()); - d->currentViewPoint = e->pos (); - cancelShapeInternal (); + d->currentPoint = view->transformViewToDoc(e->pos()); + d->currentViewPoint = e->pos(); + cancelShapeInternal(); } return; } - kpView *view = viewUnderCursor (); - Q_ASSERT (view); + kpView *view = viewUnderCursor(); + Q_ASSERT(view); #if DEBUG_KP_TOOL && 1 if (view) { - qCDebug(kpLogTools) << "\tview=" << view->objectName (); + qCDebug(kpLogTools) << "\tview=" << view->objectName(); } #endif // let user know what mouse button is being used for entire draw - d->mouseButton = mouseButton (e->buttons ()); - d->shiftPressed = (e->modifiers () & Qt::ShiftModifier); - d->controlPressed = (e->modifiers () & Qt::ControlModifier); - d->altPressed = (e->modifiers () & Qt::AltModifier); - d->startPoint = d->currentPoint = view->transformViewToDoc (e->pos ()); - d->currentViewPoint = e->pos (); + d->mouseButton = mouseButton(e->buttons()); + d->shiftPressed = (e->modifiers() & Qt::ShiftModifier); + d->controlPressed = (e->modifiers() & Qt::ControlModifier); + d->altPressed = (e->modifiers() & Qt::AltModifier); + d->startPoint = d->currentPoint = view->transformViewToDoc(e->pos()); + d->currentViewPoint = e->pos(); d->viewUnderStartPoint = view; - d->lastPoint = QPoint (-1, -1); + d->lastPoint = QPoint(-1, -1); #if DEBUG_KP_TOOL && 1 qCDebug(kpLogTools) << "\tBeginning draw @ " << d->currentPoint; #endif - beginDrawInternal (); + beginDrawInternal(); - draw (d->currentPoint, d->lastPoint, QRect (d->currentPoint, d->currentPoint)); + draw(d->currentPoint, d->lastPoint, QRect(d->currentPoint, d->currentPoint)); d->lastPoint = d->currentPoint; } @@ -167,170 +160,158 @@ // point changes, not just document points, since the selection resize // handles may be smaller than document points. Also, I wonder if // selections' accidental drag detection feature cares? -void kpTool::mouseMoveEvent (QMouseEvent *e) +void kpTool::mouseMoveEvent(QMouseEvent *e) { #if DEBUG_KP_TOOL && 0 - qCDebug(kpLogTools) << "kpTool::mouseMoveEvent pos=" << e->pos () - << " stateAfter: buttons=" << (int *) (int) e->buttons () - << " modifiers=" << (int *) (int) e->modifiers (); - kpView *v0 = viewUnderCursor (), - *v1 = viewManager ()->viewUnderCursor (true/*use Qt*/), - *v2 = viewUnderStartPoint (); - qCDebug(kpLogTools) << "\tviewUnderCursor=" << (v0 ? v0->objectName () : "(none)") - << " viewUnderCursorQt=" << (v1 ? v1->objectName () : "(none)") - << " viewUnderStartPoint=" << (v2 ? v2->objectName () : "(none)"); - qCDebug(kpLogTools) << "\tfocusWidget=" << kapp->focusWidget (); + qCDebug(kpLogTools) << "kpTool::mouseMoveEvent pos=" << e->pos() + << " stateAfter: buttons=" << (int *)(int)e->buttons() + << " modifiers=" << (int *)(int)e->modifiers(); + kpView *v0 = viewUnderCursor(), + *v1 = viewManager()->viewUnderCursor(true /*use Qt*/), + *v2 = viewUnderStartPoint(); + qCDebug(kpLogTools) << "\tviewUnderCursor=" << (v0 ? v0->objectName() : "(none)") + << " viewUnderCursorQt=" << (v1 ? v1->objectName() : "(none)") + << " viewUnderStartPoint=" << (v2 ? v2->objectName() : "(none)"); + qCDebug(kpLogTools) << "\tfocusWidget=" << kapp->focusWidget(); qCDebug(kpLogTools) << "\tbeganDraw=" << d->beganDraw; #endif - d->shiftPressed = (e->modifiers () & Qt::ShiftModifier); - d->controlPressed = (e->modifiers () & Qt::ControlModifier); - d->altPressed = (e->modifiers () & Qt::AltModifier); + d->shiftPressed = (e->modifiers() & Qt::ShiftModifier); + d->controlPressed = (e->modifiers() & Qt::ControlModifier); + d->altPressed = (e->modifiers() & Qt::AltModifier); - if (d->beganDraw) - { - kpView *view = viewUnderStartPoint (); - Q_ASSERT (view); + if (d->beganDraw) { + kpView *view = viewUnderStartPoint(); + Q_ASSERT(view); - d->currentPoint = view->transformViewToDoc (e->pos ()); - d->currentViewPoint = e->pos (); + d->currentPoint = view->transformViewToDoc(e->pos()); + d->currentViewPoint = e->pos(); #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "\tDraw!"; #endif bool dragScrolled = false; - movedAndAboutToDraw (d->currentPoint, d->lastPoint, view->zoomLevelX (), &dragScrolled); + movedAndAboutToDraw(d->currentPoint, d->lastPoint, view->zoomLevelX(), &dragScrolled); - if (dragScrolled) - { - d->currentPoint = calculateCurrentPoint (); - d->currentViewPoint = calculateCurrentPoint (false/*view point*/); + if (dragScrolled) { + d->currentPoint = calculateCurrentPoint(); + d->currentViewPoint = calculateCurrentPoint(false /*view point*/); // Scrollview has scrolled contents and has scheduled an update // for the newly exposed region. If draw() schedules an update // as well (instead of immediately updating), the scrollview's // update will be executed first and it'll only update part of // the screen resulting in ugly tearing of the viewManager's // tempImage. - viewManager ()->setFastUpdates (); + viewManager()->setFastUpdates(); } - drawInternal (); + drawInternal(); if (dragScrolled) { - viewManager ()->restoreFastUpdates (); + viewManager()->restoreFastUpdates(); } d->lastPoint = d->currentPoint; - } - else - { - kpView *view = viewUnderCursor (); - if (!view) // possible if cancelShape()'ed but still holding down initial mousebtn - { + } else { + kpView *view = viewUnderCursor(); + if (!view) { // possible if cancelShape()'ed but still holding down initial mousebtn d->currentPoint = KP_INVALID_POINT; d->currentViewPoint = KP_INVALID_POINT; return; } - d->currentPoint = view->transformViewToDoc (e->pos ()); - d->currentViewPoint = e->pos (); - hover (d->currentPoint); + d->currentPoint = view->transformViewToDoc(e->pos()); + d->currentViewPoint = e->pos(); + hover(d->currentPoint); } } //--------------------------------------------------------------------- -void kpTool::mouseReleaseEvent (QMouseEvent *e) +void kpTool::mouseReleaseEvent(QMouseEvent *e) { #if DEBUG_KP_TOOL && 1 - qCDebug(kpLogTools) << "kpTool::mouseReleaseEvent pos=" << e->pos () - << " button=" << (int) e->button () - << " stateAfter: buttons=" << (int *) (int) e->buttons () - << " modifiers=" << (int *) (int) e->modifiers () - << " beganDraw=" << d->beganDraw; + qCDebug(kpLogTools) << "kpTool::mouseReleaseEvent pos=" << e->pos() + << " button=" << (int)e->button() + << " stateAfter: buttons=" << (int *)(int)e->buttons() + << " modifiers=" << (int *)(int)e->modifiers() + << " beganDraw=" << d->beganDraw; #endif // Have _not_ already cancelShape()'ed by pressing other mouse button? // (e.g. you can cancel a line dragged out with the LMB, by pressing // the RMB) - if (d->beganDraw) - { - kpView *view = viewUnderStartPoint (); - Q_ASSERT (view); + if (d->beganDraw) { + kpView *view = viewUnderStartPoint(); + Q_ASSERT(view); - d->currentPoint = view->transformViewToDoc (e->pos ()); - d->currentViewPoint = e->pos (); + d->currentPoint = view->transformViewToDoc(e->pos()); + d->currentViewPoint = e->pos(); - drawInternal (); + drawInternal(); - endDrawInternal (d->currentPoint, normalizedRect ()); + endDrawInternal(d->currentPoint, normalizedRect()); } - if ((e->buttons () & Qt::MouseButtonMask) == 0) - { - releasedAllButtons (); + if ((e->buttons() & Qt::MouseButtonMask) == 0) { + releasedAllButtons(); } } //--------------------------------------------------------------------- -void kpTool::wheelEvent (QWheelEvent *e) +void kpTool::wheelEvent(QWheelEvent *e) { #if DEBUG_KP_TOOL - qCDebug(kpLogTools) << "kpTool::wheelEvent() modifiers=" << (int *) (int) e->modifiers () - << " hasBegunDraw=" << hasBegunDraw () - << " delta=" << e->delta (); + qCDebug(kpLogTools) << "kpTool::wheelEvent() modifiers=" << (int *)(int)e->modifiers() + << " hasBegunDraw=" << hasBegunDraw() + << " delta=" << e->delta(); #endif - e->ignore (); + e->ignore(); // If CTRL not pressed, bye. - if ((e->modifiers () & Qt::ControlModifier) == 0) - { + if ((e->modifiers() & Qt::ControlModifier) == 0) { #if DEBUG_KP_TOOL qCDebug(kpLogTools) << "\tno CTRL -> bye"; #endif return; } // If drawing, bye; don't care if a shape in progress though. - if (hasBegunDraw ()) - { + if (hasBegunDraw()) { #if DEBUG_KP_TOOL qCDebug(kpLogTools) << "\thasBegunDraw() -> bye"; #endif return; } - // Zoom in/out depending on wheel direction. // Moved wheel away from user? - if (e->delta () > 0) - { + if (e->delta() > 0) { #if DEBUG_KP_TOOL qCDebug(kpLogTools) << "\tzoom in"; #endif - d->environ->zoomIn (true/*center under cursor*/); - e->accept (); + d->environ->zoomIn(true /*center under cursor*/); + e->accept(); } // Moved wheel towards user? - else if (e->delta () < 0) - { + else if (e->delta() < 0) { #if DEBUG_KP_TOOL qCDebug(kpLogTools) << "\tzoom out"; #endif #if 1 - d->environ->zoomOut (true/*center under cursor - make zoom in/out + d->environ->zoomOut(true/*center under cursor - make zoom in/out stay under same doc pos*/); #else - d->environ->zoomOut (false/*don't center under cursor - as is + d->environ->zoomOut(false/*don't center under cursor - as is confusing behaviour when zooming out*/); #endif - e->accept (); + e->accept(); } } diff --git a/tools/kpTool_OtherEvents.cpp b/tools/kpTool_OtherEvents.cpp --- a/tools/kpTool_OtherEvents.cpp +++ b/tools/kpTool_OtherEvents.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -32,10 +31,8 @@ // 2. Non-view events // - #define DEBUG_KP_TOOL 0 - #include "tools/kpTool.h" #include "kpToolPrivate.h" @@ -49,120 +46,117 @@ // 1. View Events // -bool kpTool::viewEvent (QEvent *e) +bool kpTool::viewEvent(QEvent *e) { #if DEBUG_KP_TOOL - qCDebug(kpLogTools) << "kpTool<" << objectName () - << "," << this << ">::viewEvent(type=" << e->type () - << ") returning false" << endl; + qCDebug(kpLogTools) << "kpTool<" << objectName() + << "," << this << ">::viewEvent(type=" << e->type() + << ") returning false" << endl; #else - (void) e; + (void)e; #endif // Don't handle. return false; } //--------------------------------------------------------------------- -void kpTool::focusInEvent (QFocusEvent *) +void kpTool::focusInEvent(QFocusEvent *) { } //--------------------------------------------------------------------- -void kpTool::focusOutEvent (QFocusEvent *) +void kpTool::focusOutEvent(QFocusEvent *) { #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "kpTool::focusOutEvent() beganDraw=" << d->beganDraw; #endif if (d->beganDraw) { - endDrawInternal (d->currentPoint, normalizedRect ()); + endDrawInternal(d->currentPoint, normalizedRect()); } } //--------------------------------------------------------------------- -void kpTool::enterEvent (QEvent *) +void kpTool::enterEvent(QEvent *) { #if DEBUG_KP_TOOL && 1 qCDebug(kpLogTools) << "kpTool::enterEvent() beganDraw=" << d->beganDraw; #endif } //--------------------------------------------------------------------- -void kpTool::leaveEvent (QEvent *) +void kpTool::leaveEvent(QEvent *) { #if DEBUG_KP_TOOL && 1 qCDebug(kpLogTools) << "kpTool::leaveEvent() beganDraw=" << d->beganDraw; #endif // if we haven't started drawing (e.g. dragging a rectangle)... - if (!d->beganDraw) - { + if (!d->beganDraw) { d->currentPoint = KP_INVALID_POINT; d->currentViewPoint = KP_INVALID_POINT; - hover (d->currentPoint); + hover(d->currentPoint); } } //--------------------------------------------------------------------- // // 2. Non-view events // -void kpTool::slotColorsSwappedInternal (const kpColor &newForegroundColor, - const kpColor &newBackgroundColor) +void kpTool::slotColorsSwappedInternal(const kpColor &newForegroundColor, + const kpColor &newBackgroundColor) { - if (careAboutColorsSwapped ()) - { - slotColorsSwapped (newForegroundColor, newBackgroundColor); + if (careAboutColorsSwapped()) { + slotColorsSwapped(newForegroundColor, newBackgroundColor); d->ignoreColorSignals = 2; - } - else { + } else { d->ignoreColorSignals = 0; } } //--------------------------------------------------------------------- -void kpTool::slotForegroundColorChangedInternal (const kpColor &color) +void kpTool::slotForegroundColorChangedInternal(const kpColor &color) { - if (d->ignoreColorSignals > 0) - { + if (d->ignoreColorSignals > 0) { #if DEBUG_KP_TOOL && 1 - qCDebug(kpLogTools) << "kpTool::slotForegroundColorChangedInternal() ignoreColorSignals=" << d->ignoreColorSignals; + qCDebug(kpLogTools) << "kpTool::slotForegroundColorChangedInternal() ignoreColorSignals=" + << d->ignoreColorSignals; #endif d->ignoreColorSignals--; return; } - slotForegroundColorChanged (color); + slotForegroundColorChanged(color); } //--------------------------------------------------------------------- -void kpTool::slotBackgroundColorChangedInternal (const kpColor &color) +void kpTool::slotBackgroundColorChangedInternal(const kpColor &color) { - if (d->ignoreColorSignals > 0) - { + if (d->ignoreColorSignals > 0) { #if DEBUG_KP_TOOL && 1 - qCDebug(kpLogTools) << "kpTool::slotBackgroundColorChangedInternal() ignoreColorSignals=" << d->ignoreColorSignals; + qCDebug(kpLogTools) << "kpTool::slotBackgroundColorChangedInternal() ignoreColorSignals=" + << d->ignoreColorSignals; #endif d->ignoreColorSignals--; return; } - slotBackgroundColorChanged (color); + slotBackgroundColorChanged(color); } //--------------------------------------------------------------------- -void kpTool::slotColorSimilarityChangedInternal (double similarity, int processedSimilarity) +void kpTool::slotColorSimilarityChangedInternal(double similarity, int processedSimilarity) { - slotColorSimilarityChanged (similarity, processedSimilarity); + slotColorSimilarityChanged(similarity, processedSimilarity); } //--------------------------------------------------------------------- diff --git a/tools/kpTool_UserNotifications.cpp b/tools/kpTool_UserNotifications.cpp --- a/tools/kpTool_UserNotifications.cpp +++ b/tools/kpTool_UserNotifications.cpp @@ -36,130 +36,123 @@ //--------------------------------------------------------------------- // public static -QString kpTool::cancelUserMessage (int mouseButton) +QString kpTool::cancelUserMessage(int mouseButton) { if (mouseButton == 0) { - return i18n ("Right click to cancel."); + return i18n("Right click to cancel."); } - return i18n ("Left click to cancel."); + return i18n("Left click to cancel."); } //--------------------------------------------------------------------- // public -QString kpTool::cancelUserMessage () const +QString kpTool::cancelUserMessage() const { - return cancelUserMessage (d->mouseButton); + return cancelUserMessage(d->mouseButton); } //--------------------------------------------------------------------- // public -QString kpTool::userMessage () const +QString kpTool::userMessage() const { return d->userMessage; } //--------------------------------------------------------------------- // public -void kpTool::setUserMessage (const QString &userMessage) +void kpTool::setUserMessage(const QString &userMessage) { d->userMessage = userMessage; - if (d->userMessage.isEmpty ()) { - d->userMessage = text (); - } - else { - d->userMessage.prepend (i18n ("%1: ", text ())); + if (d->userMessage.isEmpty()) { + d->userMessage = text(); + } else { + d->userMessage.prepend(i18n("%1: ", text())); } - emit userMessageChanged (d->userMessage); + emit userMessageChanged(d->userMessage); } //--------------------------------------------------------------------- // public -QPoint kpTool::userShapeStartPoint () const +QPoint kpTool::userShapeStartPoint() const { return d->userShapeStartPoint; } //--------------------------------------------------------------------- // public -QPoint kpTool::userShapeEndPoint () const +QPoint kpTool::userShapeEndPoint() const { return d->userShapeEndPoint; } //--------------------------------------------------------------------- // public -void kpTool::setUserShapePoints (const QPoint &startPoint, - const QPoint &endPoint, - bool setSize) +void kpTool::setUserShapePoints(const QPoint &startPoint, const QPoint &endPoint, bool setSize) { d->userShapeStartPoint = startPoint; d->userShapeEndPoint = endPoint; - emit userShapePointsChanged (d->userShapeStartPoint, d->userShapeEndPoint); - - if (setSize) - { - if (startPoint != KP_INVALID_POINT && - endPoint != KP_INVALID_POINT) - { - setUserShapeSize (calculateLength (startPoint.x (), endPoint.x ()), - calculateLength (startPoint.y (), endPoint.y ())); - } - else - { - setUserShapeSize (); + emit userShapePointsChanged(d->userShapeStartPoint, d->userShapeEndPoint); + + if (setSize) { + if (startPoint != KP_INVALID_POINT + && endPoint != KP_INVALID_POINT) { + setUserShapeSize(calculateLength(startPoint.x(), endPoint.x()), + calculateLength(startPoint.y(), endPoint.y())); + } else { + setUserShapeSize(); } } } //--------------------------------------------------------------------- // public -QSize kpTool::userShapeSize () const +QSize kpTool::userShapeSize() const { return d->userShapeSize; } //--------------------------------------------------------------------- // public -int kpTool::userShapeWidth () const +int kpTool::userShapeWidth() const { - return d->userShapeSize.width (); + return d->userShapeSize.width(); } //--------------------------------------------------------------------- // public -int kpTool::userShapeHeight () const +int kpTool::userShapeHeight() const { - return d->userShapeSize.height (); + return d->userShapeSize.height(); } //--------------------------------------------------------------------- // public -void kpTool::setUserShapeSize (const QSize &size) +void kpTool::setUserShapeSize(const QSize &size) { d->userShapeSize = size; - emit userShapeSizeChanged (d->userShapeSize); + emit userShapeSizeChanged(d->userShapeSize); } //--------------------------------------------------------------------- // public -void kpTool::setUserShapeSize (int width, int height) +void kpTool::setUserShapeSize(int width, int height) { - setUserShapeSize (QSize (width, height)); + setUserShapeSize(QSize(width, height)); } //--------------------------------------------------------------------- diff --git a/tools/kpTool_Utilities.cpp b/tools/kpTool_Utilities.cpp --- a/tools/kpTool_Utilities.cpp +++ b/tools/kpTool_Utilities.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -29,10 +28,8 @@ // Tool utility methods - mainly for subclasses' convenience. // - #define DEBUG_KP_TOOL 0 - #include "tools/kpTool.h" #include "kpToolPrivate.h" @@ -51,76 +48,72 @@ //--------------------------------------------------------------------- // static -QRect kpTool::neededRect (const QRect &rect, int lineWidth) +QRect kpTool::neededRect(const QRect &rect, int lineWidth) { int x1, y1, x2, y2; - rect.getCoords (&x1, &y1, &x2, &y2); + rect.getCoords(&x1, &y1, &x2, &y2); if (lineWidth < 1) { lineWidth = 1; } // TODO: why not divide by 2? - return QRect (QPoint (x1 - lineWidth + 1, y1 - lineWidth + 1), - QPoint (x2 + lineWidth - 1, y2 + lineWidth - 1)); + return QRect(QPoint(x1 - lineWidth + 1, y1 - lineWidth + 1), + QPoint(x2 + lineWidth - 1, y2 + lineWidth - 1)); } //--------------------------------------------------------------------- // static -QImage kpTool::neededPixmap (const QImage &image, const QRect &boundingRect) +QImage kpTool::neededPixmap(const QImage &image, const QRect &boundingRect) { - return kpPixmapFX::getPixmapAt (image, boundingRect); + return kpPixmapFX::getPixmapAt(image, boundingRect); } //--------------------------------------------------------------------- // public -bool kpTool::hasCurrentPoint () const +bool kpTool::hasCurrentPoint() const { - return (viewUnderStartPoint () || viewUnderCursor ()); + return viewUnderStartPoint() || viewUnderCursor(); } //--------------------------------------------------------------------- // public -QPoint kpTool::calculateCurrentPoint (bool zoomToDoc) const +QPoint kpTool::calculateCurrentPoint(bool zoomToDoc) const { #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "kpTool::currentPoint(zoomToDoc=" << zoomToDoc << ")"; qCDebug(kpLogTools) << "\tviewUnderStartPoint=" - << (viewUnderStartPoint () ? viewUnderStartPoint ()->objectName () : "(none)") - << " viewUnderCursor=" - << (viewUnderCursor () ? viewUnderCursor ()->objectName () : "(none)") - << endl; + << (viewUnderStartPoint() ? viewUnderStartPoint()->objectName() : "(none)") + << " viewUnderCursor=" + << (viewUnderCursor() ? viewUnderCursor()->objectName() : "(none)") + << endl; #endif - kpView *v = viewUnderStartPoint (); - if (!v) - { - v = viewUnderCursor (); - if (!v) - { + kpView *v = viewUnderStartPoint(); + if (!v) { + v = viewUnderCursor(); + if (!v) { #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "\tno view - returning sentinel"; #endif return KP_INVALID_POINT; } } - - const QPoint globalPos = QCursor::pos (); - const QPoint viewPos = v->mapFromGlobal (globalPos); + const QPoint globalPos = QCursor::pos(); + const QPoint viewPos = v->mapFromGlobal(globalPos); #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "\tglobalPos=" << globalPos - << " viewPos=" << viewPos; + << " viewPos=" << viewPos; #endif if (!zoomToDoc) { return viewPos; } - - const QPoint docPos = v->transformViewToDoc (viewPos); + const QPoint docPos = v->transformViewToDoc(viewPos); #if DEBUG_KP_TOOL && 0 qCDebug(kpLogTools) << "\tdocPos=" << docPos; #endif @@ -130,81 +123,77 @@ //--------------------------------------------------------------------- // public slot -void kpTool::somethingBelowTheCursorChanged () +void kpTool::somethingBelowTheCursorChanged() { - somethingBelowTheCursorChanged (calculateCurrentPoint (), - calculateCurrentPoint (false/*view point*/)); + somethingBelowTheCursorChanged(calculateCurrentPoint(), + calculateCurrentPoint(false /*view point*/)); } //--------------------------------------------------------------------- // private // TODO: don't dup code from mouseMoveEvent() -void kpTool::somethingBelowTheCursorChanged (const QPoint ¤tPoint_, - const QPoint ¤tViewPoint_) +void kpTool::somethingBelowTheCursorChanged(const QPoint ¤tPoint_, + const QPoint ¤tViewPoint_) { #if DEBUG_KP_TOOL && 1 qCDebug(kpLogTools) << "kpTool::somethingBelowTheCursorChanged(docPoint=" - << currentPoint_ - << " viewPoint=" - << currentViewPoint_ - << ")" << endl; + << currentPoint_ + << " viewPoint=" + << currentViewPoint_ + << ")" << endl; qCDebug(kpLogTools) << "\tviewUnderStartPoint=" - << (viewUnderStartPoint () ? viewUnderStartPoint ()->objectName () : "(none)") - << " viewUnderCursor=" - << (viewUnderCursor () ? viewUnderCursor ()->objectName () : "(none)") - << endl; + << (viewUnderStartPoint() ? viewUnderStartPoint()->objectName() : "(none)") + << " viewUnderCursor=" + << (viewUnderCursor() ? viewUnderCursor()->objectName() : "(none)") + << endl; qCDebug(kpLogTools) << "\tbegan draw=" << d->beganDraw; #endif d->currentPoint = currentPoint_; d->currentViewPoint = currentViewPoint_; - if (d->beganDraw) - { - if (d->currentPoint != KP_INVALID_POINT) - { - draw (d->currentPoint, d->lastPoint, normalizedRect ()); + if (d->beganDraw) { + if (d->currentPoint != KP_INVALID_POINT) { + draw(d->currentPoint, d->lastPoint, normalizedRect()); d->lastPoint = d->currentPoint; } - } - else - { - hover (d->currentPoint); + } else { + hover(d->currentPoint); } } //--------------------------------------------------------------------- -bool kpTool::currentPointNextToLast () const +bool kpTool::currentPointNextToLast() const { - if (d->lastPoint == QPoint (-1, -1)) { + if (d->lastPoint == QPoint(-1, -1)) { return true; } - int dx = qAbs (d->currentPoint.x () - d->lastPoint.x ()); - int dy = qAbs (d->currentPoint.y () - d->lastPoint.y ()); + int dx = qAbs(d->currentPoint.x() - d->lastPoint.x()); + int dy = qAbs(d->currentPoint.y() - d->lastPoint.y()); - return (dx <= 1 && dy <= 1); + return dx <= 1 && dy <= 1; } //--------------------------------------------------------------------- -bool kpTool::currentPointCardinallyNextToLast () const +bool kpTool::currentPointCardinallyNextToLast() const { - if (d->lastPoint == QPoint (-1, -1)) { + if (d->lastPoint == QPoint(-1, -1)) { return true; } - return (d->currentPoint == d->lastPoint || - kpPainter::pointsAreCardinallyAdjacent (d->currentPoint, d->lastPoint)); + return d->currentPoint == d->lastPoint + || kpPainter::pointsAreCardinallyAdjacent(d->currentPoint, d->lastPoint); } //--------------------------------------------------------------------- // static // TODO: we don't handle Qt::XButton1 and Qt::XButton2 at the moment. -int kpTool::mouseButton (Qt::MouseButtons mouseButtons) +int kpTool::mouseButton(Qt::MouseButtons mouseButtons) { // we have nothing to do with mid-buttons if (mouseButtons & Qt::MidButton) { @@ -230,10 +219,9 @@ //--------------------------------------------------------------------- // public static -int kpTool::calculateLength (int start, int end) +int kpTool::calculateLength(int start, int end) { - if (start <= end) - { + if (start <= end) { return end - start + 1; } @@ -243,49 +231,43 @@ //--------------------------------------------------------------------- // public static -bool kpTool::warnIfBigImageSize (int oldWidth, int oldHeight, - int newWidth, int newHeight, - const QString &text, - const QString &caption, - const QString &continueButtonText, - QWidget *parent) +bool kpTool::warnIfBigImageSize(int oldWidth, int oldHeight, int newWidth, int newHeight, + const QString &text, const QString &caption, + const QString &continueButtonText, QWidget *parent) { #if DEBUG_KP_TOOL qCDebug(kpLogTools) << "kpTool::warnIfBigImageSize()" - << " old: w=" << oldWidth << " h=" << oldWidth - << " new: w=" << newWidth << " h=" << newHeight - << " pixmapSize=" - << kpPixmapFX::pixmapSize (newWidth, - newHeight, - QPixmap::defaultDepth ()) - << " vs BigImageSize=" << KP_BIG_IMAGE_SIZE - << endl; + << " old: w=" << oldWidth << " h=" << oldWidth + << " new: w=" << newWidth << " h=" << newHeight + << " pixmapSize=" + << kpPixmapFX::pixmapSize(newWidth, + newHeight, + QPixmap::defaultDepth()) + << " vs BigImageSize=" << KP_BIG_IMAGE_SIZE + << endl; #endif // Only got smaller or unchanged - don't complain - if (!(newWidth > oldWidth || newHeight > oldHeight)) - { + if (!(newWidth > oldWidth || newHeight > oldHeight)) { return true; } // Was already large - user was warned before, don't annoy him/her again - if (kpCommandSize::PixmapSize (oldWidth, oldHeight, QPixmap::defaultDepth ()) >= - KP_BIG_IMAGE_SIZE) - { + if (kpCommandSize::PixmapSize(oldWidth, oldHeight, QPixmap::defaultDepth()) + >= KP_BIG_IMAGE_SIZE) { return true; } - if (kpCommandSize::PixmapSize (newWidth, newHeight, QPixmap::defaultDepth ()) >= - KP_BIG_IMAGE_SIZE) - { - int accept = KMessageBox::warningContinueCancel (parent, - text, - caption, - KGuiItem (continueButtonText), - KStandardGuiItem::cancel(), - QStringLiteral ("BigImageDontAskAgain")); - - return (accept == KMessageBox::Continue); + if (kpCommandSize::PixmapSize(newWidth, newHeight, QPixmap::defaultDepth()) + >= KP_BIG_IMAGE_SIZE) { + int accept = KMessageBox::warningContinueCancel(parent, + text, + caption, + KGuiItem(continueButtonText), + KStandardGuiItem::cancel(), + QStringLiteral("BigImageDontAskAgain")); + + return accept == KMessageBox::Continue; } return true; diff --git a/tools/polygonal/kpToolCurve.h b/tools/polygonal/kpToolCurve.h --- a/tools/polygonal/kpToolCurve.h +++ b/tools/polygonal/kpToolCurve.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,30 +24,26 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_CURVE_H #define KP_TOOL_CURVE_H - #include "kpToolPolygonalBase.h" - class kpToolCurve : public kpToolPolygonalBase { -Q_OBJECT + Q_OBJECT public: kpToolCurve (kpToolEnvironment *environ, QObject *parent); ~kpToolCurve () override; protected: - QString haventBegunShapeUserMessage () const override; + QString haventBegunShapeUserMessage() const override; - bool drawingALine () const override; + bool drawingALine() const override; public: - void endDraw (const QPoint &, const QRect &) override; + void endDraw(const QPoint &, const QRect &) override; }; - #endif // KP_TOOL_CURVE_H diff --git a/tools/polygonal/kpToolCurve.cpp b/tools/polygonal/kpToolCurve.cpp --- a/tools/polygonal/kpToolCurve.cpp +++ b/tools/polygonal/kpToolCurve.cpp @@ -25,10 +25,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_CURVE 0 - #include "kpToolCurve.h" #include "kpLogCategories.h" #include "environments/tools/kpToolEnvironment.h" @@ -42,24 +40,20 @@ //-------------------------------------------------------------------------------- -static void DrawCurveShape (kpImage *image, - const QPolygon &points, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor, - bool isFinal) +static void DrawCurveShape(kpImage *image, const QPolygon &points, const kpColor &fcolor, + int penWidth, const kpColor &bcolor, bool isFinal) { - (void) bcolor; - (void) isFinal; + (void)bcolor; + (void)isFinal; - Q_ASSERT (points.count () >= 2 && points.count () <= 4); + Q_ASSERT(points.count() >= 2 && points.count() <= 4); const QPoint startPoint = points [0]; const QPoint endPoint = points [1]; QPoint controlPointP, controlPointQ; - switch (points.count ()) - { + switch (points.count()) { // Just a line? case 2: controlPointP = startPoint; @@ -83,10 +77,9 @@ painter.setPen(QPen(fcolor.toQColor(), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - if ( kpPixmapFX::Only1PixelInPointArray(points) ) - { - painter.drawPoint(points[0]); - return; + if (kpPixmapFX::Only1PixelInPointArray(points)) { + painter.drawPoint(points[0]); + return; } QPainterPath curvePath; @@ -99,9 +92,9 @@ //-------------------------------------------------------------------------------- kpToolCurve::kpToolCurve (kpToolEnvironment *environ, QObject *parent) - : kpToolPolygonalBase ( - i18n ("Curve"), - i18n ("Draws curves"), + : kpToolPolygonalBase( + i18n("Curve"), + i18n("Draws curves"), &::DrawCurveShape, Qt::Key_V, environ, parent, @@ -111,70 +104,60 @@ kpToolCurve::~kpToolCurve () = default; - // protected virtual [base kpToolPolygonalBase] -QString kpToolCurve::haventBegunShapeUserMessage () const +QString kpToolCurve::haventBegunShapeUserMessage() const { - return i18n ("Drag out the start and end points."); + return i18n("Drag out the start and end points."); } - // protected virtual [base kpToolPolygonalBase] -bool kpToolCurve::drawingALine () const +bool kpToolCurve::drawingALine() const { // On the initial drag (consisting of 2 points) creates a line. // Future drags are for control points. - return (points ()->count () == 2); + return points()->count() == 2; } - // public virtual [base kpTool] -void kpToolCurve::endDraw (const QPoint &, const QRect &) +void kpToolCurve::endDraw(const QPoint &, const QRect &) { #if DEBUG_KP_TOOL_CURVE qCDebug(kpLogTools) << "kpToolCurve::endDraw() points=" - << points ()->toList (); + << points()->toList(); #endif - switch (points ()->count ()) - { + switch (points()->count()) { // A click of the other mouse button (to finish shape, instead of adding // another control point) would have caused endShape() to have been // called in kpToolPolygonalBase::beginDraw(). The points list would now // be empty. We are being called by kpTool::mouseReleaseEvent(). case 0: break; case 1: - Q_ASSERT (!"kpToolPolygonalBase::beginDraw() ensures we have >= 2 ctrl points"); + Q_ASSERT(!"kpToolPolygonalBase::beginDraw() ensures we have >= 2 ctrl points"); break; // Just completed initial line? case 2: - if (originatingMouseButton () == 0) - { - setUserMessage ( - i18n ("Left drag to set the first control point or right click to finish.")); - } - else - { - setUserMessage ( - i18n ("Right drag to set the first control point or left click to finish.")); + if (originatingMouseButton() == 0) { + setUserMessage( + i18n("Left drag to set the first control point or right click to finish.")); + } else { + setUserMessage( + i18n("Right drag to set the first control point or left click to finish.")); } break; // Have initial line and first control point? case 3: - if (originatingMouseButton () == 0) - { - setUserMessage ( - i18n ("Left drag to set the last control point or right click to finish.")); - } - else - { - setUserMessage ( - i18n ("Right drag to set the last control point or left click to finish.")); + if (originatingMouseButton() == 0) { + setUserMessage( + i18n("Left drag to set the last control point or right click to finish.")); + } else { + setUserMessage( + i18n("Right drag to set the last control point or left click to finish.")); } break; @@ -184,13 +167,11 @@ #if DEBUG_KP_TOOL_CURVE qCDebug(kpLogTools) << "\tending shape"; #endif - endShape (); + endShape(); break; default: - Q_ASSERT (!"Impossible number of points"); + Q_ASSERT(!"Impossible number of points"); break; } } - - diff --git a/tools/polygonal/kpToolLine.h b/tools/polygonal/kpToolLine.h --- a/tools/polygonal/kpToolLine.h +++ b/tools/polygonal/kpToolLine.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,27 +24,23 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_LINE_H #define KP_TOOL_LINE_H - #include "kpToolPolygonalBase.h" - class kpToolLine : public kpToolPolygonalBase { -Q_OBJECT + Q_OBJECT public: kpToolLine (kpToolEnvironment *environ, QObject *parent); private: - QString haventBegunShapeUserMessage () const override; + QString haventBegunShapeUserMessage() const override; public: - void endDraw (const QPoint &, const QRect &) override; + void endDraw(const QPoint &, const QRect &) override; }; - #endif // KP_TOOL_LINE_H diff --git a/tools/polygonal/kpToolLine.cpp b/tools/polygonal/kpToolLine.cpp --- a/tools/polygonal/kpToolLine.cpp +++ b/tools/polygonal/kpToolLine.cpp @@ -24,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_LINE 0 - #include "kpToolLine.h" #include "kpToolPolyline.h" #include "kpLogCategories.h" @@ -37,9 +35,9 @@ //-------------------------------------------------------------------------------- kpToolLine::kpToolLine (kpToolEnvironment *environ, QObject *parent) - : kpToolPolygonalBase ( - i18n ("Line"), - i18n ("Draws lines"), + : kpToolPolygonalBase( + i18n("Line"), + i18n("Draws lines"), &kpToolPolyline::drawShape, Qt::Key_L, environ, parent, @@ -50,24 +48,24 @@ //-------------------------------------------------------------------------------- // private virtual [base kpToolPolygonalBase] -QString kpToolLine::haventBegunShapeUserMessage () const +QString kpToolLine::haventBegunShapeUserMessage() const { - return i18n ("Drag to draw."); + return i18n("Drag to draw."); } //-------------------------------------------------------------------------------- // public virtual [base kpTool] -void kpToolLine::endDraw (const QPoint &, const QRect &) +void kpToolLine::endDraw(const QPoint &, const QRect &) { #if DEBUG_KP_TOOL_LINE qCDebug(kpLogTools) << "kpToolLine::endDraw() points=" - << points ()->toList () << endl; + << points()->toList() << endl; #endif // After the first drag, we should have a line. - Q_ASSERT (points ()->count () == 2); - endShape (); + Q_ASSERT(points()->count() == 2); + endShape(); } //-------------------------------------------------------------------------------- diff --git a/tools/polygonal/kpToolPolygon.h b/tools/polygonal/kpToolPolygon.h --- a/tools/polygonal/kpToolPolygon.h +++ b/tools/polygonal/kpToolPolygon.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,38 +24,34 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_POLYGON_H #define KP_TOOL_POLYGON_H - #include "kpToolPolygonalBase.h" - class kpToolPolygon : public kpToolPolygonalBase { -Q_OBJECT + Q_OBJECT public: kpToolPolygon (kpToolEnvironment *environ, QObject *parent); ~kpToolPolygon () override; private: - QString haventBegunShapeUserMessage () const override; + QString haventBegunShapeUserMessage() const override; public: - void begin () override; - void end () override; + void begin() override; + void end() override; protected: - kpColor drawingBackgroundColor () const override; + kpColor drawingBackgroundColor() const override; public: - void endDraw (const QPoint &, const QRect &) override; + void endDraw(const QPoint &, const QRect &) override; private: struct kpToolPolygonPrivate *d; }; - #endif // KP_TOOL_POLYGON_H diff --git a/tools/polygonal/kpToolPolygon.cpp b/tools/polygonal/kpToolPolygon.cpp --- a/tools/polygonal/kpToolPolygon.cpp +++ b/tools/polygonal/kpToolPolygon.cpp @@ -25,10 +25,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_POLYGON 0 - #include "kpToolPolygon.h" #include "widgets/toolbars/kpToolToolBar.h" #include "environments/tools/kpToolEnvironment.h" @@ -42,43 +40,38 @@ //-------------------------------------------------------------------------------- -static void DrawPolygonShape (kpImage *image, - const QPolygon &points, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor, - bool isFinal) +static void DrawPolygonShape(kpImage *image, const QPolygon &points, const kpColor &fcolor, + int penWidth, const kpColor &bcolor, bool isFinal) { - QPainter painter(image); - painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); + QPainter painter(image); + painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); - painter.setPen(QPen(fcolor.toQColor(), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + painter.setPen(QPen(fcolor.toQColor(), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - if ( kpPixmapFX::Only1PixelInPointArray(points) ) - { - painter.drawPoint(points[0]); - return; - } + if (kpPixmapFX::Only1PixelInPointArray(points)) { + painter.drawPoint(points[0]); + return; + } - if ( bcolor.isValid() ) { - painter.setBrush(QBrush(bcolor.toQColor())); - } - else { - painter.setBrush(Qt::NoBrush); - } + if (bcolor.isValid()) { + painter.setBrush(QBrush(bcolor.toQColor())); + } else { + painter.setBrush(Qt::NoBrush); + } - painter.drawPolygon(points, Qt::OddEvenFill); + painter.drawPolygon(points, Qt::OddEvenFill); - if ( isFinal ) { - return; - } + if (isFinal) { + return; + } - if ( points.count() <= 2 ) { - return; - } + if (points.count() <= 2) { + return; + } - painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination); - painter.setPen(QPen(Qt::white)); - painter.drawLine(points[0], points[points.count() - 1]); + painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination); + painter.setPen(QPen(Qt::white)); + painter.drawLine(points[0], points[points.count() - 1]); } //-------------------------------------------------------------------------------- @@ -89,102 +82,92 @@ }; kpToolPolygon::kpToolPolygon (kpToolEnvironment *environ, QObject *parent) - : kpToolPolygonalBase ( - i18n ("Polygon"), - i18n ("Draws polygons"), + : kpToolPolygonalBase( + i18n("Polygon"), + i18n("Draws polygons"), &::DrawPolygonShape, Qt::Key_G, environ, parent, - QStringLiteral("tool_polygon")), - d (new kpToolPolygonPrivate ()) + QStringLiteral("tool_polygon")) + , d(new kpToolPolygonPrivate()) { } kpToolPolygon::~kpToolPolygon () { delete d; } - // private virtual [base kpToolPolygonBase] -QString kpToolPolygon::haventBegunShapeUserMessage () const +QString kpToolPolygon::haventBegunShapeUserMessage() const { - return i18n ("Drag to draw the first line."); + return i18n("Drag to draw the first line."); } - // public virtual [base kpToolPolygonalBase] -void kpToolPolygon::begin () +void kpToolPolygon::begin() { - kpToolPolygonalBase::begin (); + kpToolPolygonalBase::begin(); - kpToolToolBar *tb = toolToolBar (); - Q_ASSERT (tb); + kpToolToolBar *tb = toolToolBar(); + Q_ASSERT(tb); - d->toolWidgetFillStyle = tb->toolWidgetFillStyle (); - connect (d->toolWidgetFillStyle, &kpToolWidgetFillStyle::fillStyleChanged, - this, &kpToolPolygon::updateShape); - d->toolWidgetFillStyle->show (); + d->toolWidgetFillStyle = tb->toolWidgetFillStyle(); + connect(d->toolWidgetFillStyle, &kpToolWidgetFillStyle::fillStyleChanged, + this, &kpToolPolygon::updateShape); + d->toolWidgetFillStyle->show(); } // public virtual [base kpToolPolygonalBase] -void kpToolPolygon::end () +void kpToolPolygon::end() { - kpToolPolygonalBase::end (); + kpToolPolygonalBase::end(); - disconnect (d->toolWidgetFillStyle, &kpToolWidgetFillStyle::fillStyleChanged, - this, &kpToolPolygon::updateShape); + disconnect(d->toolWidgetFillStyle, &kpToolWidgetFillStyle::fillStyleChanged, + this, &kpToolPolygon::updateShape); d->toolWidgetFillStyle = nullptr; } - // TODO: code dup with kpToolRectangle // protected virtual [base kpToolPolygonalBase] -kpColor kpToolPolygon::drawingBackgroundColor () const +kpColor kpToolPolygon::drawingBackgroundColor() const { - const kpColor foregroundColor = color (originatingMouseButton ()); - const kpColor backgroundColor = color (1 - originatingMouseButton ()); + const kpColor foregroundColor = color(originatingMouseButton()); + const kpColor backgroundColor = color(1 - originatingMouseButton()); - return d->toolWidgetFillStyle->drawingBackgroundColor ( + return d->toolWidgetFillStyle->drawingBackgroundColor( foregroundColor, backgroundColor); } - // public virtual [base kpTool] // TODO: dup with kpToolPolyline but we don't want to create another level of // inheritance and readability. -void kpToolPolygon::endDraw (const QPoint &, const QRect &) +void kpToolPolygon::endDraw(const QPoint &, const QRect &) { #if DEBUG_KP_TOOL_POLYGON qCDebug(kpLogTools) << "kpToolPolygon::endDraw() points=" - << points ()->toList (); + << points()->toList(); #endif // A click of the other mouse button (to finish shape, instead of adding // another control point) would have caused endShape() to have been // called in kpToolPolygonalBase::beginDraw(). The points list would now // be empty. We are being called by kpTool::mouseReleaseEvent(). - if (points ()->count () == 0) { + if (points()->count() == 0) { return; } - if (points ()->count () >= kpToolPolygonalBase::MaxPoints) - { + if (points()->count() >= kpToolPolygonalBase::MaxPoints) { #if DEBUG_KP_TOOL_POLYGON qCDebug(kpLogTools) << "\tending shape"; #endif - endShape (); + endShape(); return; } - if (originatingMouseButton () == 0) - { - setUserMessage (i18n ("Left drag another line or right click to finish.")); - } - else - { - setUserMessage (i18n ("Right drag another line or left click to finish.")); + if (originatingMouseButton() == 0) { + setUserMessage(i18n("Left drag another line or right click to finish.")); + } else { + setUserMessage(i18n("Right drag another line or left click to finish.")); } } - - diff --git a/tools/polygonal/kpToolPolygonalBase.h b/tools/polygonal/kpToolPolygonalBase.h --- a/tools/polygonal/kpToolPolygonalBase.h +++ b/tools/polygonal/kpToolPolygonalBase.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,27 +24,22 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolPolygonalBase_H #define kpToolPolygonalBase_H - #include #include #include "imagelib/kpColor.h" #include "imagelib/kpImage.h" #include "tools/kpTool.h" #include "widgets/toolbars/options/kpToolWidgetFillStyle.h" - class QPolygon; class QString; - class kpToolWidgetFillStyle; - struct kpToolPolygonalBasePrivate; // @@ -83,37 +77,37 @@ // class kpToolPolygonalBase : public kpTool { -Q_OBJECT + Q_OBJECT public: - typedef void (*DrawShapeFunc) (kpImage * /*image*/, - const QPolygon &/*points*/, - const kpColor &/*fcolor*/, int /*penWidth = 1*/, - const kpColor &/*bcolor = kpColor::Invalid*/, - bool /*isFinal*/); + typedef void (*DrawShapeFunc)(kpImage * /*image*/, const QPolygon & /*points*/, + const kpColor & /*fcolor*/, int /*penWidth = 1*/, + const kpColor & /*bcolor = kpColor::Invalid*/, + bool /*isFinal*/); // kpToolPolygonalBase (const QString &text, const QString &description, - DrawShapeFunc drawShapeFunc, - int key, - kpToolEnvironment *environ, QObject *parent, - const QString &name); + DrawShapeFunc drawShapeFunc, int key, kpToolEnvironment *environ, + QObject *parent, const QString &name); ~kpToolPolygonalBase () override; - bool careAboutModifierState () const override { return true; } + bool careAboutModifierState() const override + { + return true; + } protected: // The maximum number of points() we should allow (mainly, to ensure // good performance). Enforced by implementors of endShape(). static const int MaxPoints = 50; - virtual QString haventBegunShapeUserMessage () const = 0; + virtual QString haventBegunShapeUserMessage() const = 0; public: - void begin () override; - void end () override; + void begin() override; + void end() override; - void beginDraw () override; + void beginDraw() override; protected: // Adjusts the current line (end points given by the last 2 points of points()) @@ -134,23 +128,23 @@ // it doesn't really make sense to call applyModifiers() (in a hypothetical // reimplementation of draw()) because you're not manipulating a line - but // you can still call applyModifiers() if you want. - void applyModifiers (); + void applyModifiers(); // Returns the current points in the shape. It is updated by beginDraw() // (see the class description). // // draw() sets the last point to the currentPoint(). If drawingALine(), // draw() then calls applyModifiers(). - QPolygon *points () const; + QPolygon *points() const; // Returns the mouse button for the drag that created the initial line. // Use this - instead of mouseButton() - for determining whether you should // use the left mouse button's or right mouse button's color. This is because // the user presses the other mouse button to finish the shape (so mouseButton() // will return the wrong one, after the initial line). // // Only valid if kpTool::hasBegunShape() returns true. - int originatingMouseButton () const; + int originatingMouseButton() const; // Returns true if the current drag is visually a line from the 2nd last point // of points() to the last point of points() e.g. the initial line drag for @@ -167,34 +161,37 @@ // the initial drag. However, for the following 2 control points, it returns // "false". The Curve tool realizes it is an initial drag if points() only // returns 2 points. - virtual bool drawingALine () const { return true; } + virtual bool drawingALine() const + { + return true; + } + public: - void draw (const QPoint &, const QPoint &, const QRect &) override; + void draw(const QPoint &, const QPoint &, const QRect &) override; private: - kpColor drawingForegroundColor () const; + kpColor drawingForegroundColor() const; protected: // This returns the invalid color so that there is never a fill. // This is in contrast to kpToolRectangularBase, which sometimes fills by // returning a valid color. // // Reimplemented in the Polygon tool for a fill. - virtual kpColor drawingBackgroundColor () const; + virtual kpColor drawingBackgroundColor() const; protected slots: - void updateShape (); + void updateShape(); public: - void cancelShape () override; - void releasedAllButtons () override; - void endShape (const QPoint & = QPoint (), const QRect & = QRect ()) override; + void cancelShape() override; + void releasedAllButtons() override; + void endShape(const QPoint & = QPoint(), const QRect & = QRect()) override; - bool hasBegunShape () const override; + bool hasBegunShape() const override; protected slots: - void slotForegroundColorChanged (const kpColor &) override; - void slotBackgroundColorChanged (const kpColor &) override; + void slotForegroundColorChanged(const kpColor &) override; + void slotBackgroundColorChanged(const kpColor &) override; private: - kpToolPolygonalBasePrivate * const d; + kpToolPolygonalBasePrivate *const d; }; - #endif // kpToolPolygonalBase_H diff --git a/tools/polygonal/kpToolPolygonalBase.cpp b/tools/polygonal/kpToolPolygonalBase.cpp --- a/tools/polygonal/kpToolPolygonalBase.cpp +++ b/tools/polygonal/kpToolPolygonalBase.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_POLYGON 0 - #include "kpToolPolygonalBase.h" #include @@ -55,11 +52,12 @@ #include "widgets/toolbars/options/kpToolWidgetLineWidth.h" #include "views/manager/kpViewManager.h" - struct kpToolPolygonalBasePrivate { kpToolPolygonalBasePrivate () - : drawShapeFunc(nullptr), toolWidgetLineWidth(nullptr), originatingMouseButton(-1) + : drawShapeFunc(nullptr) + , toolWidgetLineWidth(nullptr) + , originatingMouseButton(-1) { } @@ -75,15 +73,11 @@ //--------------------------------------------------------------------- kpToolPolygonalBase::kpToolPolygonalBase ( - const QString &text, - const QString &description, - DrawShapeFunc drawShapeFunc, - int key, - kpToolEnvironment *environ, QObject *parent, - const QString &name) - - : kpTool (text, description, key, environ, parent, name), - d (new kpToolPolygonalBasePrivate ()) + const QString &text, const QString &description, DrawShapeFunc drawShapeFunc, int key, + kpToolEnvironment *environ, QObject *parent, const QString &name) + + : kpTool(text, description, key, environ, parent, name) + , d(new kpToolPolygonalBasePrivate()) { d->drawShapeFunc = drawShapeFunc; @@ -103,399 +97,373 @@ //--------------------------------------------------------------------- // virtual -void kpToolPolygonalBase::begin () +void kpToolPolygonalBase::begin() { - kpToolToolBar *tb = toolToolBar (); - Q_ASSERT (tb); + kpToolToolBar *tb = toolToolBar(); + Q_ASSERT(tb); #if DEBUG_KP_TOOL_POLYGON qCDebug(kpLogTools) << "kpToolPolygonalBase::begin() tb=" << tb; #endif - d->toolWidgetLineWidth = tb->toolWidgetLineWidth (); - connect (d->toolWidgetLineWidth, &kpToolWidgetLineWidth::lineWidthChanged, - this, &kpToolPolygonalBase::updateShape); - d->toolWidgetLineWidth->show (); + d->toolWidgetLineWidth = tb->toolWidgetLineWidth(); + connect(d->toolWidgetLineWidth, &kpToolWidgetLineWidth::lineWidthChanged, + this, &kpToolPolygonalBase::updateShape); + d->toolWidgetLineWidth->show(); - viewManager ()->setCursor (QCursor (Qt::ArrowCursor)); + viewManager()->setCursor(QCursor(Qt::ArrowCursor)); d->originatingMouseButton = -1; - setUserMessage (/*virtual*/haventBegunShapeUserMessage ()); + setUserMessage(/*virtual*/ haventBegunShapeUserMessage()); } //--------------------------------------------------------------------- // virtual -void kpToolPolygonalBase::end () +void kpToolPolygonalBase::end() { // TODO: needed? - endShape (); + endShape(); - disconnect (d->toolWidgetLineWidth, &kpToolWidgetLineWidth::lineWidthChanged, - this, &kpToolPolygonalBase::updateShape); + disconnect(d->toolWidgetLineWidth, &kpToolWidgetLineWidth::lineWidthChanged, + this, &kpToolPolygonalBase::updateShape); d->toolWidgetLineWidth = nullptr; - viewManager ()->unsetCursor (); + viewManager()->unsetCursor(); } - -void kpToolPolygonalBase::beginDraw () +void kpToolPolygonalBase::beginDraw() { #if DEBUG_KP_TOOL_POLYGON - qCDebug(kpLogTools) << "kpToolPolygonalBase::beginDraw() d->points=" << d->points.toList () - << ", startPoint=" << startPoint (); + qCDebug(kpLogTools) << "kpToolPolygonalBase::beginDraw() d->points=" << d->points.toList() + << ", startPoint=" << startPoint(); #endif bool endedShape = false; // We now need to start with dragging out the initial line? - if (d->points.count () == 0) - { - d->originatingMouseButton = mouseButton (); + if (d->points.count() == 0) { + d->originatingMouseButton = mouseButton(); // The line starts and ends at the start point of the drag. // draw() will modify the last point in d->points to reflect the // mouse drag, as the drag proceeds. - d->points.append (startPoint ()); - d->points.append (startPoint ()); + d->points.append(startPoint()); + d->points.append(startPoint()); } // Already have control points - not dragging out initial line. - else - { + else { // Clicking the other mouse button? - if (mouseButton () != d->originatingMouseButton) - { + if (mouseButton() != d->originatingMouseButton) { // Finish shape. TODO: I suspect we need to call endShapeInternal instead. - endShape (); + endShape(); endedShape = true; } // Are we dragging out an extra control point? - else - { + else { // Add another control point. - d->points.append (startPoint ()); + d->points.append(startPoint()); } } #if DEBUG_KP_TOOL_POLYGON - qCDebug(kpLogTools) << "\tafterwards, d->points=" << d->points.toList (); + qCDebug(kpLogTools) << "\tafterwards, d->points=" << d->points.toList(); #endif - if (!endedShape) - { + if (!endedShape) { // We've started dragging. Print instructions on how to cancel shape. - setUserMessage (cancelUserMessage ()); + setUserMessage(cancelUserMessage()); } } - // protected -void kpToolPolygonalBase::applyModifiers () +void kpToolPolygonalBase::applyModifiers() { - const int count = d->points.count (); + const int count = d->points.count(); QPoint &lineStartPoint = d->points [count - 2]; QPoint &lineEndPoint = d->points [count - 1]; #if DEBUG_KP_TOOL_POLYGON && 1 qCDebug(kpLogTools) << "kpToolPolygonalBase::applyModifiers() #pts=" << count - << " line: startPt=" << lineStartPoint - << " endPt=" << lineEndPoint - << " modifiers: shift=" << shiftPressed () - << " alt=" << altPressed () - << " ctrl=" << controlPressed (); + << " line: startPt=" << lineStartPoint + << " endPt=" << lineEndPoint + << " modifiers: shift=" << shiftPressed() + << " alt=" << altPressed() + << " ctrl=" << controlPressed(); #endif // angles - if (shiftPressed () || controlPressed ()) - { - int diffx = lineEndPoint.x () - lineStartPoint.x (); - int diffy = lineEndPoint.y () - lineStartPoint.y (); + if (shiftPressed() || controlPressed()) { + int diffx = lineEndPoint.x() - lineStartPoint.x(); + int diffy = lineEndPoint.y() - lineStartPoint.y(); double ratio; if (diffx == 0) { ratio = DBL_MAX; - } - else { - ratio = fabs (double (diffy) / double (diffx)); + } else { + ratio = fabs(double(diffy) / double(diffx)); } #if DEBUG_KP_TOOL_POLYGON && 1 qCDebug(kpLogTools) << "\tdiffx=" << diffx << " diffy=" << diffy - << " ratio=" << ratio; + << " ratio=" << ratio; #endif // Shift = 0, 45, 90 // Ctrl = 0, 30, 60, 90 // Shift + Ctrl = 0, 30, 45, 60, 90 double angles [10]; // "ought to be enough for anybody" int numAngles = 0; angles [numAngles++] = 0; - if (controlPressed ()) { + if (controlPressed()) { angles [numAngles++] = M_PI / 6; } - if (shiftPressed ()) { + if (shiftPressed()) { angles [numAngles++] = M_PI / 4; } - if (controlPressed ()) { + if (controlPressed()) { angles [numAngles++] = M_PI / 3; } angles [numAngles++] = M_PI / 2; - Q_ASSERT (numAngles <= int (sizeof (angles) / sizeof (angles [0]))); + Q_ASSERT(numAngles <= int(sizeof(angles) / sizeof(angles [0]))); double angle = angles [numAngles - 1]; - for (int i = 0; i < numAngles - 1; i++) - { - double acceptingRatio = std::tan ((angles [i] + angles [i + 1]) / 2.0); - if (ratio < acceptingRatio) - { + for (int i = 0; i < numAngles - 1; i++) { + double acceptingRatio = std::tan((angles [i] + angles [i + 1]) / 2.0); + if (ratio < acceptingRatio) { angle = angles [i]; break; } } // horizontal (dist from start not maintained) - if (std::fabs (qRadiansToDegrees (angle) - 0) - < kpPixmapFX::AngleInDegreesEpsilon) - { - lineEndPoint = - QPoint (lineEndPoint.x (), lineStartPoint.y ()); + if (std::fabs(qRadiansToDegrees(angle) - 0) + < kpPixmapFX::AngleInDegreesEpsilon) { + lineEndPoint + = QPoint(lineEndPoint.x(), lineStartPoint.y()); } // vertical (dist from start not maintained) - else if (std::fabs (qRadiansToDegrees (angle) - 90) - < kpPixmapFX::AngleInDegreesEpsilon) - { - lineEndPoint = - QPoint (lineStartPoint.x (), lineEndPoint.y ()); + else if (std::fabs(qRadiansToDegrees(angle) - 90) + < kpPixmapFX::AngleInDegreesEpsilon) { + lineEndPoint + = QPoint(lineStartPoint.x(), lineEndPoint.y()); } // diagonal (dist from start maintained) - else - { - const double dist = std::sqrt (static_cast (diffx * diffx + diffy * diffy)); + else { + const double dist = std::sqrt(static_cast(diffx * diffx + diffy * diffy)); - #define sgn(a) ((a)<0?-1:1) + #define sgn(a) ((a) < 0 ? -1 : 1) // Round distances _before_ adding to any coordinate // (ensures consistent rounding behaviour in x & y directions) - const int newdx = qRound (dist * cos (angle) * sgn (diffx)); - const int newdy = qRound (dist * sin (angle) * sgn (diffy)); + const int newdx = qRound(dist * cos(angle) * sgn(diffx)); + const int newdy = qRound(dist * sin(angle) * sgn(diffy)); #undef sgn - lineEndPoint = QPoint (lineStartPoint.x () + newdx, - lineStartPoint.y () + newdy); + lineEndPoint = QPoint(lineStartPoint.x() + newdx, + lineStartPoint.y() + newdy); #if DEBUG_KP_TOOL_POLYGON && 1 qCDebug(kpLogTools) << "\t\tdiagonal line: dist=" << dist - << " angle=" << (angle * 180 / M_PI) - << " endPoint=" << lineEndPoint; + << " angle=" << (angle * 180 / M_PI) + << " endPoint=" << lineEndPoint; #endif } } // if (shiftPressed () || controlPressed ()) { // centring - if (altPressed () && 0/*ALT is unreliable*/) - { + if (altPressed() && 0 /*ALT is unreliable*/) { // start = start - diff // = start - (end - start) // = start - end + start // = 2 * start - end if (count == 2) { lineStartPoint += (lineStartPoint - lineEndPoint); - } - else { + } else { lineEndPoint += (lineEndPoint - lineStartPoint); } } // if (altPressed ()) { } - // protected -QPolygon *kpToolPolygonalBase::points () const +QPolygon *kpToolPolygonalBase::points() const { return &d->points; } - // protected -int kpToolPolygonalBase::originatingMouseButton () const +int kpToolPolygonalBase::originatingMouseButton() const { - Q_ASSERT (hasBegunShape ()); + Q_ASSERT(hasBegunShape()); return d->originatingMouseButton; } - // virtual -void kpToolPolygonalBase::draw (const QPoint &, const QPoint &, const QRect &) +void kpToolPolygonalBase::draw(const QPoint &, const QPoint &, const QRect &) { // A click of the other mouse button (to finish shape, instead of adding // another control point) would have caused endShape() to have been // called in kpToolPolygonalBase::beginDraw(). The points list would now // be empty. We are being called by kpTool::mouseReleaseEvent(). - if (d->points.count () == 0) { + if (d->points.count() == 0) { return; } #if DEBUG_KP_TOOL_POLYGON - qCDebug(kpLogTools) << "kpToolPolygonalBase::draw() d->points=" << d->points.toList () - << ", endPoint=" << currentPoint (); + qCDebug(kpLogTools) << "kpToolPolygonalBase::draw() d->points=" << d->points.toList() + << ", endPoint=" << currentPoint(); #endif // Update points() so that last point reflects current mouse position. - const int count = d->points.count (); - d->points [count - 1] = currentPoint (); + const int count = d->points.count(); + d->points [count - 1] = currentPoint(); #if DEBUG_KP_TOOL_POLYGON - qCDebug(kpLogTools) << "\tafterwards, d->points=" << d->points.toList (); + qCDebug(kpLogTools) << "\tafterwards, d->points=" << d->points.toList(); #endif // Are we drawing a line? - if (/*virtual*/drawingALine ()) - { + if (/*virtual*/ drawingALine()) { // Adjust the line (end points given by the last 2 points of points()) // in response to keyboard modifiers. - applyModifiers (); + applyModifiers(); // Update the preview of the shape. - updateShape (); + updateShape(); // Inform the user that we're dragging out a line with 2 control points. - setUserShapePoints (d->points [count - 2], d->points [count - 1]); + setUserShapePoints(d->points [count - 2], d->points [count - 1]); } // We're modifying a point. - else - { + else { // Update the preview of the shape. - updateShape (); + updateShape(); // Informs the user that we're just modifying a point (perhaps, a control // point of a Bezier). - setUserShapePoints (d->points [count - 1]); + setUserShapePoints(d->points [count - 1]); } } - // TODO: code dup with kpToolRectangle // private -kpColor kpToolPolygonalBase::drawingForegroundColor () const +kpColor kpToolPolygonalBase::drawingForegroundColor() const { - return color (originatingMouseButton ()); + return color(originatingMouseButton()); } // protected virtual -kpColor kpToolPolygonalBase::drawingBackgroundColor () const +kpColor kpToolPolygonalBase::drawingBackgroundColor() const { return kpColor::Invalid; } // TODO: code dup with kpToolRectangle // protected slot -void kpToolPolygonalBase::updateShape () +void kpToolPolygonalBase::updateShape() { - if (d->points.count () == 0) { + if (d->points.count() == 0) { return; } - const QRect boundingRect = kpTool::neededRect ( - d->points.boundingRect (), - d->toolWidgetLineWidth->lineWidth ()); + const QRect boundingRect = kpTool::neededRect( + d->points.boundingRect(), + d->toolWidgetLineWidth->lineWidth()); #if DEBUG_KP_TOOL_POLYGON qCDebug(kpLogTools) << "kpToolPolygonalBase::updateShape() boundingRect=" - << boundingRect - << " lineWidth=" - << d->toolWidgetLineWidth->lineWidth () - << endl; + << boundingRect + << " lineWidth=" + << d->toolWidgetLineWidth->lineWidth() + << endl; #endif - kpImage image = document ()->getImageAt (boundingRect); + kpImage image = document()->getImageAt(boundingRect); QPolygon pointsTranslated = d->points; - pointsTranslated.translate (-boundingRect.x (), -boundingRect.y ()); + pointsTranslated.translate(-boundingRect.x(), -boundingRect.y()); - (*d->drawShapeFunc) (&image, - pointsTranslated, - drawingForegroundColor (), d->toolWidgetLineWidth->lineWidth (), - /*virtual*/drawingBackgroundColor (), - false/*not final*/); + (*d->drawShapeFunc)(&image, + pointsTranslated, + drawingForegroundColor(), d->toolWidgetLineWidth->lineWidth(), + /*virtual*/ drawingBackgroundColor(), + false /*not final*/); - kpTempImage newTempImage (false/*always display*/, - kpTempImage::SetImage/*render mode*/, - boundingRect.topLeft (), - image); + kpTempImage newTempImage(false /*always display*/, + kpTempImage::SetImage /*render mode*/, + boundingRect.topLeft(), + image); - viewManager ()->setFastUpdates (); + viewManager()->setFastUpdates(); { - viewManager ()->setTempImage (newTempImage); + viewManager()->setTempImage(newTempImage); } - viewManager ()->restoreFastUpdates (); + viewManager()->restoreFastUpdates(); } // virtual -void kpToolPolygonalBase::cancelShape () +void kpToolPolygonalBase::cancelShape() { - viewManager ()->invalidateTempImage (); - d->points.resize (0); + viewManager()->invalidateTempImage(); + d->points.resize(0); - setUserMessage (i18n ("Let go of all the mouse buttons.")); + setUserMessage(i18n("Let go of all the mouse buttons.")); } -void kpToolPolygonalBase::releasedAllButtons () +void kpToolPolygonalBase::releasedAllButtons() { - if (!hasBegunShape ()) { - setUserMessage (/*virtual*/haventBegunShapeUserMessage ()); + if (!hasBegunShape()) { + setUserMessage(/*virtual*/ haventBegunShapeUserMessage()); } // --- else case already handled by endDraw() --- } // public virtual [base kpTool] -void kpToolPolygonalBase::endShape (const QPoint &, const QRect &) +void kpToolPolygonalBase::endShape(const QPoint &, const QRect &) { #if DEBUG_KP_TOOL_POLYGON qCDebug(kpLogTools) << "kpToolPolygonalBase::endShape() d->points=" - << d->points.toList () << endl; + << d->points.toList() << endl; #endif - if (!hasBegunShape ()) { + if (!hasBegunShape()) { return; } - viewManager ()->invalidateTempImage (); + viewManager()->invalidateTempImage(); - QRect boundingRect = kpTool::neededRect ( - d->points.boundingRect (), - d->toolWidgetLineWidth->lineWidth ()); + QRect boundingRect = kpTool::neededRect( + d->points.boundingRect(), + d->toolWidgetLineWidth->lineWidth()); - commandHistory ()->addCommand ( - new kpToolPolygonalCommand ( - text (), + commandHistory()->addCommand( + new kpToolPolygonalCommand( + text(), d->drawShapeFunc, d->points, boundingRect, - drawingForegroundColor (), d->toolWidgetLineWidth->lineWidth (), - /*virtual*/drawingBackgroundColor (), - environ ()->commandEnvironment ())); - - d->points.resize (0); - setUserMessage (/*virtual*/haventBegunShapeUserMessage ()); + drawingForegroundColor(), d->toolWidgetLineWidth->lineWidth(), + /*virtual*/ drawingBackgroundColor(), + environ()->commandEnvironment())); + d->points.resize(0); + setUserMessage(/*virtual*/ haventBegunShapeUserMessage()); } // public virtual [base kpTool] -bool kpToolPolygonalBase::hasBegunShape () const +bool kpToolPolygonalBase::hasBegunShape() const { - return (d->points.count () > 0); + return d->points.count() > 0; } - // virtual protected slot [base kpTool] -void kpToolPolygonalBase::slotForegroundColorChanged (const kpColor &) +void kpToolPolygonalBase::slotForegroundColorChanged(const kpColor &) { - updateShape (); + updateShape(); } // virtual protected slot [base kpTool] -void kpToolPolygonalBase::slotBackgroundColorChanged (const kpColor &) +void kpToolPolygonalBase::slotBackgroundColorChanged(const kpColor &) { - updateShape (); + updateShape(); } - - diff --git a/tools/polygonal/kpToolPolyline.h b/tools/polygonal/kpToolPolyline.h --- a/tools/polygonal/kpToolPolyline.h +++ b/tools/polygonal/kpToolPolyline.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,34 +24,27 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_POLYLINE_H #define KP_TOOL_POLYLINE_H - #include "kpToolPolygonalBase.h" - class kpToolPolyline : public kpToolPolygonalBase { -Q_OBJECT + Q_OBJECT public: kpToolPolyline (kpToolEnvironment *environ, QObject *parent); private: - QString haventBegunShapeUserMessage () const override; + QString haventBegunShapeUserMessage() const override; public: // (used by kpToolLine) - static void drawShape(kpImage *image, - const QPolygon &points, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor, - bool isFinal); + static void drawShape(kpImage *image, const QPolygon &points, const kpColor &fcolor, + int penWidth, const kpColor &bcolor, bool isFinal); - void endDraw (const QPoint &, const QRect &) override; + void endDraw(const QPoint &, const QRect &) override; }; - #endif // KP_TOOL_POLYLINE_H diff --git a/tools/polygonal/kpToolPolyline.cpp b/tools/polygonal/kpToolPolyline.cpp --- a/tools/polygonal/kpToolPolyline.cpp +++ b/tools/polygonal/kpToolPolyline.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_POLYLINE 0 - #include "kpToolPolyline.h" #include "kpLogCategories.h" #include "environments/tools/kpToolEnvironment.h" @@ -42,9 +39,9 @@ //-------------------------------------------------------------------------------- kpToolPolyline::kpToolPolyline (kpToolEnvironment *environ, QObject *parent) - : kpToolPolygonalBase ( - i18n ("Connected Lines"), - i18n ("Draws connected lines"), + : kpToolPolygonalBase( + i18n("Connected Lines"), + i18n("Draws connected lines"), &drawShape, Qt::Key_N, environ, parent, @@ -55,71 +52,61 @@ //-------------------------------------------------------------------------------- // private virtual [base kpToolPolygonalBase] -QString kpToolPolyline::haventBegunShapeUserMessage () const +QString kpToolPolyline::haventBegunShapeUserMessage() const { - return i18n ("Drag to draw the first line."); + return i18n("Drag to draw the first line."); } //-------------------------------------------------------------------------------- // public static -void kpToolPolyline::drawShape(kpImage *image, - const QPolygon &points, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor, - bool isFinal) +void kpToolPolyline::drawShape(kpImage *image, const QPolygon &points, const kpColor &fcolor, + int penWidth, const kpColor &bcolor, bool isFinal) { - (void) bcolor; - (void) isFinal; + (void)bcolor; + (void)isFinal; - QPainter painter(image); - painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); + QPainter painter(image); + painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); - painter.setPen(QPen(fcolor.toQColor(), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + painter.setPen(QPen(fcolor.toQColor(), penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); - if ( kpPixmapFX::Only1PixelInPointArray(points) ) { - painter.drawPoint(points[0]); - } - else { - painter.drawPolyline(points); - } + if (kpPixmapFX::Only1PixelInPointArray(points)) { + painter.drawPoint(points[0]); + } else { + painter.drawPolyline(points); + } } //-------------------------------------------------------------------------------- // public virtual [base kpTool] -void kpToolPolyline::endDraw (const QPoint &, const QRect &) +void kpToolPolyline::endDraw(const QPoint &, const QRect &) { #if DEBUG_KP_TOOL_POLYLINE qCDebug(kpLogTools) << "kpToolPolyline::endDraw() points=" - << points ()->toList (); + << points()->toList(); #endif // A click of the other mouse button (to finish shape, instead of adding // another control point) would have caused endShape() to have been // called in kpToolPolygonalBase::beginDraw(). The points list would now // be empty. We are being called by kpTool::mouseReleaseEvent(). - if (points ()->count () == 0) { + if (points()->count() == 0) { return; } - if (points ()->count () >= kpToolPolygonalBase::MaxPoints) - { + if (points()->count() >= kpToolPolygonalBase::MaxPoints) { #if DEBUG_KP_TOOL_POLYLINE qCDebug(kpLogTools) << "\tending shape"; #endif - endShape (); + endShape(); return; } - if (originatingMouseButton () == 0) - { - setUserMessage (i18n ("Left drag another line or right click to finish.")); - } - else - { - setUserMessage (i18n ("Right drag another line or left click to finish.")); + if (originatingMouseButton() == 0) { + setUserMessage(i18n("Left drag another line or right click to finish.")); + } else { + setUserMessage(i18n("Right drag another line or left click to finish.")); } } - - diff --git a/tools/rectangular/kpToolEllipse.h b/tools/rectangular/kpToolEllipse.h --- a/tools/rectangular/kpToolEllipse.h +++ b/tools/rectangular/kpToolEllipse.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,20 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_ELLIPSE_H #define KP_TOOL_ELLIPSE_H - #include "tools/rectangular/kpToolRectangularBase.h" - class kpToolEllipse : public kpToolRectangularBase { -Q_OBJECT + Q_OBJECT public: kpToolEllipse (kpToolEnvironment *environ, QObject *parent); - static void drawEllipse(kpImage *image, - int x, int y, int width, int height, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor); + static void drawEllipse(kpImage *image, int x, int y, int width, int height, + const kpColor &fcolor, int penWidth, const kpColor &bcolor); }; - #endif // KP_TOOL_ELLIPSE_H diff --git a/tools/rectangular/kpToolEllipse.cpp b/tools/rectangular/kpToolEllipse.cpp --- a/tools/rectangular/kpToolEllipse.cpp +++ b/tools/rectangular/kpToolEllipse.cpp @@ -25,7 +25,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpToolEllipse.h" #include "environments/tools/kpToolEnvironment.h" #include "imagelib/kpColor.h" @@ -39,44 +38,41 @@ //--------------------------------------------------------------------- kpToolEllipse::kpToolEllipse (kpToolEnvironment *environ, QObject *parent) - : kpToolRectangularBase (i18n ("Ellipse"), - i18n ("Draws ellipses and circles"), - &kpToolEllipse::drawEllipse, - Qt::Key_E, - environ, parent, QStringLiteral("tool_ellipse")) + : kpToolRectangularBase(i18n("Ellipse"), + i18n("Draws ellipses and circles"), + &kpToolEllipse::drawEllipse, + Qt::Key_E, + environ, parent, QStringLiteral("tool_ellipse")) { } //--------------------------------------------------------------------- -void kpToolEllipse::drawEllipse(kpImage *image, - int x, int y, int width, int height, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor) +void kpToolEllipse::drawEllipse(kpImage *image, int x, int y, int width, int height, + const kpColor &fcolor, int penWidth, const kpColor &bcolor) { - if ( (width == 0) || (height == 0) ) { - return; - } + if ((width == 0) || (height == 0)) { + return; + } - QPainter painter(image); - painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); + QPainter painter(image); + painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); - if ( ((2 * penWidth) > width) || ((2 * penWidth) > height) ) { - penWidth = qMin(width, height) / 2; - } + if (((2 * penWidth) > width) || ((2 * penWidth) > height)) { + penWidth = qMin(width, height) / 2; + } - painter.setPen(QPen(fcolor.toQColor(), penWidth)); + painter.setPen(QPen(fcolor.toQColor(), penWidth)); - if ( bcolor.isValid() ) { - painter.setBrush(QBrush(bcolor.toQColor())); - } - else { - painter.setBrush(Qt::NoBrush); - } + if (bcolor.isValid()) { + painter.setBrush(QBrush(bcolor.toQColor())); + } else { + painter.setBrush(Qt::NoBrush); + } - int offset = painter.testRenderHint(QPainter::Antialiasing) ? 1 : 0; + int offset = painter.testRenderHint(QPainter::Antialiasing) ? 1 : 0; - painter.drawEllipse( + painter.drawEllipse( x + penWidth / 2 + offset, y + penWidth / 2 + offset, qMax(1, width - penWidth - offset), diff --git a/tools/rectangular/kpToolRectangle.h b/tools/rectangular/kpToolRectangle.h --- a/tools/rectangular/kpToolRectangle.h +++ b/tools/rectangular/kpToolRectangle.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,20 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_RECTANGLE_H #define KP_TOOL_RECTANGLE_H - #include "tools/rectangular/kpToolRectangularBase.h" - class kpToolRectangle : public kpToolRectangularBase { -Q_OBJECT + Q_OBJECT public: kpToolRectangle (kpToolEnvironment *environ, QObject *parent); - static void drawRect(kpImage *image, - int x, int y, int width, int height, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor); + static void drawRect(kpImage *image, int x, int y, int width, int height, const kpColor &fcolor, + int penWidth, const kpColor &bcolor); }; - #endif // KP_TOOL_RECTANGLE_H diff --git a/tools/rectangular/kpToolRectangle.cpp b/tools/rectangular/kpToolRectangle.cpp --- a/tools/rectangular/kpToolRectangle.cpp +++ b/tools/rectangular/kpToolRectangle.cpp @@ -25,7 +25,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpToolRectangle.h" #include "environments/tools/kpToolEnvironment.h" @@ -40,44 +39,41 @@ //--------------------------------------------------------------------- kpToolRectangle::kpToolRectangle (kpToolEnvironment *environ, QObject *parent) - : kpToolRectangularBase (i18n ("Rectangle"), - i18n ("Draws rectangles and squares"), - &kpToolRectangle::drawRect, - Qt::Key_R, - environ, parent, QStringLiteral("tool_rectangle")) + : kpToolRectangularBase(i18n("Rectangle"), + i18n("Draws rectangles and squares"), + &kpToolRectangle::drawRect, + Qt::Key_R, + environ, parent, QStringLiteral("tool_rectangle")) { } //--------------------------------------------------------------------- -void kpToolRectangle::drawRect(kpImage *image, - int x, int y, int width, int height, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor) +void kpToolRectangle::drawRect(kpImage *image, int x, int y, int width, int height, + const kpColor &fcolor, int penWidth, const kpColor &bcolor) { - if ( (width == 0) || (height == 0) ) { - return; - } + if ((width == 0) || (height == 0)) { + return; + } - QPainter painter(image); - painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); + QPainter painter(image); + painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); - if ( ((2 * penWidth) > width) || ((2 * penWidth) > height) ) { - penWidth = qMin(width, height) / 2; - } + if (((2 * penWidth) > width) || ((2 * penWidth) > height)) { + penWidth = qMin(width, height) / 2; + } - painter.setPen(QPen(fcolor.toQColor(), penWidth, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin)); + painter.setPen(QPen(fcolor.toQColor(), penWidth, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin)); - if ( bcolor.isValid() ) { - painter.setBrush(QBrush(bcolor.toQColor())); - } - else { - painter.setBrush(Qt::NoBrush); - } + if (bcolor.isValid()) { + painter.setBrush(QBrush(bcolor.toQColor())); + } else { + painter.setBrush(Qt::NoBrush); + } - int offset = painter.testRenderHint(QPainter::Antialiasing) ? 1 : 0; + int offset = painter.testRenderHint(QPainter::Antialiasing) ? 1 : 0; - painter.drawRect( + painter.drawRect( x + penWidth / 2 + offset, y + penWidth / 2 + offset, qMax(1, width - penWidth - offset), diff --git a/tools/rectangular/kpToolRectangularBase.h b/tools/rectangular/kpToolRectangularBase.h --- a/tools/rectangular/kpToolRectangularBase.h +++ b/tools/rectangular/kpToolRectangularBase.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,75 +24,69 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_RECTANGULAR_BASE_H #define KP_TOOL_RECTANGULAR_BASE_H - #include "imagelib/kpImage.h" #include "tools/kpTool.h" - class QPoint; class QRect; class QString; class kpColor; - struct kpToolRectangularBasePrivate; - // it turns out that these shapes are all really the same thing // (same options, same feel) - the only real difference is the // drawing function i.e. drawShape(). class kpToolRectangularBase : public kpTool { -Q_OBJECT + Q_OBJECT public: - typedef void (*DrawShapeFunc) (kpImage * /*image*/, - int /*x*/, int /*y*/, int /*width*/, int /*height*/, - const kpColor &/*fcolor*/, int /*penWidth = 1*/, - const kpColor &/*bcolor = kpColor::Invalid*/); + typedef void (*DrawShapeFunc)(kpImage * /*image*/, int /*x*/, int /*y*/, int /*width*/, + int /*height*/, const kpColor & /*fcolor*/, int /*penWidth = 1*/, + const kpColor & /*bcolor = kpColor::Invalid*/); kpToolRectangularBase (const QString &text, const QString &description, - DrawShapeFunc drawShapeFunc, - int key, - kpToolEnvironment *environ, QObject *parent, - const QString &name); + DrawShapeFunc drawShapeFunc, int key, kpToolEnvironment *environ, + QObject *parent, const QString &name); ~kpToolRectangularBase () override; - bool careAboutModifierState () const override { return true; } + bool careAboutModifierState() const override + { + return true; + } private slots: - virtual void slotLineWidthChanged (); - virtual void slotFillStyleChanged (); + virtual void slotLineWidthChanged(); + virtual void slotFillStyleChanged(); private: - QString haventBegunDrawUserMessage () const; + QString haventBegunDrawUserMessage() const; public: - void begin () override; - void end () override; + void begin() override; + void end() override; private: - void applyModifiers (); - void beginDraw () override; + void applyModifiers(); + void beginDraw() override; private: - kpColor drawingForegroundColor () const; - kpColor drawingBackgroundColor () const; - void updateShape (); + kpColor drawingForegroundColor() const; + kpColor drawingBackgroundColor() const; + void updateShape(); public: - void draw (const QPoint &, const QPoint &, const QRect &) override; - void cancelShape () override; - void releasedAllButtons () override; - void endDraw (const QPoint &, const QRect &) override; + void draw(const QPoint &, const QPoint &, const QRect &) override; + void cancelShape() override; + void releasedAllButtons() override; + void endDraw(const QPoint &, const QRect &) override; private: - kpToolRectangularBasePrivate * const d; + kpToolRectangularBasePrivate *const d; }; - #endif // KP_TOOL_RECTANGULAR_BASE_H diff --git a/tools/rectangular/kpToolRectangularBase.cpp b/tools/rectangular/kpToolRectangularBase.cpp --- a/tools/rectangular/kpToolRectangularBase.cpp +++ b/tools/rectangular/kpToolRectangularBase.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_RECTANGULAR_BASE 0 - #include "tools/rectangular/kpToolRectangularBase.h" #include @@ -51,7 +48,6 @@ #include "views/kpView.h" #include "views/manager/kpViewManager.h" - //--------------------------------------------------------------------- struct kpToolRectangularBasePrivate @@ -67,15 +63,11 @@ //--------------------------------------------------------------------- kpToolRectangularBase::kpToolRectangularBase ( - const QString &text, - const QString &description, - DrawShapeFunc drawShapeFunc, - int key, - kpToolEnvironment *environ, QObject *parent, - const QString &name) - - : kpTool (text, description, key, environ, parent, name), - d (new kpToolRectangularBasePrivate ()) + const QString &text, const QString &description, DrawShapeFunc drawShapeFunc, int key, + kpToolEnvironment *environ, QObject *parent, const QString &name) + + : kpTool(text, description, key, environ, parent, name) + , d(new kpToolRectangularBasePrivate()) { d->drawShapeFunc = drawShapeFunc; @@ -92,153 +84,138 @@ //--------------------------------------------------------------------- - // private slot virtual -void kpToolRectangularBase::slotLineWidthChanged () +void kpToolRectangularBase::slotLineWidthChanged() { - if (hasBegunDraw ()) { - updateShape (); + if (hasBegunDraw()) { + updateShape(); } } //--------------------------------------------------------------------- // private slot virtual -void kpToolRectangularBase::slotFillStyleChanged () +void kpToolRectangularBase::slotFillStyleChanged() { - if (hasBegunDraw ()) { - updateShape (); + if (hasBegunDraw()) { + updateShape(); } } //--------------------------------------------------------------------- // private -QString kpToolRectangularBase::haventBegunDrawUserMessage () const +QString kpToolRectangularBase::haventBegunDrawUserMessage() const { - return i18n ("Drag to draw."); + return i18n("Drag to draw."); } //--------------------------------------------------------------------- // virtual -void kpToolRectangularBase::begin () +void kpToolRectangularBase::begin() { #if DEBUG_KP_TOOL_RECTANGULAR_BASE qCDebug(kpLogTools) << "kpToolRectangularBase::begin ()"; #endif - kpToolToolBar *tb = toolToolBar (); - Q_ASSERT (tb); + kpToolToolBar *tb = toolToolBar(); + Q_ASSERT(tb); #if DEBUG_KP_TOOL_RECTANGULAR_BASE qCDebug(kpLogTools) << "\ttoolToolBar=" << tb; #endif - d->toolWidgetLineWidth = tb->toolWidgetLineWidth (); - connect (d->toolWidgetLineWidth, &kpToolWidgetLineWidth::lineWidthChanged, - this, &kpToolRectangularBase::slotLineWidthChanged); - d->toolWidgetLineWidth->show (); + d->toolWidgetLineWidth = tb->toolWidgetLineWidth(); + connect(d->toolWidgetLineWidth, &kpToolWidgetLineWidth::lineWidthChanged, + this, &kpToolRectangularBase::slotLineWidthChanged); + d->toolWidgetLineWidth->show(); - d->toolWidgetFillStyle = tb->toolWidgetFillStyle (); - connect (d->toolWidgetFillStyle, &kpToolWidgetFillStyle::fillStyleChanged, - this, &kpToolRectangularBase::slotFillStyleChanged); - d->toolWidgetFillStyle->show (); + d->toolWidgetFillStyle = tb->toolWidgetFillStyle(); + connect(d->toolWidgetFillStyle, &kpToolWidgetFillStyle::fillStyleChanged, + this, &kpToolRectangularBase::slotFillStyleChanged); + d->toolWidgetFillStyle->show(); - viewManager ()->setCursor (QCursor (Qt::ArrowCursor)); + viewManager()->setCursor(QCursor(Qt::ArrowCursor)); - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- // virtual -void kpToolRectangularBase::end () +void kpToolRectangularBase::end() { #if DEBUG_KP_TOOL_RECTANGULAR_BASE qCDebug(kpLogTools) << "kpToolRectangularBase::end ()"; #endif - if (d->toolWidgetLineWidth) - { - disconnect (d->toolWidgetLineWidth, &kpToolWidgetLineWidth::lineWidthChanged, - this, &kpToolRectangularBase::slotLineWidthChanged); + if (d->toolWidgetLineWidth) { + disconnect(d->toolWidgetLineWidth, &kpToolWidgetLineWidth::lineWidthChanged, + this, &kpToolRectangularBase::slotLineWidthChanged); d->toolWidgetLineWidth = nullptr; } - if (d->toolWidgetFillStyle) - { - disconnect (d->toolWidgetFillStyle, &kpToolWidgetFillStyle::fillStyleChanged, - this, &kpToolRectangularBase::slotFillStyleChanged); + if (d->toolWidgetFillStyle) { + disconnect(d->toolWidgetFillStyle, &kpToolWidgetFillStyle::fillStyleChanged, + this, &kpToolRectangularBase::slotFillStyleChanged); d->toolWidgetFillStyle = nullptr; } - viewManager ()->unsetCursor (); + viewManager()->unsetCursor(); } //--------------------------------------------------------------------- -void kpToolRectangularBase::applyModifiers () +void kpToolRectangularBase::applyModifiers() { - QRect rect = normalizedRect (); + QRect rect = normalizedRect(); #if DEBUG_KP_TOOL_RECTANGULAR_BASE qCDebug(kpLogTools) << "kpToolRectangularBase::applyModifiers(" << rect - << ") shift=" << shiftPressed () - << " ctrl=" << controlPressed () - << endl; + << ") shift=" << shiftPressed() + << " ctrl=" << controlPressed() + << endl; #endif // user wants to startPoint () == center - if (controlPressed ()) - { - int xdiff = qAbs (startPoint ().x () - currentPoint ().x ()); - int ydiff = qAbs (startPoint ().y () - currentPoint ().y ()); - rect = QRect (startPoint ().x () - xdiff, startPoint ().y () - ydiff, - xdiff * 2 + 1, ydiff * 2 + 1); + if (controlPressed()) { + int xdiff = qAbs(startPoint().x() - currentPoint().x()); + int ydiff = qAbs(startPoint().y() - currentPoint().y()); + rect = QRect(startPoint().x() - xdiff, startPoint().y() - ydiff, + xdiff * 2 + 1, ydiff * 2 + 1); } // user wants major axis == minor axis: // rectangle --> square // rounded rectangle --> rounded square // ellipse --> circle - if (shiftPressed ()) - { - if (!controlPressed ()) - { - if (rect.width () < rect.height ()) - { - if (startPoint ().y () == rect.y ()) { - rect.setHeight (rect.width ()); + if (shiftPressed()) { + if (!controlPressed()) { + if (rect.width() < rect.height()) { + if (startPoint().y() == rect.y()) { + rect.setHeight(rect.width()); + } else { + rect.setY(rect.bottom() - rect.width() + 1); } - else { - rect.setY (rect.bottom () - rect.width () + 1); - } - } - else - { - if (startPoint ().x () == rect.x ()) { - rect.setWidth (rect.height ()); - } - else { - rect.setX (rect.right () - rect.height () + 1); + } else { + if (startPoint().x() == rect.x()) { + rect.setWidth(rect.height()); + } else { + rect.setX(rect.right() - rect.height() + 1); } } } // have to maintain the center - else - { - if (rect.width () < rect.height ()) - { - QPoint center = rect.center (); - rect.setHeight (rect.width ()); - rect.moveCenter (center); - } - else - { - QPoint center = rect.center (); - rect.setWidth (rect.height ()); - rect.moveCenter (center); + else { + if (rect.width() < rect.height()) { + QPoint center = rect.center(); + rect.setHeight(rect.width()); + rect.moveCenter(center); + } else { + QPoint center = rect.center(); + rect.setWidth(rect.height()); + rect.moveCenter(center); } } } @@ -248,141 +225,132 @@ //--------------------------------------------------------------------- -void kpToolRectangularBase::beginDraw () +void kpToolRectangularBase::beginDraw() { - setUserMessage (cancelUserMessage ()); + setUserMessage(cancelUserMessage()); } //--------------------------------------------------------------------- - // private -kpColor kpToolRectangularBase::drawingForegroundColor () const +kpColor kpToolRectangularBase::drawingForegroundColor() const { - return color (mouseButton ()); + return color(mouseButton()); } //--------------------------------------------------------------------- // private -kpColor kpToolRectangularBase::drawingBackgroundColor () const +kpColor kpToolRectangularBase::drawingBackgroundColor() const { - const kpColor foregroundColor = color (mouseButton ()); - const kpColor backgroundColor = color (1 - mouseButton ()); + const kpColor foregroundColor = color(mouseButton()); + const kpColor backgroundColor = color(1 - mouseButton()); - return d->toolWidgetFillStyle->drawingBackgroundColor ( + return d->toolWidgetFillStyle->drawingBackgroundColor( foregroundColor, backgroundColor); } //--------------------------------------------------------------------- // private -void kpToolRectangularBase::updateShape () +void kpToolRectangularBase::updateShape() { - kpImage image = document ()->getImageAt (d->toolRectangleRect); + kpImage image = document()->getImageAt(d->toolRectangleRect); // Invoke shape drawing function passed in ctor. - (*d->drawShapeFunc) (&image, - 0, 0, d->toolRectangleRect.width (), d->toolRectangleRect.height (), - drawingForegroundColor (), d->toolWidgetLineWidth->lineWidth (), - drawingBackgroundColor ()); - - kpTempImage newTempImage (false/*always display*/, - kpTempImage::SetImage/*render mode*/, - d->toolRectangleRect.topLeft (), - image); - - viewManager ()->setFastUpdates (); - viewManager ()->setTempImage (newTempImage); - viewManager ()->restoreFastUpdates (); + (*d->drawShapeFunc)(&image, + 0, 0, d->toolRectangleRect.width(), d->toolRectangleRect.height(), + drawingForegroundColor(), d->toolWidgetLineWidth->lineWidth(), + drawingBackgroundColor()); + + kpTempImage newTempImage(false /*always display*/, + kpTempImage::SetImage /*render mode*/, + d->toolRectangleRect.topLeft(), + image); + + viewManager()->setFastUpdates(); + viewManager()->setTempImage(newTempImage); + viewManager()->restoreFastUpdates(); } //--------------------------------------------------------------------- -void kpToolRectangularBase::draw (const QPoint &, const QPoint &, const QRect &) +void kpToolRectangularBase::draw(const QPoint &, const QPoint &, const QRect &) { - applyModifiers (); - - - updateShape (); + applyModifiers(); + updateShape(); // Recover the start and end points from the transformed & normalized d->toolRectangleRect // S. or S or SC or S == C // .C C - if (currentPoint ().x () >= startPoint ().x () && - currentPoint ().y () >= startPoint ().y ()) - { - setUserShapePoints (d->toolRectangleRect.topLeft (), - d->toolRectangleRect.bottomRight ()); + if (currentPoint().x() >= startPoint().x() + && currentPoint().y() >= startPoint().y()) { + setUserShapePoints(d->toolRectangleRect.topLeft(), + d->toolRectangleRect.bottomRight()); } // .C or C // S. S - else if (currentPoint ().x () >= startPoint ().x () && - currentPoint ().y () < startPoint ().y ()) - { - setUserShapePoints (d->toolRectangleRect.bottomLeft (), - d->toolRectangleRect.topRight ()); + else if (currentPoint().x() >= startPoint().x() + && currentPoint().y() < startPoint().y()) { + setUserShapePoints(d->toolRectangleRect.bottomLeft(), + d->toolRectangleRect.topRight()); } // .S or CS // C. - else if (currentPoint ().x () < startPoint ().x () && - currentPoint ().y () >= startPoint ().y ()) - { - setUserShapePoints (d->toolRectangleRect.topRight (), - d->toolRectangleRect.bottomLeft ()); + else if (currentPoint().x() < startPoint().x() + && currentPoint().y() >= startPoint().y()) { + setUserShapePoints(d->toolRectangleRect.topRight(), + d->toolRectangleRect.bottomLeft()); } // C. // .S - else - { - setUserShapePoints (d->toolRectangleRect.bottomRight (), - d->toolRectangleRect.topLeft ()); + else { + setUserShapePoints(d->toolRectangleRect.bottomRight(), + d->toolRectangleRect.topLeft()); } } //--------------------------------------------------------------------- -void kpToolRectangularBase::cancelShape () +void kpToolRectangularBase::cancelShape() { - viewManager ()->invalidateTempImage (); + viewManager()->invalidateTempImage(); - setUserMessage (i18n ("Let go of all the mouse buttons.")); + setUserMessage(i18n("Let go of all the mouse buttons.")); } //--------------------------------------------------------------------- -void kpToolRectangularBase::releasedAllButtons () +void kpToolRectangularBase::releasedAllButtons() { - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- -void kpToolRectangularBase::endDraw (const QPoint &, const QRect &) +void kpToolRectangularBase::endDraw(const QPoint &, const QRect &) { - applyModifiers (); + applyModifiers(); // TODO: flicker // Later: So why can't we use kpViewManager::setQueueUpdates()? Check SVN // log to see if this method was not available at the time of the // TODO, hence justifying the TODO. // Later2: kpToolPolygonalBase, and perhaps, other shapes will have the // same problem. - viewManager ()->invalidateTempImage (); + viewManager()->invalidateTempImage(); - environ ()->commandHistory ()->addCommand ( - new kpToolRectangularCommand ( - text (), + environ()->commandHistory()->addCommand( + new kpToolRectangularCommand( + text(), d->drawShapeFunc, d->toolRectangleRect, - drawingForegroundColor (), d->toolWidgetLineWidth->lineWidth (), - drawingBackgroundColor (), - environ ()->commandEnvironment ())); + drawingForegroundColor(), d->toolWidgetLineWidth->lineWidth(), + drawingBackgroundColor(), + environ()->commandEnvironment())); - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- - - diff --git a/tools/rectangular/kpToolRoundedRectangle.h b/tools/rectangular/kpToolRoundedRectangle.h --- a/tools/rectangular/kpToolRoundedRectangle.h +++ b/tools/rectangular/kpToolRoundedRectangle.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,20 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_ROUNDED_RECTANGLE_H #define KP_TOOL_ROUNDED_RECTANGLE_H - #include "tools/rectangular/kpToolRectangularBase.h" - class kpToolRoundedRectangle : public kpToolRectangularBase { -Q_OBJECT + Q_OBJECT public: kpToolRoundedRectangle (kpToolEnvironment *environ, QObject *parent); - static void drawRoundedRect(kpImage *image, - int x, int y, int width, int height, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor); + static void drawRoundedRect(kpImage *image, int x, int y, int width, int height, + const kpColor &fcolor, int penWidth, const kpColor &bcolor); }; - #endif // KP_TOOL_ROUNDED_RECTANGLE_H diff --git a/tools/rectangular/kpToolRoundedRectangle.cpp b/tools/rectangular/kpToolRoundedRectangle.cpp --- a/tools/rectangular/kpToolRoundedRectangle.cpp +++ b/tools/rectangular/kpToolRoundedRectangle.cpp @@ -39,46 +39,44 @@ //--------------------------------------------------------------------- kpToolRoundedRectangle::kpToolRoundedRectangle (kpToolEnvironment *environ, QObject *parent) - : kpToolRectangularBase (i18n ("Rounded Rectangle"), - i18n ("Draws rectangles and squares with rounded corners"), - &kpToolRoundedRectangle::drawRoundedRect, - Qt::Key_U, - environ, parent, QStringLiteral("tool_rounded_rectangle")) + : kpToolRectangularBase(i18n("Rounded Rectangle"), + i18n("Draws rectangles and squares with rounded corners"), + &kpToolRoundedRectangle::drawRoundedRect, + Qt::Key_U, + environ, parent, QStringLiteral("tool_rounded_rectangle")) { } //--------------------------------------------------------------------- -void kpToolRoundedRectangle::drawRoundedRect(kpImage *image, - int x, int y, int width, int height, - const kpColor &fcolor, int penWidth, - const kpColor &bcolor) +void kpToolRoundedRectangle::drawRoundedRect(kpImage *image, int x, int y, int width, int height, + const kpColor &fcolor, int penWidth, + const kpColor &bcolor) { - if ( (width == 0) || (height == 0) ) { - return; - } + if ((width == 0) || (height == 0)) { + return; + } - QPainter painter(image); - painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); + QPainter painter(image); + painter.setRenderHint(QPainter::Antialiasing, kpToolEnvironment::drawAntiAliased); - if ( ((2 * penWidth) > width) || ((2 * penWidth) > height) ) { - penWidth = qMin(width, height) / 2; - } + if (((2 * penWidth) > width) || ((2 * penWidth) > height)) { + penWidth = qMin(width, height) / 2; + } - painter.setPen(QPen(fcolor.toQColor(), penWidth, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin)); + painter.setPen(QPen(fcolor.toQColor(), penWidth, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin)); - if ( bcolor.isValid() ) { - painter.setBrush(QBrush(bcolor.toQColor())); - } - else { - painter.setBrush(Qt::NoBrush); - } + if (bcolor.isValid()) { + painter.setBrush(QBrush(bcolor.toQColor())); + } else { + painter.setBrush(Qt::NoBrush); + } - int offset = painter.testRenderHint(QPainter::Antialiasing) ? 1 : 0; + int offset = painter.testRenderHint(QPainter::Antialiasing) ? 1 : 0; - int radius = qMin(width, height) / 4; + int radius = qMin(width, height) / 4; - painter.drawRoundedRect( + painter.drawRoundedRect( x + penWidth / 2 + offset, y + penWidth / 2 + offset, qMax(1, width - penWidth - offset), diff --git a/tools/selection/image/kpAbstractImageSelectionTool.h b/tools/selection/image/kpAbstractImageSelectionTool.h --- a/tools/selection/image/kpAbstractImageSelectionTool.h +++ b/tools/selection/image/kpAbstractImageSelectionTool.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,17 +24,13 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpAbstractImageSelectionTool_H #define kpAbstractImageSelectionTool_H - #include "tools/selection/kpAbstractSelectionTool.h" - class kpImageSelectionTransparency; - // The only difference between the various subclasses of us is the kind of // selection that they create e.g. elliptical vs rectangular. // @@ -47,41 +42,37 @@ // kpDocumentEnvironment::switchToCompatibleTool()). class kpAbstractImageSelectionTool : public kpAbstractSelectionTool { -Q_OBJECT + Q_OBJECT public: - kpAbstractImageSelectionTool (const QString &text, const QString &description, - int key, - kpToolSelectionEnvironment *environ, QObject *parent, - const QString &name); - + kpAbstractImageSelectionTool (const QString &text, const QString &description, int key, + kpToolSelectionEnvironment *environ, QObject *parent, + const QString &name); // // Drawing // protected: - kpAbstractSelectionContentCommand *newGiveContentCommand () const override; - - QString nameOfCreateCommand () const override; + kpAbstractSelectionContentCommand *newGiveContentCommand() const override; + QString nameOfCreateCommand() const override; // // Create, Move, Resize/Scale // protected: - QString haventBegunDrawUserMessageCreate () const override; - QString haventBegunDrawUserMessageMove () const override; - QString haventBegunDrawUserMessageResizeScale () const override; - + QString haventBegunDrawUserMessageCreate() const override; + QString haventBegunDrawUserMessageMove() const override; + QString haventBegunDrawUserMessageResizeScale() const override; // // User Changing Selection Transparency // protected: - bool shouldChangeImageSelectionTransparency () const; + bool shouldChangeImageSelectionTransparency() const; // You must derive , the old selection transparency, from the // one obtained from the user's current settings, as given by the // kpToolSelectionEnvironment. @@ -91,16 +82,14 @@ // "document()->imageSelection().transparency()". The reason is that // transparency().transparentColor() might not be defined in Opaque // Mode. - void changeImageSelectionTransparency ( - const QString &name, - const kpImageSelectionTransparency &newTrans, + void changeImageSelectionTransparency( + const QString &name, const kpImageSelectionTransparency &newTrans, const kpImageSelectionTransparency &oldTrans); protected slots: - void slotIsOpaqueChanged (bool isOpaque) override; - void slotBackgroundColorChanged (const kpColor &color) override; - void slotColorSimilarityChanged (double similarity, int) override; + void slotIsOpaqueChanged(bool isOpaque) override; + void slotBackgroundColorChanged(const kpColor &color) override; + void slotColorSimilarityChanged(double similarity, int) override; }; - #endif // kpAbstractImageSelectionTool_H diff --git a/tools/selection/image/kpAbstractImageSelectionTool.cpp b/tools/selection/image/kpAbstractImageSelectionTool.cpp --- a/tools/selection/image/kpAbstractImageSelectionTool.cpp +++ b/tools/selection/image/kpAbstractImageSelectionTool.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpAbstractImageSelectionTool.h" #include @@ -38,66 +36,63 @@ //--------------------------------------------------------------------- kpAbstractImageSelectionTool::kpAbstractImageSelectionTool ( - const QString &text, const QString &description, - int key, - kpToolSelectionEnvironment *environ, QObject *parent, - const QString &name) - : kpAbstractSelectionTool (text, description, - key, environ, parent, name) + const QString &text, const QString &description, int key, kpToolSelectionEnvironment *environ, + QObject *parent, const QString &name) + : kpAbstractSelectionTool(text, description, + key, environ, parent, name) { } //--------------------------------------------------------------------- // protected virtual [kpAbstractSelectionTool] -kpAbstractSelectionContentCommand *kpAbstractImageSelectionTool::newGiveContentCommand () const +kpAbstractSelectionContentCommand *kpAbstractImageSelectionTool::newGiveContentCommand() const { - kpAbstractImageSelection *imageSel = document ()->imageSelection (); - Q_ASSERT (imageSel && !imageSel->hasContent ()); + kpAbstractImageSelection *imageSel = document()->imageSelection(); + Q_ASSERT(imageSel && !imageSel->hasContent()); - if (imageSel->transparency ().isTransparent ()) { - environ ()->flashColorSimilarityToolBarItem (); + if (imageSel->transparency().isTransparent()) { + environ()->flashColorSimilarityToolBarItem(); } - return new kpToolSelectionPullFromDocumentCommand ( - *imageSel, - environ ()->backgroundColor (), - QString()/*uninteresting child of macro cmd*/, - environ ()->commandEnvironment ()); + return new kpToolSelectionPullFromDocumentCommand( + *imageSel, + environ()->backgroundColor(), + QString() /*uninteresting child of macro cmd*/, + environ()->commandEnvironment()); } //--------------------------------------------------------------------- // protected virtual [kpAbstractSelectionTool] -QString kpAbstractImageSelectionTool::nameOfCreateCommand () const +QString kpAbstractImageSelectionTool::nameOfCreateCommand() const { - return i18n ("Selection: Create"); + return i18n("Selection: Create"); } //--------------------------------------------------------------------- // protected virtual [kpAbstractSelectionTool] -QString kpAbstractImageSelectionTool::haventBegunDrawUserMessageCreate () const +QString kpAbstractImageSelectionTool::haventBegunDrawUserMessageCreate() const { // TODO: This is wrong because you can still use RMB. - return i18n ("Left drag to create selection."); + return i18n("Left drag to create selection."); } //--------------------------------------------------------------------- // protected virtual [kpAbstractSelectionTool] -QString kpAbstractImageSelectionTool::haventBegunDrawUserMessageMove () const +QString kpAbstractImageSelectionTool::haventBegunDrawUserMessageMove() const { - return i18n ("Left drag to move selection."); + return i18n("Left drag to move selection."); } //--------------------------------------------------------------------- // protected virtual [kpAbstractSelectionTool] -QString kpAbstractImageSelectionTool::haventBegunDrawUserMessageResizeScale () const +QString kpAbstractImageSelectionTool::haventBegunDrawUserMessageResizeScale() const { - return i18n ("Left drag to scale selection."); + return i18n("Left drag to scale selection."); } //--------------------------------------------------------------------- - diff --git a/tools/selection/image/kpAbstractImageSelectionTool_Transparency.cpp b/tools/selection/image/kpAbstractImageSelectionTool_Transparency.cpp --- a/tools/selection/image/kpAbstractImageSelectionTool_Transparency.cpp +++ b/tools/selection/image/kpAbstractImageSelectionTool_Transparency.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpAbstractImageSelectionTool.h" #include "layers/selections/image/kpAbstractImageSelection.h" @@ -54,20 +51,18 @@ #include - // protected -bool kpAbstractImageSelectionTool::shouldChangeImageSelectionTransparency () const +bool kpAbstractImageSelectionTool::shouldChangeImageSelectionTransparency() const { - if (environ ()->settingImageSelectionTransparency ()) - { + if (environ()->settingImageSelectionTransparency()) { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "\trecursion - abort setting selection transparency: " - << environ ()->settingImageSelectionTransparency (); + << environ()->settingImageSelectionTransparency(); #endif return false; } - if (!document ()->imageSelection ()) { + if (!document()->imageSelection()) { return false; } @@ -79,28 +74,27 @@ } // protected -void kpAbstractImageSelectionTool::changeImageSelectionTransparency ( - const QString &name, - const kpImageSelectionTransparency &newTrans, - const kpImageSelectionTransparency &oldTrans) +void kpAbstractImageSelectionTool::changeImageSelectionTransparency( + const QString &name, const kpImageSelectionTransparency &newTrans, + const kpImageSelectionTransparency &oldTrans) { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "CALL(" << name << ")"; #endif - kpSetOverrideCursorSaver cursorSaver (Qt::WaitCursor); + kpSetOverrideCursorSaver cursorSaver(Qt::WaitCursor); - if (hasBegunShape ()) { - endShapeInternal (); + if (hasBegunShape()) { + endShapeInternal(); } - kpAbstractImageSelection *imageSel = document ()->imageSelection (); + kpAbstractImageSelection *imageSel = document()->imageSelection(); - if (imageSel->hasContent () && newTrans.isTransparent ()) { - environ ()->flashColorSimilarityToolBarItem (); + if (imageSel->hasContent() && newTrans.isTransparent()) { + environ()->flashColorSimilarityToolBarItem(); } - imageSel->setTransparency (newTrans); + imageSel->setTransparency(newTrans); // We _must_ add the command even if kpAbstractImageSelection::setTransparency() // above did not change the selection transparency mask at all. @@ -133,75 +127,74 @@ // has moved us to an incorrect state. // // KDE3: Copy this comment into the KDE 3 branch. - commandHistory ()->addCommand (new kpToolImageSelectionTransparencyCommand ( - name, - newTrans, oldTrans, - environ ()->commandEnvironment ()), - false/*no exec*/); + commandHistory()->addCommand(new kpToolImageSelectionTransparencyCommand( + name, + newTrans, oldTrans, + environ()->commandEnvironment()), + false /*no exec*/); } - // protected slot virtual [kpAbstractSelectionTool] -void kpAbstractImageSelectionTool::slotIsOpaqueChanged (bool /*isOpaque*/) +void kpAbstractImageSelectionTool::slotIsOpaqueChanged(bool /*isOpaque*/) { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "kpAbstractImageSelectionTool::slotIsOpaqueChanged()"; #endif - if (!shouldChangeImageSelectionTransparency ()) { + if (!shouldChangeImageSelectionTransparency()) { return; } - kpImageSelectionTransparency st = environ ()->imageSelectionTransparency (); + kpImageSelectionTransparency st = environ()->imageSelectionTransparency(); kpImageSelectionTransparency oldST = st; - oldST.setOpaque (!oldST.isOpaque ()); + oldST.setOpaque(!oldST.isOpaque()); - changeImageSelectionTransparency ( - st.isOpaque () ? - i18n ("Selection: Opaque") : - i18n ("Selection: Transparent"), + changeImageSelectionTransparency( + st.isOpaque() + ? i18n("Selection: Opaque") + : i18n("Selection: Transparent"), st, oldST); } // protected slot virtual [base kpTool] -void kpAbstractImageSelectionTool::slotBackgroundColorChanged (const kpColor &) +void kpAbstractImageSelectionTool::slotBackgroundColorChanged(const kpColor &) { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "kpAbstractImageSelectionTool::slotBackgroundColorChanged()"; #endif - if (!shouldChangeImageSelectionTransparency ()) { + if (!shouldChangeImageSelectionTransparency()) { return; } - kpImageSelectionTransparency st = environ ()->imageSelectionTransparency (); + kpImageSelectionTransparency st = environ()->imageSelectionTransparency(); kpImageSelectionTransparency oldST = st; - oldST.setTransparentColor (oldBackgroundColor ()); + oldST.setTransparentColor(oldBackgroundColor()); - changeImageSelectionTransparency ( - i18n ("Selection: Transparency Color"), + changeImageSelectionTransparency( + i18n("Selection: Transparency Color"), st, oldST); } // protected slot virtual [base kpTool] -void kpAbstractImageSelectionTool::slotColorSimilarityChanged (double, int) +void kpAbstractImageSelectionTool::slotColorSimilarityChanged(double, int) { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "kpAbstractImageSelectionTool::slotColorSimilarityChanged()"; #endif - if (!shouldChangeImageSelectionTransparency ()) { + if (!shouldChangeImageSelectionTransparency()) { return; } - kpImageSelectionTransparency st = environ ()->imageSelectionTransparency (); + kpImageSelectionTransparency st = environ()->imageSelectionTransparency(); kpImageSelectionTransparency oldST = st; - oldST.setColorSimilarity (oldColorSimilarity ()); + oldST.setColorSimilarity(oldColorSimilarity()); - changeImageSelectionTransparency ( - i18n ("Selection: Transparency Color Similarity"), + changeImageSelectionTransparency( + i18n("Selection: Transparency Color Similarity"), st, oldST); } diff --git a/tools/selection/image/kpToolEllipticalSelection.h b/tools/selection/image/kpToolEllipticalSelection.h --- a/tools/selection/image/kpToolEllipticalSelection.h +++ b/tools/selection/image/kpToolEllipticalSelection.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,21 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_ELLIPTICAL_SELECTION_H #define KP_TOOL_ELLIPTICAL_SELECTION_H - #include "kpAbstractImageSelectionTool.h" - class kpToolEllipticalSelection : public kpAbstractImageSelectionTool { public: kpToolEllipticalSelection (kpToolSelectionEnvironment *environ, QObject *parent); ~kpToolEllipticalSelection () override; protected: - bool drawCreateMoreSelectionAndUpdateStatusBar ( - bool dragAccepted, - const QPoint &accidentalDragAdjustedPoint, + bool drawCreateMoreSelectionAndUpdateStatusBar( + bool dragAccepted, const QPoint &accidentalDragAdjustedPoint, const QRect &normalizedRect) override; }; - #endif // KP_TOOL_ELLIPTICAL_SELECTION_H diff --git a/tools/selection/image/kpToolEllipticalSelection.cpp b/tools/selection/image/kpToolEllipticalSelection.cpp --- a/tools/selection/image/kpToolEllipticalSelection.cpp +++ b/tools/selection/image/kpToolEllipticalSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_ELLIPTICAL_SELECTION 0 - #include "kpToolEllipticalSelection.h" #include "kpLogCategories.h" @@ -38,42 +36,38 @@ #include kpToolEllipticalSelection::kpToolEllipticalSelection (kpToolSelectionEnvironment *environ, - QObject *parent) - : kpAbstractImageSelectionTool (i18n ("Selection (Elliptical)"), - i18n ("Makes an elliptical or circular selection"), - Qt::Key_I, - environ, parent, - QStringLiteral("tool_elliptical_selection")) + QObject *parent) + : kpAbstractImageSelectionTool(i18n("Selection (Elliptical)"), + i18n("Makes an elliptical or circular selection"), + Qt::Key_I, + environ, parent, + QStringLiteral("tool_elliptical_selection")) { } kpToolEllipticalSelection::~kpToolEllipticalSelection () = default; - // protected virtual [base kpAbstractSelectionTool] -bool kpToolEllipticalSelection::drawCreateMoreSelectionAndUpdateStatusBar ( - bool dragAccepted, - const QPoint &accidentalDragAdjustedPoint, - const QRect &normalizedRect) +bool kpToolEllipticalSelection::drawCreateMoreSelectionAndUpdateStatusBar( + bool dragAccepted, const QPoint &accidentalDragAdjustedPoint, const QRect &normalizedRect) { // Prevent unintentional creation of 1-pixel selections. - if (!dragAccepted && accidentalDragAdjustedPoint == startPoint ()) - { + if (!dragAccepted && accidentalDragAdjustedPoint == startPoint()) { #if DEBUG_KP_TOOL_ELLIPTICAL_SELECTION && 1 qCDebug(kpLogTools) << "\tnon-text NOP - return"; #endif - setUserShapePoints (accidentalDragAdjustedPoint); + setUserShapePoints(accidentalDragAdjustedPoint); return false; } - Q_ASSERT (accidentalDragAdjustedPoint == currentPoint ()); + Q_ASSERT(accidentalDragAdjustedPoint == currentPoint()); - document ()->setSelection ( - kpEllipticalImageSelection ( + document()->setSelection( + kpEllipticalImageSelection( normalizedRect, - environ ()->imageSelectionTransparency ())); + environ()->imageSelectionTransparency())); - setUserShapePoints (startPoint (), currentPoint ()); + setUserShapePoints(startPoint(), currentPoint()); return true; } diff --git a/tools/selection/image/kpToolFreeFormSelection.h b/tools/selection/image/kpToolFreeFormSelection.h --- a/tools/selection/image/kpToolFreeFormSelection.h +++ b/tools/selection/image/kpToolFreeFormSelection.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,21 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_FREE_FORM_SELECTION_H #define KP_TOOL_FREE_FORM_SELECTION_H - #include "kpAbstractImageSelectionTool.h" - class kpToolFreeFormSelection : public kpAbstractImageSelectionTool { public: kpToolFreeFormSelection (kpToolSelectionEnvironment *environ, QObject *parent); ~kpToolFreeFormSelection () override; protected: - bool drawCreateMoreSelectionAndUpdateStatusBar ( - bool dragAccepted, - const QPoint &accidentalDragAdjustedPoint, + bool drawCreateMoreSelectionAndUpdateStatusBar( + bool dragAccepted, const QPoint &accidentalDragAdjustedPoint, const QRect &normalizedRect) override; }; - #endif // KP_TOOL_FREE_FORM_SELECTION_H diff --git a/tools/selection/image/kpToolFreeFormSelection.cpp b/tools/selection/image/kpToolFreeFormSelection.cpp --- a/tools/selection/image/kpToolFreeFormSelection.cpp +++ b/tools/selection/image/kpToolFreeFormSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_FREE_FROM_SELECTION 0 - #include "kpToolFreeFormSelection.h" #include "kpLogCategories.h" @@ -41,12 +38,12 @@ //--------------------------------------------------------------------- kpToolFreeFormSelection::kpToolFreeFormSelection (kpToolSelectionEnvironment *environ, - QObject *parent) - : kpAbstractImageSelectionTool (i18n ("Selection (Free-Form)"), - i18n ("Makes a free-form selection"), - Qt::Key_M, - environ, parent, - QStringLiteral("tool_free_form_selection")) + QObject *parent) + : kpAbstractImageSelectionTool(i18n("Selection (Free-Form)"), + i18n("Makes a free-form selection"), + Qt::Key_M, + environ, parent, + QStringLiteral("tool_free_form_selection")) { } @@ -57,81 +54,72 @@ //--------------------------------------------------------------------- // protected virtual [base kpAbstractSelectionTool] -bool kpToolFreeFormSelection::drawCreateMoreSelectionAndUpdateStatusBar ( - bool dragAccepted, - const QPoint &accidentalDragAdjustedPoint, - const QRect &/*normalizedRect*/) +bool kpToolFreeFormSelection::drawCreateMoreSelectionAndUpdateStatusBar( + bool dragAccepted, const QPoint &accidentalDragAdjustedPoint, const QRect & /*normalizedRect*/) { #if DEBUG_KP_TOOL_FREE_FROM_SELECTION qCDebug(kpLogTools) << "kpToolFreeFormSelection::createMoreSelectionAndUpdateStatusBar(" - << "dragAccepted=" << dragAccepted - << ",accidentalDragAdjustedPoint=" << accidentalDragAdjustedPoint - << ")"; + << "dragAccepted=" << dragAccepted + << ",accidentalDragAdjustedPoint=" << accidentalDragAdjustedPoint + << ")"; #endif // Prevent unintentional creation of 1-pixel selections. - if (!dragAccepted && accidentalDragAdjustedPoint == startPoint ()) - { + if (!dragAccepted && accidentalDragAdjustedPoint == startPoint()) { #if DEBUG_KP_TOOL_FREE_FROM_SELECTION && 1 qCDebug(kpLogTools) << "\tnon-text NOP - return"; #endif - setUserShapePoints (accidentalDragAdjustedPoint); + setUserShapePoints(accidentalDragAdjustedPoint); return false; } - Q_ASSERT (accidentalDragAdjustedPoint == currentPoint ()); - Q_ASSERT (dragAccepted == static_cast (document ()->selection ())); + Q_ASSERT(accidentalDragAdjustedPoint == currentPoint()); + Q_ASSERT(dragAccepted == static_cast(document()->selection())); const kpFreeFormImageSelection *oldPointsSel = nullptr; - if (document ()->selection ()) - { - kpAbstractSelection *sel = document ()->selection (); - Q_ASSERT (dynamic_cast (sel)); - oldPointsSel = dynamic_cast (sel); + if (document()->selection()) { + kpAbstractSelection *sel = document()->selection(); + Q_ASSERT(dynamic_cast (sel)); + oldPointsSel = dynamic_cast (sel); } - QPolygon points; // First point in drag? - if (!dragAccepted) - { - points.append (startPoint ()); + if (!dragAccepted) { + points.append(startPoint()); } // Not first point in drag. - else - { - if ( !oldPointsSel ) { // assert above says we never reach this, but let's make coverity happy + else { + if (!oldPointsSel) { // assert above says we never reach this, but let's make coverity happy return false; } - // Get existing points in selection. - points = oldPointsSel->cardinallyAdjacentPoints (); + // Get existing points in selection. + points = oldPointsSel->cardinallyAdjacentPoints(); } - #if DEBUG_KP_TOOL_FREE_FROM_SELECTION - qCDebug(kpLogTools) << "\tlast old point=" << points.last (); + qCDebug(kpLogTools) << "\tlast old point=" << points.last(); #endif // TODO: There should be an upper limit on this before drawing the // polygon becomes too slow. - points.append (accidentalDragAdjustedPoint); - + points.append(accidentalDragAdjustedPoint); - document ()->setSelection ( - kpFreeFormImageSelection (points, environ ()->imageSelectionTransparency ())); + document()->setSelection( + kpFreeFormImageSelection(points, environ()->imageSelectionTransparency())); // Prevent accidental usage of dangling pointer to old selection // (deleted by kpDocument::setSelection()). oldPointsSel = nullptr; #if DEBUG_KP_TOOL_FREE_FROM_SELECTION && 1 qCDebug(kpLogTools) << "\t\tfreeform; #points=" - << document ()->selection ()->calculatePoints ().count (); + << document()->selection()->calculatePoints().count(); #endif - setUserShapePoints (accidentalDragAdjustedPoint); + setUserShapePoints(accidentalDragAdjustedPoint); return true; } diff --git a/tools/selection/image/kpToolRectSelection.h b/tools/selection/image/kpToolRectSelection.h --- a/tools/selection/image/kpToolRectSelection.h +++ b/tools/selection/image/kpToolRectSelection.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,21 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_RECT_SELECTION_H #define KP_TOOL_RECT_SELECTION_H - #include "kpAbstractImageSelectionTool.h" - class kpToolRectSelection : public kpAbstractImageSelectionTool { public: kpToolRectSelection (kpToolSelectionEnvironment *environ, QObject *parent); ~kpToolRectSelection () override; protected: - bool drawCreateMoreSelectionAndUpdateStatusBar ( - bool dragAccepted, - const QPoint &accidentalDragAdjustedPoint, + bool drawCreateMoreSelectionAndUpdateStatusBar( + bool dragAccepted, const QPoint &accidentalDragAdjustedPoint, const QRect &normalizedRect) override; }; - #endif // KP_TOOL_RECT_SELECTION_H diff --git a/tools/selection/image/kpToolRectSelection.cpp b/tools/selection/image/kpToolRectSelection.cpp --- a/tools/selection/image/kpToolRectSelection.cpp +++ b/tools/selection/image/kpToolRectSelection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -35,47 +34,42 @@ #include -kpToolRectSelection::kpToolRectSelection (kpToolSelectionEnvironment *environ, - QObject *parent) - : kpAbstractImageSelectionTool (i18n ("Selection (Rectangular)"), - i18n ("Makes a rectangular selection"), - Qt::Key_S, - environ, parent, - QStringLiteral("tool_rect_selection")) +kpToolRectSelection::kpToolRectSelection (kpToolSelectionEnvironment *environ, QObject *parent) + : kpAbstractImageSelectionTool(i18n("Selection (Rectangular)"), + i18n("Makes a rectangular selection"), + Qt::Key_S, + environ, parent, + QStringLiteral("tool_rect_selection")) { } kpToolRectSelection::~kpToolRectSelection () = default; - // protected virtual [base kpAbstractSelectionTool] -bool kpToolRectSelection::drawCreateMoreSelectionAndUpdateStatusBar ( - bool dragAccepted, - const QPoint &accidentalDragAdjustedPoint, - const QRect &normalizedRect) +bool kpToolRectSelection::drawCreateMoreSelectionAndUpdateStatusBar( + bool dragAccepted, const QPoint &accidentalDragAdjustedPoint, const QRect &normalizedRect) { // Prevent unintentional creation of 1-pixel selections. // REFACTOR: This line is duplicated code with other tools. - if (!dragAccepted && accidentalDragAdjustedPoint == startPoint ()) - { + if (!dragAccepted && accidentalDragAdjustedPoint == startPoint()) { #if DEBUG_KP_TOOL_RECT_SELECTION && 1 qCDebug(kpLogTools) << "\tnon-text NOP - return"; #endif - setUserShapePoints (accidentalDragAdjustedPoint); + setUserShapePoints(accidentalDragAdjustedPoint); return false; } - Q_ASSERT (accidentalDragAdjustedPoint == currentPoint ()); + Q_ASSERT(accidentalDragAdjustedPoint == currentPoint()); - const QRect usefulRect = normalizedRect.intersected (document ()->rect ()); - document ()->setSelection ( - kpRectangularImageSelection ( + const QRect usefulRect = normalizedRect.intersected(document()->rect()); + document()->setSelection( + kpRectangularImageSelection( usefulRect, - environ ()->imageSelectionTransparency ())); + environ()->imageSelectionTransparency())); - setUserShapePoints (startPoint (), - QPoint (qMax (0, qMin (currentPoint ().x (), document ()->width () - 1)), - qMax (0, qMin (currentPoint ().y (), document ()->height () - 1)))); + setUserShapePoints(startPoint(), + QPoint(qMax(0, qMin(currentPoint().x(), document()->width() - 1)), + qMax(0, qMin(currentPoint().y(), document()->height() - 1)))); return true; } diff --git a/tools/selection/kpAbstractSelectionTool.h b/tools/selection/kpAbstractSelectionTool.h --- a/tools/selection/kpAbstractSelectionTool.h +++ b/tools/selection/kpAbstractSelectionTool.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,16 +24,13 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpAbstractSelectionTool_H #define kpAbstractSelectionTool_H - #include "tools/kpTool.h" #include - class QKeyEvent; class QPoint; class QRect; @@ -44,7 +40,6 @@ class kpCommand; class kpToolSelectionEnvironment; - // The abstract base for all selection tools. // // @@ -110,22 +105,22 @@ // class kpAbstractSelectionTool : public kpTool { -Q_OBJECT + Q_OBJECT public: - kpAbstractSelectionTool (const QString &text, const QString &description, - int key, - kpToolSelectionEnvironment *environ, QObject *parent, - const QString &name); + kpAbstractSelectionTool (const QString &text, const QString &description, int key, + kpToolSelectionEnvironment *environ, QObject *parent, + const QString &name); ~kpAbstractSelectionTool () override; - // Inform kpTool to call draw() when CTRL, SHIFT and friends are // pressed. CTRL is used for copying, instead of moving, the // selection. SHIFT is used for sweeping. - bool careAboutModifierState () const override { return true; } - + bool careAboutModifierState() const override + { + return true; + } // // Drawing - Subclass Accessors @@ -138,28 +133,25 @@ None, Create, Move, SelectText, ResizeScale }; - // The return value is not "None" during a drawing operation. // // The returned value is set by beginDraw(), after being determined // by calculateDrawType(). It is cleared in cancelShape() and endDraw(). - DrawType drawType () const; - - bool hadSelectionBeforeDraw () const; + DrawType drawType() const; + bool hadSelectionBeforeDraw() const; // // Drawing // protected: // (overrides non-virtual method in kpTool) - kpToolSelectionEnvironment *environ () const; + kpToolSelectionEnvironment *environ() const; // Returns whether a CTRL or SHIFT key is currently pressed. // Convenience method. - bool controlOrShiftPressed () const; - + bool controlOrShiftPressed() const; protected: // Deselects the current selection: @@ -172,8 +164,7 @@ // 1. There is a current selection. // 2. You have not called giveContentIfNeeded() nor // addNeedingContentCommand() on the current selection. - void pushOntoDocument (); - + void pushOntoDocument(); // // The command lifecycle is as follows: @@ -194,7 +185,7 @@ // Returns a new instance of the give-the-selection-content command // that matches the current selection type. The command should not be // executed by this method. - virtual kpAbstractSelectionContentCommand *newGiveContentCommand () const = 0; + virtual kpAbstractSelectionContentCommand *newGiveContentCommand() const = 0; // Before changing a selection (e.g. moving or resizing), you must // ensure that it has content. Call this method to ensure that. @@ -204,11 +195,11 @@ // nothing. // // ASSUMPTION: There is a selection. - void giveContentIfNeeded (); + void giveContentIfNeeded(); // The name that should be given to command that is constructed in // response to a drag that creates a new selection. - virtual QString nameOfCreateCommand () const = 0; + virtual QString nameOfCreateCommand() const = 0; // Add a command to the command history. // The command is not executed. @@ -225,33 +216,29 @@ // // ASSUMPTION: giveContentIfNeeded() must have been called before // creating . - void addNeedingContentCommand (kpCommand *cmd); - + void addNeedingContentCommand(kpCommand *cmd); protected: // Sets the selection border mode when no drawing operation is active. // // Subclasses may wish to reimplement but should still call the base // implementation. Reimplementations should wrap the whole // reimplementation in a kpViewManager::setQueueUpdates() block. - virtual void setSelectionBorderForHaventBegunDraw (); + virtual void setSelectionBorderForHaventBegunDraw(); private: // Returns the statusbar message from when no draw operation is in // progress. Calls operation() with "HaventBegunDrawUserMessage". // // (not const due to purely syntactic issue: it calls the non-const // operation(); it really acts like a const method though) - QString haventBegunDrawUserMessage (); - + QString haventBegunDrawUserMessage(); public: - void begin () override; - void end () override; - + void begin() override; + void end() override; public: - void reselect () override; - + void reselect() override; // // Drawing - Beginning a Drag @@ -266,7 +253,7 @@ // // You are free to reimplement this and may choose to call this base // implementation or not. - virtual DrawType calculateDrawTypeInsideSelection () const; + virtual DrawType calculateDrawTypeInsideSelection() const; // Called by beginDraw() to determine what type of draw type is // being started. The returned draw type is passed to operation(). @@ -287,29 +274,26 @@ // supports "SelectText"). It also allows you to make certain // drags (e.g. dragging in the middle of a selection) do nothing by // returning "None" instead of calling the base implementation. - virtual DrawType calculateDrawType () const; + virtual DrawType calculateDrawType() const; public: - void beginDraw () override; - + void beginDraw() override; // // Drawing - Mouse Movement // public: - void hover (const QPoint &point) override; - void draw (const QPoint &thisPoint, const QPoint &lastPoint, - const QRect &normalizedRect) override; - + void hover(const QPoint &point) override; + void draw(const QPoint &thisPoint, const QPoint &lastPoint, + const QRect &normalizedRect) override; // // Drawing - Ending a Drag // public: - void cancelShape () override; - void releasedAllButtons () override; - + void cancelShape() override; + void releasedAllButtons() override; protected: // Displays the right-mouse-button-triggered selection menu, re-entering @@ -321,10 +305,9 @@ // If you are calling this from a view/tool event handler, // either make all your handlers re-entrant or do not put any // code in your handler after the call. - void popupRMBMenu (); + void popupRMBMenu(); public: - void endDraw (const QPoint &thisPoint, const QRect &normalizedRect) override; - + void endDraw(const QPoint &thisPoint, const QRect &normalizedRect) override; // // Drawing - Operation Dispatching @@ -343,52 +326,47 @@ SetCursor, - // // Called to start, to end, or inside, a drawing operation. // BeginDraw, Draw, Cancel, EndDraw }; // (See the class API Doc for a description). - virtual QVariant operation (DrawType drawType, Operation op, - const QVariant &data1 = QVariant (), const QVariant &data2 = QVariant ()); - + virtual QVariant operation(DrawType drawType, Operation op, + const QVariant &data1 = QVariant(), + const QVariant &data2 = QVariant()); // // Create // private: // Called by constructor to initialize the "Create" draw type. - void initCreate (); + void initCreate(); // Called by destructor to uninitialize the "Create" draw type. - void uninitCreate (); - + void uninitCreate(); private: - void beginCreate (); - void endCreate (); - + void beginCreate(); + void endCreate(); protected: - virtual QString haventBegunDrawUserMessageCreate () const = 0; + virtual QString haventBegunDrawUserMessageCreate() const = 0; private: - void setCursorCreate (); - + void setCursorCreate(); protected: // Sets the selection border mode when beginning to drag to create a // selection. // // Subclasses may wish to reimplement but should still call the base // implementation. Reimplementations should wrap the whole // reimplementation in a kpViewManager::setQueueUpdates() block. - virtual void setSelectionBorderForBeginDrawCreate (); + virtual void setSelectionBorderForBeginDrawCreate(); private: - void beginDrawCreate (); - + void beginDrawCreate(); protected: // @@ -424,117 +402,99 @@ // 2. : // This is as passed to kpTool::draw(). // - virtual bool drawCreateMoreSelectionAndUpdateStatusBar ( - bool dragAccepted, - const QPoint &accidentalDragAdjustedPoint, + virtual bool drawCreateMoreSelectionAndUpdateStatusBar( + bool dragAccepted, const QPoint &accidentalDragAdjustedPoint, const QRect &normalizedRect) = 0; - void drawCreate (const QPoint &thisPoint, const QRect &normalizedRect); + void drawCreate(const QPoint &thisPoint, const QRect &normalizedRect); private slots: - void delayedDrawCreate (); - + void delayedDrawCreate(); private: - void cancelCreate (); - void endDrawCreate (); - + void cancelCreate(); + void endDrawCreate(); private: - QVariant operationCreate (Operation op, - const QVariant &data1, const QVariant &data2); - + QVariant operationCreate(Operation op, const QVariant &data1, const QVariant &data2); // // Move // private: // Called by constructor to initialize the "Move" draw type. - void initMove (); + void initMove(); // Called by destructor to uninitialize the "Move" draw type. - void uninitMove (); - + void uninitMove(); private: - void beginMove (); - void endMove (); - + void beginMove(); + void endMove(); protected: - virtual QString haventBegunDrawUserMessageMove () const = 0; + virtual QString haventBegunDrawUserMessageMove() const = 0; private: - void setCursorMove (); - + void setCursorMove(); protected: // Sets the selection border mode when beginning to drag to move a // selection. // // Subclasses may wish to reimplement but should still call the base // implementation. Reimplementations should wrap the whole // reimplementation in a kpViewManager::setQueueUpdates() block. - virtual void setSelectionBorderForBeginDrawMove (); + virtual void setSelectionBorderForBeginDrawMove(); private: - void beginDrawMove (); + void beginDrawMove(); private slots: - void slotRMBMoveUpdateGUI (); - + void slotRMBMoveUpdateGUI(); private: - void drawMove (const QPoint &thisPoint, const QRect &normalizedRect); - + void drawMove(const QPoint &thisPoint, const QRect &normalizedRect); private: - void cancelMove (); + void cancelMove(); protected: // Returns what the name of the command that moves -- but does not smear // (not holding SHIFT) -- the selection, should be. - virtual QString nonSmearMoveCommandName () const; + virtual QString nonSmearMoveCommandName() const; private: - void endDrawMove (); - + void endDrawMove(); private: - QVariant operationMove (Operation op, - const QVariant &data1, const QVariant &data2); - + QVariant operationMove(Operation op, const QVariant &data1, const QVariant &data2); // // Resize/Scale // private: - int onSelectionResizeHandle () const; - + int onSelectionResizeHandle() const; private: // Called by constructor to initialize the "Resize/Scale" draw type. - void initResizeScale (); + void initResizeScale(); // Called by destructor to uninitialize the "Resize/Scale" draw type. - void uninitResizeScale (); - + void uninitResizeScale(); private: - void beginResizeScale (); - void endResizeScale (); - + void beginResizeScale(); + void endResizeScale(); protected: - virtual QString haventBegunDrawUserMessageResizeScale () const = 0; + virtual QString haventBegunDrawUserMessageResizeScale() const = 0; private: - void setCursorResizeScale (); - + void setCursorResizeScale(); protected: // Sets the selection border mode when beginning to drag to resize or // scale a selection. // // Subclasses may wish to reimplement but should still call the base // implementation. Reimplementations should wrap the whole // reimplementation in a kpViewManager::setQueueUpdates() block. - virtual void setSelectionBorderForBeginDrawResizeScale (); + virtual void setSelectionBorderForBeginDrawResizeScale(); private: - void beginDrawResizeScale (); - + void beginDrawResizeScale(); private: // drawResizeScaleCalculateNewSelectionPosSize() calls us with what the @@ -551,50 +511,42 @@ // The method should output its attempt at maintaining the aspect ratio. // We say "attempt" because it is constrained by the minimum allowed // size of the selection. - void drawResizeScaleTryKeepAspect (int newWidth, int newHeight, - bool horizontalGripDragged, bool verticalGripDragged, - const kpAbstractSelection &originalSelection, - int *newWidthOut, int *newHeightOut); - - void drawResizeScaleCalculateNewSelectionPosSize ( - const kpAbstractSelection &originalSelection, - int *newX, int *newY, - int *newWidth, int *newHeight); + void drawResizeScaleTryKeepAspect(int newWidth, int newHeight, bool horizontalGripDragged, + bool verticalGripDragged, + const kpAbstractSelection &originalSelection, + int *newWidthOut, int *newHeightOut); - void drawResizeScale (const QPoint &thisPoint, const QRect &normalizedRect); + void drawResizeScaleCalculateNewSelectionPosSize( + const kpAbstractSelection &originalSelection, int *newX, int *newY, int *newWidth, + int *newHeight); + void drawResizeScale(const QPoint &thisPoint, const QRect &normalizedRect); private: - void cancelResizeScale (); - void endDrawResizeScale (); - + void cancelResizeScale(); + void endDrawResizeScale(); private: - QVariant operationResizeScale (Operation op, - const QVariant &data1, const QVariant &data2); - + QVariant operationResizeScale(Operation op, const QVariant &data1, const QVariant &data2); // // User Setting Selection Options // protected slots: - virtual void slotIsOpaqueChanged (bool isOpaque) = 0; - + virtual void slotIsOpaqueChanged(bool isOpaque) = 0; // // Keyboard Events // protected: // Reimplemented to trap Esc presses for deselecting the selection. // All other keypresses are passed to the base implementation. - void keyPressEvent (QKeyEvent *e) override; - + void keyPressEvent(QKeyEvent *e) override; private: - struct kpAbstractSelectionToolPrivate * const d; + struct kpAbstractSelectionToolPrivate *const d; }; - #endif // kpAbstractSelectionTool_H diff --git a/tools/selection/kpAbstractSelectionTool.cpp b/tools/selection/kpAbstractSelectionTool.cpp --- a/tools/selection/kpAbstractSelectionTool.cpp +++ b/tools/selection/kpAbstractSelectionTool.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpAbstractSelectionTool.h" #include "kpAbstractSelectionToolPrivate.h" @@ -57,23 +54,20 @@ // For either of these timers, they are only active during the "drawing" phase // of kpTool. -static void AssertAllTimersInactive (struct kpAbstractSelectionToolPrivate *d) +static void AssertAllTimersInactive(struct kpAbstractSelectionToolPrivate *d) { - Q_ASSERT (!d->createNOPTimer->isActive ()); - Q_ASSERT (!d->RMBMoveUpdateGUITimer->isActive ()); + Q_ASSERT(!d->createNOPTimer->isActive()); + Q_ASSERT(!d->RMBMoveUpdateGUITimer->isActive()); } //--------------------------------------------------------------------- kpAbstractSelectionTool::kpAbstractSelectionTool ( - const QString &text, - const QString &description, - int key, - kpToolSelectionEnvironment *environ, QObject *parent, - const QString &name) - - : kpTool (text, description, key, environ, parent, name), - d (new kpAbstractSelectionToolPrivate ()) + const QString &text, const QString &description, int key, kpToolSelectionEnvironment *environ, + QObject *parent, const QString &name) + + : kpTool(text, description, key, environ, parent, name) + , d(new kpAbstractSelectionToolPrivate()) { d->drawType = None; d->currentSelContentCommand = nullptr; @@ -85,286 +79,271 @@ d->toolWidgetOpaqueOrTransparent = nullptr; - - initCreate (); - initMove (); - initResizeScale (); + initCreate(); + initMove(); + initResizeScale(); // It would be bad practice to have timers ticking even when this tool // is not in use. - ::AssertAllTimersInactive (d); + ::AssertAllTimersInactive(d); } //--------------------------------------------------------------------- kpAbstractSelectionTool::~kpAbstractSelectionTool () { - uninitCreate (); - uninitMove (); - uninitResizeScale (); - + uninitCreate(); + uninitMove(); + uninitResizeScale(); // (state must be after construction, or after some time after end()) - Q_ASSERT (d->drawType == None); - Q_ASSERT (!d->currentSelContentCommand); + Q_ASSERT(d->drawType == None); + Q_ASSERT(!d->currentSelContentCommand); // d->dragAccepted // d->hadSelectionBeforeDraw // d->cancelledShapeButStillHoldingButtons // d->toolWidgetOpaqueOrTransparent - delete d; } //--------------------------------------------------------------------- // protected -kpAbstractSelectionTool::DrawType kpAbstractSelectionTool::drawType () const +kpAbstractSelectionTool::DrawType kpAbstractSelectionTool::drawType() const { return d->drawType; } //--------------------------------------------------------------------- // protected -bool kpAbstractSelectionTool::hadSelectionBeforeDraw () const +bool kpAbstractSelectionTool::hadSelectionBeforeDraw() const { return d->hadSelectionBeforeDraw; } //--------------------------------------------------------------------- // protected overrides [base kpTool] -kpToolSelectionEnvironment *kpAbstractSelectionTool::environ () const +kpToolSelectionEnvironment *kpAbstractSelectionTool::environ() const { - kpToolEnvironment *e = kpTool::environ (); - Q_ASSERT (dynamic_cast (e)); - return dynamic_cast (e); + kpToolEnvironment *e = kpTool::environ(); + Q_ASSERT(dynamic_cast (e)); + return dynamic_cast (e); } //--------------------------------------------------------------------- // protected -bool kpAbstractSelectionTool::controlOrShiftPressed () const +bool kpAbstractSelectionTool::controlOrShiftPressed() const { - return (controlPressed () || shiftPressed ()); + return controlPressed() || shiftPressed(); } //--------------------------------------------------------------------- // protected -void kpAbstractSelectionTool::pushOntoDocument () +void kpAbstractSelectionTool::pushOntoDocument() { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "kpAbstractSelectionTool::pushOntoDocument() selection=" - << document ()->selection (); + << document()->selection(); #endif - Q_ASSERT (document ()->selection ()); - environ ()->deselectSelection (); + Q_ASSERT(document()->selection()); + environ()->deselectSelection(); } //--------------------------------------------------------------------- // protected -void kpAbstractSelectionTool::giveContentIfNeeded () +void kpAbstractSelectionTool::giveContentIfNeeded() { - kpAbstractSelection *sel = document ()->selection (); - Q_ASSERT (sel); + kpAbstractSelection *sel = document()->selection(); + Q_ASSERT(sel); - if (sel->hasContent ()) { + if (sel->hasContent()) { return; } if (d->currentSelContentCommand) { return; } - d->currentSelContentCommand = /*virtual*/newGiveContentCommand (); - d->currentSelContentCommand->execute (); + d->currentSelContentCommand = /*virtual*/ newGiveContentCommand(); + d->currentSelContentCommand->execute(); } //--------------------------------------------------------------------- // protected // REFACTOR: sync: Code dup with kpMainWindow::addImageOrSelectionCommand (). -void kpAbstractSelectionTool::addNeedingContentCommand (kpCommand *cmd) +void kpAbstractSelectionTool::addNeedingContentCommand(kpCommand *cmd) { - Q_ASSERT (cmd); + Q_ASSERT(cmd); // Did we fill the selection with content? - if (d->currentSelContentCommand) - { + if (d->currentSelContentCommand) { // Make the border creation a command. #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "\thave currentSelContentCommand"; #endif - commandHistory ()->addCreateSelectionCommand ( - new kpToolSelectionCreateCommand ( - /*virtual*/nameOfCreateCommand (), - *d->currentSelContentCommand->originalSelection (), - environ ()->commandEnvironment ()), - false/*no exec - user already dragged out sel*/); + commandHistory()->addCreateSelectionCommand( + new kpToolSelectionCreateCommand( + /*virtual*/ nameOfCreateCommand(), + *d->currentSelContentCommand->originalSelection(), + environ()->commandEnvironment()), + false /*no exec - user already dragged out sel*/); } // Do we have a content setting command we need to commit? // (yes, this is the same check as the previous "if") - if (d->currentSelContentCommand) - { + if (d->currentSelContentCommand) { // Put the content command + given command (e.g. movement) together // as a macro command, in the command history. - kpMacroCommand *macroCmd = new kpMacroCommand ( - cmd->name (), environ ()->commandEnvironment ()); + kpMacroCommand *macroCmd = new kpMacroCommand( + cmd->name(), environ()->commandEnvironment()); - macroCmd->addCommand (d->currentSelContentCommand); + macroCmd->addCommand(d->currentSelContentCommand); d->currentSelContentCommand = nullptr; - macroCmd->addCommand (cmd); + macroCmd->addCommand(cmd); - commandHistory ()->addCommand (macroCmd, false/*no exec*/); - } - else - { + commandHistory()->addCommand(macroCmd, false /*no exec*/); + } else { // Put the given command into the command history. - commandHistory ()->addCommand (cmd, false/*no exec*/); + commandHistory()->addCommand(cmd, false /*no exec*/); } } //--------------------------------------------------------------------- - // protected virtual -void kpAbstractSelectionTool::setSelectionBorderForHaventBegunDraw () +void kpAbstractSelectionTool::setSelectionBorderForHaventBegunDraw() { - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { - viewManager ()->setSelectionBorderVisible (true); - viewManager ()->setSelectionBorderFinished (true); + viewManager()->setSelectionBorderVisible(true); + viewManager()->setSelectionBorderFinished(true); } - viewManager ()->restoreQueueUpdates (); + viewManager()->restoreQueueUpdates(); } //--------------------------------------------------------------------- // private -QString kpAbstractSelectionTool::haventBegunDrawUserMessage () +QString kpAbstractSelectionTool::haventBegunDrawUserMessage() { #if DEBUG_KP_TOOL_SELECTION && 0 qCDebug(kpLogTools) << "kpAbstractSelectionTool::haventBegunDrawUserMessage()" - " cancelledShapeButStillHoldingButtons=" - << d->cancelledShapeButStillHoldingButtons; + " cancelledShapeButStillHoldingButtons=" + << d->cancelledShapeButStillHoldingButtons; #endif if (d->cancelledShapeButStillHoldingButtons) { - return i18n ("Let go of all the mouse buttons."); + return i18n("Let go of all the mouse buttons."); } - return operation (calculateDrawType (), HaventBegunDrawUserMessage).toString (); + return operation(calculateDrawType(), HaventBegunDrawUserMessage).toString(); } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpAbstractSelectionTool::begin () +void kpAbstractSelectionTool::begin() { #if DEBUG_KP_TOOL_SELECTION - qCDebug(kpLogTools) << "kpAbstractSelectionTool<" << objectName () << ">::begin()"; + qCDebug(kpLogTools) << "kpAbstractSelectionTool<" << objectName() << ">::begin()"; #endif - ::AssertAllTimersInactive (d); + ::AssertAllTimersInactive(d); // (state must be after construction, or after some time after end()) - Q_ASSERT (d->drawType == None); - Q_ASSERT (!d->currentSelContentCommand); + Q_ASSERT(d->drawType == None); + Q_ASSERT(!d->currentSelContentCommand); d->dragAccepted = false; // d->hadSelectionBeforeDraw d->cancelledShapeButStillHoldingButtons = false; + kpToolToolBar *tb = toolToolBar(); + Q_ASSERT(tb); - kpToolToolBar *tb = toolToolBar (); - Q_ASSERT (tb); - - d->toolWidgetOpaqueOrTransparent = tb->toolWidgetOpaqueOrTransparent (); - Q_ASSERT (d->toolWidgetOpaqueOrTransparent); - connect (d->toolWidgetOpaqueOrTransparent, - &kpToolWidgetOpaqueOrTransparent::isOpaqueChanged, - this, &kpAbstractSelectionTool::slotIsOpaqueChanged); - d->toolWidgetOpaqueOrTransparent->show (); - - /*virtual*/setSelectionBorderForHaventBegunDraw (); - + d->toolWidgetOpaqueOrTransparent = tb->toolWidgetOpaqueOrTransparent(); + Q_ASSERT(d->toolWidgetOpaqueOrTransparent); + connect(d->toolWidgetOpaqueOrTransparent, + &kpToolWidgetOpaqueOrTransparent::isOpaqueChanged, + this, &kpAbstractSelectionTool::slotIsOpaqueChanged); + d->toolWidgetOpaqueOrTransparent->show(); - beginCreate (); - beginMove (); - beginResizeScale (); + /*virtual*/ setSelectionBorderForHaventBegunDraw(); + beginCreate(); + beginMove(); + beginResizeScale(); - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpAbstractSelectionTool::end () +void kpAbstractSelectionTool::end() { #if DEBUG_KP_TOOL_SELECTION - qCDebug(kpLogTools) << "kpAbstractSelectionTool<" << objectName () << ">::end()"; + qCDebug(kpLogTools) << "kpAbstractSelectionTool<" << objectName() << ">::end()"; #endif - if (document ()->selection ()) { - pushOntoDocument (); + if (document()->selection()) { + pushOntoDocument(); } - - endCreate (); - endMove (); - endResizeScale (); - + endCreate(); + endMove(); + endResizeScale(); // (should have been killed by cancelShape() or endDraw()) - Q_ASSERT (d->drawType == None); - Q_ASSERT (!d->currentSelContentCommand); + Q_ASSERT(d->drawType == None); + Q_ASSERT(!d->currentSelContentCommand); // d->dragAccepted // d->hadSelectionBeforeDraw // d->cancelledShapeButStillHoldingButtons - - Q_ASSERT (d->toolWidgetOpaqueOrTransparent); - disconnect (d->toolWidgetOpaqueOrTransparent, - &kpToolWidgetOpaqueOrTransparent::isOpaqueChanged, - this, &kpAbstractSelectionTool::slotIsOpaqueChanged); + Q_ASSERT(d->toolWidgetOpaqueOrTransparent); + disconnect(d->toolWidgetOpaqueOrTransparent, + &kpToolWidgetOpaqueOrTransparent::isOpaqueChanged, + this, &kpAbstractSelectionTool::slotIsOpaqueChanged); d->toolWidgetOpaqueOrTransparent = nullptr; + viewManager()->unsetCursor(); - viewManager ()->unsetCursor (); - - ::AssertAllTimersInactive (d); + ::AssertAllTimersInactive(d); } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpAbstractSelectionTool::reselect () +void kpAbstractSelectionTool::reselect() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "kpAbstractSelectionTool::reselect()"; #endif - if (document ()->selection ()) { - pushOntoDocument (); + if (document()->selection()) { + pushOntoDocument(); } } //--------------------------------------------------------------------- // protected virtual -kpAbstractSelectionTool::DrawType kpAbstractSelectionTool::calculateDrawTypeInsideSelection () const +kpAbstractSelectionTool::DrawType kpAbstractSelectionTool::calculateDrawTypeInsideSelection() const { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "\t\tis move"; @@ -375,204 +354,189 @@ //--------------------------------------------------------------------- // protected virtual -kpAbstractSelectionTool::DrawType kpAbstractSelectionTool::calculateDrawType () const +kpAbstractSelectionTool::DrawType kpAbstractSelectionTool::calculateDrawType() const { - kpAbstractSelection *sel = document ()->selection (); + kpAbstractSelection *sel = document()->selection(); if (!sel) { return Create; } #if DEBUG_KP_TOOL_SELECTION - qCDebug(kpLogTools) << "\thas sel region rect=" << sel->boundingRect (); + qCDebug(kpLogTools) << "\thas sel region rect=" << sel->boundingRect(); #endif - if (onSelectionResizeHandle () && !controlOrShiftPressed ()) { + if (onSelectionResizeHandle() && !controlOrShiftPressed()) { return ResizeScale; } - if (sel->contains (currentPoint ())) { - return /*virtual*/calculateDrawTypeInsideSelection (); + if (sel->contains(currentPoint())) { + return /*virtual*/ calculateDrawTypeInsideSelection(); } return Create; } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpAbstractSelectionTool::beginDraw () +void kpAbstractSelectionTool::beginDraw() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "kpAbstractSelectionTool::beginDraw() startPoint ()=" - << startPoint () - << " QCursor::pos() view startPoint=" - << viewUnderStartPoint ()->mapFromGlobal (QCursor::pos ()); + << startPoint() + << " QCursor::pos() view startPoint=" + << viewUnderStartPoint()->mapFromGlobal(QCursor::pos()); #endif // endDraw() and cancelShape() should have taken care of these. - ::AssertAllTimersInactive (d); + ::AssertAllTimersInactive(d); // In case the cursor was wrong to start with // (forgot to call kpTool::somethingBelowTheCursorChanged()), // make sure it is correct during this operation. - hover (currentPoint ()); + hover(currentPoint()); // Currently used only to end the current text - if (hasBegunShape ()) - { + if (hasBegunShape()) { endShape(currentPoint(), - kpPainter::normalizedRect(startPoint()/* TODO: wrong */, currentPoint())); + kpPainter::normalizedRect(startPoint() /* TODO: wrong */, currentPoint())); } - d->drawType = calculateDrawType (); + d->drawType = calculateDrawType(); d->dragAccepted = false; - kpAbstractSelection *sel = document ()->selection (); - d->hadSelectionBeforeDraw = bool (sel); + kpAbstractSelection *sel = document()->selection(); + d->hadSelectionBeforeDraw = bool(sel); - operation (d->drawType, BeginDraw); + operation(d->drawType, BeginDraw); } //--------------------------------------------------------------------- - // public virtual [base kpTool] -void kpAbstractSelectionTool::hover (const QPoint &point) +void kpAbstractSelectionTool::hover(const QPoint &point) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "kpAbstractSelectionTool::hover" << point; #endif - operation (calculateDrawType (), SetCursor); + operation(calculateDrawType(), SetCursor); - setUserShapePoints (point, KP_INVALID_POINT, false/*don't set size*/); - if (document () && document ()->selection ()) - { - setUserShapeSize (document ()->selection ()->width (), - document ()->selection ()->height ()); - } - else - { - setUserShapeSize (KP_INVALID_SIZE); + setUserShapePoints(point, KP_INVALID_POINT, false /*don't set size*/); + if (document() && document()->selection()) { + setUserShapeSize(document()->selection()->width(), + document()->selection()->height()); + } else { + setUserShapeSize(KP_INVALID_SIZE); } - QString mess = haventBegunDrawUserMessage (); - if (mess != userMessage ()) { - setUserMessage (mess); + QString mess = haventBegunDrawUserMessage(); + if (mess != userMessage()) { + setUserMessage(mess); } } //--------------------------------------------------------------------- - // public virtual [base kpTool] -void kpAbstractSelectionTool::draw (const QPoint &thisPoint, const QPoint & /*lastPoint*/, - const QRect &normalizedRect) +void kpAbstractSelectionTool::draw(const QPoint &thisPoint, const QPoint & /*lastPoint*/, + const QRect &normalizedRect) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "kpAbstractSelectionTool::draw (" << thisPoint - << ",startPoint=" << startPoint () - << ",normalizedRect=" << normalizedRect << ")"; + << ",startPoint=" << startPoint() + << ",normalizedRect=" << normalizedRect << ")"; #else - Q_UNUSED (thisPoint); - Q_UNUSED (normalizedRect); + Q_UNUSED(thisPoint); + Q_UNUSED(normalizedRect); #endif - // OPT: return when thisPoint == lastPoint () so that e.g. when creating // Points sel, press modifiers doesn't add multiple points in same // place - - operation (d->drawType, Draw); + operation(d->drawType, Draw); } //--------------------------------------------------------------------- - // public virtual [base kpTool] -void kpAbstractSelectionTool::cancelShape () +void kpAbstractSelectionTool::cancelShape() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "kpAbstractSelectionTool::cancelShape() mouseButton=" - << mouseButton (); + << mouseButton(); #endif const DrawType oldDrawType = d->drawType; // kpTool::hasBegunDraw() returns false in this method so be consistent // and clear "drawType" before dispatching the operation() below. d->drawType = None; - - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { - operation (oldDrawType, Cancel); + operation(oldDrawType, Cancel); - - if (d->currentSelContentCommand) - { + if (d->currentSelContentCommand) { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "\t\tundo sel content"; #endif - d->currentSelContentCommand->unexecute (); + d->currentSelContentCommand->unexecute(); delete d->currentSelContentCommand; d->currentSelContentCommand = nullptr; } - - /*virtual*/setSelectionBorderForHaventBegunDraw (); + /*virtual*/ setSelectionBorderForHaventBegunDraw(); } - viewManager ()->restoreQueueUpdates (); - + viewManager()->restoreQueueUpdates(); d->cancelledShapeButStillHoldingButtons = true; - setUserMessage (i18n ("Let go of all the mouse buttons.")); - + setUserMessage(i18n("Let go of all the mouse buttons.")); - ::AssertAllTimersInactive (d); + ::AssertAllTimersInactive(d); } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpAbstractSelectionTool::releasedAllButtons () +void kpAbstractSelectionTool::releasedAllButtons() { d->cancelledShapeButStillHoldingButtons = false; - setUserMessage (haventBegunDrawUserMessage ()); + setUserMessage(haventBegunDrawUserMessage()); } //--------------------------------------------------------------------- // protected -void kpAbstractSelectionTool::popupRMBMenu () +void kpAbstractSelectionTool::popupRMBMenu() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "CALL - exec'ing menu"; #endif - QMenu *pop = environ ()->selectionToolRMBMenu (); - Q_ASSERT (pop); + QMenu *pop = environ()->selectionToolRMBMenu(); + Q_ASSERT(pop); // Blocks until the menu closes. // WARNING: Enters event loop - may re-enter view/tool event handlers. - pop->exec (QCursor::pos ()); + pop->exec(QCursor::pos()); #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "calling somethingBelowTheCursorChanged()"; #endif // Cursor may have moved while the menu was up, triggering QMouseMoveEvents // for the menu -- but not the view -- so we may have missed cursor moves. // Update cursor position now. - somethingBelowTheCursorChanged (); + somethingBelowTheCursorChanged(); #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "DONE"; #endif } //--------------------------------------------------------------------- // public virtual [base kpTool] -void kpAbstractSelectionTool::endDraw (const QPoint & /*thisPoint*/, - const QRect & /*normalizedRect*/) +void kpAbstractSelectionTool::endDraw(const QPoint & /*thisPoint*/, + const QRect & /*normalizedRect*/) { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "kpAbstractSelectionTool::endDraw()"; @@ -583,59 +547,50 @@ // and clear "drawType" before dispatching the operation() below. d->drawType = None; - - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { - operation (oldDrawType, EndDraw); + operation(oldDrawType, EndDraw); - /*virtual*/setSelectionBorderForHaventBegunDraw (); + /*virtual*/ setSelectionBorderForHaventBegunDraw(); } - viewManager ()->restoreQueueUpdates (); - - - setUserMessage (haventBegunDrawUserMessage ()); - + viewManager()->restoreQueueUpdates(); - ::AssertAllTimersInactive (d); + setUserMessage(haventBegunDrawUserMessage()); + ::AssertAllTimersInactive(d); - if (mouseButton () == 1/*right*/) { - popupRMBMenu (); + if (mouseButton() == 1 /*right*/) { + popupRMBMenu(); } - // WARNING: Do not place any code after the popupRMBMenu() call // (see the popupRMBMenu() API). } //--------------------------------------------------------------------- // protected virtual -QVariant kpAbstractSelectionTool::operation (DrawType drawType, Operation op, - const QVariant &data1, const QVariant &data2) +QVariant kpAbstractSelectionTool::operation(DrawType drawType, Operation op, const QVariant &data1, + const QVariant &data2) { - switch (drawType) - { + switch (drawType) { case None: // NOP. return {}; case Create: - return operationCreate (op, data1, data2); + return operationCreate(op, data1, data2); case Move: - return operationMove (op, data1, data2); + return operationMove(op, data1, data2); case ResizeScale: - return operationResizeScale (op, data1, data2); + return operationResizeScale(op, data1, data2); default: - Q_ASSERT (!"Unhandled draw type"); + Q_ASSERT(!"Unhandled draw type"); return {}; } } //--------------------------------------------------------------------- - - - diff --git a/tools/selection/kpAbstractSelectionToolPrivate.h b/tools/selection/kpAbstractSelectionToolPrivate.h --- a/tools/selection/kpAbstractSelectionToolPrivate.h +++ b/tools/selection/kpAbstractSelectionToolPrivate.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,23 +24,20 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpAbstractSelectionToolPrivate_H #define kpAbstractSelectionToolPrivate_H #include "kpAbstractSelectionTool.h" #include - class QTimer; class kpAbstractSelectionContentCommand; class kpToolSelectionMoveCommand; class kpToolSelectionResizeScaleCommand; class kpToolWidgetOpaqueOrTransparent; - struct kpAbstractSelectionToolPrivate { kpAbstractSelectionTool::DrawType drawType; @@ -59,14 +55,12 @@ kpToolWidgetOpaqueOrTransparent *toolWidgetOpaqueOrTransparent; - // // Create // QTimer *createNOPTimer; - // // Move // @@ -78,14 +72,12 @@ QTimer *RMBMoveUpdateGUITimer; - // // Resize / Scale // kpToolSelectionResizeScaleCommand *currentResizeScaleCommand; int resizeScaleType; }; - #endif // kpAbstractSelectionToolPrivate_H diff --git a/tools/selection/kpAbstractSelectionTool_Create.cpp b/tools/selection/kpAbstractSelectionTool_Create.cpp --- a/tools/selection/kpAbstractSelectionTool_Create.cpp +++ b/tools/selection/kpAbstractSelectionTool_Create.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpAbstractSelectionTool.h" #include "kpAbstractSelectionToolPrivate.h" @@ -56,31 +53,29 @@ #include "views/kpView.h" #include "views/manager/kpViewManager.h" - // private -void kpAbstractSelectionTool::initCreate () +void kpAbstractSelectionTool::initCreate() { - d->createNOPTimer = new QTimer (this); - d->createNOPTimer->setSingleShot (true); - connect (d->createNOPTimer, &QTimer::timeout, - this, &kpAbstractSelectionTool::delayedDrawCreate); + d->createNOPTimer = new QTimer(this); + d->createNOPTimer->setSingleShot(true); + connect(d->createNOPTimer, &QTimer::timeout, + this, &kpAbstractSelectionTool::delayedDrawCreate); } // private -void kpAbstractSelectionTool::uninitCreate () +void kpAbstractSelectionTool::uninitCreate() { // d->createNOPTimer (deleted by QObject mechanism) } - // private -void kpAbstractSelectionTool::beginCreate () +void kpAbstractSelectionTool::beginCreate() { // d->createNOPTimer } // private -void kpAbstractSelectionTool::endCreate () +void kpAbstractSelectionTool::endCreate() { // d->createNOPTimer } @@ -90,211 +85,199 @@ // to the contrary of the "themed" crosshair cursors which might look nice // but does not allow to exactly position the hot-spot. /* XPM */ -static const char *crosshair[]={ -"17 17 3 1", -". c None", -"x c #FFFFFF", -"# c #000000", -".......xxx.......", -".......x#x.......", -".......x#x.......", -".......x#x.......", -".......x#x.......", -".......x#x.......", -".......x#x.......", -"xxxxxxxx#xxxxxxxx", -"x#######.#######x", -"xxxxxxxx#xxxxxxxx", -".......x#x.......", -".......x#x.......", -".......x#x.......", -".......x#x.......", -".......x#x.......", -".......x#x.......", -".......xxx......."}; +static const char *crosshair[] = { + "17 17 3 1", + ". c None", + "x c #FFFFFF", + "# c #000000", + ".......xxx.......", + ".......x#x.......", + ".......x#x.......", + ".......x#x.......", + ".......x#x.......", + ".......x#x.......", + ".......x#x.......", + "xxxxxxxx#xxxxxxxx", + "x#######.#######x", + "xxxxxxxx#xxxxxxxx", + ".......x#x.......", + ".......x#x.......", + ".......x#x.......", + ".......x#x.......", + ".......x#x.......", + ".......x#x.......", + ".......xxx......." +}; // private -void kpAbstractSelectionTool::setCursorCreate () +void kpAbstractSelectionTool::setCursorCreate() { viewManager()->setCursor(QCursor(QPixmap(crosshair), 8, 8)); } //--------------------------------------------------------------------- // protected virtual -void kpAbstractSelectionTool::setSelectionBorderForBeginDrawCreate () +void kpAbstractSelectionTool::setSelectionBorderForBeginDrawCreate() { - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { // LOREFACTOR: I suspect some calls to viewManager() in this // file (including this) are redundant since any // code that tweaks such settings, returns them to // their original state, after the code is complete. - viewManager ()->setSelectionBorderVisible (true); + viewManager()->setSelectionBorderVisible(true); - viewManager ()->setSelectionBorderFinished (false); + viewManager()->setSelectionBorderFinished(false); } - viewManager ()->restoreQueueUpdates (); + viewManager()->restoreQueueUpdates(); } // private -void kpAbstractSelectionTool::beginDrawCreate () +void kpAbstractSelectionTool::beginDrawCreate() { - if (document ()->selection ()) { - pushOntoDocument (); + if (document()->selection()) { + pushOntoDocument(); } - /*virtual*/setSelectionBorderForBeginDrawCreate (); + /*virtual*/ setSelectionBorderForBeginDrawCreate(); // (single shot) - d->createNOPTimer->start (200/*ms*/); + d->createNOPTimer->start(200 /*ms*/); - setUserMessage (cancelUserMessage ()); + setUserMessage(cancelUserMessage()); } - // private -void kpAbstractSelectionTool::drawCreate (const QPoint &thisPoint, - const QRect &normalizedRect) +void kpAbstractSelectionTool::drawCreate(const QPoint &thisPoint, const QRect &normalizedRect) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "\tnot moving - resizing rect to" << normalizedRect; qCDebug(kpLogTools) << "\t\tcreateNOPTimer->isActive()=" - << d->createNOPTimer->isActive () - << " viewManhattanLength from startPoint=" - << viewUnderStartPoint ()->transformDocToViewX ((thisPoint - startPoint ()).manhattanLength ()); + << d->createNOPTimer->isActive() + << " viewManhattanLength from startPoint=" + << viewUnderStartPoint()->transformDocToViewX( + (thisPoint - startPoint()).manhattanLength()); #endif QPoint accidentalDragAdjustedPoint = thisPoint; - if (d->createNOPTimer->isActive ()) - { + if (d->createNOPTimer->isActive()) { // See below "d->createNOPTimer->stop()". - Q_ASSERT (!d->dragAccepted); + Q_ASSERT(!d->dragAccepted); - if (viewUnderStartPoint ()->transformDocToViewX ( - (accidentalDragAdjustedPoint - startPoint ()).manhattanLength ()) <= 6) - { + if (viewUnderStartPoint()->transformDocToViewX( + (accidentalDragAdjustedPoint - startPoint()).manhattanLength()) <= 6) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "\t\tsuppress accidental movement"; #endif - accidentalDragAdjustedPoint = startPoint (); - } - else - { + accidentalDragAdjustedPoint = startPoint(); + } else { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "\t\tit's a \"big\" intended move - stop timer"; #endif - d->createNOPTimer->stop (); + d->createNOPTimer->stop(); } } - - const bool hadSelection = document ()->selection (); + const bool hadSelection = document()->selection(); const bool oldDrawAcceptedAsDrag = d->dragAccepted; - d->dragAccepted = /*virtual*/drawCreateMoreSelectionAndUpdateStatusBar ( + d->dragAccepted = /*virtual*/ drawCreateMoreSelectionAndUpdateStatusBar( d->dragAccepted, accidentalDragAdjustedPoint, normalizedRect); if (oldDrawAcceptedAsDrag) { - Q_ASSERT (d->dragAccepted); + Q_ASSERT(d->dragAccepted); } - if (d->dragAccepted) - { + if (d->dragAccepted) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "\t\tdrawHasDoneSomething - kill create timer"; #endif // No longer a NOP. - d->createNOPTimer->stop (); + d->createNOPTimer->stop(); } // Did we just create a selection? - if (!hadSelection && document ()->selection ()) { - viewManager ()->setSelectionBorderVisible (true); + if (!hadSelection && document()->selection()) { + viewManager()->setSelectionBorderVisible(true); } } // private slot -void kpAbstractSelectionTool::delayedDrawCreate () +void kpAbstractSelectionTool::delayedDrawCreate() { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "kpAbstractSelectionTool::delayedDrawCreate() hasBegunDraw=" - << hasBegunDraw () - << " currentPoint=" << currentPoint () - << " lastPoint=" << lastPoint () - << " startPoint=" << startPoint (); + << hasBegunDraw() + << " currentPoint=" << currentPoint() + << " lastPoint=" << lastPoint() + << " startPoint=" << startPoint(); #endif // (just in case not called from single shot) - d->createNOPTimer->stop (); + d->createNOPTimer->stop(); - if (hasBegunDraw ()) - { - draw (currentPoint (), lastPoint (), normalizedRect ()); + if (hasBegunDraw()) { + draw(currentPoint(), lastPoint(), normalizedRect()); } } - // private -void kpAbstractSelectionTool::cancelCreate () +void kpAbstractSelectionTool::cancelCreate() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "\twas creating sel - kill"; #endif - d->createNOPTimer->stop (); + d->createNOPTimer->stop(); // TODO: should we give the user back the selection s/he had before (if any)? - if (document ()->selection ()) { - document ()->selectionDelete (); + if (document()->selection()) { + document()->selectionDelete(); } } // private -void kpAbstractSelectionTool::endDrawCreate () +void kpAbstractSelectionTool::endDrawCreate() { - d->createNOPTimer->stop (); + d->createNOPTimer->stop(); } - // private -QVariant kpAbstractSelectionTool::operationCreate (Operation op, - const QVariant &data1, const QVariant &data2) +QVariant kpAbstractSelectionTool::operationCreate(Operation op, const QVariant &data1, + const QVariant &data2) { - (void) data1; - (void) data2; - + (void)data1; + (void)data2; - switch (op) - { + switch (op) { case HaventBegunDrawUserMessage: - return /*virtual*/haventBegunDrawUserMessageCreate (); + return /*virtual*/ haventBegunDrawUserMessageCreate(); case SetCursor: - setCursorCreate (); + setCursorCreate(); break; case BeginDraw: - beginDrawCreate (); + beginDrawCreate(); break; case Draw: - drawCreate (currentPoint (), normalizedRect ()); + drawCreate(currentPoint(), normalizedRect()); break; case Cancel: - cancelCreate (); + cancelCreate(); break; case EndDraw: - endDrawCreate (); + endDrawCreate(); break; default: - Q_ASSERT (!"Unhandled operation"); + Q_ASSERT(!"Unhandled operation"); break; } - return {}; } diff --git a/tools/selection/kpAbstractSelectionTool_KeyboardEvents.cpp b/tools/selection/kpAbstractSelectionTool_KeyboardEvents.cpp --- a/tools/selection/kpAbstractSelectionTool_KeyboardEvents.cpp +++ b/tools/selection/kpAbstractSelectionTool_KeyboardEvents.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpAbstractSelectionTool.h" #include "kpAbstractSelectionToolPrivate.h" @@ -44,58 +41,53 @@ //--------------------------------------------------------------------- // protected virtual [base kpTool] -void kpAbstractSelectionTool::keyPressEvent (QKeyEvent *e) +void kpAbstractSelectionTool::keyPressEvent(QKeyEvent *e) { #if DEBUG_KP_TOOL_SELECTION && 0 qCDebug(kpLogTools) << "kpAbstractSelectionTool::keyPressEvent(e->text='" - << e->text () << "')"; + << e->text() << "')"; #endif - e->ignore (); + e->ignore(); - if (document ()->selection () && - !hasBegunDraw () && - e->key () == Qt::Key_Escape) - { + if (document()->selection() + && !hasBegunDraw() + && e->key() == Qt::Key_Escape) { #if DEBUG_KP_TOOL_SELECTION && 0 qCDebug(kpLogTools) << "\tescape pressed with sel when not begun draw - deselecting"; #endif - pushOntoDocument (); - e->accept (); - } - else - { + pushOntoDocument(); + e->accept(); + } else { #if DEBUG_KP_TOOL_SELECTION && 0 qCDebug(kpLogTools) << "\tkey processing did not accept (text was '" - << e->text () - << "') - passing on event to kpTool"; + << e->text() + << "') - passing on event to kpTool"; #endif - if ( document()->selection() && !hasBegunDraw() && - ((e->key() == Qt::Key_Left) || - (e->key() == Qt::Key_Right) || - (e->key() == Qt::Key_Up) || - (e->key() == Qt::Key_Down)) ) - { - // move selection with cursor keys pixel-wise - giveContentIfNeeded(); - - if ( !d->currentMoveCommand ) - { - d->currentMoveCommand = new kpToolSelectionMoveCommand( - QString()/*uninteresting child of macro cmd*/, - environ()->commandEnvironment()); - d->currentMoveCommandIsSmear = false; + if (document()->selection() && !hasBegunDraw() + && ((e->key() == Qt::Key_Left) + || (e->key() == Qt::Key_Right) + || (e->key() == Qt::Key_Up) + || (e->key() == Qt::Key_Down))) { + // move selection with cursor keys pixel-wise + giveContentIfNeeded(); + + if (!d->currentMoveCommand) { + d->currentMoveCommand = new kpToolSelectionMoveCommand( + QString() /*uninteresting child of macro cmd*/, + environ()->commandEnvironment()); + d->currentMoveCommandIsSmear = false; + } + + int dx, dy; + arrowKeyPressDirection(e, &dx, &dy); + d->currentMoveCommand->moveTo(document()->selection()->topLeft() + QPoint(dx, dy)); + endDrawMove(); + } else { + kpTool::keyPressEvent(e); } - - int dx, dy; - arrowKeyPressDirection(e, &dx, &dy); - d->currentMoveCommand->moveTo(document()->selection()->topLeft() + QPoint(dx, dy)); - endDrawMove(); - } - else - kpTool::keyPressEvent(e); } } diff --git a/tools/selection/kpAbstractSelectionTool_Move.cpp b/tools/selection/kpAbstractSelectionTool_Move.cpp --- a/tools/selection/kpAbstractSelectionTool_Move.cpp +++ b/tools/selection/kpAbstractSelectionTool_Move.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpAbstractSelectionTool.h" #include "kpAbstractSelectionToolPrivate.h" #include "kpLogCategories.h" @@ -56,27 +53,27 @@ //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::initMove () +void kpAbstractSelectionTool::initMove() { d->currentMoveCommand = nullptr; // d->currentMoveCommandIsSmear // d->startMoveDragFromSelectionTopLeft - d->RMBMoveUpdateGUITimer = new QTimer (this); - d->RMBMoveUpdateGUITimer->setSingleShot (true); - connect (d->RMBMoveUpdateGUITimer, &QTimer::timeout, - this, &kpAbstractSelectionTool::slotRMBMoveUpdateGUI); + d->RMBMoveUpdateGUITimer = new QTimer(this); + d->RMBMoveUpdateGUITimer->setSingleShot(true); + connect(d->RMBMoveUpdateGUITimer, &QTimer::timeout, + this, &kpAbstractSelectionTool::slotRMBMoveUpdateGUI); } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::uninitMove () +void kpAbstractSelectionTool::uninitMove() { // (state must be after construction, or after some time after endMove()) - Q_ASSERT (!d->currentMoveCommand); + Q_ASSERT(!d->currentMoveCommand); // d->currentMoveCommandIsSmear @@ -88,10 +85,10 @@ //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::beginMove () +void kpAbstractSelectionTool::beginMove() { // (state must be after construction, or after some time after endMove()) - Q_ASSERT (!d->currentMoveCommand); + Q_ASSERT(!d->currentMoveCommand); // d->currentMoveCommandIsSmear @@ -103,10 +100,10 @@ //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::endMove () +void kpAbstractSelectionTool::endMove() { // (should have been killed by cancelMove() or endDrawMove()) - Q_ASSERT (!d->currentMoveCommand); + Q_ASSERT(!d->currentMoveCommand); // d->currentMoveCommandIsSmear @@ -118,189 +115,174 @@ //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::setCursorMove () +void kpAbstractSelectionTool::setCursorMove() { - viewManager ()->setCursor (Qt::SizeAllCursor); + viewManager()->setCursor(Qt::SizeAllCursor); } //--------------------------------------------------------------------- // protected virtual -void kpAbstractSelectionTool::setSelectionBorderForBeginDrawMove () +void kpAbstractSelectionTool::setSelectionBorderForBeginDrawMove() { // don't show border while moving - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { - viewManager ()->setSelectionBorderVisible (false); - viewManager ()->setSelectionBorderFinished (true); + viewManager()->setSelectionBorderVisible(false); + viewManager()->setSelectionBorderFinished(true); } - viewManager ()->restoreQueueUpdates (); + viewManager()->restoreQueueUpdates(); } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::beginDrawMove () +void kpAbstractSelectionTool::beginDrawMove() { - d->startMoveDragFromSelectionTopLeft = - currentPoint () - document ()->selection ()->topLeft (); + d->startMoveDragFromSelectionTopLeft + = currentPoint() - document()->selection()->topLeft(); - if (mouseButton () == 0) - { - /*virtual*/setSelectionBorderForBeginDrawMove (); - } - else - { + if (mouseButton() == 0) { + /*virtual*/ + setSelectionBorderForBeginDrawMove(); + } else { // Don't hide sel border momentarily if user is just // right _clicking_ selection. // (single shot timer) - d->RMBMoveUpdateGUITimer->start (100/*ms*/); + d->RMBMoveUpdateGUITimer->start(100 /*ms*/); } - setUserMessage (cancelUserMessage ()); + setUserMessage(cancelUserMessage()); } //--------------------------------------------------------------------- // private slot -void kpAbstractSelectionTool::slotRMBMoveUpdateGUI () +void kpAbstractSelectionTool::slotRMBMoveUpdateGUI() { // (just in case not called from single shot) - d->RMBMoveUpdateGUITimer->stop (); + d->RMBMoveUpdateGUITimer->stop(); - /*virtual*/setSelectionBorderForBeginDrawMove (); + /*virtual*/ setSelectionBorderForBeginDrawMove(); - kpAbstractSelection * const sel = document ()->selection (); + kpAbstractSelection *const sel = document()->selection(); if (sel) { - setUserShapePoints (sel->topLeft ()); + setUserShapePoints(sel->topLeft()); } } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::drawMove (const QPoint &thisPoint, const QRect &/*normalizedRect*/) +void kpAbstractSelectionTool::drawMove(const QPoint &thisPoint, const QRect & /*normalizedRect*/) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "\tmoving selection"; #endif - kpAbstractSelection *sel = document ()->selection (); + kpAbstractSelection *sel = document()->selection(); - QRect targetSelRect (thisPoint.x () - d->startMoveDragFromSelectionTopLeft.x (), - thisPoint.y () - d->startMoveDragFromSelectionTopLeft.y (), - sel->width (), - sel->height ()); + QRect targetSelRect(thisPoint.x() - d->startMoveDragFromSelectionTopLeft.x(), + thisPoint.y() - d->startMoveDragFromSelectionTopLeft.y(), + sel->width(), + sel->height()); #if DEBUG_KP_TOOL_SELECTION && 1 - qCDebug(kpLogTools) << "\t\tstartPoint=" << startPoint () - << " thisPoint=" << thisPoint - << " startDragFromSel=" << d->startMoveDragFromSelectionTopLeft - << " targetSelRect=" << targetSelRect; + qCDebug(kpLogTools) << "\t\tstartPoint=" << startPoint() + << " thisPoint=" << thisPoint + << " startDragFromSel=" << d->startMoveDragFromSelectionTopLeft + << " targetSelRect=" << targetSelRect; #endif // Try to make sure selection still intersects document so that it's // reachable. - if (targetSelRect.right () < 0) { - targetSelRect.translate (-targetSelRect.right (), 0); - } - else if (targetSelRect.left () >= document ()->width ()) { - targetSelRect.translate (document ()->width () - targetSelRect.left () - 1, 0); + if (targetSelRect.right() < 0) { + targetSelRect.translate(-targetSelRect.right(), 0); + } else if (targetSelRect.left() >= document()->width()) { + targetSelRect.translate(document()->width() - targetSelRect.left() - 1, 0); } - if (targetSelRect.bottom () < 0) { - targetSelRect.translate (0, -targetSelRect.bottom ()); - } - else if (targetSelRect.top () >= document ()->height ()) { - targetSelRect.translate (0, document ()->height () - targetSelRect.top () - 1); + if (targetSelRect.bottom() < 0) { + targetSelRect.translate(0, -targetSelRect.bottom()); + } else if (targetSelRect.top() >= document()->height()) { + targetSelRect.translate(0, document()->height() - targetSelRect.top() - 1); } #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "\t\t\tafter ensure sel rect clickable=" << targetSelRect; #endif - - if (!d->dragAccepted && - targetSelRect.topLeft () + d->startMoveDragFromSelectionTopLeft == startPoint ()) - { + if (!d->dragAccepted + && targetSelRect.topLeft() + d->startMoveDragFromSelectionTopLeft == startPoint()) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "\t\t\t\tnop"; #endif - - if (!d->RMBMoveUpdateGUITimer->isActive ()) - { + if (!d->RMBMoveUpdateGUITimer->isActive()) { // (slotRMBMoveUpdateGUI() calls similar line) - setUserShapePoints (sel->topLeft ()); + setUserShapePoints(sel->topLeft()); } // Prevent both NOP drag-moves return; } - - if (d->RMBMoveUpdateGUITimer->isActive ()) - { - d->RMBMoveUpdateGUITimer->stop (); - slotRMBMoveUpdateGUI (); + if (d->RMBMoveUpdateGUITimer->isActive()) { + d->RMBMoveUpdateGUITimer->stop(); + slotRMBMoveUpdateGUI(); } + giveContentIfNeeded(); - giveContentIfNeeded (); - - - if (!d->currentMoveCommand) - { - d->currentMoveCommand = new kpToolSelectionMoveCommand ( - QString()/*uninteresting child of macro cmd*/, - environ ()->commandEnvironment ()); + if (!d->currentMoveCommand) { + d->currentMoveCommand = new kpToolSelectionMoveCommand( + QString() /*uninteresting child of macro cmd*/, + environ()->commandEnvironment()); d->currentMoveCommandIsSmear = false; } - //viewManager ()->setQueueUpdates (); //viewManager ()->setFastUpdates (); - if (shiftPressed ()) { + if (shiftPressed()) { d->currentMoveCommandIsSmear = true; } - if (!d->dragAccepted && (controlPressed () || shiftPressed ())) { - d->currentMoveCommand->copyOntoDocument (); + if (!d->dragAccepted && (controlPressed() || shiftPressed())) { + d->currentMoveCommand->copyOntoDocument(); } - d->currentMoveCommand->moveTo (targetSelRect.topLeft ()); + d->currentMoveCommand->moveTo(targetSelRect.topLeft()); - if (shiftPressed ()) { - d->currentMoveCommand->copyOntoDocument (); + if (shiftPressed()) { + d->currentMoveCommand->copyOntoDocument(); } //viewManager ()->restoreFastUpdates (); //viewManager ()->restoreQueueUpdates (); // REFACTOR: yuck, yuck - kpAbstractSelection *orgSel = d->currentMoveCommand->originalSelectionClone (); - QPoint start = orgSel->topLeft (); + kpAbstractSelection *orgSel = d->currentMoveCommand->originalSelectionClone(); + QPoint start = orgSel->topLeft(); delete orgSel; - QPoint end = targetSelRect.topLeft (); - setUserShapePoints (start, end, false/*don't set size*/); - setUserShapeSize (end.x () - start.x (), end.y () - start.y ()); - + QPoint end = targetSelRect.topLeft(); + setUserShapePoints(start, end, false /*don't set size*/); + setUserShapeSize(end.x() - start.x(), end.y() - start.y()); d->dragAccepted = true; } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::cancelMove () +void kpAbstractSelectionTool::cancelMove() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "\twas drag moving - undo drag and undo acquire"; #endif - d->RMBMoveUpdateGUITimer->stop (); + d->RMBMoveUpdateGUITimer->stop(); // NOP drag? if (!d->currentMoveCommand) { @@ -310,94 +292,89 @@ #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "\t\tundo currentMoveCommand"; #endif - d->currentMoveCommand->finalize (); - d->currentMoveCommand->unexecute (); + d->currentMoveCommand->finalize(); + d->currentMoveCommand->unexecute(); delete d->currentMoveCommand; d->currentMoveCommand = nullptr; } //--------------------------------------------------------------------- // protected virtual -QString kpAbstractSelectionTool::nonSmearMoveCommandName () const +QString kpAbstractSelectionTool::nonSmearMoveCommandName() const { - return i18n ("Selection: Move"); + return i18n("Selection: Move"); } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::endDrawMove () +void kpAbstractSelectionTool::endDrawMove() { - d->RMBMoveUpdateGUITimer->stop (); + d->RMBMoveUpdateGUITimer->stop(); // NOP drag? if (!d->currentMoveCommand) { return; } - d->currentMoveCommand->finalize (); + d->currentMoveCommand->finalize(); kpMacroCommand *renamedCmd = nullptr; #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "\thave moveCommand"; #endif - if (d->currentMoveCommandIsSmear) - { - renamedCmd = new kpMacroCommand (i18n ("%1: Smear", - document ()->selection ()->name ()), - environ ()->commandEnvironment ()); - } - else - { - renamedCmd = new kpMacroCommand ( - /*virtual*/nonSmearMoveCommandName (), - environ ()->commandEnvironment ()); + if (d->currentMoveCommandIsSmear) { + renamedCmd = new kpMacroCommand(i18n("%1: Smear", + document()->selection()->name()), + environ()->commandEnvironment()); + } else { + renamedCmd = new kpMacroCommand( + /*virtual*/ nonSmearMoveCommandName(), + environ()->commandEnvironment()); } - renamedCmd->addCommand (d->currentMoveCommand); + renamedCmd->addCommand(d->currentMoveCommand); d->currentMoveCommand = nullptr; - addNeedingContentCommand (renamedCmd); + addNeedingContentCommand(renamedCmd); } //--------------------------------------------------------------------- // private -QVariant kpAbstractSelectionTool::operationMove (Operation op, - const QVariant &data1, const QVariant &data2) +QVariant kpAbstractSelectionTool::operationMove(Operation op, const QVariant &data1, + const QVariant &data2) { - (void) data1; - (void) data2; - + (void)data1; + (void)data2; - switch (op) - { + switch (op) { case HaventBegunDrawUserMessage: - return /*virtual*/haventBegunDrawUserMessageMove (); + return /*virtual*/ haventBegunDrawUserMessageMove(); case SetCursor: - setCursorMove (); + setCursorMove(); break; case BeginDraw: - beginDrawMove (); + beginDrawMove(); break; case Draw: - drawMove (currentPoint (), normalizedRect ()); + drawMove(currentPoint(), normalizedRect()); break; case Cancel: - cancelMove (); + cancelMove(); break; case EndDraw: - endDrawMove (); + endDrawMove(); break; default: - Q_ASSERT (!"Unhandled operation"); + Q_ASSERT(!"Unhandled operation"); break; } diff --git a/tools/selection/kpAbstractSelectionTool_ResizeScale.cpp b/tools/selection/kpAbstractSelectionTool_ResizeScale.cpp --- a/tools/selection/kpAbstractSelectionTool_ResizeScale.cpp +++ b/tools/selection/kpAbstractSelectionTool_ResizeScale.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_SELECTION 0 - #include "kpAbstractSelectionTool.h" #include "kpAbstractSelectionToolPrivate.h" #include "kpLogCategories.h" @@ -52,69 +49,66 @@ #include "views/kpView.h" #include "views/manager/kpViewManager.h" - // private -int kpAbstractSelectionTool::onSelectionResizeHandle () const +int kpAbstractSelectionTool::onSelectionResizeHandle() const { - kpView *v = viewManager ()->viewUnderCursor (); + kpView *v = viewManager()->viewUnderCursor(); if (!v) { return 0; } - return v->mouseOnSelectionResizeHandle (currentViewPoint ()); + return v->mouseOnSelectionResizeHandle(currentViewPoint()); } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::initResizeScale () +void kpAbstractSelectionTool::initResizeScale() { d->currentResizeScaleCommand = nullptr; - // d->resizeScaleType + // d->resizeScaleType } // private -void kpAbstractSelectionTool::uninitResizeScale () +void kpAbstractSelectionTool::uninitResizeScale() { // (state must be after construction, or after some time after endResizeScale()) - Q_ASSERT (!d->currentResizeScaleCommand); + Q_ASSERT(!d->currentResizeScaleCommand); // d->resizeScaleType } - // private -void kpAbstractSelectionTool::beginResizeScale () +void kpAbstractSelectionTool::beginResizeScale() { // (state must be after construction, or after some time after endResizeScale()) - Q_ASSERT (!d->currentResizeScaleCommand); + Q_ASSERT(!d->currentResizeScaleCommand); // d->resizeScaleType } // private -void kpAbstractSelectionTool::endResizeScale () +void kpAbstractSelectionTool::endResizeScale() { // (should have been killed by cancelResizeScale() or endResizeScale()) - Q_ASSERT (!d->currentResizeScaleCommand); + Q_ASSERT(!d->currentResizeScaleCommand); // d->resizeScaleType } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::setCursorResizeScale () +void kpAbstractSelectionTool::setCursorResizeScale() { #if DEBUG_KP_TOOL_SELECTION && 0 qCDebug(kpLogTools) << "\tonSelectionResizeHandle=" - << onSelectionResizeHandle (); + << onSelectionResizeHandle(); #endif Qt::CursorShape shape = Qt::ArrowCursor; - switch (onSelectionResizeHandle ()) - { + switch (onSelectionResizeHandle()) { case (kpView::Top | kpView::Left): case (kpView::Bottom | kpView::Right): shape = Qt::SizeFDiagCursor; @@ -136,46 +130,43 @@ break; } - viewManager ()->setCursor (shape); + viewManager()->setCursor(shape); } //--------------------------------------------------------------------- // protected virtual -void kpAbstractSelectionTool::setSelectionBorderForBeginDrawResizeScale () +void kpAbstractSelectionTool::setSelectionBorderForBeginDrawResizeScale() { - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { - viewManager ()->setSelectionBorderVisible (true); - viewManager ()->setSelectionBorderFinished (true); + viewManager()->setSelectionBorderVisible(true); + viewManager()->setSelectionBorderFinished(true); } - viewManager ()->restoreQueueUpdates (); + viewManager()->restoreQueueUpdates(); } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::beginDrawResizeScale () +void kpAbstractSelectionTool::beginDrawResizeScale() { - d->resizeScaleType = onSelectionResizeHandle (); + d->resizeScaleType = onSelectionResizeHandle(); - /*virtual*/setSelectionBorderForBeginDrawResizeScale (); + /*virtual*/ setSelectionBorderForBeginDrawResizeScale(); - setUserMessage (cancelUserMessage ()); + setUserMessage(cancelUserMessage()); } //--------------------------------------------------------------------- - // private -void kpAbstractSelectionTool::drawResizeScaleTryKeepAspect ( - int newWidth, int newHeight, - bool horizontalGripDragged, bool verticalGripDragged, - const kpAbstractSelection &originalSelection, - int *newWidthOut, int *newHeightOut) +void kpAbstractSelectionTool::drawResizeScaleTryKeepAspect( + int newWidth, int newHeight, bool horizontalGripDragged, bool verticalGripDragged, + const kpAbstractSelection &originalSelection, int *newWidthOut, int *newHeightOut) { - const int oldWidth = originalSelection.width (), - oldHeight = originalSelection.height (); + const int oldWidth = originalSelection.width(), + oldHeight = originalSelection.height(); // Width changed more than height? At equality, favor width. // Fix width, change height. @@ -185,28 +176,25 @@ // we're not dragging a vertical grip. We certainly don't want this // code to modify the width - we want to fix the width and change the // height. - if ((horizontalGripDragged ? double (newWidth) / oldWidth : 0) >= - (verticalGripDragged ? double (newHeight) / oldHeight : 0)) - { + if ((horizontalGripDragged ? double(newWidth) / oldWidth : 0) + >= (verticalGripDragged ? double(newHeight) / oldHeight : 0)) { *newHeightOut = newWidth * oldHeight / oldWidth; - *newHeightOut = qMax (originalSelection.minimumHeight (), *newHeightOut); + *newHeightOut = qMax(originalSelection.minimumHeight(), *newHeightOut); } // Height changed more than width? // Fix height, change width. - else - { + else { *newWidthOut = newHeight * oldWidth / oldHeight; - *newWidthOut = qMax (originalSelection.minimumWidth (), *newWidthOut); + *newWidthOut = qMax(originalSelection.minimumWidth(), *newWidthOut); } } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::drawResizeScaleCalculateNewSelectionPosSize ( - const kpAbstractSelection &originalSelection, - int *newX, int *newY, - int *newWidth, int *newHeight) +void kpAbstractSelectionTool::drawResizeScaleCalculateNewSelectionPosSize( + const kpAbstractSelection &originalSelection, int *newX, int *newY, int *newWidth, + int *newHeight) { // // Determine new width. @@ -218,19 +206,17 @@ int userXSign = 0; if (d->resizeScaleType & kpView::Left) { userXSign = -1; - } - else if (d->resizeScaleType & kpView::Right) { + } else if (d->resizeScaleType & kpView::Right) { userXSign = +1; } // Calcluate new width. - *newWidth = originalSelection.width () + - userXSign * (currentPoint ().x () - startPoint ().x ()); + *newWidth = originalSelection.width() + +userXSign * (currentPoint().x() - startPoint().x()); // Don't allow new width to be less than that kind of selection type's // minimum. - *newWidth = qMax (originalSelection.minimumWidth (), *newWidth); - + *newWidth = qMax(originalSelection.minimumWidth(), *newWidth); // // Determine new height. @@ -242,132 +228,115 @@ int userYSign = 0; if (d->resizeScaleType & kpView::Top) { userYSign = -1; - } - else if (d->resizeScaleType & kpView::Bottom) { + } else if (d->resizeScaleType & kpView::Bottom) { userYSign = +1; } // Calcluate new height. - *newHeight = originalSelection.height () + - userYSign * (currentPoint ().y () - startPoint ().y ()); + *newHeight = originalSelection.height() + +userYSign * (currentPoint().y() - startPoint().y()); // Don't allow new height to be less than that kind of selection type's // minimum. - *newHeight = qMax (originalSelection.minimumHeight (), *newHeight); - + *newHeight = qMax(originalSelection.minimumHeight(), *newHeight); // Keep aspect ratio? - if (shiftPressed ()) - { - drawResizeScaleTryKeepAspect (*newWidth, *newHeight, - (userXSign != 0)/*X or XY grip dragged*/, - (userYSign != 0)/*Y or XY grip dragged*/, - originalSelection, - newWidth/*ptr*/, newHeight/*ptr*/); + if (shiftPressed()) { + drawResizeScaleTryKeepAspect(*newWidth, *newHeight, + (userXSign != 0) /*X or XY grip dragged*/, + (userYSign != 0) /*Y or XY grip dragged*/, + originalSelection, + newWidth /*ptr*/, newHeight /*ptr*/); } - - *newX = originalSelection.x (); - *newY = originalSelection.y (); - + *newX = originalSelection.x(); + *newY = originalSelection.y(); // // Adjust x/y to new width/height for left/top resizes. // - if (d->resizeScaleType & kpView::Left) - { - *newX -= (*newWidth - originalSelection.width ()); + if (d->resizeScaleType & kpView::Left) { + *newX -= (*newWidth - originalSelection.width()); } - if (d->resizeScaleType & kpView::Top) - { - *newY -= (*newHeight - originalSelection.height ()); + if (d->resizeScaleType & kpView::Top) { + *newY -= (*newHeight - originalSelection.height()); } #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "\t\tnewX=" << *newX - << " newY=" << *newY - << " newWidth=" << *newWidth - << " newHeight=" << *newHeight; + << " newY=" << *newY + << " newWidth=" << *newWidth + << " newHeight=" << *newHeight; #endif } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::drawResizeScale ( - const QPoint &thisPoint, - const QRect &/*normalizedRect*/) +void kpAbstractSelectionTool::drawResizeScale( + const QPoint &thisPoint, const QRect & /*normalizedRect*/) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "\tresize/scale"; #endif - kpAbstractSelection *sel = document ()->selection (); + kpAbstractSelection *sel = document()->selection(); - if (!d->dragAccepted && thisPoint == startPoint ()) - { + if (!d->dragAccepted && thisPoint == startPoint()) { #if DEBUG_KP_TOOL_SELECTION && 1 qCDebug(kpLogTools) << "\t\tnop"; #endif - setUserShapePoints (QPoint (sel->width (), sel->height ())); + setUserShapePoints(QPoint(sel->width(), sel->height())); return; } + giveContentIfNeeded(); - giveContentIfNeeded (); - - - if (!d->currentResizeScaleCommand) - { + if (!d->currentResizeScaleCommand) { d->currentResizeScaleCommand - = new kpToolSelectionResizeScaleCommand (environ ()->commandEnvironment ()); + = new kpToolSelectionResizeScaleCommand(environ()->commandEnvironment()); } - - const kpAbstractSelection *originalSelection = - d->currentResizeScaleCommand->originalSelection (); - + const kpAbstractSelection *originalSelection + = d->currentResizeScaleCommand->originalSelection(); // There is nothing illegal about position (-1,-1) but why not. int newX = -1, newY = -1, newWidth = 0, newHeight = 0; // This should change all of the above values. - drawResizeScaleCalculateNewSelectionPosSize ( + drawResizeScaleCalculateNewSelectionPosSize( *originalSelection, &newX, &newY, &newWidth, &newHeight); - - viewManager ()->setFastUpdates (); + viewManager()->setFastUpdates(); { - d->currentResizeScaleCommand->resizeAndMoveTo ( + d->currentResizeScaleCommand->resizeAndMoveTo( newWidth, newHeight, - QPoint (newX, newY), - true/*smooth scale delayed*/); + QPoint(newX, newY), + true /*smooth scale delayed*/); } - viewManager ()->restoreFastUpdates (); - - setUserShapePoints (QPoint (originalSelection->width (), - originalSelection->height ()), - QPoint (newWidth, - newHeight), - false/*don't set size*/); - setUserShapeSize (newWidth - originalSelection->width (), - newHeight - originalSelection->height ()); + viewManager()->restoreFastUpdates(); + setUserShapePoints(QPoint(originalSelection->width(), + originalSelection->height()), + QPoint(newWidth, + newHeight), + false /*don't set size*/); + setUserShapeSize(newWidth - originalSelection->width(), + newHeight - originalSelection->height()); d->dragAccepted = true; } //--------------------------------------------------------------------- - // private -void kpAbstractSelectionTool::cancelResizeScale () +void kpAbstractSelectionTool::cancelResizeScale() { #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "\twas resize/scale sel - kill"; @@ -381,69 +350,66 @@ #if DEBUG_KP_TOOL_SELECTION qCDebug(kpLogTools) << "\t\tundo currentResizeScaleCommand"; #endif - d->currentResizeScaleCommand->finalize (); // (unneeded but let's be safe) - d->currentResizeScaleCommand->unexecute (); + d->currentResizeScaleCommand->finalize(); // (unneeded but let's be safe) + d->currentResizeScaleCommand->unexecute(); delete d->currentResizeScaleCommand; d->currentResizeScaleCommand = nullptr; } //--------------------------------------------------------------------- // private -void kpAbstractSelectionTool::endDrawResizeScale () +void kpAbstractSelectionTool::endDrawResizeScale() { // NOP drag? if (!d->currentResizeScaleCommand) { return; } - d->currentResizeScaleCommand->finalize (); + d->currentResizeScaleCommand->finalize(); - addNeedingContentCommand (d->currentResizeScaleCommand); + addNeedingContentCommand(d->currentResizeScaleCommand); d->currentResizeScaleCommand = nullptr; } //--------------------------------------------------------------------- // private -QVariant kpAbstractSelectionTool::operationResizeScale (Operation op, - const QVariant &data1, const QVariant &data2) +QVariant kpAbstractSelectionTool::operationResizeScale(Operation op, const QVariant &data1, + const QVariant &data2) { - (void) data1; - (void) data2; - + (void)data1; + (void)data2; - switch (op) - { + switch (op) { case HaventBegunDrawUserMessage: - return /*virtual*/haventBegunDrawUserMessageResizeScale (); + return /*virtual*/ haventBegunDrawUserMessageResizeScale(); case SetCursor: - setCursorResizeScale (); + setCursorResizeScale(); break; case BeginDraw: - beginDrawResizeScale (); + beginDrawResizeScale(); break; case Draw: - drawResizeScale (currentPoint (), normalizedRect ()); + drawResizeScale(currentPoint(), normalizedRect()); break; case Cancel: - cancelResizeScale (); + cancelResizeScale(); break; case EndDraw: - endDrawResizeScale (); + endDrawResizeScale(); break; default: - Q_ASSERT (!"Unhandled operation"); + Q_ASSERT(!"Unhandled operation"); break; } - return {}; } diff --git a/tools/selection/text/kpToolText.h b/tools/selection/text/kpToolText.h --- a/tools/selection/text/kpToolText.h +++ b/tools/selection/text/kpToolText.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_TEXT_H #define KP_TOOL_TEXT_H - #include "tools/selection/kpAbstractSelectionTool.h" - class QKeyEvent; class kpColor; @@ -43,7 +39,6 @@ class kpToolTextBackspaceCommand; class kpToolTextDeleteCommand; - // // kpAbstractSelectionTool considers a drawing operation to be a mouse // drag that creates, moves or resize/scales a selection. @@ -76,13 +71,12 @@ // class kpToolText : public kpAbstractSelectionTool { -Q_OBJECT + Q_OBJECT public: kpToolText (kpToolSelectionEnvironment *environ, QObject *parent); ~kpToolText () override; - // // Text Command Handling // @@ -103,8 +97,7 @@ * might be split into 10 text insertion commands, each containing 1 * character. */ - void endTypingCommands (); - + void endTypingCommands(); /** * Ends the current text editing command by eventually calling @@ -115,7 +108,7 @@ * On function return, the pointed-to d->backspace.*Command * pointer will point to a new kpToolTextBackspaceCommand. */ - void addNewBackspaceCommand (kpToolTextBackspaceCommand **cmd); + void addNewBackspaceCommand(kpToolTextBackspaceCommand **cmd); /** * Ends the current text editing command by eventually calling @@ -126,73 +119,63 @@ * function return, the pointed-to d->delete.*Command pointer * will point to a new kpToolTextDeleteCommand. */ - void addNewDeleteCommand (kpToolTextDeleteCommand **cmd); - - void addNewEnterCommand (kpToolTextEnterCommand **cmd); + void addNewDeleteCommand(kpToolTextDeleteCommand **cmd); - void addNewInsertCommand (kpToolTextInsertCommand **cmd); + void addNewEnterCommand(kpToolTextEnterCommand **cmd); + void addNewInsertCommand(kpToolTextInsertCommand **cmd); // // Drawing // protected: - kpAbstractSelectionContentCommand *newGiveContentCommand () const override; - - QString nameOfCreateCommand () const override; + kpAbstractSelectionContentCommand *newGiveContentCommand() const override; + QString nameOfCreateCommand() const override; protected: - void setSelectionBorderForHaventBegunDraw () override; - + void setSelectionBorderForHaventBegunDraw() override; public: - void begin () override; - void end () override; - + void begin() override; + void end() override; public: - bool hasBegunText () const; - bool hasBegunShape () const override; - + bool hasBegunText() const; + bool hasBegunShape() const override; // // Drawing - Beginning a Drag // protected: - DrawType calculateDrawTypeInsideSelection () const override; - + DrawType calculateDrawTypeInsideSelection() const override; public: - void cancelShape () override; - + void cancelShape() override; public: - void endShape (const QPoint &thisPoint, const QRect &normalizedRect) override; - + void endShape(const QPoint &thisPoint, const QRect &normalizedRect) override; // // Drawing - Operation Dispatching // protected: - QVariant operation (DrawType drawType, Operation op, - const QVariant &data1 = QVariant (), const QVariant &data2 = QVariant ()) override; - + QVariant operation(DrawType drawType, Operation op, + const QVariant &data1 = QVariant(), + const QVariant &data2 = QVariant()) override; // // Create // protected: - QString haventBegunDrawUserMessageCreate () const override; - + QString haventBegunDrawUserMessageCreate() const override; protected: - void setSelectionBorderForBeginDrawCreate () override; - + void setSelectionBorderForBeginDrawCreate() override; private: // Returns the suggested width/height of a click-created text box: @@ -204,79 +187,66 @@ // = the legal minimum width/height of the selection // // = the width/height of the document - int calcClickCreateDimension (int mouseStart, int mouseEnd, - int preferredMin, int smallestMin, - int docSize); - bool shouldCreate ( - bool drawAcceptedAsDrag, - const QPoint &accidentalDragAdjustedPoint, - const kpTextStyle &textStyle, - int *minimumWidthOut, int *minimumHeightOut, + int calcClickCreateDimension(int mouseStart, int mouseEnd, int preferredMin, int smallestMin, + int docSize); + bool shouldCreate( + bool drawAcceptedAsDrag, const QPoint &accidentalDragAdjustedPoint, + const kpTextStyle &textStyle, int *minimumWidthOut, int *minimumHeightOut, bool *newDragHasBegun); protected: - bool drawCreateMoreSelectionAndUpdateStatusBar ( - bool drawAcceptedAsDrag, - const QPoint &accidentalDragAdjustedPoint, + bool drawCreateMoreSelectionAndUpdateStatusBar( + bool drawAcceptedAsDrag, const QPoint &accidentalDragAdjustedPoint, const QRect &normalizedRectIn) override; - // // Move // protected: - QString haventBegunDrawUserMessageMove () const override; - + QString haventBegunDrawUserMessageMove() const override; protected: - void setSelectionBorderForBeginDrawMove () override; - + void setSelectionBorderForBeginDrawMove() override; protected: - QString nonSmearMoveCommandName () const override; - + QString nonSmearMoveCommandName() const override; // // Resize/Scale // protected: - QString haventBegunDrawUserMessageResizeScale () const override; - + QString haventBegunDrawUserMessageResizeScale() const override; protected: - void setSelectionBorderForBeginDrawResizeScale () override; - + void setSelectionBorderForBeginDrawResizeScale() override; // // Select Text // private: - bool onSelectionToSelectText () const; - + bool onSelectionToSelectText() const; private: - QString haventBegunDrawUserMessageSelectText () const; - - void setCursorSelectText (); + QString haventBegunDrawUserMessageSelectText() const; + void setCursorSelectText(); private: - void beginDrawSelectText (); - + void beginDrawSelectText(); protected: - virtual QVariant selectTextOperation (Operation op, - const QVariant &data1 = QVariant (), const QVariant &data2 = QVariant ()); - + virtual QVariant selectTextOperation(Operation op, + const QVariant &data1 = QVariant(), + const QVariant &data2 = QVariant()); // // User Changing Text Style Elements // protected: - bool shouldChangeTextStyle () const; + bool shouldChangeTextStyle() const; /** * Adds a kpToolTextChangeStyleCommand to commandHistory(). @@ -290,39 +260,39 @@ * * You should only call this if shouldChangeTextStyle() returns true. */ - void changeTextStyle (const QString &name, - const kpTextStyle &newTextStyle, - const kpTextStyle &oldTextStyle); + void changeTextStyle(const QString &name, const kpTextStyle &newTextStyle, + const kpTextStyle &oldTextStyle); protected slots: - void slotIsOpaqueChanged (bool isOpaque) override; - + void slotIsOpaqueChanged(bool isOpaque) override; protected: /** * Asks kpTool to call slotColorsSwapped() when the foreground and * background color are swapped. * * Re-implemented from kpTool. */ - bool careAboutColorsSwapped () const override { return true; } + bool careAboutColorsSwapped() const override + { + return true; + } protected slots: - void slotColorsSwapped (const kpColor &newForegroundColor, - const kpColor &newBackgroundColor) override; + void slotColorsSwapped(const kpColor &newForegroundColor, + const kpColor &newBackgroundColor) override; - void slotForegroundColorChanged (const kpColor &color) override; - void slotBackgroundColorChanged (const kpColor &color) override; - void slotColorSimilarityChanged (double, int) override; + void slotForegroundColorChanged(const kpColor &color) override; + void slotBackgroundColorChanged(const kpColor &color) override; + void slotColorSimilarityChanged(double, int) override; public slots: - void slotFontFamilyChanged (const QString &fontFamily, const QString &oldFontFamily); - void slotFontSizeChanged (int fontSize, int oldFontSize); - void slotBoldChanged (bool isBold); - void slotItalicChanged (bool isItalic); - void slotUnderlineChanged (bool isUnderline); - void slotStrikeThruChanged (bool isStrikeThru); - + void slotFontFamilyChanged(const QString &fontFamily, const QString &oldFontFamily); + void slotFontSizeChanged(int fontSize, int oldFontSize); + void slotBoldChanged(bool isBold); + void slotItalicChanged(bool isItalic); + void slotUnderlineChanged(bool isUnderline); + void slotStrikeThruChanged(bool isStrikeThru); // // Text Cursor Calculations (all static, no mutations) @@ -337,9 +307,7 @@ * @returns whether the cursor is currently on a word character * (not a space). */ - static bool CursorIsOnWordChar (const QList &textLines, - int cursorRow, int cursorCol); - + static bool CursorIsOnWordChar(const QList &textLines, int cursorRow, int cursorCol); /** * @param textLines One or more lines of text. @@ -350,8 +318,7 @@ * textLines (on the first character of the first line) * i.e. when moveCursorLeft() won't do anything. */ - static bool CursorIsAtStart (const QList &textLines, - int cursorRow, int cursorCol); + static bool CursorIsAtStart(const QList &textLines, int cursorRow, int cursorCol); /** * @param textLines One or more lines of text. @@ -362,9 +329,7 @@ * textLines (after the last character of the last line) * i.e. when moveCursorRight() won't do anything. */ - static bool CursorIsAtEnd (const QList &textLines, - int cursorRow, int cursorCol); - + static bool CursorIsAtEnd(const QList &textLines, int cursorRow, int cursorCol); /** * Moves the given cursor position one character to the left, if @@ -379,8 +344,7 @@ * the current column of the cursor and modified on * return to indicate the new column. */ - static void MoveCursorLeft (const QList &textLines, - int *cursorRow, int *cursorCol); + static void MoveCursorLeft(const QList &textLines, int *cursorRow, int *cursorCol); /** * Moves the given cursor position one character to the right, if @@ -395,9 +359,7 @@ * the current column of the cursor and modified on * return to indicate the new column. */ - static void MoveCursorRight (const QList &textLines, - int *cursorRow, int *cursorCol); - + static void MoveCursorRight(const QList &textLines, int *cursorRow, int *cursorCol); /** * Moves the row and column values, representing the current cursor @@ -418,8 +380,8 @@ * Note: Attempting to moving left when cursorIsAtStart() * may still be counted as a move. */ - static int MoveCursorToWordStart (const QList &textLines, - int *cursorRow, int *cursorCol); + static int MoveCursorToWordStart(const QList &textLines, int *cursorRow, + int *cursorCol); /** * Moves the row and column values, representing the current cursor @@ -440,9 +402,8 @@ * Note: Attempting to moving right when cursorIsAtEnd() * may still be counted as a move. */ - static int MoveCursorToNextWordStart (const QList &textLines, - int *cursorRow, int *cursorCol); - + static int MoveCursorToNextWordStart(const QList &textLines, int *cursorRow, + int *cursorCol); // // Keyboard Events - Handling Arrow Keys @@ -477,8 +438,8 @@ * * Called by keyPressEvent(). */ - void handleUpKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol); + void handleUpKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol); /** * Moves the text cursor down one character. Accepts the key event @p e. @@ -492,8 +453,8 @@ * * Called by keyPressEvent(). */ - void handleDownKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol); + void handleDownKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol); /** * Moves the text cursor left one character or if CTRL is held, one @@ -508,8 +469,8 @@ * * Called by keyPressEvent(). */ - void handleLeftKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol); + void handleLeftKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol); /** * Moves the text cursor right one character or if CTRL is held, one @@ -524,9 +485,8 @@ * * Called by keyPressEvent(). */ - void handleRightKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol); - + void handleRightKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol); /** * Moves the text cursor to the start of the line and if CTRL is held, @@ -541,8 +501,8 @@ * * Called by keyPressEvent(). */ - void handleHomeKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol); + void handleHomeKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol); /** * Moves the text cursor to after the last character of the current @@ -558,9 +518,8 @@ * * Called by keyPressEvent(). */ - void handleEndKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol); - + void handleEndKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol); // // Keyboard Events - Handling Typing Keys @@ -607,8 +566,8 @@ * * Called by keyPressEvent(). */ - void handleBackspaceKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol); + void handleBackspaceKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol); /** * Deletes and if the active text editing command is not @@ -632,9 +591,8 @@ * * Called by keyPressEvent(). */ - void handleDeleteKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol); - + void handleDeleteKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol); /** * Enters and if the active text editing command is not @@ -650,9 +608,8 @@ * * Called by keyPressEvent(). */ - void handleEnterKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol); - + void handleEnterKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol); /** * Inserts the printable characters of e->text() and accepts the key @@ -673,9 +630,8 @@ * * Called by keyPressEvent(). */ - void handleTextTyped (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol); - + void handleTextTyped(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol); // // Keyboard Events @@ -686,7 +642,7 @@ // keystrokes while a text selection is active. This is important // because the Tool Box actions default to single letter/number // shortcuts. - bool viewEvent (QEvent *e) override; + bool viewEvent(QEvent *e) override; /** * Handles key press events. @@ -706,20 +662,17 @@ * Re-implemented from kpAbstractSelectionTool. */ - void keyPressEvent (QKeyEvent *e) override; - + void keyPressEvent(QKeyEvent *e) override; // // Input Method Text Entry // protected: - void inputMethodEvent (QInputMethodEvent *e) override; - + void inputMethodEvent(QInputMethodEvent *e) override; private: - struct kpToolTextPrivate * const d; + struct kpToolTextPrivate *const d; }; - #endif // KP_TOOL_TEXT_H diff --git a/tools/selection/text/kpToolText.cpp b/tools/selection/text/kpToolText.cpp --- a/tools/selection/text/kpToolText.cpp +++ b/tools/selection/text/kpToolText.cpp @@ -1,4 +1,3 @@ - // REFACTOR: For all files involved in the class, refactor remaining bits and pieces and add APIDoc /* @@ -29,7 +28,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpToolTextPrivate.h" #include "kpLogCategories.h" @@ -52,171 +50,154 @@ #include kpToolText::kpToolText (kpToolSelectionEnvironment *environ, QObject *parent) - : kpAbstractSelectionTool (i18n ("Text"), i18n ("Writes text"), - Qt::Key_T, - environ, parent, QStringLiteral("tool_text")), - d (new kpToolTextPrivate ()) + : kpAbstractSelectionTool(i18n("Text"), i18n("Writes text"), + Qt::Key_T, + environ, parent, QStringLiteral("tool_text")) + , d(new kpToolTextPrivate()) { } kpToolText::~kpToolText () { delete d; } - // protected virtual [kpAbstractSelectionTool] -kpAbstractSelectionContentCommand *kpToolText::newGiveContentCommand () const +kpAbstractSelectionContentCommand *kpToolText::newGiveContentCommand() const { - kpTextSelection *textSel = document ()->textSelection (); + kpTextSelection *textSel = document()->textSelection(); #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::newGiveContentCommand()" - << " textSel=" << textSel - << "; hasContent=" << textSel->hasContent (); + << " textSel=" << textSel + << "; hasContent=" << textSel->hasContent(); #endif - Q_ASSERT (textSel && !textSel->hasContent ()); - - return new kpToolTextGiveContentCommand ( + Q_ASSERT(textSel && !textSel->hasContent()); + + return new kpToolTextGiveContentCommand( *textSel, - QString()/*uninteresting child of macro cmd*/, - environ ()->commandEnvironment ()); + QString() /*uninteresting child of macro cmd*/, + environ()->commandEnvironment()); } - // protected virtual [kpAbstractSelectionTool] -QString kpToolText::nameOfCreateCommand () const +QString kpToolText::nameOfCreateCommand() const { - return i18n ("Text: Create Box"); + return i18n("Text: Create Box"); } - // protected virtual [base kpAbstractSelectionTool] -void kpToolText::setSelectionBorderForHaventBegunDraw () +void kpToolText::setSelectionBorderForHaventBegunDraw() { - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { - kpAbstractSelectionTool::setSelectionBorderForHaventBegunDraw (); - viewManager ()->setTextCursorEnabled (true); + kpAbstractSelectionTool::setSelectionBorderForHaventBegunDraw(); + viewManager()->setTextCursorEnabled(true); } - viewManager ()->restoreQueueUpdates (); + viewManager()->restoreQueueUpdates(); } - // public virtual [base kpAbstractSelectionTool] -void kpToolText::begin () +void kpToolText::begin() { #if DEBUG_KP_TOOL_TEXT && 1 qCDebug(kpLogTools) << "kpToolText::begin()"; #endif - environ ()->enableTextToolBarActions (true); + environ()->enableTextToolBarActions(true); // We don't actually need this since begin() already calls it via // setSelectionBorderForHaventBegunDraw(). We leave this in for // consistency with end(). - viewManager ()->setTextCursorEnabled (true); - viewManager()->setInputMethodEnabled (true); + viewManager()->setTextCursorEnabled(true); + viewManager()->setInputMethodEnabled(true); - endTypingCommands (); + endTypingCommands(); - kpAbstractSelectionTool::begin (); + kpAbstractSelectionTool::begin(); } // public virtual [base kpAbstractSelectionTool] -void kpToolText::end () +void kpToolText::end() { #if DEBUG_KP_TOOL_TEXT && 1 qCDebug(kpLogTools) << "kpToolText::end()"; #endif - kpAbstractSelectionTool::end (); + kpAbstractSelectionTool::end(); - viewManager()->setInputMethodEnabled (false); - viewManager ()->setTextCursorEnabled (false); - environ ()->enableTextToolBarActions (false); + viewManager()->setInputMethodEnabled(false); + viewManager()->setTextCursorEnabled(false); + environ()->enableTextToolBarActions(false); } - // public -bool kpToolText::hasBegunText () const +bool kpToolText::hasBegunText() const { - return (d->insertCommand || - d->enterCommand || - d->backspaceCommand || - d->backspaceWordCommand || - d->deleteCommand || - d->deleteWordCommand); + return d->insertCommand + || d->enterCommand + || d->backspaceCommand + || d->backspaceWordCommand + || d->deleteCommand + || d->deleteWordCommand; } // public virtual [base kpTool] -bool kpToolText::hasBegunShape () const +bool kpToolText::hasBegunShape() const { - return (hasBegunDraw () || hasBegunText ()); + return hasBegunDraw() || hasBegunText(); } - // protected virtual [base kpAbstractSelectionTool] -kpAbstractSelectionTool::DrawType kpToolText::calculateDrawTypeInsideSelection () const +kpAbstractSelectionTool::DrawType kpToolText::calculateDrawTypeInsideSelection() const { - if (onSelectionToSelectText () && !controlOrShiftPressed ()) - { + if (onSelectionToSelectText() && !controlOrShiftPressed()) { return kpAbstractSelectionTool::SelectText; } - return kpAbstractSelectionTool::calculateDrawTypeInsideSelection (); + return kpAbstractSelectionTool::calculateDrawTypeInsideSelection(); } - // public virtual [base kpAbstractSelectionTool] -void kpToolText::cancelShape () +void kpToolText::cancelShape() { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::cancelShape()"; #endif - if (drawType () != None) { - kpAbstractSelectionTool::cancelShape (); - } - else if (hasBegunText ()) - { - endTypingCommands (); + if (drawType() != None) { + kpAbstractSelectionTool::cancelShape(); + } else if (hasBegunText()) { + endTypingCommands(); - commandHistory ()->undo (); - } - else { - kpAbstractSelectionTool::cancelShape (); + commandHistory()->undo(); + } else { + kpAbstractSelectionTool::cancelShape(); } } - // public virtual [base kpTool] -void kpToolText::endShape (const QPoint &thisPoint, const QRect &normalizedRect) +void kpToolText::endShape(const QPoint &thisPoint, const QRect &normalizedRect) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::endShape()"; #endif - if (drawType () != None) { - kpAbstractSelectionTool::endDraw (thisPoint, normalizedRect); - } - else if (hasBegunText ()) { - endTypingCommands (); - } - else { - kpAbstractSelectionTool::endDraw (thisPoint, normalizedRect); + if (drawType() != None) { + kpAbstractSelectionTool::endDraw(thisPoint, normalizedRect); + } else if (hasBegunText()) { + endTypingCommands(); + } else { + kpAbstractSelectionTool::endDraw(thisPoint, normalizedRect); } } - // protected virtual [base kpAbstractSelectionTool] -QVariant kpToolText::operation (DrawType drawType, Operation op, - const QVariant &data1, const QVariant &data2) +QVariant kpToolText::operation(DrawType drawType, Operation op, const QVariant &data1, + const QVariant &data2) { if (drawType == SelectText) { - return selectTextOperation (op, data1, data2); + return selectTextOperation(op, data1, data2); } - return kpAbstractSelectionTool::operation (drawType, op, data1, data2); + return kpAbstractSelectionTool::operation(drawType, op, data1, data2); } - - diff --git a/tools/selection/text/kpToolTextPrivate.h b/tools/selection/text/kpToolTextPrivate.h --- a/tools/selection/text/kpToolTextPrivate.h +++ b/tools/selection/text/kpToolTextPrivate.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,27 +24,22 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpToolTextPrivate_H #define kpToolTextPrivate_H - #include - class kpToolTextInsertCommand; class kpToolTextEnterCommand; class kpToolTextBackspaceCommand; class kpToolTextDeleteCommand; - struct kpToolTextPrivate { kpToolTextInsertCommand *insertCommand; kpToolTextEnterCommand *enterCommand; kpToolTextBackspaceCommand *backspaceCommand, *backspaceWordCommand; kpToolTextDeleteCommand *deleteCommand, *deleteWordCommand; }; - #endif // kpToolTextPrivate_H diff --git a/tools/selection/text/kpToolText_Commands.cpp b/tools/selection/text/kpToolText_Commands.cpp --- a/tools/selection/text/kpToolText_Commands.cpp +++ b/tools/selection/text/kpToolText_Commands.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "kpToolText.h" #include "kpToolTextPrivate.h" #include "kpLogCategories.h" @@ -42,7 +40,7 @@ #include // private -void kpToolText::endTypingCommands () +void kpToolText::endTypingCommands() { d->insertCommand = nullptr; d->enterCommand = nullptr; @@ -54,72 +52,71 @@ d->deleteWordCommand = nullptr; } - // private -void kpToolText::addNewBackspaceCommand (kpToolTextBackspaceCommand **cmd) +void kpToolText::addNewBackspaceCommand(kpToolTextBackspaceCommand **cmd) { // TODO: why not endShapeInternal(); ditto for everywhere else in kpToolText*.cpp? - if (hasBegunShape ()) - { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - giveContentIfNeeded (); + giveContentIfNeeded(); - *cmd = new kpToolTextBackspaceCommand (i18n ("Text: Backspace"), - viewManager ()->textCursorRow (), viewManager ()->textCursorCol (), - kpToolTextBackspaceCommand::DontAddBackspaceYet, - environ ()->commandEnvironment ()); - addNeedingContentCommand (*cmd); + *cmd = new kpToolTextBackspaceCommand(i18n("Text: Backspace"), + viewManager()->textCursorRow(), + viewManager()->textCursorCol(), + kpToolTextBackspaceCommand::DontAddBackspaceYet, + environ()->commandEnvironment()); + addNeedingContentCommand(*cmd); } // private -void kpToolText::addNewDeleteCommand (kpToolTextDeleteCommand **cmd) +void kpToolText::addNewDeleteCommand(kpToolTextDeleteCommand **cmd) { - if (hasBegunShape ()) - { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - giveContentIfNeeded (); + giveContentIfNeeded(); - *cmd = new kpToolTextDeleteCommand (i18n ("Text: Delete"), - viewManager ()->textCursorRow (), viewManager ()->textCursorCol (), - kpToolTextDeleteCommand::DontAddDeleteYet, - environ ()->commandEnvironment ()); - addNeedingContentCommand (*cmd); + *cmd = new kpToolTextDeleteCommand(i18n("Text: Delete"), + viewManager()->textCursorRow(), + viewManager()->textCursorCol(), + kpToolTextDeleteCommand::DontAddDeleteYet, + environ()->commandEnvironment()); + addNeedingContentCommand(*cmd); } // private -void kpToolText::addNewEnterCommand (kpToolTextEnterCommand **cmd) +void kpToolText::addNewEnterCommand(kpToolTextEnterCommand **cmd) { - if (hasBegunShape ()) - { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - giveContentIfNeeded (); + giveContentIfNeeded(); - *cmd = new kpToolTextEnterCommand (i18n ("Text: New Line"), - viewManager ()->textCursorRow (), viewManager ()->textCursorCol (), - kpToolTextEnterCommand::DontAddEnterYet, - environ ()->commandEnvironment ()); - addNeedingContentCommand (*cmd); + *cmd = new kpToolTextEnterCommand(i18n("Text: New Line"), + viewManager()->textCursorRow(), + viewManager()->textCursorCol(), + kpToolTextEnterCommand::DontAddEnterYet, + environ()->commandEnvironment()); + addNeedingContentCommand(*cmd); } // private -void kpToolText::addNewInsertCommand (kpToolTextInsertCommand **cmd) +void kpToolText::addNewInsertCommand(kpToolTextInsertCommand **cmd) { - if (hasBegunShape ()) - { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - giveContentIfNeeded (); + giveContentIfNeeded(); - *cmd = new kpToolTextInsertCommand (i18n ("Text: Write"), - viewManager ()->textCursorRow (), viewManager ()->textCursorCol (), - QString (), - environ ()->commandEnvironment ()); - addNeedingContentCommand (*cmd); + *cmd = new kpToolTextInsertCommand(i18n("Text: Write"), + viewManager()->textCursorRow(), + viewManager()->textCursorCol(), + QString(), + environ()->commandEnvironment()); + addNeedingContentCommand(*cmd); } diff --git a/tools/selection/text/kpToolText_Create.cpp b/tools/selection/text/kpToolText_Create.cpp --- a/tools/selection/text/kpToolText_Create.cpp +++ b/tools/selection/text/kpToolText_Create.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpToolTextPrivate.h" @@ -41,87 +39,75 @@ #include "environments/tools/selection/kpToolSelectionEnvironment.h" #include "views/manager/kpViewManager.h" - // protected virtual [kpAbstractSelectionTool] -QString kpToolText::haventBegunDrawUserMessageCreate () const +QString kpToolText::haventBegunDrawUserMessageCreate() const { - return i18n ("Left drag to create text box."); + return i18n("Left drag to create text box."); } - // protected virtual [base kpAbstractSelectionTool] -void kpToolText::setSelectionBorderForBeginDrawCreate () +void kpToolText::setSelectionBorderForBeginDrawCreate() { - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { - kpAbstractSelectionTool::setSelectionBorderForBeginDrawCreate (); - viewManager ()->setTextCursorEnabled (false); + kpAbstractSelectionTool::setSelectionBorderForBeginDrawCreate(); + viewManager()->setTextCursorEnabled(false); } - viewManager ()->restoreQueueUpdates (); + viewManager()->restoreQueueUpdates(); } - // private -int kpToolText::calcClickCreateDimension (int mouseStart, int mouseEnd, - int preferredMin, int smallestMin, - int docSize) +int kpToolText::calcClickCreateDimension(int mouseStart, int mouseEnd, int preferredMin, + int smallestMin, int docSize) { - Q_ASSERT (preferredMin >= smallestMin); - Q_ASSERT (docSize > 0); + Q_ASSERT(preferredMin >= smallestMin); + Q_ASSERT(docSize > 0); // Get reasonable width/height for a text box. int ret = preferredMin; // X or Y increasing? - if (mouseEnd >= mouseStart) - { + if (mouseEnd >= mouseStart) { // Text box extends past document width/height? - if (mouseStart + ret - 1 >= docSize) - { + if (mouseStart + ret - 1 >= docSize) { // Cap width/height to not extend past but not below smallest // possible selection width/height - ret = qMax (smallestMin, docSize - mouseStart); + ret = qMax(smallestMin, docSize - mouseStart); } } // X or Y decreasing - else - { + else { // Text box extends past document start? // TODO: I doubt this code can be invoked for a click. // Maybe very tricky interplay with accidental drag detection? - if (mouseStart - ret + 1 < 0) - { + if (mouseStart - ret + 1 < 0) { // Cap width/height to not extend past but not below smallest // possible selection width/height. - ret = qMax (smallestMin, mouseStart + 1); + ret = qMax(smallestMin, mouseStart + 1); } } return ret; } // private -bool kpToolText::shouldCreate (bool dragAccepted, - const QPoint &accidentalDragAdjustedPoint, - const kpTextStyle &textStyle, - int *minimumWidthOut, int *minimumHeightOut, - bool *newDragAccepted) +bool kpToolText::shouldCreate(bool dragAccepted, const QPoint &accidentalDragAdjustedPoint, + const kpTextStyle &textStyle, int *minimumWidthOut, + int *minimumHeightOut, bool *newDragAccepted) { #if DEBUG_KP_TOOL_TEXT && 1 qCDebug(kpLogTools) << "CALL(dragAccepted=" << dragAccepted - << ",accidentalDragAdjustedPoint=" << accidentalDragAdjustedPoint - << ")"; + << ",accidentalDragAdjustedPoint=" << accidentalDragAdjustedPoint + << ")"; #endif *newDragAccepted = dragAccepted; // Is the drag so short that we're essentially just clicking? // Basically, we're trying to prevent unintentional creation of 1-pixel // selections. - if (!dragAccepted && accidentalDragAdjustedPoint == startPoint ()) - { + if (!dragAccepted && accidentalDragAdjustedPoint == startPoint()) { // We had an existing text box before the click? - if (hadSelectionBeforeDraw ()) - { + if (hadSelectionBeforeDraw()) { #if DEBUG_KP_TOOL_TEXT && 1 qCDebug(kpLogTools) << "\ttext box deselect - NOP - return"; #endif @@ -132,7 +118,6 @@ } // We are probably creating a new box. - // This drag is currently a click -- not a drag. // As a special case, allow user to create a text box, // of reasonable ("preferred minimum") size, using a single @@ -151,62 +136,56 @@ // afterwards) // TODO: I suspect this logic is simply too late // TODO: We setUserShapePoints() on return but didn't before. - if (mouseButton () == 1) { - return false/*do not create text box*/; + if (mouseButton() == 1) { + return false /*do not create text box*/; } - // Calculate suggested width. - *minimumWidthOut = calcClickCreateDimension ( - startPoint ().x (), - accidentalDragAdjustedPoint.x (), - kpTextSelection::PreferredMinimumWidthForTextStyle (textStyle), - kpTextSelection::MinimumWidthForTextStyle (textStyle), - document ()->width ()); + *minimumWidthOut = calcClickCreateDimension( + startPoint().x(), + accidentalDragAdjustedPoint.x(), + kpTextSelection::PreferredMinimumWidthForTextStyle(textStyle), + kpTextSelection::MinimumWidthForTextStyle(textStyle), + document()->width()); // Calculate suggested height. - *minimumHeightOut = calcClickCreateDimension ( - startPoint ().y (), - accidentalDragAdjustedPoint.y (), - kpTextSelection::PreferredMinimumHeightForTextStyle (textStyle), - kpTextSelection::MinimumHeightForTextStyle (textStyle), - document ()->height ()); - + *minimumHeightOut = calcClickCreateDimension( + startPoint().y(), + accidentalDragAdjustedPoint.y(), + kpTextSelection::PreferredMinimumHeightForTextStyle(textStyle), + kpTextSelection::MinimumHeightForTextStyle(textStyle), + document()->height()); // Do _not_ set "newDragAccepted" to true as we want // this text box to remain at the click-given size, in the absence // of any dragging. In other words, if draw() is called again // and therefore, we are called again, but the mouse has not // moved, we do want this branch to execute again, not // Branch [x]. - return true/*do create text box*/; + return true /*do create text box*/; } // Dragging to create a text box [x]. // // The size will be determined based on the size of the drag. - #if DEBUG_KP_TOOL_TEXT && 1 qCDebug(kpLogTools) << "\tdrag creating text box"; #endif - *minimumWidthOut = kpTextSelection::MinimumWidthForTextStyle (textStyle); - *minimumHeightOut = kpTextSelection::MinimumHeightForTextStyle (textStyle); + *minimumWidthOut = kpTextSelection::MinimumWidthForTextStyle(textStyle); + *minimumHeightOut = kpTextSelection::MinimumHeightForTextStyle(textStyle); *newDragAccepted = true; - return true/*do create text box*/; + return true /*do create text box*/; } // protected virtual [kpAbstractSelectionTool] -bool kpToolText::drawCreateMoreSelectionAndUpdateStatusBar ( - bool dragAccepted, - const QPoint &accidentalDragAdjustedPoint, - const QRect &normalizedRectIn) +bool kpToolText::drawCreateMoreSelectionAndUpdateStatusBar( + bool dragAccepted, const QPoint &accidentalDragAdjustedPoint, const QRect &normalizedRectIn) { // (will mutate this) QRect normalizedRect = normalizedRectIn; - const kpTextStyle textStyle = environ ()->textStyle (); - + const kpTextStyle textStyle = environ()->textStyle(); // // Calculate Text Box Rectangle. @@ -216,78 +195,66 @@ // (will set both variables) int minimumWidth = 0, minimumHeight = 0; - if (!shouldCreate (dragAccepted, accidentalDragAdjustedPoint, textStyle, - &minimumWidth, &minimumHeight, &newDragAccepted)) - { - setUserShapePoints (accidentalDragAdjustedPoint); + if (!shouldCreate(dragAccepted, accidentalDragAdjustedPoint, textStyle, + &minimumWidth, &minimumHeight, &newDragAccepted)) { + setUserShapePoints(accidentalDragAdjustedPoint); return newDragAccepted; } - // Make sure the dragged out rectangle is of the minimum width we just // calculated. - if (normalizedRect.width () < minimumWidth) - { - if (accidentalDragAdjustedPoint.x () >= startPoint ().x ()) { - normalizedRect.setWidth (minimumWidth); - } - else { - normalizedRect.setX (normalizedRect.right () - minimumWidth + 1); + if (normalizedRect.width() < minimumWidth) { + if (accidentalDragAdjustedPoint.x() >= startPoint().x()) { + normalizedRect.setWidth(minimumWidth); + } else { + normalizedRect.setX(normalizedRect.right() - minimumWidth + 1); } } // Make sure the dragged out rectangle is of the minimum height we just // calculated. - if (normalizedRect.height () < minimumHeight) - { - if (accidentalDragAdjustedPoint.y () >= startPoint ().y ()) { - normalizedRect.setHeight (minimumHeight); - } - else { - normalizedRect.setY (normalizedRect.bottom () - minimumHeight + 1); + if (normalizedRect.height() < minimumHeight) { + if (accidentalDragAdjustedPoint.y() >= startPoint().y()) { + normalizedRect.setHeight(minimumHeight); + } else { + normalizedRect.setY(normalizedRect.bottom() - minimumHeight + 1); } } #if DEBUG_KP_TOOL_TEXT && 1 qCDebug(kpLogTools) << "\t\tnormalizedRect=" << normalizedRect - << " kpTextSelection::preferredMinimumSize=" - << QSize (minimumWidth, minimumHeight); + << " kpTextSelection::preferredMinimumSize=" + << QSize(minimumWidth, minimumHeight); #endif - // // Construct and Deploy Text Box. // // Create empty text box. QList textLines; - kpTextSelection textSel (normalizedRect, textLines, textStyle); + kpTextSelection textSel(normalizedRect, textLines, textStyle); // Render. - viewManager ()->setTextCursorPosition (0, 0); - document ()->setSelection (textSel); - + viewManager()->setTextCursorPosition(0, 0); + document()->setSelection(textSel); // // Update Status Bar. // QPoint actualEndPoint = KP_INVALID_POINT; - if (startPoint () == normalizedRect.topLeft ()) { - actualEndPoint = normalizedRect.bottomRight (); - } - else if (startPoint () == normalizedRect.bottomRight ()) { - actualEndPoint = normalizedRect.topLeft (); - } - else if (startPoint () == normalizedRect.topRight ()) { - actualEndPoint = normalizedRect.bottomLeft (); - } - else if (startPoint () == normalizedRect.bottomLeft ()) { - actualEndPoint = normalizedRect.topRight (); + if (startPoint() == normalizedRect.topLeft()) { + actualEndPoint = normalizedRect.bottomRight(); + } else if (startPoint() == normalizedRect.bottomRight()) { + actualEndPoint = normalizedRect.topLeft(); + } else if (startPoint() == normalizedRect.topRight()) { + actualEndPoint = normalizedRect.bottomLeft(); + } else if (startPoint() == normalizedRect.bottomLeft()) { + actualEndPoint = normalizedRect.topRight(); } - setUserShapePoints (startPoint (), actualEndPoint); + setUserShapePoints(startPoint(), actualEndPoint); return newDragAccepted; } - diff --git a/tools/selection/text/kpToolText_CursorCalc.cpp b/tools/selection/text/kpToolText_CursorCalc.cpp --- a/tools/selection/text/kpToolText_CursorCalc.cpp +++ b/tools/selection/text/kpToolText_CursorCalc.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpLogCategories.h" #include "document/kpDocument.h" @@ -48,173 +46,154 @@ #include // protected static -bool kpToolText::CursorIsOnWordChar (const QList &textLines, - int cursorRow, int cursorCol) +bool kpToolText::CursorIsOnWordChar(const QList &textLines, int cursorRow, int cursorCol) { - return (cursorRow >= 0 && cursorRow < textLines.size () && - cursorCol >= 0 && cursorCol < textLines [cursorRow].length () && - !textLines [cursorRow][cursorCol].isSpace ()); + return cursorRow >= 0 && cursorRow < textLines.size() + && cursorCol >= 0 && cursorCol < textLines [cursorRow].length() + && !textLines [cursorRow][cursorCol].isSpace(); } - // protected static -bool kpToolText::CursorIsAtStart (const QList &, - int cursorRow, int cursorCol) +bool kpToolText::CursorIsAtStart(const QList &, int cursorRow, int cursorCol) { - return (cursorRow == 0 && cursorCol == 0); + return cursorRow == 0 && cursorCol == 0; } // protected static -bool kpToolText::CursorIsAtEnd (const QList &textLines, - int cursorRow, int cursorCol) +bool kpToolText::CursorIsAtEnd(const QList &textLines, int cursorRow, int cursorCol) { - if (textLines.isEmpty ()) { - return (cursorRow == 0 && cursorCol == 0); + if (textLines.isEmpty()) { + return cursorRow == 0 && cursorCol == 0; } - - return (cursorRow == textLines.size () - 1 && - cursorCol == textLines [cursorRow].length ()); -} + return cursorRow == textLines.size() - 1 + && cursorCol == textLines [cursorRow].length(); +} // protected static -void kpToolText::MoveCursorLeft (const QList &textLines, - int *cursorRow, int *cursorCol) +void kpToolText::MoveCursorLeft(const QList &textLines, int *cursorRow, int *cursorCol) { - if (textLines.isEmpty ()) { + if (textLines.isEmpty()) { return; } - + (*cursorCol)--; - if (*cursorCol < 0) - { + if (*cursorCol < 0) { (*cursorRow)--; - if (*cursorRow < 0) - { + if (*cursorRow < 0) { *cursorRow = 0; *cursorCol = 0; - } - else { - *cursorCol = textLines [*cursorRow].length (); + } else { + *cursorCol = textLines [*cursorRow].length(); } } } // protected static -void kpToolText::MoveCursorRight (const QList &textLines, - int *cursorRow, int *cursorCol) +void kpToolText::MoveCursorRight(const QList &textLines, int *cursorRow, int *cursorCol) { - if (textLines.isEmpty ()) { + if (textLines.isEmpty()) { return; } - + (*cursorCol)++; - if (*cursorCol > textLines [*cursorRow].length ()) - { + if (*cursorCol > textLines [*cursorRow].length()) { (*cursorRow)++; - if (*cursorRow > textLines.size () - 1) - { - *cursorRow = textLines.size () - 1; - *cursorCol = textLines [*cursorRow].length (); - } - else { + if (*cursorRow > textLines.size() - 1) { + *cursorRow = textLines.size() - 1; + *cursorCol = textLines [*cursorRow].length(); + } else { *cursorCol = 0; } } } - -#define IS_ON_SPACE_OR_EOL() !CursorIsOnWordChar (textLines, *cursorRow, *cursorCol) +#define IS_ON_SPACE_OR_EOL() !CursorIsOnWordChar(textLines, *cursorRow, *cursorCol) // protected static -int kpToolText::MoveCursorToWordStart (const QList &textLines, - int *cursorRow, int *cursorCol) +int kpToolText::MoveCursorToWordStart(const QList &textLines, int *cursorRow, + int *cursorCol) { - if (textLines.isEmpty ()) { + if (textLines.isEmpty()) { return 0; } int numMoves = 0; #define IS_ON_ANCHOR() \ - (CursorIsOnWordChar (textLines, *cursorRow, *cursorCol) && \ - (cursorCol == 0 || \ - !CursorIsOnWordChar (textLines, *cursorRow, *cursorCol - 1))) + (CursorIsOnWordChar(textLines, *cursorRow, *cursorCol) \ + && (cursorCol == 0 \ + || !CursorIsOnWordChar(textLines, *cursorRow, *cursorCol - 1))) #define MOVE_CURSOR_LEFT() \ - (MoveCursorLeft (textLines, cursorRow, cursorCol), ++numMoves) - + (MoveCursorLeft(textLines, cursorRow, cursorCol), ++numMoves) // (these comments will exclude the row=0,col=0 boundary case) - if (IS_ON_ANCHOR ()) { - MOVE_CURSOR_LEFT (); + if (IS_ON_ANCHOR()) { + MOVE_CURSOR_LEFT(); } // --- now we're not on an anchor point (start of word) --- // End up on a letter... - while (!(*cursorRow == 0 && *cursorCol == 0) && - (IS_ON_SPACE_OR_EOL ())) + while (!(*cursorRow == 0 && *cursorCol == 0) + && (IS_ON_SPACE_OR_EOL())) { - MOVE_CURSOR_LEFT (); + MOVE_CURSOR_LEFT(); } // --- now we're on a letter --- // Find anchor point - while (!(*cursorRow == 0 && *cursorCol == 0) && !IS_ON_ANCHOR ()) + while (!(*cursorRow == 0 && *cursorCol == 0) && !IS_ON_ANCHOR()) { - MOVE_CURSOR_LEFT (); + MOVE_CURSOR_LEFT(); } - #undef IS_ON_ANCHOR #undef MOVE_CURSOR_LEFT return numMoves; } // protected static -int kpToolText::MoveCursorToNextWordStart (const QList &textLines, - int *cursorRow, int *cursorCol) +int kpToolText::MoveCursorToNextWordStart(const QList &textLines, int *cursorRow, + int *cursorCol) { - if (textLines.isEmpty ()) { + if (textLines.isEmpty()) { return 0; } - + int numMoves = 0; -#define IS_AT_END() CursorIsAtEnd (textLines, *cursorRow, *cursorCol) +#define IS_AT_END() CursorIsAtEnd(textLines, *cursorRow, *cursorCol) #define MOVE_CURSOR_RIGHT() \ - (MoveCursorRight (textLines, cursorRow, cursorCol), ++numMoves) - + (MoveCursorRight(textLines, cursorRow, cursorCol), ++numMoves) // (these comments will exclude the last row,end col boundary case) // Find space - while (!IS_AT_END () && !IS_ON_SPACE_OR_EOL ()) + while (!IS_AT_END() && !IS_ON_SPACE_OR_EOL()) { - MOVE_CURSOR_RIGHT (); + MOVE_CURSOR_RIGHT(); } // --- now we're on a space --- // Find letter - while (!IS_AT_END () && IS_ON_SPACE_OR_EOL ()) + while (!IS_AT_END() && IS_ON_SPACE_OR_EOL()) { - MOVE_CURSOR_RIGHT (); + MOVE_CURSOR_RIGHT(); } // --- now we're on a letter --- - #undef IS_AT_END #undef MOVE_CURSOR_RIGHT return numMoves; } #undef IS_ON_SPACE_OR_EOL - diff --git a/tools/selection/text/kpToolText_InputMethodEvents.cpp b/tools/selection/text/kpToolText_InputMethodEvents.cpp --- a/tools/selection/text/kpToolText_InputMethodEvents.cpp +++ b/tools/selection/text/kpToolText_InputMethodEvents.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2005 Kazuki Ohta @@ -29,7 +28,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpToolTextPrivate.h" #include "commands/tools/selection/text/kpToolTextInsertCommand.h" @@ -45,52 +43,46 @@ //--------------------------------------------------------------------- -void kpToolText::inputMethodEvent (QInputMethodEvent *e) +void kpToolText::inputMethodEvent(QInputMethodEvent *e) { #if DEBUG_KP_TOOL_TEXT && 1 - qCDebug(kpLogTools) << "kpToolText::inputMethodEvent() preeditString='" << e->preeditString () - << "commitString = " << e->commitString () - << " replacementStart=" << e->replacementStart () - << " replacementLength=" << e->replacementLength (); + qCDebug(kpLogTools) << "kpToolText::inputMethodEvent() preeditString='" << e->preeditString() + << "commitString = " << e->commitString() + << " replacementStart=" << e->replacementStart() + << " replacementLength=" << e->replacementLength(); #endif - kpTextSelection *textSel = document ()->textSelection (); - if (hasBegunDraw() || !textSel) - { + kpTextSelection *textSel = document()->textSelection(); + if (hasBegunDraw() || !textSel) { e->ignore(); return; } - kpPreeditText previous = textSel->preeditText (); - kpPreeditText next (e); + kpPreeditText previous = textSel->preeditText(); + kpPreeditText next(e); - int textCursorRow = viewManager ()->textCursorRow (); - int textCursorCol = viewManager ()->textCursorCol (); - if (!next.isEmpty ()) - { - if (previous.position().x () < 0 && previous.position().y () < 0) - { - next.setPosition (QPoint(textCursorCol, textCursorRow)); - } - else - { - next.setPosition(previous.position ()); + int textCursorRow = viewManager()->textCursorRow(); + int textCursorCol = viewManager()->textCursorCol(); + if (!next.isEmpty()) { + if (previous.position().x() < 0 && previous.position().y() < 0) { + next.setPosition(QPoint(textCursorCol, textCursorRow)); + } else { + next.setPosition(previous.position()); } } - textSel->setPreeditText (next); - textCursorCol = textCursorCol - previous.cursorPosition () + next.cursorPosition (); - viewManager ()->setTextCursorPosition (textCursorRow, textCursorCol); + textSel->setPreeditText(next); + textCursorCol = textCursorCol - previous.cursorPosition() + next.cursorPosition(); + viewManager()->setTextCursorPosition(textCursorRow, textCursorCol); - QString commitString = e->commitString (); - if (!commitString.isEmpty ()) - { + QString commitString = e->commitString(); + if (!commitString.isEmpty()) { // commit string if (!d->insertCommand) { - addNewInsertCommand (&d->insertCommand); + addNewInsertCommand(&d->insertCommand); } - d->insertCommand->addText (commitString); + d->insertCommand->addText(commitString); } - e->accept (); + e->accept(); } //--------------------------------------------------------------------- diff --git a/tools/selection/text/kpToolText_KeyboardEvents.cpp b/tools/selection/text/kpToolText_KeyboardEvents.cpp --- a/tools/selection/text/kpToolText_KeyboardEvents.cpp +++ b/tools/selection/text/kpToolText_KeyboardEvents.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpToolTextPrivate.h" @@ -52,161 +50,142 @@ #include // protected virtual [base kpTool] -bool kpToolText::viewEvent (QEvent *e) +bool kpToolText::viewEvent(QEvent *e) { - const bool isShortcutOverrideEvent = - (e->type () == QEvent::ShortcutOverride); - const bool haveTextSelection = document ()->textSelection (); + const bool isShortcutOverrideEvent + = (e->type() == QEvent::ShortcutOverride); + const bool haveTextSelection = document()->textSelection(); #if DEBUG_KP_TOOL_TEXT && 0 - qCDebug(kpLogTools) << "kpToolText::viewEvent() type=" << e->type () - << " isShortcutOverrideEvent=" << isShortcutOverrideEvent - << " haveTextSel=" << haveTextSelection; + qCDebug(kpLogTools) << "kpToolText::viewEvent() type=" << e->type() + << " isShortcutOverrideEvent=" << isShortcutOverrideEvent + << " haveTextSel=" << haveTextSelection; #endif if (!isShortcutOverrideEvent || !haveTextSelection) { - return kpAbstractSelectionTool::viewEvent (e); + return kpAbstractSelectionTool::viewEvent(e); } - auto *ke = dynamic_cast (e); + auto *ke = dynamic_cast (e); #if DEBUG_KP_TOOL_TEXT - qCDebug(kpLogTools) << "kpToolText::viewEvent() key=" << ke->key () - << " modifiers=" << ke->modifiers () - << " QChar.isPrint()=" << QChar (ke->key ()).isPrint (); + qCDebug(kpLogTools) << "kpToolText::viewEvent() key=" << ke->key() + << " modifiers=" << ke->modifiers() + << " QChar.isPrint()=" << QChar(ke->key()).isPrint(); #endif // Can't be shortcut? - if (ke->key () == 0 && ke->key () == Qt::Key_unknown) - { + if (ke->key() == 0 && ke->key() == Qt::Key_unknown) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tcan't be shortcut - safe to not react"; #endif } // Normal letter (w/ or w/o shift, keypad button ok)? // TODO: don't like this check - else if ((ke->modifiers () & - (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) == 0 && - !( ke->text ().isEmpty ())) - { + else if ((ke->modifiers() + &(Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) == 0 + && !(ke->text().isEmpty())) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tis text - grab"; #endif - e->accept (); - } - else - { + e->accept(); + } else { // Strickly speaking, we should grab stuff like the arrow keys // and enter. In any case, should be done down in kpTool (as that // uses arrow keys too). } - return kpAbstractSelectionTool::event (e); + return kpAbstractSelectionTool::event(e); } - // protected virtual [base kpAbstractSelectionTool] -void kpToolText::keyPressEvent (QKeyEvent *e) +void kpToolText::keyPressEvent(QKeyEvent *e) { #if DEBUG_KP_TOOL_TEXT - qCDebug(kpLogTools) << "kpToolText::keyPressEvent(e->text='" << e->text () << "')"; + qCDebug(kpLogTools) << "kpToolText::keyPressEvent(e->text='" << e->text() << "')"; #endif + e->ignore(); - e->ignore (); - - - if (hasBegunDraw ()) - { + if (hasBegunDraw()) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\talready began draw with mouse - passing on event to kpTool"; #endif - kpAbstractSelectionTool::keyPressEvent (e); + kpAbstractSelectionTool::keyPressEvent(e); return; } + kpTextSelection *const textSel = document()->textSelection(); - kpTextSelection * const textSel = document ()->textSelection (); - - if (!textSel) - { + if (!textSel) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tno text sel - passing on event to kpTool"; #endif //if (hasBegunShape ()) // endShape (currentPoint (), normalizedRect ()); - kpAbstractSelectionTool::keyPressEvent (e); + kpAbstractSelectionTool::keyPressEvent(e); return; } - // (All handle.+()'s require this info) - const QList textLines = textSel->textLines (); - const int cursorRow = viewManager ()->textCursorRow (); - const int cursorCol = viewManager ()->textCursorCol (); - + const QList textLines = textSel->textLines(); + const int cursorRow = viewManager()->textCursorRow(); + const int cursorCol = viewManager()->textCursorCol(); // TODO: KTextEdit::keyPressEvent() uses KStandardShortcut instead of hardcoding; same fix for kpTool? - switch (e->key ()) - { + switch (e->key()) { case Qt::Key_Up: - handleUpKeyPress (e, textLines, cursorRow, cursorCol); + handleUpKeyPress(e, textLines, cursorRow, cursorCol); break; case Qt::Key_Down: - handleDownKeyPress (e, textLines, cursorRow, cursorCol); + handleDownKeyPress(e, textLines, cursorRow, cursorCol); break; case Qt::Key_Left: - handleLeftKeyPress (e, textLines, cursorRow, cursorCol); + handleLeftKeyPress(e, textLines, cursorRow, cursorCol); break; case Qt::Key_Right: - handleRightKeyPress (e, textLines, cursorRow, cursorCol); + handleRightKeyPress(e, textLines, cursorRow, cursorCol); break; - case Qt::Key_Home: - handleHomeKeyPress (e, textLines, cursorRow, cursorCol); + handleHomeKeyPress(e, textLines, cursorRow, cursorCol); break; case Qt::Key_End: - handleEndKeyPress (e, textLines, cursorRow, cursorCol); + handleEndKeyPress(e, textLines, cursorRow, cursorCol); break; - case Qt::Key_Backspace: - handleBackspaceKeyPress (e, textLines, cursorRow, cursorCol); + handleBackspaceKeyPress(e, textLines, cursorRow, cursorCol); break; case Qt::Key_Delete: - handleDeleteKeyPress (e, textLines, cursorRow, cursorCol); + handleDeleteKeyPress(e, textLines, cursorRow, cursorCol); break; - case Qt::Key_Enter: case Qt::Key_Return: - handleEnterKeyPress (e, textLines, cursorRow, cursorCol); + handleEnterKeyPress(e, textLines, cursorRow, cursorCol); break; - default: - handleTextTyped (e, textLines, cursorRow, cursorCol); + handleTextTyped(e, textLines, cursorRow, cursorCol); break; } - - if (!e->isAccepted ()) - { + if (!e->isAccepted()) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tkey processing did not accept (text was '" - << e->text () - << "') - passing on event to kpAbstractSelectionTool"; + << e->text() + << "') - passing on event to kpAbstractSelectionTool"; #endif //if (hasBegunShape ()) // endShape (currentPoint (), normalizedRect ()); - kpAbstractSelectionTool::keyPressEvent (e); + kpAbstractSelectionTool::keyPressEvent(e); return; } } diff --git a/tools/selection/text/kpToolText_KeyboardEvents_HandleArrowKeys.cpp b/tools/selection/text/kpToolText_KeyboardEvents_HandleArrowKeys.cpp --- a/tools/selection/text/kpToolText_KeyboardEvents_HandleArrowKeys.cpp +++ b/tools/selection/text/kpToolText_KeyboardEvents_HandleArrowKeys.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpToolTextPrivate.h" @@ -50,172 +48,159 @@ #include "views/manager/kpViewManager.h" // protected -void kpToolText::handleUpKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol) +void kpToolText::handleUpKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tup pressed"; #endif - if (hasBegunShape ()) { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - if (!textLines.isEmpty () && cursorRow > 0) - { + if (!textLines.isEmpty() && cursorRow > 0) { cursorRow--; - cursorCol = qMin (cursorCol, textLines [cursorRow].length ()); - viewManager ()->setTextCursorPosition (cursorRow, cursorCol); + cursorCol = qMin(cursorCol, textLines [cursorRow].length()); + viewManager()->setTextCursorPosition(cursorRow, cursorCol); } - e->accept (); + e->accept(); } // protected -void kpToolText::handleDownKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol) +void kpToolText::handleDownKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tdown pressed"; #endif - if (hasBegunShape ()) { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - if (!textLines.isEmpty () && cursorRow < textLines.size () - 1) - { + if (!textLines.isEmpty() && cursorRow < textLines.size() - 1) { cursorRow++; - cursorCol = qMin (cursorCol, textLines [cursorRow].length ()); - viewManager ()->setTextCursorPosition (cursorRow, cursorCol); + cursorCol = qMin(cursorCol, textLines [cursorRow].length()); + viewManager()->setTextCursorPosition(cursorRow, cursorCol); } - e->accept (); + e->accept(); } // protected -void kpToolText::handleLeftKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol) +void kpToolText::handleLeftKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tleft pressed"; #endif - if (hasBegunShape ()) { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - if (!textLines.isEmpty ()) - { - if ((e->modifiers () & Qt::ControlModifier) == 0) - { + if (!textLines.isEmpty()) { + if ((e->modifiers() & Qt::ControlModifier) == 0) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tmove single char"; #endif - - MoveCursorLeft (textLines, &cursorRow, &cursorCol); - viewManager ()->setTextCursorPosition (cursorRow, cursorCol); - } - else - { + + MoveCursorLeft(textLines, &cursorRow, &cursorCol); + viewManager()->setTextCursorPosition(cursorRow, cursorCol); + } else { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tmove to start of word"; #endif - - MoveCursorToWordStart (textLines, &cursorRow, &cursorCol); - viewManager ()->setTextCursorPosition (cursorRow, cursorCol); + + MoveCursorToWordStart(textLines, &cursorRow, &cursorCol); + viewManager()->setTextCursorPosition(cursorRow, cursorCol); } } - e->accept (); + e->accept(); } // protected -void kpToolText::handleRightKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol) +void kpToolText::handleRightKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tright pressed"; #endif - if (hasBegunShape ()) { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - if (!textLines.isEmpty ()) - { - if ((e->modifiers () & Qt::ControlModifier) == 0) - { + if (!textLines.isEmpty()) { + if ((e->modifiers() & Qt::ControlModifier) == 0) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tmove single char"; #endif - - MoveCursorRight (textLines, &cursorRow, &cursorCol); - viewManager ()->setTextCursorPosition (cursorRow, cursorCol); - } - else - { + + MoveCursorRight(textLines, &cursorRow, &cursorCol); + viewManager()->setTextCursorPosition(cursorRow, cursorCol); + } else { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tmove to start of next word"; #endif - - MoveCursorToNextWordStart (textLines, &cursorRow, &cursorCol); - viewManager ()->setTextCursorPosition (cursorRow, cursorCol); + + MoveCursorToNextWordStart(textLines, &cursorRow, &cursorCol); + viewManager()->setTextCursorPosition(cursorRow, cursorCol); } } - e->accept (); + e->accept(); } - // protected -void kpToolText::handleHomeKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol) +void kpToolText::handleHomeKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\thome pressed"; #endif - if (hasBegunShape ()) { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - if (!textLines.isEmpty ()) - { - if (e->modifiers () & Qt::ControlModifier) { + if (!textLines.isEmpty()) { + if (e->modifiers() & Qt::ControlModifier) { cursorRow = 0; } - + cursorCol = 0; - - viewManager ()->setTextCursorPosition (cursorRow, cursorCol); + + viewManager()->setTextCursorPosition(cursorRow, cursorCol); } - e->accept (); + e->accept(); } // protected -void kpToolText::handleEndKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol) +void kpToolText::handleEndKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tend pressed"; #endif - if (hasBegunShape ()) { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - if (!textLines.isEmpty ()) - { - if (e->modifiers () & Qt::ControlModifier) { - cursorRow = textLines.size () - 1; + if (!textLines.isEmpty()) { + if (e->modifiers() & Qt::ControlModifier) { + cursorRow = textLines.size() - 1; } - - cursorCol = textLines [cursorRow].length (); - - viewManager ()->setTextCursorPosition (cursorRow, cursorCol); + + cursorCol = textLines [cursorRow].length(); + + viewManager()->setTextCursorPosition(cursorRow, cursorCol); } - e->accept (); + e->accept(); } diff --git a/tools/selection/text/kpToolText_KeyboardEvents_HandleTypingKeys.cpp b/tools/selection/text/kpToolText_KeyboardEvents_HandleTypingKeys.cpp --- a/tools/selection/text/kpToolText_KeyboardEvents_HandleTypingKeys.cpp +++ b/tools/selection/text/kpToolText_KeyboardEvents_HandleTypingKeys.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpToolTextPrivate.h" #include "kpLogCategories.h" @@ -50,153 +48,144 @@ //--------------------------------------------------------------------- // protected -void kpToolText::handleBackspaceKeyPress (QKeyEvent *e, - const QList &textLines, int cursorRow, int cursorCol) +void kpToolText::handleBackspaceKeyPress(QKeyEvent *e, const QList &textLines, + int cursorRow, int cursorCol) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tbackspace pressed"; #endif - if (!textLines.isEmpty ()) - { - if ((e->modifiers () & Qt::ControlModifier) == 0) - { + if (!textLines.isEmpty()) { + if ((e->modifiers() & Qt::ControlModifier) == 0) { if (!d->backspaceCommand) { - addNewBackspaceCommand (&d->backspaceCommand); + addNewBackspaceCommand(&d->backspaceCommand); } - - d->backspaceCommand->addBackspace (); - } - else - { + + d->backspaceCommand->addBackspace(); + } else { if (!d->backspaceWordCommand) { - addNewBackspaceCommand (&d->backspaceWordCommand); + addNewBackspaceCommand(&d->backspaceWordCommand); } - - const int numMoves = MoveCursorToWordStart (textLines, - &cursorRow, &cursorCol); - - viewManager ()->setQueueUpdates (); + + const int numMoves = MoveCursorToWordStart(textLines, + &cursorRow, &cursorCol); + + viewManager()->setQueueUpdates(); { for (int i = 0; i < numMoves; i++) { - d->backspaceWordCommand->addBackspace (); + d->backspaceWordCommand->addBackspace(); } } - viewManager ()->restoreQueueUpdates (); - - Q_ASSERT (cursorRow == viewManager ()->textCursorRow ()); - Q_ASSERT (cursorCol == viewManager ()->textCursorCol ()); + viewManager()->restoreQueueUpdates(); + + Q_ASSERT(cursorRow == viewManager()->textCursorRow()); + Q_ASSERT(cursorCol == viewManager()->textCursorCol()); } } - e->accept (); + e->accept(); } //--------------------------------------------------------------------- // protected -void kpToolText::handleDeleteKeyPress (QKeyEvent *e, - const QList & textLines, int cursorRow, int cursorCol) +void kpToolText::handleDeleteKeyPress(QKeyEvent *e, const QList &textLines, int cursorRow, + int cursorCol) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tdelete pressed"; #endif - if (!textLines.isEmpty ()) - { - if ((e->modifiers () & Qt::ControlModifier) == 0) - { + if (!textLines.isEmpty()) { + if ((e->modifiers() & Qt::ControlModifier) == 0) { if (!d->deleteCommand) { - addNewDeleteCommand (&d->deleteCommand); + addNewDeleteCommand(&d->deleteCommand); } - - d->deleteCommand->addDelete (); - } - else - { + + d->deleteCommand->addDelete(); + } else { if (!d->deleteWordCommand) { - addNewDeleteCommand (&d->deleteWordCommand); + addNewDeleteCommand(&d->deleteWordCommand); } - + // We don't want to know the cursor pos of the next word start // as delete should keep cursor in same pos. int cursorRowThrowAway = cursorRow, cursorColThrowAway = cursorCol; - const int numMoves = MoveCursorToNextWordStart (textLines, - &cursorRowThrowAway, &cursorColThrowAway); - - viewManager ()->setQueueUpdates (); + const int numMoves = MoveCursorToNextWordStart(textLines, + &cursorRowThrowAway, + &cursorColThrowAway); + + viewManager()->setQueueUpdates(); { for (int i = 0; i < numMoves; i++) { - d->deleteWordCommand->addDelete (); + d->deleteWordCommand->addDelete(); } } - viewManager ()->restoreQueueUpdates (); - + viewManager()->restoreQueueUpdates(); + // Assert unchanged as delete should keep cursor in same pos. - Q_ASSERT (cursorRow == viewManager ()->textCursorRow ()); - Q_ASSERT (cursorCol == viewManager ()->textCursorCol ()); + Q_ASSERT(cursorRow == viewManager()->textCursorRow()); + Q_ASSERT(cursorCol == viewManager()->textCursorCol()); } } - e->accept (); + e->accept(); } //--------------------------------------------------------------------- // protected -void kpToolText::handleEnterKeyPress (QKeyEvent *e, - const QList & /*textLines*/, int /*cursorRow*/, int /*cursorCol*/) +void kpToolText::handleEnterKeyPress(QKeyEvent *e, const QList & /*textLines*/, + int /*cursorRow*/, int /*cursorCol*/) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tenter pressed"; #endif // It's OK for to be empty. - + if (!d->enterCommand) { - addNewEnterCommand (&d->enterCommand); + addNewEnterCommand(&d->enterCommand); } - d->enterCommand->addEnter (); + d->enterCommand->addEnter(); - e->accept (); + e->accept(); } //--------------------------------------------------------------------- // protected -void kpToolText::handleTextTyped (QKeyEvent *e, - const QList & /*textLines*/, int /*cursorRow*/, int /*cursorCol*/) +void kpToolText::handleTextTyped(QKeyEvent *e, const QList & /*textLines*/, + int /*cursorRow*/, int /*cursorCol*/) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\ttext=" << e->text(); #endif QString usableText; - for (int i = 0; i < e->text ().length (); i++) - { - if (e->text ().at (i).isPrint ()) { - usableText += e->text ().at (i); + for (int i = 0; i < e->text().length(); i++) { + if (e->text().at(i).isPrint()) { + usableText += e->text().at(i); } } #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tusableText=" << usableText; #endif - if (usableText.isEmpty ()) - { + if (usableText.isEmpty()) { // Don't end the current shape nor accept the event -- the event // wasn't for us. return; } // --- It's OK for to be empty. --- if (!d->insertCommand) { - addNewInsertCommand (&d->insertCommand); + addNewInsertCommand(&d->insertCommand); } - d->insertCommand->addText (usableText); + d->insertCommand->addText(usableText); - e->accept (); + e->accept(); } diff --git a/tools/selection/text/kpToolText_Move.cpp b/tools/selection/text/kpToolText_Move.cpp --- a/tools/selection/text/kpToolText_Move.cpp +++ b/tools/selection/text/kpToolText_Move.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,37 +26,32 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpToolTextPrivate.h" #include #include "views/manager/kpViewManager.h" - // protected virtual [kpAbstractSelectionTool] -QString kpToolText::haventBegunDrawUserMessageMove () const +QString kpToolText::haventBegunDrawUserMessageMove() const { - return i18n ("Left drag to move text box."); + return i18n("Left drag to move text box."); } - // protected virtual [base kpAbstractSelectionTool] -void kpToolText::setSelectionBorderForBeginDrawMove () +void kpToolText::setSelectionBorderForBeginDrawMove() { - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { - kpAbstractSelectionTool::setSelectionBorderForBeginDrawMove (); - viewManager ()->setTextCursorEnabled (false); + kpAbstractSelectionTool::setSelectionBorderForBeginDrawMove(); + viewManager()->setTextCursorEnabled(false); } - viewManager ()->restoreQueueUpdates (); + viewManager()->restoreQueueUpdates(); } - // protected virtual [kpAbstractSelectionTool] -QString kpToolText::nonSmearMoveCommandName () const +QString kpToolText::nonSmearMoveCommandName() const { - return i18n ("Text: Move Box"); + return i18n("Text: Move Box"); } - diff --git a/tools/selection/text/kpToolText_ResizeScale.cpp b/tools/selection/text/kpToolText_ResizeScale.cpp --- a/tools/selection/text/kpToolText_ResizeScale.cpp +++ b/tools/selection/text/kpToolText_ResizeScale.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,29 +26,26 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpToolTextPrivate.h" #include #include "views/manager/kpViewManager.h" - // protected virtual [kpAbstractSelectionTool] -QString kpToolText::haventBegunDrawUserMessageResizeScale () const +QString kpToolText::haventBegunDrawUserMessageResizeScale() const { - return i18n ("Left drag to resize text box."); + return i18n("Left drag to resize text box."); } - // protected virtual [base kpAbstractSelectionTool] -void kpToolText::setSelectionBorderForBeginDrawResizeScale () +void kpToolText::setSelectionBorderForBeginDrawResizeScale() { - viewManager ()->setQueueUpdates (); + viewManager()->setQueueUpdates(); { - kpAbstractSelectionTool::setSelectionBorderForBeginDrawResizeScale (); - viewManager ()->setTextCursorEnabled (false); + kpAbstractSelectionTool::setSelectionBorderForBeginDrawResizeScale(); + viewManager()->setTextCursorEnabled(false); } - viewManager ()->restoreQueueUpdates (); + viewManager()->restoreQueueUpdates(); } diff --git a/tools/selection/text/kpToolText_SelectText.cpp b/tools/selection/text/kpToolText_SelectText.cpp --- a/tools/selection/text/kpToolText_SelectText.cpp +++ b/tools/selection/text/kpToolText_SelectText.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpToolTextPrivate.h" @@ -38,81 +36,71 @@ #include "views/kpView.h" #include "views/manager/kpViewManager.h" - // private -bool kpToolText::onSelectionToSelectText () const +bool kpToolText::onSelectionToSelectText() const { - kpView *v = viewManager ()->viewUnderCursor (); + kpView *v = viewManager()->viewUnderCursor(); if (!v) { return false; } - return v->mouseOnSelectionToSelectText (currentViewPoint ()); + return v->mouseOnSelectionToSelectText(currentViewPoint()); } - // private -QString kpToolText::haventBegunDrawUserMessageSelectText () const +QString kpToolText::haventBegunDrawUserMessageSelectText() const { - return i18n ("Left click to change cursor position."); + return i18n("Left click to change cursor position."); } // private -void kpToolText::setCursorSelectText () +void kpToolText::setCursorSelectText() { - viewManager ()->setCursor (Qt::IBeamCursor); + viewManager()->setCursor(Qt::IBeamCursor); } - // private -void kpToolText::beginDrawSelectText () +void kpToolText::beginDrawSelectText() { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\t\tis select cursor pos"; #endif - kpTextSelection *textSel = document ()->textSelection (); - Q_ASSERT (textSel); + kpTextSelection *textSel = document()->textSelection(); + Q_ASSERT(textSel); int newRow, newCol; - if (textSel->hasContent ()) - { - newRow = textSel->closestTextRowForPoint (currentPoint ()); - newCol = textSel->closestTextColForPoint (currentPoint ()); - } - else - { + if (textSel->hasContent()) { + newRow = textSel->closestTextRowForPoint(currentPoint()); + newCol = textSel->closestTextColForPoint(currentPoint()); + } else { newRow = newCol = 0; } #if DEBUG_KP_TOOL_TEXT - qCDebug(kpLogTools) << "\t\t\told: row=" << viewManager ()->textCursorRow () - << "col=" << viewManager ()->textCursorCol (); + qCDebug(kpLogTools) << "\t\t\told: row=" << viewManager()->textCursorRow() + << "col=" << viewManager()->textCursorCol(); qCDebug(kpLogTools) << "\t\t\tnew: row=" << newRow << "col=" << newCol; #endif - viewManager ()->setTextCursorPosition (newRow, newCol); + viewManager()->setTextCursorPosition(newRow, newCol); } - // protected virtual -QVariant kpToolText::selectTextOperation (Operation op, - const QVariant &data1, const QVariant &data2) +QVariant kpToolText::selectTextOperation(Operation op, const QVariant &data1, const QVariant &data2) { - (void) data1; - (void) data2; + (void)data1; + (void)data2; - - switch (op) - { + switch (op) { case HaventBegunDrawUserMessage: - return haventBegunDrawUserMessageSelectText (); + return haventBegunDrawUserMessageSelectText(); case SetCursor: - setCursorSelectText (); + setCursorSelectText(); break; case BeginDraw: - beginDrawSelectText (); + beginDrawSelectText(); break; case Draw: @@ -128,10 +116,9 @@ break; default: - Q_ASSERT (!"Unhandled operation"); + Q_ASSERT(!"Unhandled operation"); break; } - return {}; } diff --git a/tools/selection/text/kpToolText_TextStyle.cpp b/tools/selection/text/kpToolText_TextStyle.cpp --- a/tools/selection/text/kpToolText_TextStyle.cpp +++ b/tools/selection/text/kpToolText_TextStyle.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_TOOL_TEXT 0 - #include "tools/selection/text/kpToolText.h" #include "kpToolTextPrivate.h" #include "kpLogCategories.h" @@ -49,19 +47,17 @@ #include // protected -bool kpToolText::shouldChangeTextStyle () const +bool kpToolText::shouldChangeTextStyle() const { - if (environ ()->settingTextStyle ()) - { + if (environ()->settingTextStyle()) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\trecursion - abort setting text style: " - << environ ()->settingTextStyle (); + << environ()->settingTextStyle(); #endif return false; } - if (!document ()->textSelection ()) - { + if (!document()->textSelection()) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "\tno text selection - abort setting text style"; #endif @@ -72,263 +68,258 @@ } // protected -void kpToolText::changeTextStyle (const QString &name, - const kpTextStyle &newTextStyle, - const kpTextStyle &oldTextStyle) +void kpToolText::changeTextStyle(const QString &name, const kpTextStyle &newTextStyle, + const kpTextStyle &oldTextStyle) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::changeTextStyle(" << name << ")"; #endif - if (hasBegunShape ()) { - endShape (currentPoint (), normalizedRect ()); + if (hasBegunShape()) { + endShape(currentPoint(), normalizedRect()); } - commandHistory ()->addCommand ( - new kpToolTextChangeStyleCommand ( + commandHistory()->addCommand( + new kpToolTextChangeStyleCommand( name, newTextStyle, oldTextStyle, - environ ()->commandEnvironment ())); + environ()->commandEnvironment())); } - // protected slot virtual [base kpAbstractSelectionTool] -void kpToolText::slotIsOpaqueChanged (bool isOpaque) +void kpToolText::slotIsOpaqueChanged(bool isOpaque) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::slotIsOpaqueChanged()"; #endif - if (!shouldChangeTextStyle ()) { + if (!shouldChangeTextStyle()) { return; } - kpTextStyle newTextStyle = environ ()->textStyle (); + kpTextStyle newTextStyle = environ()->textStyle(); kpTextStyle oldTextStyle = newTextStyle; - oldTextStyle.setBackgroundOpaque (!isOpaque); + oldTextStyle.setBackgroundOpaque(!isOpaque); - changeTextStyle (newTextStyle.isBackgroundOpaque () ? - i18n ("Text: Opaque Background") : - i18n ("Text: Transparent Background"), - newTextStyle, - oldTextStyle); + changeTextStyle(newTextStyle.isBackgroundOpaque() + ? i18n("Text: Opaque Background") + : i18n("Text: Transparent Background"), + newTextStyle, + oldTextStyle); } // protected slot virtual [base kpTool] -void kpToolText::slotColorsSwapped (const kpColor &newForegroundColor, - const kpColor &newBackgroundColor) +void kpToolText::slotColorsSwapped(const kpColor &newForegroundColor, + const kpColor &newBackgroundColor) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::slotColorsSwapped()"; #endif - if (!shouldChangeTextStyle ()) { + if (!shouldChangeTextStyle()) { return; } - kpTextStyle newTextStyle = environ ()->textStyle (); + kpTextStyle newTextStyle = environ()->textStyle(); kpTextStyle oldTextStyle = newTextStyle; - oldTextStyle.setForegroundColor (newBackgroundColor); - oldTextStyle.setBackgroundColor (newForegroundColor); + oldTextStyle.setForegroundColor(newBackgroundColor); + oldTextStyle.setBackgroundColor(newForegroundColor); - changeTextStyle (i18n ("Text: Swap Colors"), - newTextStyle, - oldTextStyle); + changeTextStyle(i18n("Text: Swap Colors"), + newTextStyle, + oldTextStyle); } // protected slot virtual [base kpTool] -void kpToolText::slotForegroundColorChanged (const kpColor & /*color*/) +void kpToolText::slotForegroundColorChanged(const kpColor & /*color*/) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::slotForegroundColorChanged()"; #endif - if (!shouldChangeTextStyle ()) { + if (!shouldChangeTextStyle()) { return; } - kpTextStyle newTextStyle = environ ()->textStyle (); + kpTextStyle newTextStyle = environ()->textStyle(); kpTextStyle oldTextStyle = newTextStyle; - oldTextStyle.setForegroundColor (oldForegroundColor ()); + oldTextStyle.setForegroundColor(oldForegroundColor()); - changeTextStyle (i18n ("Text: Foreground Color"), - newTextStyle, - oldTextStyle); + changeTextStyle(i18n("Text: Foreground Color"), + newTextStyle, + oldTextStyle); } // protected slot virtual [base kpAbstractSelectionTool] -void kpToolText::slotBackgroundColorChanged (const kpColor & /*color*/) +void kpToolText::slotBackgroundColorChanged(const kpColor & /*color*/) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::slotBackgroundColorChanged()"; #endif - if (!shouldChangeTextStyle ()) { + if (!shouldChangeTextStyle()) { return; } - kpTextStyle newTextStyle = environ ()->textStyle (); + kpTextStyle newTextStyle = environ()->textStyle(); kpTextStyle oldTextStyle = newTextStyle; - oldTextStyle.setBackgroundColor (oldBackgroundColor ()); + oldTextStyle.setBackgroundColor(oldBackgroundColor()); - changeTextStyle (i18n ("Text: Background Color"), - newTextStyle, - oldTextStyle); + changeTextStyle(i18n("Text: Background Color"), + newTextStyle, + oldTextStyle); } // protected slot virtual [base kpAbstractSelectionTool] -void kpToolText::slotColorSimilarityChanged (double, int) +void kpToolText::slotColorSimilarityChanged(double, int) { // --- don't pass on event to kpAbstractSelectionTool which would have set the // SelectionTransparency - not relevant to the Text Tool --- } - // public slot -void kpToolText::slotFontFamilyChanged (const QString &fontFamily, - const QString &oldFontFamily) +void kpToolText::slotFontFamilyChanged(const QString &fontFamily, const QString &oldFontFamily) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::slotFontFamilyChanged() new=" - << fontFamily - << " old=" - << oldFontFamily; + << fontFamily + << " old=" + << oldFontFamily; #else - (void) fontFamily; + (void)fontFamily; #endif - if (!shouldChangeTextStyle ()) { + if (!shouldChangeTextStyle()) { return; } - kpTextStyle newTextStyle = environ ()->textStyle (); + kpTextStyle newTextStyle = environ()->textStyle(); // Figure out old text style. kpTextStyle oldTextStyle = newTextStyle; - oldTextStyle.setFontFamily (oldFontFamily); + oldTextStyle.setFontFamily(oldFontFamily); - changeTextStyle (i18n ("Text: Font"), - newTextStyle, - oldTextStyle); + changeTextStyle(i18n("Text: Font"), + newTextStyle, + oldTextStyle); } // public slot -void kpToolText::slotFontSizeChanged (int fontSize, int oldFontSize) +void kpToolText::slotFontSizeChanged(int fontSize, int oldFontSize) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::slotFontSizeChanged() new=" - << fontSize - << " old=" - << oldFontSize; + << fontSize + << " old=" + << oldFontSize; #else - (void) fontSize; + (void)fontSize; #endif - if (!shouldChangeTextStyle ()) { + if (!shouldChangeTextStyle()) { return; } - kpTextStyle newTextStyle = environ ()->textStyle (); + kpTextStyle newTextStyle = environ()->textStyle(); // Figure out old text style. kpTextStyle oldTextStyle = newTextStyle; - oldTextStyle.setFontSize (oldFontSize); + oldTextStyle.setFontSize(oldFontSize); - changeTextStyle (i18n ("Text: Font Size"), - newTextStyle, - oldTextStyle); + changeTextStyle(i18n("Text: Font Size"), + newTextStyle, + oldTextStyle); } - // public slot -void kpToolText::slotBoldChanged (bool isBold) +void kpToolText::slotBoldChanged(bool isBold) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::slotBoldChanged(" << isBold << ")"; #endif - if (!shouldChangeTextStyle ()) { + if (!shouldChangeTextStyle()) { return; } - kpTextStyle newTextStyle = environ ()->textStyle (); + kpTextStyle newTextStyle = environ()->textStyle(); // Figure out old text style. kpTextStyle oldTextStyle = newTextStyle; - oldTextStyle.setBold (!isBold); + oldTextStyle.setBold(!isBold); - changeTextStyle (i18n ("Text: Bold"), - newTextStyle, - oldTextStyle); + changeTextStyle(i18n("Text: Bold"), + newTextStyle, + oldTextStyle); } // public slot -void kpToolText::slotItalicChanged (bool isItalic) +void kpToolText::slotItalicChanged(bool isItalic) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::slotItalicChanged(" << isItalic << ")"; #endif - if (!shouldChangeTextStyle ()) { + if (!shouldChangeTextStyle()) { return; } - kpTextStyle newTextStyle = environ ()->textStyle (); + kpTextStyle newTextStyle = environ()->textStyle(); // Figure out old text style. kpTextStyle oldTextStyle = newTextStyle; - oldTextStyle.setItalic (!isItalic); + oldTextStyle.setItalic(!isItalic); - changeTextStyle (i18n ("Text: Italic"), - newTextStyle, - oldTextStyle); + changeTextStyle(i18n("Text: Italic"), + newTextStyle, + oldTextStyle); } // public slot -void kpToolText::slotUnderlineChanged (bool isUnderline) +void kpToolText::slotUnderlineChanged(bool isUnderline) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::slotUnderlineChanged(" << isUnderline << ")"; #endif - if (!shouldChangeTextStyle ()) { + if (!shouldChangeTextStyle()) { return; } - kpTextStyle newTextStyle = environ ()->textStyle (); + kpTextStyle newTextStyle = environ()->textStyle(); // Figure out old text style. kpTextStyle oldTextStyle = newTextStyle; - oldTextStyle.setUnderline (!isUnderline); + oldTextStyle.setUnderline(!isUnderline); - changeTextStyle (i18n ("Text: Underline"), - newTextStyle, - oldTextStyle); + changeTextStyle(i18n("Text: Underline"), + newTextStyle, + oldTextStyle); } // public slot -void kpToolText::slotStrikeThruChanged (bool isStrikeThru) +void kpToolText::slotStrikeThruChanged(bool isStrikeThru) { #if DEBUG_KP_TOOL_TEXT qCDebug(kpLogTools) << "kpToolText::slotStrikeThruChanged(" << isStrikeThru << ")"; #endif - if (!shouldChangeTextStyle ()) { + if (!shouldChangeTextStyle()) { return; } - kpTextStyle newTextStyle = environ ()->textStyle (); + kpTextStyle newTextStyle = environ()->textStyle(); // Figure out old text style. kpTextStyle oldTextStyle = newTextStyle; - oldTextStyle.setStrikeThru (!isStrikeThru); + oldTextStyle.setStrikeThru(!isStrikeThru); - changeTextStyle (i18n ("Text: Strike Through"), - newTextStyle, - oldTextStyle); + changeTextStyle(i18n("Text: Strike Through"), + newTextStyle, + oldTextStyle); } diff --git a/views/kpThumbnailView.h b/views/kpThumbnailView.h --- a/views/kpThumbnailView.h +++ b/views/kpThumbnailView.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,47 +24,39 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_THUMBNAIL_VIEW_H #define KP_THUMBNAIL_VIEW_H - #include "views/kpView.h" - /** * @short Abstract base class for all thumbnail views. * * @author Clarence Dang */ class kpThumbnailView : public kpView { -Q_OBJECT + Q_OBJECT public: /** * Constructs a thumbnail view. * * You must call adjustEnvironment() at the end of your constructor. */ - kpThumbnailView (kpDocument *document, - kpToolToolBar *toolToolBar, - kpViewManager *viewManager, - kpView *buddyView, - kpViewScrollableContainer *scrollableContainer, + kpThumbnailView (kpDocument *document, kpToolToolBar *toolToolBar, kpViewManager *viewManager, + kpView *buddyView, kpViewScrollableContainer *scrollableContainer, QWidget *parent); /** * Destructs this thumbnail view. */ ~kpThumbnailView () override; - /** * @returns the caption to display in an enclosing thumbnail window. */ - virtual QString caption () const = 0; - + virtual QString caption() const = 0; protected: /** @@ -75,16 +66,14 @@ * that all pixels are initialised with either document pixels or the * standard widget background. */ - void setMaskToCoverDocument (); - + void setMaskToCoverDocument(); /** * Calls adjustToEnvironment() in response to a resize event. * * Extends @ref kpView. */ - void resizeEvent (QResizeEvent *e) override; + void resizeEvent(QResizeEvent *e) override; }; - #endif // KP_THUMBNAIL_VIEW_H diff --git a/views/kpThumbnailView.cpp b/views/kpThumbnailView.cpp --- a/views/kpThumbnailView.cpp +++ b/views/kpThumbnailView.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,72 +24,61 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_THUMBNAIL_VIEW 0 - #include "views/kpThumbnailView.h" #include "kpLogCategories.h" +kpThumbnailView::kpThumbnailView (kpDocument *document, kpToolToolBar *toolToolBar, + kpViewManager *viewManager, kpView *buddyView, + kpViewScrollableContainer *scrollableContainer, QWidget *parent) -kpThumbnailView::kpThumbnailView (kpDocument *document, - kpToolToolBar *toolToolBar, - kpViewManager *viewManager, - kpView *buddyView, - kpViewScrollableContainer *scrollableContainer, - QWidget *parent) - - : kpView (document, toolToolBar, viewManager, - buddyView, - scrollableContainer, - parent) + : kpView(document, toolToolBar, viewManager, + buddyView, + scrollableContainer, + parent) { } kpThumbnailView::~kpThumbnailView () = default; - // protected -void kpThumbnailView::setMaskToCoverDocument () +void kpThumbnailView::setMaskToCoverDocument() { #if DEBUG_KP_THUMBNAIL_VIEW qCDebug(kpLogViews) << "kpThumbnailView::setMaskToCoverDocument()" - << " origin=" << origin () - << " zoomedDoc: width=" << zoomedDocWidth () - << " height=" << zoomedDocHeight () - << endl; + << " origin=" << origin() + << " zoomedDoc: width=" << zoomedDocWidth() + << " height=" << zoomedDocHeight() + << endl; #endif - setMask (QRegion (QRect (origin ().x (), origin ().y (), - zoomedDocWidth (), zoomedDocHeight ()))); + setMask(QRegion(QRect(origin().x(), origin().y(), + zoomedDocWidth(), zoomedDocHeight()))); } - // protected virtual [base kpView] -void kpThumbnailView::resizeEvent (QResizeEvent *e) +void kpThumbnailView::resizeEvent(QResizeEvent *e) { #if DEBUG_KP_THUMBNAIL_VIEW - qCDebug(kpLogViews) << "kpThumbnailView(" << name () << ")::resizeEvent()" - << endl; + qCDebug(kpLogViews) << "kpThumbnailView(" << name() << ")::resizeEvent()" + << endl; #endif // For QResizeEvent's, Qt already throws an entire widget repaint into // the event loop. So eat useless update() calls that can only slow // things down. // TODO: this doesn't seem to work. // Later: In Qt4, setUpdatesEnabled(true) calls update(). - const bool oldIsUpdatesEnabled = updatesEnabled (); - setUpdatesEnabled (false); + const bool oldIsUpdatesEnabled = updatesEnabled(); + setUpdatesEnabled(false); { - kpView::resizeEvent (e); + kpView::resizeEvent(e); - adjustToEnvironment (); + adjustToEnvironment(); } - setUpdatesEnabled (oldIsUpdatesEnabled); + setUpdatesEnabled(oldIsUpdatesEnabled); } - - - diff --git a/views/kpUnzoomedThumbnailView.h b/views/kpUnzoomedThumbnailView.h --- a/views/kpUnzoomedThumbnailView.h +++ b/views/kpUnzoomedThumbnailView.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,17 +24,13 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_UNZOOMED_THUMBNAIL_VIEW_H #define KP_UNZOOMED_THUMBNAIL_VIEW_H - #include "views/kpThumbnailView.h" - class kpViewScrollableContainer; - /** * @short Unzoomed thumbnail view of a document. * @@ -54,30 +49,25 @@ */ /*sealed*/ class kpUnzoomedThumbnailView : public kpThumbnailView { -Q_OBJECT + Q_OBJECT public: /** * Constructs an unzoomed thumbnail view. */ - kpUnzoomedThumbnailView (kpDocument *document, - kpToolToolBar *toolToolBar, - kpViewManager *viewManager, - kpView *buddyView, - kpViewScrollableContainer *scrollableContainer, - QWidget *parent); + kpUnzoomedThumbnailView (kpDocument *document, kpToolToolBar *toolToolBar, + kpViewManager *viewManager, kpView *buddyView, + kpViewScrollableContainer *scrollableContainer, QWidget *parent); /** * Destructs an unzoomed thumbnail view. */ ~kpUnzoomedThumbnailView () override; - /** * Implements @ref kpThumbnailView. */ - QString caption () const override; - + QString caption() const override; public slots: /** @@ -95,12 +85,10 @@ * * Implements @ref kpView. */ - void adjustToEnvironment () override; - + void adjustToEnvironment() override; private: struct kpUnzoomedThumbnailViewPrivate *d; }; - #endif // KP_UNZOOMED_THUMBNAIL_VIEW_H diff --git a/views/kpUnzoomedThumbnailView.cpp b/views/kpUnzoomedThumbnailView.cpp --- a/views/kpUnzoomedThumbnailView.cpp +++ b/views/kpUnzoomedThumbnailView.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_UNZOOMED_THUMBNAIL_VIEW 0 - #include "views/kpUnzoomedThumbnailView.h" #include "kpLogCategories.h" @@ -46,29 +43,23 @@ { }; - kpUnzoomedThumbnailView::kpUnzoomedThumbnailView ( - kpDocument *document, - kpToolToolBar *toolToolBar, - kpViewManager *viewManager, - kpView *buddyView, - kpViewScrollableContainer *scrollableContainer, - QWidget *parent) - - : kpThumbnailView (document, toolToolBar, viewManager, - buddyView, - scrollableContainer, - parent), - d (new kpUnzoomedThumbnailViewPrivate ()) + kpDocument *document, kpToolToolBar *toolToolBar, kpViewManager *viewManager, kpView *buddyView, + kpViewScrollableContainer *scrollableContainer, QWidget *parent) + + : kpThumbnailView(document, toolToolBar, viewManager, + buddyView, + scrollableContainer, + parent) + , d(new kpUnzoomedThumbnailViewPrivate()) { - if (buddyViewScrollableContainer ()) - { - connect (buddyViewScrollableContainer(), &kpViewScrollableContainer::contentsMoved, - this, &kpUnzoomedThumbnailView::adjustToEnvironment); + if (buddyViewScrollableContainer()) { + connect(buddyViewScrollableContainer(), &kpViewScrollableContainer::contentsMoved, + this, &kpUnzoomedThumbnailView::adjustToEnvironment); } // Call to virtual function - this is why the class is sealed - adjustToEnvironment (); + adjustToEnvironment(); } //--------------------------------------------------------------------- @@ -81,142 +72,131 @@ //--------------------------------------------------------------------- // public virtual [base kpThumbnailView] -QString kpUnzoomedThumbnailView::caption () const +QString kpUnzoomedThumbnailView::caption() const { - return i18n ("Unzoomed Mode - Thumbnail"); + return i18n("Unzoomed Mode - Thumbnail"); } //--------------------------------------------------------------------- // public slot virtual [base kpView] -void kpUnzoomedThumbnailView::adjustToEnvironment () +void kpUnzoomedThumbnailView::adjustToEnvironment() { - if (!buddyView () || !buddyViewScrollableContainer () || !document ()) { + if (!buddyView() || !buddyViewScrollableContainer() || !document()) { return; } - const int scrollViewContentsX = - buddyViewScrollableContainer()->horizontalScrollBar()->value(); - const int scrollViewContentsY = - buddyViewScrollableContainer ()->verticalScrollBar()->value(); + const int scrollViewContentsX + = buddyViewScrollableContainer()->horizontalScrollBar()->value(); + const int scrollViewContentsY + = buddyViewScrollableContainer()->verticalScrollBar()->value(); #if DEBUG_KP_UNZOOMED_THUMBNAIL_VIEW - qCDebug(kpLogViews) << "kpUnzoomedThumbnailView(" << name () - << ")::adjustToEnvironment(" - << scrollViewContentsX - << "," - << scrollViewContentsY - << ") width=" << width () - << " height=" << height () - << endl; + qCDebug(kpLogViews) << "kpUnzoomedThumbnailView(" << name() + << ")::adjustToEnvironment(" + << scrollViewContentsX + << "," + << scrollViewContentsY + << ") width=" << width() + << " height=" << height() + << endl; #endif - #if 1 int x; - if (document ()->width () > width ()) - { - x = static_cast (buddyView ()->transformViewToDocX (scrollViewContentsX)); - const int rightMostAllowedX = qMax (0, document ()->width () - width ()); + if (document()->width() > width()) { + x = static_cast(buddyView()->transformViewToDocX(scrollViewContentsX)); + const int rightMostAllowedX = qMax(0, document()->width() - width()); #if DEBUG_KP_UNZOOMED_THUMBNAIL_VIEW qCDebug(kpLogViews) << "\tdocX=" << x - << " docWidth=" << document ()->width () - << " rightMostAllowedX=" << rightMostAllowedX; + << " docWidth=" << document()->width() + << " rightMostAllowedX=" << rightMostAllowedX; #endif if (x > rightMostAllowedX) { x = rightMostAllowedX; } } // Thumbnail width <= doc width - else - { + else { // Center X (rather than flush left to be consistent with // kpZoomedThumbnailView) - x = -(width () - document ()->width ()) / 2; + x = -(width() - document()->width()) / 2; } - int y; - if (document ()->height () > height ()) - { - y = static_cast (buddyView ()->transformViewToDocY (scrollViewContentsY)); - const int bottomMostAllowedY = qMax (0, document ()->height () - height ()); + if (document()->height() > height()) { + y = static_cast(buddyView()->transformViewToDocY(scrollViewContentsY)); + const int bottomMostAllowedY = qMax(0, document()->height() - height()); #if DEBUG_KP_UNZOOMED_THUMBNAIL_VIEW qCDebug(kpLogViews) << "\tdocY=" << y - << " docHeight=" << document ()->height () - << " bottomMostAllowedY=" << bottomMostAllowedY; + << " docHeight=" << document()->height() + << " bottomMostAllowedY=" << bottomMostAllowedY; #endif if (y > bottomMostAllowedY) { y = bottomMostAllowedY; } } // Thumbnail height <= doc height - else - { + else { // Center Y (rather than flush top to be consistent with // kpZoomedThumbnailView) - y = -(height () - document ()->height ()) / 2; + y = -(height() - document()->height()) / 2; } // Prefer to keep visible area centred in thumbnail instead of flushed left. // Gives more editing context to the left and top. // But feels awkward for left-to-right users. So disabled for now. // Not totally tested. #else - if (!buddyViewScrollableContainer ()) { + if (!buddyViewScrollableContainer()) { return; } - QRect docRect = buddyView ()->transformViewToDoc ( - QRect (buddyViewScrollableContainer ()->horizontalScrollBar()->value(), - buddyViewScrollableContainer ()->verticalScrollBar()->value(), - qMin (buddyView ()->width (), buddyViewScrollableContainer ()->viewport()->width ()), - qMin (buddyView ()->height (), buddyViewScrollableContainer ()->viewport()->height ()))); + QRect docRect = buddyView()->transformViewToDoc( + QRect(buddyViewScrollableContainer()->horizontalScrollBar()->value(), + buddyViewScrollableContainer()->verticalScrollBar()->value(), + qMin(buddyView()->width(), buddyViewScrollableContainer()->viewport()->width()), + qMin(buddyView()->height(), buddyViewScrollableContainer()->viewport()->height()))); - x = docRect.x () - (width () - docRect.width ()) / 2; + x = docRect.x() - (width() - docRect.width()) / 2; qCDebug(kpLogViews) << "\tnew suggest x=" << x; - const int rightMostAllowedX = qMax (0, document ()->width () - width ()); + const int rightMostAllowedX = qMax(0, document()->width() - width()); if (x < 0) { x = 0; } if (x > rightMostAllowedX) { x = rightMostAllowedX; } - y = docRect.y () - (height () - docRect.height ()) / 2; + y = docRect.y() - (height() - docRect.height()) / 2; qCDebug(kpLogViews) << "\tnew suggest y=" << y; - const int bottomMostAllowedY = qMax (0, document ()->height () - height ()); + const int bottomMostAllowedY = qMax(0, document()->height() - height()); if (y < 0) { y = 0; } if (y > bottomMostAllowedY) { y = bottomMostAllowedY; } #endif - - if (viewManager ()) - { - viewManager ()->setFastUpdates (); - viewManager ()->setQueueUpdates (); + if (viewManager()) { + viewManager()->setFastUpdates(); + viewManager()->setQueueUpdates(); } { // OPT: scrollView impl would be much, much faster - setOrigin (QPoint (-x, -y)); - setMaskToCoverDocument (); + setOrigin(QPoint(-x, -y)); + setMaskToCoverDocument(); // Above might be a NOP even if e.g. doc size changed so force // update - if (viewManager ()) { - viewManager ()->updateView (this); + if (viewManager()) { + viewManager()->updateView(this); } } - if (viewManager ()) - { - viewManager ()->restoreQueueUpdates (); - viewManager ()->restoreFastUpdates (); + if (viewManager()) { + viewManager()->restoreQueueUpdates(); + viewManager()->restoreFastUpdates(); } } - - diff --git a/views/kpView.h b/views/kpView.h --- a/views/kpView.h +++ b/views/kpView.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,16 +24,13 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_VIEW_H #define KP_VIEW_H - #include #include "kpDefs.h" - class QDragEnterEvent; class QDragLeaveEvent; class QEvent; @@ -52,7 +48,6 @@ class kpViewManager; class kpViewScrollableContainer; - /** * @short Abstract base class for all views. * @@ -68,7 +63,7 @@ */ class kpView : public QWidget { -Q_OBJECT + Q_OBJECT public: /** @@ -85,82 +80,75 @@ * * You must call adjustEnvironment() at the end of your constructor. */ - kpView (kpDocument *document, - kpToolToolBar *toolToolBar, - kpViewManager *viewManager, - kpView *buddyView, - kpViewScrollableContainer *scrollableContainer, - QWidget *parent); + kpView (kpDocument *document, kpToolToolBar *toolToolBar, kpViewManager *viewManager, + kpView *buddyView, kpViewScrollableContainer *scrollableContainer, QWidget *parent); /** * Destructs this view. Informs the viewManager() that the mouse * cursor is no longer above this view. */ ~kpView () override; - // // Constants (enforced by methods) // static const int MinZoomLevel, MaxZoomLevel; - /** * @returns the document. */ - kpDocument *document () const; + kpDocument *document() const; protected: /** * @returns the document's selection. */ - kpAbstractSelection *selection () const; + kpAbstractSelection *selection() const; - kpTextSelection *textSelection () const; + kpTextSelection *textSelection() const; public: /** * @returns the tool tool bar. */ - kpToolToolBar *toolToolBar () const; + kpToolToolBar *toolToolBar() const; protected: /** * @returns the currently selected tool. */ - kpTool *tool () const; + kpTool *tool() const; public: /** * @returns the view manager. */ - kpViewManager *viewManager () const; + kpViewManager *viewManager() const; /** * @returns the buddy view. */ - kpView *buddyView () const; + kpView *buddyView() const; /** * @returns the buddyView()'s scrollable container. */ - kpViewScrollableContainer *buddyViewScrollableContainer () const; + kpViewScrollableContainer *buddyViewScrollableContainer() const; /** * @returns this view's scrollable container. */ - kpViewScrollableContainer *scrollableContainer () const; - + kpViewScrollableContainer *scrollableContainer() const; /** * @returns the horizontal zoom level (100 is unzoomed). */ - int zoomLevelX (void) const; + int zoomLevelX(void) const; /** * @returns the vertical zoom level (100 is unzoomed). */ - int zoomLevelY (void) const; + int zoomLevelY(void) const; /** * Sets the horizontal and vertical zoom levels. @@ -173,65 +161,62 @@ * * If reimplementing, you must call this base implementation. */ - virtual void setZoomLevel (int hzoom, int vzoom); - + virtual void setZoomLevel(int hzoom, int vzoom); /** * @returns in views coordinates, where the top-left document() pixel * will be rendered (default: (0,0)). */ - QPoint origin () const; + QPoint origin() const; /** * Sets the origin. * * @param origin New origin. * * If reimplementing, you must call this base implementation. */ - virtual void setOrigin (const QPoint &origin); - + virtual void setOrigin(const QPoint &origin); /** * @returns whether at this zoom level, the grid can be enabled. * This is based on whether the grid can be sensibly rendered. */ - bool canShowGrid () const; + bool canShowGrid() const; /** * @returns whether the grid is currently shown. */ - bool isGridShown () const; + bool isGridShown() const; /** * Turns on/off the grid. * * @param yes Whether to enable the grid. */ - void showGrid (bool yes = true); - + void showGrid(bool yes = true); /** * @returns whether to draw a rectangle highlighting the area of * buddyView() visible through buddyViewScrollableContainer(). */ - bool isBuddyViewScrollableContainerRectangleShown () const; + bool isBuddyViewScrollableContainerRectangleShown() const; /** * Turns on/off the rectangle highlighting the area of buddyView() * visible through buddyViewScrollableContainer() and redraws. * * @param yes Whether to turn on the rectangle. */ - void showBuddyViewScrollableContainerRectangle (bool yes = true); + void showBuddyViewScrollableContainerRectangle(bool yes = true); protected: /** * @returns the current rectangle highlighting the area of buddyView() * visible through buddyViewScrollableContainer(), that is being * rendered by this view. */ - QRect buddyViewScrollableContainerRectangle () const; + QRect buddyViewScrollableContainerRectangle() const; protected slots: /** @@ -242,8 +227,7 @@ * buddyView() and buddyViewScrollableContainer() signals. There is probably no * need to call this function directly. */ - void updateBuddyViewScrollableContainerRectangle (); - + void updateBuddyViewScrollableContainerRectangle(); public: @@ -253,23 +237,23 @@ * @returns viewX transformed to document coordinates, based on the * origin() and zoomLevelX(). */ - double transformViewToDocX (double viewX) const; + double transformViewToDocX(double viewX) const; /** * @param viewY Vertical position in view coordinates. * * @returns viewY transformed to document coordinates, based on the * origin() and zoomLevelY(). */ - double transformViewToDocY (double viewY) const; + double transformViewToDocY(double viewY) const; /** * @param viewPoint Position in view coordinates. * * @returns viewPoint transformed to document coordinates, based on the * origin(), zoomLevelX() and zoomLevelY(). */ - QPoint transformViewToDoc (const QPoint &viewPoint) const; + QPoint transformViewToDoc(const QPoint &viewPoint) const; /** * @param viewRect Rectangle in view coordinates. @@ -281,32 +265,31 @@ * transformViewToDocX(), transformViewToDocY() or * transformViewToDoc(const QPoint &) which act on coordinates only. */ - QRect transformViewToDoc (const QRect &viewRect) const; - + QRect transformViewToDoc(const QRect &viewRect) const; /** * @param docX Horizontal position in document coordinates. * * @returns docX transformed to view coordinates, based on the origin() * and zoomLevelX(). */ - double transformDocToViewX (double docX) const; + double transformDocToViewX(double docX) const; /** * @param docY Vertical position in document coordinates. * * @returns docY transformed to view coordinates, based on the origin() * and zoomLevelY(). */ - double transformDocToViewY (double docY) const; + double transformDocToViewY(double docY) const; /** * @param docPoint Position in document coordinates. * * @returns docPoint transformed to view coordinates, based on the * origin(), zoomLevelX(), zoomLevelY(). */ - QPoint transformDocToView (const QPoint &docPoint) const; + QPoint transformDocToView(const QPoint &docPoint) const; /** * @param docRect Rectangle in document coordinates. @@ -318,8 +301,7 @@ * transformDocToViewX(), transformDocToViewY() or * transformDocToView(const QPoint &) which act on coordinates only. */ - QRect transformDocToView (const QRect &docRect) const; - + QRect transformDocToView(const QRect &docRect) const; /** * @param viewPoint Position in view coordinates. @@ -331,22 +313,19 @@ * zoomLevelX() and zoomLevelY(). This has less rounding * error than otherView->transformDocToView (transformViewToDoc (viewPoint)). */ - QPoint transformViewToOtherView (const QPoint &viewPoint, - const kpView *otherView); - + QPoint transformViewToOtherView(const QPoint &viewPoint, const kpView *otherView); /** * @returns the approximate view width required to display the entire * document(), based on the zoom level only. */ - int zoomedDocWidth () const; + int zoomedDocWidth() const; /** * @returns the approximate view height required to display the entire * document(), based on the zoom level only. */ - int zoomedDocHeight () const; - + int zoomedDocHeight() const; protected: /** @@ -358,8 +337,7 @@ * * @param yes Whether the mouse is directly above this view. */ - void setHasMouse (bool yes = true); - + void setHasMouse(bool yes = true); public: /** @@ -369,7 +347,7 @@ * * @param region Region (in view coordinates) that needs repainting. */ - void addToQueuedArea (const QRegion ®ion); + void addToQueuedArea(const QRegion ®ion); /** * Convenience function. Same as above. @@ -380,22 +358,22 @@ * * @param rect Rectangle (in view coordinates) that needs repainting. */ - void addToQueuedArea (const QRect &rect); + void addToQueuedArea(const QRect &rect); /** * Removes the dirty region that has been queued for updating. * Does not update the view. */ - void invalidateQueuedArea (); + void invalidateQueuedArea(); /** * Updates the part of the view described by dirty region and then * calls invalidateQueuedArea(). Does nothing if @ref kpViewManager * is set to queue updates. */ - void updateQueuedArea (); + void updateQueuedArea(); - QVariant inputMethodQuery (Qt::InputMethodQuery query) const override; + QVariant inputMethodQuery(Qt::InputMethodQuery query) const override; public slots: /** @@ -411,31 +389,29 @@ * type of view. For instance, an unzoomed view would resize itself; * a zoomed thumbnail would change the zoom level. */ - virtual void adjustToEnvironment () = 0; - + virtual void adjustToEnvironment() = 0; public: // If is not KP_INVALID_POINT, it spits it back. // Else, it returns the current mouse position in view coordinates. // REFACTOR: Seems like a bad API. - QPoint mouseViewPoint (const QPoint &returnViewPoint = KP_INVALID_POINT) const; - + QPoint mouseViewPoint(const QPoint &returnViewPoint = KP_INVALID_POINT) const; signals: /** * Emitted after all zooming code has been executed. * * @param zoomLevelX New zoomLevelX() * @param zoomLevelY New zoomLevelY() */ - void zoomLevelChanged (int zoomLevelX, int zoomLevelY); + void zoomLevelChanged(int zoomLevelX, int zoomLevelY); /** * Emitted after all resizing code has been executed. * * @param size New view size. */ - void sizeChanged (const QSize &size); + void sizeChanged(const QSize &size); /** * Convenience signal - same as above. @@ -445,39 +421,37 @@ * @param width New view width. * @param height New view height. */ - void sizeChanged (int width, int height); + void sizeChanged(int width, int height); /** * Emitted after all origin changing code has been executed. * * @param origin The new origin. */ - void originChanged (const QPoint &origin); - - + void originChanged(const QPoint &origin); // // Selections // public: - QRect selectionViewRect () const; + QRect selectionViewRect() const; // (if is KP_INVALID_POINT, it uses QCursor::pos()) - QPoint mouseViewPointRelativeToSelection (const QPoint &viewPoint = KP_INVALID_POINT) const; - bool mouseOnSelection (const QPoint &viewPoint = KP_INVALID_POINT) const; + QPoint mouseViewPointRelativeToSelection(const QPoint &viewPoint = KP_INVALID_POINT) const; + bool mouseOnSelection(const QPoint &viewPoint = KP_INVALID_POINT) const; - int textSelectionMoveBorderAtomicSize () const; - bool mouseOnSelectionToMove (const QPoint &viewPoint = KP_INVALID_POINT) const; + int textSelectionMoveBorderAtomicSize() const; + bool mouseOnSelectionToMove(const QPoint &viewPoint = KP_INVALID_POINT) const; protected: - bool selectionLargeEnoughToHaveResizeHandlesIfAtomicSize (int atomicSize) const; + bool selectionLargeEnoughToHaveResizeHandlesIfAtomicSize(int atomicSize) const; public: - int selectionResizeHandleAtomicSize () const; - bool selectionLargeEnoughToHaveResizeHandles () const; + int selectionResizeHandleAtomicSize() const; + bool selectionLargeEnoughToHaveResizeHandles() const; - QRegion selectionResizeHandlesViewRegion (bool forRenderer = false) const; + QRegion selectionResizeHandlesViewRegion(bool forRenderer = false) const; enum SelectionResizeType { @@ -489,54 +463,47 @@ }; // Returns a bitwise OR of the SelectionResizeType's - int mouseOnSelectionResizeHandle (const QPoint &viewPoint = KP_INVALID_POINT) const; - - bool mouseOnSelectionToSelectText (const QPoint &viewPoint = KP_INVALID_POINT) const; + int mouseOnSelectionResizeHandle(const QPoint &viewPoint = KP_INVALID_POINT) const; + bool mouseOnSelectionToSelectText(const QPoint &viewPoint = KP_INVALID_POINT) const; // // Events // protected: - void mouseMoveEvent (QMouseEvent *e) override; - void mousePressEvent (QMouseEvent *e) override; - void mouseReleaseEvent (QMouseEvent *e) override; + void mouseMoveEvent(QMouseEvent *e) override; + void mousePressEvent(QMouseEvent *e) override; + void mouseReleaseEvent(QMouseEvent *e) override; public: // (needs to be public as it may also get event from // QScrollView::contentsWheelEvent()) - void wheelEvent (QWheelEvent *e) override; - + void wheelEvent(QWheelEvent *e) override; protected: - void keyPressEvent (QKeyEvent *e) override; - void keyReleaseEvent (QKeyEvent *e) override; + void keyPressEvent(QKeyEvent *e) override; + void keyReleaseEvent(QKeyEvent *e) override; protected: - void inputMethodEvent (QInputMethodEvent *e) override; + void inputMethodEvent(QInputMethodEvent *e) override; protected: - bool event (QEvent *e) override; - + bool event(QEvent *e) override; protected: - void focusInEvent (QFocusEvent *e) override; - void focusOutEvent (QFocusEvent *e) override; - + void focusInEvent(QFocusEvent *e) override; + void focusOutEvent(QFocusEvent *e) override; protected: - void enterEvent (QEvent *e) override; - void leaveEvent (QEvent *e) override; - + void enterEvent(QEvent *e) override; + void leaveEvent(QEvent *e) override; protected: - void dragEnterEvent (QDragEnterEvent *) override; - void dragLeaveEvent (QDragLeaveEvent *) override; - + void dragEnterEvent(QDragEnterEvent *) override; + void dragLeaveEvent(QDragLeaveEvent *) override; protected: - void resizeEvent (QResizeEvent *e) override; - + void resizeEvent(QResizeEvent *e) override; // // Painting @@ -547,7 +514,7 @@ // is "guaranteed" to at least cover and possibly more // ("guaranteed" in quotes because it doesn't seem so reliable for // zoom levels that aren't multiples of 100%). - QRect paintEventGetDocRect (const QRect &viewRect) const; + QRect paintEventGetDocRect(const QRect &viewRect) const; public: /** * Draws an opaque background representing transparency. @@ -564,35 +531,30 @@ * e.g. editing. If set, this function may render * slightly differently. */ - static void drawTransparentBackground (QPainter *painter, - const QPoint &patternOrigin, - const QRect &viewRect, - bool isPreview = false); + static void drawTransparentBackground(QPainter *painter, const QPoint &patternOrigin, + const QRect &viewRect, bool isPreview = false); protected: // Draws a checkerboard that looks static even if the view is scrollable. - void paintEventDrawCheckerBoard (QPainter *painter, - const QRect &viewRect); + void paintEventDrawCheckerBoard(QPainter *painter, const QRect &viewRect); // Draws the selection and its border onto . // is the part of the document given by . - void paintEventDrawSelection (QImage *destPixmap, const QRect &docRect); + void paintEventDrawSelection(QImage *destPixmap, const QRect &docRect); // Draws the parts of the selection's resize handles that are inside // onto the view - void paintEventDrawSelectionResizeHandles (const QRect &clipRect); - void paintEventDrawTempImage (QImage *destPixmap, const QRect &docRect); + void paintEventDrawSelectionResizeHandles(const QRect &clipRect); + void paintEventDrawTempImage(QImage *destPixmap, const QRect &docRect); // Draws the parts of the grid lines that are inside on // . - void paintEventDrawGridLines (QPainter *painter, const QRect &viewRect); - - void paintEventDrawDoc_Unclipped (const QRect &viewRect); - void paintEvent (QPaintEvent *e) override; + void paintEventDrawGridLines(QPainter *painter, const QRect &viewRect); + void paintEventDrawDoc_Unclipped(const QRect &viewRect); + void paintEvent(QPaintEvent *e) override; private: struct kpViewPrivate *d; }; - #endif // KP_VIEW_H diff --git a/views/kpView.cpp b/views/kpView.cpp --- a/views/kpView.cpp +++ b/views/kpView.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2005 Kazuki Ohta @@ -27,11 +26,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_VIEW 0 #define DEBUG_KP_VIEW_RENDERER ((DEBUG_KP_VIEW && 1) || 0) - #include "kpView.h" #include "kpViewPrivate.h" @@ -61,14 +58,10 @@ //--------------------------------------------------------------------- -kpView::kpView (kpDocument *document, - kpToolToolBar *toolToolBar, - kpViewManager *viewManager, - kpView *buddyView, - kpViewScrollableContainer *scrollableContainer, - QWidget *parent) - : QWidget (parent), - d (new kpViewPrivate ()) +kpView::kpView (kpDocument *document, kpToolToolBar *toolToolBar, kpViewManager *viewManager, + kpView *buddyView, kpViewScrollableContainer *scrollableContainer, QWidget *parent) + : QWidget(parent) + , d(new kpViewPrivate()) { d->document = document; d->toolToolBar = toolToolBar; @@ -78,611 +71,583 @@ d->hzoom = 100; d->vzoom = 100; - d->origin = QPoint (0, 0); + d->origin = QPoint(0, 0); d->showGrid = false; d->isBuddyViewScrollableContainerRectangleShown = false; // Don't waste CPU drawing default background since its overridden by // our fully opaque drawing. In reality, this seems to make no // difference in performance. setAttribute(Qt::WA_OpaquePaintEvent, true); - setFocusPolicy (Qt::WheelFocus); - setMouseTracking (true); // mouseMoveEvent's even when no mousebtn down - setAttribute (Qt::WA_KeyCompression, true); + setFocusPolicy(Qt::WheelFocus); + setMouseTracking(true); // mouseMoveEvent's even when no mousebtn down + setAttribute(Qt::WA_KeyCompression, true); } //--------------------------------------------------------------------- kpView::~kpView () { - setHasMouse (false); + setHasMouse(false); delete d; } //--------------------------------------------------------------------- // public -kpDocument *kpView::document () const +kpDocument *kpView::document() const { return d->document; } //--------------------------------------------------------------------- // protected -kpAbstractSelection *kpView::selection () const +kpAbstractSelection *kpView::selection() const { - return document () ? document ()->selection () : nullptr; + return document() ? document()->selection() : nullptr; } //--------------------------------------------------------------------- // protected -kpTextSelection *kpView::textSelection () const +kpTextSelection *kpView::textSelection() const { - return document () ? document ()->textSelection () : nullptr; + return document() ? document()->textSelection() : nullptr; } //--------------------------------------------------------------------- // public -kpToolToolBar *kpView::toolToolBar () const +kpToolToolBar *kpView::toolToolBar() const { return d->toolToolBar; } // protected -kpTool *kpView::tool () const +kpTool *kpView::tool() const { - return toolToolBar () ? toolToolBar ()->tool () : nullptr; + return toolToolBar() ? toolToolBar()->tool() : nullptr; } // public -kpViewManager *kpView::viewManager () const +kpViewManager *kpView::viewManager() const { return d->viewManager; } // public -kpView *kpView::buddyView () const +kpView *kpView::buddyView() const { return d->buddyView; } // public -kpViewScrollableContainer *kpView::buddyViewScrollableContainer () const +kpViewScrollableContainer *kpView::buddyViewScrollableContainer() const { - return (buddyView () ? buddyView ()->scrollableContainer () : nullptr); + return buddyView() ? buddyView()->scrollableContainer() : nullptr; } // public -kpViewScrollableContainer *kpView::scrollableContainer () const +kpViewScrollableContainer *kpView::scrollableContainer() const { return d->scrollableContainer; } - // public -int kpView::zoomLevelX () const +int kpView::zoomLevelX() const { return d->hzoom; } // public -int kpView::zoomLevelY () const +int kpView::zoomLevelY() const { return d->vzoom; } // public virtual -void kpView::setZoomLevel (int hzoom, int vzoom) +void kpView::setZoomLevel(int hzoom, int vzoom) { - hzoom = qBound (MinZoomLevel, hzoom, MaxZoomLevel); - vzoom = qBound (MinZoomLevel, vzoom, MaxZoomLevel); + hzoom = qBound(MinZoomLevel, hzoom, MaxZoomLevel); + vzoom = qBound(MinZoomLevel, vzoom, MaxZoomLevel); if (hzoom == d->hzoom && vzoom == d->vzoom) { return; } d->hzoom = hzoom; d->vzoom = vzoom; - if (viewManager ()) { - viewManager ()->updateView (this); + if (viewManager()) { + viewManager()->updateView(this); } - emit zoomLevelChanged (hzoom, vzoom); + emit zoomLevelChanged(hzoom, vzoom); } - // public -QPoint kpView::origin () const +QPoint kpView::origin() const { return d->origin; } // public virtual -void kpView::setOrigin (const QPoint &origin) +void kpView::setOrigin(const QPoint &origin) { #if DEBUG_KP_VIEW - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::setOrigin" << origin; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::setOrigin" << origin; #endif - if (origin == d->origin) - { + if (origin == d->origin) { #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tNOP"; #endif return; } d->origin = origin; - if (viewManager ()) { - viewManager ()->updateView (this); + if (viewManager()) { + viewManager()->updateView(this); } - emit originChanged (origin); + emit originChanged(origin); } - // public -bool kpView::canShowGrid () const +bool kpView::canShowGrid() const { // (minimum zoom level < 400% would probably be reported as a bug by // users who thought that the grid was a part of the image!) - return ((zoomLevelX () >= 400 && zoomLevelX () % 100 == 0) && - (zoomLevelY () >= 400 && zoomLevelY () % 100 == 0)); + return (zoomLevelX() >= 400 && zoomLevelX() % 100 == 0) + && (zoomLevelY() >= 400 && zoomLevelY() % 100 == 0); } // public -bool kpView::isGridShown () const +bool kpView::isGridShown() const { return d->showGrid; } // public -void kpView::showGrid (bool yes) +void kpView::showGrid(bool yes) { if (d->showGrid == yes) { return; } - if (yes && !canShowGrid ()) { + if (yes && !canShowGrid()) { return; } d->showGrid = yes; - if (viewManager ()) { - viewManager ()->updateView (this); + if (viewManager()) { + viewManager()->updateView(this); } } - // public -bool kpView::isBuddyViewScrollableContainerRectangleShown () const +bool kpView::isBuddyViewScrollableContainerRectangleShown() const { return d->isBuddyViewScrollableContainerRectangleShown; } // public -void kpView::showBuddyViewScrollableContainerRectangle (bool yes) +void kpView::showBuddyViewScrollableContainerRectangle(bool yes) { if (yes == d->isBuddyViewScrollableContainerRectangleShown) { return; } d->isBuddyViewScrollableContainerRectangleShown = yes; - if (d->isBuddyViewScrollableContainerRectangleShown) - { + if (d->isBuddyViewScrollableContainerRectangleShown) { // Got these connect statements by analysing deps of // updateBuddyViewScrollableContainerRectangle() rect update code. - connect (this, &kpView::zoomLevelChanged, - this, &kpView::updateBuddyViewScrollableContainerRectangle); + connect(this, &kpView::zoomLevelChanged, + this, &kpView::updateBuddyViewScrollableContainerRectangle); - connect (this, &kpView::originChanged, - this, &kpView::updateBuddyViewScrollableContainerRectangle); + connect(this, &kpView::originChanged, + this, &kpView::updateBuddyViewScrollableContainerRectangle); - if (buddyViewScrollableContainer ()) - { - connect (buddyViewScrollableContainer (), - &kpViewScrollableContainer::contentsMoved, - this, &kpView::updateBuddyViewScrollableContainerRectangle); + if (buddyViewScrollableContainer()) { + connect(buddyViewScrollableContainer(), + &kpViewScrollableContainer::contentsMoved, + this, &kpView::updateBuddyViewScrollableContainerRectangle); - connect (buddyViewScrollableContainer (), &kpViewScrollableContainer::resized, - this, &kpView::updateBuddyViewScrollableContainerRectangle); + connect(buddyViewScrollableContainer(), &kpViewScrollableContainer::resized, + this, &kpView::updateBuddyViewScrollableContainerRectangle); } - if (buddyView ()) - { - connect (buddyView (), &kpView::zoomLevelChanged, - this, &kpView::updateBuddyViewScrollableContainerRectangle); - - connect (buddyView (), &kpView::originChanged, - this, &kpView::updateBuddyViewScrollableContainerRectangle); + if (buddyView()) { + connect(buddyView(), &kpView::zoomLevelChanged, + this, &kpView::updateBuddyViewScrollableContainerRectangle); - connect (buddyView (), - static_cast(&kpView::sizeChanged), - this, &kpView::updateBuddyViewScrollableContainerRectangle); - } + connect(buddyView(), &kpView::originChanged, + this, &kpView::updateBuddyViewScrollableContainerRectangle); - } - else - { - disconnect (this, &kpView::zoomLevelChanged, + connect(buddyView(), + static_cast(&kpView::sizeChanged), this, &kpView::updateBuddyViewScrollableContainerRectangle); + } + } else { + disconnect(this, &kpView::zoomLevelChanged, + this, &kpView::updateBuddyViewScrollableContainerRectangle); - disconnect (this, &kpView::originChanged, - this, &kpView::updateBuddyViewScrollableContainerRectangle); + disconnect(this, &kpView::originChanged, + this, &kpView::updateBuddyViewScrollableContainerRectangle); - if (buddyViewScrollableContainer ()) - { - disconnect (buddyViewScrollableContainer (), - &kpViewScrollableContainer::contentsMoved, - this, &kpView::updateBuddyViewScrollableContainerRectangle); + if (buddyViewScrollableContainer()) { + disconnect(buddyViewScrollableContainer(), + &kpViewScrollableContainer::contentsMoved, + this, &kpView::updateBuddyViewScrollableContainerRectangle); - disconnect (buddyViewScrollableContainer (), &kpViewScrollableContainer::resized, - this, &kpView::updateBuddyViewScrollableContainerRectangle); + disconnect(buddyViewScrollableContainer(), &kpViewScrollableContainer::resized, + this, &kpView::updateBuddyViewScrollableContainerRectangle); } - if (buddyView ()) - { - disconnect (buddyView (), &kpView::zoomLevelChanged, - this, &kpView::updateBuddyViewScrollableContainerRectangle); + if (buddyView()) { + disconnect(buddyView(), &kpView::zoomLevelChanged, + this, &kpView::updateBuddyViewScrollableContainerRectangle); - disconnect (buddyView (), &kpView::originChanged, - this, &kpView::updateBuddyViewScrollableContainerRectangle); + disconnect(buddyView(), &kpView::originChanged, + this, &kpView::updateBuddyViewScrollableContainerRectangle); - disconnect (buddyView (), - static_cast(&kpView::sizeChanged), - this, &kpView::updateBuddyViewScrollableContainerRectangle); + disconnect(buddyView(), + static_cast(&kpView::sizeChanged), + this, &kpView::updateBuddyViewScrollableContainerRectangle); } - } - updateBuddyViewScrollableContainerRectangle (); + updateBuddyViewScrollableContainerRectangle(); } - // protected -QRect kpView::buddyViewScrollableContainerRectangle () const +QRect kpView::buddyViewScrollableContainerRectangle() const { return d->buddyViewScrollableContainerRectangle; } // protected slot -void kpView::updateBuddyViewScrollableContainerRectangle () +void kpView::updateBuddyViewScrollableContainerRectangle() { - if (viewManager ()) { - viewManager ()->setQueueUpdates (); + if (viewManager()) { + viewManager()->setQueueUpdates(); } { - if (d->buddyViewScrollableContainerRectangle.isValid ()) - { - if (viewManager ()) - { + if (d->buddyViewScrollableContainerRectangle.isValid()) { + if (viewManager()) { // Erase last - viewManager ()->updateViewRectangleEdges (this, - d->buddyViewScrollableContainerRectangle); + viewManager()->updateViewRectangleEdges(this, + d->buddyViewScrollableContainerRectangle); } } - QRect newRect; - if (isBuddyViewScrollableContainerRectangleShown () && - buddyViewScrollableContainer () && buddyView ()) - { - QRect docRect = buddyView ()->transformViewToDoc ( - QRect (buddyViewScrollableContainer ()->horizontalScrollBar()->value(), - buddyViewScrollableContainer ()->verticalScrollBar()->value(), - qMin (buddyView ()->width (), - buddyViewScrollableContainer ()->viewport()->width ()), - qMin (buddyView ()->height (), - buddyViewScrollableContainer ()->viewport()->height ()))); - - - QRect viewRect = this->transformDocToView (docRect); - + if (isBuddyViewScrollableContainerRectangleShown() + && buddyViewScrollableContainer() && buddyView()) { + QRect docRect = buddyView()->transformViewToDoc( + QRect(buddyViewScrollableContainer()->horizontalScrollBar()->value(), + buddyViewScrollableContainer()->verticalScrollBar()->value(), + qMin(buddyView()->width(), + buddyViewScrollableContainer()->viewport()->width()), + qMin(buddyView()->height(), + buddyViewScrollableContainer()->viewport()->height()))); + + QRect viewRect = this->transformDocToView(docRect); // (Surround the area of interest by moving outwards by 1 pixel in each // direction - don't overlap area) - newRect = QRect (viewRect.x () - 1, - viewRect.y () - 1, - viewRect.width () + 2, - viewRect.height () + 2); - } - else - { - newRect = QRect (); + newRect = QRect(viewRect.x() - 1, + viewRect.y() - 1, + viewRect.width() + 2, + viewRect.height() + 2); + } else { + newRect = QRect(); } - if (newRect != d->buddyViewScrollableContainerRectangle) - { + if (newRect != d->buddyViewScrollableContainerRectangle) { // (must set before updateView() for paintEvent() to see new // rect) d->buddyViewScrollableContainerRectangle = newRect; - if (newRect.isValid ()) - { - if (viewManager ()) - { - viewManager ()->updateViewRectangleEdges (this, - d->buddyViewScrollableContainerRectangle); + if (newRect.isValid()) { + if (viewManager()) { + viewManager()->updateViewRectangleEdges(this, + d->buddyViewScrollableContainerRectangle); } } } } - if (viewManager ()) { - viewManager ()->restoreQueueUpdates (); + if (viewManager()) { + viewManager()->restoreQueueUpdates(); } } //--------------------------------------------------------------------- // public -double kpView::transformViewToDocX (double viewX) const +double kpView::transformViewToDocX(double viewX) const { - return (viewX - origin ().x ()) * 100.0 / zoomLevelX (); + return (viewX - origin().x()) * 100.0 / zoomLevelX(); } //--------------------------------------------------------------------- // public -double kpView::transformViewToDocY (double viewY) const +double kpView::transformViewToDocY(double viewY) const { - return (viewY - origin ().y ()) * 100.0 / zoomLevelY (); + return (viewY - origin().y()) * 100.0 / zoomLevelY(); } //--------------------------------------------------------------------- // public -QPoint kpView::transformViewToDoc (const QPoint &viewPoint) const +QPoint kpView::transformViewToDoc(const QPoint &viewPoint) const { - return {static_cast (transformViewToDocX (viewPoint.x ())), - static_cast (transformViewToDocY (viewPoint.y ()))}; + return { + static_cast(transformViewToDocX(viewPoint.x())), + static_cast(transformViewToDocY(viewPoint.y())) + }; } //--------------------------------------------------------------------- // public -QRect kpView::transformViewToDoc (const QRect &viewRect) const +QRect kpView::transformViewToDoc(const QRect &viewRect) const { - if (zoomLevelX () == 100 && zoomLevelY () == 100) - { - return {viewRect.x () - origin ().x (), viewRect.y () - origin ().y (), - viewRect.width (), viewRect.height ()}; + if (zoomLevelX() == 100 && zoomLevelY() == 100) { + return { + viewRect.x() - origin().x(), viewRect.y() - origin().y(), + viewRect.width(), viewRect.height() + }; } - const QPoint docTopLeft = transformViewToDoc (viewRect.topLeft ()); + const QPoint docTopLeft = transformViewToDoc(viewRect.topLeft()); // (don't call transformViewToDoc[XY]() - need to round up dimensions) - const auto docWidth = qRound (double (viewRect.width ()) * 100.0 / double (zoomLevelX ())); - const auto docHeight = qRound (double (viewRect.height ()) * 100.0 / double (zoomLevelY ())); + const auto docWidth = qRound(double(viewRect.width()) * 100.0 / double(zoomLevelX())); + const auto docHeight = qRound(double(viewRect.height()) * 100.0 / double(zoomLevelY())); // (like QWMatrix::Areas) - return {docTopLeft.x (), docTopLeft.y (), docWidth, docHeight}; - + return { + docTopLeft.x(), docTopLeft.y(), docWidth, docHeight + }; } //--------------------------------------------------------------------- // public -double kpView::transformDocToViewX (double docX) const +double kpView::transformDocToViewX(double docX) const { - return (docX * zoomLevelX () / 100.0) + origin ().x (); + return (docX * zoomLevelX() / 100.0) + origin().x(); } // public -double kpView::transformDocToViewY (double docY) const +double kpView::transformDocToViewY(double docY) const { - return (docY * zoomLevelY () / 100.0) + origin ().y (); + return (docY * zoomLevelY() / 100.0) + origin().y(); } // public -QPoint kpView::transformDocToView (const QPoint &docPoint) const +QPoint kpView::transformDocToView(const QPoint &docPoint) const { - return {static_cast (transformDocToViewX (docPoint.x ())), - static_cast (transformDocToViewY (docPoint.y ()))}; + return { + static_cast(transformDocToViewX(docPoint.x())), + static_cast(transformDocToViewY(docPoint.y())) + }; } // public -QRect kpView::transformDocToView (const QRect &docRect) const +QRect kpView::transformDocToView(const QRect &docRect) const { - if (zoomLevelX () == 100 && zoomLevelY () == 100) - { - return {docRect.x () + origin ().x (), docRect.y () + origin ().y (), - docRect.width (), docRect.height ()}; + if (zoomLevelX() == 100 && zoomLevelY() == 100) { + return { + docRect.x() + origin().x(), docRect.y() + origin().y(), + docRect.width(), docRect.height() + }; } - const QPoint viewTopLeft = transformDocToView (docRect.topLeft ()); + const QPoint viewTopLeft = transformDocToView(docRect.topLeft()); // (don't call transformDocToView[XY]() - need to round up dimensions) - const int viewWidth = qRound (double (docRect.width ()) * double (zoomLevelX ()) / 100.0); - const int viewHeight = qRound (double (docRect.height ()) * double (zoomLevelY ()) / 100.0); + const int viewWidth = qRound(double(docRect.width()) * double(zoomLevelX()) / 100.0); + const int viewHeight = qRound(double(docRect.height()) * double(zoomLevelY()) / 100.0); // (like QWMatrix::Areas) - return QRect (viewTopLeft.x (), viewTopLeft.y (), viewWidth, viewHeight); + return QRect(viewTopLeft.x(), viewTopLeft.y(), viewWidth, viewHeight); } - // public -QPoint kpView::transformViewToOtherView (const QPoint &viewPoint, - const kpView *otherView) +QPoint kpView::transformViewToOtherView(const QPoint &viewPoint, const kpView *otherView) { if (this == otherView) { return viewPoint; } - const double docX = transformViewToDocX (viewPoint.x ()); - const double docY = transformViewToDocY (viewPoint.y ()); + const double docX = transformViewToDocX(viewPoint.x()); + const double docY = transformViewToDocY(viewPoint.y()); - const double otherViewX = otherView->transformDocToViewX (docX); - const double otherViewY = otherView->transformDocToViewY (docY); + const double otherViewX = otherView->transformDocToViewX(docX); + const double otherViewY = otherView->transformDocToViewY(docY); - return {static_cast (otherViewX), static_cast (otherViewY)}; + return { + static_cast(otherViewX), static_cast(otherViewY) + }; } - // public -int kpView::zoomedDocWidth () const +int kpView::zoomedDocWidth() const { - return document () ? document ()->width () * zoomLevelX () / 100 : 0; + return document() ? document()->width() * zoomLevelX() / 100 : 0; } // public -int kpView::zoomedDocHeight () const +int kpView::zoomedDocHeight() const { - return document () ? document ()->height () * zoomLevelY () / 100 : 0; + return document() ? document()->height() * zoomLevelY() / 100 : 0; } - // public -void kpView::setHasMouse (bool yes) +void kpView::setHasMouse(bool yes) { - kpViewManager *vm = viewManager (); + kpViewManager *vm = viewManager(); if (!vm) { return; } #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () - << ")::setHasMouse(" << yes - << ") existing viewUnderCursor=" - << (vm->viewUnderCursor () ? vm->viewUnderCursor ()->objectName () : "(none)"); + qCDebug(kpLogViews) << "kpView(" << objectName() + << ")::setHasMouse(" << yes + << ") existing viewUnderCursor=" + << (vm->viewUnderCursor() ? vm->viewUnderCursor()->objectName() : "(none)"); #endif - if (yes && vm->viewUnderCursor () != this) { - vm->setViewUnderCursor (this); - } - else if (!yes && vm->viewUnderCursor () == this) { - vm->setViewUnderCursor (nullptr); + if (yes && vm->viewUnderCursor() != this) { + vm->setViewUnderCursor(this); + } else if (!yes && vm->viewUnderCursor() == this) { + vm->setViewUnderCursor(nullptr); } } //--------------------------------------------------------------------- // public -void kpView::addToQueuedArea (const QRegion ®ion) +void kpView::addToQueuedArea(const QRegion ®ion) { #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () - << ")::addToQueuedArea() already=" << d->queuedUpdateArea - << " - plus - " << region - << endl; + qCDebug(kpLogViews) << "kpView(" << objectName() + << ")::addToQueuedArea() already=" << d->queuedUpdateArea + << " - plus - " << region + << endl; #endif d->queuedUpdateArea += region; } //--------------------------------------------------------------------- // public -void kpView::addToQueuedArea (const QRect &rect) +void kpView::addToQueuedArea(const QRect &rect) { #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () - << ")::addToQueuedArea() already=" << d->queuedUpdateArea - << " - plus - " << rect - << endl; + qCDebug(kpLogViews) << "kpView(" << objectName() + << ")::addToQueuedArea() already=" << d->queuedUpdateArea + << " - plus - " << rect + << endl; #endif d->queuedUpdateArea += rect; } //--------------------------------------------------------------------- // public -void kpView::invalidateQueuedArea () +void kpView::invalidateQueuedArea() { #if DEBUG_KP_VIEW && 0 qCDebug(kpLogViews) << "kpView::invalidateQueuedArea()"; #endif - d->queuedUpdateArea = QRegion (); + d->queuedUpdateArea = QRegion(); } //--------------------------------------------------------------------- // public -void kpView::updateQueuedArea () +void kpView::updateQueuedArea() { - kpViewManager *vm = viewManager (); + kpViewManager *vm = viewManager(); #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () - << ")::updateQueuedArea() vm=" << (bool) vm - << " queueUpdates=" << (vm && vm->queueUpdates ()) - << " fastUpdates=" << (vm && vm->fastUpdates ()) - << " area=" << d->queuedUpdateArea - << endl; + qCDebug(kpLogViews) << "kpView(" << objectName() + << ")::updateQueuedArea() vm=" << (bool)vm + << " queueUpdates=" << (vm && vm->queueUpdates()) + << " fastUpdates=" << (vm && vm->fastUpdates()) + << " area=" << d->queuedUpdateArea + << endl; #endif if (!vm) { return; } - if (vm->queueUpdates ()) { + if (vm->queueUpdates()) { return; } - if (!d->queuedUpdateArea.isEmpty ()) { - vm->updateView (this, d->queuedUpdateArea); + if (!d->queuedUpdateArea.isEmpty()) { + vm->updateView(this, d->queuedUpdateArea); } - invalidateQueuedArea (); + invalidateQueuedArea(); } //--------------------------------------------------------------------- // public -QPoint kpView::mouseViewPoint (const QPoint &returnViewPoint) const +QPoint kpView::mouseViewPoint(const QPoint &returnViewPoint) const { if (returnViewPoint != KP_INVALID_POINT) { return returnViewPoint; } // TODO: I don't think this is right for the main view since that's // inside the scrollview (which can scroll). - return mapFromGlobal (QCursor::pos ()); + return mapFromGlobal(QCursor::pos()); } //--------------------------------------------------------------------- // public virtual -QVariant kpView::inputMethodQuery (Qt::InputMethodQuery query) const +QVariant kpView::inputMethodQuery(Qt::InputMethodQuery query) const { #if DEBUG_KP_VIEW && 1 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::inputMethodQuery()"; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::inputMethodQuery()"; #endif QVariant ret; - switch (query) + switch (query) { + case Qt::ImMicroFocus: { - case Qt::ImMicroFocus: - { - QRect r = d->viewManager->textCursorRect (); - r.setTopLeft (r.topLeft () + origin ()); - r.setHeight (r.height() + 2); - r = transformDocToView (r); - ret = r; - break; - } - case Qt::ImFont: - { - if (textSelection ()) - { - ret = textSelection ()->textStyle ().font (); + QRect r = d->viewManager->textCursorRect(); + r.setTopLeft(r.topLeft() + origin()); + r.setHeight(r.height() + 2); + r = transformDocToView(r); + ret = r; + break; + } + case Qt::ImFont: + if (textSelection()) { + ret = textSelection()->textStyle().font(); } break; - } - default: + default: break; } return ret; } //--------------------------------------------------------------------- - - diff --git a/views/kpViewPrivate.h b/views/kpViewPrivate.h --- a/views/kpViewPrivate.h +++ b/views/kpViewPrivate.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,23 +24,19 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpViewPrivate_H #define kpViewPrivate_H - #include #include #include #include - class kpDocument; class kpToolToolBar; class kpView; class kpViewScrollableContainer; - struct kpViewPrivate { // sync: kpView::paintEvent() @@ -73,5 +68,4 @@ QRegion queuedUpdateArea; }; - #endif // kpViewPrivate_H diff --git a/views/kpView_Events.cpp b/views/kpView_Events.cpp --- a/views/kpView_Events.cpp +++ b/views/kpView_Events.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2005 Kazuki Ohta @@ -27,11 +26,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_VIEW 0 #define DEBUG_KP_VIEW_RENDERER ((DEBUG_KP_VIEW && 1) || 0) - #include "views/kpView.h" #include "kpViewPrivate.h" @@ -47,129 +44,128 @@ //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpView::mouseMoveEvent (QMouseEvent *e) +void kpView::mouseMoveEvent(QMouseEvent *e) { #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::mouseMoveEvent (" - << e->x () << "," << e->y () << ")" - << endl; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::mouseMoveEvent (" + << e->x() << "," << e->y() << ")" + << endl; #endif // TODO: This is wrong if you leaveEvent the mainView by mouseMoving on the // mainView, landing on top of the thumbnailView cleverly put on top // of the mainView. - setHasMouse (rect ().contains (e->pos ())); + setHasMouse(rect().contains(e->pos())); - if (tool ()) { - tool ()->mouseMoveEvent (e); + if (tool()) { + tool()->mouseMoveEvent(e); } - e->accept (); + e->accept(); } // protected virtual [base QWidget] -void kpView::mousePressEvent (QMouseEvent *e) +void kpView::mousePressEvent(QMouseEvent *e) { #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::mousePressEvent (" - << e->x () << "," << e->y () << ")" - << endl; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::mousePressEvent (" + << e->x() << "," << e->y() << ")" + << endl; #endif - setHasMouse (true); + setHasMouse(true); - if (tool ()) { - tool ()->mousePressEvent (e); + if (tool()) { + tool()->mousePressEvent(e); } - e->accept (); + e->accept(); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpView::mouseReleaseEvent (QMouseEvent *e) +void kpView::mouseReleaseEvent(QMouseEvent *e) { #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::mouseReleaseEvent (" - << e->x () << "," << e->y () << ")" - << endl; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::mouseReleaseEvent (" + << e->x() << "," << e->y() << ")" + << endl; #endif - setHasMouse (rect ().contains (e->pos ())); + setHasMouse(rect().contains(e->pos())); - if (tool ()) { - tool ()->mouseReleaseEvent (e); + if (tool()) { + tool()->mouseReleaseEvent(e); } - e->accept (); + e->accept(); } //--------------------------------------------------------------------- // public virtual [base QWidget] -void kpView::wheelEvent (QWheelEvent *e) +void kpView::wheelEvent(QWheelEvent *e) { - if (tool ()) { - tool ()->wheelEvent (e); + if (tool()) { + tool()->wheelEvent(e); } } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpView::keyPressEvent (QKeyEvent *e) +void kpView::keyPressEvent(QKeyEvent *e) { #if DEBUG_KP_VIEW - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::keyPressEvent()" << e->text(); + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::keyPressEvent()" << e->text(); #endif - if (tool ()) { - tool ()->keyPressEvent (e); + if (tool()) { + tool()->keyPressEvent(e); } - e->accept (); + e->accept(); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpView::keyReleaseEvent (QKeyEvent *e) +void kpView::keyReleaseEvent(QKeyEvent *e) { #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::keyReleaseEvent()"; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::keyReleaseEvent()"; #endif - if (tool ()) { - tool ()->keyReleaseEvent (e); + if (tool()) { + tool()->keyReleaseEvent(e); } - e->accept (); + e->accept(); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpView::inputMethodEvent (QInputMethodEvent *e) +void kpView::inputMethodEvent(QInputMethodEvent *e) { #if DEBUG_KP_VIEW && 1 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::inputMethodEvent()"; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::inputMethodEvent()"; #endif - if (tool ()) { - tool ()->inputMethodEvent (e); + if (tool()) { + tool()->inputMethodEvent(e); } - e->accept (); + e->accept(); } // protected virtual [base QWidget] -bool kpView::event (QEvent *e) +bool kpView::event(QEvent *e) { #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "kpView::event() invoking kpTool::event()"; #endif - if (tool () && tool ()->viewEvent (e)) - { + if (tool() && tool()->viewEvent(e)) { #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tkpView::event() - tool said eat event, ret true"; #endif @@ -179,38 +175,36 @@ #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tkpView::event() - no tool or said false, call QWidget::event()"; #endif - return QWidget::event (e); + return QWidget::event(e); } - // protected virtual [base QWidget] -void kpView::focusInEvent (QFocusEvent *e) +void kpView::focusInEvent(QFocusEvent *e) { #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::focusInEvent()"; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::focusInEvent()"; #endif - if (tool ()) { - tool ()->focusInEvent (e); + if (tool()) { + tool()->focusInEvent(e); } } // protected virtual [base QWidget] -void kpView::focusOutEvent (QFocusEvent *e) +void kpView::focusOutEvent(QFocusEvent *e) { #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::focusOutEvent()"; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::focusOutEvent()"; #endif - if (tool ()) { - tool ()->focusOutEvent (e); + if (tool()) { + tool()->focusOutEvent(e); } } - // protected virtual [base QWidget] -void kpView::enterEvent (QEvent *e) +void kpView::enterEvent(QEvent *e) { #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::enterEvent()"; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::enterEvent()"; #endif // Don't call setHasMouse(true) as it displays the brush cursor (if @@ -222,60 +216,58 @@ // box and Esc. We have no other reliable way to determine if the // mouse is still above the view (user could have moved mouse out // while RMB menu was up) and hence the cursor is not updated. - setHasMouse (true); + setHasMouse(true); - if (tool ()) { - tool ()->enterEvent (e); + if (tool()) { + tool()->enterEvent(e); } } // protected virtual [base QWidget] -void kpView::leaveEvent (QEvent *e) +void kpView::leaveEvent(QEvent *e) { #if DEBUG_KP_VIEW && 0 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::leaveEvent()"; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::leaveEvent()"; #endif - setHasMouse (false); - if (tool ()) { - tool ()->leaveEvent (e); + setHasMouse(false); + if (tool()) { + tool()->leaveEvent(e); } } - // protected virtual [base QWidget] -void kpView::dragEnterEvent (QDragEnterEvent *) +void kpView::dragEnterEvent(QDragEnterEvent *) { #if DEBUG_KP_VIEW && 1 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::dragEnterEvent()"; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::dragEnterEvent()"; #endif - setHasMouse (true); + setHasMouse(true); } // protected virtual [base QWidget] -void kpView::dragLeaveEvent (QDragLeaveEvent *) +void kpView::dragLeaveEvent(QDragLeaveEvent *) { #if DEBUG_KP_VIEW && 1 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::dragLeaveEvent"; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::dragLeaveEvent"; #endif - setHasMouse (false); + setHasMouse(false); } - // protected virtual [base QWidget] -void kpView::resizeEvent (QResizeEvent *e) +void kpView::resizeEvent(QResizeEvent *e) { #if DEBUG_KP_VIEW && 1 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::resizeEvent(" - << e->size () - << " vs actual=" << size () - << ") old=" << e->oldSize () << endl; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::resizeEvent(" + << e->size() + << " vs actual=" << size() + << ") old=" << e->oldSize() << endl; #endif - QWidget::resizeEvent (e); + QWidget::resizeEvent(e); - emit sizeChanged (width (), height ()); - emit sizeChanged (size ()); + emit sizeChanged(width(), height()); + emit sizeChanged(size()); } diff --git a/views/kpView_Paint.cpp b/views/kpView_Paint.cpp --- a/views/kpView_Paint.cpp +++ b/views/kpView_Paint.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,11 +24,9 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_VIEW 0 #define DEBUG_KP_VIEW_RENDERER ((DEBUG_KP_VIEW && 1) || 0) - #include "views/kpView.h" #include "kpViewPrivate.h" @@ -51,7 +48,7 @@ //--------------------------------------------------------------------- // protected -QRect kpView::paintEventGetDocRect (const QRect &viewRect) const +QRect kpView::paintEventGetDocRect(const QRect &viewRect) const { #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "kpView::paintEventGetDocRect(" << viewRect << ")"; @@ -61,32 +58,28 @@ // From the "we aren't sure whether to round up or round down" department: - if (zoomLevelX () < 100 || zoomLevelY () < 100) { - docRect = transformViewToDoc (viewRect); - } - else - { + if (zoomLevelX() < 100 || zoomLevelY() < 100) { + docRect = transformViewToDoc(viewRect); + } else { // think of a grid - you need to fully cover the zoomed-in pixels // when docRect is zoomed back to the view later - docRect = QRect (transformViewToDoc (viewRect.topLeft ()), // round down - transformViewToDoc (viewRect.bottomRight ())); // round down + docRect = QRect(transformViewToDoc(viewRect.topLeft()), // round down + transformViewToDoc(viewRect.bottomRight())); // round down } - if (zoomLevelX () % 100 || zoomLevelY () % 100) - { + if (zoomLevelX() % 100 || zoomLevelY() % 100) { // at least round up the bottom-right point and deal with matrix weirdness: // - helpful because it ensures we at least cover the required area // at e.g. 67% or 573% - docRect.setBottomRight (docRect.bottomRight () + QPoint (2, 2)); + docRect.setBottomRight(docRect.bottomRight() + QPoint(2, 2)); } #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\tdocRect=" << docRect; #endif - kpDocument *doc = document (); - if (doc) - { - docRect = docRect.intersected (doc->rect ()); + kpDocument *doc = document(); + if (doc) { + docRect = docRect.intersected(doc->rect()); #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\tintersected with doc=" << docRect; #endif @@ -98,165 +91,151 @@ //--------------------------------------------------------------------- // public static -void kpView::drawTransparentBackground (QPainter *painter, - const QPoint &patternOrigin, - const QRect &viewRect, - bool isPreview) +void kpView::drawTransparentBackground(QPainter *painter, const QPoint &patternOrigin, + const QRect &viewRect, bool isPreview) { #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "kpView::drawTransparentBackground() patternOrigin=" - << patternOrigin - << " viewRect=" << viewRect - << " isPreview=" << isPreview - << endl; + << patternOrigin + << " viewRect=" << viewRect + << " isPreview=" << isPreview + << endl; #endif const int cellSize = !isPreview ? 16 : 10; // TODO: % is unpredictable with negatives. - int starty = viewRect.y (); - if ((starty - patternOrigin.y ()) % cellSize) { - starty -= ((starty - patternOrigin.y ()) % cellSize); + int starty = viewRect.y(); + if ((starty - patternOrigin.y()) % cellSize) { + starty -= ((starty - patternOrigin.y()) % cellSize); } - int startx = viewRect.x (); - if ((startx - patternOrigin.x ()) % cellSize) { - startx -= ((startx - patternOrigin.x ()) % cellSize); + int startx = viewRect.x(); + if ((startx - patternOrigin.x()) % cellSize) { + startx -= ((startx - patternOrigin.x()) % cellSize); } #if DEBUG_KP_VIEW_RENDERER && 1 - qCDebug(kpLogViews) << "\tstartXY=" << QPoint (startx, starty); + qCDebug(kpLogViews) << "\tstartXY=" << QPoint(startx, starty); #endif - painter->save (); + painter->save(); // Clip to as we may draw outside it on all sides. - painter->setClipRect (viewRect, Qt::IntersectClip/*honor existing clip*/); - - for (int y = starty; y <= viewRect.bottom (); y += cellSize) - { - for (int x = startx; x <= viewRect.right (); x += cellSize) - { - bool parity = ((x - patternOrigin.x ()) / cellSize + - (y - patternOrigin.y ()) / cellSize) % 2; + painter->setClipRect(viewRect, Qt::IntersectClip /*honor existing clip*/); + + for (int y = starty; y <= viewRect.bottom(); y += cellSize) { + for (int x = startx; x <= viewRect.right(); x += cellSize) { + bool parity = ((x - patternOrigin.x()) / cellSize + +(y - patternOrigin.y()) / cellSize) % 2; QColor col; - if (parity) - { + if (parity) { if (!isPreview) { - col = QColor (213, 213, 213); - } - else { - col = QColor (224, 224, 224); + col = QColor(213, 213, 213); + } else { + col = QColor(224, 224, 224); } - } - else { + } else { col = Qt::white; } - painter->fillRect (x, y, cellSize, cellSize, col); + painter->fillRect(x, y, cellSize, cellSize, col); } } - painter->restore (); + painter->restore(); } //--------------------------------------------------------------------- // protected -void kpView::paintEventDrawCheckerBoard (QPainter *painter, const QRect &viewRect) +void kpView::paintEventDrawCheckerBoard(QPainter *painter, const QRect &viewRect) { #if DEBUG_KP_VIEW_RENDERER && 1 - qCDebug(kpLogViews) << "kpView(" << objectName () - << ")::paintEventDrawCheckerBoard(viewRect=" << viewRect - << ") origin=" << origin (); + qCDebug(kpLogViews) << "kpView(" << objectName() + << ")::paintEventDrawCheckerBoard(viewRect=" << viewRect + << ") origin=" << origin(); #endif - kpDocument *doc = document (); + kpDocument *doc = document(); if (!doc) { return; } - QPoint patternOrigin = origin (); + QPoint patternOrigin = origin(); - if (scrollableContainer ()) - { + if (scrollableContainer()) { #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\tscrollableContainer: contents[XY]=" - << QPoint (scrollableContainer ()->horizontalScrollBar()->value (), - scrollableContainer ()->verticalScrollBar()->value ()) - << endl; + << QPoint(scrollableContainer()->horizontalScrollBar()->value(), + scrollableContainer()->verticalScrollBar()->value()) + << endl; #endif // Make checkerboard appear static relative to the scroll view. // This makes it more obvious that any visible bits of the // checkboard represent transparent pixels and not gray and white // squares. - patternOrigin = QPoint (scrollableContainer ()->horizontalScrollBar()->value(), - scrollableContainer ()->verticalScrollBar()->value()); + patternOrigin = QPoint(scrollableContainer()->horizontalScrollBar()->value(), + scrollableContainer()->verticalScrollBar()->value()); #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\t\tpatternOrigin=" << patternOrigin; #endif } // TODO: this static business doesn't work yet - patternOrigin = QPoint (0, 0); + patternOrigin = QPoint(0, 0); - drawTransparentBackground (painter, patternOrigin, viewRect); + drawTransparentBackground(painter, patternOrigin, viewRect); } //--------------------------------------------------------------------- // protected -void kpView::paintEventDrawSelection (QImage *destPixmap, const QRect &docRect) +void kpView::paintEventDrawSelection(QImage *destPixmap, const QRect &docRect) { #if DEBUG_KP_VIEW_RENDERER && 1 || 0 qCDebug(kpLogViews) << "kpView::paintEventDrawSelection() docRect=" << docRect; #endif - kpDocument *doc = document (); - if (!doc) - { + kpDocument *doc = document(); + if (!doc) { #if DEBUG_KP_VIEW_RENDERER && 1 || 0 qCDebug(kpLogViews) << "\tno doc - abort"; #endif return; } - kpAbstractSelection *sel = doc->selection (); - if (!sel) - { + kpAbstractSelection *sel = doc->selection(); + if (!sel) { #if DEBUG_KP_VIEW_RENDERER && 1 || 0 qCDebug(kpLogViews) << "\tno sel - abort"; #endif return; } - // // Draw selection pixmap (if there is one) // #if DEBUG_KP_VIEW_RENDERER && 1 || 0 - qCDebug(kpLogViews) << "\tdraw sel pixmap @ " << sel->topLeft (); + qCDebug(kpLogViews) << "\tdraw sel pixmap @ " << sel->topLeft(); #endif - sel->paint (destPixmap, docRect); - + sel->paint(destPixmap, docRect); // // Draw selection border // - kpViewManager *vm = viewManager (); + kpViewManager *vm = viewManager(); #if DEBUG_KP_VIEW_RENDERER && 1 || 0 qCDebug(kpLogViews) << "\tsel border visible=" - << vm->selectionBorderVisible (); + << vm->selectionBorderVisible(); #endif - if (vm->selectionBorderVisible ()) - { - sel->paintBorder (destPixmap, docRect, vm->selectionBorderFinished ()); + if (vm->selectionBorderVisible()) { + sel->paintBorder(destPixmap, docRect, vm->selectionBorderFinished()); } - // // Draw text cursor // @@ -267,137 +246,132 @@ // // However, too much selection repaint code assumes that it // only paints inside its kpAbstractSelection::boundingRect(). - auto *textSel = dynamic_cast (sel); - if (textSel && - vm->textCursorEnabled () && - (vm->textCursorBlinkState () || - // For the current main window: - // As long as _any_ view has focus, blink _all_ views not just the - // one with focus. - !vm->hasAViewWithFocus ())) // sync: call will break when vm is not held by 1 mainWindow - { - QRect rect = vm->textCursorRect (); - rect = rect.intersected (textSel->textAreaRect ()); - if (!rect.isEmpty ()) - { - kpPixmapFX::fillRect(destPixmap, - rect.x () - docRect.x (), rect.y () - docRect.y (), - rect.width (), rect.height (), - kpColor::LightGray, kpColor::DarkGray); + auto *textSel = dynamic_cast (sel); + if (textSel + && vm->textCursorEnabled() + && (vm->textCursorBlinkState() + ||// For the current main window: + // As long as _any_ view has focus, blink _all_ views not just the + // one with focus. + !vm->hasAViewWithFocus())) { // sync: call will break when vm is not held by 1 mainWindow + QRect rect = vm->textCursorRect(); + rect = rect.intersected(textSel->textAreaRect()); + if (!rect.isEmpty()) { + kpPixmapFX::fillRect(destPixmap, + rect.x() - docRect.x(), rect.y() - docRect.y(), + rect.width(), rect.height(), + kpColor::LightGray, kpColor::DarkGray); } } } //--------------------------------------------------------------------- // protected -void kpView::paintEventDrawSelectionResizeHandles (const QRect &clipRect) +void kpView::paintEventDrawSelectionResizeHandles(const QRect &clipRect) { #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "kpView::paintEventDrawSelectionResizeHandles(" - << clipRect << ")"; + << clipRect << ")"; #endif - if (!selectionLargeEnoughToHaveResizeHandles ()) - { + if (!selectionLargeEnoughToHaveResizeHandles()) { #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\tsel not large enough to have resize handles"; #endif return; } - kpViewManager *vm = viewManager (); - if (!vm || !vm->selectionBorderVisible () || !vm->selectionBorderFinished ()) - { + kpViewManager *vm = viewManager(); + if (!vm || !vm->selectionBorderVisible() || !vm->selectionBorderFinished()) { #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\tsel border not visible or not finished"; #endif return; } - const QRect selViewRect = selectionViewRect (); + const QRect selViewRect = selectionViewRect(); #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\tselViewRect=" << selViewRect; #endif - if (!selViewRect.intersects (clipRect)) - { + if (!selViewRect.intersects(clipRect)) { #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\tdoesn't intersect viewRect"; #endif return; } - QRegion selResizeHandlesRegion = selectionResizeHandlesViewRegion (true/*for renderer*/); + QRegion selResizeHandlesRegion = selectionResizeHandlesViewRegion(true /*for renderer*/); #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\tsel resize handles view region=" - << selResizeHandlesRegion << endl; + << selResizeHandlesRegion << endl; #endif QPainter painter(this); painter.setPen(Qt::black); painter.setBrush(Qt::cyan); for (const auto &r : selResizeHandlesRegion.rects()) { - painter.drawRect(r); + painter.drawRect(r); } } //--------------------------------------------------------------------- // protected -void kpView::paintEventDrawTempImage (QImage *destPixmap, const QRect &docRect) +void kpView::paintEventDrawTempImage(QImage *destPixmap, const QRect &docRect) { - kpViewManager *vm = viewManager (); + kpViewManager *vm = viewManager(); if (!vm) { return; } - const kpTempImage *tpi = vm->tempImage (); + const kpTempImage *tpi = vm->tempImage(); #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "kpView::paintEventDrawTempImage() tempImage=" - << tpi - << " isVisible=" - << (tpi ? tpi->isVisible (vm) : false) - << endl; + << tpi + << " isVisible=" + << (tpi ? tpi->isVisible(vm) : false) + << endl; #endif - if (!tpi || !tpi->isVisible (vm)) { + if (!tpi || !tpi->isVisible(vm)) { return; } - tpi->paint (destPixmap, docRect); + tpi->paint(destPixmap, docRect); } //--------------------------------------------------------------------- // protected -void kpView::paintEventDrawGridLines (QPainter *painter, const QRect &viewRect) +void kpView::paintEventDrawGridLines(QPainter *painter, const QRect &viewRect) { - int hzoomMultiple = zoomLevelX () / 100; - int vzoomMultiple = zoomLevelY () / 100; - - painter->setPen(Qt::gray); - - // horizontal lines - int starty = viewRect.top(); - if (starty % vzoomMultiple) { - starty = (starty + vzoomMultiple) / vzoomMultiple * vzoomMultiple; - } - - for (int y = starty; y <= viewRect.bottom(); y += vzoomMultiple) { - painter->drawLine(viewRect.left(), y, viewRect.right(), y); - } - - // vertical lines - int startx = viewRect.left(); - if (startx % hzoomMultiple) { - startx = (startx + hzoomMultiple) / hzoomMultiple * hzoomMultiple; - } - - for (int x = startx; x <= viewRect.right(); x += hzoomMultiple) { - painter->drawLine(x, viewRect.top (), x, viewRect.bottom()); - } + int hzoomMultiple = zoomLevelX() / 100; + int vzoomMultiple = zoomLevelY() / 100; + + painter->setPen(Qt::gray); + + // horizontal lines + int starty = viewRect.top(); + if (starty % vzoomMultiple) { + starty = (starty + vzoomMultiple) / vzoomMultiple * vzoomMultiple; + } + + for (int y = starty; y <= viewRect.bottom(); y += vzoomMultiple) { + painter->drawLine(viewRect.left(), y, viewRect.right(), y); + } + + // vertical lines + int startx = viewRect.left(); + if (startx % hzoomMultiple) { + startx = (startx + hzoomMultiple) / hzoomMultiple * hzoomMultiple; + } + + for (int x = startx; x <= viewRect.right(); x += hzoomMultiple) { + painter->drawLine(x, viewRect.top(), x, viewRect.bottom()); + } } //--------------------------------------------------------------------- @@ -431,163 +405,157 @@ // This over-drawing is only safe from Qt's perspective since Qt // automatically clips all drawing in paintEvent() (which calls us) to // QPaintEvent::region(). -void kpView::paintEventDrawDoc_Unclipped (const QRect &viewRect) +void kpView::paintEventDrawDoc_Unclipped(const QRect &viewRect) { #if DEBUG_KP_VIEW_RENDERER QTime timer; - timer.start (); + timer.start(); qCDebug(kpLogViews) << "\tviewRect=" << viewRect; #endif - kpViewManager *vm = viewManager (); - const kpDocument *doc = document (); + kpViewManager *vm = viewManager(); + const kpDocument *doc = document(); - Q_ASSERT (vm); - Q_ASSERT (doc); + Q_ASSERT(vm); + Q_ASSERT(doc); - if (viewRect.isEmpty ()) { + if (viewRect.isEmpty()) { return; } - QRect docRect = paintEventGetDocRect (viewRect); + QRect docRect = paintEventGetDocRect(viewRect); #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\tdocRect=" << docRect; #endif - QPainter painter (this); + QPainter painter(this); //painter.setCompositionMode(QPainter::CompositionMode_Source); QImage docPixmap; bool tempImageWillBeRendered = false; // LOTODO: I think being empty would be a bug. - if (!docRect.isEmpty ()) - { - docPixmap = doc->getImageAt (docRect); + if (!docRect.isEmpty()) { + docPixmap = doc->getImageAt(docRect); #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\tdocPixmap.hasAlphaChannel()=" - << docPixmap.hasAlphaChannel (); + << docPixmap.hasAlphaChannel(); #endif - tempImageWillBeRendered = - (!doc->selection () && - vm->tempImage () && - vm->tempImage ()->isVisible (vm) && - docRect.intersects (vm->tempImage ()->rect ())); + tempImageWillBeRendered + = (!doc->selection() + && vm->tempImage() + && vm->tempImage()->isVisible(vm) + && docRect.intersects(vm->tempImage()->rect())); #if DEBUG_KP_VIEW_RENDERER && 1 qCDebug(kpLogViews) << "\ttempImageWillBeRendered=" << tempImageWillBeRendered - << " (sel=" << doc->selection () - << " tempImage=" << vm->tempImage () - << " tempImage.isVisible=" << (vm->tempImage () ? vm->tempImage ()->isVisible (vm) : false) - << " docRect.intersects(tempImage.rect)=" << (vm->tempImage () ? docRect.intersects (vm->tempImage ()->rect ()) : false) - << ")" - << endl; + << " (sel=" << doc->selection() + << " tempImage=" << vm->tempImage() + << " tempImage.isVisible=" + << (vm->tempImage() ? vm->tempImage()->isVisible(vm) : false) + << " docRect.intersects(tempImage.rect)=" + << (vm->tempImage() ? docRect.intersects(vm->tempImage()->rect()) : + false) + << ")" + << endl; #endif } - // // Draw checkboard for transparent images and/or views with borders // - if (docPixmap.hasAlphaChannel() || - (tempImageWillBeRendered && vm->tempImage ()->paintMayAddMask ())) - { - paintEventDrawCheckerBoard (&painter, viewRect); + if (docPixmap.hasAlphaChannel() + || (tempImageWillBeRendered && vm->tempImage()->paintMayAddMask())) { + paintEventDrawCheckerBoard(&painter, viewRect); } - if (!docRect.isEmpty ()) - { + if (!docRect.isEmpty()) { // // Draw docPixmap + tempImage // - if (doc->selection ()) - { - paintEventDrawSelection (&docPixmap, docRect); - } - else if (tempImageWillBeRendered) - { - paintEventDrawTempImage (&docPixmap, docRect); + if (doc->selection()) { + paintEventDrawSelection(&docPixmap, docRect); + } else if (tempImageWillBeRendered) { + paintEventDrawTempImage(&docPixmap, docRect); } #if DEBUG_KP_VIEW_RENDERER && 1 - qCDebug(kpLogViews) << "\torigin=" << origin (); + qCDebug(kpLogViews) << "\torigin=" << origin(); #endif // Blit scaled version of docPixmap + tempImage. #if DEBUG_KP_VIEW_RENDERER && 1 - QTime scaleTimer; scaleTimer.start (); + QTime scaleTimer; + scaleTimer.start(); #endif // This is the only troublesome part of the method that draws unclipped. - painter.translate (origin ().x (), origin ().y ()); - painter.scale (double (zoomLevelX ()) / 100.0, - double (zoomLevelY ()) / 100.0); - painter.drawImage (docRect, docPixmap); + painter.translate(origin().x(), origin().y()); + painter.scale(double(zoomLevelX()) / 100.0, + double(zoomLevelY()) / 100.0); + painter.drawImage(docRect, docPixmap); //painter.resetMatrix (); // back to 1-1 scaling #if DEBUG_KP_VIEW_RENDERER && 1 - qCDebug(kpLogViews) << "\tscale time=" << scaleTimer.elapsed (); + qCDebug(kpLogViews) << "\tscale time=" << scaleTimer.elapsed(); #endif - } // if (!docRect.isEmpty ()) { #if DEBUG_KP_VIEW_RENDERER && 1 - qCDebug(kpLogViews) << "\tdrawDocRect done in: " << timer.restart () << "ms"; + qCDebug(kpLogViews) << "\tdrawDocRect done in: " << timer.restart() << "ms"; #endif } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpView::paintEvent (QPaintEvent *e) +void kpView::paintEvent(QPaintEvent *e) { // sync: kpViewPrivate // WARNING: document(), viewManager() and friends might be 0 in this method. // TODO: I'm not 100% convinced that we always check if their friends are 0. #if DEBUG_KP_VIEW_RENDERER && 1 QTime timer; - timer.start (); + timer.start(); #endif - kpViewManager *vm = viewManager (); + kpViewManager *vm = viewManager(); #if DEBUG_KP_VIEW_RENDERER && 1 - qCDebug(kpLogViews) << "kpView(" << objectName () << ")::paintEvent() vm=" << (bool) vm - << " queueUpdates=" << (vm && vm->queueUpdates ()) - << " fastUpdates=" << (vm && vm->fastUpdates ()) - << " viewRect=" << e->rect () - << " topLeft=" << QPoint (x (), y ()) - << endl; + qCDebug(kpLogViews) << "kpView(" << objectName() << ")::paintEvent() vm=" << (bool)vm + << " queueUpdates=" << (vm && vm->queueUpdates()) + << " fastUpdates=" << (vm && vm->fastUpdates()) + << " viewRect=" << e->rect() + << " topLeft=" << QPoint(x(), y()) + << endl; #endif if (!vm) { return; } - if (vm->queueUpdates ()) - { + if (vm->queueUpdates()) { // OPT: if this update was due to the document, // use document coordinates (in case of a zoom change in // which view coordinates become out of date) - addToQueuedArea (e->region ()); + addToQueuedArea(e->region()); return; } - kpDocument *doc = document (); + kpDocument *doc = document(); if (!doc) { return; } - // It seems that e->region() is already clipped by Qt to the visible // part of the view (which could be quite small inside a scrollview). - const auto& viewRegion = e->region (); - QVector rects = viewRegion.rects (); + const auto &viewRegion = e->region(); + QVector rects = viewRegion.rects(); #if DEBUG_KP_VIEW_RENDERER - qCDebug(kpLogViews) << "\t#rects = " << rects.count (); + qCDebug(kpLogViews) << "\t#rects = " << rects.count(); #endif // Draw all of the requested regions of the document _before_ drawing @@ -602,42 +570,39 @@ // parts of nearby grid lines (which were drawn in a previous iteration) // with document pixels. Those grid line parts are probably not going to // be redrawn, so will appear to be missing. - for (const auto &r : rects) - { - paintEventDrawDoc_Unclipped (r); + for (const auto &r : rects) { + paintEventDrawDoc_Unclipped(r); } // // Draw Grid Lines // - if ( isGridShown() ) - { - QPainter painter(this); - for (const auto &r : rects) - paintEventDrawGridLines(&painter, r); + if (isGridShown()) { + QPainter painter(this); + for (const auto &r : rects) { + paintEventDrawGridLines(&painter, r); + } } const QRect r = buddyViewScrollableContainerRectangle(); - if ( !r.isEmpty() ) - { - QPainter painter(this); + if (!r.isEmpty()) { + QPainter painter(this); - painter.setPen(QPen(Qt::lightGray, 1/*width*/, Qt::DotLine)); - painter.setBackground(Qt::darkGray); - painter.setBackgroundMode(Qt::OpaqueMode); + painter.setPen(QPen(Qt::lightGray, 1 /*width*/, Qt::DotLine)); + painter.setBackground(Qt::darkGray); + painter.setBackgroundMode(Qt::OpaqueMode); - painter.drawRect(r.x(), r.y(), r.width() - 1, r.height() - 1); + painter.drawRect(r.x(), r.y(), r.width() - 1, r.height() - 1); } - if (doc->selection ()) - { + if (doc->selection()) { // Draw resize handles on top of possible grid lines - paintEventDrawSelectionResizeHandles (e->rect ()); + paintEventDrawSelectionResizeHandles(e->rect()); } #if DEBUG_KP_VIEW_RENDERER && 1 - qCDebug(kpLogViews) << "\tall done in: " << timer.restart () << "ms"; + qCDebug(kpLogViews) << "\tall done in: " << timer.restart() << "ms"; #endif } diff --git a/views/kpView_Selections.cpp b/views/kpView_Selections.cpp --- a/views/kpView_Selections.cpp +++ b/views/kpView_Selections.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,120 +24,111 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_VIEW 0 #define DEBUG_KP_VIEW_RENDERER ((DEBUG_KP_VIEW && 1) || 0) - #include "views/kpView.h" #include "kpViewPrivate.h" #include "layers/selections/kpAbstractSelection.h" #include "layers/selections/text/kpTextSelection.h" #include "tools/kpTool.h" - // public -QRect kpView::selectionViewRect () const +QRect kpView::selectionViewRect() const { - return selection () ? - transformDocToView (selection ()->boundingRect ()) : - QRect (); - + return selection() + ? transformDocToView(selection()->boundingRect()) + : QRect(); } - // public -QPoint kpView::mouseViewPointRelativeToSelection (const QPoint &viewPoint) const +QPoint kpView::mouseViewPointRelativeToSelection(const QPoint &viewPoint) const { - if (!selection ()) { + if (!selection()) { return KP_INVALID_POINT; } - return mouseViewPoint (viewPoint) - transformDocToView (selection ()->topLeft ()); + return mouseViewPoint(viewPoint) - transformDocToView(selection()->topLeft()); } // public -bool kpView::mouseOnSelection (const QPoint &viewPoint) const +bool kpView::mouseOnSelection(const QPoint &viewPoint) const { - const QRect selViewRect = selectionViewRect (); - if (!selViewRect.isValid ()) { + const QRect selViewRect = selectionViewRect(); + if (!selViewRect.isValid()) { return false; } - return selViewRect.contains (mouseViewPoint (viewPoint)); + return selViewRect.contains(mouseViewPoint(viewPoint)); } - // public -int kpView::textSelectionMoveBorderAtomicSize () const +int kpView::textSelectionMoveBorderAtomicSize() const { - if (!textSelection ()) { + if (!textSelection()) { return 0; } - return qMax (4, zoomLevelX () / 100); + return qMax(4, zoomLevelX() / 100); } // public -bool kpView::mouseOnSelectionToMove (const QPoint &viewPoint) const +bool kpView::mouseOnSelectionToMove(const QPoint &viewPoint) const { - if (!mouseOnSelection (viewPoint)) { + if (!mouseOnSelection(viewPoint)) { return false; } - if (!textSelection ()) { + if (!textSelection()) { return true; } - if (mouseOnSelectionResizeHandle (viewPoint)) { + if (mouseOnSelectionResizeHandle(viewPoint)) { return false; } - - const QPoint viewPointRelSel = mouseViewPointRelativeToSelection (viewPoint); + const QPoint viewPointRelSel = mouseViewPointRelativeToSelection(viewPoint); // Middle point should always be selectable - const QPoint selCenterDocPoint = selection ()->boundingRect ().center (); - if (tool () && - tool ()->calculateCurrentPoint () == selCenterDocPoint) - { + const QPoint selCenterDocPoint = selection()->boundingRect().center(); + if (tool() + && tool()->calculateCurrentPoint() == selCenterDocPoint) { return false; } + const int atomicSize = textSelectionMoveBorderAtomicSize(); + const QRect selViewRect = selectionViewRect(); - const int atomicSize = textSelectionMoveBorderAtomicSize (); - const QRect selViewRect = selectionViewRect (); - - return (viewPointRelSel.x () < atomicSize || - viewPointRelSel.x () >= selViewRect.width () - atomicSize || - viewPointRelSel.y () < atomicSize || - viewPointRelSel.y () >= selViewRect.height () - atomicSize); + return viewPointRelSel.x() < atomicSize + || viewPointRelSel.x() >= selViewRect.width() - atomicSize + || viewPointRelSel.y() < atomicSize + || viewPointRelSel.y() >= selViewRect.height() - atomicSize; } //--------------------------------------------------------------------- // protected -bool kpView::selectionLargeEnoughToHaveResizeHandlesIfAtomicSize (int atomicSize) const +bool kpView::selectionLargeEnoughToHaveResizeHandlesIfAtomicSize(int atomicSize) const { - if (!selection ()) { + if (!selection()) { return false; } - const QRect selViewRect = selectionViewRect (); + const QRect selViewRect = selectionViewRect(); - return (selViewRect.width () >= atomicSize * 5 || - selViewRect.height () >= atomicSize * 5); + return selViewRect.width() >= atomicSize * 5 + || selViewRect.height() >= atomicSize * 5; } //--------------------------------------------------------------------- // public -int kpView::selectionResizeHandleAtomicSize () const +int kpView::selectionResizeHandleAtomicSize() const { - int atomicSize = qMin (13, qMax (9, zoomLevelX () / 100)); - while (atomicSize > 0 && - !selectionLargeEnoughToHaveResizeHandlesIfAtomicSize (atomicSize)) + int atomicSize = qMin(13, qMax(9, zoomLevelX() / 100)); + while (atomicSize > 0 + && !selectionLargeEnoughToHaveResizeHandlesIfAtomicSize(atomicSize)) { atomicSize--; } @@ -149,22 +139,21 @@ //--------------------------------------------------------------------- // public -bool kpView::selectionLargeEnoughToHaveResizeHandles () const +bool kpView::selectionLargeEnoughToHaveResizeHandles() const { - return (selectionResizeHandleAtomicSize () > 0); + return selectionResizeHandleAtomicSize() > 0; } //--------------------------------------------------------------------- // public -QRegion kpView::selectionResizeHandlesViewRegion (bool forRenderer) const +QRegion kpView::selectionResizeHandlesViewRegion(bool forRenderer) const { - const int atomicLength = selectionResizeHandleAtomicSize (); + const int atomicLength = selectionResizeHandleAtomicSize(); if (atomicLength <= 0) { return {}; } - // HACK: At low zoom (e.g. 100%), resize handles will probably be too // big and overlap text / cursor / too much of selection. // @@ -177,10 +166,8 @@ // at least for text boxes, render text on top of handles. int normalAtomicLength = atomicLength; int vertEdgeAtomicLength = atomicLength; - if (forRenderer && selection ()) - { - if (zoomLevelX () <= 150) - { + if (forRenderer && selection()) { + if (zoomLevelX() <= 150) { if (normalAtomicLength > 1) { normalAtomicLength--; } @@ -191,19 +178,16 @@ } // 1 line of text? - if (textSelection () && textSelection ()->textLines ().size () == 1) - { - if (zoomLevelX () <= 150) { - vertEdgeAtomicLength = qMin (vertEdgeAtomicLength, qMax (2, zoomLevelX () / 100)); - } - else if (zoomLevelX () <= 250) { - vertEdgeAtomicLength = qMin (vertEdgeAtomicLength, qMax (3, zoomLevelX () / 100)); + if (textSelection() && textSelection()->textLines().size() == 1) { + if (zoomLevelX() <= 150) { + vertEdgeAtomicLength = qMin(vertEdgeAtomicLength, qMax(2, zoomLevelX() / 100)); + } else if (zoomLevelX() <= 250) { + vertEdgeAtomicLength = qMin(vertEdgeAtomicLength, qMax(3, zoomLevelX() / 100)); } } } - - const QRect selViewRect = selectionViewRect (); + const QRect selViewRect = selectionViewRect(); QRegion ret; // top left @@ -222,122 +206,110 @@ vertEdgeAtomicLength, vertEdgeAtomicLength); // right middle - ret += QRect(selViewRect.width() - vertEdgeAtomicLength - 1, (selViewRect.height() - vertEdgeAtomicLength) / 2, + ret + += QRect(selViewRect.width() - vertEdgeAtomicLength - 1, + (selViewRect.height() - vertEdgeAtomicLength) / 2, vertEdgeAtomicLength, vertEdgeAtomicLength); // bottom left ret += QRect(0, selViewRect.height() - normalAtomicLength - 1, normalAtomicLength, normalAtomicLength); // bottom middle - ret += QRect((selViewRect.width() - normalAtomicLength) / 2, selViewRect.height() - normalAtomicLength - 1, + ret += QRect((selViewRect.width() - normalAtomicLength) / 2, + selViewRect.height() - normalAtomicLength - 1, normalAtomicLength, normalAtomicLength); // bottom right - ret += QRect(selViewRect.width() - normalAtomicLength - 1, selViewRect.height() - normalAtomicLength - 1, + ret += QRect(selViewRect.width() - normalAtomicLength - 1, + selViewRect.height() - normalAtomicLength - 1, normalAtomicLength, normalAtomicLength); - ret.translate (selViewRect.x (), selViewRect.y ()); - ret = ret.intersected (selViewRect); + ret.translate(selViewRect.x(), selViewRect.y()); + ret = ret.intersected(selViewRect); return ret; } //--------------------------------------------------------------------- // public // REFACTOR: use QFlags as the return type for better type safety. -int kpView::mouseOnSelectionResizeHandle (const QPoint &viewPoint) const +int kpView::mouseOnSelectionResizeHandle(const QPoint &viewPoint) const { #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "kpView::mouseOnSelectionResizeHandle(viewPoint=" - << viewPoint << ")" << endl; + << viewPoint << ")" << endl; #endif - if (!mouseOnSelection (viewPoint)) - { + if (!mouseOnSelection(viewPoint)) { #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tmouse not on sel"; #endif return 0; } - - const QRect selViewRect = selectionViewRect (); + const QRect selViewRect = selectionViewRect(); #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tselViewRect=" << selViewRect; #endif - - const int atomicLength = selectionResizeHandleAtomicSize (); + const int atomicLength = selectionResizeHandleAtomicSize(); #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tatomicLength=" << atomicLength; #endif - if (atomicLength <= 0) - { + if (atomicLength <= 0) { #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tsel not large enough to have resize handles"; #endif // Want to make it possible to move a small selection return 0; } - - const QPoint viewPointRelSel = mouseViewPointRelativeToSelection (viewPoint); + const QPoint viewPointRelSel = mouseViewPointRelativeToSelection(viewPoint); #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tviewPointRelSel=" << viewPointRelSel; #endif - -#define LOCAL_POINT_IN_BOX_AT(x,y) \ - QRect ((x), (y), atomicLength, atomicLength).contains (viewPointRelSel) +#define LOCAL_POINT_IN_BOX_AT(x, y) \ + QRect((x), (y), atomicLength, atomicLength).contains(viewPointRelSel) // Favour the bottom & right and the corners. - if (LOCAL_POINT_IN_BOX_AT (selViewRect.width () - atomicLength, - selViewRect.height () - atomicLength)) - { + if (LOCAL_POINT_IN_BOX_AT(selViewRect.width() - atomicLength, + selViewRect.height() - atomicLength)) { return kpView::Bottom | kpView::Right; } - if (LOCAL_POINT_IN_BOX_AT (selViewRect.width () - atomicLength, 0)) - { + if (LOCAL_POINT_IN_BOX_AT(selViewRect.width() - atomicLength, 0)) { return kpView::Top | kpView::Right; } - if (LOCAL_POINT_IN_BOX_AT (0, selViewRect.height () - atomicLength)) - { + if (LOCAL_POINT_IN_BOX_AT(0, selViewRect.height() - atomicLength)) { return kpView::Bottom | kpView::Left; } - if (LOCAL_POINT_IN_BOX_AT (0, 0)) - { + if (LOCAL_POINT_IN_BOX_AT(0, 0)) { return kpView::Top | kpView::Left; } - if (LOCAL_POINT_IN_BOX_AT (selViewRect.width () - atomicLength, - (selViewRect.height () - atomicLength) / 2)) - { + if (LOCAL_POINT_IN_BOX_AT(selViewRect.width() - atomicLength, + (selViewRect.height() - atomicLength) / 2)) { return kpView::Right; } - if (LOCAL_POINT_IN_BOX_AT ((selViewRect.width () - atomicLength) / 2, - selViewRect.height () - atomicLength)) - { + if (LOCAL_POINT_IN_BOX_AT((selViewRect.width() - atomicLength) / 2, + selViewRect.height() - atomicLength)) { return kpView::Bottom; } - if (LOCAL_POINT_IN_BOX_AT ((selViewRect.width () - atomicLength) / 2, 0)) - { + if (LOCAL_POINT_IN_BOX_AT((selViewRect.width() - atomicLength) / 2, 0)) { return kpView::Top; } - if (LOCAL_POINT_IN_BOX_AT (0, (selViewRect.height () - atomicLength) / 2)) - { + if (LOCAL_POINT_IN_BOX_AT(0, (selViewRect.height() - atomicLength) / 2)) { return kpView::Left; - } - else - { + } else { #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tnot on sel resize handle"; #endif @@ -347,35 +319,33 @@ } // public -bool kpView::mouseOnSelectionToSelectText (const QPoint &viewPoint) const +bool kpView::mouseOnSelectionToSelectText(const QPoint &viewPoint) const { #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "kpView::mouseOnSelectionToSelectText(viewPoint=" - << viewPoint << ")" << endl; + << viewPoint << ")" << endl; #endif - if (!mouseOnSelection (viewPoint)) - { + if (!mouseOnSelection(viewPoint)) { #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tmouse non on sel"; #endif return false; } - if (!textSelection ()) - { + if (!textSelection()) { #if DEBUG_KP_VIEW qCDebug(kpLogViews) << "\tsel not text"; #endif return false; } #if DEBUG_KP_VIEW - qCDebug(kpLogViews) << "\tmouse on sel: to move=" << mouseOnSelectionToMove () - << " to resize=" << mouseOnSelectionResizeHandle () - << endl; + qCDebug(kpLogViews) << "\tmouse on sel: to move=" << mouseOnSelectionToMove() + << " to resize=" << mouseOnSelectionResizeHandle() + << endl; #endif - return (!mouseOnSelectionToMove (viewPoint) && - !mouseOnSelectionResizeHandle (viewPoint)); + return !mouseOnSelectionToMove(viewPoint) + && !mouseOnSelectionResizeHandle(viewPoint); } diff --git a/views/kpZoomedThumbnailView.h b/views/kpZoomedThumbnailView.h --- a/views/kpZoomedThumbnailView.h +++ b/views/kpZoomedThumbnailView.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_ZOOMED_THUMBNAIL_VIEW_H #define KP_ZOOMED_THUMBNAIL_VIEW_H - #include "kpThumbnailView.h" - /** * @short Zoomed thumbnail view of a document. * @@ -49,30 +45,25 @@ */ /*sealed*/ class kpZoomedThumbnailView : public kpThumbnailView { -Q_OBJECT + Q_OBJECT public: /** * Constructs a zoomed thumbnail view. */ - kpZoomedThumbnailView (kpDocument *document, - kpToolToolBar *toolToolBar, - kpViewManager *viewManager, - kpView *buddyView, - kpViewScrollableContainer *scrollableContainer, - QWidget *parent); + kpZoomedThumbnailView (kpDocument *document, kpToolToolBar *toolToolBar, + kpViewManager *viewManager, kpView *buddyView, + kpViewScrollableContainer *scrollableContainer, QWidget *parent); /** * Destructs a zoomed thumbnail view. */ ~kpZoomedThumbnailView () override; - /** * Implements @ref kpThumbnailView. */ - QString caption () const override; - + QString caption() const override; public slots: /** @@ -84,12 +75,10 @@ * * Implements @ref kpView. */ - void adjustToEnvironment () override; - + void adjustToEnvironment() override; private: struct kpZoomedThumbnailViewPrivate *d; }; - #endif // KP_ZOOMED_THUMBNAIL_VIEW_H diff --git a/views/kpZoomedThumbnailView.cpp b/views/kpZoomedThumbnailView.cpp --- a/views/kpZoomedThumbnailView.cpp +++ b/views/kpZoomedThumbnailView.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_ZOOMED_THUMBNAIL_VIEW 0 - #include "views/kpZoomedThumbnailView.h" #include "kpLogCategories.h" @@ -39,106 +36,94 @@ //-------------------------------------------------------------------------------- -kpZoomedThumbnailView::kpZoomedThumbnailView (kpDocument *document, - kpToolToolBar *toolToolBar, - kpViewManager *viewManager, - kpView *buddyView, - kpViewScrollableContainer *scrollableContainer, - QWidget *parent ) - - : kpThumbnailView (document, toolToolBar, viewManager, - buddyView, - scrollableContainer, - parent) +kpZoomedThumbnailView::kpZoomedThumbnailView (kpDocument *document, kpToolToolBar *toolToolBar, + kpViewManager *viewManager, kpView *buddyView, + kpViewScrollableContainer *scrollableContainer, + QWidget *parent) + + : kpThumbnailView(document, toolToolBar, viewManager, + buddyView, + scrollableContainer, + parent) { // Call to virtual function - this is why the class is sealed - adjustToEnvironment (); + adjustToEnvironment(); } - kpZoomedThumbnailView::~kpZoomedThumbnailView () = default; - // public virtual [base kpThumbnailView] -QString kpZoomedThumbnailView::caption () const +QString kpZoomedThumbnailView::caption() const { - return i18n ("%1% - Thumbnail", zoomLevelX ()); + return i18n("%1% - Thumbnail", zoomLevelX()); } - // public slot virtual [base kpView] -void kpZoomedThumbnailView::adjustToEnvironment () +void kpZoomedThumbnailView::adjustToEnvironment() { #if DEBUG_KP_ZOOMED_THUMBNAIL_VIEW - qCDebug(kpLogViews) << "kpZoomedThumbnailView(" << name () - << ")::adjustToEnvironment()" - << " width=" << width () - << " height=" << height () - << endl; + qCDebug(kpLogViews) << "kpZoomedThumbnailView(" << name() + << ")::adjustToEnvironment()" + << " width=" << width() + << " height=" << height() + << endl; #endif - if (!document ()) { + if (!document()) { return; } #if DEBUG_KP_ZOOMED_THUMBNAIL_VIEW - qCDebug(kpLogViews) << "\tdoc: width=" << document ()->width () - << " height=" << document ()->height () - << endl; + qCDebug(kpLogViews) << "\tdoc: width=" << document()->width() + << " height=" << document()->height() + << endl; #endif - if (document ()->width () <= 0 || document ()->height () <= 0) - { + if (document()->width() <= 0 || document()->height() <= 0) { qCCritical(kpLogViews) << "kpZoomedThumbnailView::adjustToEnvironment() doc:" - << " width=" << document ()->width () - << " height=" << document ()->height (); + << " width=" << document()->width() + << " height=" << document()->height(); return; } - - int hzoom = qMax (1, width () * 100 / document ()->width ()); - int vzoom = qMax (1, height () * 100 / document ()->height ()); + int hzoom = qMax(1, width() * 100 / document()->width()); + int vzoom = qMax(1, height() * 100 / document()->height()); // keep aspect ratio if (hzoom < vzoom) { vzoom = hzoom; - } - else { + } else { hzoom = vzoom; } #if DEBUG_KP_ZOOMED_THUMBNAIL_VIEW && 1 qCDebug(kpLogViews) << "\tproposed zoom=" << hzoom; #endif - if (hzoom > 100 || vzoom > 100) - { + if (hzoom > 100 || vzoom > 100) { #if DEBUG_KP_ZOOMED_THUMBNAIL_VIEW && 1 qCDebug(kpLogViews) << "\twon't magnify - setting zoom to 100%"; #endif hzoom = 100; vzoom = 100; } - - if (viewManager ()) { - viewManager ()->setQueueUpdates (); + if (viewManager()) { + viewManager()->setQueueUpdates(); } { - setZoomLevel (hzoom, vzoom); + setZoomLevel(hzoom, vzoom); - setOrigin (QPoint ((width () - zoomedDocWidth ()) / 2, - (height () - zoomedDocHeight ()) / 2)); - setMaskToCoverDocument (); + setOrigin(QPoint((width() - zoomedDocWidth()) / 2, + (height() - zoomedDocHeight()) / 2)); + setMaskToCoverDocument(); - if (viewManager ()) { - viewManager ()->updateView (this); + if (viewManager()) { + viewManager()->updateView(this); } } - if (viewManager ()) { - viewManager ()->restoreQueueUpdates (); + if (viewManager()) { + viewManager()->restoreQueueUpdates(); } } - - diff --git a/views/kpZoomedView.h b/views/kpZoomedView.h --- a/views/kpZoomedView.h +++ b/views/kpZoomedView.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_ZOOMED_VIEW_H #define KP_ZOOMED_VIEW_H - #include "views/kpView.h" - /** * @short Zoomed view of a document. Suitable as an ordinary editing view. * @@ -50,30 +46,25 @@ */ /*sealed*/ class kpZoomedView : public kpView { -Q_OBJECT + Q_OBJECT public: /** * Constructs a zoomed view. */ - kpZoomedView (kpDocument *document, - kpToolToolBar *toolToolBar, - kpViewManager *viewManager, - kpView *buddyView, - kpViewScrollableContainer *scrollableContainer, + kpZoomedView (kpDocument *document, kpToolToolBar *toolToolBar, kpViewManager *viewManager, + kpView *buddyView, kpViewScrollableContainer *scrollableContainer, QWidget *parent); /** * Destructs an unzoomed view. */ ~kpZoomedView () override; - /** * Extends @kpView. Calls adjustToEnvironment(). */ - void setZoomLevel (int hzoom, int vzoom) override; - + void setZoomLevel(int hzoom, int vzoom) override; public slots: /** @@ -85,12 +76,10 @@ * * Implements @ref kpView. */ - void adjustToEnvironment () override; - + void adjustToEnvironment() override; private: struct kpZoomedViewPrivate *d; }; - #endif // KP_ZOOMED_VIEW_H diff --git a/views/kpZoomedView.cpp b/views/kpZoomedView.cpp --- a/views/kpZoomedView.cpp +++ b/views/kpZoomedView.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,78 +24,67 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_ZOOMED_VIEW 0 - #include "views/kpZoomedView.h" #include "kpLogCategories.h" #include "document/kpDocument.h" #include "views/kpView.h" #include "views/manager/kpViewManager.h" +kpZoomedView::kpZoomedView (kpDocument *document, kpToolToolBar *toolToolBar, + kpViewManager *viewManager, kpView *buddyView, + kpViewScrollableContainer *scrollableContainer, QWidget *parent) -kpZoomedView::kpZoomedView (kpDocument *document, - kpToolToolBar *toolToolBar, - kpViewManager *viewManager, - kpView *buddyView, - kpViewScrollableContainer *scrollableContainer, - QWidget *parent) - - : kpView (document, toolToolBar, viewManager, - buddyView, - scrollableContainer, - parent) + : kpView(document, toolToolBar, viewManager, + buddyView, + scrollableContainer, + parent) { // Call to virtual function - this is why the class is sealed - adjustToEnvironment (); + adjustToEnvironment(); } kpZoomedView::~kpZoomedView () = default; - // public virtual [base kpView] -void kpZoomedView::setZoomLevel (int hzoom, int vzoom) +void kpZoomedView::setZoomLevel(int hzoom, int vzoom) { #if DEBUG_KP_ZOOMED_VIEW - qCDebug(kpLogViews) << "kpZoomedView(" << name () << ")::setZoomLevel(" - << hzoom << "," << vzoom << ")" << endl; + qCDebug(kpLogViews) << "kpZoomedView(" << name() << ")::setZoomLevel(" + << hzoom << "," << vzoom << ")" << endl; #endif - if (viewManager ()) { - viewManager ()->setQueueUpdates (); + if (viewManager()) { + viewManager()->setQueueUpdates(); } { - kpView::setZoomLevel (hzoom, vzoom); + kpView::setZoomLevel(hzoom, vzoom); - adjustToEnvironment (); + adjustToEnvironment(); } - if (viewManager ()) { - viewManager ()->restoreQueueUpdates (); + if (viewManager()) { + viewManager()->restoreQueueUpdates(); } } - // public slot virtual [base kpView] -void kpZoomedView::adjustToEnvironment () +void kpZoomedView::adjustToEnvironment() { #if DEBUG_KP_ZOOMED_VIEW - qCDebug(kpLogViews) << "kpZoomedView(" << name () << ")::adjustToEnvironment()" - << " doc: width=" << document ()->width () - << " height=" << document ()->height () - << endl; + qCDebug(kpLogViews) << "kpZoomedView(" << name() << ")::adjustToEnvironment()" + << " doc: width=" << document()->width() + << " height=" << document()->height() + << endl; #endif - if (document ()) - { + if (document()) { // TODO: use zoomedDocWidth() & zoomedDocHeight()? - resize (static_cast (transformDocToViewX (document ()->width ())), - static_cast (transformDocToViewY (document ()->height ()))); + resize(static_cast(transformDocToViewX(document()->width())), + static_cast(transformDocToViewY(document()->height()))); } } - - diff --git a/views/manager/kpViewManager.h b/views/manager/kpViewManager.h --- a/views/manager/kpViewManager.h +++ b/views/manager/kpViewManager.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_VIEW_MANAGER_H #define KP_VIEW_MANAGER_H - #include - class QCursor; class QRegion; class QRect; @@ -42,36 +38,32 @@ class kpMainWindow; class kpTempImage; - class kpViewManager : public QObject { -Q_OBJECT + Q_OBJECT public: kpViewManager (kpMainWindow *mainWindow); ~kpViewManager () override; - private: - kpDocument *document () const; - + kpDocument *document() const; // // Registering views // public: - void registerView (kpView *view); - void unregisterView (kpView *view); - void unregisterAllViews (); - + void registerView(kpView *view); + void unregisterView(kpView *view); + void unregisterAllViews(); // // View // public: - kpView *viewUnderCursor (bool usingQt = false) const; + kpView *viewUnderCursor(bool usingQt = false) const; // // QWidget::hasMouse() is unreliable: @@ -90,46 +82,41 @@ // as a reasonable replacement (although there is at least one case where // it still won't work - just after a fake drag onto the view). // - void setViewUnderCursor (kpView *view); - + void setViewUnderCursor(kpView *view); public: // Returns whether at least 1 view has keyboard focus. // A pointer is not returned to such a view because more than one can // have focus at the same time (see QWidget::isActiveWindow()). - bool hasAViewWithFocus () const; - + bool hasAViewWithFocus() const; // // Mouse Cursors // public: - void setCursor (const QCursor &cursor); - void unsetCursor (); - + void setCursor(const QCursor &cursor); + void unsetCursor(); // // Temp Image // public: - const kpTempImage *tempImage () const; - void setTempImage (const kpTempImage &tempImage); - void invalidateTempImage (); - + const kpTempImage *tempImage() const; + void setTempImage(const kpTempImage &tempImage); + void invalidateTempImage(); // // Selections // public: - bool selectionBorderVisible () const; - void setSelectionBorderVisible (bool yes = true); - - bool selectionBorderFinished () const; - void setSelectionBorderFinished (bool yes = true); + bool selectionBorderVisible() const; + void setSelectionBorderVisible(bool yes = true); + bool selectionBorderFinished() const; + void setSelectionBorderFinished(bool yes = true); // // Text Cursor @@ -140,20 +127,20 @@ // the text cursor. If no text selection is active, the update will // be a NOP but the timer will still tick and textCursorEnabled() will // still return true. - bool textCursorEnabled () const; - void setTextCursorEnabled (bool yes = true); + bool textCursorEnabled() const; + void setTextCursorEnabled(bool yes = true); - bool textCursorBlinkState () const; - void setTextCursorBlinkState (bool on = true); + bool textCursorBlinkState() const; + void setTextCursorBlinkState(bool on = true); // By convention, a text box with no content (i.e. no text lines) should // have a cursor position of (row=0,col=0). Some code assumes this. // // (no error checking is performed - the row and col are as per // setTextCursorPosition() so may be out of the bounds of the // text selection) - int textCursorRow () const; - int textCursorCol () const; + int textCursorRow() const; + int textCursorCol() const; // See kpToolText::beginDrawSelectText() for a correct use of this // method, satisfying the above convention. // @@ -165,7 +152,7 @@ // Always ensure that the text cursor position is valid. // TODO: We need to check this in all source files. // e.g. It's definitely wrong for kpToolTextBackspaceCommand. - void setTextCursorPosition (int row, int col); + void setTextCursorPosition(int row, int col); // Returns the document rectangle where cursor would be placed, using // textCursorRow() and textCursorCol (). @@ -175,18 +162,17 @@ // // If there is no text selection or textCursorRow() or // textCursorCol() are invalid, it returns an empty rectangle. - QRect textCursorRect () const; + QRect textCursorRect() const; protected: // If textCursorRect() is valid, updates all views at that rectangle. // The cursor blink state and timer are not affected at all. // TODO: This and other methods will happily execute even if // !textCursorEnabled(). We should fix this. - void updateTextCursor (); + void updateTextCursor(); protected slots: - void slotTextCursorBlink (); - + void slotTextCursorBlink(); // // View Updates @@ -204,9 +190,9 @@ // only the _regions_ that need to be repainted. // // You can nest blocks of setQueueUpdates()/restoreQueueUpdates(). - bool queueUpdates () const; - void setQueueUpdates (); - void restoreQueueUpdates (); + bool queueUpdates() const; + void setQueueUpdates(); + void restoreQueueUpdates(); public: // Controls behaviour of updateViews(): @@ -225,30 +211,28 @@ // unnecessary redraws and incredibly slugish performance. // // You can nest blocks of setFastUpdates()/restoreFastUpdates(). - bool fastUpdates () const; - void setFastUpdates (); - void restoreFastUpdates (); + bool fastUpdates() const; + void setFastUpdates(); + void restoreFastUpdates(); public slots: - void updateView (kpView *v); - void updateView (kpView *v, const QRect &viewRect); - void updateView (kpView *v, int x, int y, int w, int h); - void updateView (kpView *v, const QRegion &viewRegion); + void updateView(kpView *v); + void updateView(kpView *v, const QRect &viewRect); + void updateView(kpView *v, int x, int y, int w, int h); + void updateView(kpView *v, const QRegion &viewRegion); - void updateViewRectangleEdges (kpView *v, const QRect &viewRect); - - void updateViews (const QRect &docRect); + void updateViewRectangleEdges(kpView *v, const QRect &viewRect); + void updateViews(const QRect &docRect); public slots: - void adjustViewsToEnvironment (); + void adjustViewsToEnvironment(); public slots: - void setInputMethodEnabled (bool inputMethodEnabled); + void setInputMethodEnabled(bool inputMethodEnabled); private: - struct kpViewManagerPrivate * const d; + struct kpViewManagerPrivate *const d; }; - #endif // KP_VIEW_MANAGER_H diff --git a/views/manager/kpViewManager.cpp b/views/manager/kpViewManager.cpp --- a/views/manager/kpViewManager.cpp +++ b/views/manager/kpViewManager.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_VIEW_MANAGER 0 - #include "views/manager/kpViewManager.h" #include "kpViewManagerPrivate.h" @@ -49,9 +46,9 @@ //--------------------------------------------------------------------- kpViewManager::kpViewManager (kpMainWindow *mainWindow) - : d (new kpViewManagerPrivate ()) + : d(new kpViewManagerPrivate()) { - Q_ASSERT (mainWindow); + Q_ASSERT(mainWindow); d->mainWindow = mainWindow; @@ -65,15 +62,13 @@ d->selectionBorderVisible = false; d->selectionBorderFinished = false; - d->textCursorBlinkTimer = nullptr; d->textCursorRow = -1; d->textCursorCol = -1; d->textCursorBlinkState = true; - d->queueUpdatesCounter = d->fastUpdatesCounter = 0; d->inputMethodEnabled = false; @@ -83,80 +78,77 @@ kpViewManager::~kpViewManager () { - unregisterAllViews (); + unregisterAllViews(); delete d->tempImage; delete d; } //--------------------------------------------------------------------- // private -kpDocument *kpViewManager::document () const +kpDocument *kpViewManager::document() const { - return d->mainWindow->document (); + return d->mainWindow->document(); } //--------------------------------------------------------------------- // public -void kpViewManager::registerView (kpView *view) +void kpViewManager::registerView(kpView *view) { #if DEBUG_KP_VIEW_MANAGER && 1 qCDebug(kpLogViews) << "kpViewManager::registerView (" << view << ")"; #endif - Q_ASSERT (view); - Q_ASSERT (!d->views.contains (view)); + Q_ASSERT(view); + Q_ASSERT(!d->views.contains(view)); #if DEBUG_KP_VIEW_MANAGER && 1 qCDebug(kpLogViews) << "\tadded view"; #endif - view->setCursor (d->cursor); - d->views.append (view); + view->setCursor(d->cursor); + d->views.append(view); } //--------------------------------------------------------------------- // public -void kpViewManager::unregisterView (kpView *view) +void kpViewManager::unregisterView(kpView *view) { - Q_ASSERT (view); - Q_ASSERT (d->views.contains (view)); + Q_ASSERT(view); + Q_ASSERT(d->views.contains(view)); if (view == d->viewUnderCursor) { d->viewUnderCursor = nullptr; } - view->unsetCursor (); - d->views.removeAll (view); + view->unsetCursor(); + d->views.removeAll(view); } //--------------------------------------------------------------------- // public -void kpViewManager::unregisterAllViews () +void kpViewManager::unregisterAllViews() { - d->views.clear (); + d->views.clear(); } //--------------------------------------------------------------------- // public -kpView *kpViewManager::viewUnderCursor (bool usingQt) const +kpView *kpViewManager::viewUnderCursor(bool usingQt) const { - if (!usingQt) - { - Q_ASSERT (!d->viewUnderCursor || d->views.contains (d->viewUnderCursor)); + if (!usingQt) { + Q_ASSERT(!d->viewUnderCursor || d->views.contains(d->viewUnderCursor)); return d->viewUnderCursor; } - - for (QLinkedList ::const_iterator it = d->views.begin (); - it != d->views.end (); - ++it) - { - if ((*it)->underMouse ()) { - return (*it); + for (QLinkedList ::const_iterator it = d->views.begin(); + it != d->views.end(); + ++it) { + if ((*it)->underMouse()) { + return *it; } } @@ -166,56 +158,51 @@ //--------------------------------------------------------------------- // public -void kpViewManager::setViewUnderCursor (kpView *view) +void kpViewManager::setViewUnderCursor(kpView *view) { #if DEBUG_KP_VIEW_MANAGER && 1 qCDebug(kpLogViews) << "kpViewManager::setViewUnderCursor (" - << (view ? view->objectName () : "(none)") << ")" - << " old=" << (d->viewUnderCursor ? d->viewUnderCursor->objectName () : "(none)"); + << (view ? view->objectName() : "(none)") << ")" + << " old=" + << (d->viewUnderCursor ? d->viewUnderCursor->objectName() : "(none)"); #endif if (view == d->viewUnderCursor) { return; } d->viewUnderCursor = view; if (d->viewUnderCursor) { - d->viewUnderCursor->setAttribute (Qt::WA_InputMethodEnabled, d->inputMethodEnabled); + d->viewUnderCursor->setAttribute(Qt::WA_InputMethodEnabled, d->inputMethodEnabled); } - if (!d->viewUnderCursor) - { + if (!d->viewUnderCursor) { // Hide the brush if the mouse cursor just left the view. - if (d->tempImage && d->tempImage->isBrush ()) - { + if (d->tempImage && d->tempImage->isBrush()) { #if DEBUG_KP_VIEW_MANAGER && 1 qCDebug(kpLogViews) << "\thiding brush pixmap since cursor left view"; #endif - updateViews (d->tempImage->rect ()); + updateViews(d->tempImage->rect()); } - } - else - { - if (d->mainWindow->tool ()) - { + } else { + if (d->mainWindow->tool()) { #if DEBUG_KP_VIEW_MANAGER && 1 qCDebug(kpLogViews) << "\tnotify tool that something changed below cursor"; #endif - d->mainWindow->tool ()->somethingBelowTheCursorChanged (); + d->mainWindow->tool()->somethingBelowTheCursorChanged(); } } } //--------------------------------------------------------------------- // public -bool kpViewManager::hasAViewWithFocus () const +bool kpViewManager::hasAViewWithFocus() const { - for (QLinkedList ::const_iterator it = d->views.begin (); - it != d->views.end (); - ++it) - { - if ((*it)->isActiveWindow ()) { + for (QLinkedList ::const_iterator it = d->views.begin(); + it != d->views.end(); + ++it) { + if ((*it)->isActiveWindow()) { return true; } } @@ -226,149 +213,145 @@ //--------------------------------------------------------------------- // public -void kpViewManager::setCursor (const QCursor &cursor) +void kpViewManager::setCursor(const QCursor &cursor) { - for (QLinkedList ::const_iterator it = d->views.begin (); - it != d->views.end (); - ++it) - { - (*it)->setCursor (cursor); + for (QLinkedList ::const_iterator it = d->views.begin(); + it != d->views.end(); + ++it) { + (*it)->setCursor(cursor); } d->cursor = cursor; } //--------------------------------------------------------------------- // public -void kpViewManager::unsetCursor () +void kpViewManager::unsetCursor() { - for (QLinkedList ::const_iterator it = d->views.begin (); - it != d->views.end (); - ++it) - { - (*it)->unsetCursor (); + for (QLinkedList ::const_iterator it = d->views.begin(); + it != d->views.end(); + ++it) { + (*it)->unsetCursor(); } - d->cursor = QCursor (); + d->cursor = QCursor(); } //--------------------------------------------------------------------- // public -const kpTempImage *kpViewManager::tempImage () const +const kpTempImage *kpViewManager::tempImage() const { return d->tempImage; } //--------------------------------------------------------------------- // public -void kpViewManager::setTempImage (const kpTempImage &tempImage) +void kpViewManager::setTempImage(const kpTempImage &tempImage) { #if DEBUG_KP_VIEW_MANAGER qCDebug(kpLogViews) << "kpViewManager::setTempImage(isBrush=" - << tempImage.isBrush () - << ",topLeft=" << tempImage.topLeft () - << ",image.rect=" << tempImage.image ().rect () - << ")"; + << tempImage.isBrush() + << ",topLeft=" << tempImage.topLeft() + << ",image.rect=" << tempImage.image().rect() + << ")"; #endif QRect oldRect; - if (d->tempImage) - { - oldRect = d->tempImage->rect (); + if (d->tempImage) { + oldRect = d->tempImage->rect(); delete d->tempImage; d->tempImage = nullptr; } - d->tempImage = new kpTempImage (tempImage); + d->tempImage = new kpTempImage(tempImage); - setQueueUpdates (); + setQueueUpdates(); { - if (oldRect.isValid ()) { - updateViews (oldRect); + if (oldRect.isValid()) { + updateViews(oldRect); } - updateViews (d->tempImage->rect ()); + updateViews(d->tempImage->rect()); } - restoreQueueUpdates (); + restoreQueueUpdates(); } //--------------------------------------------------------------------- // public -void kpViewManager::invalidateTempImage () +void kpViewManager::invalidateTempImage() { if (!d->tempImage) { return; } - QRect oldRect = d->tempImage->rect (); + QRect oldRect = d->tempImage->rect(); delete d->tempImage; d->tempImage = nullptr; - updateViews (oldRect); + updateViews(oldRect); } //--------------------------------------------------------------------- // public -bool kpViewManager::selectionBorderVisible () const +bool kpViewManager::selectionBorderVisible() const { return d->selectionBorderVisible; } //--------------------------------------------------------------------- // public -void kpViewManager::setSelectionBorderVisible (bool yes) +void kpViewManager::setSelectionBorderVisible(bool yes) { if (d->selectionBorderVisible == yes) { return; } d->selectionBorderVisible = yes; - if (document ()->selection ()) { - updateViews (document ()->selection ()->boundingRect ()); + if (document()->selection()) { + updateViews(document()->selection()->boundingRect()); } } //--------------------------------------------------------------------- // public -bool kpViewManager::selectionBorderFinished () const +bool kpViewManager::selectionBorderFinished() const { return d->selectionBorderFinished; } //--------------------------------------------------------------------- // public -void kpViewManager::setSelectionBorderFinished (bool yes) +void kpViewManager::setSelectionBorderFinished(bool yes) { if (d->selectionBorderFinished == yes) { return; } d->selectionBorderFinished = yes; - if (document ()->selection ()) { - updateViews (document ()->selection ()->boundingRect ()); + if (document()->selection()) { + updateViews(document()->selection()->boundingRect()); } } //--------------------------------------------------------------------- -void kpViewManager::setInputMethodEnabled (bool inputMethodEnabled) +void kpViewManager::setInputMethodEnabled(bool inputMethodEnabled) { d->inputMethodEnabled = inputMethodEnabled; if (d->viewUnderCursor) { - d->viewUnderCursor->setAttribute (Qt::WA_InputMethodEnabled, inputMethodEnabled); + d->viewUnderCursor->setAttribute(Qt::WA_InputMethodEnabled, inputMethodEnabled); } } //--------------------------------------------------------------------- - diff --git a/views/manager/kpViewManagerPrivate.h b/views/manager/kpViewManagerPrivate.h --- a/views/manager/kpViewManagerPrivate.h +++ b/views/manager/kpViewManagerPrivate.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,20 +24,16 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpViewManagerPrivate_H #define kpViewManagerPrivate_H - #include #include - class kpMainWindow; class QTimer; class kpView; - struct kpViewManagerPrivate { kpMainWindow *mainWindow; @@ -53,7 +48,6 @@ bool selectionBorderVisible; bool selectionBorderFinished; - // // Text Cursor // @@ -67,7 +61,6 @@ // (undefined if there is not currently a text selection) bool textCursorBlinkState; - // // View Updates // @@ -81,5 +74,4 @@ bool inputMethodEnabled; }; - #endif // kpViewManagerPrivate_H diff --git a/views/manager/kpViewManager_TextCursor.cpp b/views/manager/kpViewManager_TextCursor.cpp --- a/views/manager/kpViewManager_TextCursor.cpp +++ b/views/manager/kpViewManager_TextCursor.cpp @@ -1,4 +1,3 @@ - // TODO: This is bad design as it's easy to get out of sync with the selection. // e.g. You could have textCursorEnabled() but no text selection or // vice versa. And the cursor could be outside of the selection. @@ -43,10 +42,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_VIEW_MANAGER 0 - #include "kpViewManager.h" #include "kpViewManagerPrivate.h" @@ -65,170 +62,163 @@ #include "tools/kpTool.h" #include "views/kpView.h" - // public -bool kpViewManager::textCursorEnabled () const +bool kpViewManager::textCursorEnabled() const { - return static_cast (d->textCursorBlinkTimer); + return static_cast(d->textCursorBlinkTimer); } // public -void kpViewManager::setTextCursorEnabled (bool yes) +void kpViewManager::setTextCursorEnabled(bool yes) { #if DEBUG_KP_VIEW_MANAGER && 1 qCDebug(kpLogViews) << "kpViewManager::setTextCursorEnabled(" << yes << ")"; #endif - if (yes == textCursorEnabled ()) { + if (yes == textCursorEnabled()) { return; } delete d->textCursorBlinkTimer; d->textCursorBlinkTimer = nullptr; - setFastUpdates (); - setQueueUpdates (); + setFastUpdates(); + setQueueUpdates(); { - if (yes) - { - d->textCursorBlinkTimer = new QTimer (this); - d->textCursorBlinkTimer->setSingleShot (true); - connect (d->textCursorBlinkTimer, &QTimer::timeout, this, &kpViewManager::slotTextCursorBlink); + if (yes) { + d->textCursorBlinkTimer = new QTimer(this); + d->textCursorBlinkTimer->setSingleShot(true); + connect(d->textCursorBlinkTimer, &QTimer::timeout, this, + &kpViewManager::slotTextCursorBlink); d->textCursorBlinkState = true; - slotTextCursorBlink (); - } - else - { + slotTextCursorBlink(); + } else { d->textCursorBlinkState = false; - updateTextCursor (); + updateTextCursor(); } } - restoreQueueUpdates (); - restoreFastUpdates (); + restoreQueueUpdates(); + restoreFastUpdates(); } - // public -bool kpViewManager::textCursorBlinkState () const +bool kpViewManager::textCursorBlinkState() const { return d->textCursorBlinkState; } // public -void kpViewManager::setTextCursorBlinkState (bool on) +void kpViewManager::setTextCursorBlinkState(bool on) { if (on == d->textCursorBlinkState) { return; } d->textCursorBlinkState = on; - updateTextCursor (); + updateTextCursor(); } - // public -int kpViewManager::textCursorRow () const +int kpViewManager::textCursorRow() const { return d->textCursorRow; } // public -int kpViewManager::textCursorCol () const +int kpViewManager::textCursorCol() const { return d->textCursorCol; } // public -void kpViewManager::setTextCursorPosition (int row, int col) +void kpViewManager::setTextCursorPosition(int row, int col) { if (row == d->textCursorRow && col == d->textCursorCol) { return; } - setFastUpdates (); - setQueueUpdates (); + setFastUpdates(); + setQueueUpdates(); { // Clear the old cursor. d->textCursorBlinkState = false; - updateTextCursor (); + updateTextCursor(); d->textCursorRow = row; d->textCursorCol = col; // Render the new cursor. d->textCursorBlinkState = true; - updateTextCursor (); + updateTextCursor(); } - restoreQueueUpdates (); - restoreFastUpdates (); + restoreQueueUpdates(); + restoreFastUpdates(); } - // public -QRect kpViewManager::textCursorRect () const +QRect kpViewManager::textCursorRect() const { - kpTextSelection *textSel = document ()->textSelection (); + kpTextSelection *textSel = document()->textSelection(); if (!textSel) { return {}; } - QPoint topLeft = textSel->pointForTextRowCol (d->textCursorRow, d->textCursorCol); - if (topLeft == KP_INVALID_POINT) - { + QPoint topLeft = textSel->pointForTextRowCol(d->textCursorRow, d->textCursorCol); + if (topLeft == KP_INVALID_POINT) { // Text cursor row/col hasn't been specified yet? - if (textSel->hasContent ()) { + if (textSel->hasContent()) { return {}; } // Empty text box should still display a cursor so that the user // knows where typed text will go. - topLeft = textSel->textAreaRect ().topLeft (); + topLeft = textSel->textAreaRect().topLeft(); } - Q_ASSERT (topLeft != KP_INVALID_POINT); + Q_ASSERT(topLeft != KP_INVALID_POINT); - return {topLeft.x (), topLeft.y (), - 1, textSel->textStyle ().fontMetrics ().height ()}; + return { + topLeft.x(), topLeft.y(), + 1, textSel->textStyle().fontMetrics().height() + }; } - // protected -void kpViewManager::updateTextCursor () +void kpViewManager::updateTextCursor() { #if DEBUG_KP_VIEW_MANAGER && 0 qCDebug(kpLogViews) << "kpViewManager::updateTextCursor()"; #endif - const QRect r = textCursorRect (); - if (!r.isValid ()) { + const QRect r = textCursorRect(); + if (!r.isValid()) { return; } - setFastUpdates (); + setFastUpdates(); { // If !textCursorEnabled(), this will clear. - updateViews (r); + updateViews(r); } - restoreFastUpdates (); + restoreFastUpdates(); } // protected slot -void kpViewManager::slotTextCursorBlink () +void kpViewManager::slotTextCursorBlink() { #if DEBUG_KP_VIEW_MANAGER && 0 qCDebug(kpLogViews) << "kpViewManager::slotTextCursorBlink() cursorBlinkState=" - << d->textCursorBlinkState; + << d->textCursorBlinkState; #endif - if (d->textCursorBlinkTimer) - { + if (d->textCursorBlinkTimer) { // (single shot) - d->textCursorBlinkTimer->start (QApplication::cursorFlashTime () / 2); + d->textCursorBlinkTimer->start(QApplication::cursorFlashTime() / 2); } - updateTextCursor (); + updateTextCursor(); // TODO: Shouldn't this be done _before_ updating the text cursor // because textCursorBlinkState() is supposed to reflect what // updateTextCursor() just rendered, until the next timer tick? diff --git a/views/manager/kpViewManager_ViewUpdates.cpp b/views/manager/kpViewManager_ViewUpdates.cpp --- a/views/manager/kpViewManager_ViewUpdates.cpp +++ b/views/manager/kpViewManager_ViewUpdates.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_VIEW_MANAGER 0 - #include "views/manager/kpViewManager.h" #include "kpViewManagerPrivate.h" @@ -46,215 +43,194 @@ #include "tools/kpTool.h" #include "views/kpView.h" - // public slot -bool kpViewManager::queueUpdates () const +bool kpViewManager::queueUpdates() const { - return (d->queueUpdatesCounter > 0); + return d->queueUpdatesCounter > 0; } // public slot -void kpViewManager::setQueueUpdates () +void kpViewManager::setQueueUpdates() { d->queueUpdatesCounter++; #if DEBUG_KP_VIEW_MANAGER && 1 qCDebug(kpLogViews) << "kpViewManager::setQueueUpdates() counter=" - << d->queueUpdatesCounter << endl; + << d->queueUpdatesCounter << endl; #endif } // public slot -void kpViewManager::restoreQueueUpdates () +void kpViewManager::restoreQueueUpdates() { d->queueUpdatesCounter--; #if DEBUG_KP_VIEW_MANAGER && 1 qCDebug(kpLogViews) << "kpViewManager::restoreQueueUpdates() counter=" - << d->queueUpdatesCounter; + << d->queueUpdatesCounter; #endif - Q_ASSERT (d->queueUpdatesCounter >= 0); - - if (d->queueUpdatesCounter == 0) - { - for (QLinkedList ::const_iterator it = d->views.begin (); - it != d->views.end (); - ++it) - { - (*it)->updateQueuedArea (); + Q_ASSERT(d->queueUpdatesCounter >= 0); + + if (d->queueUpdatesCounter == 0) { + for (QLinkedList ::const_iterator it = d->views.begin(); + it != d->views.end(); + ++it) { + (*it)->updateQueuedArea(); } } } - // public slot -bool kpViewManager::fastUpdates () const +bool kpViewManager::fastUpdates() const { - return (d->fastUpdatesCounter > 0); + return d->fastUpdatesCounter > 0; } // public slot -void kpViewManager::setFastUpdates () +void kpViewManager::setFastUpdates() { d->fastUpdatesCounter++; #if DEBUG_KP_VIEW_MANAGER && 0 qCDebug(kpLogViews) << "kpViewManager::setFastUpdates() counter=" - << d->fastUpdatesCounter << endl; + << d->fastUpdatesCounter << endl; #endif } // public slot -void kpViewManager::restoreFastUpdates () +void kpViewManager::restoreFastUpdates() { d->fastUpdatesCounter--; #if DEBUG_KP_VIEW_MANAGER && 0 qCDebug(kpLogViews) << "kpViewManager::restoreFastUpdates() counter=" - << d->fastUpdatesCounter << endl; + << d->fastUpdatesCounter << endl; #endif - Q_ASSERT (d->fastUpdatesCounter >= 0); + Q_ASSERT(d->fastUpdatesCounter >= 0); } - // public slot -void kpViewManager::updateView (kpView *v) +void kpViewManager::updateView(kpView *v) { - updateView (v, QRect (0, 0, v->width (), v->height ())); + updateView(v, QRect(0, 0, v->width(), v->height())); } // public slot -void kpViewManager::updateView (kpView *v, const QRect &viewRect) +void kpViewManager::updateView(kpView *v, const QRect &viewRect) { - if (!queueUpdates ()) - { - if (fastUpdates ()) { - v->repaint (viewRect); + if (!queueUpdates()) { + if (fastUpdates()) { + v->repaint(viewRect); + } else { + v->update(viewRect); } - else { - v->update (viewRect); - } - } - else { - v->addToQueuedArea (viewRect); + } else { + v->addToQueuedArea(viewRect); } } // public slot -void kpViewManager::updateView (kpView *v, int x, int y, int w, int h) +void kpViewManager::updateView(kpView *v, int x, int y, int w, int h) { - updateView (v, QRect (x, y, w, h)); + updateView(v, QRect(x, y, w, h)); } // public slot -void kpViewManager::updateView (kpView *v, const QRegion &viewRegion) +void kpViewManager::updateView(kpView *v, const QRegion &viewRegion) { - if (!queueUpdates ()) - { - if (fastUpdates ()) { - v->repaint (viewRegion); + if (!queueUpdates()) { + if (fastUpdates()) { + v->repaint(viewRegion); + } else { + v->update(viewRegion.boundingRect()); } - else { - v->update (viewRegion.boundingRect ()); - } - } - else { - v->addToQueuedArea (viewRegion); + } else { + v->addToQueuedArea(viewRegion); } } - // public slot -void kpViewManager::updateViewRectangleEdges (kpView *v, const QRect &viewRect) +void kpViewManager::updateViewRectangleEdges(kpView *v, const QRect &viewRect) { - if (viewRect.height () <= 0 || viewRect.width () <= 0) { + if (viewRect.height() <= 0 || viewRect.width() <= 0) { return; } // Top line - updateView (v, QRect (viewRect.x (), viewRect.y (), - viewRect.width (), 1)); + updateView(v, QRect(viewRect.x(), viewRect.y(), + viewRect.width(), 1)); - if (viewRect.height () >= 2) - { + if (viewRect.height() >= 2) { // Bottom line - updateView (v, QRect (viewRect.x (), viewRect.bottom (), - viewRect.width (), 1)); + updateView(v, QRect(viewRect.x(), viewRect.bottom(), + viewRect.width(), 1)); - if (viewRect.height () > 2) - { + if (viewRect.height() > 2) { // Left line - updateView (v, QRect (viewRect.x (), viewRect.y () + 1, - 1, viewRect.height () - 2)); + updateView(v, QRect(viewRect.x(), viewRect.y() + 1, + 1, viewRect.height() - 2)); - if (viewRect.width () >= 2) - { + if (viewRect.width() >= 2) { // Right line - updateView (v, QRect (viewRect.right (), viewRect.y () + 1, - 1, viewRect.height () - 2)); + updateView(v, QRect(viewRect.right(), viewRect.y() + 1, + 1, viewRect.height() - 2)); } } } } // public slot -void kpViewManager::updateViews (const QRect &docRect) +void kpViewManager::updateViews(const QRect &docRect) { #if DEBUG_KP_VIEW_MANAGER && 0 qCDebug(kpLogViews) << "kpViewManager::updateViews (" << docRect << ")"; #endif - for (QLinkedList ::const_iterator it = d->views.begin (); - it != d->views.end (); - ++it) - { + for (QLinkedList ::const_iterator it = d->views.begin(); + it != d->views.end(); + ++it) { kpView *view = *it; #if DEBUG_KP_VIEW_MANAGER && 0 - qCDebug(kpLogViews) << "\tupdating view " << view->name (); + qCDebug(kpLogViews) << "\tupdating view " << view->name(); #endif - if (view->zoomLevelX () % 100 == 0 && view->zoomLevelY () % 100 == 0) - { + if (view->zoomLevelX() % 100 == 0 && view->zoomLevelY() % 100 == 0) { #if DEBUG_KP_VIEW_MANAGER && 0 - qCDebug(kpLogViews) << "\t\tviewRect=" << view->transformDocToView (docRect); + qCDebug(kpLogViews) << "\t\tviewRect=" << view->transformDocToView(docRect); #endif - updateView (view, view->transformDocToView (docRect)); - } - else - { - QRect viewRect = view->transformDocToView (docRect); + updateView(view, view->transformDocToView(docRect)); + } else { + QRect viewRect = view->transformDocToView(docRect); - int diff = qRound (double (qMax (view->zoomLevelX (), view->zoomLevelY ())) / 100.0) + 1; + int diff = qRound(double(qMax(view->zoomLevelX(), view->zoomLevelY())) / 100.0) + 1; - QRect newRect = QRect (viewRect.x () - diff, - viewRect.y () - diff, - viewRect.width () + 2 * diff, - viewRect.height () + 2 * diff) - .intersected (QRect (0, 0, view->width (), view->height ())); + QRect newRect = QRect(viewRect.x() - diff, + viewRect.y() - diff, + viewRect.width() + 2 * diff, + viewRect.height() + 2 * diff) + .intersected(QRect(0, 0, view->width(), view->height())); #if DEBUG_KP_VIEW_MANAGER && 0 qCDebug(kpLogViews) << "\t\tviewRect (+compensate)=" << newRect; #endif - updateView (view, newRect); + updateView(view, newRect); } } } - // public slot -void kpViewManager::adjustViewsToEnvironment () +void kpViewManager::adjustViewsToEnvironment() { #if DEBUG_KP_VIEW_MANAGER && 1 qCDebug(kpLogViews) << "kpViewManager::adjustViewsToEnvironment()" - << " numViews=" << d->views.count () - << endl; + << " numViews=" << d->views.count() + << endl; #endif - for (QLinkedList ::const_iterator it = d->views.begin (); - it != d->views.end (); - ++it) - { + for (QLinkedList ::const_iterator it = d->views.begin(); + it != d->views.end(); + ++it) { kpView *view = *it; #if DEBUG_KP_VIEW_MANAGER && 1 - qCDebug(kpLogViews) << "\tview: " << view->name () - << endl; + qCDebug(kpLogViews) << "\tview: " << view->name() + << endl; #endif - view->adjustToEnvironment (); + view->adjustToEnvironment(); } } diff --git a/widgets/colorSimilarity/kpColorSimilarityCubeRenderer.h b/widgets/colorSimilarity/kpColorSimilarityCubeRenderer.h --- a/widgets/colorSimilarity/kpColorSimilarityCubeRenderer.h +++ b/widgets/colorSimilarity/kpColorSimilarityCubeRenderer.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpColorSimilarityCubeRenderer_H #define kpColorSimilarityCubeRenderer_H - class QPaintDevice; - class kpColorSimilarityCubeRenderer { public: @@ -44,11 +40,8 @@ // . // 255 = full highlight - static void Paint(QPaintDevice *target, - int x, int y, int size, - double colorSimilarity, - int highlight = 0); + static void Paint(QPaintDevice *target, int x, int y, int size, double colorSimilarity, + int highlight = 0); }; - #endif // kpColorSimilarityCubeRenderer_H diff --git a/widgets/colorSimilarity/kpColorSimilarityCubeRenderer.cpp b/widgets/colorSimilarity/kpColorSimilarityCubeRenderer.cpp --- a/widgets/colorSimilarity/kpColorSimilarityCubeRenderer.cpp +++ b/widgets/colorSimilarity/kpColorSimilarityCubeRenderer.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COLOR_SIMILARITY_CUBE 0 - #include "kpColorSimilarityCubeRenderer.h" #include @@ -43,47 +40,52 @@ //--------------------------------------------------------------------- -static QColor Color (int redOrGreenOrBlue, - int baseBrightness, - double colorSimilarity, - int similarityDirection, - int highlight) +static QColor Color(int redOrGreenOrBlue, int baseBrightness, double colorSimilarity, + int similarityDirection, int highlight) { - int brightness = int (baseBrightness + - similarityDirection * - 0.5 * colorSimilarity * kpColorSimilarityHolder::ColorCubeDiagonalDistance); + int brightness = int(baseBrightness + +similarityDirection + *0.5 * colorSimilarity + * kpColorSimilarityHolder::ColorCubeDiagonalDistance); if (brightness < 0) { brightness = 0; - } - else if (brightness > 255) { + } else if (brightness > 255) { brightness = 255; } - switch (redOrGreenOrBlue) - { - default: - case 0: return {brightness, highlight, highlight}; - case 1: return {highlight, brightness, highlight}; - case 2: return {highlight, highlight, brightness}; + switch (redOrGreenOrBlue) { + default: + case 0: + return { + brightness, highlight, highlight + }; + case 1: + return { + highlight, brightness, highlight + }; + case 2: + return { + highlight, highlight, brightness + }; } } //--------------------------------------------------------------------- static QPointF PointBetween(const QPointF &p, const QPointF &q) { - return {(p.x() + q.x()) / 2.0, (p.y() + q.y()) / 2.0}; + return { + (p.x() + q.x()) / 2.0, (p.y() + q.y()) / 2.0 + }; } //--------------------------------------------------------------------- -static void DrawQuadrant(QPaintDevice *target, - const QColor &col, - const QPointF &p1, const QPointF &p2, const QPointF &p3, - const QPointF &pointNotOnOutline) +static void DrawQuadrant(QPaintDevice *target, const QColor &col, const QPointF &p1, + const QPointF &p2, const QPointF &p3, const QPointF &pointNotOnOutline) { - QPolygonF points (4); + QPolygonF points(4); points [0] = p1; points [1] = p2; points [2] = p3; @@ -102,21 +104,19 @@ //--------------------------------------------------------------------- -static void DrawFace (QPaintDevice *target, - double colorSimilarity, - int redOrGreenOrBlue, - const QPointF &tl, const QPointF &tr, - const QPointF &bl, const QPointF &br, - int highlight) +static void DrawFace(QPaintDevice *target, double colorSimilarity, int redOrGreenOrBlue, + const QPointF &tl, const QPointF &tr, const QPointF &bl, const QPointF &br, + int highlight) { #if DEBUG_KP_COLOR_SIMILARITY_CUBE - qCDebug(kpLogWidgets) << "kpColorSimilarityCubeRenderer.cpp:DrawFace(RorGorB=" << redOrGreenOrBlue - << ",tl=" << tl - << ",tr=" << tr - << ",bl=" << bl - << ",br=" << br - << ")" - << endl; + qCDebug(kpLogWidgets) << "kpColorSimilarityCubeRenderer.cpp:DrawFace(RorGorB=" + << redOrGreenOrBlue + << ",tl=" << tl + << ",tr=" << tr + << ",bl=" << bl + << ",br=" << br + << ")" + << endl; #endif // tl --- tm --- tr @@ -127,35 +127,36 @@ // | | | // bl --- bm --- br - const QPointF tm (::PointBetween (tl, tr)); - const QPointF bm (::PointBetween (bl, br)); + const QPointF tm(::PointBetween(tl, tr)); + const QPointF bm(::PointBetween(bl, br)); - const QPointF ml (::PointBetween (tl, bl)); - const QPointF mr (::PointBetween (tr, br)); - const QPointF mm (::PointBetween (ml, mr)); + const QPointF ml(::PointBetween(tl, bl)); + const QPointF mr(::PointBetween(tr, br)); + const QPointF mm(::PointBetween(ml, mr)); - - const int baseBrightness = - qMax (127, - 255 - int (kpColorSimilarityHolder::MaxColorSimilarity * + const int baseBrightness + = qMax(127, + 255 - int(kpColorSimilarityHolder::MaxColorSimilarity * kpColorSimilarityHolder::ColorCubeDiagonalDistance / 2)); QColor colors [2] = { - ::Color (redOrGreenOrBlue, baseBrightness, colorSimilarity, -1, highlight), - ::Color (redOrGreenOrBlue, baseBrightness, colorSimilarity, +1, highlight) + ::Color(redOrGreenOrBlue, baseBrightness, colorSimilarity, -1, highlight), + ::Color(redOrGreenOrBlue, baseBrightness, colorSimilarity, +1, highlight) }; #if DEBUG_KP_COLOR_SIMILARITY_CUBE qCDebug(kpLogWidgets) << "\tmaxColorSimilarity=" << kpColorSimilarityHolder::MaxColorSimilarity - << " colorCubeDiagDist=" << kpColorSimilarityHolder::ColorCubeDiagonalDistance - << "\n" - << "\tbaseBrightness=" << baseBrightness - << " color[0]=" << ((colors [0].rgba() & RGB_MASK) >> ((2 - redOrGreenOrBlue) * 8)) - << " color[1]=" << ((colors [1].rgba() & RGB_MASK) >> ((2 - redOrGreenOrBlue) * 8)) - << endl; + << " colorCubeDiagDist=" + << kpColorSimilarityHolder::ColorCubeDiagonalDistance + << "\n" + << "\tbaseBrightness=" << baseBrightness + << " color[0]=" + << ((colors [0].rgba() & RGB_MASK) >> ((2 - redOrGreenOrBlue) * 8)) + << " color[1]=" + << ((colors [1].rgba() & RGB_MASK) >> ((2 - redOrGreenOrBlue) * 8)) + << endl; #endif - ::DrawQuadrant(target, colors [0], tm, tl, ml, mm); ::DrawQuadrant(target, colors [1], tm, tr, mr, mm); ::DrawQuadrant(target, colors [1], ml, bl, bm, mm); @@ -165,12 +166,10 @@ //--------------------------------------------------------------------- // public static -void kpColorSimilarityCubeRenderer::Paint(QPaintDevice *target, - int x, int y, int cubeRectSize, - double colorSimilarity, - int highlight) +void kpColorSimilarityCubeRenderer::Paint(QPaintDevice *target, int x, int y, int cubeRectSize, + double colorSimilarity, int highlight) { - Q_ASSERT (highlight >= 0 && highlight <= 255); + Q_ASSERT(highlight >= 0 && highlight <= 255); // // P------- Q --- --- @@ -187,50 +186,46 @@ // // - const double angle = qDegreesToRadians (45.0); + const double angle = qDegreesToRadians(45.0); // S + S sin A = cubeRectSize // (1 + sin A) x S = cubeRectSize const double side = double(cubeRectSize) / (1.0 + std::sin(angle)); - - const QPointF pointP(x + (side * std::cos (angle)), + const QPointF pointP(x + (side * std::cos(angle)), y); const QPointF pointQ(x + cubeRectSize - 1, y); const QPointF pointR(x, - y + (side * std::sin (angle))); + y + (side * std::sin(angle))); const QPointF pointS(x + (side), - y + (side * std::sin (angle))); + y + (side * std::sin(angle))); const QPointF pointT(x + cubeRectSize - 1, y + (side)); const QPointF pointU(x, y + cubeRectSize - 1); const QPointF pointV(x + (side), y + cubeRectSize - 1); - // Top Face ::DrawFace(target, - colorSimilarity, 0/*red*/, - pointP, pointQ, - pointR, pointS, - highlight); - + colorSimilarity, 0 /*red*/, + pointP, pointQ, + pointR, pointS, + highlight); // Front Face ::DrawFace(target, - colorSimilarity, 1/*green*/, - pointR, pointS, - pointU, pointV, - highlight); - + colorSimilarity, 1 /*green*/, + pointR, pointS, + pointU, pointV, + highlight); // Right Face ::DrawFace(target, - colorSimilarity, 2/*blue*/, - pointS, pointQ, - pointV, pointT, - highlight); + colorSimilarity, 2 /*blue*/, + pointS, pointQ, + pointV, pointT, + highlight); } //--------------------------------------------------------------------- diff --git a/widgets/colorSimilarity/kpColorSimilarityFrame.h b/widgets/colorSimilarity/kpColorSimilarityFrame.h --- a/widgets/colorSimilarity/kpColorSimilarityFrame.h +++ b/widgets/colorSimilarity/kpColorSimilarityFrame.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,27 +24,24 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpColorSimilarityFrame_H #define kpColorSimilarityFrame_H #include "kpColorSimilarityHolder.h" #include - class kpColorSimilarityFrame : public QWidget, public kpColorSimilarityHolder { public: kpColorSimilarityFrame(QWidget *parent); - void setColorSimilarity (double similarity) override; + void setColorSimilarity(double similarity) override; - QSize sizeHint () const override; + QSize sizeHint() const override; protected: - void paintEvent (QPaintEvent *e) override; + void paintEvent(QPaintEvent *e) override; }; - #endif // kpColorSimilarityFrame_H diff --git a/widgets/colorSimilarity/kpColorSimilarityFrame.cpp b/widgets/colorSimilarity/kpColorSimilarityFrame.cpp --- a/widgets/colorSimilarity/kpColorSimilarityFrame.cpp +++ b/widgets/colorSimilarity/kpColorSimilarityFrame.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COLOR_SIMILARITY_CUBE 0 - #include "kpColorSimilarityFrame.h" #include "kpColorSimilarityCubeRenderer.h" @@ -40,39 +37,41 @@ kpColorSimilarityFrame::kpColorSimilarityFrame(QWidget *parent) : QWidget(parent) { - setWhatsThis (WhatsThis ()); + setWhatsThis(WhatsThis()); } //--------------------------------------------------------------------- // public virtual [base kpColorSimilarityHolder] -void kpColorSimilarityFrame::setColorSimilarity (double similarity) +void kpColorSimilarityFrame::setColorSimilarity(double similarity) { - kpColorSimilarityHolder::setColorSimilarity (similarity); + kpColorSimilarityHolder::setColorSimilarity(similarity); - repaint (); + repaint(); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -QSize kpColorSimilarityFrame::sizeHint () const +QSize kpColorSimilarityFrame::sizeHint() const { - return {52, 52}; + return { + 52, 52 + }; } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpColorSimilarityFrame::paintEvent (QPaintEvent *) +void kpColorSimilarityFrame::paintEvent(QPaintEvent *) { int cubeRectSize = qMin(width() * 6 / 8, height() * 6 / 8); int x = (width() - cubeRectSize) / 2; int y = (height() - cubeRectSize) / 2; kpColorSimilarityCubeRenderer::Paint(this, - x, y, cubeRectSize, - colorSimilarity()); + x, y, cubeRectSize, + colorSimilarity()); } //--------------------------------------------------------------------- diff --git a/widgets/colorSimilarity/kpColorSimilarityHolder.h b/widgets/colorSimilarity/kpColorSimilarityHolder.h --- a/widgets/colorSimilarity/kpColorSimilarityHolder.h +++ b/widgets/colorSimilarity/kpColorSimilarityHolder.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpColorSimilarityHolder_H #define kpColorSimilarityHolder_H - class QString; - class kpColorSimilarityHolder { public: @@ -42,10 +38,10 @@ static const double ColorCubeDiagonalDistance; static const double MaxColorSimilarity; - static QString WhatsThisWithClickInstructions (); - static QString WhatsThis (); + static QString WhatsThisWithClickInstructions(); + static QString WhatsThis(); - double colorSimilarity () const; + double colorSimilarity() const; // This automatically restricts the given to the range // 0 .. MaxColorSimilarity inclusive. @@ -55,11 +51,10 @@ // // WARNING: The base constructor does not call this as virtual method // calls in constructors do not invoke overrides anyway. - virtual void setColorSimilarity (double similarity); + virtual void setColorSimilarity(double similarity); private: double m_colorSimilarity; }; - #endif // kpColorSimilarityHolder_H diff --git a/widgets/colorSimilarity/kpColorSimilarityHolder.cpp b/widgets/colorSimilarity/kpColorSimilarityHolder.cpp --- a/widgets/colorSimilarity/kpColorSimilarityHolder.cpp +++ b/widgets/colorSimilarity/kpColorSimilarityHolder.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COLOR_SIMILARITY_CUBE 0 - #include "kpColorSimilarityHolder.h" #include "kpColorSimilarityCubeRenderer.h" @@ -46,130 +43,127 @@ #include // public static -const double kpColorSimilarityHolder::ColorCubeDiagonalDistance = - std::sqrt (255.0 * 255 * 3); +const double kpColorSimilarityHolder::ColorCubeDiagonalDistance + = std::sqrt(255.0 * 255 * 3); // public static const double kpColorSimilarityHolder::MaxColorSimilarity = 0.30; - kpColorSimilarityHolder::kpColorSimilarityHolder () - : m_colorSimilarity (0) + : m_colorSimilarity(0) { } kpColorSimilarityHolder::~kpColorSimilarityHolder () = default; - // Don't cause the translators grief by appending strings etc. // - duplicate text with 2 cases // public static -QString kpColorSimilarityHolder::WhatsThisWithClickInstructions () +QString kpColorSimilarityHolder::WhatsThisWithClickInstructions() { - return i18n ("" - "

Color Similarity is how similar the colors of different pixels" - " must be, for operations to consider them to be the same.

" - - "

If you set it to something other than Exact Match," - " you can work more effectively with dithered" - " images and photos, in a comparable manner to the \"Magic Wand\"" - " feature of other paint programs.

" - - "

This feature applies to:

" - - "
    " - - "
  • Selections: In Transparent mode, any color in the" - " selection that is similar to the background color will" - " be made transparent.
  • " - - "
  • Flood Fill: For regions with similar - but not" - " identical - colored pixels, a higher setting is likely to" - " fill more pixels.
  • " - - "
  • Color Eraser: Any pixel whose color is similar" - " to the foreground color will be replaced with the background" - " color.
  • " - - "
  • Autocrop and Remove Internal Border: For" - " borders with similar - but not identical - colored pixels," - " a higher setting is more likely to crop the whole border.
  • " - - "
" - - "

Higher settings mean that operations consider an increased range" - " of colors to be sufficiently similar so as to be the same. Therefore," - " you should increase the setting if the above operations are not" - " affecting pixels whose colors you consider to be similar enough.

" - - "

However, if they are having too much of an effect and are changing" - " pixels whose colors you do not consider to be similar" - " (e.g. if Flood Fill is changing too many pixels), you" - " should decrease this setting.

" - - // sync: Compared to the other string below, we've added this line. - "

To configure it, click on the cube.

" - - "
"); + return i18n("" + "

Color Similarity is how similar the colors of different pixels" + " must be, for operations to consider them to be the same.

" + + "

If you set it to something other than Exact Match," + " you can work more effectively with dithered" + " images and photos, in a comparable manner to the \"Magic Wand\"" + " feature of other paint programs.

" + + "

This feature applies to:

" + + "
    " + + "
  • Selections: In Transparent mode, any color in the" + " selection that is similar to the background color will" + " be made transparent.
  • " + + "
  • Flood Fill: For regions with similar - but not" + " identical - colored pixels, a higher setting is likely to" + " fill more pixels.
  • " + + "
  • Color Eraser: Any pixel whose color is similar" + " to the foreground color will be replaced with the background" + " color.
  • " + + "
  • Autocrop and Remove Internal Border: For" + " borders with similar - but not identical - colored pixels," + " a higher setting is more likely to crop the whole border.
  • " + + "
" + + "

Higher settings mean that operations consider an increased range" + " of colors to be sufficiently similar so as to be the same. Therefore," + " you should increase the setting if the above operations are not" + " affecting pixels whose colors you consider to be similar enough.

" + + "

However, if they are having too much of an effect and are changing" + " pixels whose colors you do not consider to be similar" + " (e.g. if Flood Fill is changing too many pixels), you" + " should decrease this setting.

" + + // sync: Compared to the other string below, we've added this line. + "

To configure it, click on the cube.

" + + "
"); } // public static -QString kpColorSimilarityHolder::WhatsThis () +QString kpColorSimilarityHolder::WhatsThis() { - return i18n ("" - "

Color Similarity is how similar the colors of different pixels" - " must be, for operations to consider them to be the same.

" - - "

If you set it to something other than Exact Match," - " you can work more effectively with dithered" - " images and photos, in a comparable manner to the \"Magic Wand\"" - " feature of other paint programs.

" - - "

This feature applies to:

" - - "
    " - - "
  • Selections: In Transparent mode, any color in the" - " selection that is similar to the background color will" - " be made transparent.
  • " - - "
  • Flood Fill: For regions with similar - but not" - " identical - colored pixels, a higher setting is likely to" - " fill more pixels.
  • " - - "
  • Color Eraser: Any pixel whose color is similar" - " to the foreground color will be replaced with the background" - " color.
  • " - - "
  • Autocrop and Remove Internal Border: For" - " borders with similar - but not identical - colored pixels," - " a higher setting is more likely to crop the whole border.
  • " - - "
" - - "

Higher settings mean that operations consider an increased range" - " of colors to be sufficiently similar so as to be the same. Therefore," - " you should increase the setting if the above operations are not" - " affecting pixels whose colors you consider to be similar enough.

" - - "

However, if they are having too much of an effect and are changing" - " pixels whose colors you do not consider to be similar" - " (e.g. if Flood Fill is changing too many pixels), you" - " should decrease this setting.

" - - "
"); -} + return i18n("" + "

Color Similarity is how similar the colors of different pixels" + " must be, for operations to consider them to be the same.

" + + "

If you set it to something other than Exact Match," + " you can work more effectively with dithered" + " images and photos, in a comparable manner to the \"Magic Wand\"" + " feature of other paint programs.

" + + "

This feature applies to:

" + + "
    " + + "
  • Selections: In Transparent mode, any color in the" + " selection that is similar to the background color will" + " be made transparent.
  • " + + "
  • Flood Fill: For regions with similar - but not" + " identical - colored pixels, a higher setting is likely to" + " fill more pixels.
  • " + "
  • Color Eraser: Any pixel whose color is similar" + " to the foreground color will be replaced with the background" + " color.
  • " + + "
  • Autocrop and Remove Internal Border: For" + " borders with similar - but not identical - colored pixels," + " a higher setting is more likely to crop the whole border.
  • " + + "
" + + "

Higher settings mean that operations consider an increased range" + " of colors to be sufficiently similar so as to be the same. Therefore," + " you should increase the setting if the above operations are not" + " affecting pixels whose colors you consider to be similar enough.

" + + "

However, if they are having too much of an effect and are changing" + " pixels whose colors you do not consider to be similar" + " (e.g. if Flood Fill is changing too many pixels), you" + " should decrease this setting.

" + + "
"); +} // public -double kpColorSimilarityHolder::colorSimilarity () const +double kpColorSimilarityHolder::colorSimilarity() const { return m_colorSimilarity; } // public virtual -void kpColorSimilarityHolder::setColorSimilarity (double similarity) +void kpColorSimilarityHolder::setColorSimilarity(double similarity) { #if DEBUG_KP_COLOR_SIMILARITY_CUBE qCDebug(kpLogWidgets) << "kpColorSimilarityHolder::setColorSimilarity(" << similarity << ")"; @@ -181,8 +175,7 @@ if (similarity < 0) { similarity = 0; - } - else if (similarity > MaxColorSimilarity) { + } else if (similarity > MaxColorSimilarity) { similarity = MaxColorSimilarity; } diff --git a/widgets/colorSimilarity/kpColorSimilarityToolBarItem.h b/widgets/colorSimilarity/kpColorSimilarityToolBarItem.h --- a/widgets/colorSimilarity/kpColorSimilarityToolBarItem.h +++ b/widgets/colorSimilarity/kpColorSimilarityToolBarItem.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,71 +24,63 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpColorSimilarityToolBarItem_H #define kpColorSimilarityToolBarItem_H - #include "widgets/colorSimilarity/kpColorSimilarityHolder.h" #include - class QTimer; - -class kpColorSimilarityToolBarItem : public QToolButton, - public kpColorSimilarityHolder +class kpColorSimilarityToolBarItem : public QToolButton, public kpColorSimilarityHolder { -Q_OBJECT + Q_OBJECT public: // (reads the color similarity config setting) kpColorSimilarityToolBarItem (QWidget *parent); - int processedColorSimilarity () const; + int processedColorSimilarity() const; private: // specifies whether to write the color similarity config // setting. - void setColorSimilarityInternal (double similarity, bool writeConfig); + void setColorSimilarityInternal(double similarity, bool writeConfig); public: - void setColorSimilarity (double similarity) override; + void setColorSimilarity(double similarity) override; signals: - void colorSimilarityChanged (double similarity, int processedSimilarity); + void colorSimilarityChanged(double similarity, int processedSimilarity); public: // (only valid in slots connected to colorSimilarityChanged()); - double oldColorSimilarity () const; - + double oldColorSimilarity() const; public slots: // Open configuration dialog for color similarity. - void openDialog (); + void openDialog(); private slots: - void slotFlashTimerTimeout (); + void slotFlashTimerTimeout(); public: // Animates the cube, so that the user is aware of its existence. // Call this whenever a tool or command uses color similarity. - void flash (); + void flash(); public: // Whether to ignore calls to flash(). // You can nest blocks of suppressFlash()/unsuppressFlash(). - bool isSuppressingFlash () const; - void suppressFlash (); - void unsupressFlash (); - + bool isSuppressingFlash() const; + void suppressFlash(); + void unsupressFlash(); private: - void updateToolTip (); - void updateIcon (); - - void resizeEvent (QResizeEvent *e) override; + void updateToolTip(); + void updateIcon(); + void resizeEvent(QResizeEvent *e) override; private: double m_oldColorSimilarity; @@ -100,5 +91,4 @@ int m_suppressingFlashCounter; }; - #endif // kpColorSimilarityToolBarItem_H diff --git a/widgets/colorSimilarity/kpColorSimilarityToolBarItem.cpp b/widgets/colorSimilarity/kpColorSimilarityToolBarItem.cpp --- a/widgets/colorSimilarity/kpColorSimilarityToolBarItem.cpp +++ b/widgets/colorSimilarity/kpColorSimilarityToolBarItem.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COLOR_SIMILARITY_TOOL_BAR_ITEM 0 - #include "kpColorSimilarityToolBarItem.h" #include @@ -46,197 +43,187 @@ //--------------------------------------------------------------------- kpColorSimilarityToolBarItem::kpColorSimilarityToolBarItem (QWidget *parent) - : QToolButton (parent), - kpColorSimilarityHolder (), - - m_oldColorSimilarity (0), - m_processedColorSimilarity (kpColor::Exact), - m_flashTimer (new QTimer (this)), - m_flashHighlight (0), - m_suppressingFlashCounter (0) + : QToolButton(parent) + , kpColorSimilarityHolder() + , m_oldColorSimilarity(0) + , m_processedColorSimilarity(kpColor::Exact) + , m_flashTimer(new QTimer(this)) + , m_flashHighlight(0) + , m_suppressingFlashCounter(0) { - setAutoRaise (true); - setFixedSize (52, 52); + setAutoRaise(true); + setFixedSize(52, 52); - setWhatsThis (WhatsThisWithClickInstructions ()); + setWhatsThis(WhatsThisWithClickInstructions()); - connect (this, &kpColorSimilarityToolBarItem::clicked, - this, &kpColorSimilarityToolBarItem::openDialog); + connect(this, &kpColorSimilarityToolBarItem::clicked, + this, &kpColorSimilarityToolBarItem::openDialog); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupGeneral); - setColorSimilarityInternal (cfg.readEntry (kpSettingColorSimilarity, 0.0), - false/*don't write config*/); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); + setColorSimilarityInternal(cfg.readEntry(kpSettingColorSimilarity, 0.0), + false /*don't write config*/); - m_flashTimer->setInterval (100/*ms*/); - connect (m_flashTimer, &QTimer::timeout, - this, &kpColorSimilarityToolBarItem::slotFlashTimerTimeout); + m_flashTimer->setInterval(100 /*ms*/); + connect(m_flashTimer, &QTimer::timeout, + this, &kpColorSimilarityToolBarItem::slotFlashTimerTimeout); } //--------------------------------------------------------------------- // public -int kpColorSimilarityToolBarItem::processedColorSimilarity () const +int kpColorSimilarityToolBarItem::processedColorSimilarity() const { return m_processedColorSimilarity; } //--------------------------------------------------------------------- // private -void kpColorSimilarityToolBarItem::setColorSimilarityInternal (double similarity, - bool writeConfig) +void kpColorSimilarityToolBarItem::setColorSimilarityInternal(double similarity, bool writeConfig) { #if DEBUG_KP_COLOR_SIMILARITY_TOOL_BAR_ITEM qCDebug(kpLogWidgets) << "kpColorSimilarityToolBarItem::setColorSimilarityInternal(" - << "similarity=" << similarity << ",writeConfig=" << writeConfig - << ")"; + << "similarity=" << similarity << ",writeConfig=" << writeConfig + << ")"; #endif - m_oldColorSimilarity = colorSimilarity (); + m_oldColorSimilarity = colorSimilarity(); - kpColorSimilarityHolder::setColorSimilarity (similarity); - m_processedColorSimilarity = kpColor::processSimilarity (colorSimilarity ()); + kpColorSimilarityHolder::setColorSimilarity(similarity); + m_processedColorSimilarity = kpColor::processSimilarity(colorSimilarity()); - updateIcon (); - updateToolTip (); + updateIcon(); + updateToolTip(); - if (writeConfig) - { - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupGeneral); - cfg.writeEntry (kpSettingColorSimilarity, colorSimilarity ()); - cfg.sync (); + if (writeConfig) { + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupGeneral); + cfg.writeEntry(kpSettingColorSimilarity, colorSimilarity()); + cfg.sync(); } - emit colorSimilarityChanged (colorSimilarity (), m_processedColorSimilarity); + emit colorSimilarityChanged(colorSimilarity(), m_processedColorSimilarity); } //--------------------------------------------------------------------- // public virtual [base kopColorSimilarityHolder] -void kpColorSimilarityToolBarItem::setColorSimilarity (double similarity) +void kpColorSimilarityToolBarItem::setColorSimilarity(double similarity) { // (this calls the base setColorSimilarity() as required by base) - setColorSimilarityInternal (similarity, true/*write config*/); + setColorSimilarityInternal(similarity, true /*write config*/); } //--------------------------------------------------------------------- // public -double kpColorSimilarityToolBarItem::oldColorSimilarity () const +double kpColorSimilarityToolBarItem::oldColorSimilarity() const { return m_oldColorSimilarity; } //--------------------------------------------------------------------- // public -void kpColorSimilarityToolBarItem::openDialog () +void kpColorSimilarityToolBarItem::openDialog() { - kpColorSimilarityDialog dialog (this); - dialog.setColorSimilarity (colorSimilarity ()); - if (dialog.exec ()) - { - setColorSimilarity (dialog.colorSimilarity ()); + kpColorSimilarityDialog dialog(this); + dialog.setColorSimilarity(colorSimilarity()); + if (dialog.exec()) { + setColorSimilarity(dialog.colorSimilarity()); } } //--------------------------------------------------------------------- // private slot: -void kpColorSimilarityToolBarItem::slotFlashTimerTimeout () +void kpColorSimilarityToolBarItem::slotFlashTimerTimeout() { #if DEBUG_KP_COLOR_SIMILARITY_TOOL_BAR_ITEM qCDebug(kpLogWidgets) << "kpColorSimilarityToolBarItem::slotFlashTimerTimeout()" - << " highlight=" << m_flashHighlight << endl; + << " highlight=" << m_flashHighlight << endl; #endif int newHigh = m_flashHighlight - 20; if (newHigh < 0) { newHigh = 0; } m_flashHighlight = newHigh; - updateIcon (); + updateIcon(); if (newHigh == 0) { - m_flashTimer->stop (); + m_flashTimer->stop(); } } //--------------------------------------------------------------------- // public -void kpColorSimilarityToolBarItem::flash () +void kpColorSimilarityToolBarItem::flash() { #if DEBUG_KP_COLOR_SIMILARITY_TOOL_BAR_ITEM qCDebug(kpLogWidgets) << "kpColorSimilarityToolBarItem::flash()"; #endif - if (isSuppressingFlash ()) { + if (isSuppressingFlash()) { return; } - if (m_flashHighlight == 255) - { + if (m_flashHighlight == 255) { #if DEBUG_KP_COLOR_SIMILARITY_TOOL_BAR_ITEM qCDebug(kpLogWidgets) << "\tNOP"; #endif - } - else - { + } else { m_flashHighlight = 255; - updateIcon (); + updateIcon(); } - m_flashTimer->start (); + m_flashTimer->start(); } //--------------------------------------------------------------------- // public -bool kpColorSimilarityToolBarItem::isSuppressingFlash () const +bool kpColorSimilarityToolBarItem::isSuppressingFlash() const { - return (m_suppressingFlashCounter > 0); + return m_suppressingFlashCounter > 0; } //--------------------------------------------------------------------- // public -void kpColorSimilarityToolBarItem::suppressFlash () +void kpColorSimilarityToolBarItem::suppressFlash() { m_suppressingFlashCounter++; } //--------------------------------------------------------------------- // public -void kpColorSimilarityToolBarItem::unsupressFlash () +void kpColorSimilarityToolBarItem::unsupressFlash() { m_suppressingFlashCounter--; - Q_ASSERT (m_suppressingFlashCounter >= 0); + Q_ASSERT(m_suppressingFlashCounter >= 0); } //--------------------------------------------------------------------- // private -void kpColorSimilarityToolBarItem::updateToolTip () +void kpColorSimilarityToolBarItem::updateToolTip() { #if DEBUG_KP_COLOR_SIMILARITY_TOOL_BAR_ITEM qCDebug(kpLogWidgets) << "kpColorSimilarityToolBarItem::updateToolTip()"; #endif - if (colorSimilarity () > 0) - { - setToolTip ( - i18n ("

Color Similarity: %1%

" - "

Click to configure.

", - qRound (colorSimilarity () * 100))); - } - else - { - setToolTip ( - i18n ("

Color Similarity: Exact Match

" - "

Click to configure.

")); + if (colorSimilarity() > 0) { + setToolTip( + i18n("

Color Similarity: %1%

" + "

Click to configure.

", + qRound(colorSimilarity() * 100))); + } else { + setToolTip( + i18n("

Color Similarity: Exact Match

" + "

Click to configure.

")); } } @@ -249,38 +236,37 @@ // 2. resizeEvent() when it's first shown() // // We could get rid of the first and save a few milliseconds. -void kpColorSimilarityToolBarItem::updateIcon () +void kpColorSimilarityToolBarItem::updateIcon() { - const int side = width () * 6 / 8; + const int side = width() * 6 / 8; #if DEBUG_KP_COLOR_SIMILARITY_TOOL_BAR_ITEM - qCDebug(kpLogWidgets) << "kpColorSimilarityToolBarItem::updateIcon() width=" << width () - << " side=" << side; + qCDebug(kpLogWidgets) << "kpColorSimilarityToolBarItem::updateIcon() width=" << width() + << " side=" << side; #endif QPixmap icon(side, side); icon.fill(Qt::transparent); - kpColorSimilarityCubeRenderer::Paint (&icon, - 0/*x*/, 0/*y*/, side, - colorSimilarity (), m_flashHighlight); + kpColorSimilarityCubeRenderer::Paint(&icon, + 0 /*x*/, 0 /*y*/, side, + colorSimilarity(), m_flashHighlight); setIconSize(QSize(side, side)); setIcon(icon); } //--------------------------------------------------------------------- // private virtual [base QWidget] -void kpColorSimilarityToolBarItem::resizeEvent (QResizeEvent *e) +void kpColorSimilarityToolBarItem::resizeEvent(QResizeEvent *e) { #if DEBUG_KP_COLOR_SIMILARITY_TOOL_BAR_ITEM - qCDebug(kpLogWidgets) << "kpColorSimilarityToolBarItem::resizeEvent() size=" << size () - << " oldSize=" << e->oldSize (); + qCDebug(kpLogWidgets) << "kpColorSimilarityToolBarItem::resizeEvent() size=" << size() + << " oldSize=" << e->oldSize(); #endif - QToolButton::resizeEvent (e); + QToolButton::resizeEvent(e); - updateIcon (); + updateIcon(); } //--------------------------------------------------------------------- - diff --git a/widgets/imagelib/effects/kpEffectBalanceWidget.h b/widgets/imagelib/effects/kpEffectBalanceWidget.h --- a/widgets/imagelib/effects/kpEffectBalanceWidget.h +++ b/widgets/imagelib/effects/kpEffectBalanceWidget.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,61 +24,55 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectBalanceWidget_H #define kpEffectBalanceWidget_H - #include "kpEffectWidgetBase.h" #include "imagelib/kpImage.h" - class QLabel; class QComboBox; class kpIntNumInput; - - class kpEffectBalanceWidget : public kpEffectWidgetBase { -Q_OBJECT + Q_OBJECT public: kpEffectBalanceWidget (bool actOnSelection, QWidget *parent); ~kpEffectBalanceWidget () override; - QString caption () const override; + QString caption() const override; - bool isNoOp () const override; - kpImage applyEffect (const kpImage &image) override; + bool isNoOp() const override; + kpImage applyEffect(const kpImage &image) override; - kpEffectCommandBase *createCommand ( + kpEffectCommandBase *createCommand( kpCommandEnvironment *cmdEnviron) const override; protected: - int channels () const; + int channels() const; - int brightness () const; - int contrast () const; - int gamma () const; + int brightness() const; + int contrast() const; + int gamma() const; protected slots: - void recalculateGammaLabel (); + void recalculateGammaLabel(); - void resetBrightness (); - void resetContrast (); - void resetGamma (); + void resetBrightness(); + void resetContrast(); + void resetGamma(); - void resetAll (); + void resetAll(); protected: kpIntNumInput *m_brightnessInput, - *m_contrastInput, - *m_gammaInput; + *m_contrastInput, + *m_gammaInput; QLabel *m_gammaLabel; QComboBox *m_channelsComboBox; }; - #endif // kpEffectBalanceWidget_H diff --git a/widgets/imagelib/effects/kpEffectBalanceWidget.cpp b/widgets/imagelib/effects/kpEffectBalanceWidget.cpp --- a/widgets/imagelib/effects/kpEffectBalanceWidget.cpp +++ b/widgets/imagelib/effects/kpEffectBalanceWidget.cpp @@ -24,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_BALANCE 0 - #include "kpEffectBalanceWidget.h" #include "imagelib/effects/kpEffectBalance.h" @@ -50,148 +48,136 @@ #include #endif - -kpEffectBalanceWidget::kpEffectBalanceWidget (bool actOnSelection, - QWidget *parent) - : kpEffectWidgetBase (actOnSelection, parent) +kpEffectBalanceWidget::kpEffectBalanceWidget (bool actOnSelection, QWidget *parent) + : kpEffectWidgetBase(actOnSelection, parent) { - auto *lay = new QGridLayout (this); + auto *lay = new QGridLayout(this); lay->setContentsMargins(0, 0, 0, 0); - auto *brightnessLabel = new QLabel (i18n ("&Brightness:"), this); - m_brightnessInput = new kpIntNumInput (0/*value*/, this); - m_brightnessInput->setRange (-50, 50); - auto *brightnessResetPushButton = new QPushButton (i18n ("Re&set"), this); + auto *brightnessLabel = new QLabel(i18n("&Brightness:"), this); + m_brightnessInput = new kpIntNumInput(0 /*value*/, this); + m_brightnessInput->setRange(-50, 50); + auto *brightnessResetPushButton = new QPushButton(i18n("Re&set"), this); - auto *contrastLabel = new QLabel (i18n ("Co&ntrast:"), this); - m_contrastInput = new kpIntNumInput (0/*value*/, this); - m_contrastInput->setRange (-50, 50); - auto *contrastResetPushButton = new QPushButton (i18n ("&Reset"), this); + auto *contrastLabel = new QLabel(i18n("Co&ntrast:"), this); + m_contrastInput = new kpIntNumInput(0 /*value*/, this); + m_contrastInput->setRange(-50, 50); + auto *contrastResetPushButton = new QPushButton(i18n("&Reset"), this); - auto *gammaLabel = new QLabel (i18n ("&Gamma:"), this); - m_gammaInput = new kpIntNumInput (0/*value*/, this); - m_gammaInput->setRange (-50, 50); + auto *gammaLabel = new QLabel(i18n("&Gamma:"), this); + m_gammaInput = new kpIntNumInput(0 /*value*/, this); + m_gammaInput->setRange(-50, 50); // TODO: This is what should be shown in the m_gammaInput spinbox - m_gammaLabel = new QLabel (this); + m_gammaLabel = new QLabel(this); // TODO: This doesn't seem to be wide enough with some fonts so the // whole layout moves when we drag the gamma slider. - m_gammaLabel->setMinimumWidth (m_gammaLabel->fontMetrics ().width (QStringLiteral (" 10.00 "))); - m_gammaLabel->setAlignment (m_gammaLabel->alignment () | Qt::AlignRight); - auto *gammaResetPushButton = new QPushButton (i18n ("Rese&t"), this); - - - auto *spaceWidget = new QLabel (this); - spaceWidget->setFixedSize (1, fontMetrics ().height () / 4); + m_gammaLabel->setMinimumWidth(m_gammaLabel->fontMetrics().width(QStringLiteral(" 10.00 "))); + m_gammaLabel->setAlignment(m_gammaLabel->alignment() | Qt::AlignRight); + auto *gammaResetPushButton = new QPushButton(i18n("Rese&t"), this); + auto *spaceWidget = new QLabel(this); + spaceWidget->setFixedSize(1, fontMetrics().height() / 4); - auto *channelLabel = new QLabel (i18n ("C&hannels:"), this); - m_channelsComboBox = new QComboBox (this); - m_channelsComboBox->addItem (i18n ("All")); - m_channelsComboBox->addItem (i18n ("Red")); - m_channelsComboBox->addItem (i18n ("Green")); - m_channelsComboBox->addItem (i18n ("Blue")); + auto *channelLabel = new QLabel(i18n("C&hannels:"), this); + m_channelsComboBox = new QComboBox(this); + m_channelsComboBox->addItem(i18n("All")); + m_channelsComboBox->addItem(i18n("Red")); + m_channelsComboBox->addItem(i18n("Green")); + m_channelsComboBox->addItem(i18n("Blue")); + auto *resetPushButton = new QPushButton(i18n("Reset &All Values"), this); - auto *resetPushButton = new QPushButton (i18n ("Reset &All Values"), this); + brightnessLabel->setBuddy(m_brightnessInput); + contrastLabel->setBuddy(m_contrastInput); + gammaLabel->setBuddy(m_gammaInput); + channelLabel->setBuddy(m_channelsComboBox); - brightnessLabel->setBuddy (m_brightnessInput); - contrastLabel->setBuddy (m_contrastInput); - gammaLabel->setBuddy (m_gammaInput); + lay->addWidget(brightnessLabel, 0, 0); + lay->addWidget(m_brightnessInput, 0, 1, 1, 2); + lay->addWidget(brightnessResetPushButton, 0, 4); - channelLabel->setBuddy (m_channelsComboBox); + lay->addWidget(contrastLabel, 1, 0); + lay->addWidget(m_contrastInput, 1, 1, 1, 2); + lay->addWidget(contrastResetPushButton, 1, 4); + lay->addWidget(gammaLabel, 2, 0); + lay->addWidget(m_gammaInput, 2, 1, 1, 2); + lay->addWidget(m_gammaLabel, 2, 3); + lay->addWidget(gammaResetPushButton, 2, 4); - lay->addWidget (brightnessLabel, 0, 0); - lay->addWidget (m_brightnessInput, 0, 1, 1, 2); - lay->addWidget (brightnessResetPushButton, 0, 4); + lay->addWidget(spaceWidget, 3, 0, 1, 5); + lay->addWidget(resetPushButton, 4, 2, 1, 3, Qt::AlignRight); - lay->addWidget (contrastLabel, 1, 0); - lay->addWidget (m_contrastInput, 1, 1, 1, 2); - lay->addWidget (contrastResetPushButton, 1, 4); - - lay->addWidget (gammaLabel, 2, 0); - lay->addWidget (m_gammaInput, 2, 1, 1, 2); - lay->addWidget (m_gammaLabel, 2, 3); - lay->addWidget (gammaResetPushButton, 2, 4); - - lay->addWidget (spaceWidget, 3, 0, 1, 5); - lay->addWidget (resetPushButton, 4, 2, 1, 3, Qt::AlignRight); - - lay->addWidget (channelLabel, 4, 0); - lay->addWidget (m_channelsComboBox, 4, 1, Qt::AlignLeft); + lay->addWidget(channelLabel, 4, 0); + lay->addWidget(m_channelsComboBox, 4, 1, Qt::AlignLeft); //lay->addWidget (resetPushButton, 4, 2, Qt::AlignRight); - lay->setColumnStretch (1, 1); - + lay->setColumnStretch(1, 1); // (no need for settingsChangedDelayed() since BCG effect is so fast :)) - connect (m_brightnessInput, &kpIntNumInput::valueChanged, - this, &kpEffectBalanceWidget::settingsChangedNoWaitCursor); - connect (m_contrastInput, &kpIntNumInput::valueChanged, - this, &kpEffectBalanceWidget::settingsChangedNoWaitCursor); - - connect (m_gammaInput, &kpIntNumInput::valueChanged, - this, &kpEffectBalanceWidget::recalculateGammaLabel); - connect (m_gammaInput, &kpIntNumInput::valueChanged, - this, &kpEffectBalanceWidget::settingsChangedNoWaitCursor); - - connect (m_channelsComboBox, - static_cast(&QComboBox::activated), - this, &kpEffectBalanceWidget::settingsChanged); - - connect (brightnessResetPushButton, &QPushButton::clicked, - this, &kpEffectBalanceWidget::resetBrightness); - connect (contrastResetPushButton, &QPushButton::clicked, - this, &kpEffectBalanceWidget::resetContrast); - connect (gammaResetPushButton, &QPushButton::clicked, - this, &kpEffectBalanceWidget::resetGamma); - - connect (resetPushButton, &QPushButton::clicked, - this, &kpEffectBalanceWidget::resetAll); - - recalculateGammaLabel (); + connect(m_brightnessInput, &kpIntNumInput::valueChanged, + this, &kpEffectBalanceWidget::settingsChangedNoWaitCursor); + connect(m_contrastInput, &kpIntNumInput::valueChanged, + this, &kpEffectBalanceWidget::settingsChangedNoWaitCursor); + + connect(m_gammaInput, &kpIntNumInput::valueChanged, + this, &kpEffectBalanceWidget::recalculateGammaLabel); + connect(m_gammaInput, &kpIntNumInput::valueChanged, + this, &kpEffectBalanceWidget::settingsChangedNoWaitCursor); + + connect(m_channelsComboBox, + static_cast(&QComboBox::activated), + this, &kpEffectBalanceWidget::settingsChanged); + + connect(brightnessResetPushButton, &QPushButton::clicked, + this, &kpEffectBalanceWidget::resetBrightness); + connect(contrastResetPushButton, &QPushButton::clicked, + this, &kpEffectBalanceWidget::resetContrast); + connect(gammaResetPushButton, &QPushButton::clicked, + this, &kpEffectBalanceWidget::resetGamma); + + connect(resetPushButton, &QPushButton::clicked, + this, &kpEffectBalanceWidget::resetAll); + + recalculateGammaLabel(); } kpEffectBalanceWidget::~kpEffectBalanceWidget () = default; - // public virtual [base kpEffectWidgetBase] -QString kpEffectBalanceWidget::caption () const +QString kpEffectBalanceWidget::caption() const { - return i18n ("Settings"); + return i18n("Settings"); } - // public virtual [base kpEffectWidgetBase] -bool kpEffectBalanceWidget::isNoOp () const +bool kpEffectBalanceWidget::isNoOp() const { - return (brightness () == 0 && contrast () == 0 && gamma () == 0); + return brightness() == 0 && contrast() == 0 && gamma() == 0; } // public virtual [base kpEffectWidgetBase] -kpImage kpEffectBalanceWidget::applyEffect (const kpImage &image) +kpImage kpEffectBalanceWidget::applyEffect(const kpImage &image) { - return kpEffectBalance::applyEffect (image, - channels (), brightness (), contrast (), gamma ()); + return kpEffectBalance::applyEffect(image, + channels(), brightness(), contrast(), gamma()); } // public virtual [base kpEffectWidgetBase] -kpEffectCommandBase *kpEffectBalanceWidget::createCommand ( - kpCommandEnvironment *cmdEnviron) const +kpEffectCommandBase *kpEffectBalanceWidget::createCommand( + kpCommandEnvironment *cmdEnviron) const { - return new kpEffectBalanceCommand (channels (), - brightness (), contrast (), gamma (), - m_actOnSelection, - cmdEnviron); + return new kpEffectBalanceCommand(channels(), + brightness(), contrast(), gamma(), + m_actOnSelection, + cmdEnviron); } - // protected -int kpEffectBalanceWidget::channels () const +int kpEffectBalanceWidget::channels() const { - switch (m_channelsComboBox->currentIndex ()) - { + switch (m_channelsComboBox->currentIndex()) { default: case 0: return kpEffectBalance::RGB; @@ -207,124 +193,118 @@ } } - // protected -int kpEffectBalanceWidget::brightness () const +int kpEffectBalanceWidget::brightness() const { - return m_brightnessInput->value (); + return m_brightnessInput->value(); } // protected -int kpEffectBalanceWidget::contrast () const +int kpEffectBalanceWidget::contrast() const { - return m_contrastInput->value (); + return m_contrastInput->value(); } // protected -int kpEffectBalanceWidget::gamma () const +int kpEffectBalanceWidget::gamma() const { - return m_gammaInput->value (); + return m_gammaInput->value(); } - // protected slot -void kpEffectBalanceWidget::recalculateGammaLabel () +void kpEffectBalanceWidget::recalculateGammaLabel() { - m_gammaLabel->setText ( - QLatin1String (" ") + - QString::number (std::pow (10, gamma () / 50.0), - 'f'/*[-]9.9*/, - 2/*precision*/) + - QLatin1String (" ")); - m_gammaLabel->repaint (); + m_gammaLabel->setText( + QLatin1String(" ") + +QString::number(std::pow(10, gamma() / 50.0), + 'f' /*[-]9.9*/, + 2 /*precision*/) + +QLatin1String(" ")); + m_gammaLabel->repaint(); } - // protected slot -void kpEffectBalanceWidget::resetBrightness () +void kpEffectBalanceWidget::resetBrightness() { - if (brightness () == 0) { + if (brightness() == 0) { return; } - bool sb = signalsBlocked (); + bool sb = signalsBlocked(); if (!sb) { - blockSignals (true); + blockSignals(true); } - m_brightnessInput->setValue (0); + m_brightnessInput->setValue(0); if (!sb) { - blockSignals (false); + blockSignals(false); } // Immediate update (if signals aren't blocked) - emit settingsChanged (); + emit settingsChanged(); } // protected slot -void kpEffectBalanceWidget::resetContrast () +void kpEffectBalanceWidget::resetContrast() { - if (contrast () == 0) { + if (contrast() == 0) { return; } - bool sb = signalsBlocked (); + bool sb = signalsBlocked(); if (!sb) { - blockSignals (true); + blockSignals(true); } - m_contrastInput->setValue (0); + m_contrastInput->setValue(0); if (!sb) { - blockSignals (false); + blockSignals(false); } // Immediate update (if signals aren't blocked) - emit settingsChanged (); + emit settingsChanged(); } // protected slot -void kpEffectBalanceWidget::resetGamma () +void kpEffectBalanceWidget::resetGamma() { - if (gamma () == 0) { + if (gamma() == 0) { return; } - bool sb = signalsBlocked (); + bool sb = signalsBlocked(); if (!sb) { - blockSignals (true); + blockSignals(true); } - m_gammaInput->setValue (0); - recalculateGammaLabel (); + m_gammaInput->setValue(0); + recalculateGammaLabel(); if (!sb) { - blockSignals (false); + blockSignals(false); } // Immediate update (if signals aren't blocked) - emit settingsChanged (); + emit settingsChanged(); } - // protected slot -void kpEffectBalanceWidget::resetAll () +void kpEffectBalanceWidget::resetAll() { - if (isNoOp ()) { + if (isNoOp()) { return; } // Prevent multiple settingsChanged() which would normally result in // redundant, expensive preview repaints - blockSignals (true); + blockSignals(true); - resetBrightness (); - resetContrast (); - resetGamma (); + resetBrightness(); + resetContrast(); + resetGamma(); - recalculateGammaLabel (); + recalculateGammaLabel(); - blockSignals (false); + blockSignals(false); - emit settingsChanged (); + emit settingsChanged(); } - - diff --git a/widgets/imagelib/effects/kpEffectBlurSharpenWidget.h b/widgets/imagelib/effects/kpEffectBlurSharpenWidget.h --- a/widgets/imagelib/effects/kpEffectBlurSharpenWidget.h +++ b/widgets/imagelib/effects/kpEffectBlurSharpenWidget.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,48 +24,43 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectBlurSharpenWidget_H #define kpEffectBlurSharpenWidget_H - #include "imagelib/kpColor.h" #include "kpEffectWidgetBase.h" #include "imagelib/effects/kpEffectBlurSharpen.h" - class QLabel; class kpIntNumInput; - class kpEffectBlurSharpenWidget : public kpEffectWidgetBase { -Q_OBJECT + Q_OBJECT public: kpEffectBlurSharpenWidget (bool actOnSelection, QWidget *parent); ~kpEffectBlurSharpenWidget () override; - QString caption () const override; + QString caption() const override; - bool isNoOp () const override; - kpImage applyEffect (const kpImage &image) override; + bool isNoOp() const override; + kpImage applyEffect(const kpImage &image) override; - kpEffectCommandBase *createCommand ( + kpEffectCommandBase *createCommand( kpCommandEnvironment *cmdEnviron) const override; protected slots: - void slotUpdateTypeLabel (); + void slotUpdateTypeLabel(); protected: - kpEffectBlurSharpen::Type type () const; - int strength () const; + kpEffectBlurSharpen::Type type() const; + int strength() const; kpIntNumInput *m_amountInput; QLabel *m_typeLabel; }; - #endif // kpEffectBlurSharpenWidget_H diff --git a/widgets/imagelib/effects/kpEffectBlurSharpenWidget.cpp b/widgets/imagelib/effects/kpEffectBlurSharpenWidget.cpp --- a/widgets/imagelib/effects/kpEffectBlurSharpenWidget.cpp +++ b/widgets/imagelib/effects/kpEffectBlurSharpenWidget.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_BLUR_SHARPEN 0 - #include "kpEffectBlurSharpenWidget.h" #include "commands/imagelib/effects/kpEffectBlurSharpenCommand.h" @@ -41,20 +38,18 @@ #include #include - -kpEffectBlurSharpenWidget::kpEffectBlurSharpenWidget (bool actOnSelection, - QWidget *parent) - : kpEffectWidgetBase (actOnSelection, parent) +kpEffectBlurSharpenWidget::kpEffectBlurSharpenWidget (bool actOnSelection, QWidget *parent) + : kpEffectWidgetBase(actOnSelection, parent) { - auto *lay = new QGridLayout (this); + auto *lay = new QGridLayout(this); lay->setContentsMargins(0, 0, 0, 0); - auto *amountLabel = new QLabel (i18n ("&Amount:"), this); - m_amountInput = new kpIntNumInput (this); - m_amountInput->setRange (-kpEffectBlurSharpen::MaxStrength/*- for blur*/, - +kpEffectBlurSharpen::MaxStrength/*+ for sharpen*/); + auto *amountLabel = new QLabel(i18n("&Amount:"), this); + m_amountInput = new kpIntNumInput(this); + m_amountInput->setRange(-kpEffectBlurSharpen::MaxStrength /*- for blur*/, + +kpEffectBlurSharpen::MaxStrength /*+ for sharpen*/); - m_typeLabel = new QLabel (this); + m_typeLabel = new QLabel(this); // Make sure doesn't expand when the effect type changes, // as otherwise, that would cause the preview pixmap label in the @@ -64,121 +59,111 @@ // We do this by setting the label to every possible string it could // contain and fixing its height to the maximum seen size hint height. - auto h = m_typeLabel->sizeHint ().height (); + auto h = m_typeLabel->sizeHint().height(); #if DEBUG_KP_EFFECT_BLUR_SHARPEN qCDebug(kpLogWidgets) << "initial size hint height=" << h; #endif - m_typeLabel->setText ( - kpEffectBlurSharpenCommand::nameForType (kpEffectBlurSharpen::Blur)); - h = qMax (h, m_typeLabel->sizeHint ().height ()); + m_typeLabel->setText( + kpEffectBlurSharpenCommand::nameForType(kpEffectBlurSharpen::Blur)); + h = qMax(h, m_typeLabel->sizeHint().height()); - m_typeLabel->setText ( - kpEffectBlurSharpenCommand::nameForType (kpEffectBlurSharpen::Sharpen)); - h = qMax (h, m_typeLabel->sizeHint ().height ()); + m_typeLabel->setText( + kpEffectBlurSharpenCommand::nameForType(kpEffectBlurSharpen::Sharpen)); + h = qMax(h, m_typeLabel->sizeHint().height()); // Set this text last as the label's text needs to reflect the default // effect of "None". - m_typeLabel->setText ( - kpEffectBlurSharpenCommand::nameForType (kpEffectBlurSharpen::None)); - h = qMax (h, m_typeLabel->sizeHint ().height ()); + m_typeLabel->setText( + kpEffectBlurSharpenCommand::nameForType(kpEffectBlurSharpen::None)); + h = qMax(h, m_typeLabel->sizeHint().height()); #if DEBUG_KP_EFFECT_BLUR_SHARPEN qCDebug(kpLogWidgets) << "maximum size hint height" << h; #endif - m_typeLabel->setFixedHeight (h); - m_typeLabel->setAlignment (Qt::AlignCenter); - - - amountLabel->setBuddy (m_amountInput); - + m_typeLabel->setFixedHeight(h); + m_typeLabel->setAlignment(Qt::AlignCenter); - lay->addWidget (amountLabel, 0, 0); - lay->addWidget (m_amountInput, 0, 1); + amountLabel->setBuddy(m_amountInput); - lay->addWidget (m_typeLabel, 1, 0, 1, 2, Qt::AlignCenter); + lay->addWidget(amountLabel, 0, 0); + lay->addWidget(m_amountInput, 0, 1); - lay->setColumnStretch (1, 1); + lay->addWidget(m_typeLabel, 1, 0, 1, 2, Qt::AlignCenter); + lay->setColumnStretch(1, 1); - connect (m_amountInput, &kpIntNumInput::valueChanged, - this, &kpEffectBlurSharpenWidget::settingsChangedDelayed); + connect(m_amountInput, &kpIntNumInput::valueChanged, + this, &kpEffectBlurSharpenWidget::settingsChangedDelayed); - connect (m_amountInput, &kpIntNumInput::valueChanged, - this, &kpEffectBlurSharpenWidget::slotUpdateTypeLabel); + connect(m_amountInput, &kpIntNumInput::valueChanged, + this, &kpEffectBlurSharpenWidget::slotUpdateTypeLabel); } kpEffectBlurSharpenWidget::~kpEffectBlurSharpenWidget () = default; - // public virtual [base kpEffectWidgetBase] -QString kpEffectBlurSharpenWidget::caption () const +QString kpEffectBlurSharpenWidget::caption() const { return {}; } - // public virtual [base kpEffectWidgetBase] -bool kpEffectBlurSharpenWidget::isNoOp () const +bool kpEffectBlurSharpenWidget::isNoOp() const { - return (type () == kpEffectBlurSharpen::None); + return type() == kpEffectBlurSharpen::None; } // public virtual [base kpEffectWidgetBase] -kpImage kpEffectBlurSharpenWidget::applyEffect (const kpImage &image) +kpImage kpEffectBlurSharpenWidget::applyEffect(const kpImage &image) { - return kpEffectBlurSharpen::applyEffect (image, - type (), strength ()); + return kpEffectBlurSharpen::applyEffect(image, + type(), strength()); } // public virtual [base kpEffectWidgetBase] -kpEffectCommandBase *kpEffectBlurSharpenWidget::createCommand ( - kpCommandEnvironment *cmdEnviron) const +kpEffectCommandBase *kpEffectBlurSharpenWidget::createCommand( + kpCommandEnvironment *cmdEnviron) const { - return new kpEffectBlurSharpenCommand (type (), strength (), - m_actOnSelection, - cmdEnviron); + return new kpEffectBlurSharpenCommand(type(), strength(), + m_actOnSelection, + cmdEnviron); } - // protected slot -void kpEffectBlurSharpenWidget::slotUpdateTypeLabel () +void kpEffectBlurSharpenWidget::slotUpdateTypeLabel() { - QString text = kpEffectBlurSharpenCommand::nameForType (type ()); + QString text = kpEffectBlurSharpenCommand::nameForType(type()); #if DEBUG_KP_EFFECT_BLUR_SHARPEN qCDebug(kpLogWidgets) << "kpEffectBlurSharpenWidget::slotUpdateTypeLabel() text=" - << text; + << text; #endif - const int h = m_typeLabel->height (); - m_typeLabel->setText (text); - if (m_typeLabel->height () != h) - { + const int h = m_typeLabel->height(); + m_typeLabel->setText(text); + if (m_typeLabel->height() != h) { qCCritical(kpLogWidgets) << "Label changed height despite the hack in ctor:" - << "was=" << h - << "now=" << m_typeLabel->height (); + << "was=" << h + << "now=" << m_typeLabel->height(); } } - // protected -kpEffectBlurSharpen::Type kpEffectBlurSharpenWidget::type () const +kpEffectBlurSharpen::Type kpEffectBlurSharpenWidget::type() const { - if (m_amountInput->value () == 0) { + if (m_amountInput->value() == 0) { return kpEffectBlurSharpen::None; } - if (m_amountInput->value () < 0) { + if (m_amountInput->value() < 0) { return kpEffectBlurSharpen::Blur; } return kpEffectBlurSharpen::Sharpen; } // protected -int kpEffectBlurSharpenWidget::strength () const +int kpEffectBlurSharpenWidget::strength() const { - return qAbs (m_amountInput->value ()); + return qAbs(m_amountInput->value()); } - - diff --git a/widgets/imagelib/effects/kpEffectEmbossWidget.h b/widgets/imagelib/effects/kpEffectEmbossWidget.h --- a/widgets/imagelib/effects/kpEffectEmbossWidget.h +++ b/widgets/imagelib/effects/kpEffectEmbossWidget.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,38 +24,34 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectEmbossWidget_H #define kpEffectEmbossWidget_H - #include "imagelib/kpColor.h" #include "kpEffectWidgetBase.h" - class QCheckBox; class kpEffectEmbossWidget : public kpEffectWidgetBase { -Q_OBJECT + Q_OBJECT public: kpEffectEmbossWidget (bool actOnSelection, QWidget *parent); ~kpEffectEmbossWidget () override; - QString caption () const override; + QString caption() const override; - bool isNoOp () const override; - kpImage applyEffect (const kpImage &image) override; + bool isNoOp() const override; + kpImage applyEffect(const kpImage &image) override; - kpEffectCommandBase *createCommand ( + kpEffectCommandBase *createCommand( kpCommandEnvironment *cmdEnviron) const override; protected: - int strength () const; + int strength() const; QCheckBox *m_enableCheckBox; }; - #endif // kpEffectEmbossWidget_H diff --git a/widgets/imagelib/effects/kpEffectEmbossWidget.cpp b/widgets/imagelib/effects/kpEffectEmbossWidget.cpp --- a/widgets/imagelib/effects/kpEffectEmbossWidget.cpp +++ b/widgets/imagelib/effects/kpEffectEmbossWidget.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_EMBOSS 0 - #include "kpEffectEmbossWidget.h" #include @@ -40,67 +37,59 @@ #include "imagelib/effects/kpEffectEmboss.h" #include "commands/imagelib/effects/kpEffectEmbossCommand.h" - -kpEffectEmbossWidget::kpEffectEmbossWidget (bool actOnSelection, - QWidget *parent) - : kpEffectWidgetBase (actOnSelection, parent) +kpEffectEmbossWidget::kpEffectEmbossWidget (bool actOnSelection, QWidget *parent) + : kpEffectWidgetBase(actOnSelection, parent) { - auto *lay = new QGridLayout (this); + auto *lay = new QGridLayout(this); lay->setContentsMargins(0, 0, 0, 0); - m_enableCheckBox = new QCheckBox (i18n ("E&nable"), this); - - - lay->addWidget (m_enableCheckBox, 0, 0, 1, 2, Qt::AlignCenter); + m_enableCheckBox = new QCheckBox(i18n("E&nable"), this); + lay->addWidget(m_enableCheckBox, 0, 0, 1, 2, Qt::AlignCenter); // (settingsChangedDelayed() instead of settingsChanged() so that the // user can quickly press OK to apply effect to document directly and // not have to wait for the also slow preview) - connect (m_enableCheckBox, &QCheckBox::toggled, - this, &kpEffectEmbossWidget::settingsChangedDelayed); + connect(m_enableCheckBox, &QCheckBox::toggled, + this, &kpEffectEmbossWidget::settingsChangedDelayed); } kpEffectEmbossWidget::~kpEffectEmbossWidget () = default; - // public virtual [base kpEffectWidgetBase] -QString kpEffectEmbossWidget::caption () const +QString kpEffectEmbossWidget::caption() const { return {}; } - // public virtual [base kpEffectWidgetBase] -bool kpEffectEmbossWidget::isNoOp () const +bool kpEffectEmbossWidget::isNoOp() const { //return (m_amountInput->value () == 0); - return !m_enableCheckBox->isChecked (); + return !m_enableCheckBox->isChecked(); } // public virtual [base kpEffectWidgetBase] -kpImage kpEffectEmbossWidget::applyEffect (const kpImage &image) +kpImage kpEffectEmbossWidget::applyEffect(const kpImage &image) { - if (isNoOp ()) { + if (isNoOp()) { return image; } - return kpEffectEmboss::applyEffect (image, strength ()); + return kpEffectEmboss::applyEffect(image, strength()); } // public virtual [base kpEffectWidgetBase] -kpEffectCommandBase *kpEffectEmbossWidget::createCommand ( - kpCommandEnvironment *cmdEnviron) const +kpEffectCommandBase *kpEffectEmbossWidget::createCommand( + kpCommandEnvironment *cmdEnviron) const { - return new kpEffectEmbossCommand (strength (), - m_actOnSelection, - cmdEnviron); + return new kpEffectEmbossCommand(strength(), + m_actOnSelection, + cmdEnviron); } // protected -int kpEffectEmbossWidget::strength () const +int kpEffectEmbossWidget::strength() const { return kpEffectEmboss::MaxStrength; } - - diff --git a/widgets/imagelib/effects/kpEffectFlattenWidget.h b/widgets/imagelib/effects/kpEffectFlattenWidget.h --- a/widgets/imagelib/effects/kpEffectFlattenWidget.h +++ b/widgets/imagelib/effects/kpEffectFlattenWidget.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,56 +24,48 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectFlattenWidget_H #define kpEffectFlattenWidget_H - #include #include "kpEffectWidgetBase.h" - class QCheckBox; class KColorButton; - class kpEffectFlattenWidget : public kpEffectWidgetBase { -Q_OBJECT + Q_OBJECT public: kpEffectFlattenWidget (bool actOnSelection, QWidget *parent); ~kpEffectFlattenWidget () override; - static QColor s_lastColor1, s_lastColor2; - - QColor color1 () const; - QColor color2 () const; - + QColor color1() const; + QColor color2() const; // // kpEffectWidgetBase interface // - QString caption () const override; + QString caption() const override; - bool isNoOp () const override; - kpImage applyEffect (const kpImage &image) override; + bool isNoOp() const override; + kpImage applyEffect(const kpImage &image) override; - kpEffectCommandBase *createCommand ( + kpEffectCommandBase *createCommand( kpCommandEnvironment *cmdEnviron) const override; protected slots: - void slotEnableChanged (bool enable); + void slotEnableChanged(bool enable); protected: QCheckBox *m_enableCheckBox; KColorButton *m_color1Button, *m_color2Button; }; - #endif // kpEffectFlattenWidget_H diff --git a/widgets/imagelib/effects/kpEffectFlattenWidget.cpp b/widgets/imagelib/effects/kpEffectFlattenWidget.cpp --- a/widgets/imagelib/effects/kpEffectFlattenWidget.cpp +++ b/widgets/imagelib/effects/kpEffectFlattenWidget.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_FLATTEN 0 - #include "kpEffectFlattenWidget.h" #include "kpDefs.h" @@ -44,139 +41,126 @@ #include #include - // public static QColor kpEffectFlattenWidget::s_lastColor1; QColor kpEffectFlattenWidget::s_lastColor2; -kpEffectFlattenWidget::kpEffectFlattenWidget (bool actOnSelection, - QWidget *parent) - : kpEffectWidgetBase (actOnSelection, parent) +kpEffectFlattenWidget::kpEffectFlattenWidget (bool actOnSelection, QWidget *parent) + : kpEffectWidgetBase(actOnSelection, parent) { - if (!s_lastColor1.isValid () || !s_lastColor2.isValid ()) - { - KConfigGroup cfgGroupSaver (KSharedConfig::openConfig (), kpSettingsGroupFlattenEffect); + if (!s_lastColor1.isValid() || !s_lastColor2.isValid()) { + KConfigGroup cfgGroupSaver(KSharedConfig::openConfig(), kpSettingsGroupFlattenEffect); - s_lastColor1 = cfgGroupSaver.readEntry (kpSettingFlattenEffectColor1, QColor ()); - if (!s_lastColor1.isValid ()) { + s_lastColor1 = cfgGroupSaver.readEntry(kpSettingFlattenEffectColor1, QColor()); + if (!s_lastColor1.isValid()) { s_lastColor1 = Qt::red; } - s_lastColor2 = cfgGroupSaver.readEntry (kpSettingFlattenEffectColor2, QColor ()); - if (!s_lastColor2.isValid ()) { + s_lastColor2 = cfgGroupSaver.readEntry(kpSettingFlattenEffectColor2, QColor()); + if (!s_lastColor2.isValid()) { s_lastColor2 = Qt::blue; } } + m_enableCheckBox = new QCheckBox(i18n("E&nable"), this); - m_enableCheckBox = new QCheckBox (i18n ("E&nable"), this); + m_color1Button = new KColorButton(s_lastColor1, this); + m_color2Button = new KColorButton(s_lastColor2, this); - m_color1Button = new KColorButton (s_lastColor1, this); - m_color2Button = new KColorButton (s_lastColor2, this); + m_color1Button->setEnabled(false); + m_color2Button->setEnabled(false); - - m_color1Button->setEnabled (false); - m_color2Button->setEnabled (false); - - auto *lay = new QVBoxLayout (this); + auto *lay = new QVBoxLayout(this); lay->setContentsMargins(0, 0, 0, 0); - lay->addWidget (m_enableCheckBox); - lay->addWidget (m_color1Button); - lay->addWidget (m_color2Button); + lay->addWidget(m_enableCheckBox); + lay->addWidget(m_color1Button); + lay->addWidget(m_color2Button); - connect (m_enableCheckBox, &QCheckBox::toggled, - this, &kpEffectFlattenWidget::slotEnableChanged); + connect(m_enableCheckBox, &QCheckBox::toggled, + this, &kpEffectFlattenWidget::slotEnableChanged); - connect (m_color1Button, &KColorButton::changed, - this, &kpEffectFlattenWidget::settingsChanged); + connect(m_color1Button, &KColorButton::changed, + this, &kpEffectFlattenWidget::settingsChanged); - connect (m_color2Button, &KColorButton::changed, - this, &kpEffectFlattenWidget::settingsChanged); + connect(m_color2Button, &KColorButton::changed, + this, &kpEffectFlattenWidget::settingsChanged); } kpEffectFlattenWidget::~kpEffectFlattenWidget () { - s_lastColor1 = color1 (); - s_lastColor2 = color2 (); - + s_lastColor1 = color1(); + s_lastColor2 = color2(); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupFlattenEffect); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupFlattenEffect); - cfg.writeEntry (kpSettingFlattenEffectColor1, s_lastColor1); - cfg.writeEntry (kpSettingFlattenEffectColor2, s_lastColor2); - cfg.sync (); + cfg.writeEntry(kpSettingFlattenEffectColor1, s_lastColor1); + cfg.writeEntry(kpSettingFlattenEffectColor2, s_lastColor2); + cfg.sync(); } - // public -QColor kpEffectFlattenWidget::color1 () const +QColor kpEffectFlattenWidget::color1() const { - return m_color1Button->color (); + return m_color1Button->color(); } // public -QColor kpEffectFlattenWidget::color2 () const +QColor kpEffectFlattenWidget::color2() const { - return m_color2Button->color (); + return m_color2Button->color(); } - // // kpEffectFlattenWidget implements kpEffectWidgetBase interface // // public virtual [base kpEffectWidgetBase] -QString kpEffectFlattenWidget::caption () const +QString kpEffectFlattenWidget::caption() const { - return i18n ("Colors"); + return i18n("Colors"); } - // public virtual [base kpEffectWidgetBase] -bool kpEffectFlattenWidget::isNoOp () const +bool kpEffectFlattenWidget::isNoOp() const { - return !m_enableCheckBox->isChecked (); + return !m_enableCheckBox->isChecked(); } // public virtual [base kpEffectWidgetBase] -kpImage kpEffectFlattenWidget::applyEffect (const kpImage &image) +kpImage kpEffectFlattenWidget::applyEffect(const kpImage &image) { #if DEBUG_KP_EFFECT_FLATTEN qCDebug(kpLogWidgets) << "kpEffectFlattenWidget::applyEffect() nop=" - << isNoOp () << endl; + << isNoOp() << endl; #endif - if (isNoOp ()) { + if (isNoOp()) { return image; } - return kpEffectFlatten::applyEffect (image, color1 (), color2 ()); + return kpEffectFlatten::applyEffect(image, color1(), color2()); } - // public virtual [base kpEffectWidgetBase] -kpEffectCommandBase *kpEffectFlattenWidget::createCommand ( - kpCommandEnvironment *cmdEnviron) const +kpEffectCommandBase *kpEffectFlattenWidget::createCommand( + kpCommandEnvironment *cmdEnviron) const { - return new kpEffectFlattenCommand (color1 (), color2 (), - m_actOnSelection, - cmdEnviron); + return new kpEffectFlattenCommand(color1(), color2(), + m_actOnSelection, + cmdEnviron); } - // protected slot: -void kpEffectFlattenWidget::slotEnableChanged (bool enable) +void kpEffectFlattenWidget::slotEnableChanged(bool enable) { #if DEBUG_KP_EFFECT_FLATTEN qCDebug(kpLogWidgets) << "kpEffectFlattenWidget::slotEnableChanged(" << enable - << ") enableButton=" << m_enableCheckBox->isChecked () - << endl; + << ") enableButton=" << m_enableCheckBox->isChecked() + << endl; #endif - m_color1Button->setEnabled (enable); - m_color2Button->setEnabled (enable); + m_color1Button->setEnabled(enable); + m_color2Button->setEnabled(enable); - emit settingsChanged (); + emit settingsChanged(); } - - diff --git a/widgets/imagelib/effects/kpEffectHSVWidget.h b/widgets/imagelib/effects/kpEffectHSVWidget.h --- a/widgets/imagelib/effects/kpEffectHSVWidget.h +++ b/widgets/imagelib/effects/kpEffectHSVWidget.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2007 Mike Gashler All rights reserved. @@ -25,38 +24,34 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectHSVWidget_H #define kpEffectHSVWidget_H - #include "kpEffectWidgetBase.h" #include "kpNumInput.h" class kpDoubleNumInput; - class kpEffectHSVWidget : public kpEffectWidgetBase { -Q_OBJECT + Q_OBJECT public: kpEffectHSVWidget (bool actOnSelection, QWidget *parent); ~kpEffectHSVWidget () override; - QString caption () const override; + QString caption() const override; - bool isNoOp () const override; - kpImage applyEffect (const kpImage &image) override; + bool isNoOp() const override; + kpImage applyEffect(const kpImage &image) override; - kpEffectCommandBase *createCommand ( + kpEffectCommandBase *createCommand( kpCommandEnvironment *cmdEnviron) const override; protected: kpDoubleNumInput *m_hueInput; kpDoubleNumInput *m_saturationInput; kpDoubleNumInput *m_valueInput; }; - #endif // kpEffectHSVWidget_H diff --git a/widgets/imagelib/effects/kpEffectHSVWidget.cpp b/widgets/imagelib/effects/kpEffectHSVWidget.cpp --- a/widgets/imagelib/effects/kpEffectHSVWidget.cpp +++ b/widgets/imagelib/effects/kpEffectHSVWidget.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2007 Mike Gashler All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpEffectHSVWidget.h" #include @@ -38,84 +36,80 @@ #include "imagelib/effects/kpEffectHSV.h" #include "commands/imagelib/effects/kpEffectHSVCommand.h" - kpEffectHSVWidget::kpEffectHSVWidget (bool actOnSelection, QWidget *parent) - : kpEffectWidgetBase (actOnSelection, parent) + : kpEffectWidgetBase(actOnSelection, parent) { - auto *lay = new QGridLayout (this); + auto *lay = new QGridLayout(this); lay->setContentsMargins(0, 0, 0, 0); - auto *hueLabel = new QLabel (i18n ("&Hue:"), this); - auto *saturationLabel = new QLabel (i18n ("&Saturation:"), this); - auto *valueLabel = new QLabel (i18nc ("The V of HSV", "&Value:"), this); - - m_hueInput = new kpDoubleNumInput (this); - m_hueInput->setRange (-180, 180, 15/*step*/); + auto *hueLabel = new QLabel(i18n("&Hue:"), this); + auto *saturationLabel = new QLabel(i18n("&Saturation:"), this); + auto *valueLabel = new QLabel(i18nc("The V of HSV", "&Value:"), this); - m_saturationInput = new kpDoubleNumInput (this); - m_saturationInput->setRange (-1, 1, 0.1/*step*/); + m_hueInput = new kpDoubleNumInput(this); + m_hueInput->setRange(-180, 180, 15 /*step*/); - m_valueInput = new kpDoubleNumInput (this); - m_valueInput->setRange (-1, 1, 0.1/*step*/); + m_saturationInput = new kpDoubleNumInput(this); + m_saturationInput->setRange(-1, 1, 0.1 /*step*/); - hueLabel->setBuddy (m_hueInput); - saturationLabel->setBuddy (m_saturationInput); - valueLabel->setBuddy (m_valueInput); + m_valueInput = new kpDoubleNumInput(this); + m_valueInput->setRange(-1, 1, 0.1 /*step*/); - lay->addWidget (hueLabel, 0, 0); - lay->addWidget (m_hueInput, 0, 1); + hueLabel->setBuddy(m_hueInput); + saturationLabel->setBuddy(m_saturationInput); + valueLabel->setBuddy(m_valueInput); - lay->addWidget (saturationLabel, 1, 0); - lay->addWidget (m_saturationInput, 1, 1); + lay->addWidget(hueLabel, 0, 0); + lay->addWidget(m_hueInput, 0, 1); - lay->addWidget (valueLabel, 2, 0); - lay->addWidget (m_valueInput, 2, 1); + lay->addWidget(saturationLabel, 1, 0); + lay->addWidget(m_saturationInput, 1, 1); - lay->setColumnStretch (1, 1); + lay->addWidget(valueLabel, 2, 0); + lay->addWidget(m_valueInput, 2, 1); + lay->setColumnStretch(1, 1); - connect (m_hueInput, &kpDoubleNumInput::valueChanged, - this, &kpEffectHSVWidget::settingsChangedDelayed); + connect(m_hueInput, &kpDoubleNumInput::valueChanged, + this, &kpEffectHSVWidget::settingsChangedDelayed); - connect (m_saturationInput, &kpDoubleNumInput::valueChanged, - this, &kpEffectHSVWidget::settingsChangedDelayed); + connect(m_saturationInput, &kpDoubleNumInput::valueChanged, + this, &kpEffectHSVWidget::settingsChangedDelayed); - connect (m_valueInput, &kpDoubleNumInput::valueChanged, - this, &kpEffectHSVWidget::settingsChangedDelayed); + connect(m_valueInput, &kpDoubleNumInput::valueChanged, + this, &kpEffectHSVWidget::settingsChangedDelayed); } kpEffectHSVWidget::~kpEffectHSVWidget () = default; - // public virtual [base kpEffectWidgetBase] -QString kpEffectHSVWidget::caption () const +QString kpEffectHSVWidget::caption() const { // TODO: Why doesn't this have a caption? Ditto for the other effects. return {}; } - // public virtual [base kpEffectWidgetBase] -bool kpEffectHSVWidget::isNoOp () const +bool kpEffectHSVWidget::isNoOp() const { - return m_hueInput->value () == 0 && m_saturationInput->value () == 0 && m_valueInput->value () == 0; + return m_hueInput->value() == 0 && m_saturationInput->value() == 0 + && m_valueInput->value() == 0; } // public virtual [base kpEffectWidgetBase] -kpImage kpEffectHSVWidget::applyEffect (const kpImage &image) +kpImage kpEffectHSVWidget::applyEffect(const kpImage &image) { - return kpEffectHSV::applyEffect (image, - m_hueInput->value (), m_saturationInput->value (), m_valueInput->value ()); + return kpEffectHSV::applyEffect(image, + m_hueInput->value(), + m_saturationInput->value(), m_valueInput->value()); } // public virtual [base kpEffectWidgetBase] -kpEffectCommandBase *kpEffectHSVWidget::createCommand ( - kpCommandEnvironment *cmdEnviron) const +kpEffectCommandBase *kpEffectHSVWidget::createCommand( + kpCommandEnvironment *cmdEnviron) const { - return new kpEffectHSVCommand ( - m_hueInput->value (), m_saturationInput->value (), m_valueInput->value (), + return new kpEffectHSVCommand( + m_hueInput->value(), m_saturationInput->value(), m_valueInput->value(), m_actOnSelection, cmdEnviron); } - - diff --git a/widgets/imagelib/effects/kpEffectInvertWidget.h b/widgets/imagelib/effects/kpEffectInvertWidget.h --- a/widgets/imagelib/effects/kpEffectInvertWidget.h +++ b/widgets/imagelib/effects/kpEffectInvertWidget.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,45 +24,38 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectInvertWidget_H #define kpEffectInvertWidget_H - #include "kpEffectWidgetBase.h" - class QCheckBox; - class kpEffectInvertWidget : public kpEffectWidgetBase { -Q_OBJECT + Q_OBJECT public: - kpEffectInvertWidget (bool actOnSelection, - QWidget *parent); + kpEffectInvertWidget (bool actOnSelection, QWidget *parent); ~kpEffectInvertWidget () override; - - int channels () const; - + int channels() const; // // kpEffectWidgetBase interface // - QString caption () const override; + QString caption() const override; - bool isNoOp () const override; - kpImage applyEffect (const kpImage &image) override; + bool isNoOp() const override; + kpImage applyEffect(const kpImage &image) override; - kpEffectCommandBase *createCommand ( + kpEffectCommandBase *createCommand( kpCommandEnvironment *cmdEnviron) const override; protected slots: - void slotRGBCheckBoxToggled (); - void slotAllCheckBoxToggled (); + void slotRGBCheckBoxToggled(); + void slotAllCheckBoxToggled(); protected: QCheckBox *m_redCheckBox, *m_greenCheckBox, *m_blueCheckBox, @@ -73,5 +65,4 @@ bool m_inSignalHandler; }; - #endif // kpEffectInvertWidget_H diff --git a/widgets/imagelib/effects/kpEffectInvertWidget.cpp b/widgets/imagelib/effects/kpEffectInvertWidget.cpp --- a/widgets/imagelib/effects/kpEffectInvertWidget.cpp +++ b/widgets/imagelib/effects/kpEffectInvertWidget.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_INVERT 0 - #include "kpEffectInvertWidget.h" #include "imagelib/effects/kpEffectInvert.h" @@ -43,170 +40,155 @@ #include #include - -kpEffectInvertWidget::kpEffectInvertWidget (bool actOnSelection, - QWidget *parent) - : kpEffectWidgetBase (actOnSelection, parent) +kpEffectInvertWidget::kpEffectInvertWidget (bool actOnSelection, QWidget *parent) + : kpEffectWidgetBase(actOnSelection, parent) { - auto *topLevelLay = new QVBoxLayout (this); + auto *topLevelLay = new QVBoxLayout(this); topLevelLay->setContentsMargins(0, 0, 0, 0); - auto *centerWidget = new QWidget (this); - topLevelLay->addWidget (centerWidget, 0/*stretch*/, Qt::AlignCenter); + auto *centerWidget = new QWidget(this); + topLevelLay->addWidget(centerWidget, 0 /*stretch*/, Qt::AlignCenter); - auto *centerWidgetLay = new QVBoxLayout (centerWidget ); + auto *centerWidgetLay = new QVBoxLayout(centerWidget); centerWidgetLay->setContentsMargins(0, 0, 0, 0); - m_redCheckBox = new QCheckBox (i18n ("&Red"), centerWidget); - m_greenCheckBox = new QCheckBox (i18n ("&Green"), centerWidget); - m_blueCheckBox = new QCheckBox (i18n ("&Blue"), centerWidget); - - auto *spaceWidget = new QWidget (centerWidget); - spaceWidget->setFixedSize (1, fontMetrics ().height () / 4); + m_redCheckBox = new QCheckBox(i18n("&Red"), centerWidget); + m_greenCheckBox = new QCheckBox(i18n("&Green"), centerWidget); + m_blueCheckBox = new QCheckBox(i18n("&Blue"), centerWidget); - m_allCheckBox = new QCheckBox (i18n ("&All"), centerWidget); + auto *spaceWidget = new QWidget(centerWidget); + spaceWidget->setFixedSize(1, fontMetrics().height() / 4); + m_allCheckBox = new QCheckBox(i18n("&All"), centerWidget); - m_redCheckBox->setChecked (false); - m_greenCheckBox->setChecked (false); - m_blueCheckBox->setChecked (false); + m_redCheckBox->setChecked(false); + m_greenCheckBox->setChecked(false); + m_blueCheckBox->setChecked(false); - m_allCheckBox->setChecked (false); + m_allCheckBox->setChecked(false); + centerWidgetLay->addWidget(m_redCheckBox); + centerWidgetLay->addWidget(m_greenCheckBox); + centerWidgetLay->addWidget(m_blueCheckBox); - centerWidgetLay->addWidget (m_redCheckBox); - centerWidgetLay->addWidget (m_greenCheckBox); - centerWidgetLay->addWidget (m_blueCheckBox); - - centerWidgetLay->addWidget (spaceWidget); - - centerWidgetLay->addWidget (m_allCheckBox); + centerWidgetLay->addWidget(spaceWidget); + centerWidgetLay->addWidget(m_allCheckBox); m_inSignalHandler = false; - connect (m_redCheckBox, &QCheckBox::toggled, - this, &kpEffectInvertWidget::slotRGBCheckBoxToggled); + connect(m_redCheckBox, &QCheckBox::toggled, + this, &kpEffectInvertWidget::slotRGBCheckBoxToggled); - connect (m_greenCheckBox, &QCheckBox::toggled, - this, &kpEffectInvertWidget::slotRGBCheckBoxToggled); + connect(m_greenCheckBox, &QCheckBox::toggled, + this, &kpEffectInvertWidget::slotRGBCheckBoxToggled); - connect (m_blueCheckBox, &QCheckBox::toggled, - this, &kpEffectInvertWidget::slotRGBCheckBoxToggled); + connect(m_blueCheckBox, &QCheckBox::toggled, + this, &kpEffectInvertWidget::slotRGBCheckBoxToggled); - connect (m_allCheckBox, &QCheckBox::toggled, - this, &kpEffectInvertWidget::slotAllCheckBoxToggled); + connect(m_allCheckBox, &QCheckBox::toggled, + this, &kpEffectInvertWidget::slotAllCheckBoxToggled); } kpEffectInvertWidget::~kpEffectInvertWidget () = default; - // public -int kpEffectInvertWidget::channels () const +int kpEffectInvertWidget::channels() const { #if DEBUG_KP_EFFECT_INVERT qCDebug(kpLogWidgets) << "kpEffectInvertWidget::channels()" - << " isChecked: r=" << m_redCheckBox->isChecked () - << " g=" << m_greenCheckBox->isChecked () - << " b=" << m_blueCheckBox->isChecked () - << endl; + << " isChecked: r=" << m_redCheckBox->isChecked() + << " g=" << m_greenCheckBox->isChecked() + << " b=" << m_blueCheckBox->isChecked() + << endl; #endif int channels = 0; - - if (m_redCheckBox->isChecked ()) { + if (m_redCheckBox->isChecked()) { channels |= kpEffectInvert::Red; } - if (m_greenCheckBox->isChecked ()) { + if (m_greenCheckBox->isChecked()) { channels |= kpEffectInvert::Green; } - if (m_blueCheckBox->isChecked ()) { + if (m_blueCheckBox->isChecked()) { channels |= kpEffectInvert::Blue; } - #if DEBUG_KP_EFFECT_INVERT - qCDebug(kpLogWidgets) << "\treturning channels=" << (int *) channels; + qCDebug(kpLogWidgets) << "\treturning channels=" << (int *)channels; #endif return channels; } - // // kpEffectInvertWidget implements kpEffectWidgetBase interface // // public virtual [base kpEffectWidgetBase] -QString kpEffectInvertWidget::caption () const +QString kpEffectInvertWidget::caption() const { - return i18n ("Channels"); + return i18n("Channels"); } - // public virtual [base kpEffectWidgetBase] -bool kpEffectInvertWidget::isNoOp () const +bool kpEffectInvertWidget::isNoOp() const { - return (channels () == kpEffectInvert::None); + return channels() == kpEffectInvert::None; } // public virtual [base kpEffectWidgetBase] -kpImage kpEffectInvertWidget::applyEffect (const kpImage &image) +kpImage kpEffectInvertWidget::applyEffect(const kpImage &image) { - return kpEffectInvert::applyEffect (image, channels ()); + return kpEffectInvert::applyEffect(image, channels()); } - // public virtual [base kpEffectWidgetBase] -kpEffectCommandBase *kpEffectInvertWidget::createCommand ( - kpCommandEnvironment *cmdEnviron) const +kpEffectCommandBase *kpEffectInvertWidget::createCommand( + kpCommandEnvironment *cmdEnviron) const { - return new kpEffectInvertCommand (channels (), - m_actOnSelection, - cmdEnviron); + return new kpEffectInvertCommand(channels(), + m_actOnSelection, + cmdEnviron); } - // protected slots -void kpEffectInvertWidget::slotRGBCheckBoxToggled () +void kpEffectInvertWidget::slotRGBCheckBoxToggled() { if (m_inSignalHandler) { return; } m_inSignalHandler = true; //blockSignals (true); - m_allCheckBox->setChecked (m_redCheckBox->isChecked () && - m_blueCheckBox->isChecked () && - m_greenCheckBox->isChecked ()); + m_allCheckBox->setChecked(m_redCheckBox->isChecked() + && m_blueCheckBox->isChecked() + && m_greenCheckBox->isChecked()); //blockSignals (false); - emit settingsChanged (); + emit settingsChanged(); m_inSignalHandler = false; } // protected slot -void kpEffectInvertWidget::slotAllCheckBoxToggled () +void kpEffectInvertWidget::slotAllCheckBoxToggled() { if (m_inSignalHandler) { return; } m_inSignalHandler = true; //blockSignals (true); - m_redCheckBox->setChecked (m_allCheckBox->isChecked ()); - m_greenCheckBox->setChecked (m_allCheckBox->isChecked ()); - m_blueCheckBox->setChecked (m_allCheckBox->isChecked ()); + m_redCheckBox->setChecked(m_allCheckBox->isChecked()); + m_greenCheckBox->setChecked(m_allCheckBox->isChecked()); + m_blueCheckBox->setChecked(m_allCheckBox->isChecked()); //blockSignals (false); - emit settingsChanged (); + emit settingsChanged(); m_inSignalHandler = false; } - - - diff --git a/widgets/imagelib/effects/kpEffectReduceColorsWidget.h b/widgets/imagelib/effects/kpEffectReduceColorsWidget.h --- a/widgets/imagelib/effects/kpEffectReduceColorsWidget.h +++ b/widgets/imagelib/effects/kpEffectReduceColorsWidget.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,39 +24,33 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectReduceColorsWidget_H #define kpEffectReduceColorsWidget_H - #include "kpEffectWidgetBase.h" - class QRadioButton; - class kpEffectReduceColorsWidget : public kpEffectWidgetBase { -Q_OBJECT + Q_OBJECT public: - kpEffectReduceColorsWidget (bool actOnSelection, - QWidget *parent); - - int depth () const; - bool dither () const; + kpEffectReduceColorsWidget (bool actOnSelection, QWidget *parent); + int depth() const; + bool dither() const; // // kpEffectWidgetBase interface // - QString caption () const override; + QString caption() const override; - bool isNoOp () const override; - kpImage applyEffect (const kpImage &image) override; + bool isNoOp() const override; + kpImage applyEffect(const kpImage &image) override; - kpEffectCommandBase *createCommand ( + kpEffectCommandBase *createCommand( kpCommandEnvironment *cmdEnviron) const override; protected: @@ -69,5 +62,4 @@ QRadioButton *m_defaultRadioButton; }; - #endif // kpEffectReduceColorsWidget_H diff --git a/widgets/imagelib/effects/kpEffectReduceColorsWidget.cpp b/widgets/imagelib/effects/kpEffectReduceColorsWidget.cpp --- a/widgets/imagelib/effects/kpEffectReduceColorsWidget.cpp +++ b/widgets/imagelib/effects/kpEffectReduceColorsWidget.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_EFFECT_REDUCE_COLORS 0 - #include "kpEffectReduceColorsWidget.h" #include "imagelib/effects/kpEffectReduceColors.h" @@ -46,81 +43,75 @@ #include #include - -kpEffectReduceColorsWidget::kpEffectReduceColorsWidget (bool actOnSelection, - QWidget *parent) - : kpEffectWidgetBase (actOnSelection, parent) +kpEffectReduceColorsWidget::kpEffectReduceColorsWidget (bool actOnSelection, QWidget *parent) + : kpEffectWidgetBase(actOnSelection, parent) { - auto *lay = new QVBoxLayout (this); + auto *lay = new QVBoxLayout(this); lay->setContentsMargins(0, 0, 0, 0); - m_blackAndWhiteRadioButton = - new QRadioButton (i18n ("&Monochrome"), this); - - m_blackAndWhiteDitheredRadioButton = - new QRadioButton (i18n ("Mo&nochrome (dithered)"), this); + m_blackAndWhiteRadioButton + = new QRadioButton(i18n("&Monochrome"), this); - m_8BitRadioButton = new QRadioButton (i18n ("256 co&lor"), this); + m_blackAndWhiteDitheredRadioButton + = new QRadioButton(i18n("Mo&nochrome (dithered)"), this); - m_8BitDitheredRadioButton = new QRadioButton (i18n ("256 colo&r (dithered)"), this); + m_8BitRadioButton = new QRadioButton(i18n("256 co&lor"), this); - m_24BitRadioButton = new QRadioButton (i18n ("24-&bit color"), this); + m_8BitDitheredRadioButton = new QRadioButton(i18n("256 colo&r (dithered)"), this); + m_24BitRadioButton = new QRadioButton(i18n("24-&bit color"), this); // LOCOMPAT: don't think this is needed - auto *buttonGroup = new QButtonGroup (this); - buttonGroup->addButton (m_blackAndWhiteRadioButton); - buttonGroup->addButton (m_blackAndWhiteDitheredRadioButton); - buttonGroup->addButton (m_8BitRadioButton); - buttonGroup->addButton (m_8BitDitheredRadioButton); - buttonGroup->addButton (m_24BitRadioButton); + auto *buttonGroup = new QButtonGroup(this); + buttonGroup->addButton(m_blackAndWhiteRadioButton); + buttonGroup->addButton(m_blackAndWhiteDitheredRadioButton); + buttonGroup->addButton(m_8BitRadioButton); + buttonGroup->addButton(m_8BitDitheredRadioButton); + buttonGroup->addButton(m_24BitRadioButton); m_defaultRadioButton = m_24BitRadioButton; - m_defaultRadioButton->setChecked (true); + m_defaultRadioButton->setChecked(true); - lay->addWidget (m_blackAndWhiteRadioButton); - lay->addWidget (m_blackAndWhiteDitheredRadioButton); - lay->addWidget (m_8BitRadioButton); - lay->addWidget (m_8BitDitheredRadioButton); - lay->addWidget (m_24BitRadioButton); + lay->addWidget(m_blackAndWhiteRadioButton); + lay->addWidget(m_blackAndWhiteDitheredRadioButton); + lay->addWidget(m_8BitRadioButton); + lay->addWidget(m_8BitDitheredRadioButton); + lay->addWidget(m_24BitRadioButton); - connect (m_blackAndWhiteRadioButton, &QRadioButton::toggled, - this, &kpEffectReduceColorsWidget::settingsChanged); + connect(m_blackAndWhiteRadioButton, &QRadioButton::toggled, + this, &kpEffectReduceColorsWidget::settingsChanged); - connect (m_blackAndWhiteDitheredRadioButton, &QRadioButton::toggled, - this, &kpEffectReduceColorsWidget::settingsChanged); + connect(m_blackAndWhiteDitheredRadioButton, &QRadioButton::toggled, + this, &kpEffectReduceColorsWidget::settingsChanged); - connect (m_8BitRadioButton, &QRadioButton::toggled, - this, &kpEffectReduceColorsWidget::settingsChanged); + connect(m_8BitRadioButton, &QRadioButton::toggled, + this, &kpEffectReduceColorsWidget::settingsChanged); - connect (m_8BitDitheredRadioButton, &QRadioButton::toggled, - this, &kpEffectReduceColorsWidget::settingsChanged); + connect(m_8BitDitheredRadioButton, &QRadioButton::toggled, + this, &kpEffectReduceColorsWidget::settingsChanged); - connect (m_24BitRadioButton, &QRadioButton::toggled, - this, &kpEffectReduceColorsWidget::settingsChanged); + connect(m_24BitRadioButton, &QRadioButton::toggled, + this, &kpEffectReduceColorsWidget::settingsChanged); } //--------------------------------------------------------------------- // public -int kpEffectReduceColorsWidget::depth () const +int kpEffectReduceColorsWidget::depth() const { // These values (1, 8, 32) are QImage's supported depths. // TODO: Qt-4.7.1: 1, 8, 16, 24 and 32 - if (m_blackAndWhiteRadioButton->isChecked () || - m_blackAndWhiteDitheredRadioButton->isChecked ()) - { + if (m_blackAndWhiteRadioButton->isChecked() + || m_blackAndWhiteDitheredRadioButton->isChecked()) { return 1; } - if (m_8BitRadioButton->isChecked () || - m_8BitDitheredRadioButton->isChecked ()) - { + if (m_8BitRadioButton->isChecked() + || m_8BitDitheredRadioButton->isChecked()) { return 8; } - if (m_24BitRadioButton->isChecked ()) - { + if (m_24BitRadioButton->isChecked()) { return 32; } @@ -130,49 +121,48 @@ //--------------------------------------------------------------------- // public -bool kpEffectReduceColorsWidget::dither () const +bool kpEffectReduceColorsWidget::dither() const { - return (m_blackAndWhiteDitheredRadioButton->isChecked () || - m_8BitDitheredRadioButton->isChecked ()); + return m_blackAndWhiteDitheredRadioButton->isChecked() + || m_8BitDitheredRadioButton->isChecked(); } //--------------------------------------------------------------------- // // kpEffectReduceColorsWidget implements kpEffectWidgetBase interface // // public virtual [base kpEffectWidgetBase] -QString kpEffectReduceColorsWidget::caption () const +QString kpEffectReduceColorsWidget::caption() const { - return i18n ("Reduce To"); + return i18n("Reduce To"); } //--------------------------------------------------------------------- // public virtual [base kpEffectWidgetBase] -bool kpEffectReduceColorsWidget::isNoOp () const +bool kpEffectReduceColorsWidget::isNoOp() const { - return (!m_defaultRadioButton || m_defaultRadioButton->isChecked ()); + return !m_defaultRadioButton || m_defaultRadioButton->isChecked(); } //--------------------------------------------------------------------- // public virtual [base kpEffectWidgetBase] -kpImage kpEffectReduceColorsWidget::applyEffect (const kpImage &image) +kpImage kpEffectReduceColorsWidget::applyEffect(const kpImage &image) { - return kpEffectReduceColors::applyEffect (image, depth (), dither ()); + return kpEffectReduceColors::applyEffect(image, depth(), dither()); } //--------------------------------------------------------------------- // public virtual [base kpEffectWidgetBase] -kpEffectCommandBase *kpEffectReduceColorsWidget::createCommand ( - kpCommandEnvironment *cmdEnviron) const +kpEffectCommandBase *kpEffectReduceColorsWidget::createCommand( + kpCommandEnvironment *cmdEnviron) const { - return new kpEffectReduceColorsCommand (depth (), dither (), - m_actOnSelection, - cmdEnviron); + return new kpEffectReduceColorsCommand(depth(), dither(), + m_actOnSelection, + cmdEnviron); } //--------------------------------------------------------------------- - diff --git a/widgets/imagelib/effects/kpEffectToneEnhanceWidget.h b/widgets/imagelib/effects/kpEffectToneEnhanceWidget.h --- a/widgets/imagelib/effects/kpEffectToneEnhanceWidget.h +++ b/widgets/imagelib/effects/kpEffectToneEnhanceWidget.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2006 Mike Gashler @@ -26,43 +25,38 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectToneEnhanceWidget_H #define kpEffectToneEnhanceWidget_H - #include "kpEffectWidgetBase.h" #include "kpNumInput.h" class kpDoubleNumInput; - class kpEffectToneEnhanceWidget : public kpEffectWidgetBase { -Q_OBJECT + Q_OBJECT public: - kpEffectToneEnhanceWidget (bool actOnSelection, - QWidget *parent); + kpEffectToneEnhanceWidget (bool actOnSelection, QWidget *parent); ~kpEffectToneEnhanceWidget () override; - QString caption () const override; + QString caption() const override; private: - double amount () const; - double granularity () const; + double amount() const; + double granularity() const; public: - bool isNoOp () const override; - kpImage applyEffect (const kpImage &image) override; + bool isNoOp() const override; + kpImage applyEffect(const kpImage &image) override; - kpEffectCommandBase *createCommand ( + kpEffectCommandBase *createCommand( kpCommandEnvironment *cmdEnviron) const override; protected: kpDoubleNumInput *m_granularityInput; kpDoubleNumInput *m_amountInput; }; - #endif // kpEffectToneEnhanceWidget_H diff --git a/widgets/imagelib/effects/kpEffectToneEnhanceWidget.cpp b/widgets/imagelib/effects/kpEffectToneEnhanceWidget.cpp --- a/widgets/imagelib/effects/kpEffectToneEnhanceWidget.cpp +++ b/widgets/imagelib/effects/kpEffectToneEnhanceWidget.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2006 Mike Gashler @@ -26,7 +25,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpEffectToneEnhanceWidget.h" #include "imagelib/effects/kpEffectToneEnhance.h" @@ -40,100 +38,90 @@ #include "kpLogCategories.h" #include -kpEffectToneEnhanceWidget::kpEffectToneEnhanceWidget (bool actOnSelection, - QWidget *parent) - : kpEffectWidgetBase (actOnSelection, parent), - m_granularityInput (nullptr), - m_amountInput (nullptr) - +kpEffectToneEnhanceWidget::kpEffectToneEnhanceWidget (bool actOnSelection, QWidget *parent) + : kpEffectWidgetBase(actOnSelection, parent) + , m_granularityInput(nullptr) + , m_amountInput(nullptr) { - auto *lay = new QGridLayout (this); + auto *lay = new QGridLayout(this); lay->setContentsMargins(0, 0, 0, 0); // See kpEffectToneEnhance::applyEffect(). - auto *granularityLabel = new QLabel (i18n ("&Granularity:"), this); - - auto *amountLabel = new QLabel (i18n ("&Amount:"), this); - - m_granularityInput = new kpDoubleNumInput (this); - m_granularityInput->setRange (0, 1, 0.1/*step*/); - - m_amountInput = new kpDoubleNumInput (this); - m_amountInput->setRange (0, 1, 0.1/*step*/); + auto *granularityLabel = new QLabel(i18n("&Granularity:"), this); - granularityLabel->setBuddy (m_granularityInput); - amountLabel->setBuddy (m_amountInput); + auto *amountLabel = new QLabel(i18n("&Amount:"), this); + m_granularityInput = new kpDoubleNumInput(this); + m_granularityInput->setRange(0, 1, 0.1 /*step*/); - lay->addWidget (granularityLabel, 0, 0); - lay->addWidget (m_granularityInput, 0, 1); + m_amountInput = new kpDoubleNumInput(this); + m_amountInput->setRange(0, 1, 0.1 /*step*/); - lay->addWidget (amountLabel, 1, 0); - lay->addWidget (m_amountInput, 1, 1); + granularityLabel->setBuddy(m_granularityInput); + amountLabel->setBuddy(m_amountInput); - lay->setColumnStretch (1, 1); + lay->addWidget(granularityLabel, 0, 0); + lay->addWidget(m_granularityInput, 0, 1); + lay->addWidget(amountLabel, 1, 0); + lay->addWidget(m_amountInput, 1, 1); - connect (m_granularityInput, &kpDoubleNumInput::valueChanged, - this, &kpEffectToneEnhanceWidget::settingsChangedDelayed); + lay->setColumnStretch(1, 1); - connect (m_amountInput, &kpDoubleNumInput::valueChanged, - this, &kpEffectToneEnhanceWidget::settingsChangedDelayed); + connect(m_granularityInput, &kpDoubleNumInput::valueChanged, + this, &kpEffectToneEnhanceWidget::settingsChangedDelayed); + connect(m_amountInput, &kpDoubleNumInput::valueChanged, + this, &kpEffectToneEnhanceWidget::settingsChangedDelayed); } kpEffectToneEnhanceWidget::~kpEffectToneEnhanceWidget () = default; - // public virtual [base kpEffectWidgetBase] -QString kpEffectToneEnhanceWidget::caption () const +QString kpEffectToneEnhanceWidget::caption() const { // TODO: Why doesn't this have a caption? Ditto for the other effects. return {}; } - // private -double kpEffectToneEnhanceWidget::amount () const +double kpEffectToneEnhanceWidget::amount() const { - return m_amountInput ? m_amountInput->value () : 0; + return m_amountInput ? m_amountInput->value() : 0; } // private -double kpEffectToneEnhanceWidget::granularity () const +double kpEffectToneEnhanceWidget::granularity() const { - return m_granularityInput ? m_granularityInput->value () : 0; + return m_granularityInput ? m_granularityInput->value() : 0; } - // public virtual [base kpEffectWidgetBase] -bool kpEffectToneEnhanceWidget::isNoOp () const +bool kpEffectToneEnhanceWidget::isNoOp() const { // If the "amount" is 0, nothing happens regardless of the granularity. // Note that if "granularity" is 0 but "amount" > 0, the effect _is_ active. // Therefore, "granularity" should have no involvement in this check. - if (amount () == 0) { + if (amount() == 0) { return true; } return false; } // public virtual [base kpEffectWidgetBase] -kpImage kpEffectToneEnhanceWidget::applyEffect (const kpImage &image) +kpImage kpEffectToneEnhanceWidget::applyEffect(const kpImage &image) { - return kpEffectToneEnhance::applyEffect (image, - granularity (), amount ()); + return kpEffectToneEnhance::applyEffect(image, + granularity(), amount()); } // public virtual [base kpEffectWidgetBase] -kpEffectCommandBase *kpEffectToneEnhanceWidget::createCommand ( - kpCommandEnvironment *cmdEnviron) const +kpEffectCommandBase *kpEffectToneEnhanceWidget::createCommand( + kpCommandEnvironment *cmdEnviron) const { - return new kpEffectToneEnhanceCommand (granularity (), amount (), - m_actOnSelection, - cmdEnviron); + return new kpEffectToneEnhanceCommand(granularity(), amount(), + m_actOnSelection, + cmdEnviron); } - - diff --git a/widgets/imagelib/effects/kpEffectWidgetBase.h b/widgets/imagelib/effects/kpEffectWidgetBase.h --- a/widgets/imagelib/effects/kpEffectWidgetBase.h +++ b/widgets/imagelib/effects/kpEffectWidgetBase.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,49 +24,44 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpEffectWidgetBase_H #define kpEffectWidgetBase_H - #include #include "imagelib/kpImage.h" - class kpCommandEnvironment; class kpEffectCommandBase; - class kpEffectWidgetBase : public QWidget { -Q_OBJECT + Q_OBJECT public: kpEffectWidgetBase (bool actOnSelection, QWidget *parent); ~kpEffectWidgetBase () override; signals: - void settingsChangedNoWaitCursor (); + void settingsChangedNoWaitCursor(); - void settingsChanged (); + void settingsChanged(); // (same as settingsChanged() but preview doesn't update until there // has been no activity for a while - used for sliders in slow effects) - void settingsChangedDelayed (); + void settingsChangedDelayed(); public: - virtual QString caption () const; + virtual QString caption() const; - virtual bool isNoOp () const = 0; - virtual kpImage applyEffect (const kpImage &image) = 0; + virtual bool isNoOp() const = 0; + virtual kpImage applyEffect(const kpImage &image) = 0; - virtual kpEffectCommandBase *createCommand ( + virtual kpEffectCommandBase *createCommand( kpCommandEnvironment *cmdEnviron) const = 0; protected: bool m_actOnSelection; }; - #endif // kpEffectWidgetBase_H diff --git a/widgets/imagelib/effects/kpEffectWidgetBase.cpp b/widgets/imagelib/effects/kpEffectWidgetBase.cpp --- a/widgets/imagelib/effects/kpEffectWidgetBase.cpp +++ b/widgets/imagelib/effects/kpEffectWidgetBase.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,24 +24,18 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpEffectWidgetBase.h" - -kpEffectWidgetBase::kpEffectWidgetBase (bool actOnSelection, - QWidget *parent) - : QWidget (parent), - m_actOnSelection (actOnSelection) +kpEffectWidgetBase::kpEffectWidgetBase (bool actOnSelection, QWidget *parent) + : QWidget(parent) + , m_actOnSelection(actOnSelection) { } kpEffectWidgetBase::~kpEffectWidgetBase () = default; - // public -QString kpEffectWidgetBase::caption () const +QString kpEffectWidgetBase::caption() const { return {}; } - - diff --git a/widgets/imagelib/effects/kpNumInput.h b/widgets/imagelib/effects/kpNumInput.h --- a/widgets/imagelib/effects/kpNumInput.h +++ b/widgets/imagelib/effects/kpNumInput.h @@ -243,7 +243,8 @@ */ void setSpecialValueText(const QString &text); - void setLabel(const QString &label, Qt::Alignment a = Qt::AlignLeft | Qt::AlignTop) Q_DECL_OVERRIDE; + void setLabel(const QString &label, + Qt::Alignment a = Qt::AlignLeft | Qt::AlignTop) Q_DECL_OVERRIDE; /** * This method returns the minimum size necessary to display the @@ -284,7 +285,6 @@ */ void valueChanged(int); - private Q_SLOTS: void spinValueChanged(int); @@ -362,8 +362,8 @@ * @param precision number of digits after the decimal point * @param parent parent QWidget */ - kpDoubleNumInput(double lower, double upper, double value, QWidget *parent = 0, double singleStep = 0.01, - int precision = 2); + kpDoubleNumInput(double lower, double upper, double value, QWidget *parent = 0, + double singleStep = 0.01, int precision = 2); /** * destructor @@ -441,7 +441,8 @@ */ void setSpecialValueText(const QString &text); - void setLabel(const QString &label, Qt::Alignment a = Qt::AlignLeft | Qt::AlignTop) Q_DECL_OVERRIDE; + void setLabel(const QString &label, + Qt::Alignment a = Qt::AlignLeft | Qt::AlignTop) Q_DECL_OVERRIDE; QSize minimumSizeHint() const Q_DECL_OVERRIDE; public Q_SLOTS: @@ -476,8 +477,7 @@ friend class kpDoubleLine; private: - void initWidget(double value, double lower, double upper, - double singleStep, int precision); + void initWidget(double value, double lower, double upper, double singleStep, int precision); double mapSliderToSpin(int) const; private: @@ -488,5 +488,4 @@ Q_DISABLE_COPY(kpDoubleNumInput) }; - #endif // kpNumInput_H diff --git a/widgets/imagelib/effects/kpNumInput.cpp b/widgets/imagelib/effects/kpNumInput.cpp --- a/widgets/imagelib/effects/kpNumInput.cpp +++ b/widgets/imagelib/effects/kpNumInput.cpp @@ -46,13 +46,13 @@ class kpNumInputPrivate { public: - kpNumInputPrivate(kpNumInput *q) : - q(q), - column1Width(0), - column2Width(0), - label(nullptr), - slider(nullptr), - labelAlignment(nullptr) + kpNumInputPrivate(kpNumInput *q) + : q(q) + , column1Width(0) + , column2Width(0) + , label(nullptr) + , slider(nullptr) + , labelAlignment(nullptr) { } @@ -64,23 +64,27 @@ kpNumInput *q; int column1Width, column2Width; - QLabel *label; + QLabel *label; QSlider *slider; - QSize sliderSize, labelSize; + QSize sliderSize, labelSize; Qt::Alignment labelAlignment; }; #define K_USING_kpNumInput_P(_d) kpNumInputPrivate *_d = kpNumInputPrivate::get(this) kpNumInput::kpNumInput(QWidget *parent) - : QWidget(parent), d(new kpNumInputPrivate(this)) + : QWidget(parent) + , d(new kpNumInputPrivate(this)) { setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed)); setFocusPolicy(Qt::StrongFocus); - KConfigDialogManager::changedMap()->insert(QStringLiteral("kpIntNumInput"), SIGNAL(valueChanged(int))); - KConfigDialogManager::changedMap()->insert(QStringLiteral("QSpinBox"), SIGNAL(valueChanged(int))); - KConfigDialogManager::changedMap()->insert(QStringLiteral("kpDoubleSpinBox"), SIGNAL(valueChanged(double))); + KConfigDialogManager::changedMap()->insert(QStringLiteral("kpIntNumInput"), + SIGNAL(valueChanged(int))); + KConfigDialogManager::changedMap()->insert(QStringLiteral("QSpinBox"), + SIGNAL(valueChanged(int))); + KConfigDialogManager::changedMap()->insert(QStringLiteral("kpDoubleSpinBox"), + SIGNAL(valueChanged(double))); } kpNumInput::~kpNumInput() @@ -141,7 +145,6 @@ d->sliderSize = (d->slider ? d->slider->sizeHint() : QSize(0, 0)); doLayout(); - } QSize kpNumInput::sizeHint() const @@ -163,11 +166,13 @@ { public: kpIntNumInput *q; - QSpinBox *intSpinBox; - QSize intSpinBoxSize; + QSpinBox *intSpinBox; + QSize intSpinBoxSize; kpIntNumInputPrivate(kpIntNumInput *q) - : q(q) {} + : q(q) + { + } }; kpIntNumInput::kpIntNumInput(QWidget *parent) @@ -197,7 +202,8 @@ d->intSpinBox->setValue(val); d->intSpinBox->setObjectName(QStringLiteral("kpIntNumInput::QSpinBox")); - connect(d->intSpinBox, QOverload::of(&QSpinBox::valueChanged), this, &kpIntNumInput::spinValueChanged); + connect(d->intSpinBox, QOverload::of( + &QSpinBox::valueChanged), this, &kpIntNumInput::spinValueChanged); setFocusProxy(d->intSpinBox); layout(); @@ -217,7 +223,8 @@ void kpIntNumInput::setRange(int lower, int upper, int singleStep) { if (upper < lower || singleStep <= 0) { - qDebug() << "WARNING: kpIntNumInput::setRange() called with bad arguments. Ignoring call..."; + qDebug() + << "WARNING: kpIntNumInput::setRange() called with bad arguments. Ignoring call..."; return; } @@ -295,8 +302,7 @@ void kpIntNumInput::setEditFocus(bool mark) { - if (mark) - { + if (mark) { d->intSpinBox->setFocus(); } } @@ -327,7 +333,9 @@ w = qMax(w, priv->labelSize.width() + 4); } - return {w, h}; + return { + w, h + }; } void kpIntNumInput::doLayout() @@ -360,17 +368,26 @@ } if (qApp->layoutDirection() == Qt::RightToLeft) { - d->intSpinBox->setGeometry(w, h, priv->slider ? priv->column2Width : qMax(priv->column2Width, e->size().width() - w), d->intSpinBoxSize.height()); + d->intSpinBox->setGeometry(w, h, + priv->slider ? priv->column2Width : qMax(priv->column2Width, + e->size().width() - w), + d->intSpinBoxSize.height()); w += priv->column2Width + spacingHint; if (priv->slider) { - priv->slider->setGeometry(w, h, e->size().width() - w, d->intSpinBoxSize.height() + spacingHint); + priv->slider->setGeometry(w, h, e->size().width() - w, + d->intSpinBoxSize.height() + spacingHint); } } else if (priv->slider) { - priv->slider->setGeometry(w, h, e->size().width() - (w + priv->column2Width + spacingHint), d->intSpinBoxSize.height() + spacingHint); - d->intSpinBox->setGeometry(w + priv->slider->size().width() + spacingHint, h, priv->column2Width, d->intSpinBoxSize.height()); + priv->slider->setGeometry(w, h, + e->size().width() - (w + priv->column2Width + spacingHint), + d->intSpinBoxSize.height() + spacingHint); + d->intSpinBox->setGeometry( + w + priv->slider->size().width() + spacingHint, h, priv->column2Width, + d->intSpinBoxSize.height()); } else { - d->intSpinBox->setGeometry(w, h, qMax(priv->column2Width, e->size().width() - w), d->intSpinBoxSize.height()); + d->intSpinBox->setGeometry(w, h, qMax(priv->column2Width, + e->size().width() - w), d->intSpinBoxSize.height()); } h += d->intSpinBoxSize.height() + 2; @@ -424,22 +441,24 @@ { public: kpDoubleNumInputPrivate() - : spin(nullptr) {} + : spin(nullptr) + { + } + QDoubleSpinBox *spin; QSize editSize; QString specialValue; }; kpDoubleNumInput::kpDoubleNumInput(QWidget *parent) : kpNumInput(parent) , d(new kpDoubleNumInputPrivate()) - { initWidget(0.0, 0.0, 9999.0, 0.01, 2); } kpDoubleNumInput::kpDoubleNumInput(double lower, double upper, double value, QWidget *parent, - double singleStep, int precision) + double singleStep, int precision) : kpNumInput(parent) , d(new kpDoubleNumInputPrivate()) { @@ -456,8 +475,8 @@ return d->specialValue; } -void kpDoubleNumInput::initWidget(double value, double lower, double upper, - double singleStep, int precision) +void kpDoubleNumInput::initWidget(double value, double lower, double upper, double singleStep, + int precision) { d->spin = new QDoubleSpinBox(this); d->spin->setRange(lower, upper); @@ -536,7 +555,9 @@ w = qMax(w, priv->labelSize.width() + 4); } - return {w, h}; + return { + w, h + }; } void kpDoubleNumInput::resizeEvent(QResizeEvent *e) @@ -562,11 +583,12 @@ w += priv->column2Width + spacingHint; if (priv->slider) { - priv->slider->setGeometry(w, h, e->size().width() - w, d->editSize.height() + spacingHint); + priv->slider->setGeometry(w, h, e->size().width() - w, + d->editSize.height() + spacingHint); } } else if (priv->slider) { - priv->slider->setGeometry(w, h, e->size().width() - - (priv->column1Width + priv->column2Width + spacingHint), + priv->slider->setGeometry(w, h, e->size().width() + -(priv->column1Width + priv->column2Width + spacingHint), d->editSize.height() + spacingHint); d->spin->setGeometry(w + priv->slider->width() + spacingHint, h, priv->column2Width, d->editSize.height()); @@ -613,7 +635,7 @@ this, &kpDoubleNumInput::sliderMoved); layout(); } - if (steps > 1000 ) { + if (steps > 1000) { priv->slider->setRange(0, 1000); priv->slider->setSingleStep(1); priv->slider->setPageStep(50); @@ -625,7 +647,8 @@ priv->slider->setPageStep(pageSteps); } spinBoxChanged(spin->value()); - connect(spin, QOverload::of(&QDoubleSpinBox::valueChanged), this, &kpDoubleNumInput::spinBoxChanged); + connect(spin, QOverload::of( + &QDoubleSpinBox::valueChanged), this, &kpDoubleNumInput::spinBoxChanged); layout(); } diff --git a/widgets/kpColorCells.h b/widgets/kpColorCells.h --- a/widgets/kpColorCells.h +++ b/widgets/kpColorCells.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,22 +24,17 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpColorCells_H #define kpColorCells_H - #include #include "lgpl/generic/widgets/kpColorCellsBase.h" - - class kpColorCollection; class kpColor; - // This widget consists of rows of 11 cells of colors. The cells become // shorter as soon as there are 3 rows. After that, a vertical scrollbar // is usually displayed. @@ -75,50 +69,48 @@ // TODO: For now, only horizontal orientation is supported. class kpColorCells : public kpColorCellsBase { -Q_OBJECT + Q_OBJECT public: - kpColorCells (QWidget *parent, - Qt::Orientation o = Qt::Horizontal); + kpColorCells (QWidget *parent, Qt::Orientation o = Qt::Horizontal); ~kpColorCells () override; - static kpColorCollection DefaultColorCollection (); + static kpColorCollection DefaultColorCollection(); - Qt::Orientation orientation () const; - void setOrientation (Qt::Orientation o); + Qt::Orientation orientation() const; + void setOrientation(Qt::Orientation o); protected: - void makeCellsMatchColorCollection (); + void makeCellsMatchColorCollection(); public: - bool isModified () const; + bool isModified() const; // (this emits isModifiedChanged() if the modified state changes) - void setModified (bool yes); + void setModified(bool yes); public slots: // (this emits isModifiedChanged() if the modified state changes) - void setModified (); + void setModified(); public: // The source URL of the kpColorCollection. Empty for color // collections that did not come from files. - QUrl url () const; + QUrl url() const; // The name of the kpColorCollection. Empty for color collections // managed by KDE. - QString name () const; + QString name() const; - const kpColorCollection *colorCollection () const; + const kpColorCollection *colorCollection() const; private: // Ensures there's a least one row of cells, to avoid a confusing UI. - void ensureHaveAtLeastOneRow (); + void ensureHaveAtLeastOneRow(); public: - void setColorCollection (const kpColorCollection &colorCol, - const QUrl &url = QUrl ()); + void setColorCollection(const kpColorCollection &colorCol, const QUrl &url = QUrl()); - bool openColorCollection (const QUrl &url); - bool saveColorCollectionAs (const QUrl &url); - bool saveColorCollection (); + bool openColorCollection(const QUrl &url); + bool saveColorCollectionAs(const QUrl &url); + bool saveColorCollection(); // These add and delete visual/table rows, independent of whether the number // of colors in the color collection is divisible by the columnCount() @@ -135,34 +127,33 @@ // 2. deleteRow() will delete a visual row so that there will be 1 visual // row (11 cells in total) remaining. (15 - 11) colors will be deleted // from the back of the color collection. - void appendRow (); - void deleteLastRow (); + void appendRow(); + void deleteLastRow(); signals: - void foregroundColorChanged (const kpColor &color); - void backgroundColorChanged (const kpColor &color); + void foregroundColorChanged(const kpColor &color); + void backgroundColorChanged(const kpColor &color); - void rowCountChanged (int rowCount); + void rowCountChanged(int rowCount); - void nameChanged (const QString &name); - void urlChanged (const QUrl &url); + void nameChanged(const QString &name); + void urlChanged(const QUrl &url); // Emitted when setModified() is called and the modified state changes. // It may be called at other times, even when the modified state did // not change. - void isModifiedChanged (bool isModified); + void isModifiedChanged(bool isModified); protected: - void contextMenuEvent (QContextMenuEvent *e) override; + void contextMenuEvent(QContextMenuEvent *e) override; protected slots: - void slotColorSelected (int cell, const QColor &color, Qt::MouseButton button); - void slotColorDoubleClicked (int cell, const QColor &color); - void slotColorChanged (int cell, const QColor &color); + void slotColorSelected(int cell, const QColor &color, Qt::MouseButton button); + void slotColorDoubleClicked(int cell, const QColor &color); + void slotColorChanged(int cell, const QColor &color); private: - struct kpColorCellsPrivate * const d; + struct kpColorCellsPrivate *const d; }; - #endif // kpColorCells_H diff --git a/widgets/kpColorCells.cpp b/widgets/kpColorCells.cpp --- a/widgets/kpColorCells.cpp +++ b/widgets/kpColorCells.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COLOR_CELLS 0 - #include "widgets/kpColorCells.h" #include "imagelib/kpColor.h" @@ -48,57 +45,52 @@ // Table Geometry // - // The number of columns that the table normally has. const int TableDefaultNumColumns = 11; const int TableDefaultWidth = ::TableDefaultNumColumns * 26; const int TableDefaultHeight = 52; - -static int TableNumColumns (const kpColorCollection &colorCol) +static int TableNumColumns(const kpColorCollection &colorCol) { - if (colorCol.count () == 0) { + if (colorCol.count() == 0) { return 0; } return ::TableDefaultNumColumns; } -static int TableNumRows (const kpColorCollection &colorCol) +static int TableNumRows(const kpColorCollection &colorCol) { - const int cols = ::TableNumColumns (colorCol); + const int cols = ::TableNumColumns(colorCol); if (cols == 0) { return 0; } - return (colorCol.count () + (cols - 1)) / cols; + return (colorCol.count() + (cols - 1)) / cols; } - -static int TableCellWidth (const kpColorCollection &colorCol) +static int TableCellWidth(const kpColorCollection &colorCol) { - Q_UNUSED (colorCol); + Q_UNUSED(colorCol); return ::TableDefaultWidth / ::TableDefaultNumColumns; } -static int TableCellHeight (const kpColorCollection &colorCol) +static int TableCellHeight(const kpColorCollection &colorCol) { - if (::TableNumRows (colorCol) <= 2) { + if (::TableNumRows(colorCol) <= 2) { return ::TableDefaultHeight / 2; } return ::TableDefaultHeight / 3; } - // // kpColorCells // - struct kpColorCellsPrivate { Qt::Orientation orientation{}; @@ -131,68 +123,60 @@ //--------------------------------------------------------------------- -kpColorCells::kpColorCells (QWidget *parent, - Qt::Orientation o) - : kpColorCellsBase (parent, 0/*rows for now*/, 0/*cols for now*/), - d (new kpColorCellsPrivate ()) +kpColorCells::kpColorCells (QWidget *parent, Qt::Orientation o) + : kpColorCellsBase(parent, 0 /*rows for now*/, 0 /*cols for now*/) + , d(new kpColorCellsPrivate()) { d->orientation = o; d->isModified = false; d->blockColorChangedSig = false; - // When a text box is active, clicking to change the background color // should not move the keyboard focus away from the text box. - setFocusPolicy (Qt::TabFocus); - - setShading (false); // no 3D look + setFocusPolicy(Qt::TabFocus); - setAcceptDrops (true); - setAcceptDrags (true); + setShading(false); // no 3D look + setAcceptDrops(true); + setAcceptDrags(true); - setCellsResizable (false); + setCellsResizable(false); - if (o == Qt::Horizontal) - { + if (o == Qt::Horizontal) { // Reserve enough room for the default color collection's cells _and_ // a vertical scrollbar, which only appears when it's required. // This ensures that if the vertical scrollbar appears, it does not obscure // any cells or require the addition of a horizontal scrollbar, which would // look ugly and take even more precious room. // // We do not dynamically reserve room based on the actual number of rows // of cells, as that would make our containing widgets too big. - setMinimumSize (::TableDefaultWidth + frameWidth () * 2 + - verticalScrollBar()->sizeHint().width(), - ::TableDefaultHeight + frameWidth () * 2); - } - else - { - Q_ASSERT (!"implemented"); + setMinimumSize(::TableDefaultWidth + frameWidth() * 2 + +verticalScrollBar()->sizeHint().width(), + ::TableDefaultHeight + frameWidth() * 2); + } else { + Q_ASSERT(!"implemented"); } - setVerticalScrollBarPolicy (Qt::ScrollBarAsNeeded); + setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // The default QTableWidget policy of QSizePolicy::Expanding forces our // containing widgets to get too big. Override it. - setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Minimum); - - connect (this, &kpColorCells::colorSelectedWhitButton, - this, &kpColorCells::slotColorSelected); + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - connect (this, &kpColorCells::colorDoubleClicked, - this, &kpColorCells::slotColorDoubleClicked); + connect(this, &kpColorCells::colorSelectedWhitButton, + this, &kpColorCells::slotColorSelected); - connect (this, &kpColorCells::colorChanged, - this, &kpColorCells::slotColorChanged); + connect(this, &kpColorCells::colorDoubleClicked, + this, &kpColorCells::slotColorDoubleClicked); + connect(this, &kpColorCells::colorChanged, + this, &kpColorCells::slotColorChanged); - setColorCollection (DefaultColorCollection ()); + setColorCollection(DefaultColorCollection()); - - setWhatsThis ( - i18n ( + setWhatsThis( + i18n( "" "

To select the foreground color that tools use to draw," @@ -219,133 +203,120 @@ //--------------------------------------------------------------------- - // public static -kpColorCollection kpColorCells::DefaultColorCollection () +kpColorCollection kpColorCells::DefaultColorCollection() { - return kpDefaultColorCollection (); + return kpDefaultColorCollection(); } //--------------------------------------------------------------------- - // public -Qt::Orientation kpColorCells::orientation () const +Qt::Orientation kpColorCells::orientation() const { return d->orientation; } //--------------------------------------------------------------------- // public -void kpColorCells::setOrientation (Qt::Orientation o) +void kpColorCells::setOrientation(Qt::Orientation o) { d->orientation = o; - makeCellsMatchColorCollection (); + makeCellsMatchColorCollection(); } //--------------------------------------------------------------------- - // protected // OPT: Find out why this is being called multiple times on startup. -void kpColorCells::makeCellsMatchColorCollection () +void kpColorCells::makeCellsMatchColorCollection() { int c, r; - if (orientation () == Qt::Horizontal) - { - c = ::TableNumColumns (d->colorCol); - r = ::TableNumRows (d->colorCol); - } - else - { - c = ::TableNumRows (d->colorCol); - r = ::TableNumColumns (d->colorCol); + if (orientation() == Qt::Horizontal) { + c = ::TableNumColumns(d->colorCol); + r = ::TableNumRows(d->colorCol); + } else { + c = ::TableNumRows(d->colorCol); + r = ::TableNumColumns(d->colorCol); } #if DEBUG_KP_COLOR_CELLS qCDebug(kpLogWidgets) << "kpColorCells::makeCellsMatchColorCollection():" - << "r=" << r << "c=" << c; - qCDebug(kpLogWidgets) << "verticalScrollBar=" << verticalScrollBar () - << " sizeHint=" - << (verticalScrollBar () ? - verticalScrollBar ()->sizeHint () : - QSize (-12, -34)); + << "r=" << r << "c=" << c; + qCDebug(kpLogWidgets) << "verticalScrollBar=" << verticalScrollBar() + << " sizeHint=" + << (verticalScrollBar() + ? verticalScrollBar()->sizeHint() + : QSize(-12, -34)); #endif // Delete all cell widgets. This ensures that there will be no left-over // cell widgets, for the colors in the new color collection that are // actually invalid (which should not have cell widgets). - clearContents (); + clearContents(); - setRowCount (r); - setColumnCount (c); + setRowCount(r); + setColumnCount(c); - - int CellWidth = ::TableCellWidth (d->colorCol), - CellHeight = ::TableCellHeight (d->colorCol); + int CellWidth = ::TableCellWidth(d->colorCol), + CellHeight = ::TableCellHeight(d->colorCol); // TODO: Take a screenshot of KolourPaint, magnify it and you'll find the // cells don't have exactly the sizes requested here. e.g. the // top row of cells is 1 pixel shorter than the bottom row. There // are probably other glitches. for (int y = 0; y < r; y++) { - setRowHeight (y, CellHeight); + setRowHeight(y, CellHeight); } for (int x = 0; x < c; x++) { - setColumnWidth (x, CellWidth); + setColumnWidth(x, CellWidth); } - const bool oldBlockColorChangedSig = d->blockColorChangedSig; d->blockColorChangedSig = true; // The last "(rowCount() * columnCount()) - d->colorCol.count()" cells // will be empty because we did not initialize them. - for (int i = 0; i < d->colorCol.count (); i++) - { + for (int i = 0; i < d->colorCol.count(); i++) { int y, x; int pos; - if (orientation () == Qt::Horizontal) - { + if (orientation() == Qt::Horizontal) { y = i / c; x = i % c; pos = i; - } - else - { + } else { y = i % r; x = i / r; // int x = c - 1 - i / r; pos = y * c + x; } #if DEBUG_KP_COLOR_CELLS && 0 qCDebug(kpLogWidgets) << "\tSetting cell " << i << ": y=" << y << " x=" << x - << " pos=" << pos; - qCDebug(kpLogWidgets) << "\t\tcolor=" << (int *) d->colorCol.color (i).rgba() - << "isValid=" << d->colorCol.color (i).isValid (); + << " pos=" << pos; + qCDebug(kpLogWidgets) << "\t\tcolor=" << (int *)d->colorCol.color(i).rgba() + << "isValid=" << d->colorCol.color(i).isValid(); #endif // (color may be invalid resulting in a hole in the middle of the table) - setColor (pos, d->colorCol.color (i)); + setColor(pos, d->colorCol.color(i)); //this->setToolTip( cellGeometry (y, x), colors [i].name ()); } d->blockColorChangedSig = oldBlockColorChangedSig; } //--------------------------------------------------------------------- - -bool kpColorCells::isModified () const +bool kpColorCells::isModified() const { return d->isModified; } //--------------------------------------------------------------------- -void kpColorCells::setModified (bool yes) +void kpColorCells::setModified(bool yes) { #if DEBUG_KP_COLOR_CELLS qCDebug(kpLogWidgets) << "kpColorCells::setModified(" << yes << ")"; @@ -357,84 +328,79 @@ d->isModified = yes; - emit isModifiedChanged (yes); + emit isModifiedChanged(yes); } //--------------------------------------------------------------------- -void kpColorCells::setModified () +void kpColorCells::setModified() { - setModified (true); + setModified(true); } //--------------------------------------------------------------------- - -QUrl kpColorCells::url () const +QUrl kpColorCells::url() const { return d->url; } //--------------------------------------------------------------------- -QString kpColorCells::name () const +QString kpColorCells::name() const { - return d->colorCol.name (); + return d->colorCol.name(); } //--------------------------------------------------------------------- - -const kpColorCollection *kpColorCells::colorCollection () const +const kpColorCollection *kpColorCells::colorCollection() const { return &d->colorCol; } //--------------------------------------------------------------------- - -void kpColorCells::ensureHaveAtLeastOneRow () +void kpColorCells::ensureHaveAtLeastOneRow() { - if (d->colorCol.count () == 0) { - d->colorCol.resize (::TableDefaultNumColumns); + if (d->colorCol.count() == 0) { + d->colorCol.resize(::TableDefaultNumColumns); } } //--------------------------------------------------------------------- -void kpColorCells::setColorCollection (const kpColorCollection &colorCol, const QUrl &url) +void kpColorCells::setColorCollection(const kpColorCollection &colorCol, const QUrl &url) { d->colorCol = colorCol; - ensureHaveAtLeastOneRow (); + ensureHaveAtLeastOneRow(); d->url = url; - setModified (false); + setModified(false); - makeCellsMatchColorCollection (); + makeCellsMatchColorCollection(); - emit rowCountChanged (rowCount ()); - emit urlChanged (d->url); - emit nameChanged (name ()); + emit rowCountChanged(rowCount()); + emit urlChanged(d->url); + emit nameChanged(name()); } //--------------------------------------------------------------------- - -bool kpColorCells::openColorCollection (const QUrl &url) +bool kpColorCells::openColorCollection(const QUrl &url) { // (this will pop up an error dialog on failure) - if (d->colorCol.open (url, this)) - { - ensureHaveAtLeastOneRow (); + if (d->colorCol.open(url, this)) { + ensureHaveAtLeastOneRow(); d->url = url; - setModified (false); + setModified(false); - makeCellsMatchColorCollection (); + makeCellsMatchColorCollection(); - emit rowCountChanged (rowCount ()); - emit urlChanged (d->url); - emit nameChanged (name ()); + emit rowCountChanged(rowCount()); + emit urlChanged(d->url); + emit nameChanged(name()); return true; } @@ -444,109 +410,101 @@ //--------------------------------------------------------------------- -bool kpColorCells::saveColorCollectionAs (const QUrl &url) +bool kpColorCells::saveColorCollectionAs(const QUrl &url) { // (this will pop up an error dialog on failure) - if (d->colorCol.saveAs (url, true/*show overwrite prompt*/, this)) - { + if (d->colorCol.saveAs(url, true /*show overwrite prompt*/, this)) { d->url = url; - setModified (false); + setModified(false); - emit urlChanged (d->url); + emit urlChanged(d->url); return true; } return false; } //--------------------------------------------------------------------- -bool kpColorCells::saveColorCollection () +bool kpColorCells::saveColorCollection() { // (this will pop up an error dialog on failure) - if (d->colorCol.saveAs (d->url, false/*no overwrite prompt*/, this)) - { - setModified (false); + if (d->colorCol.saveAs(d->url, false /*no overwrite prompt*/, this)) { + setModified(false); return true; } return false; } //--------------------------------------------------------------------- - -void kpColorCells::appendRow () +void kpColorCells::appendRow() { // This is the easiest implementation: change the color collection // and then synchronize the table cells. The other way is to call // setRowCount() and then, synchronize the color collection. - const int targetNumCells = (rowCount () + 1) * ::TableDefaultNumColumns; - d->colorCol.resize (targetNumCells); + const int targetNumCells = (rowCount() + 1) * ::TableDefaultNumColumns; + d->colorCol.resize(targetNumCells); - setModified (true); + setModified(true); - makeCellsMatchColorCollection (); + makeCellsMatchColorCollection(); - emit rowCountChanged (rowCount ()); + emit rowCountChanged(rowCount()); } //--------------------------------------------------------------------- -void kpColorCells::deleteLastRow () +void kpColorCells::deleteLastRow() { // This is the easiest implementation: change the color collection // and then synchronize the table cells. The other way is to call // setRowCount() and then, synchronize the color collection. - const int targetNumCells = - qMax (0, (rowCount () - 1) * ::TableDefaultNumColumns); - d->colorCol.resize (targetNumCells); + const int targetNumCells + = qMax(0, (rowCount() - 1) * ::TableDefaultNumColumns); + d->colorCol.resize(targetNumCells); // If there was only one row of colors to start with, the effect of this // line (after the above resize()) is to change that row to a row of // invalid colors. - ensureHaveAtLeastOneRow (); + ensureHaveAtLeastOneRow(); - setModified (true); + setModified(true); - makeCellsMatchColorCollection (); + makeCellsMatchColorCollection(); - emit rowCountChanged (rowCount ()); + emit rowCountChanged(rowCount()); } //--------------------------------------------------------------------- - // protected virtual [base QWidget] -void kpColorCells::contextMenuEvent (QContextMenuEvent *e) +void kpColorCells::contextMenuEvent(QContextMenuEvent *e) { // Eat right-mouse press to prevent it from getting to the toolbar. - e->accept (); + e->accept(); } //--------------------------------------------------------------------- // protected slot -void kpColorCells::slotColorSelected (int cell, const QColor &color, - Qt::MouseButton button) +void kpColorCells::slotColorSelected(int cell, const QColor &color, Qt::MouseButton button) { #if DEBUG_KP_COLOR_CELLS qCDebug(kpLogWidgets) << "kpColorCells::slotColorSelected(cell=" << cell - << ") mouseButton = " << button - << " rgb=" << (int *) color.rgba(); + << ") mouseButton = " << button + << " rgb=" << (int *)color.rgba(); #else - Q_UNUSED (cell); + Q_UNUSED(cell); #endif - if (button == Qt::LeftButton) - { - emit foregroundColorChanged (kpColor (color.rgba())); - } - else if (button == Qt::RightButton) - { - emit backgroundColorChanged (kpColor (color.rgba())); + if (button == Qt::LeftButton) { + emit foregroundColorChanged(kpColor(color.rgba())); + } else if (button == Qt::RightButton) { + emit backgroundColorChanged(kpColor(color.rgba())); } // REFACTOR: Make selectedness configurable inside kpColorCellsBase? @@ -560,45 +518,45 @@ // clearSelection(). I think setSelectionMode() concerns when the user // directly selects a cell - not when kpColorCellsBase::mouseReleaseEvent() // selects a cell programmatically. - clearSelection (); + clearSelection(); } //--------------------------------------------------------------------- // protected slot -void kpColorCells::slotColorDoubleClicked (int cell, const QColor &) +void kpColorCells::slotColorDoubleClicked(int cell, const QColor &) { QColorDialog dialog(this); dialog.setCurrentColor(kpColorCellsBase::color(cell)); dialog.setOptions(QColorDialog::ShowAlphaChannel); - if ( dialog.exec() == QDialog::Accepted ) - setColor (cell, dialog.currentColor()); + if (dialog.exec() == QDialog::Accepted) { + setColor(cell, dialog.currentColor()); + } } //--------------------------------------------------------------------- // protected slot -void kpColorCells::slotColorChanged (int cell, const QColor &color) +void kpColorCells::slotColorChanged(int cell, const QColor &color) { #if DEBUG_KP_COLOR_CELLS - qCDebug(kpLogWidgets) << "cell=" << cell << "color=" << (const int *) color.rgba() - << "d->colorCol.count()=" << d->colorCol.count (); + qCDebug(kpLogWidgets) << "cell=" << cell << "color=" << (const int *)color.rgba() + << "d->colorCol.count()=" << d->colorCol.count(); #endif if (d->blockColorChangedSig) { return; } // Cater for adding new colors to the end. - if (cell >= d->colorCol.count ()) { - d->colorCol.resize (cell + 1); + if (cell >= d->colorCol.count()) { + d->colorCol.resize(cell + 1); } // TODO: We lose color names on a color swap (during drag-and-drop). - const int ret = d->colorCol.changeColor (cell, color, - QString ()/*color name*/); - Q_ASSERT (ret == cell); + const int ret = d->colorCol.changeColor(cell, color, + QString() /*color name*/); + Q_ASSERT(ret == cell); - setModified (true); + setModified(true); } - diff --git a/widgets/kpColorPalette.h b/widgets/kpColorPalette.h --- a/widgets/kpColorPalette.h +++ b/widgets/kpColorPalette.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,39 +24,33 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpColorPalette_H #define kpColorPalette_H - #include - class kpColor; class kpColorCells; - class kpColorPalette : public QWidget { -Q_OBJECT + Q_OBJECT public: - kpColorPalette (QWidget *parent, - Qt::Orientation o = Qt::Horizontal); + kpColorPalette (QWidget *parent, Qt::Orientation o = Qt::Horizontal); ~kpColorPalette () override; - Qt::Orientation orientation () const; - void setOrientation (Qt::Orientation o); + Qt::Orientation orientation() const; + void setOrientation(Qt::Orientation o); - kpColorCells *colorCells () const; + kpColorCells *colorCells() const; signals: - void foregroundColorChanged (const kpColor &color); - void backgroundColorChanged (const kpColor &color); + void foregroundColorChanged(const kpColor &color); + void backgroundColorChanged(const kpColor &color); private: - struct kpColorPalettePrivate * const d; + struct kpColorPalettePrivate *const d; }; - #endif // kpColorPalette_H diff --git a/widgets/kpColorPalette.cpp b/widgets/kpColorPalette.cpp --- a/widgets/kpColorPalette.cpp +++ b/widgets/kpColorPalette.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COLOR_PALETTE 0 - #include "kpColorPalette.h" #include "kpColorCells.h" @@ -52,26 +49,26 @@ //--------------------------------------------------------------------- kpColorPalette::kpColorPalette (QWidget *parent, Qt::Orientation o) - : QWidget (parent), - d (new kpColorPalettePrivate ()) + : QWidget(parent) + , d(new kpColorPalettePrivate()) { d->boxLayout = nullptr; - d->transparentColorCell = new kpTransparentColorCell (this); - connect (d->transparentColorCell, &kpTransparentColorCell::foregroundColorChanged, - this, &kpColorPalette::foregroundColorChanged); + d->transparentColorCell = new kpTransparentColorCell(this); + connect(d->transparentColorCell, &kpTransparentColorCell::foregroundColorChanged, + this, &kpColorPalette::foregroundColorChanged); - connect (d->transparentColorCell, &kpTransparentColorCell::backgroundColorChanged, - this, &kpColorPalette::backgroundColorChanged); + connect(d->transparentColorCell, &kpTransparentColorCell::backgroundColorChanged, + this, &kpColorPalette::backgroundColorChanged); - d->colorCells = new kpColorCells (this); - connect (d->colorCells, &kpColorCells::foregroundColorChanged, - this, &kpColorPalette::foregroundColorChanged); + d->colorCells = new kpColorCells(this); + connect(d->colorCells, &kpColorCells::foregroundColorChanged, + this, &kpColorPalette::foregroundColorChanged); - connect (d->colorCells, &kpColorCells::backgroundColorChanged, - this, &kpColorPalette::backgroundColorChanged); + connect(d->colorCells, &kpColorCells::backgroundColorChanged, + this, &kpColorPalette::backgroundColorChanged); - setOrientation (o); + setOrientation(o); } //--------------------------------------------------------------------- @@ -84,43 +81,39 @@ //--------------------------------------------------------------------- // public -Qt::Orientation kpColorPalette::orientation () const +Qt::Orientation kpColorPalette::orientation() const { return d->orientation; } //--------------------------------------------------------------------- -void kpColorPalette::setOrientation (Qt::Orientation o) +void kpColorPalette::setOrientation(Qt::Orientation o) { - d->colorCells->setOrientation (o); + d->colorCells->setOrientation(o); delete d->boxLayout; - if (o == Qt::Horizontal) - { - d->boxLayout = new QBoxLayout (QBoxLayout::LeftToRight, this); - d->boxLayout->addWidget (d->transparentColorCell, 0/*stretch*/, Qt::AlignTop); - d->boxLayout->addWidget (d->colorCells); + if (o == Qt::Horizontal) { + d->boxLayout = new QBoxLayout(QBoxLayout::LeftToRight, this); + d->boxLayout->addWidget(d->transparentColorCell, 0 /*stretch*/, Qt::AlignTop); + d->boxLayout->addWidget(d->colorCells); + } else { + d->boxLayout = new QBoxLayout(QBoxLayout::TopToBottom, this); + d->boxLayout->addWidget(d->transparentColorCell, 0 /*stretch*/, Qt::AlignTop); + d->boxLayout->addWidget(d->colorCells); } - else - { - d->boxLayout = new QBoxLayout (QBoxLayout::TopToBottom, this); - d->boxLayout->addWidget (d->transparentColorCell, 0/*stretch*/, Qt::AlignTop); - d->boxLayout->addWidget (d->colorCells); - } - d->boxLayout->setSpacing (5); + d->boxLayout->setSpacing(5); d->orientation = o; } //--------------------------------------------------------------------- // public -kpColorCells *kpColorPalette::colorCells () const +kpColorCells *kpColorPalette::colorCells() const { return d->colorCells; } //--------------------------------------------------------------------- - diff --git a/widgets/kpDefaultColorCollection.h b/widgets/kpDefaultColorCollection.h --- a/widgets/kpDefaultColorCollection.h +++ b/widgets/kpDefaultColorCollection.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,14 +24,11 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpDefaultColorCollection_H #define kpDefaultColorCollection_H - #include "lgpl/generic/kpColorCollection.h" - // // The default set of colors offered by KolourPaint to the user. // @@ -46,5 +42,4 @@ ~kpDefaultColorCollection (); }; - #endif // kpDefaultColorCollection_H diff --git a/widgets/kpDefaultColorCollection.cpp b/widgets/kpDefaultColorCollection.cpp --- a/widgets/kpDefaultColorCollection.cpp +++ b/widgets/kpDefaultColorCollection.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,12 +24,10 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "kpDefaultColorCollection.h" #include "imagelib/kpColor.h" - kpDefaultColorCollection::kpDefaultColorCollection () { kpColor colors [] = @@ -60,9 +57,8 @@ kpColor::Tan }; - for (const auto & color : colors) - { - addColor (color.toQColor ()); + for (const auto &color : colors) { + addColor(color.toQColor()); } } diff --git a/widgets/kpDocumentSaveOptionsWidget.h b/widgets/kpDocumentSaveOptionsWidget.h --- a/widgets/kpDocumentSaveOptionsWidget.h +++ b/widgets/kpDocumentSaveOptionsWidget.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,19 +24,16 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpDocumentSaveOptionsWidget_H #define kpDocumentSaveOptionsWidget_H - #include #include #include #include "imagelib/kpDocumentMetaInfo.h" #include "document/kpDocumentSaveOptions.h" - class QComboBox; class QImage; class QLabel; @@ -47,84 +43,74 @@ class kpDocumentSaveOptionsPreviewDialog; - class kpDocumentSaveOptionsWidget : public QWidget { -Q_OBJECT + Q_OBJECT public: - kpDocumentSaveOptionsWidget (const QImage &docPixmap, - const kpDocumentSaveOptions &saveOptions, - const kpDocumentMetaInfo &metaInfo, - QWidget *parent); + kpDocumentSaveOptionsWidget (const QImage &docPixmap, const kpDocumentSaveOptions &saveOptions, + const kpDocumentMetaInfo &metaInfo, QWidget *parent); kpDocumentSaveOptionsWidget (QWidget *parent); private: - void init (); + void init(); public: ~kpDocumentSaveOptionsWidget () override; - // is usually the filedialog - void setVisualParent (QWidget *visualParent); - + void setVisualParent(QWidget *visualParent); protected: - bool mimeTypeHasConfigurableColorDepth () const; - bool mimeTypeHasConfigurableQuality () const; + bool mimeTypeHasConfigurableColorDepth() const; + bool mimeTypeHasConfigurableQuality() const; public: - QString mimeType () const; + QString mimeType() const; public slots: - void setMimeType (const QString &string); + void setMimeType(const QString &string); public: - int colorDepth () const; - bool dither () const; + int colorDepth() const; + bool dither() const; protected: - static int colorDepthComboItemFromColorDepthAndDither (int depth, bool dither); + static int colorDepthComboItemFromColorDepthAndDither(int depth, bool dither); public slots: - void setColorDepthDither (int depth, - bool dither = kpDocumentSaveOptions::initialDither ()); + void setColorDepthDither(int depth, bool dither = kpDocumentSaveOptions::initialDither()); protected slots: - void slotColorDepthSelected (); + void slotColorDepthSelected(); public: - int quality () const; + int quality() const; public slots: - void setQuality (int newQuality); + void setQuality(int newQuality); public: - kpDocumentSaveOptions documentSaveOptions () const; + kpDocumentSaveOptions documentSaveOptions() const; public slots: - void setDocumentSaveOptions (const kpDocumentSaveOptions &saveOptions); - + void setDocumentSaveOptions(const kpDocumentSaveOptions &saveOptions); public: - void setDocumentPixmap (const QImage &documentPixmap); - void setDocumentMetaInfo (const kpDocumentMetaInfo &metaInfo); - + void setDocumentPixmap(const QImage &documentPixmap); + void setDocumentMetaInfo(const kpDocumentMetaInfo &metaInfo); protected: enum Mode { // (mutually exclusive) None, ColorDepth, Quality }; - Mode mode () const; - void setMode (Mode mode); + Mode mode() const; + void setMode(Mode mode); protected slots: - void repaintLabels (); - + void repaintLabels(); protected slots: - void showPreview (bool yes = true); - void hidePreview (); - void updatePreviewDelayed (); - void updatePreview (); - void updatePreviewDialogLastRelativeGeometry (); - + void showPreview(bool yes = true); + void hidePreview(); + void updatePreviewDelayed(); + void updatePreview(); + void updatePreviewDialogLastRelativeGeometry(); protected: QWidget *m_visualParent; @@ -152,5 +138,4 @@ QTimer *m_updatePreviewDialogLastRelativeGeometryTimer; }; - #endif // kpDocumentSaveOptionsWidget_H diff --git a/widgets/kpDocumentSaveOptionsWidget.cpp b/widgets/kpDocumentSaveOptionsWidget.cpp --- a/widgets/kpDocumentSaveOptionsWidget.cpp +++ b/widgets/kpDocumentSaveOptionsWidget.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,7 +26,6 @@ #define DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET 0 - #include "widgets/kpDocumentSaveOptionsWidget.h" #include "kpDefs.h" @@ -55,237 +53,214 @@ #include #include - kpDocumentSaveOptionsWidget::kpDocumentSaveOptionsWidget ( - const QImage &docPixmap, - const kpDocumentSaveOptions &saveOptions, - const kpDocumentMetaInfo &metaInfo, - QWidget *parent) - : QWidget (parent), - m_visualParent (parent) + const QImage &docPixmap, const kpDocumentSaveOptions &saveOptions, + const kpDocumentMetaInfo &metaInfo, QWidget *parent) + : QWidget(parent) + , m_visualParent(parent) { - init (); - setDocumentSaveOptions (saveOptions); - setDocumentPixmap (docPixmap); - setDocumentMetaInfo (metaInfo); + init(); + setDocumentSaveOptions(saveOptions); + setDocumentPixmap(docPixmap); + setDocumentMetaInfo(metaInfo); } kpDocumentSaveOptionsWidget::kpDocumentSaveOptionsWidget ( - QWidget *parent) - : QWidget (parent), - m_visualParent (parent) + QWidget *parent) + : QWidget(parent) + , m_visualParent(parent) { - init (); + init(); } // private -void kpDocumentSaveOptionsWidget::init () +void kpDocumentSaveOptionsWidget::init() { m_documentPixmap = nullptr; m_previewDialog = nullptr; m_visualParent = nullptr; + m_colorDepthLabel = new QLabel(i18n("Convert &to:"), this); + m_colorDepthCombo = new QComboBox(this); - m_colorDepthLabel = new QLabel (i18n ("Convert &to:"), this); - m_colorDepthCombo = new QComboBox (this); + m_colorDepthSpaceWidget = new QWidget(this); - m_colorDepthSpaceWidget = new QWidget (this); - - m_qualityLabel = new QLabel(i18n ("Quali&ty:"), this); + m_qualityLabel = new QLabel(i18n("Quali&ty:"), this); m_qualityInput = new QSpinBox(this); // Note that we set min to 1 not 0 since "0 Quality" is a bit misleading // and 101 quality settings would be weird. So we lose 1 quality setting // according to QImage::save(). // TODO: 100 quality is also misleading since that implies perfect quality. - m_qualityInput->setRange (1, 100); - - m_previewButton = new QPushButton (i18n ("&Preview"), this); - m_previewButton->setCheckable (true); - + m_qualityInput->setRange(1, 100); - m_colorDepthLabel->setBuddy (m_colorDepthCombo); + m_previewButton = new QPushButton(i18n("&Preview"), this); + m_previewButton->setCheckable(true); - m_qualityLabel->setBuddy (m_qualityInput); + m_colorDepthLabel->setBuddy(m_colorDepthCombo); + m_qualityLabel->setBuddy(m_qualityInput); - auto *lay = new QHBoxLayout (this); + auto *lay = new QHBoxLayout(this); lay->setContentsMargins(0, 0, 0, 0); - lay->addWidget (m_colorDepthLabel, 0/*stretch*/, Qt::AlignLeft); - lay->addWidget (m_colorDepthCombo, 0/*stretch*/); + lay->addWidget(m_colorDepthLabel, 0 /*stretch*/, Qt::AlignLeft); + lay->addWidget(m_colorDepthCombo, 0 /*stretch*/); - lay->addWidget (m_colorDepthSpaceWidget, 1/*stretch*/); + lay->addWidget(m_colorDepthSpaceWidget, 1 /*stretch*/); - lay->addWidget (m_qualityLabel, 0/*stretch*/, Qt::AlignLeft); - lay->addWidget (m_qualityInput, 2/*stretch*/); + lay->addWidget(m_qualityLabel, 0 /*stretch*/, Qt::AlignLeft); + lay->addWidget(m_qualityInput, 2 /*stretch*/); - lay->addWidget (m_previewButton, 0/*stretch*/, Qt::AlignRight); + lay->addWidget(m_previewButton, 0 /*stretch*/, Qt::AlignRight); + connect(m_colorDepthCombo, + static_cast(&QComboBox::activated), + this, &kpDocumentSaveOptionsWidget::slotColorDepthSelected); - connect (m_colorDepthCombo, - static_cast(&QComboBox::activated), - this, &kpDocumentSaveOptionsWidget::slotColorDepthSelected); + connect(m_colorDepthCombo, + static_cast(&QComboBox::activated), + this, &kpDocumentSaveOptionsWidget::updatePreview); - connect (m_colorDepthCombo, - static_cast(&QComboBox::activated), - this, &kpDocumentSaveOptionsWidget::updatePreview); + connect(m_qualityInput, + static_cast(&QSpinBox::valueChanged), + this, &kpDocumentSaveOptionsWidget::updatePreviewDelayed); - connect (m_qualityInput, - static_cast(&QSpinBox::valueChanged), - this, &kpDocumentSaveOptionsWidget::updatePreviewDelayed); + connect(m_previewButton, &QPushButton::toggled, + this, &kpDocumentSaveOptionsWidget::showPreview); - connect (m_previewButton, &QPushButton::toggled, - this, &kpDocumentSaveOptionsWidget::showPreview); + m_updatePreviewDelay = 200 /*ms*/; + m_updatePreviewTimer = new QTimer(this); + m_updatePreviewTimer->setSingleShot(true); + connect(m_updatePreviewTimer, &QTimer::timeout, + this, &kpDocumentSaveOptionsWidget::updatePreview); - m_updatePreviewDelay = 200/*ms*/; + m_updatePreviewDialogLastRelativeGeometryTimer = new QTimer(this); + connect(m_updatePreviewDialogLastRelativeGeometryTimer, + &QTimer::timeout, + this, &kpDocumentSaveOptionsWidget::updatePreviewDialogLastRelativeGeometry); - m_updatePreviewTimer = new QTimer (this); - m_updatePreviewTimer->setSingleShot (true); - connect (m_updatePreviewTimer, &QTimer::timeout, - this, &kpDocumentSaveOptionsWidget::updatePreview); + setMode(None); - m_updatePreviewDialogLastRelativeGeometryTimer = new QTimer (this); - connect (m_updatePreviewDialogLastRelativeGeometryTimer, - &QTimer::timeout, - this, &kpDocumentSaveOptionsWidget::updatePreviewDialogLastRelativeGeometry); - - setMode (None); - - slotColorDepthSelected (); + slotColorDepthSelected(); } kpDocumentSaveOptionsWidget::~kpDocumentSaveOptionsWidget () { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "kpDocumentSaveOptionsWidget::()"; #endif - hidePreview (); + hidePreview(); delete m_documentPixmap; } - // public -void kpDocumentSaveOptionsWidget::setVisualParent (QWidget *visualParent) +void kpDocumentSaveOptionsWidget::setVisualParent(QWidget *visualParent) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "kpDocumentSaveOptionsWidget::setVisualParent(" - << visualParent << ")" << endl; + << visualParent << ")" << endl; #endif m_visualParent = visualParent; } - // protected -bool kpDocumentSaveOptionsWidget::mimeTypeHasConfigurableColorDepth () const +bool kpDocumentSaveOptionsWidget::mimeTypeHasConfigurableColorDepth() const { - return kpDocumentSaveOptions::mimeTypeHasConfigurableColorDepth (mimeType ()); + return kpDocumentSaveOptions::mimeTypeHasConfigurableColorDepth(mimeType()); } // protected -bool kpDocumentSaveOptionsWidget::mimeTypeHasConfigurableQuality () const +bool kpDocumentSaveOptionsWidget::mimeTypeHasConfigurableQuality() const { - return kpDocumentSaveOptions::mimeTypeHasConfigurableQuality (mimeType ()); + return kpDocumentSaveOptions::mimeTypeHasConfigurableQuality(mimeType()); } - // public -QString kpDocumentSaveOptionsWidget::mimeType () const +QString kpDocumentSaveOptionsWidget::mimeType() const { - return m_baseDocumentSaveOptions.mimeType (); + return m_baseDocumentSaveOptions.mimeType(); } // public slots -void kpDocumentSaveOptionsWidget::setMimeType (const QString &string) +void kpDocumentSaveOptionsWidget::setMimeType(const QString &string) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "kpDocumentSaveOptionsWidget::setMimeType(" << string - << ") maxColorDepth=" - << kpDocumentSaveOptions::mimeTypeMaximumColorDepth (string) - << endl; + << ") maxColorDepth=" + << kpDocumentSaveOptions::mimeTypeMaximumColorDepth(string) + << endl; #endif - const int newMimeTypeMaxDepth = - kpDocumentSaveOptions::mimeTypeMaximumColorDepth (string); + const int newMimeTypeMaxDepth + = kpDocumentSaveOptions::mimeTypeMaximumColorDepth(string); #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET - qCDebug(kpLogWidgets) << "\toldMimeType=" << mimeType () - << " maxColorDepth=" - << kpDocumentSaveOptions::mimeTypeMaximumColorDepth ( - mimeType ()) - << endl; + qCDebug(kpLogWidgets) << "\toldMimeType=" << mimeType() + << " maxColorDepth=" + << kpDocumentSaveOptions::mimeTypeMaximumColorDepth( + mimeType()) + << endl; #endif - if (mimeType ().isEmpty () || - kpDocumentSaveOptions::mimeTypeMaximumColorDepth (mimeType ()) != - newMimeTypeMaxDepth) - { - m_colorDepthCombo->clear (); + if (mimeType().isEmpty() + || kpDocumentSaveOptions::mimeTypeMaximumColorDepth(mimeType()) + != newMimeTypeMaxDepth) { + m_colorDepthCombo->clear(); - m_colorDepthCombo->insertItem (0, i18n ("Monochrome")); - m_colorDepthCombo->insertItem (1, i18n ("Monochrome (Dithered)")); + m_colorDepthCombo->insertItem(0, i18n("Monochrome")); + m_colorDepthCombo->insertItem(1, i18n("Monochrome (Dithered)")); - if (newMimeTypeMaxDepth >= 8) - { - m_colorDepthCombo->insertItem (2, i18n ("256 Color")); - m_colorDepthCombo->insertItem (3, i18n ("256 Color (Dithered)")); + if (newMimeTypeMaxDepth >= 8) { + m_colorDepthCombo->insertItem(2, i18n("256 Color")); + m_colorDepthCombo->insertItem(3, i18n("256 Color (Dithered)")); } - if (newMimeTypeMaxDepth >= 24) - { - m_colorDepthCombo->insertItem (4, i18n ("24-bit Color")); + if (newMimeTypeMaxDepth >= 24) { + m_colorDepthCombo->insertItem(4, i18n("24-bit Color")); } - if (m_colorDepthComboLastSelectedItem >= 0 && - m_colorDepthComboLastSelectedItem < m_colorDepthCombo->count ()) - { + if (m_colorDepthComboLastSelectedItem >= 0 + && m_colorDepthComboLastSelectedItem < m_colorDepthCombo->count()) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\tsetting colorDepthCombo to " - << m_colorDepthComboLastSelectedItem << endl; + << m_colorDepthComboLastSelectedItem << endl; #endif - m_colorDepthCombo->setCurrentIndex (m_colorDepthComboLastSelectedItem); - } - else - { + m_colorDepthCombo->setCurrentIndex(m_colorDepthComboLastSelectedItem); + } else { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\tsetting colorDepthCombo to max item since" - << " m_colorDepthComboLastSelectedItem=" - << m_colorDepthComboLastSelectedItem - << " out of range" << endl; + << " m_colorDepthComboLastSelectedItem=" + << m_colorDepthComboLastSelectedItem + << " out of range" << endl; #endif - m_colorDepthCombo->setCurrentIndex (m_colorDepthCombo->count () - 1); + m_colorDepthCombo->setCurrentIndex(m_colorDepthCombo->count() - 1); } } + m_baseDocumentSaveOptions.setMimeType(string); - m_baseDocumentSaveOptions.setMimeType (string); - - if (mimeTypeHasConfigurableColorDepth ()) { - setMode (ColorDepth); - } - else if (mimeTypeHasConfigurableQuality ()) { - setMode (Quality); - } - else { - setMode (None); + if (mimeTypeHasConfigurableColorDepth()) { + setMode(ColorDepth); + } else if (mimeTypeHasConfigurableQuality()) { + setMode(Quality); + } else { + setMode(None); } - updatePreview (); + updatePreview(); } - // public -int kpDocumentSaveOptionsWidget::colorDepth () const +int kpDocumentSaveOptionsWidget::colorDepth() const { - if (mode () & ColorDepth) - { + if (mode() & ColorDepth) { // The returned values match QImage's supported depths. - switch (m_colorDepthCombo->currentIndex ()) - { + switch (m_colorDepthCombo->currentIndex()) { case 0: case 1: return 1; @@ -299,29 +274,26 @@ return 32; default: - return kpDocumentSaveOptions::invalidColorDepth (); + return kpDocumentSaveOptions::invalidColorDepth(); } - } - else - { - return m_baseDocumentSaveOptions.colorDepth (); + } else { + return m_baseDocumentSaveOptions.colorDepth(); } } // public -bool kpDocumentSaveOptionsWidget::dither () const +bool kpDocumentSaveOptionsWidget::dither() const { - if (mode () & ColorDepth) - { - return (m_colorDepthCombo->currentIndex () == 1 || - m_colorDepthCombo->currentIndex () == 3); + if (mode() & ColorDepth) { + return m_colorDepthCombo->currentIndex() == 1 + || m_colorDepthCombo->currentIndex() == 3; } - return m_baseDocumentSaveOptions.dither (); + return m_baseDocumentSaveOptions.dither(); } // protected static -int kpDocumentSaveOptionsWidget::colorDepthComboItemFromColorDepthAndDither ( +int kpDocumentSaveOptionsWidget::colorDepthComboItemFromColorDepthAndDither( int depth, bool dither) { switch (depth) { @@ -346,204 +318,184 @@ } // public slots -void kpDocumentSaveOptionsWidget::setColorDepthDither (int newDepth, bool newDither) +void kpDocumentSaveOptionsWidget::setColorDepthDither(int newDepth, bool newDither) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "kpDocumentSaveOptionsWidget::setColorDepthDither(" - << "depth=" << newDepth - << ",dither=" << newDither - << ")" << endl; + << "depth=" << newDepth + << ",dither=" << newDither + << ")" << endl; #endif - m_baseDocumentSaveOptions.setColorDepth (newDepth); - m_baseDocumentSaveOptions.setDither (newDither); - + m_baseDocumentSaveOptions.setColorDepth(newDepth); + m_baseDocumentSaveOptions.setDither(newDither); - const int comboItem = colorDepthComboItemFromColorDepthAndDither ( - newDepth, newDither); + const int comboItem = colorDepthComboItemFromColorDepthAndDither( + newDepth, newDither); // TODO: Ignoring when comboItem >= m_colorDepthCombo->count() is wrong. // This happens if this mimeType has configurable colour depth // and an incorrect maximum colour depth (less than a QImage of // this mimeType, opened by kpDocument). - if (comboItem >= 0 && comboItem < m_colorDepthCombo->count ()) { - m_colorDepthCombo->setCurrentIndex (comboItem); + if (comboItem >= 0 && comboItem < m_colorDepthCombo->count()) { + m_colorDepthCombo->setCurrentIndex(comboItem); } - - slotColorDepthSelected (); + slotColorDepthSelected(); } - // protected slot -void kpDocumentSaveOptionsWidget::slotColorDepthSelected () +void kpDocumentSaveOptionsWidget::slotColorDepthSelected() { - if (mode () & ColorDepth) - { - m_colorDepthComboLastSelectedItem = m_colorDepthCombo->currentIndex (); - } - else - { - m_colorDepthComboLastSelectedItem = - colorDepthComboItemFromColorDepthAndDither ( - m_baseDocumentSaveOptions.colorDepth (), - m_baseDocumentSaveOptions.dither ()); + if (mode() & ColorDepth) { + m_colorDepthComboLastSelectedItem = m_colorDepthCombo->currentIndex(); + } else { + m_colorDepthComboLastSelectedItem + = colorDepthComboItemFromColorDepthAndDither( + m_baseDocumentSaveOptions.colorDepth(), + m_baseDocumentSaveOptions.dither()); } #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "kpDocumentSaveOptionsWidget::slotColorDepthSelected()" - << " mode&ColorDepth=" << (mode () & ColorDepth) - << " colorDepthComboLastSelectedItem=" - << m_colorDepthComboLastSelectedItem - << endl; + << " mode&ColorDepth=" << (mode() & ColorDepth) + << " colorDepthComboLastSelectedItem=" + << m_colorDepthComboLastSelectedItem + << endl; #endif } - // public -int kpDocumentSaveOptionsWidget::quality () const +int kpDocumentSaveOptionsWidget::quality() const { - if (mode () & Quality) - { - return m_qualityInput->value (); + if (mode() & Quality) { + return m_qualityInput->value(); } - return m_baseDocumentSaveOptions.quality (); + return m_baseDocumentSaveOptions.quality(); } // public -void kpDocumentSaveOptionsWidget::setQuality (int newQuality) +void kpDocumentSaveOptionsWidget::setQuality(int newQuality) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "kpDocumentSaveOptionsWidget::setQuality(" - << newQuality << ")" << endl; + << newQuality << ")" << endl; #endif - m_baseDocumentSaveOptions.setQuality (newQuality); - m_qualityInput->setValue (newQuality == -1/*QImage::save() default*/ ? - 75 : - newQuality); + m_baseDocumentSaveOptions.setQuality(newQuality); + m_qualityInput->setValue(newQuality == -1 /*QImage::save() default*/ + ? 75 + : newQuality); } - // public -kpDocumentSaveOptions kpDocumentSaveOptionsWidget::documentSaveOptions () const +kpDocumentSaveOptions kpDocumentSaveOptionsWidget::documentSaveOptions() const { - return kpDocumentSaveOptions (mimeType (), colorDepth (), dither (), quality ()); + return kpDocumentSaveOptions(mimeType(), colorDepth(), dither(), quality()); } // public -void kpDocumentSaveOptionsWidget::setDocumentSaveOptions ( +void kpDocumentSaveOptionsWidget::setDocumentSaveOptions( const kpDocumentSaveOptions &saveOptions) { - setMimeType (saveOptions.mimeType ()); - setColorDepthDither (saveOptions.colorDepth (), saveOptions.dither ()); - setQuality (saveOptions.quality ()); + setMimeType(saveOptions.mimeType()); + setColorDepthDither(saveOptions.colorDepth(), saveOptions.dither()); + setQuality(saveOptions.quality()); } - // public -void kpDocumentSaveOptionsWidget::setDocumentPixmap (const QImage &documentPixmap) +void kpDocumentSaveOptionsWidget::setDocumentPixmap(const QImage &documentPixmap) { delete m_documentPixmap; - m_documentPixmap = new QImage (documentPixmap); + m_documentPixmap = new QImage(documentPixmap); - updatePreview (); + updatePreview(); } // public -void kpDocumentSaveOptionsWidget::setDocumentMetaInfo ( +void kpDocumentSaveOptionsWidget::setDocumentMetaInfo( const kpDocumentMetaInfo &metaInfo) { m_documentMetaInfo = metaInfo; - updatePreview (); + updatePreview(); } - // public -kpDocumentSaveOptionsWidget::Mode kpDocumentSaveOptionsWidget::mode () const +kpDocumentSaveOptionsWidget::Mode kpDocumentSaveOptionsWidget::mode() const { return m_mode; } // public -void kpDocumentSaveOptionsWidget::setMode (Mode mode) +void kpDocumentSaveOptionsWidget::setMode(Mode mode) { m_mode = mode; - // If mode == None, we show still show the Color Depth widgets but disabled - m_colorDepthLabel->setVisible (mode != Quality); - m_colorDepthCombo->setVisible (mode != Quality); - m_colorDepthSpaceWidget->setVisible (mode != Quality); + m_colorDepthLabel->setVisible(mode != Quality); + m_colorDepthCombo->setVisible(mode != Quality); + m_colorDepthSpaceWidget->setVisible(mode != Quality); - m_qualityLabel->setVisible (mode == Quality); - m_qualityInput->setVisible (mode == Quality); + m_qualityLabel->setVisible(mode == Quality); + m_qualityInput->setVisible(mode == Quality); + m_colorDepthLabel->setEnabled(mode == ColorDepth); + m_colorDepthCombo->setEnabled(mode == ColorDepth); - m_colorDepthLabel->setEnabled (mode == ColorDepth); - m_colorDepthCombo->setEnabled (mode == ColorDepth); - - m_qualityLabel->setEnabled (mode == Quality); - m_qualityInput->setEnabled (mode == Quality); - + m_qualityLabel->setEnabled(mode == Quality); + m_qualityInput->setEnabled(mode == Quality); // SYNC: HACK: When changing between color depth and quality widgets, // we change the height of "this", causing the text on the labels // to move but the first instance of the text doesn't get erased. // Qt bug. - QTimer::singleShot (0, this, &kpDocumentSaveOptionsWidget::repaintLabels); + QTimer::singleShot(0, this, &kpDocumentSaveOptionsWidget::repaintLabels); } // protected slot -void kpDocumentSaveOptionsWidget::repaintLabels () +void kpDocumentSaveOptionsWidget::repaintLabels() { - if (mode () != Quality) { - m_colorDepthLabel->repaint (); + if (mode() != Quality) { + m_colorDepthLabel->repaint(); } - if (mode () == Quality) { - m_qualityLabel->repaint (); + if (mode() == Quality) { + m_qualityLabel->repaint(); } } - // protected slot -void kpDocumentSaveOptionsWidget::showPreview (bool yes) +void kpDocumentSaveOptionsWidget::showPreview(bool yes) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "kpDocumentSaveOptionsWidget::showPreview(" << yes << ")" - << " m_previewDialog=" << bool (m_previewDialog) - << endl; + << " m_previewDialog=" << bool(m_previewDialog) + << endl; #endif - if (yes == bool (m_previewDialog)) { + if (yes == bool(m_previewDialog)) { return; } if (!m_visualParent) { return; } - if (yes) - { - m_previewDialog = new kpDocumentSaveOptionsPreviewDialog( m_visualParent ); - m_previewDialog->setObjectName( QStringLiteral( "previewSaveDialog" ) ); - updatePreview (); + if (yes) { + m_previewDialog = new kpDocumentSaveOptionsPreviewDialog(m_visualParent); + m_previewDialog->setObjectName(QStringLiteral("previewSaveDialog")); + updatePreview(); - connect (m_previewDialog, &kpDocumentSaveOptionsPreviewDialog::finished, - this, &kpDocumentSaveOptionsWidget::hidePreview); + connect(m_previewDialog, &kpDocumentSaveOptionsPreviewDialog::finished, + this, &kpDocumentSaveOptionsWidget::hidePreview); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupPreviewSave); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupPreviewSave); - - if (cfg.hasKey (kpSettingPreviewSaveUpdateDelay)) - { - m_updatePreviewDelay = cfg.readEntry (kpSettingPreviewSaveUpdateDelay, 0); - } - else - { - cfg.writeEntry (kpSettingPreviewSaveUpdateDelay, m_updatePreviewDelay); - cfg.sync (); + if (cfg.hasKey(kpSettingPreviewSaveUpdateDelay)) { + m_updatePreviewDelay = cfg.readEntry(kpSettingPreviewSaveUpdateDelay, 0); + } else { + cfg.writeEntry(kpSettingPreviewSaveUpdateDelay, m_updatePreviewDelay); + cfg.sync(); } if (m_updatePreviewDelay < 0) { @@ -553,150 +505,136 @@ qCDebug(kpLogWidgets) << "\tread cfg preview dialog update delay=" << m_updatePreviewDelay; #endif - - if (m_previewDialogLastRelativeGeometry.isEmpty ()) - { + if (m_previewDialogLastRelativeGeometry.isEmpty()) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\tread cfg preview dialog last rel geometry"; #endif - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupPreviewSave); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupPreviewSave); - m_previewDialogLastRelativeGeometry = cfg.readEntry ( - kpSettingPreviewSaveGeometry, QRect ()); + m_previewDialogLastRelativeGeometry = cfg.readEntry( + kpSettingPreviewSaveGeometry, QRect()); } #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\tpreviewDialogLastRelativeGeometry=" - << m_previewDialogLastRelativeGeometry - << " visualParent->rect()=" << m_visualParent->rect () - << endl; + << m_previewDialogLastRelativeGeometry + << " visualParent->rect()=" << m_visualParent->rect() + << endl; #endif QRect relativeGeometry; - if (!m_previewDialogLastRelativeGeometry.isEmpty () && - m_visualParent->rect ().intersects (m_previewDialogLastRelativeGeometry)) - { + if (!m_previewDialogLastRelativeGeometry.isEmpty() + && m_visualParent->rect().intersects(m_previewDialogLastRelativeGeometry)) { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\tok"; #endif relativeGeometry = m_previewDialogLastRelativeGeometry; - } - else - { + } else { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\t\tinvalid"; #endif const int margin = 20; - relativeGeometry = - QRect (m_visualParent->width () - - m_previewDialog->preferredMinimumSize ().width () - - margin, - margin * 2, // Avoid folder combo - m_previewDialog->preferredMinimumSize ().width (), - m_previewDialog->preferredMinimumSize ().height ()); + relativeGeometry + = QRect(m_visualParent->width() + -m_previewDialog->preferredMinimumSize().width() + -margin, + margin * 2, // Avoid folder combo + m_previewDialog->preferredMinimumSize().width(), + m_previewDialog->preferredMinimumSize().height()); } - - const QRect globalGeometry = - kpWidgetMapper::toGlobal (m_visualParent, - relativeGeometry); + const QRect globalGeometry + = kpWidgetMapper::toGlobal(m_visualParent, + relativeGeometry); #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\trelativeGeometry=" << relativeGeometry - << " globalGeometry=" << globalGeometry - << endl; + << " globalGeometry=" << globalGeometry + << endl; #endif - m_previewDialog->resize (globalGeometry.size ()); - m_previewDialog->move (globalGeometry.topLeft ()); - - - m_previewDialog->show (); + m_previewDialog->resize(globalGeometry.size()); + m_previewDialog->move(globalGeometry.topLeft()); + m_previewDialog->show(); #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\tgeometry after show=" - << QRect (m_previewDialog->x (), m_previewDialog->y (), - m_previewDialog->width (), m_previewDialog->height ()) - << endl; + << QRect(m_previewDialog->x(), m_previewDialog->y(), + m_previewDialog->width(), m_previewDialog->height()) + << endl; #endif - updatePreviewDialogLastRelativeGeometry (); + updatePreviewDialogLastRelativeGeometry(); - connect (m_previewDialog, &kpDocumentSaveOptionsPreviewDialog::moved, - this, &kpDocumentSaveOptionsWidget::updatePreviewDialogLastRelativeGeometry); + connect(m_previewDialog, &kpDocumentSaveOptionsPreviewDialog::moved, + this, &kpDocumentSaveOptionsWidget::updatePreviewDialogLastRelativeGeometry); - connect (m_previewDialog, &kpDocumentSaveOptionsPreviewDialog::resized, - this, &kpDocumentSaveOptionsWidget::updatePreviewDialogLastRelativeGeometry); + connect(m_previewDialog, &kpDocumentSaveOptionsPreviewDialog::resized, + this, &kpDocumentSaveOptionsWidget::updatePreviewDialogLastRelativeGeometry); - m_updatePreviewDialogLastRelativeGeometryTimer->start (200/*ms*/); - } - else - { - m_updatePreviewDialogLastRelativeGeometryTimer->stop (); + m_updatePreviewDialogLastRelativeGeometryTimer->start(200 /*ms*/); + } else { + m_updatePreviewDialogLastRelativeGeometryTimer->stop(); - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupPreviewSave); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupPreviewSave); - cfg.writeEntry (kpSettingPreviewSaveGeometry, m_previewDialogLastRelativeGeometry); - cfg.sync (); + cfg.writeEntry(kpSettingPreviewSaveGeometry, m_previewDialogLastRelativeGeometry); + cfg.sync(); #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\tsaving preview geometry " - << m_previewDialogLastRelativeGeometry - << " (Qt would have us believe " - << kpWidgetMapper::fromGlobal (m_visualParent, - QRect (m_previewDialog->x (), m_previewDialog->y (), - m_previewDialog->width (), m_previewDialog->height ())) - << ")" - << endl; + << m_previewDialogLastRelativeGeometry + << " (Qt would have us believe " + << kpWidgetMapper::fromGlobal(m_visualParent, + QRect(m_previewDialog->x(), m_previewDialog->y(), + m_previewDialog->width(), m_previewDialog->height())) + << ")" + << endl; #endif - m_previewDialog->deleteLater (); + m_previewDialog->deleteLater(); m_previewDialog = nullptr; } } // protected slot -void kpDocumentSaveOptionsWidget::hidePreview () +void kpDocumentSaveOptionsWidget::hidePreview() { - if (m_previewButton->isChecked ()) { - m_previewButton->toggle (); + if (m_previewButton->isChecked()) { + m_previewButton->toggle(); } } - // protected slot -void kpDocumentSaveOptionsWidget::updatePreviewDelayed () +void kpDocumentSaveOptionsWidget::updatePreviewDelayed() { // (single shot) - m_updatePreviewTimer->start (m_updatePreviewDelay); + m_updatePreviewTimer->start(m_updatePreviewDelay); } // protected slot -void kpDocumentSaveOptionsWidget::updatePreview () +void kpDocumentSaveOptionsWidget::updatePreview() { if (!m_previewDialog || !m_documentPixmap) { return; } + m_updatePreviewTimer->stop(); - m_updatePreviewTimer->stop (); - - - QApplication::setOverrideCursor (Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); QByteArray data; - QBuffer buffer (&data); - buffer.open (QIODevice::WriteOnly); - bool savedOK = kpDocument::savePixmapToDevice (*m_documentPixmap, - &buffer, - documentSaveOptions (), - m_documentMetaInfo, - false/*no lossy prompt*/, - this); - buffer.close (); - + QBuffer buffer(&data); + buffer.open(QIODevice::WriteOnly); + bool savedOK = kpDocument::savePixmapToDevice(*m_documentPixmap, + &buffer, + documentSaveOptions(), + m_documentMetaInfo, + false /*no lossy prompt*/, + this); + buffer.close(); QImage image; @@ -706,49 +644,42 @@ // save (when the user clicks OK), _will_ fail so we shouldn't have a // preview even if this "half a file" is actually loadable by // QImage::loadFormData(). - if (savedOK) - { + if (savedOK) { image.loadFromData(data); - } - else - { + } else { // Leave as invalid. // TODO: This code path has not been well tested. // Will we trigger divide by zero errors in "m_previewDialog"? } // REFACTOR: merge with kpDocument::getPixmapFromFile() - m_previewDialog->setFilePixmapAndSize (image, data.size ()); + m_previewDialog->setFilePixmapAndSize(image, data.size()); - QApplication::restoreOverrideCursor (); + QApplication::restoreOverrideCursor(); } // protected slot -void kpDocumentSaveOptionsWidget::updatePreviewDialogLastRelativeGeometry () +void kpDocumentSaveOptionsWidget::updatePreviewDialogLastRelativeGeometry() { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "kpDocumentSaveOptionsWidget::" - << "updatePreviewDialogLastRelativeGeometry()" - << endl; + << "updatePreviewDialogLastRelativeGeometry()" + << endl; #endif - if (m_previewDialog && m_previewDialog->isVisible ()) - { - m_previewDialogLastRelativeGeometry = - kpWidgetMapper::fromGlobal (m_visualParent, - QRect (m_previewDialog->x (), m_previewDialog->y (), - m_previewDialog->width (), m_previewDialog->height ())); + if (m_previewDialog && m_previewDialog->isVisible()) { + m_previewDialogLastRelativeGeometry + = kpWidgetMapper::fromGlobal(m_visualParent, + QRect(m_previewDialog->x(), m_previewDialog->y(), + m_previewDialog->width(), + m_previewDialog->height())); #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\tcaching pos = " - << m_previewDialogLastRelativeGeometry; + << m_previewDialogLastRelativeGeometry; #endif - } - else - { + } else { #if DEBUG_KP_DOCUMENT_SAVE_OPTIONS_WIDGET qCDebug(kpLogWidgets) << "\tnot visible - ignoring geometry"; #endif } } - - diff --git a/widgets/kpDualColorButton.h b/widgets/kpDualColorButton.h --- a/widgets/kpDualColorButton.h +++ b/widgets/kpDualColorButton.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,72 +24,67 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpDualColorButton_H #define kpDualColorButton_H - #include #include "imagelib/kpColor.h" - class kpDualColorButton : public QFrame { -Q_OBJECT + Q_OBJECT public: kpDualColorButton (QWidget *parent); - kpColor color (int which) const; - kpColor foregroundColor () const; - kpColor backgroundColor () const; + kpColor color(int which) const; + kpColor foregroundColor() const; + kpColor backgroundColor() const; public slots: - void setColor (int which, const kpColor &color); - void setForegroundColor (const kpColor &color); - void setBackgroundColor (const kpColor &color); + void setColor(int which, const kpColor &color); + void setForegroundColor(const kpColor &color); + void setBackgroundColor(const kpColor &color); signals: // If you connect to this signal, ignore the following // foregroundColorChanged() and backgroundColorChanged() signals - void colorsSwapped (const kpColor &newForegroundColor, - const kpColor &newBackgroundColor); + void colorsSwapped(const kpColor &newForegroundColor, const kpColor &newBackgroundColor); - void foregroundColorChanged (const kpColor &color); - void backgroundColorChanged (const kpColor &color); + void foregroundColorChanged(const kpColor &color); + void backgroundColorChanged(const kpColor &color); public: // (only valid in slots connected to foregroundColorChanged()) - kpColor oldForegroundColor () const; + kpColor oldForegroundColor() const; // (only valid in slots connected to backgroundColorChanged()) - kpColor oldBackgroundColor () const; + kpColor oldBackgroundColor() const; public: - QSize sizeHint () const override; + QSize sizeHint() const override; protected: - QRect swapPixmapRect () const; - QRect foregroundBackgroundRect () const; - QRect foregroundRect () const; - QRect backgroundRect () const; + QRect swapPixmapRect() const; + QRect foregroundBackgroundRect() const; + QRect foregroundRect() const; + QRect backgroundRect() const; - void dragEnterEvent (QDragEnterEvent *e) override; - void dragMoveEvent (QDragMoveEvent *e) override; - void dropEvent (QDropEvent *e) override; + void dragEnterEvent(QDragEnterEvent *e) override; + void dragMoveEvent(QDragMoveEvent *e) override; + void dropEvent(QDropEvent *e) override; - void mousePressEvent (QMouseEvent *e) override; - void mouseMoveEvent (QMouseEvent *e) override; - void mouseReleaseEvent (QMouseEvent *e) override; + void mousePressEvent(QMouseEvent *e) override; + void mouseMoveEvent(QMouseEvent *e) override; + void mouseReleaseEvent(QMouseEvent *e) override; - void mouseDoubleClickEvent (QMouseEvent *e) override; + void mouseDoubleClickEvent(QMouseEvent *e) override; - void paintEvent (QPaintEvent *e) override; + void paintEvent(QPaintEvent *e) override; QPoint m_dragStartPoint; kpColor m_color [2]; kpColor m_oldColor [2]; }; - #endif // kpDualColorButton_H diff --git a/widgets/kpDualColorButton.cpp b/widgets/kpDualColorButton.cpp --- a/widgets/kpDualColorButton.cpp +++ b/widgets/kpDualColorButton.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_DUAL_COLOR_BUTTON 0 - #include "kpDualColorButton.h" #include "views/kpView.h" @@ -48,263 +45,261 @@ //--------------------------------------------------------------------- kpDualColorButton::kpDualColorButton (QWidget *parent) - : QFrame (parent), - m_dragStartPoint (KP_INVALID_POINT) + : QFrame(parent) + , m_dragStartPoint(KP_INVALID_POINT) { - setSizePolicy (QSizePolicy::Fixed/*horizontal*/, - QSizePolicy::Fixed/*vertical*/); - setFrameStyle (QFrame::Panel | QFrame::Sunken); + setSizePolicy(QSizePolicy::Fixed /*horizontal*/, + QSizePolicy::Fixed /*vertical*/); + setFrameStyle(QFrame::Panel | QFrame::Sunken); - m_color [0] = kpColor (0, 0, 0); // black - m_color [1] = kpColor (255, 255, 255); // white + m_color [0] = kpColor(0, 0, 0); // black + m_color [1] = kpColor(255, 255, 255); // white - setAcceptDrops (true); + setAcceptDrops(true); } //--------------------------------------------------------------------- -kpColor kpDualColorButton::color (int which) const +kpColor kpDualColorButton::color(int which) const { - Q_ASSERT (which == 0 || which == 1); + Q_ASSERT(which == 0 || which == 1); return m_color [which]; } //--------------------------------------------------------------------- -kpColor kpDualColorButton::foregroundColor () const +kpColor kpDualColorButton::foregroundColor() const { - return color (0); + return color(0); } //--------------------------------------------------------------------- -kpColor kpDualColorButton::backgroundColor () const +kpColor kpDualColorButton::backgroundColor() const { - return color (1); + return color(1); } //--------------------------------------------------------------------- -void kpDualColorButton::setColor (int which, const kpColor &color) +void kpDualColorButton::setColor(int which, const kpColor &color) { - Q_ASSERT (which == 0 || which == 1); + Q_ASSERT(which == 0 || which == 1); if (m_color [which] == color) { return; } m_oldColor [which] = m_color [which]; m_color [which] = color; - update (); + update(); if (which == 0) { - emit foregroundColorChanged (color); - } - else { - emit backgroundColorChanged (color); + emit foregroundColorChanged(color); + } else { + emit backgroundColorChanged(color); } } //--------------------------------------------------------------------- -void kpDualColorButton::setForegroundColor (const kpColor &color) +void kpDualColorButton::setForegroundColor(const kpColor &color) { - setColor (0, color); + setColor(0, color); } //--------------------------------------------------------------------- -void kpDualColorButton::setBackgroundColor (const kpColor &color) +void kpDualColorButton::setBackgroundColor(const kpColor &color) { - setColor (1, color); + setColor(1, color); } //--------------------------------------------------------------------- - // public -kpColor kpDualColorButton::oldForegroundColor () const +kpColor kpDualColorButton::oldForegroundColor() const { return m_oldColor [0]; } //--------------------------------------------------------------------- // public -kpColor kpDualColorButton::oldBackgroundColor () const +kpColor kpDualColorButton::oldBackgroundColor() const { return m_oldColor [1]; } //--------------------------------------------------------------------- - // public virtual [base QWidget] -QSize kpDualColorButton::sizeHint () const +QSize kpDualColorButton::sizeHint() const { - return {52, 52}; + return { + 52, 52 + }; } //--------------------------------------------------------------------- - // protected -QRect kpDualColorButton::swapPixmapRect () const +QRect kpDualColorButton::swapPixmapRect() const { - QPixmap swapPixmap = UserIcon (QStringLiteral("colorbutton_swap_16x16")); + QPixmap swapPixmap = UserIcon(QStringLiteral("colorbutton_swap_16x16")); - return {contentsRect ().width () - swapPixmap.width (), 0, - swapPixmap.width (), swapPixmap.height ()}; + return { + contentsRect().width() - swapPixmap.width(), 0, + swapPixmap.width(), swapPixmap.height() + }; } //--------------------------------------------------------------------- // protected -QRect kpDualColorButton::foregroundBackgroundRect () const +QRect kpDualColorButton::foregroundBackgroundRect() const { - QRect cr (contentsRect ()); - return {cr.width () / 8, cr.height () / 8, - cr.width () * 6 / 8, cr.height () * 6 / 8}; + QRect cr(contentsRect()); + return { + cr.width() / 8, cr.height() / 8, + cr.width() * 6 / 8, cr.height() * 6 / 8 + }; } //--------------------------------------------------------------------- // protected -QRect kpDualColorButton::foregroundRect () const +QRect kpDualColorButton::foregroundRect() const { - QRect fbr (foregroundBackgroundRect ()); - return {fbr.x (), fbr.y (), - fbr.width () * 3 / 4, fbr.height () * 3 / 4}; + QRect fbr(foregroundBackgroundRect()); + return { + fbr.x(), fbr.y(), + fbr.width() * 3 / 4, fbr.height() * 3 / 4 + }; } //--------------------------------------------------------------------- // protected -QRect kpDualColorButton::backgroundRect () const +QRect kpDualColorButton::backgroundRect() const { - QRect fbr (foregroundBackgroundRect ()); - return {fbr.x () + fbr.width () / 4, fbr.y () + fbr.height () / 4, - fbr.width () * 3 / 4, fbr.height () * 3 / 4}; + QRect fbr(foregroundBackgroundRect()); + return { + fbr.x() + fbr.width() / 4, fbr.y() + fbr.height() / 4, + fbr.width() * 3 / 4, fbr.height() * 3 / 4 + }; } //--------------------------------------------------------------------- - // protected virtual -void kpDualColorButton::dragEnterEvent (QDragEnterEvent *e) +void kpDualColorButton::dragEnterEvent(QDragEnterEvent *e) { #if DEBUG_KP_DUAL_COLOR_BUTTON qCDebug(kpLogWidgets) << "kpDualColorButton::dragEnterEvent() canDecode=" - << KColorMimeData::canDecode (e->mimeData ()); + << KColorMimeData::canDecode(e->mimeData()); #endif - e->accept (); + e->accept(); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpDualColorButton::dragMoveEvent (QDragMoveEvent *e) +void kpDualColorButton::dragMoveEvent(QDragMoveEvent *e) { #if DEBUG_KP_DUAL_COLOR_BUTTON qCDebug(kpLogWidgets) << "kpDualColorButton::dragMoveEvent() canDecode=" - << KColorMimeData::canDecode (e->mimeData ()); + << KColorMimeData::canDecode(e->mimeData()); #endif - e->setAccepted ( - (foregroundRect ().contains (e->pos ()) || - backgroundRect ().contains (e->pos ())) && - KColorMimeData::canDecode (e->mimeData ())); + e->setAccepted( + (foregroundRect().contains(e->pos()) + || backgroundRect().contains(e->pos())) + && KColorMimeData::canDecode(e->mimeData())); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpDualColorButton::dropEvent (QDropEvent *e) +void kpDualColorButton::dropEvent(QDropEvent *e) { - QColor col = KColorMimeData::fromMimeData (e->mimeData ()); + QColor col = KColorMimeData::fromMimeData(e->mimeData()); #if DEBUG_KP_DUAL_COLOR_BUTTON qCDebug(kpLogWidgets) << "kpDualColorButton::dropEvent() col=" - << (int *) col.rgba() - << " (with alpha=" << (int *) col.rgba () << ")"; + << (int *)col.rgba() + << " (with alpha=" << (int *)col.rgba() << ")"; #endif - if (col.isValid ()) - { - if (foregroundRect ().contains (e->pos ())) { - setForegroundColor (kpColor (col.rgba())); - } - else if (backgroundRect ().contains (e->pos ())) { - setBackgroundColor (kpColor (col.rgba())); + if (col.isValid()) { + if (foregroundRect().contains(e->pos())) { + setForegroundColor(kpColor(col.rgba())); + } else if (backgroundRect().contains(e->pos())) { + setBackgroundColor(kpColor(col.rgba())); } } } //--------------------------------------------------------------------- - // protected virtual [base QWidget] -void kpDualColorButton::mousePressEvent (QMouseEvent *e) +void kpDualColorButton::mousePressEvent(QMouseEvent *e) { #if DEBUG_KP_DUAL_COLOR_BUTTON - qCDebug(kpLogWidgets) << "kpDualColorButton::mousePressEvent() pos=" << e->pos (); + qCDebug(kpLogWidgets) << "kpDualColorButton::mousePressEvent() pos=" << e->pos(); #endif m_dragStartPoint = KP_INVALID_POINT; - if (e->button () == Qt::LeftButton) { - m_dragStartPoint = e->pos (); + if (e->button() == Qt::LeftButton) { + m_dragStartPoint = e->pos(); } } //--------------------------------------------------------------------- -void kpDualColorButton::mouseMoveEvent (QMouseEvent *e) +void kpDualColorButton::mouseMoveEvent(QMouseEvent *e) { #if DEBUG_KP_DUAL_COLOR_BUTTON - qCDebug(kpLogWidgets) << "kpDualColorButton::mouseMoveEvent() pos=" << e->pos () - << " buttons=" << e->buttons () - << " dragStartPoint=" << m_dragStartPoint << endl; + qCDebug(kpLogWidgets) << "kpDualColorButton::mouseMoveEvent() pos=" << e->pos() + << " buttons=" << e->buttons() + << " dragStartPoint=" << m_dragStartPoint << endl; #endif if (m_dragStartPoint == KP_INVALID_POINT) { return; } - if (!(e->buttons () & Qt::LeftButton)) - { + if (!(e->buttons() & Qt::LeftButton)) { m_dragStartPoint = KP_INVALID_POINT; return; } - const int delay = QApplication::startDragDistance (); - if (e->x () < m_dragStartPoint.x () - delay || - e->x () > m_dragStartPoint.x () + delay || - e->y () < m_dragStartPoint.y () - delay || - e->y () > m_dragStartPoint.y () + delay) - { + const int delay = QApplication::startDragDistance(); + if (e->x() < m_dragStartPoint.x() - delay + || e->x() > m_dragStartPoint.x() + delay + || e->y() < m_dragStartPoint.y() - delay + || e->y() > m_dragStartPoint.y() + delay) { #if DEBUG_KP_DUAL_COLOR_BUTTON qCDebug(kpLogWidgets) << "\tstarting drag as long as it's in a rectangle"; #endif kpColor color; - if (foregroundRect ().contains (m_dragStartPoint)) { - color = foregroundColor (); - } - else if (backgroundRect ().contains (m_dragStartPoint)) { - color = backgroundColor (); + if (foregroundRect().contains(m_dragStartPoint)) { + color = foregroundColor(); + } else if (backgroundRect().contains(m_dragStartPoint)) { + color = backgroundColor(); } #if DEBUG_KP_DUAL_COLOR_BUTTON - qCDebug(kpLogWidgets) << "\tcolor.isValid=" << color.isValid () - << " rgb=" << (color.isValid () ? (int *) color.toQRgb () : 0) - << endl; + qCDebug(kpLogWidgets) << "\tcolor.isValid=" << color.isValid() + << " rgb=" << (color.isValid() ? (int *)color.toQRgb() : 0) + << endl; #endif - if (color.isValid ()) - { - if (!color.isTransparent ()) { - KColorMimeData::createDrag (color.toQColor (), this)->exec (); + if (color.isValid()) { + if (!color.isTransparent()) { + KColorMimeData::createDrag(color.toQColor(), this)->exec(); } } @@ -315,13 +310,12 @@ //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpDualColorButton::mouseReleaseEvent (QMouseEvent *e) +void kpDualColorButton::mouseReleaseEvent(QMouseEvent *e) { m_dragStartPoint = KP_INVALID_POINT; - if (swapPixmapRect ().contains (e->pos ()) && - m_color [0] != m_color [1]) - { + if (swapPixmapRect().contains(e->pos()) + && m_color [0] != m_color [1]) { #if DEBUG_KP_DUAL_COLOR_BUTTON && 1 qCDebug(kpLogWidgets) << "kpDualColorButton::mouseReleaseEvent() swap colors:"; #endif @@ -332,139 +326,120 @@ m_color [0] = m_color [1]; m_color [1] = temp; - update (); + update(); - emit colorsSwapped (m_color [0], m_color [1]); - emit foregroundColorChanged (m_color [0]); - emit backgroundColorChanged (m_color [1]); + emit colorsSwapped(m_color [0], m_color [1]); + emit foregroundColorChanged(m_color [0]); + emit backgroundColorChanged(m_color [1]); } } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpDualColorButton::mouseDoubleClickEvent (QMouseEvent *e) +void kpDualColorButton::mouseDoubleClickEvent(QMouseEvent *e) { int whichColor = -1; - if (foregroundRect ().contains (e->pos ())) { + if (foregroundRect().contains(e->pos())) { whichColor = 0; - } - else if (backgroundRect ().contains (e->pos ())) { + } else if (backgroundRect().contains(e->pos())) { whichColor = 1; } - if (whichColor == 0 || whichColor == 1) - { + if (whichColor == 0 || whichColor == 1) { QColorDialog dialog(this); dialog.setCurrentColor(color(whichColor).toQColor()); dialog.setOptions(QColorDialog::ShowAlphaChannel); - if ( dialog.exec() == QDialog::Accepted ) { - setColor(whichColor, kpColor(dialog.currentColor().rgba())); + if (dialog.exec() == QDialog::Accepted) { + setColor(whichColor, kpColor(dialog.currentColor().rgba())); } } } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpDualColorButton::paintEvent (QPaintEvent *e) +void kpDualColorButton::paintEvent(QPaintEvent *e) { #if DEBUG_KP_DUAL_COLOR_BUTTON && 1 - qCDebug(kpLogWidgets) << "kpDualColorButton::draw() rect=" << rect () - << " contentsRect=" << contentsRect () - << endl; + qCDebug(kpLogWidgets) << "kpDualColorButton::draw() rect=" << rect() + << " contentsRect=" << contentsRect() + << endl; #endif // Draw frame first. - QFrame::paintEvent (e); + QFrame::paintEvent(e); - QPainter painter (this); + QPainter painter(this); // Fill with background. - if (isEnabled ()) - { - kpView::drawTransparentBackground (&painter, - contentsRect ().topLeft ()/*checkerboard top-left*/, - contentsRect (), - true/*preview*/); - } - else - { + if (isEnabled()) { + kpView::drawTransparentBackground(&painter, + contentsRect().topLeft() /*checkerboard top-left*/, + contentsRect(), + true /*preview*/); + } else { // Use default widget background. } - - painter.translate (contentsRect ().x (), contentsRect ().y ()); - + painter.translate(contentsRect().x(), contentsRect().y()); // Draw "Swap Colours" button (top-right). - QPixmap swapPixmap = UserIcon (QStringLiteral("colorbutton_swap_16x16")); - if (!isEnabled ()) - { + QPixmap swapPixmap = UserIcon(QStringLiteral("colorbutton_swap_16x16")); + if (!isEnabled()) { // Don't let the fill() touch the mask. - QBitmap swapBitmapMask = swapPixmap.mask (); - swapPixmap.setMask (QBitmap ()); + QBitmap swapBitmapMask = swapPixmap.mask(); + swapPixmap.setMask(QBitmap()); // Grey out the opaque parts of "swapPixmap". - swapPixmap.fill (palette ().color (QPalette::Dark)); + swapPixmap.fill(palette().color(QPalette::Dark)); - swapPixmap.setMask (swapBitmapMask); + swapPixmap.setMask(swapBitmapMask); } - painter.drawPixmap (swapPixmapRect ().topLeft (), swapPixmap); - + painter.drawPixmap(swapPixmapRect().topLeft(), swapPixmap); // Draw background colour patch. - QRect bgRect = backgroundRect (); - QRect bgRectInside = QRect (bgRect.x () + 2, bgRect.y () + 2, - bgRect.width () - 4, bgRect.height () - 4); - if (isEnabled ()) - { + QRect bgRect = backgroundRect(); + QRect bgRectInside = QRect(bgRect.x() + 2, bgRect.y() + 2, + bgRect.width() - 4, bgRect.height() - 4); + if (isEnabled()) { #if DEBUG_KP_DUAL_COLOR_BUTTON && 1 - qCDebug(kpLogWidgets) << "\tbackgroundColor=" << (int *) m_color [1].toQRgb () - << endl; + qCDebug(kpLogWidgets) << "\tbackgroundColor=" << (int *)m_color [1].toQRgb() + << endl; #endif - if (m_color [1].isTransparent ()) { // only if fully transparent - painter.drawPixmap (bgRectInside, UserIcon (QStringLiteral("color_transparent_26x26"))); - } - else { - painter.fillRect (bgRectInside, m_color [1].toQColor ()); + if (m_color [1].isTransparent()) { // only if fully transparent + painter.drawPixmap(bgRectInside, UserIcon(QStringLiteral("color_transparent_26x26"))); + } else { + painter.fillRect(bgRectInside, m_color [1].toQColor()); } + } else { + painter.fillRect(bgRectInside, palette().color(QPalette::Button)); } - else { - painter.fillRect (bgRectInside, palette().color (QPalette::Button)); - } - qDrawShadePanel (&painter, bgRect, palette(), - false/*not sunken*/, 2/*lineWidth*/, - nullptr/*never fill*/); - - + qDrawShadePanel(&painter, bgRect, palette(), + false /*not sunken*/, 2 /*lineWidth*/, + nullptr /*never fill*/); // Draw foreground colour patch. // Must be drawn after background patch since we're on top. - QRect fgRect = foregroundRect (); - QRect fgRectInside = QRect (fgRect.x () + 2, fgRect.y () + 2, - fgRect.width () - 4, fgRect.height () - 4); - if (isEnabled ()) - { + QRect fgRect = foregroundRect(); + QRect fgRectInside = QRect(fgRect.x() + 2, fgRect.y() + 2, + fgRect.width() - 4, fgRect.height() - 4); + if (isEnabled()) { #if DEBUG_KP_DUAL_COLOR_BUTTON && 1 - qCDebug(kpLogWidgets) << "\tforegroundColor=" << (int *) m_color [0].toQRgb () - << endl; + qCDebug(kpLogWidgets) << "\tforegroundColor=" << (int *)m_color [0].toQRgb() + << endl; #endif - if (m_color [0].isTransparent ()) { // only if fully transparent - painter.drawPixmap (fgRectInside, UserIcon (QStringLiteral("color_transparent_26x26"))); - } - else { - painter.fillRect (fgRectInside, m_color [0].toQColor ()); + if (m_color [0].isTransparent()) { // only if fully transparent + painter.drawPixmap(fgRectInside, UserIcon(QStringLiteral("color_transparent_26x26"))); + } else { + painter.fillRect(fgRectInside, m_color [0].toQColor()); } - } - else { - painter.fillRect (fgRectInside, palette ().color (QPalette::Button)); + } else { + painter.fillRect(fgRectInside, palette().color(QPalette::Button)); } - qDrawShadePanel (&painter, fgRect, palette (), - false/*not sunken*/, 2/*lineWidth*/, - nullptr/*never fill*/); + qDrawShadePanel(&painter, fgRect, palette(), + false /*not sunken*/, 2 /*lineWidth*/, + nullptr /*never fill*/); } - - diff --git a/widgets/kpPrintDialogPage.h b/widgets/kpPrintDialogPage.h --- a/widgets/kpPrintDialogPage.h +++ b/widgets/kpPrintDialogPage.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2007 John Layt @@ -26,27 +25,24 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpPrintDialogPage_H #define kpPrintDialogPage_H #include - class kpPrintDialogPage : public QWidget { -Q_OBJECT + Q_OBJECT public: kpPrintDialogPage (QWidget *parent); ~kpPrintDialogPage () override; - bool printImageCenteredOnPage (); - void setPrintImageCenteredOnPage (bool printCentered); + bool printImageCenteredOnPage(); + void setPrintImageCenteredOnPage(bool printCentered); private: - struct kpPrintDialogPagePrivate * const d; + struct kpPrintDialogPagePrivate *const d; }; - #endif // kpPrintDialogPage_H diff --git a/widgets/kpPrintDialogPage.cpp b/widgets/kpPrintDialogPage.cpp --- a/widgets/kpPrintDialogPage.cpp +++ b/widgets/kpPrintDialogPage.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2007 John Layt @@ -26,10 +25,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_PRINT_DIALOG_PAGE 0 - #include "kpPrintDialogPage.h" #include @@ -41,62 +38,56 @@ #include "kpDefs.h" - struct kpPrintDialogPagePrivate { QRadioButton *printCenteredRadio, *printTopLeftRadio; }; kpPrintDialogPage::kpPrintDialogPage (QWidget *parent) - : QWidget (parent), - d (new kpPrintDialogPagePrivate ()) + : QWidget(parent) + , d(new kpPrintDialogPagePrivate()) { #if DEBUG_KP_PRINT_DIALOG_PAGE qCDebug(kpLogWidgets) << "kpPrintDialogPage::()"; #endif - setWindowTitle (i18nc ("@title:tab", "I&mage Position")); + setWindowTitle(i18nc("@title:tab", "I&mage Position")); - d->printCenteredRadio = new QRadioButton (i18n ("&Center of the page"), - this); - d->printTopLeftRadio = new QRadioButton (i18n ("Top-&left of the page"), - this); + d->printCenteredRadio = new QRadioButton(i18n("&Center of the page"), + this); + d->printTopLeftRadio = new QRadioButton(i18n("Top-&left of the page"), + this); - auto *lay = new QVBoxLayout (this); - lay->addWidget (d->printCenteredRadio); - lay->addWidget (d->printTopLeftRadio); - lay->addStretch (); + auto *lay = new QVBoxLayout(this); + lay->addWidget(d->printCenteredRadio); + lay->addWidget(d->printTopLeftRadio); + lay->addStretch(); - setPrintImageCenteredOnPage (true); + setPrintImageCenteredOnPage(true); } kpPrintDialogPage::~kpPrintDialogPage () { delete d; } - -bool kpPrintDialogPage::printImageCenteredOnPage () +bool kpPrintDialogPage::printImageCenteredOnPage() { #if DEBUG_KP_PRINT_DIALOG_PAGE qCDebug(kpLogWidgets) << "kpPrintDialogPage::printImageCenteredOnPage()" - << " returning " << d->printCenteredRadio->isChecked(); + << " returning " << d->printCenteredRadio->isChecked(); #endif - return d->printCenteredRadio->isChecked (); + return d->printCenteredRadio->isChecked(); } - -void kpPrintDialogPage::setPrintImageCenteredOnPage (bool printCentered) +void kpPrintDialogPage::setPrintImageCenteredOnPage(bool printCentered) { #if DEBUG_KP_PRINT_DIALOG_PAGE qCDebug(kpLogWidgets) << "kpPrintDialogPage::setOptions(" << printCentered << ")"; #endif if (printCentered) { - d->printCenteredRadio->setChecked (true); - } - else { - d->printTopLeftRadio->setChecked (true); + d->printCenteredRadio->setChecked(true); + } else { + d->printTopLeftRadio->setChecked(true); } } - - diff --git a/widgets/kpTransparentColorCell.h b/widgets/kpTransparentColorCell.h --- a/widgets/kpTransparentColorCell.h +++ b/widgets/kpTransparentColorCell.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,42 +24,37 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef kpTransparentColorCell_H #define kpTransparentColorCell_H - #include - class kpColor; - class kpTransparentColorCell : public QFrame { -Q_OBJECT + Q_OBJECT public: kpTransparentColorCell (QWidget *parent); - QSize sizeHint () const override; + QSize sizeHint() const override; signals: - void transparentColorSelected (int mouseButton); + void transparentColorSelected(int mouseButton); // lazy - void foregroundColorChanged (const kpColor &color); - void backgroundColorChanged (const kpColor &color); + void foregroundColorChanged(const kpColor &color); + void backgroundColorChanged(const kpColor &color); protected: - void mousePressEvent (QMouseEvent *e) override; - void contextMenuEvent (QContextMenuEvent *e) override; - void mouseReleaseEvent (QMouseEvent *e) override; + void mousePressEvent(QMouseEvent *e) override; + void contextMenuEvent(QContextMenuEvent *e) override; + void mouseReleaseEvent(QMouseEvent *e) override; - void paintEvent (QPaintEvent *e) override; + void paintEvent(QPaintEvent *e) override; QPixmap m_pixmap; }; - #endif // kpTransparentColorCell_H diff --git a/widgets/kpTransparentColorCell.cpp b/widgets/kpTransparentColorCell.cpp --- a/widgets/kpTransparentColorCell.cpp +++ b/widgets/kpTransparentColorCell.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TRANSPARENT_COLOR_CELL 0 - #include "kpTransparentColorCell.h" #include "imagelib/kpColor.h" @@ -43,30 +40,32 @@ //--------------------------------------------------------------------- kpTransparentColorCell::kpTransparentColorCell (QWidget *parent) - : QFrame (parent) + : QFrame(parent) { - setSizePolicy (QSizePolicy::Fixed/*horizontal*/, - QSizePolicy::Fixed/*vertical*/); - setFrameStyle (QFrame::Panel | QFrame::Sunken); + setSizePolicy(QSizePolicy::Fixed /*horizontal*/, + QSizePolicy::Fixed /*vertical*/); + setFrameStyle(QFrame::Panel | QFrame::Sunken); - m_pixmap = UserIcon (QStringLiteral("color_transparent_26x26")); + m_pixmap = UserIcon(QStringLiteral("color_transparent_26x26")); - this->setToolTip( i18n ("Transparent")); + this->setToolTip(i18n("Transparent")); } //--------------------------------------------------------------------- // public virtual [base QWidget] -QSize kpTransparentColorCell::sizeHint () const +QSize kpTransparentColorCell::sizeHint() const { - return {m_pixmap.width () + frameWidth () * 2, - m_pixmap.height () + frameWidth () * 2}; + return { + m_pixmap.width() + frameWidth() * 2, + m_pixmap.height() + frameWidth() * 2 + }; } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpTransparentColorCell::mousePressEvent (QMouseEvent * /*e*/) +void kpTransparentColorCell::mousePressEvent(QMouseEvent * /*e*/) { // Eat press so that we own the mouseReleaseEvent(). // [http://blogs.qtdeveloper.net/archives/2006/05/27/mouse-event-propagation/] @@ -77,52 +76,45 @@ //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpTransparentColorCell::contextMenuEvent (QContextMenuEvent *e) +void kpTransparentColorCell::contextMenuEvent(QContextMenuEvent *e) { // Eat right-mouse press to prevent it from getting to the toolbar. - e->accept (); + e->accept(); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpTransparentColorCell::mouseReleaseEvent (QMouseEvent *e) +void kpTransparentColorCell::mouseReleaseEvent(QMouseEvent *e) { - if (rect ().contains (e->pos ())) - { - if (e->button () == Qt::LeftButton) - { - emit transparentColorSelected (0); - emit foregroundColorChanged (kpColor::Transparent); - } - else if (e->button () == Qt::RightButton) - { - emit transparentColorSelected (1); - emit backgroundColorChanged (kpColor::Transparent); + if (rect().contains(e->pos())) { + if (e->button() == Qt::LeftButton) { + emit transparentColorSelected(0); + emit foregroundColorChanged(kpColor::Transparent); + } else if (e->button() == Qt::RightButton) { + emit transparentColorSelected(1); + emit backgroundColorChanged(kpColor::Transparent); } } } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpTransparentColorCell::paintEvent (QPaintEvent *e) +void kpTransparentColorCell::paintEvent(QPaintEvent *e) { // Draw frame first. - QFrame::paintEvent (e); + QFrame::paintEvent(e); - if (isEnabled ()) - { + if (isEnabled()) { #if DEBUG_KP_TRANSPARENT_COLOR_CELL qCDebug(kpLogWidgets) << "kpTransparentColorCell::paintEvent() contentsRect=" - << contentsRect () - << endl; + << contentsRect() + << endl; #endif - QPainter p (this); - p.drawPixmap (contentsRect (), m_pixmap); + QPainter p(this); + p.drawPixmap(contentsRect(), m_pixmap); } } //--------------------------------------------------------------------- - - diff --git a/widgets/toolbars/kpColorToolBar.h b/widgets/toolbars/kpColorToolBar.h --- a/widgets/toolbars/kpColorToolBar.h +++ b/widgets/toolbars/kpColorToolBar.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,26 +24,22 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_COLOR_TOOLBAR_H #define KP_COLOR_TOOLBAR_H - #include #include #include #include "imagelib/kpColor.h" - class QBoxLayout; class kpColorCells; class kpColorPalette; class kpColorSimilarityToolBarItem; class kpDualColorButton; - // COMPAT: Vertical orientation and undocking were broken by the Qt4 port // so kpMainWindow::init() keeps this tool bar in a constant position for // the time being. To help make this workaround possible, we use QDockWidget, @@ -58,67 +53,65 @@ // support back in, somehow (create a "KDockWidget" class?). class kpColorToolBar : public QDockWidget { -Q_OBJECT + Q_OBJECT public: kpColorToolBar (const QString &label, QWidget *parent); - kpColorCells *colorCells () const; + kpColorCells *colorCells() const; - kpColor color (int which) const; - void setColor (int which, const kpColor &color); + kpColor color(int which) const; + void setColor(int which, const kpColor &color); - kpColor foregroundColor () const; - kpColor backgroundColor () const; + kpColor foregroundColor() const; + kpColor backgroundColor() const; - double colorSimilarity () const; - void setColorSimilarity (double similarity); - int processedColorSimilarity () const; + double colorSimilarity() const; + void setColorSimilarity(double similarity); + int processedColorSimilarity() const; - void openColorSimilarityDialog (); - void flashColorSimilarityToolBarItem (); + void openColorSimilarityDialog(); + void flashColorSimilarityToolBarItem(); signals: // If you connect to this signal, ignore the following // foregroundColorChanged() and backgroundColorChanged() signals - void colorsSwapped (const kpColor &newForegroundColor, - const kpColor &newBackgroundColor); + void colorsSwapped(const kpColor &newForegroundColor, const kpColor &newBackgroundColor); - void foregroundColorChanged (const kpColor &color); - void backgroundColorChanged (const kpColor &color); - void colorSimilarityChanged (double similarity, int processedSimilarity); + void foregroundColorChanged(const kpColor &color); + void backgroundColorChanged(const kpColor &color); + void colorSimilarityChanged(double similarity, int processedSimilarity); public: // (only valid in slots connected to foregroundColorChanged()) - kpColor oldForegroundColor () const; + kpColor oldForegroundColor() const; // (only valid in slots connected to backgroundColorChanged()) - kpColor oldBackgroundColor () const; + kpColor oldBackgroundColor() const; // (only valid in slots connected to colorSimilarityChanged()) - double oldColorSimilarity () const; + double oldColorSimilarity() const; public slots: - void setForegroundColor (const kpColor &color); - void setBackgroundColor (const kpColor &color); + void setForegroundColor(const kpColor &color); + void setBackgroundColor(const kpColor &color); private slots: - void updateNameOrUrlLabel (); + void updateNameOrUrlLabel(); protected: // Eat color drops (which are usually accidental drags from one of our // child widgets) to prevent them from being pasted as text in the // main window (by kpMainWindow::dropEvent()). - void dragEnterEvent (QDragEnterEvent *e) override; - void dragMoveEvent (QDragMoveEvent *e) override; + void dragEnterEvent(QDragEnterEvent *e) override; + void dragMoveEvent(QDragMoveEvent *e) override; private: - void adjustToOrientation (Qt::Orientation o); + void adjustToOrientation(Qt::Orientation o); QBoxLayout *m_boxLayout; kpDualColorButton *m_dualColorButton; kpColorPalette *m_colorPalette; kpColorSimilarityToolBarItem *m_colorSimilarityToolBarItem; }; - #endif // KP_COLOR_TOOLBAR_H diff --git a/widgets/toolbars/kpColorToolBar.cpp b/widgets/toolbars/kpColorToolBar.cpp --- a/widgets/toolbars/kpColorToolBar.cpp +++ b/widgets/toolbars/kpColorToolBar.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_COLOR_TOOL_BAR 0 - #include "widgets/toolbars/kpColorToolBar.h" #include @@ -49,256 +46,245 @@ //--------------------------------------------------------------------- kpColorToolBar::kpColorToolBar (const QString &label, QWidget *parent) - : QDockWidget (parent) + : QDockWidget(parent) { - setWindowTitle (label); + setWindowTitle(label); // not closable, as it's not a KDE toolbar yet and can not be made shown easily again setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); - setAcceptDrops (true); + setAcceptDrops(true); - QWidget *base = new QWidget (this); - m_boxLayout = new QBoxLayout (QBoxLayout::LeftToRight, base); - m_boxLayout->setMargin (5); - m_boxLayout->setSpacing (10 * 3); + QWidget *base = new QWidget(this); + m_boxLayout = new QBoxLayout(QBoxLayout::LeftToRight, base); + m_boxLayout->setMargin(5); + m_boxLayout->setSpacing(10 * 3); // This holds the current global foreground and background colors, for // tools. - m_dualColorButton = new kpDualColorButton (base); - connect (m_dualColorButton, &kpDualColorButton::colorsSwapped, - this, &kpColorToolBar::colorsSwapped); + m_dualColorButton = new kpDualColorButton(base); + connect(m_dualColorButton, &kpDualColorButton::colorsSwapped, + this, &kpColorToolBar::colorsSwapped); - connect (m_dualColorButton, &kpDualColorButton::foregroundColorChanged, - this, &kpColorToolBar::foregroundColorChanged); + connect(m_dualColorButton, &kpDualColorButton::foregroundColorChanged, + this, &kpColorToolBar::foregroundColorChanged); - connect (m_dualColorButton, &kpDualColorButton::backgroundColorChanged, - this, &kpColorToolBar::backgroundColorChanged); + connect(m_dualColorButton, &kpDualColorButton::backgroundColorChanged, + this, &kpColorToolBar::backgroundColorChanged); - m_boxLayout->addWidget (m_dualColorButton, 0/*stretch*/, Qt::AlignVCenter); + m_boxLayout->addWidget(m_dualColorButton, 0 /*stretch*/, Qt::AlignVCenter); - m_colorPalette = new kpColorPalette (base); - connect (m_colorPalette, &kpColorPalette::foregroundColorChanged, - m_dualColorButton, &kpDualColorButton::setForegroundColor); + m_colorPalette = new kpColorPalette(base); + connect(m_colorPalette, &kpColorPalette::foregroundColorChanged, + m_dualColorButton, &kpDualColorButton::setForegroundColor); - connect (m_colorPalette, &kpColorPalette::backgroundColorChanged, - m_dualColorButton, &kpDualColorButton::setBackgroundColor); + connect(m_colorPalette, &kpColorPalette::backgroundColorChanged, + m_dualColorButton, &kpDualColorButton::setBackgroundColor); - connect (m_colorPalette->colorCells (), &kpColorCells::isModifiedChanged, - this, &kpColorToolBar::updateNameOrUrlLabel); + connect(m_colorPalette->colorCells(), &kpColorCells::isModifiedChanged, + this, &kpColorToolBar::updateNameOrUrlLabel); - connect (m_colorPalette->colorCells (), &kpColorCells::urlChanged, - this, &kpColorToolBar::updateNameOrUrlLabel); + connect(m_colorPalette->colorCells(), &kpColorCells::urlChanged, + this, &kpColorToolBar::updateNameOrUrlLabel); - connect (m_colorPalette->colorCells (), &kpColorCells::nameChanged, - this, &kpColorToolBar::updateNameOrUrlLabel); + connect(m_colorPalette->colorCells(), &kpColorCells::nameChanged, + this, &kpColorToolBar::updateNameOrUrlLabel); - updateNameOrUrlLabel (); + updateNameOrUrlLabel(); - m_boxLayout->addWidget (m_colorPalette, 0/*stretch*/); + m_boxLayout->addWidget(m_colorPalette, 0 /*stretch*/); - m_colorSimilarityToolBarItem = new kpColorSimilarityToolBarItem (base); - connect (m_colorSimilarityToolBarItem, - &kpColorSimilarityToolBarItem::colorSimilarityChanged, - this, &kpColorToolBar::colorSimilarityChanged); + m_colorSimilarityToolBarItem = new kpColorSimilarityToolBarItem(base); + connect(m_colorSimilarityToolBarItem, + &kpColorSimilarityToolBarItem::colorSimilarityChanged, + this, &kpColorToolBar::colorSimilarityChanged); - m_boxLayout->addWidget (m_colorSimilarityToolBarItem, 0/*stretch*/); + m_boxLayout->addWidget(m_colorSimilarityToolBarItem, 0 /*stretch*/); // Pad out all the horizontal space on the right of the Color Tool Bar so that // that the real Color Tool Bar widgets aren't placed in the center of the // Color Tool Bar. - m_boxLayout->addItem ( - new QSpacerItem (1, 1, QSizePolicy::Expanding, QSizePolicy::Preferred)); + m_boxLayout->addItem( + new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Preferred)); - adjustToOrientation (Qt::Horizontal); + adjustToOrientation(Qt::Horizontal); - setWidget (base); + setWidget(base); } //--------------------------------------------------------------------- -void kpColorToolBar::adjustToOrientation (Qt::Orientation o) +void kpColorToolBar::adjustToOrientation(Qt::Orientation o) { #if DEBUG_KP_COLOR_TOOL_BAR qCDebug(kpLogWidgets) << "kpColorToolBar::adjustToOrientation(" - << (o == Qt::Vertical ? "vertical" : "horizontal") - << ") called!"; + << (o == Qt::Vertical ? "vertical" : "horizontal") + << ") called!"; #endif - Q_ASSERT (o == Qt::Horizontal); + Q_ASSERT(o == Qt::Horizontal); - if (o == Qt::Horizontal) - { - m_boxLayout->setDirection (QBoxLayout::LeftToRight); - } - else - { - m_boxLayout->setDirection (QBoxLayout::TopToBottom); + if (o == Qt::Horizontal) { + m_boxLayout->setDirection(QBoxLayout::LeftToRight); + } else { + m_boxLayout->setDirection(QBoxLayout::TopToBottom); } - m_colorPalette->setOrientation (o); + m_colorPalette->setOrientation(o); } //--------------------------------------------------------------------- // public -kpColorCells *kpColorToolBar::colorCells () const +kpColorCells *kpColorToolBar::colorCells() const { - return m_colorPalette->colorCells (); + return m_colorPalette->colorCells(); } //--------------------------------------------------------------------- -kpColor kpColorToolBar::color (int which) const +kpColor kpColorToolBar::color(int which) const { - Q_ASSERT (which == 0 || which == 1); + Q_ASSERT(which == 0 || which == 1); - return m_dualColorButton->color (which); + return m_dualColorButton->color(which); } //--------------------------------------------------------------------- -void kpColorToolBar::setColor (int which, const kpColor &color) +void kpColorToolBar::setColor(int which, const kpColor &color) { - Q_ASSERT (which == 0 || which == 1); + Q_ASSERT(which == 0 || which == 1); - m_dualColorButton->setColor (which, color); + m_dualColorButton->setColor(which, color); } //--------------------------------------------------------------------- -kpColor kpColorToolBar::foregroundColor () const +kpColor kpColorToolBar::foregroundColor() const { - return m_dualColorButton->foregroundColor (); + return m_dualColorButton->foregroundColor(); } //--------------------------------------------------------------------- -void kpColorToolBar::setForegroundColor (const kpColor &color) +void kpColorToolBar::setForegroundColor(const kpColor &color) { #if DEBUG_KP_COLOR_TOOL_BAR qCDebug(kpLogWidgets) << "kpColorToolBar::setForegroundColor(" - << (int *) color.toQRgb () << ")"; + << (int *)color.toQRgb() << ")"; #endif - m_dualColorButton->setForegroundColor (color); + m_dualColorButton->setForegroundColor(color); } //--------------------------------------------------------------------- -kpColor kpColorToolBar::backgroundColor () const +kpColor kpColorToolBar::backgroundColor() const { - return m_dualColorButton->backgroundColor (); + return m_dualColorButton->backgroundColor(); } //--------------------------------------------------------------------- -void kpColorToolBar::setBackgroundColor (const kpColor &color) +void kpColorToolBar::setBackgroundColor(const kpColor &color) { #if DEBUG_KP_COLOR_TOOL_BAR qCDebug(kpLogWidgets) << "kpColorToolBar::setBackgroundColor(" - << (int *) color.toQRgb () << ")"; + << (int *)color.toQRgb() << ")"; #endif - m_dualColorButton->setBackgroundColor (color); + m_dualColorButton->setBackgroundColor(color); } //--------------------------------------------------------------------- - -kpColor kpColorToolBar::oldForegroundColor () const +kpColor kpColorToolBar::oldForegroundColor() const { - return m_dualColorButton->oldForegroundColor (); + return m_dualColorButton->oldForegroundColor(); } //--------------------------------------------------------------------- -kpColor kpColorToolBar::oldBackgroundColor () const +kpColor kpColorToolBar::oldBackgroundColor() const { - return m_dualColorButton->oldBackgroundColor (); + return m_dualColorButton->oldBackgroundColor(); } //--------------------------------------------------------------------- -double kpColorToolBar::oldColorSimilarity () const +double kpColorToolBar::oldColorSimilarity() const { - return m_colorSimilarityToolBarItem->oldColorSimilarity (); + return m_colorSimilarityToolBarItem->oldColorSimilarity(); } //--------------------------------------------------------------------- -double kpColorToolBar::colorSimilarity () const +double kpColorToolBar::colorSimilarity() const { - return m_colorSimilarityToolBarItem->colorSimilarity (); + return m_colorSimilarityToolBarItem->colorSimilarity(); } //--------------------------------------------------------------------- -void kpColorToolBar::setColorSimilarity (double similarity) +void kpColorToolBar::setColorSimilarity(double similarity) { - m_colorSimilarityToolBarItem->setColorSimilarity (similarity); + m_colorSimilarityToolBarItem->setColorSimilarity(similarity); } //--------------------------------------------------------------------- -int kpColorToolBar::processedColorSimilarity () const +int kpColorToolBar::processedColorSimilarity() const { - return m_colorSimilarityToolBarItem->processedColorSimilarity (); + return m_colorSimilarityToolBarItem->processedColorSimilarity(); } //--------------------------------------------------------------------- -void kpColorToolBar::openColorSimilarityDialog () +void kpColorToolBar::openColorSimilarityDialog() { - m_colorSimilarityToolBarItem->openDialog (); + m_colorSimilarityToolBarItem->openDialog(); } //--------------------------------------------------------------------- -void kpColorToolBar::flashColorSimilarityToolBarItem () +void kpColorToolBar::flashColorSimilarityToolBarItem() { - m_colorSimilarityToolBarItem->flash (); + m_colorSimilarityToolBarItem->flash(); } //--------------------------------------------------------------------- // private slot -void kpColorToolBar::updateNameOrUrlLabel () +void kpColorToolBar::updateNameOrUrlLabel() { QString name; - kpColorCells *colorCells = m_colorPalette->colorCells (); - if (!colorCells->url ().isEmpty ()) { - name = kpUrlFormatter::PrettyFilename (colorCells->url ()); - } - else - { - if (!colorCells->name ().isEmpty ()) { - name = colorCells->name (); - } - else { - name = i18n ("KolourPaint Defaults"); + kpColorCells *colorCells = m_colorPalette->colorCells(); + if (!colorCells->url().isEmpty()) { + name = kpUrlFormatter::PrettyFilename(colorCells->url()); + } else { + if (!colorCells->name().isEmpty()) { + name = colorCells->name(); + } else { + name = i18n("KolourPaint Defaults"); } } - if (name.isEmpty ()) { - name = i18n ("Untitled"); + if (name.isEmpty()) { + name = i18n("Untitled"); } - KLocalizedString labelStr; - if (!m_colorPalette->colorCells ()->isModified ()) - { - labelStr = - ki18nc ("Colors: name_or_url_of_color_palette", - "Colors: %1") - .subs (name); - } - else - { - labelStr = - ki18nc ("Colors: name_or_url_of_color_palette [modified]", - "Colors: %1 [modified]") - .subs (name); + if (!m_colorPalette->colorCells()->isModified()) { + labelStr + = ki18nc("Colors: name_or_url_of_color_palette", + "Colors: %1") + .subs(name); + } else { + labelStr + = ki18nc("Colors: name_or_url_of_color_palette [modified]", + "Colors: %1 [modified]") + .subs(name); } // Kill 2 birds with 1 stone: @@ -309,33 +295,32 @@ // TODO: This currently hides the windowTitle() even when it's not docked, // because we've abused it to show the name of open color palette // instead. - setWindowTitle (labelStr.toString ()); + setWindowTitle(labelStr.toString()); } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpColorToolBar::dragEnterEvent (QDragEnterEvent *e) +void kpColorToolBar::dragEnterEvent(QDragEnterEvent *e) { // Grab the color drag for this widget, preventing it from being // handled by our parent, the main window. - e->setAccepted (KColorMimeData::canDecode (e->mimeData ())); + e->setAccepted(KColorMimeData::canDecode(e->mimeData())); #if DEBUG_KP_COLOR_TOOL_BAR - qCDebug(kpLogWidgets) << "isAccepted=" << e->isAccepted (); + qCDebug(kpLogWidgets) << "isAccepted=" << e->isAccepted(); #endif } //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpColorToolBar::dragMoveEvent (QDragMoveEvent *e) +void kpColorToolBar::dragMoveEvent(QDragMoveEvent *e) { // Stop the grabbed drag from being dropped. - e->setAccepted (!KColorMimeData::canDecode (e->mimeData ())); + e->setAccepted(!KColorMimeData::canDecode(e->mimeData())); #if DEBUG_KP_COLOR_TOOL_BAR - qCDebug(kpLogWidgets) << "isAccepted=" << e->isAccepted (); + qCDebug(kpLogWidgets) << "isAccepted=" << e->isAccepted(); #endif } //--------------------------------------------------------------------- - diff --git a/widgets/toolbars/kpToolToolBar.h b/widgets/toolbars/kpToolToolBar.h --- a/widgets/toolbars/kpToolToolBar.h +++ b/widgets/toolbars/kpToolToolBar.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang Copyright (c) 2011 Martin Koller @@ -26,16 +25,13 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_TOOL_BAR_H #define KP_TOOL_TOOL_BAR_H - #include #include - class QAbstractButton; class QBoxLayout; class QButtonGroup; @@ -55,47 +51,70 @@ class kpToolToolBar : public KToolBar { -Q_OBJECT + Q_OBJECT public: kpToolToolBar (const QString &name, int colsOrRows, QMainWindow *parent); ~kpToolToolBar () override; void registerTool(kpTool *tool); void unregisterTool(kpTool *tool); - kpTool *tool () const; - void selectTool (const kpTool *tool, bool reselectIfSameTool = false); + kpTool *tool() const; + void selectTool(const kpTool *tool, bool reselectIfSameTool = false); - kpTool *previousTool () const; - void selectPreviousTool (); + kpTool *previousTool() const; + void selectPreviousTool(); - void hideAllToolWidgets (); + void hideAllToolWidgets(); // could this be cleaner (the tools have to access them individually somehow)? - kpToolWidgetBrush *toolWidgetBrush () const { return m_toolWidgetBrush; } - kpToolWidgetEraserSize *toolWidgetEraserSize () const { return m_toolWidgetEraserSize; } - kpToolWidgetFillStyle *toolWidgetFillStyle () const { return m_toolWidgetFillStyle; } - kpToolWidgetLineWidth *toolWidgetLineWidth () const { return m_toolWidgetLineWidth; } - kpToolWidgetOpaqueOrTransparent *toolWidgetOpaqueOrTransparent () const { return m_toolWidgetOpaqueOrTransparent; } - kpToolWidgetSpraycanSize *toolWidgetSpraycanSize () const { return m_toolWidgetSpraycanSize; } - - kpToolWidgetBase *shownToolWidget (int which) const; + kpToolWidgetBrush *toolWidgetBrush() const + { + return m_toolWidgetBrush; + } + + kpToolWidgetEraserSize *toolWidgetEraserSize() const + { + return m_toolWidgetEraserSize; + } + + kpToolWidgetFillStyle *toolWidgetFillStyle() const + { + return m_toolWidgetFillStyle; + } + + kpToolWidgetLineWidth *toolWidgetLineWidth() const + { + return m_toolWidgetLineWidth; + } + + kpToolWidgetOpaqueOrTransparent *toolWidgetOpaqueOrTransparent() const + { + return m_toolWidgetOpaqueOrTransparent; + } + + kpToolWidgetSpraycanSize *toolWidgetSpraycanSize() const + { + return m_toolWidgetSpraycanSize; + } + + kpToolWidgetBase *shownToolWidget(int which) const; signals: - void sigToolSelected (kpTool *tool); // tool may be 0 - void toolWidgetOptionSelected (); + void sigToolSelected(kpTool *tool); // tool may be 0 + void toolWidgetOptionSelected(); private slots: - void slotToolButtonClicked (); + void slotToolButtonClicked(); - void slotToolActionActivated (); + void slotToolActionActivated(); void adjustToOrientation(Qt::Orientation o); void slotIconSizeChanged(const QSize &); void slotToolButtonStyleChanged(Qt::ToolButtonStyle style); private: - void addButton (QAbstractButton *button, Qt::Orientation o, int num); + void addButton(QAbstractButton *button, Qt::Orientation o, int num); void adjustSizeConstraint(); int m_vertCols; @@ -119,5 +138,4 @@ kpTool *m_previousTool, *m_currentTool; }; - #endif // KP_TOOL_TOOL_BAR_H diff --git a/widgets/toolbars/kpToolToolBar.cpp b/widgets/toolbars/kpToolToolBar.cpp --- a/widgets/toolbars/kpToolToolBar.cpp +++ b/widgets/toolbars/kpToolToolBar.cpp @@ -25,10 +25,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_TOOL_BAR 0 - #include "widgets/toolbars/kpToolToolBar.h" #include @@ -55,18 +53,21 @@ { public: kpToolButton (kpTool *tool, QWidget *parent) - : QToolButton (parent), - m_tool (tool) + : QToolButton(parent) + , m_tool(tool) { } - kpTool *tool() const { return m_tool; } + kpTool *tool() const + { + return m_tool; + } protected: void mouseDoubleClickEvent(QMouseEvent *e) override { - if (e->button () == Qt::LeftButton && m_tool) { - m_tool->globalDraw (); + if (e->button() == Qt::LeftButton && m_tool) { + m_tool->globalDraw(); } } @@ -76,72 +77,79 @@ //--------------------------------------------------------------------- kpToolToolBar::kpToolToolBar(const QString &name, int colsOrRows, QMainWindow *parent) - : KToolBar(name, parent, Qt::LeftToolBarArea), - m_vertCols (colsOrRows), - m_buttonGroup (nullptr), - m_baseWidget (nullptr), - m_baseLayout (nullptr), - m_toolLayout (nullptr), - m_previousTool (nullptr), m_currentTool (nullptr) + : KToolBar(name, parent, Qt::LeftToolBarArea) + , m_vertCols(colsOrRows) + , m_buttonGroup(nullptr) + , m_baseWidget(nullptr) + , m_baseLayout(nullptr) + , m_toolLayout(nullptr) + , m_previousTool(nullptr) + , m_currentTool(nullptr) { m_baseWidget = new QWidget(this); - m_toolWidgets.append (m_toolWidgetBrush = - new kpToolWidgetBrush (m_baseWidget, QStringLiteral("Tool Widget Brush"))); - m_toolWidgets.append (m_toolWidgetEraserSize = - new kpToolWidgetEraserSize (m_baseWidget, QStringLiteral("Tool Widget Eraser Size"))); - m_toolWidgets.append (m_toolWidgetFillStyle = - new kpToolWidgetFillStyle (m_baseWidget, QStringLiteral("Tool Widget Fill Style"))); - m_toolWidgets.append (m_toolWidgetLineWidth = - new kpToolWidgetLineWidth (m_baseWidget, QStringLiteral("Tool Widget Line Width"))); - m_toolWidgets.append (m_toolWidgetOpaqueOrTransparent = - new kpToolWidgetOpaqueOrTransparent (m_baseWidget, QStringLiteral("Tool Widget Opaque/Transparent"))); - m_toolWidgets.append (m_toolWidgetSpraycanSize = - new kpToolWidgetSpraycanSize (m_baseWidget, QStringLiteral("Tool Widget Spraycan Size"))); - - for (auto *w : m_toolWidgets) - { - connect (w, &kpToolWidgetBase::optionSelected, - this, &kpToolToolBar::toolWidgetOptionSelected); + m_toolWidgets.append(m_toolWidgetBrush + = new kpToolWidgetBrush(m_baseWidget, + QStringLiteral("Tool Widget Brush"))); + m_toolWidgets.append(m_toolWidgetEraserSize + = new kpToolWidgetEraserSize(m_baseWidget, + QStringLiteral("Tool Widget Eraser Size"))); + m_toolWidgets.append(m_toolWidgetFillStyle + = new kpToolWidgetFillStyle(m_baseWidget, + QStringLiteral("Tool Widget Fill Style"))); + m_toolWidgets.append(m_toolWidgetLineWidth + = new kpToolWidgetLineWidth(m_baseWidget, + QStringLiteral("Tool Widget Line Width"))); + m_toolWidgets.append(m_toolWidgetOpaqueOrTransparent + = new kpToolWidgetOpaqueOrTransparent(m_baseWidget, + QStringLiteral( + "Tool Widget Opaque/Transparent"))); + m_toolWidgets.append(m_toolWidgetSpraycanSize + = new kpToolWidgetSpraycanSize(m_baseWidget, + QStringLiteral( + "Tool Widget Spraycan Size"))); + + for (auto *w : m_toolWidgets) { + connect(w, &kpToolWidgetBase::optionSelected, + this, &kpToolToolBar::toolWidgetOptionSelected); } adjustToOrientation(orientation()); - connect (this, &kpToolToolBar::orientationChanged, - this, &kpToolToolBar::adjustToOrientation); + connect(this, &kpToolToolBar::orientationChanged, + this, &kpToolToolBar::adjustToOrientation); - m_buttonGroup = new QButtonGroup (this); - connect (m_buttonGroup, - static_cast(&QButtonGroup::buttonClicked), - this, &kpToolToolBar::slotToolButtonClicked); + m_buttonGroup = new QButtonGroup(this); + connect(m_buttonGroup, + static_cast(&QButtonGroup::buttonClicked), + this, &kpToolToolBar::slotToolButtonClicked); - hideAllToolWidgets (); + hideAllToolWidgets(); addWidget(m_baseWidget); - connect (this, &kpToolToolBar::iconSizeChanged, - this, &kpToolToolBar::slotIconSizeChanged); + connect(this, &kpToolToolBar::iconSizeChanged, + this, &kpToolToolBar::slotIconSizeChanged); - connect (this, &kpToolToolBar::toolButtonStyleChanged, - this, &kpToolToolBar::slotToolButtonStyleChanged); + connect(this, &kpToolToolBar::toolButtonStyleChanged, + this, &kpToolToolBar::slotToolButtonStyleChanged); } //--------------------------------------------------------------------- kpToolToolBar::~kpToolToolBar() { - while ( !m_toolButtons.isEmpty() ) { + while (!m_toolButtons.isEmpty()) { delete m_toolButtons.takeFirst(); } } //--------------------------------------------------------------------- // public -void kpToolToolBar::registerTool (kpTool *tool) +void kpToolToolBar::registerTool(kpTool *tool) { - for (const auto *b : m_toolButtons) - { - if ( b->tool() == tool ) { // already given + for (const auto *b : m_toolButtons) { + if (b->tool() == tool) { // already given return; } } @@ -162,8 +170,8 @@ m_toolButtons.append(b); - connect (tool, &kpTool::actionActivated, - this, &kpToolToolBar::slotToolActionActivated); + connect(tool, &kpTool::actionActivated, + this, &kpToolToolBar::slotToolActionActivated); adjustSizeConstraint(); } @@ -173,105 +181,97 @@ void kpToolToolBar::unregisterTool(kpTool *tool) { - for (int i = 0; i < m_toolButtons.count(); i++) - { - if ( m_toolButtons[i]->tool() == tool ) - { - delete m_toolButtons.takeAt(i); - disconnect (tool, &kpTool::actionActivated, - this, &kpToolToolBar::slotToolActionActivated); - return; - } + for (int i = 0; i < m_toolButtons.count(); i++) { + if (m_toolButtons[i]->tool() == tool) { + delete m_toolButtons.takeAt(i); + disconnect(tool, &kpTool::actionActivated, + this, &kpToolToolBar::slotToolActionActivated); + return; + } } } //--------------------------------------------------------------------- // public -kpTool *kpToolToolBar::tool () const +kpTool *kpToolToolBar::tool() const { return m_currentTool; } //--------------------------------------------------------------------- // public -void kpToolToolBar::selectTool (const kpTool *tool, bool reselectIfSameTool) +void kpToolToolBar::selectTool(const kpTool *tool, bool reselectIfSameTool) { #if DEBUG_KP_TOOL_TOOL_BAR qCDebug(kpLogWidgets) << "kpToolToolBar::selectTool (tool=" << tool - << ") currentTool=" << m_currentTool - << endl; + << ") currentTool=" << m_currentTool + << endl; #endif if (!reselectIfSameTool && tool == m_currentTool) { return; } - if (tool) - { - tool->action()->setChecked(true); - slotToolButtonClicked(); - } - else - { + if (tool) { + tool->action()->setChecked(true); + slotToolButtonClicked(); + } else { QAbstractButton *b = m_buttonGroup->checkedButton(); - if (b) - { + if (b) { // HACK: qbuttongroup.html says the following about exclusive // button groups: // // "to untoggle a button you must click on another button // in the group" // // But we don't want any button to be selected. // So don't be an exclusive button group temporarily. - m_buttonGroup->setExclusive (false); - b->setChecked (false); - m_buttonGroup->setExclusive (true); + m_buttonGroup->setExclusive(false); + b->setChecked(false); + m_buttonGroup->setExclusive(true); - slotToolButtonClicked (); + slotToolButtonClicked(); } } } //--------------------------------------------------------------------- // public -kpTool *kpToolToolBar::previousTool () const +kpTool *kpToolToolBar::previousTool() const { return m_previousTool; } //--------------------------------------------------------------------- // public -void kpToolToolBar::selectPreviousTool () +void kpToolToolBar::selectPreviousTool() { - selectTool (m_previousTool); + selectTool(m_previousTool); } //--------------------------------------------------------------------- // public -void kpToolToolBar::hideAllToolWidgets () +void kpToolToolBar::hideAllToolWidgets() { for (auto *w : m_toolWidgets) { - w->hide (); + w->hide(); } } //--------------------------------------------------------------------- // public -kpToolWidgetBase *kpToolToolBar::shownToolWidget (int which) const +kpToolWidgetBase *kpToolToolBar::shownToolWidget(int which) const { int uptoVisibleWidget = 0; - for(auto *w : m_toolWidgets) - { - if ( !w->isHidden() ) - { + for (auto *w : m_toolWidgets) { + if (!w->isHidden()) { if (which == uptoVisibleWidget) { return w; } @@ -286,76 +286,71 @@ //--------------------------------------------------------------------- // private slot -void kpToolToolBar::slotToolButtonClicked () +void kpToolToolBar::slotToolButtonClicked() { QAbstractButton *b = m_buttonGroup->checkedButton(); #if DEBUG_KP_TOOL_TOOL_BAR qCDebug(kpLogWidgets) << "kpToolToolBar::slotToolButtonClicked() button=" << b; #endif kpTool *tool = nullptr; - for (const auto *button : m_toolButtons) - { - if ( button == b ) - { - tool = button->tool(); - break; - } + for (const auto *button : m_toolButtons) { + if (button == b) { + tool = button->tool(); + break; + } } #if DEBUG_KP_TOOL_TOOL_BAR qCDebug(kpLogWidgets) << "\ttool=" << tool - << " currentTool=" << m_currentTool - << endl; + << " currentTool=" << m_currentTool + << endl; #endif - if (tool == m_currentTool) - { + if (tool == m_currentTool) { if (m_currentTool) { - m_currentTool->reselect (); + m_currentTool->reselect(); } return; } if (m_currentTool) { - m_currentTool->endInternal (); + m_currentTool->endInternal(); } m_previousTool = m_currentTool; m_currentTool = tool; - if (m_currentTool) - { - kpToolAction *action = m_currentTool->action (); - if (action) - { - action->setChecked (true); + if (m_currentTool) { + kpToolAction *action = m_currentTool->action(); + if (action) { + action->setChecked(true); } - m_currentTool->beginInternal (); + m_currentTool->beginInternal(); } - emit sigToolSelected (m_currentTool); + emit sigToolSelected(m_currentTool); m_baseLayout->activate(); adjustSizeConstraint(); } //--------------------------------------------------------------------- // private slot -void kpToolToolBar::slotToolActionActivated () +void kpToolToolBar::slotToolActionActivated() { const auto *tool = dynamic_cast(sender()); #if DEBUG_KP_TOOL_TOOL_BAR qCDebug(kpLogWidgets) << "kpToolToolBar::slotToolActionActivated() tool=" - << (tool ? tool->objectName () : "null") - << endl; + << (tool ? tool->objectName() : "null") + << endl; #endif - selectTool (tool, true/*reselect if same tool*/); + selectTool(tool, true /*reselect if same tool*/); } //--------------------------------------------------------------------- @@ -365,41 +360,36 @@ { #if DEBUG_KP_TOOL_TOOL_BAR qCDebug(kpLogWidgets) << "kpToolToolBar::adjustToOrientation(" - << (o == Qt::Vertical ? "vertical" : "horizontal") - << ") called!" << endl; + << (o == Qt::Vertical ? "vertical" : "horizontal") + << ") called!" << endl; #endif delete m_baseLayout; - if (o == Qt::Vertical) - { - m_baseLayout = new QBoxLayout (QBoxLayout::TopToBottom, m_baseWidget); - } - else // if (o == Qt::Horizontal) - { - m_baseLayout = new QBoxLayout (QBoxLayout::LeftToRight, m_baseWidget); + if (o == Qt::Vertical) { + m_baseLayout = new QBoxLayout(QBoxLayout::TopToBottom, m_baseWidget); + } else { // if (o == Qt::Horizontal) + m_baseLayout = new QBoxLayout(QBoxLayout::LeftToRight, m_baseWidget); } m_baseLayout->setSizeConstraint(QLayout::SetFixedSize); m_baseLayout->setContentsMargins(0, 0, 0, 0); m_toolLayout = new QGridLayout(); m_toolLayout->setContentsMargins(0, 0, 0, 0); // (ownership is transferred to m_baseLayout) - m_baseLayout->addItem (m_toolLayout); + m_baseLayout->addItem(m_toolLayout); auto num = 0; - for (auto *b : m_toolButtons) - { - addButton(b, o, num); - num++; + for (auto *b : m_toolButtons) { + addButton(b, o, num); + num++; } - for (auto *w : m_toolWidgets) - { - m_baseLayout->addWidget(w, - 0/*stretch*/, - o == Qt::Vertical ? Qt::AlignHCenter : Qt::AlignVCenter); + for (auto *w : m_toolWidgets) { + m_baseLayout->addWidget(w, + 0 /*stretch*/, + o == Qt::Vertical ? Qt::AlignHCenter : Qt::AlignVCenter); } adjustSizeConstraint(); @@ -413,17 +403,14 @@ // remove constraints setFixedSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); - if ( orientation() == Qt::Vertical ) - { - setFixedWidth(m_baseLayout->sizeHint().width() + - layout()->contentsMargins().left() + - layout()->contentsMargins().right()); - } - else - { - setFixedHeight(m_baseLayout->sizeHint().height() + - layout()->contentsMargins().top() + - layout()->contentsMargins().bottom()); + if (orientation() == Qt::Vertical) { + setFixedWidth(m_baseLayout->sizeHint().width() + +layout()->contentsMargins().left() + +layout()->contentsMargins().right()); + } else { + setFixedHeight(m_baseLayout->sizeHint().height() + +layout()->contentsMargins().top() + +layout()->contentsMargins().bottom()); } } @@ -433,13 +420,11 @@ void kpToolToolBar::addButton(QAbstractButton *button, Qt::Orientation o, int num) { if (o == Qt::Vertical) { - m_toolLayout->addWidget (button, num / m_vertCols, num % m_vertCols); - } - else - { + m_toolLayout->addWidget(button, num / m_vertCols, num % m_vertCols); + } else { // maps Left (o = vertical) to Bottom (o = horizontal) int row = (m_vertCols - 1) - (num % m_vertCols); - m_toolLayout->addWidget (button, row, num / m_vertCols); + m_toolLayout->addWidget(button, row, num / m_vertCols); } } @@ -468,4 +453,3 @@ } //--------------------------------------------------------------------- - diff --git a/widgets/toolbars/options/kpToolWidgetBase.h b/widgets/toolbars/options/kpToolWidgetBase.h --- a/widgets/toolbars/options/kpToolWidgetBase.h +++ b/widgets/toolbars/options/kpToolWidgetBase.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,80 +24,76 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_WIDGET_BASE_H #define KP_TOOL_WIDGET_BASE_H - #include #include #include #include #include #include - class QMouseEvent; - // TODO: This is a crazy and overcomplicated class that invents its own (buggy) // layout management. It should be simplified or removed. class kpToolWidgetBase : public QFrame { -Q_OBJECT + Q_OBJECT public: // (must provide a for config to work) kpToolWidgetBase (QWidget *parent, const QString &name); ~kpToolWidgetBase () override; public: - void addOption (const QPixmap &pixmap, const QString &toolTip = QString()); - void startNewOptionRow (); + void addOption(const QPixmap &pixmap, const QString &toolTip = QString()); + void startNewOptionRow(); // Call this at the end of your constructor. // If the default row & col could not be read from the config, // & are passed to setSelected(). - void finishConstruction (int fallBackRow, int fallBackCol); + void finishConstruction(int fallBackRow, int fallBackCol); private: - QList spreadOutElements (const QList &sizes, int maxSize); + QList spreadOutElements(const QList &sizes, int maxSize); public: // (only have to use these if you don't use finishConstruction()) // (rereads from config file) - QPair defaultSelectedRowAndCol () const; - int defaultSelectedRow () const; - int defaultSelectedCol () const; + QPair defaultSelectedRowAndCol() const; + int defaultSelectedRow() const; + int defaultSelectedCol() const; - void saveSelectedAsDefault () const; + void saveSelectedAsDefault() const; - void relayoutOptions (); + void relayoutOptions(); public: - int selectedRow () const; - int selectedCol () const; + int selectedRow() const; + int selectedCol() const; - int selected () const; + int selected() const; - bool hasPreviousOption (int *row = nullptr, int *col = nullptr) const; - bool hasNextOption (int *row = nullptr, int *col = nullptr) const; + bool hasPreviousOption(int *row = nullptr, int *col = nullptr) const; + bool hasNextOption(int *row = nullptr, int *col = nullptr) const; public slots: // (returns whether and were in range) - virtual bool setSelected (int row, int col, bool saveAsDefault); - bool setSelected (int row, int col); + virtual bool setSelected(int row, int col, bool saveAsDefault); + bool setSelected(int row, int col); - bool selectPreviousOption (); - bool selectNextOption (); + bool selectPreviousOption(); + bool selectNextOption(); signals: - void optionSelected (int row, int col); + void optionSelected(int row, int col); protected: - bool event (QEvent *e) override; - - void mousePressEvent (QMouseEvent *e) override; - void paintEvent (QPaintEvent *e) override; + bool event(QEvent *e) override; + + void mousePressEvent(QMouseEvent *e) override; + void paintEvent(QPaintEvent *e) override; QWidget *m_baseWidget; @@ -110,5 +105,4 @@ int m_selectedRow, m_selectedCol; }; - #endif // KP_TOOL_WIDGET_BASE_H diff --git a/widgets/toolbars/options/kpToolWidgetBase.cpp b/widgets/toolbars/options/kpToolWidgetBase.cpp --- a/widgets/toolbars/options/kpToolWidgetBase.cpp +++ b/widgets/toolbars/options/kpToolWidgetBase.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_WIDGET_BASE 0 - #include "kpToolWidgetBase.h" #include "kpDefs.h" @@ -47,19 +44,20 @@ #include #include - //--------------------------------------------------------------------- kpToolWidgetBase::kpToolWidgetBase (QWidget *parent, const QString &name) - : QFrame(parent), m_baseWidget(nullptr), - m_selectedRow(-1), m_selectedCol(-1) + : QFrame(parent) + , m_baseWidget(nullptr) + , m_selectedRow(-1) + , m_selectedCol(-1) { - setObjectName (name); + setObjectName(name); - setFrameStyle (QFrame::Panel | QFrame::Sunken); + setFrameStyle(QFrame::Panel | QFrame::Sunken); - setFixedSize (44, 66); - setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Minimum); + setFixedSize(44, 66); + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); } //--------------------------------------------------------------------- @@ -69,40 +67,40 @@ //--------------------------------------------------------------------- // public -void kpToolWidgetBase::addOption (const QPixmap &pixmap, const QString &toolTip) +void kpToolWidgetBase::addOption(const QPixmap &pixmap, const QString &toolTip) { - if (m_pixmaps.isEmpty ()) { - startNewOptionRow (); + if (m_pixmaps.isEmpty()) { + startNewOptionRow(); } - m_pixmaps.last ().append (pixmap); - m_pixmapRects.last ().append (QRect ()); - m_toolTips.last ().append (toolTip); + m_pixmaps.last().append(pixmap); + m_pixmapRects.last().append(QRect()); + m_toolTips.last().append(toolTip); } //--------------------------------------------------------------------- // public -void kpToolWidgetBase::startNewOptionRow () +void kpToolWidgetBase::startNewOptionRow() { - m_pixmaps.append (QList ()); - m_pixmapRects.append (QList ()); - m_toolTips.append (QList ()); + m_pixmaps.append(QList ()); + m_pixmapRects.append(QList ()); + m_toolTips.append(QList ()); } //--------------------------------------------------------------------- // public -void kpToolWidgetBase::finishConstruction (int fallBackRow, int fallBackCol) +void kpToolWidgetBase::finishConstruction(int fallBackRow, int fallBackCol) { #if DEBUG_KP_TOOL_WIDGET_BASE - qCDebug(kpLogWidgets) << "kpToolWidgetBase(" << objectName () - << ")::kpToolWidgetBase(fallBack:row=" << fallBackRow - << ",col=" << fallBackCol - << ")"; + qCDebug(kpLogWidgets) << "kpToolWidgetBase(" << objectName() + << ")::kpToolWidgetBase(fallBack:row=" << fallBackRow + << ",col=" << fallBackCol + << ")"; #endif - relayoutOptions (); + relayoutOptions(); // HACK: Undo the maximum half of setFixedSize() in the ctor to avoid // bizarre redraw errors when tool widgets are hidden and others @@ -113,56 +111,51 @@ // on the size() in the ctor, so we needed to get the correct size // in there. This is bad design because it means that tool widgets // can't really be resized. - setMaximumSize (QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); + setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); - const QPair rowColPair = defaultSelectedRowAndCol (); - if (!setSelected (rowColPair.first, rowColPair.second, false/*don't save*/)) - { - if (!setSelected (fallBackRow, fallBackCol)) - { - if (!setSelected (0, 0)) - { + const QPair rowColPair = defaultSelectedRowAndCol(); + if (!setSelected(rowColPair.first, rowColPair.second, false /*don't save*/)) { + if (!setSelected(fallBackRow, fallBackCol)) { + if (!setSelected(0, 0)) { qCCritical(kpLogWidgets) << "kpToolWidgetBase::finishConstruction() " - "can't even fall back to setSelected(row=0,col=0)"; + "can't even fall back to setSelected(row=0,col=0)"; } } } } //--------------------------------------------------------------------- // private -QList kpToolWidgetBase::spreadOutElements (const QList &sizes, int max) +QList kpToolWidgetBase::spreadOutElements(const QList &sizes, int max) { - if (sizes.count () == 0) { + if (sizes.count() == 0) { return {}; } - if (sizes.count () == 1) - { + if (sizes.count() == 1) { QList ret; - ret.append (sizes.first () > max ? 0 : 1/*margin*/); + ret.append(sizes.first() > max ? 0 : 1 /*margin*/); return ret; } QList retOffsets; - for (int i = 0; i < sizes.count (); i++) { - retOffsets.append (0); + for (int i = 0; i < sizes.count(); i++) { + retOffsets.append(0); } int totalSize = 0; - for (int i = 0; i < sizes.count (); i++) { + for (int i = 0; i < sizes.count(); i++) { totalSize += sizes [i]; } int margin = 1; // if don't fit with margin, then just return elements // packed right next to each other - if (totalSize + margin * 2 > max) - { + if (totalSize + margin * 2 > max) { retOffsets [0] = 0; - for (int i = 1; i < sizes.count (); i++) { + for (int i = 1; i < sizes.count(); i++) { retOffsets [i] = retOffsets [i - 1] + sizes [i - 1]; } @@ -176,109 +169,106 @@ int spacing = 0; - spacing = maxLeftOver / (sizes.count () - 1); - if (spacing * int (sizes.count () - 1) < maxLeftOver) - { - numCompensate = maxLeftOver - spacing * (sizes.count () - 1); - startCompensating = ((sizes.count () - 1) - numCompensate) / 2; + spacing = maxLeftOver / (sizes.count() - 1); + if (spacing * int(sizes.count() - 1) < maxLeftOver) { + numCompensate = maxLeftOver - spacing * (sizes.count() - 1); + startCompensating = ((sizes.count() - 1) - numCompensate) / 2; } retOffsets [0] = margin; - for (int i = 1; i < sizes.count (); i++) - { - retOffsets [i] += retOffsets [i - 1] + - sizes [i - 1] + - spacing + - ((numCompensate && - i >= startCompensating && - i < startCompensating + numCompensate) ? 1 : 0); + for (int i = 1; i < sizes.count(); i++) { + retOffsets [i] += retOffsets [i - 1] + +sizes [i - 1] + +spacing + +((numCompensate + && i >= startCompensating + && i < startCompensating + numCompensate) ? 1 : 0); } return retOffsets; } //--------------------------------------------------------------------- // public -QPair kpToolWidgetBase::defaultSelectedRowAndCol () const +QPair kpToolWidgetBase::defaultSelectedRowAndCol() const { int row = -1, col = -1; - if (!objectName ().isEmpty ()) - { - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupTools); + if (!objectName().isEmpty()) { + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupTools); - row = cfg.readEntry (objectName () + QLatin1String (" Row"), -1); - col = cfg.readEntry (objectName () + QLatin1String (" Col"), -1); + row = cfg.readEntry(objectName() + QLatin1String(" Row"), -1); + col = cfg.readEntry(objectName() + QLatin1String(" Col"), -1); } #if DEBUG_KP_TOOL_WIDGET_BASE - qCDebug(kpLogWidgets) << "kpToolWidgetBase(" << objectName () - << ")::defaultSelectedRowAndCol() returning row=" << row - << " col=" << col; + qCDebug(kpLogWidgets) << "kpToolWidgetBase(" << objectName() + << ")::defaultSelectedRowAndCol() returning row=" << row + << " col=" << col; #endif - return qMakePair (row, col); + return qMakePair(row, col); } //--------------------------------------------------------------------- // public -int kpToolWidgetBase::defaultSelectedRow () const +int kpToolWidgetBase::defaultSelectedRow() const { - return defaultSelectedRowAndCol ().first; + return defaultSelectedRowAndCol().first; } //--------------------------------------------------------------------- // public -int kpToolWidgetBase::defaultSelectedCol () const +int kpToolWidgetBase::defaultSelectedCol() const { - return defaultSelectedRowAndCol ().second; + return defaultSelectedRowAndCol().second; } //--------------------------------------------------------------------- // public -void kpToolWidgetBase::saveSelectedAsDefault () const +void kpToolWidgetBase::saveSelectedAsDefault() const { #if DEBUG_KP_TOOL_WIDGET_BASE - qCDebug(kpLogWidgets) << "kpToolWidgetBase(" << objectName () - << ")::saveSelectedAsDefault() row=" << m_selectedRow - << " col=" << m_selectedCol; + qCDebug(kpLogWidgets) << "kpToolWidgetBase(" << objectName() + << ")::saveSelectedAsDefault() row=" << m_selectedRow + << " col=" << m_selectedCol; #endif - if (objectName ().isEmpty ()) { + if (objectName().isEmpty()) { return; } - KConfigGroup cfg (KSharedConfig::openConfig (), kpSettingsGroupTools); + KConfigGroup cfg(KSharedConfig::openConfig(), kpSettingsGroupTools); - cfg.writeEntry (objectName () + QLatin1String (" Row"), m_selectedRow); - cfg.writeEntry (objectName () + QLatin1String (" Col"), m_selectedCol); - cfg.sync (); + cfg.writeEntry(objectName() + QLatin1String(" Row"), m_selectedRow); + cfg.writeEntry(objectName() + QLatin1String(" Col"), m_selectedCol); + cfg.sync(); } //--------------------------------------------------------------------- // public -void kpToolWidgetBase::relayoutOptions () +void kpToolWidgetBase::relayoutOptions() { #if DEBUG_KP_TOOL_WIDGET_BASE - qCDebug(kpLogWidgets) << "kpToolWidgetBase::relayoutOptions() size=" << size (); + qCDebug(kpLogWidgets) << "kpToolWidgetBase::relayoutOptions() size=" << size(); #endif - while (!m_pixmaps.isEmpty () && m_pixmaps.last ().count () == 0) + while (!m_pixmaps.isEmpty() && m_pixmaps.last().count() == 0) { #if DEBUG_KP_TOOL_WIDGET_BASE - qCDebug(kpLogWidgets) << "\tkilling #" << m_pixmaps.count () - 1; + qCDebug(kpLogWidgets) << "\tkilling #" << m_pixmaps.count() - 1; #endif - m_pixmaps.removeLast (); - m_pixmapRects.removeLast (); - m_toolTips.removeLast (); + m_pixmaps.removeLast(); + m_pixmapRects.removeLast(); + m_toolTips.removeLast(); } - if (m_pixmaps.isEmpty ()) { + if (m_pixmaps.isEmpty()) { return; } @@ -288,129 +278,118 @@ #endif QList maxHeightOfRow; - for (int r = 0; r < m_pixmaps.count (); r++) { - maxHeightOfRow.append (0); + for (int r = 0; r < m_pixmaps.count(); r++) { + maxHeightOfRow.append(0); } - for (int r = 0; r < m_pixmaps.count (); r++) - { - for (int c = 0; c < m_pixmaps [r].count (); c++) - { - if (c == 0 || m_pixmaps [r][c].height () > maxHeightOfRow [r]) { - maxHeightOfRow [r] = m_pixmaps [r][c].height (); + for (int r = 0; r < m_pixmaps.count(); r++) { + for (int c = 0; c < m_pixmaps [r].count(); c++) { + if (c == 0 || m_pixmaps [r][c].height() > maxHeightOfRow [r]) { + maxHeightOfRow [r] = m_pixmaps [r][c].height(); } } #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "\t\t" << r << ": " << maxHeightOfRow [r]; #endif } - QList rowYOffset = spreadOutElements (maxHeightOfRow, height ()); + QList rowYOffset = spreadOutElements(maxHeightOfRow, height()); #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "\tspread out offsets of rows:"; - for (int r = 0; r < (int) rowYOffset.count (); r++) { + for (int r = 0; r < (int)rowYOffset.count(); r++) { qCDebug(kpLogWidgets) << "\t\t" << r << ": " << rowYOffset [r]; } #endif - for (int r = 0; r < m_pixmaps.count (); r++) - { + for (int r = 0; r < m_pixmaps.count(); r++) { #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "\tlaying out row " << r << ":"; #endif QList widths; - for (int c = 0; c < m_pixmaps [r].count (); c++) - widths.append (m_pixmaps [r][c].width ()); + for (int c = 0; c < m_pixmaps [r].count(); c++) { + widths.append(m_pixmaps [r][c].width()); + } #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "\t\twidths of cols:"; - for (int c = 0; c < m_pixmaps [r].count (); c++) { + for (int c = 0; c < m_pixmaps [r].count(); c++) { qCDebug(kpLogWidgets) << "\t\t\t" << c << ": " << widths [c]; } #endif - QList colXOffset = spreadOutElements (widths, width ()); + QList colXOffset = spreadOutElements(widths, width()); #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "\t\tspread out offsets of cols:"; - for (int c = 0; c < colXOffset.count (); c++) { + for (int c = 0; c < colXOffset.count(); c++) { qCDebug(kpLogWidgets) << "\t\t\t" << c << ": " << colXOffset [c]; } #endif - for (int c = 0; c < colXOffset.count (); c++) - { + for (int c = 0; c < colXOffset.count(); c++) { int x = colXOffset [c]; int y = rowYOffset [r]; int w, h; - if (c == colXOffset.count () - 1) - { - if (x + m_pixmaps [r][c].width () >= width ()) { - w = m_pixmaps [r][c].width (); + if (c == colXOffset.count() - 1) { + if (x + m_pixmaps [r][c].width() >= width()) { + w = m_pixmaps [r][c].width(); + } else { + w = width() - 1 - x; } - else { - w = width () - 1 - x; - } - } - else { + } else { w = colXOffset [c + 1] - x; } - if (r == m_pixmaps.count () - 1) - { - if (y + m_pixmaps [r][c].height () >= height ()) { - h = m_pixmaps [r][c].height (); + if (r == m_pixmaps.count() - 1) { + if (y + m_pixmaps [r][c].height() >= height()) { + h = m_pixmaps [r][c].height(); + } else { + h = height() - 1 - y; } - else { - h = height () - 1 - y; - } - } - else { + } else { h = rowYOffset [r + 1] - y; } - m_pixmapRects [r][c] = QRect (x, y, w, h); + m_pixmapRects [r][c] = QRect(x, y, w, h); } } - update (); + update(); } //--------------------------------------------------------------------- - // public -int kpToolWidgetBase::selectedRow () const +int kpToolWidgetBase::selectedRow() const { return m_selectedRow; } //--------------------------------------------------------------------- // public -int kpToolWidgetBase::selectedCol () const +int kpToolWidgetBase::selectedCol() const { return m_selectedCol; } //--------------------------------------------------------------------- // public -int kpToolWidgetBase::selected () const +int kpToolWidgetBase::selected() const { - if (m_selectedRow < 0 || - m_selectedRow >= m_pixmaps.count () || - m_selectedCol < 0) - { + if (m_selectedRow < 0 + || m_selectedRow >= m_pixmaps.count() + || m_selectedCol < 0) { return -1; } int upto = 0; for (int y = 0; y < m_selectedRow; y++) { - upto += m_pixmaps [y].count (); + upto += m_pixmaps [y].count(); } - if (m_selectedCol >= m_pixmaps [m_selectedRow].count ()) { + if (m_selectedCol >= m_pixmaps [m_selectedRow].count()) { return -1; } @@ -421,45 +400,41 @@ //--------------------------------------------------------------------- - // public -bool kpToolWidgetBase::hasPreviousOption (int *row, int *col) const +bool kpToolWidgetBase::hasPreviousOption(int *row, int *col) const { #if DEBUG_KP_TOOL_WIDGET_BASE - qCDebug(kpLogWidgets) << "kpToolWidgetBase(" << objectName () - << ")::hasPreviousOption() current row=" << m_selectedRow - << " col=" << m_selectedCol; + qCDebug(kpLogWidgets) << "kpToolWidgetBase(" << objectName() + << ")::hasPreviousOption() current row=" << m_selectedRow + << " col=" << m_selectedCol; #endif if (row) { *row = -1; } if (col) { *col = -1; } - if (m_selectedRow < 0 || m_selectedCol < 0) { return false; } int newRow = m_selectedRow, newCol = m_selectedCol; newCol--; - if (newCol < 0) - { + if (newCol < 0) { newRow--; if (newRow < 0) { return false; } - newCol = m_pixmaps [newRow].count () - 1; + newCol = m_pixmaps [newRow].count() - 1; if (newCol < 0) { return false; } } - if (row) { *row = newRow; } @@ -473,12 +448,12 @@ //--------------------------------------------------------------------- // public -bool kpToolWidgetBase::hasNextOption (int *row, int *col) const +bool kpToolWidgetBase::hasNextOption(int *row, int *col) const { #if DEBUG_KP_TOOL_WIDGET_BASE - qCDebug(kpLogWidgets) << "kpToolWidgetBase(" << objectName () - << ")::hasNextOption() current row=" << m_selectedRow - << " col=" << m_selectedCol; + qCDebug(kpLogWidgets) << "kpToolWidgetBase(" << objectName() + << ")::hasNextOption() current row=" << m_selectedRow + << " col=" << m_selectedCol; #endif if (row) { @@ -488,29 +463,26 @@ *col = -1; } - if (m_selectedRow < 0 || m_selectedCol < 0) { return false; } int newRow = m_selectedRow, newCol = m_selectedCol; newCol++; - if (newCol >= m_pixmaps [newRow].count ()) - { + if (newCol >= m_pixmaps [newRow].count()) { newRow++; - if (newRow >= m_pixmaps.count ()) { + if (newRow >= m_pixmaps.count()) { return false; } newCol = 0; - if (newCol >= m_pixmaps [newRow].count ()) { + if (newCol >= m_pixmaps [newRow].count()) { return false; } } - if (row) { *row = newRow; } @@ -523,34 +495,31 @@ //--------------------------------------------------------------------- - // public slot virtual -bool kpToolWidgetBase::setSelected (int row, int col, bool saveAsDefault) +bool kpToolWidgetBase::setSelected(int row, int col, bool saveAsDefault) { #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "kpToolWidgetBase::setSelected(row=" << row - << ",col=" << col - << ",saveAsDefault=" << saveAsDefault - << ")"; + << ",col=" << col + << ",saveAsDefault=" << saveAsDefault + << ")"; #endif - if (row < 0 || col < 0 || - row >= m_pixmapRects.count () || col >= m_pixmapRects [row].count ()) - { + if (row < 0 || col < 0 + || row >= m_pixmapRects.count() || col >= m_pixmapRects [row].count()) { #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "\tout of range"; #endif return false; } - if (row == m_selectedRow && col == m_selectedCol) - { + if (row == m_selectedRow && col == m_selectedCol) { #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "\tNOP"; #endif if (saveAsDefault) { - saveSelectedAsDefault (); + saveSelectedAsDefault(); } return true; @@ -562,139 +531,125 @@ m_selectedRow = row; m_selectedCol = col; - if (wasSelectedRow >= 0 && wasSelectedCol >= 0) - { + if (wasSelectedRow >= 0 && wasSelectedCol >= 0) { // unhighlight old option - update (m_pixmapRects [wasSelectedRow][wasSelectedCol]); + update(m_pixmapRects [wasSelectedRow][wasSelectedCol]); } // highlight new option - update (m_pixmapRects [row][col]); + update(m_pixmapRects [row][col]); #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "\tOK"; #endif if (saveAsDefault) { - saveSelectedAsDefault (); + saveSelectedAsDefault(); } - emit optionSelected (row, col); + emit optionSelected(row, col); return true; } //--------------------------------------------------------------------- // public slot -bool kpToolWidgetBase::setSelected (int row, int col) +bool kpToolWidgetBase::setSelected(int row, int col) { - return setSelected (row, col, true/*set as default*/); + return setSelected(row, col, true /*set as default*/); } //--------------------------------------------------------------------- - // public slot -bool kpToolWidgetBase::selectPreviousOption () +bool kpToolWidgetBase::selectPreviousOption() { int newRow, newCol; - if (!hasPreviousOption (&newRow, &newCol)) { + if (!hasPreviousOption(&newRow, &newCol)) { return false; } - return setSelected (newRow, newCol); + return setSelected(newRow, newCol); } //--------------------------------------------------------------------- // public slot -bool kpToolWidgetBase::selectNextOption () +bool kpToolWidgetBase::selectNextOption() { int newRow, newCol; - if (!hasNextOption (&newRow, &newCol)) { + if (!hasNextOption(&newRow, &newCol)) { return false; } - return setSelected (newRow, newCol); + return setSelected(newRow, newCol); } //--------------------------------------------------------------------- - // protected virtual [base QWidget] -bool kpToolWidgetBase::event (QEvent *e) +bool kpToolWidgetBase::event(QEvent *e) { // TODO: It's unclear when we should call the base, call accept() and // return true or false. Look at other event() handlers. The // kpToolText one is wrong since after calling accept(), it calls // its base which calls ignore() :) - if (e->type () == QEvent::ToolTip) - { - auto *he = dynamic_cast (e); + if (e->type() == QEvent::ToolTip) { + auto *he = dynamic_cast(e); #if DEBUG_KP_TOOL_WIDGET_BASE - qCDebug(kpLogWidgets) << "kpToolWidgetBase::event() QHelpEvent pos=" << he->pos (); + qCDebug(kpLogWidgets) << "kpToolWidgetBase::event() QHelpEvent pos=" << he->pos(); #endif bool showedText = false; - for (int r = 0; r < m_pixmapRects.count (); r++) - { - for (int c = 0; c < m_pixmapRects [r].count (); c++) - { - if (m_pixmapRects [r][c].contains (he->pos ())) - { + for (int r = 0; r < m_pixmapRects.count(); r++) { + for (int c = 0; c < m_pixmapRects [r].count(); c++) { + if (m_pixmapRects [r][c].contains(he->pos())) { const QString tip = m_toolTips [r][c]; #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "\tin option: r=" << r << "c=" << c - << "tip='" << tip << "'"; - #endif - if (!tip.isEmpty ()) - { - QToolTip::showText (he->globalPos (), tip, this); + << "tip='" << tip << "'"; + #endif + if (!tip.isEmpty()) { + QToolTip::showText(he->globalPos(), tip, this); showedText = true; } - e->accept (); + e->accept(); goto exit_loops; } } } - exit_loops: - if (!showedText) - { +exit_loops: + if (!showedText) { #if DEBUG_KP_TOOL_WIDGET_BASE qCDebug(kpLogWidgets) << "\thiding text"; #endif - QToolTip::hideText (); + QToolTip::hideText(); } return true; } - return QWidget::event (e); + return QWidget::event(e); } //--------------------------------------------------------------------- - // protected virtual [base QWidget] -void kpToolWidgetBase::mousePressEvent (QMouseEvent *e) +void kpToolWidgetBase::mousePressEvent(QMouseEvent *e) { - e->ignore (); + e->ignore(); - if (e->button () != Qt::LeftButton) { + if (e->button() != Qt::LeftButton) { return; } - - for (int i = 0; i < m_pixmapRects.count (); i++) - { - for (int j = 0; j < m_pixmapRects [i].count (); j++) - { - if (m_pixmapRects [i][j].contains (e->pos ())) - { - setSelected (i, j); - e->accept (); + for (int i = 0; i < m_pixmapRects.count(); i++) { + for (int j = 0; j < m_pixmapRects [i].count(); j++) { + if (m_pixmapRects [i][j].contains(e->pos())) { + setSelected(i, j); + e->accept(); return; } } @@ -704,51 +659,47 @@ //--------------------------------------------------------------------- // protected virtual [base QWidget] -void kpToolWidgetBase::paintEvent (QPaintEvent *e) +void kpToolWidgetBase::paintEvent(QPaintEvent *e) { #if DEBUG_KP_TOOL_WIDGET_BASE && 1 - qCDebug(kpLogWidgets) << "kpToolWidgetBase::paintEvent(): rect=" << contentsRect (); + qCDebug(kpLogWidgets) << "kpToolWidgetBase::paintEvent(): rect=" << contentsRect(); #endif // Draw frame first. - QFrame::paintEvent (e); + QFrame::paintEvent(e); - QPainter painter (this); + QPainter painter(this); - for (int i = 0; i < m_pixmaps.count (); i++) - { + for (int i = 0; i < m_pixmaps.count(); i++) { #if DEBUG_KP_TOOL_WIDGET_BASE && 1 - qCDebug(kpLogWidgets) << "\tRow: " << i; + qCDebug(kpLogWidgets) << "\tRow: " << i; #endif - for (int j = 0; j < m_pixmaps [i].count (); j++) - { + for (int j = 0; j < m_pixmaps [i].count(); j++) { QRect rect = m_pixmapRects [i][j]; QPixmap pixmap = m_pixmaps [i][j]; #if DEBUG_KP_TOOL_WIDGET_BASE && 1 qCDebug(kpLogWidgets) << "\t\tCol: " << j << " rect=" << rect; #endif - if (i == m_selectedRow && j == m_selectedCol) - { + if (i == m_selectedRow && j == m_selectedCol) { painter.fillRect(rect, palette().color(QPalette::Highlight).rgb()); } #if DEBUG_KP_TOOL_WIDGET_BASE && 1 qCDebug(kpLogWidgets) << "\t\t\tdraw pixmap @ x=" - << rect.x () + (rect.width () - pixmap.width ()) / 2 - << " y=" - << rect.y () + (rect.height () - pixmap.height ()) / 2; + << rect.x() + (rect.width() - pixmap.width()) / 2 + << " y=" + << rect.y() + (rect.height() - pixmap.height()) / 2; #endif - painter.drawPixmap(QPoint(rect.x () + (rect.width () - pixmap.width ()) / 2, - rect.y () + (rect.height () - pixmap.height ()) / 2), + painter.drawPixmap(QPoint(rect.x() + (rect.width() - pixmap.width()) / 2, + rect.y() + (rect.height() - pixmap.height()) / 2), pixmap); } } } //--------------------------------------------------------------------- - diff --git a/widgets/toolbars/options/kpToolWidgetBrush.h b/widgets/toolbars/options/kpToolWidgetBrush.h --- a/widgets/toolbars/options/kpToolWidgetBrush.h +++ b/widgets/toolbars/options/kpToolWidgetBrush.h @@ -1,18 +1,17 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_WIDGET_BRUSH_H #define KP_TOOL_WIDGET_BRUSH_H @@ -35,21 +33,20 @@ #include - class kpToolWidgetBrush : public kpToolWidgetBase { -Q_OBJECT + Q_OBJECT public: kpToolWidgetBrush (QWidget *parent, const QString &name); ~kpToolWidgetBrush () override; private: - QString brushName (int shape, int whichSize) const; + QString brushName(int shape, int whichSize) const; public: - int brushSize () const; - bool brushIsDiagonalLine () const; + int brushSize() const; + bool brushIsDiagonalLine() const; struct DrawPackage { @@ -63,18 +60,16 @@ // to it. // // TODO: change function + data -> object - kpTempImage::UserFunctionType drawFunction () const; + kpTempImage::UserFunctionType drawFunction() const; - static DrawPackage drawFunctionDataForRowCol (const kpColor &color, - int row, int col); - DrawPackage drawFunctionData (const kpColor &color) const; + static DrawPackage drawFunctionDataForRowCol(const kpColor &color, int row, int col); + DrawPackage drawFunctionData(const kpColor &color) const; signals: - void brushChanged (); + void brushChanged(); protected slots: - bool setSelected (int row, int col, bool saveAsDefault) override; + bool setSelected(int row, int col, bool saveAsDefault) override; }; - #endif // KP_TOOL_WIDGET_BRUSH_H diff --git a/widgets/toolbars/options/kpToolWidgetBrush.cpp b/widgets/toolbars/options/kpToolWidgetBrush.cpp --- a/widgets/toolbars/options/kpToolWidgetBrush.cpp +++ b/widgets/toolbars/options/kpToolWidgetBrush.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_WIDGET_BRUSH 0 - #include "widgets/toolbars/options/kpToolWidgetBrush.h" #include @@ -45,144 +42,124 @@ /* sync: */ static int BrushSizes [][3] = { - {8, 4, 1/*like Pen*/}, + {8, 4, 1 /*like Pen*/}, {9, 5, 2}, {9, 5, 2}, {9, 5, 2} }; -#define BRUSH_SIZE_NUM_COLS (int (sizeof (::BrushSizes [0]) / sizeof (::BrushSizes [0][0]))) -#define BRUSH_SIZE_NUM_ROWS (int (sizeof (::BrushSizes) / sizeof (::BrushSizes [0]))) - +#define BRUSH_SIZE_NUM_COLS (int(sizeof(::BrushSizes [0]) / sizeof(::BrushSizes [0][0]))) +#define BRUSH_SIZE_NUM_ROWS (int(sizeof(::BrushSizes) / sizeof(::BrushSizes [0]))) //--------------------------------------------------------------------- -static void Draw (kpImage *destImage, const QPoint &topLeft, void *userData) +static void Draw(kpImage *destImage, const QPoint &topLeft, void *userData) { - auto *pack = static_cast (userData); + auto *pack = static_cast (userData); #if DEBUG_KP_TOOL_WIDGET_BRUSH qCDebug(kpLogWidgets) << "kptoolwidgetbrush.cpp:Draw(destImage,topLeft=" - << topLeft << " pack: row=" << pack->row << " col=" << pack->col - << " color=" << (int *) pack->color.toQRgb (); + << topLeft << " pack: row=" << pack->row << " col=" << pack->col + << " color=" << (int *)pack->color.toQRgb(); #endif const int size = ::BrushSizes [pack->row][pack->col]; #if DEBUG_KP_TOOL_WIDGET_BRUSH qCDebug(kpLogWidgets) << "\tsize=" << size; #endif QPainter painter(destImage); - if ( size == 1 ) - { - painter.setPen(pack->color.toQColor()); - painter.drawPoint(topLeft); - return; + if (size == 1) { + painter.setPen(pack->color.toQColor()); + painter.drawPoint(topLeft); + return; } // sync: - switch (pack->row/*shape*/) - { - case 0: - { + switch (pack->row /*shape*/) { + case 0: // work around ugly circle when using QPainter on QImage - if ( size == 4 ) - { - // do not draw a pixel twice, as with an alpha color it will become darker - painter.setPen(Qt::NoPen); - painter.setBrush(pack->color.toQColor()); - painter.drawRect(topLeft.x() + 1, topLeft.y(), 2, size); - painter.setPen(pack->color.toQColor()); - painter.drawLine(topLeft.x(), topLeft.y() + 1, topLeft.x(), topLeft.y() + 2); - painter.drawLine(topLeft.x() + 3, topLeft.y() + 1, topLeft.x() + 3, topLeft.y() + 2); - } - else if ( size == 8 ) // size defined in BrushSizes above - { - // do not draw a pixel twice, as with an alpha color it will become darker - painter.setPen(Qt::NoPen); - painter.setBrush(pack->color.toQColor()); - painter.drawRect(topLeft.x() + 2, topLeft.y(), 4, size); - painter.drawRect(topLeft.x(), topLeft.y() + 2, 2, 4); - painter.drawRect(topLeft.x() + 6, topLeft.y() + 2, 2, 4); - painter.setPen(pack->color.toQColor()); - painter.drawPoint(topLeft.x() + 1, topLeft.y() + 1); - painter.drawPoint(topLeft.x() + 6, topLeft.y() + 1); - painter.drawPoint(topLeft.x() + 1, topLeft.y() + 6); - painter.drawPoint(topLeft.x() + 6, topLeft.y() + 6); - } - else - { - Q_ASSERT(!"illegal size"); + if (size == 4) { + // do not draw a pixel twice, as with an alpha color it will become darker + painter.setPen(Qt::NoPen); + painter.setBrush(pack->color.toQColor()); + painter.drawRect(topLeft.x() + 1, topLeft.y(), 2, size); + painter.setPen(pack->color.toQColor()); + painter.drawLine(topLeft.x(), topLeft.y() + 1, topLeft.x(), topLeft.y() + 2); + painter.drawLine(topLeft.x() + 3, topLeft.y() + 1, topLeft.x() + 3, topLeft.y() + 2); + } else if (size == 8) { // size defined in BrushSizes above + // do not draw a pixel twice, as with an alpha color it will become darker + painter.setPen(Qt::NoPen); + painter.setBrush(pack->color.toQColor()); + painter.drawRect(topLeft.x() + 2, topLeft.y(), 4, size); + painter.drawRect(topLeft.x(), topLeft.y() + 2, 2, 4); + painter.drawRect(topLeft.x() + 6, topLeft.y() + 2, 2, 4); + painter.setPen(pack->color.toQColor()); + painter.drawPoint(topLeft.x() + 1, topLeft.y() + 1); + painter.drawPoint(topLeft.x() + 6, topLeft.y() + 1); + painter.drawPoint(topLeft.x() + 1, topLeft.y() + 6); + painter.drawPoint(topLeft.x() + 6, topLeft.y() + 6); + } else { + Q_ASSERT(!"illegal size"); } break; - } - case 1: - { + case 1: // only paint filling so that a color with an alpha channel does not // create a darker border due to drawing some pixels twice with composition painter.setPen(Qt::NoPen); painter.setBrush(pack->color.toQColor()); painter.drawRect(topLeft.x(), topLeft.y(), size, size); break; - } - case 2: - { + case 2: painter.setPen(pack->color.toQColor()); painter.drawLine(topLeft.x() + size - 1, topLeft.y(), topLeft.x(), topLeft.y() + size - 1); break; - } - case 3: - { + case 3: painter.setPen(pack->color.toQColor()); painter.drawLine(topLeft.x(), topLeft.y(), topLeft.x() + size - 1, topLeft.y() + size - 1); break; - } default: - Q_ASSERT (!"Unknown row"); + Q_ASSERT(!"Unknown row"); break; } } //--------------------------------------------------------------------- kpToolWidgetBrush::kpToolWidgetBrush (QWidget *parent, const QString &name) - : kpToolWidgetBase (parent, name) + : kpToolWidgetBase(parent, name) { - for (int shape = 0; shape < BRUSH_SIZE_NUM_ROWS; shape++) - { - for (int i = 0; i < BRUSH_SIZE_NUM_COLS; i++) - { + for (int shape = 0; shape < BRUSH_SIZE_NUM_ROWS; shape++) { + for (int i = 0; i < BRUSH_SIZE_NUM_COLS; i++) { const int s = ::BrushSizes [shape][i]; - - const int w = (width () - 2/*margin*/ - 2/*spacing*/) - / BRUSH_SIZE_NUM_COLS; - const int h = (height () - 2/*margin*/ - 3/*spacing*/) - / BRUSH_SIZE_NUM_ROWS; - Q_ASSERT (w >= s && h >= s); - QImage previewPixmap (w, h, QImage::Format_ARGB32_Premultiplied); + const int w = (width() - 2 /*margin*/ - 2 /*spacing*/) + / BRUSH_SIZE_NUM_COLS; + const int h = (height() - 2 /*margin*/ - 3 /*spacing*/) + / BRUSH_SIZE_NUM_ROWS; + Q_ASSERT(w >= s && h >= s); + QImage previewPixmap(w, h, QImage::Format_ARGB32_Premultiplied); previewPixmap.fill(0); - DrawPackage pack = drawFunctionDataForRowCol (kpColor::Black, shape, i); - ::Draw (&previewPixmap, - QPoint ((previewPixmap.width () - s) / 2, - (previewPixmap.height () - s) / 2), - &pack); + DrawPackage pack = drawFunctionDataForRowCol(kpColor::Black, shape, i); + ::Draw(&previewPixmap, + QPoint((previewPixmap.width() - s) / 2, + (previewPixmap.height() - s) / 2), + &pack); - - addOption (QPixmap::fromImage(previewPixmap), brushName (shape, i)/*tooltip*/); + addOption(QPixmap::fromImage(previewPixmap), brushName(shape, i) /*tooltip*/); } - startNewOptionRow (); + startNewOptionRow(); } - finishConstruction (0, 0); + finishConstruction(0, 0); } //--------------------------------------------------------------------- @@ -192,76 +169,73 @@ //--------------------------------------------------------------------- // private -QString kpToolWidgetBrush::brushName (int shape, int whichSize) const +QString kpToolWidgetBrush::brushName(int shape, int whichSize) const { int s = ::BrushSizes [shape][whichSize]; if (s == 1) { - return i18n ("1x1"); + return i18n("1x1"); } QString shapeName; // sync: - switch (shape) - { + switch (shape) { case 0: - shapeName = i18n ("Circle"); + shapeName = i18n("Circle"); break; case 1: - shapeName = i18n ("Square"); + shapeName = i18n("Square"); break; case 2: // TODO: is this really the name of a shape? :) - shapeName = i18n ("Slash"); + shapeName = i18n("Slash"); break; case 3: // TODO: is this really the name of a shape? :) - shapeName = i18n ("Backslash"); + shapeName = i18n("Backslash"); break; } - if (shapeName.isEmpty ()) { + if (shapeName.isEmpty()) { return {}; } - return i18n ("%1x%2 %3", s, s, shapeName); + return i18n("%1x%2 %3", s, s, shapeName); } //--------------------------------------------------------------------- // public -int kpToolWidgetBrush::brushSize () const +int kpToolWidgetBrush::brushSize() const { - return ::BrushSizes [selectedRow ()][selectedCol ()]; + return ::BrushSizes [selectedRow()][selectedCol()]; } //--------------------------------------------------------------------- // public -bool kpToolWidgetBrush::brushIsDiagonalLine () const +bool kpToolWidgetBrush::brushIsDiagonalLine() const { // sync: - return (selectedRow () >= 2); + return selectedRow() >= 2; } //--------------------------------------------------------------------- - // public -kpTempImage::UserFunctionType kpToolWidgetBrush::drawFunction () const +kpTempImage::UserFunctionType kpToolWidgetBrush::drawFunction() const { return &::Draw; } //--------------------------------------------------------------------- - // public static -kpToolWidgetBrush::DrawPackage kpToolWidgetBrush::drawFunctionDataForRowCol ( - const kpColor &color, int row, int col) +kpToolWidgetBrush::DrawPackage kpToolWidgetBrush::drawFunctionDataForRowCol( + const kpColor &color, int row, int col) { - Q_ASSERT (row >= 0 && col >= 0); + Q_ASSERT(row >= 0 && col >= 0); DrawPackage pack; @@ -275,23 +249,22 @@ //--------------------------------------------------------------------- // public -kpToolWidgetBrush::DrawPackage kpToolWidgetBrush::drawFunctionData ( - const kpColor &color) const +kpToolWidgetBrush::DrawPackage kpToolWidgetBrush::drawFunctionData( + const kpColor &color) const { - return drawFunctionDataForRowCol (color, selectedRow (), selectedCol ()); + return drawFunctionDataForRowCol(color, selectedRow(), selectedCol()); } //--------------------------------------------------------------------- // protected slot virtual [base kpToolWidgetBase] -bool kpToolWidgetBrush::setSelected (int row, int col, bool saveAsDefault) +bool kpToolWidgetBrush::setSelected(int row, int col, bool saveAsDefault) { - const bool ret = kpToolWidgetBase::setSelected (row, col, saveAsDefault); + const bool ret = kpToolWidgetBase::setSelected(row, col, saveAsDefault); if (ret) { - emit brushChanged (); + emit brushChanged(); } return ret; } //--------------------------------------------------------------------- - diff --git a/widgets/toolbars/options/kpToolWidgetEraserSize.h b/widgets/toolbars/options/kpToolWidgetEraserSize.h --- a/widgets/toolbars/options/kpToolWidgetEraserSize.h +++ b/widgets/toolbars/options/kpToolWidgetEraserSize.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_WIDGET_ERASER_SIZE_H #define KP_TOOL_WIDGET_ERASER_SIZE_H @@ -35,20 +33,18 @@ #include - class kpColor; - class kpToolWidgetEraserSize : public kpToolWidgetBase { -Q_OBJECT + Q_OBJECT public: kpToolWidgetEraserSize (QWidget *parent, const QString &name); ~kpToolWidgetEraserSize () override; - int eraserSize () const; - + int eraserSize() const; + struct DrawPackage { int selected; @@ -63,19 +59,17 @@ // border suitable as a cursor only. // // TODO: change function + data -> object - kpTempImage::UserFunctionType drawFunction () const; - kpTempImage::UserFunctionType drawCursorFunction () const; - - static DrawPackage drawFunctionDataForSelected (const kpColor &color, - int selectedIndex); - DrawPackage drawFunctionData (const kpColor &color) const; + kpTempImage::UserFunctionType drawFunction() const; + kpTempImage::UserFunctionType drawCursorFunction() const; + + static DrawPackage drawFunctionDataForSelected(const kpColor &color, int selectedIndex); + DrawPackage drawFunctionData(const kpColor &color) const; signals: - void eraserSizeChanged (int size); + void eraserSizeChanged(int size); protected slots: - bool setSelected (int row, int col, bool saveAsDefault) override; + bool setSelected(int row, int col, bool saveAsDefault) override; }; - #endif // KP_TOOL_WIDGET_ERASER_SIZE_H diff --git a/widgets/toolbars/options/kpToolWidgetEraserSize.cpp b/widgets/toolbars/options/kpToolWidgetEraserSize.cpp --- a/widgets/toolbars/options/kpToolWidgetEraserSize.cpp +++ b/widgets/toolbars/options/kpToolWidgetEraserSize.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_WIDGET_ERASER_SIZE 0 - #include "kpToolWidgetEraserSize.h" #include "imagelib/kpColor.h" @@ -43,32 +40,29 @@ #include #include - static int EraserSizes [] = {2, 3, 5, 9, 17, 29}; -static const int NumEraserSizes = - int (sizeof (::EraserSizes) / sizeof (::EraserSizes [0])); +static const int NumEraserSizes + = int(sizeof(::EraserSizes) / sizeof(::EraserSizes [0])); - -static void DrawImage (kpImage *destImage, const QPoint &topLeft, void *userData) +static void DrawImage(kpImage *destImage, const QPoint &topLeft, void *userData) { - auto *pack = static_cast (userData); + auto *pack = static_cast (userData); const int size = ::EraserSizes [pack->selected]; - kpPainter::fillRect (destImage, - topLeft.x (), topLeft.y (), size, size, - pack->color); + kpPainter::fillRect(destImage, + topLeft.x(), topLeft.y(), size, size, + pack->color); } -static void DrawCursor (kpImage *destImage, const QPoint &topLeft, void *userData) +static void DrawCursor(kpImage *destImage, const QPoint &topLeft, void *userData) { - ::DrawImage (destImage, topLeft, userData); - + ::DrawImage(destImage, topLeft, userData); - auto *pack = static_cast (userData); + auto *pack = static_cast (userData); const int size = ::EraserSizes [pack->selected]; - + // Would 1-pixel border on all sides completely cover the color of the // eraser? if (size <= 2) { @@ -83,75 +77,69 @@ //--------------------------------------------------------------------- kpToolWidgetEraserSize::kpToolWidgetEraserSize (QWidget *parent, const QString &name) - : kpToolWidgetBase (parent, name) + : kpToolWidgetBase(parent, name) { - for (int i = 0; i < ::NumEraserSizes; i++) - { + for (int i = 0; i < ::NumEraserSizes; i++) { if (i == 3 || i == 5) { - startNewOptionRow (); + startNewOptionRow(); } const int s = ::EraserSizes [i]; - QImage previewPixmap (s, s, QImage::Format_ARGB32_Premultiplied); - if (i < 3) - { + QImage previewPixmap(s, s, QImage::Format_ARGB32_Premultiplied); + if (i < 3) { // HACK: kpToolWidgetBase's layout code sucks and gives uneven spacing - previewPixmap = QImage ((width () - 4) / 3, 9, QImage::Format_ARGB32_Premultiplied); - Q_ASSERT (previewPixmap.width () >= s && - previewPixmap.height () >= s); + previewPixmap = QImage((width() - 4) / 3, 9, QImage::Format_ARGB32_Premultiplied); + Q_ASSERT(previewPixmap.width() >= s + && previewPixmap.height() >= s); } previewPixmap.fill(0); - DrawPackage pack = drawFunctionDataForSelected (kpColor::Black, i); - ::DrawImage (&previewPixmap, - QPoint ((previewPixmap.width () - s) / 2, - (previewPixmap.height () - s) / 2), - &pack); + DrawPackage pack = drawFunctionDataForSelected(kpColor::Black, i); + ::DrawImage(&previewPixmap, + QPoint((previewPixmap.width() - s) / 2, + (previewPixmap.height() - s) / 2), + &pack); - - addOption (QPixmap::fromImage(previewPixmap), i18n ("%1x%2", s, s)/*tooltip*/); + addOption(QPixmap::fromImage(previewPixmap), i18n("%1x%2", s, s) /*tooltip*/); } - finishConstruction (1, 0); + finishConstruction(1, 0); } //--------------------------------------------------------------------- kpToolWidgetEraserSize::~kpToolWidgetEraserSize () = default; //--------------------------------------------------------------------- - // public -int kpToolWidgetEraserSize::eraserSize () const +int kpToolWidgetEraserSize::eraserSize() const { return ::EraserSizes[selected() < 0 ? 0 : selected()]; } - // public -kpTempImage::UserFunctionType kpToolWidgetEraserSize::drawFunction () const +kpTempImage::UserFunctionType kpToolWidgetEraserSize::drawFunction() const { return &::DrawImage; } // public -kpTempImage::UserFunctionType kpToolWidgetEraserSize::drawCursorFunction () const +kpTempImage::UserFunctionType kpToolWidgetEraserSize::drawCursorFunction() const { return &::DrawCursor; } //--------------------------------------------------------------------- - // public static -kpToolWidgetEraserSize::DrawPackage kpToolWidgetEraserSize::drawFunctionDataForSelected ( - const kpColor &color, int selectedIndex) +kpToolWidgetEraserSize::DrawPackage kpToolWidgetEraserSize::drawFunctionDataForSelected( + const kpColor &color, int selectedIndex) { DrawPackage pack; - + pack.selected = selectedIndex; pack.color = color; @@ -161,25 +149,22 @@ //--------------------------------------------------------------------- // public -kpToolWidgetEraserSize::DrawPackage kpToolWidgetEraserSize::drawFunctionData ( - const kpColor &color) const +kpToolWidgetEraserSize::DrawPackage kpToolWidgetEraserSize::drawFunctionData( + const kpColor &color) const { - return drawFunctionDataForSelected (color, selected ()); + return drawFunctionDataForSelected(color, selected()); } //--------------------------------------------------------------------- - // protected slot virtual [base kpToolWidgetBase] -bool kpToolWidgetEraserSize::setSelected (int row, int col, bool saveAsDefault) +bool kpToolWidgetEraserSize::setSelected(int row, int col, bool saveAsDefault) { - const bool ret = kpToolWidgetBase::setSelected (row, col, saveAsDefault); + const bool ret = kpToolWidgetBase::setSelected(row, col, saveAsDefault); if (ret) { - emit eraserSizeChanged (eraserSize ()); + emit eraserSizeChanged(eraserSize()); } return ret; } //--------------------------------------------------------------------- - - diff --git a/widgets/toolbars/options/kpToolWidgetFillStyle.h b/widgets/toolbars/options/kpToolWidgetFillStyle.h --- a/widgets/toolbars/options/kpToolWidgetFillStyle.h +++ b/widgets/toolbars/options/kpToolWidgetFillStyle.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,22 +24,18 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_WIDGET_FILL_STYLE_H #define KP_TOOL_WIDGET_FILL_STYLE_H - #include "kpToolWidgetBase.h" - class QPixmap; class kpColor; - class kpToolWidgetFillStyle : public kpToolWidgetBase { -Q_OBJECT + Q_OBJECT public: kpToolWidgetFillStyle (QWidget *parent, const QString &name); @@ -55,24 +50,23 @@ }; private: - QPixmap fillStylePixmap (FillStyle fs, int width, int height); - QString fillStyleName (FillStyle fs) const; + QPixmap fillStylePixmap(FillStyle fs, int width, int height); + QString fillStyleName(FillStyle fs) const; public: - FillStyle fillStyle () const; + FillStyle fillStyle() const; // Returns the actual fill colour. // e.g. "FillWithBackground" fillStyle() -> , // "FillWithForeground" fillStyle() -> . - kpColor drawingBackgroundColor ( + kpColor drawingBackgroundColor( const kpColor &foregroundColor, const kpColor &backgroundColor) const; signals: - void fillStyleChanged (kpToolWidgetFillStyle::FillStyle fillStyle); + void fillStyleChanged(kpToolWidgetFillStyle::FillStyle fillStyle); protected slots: - bool setSelected (int row, int col, bool saveAsDefault) override; + bool setSelected(int row, int col, bool saveAsDefault) override; }; - #endif // KP_TOOL_WIDGET_FILL_STYLE_H diff --git a/widgets/toolbars/options/kpToolWidgetFillStyle.cpp b/widgets/toolbars/options/kpToolWidgetFillStyle.cpp --- a/widgets/toolbars/options/kpToolWidgetFillStyle.cpp +++ b/widgets/toolbars/options/kpToolWidgetFillStyle.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_WIDGET_FILL_STYLE 0 - #include "kpToolWidgetFillStyle.h" #include "imagelib/kpColor.h" @@ -45,21 +42,20 @@ //--------------------------------------------------------------------- kpToolWidgetFillStyle::kpToolWidgetFillStyle (QWidget *parent, const QString &name) - : kpToolWidgetBase (parent, name) + : kpToolWidgetBase(parent, name) { - for (int i = 0; i < FillStyleNum; i++) - { + for (int i = 0; i < FillStyleNum; i++) { QPixmap pixmap; - pixmap = fillStylePixmap (static_cast (i), - (width () - 2/*margin*/) * 3 / 4, - (height () - 2/*margin*/ - 2/*spacing*/) * 3 / (3 * 4)); - addOption (pixmap, fillStyleName (static_cast (i))/*tooltip*/); + pixmap = fillStylePixmap(static_cast(i), + (width() - 2 /*margin*/) * 3 / 4, + (height() - 2 /*margin*/ - 2 /*spacing*/) * 3 / (3 * 4)); + addOption(pixmap, fillStyleName(static_cast(i)) /*tooltip*/); - startNewOptionRow (); + startNewOptionRow(); } - finishConstruction (0, 0); + finishConstruction(0, 0); } //--------------------------------------------------------------------- @@ -69,9 +65,9 @@ //--------------------------------------------------------------------- // private -QPixmap kpToolWidgetFillStyle::fillStylePixmap (FillStyle fs, int w, int h) +QPixmap kpToolWidgetFillStyle::fillStylePixmap(FillStyle fs, int w, int h) { - QPixmap pixmap ((w <= 0 ? width () : w), (h <= 0 ? height () : h)); + QPixmap pixmap((w <= 0 ? width() : w), (h <= 0 ? height() : h)); pixmap.fill(palette().color(QPalette::Window)); const int penWidth = 2; @@ -81,24 +77,18 @@ QPainter painter(&pixmap); painter.setPen(kpPixmapFX::QPainterDrawRectPen(Qt::black, penWidth)); - switch ( fs ) - { - case NoFill: - { + switch (fs) { + case NoFill: painter.setBrush(Qt::NoBrush); break; - } - case FillWithBackground: - { + case FillWithBackground: painter.setBrush(Qt::gray); break; - } - case FillWithForeground: - { + case FillWithForeground: painter.setBrush(Qt::black); break; - } - default: ; + default: + ; } painter.drawRect(rectRect); @@ -110,18 +100,17 @@ //--------------------------------------------------------------------- // private -QString kpToolWidgetFillStyle::fillStyleName (FillStyle fs) const +QString kpToolWidgetFillStyle::fillStyleName(FillStyle fs) const { - switch (fs) - { + switch (fs) { case NoFill: - return i18n ("No Fill"); + return i18n("No Fill"); case FillWithBackground: - return i18n ("Fill with Background Color"); + return i18n("Fill with Background Color"); case FillWithForeground: - return i18n ("Fill with Foreground Color"); + return i18n("Fill with Foreground Color"); default: return {}; @@ -131,45 +120,43 @@ //--------------------------------------------------------------------- // public -kpToolWidgetFillStyle::FillStyle kpToolWidgetFillStyle::fillStyle () const +kpToolWidgetFillStyle::FillStyle kpToolWidgetFillStyle::fillStyle() const { #if DEBUG_KP_TOOL_WIDGET_FILL_STYLE qCDebug(kpLogWidgets) << "kpToolWidgetFillStyle::fillStyle() selected=" - << selectedRow (); + << selectedRow(); #endif - return static_cast (selectedRow ()); + return static_cast(selectedRow()); } //--------------------------------------------------------------------- -kpColor kpToolWidgetFillStyle::drawingBackgroundColor ( - const kpColor &foregroundColor, const kpColor &backgroundColor) const +kpColor kpToolWidgetFillStyle::drawingBackgroundColor( + const kpColor &foregroundColor, const kpColor &backgroundColor) const { - switch (fillStyle ()) - { - default: - case NoFill: + switch (fillStyle()) { + default: + case NoFill: return kpColor::Invalid; - case FillWithBackground: + case FillWithBackground: return backgroundColor; - case FillWithForeground: + case FillWithForeground: return foregroundColor; } } //--------------------------------------------------------------------- // virtual protected slot [base kpToolWidgetBase] -bool kpToolWidgetFillStyle::setSelected (int row, int col, bool saveAsDefault) +bool kpToolWidgetFillStyle::setSelected(int row, int col, bool saveAsDefault) { - const bool ret = kpToolWidgetBase::setSelected (row, col, saveAsDefault); + const bool ret = kpToolWidgetBase::setSelected(row, col, saveAsDefault); if (ret) { - emit fillStyleChanged (fillStyle ()); + emit fillStyleChanged(fillStyle()); } return ret; } //--------------------------------------------------------------------- - diff --git a/widgets/toolbars/options/kpToolWidgetLineWidth.h b/widgets/toolbars/options/kpToolWidgetLineWidth.h --- a/widgets/toolbars/options/kpToolWidgetLineWidth.h +++ b/widgets/toolbars/options/kpToolWidgetLineWidth.h @@ -1,18 +1,17 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. @@ -25,30 +24,26 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_WIDGET_LINE_WIDTH_H #define KP_TOOL_WIDGET_LINE_WIDTH_H - #include "kpToolWidgetBase.h" - class kpToolWidgetLineWidth : public kpToolWidgetBase { -Q_OBJECT + Q_OBJECT public: kpToolWidgetLineWidth (QWidget *parent, const QString &name); ~kpToolWidgetLineWidth () override; - int lineWidth () const; + int lineWidth() const; signals: - void lineWidthChanged (int width); + void lineWidthChanged(int width); protected slots: - bool setSelected (int row, int col, bool saveAsDefault) override; + bool setSelected(int row, int col, bool saveAsDefault) override; }; - #endif // KP_TOOL_WIDGET_LINE_WIDTH_H diff --git a/widgets/toolbars/options/kpToolWidgetLineWidth.cpp b/widgets/toolbars/options/kpToolWidgetLineWidth.cpp --- a/widgets/toolbars/options/kpToolWidgetLineWidth.cpp +++ b/widgets/toolbars/options/kpToolWidgetLineWidth.cpp @@ -1,18 +1,17 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. @@ -25,7 +24,6 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "widgets/toolbars/options/kpToolWidgetLineWidth.h" #include "imagelib/kpColor.h" @@ -37,52 +35,46 @@ #include #include - static int lineWidths [] = {1, 2, 3, 5, 8}; kpToolWidgetLineWidth::kpToolWidgetLineWidth (QWidget *parent, const QString &name) - : kpToolWidgetBase (parent, name) + : kpToolWidgetBase(parent, name) { - int numLineWidths = sizeof (lineWidths) / sizeof (lineWidths [0]); + int numLineWidths = sizeof(lineWidths) / sizeof(lineWidths [0]); - int w = (width () - 2/*margin*/) * 3 / 4; - int h = (height () - 2/*margin*/ - (numLineWidths - 1)/*spacing*/) * 3 / (numLineWidths * 4); + int w = (width() - 2 /*margin*/) * 3 / 4; + int h = (height() - 2 /*margin*/ - (numLineWidths - 1) /*spacing*/) * 3 / (numLineWidths * 4); - for (int i = 0; i < numLineWidths; i++) - { - QImage image ((w <= 0 ? width () : w), - (h <= 0 ? height () : h), QImage::Format_ARGB32_Premultiplied); + for (int i = 0; i < numLineWidths; i++) { + QImage image((w <= 0 ? width() : w), + (h <= 0 ? height() : h), QImage::Format_ARGB32_Premultiplied); image.fill(QColor(Qt::transparent).rgba()); + kpPixmapFX::fillRect(&image, + 0, (image.height() - lineWidths [i]) / 2, + image.width(), lineWidths [i], + kpColor::Black); - kpPixmapFX::fillRect (&image, - 0, (image.height () - lineWidths [i]) / 2, - image.width (), lineWidths [i], - kpColor::Black); - - - addOption (QPixmap::fromImage(image), QString::number (lineWidths [i])); - startNewOptionRow (); + addOption(QPixmap::fromImage(image), QString::number(lineWidths [i])); + startNewOptionRow(); } - finishConstruction (0, 0); + finishConstruction(0, 0); } kpToolWidgetLineWidth::~kpToolWidgetLineWidth () = default; -int kpToolWidgetLineWidth::lineWidth () const +int kpToolWidgetLineWidth::lineWidth() const { - return lineWidths [selectedRow ()]; + return lineWidths [selectedRow()]; } // virtual protected slot [base kpToolWidgetBase] -bool kpToolWidgetLineWidth::setSelected (int row, int col, bool saveAsDefault) +bool kpToolWidgetLineWidth::setSelected(int row, int col, bool saveAsDefault) { - const bool ret = kpToolWidgetBase::setSelected (row, col, saveAsDefault); + const bool ret = kpToolWidgetBase::setSelected(row, col, saveAsDefault); if (ret) { - emit lineWidthChanged (lineWidth ()); + emit lineWidthChanged(lineWidth()); } return ret; } - - diff --git a/widgets/toolbars/options/kpToolWidgetOpaqueOrTransparent.h b/widgets/toolbars/options/kpToolWidgetOpaqueOrTransparent.h --- a/widgets/toolbars/options/kpToolWidgetOpaqueOrTransparent.h +++ b/widgets/toolbars/options/kpToolWidgetOpaqueOrTransparent.h @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -25,33 +24,29 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_WIDGET_OPAQUE_OR_TRANSPARENT_H #define KP_TOOL_WIDGET_OPAQUE_OR_TRANSPARENT_H - #include "kpToolWidgetBase.h" - class kpToolWidgetOpaqueOrTransparent : public kpToolWidgetBase { -Q_OBJECT + Q_OBJECT public: kpToolWidgetOpaqueOrTransparent (QWidget *parent, const QString &name); ~kpToolWidgetOpaqueOrTransparent () override; - bool isOpaque () const; - bool isTransparent () const; - void setOpaque (bool yes = true); - void setTransparent (bool yes = true); + bool isOpaque() const; + bool isTransparent() const; + void setOpaque(bool yes = true); + void setTransparent(bool yes = true); signals: - void isOpaqueChanged (bool isOpaque); + void isOpaqueChanged(bool isOpaque); protected slots: - bool setSelected (int row, int col, bool saveAsDefault) override; + bool setSelected(int row, int col, bool saveAsDefault) override; }; - #endif // KP_TOOL_WIDGET_OPAQUE_OR_TRANSPARENT_H diff --git a/widgets/toolbars/options/kpToolWidgetOpaqueOrTransparent.cpp b/widgets/toolbars/options/kpToolWidgetOpaqueOrTransparent.cpp --- a/widgets/toolbars/options/kpToolWidgetOpaqueOrTransparent.cpp +++ b/widgets/toolbars/options/kpToolWidgetOpaqueOrTransparent.cpp @@ -1,4 +1,3 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. @@ -27,76 +26,71 @@ #define DEBUG_KP_TOOL_WIDGET_OPAQUE_OR_TRANSPARENT 0 - #include "widgets/toolbars/options/kpToolWidgetOpaqueOrTransparent.h" #include "kpLogCategories.h" #include #include - //--------------------------------------------------------------------- -kpToolWidgetOpaqueOrTransparent::kpToolWidgetOpaqueOrTransparent (QWidget *parent, const QString &name) - : kpToolWidgetBase (parent, name) +kpToolWidgetOpaqueOrTransparent::kpToolWidgetOpaqueOrTransparent (QWidget *parent, + const QString &name) + : kpToolWidgetBase(parent, name) { - addOption (UserIcon (QStringLiteral("option_opaque")), i18n ("Opaque")/*tooltip*/); - startNewOptionRow (); - addOption (UserIcon (QStringLiteral("option_transparent")), i18n ("Transparent")/*tooltip*/); + addOption(UserIcon(QStringLiteral("option_opaque")), i18n("Opaque") /*tooltip*/); + startNewOptionRow(); + addOption(UserIcon(QStringLiteral("option_transparent")), i18n("Transparent") /*tooltip*/); - finishConstruction (0, 0); + finishConstruction(0, 0); } //--------------------------------------------------------------------- kpToolWidgetOpaqueOrTransparent::~kpToolWidgetOpaqueOrTransparent () = default; //--------------------------------------------------------------------- - // public -bool kpToolWidgetOpaqueOrTransparent::isOpaque () const +bool kpToolWidgetOpaqueOrTransparent::isOpaque() const { - return (selected () == 0); + return selected() == 0; } // public -bool kpToolWidgetOpaqueOrTransparent::isTransparent () const +bool kpToolWidgetOpaqueOrTransparent::isTransparent() const { - return (!isOpaque ()); + return !isOpaque(); } // public -void kpToolWidgetOpaqueOrTransparent::setOpaque (bool yes) +void kpToolWidgetOpaqueOrTransparent::setOpaque(bool yes) { #if DEBUG_KP_TOOL_WIDGET_OPAQUE_OR_TRANSPARENT && 1 qCDebug(kpLogWidgets) << "kpToolWidgetOpaqueOrTransparent::setOpaque(" << yes << ")"; #endif - setSelected (yes ? 0 : 1, 0, false/*don't save*/); + setSelected(yes ? 0 : 1, 0, false /*don't save*/); } // public -void kpToolWidgetOpaqueOrTransparent::setTransparent (bool yes) +void kpToolWidgetOpaqueOrTransparent::setTransparent(bool yes) { #if DEBUG_KP_TOOL_WIDGET_OPAQUE_OR_TRANSPARENT && 1 qCDebug(kpLogWidgets) << "kpToolWidgetOpaqueOrTransparent::setTransparent(" << yes << ")"; #endif - setSelected (yes ? 1 : 0, 0, false/*don't save*/); + setSelected(yes ? 1 : 0, 0, false /*don't save*/); } - // protected slot virtual [base kpToolWidgetBase] -bool kpToolWidgetOpaqueOrTransparent::setSelected (int row, int col, bool saveAsDefault) +bool kpToolWidgetOpaqueOrTransparent::setSelected(int row, int col, bool saveAsDefault) { #if DEBUG_KP_TOOL_WIDGET_OPAQUE_OR_TRANSPARENT && 1 qCDebug(kpLogWidgets) << "kpToolWidgetOpaqueOrTransparent::setSelected(" - << row << "," << col << ")"; + << row << "," << col << ")"; #endif - const bool ret = kpToolWidgetBase::setSelected (row, col, saveAsDefault); + const bool ret = kpToolWidgetBase::setSelected(row, col, saveAsDefault); if (ret) { - emit isOpaqueChanged (isOpaque ()); + emit isOpaqueChanged(isOpaque()); } return ret; } - - diff --git a/widgets/toolbars/options/kpToolWidgetSpraycanSize.h b/widgets/toolbars/options/kpToolWidgetSpraycanSize.h --- a/widgets/toolbars/options/kpToolWidgetSpraycanSize.h +++ b/widgets/toolbars/options/kpToolWidgetSpraycanSize.h @@ -1,18 +1,17 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. @@ -25,30 +24,26 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef KP_TOOL_WIDGET_SPRAYCAN_SIZE_H #define KP_TOOL_WIDGET_SPRAYCAN_SIZE_H - #include "kpToolWidgetBase.h" - class kpToolWidgetSpraycanSize : public kpToolWidgetBase { -Q_OBJECT + Q_OBJECT public: kpToolWidgetSpraycanSize (QWidget *parent, const QString &name); ~kpToolWidgetSpraycanSize () override; - int spraycanSize () const; + int spraycanSize() const; signals: - void spraycanSizeChanged (int size); + void spraycanSizeChanged(int size); protected slots: - bool setSelected (int row, int col, bool saveAsDefault) override; + bool setSelected(int row, int col, bool saveAsDefault) override; }; - #endif // KP_TOOL_WIDGET_SPRAYCAN_SIZE_H diff --git a/widgets/toolbars/options/kpToolWidgetSpraycanSize.cpp b/widgets/toolbars/options/kpToolWidgetSpraycanSize.cpp --- a/widgets/toolbars/options/kpToolWidgetSpraycanSize.cpp +++ b/widgets/toolbars/options/kpToolWidgetSpraycanSize.cpp @@ -1,18 +1,17 @@ - /* Copyright (c) 2003-2007 Clarence Dang All rights reserved. - + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. @@ -25,10 +24,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #define DEBUG_KP_TOOL_WIDGET_SPRAYCAN_SIZE 0 - #include "kpToolWidgetSpraycanSize.h" #include "pixmapfx/kpPixmapFX.h" @@ -42,79 +39,73 @@ #include #include - static int spraycanSizes [] = {9, 17, 29}; kpToolWidgetSpraycanSize::kpToolWidgetSpraycanSize (QWidget *parent, const QString &name) - : kpToolWidgetBase (parent, name) + : kpToolWidgetBase(parent, name) { #if DEBUG_KP_TOOL_WIDGET_SPRAYCAN_SIZE qCDebug(kpLogWidgets) << "kpToolWidgetSpraycanSize::kpToolWidgetSpraycanSize() CALLED!"; #endif - for (int i = 0; i < int (sizeof (spraycanSizes) / sizeof (spraycanSizes [0])); i++) - { + for (int i = 0; i < int(sizeof(spraycanSizes) / sizeof(spraycanSizes [0])); i++) { int s = spraycanSizes [i]; - QString iconName = QStringLiteral ("tool_spraycan_%1x%2").arg (s).arg(s); - + QString iconName = QStringLiteral("tool_spraycan_%1x%2").arg(s).arg(s); + #if DEBUG_KP_TOOL_WIDGET_SPRAYCAN_SIZE qCDebug(kpLogWidgets) << "\ticonName=" << iconName; #endif - QPixmap pixmap (s, s); - pixmap.fill (Qt::white); - - QPainter painter (&pixmap); - painter.drawPixmap (0, 0, UserIcon (iconName)); - painter.end (); + QPixmap pixmap(s, s); + pixmap.fill(Qt::white); + + QPainter painter(&pixmap); + painter.drawPixmap(0, 0, UserIcon(iconName)); + painter.end(); QImage image = pixmap.toImage(); - QBitmap mask (pixmap.width (), pixmap.height ()); - mask.fill (Qt::color0); - - painter.begin (&mask); - painter.setPen (Qt::color1); - - for (int y = 0; y < image.height (); y++) - { - for (int x = 0; x < image.width (); x++) - { - if ((image.pixel (x, y) & RGB_MASK) == 0/*black*/) { - painter.drawPoint (x, y); // mark as opaque + QBitmap mask(pixmap.width(), pixmap.height()); + mask.fill(Qt::color0); + + painter.begin(&mask); + painter.setPen(Qt::color1); + + for (int y = 0; y < image.height(); y++) { + for (int x = 0; x < image.width(); x++) { + if ((image.pixel(x, y) & RGB_MASK) == 0 /*black*/) { + painter.drawPoint(x, y); // mark as opaque } } } - painter.end (); + painter.end(); - pixmap.setMask (mask); - - addOption (pixmap, i18n ("%1x%2", s, s)/*tooltip*/); + pixmap.setMask(mask); + + addOption(pixmap, i18n("%1x%2", s, s) /*tooltip*/); if (i == 1) { - startNewOptionRow (); + startNewOptionRow(); } } - finishConstruction (0, 0); + finishConstruction(0, 0); } kpToolWidgetSpraycanSize::~kpToolWidgetSpraycanSize () = default; - // public -int kpToolWidgetSpraycanSize::spraycanSize () const +int kpToolWidgetSpraycanSize::spraycanSize() const { return spraycanSizes[selected() < 0 ? 0 : selected()]; } // protected slot virtual [base kpToolWidgetBase] -bool kpToolWidgetSpraycanSize::setSelected (int row, int col, bool saveAsDefault) +bool kpToolWidgetSpraycanSize::setSelected(int row, int col, bool saveAsDefault) { - const bool ret = kpToolWidgetBase::setSelected (row, col, saveAsDefault); + const bool ret = kpToolWidgetBase::setSelected(row, col, saveAsDefault); if (ret) { - emit spraycanSizeChanged (spraycanSize ()); + emit spraycanSizeChanged(spraycanSize()); } return ret; } -