diff --git a/libs/image/commands/kis_image_layer_move_command.h b/libs/image/commands/kis_image_layer_move_command.h index 4b98dd98e7..d89e572bd3 100644 --- a/libs/image/commands/kis_image_layer_move_command.h +++ b/libs/image/commands/kis_image_layer_move_command.h @@ -1,62 +1,63 @@ /* * Copyright (c) 2002 Patrick Julien * Copyright (c) 2007 Sven Langkamp * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_IMAGE_LAYER_MOVE_COMMAND_H_ #define KIS_IMAGE_LAYER_MOVE_COMMAND_H_ #include #include #include #include "kis_types.h" #include "kis_image_command.h" /// The command for layer moves inside the layer stack class KRITAIMAGE_EXPORT KisImageLayerMoveCommand : public KisImageCommand { public: /** * Command for layer moves inside the layer stack * * @param image the image - * @param layer the moved layer + * @param node the moved node * @param newParent the next parent of the layer * @param newAbove the layer that will be below the layer after the move + * @param doUpdates whether to do updates */ KisImageLayerMoveCommand(KisImageWSP image, KisNodeSP node, KisNodeSP newParent, KisNodeSP newAbove, bool doUpdates = true); KisImageLayerMoveCommand(KisImageWSP image, KisNodeSP node, KisNodeSP newParent, quint32 index); void redo() override; void undo() override; private: KisNodeSP m_layer; KisNodeSP m_prevParent; KisNodeSP m_prevAbove; KisNodeSP m_newParent; KisNodeSP m_newAbove; quint32 m_index; bool m_useIndex; bool m_doUpdates; }; #endif diff --git a/libs/image/kis_base_mask_generator.h b/libs/image/kis_base_mask_generator.h index 8df0dfe275..4a21fc26d2 100644 --- a/libs/image/kis_base_mask_generator.h +++ b/libs/image/kis_base_mask_generator.h @@ -1,130 +1,133 @@ /* * Copyright (c) 2008-2009 Cyrille Berger * Copyright (c) 2010 Lukáš Tvrdý * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _KIS_MASK_GENERATOR_H_ #define _KIS_MASK_GENERATOR_H_ #include #include //MSVC requires that Vc come first #include #include #include "kritaimage_export.h" class QDomElement; class QDomDocument; class KisBrushMaskApplicatorBase; const KoID DefaultId("default", ki18n("Default")); ///< generate Krita default mask generator const KoID SoftId("soft", ki18n("Soft")); ///< generate brush mask from former softbrush paintop, where softness is based on curve const KoID GaussId("gauss", ki18n("Gaussian")); ///< generate brush mask with a Gaussian-blurred edge static const int OVERSAMPLING = 4; /** * This is the base class for mask shapes * You should subclass it if you want to create a new * shape. */ class KRITAIMAGE_EXPORT KisMaskGenerator { public: enum Type { CIRCLE, RECTANGLE }; public: /** - * This function creates an auto brush shape with the following value : - * @param w width - * @param h height - * @param fh horizontal fade (fh \< w / 2 ) - * @param fv vertical fade (fv \< h / 2 ) + * This function creates an auto brush shape with the following values: + * @param radius radius + * @param ratio aspect ratio + * @param fh horizontal fade + * @param fv vertical fade + * @param spikes number of spikes + * @param antialiasEdges whether to antialias edges + * @param id the brush identifier */ KisMaskGenerator(qreal radius, qreal ratio, qreal fh, qreal fv, int spikes, bool antialiasEdges, Type type, const KoID& id = DefaultId); KisMaskGenerator(const KisMaskGenerator &rhs); virtual ~KisMaskGenerator(); virtual KisMaskGenerator* clone() const = 0; private: void init(); public: /** * @return the alpha value at the position (x,y) */ virtual quint8 valueAt(qreal x, qreal y) const = 0; virtual bool shouldSupersample() const; virtual bool shouldVectorize() const; virtual KisBrushMaskApplicatorBase* applicator(); virtual void toXML(QDomDocument& , QDomElement&) const; /** * Unserialise a \ref KisMaskGenerator */ static KisMaskGenerator* fromXML(const QDomElement&); qreal width() const; qreal height() const; qreal diameter() const; void setDiameter(qreal value); qreal ratio() const; qreal horizontalFade() const; qreal verticalFade() const; int spikes() const; Type type() const; bool isEmpty() const; void fixRotation(qreal &xr, qreal &yr) const; inline QString id() const { return m_id.id(); } inline QString name() const { return m_id.name(); } static QList maskGeneratorIds(); qreal softness() const; virtual void setSoftness(qreal softness); QString curveString() const; void setCurveString(const QString& curveString); bool antialiasEdges() const; virtual void setScale(qreal scaleX, qreal scaleY); protected: qreal effectiveSrcWidth() const; qreal effectiveSrcHeight() const; private: struct Private; const QScopedPointer d; const KoID& m_id; }; #endif diff --git a/libs/image/kis_datamanager.h b/libs/image/kis_datamanager.h index 3b45d115e8..dcf74d37ba 100644 --- a/libs/image/kis_datamanager.h +++ b/libs/image/kis_datamanager.h @@ -1,349 +1,357 @@ /* * Copyright (c) 2004 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_DATAMANAGER_H_ #define KIS_DATAMANAGER_H_ #include class QRect; class KisPaintDeviceWriter; class QIODevice; #include #include #define ACTUAL_DATAMGR KisTiledDataManager /** * KisDataManager defines the interface that modules responsible for * storing and retrieving data must inmplement. Data modules, like * the tile manager, are responsible for: * * * Storing undo/redo data * * Offering ordered and unordered iterators over rects of pixels * * (eventually) efficiently loading and saving data in a format * that may allow deferred loading. * * A datamanager knows nothing about the type of pixel data except * how many quint8's a single pixel takes. */ class KisDataManager : public ACTUAL_DATAMGR { public: /** * Create a new datamanger where every pixel will take pixelSize bytes and will be initialized * by default with defPixel. The value of defPixel is copied, the caller still owns the pointer. * * Note that if pixelSize > size of the defPixel array, we will happily read beyond the * defPixel array. */ KisDataManager(quint32 pixelSize, const quint8 *defPixel) : ACTUAL_DATAMGR(pixelSize, defPixel) {} KisDataManager(const KisDataManager& dm) : ACTUAL_DATAMGR(dm) { } ~KisDataManager() override { } public: /** * Sets the default pixel. New data will be initialised with this pixel. The pixel is copied: the * caller still owns the pointer. */ inline void setDefaultPixel(const quint8 *defPixel) { return ACTUAL_DATAMGR::setDefaultPixel(defPixel); } /** * Get a pointer to the default pixel. */ inline const quint8 *defaultPixel() const { return ACTUAL_DATAMGR::defaultPixel(); } /** * Reguests a memento from the data manager. There is only one memento active * at any given moment for a given paint device and all and any * write actions on the datamanger builds undo data into this memento * necessary to rollback the transaction. */ inline KisMementoSP getMemento() { return ACTUAL_DATAMGR::getMemento(); } /** * Restores the image data to the state at the time of the getMemento() call. * * Note that rollback should be performed with mementos in the reverse order of * their creation, as mementos only store incremental changes */ inline void rollback(KisMementoSP memento) { ACTUAL_DATAMGR::rollback(memento); } /** * Restores the image data to the state at the time of the rollback call of the memento. * * Note that rollforward must only be called when an rollback have previously been performed, and * no intermittent actions have been performed (though it's ok to rollback other mementos and * roll them forward again) */ inline void rollforward(KisMementoSP memento) { ACTUAL_DATAMGR::rollforward(memento); } /** * @returns true if there is a memento active. This means that * iterators can rely on the oldData() function. */ inline bool hasCurrentMemento() const { return ACTUAL_DATAMGR::hasCurrentMemento(); } public: /** * Reads and writes the tiles * */ inline bool write(KisPaintDeviceWriter &writer) { return ACTUAL_DATAMGR::write(writer); } inline bool read(QIODevice *io) { return ACTUAL_DATAMGR::read(io); } inline void purge(const QRect& area) { ACTUAL_DATAMGR::purge(area); } /** * The tiles may be not allocated directly from the glibc, but * instead can be allocated in bigger blobs. After you freed quite * a lot of data and are sure you won't need it anymore, you can * release these pools to save the memory. */ static inline void releaseInternalPools() { ACTUAL_DATAMGR::releaseInternalPools(); } public: /** * Returns the number of bytes a pixel takes */ inline quint32 pixelSize() const { return ACTUAL_DATAMGR::pixelSize(); } /** * Return the extent of the data in x,y,w,h. */ inline void extent(qint32 &x, qint32 &y, qint32 &w, qint32 &h) const { return ACTUAL_DATAMGR::extent(x, y, w, h); } QRect extent() const { return ACTUAL_DATAMGR::extent(); } QRegion region() const { return ACTUAL_DATAMGR::region(); } public: /** * Crop or extend the data to x, y, w, h. */ inline void setExtent(qint32 x, qint32 y, qint32 w, qint32 h) { return ACTUAL_DATAMGR::setExtent(x, y, w, h); } inline void setExtent(const QRect & rect) { setExtent(rect.x(), rect.y(), rect.width(), rect.height()); } public: /** * Clear the specified rect to the specified value. */ inline void clear(qint32 x, qint32 y, qint32 w, qint32 h, quint8 def) { ACTUAL_DATAMGR::clear(x, y, w, h, def); } /** * Clear the specified rect to the specified pixel value. */ inline void clear(qint32 x, qint32 y, qint32 w, qint32 h, const quint8 * def) { ACTUAL_DATAMGR::clear(x, y, w, h, def); } /** * Clear all back to default values. */ inline void clear() { ACTUAL_DATAMGR::clear(); } public: /** * Clones rect from another datamanager. The cloned area will be * shared between both datamanagers as much as possible using * copy-on-write. Parts of the rect that cannot be shared * (cross tiles) are deep-copied, */ inline void bitBlt(KisTiledDataManagerSP srcDM, const QRect &rect) { ACTUAL_DATAMGR::bitBlt(const_cast(srcDM.data()), rect); } /** * The same as \ref bitBlt() but reads old data */ inline void bitBltOldData(KisTiledDataManagerSP srcDM, const QRect &rect) { ACTUAL_DATAMGR::bitBltOldData(const_cast(srcDM.data()), rect); } /** * Clones rect from another datamanager in a rough and fast way. * All the tiles touched by rect will be shared, between both * devices, that means it will copy a bigger area than was * requested. This method is supposed to be used for bitBlt'ing * into temporary paint devices. */ inline void bitBltRough(KisTiledDataManagerSP srcDM, const QRect &rect) { ACTUAL_DATAMGR::bitBltRough(const_cast(srcDM.data()), rect); } /** * The same as \ref bitBltRough() but reads old data */ inline void bitBltRoughOldData(KisTiledDataManagerSP srcDM, const QRect &rect) { ACTUAL_DATAMGR::bitBltRoughOldData(const_cast(srcDM.data()), rect); } public: /** * Write the specified data to x, y. There is no checking on pixelSize! */ inline void setPixel(qint32 x, qint32 y, const quint8 * data) { ACTUAL_DATAMGR::setPixel(x, y, data); } /** * Copy the bytes in the specified rect to a chunk of memory. * The pixelSize in bytes is w * h * pixelSize */ inline void readBytes(quint8 * data, qint32 x, qint32 y, qint32 w, qint32 h, qint32 dataRowStride = -1) const { ACTUAL_DATAMGR::readBytes(data, x, y, w, h, dataRowStride); } /** * Copy the bytes to the specified rect. w * h * pixelSize bytes * will be read, whether the caller prepared them or not. */ inline void writeBytes(const quint8 * data, qint32 x, qint32 y, qint32 w, qint32 h, qint32 dataRowStride = -1) { ACTUAL_DATAMGR::writeBytes(data, x, y, w, h, dataRowStride); } /** * Copy the bytes in the paint device into a vector of arrays of bytes, * where the number of arrays is the number of channels in the * paint device. If the specified area is larger than the paint * device's extent, the default pixel will be read. * - * @param channelsize a vector with for every channel its size in bytes + * @param channelsizes a vector with for every channel its size in bytes + * @param x x coordinate of the top left corner + * @param y y coordinate of the top left corner + * @param w width + * @param h height */ QVector readPlanarBytes(QVector channelsizes, qint32 x, qint32 y, qint32 w, qint32 h) const { return ACTUAL_DATAMGR::readPlanarBytes(channelsizes, x, y, w, h); } /** * Write the data in the separate arrays to the channels. If there * are less vectors than channels, the remaining channels will not * be copied. If any of the arrays points to 0, the channel in * that location will not be touched. If the specified area is * larger than the paint device, the paint device will be * extended. There are no guards: if the area covers more pixels * than there are bytes in the arrays, krita will happily fill * your paint device with areas of memory you never wanted to be * read. Krita may also crash. * * @param planes a vector with a byte array for every plane - * @param channelsize a vector with for every channel its size in + * @param channelsizes a vector with for every channel its size in * bytes + * @param x x coordinate of the top left corner + * @param y y coordinate of the top left corner + * @param w width + * @param h height * * XXX: what about undo? */ void writePlanarBytes(QVector planes, QVector channelsizes, qint32 x, qint32 y, qint32 w, qint32 h) { ACTUAL_DATAMGR::writePlanarBytes(planes, channelsizes, x, y, w, h); } /** * Get the number of contiguous columns starting at x, valid for all values * of y between minY and maxY. */ inline qint32 numContiguousColumns(qint32 x, qint32 minY, qint32 maxY) const { return ACTUAL_DATAMGR::numContiguousColumns(x, minY, maxY); } /** * Get the number of contiguous rows starting at y, valid for all * values of x between minX and maxX. */ inline qint32 numContiguousRows(qint32 y, qint32 minX, qint32 maxX) const { return ACTUAL_DATAMGR::numContiguousRows(y, minX, maxX); } /** * Get the row stride at pixel (x, y). This is the number of bytes * to add to a pointer to pixel (x, y) to access (x, y + 1). */ inline qint32 rowStride(qint32 x, qint32 y) const { return ACTUAL_DATAMGR::rowStride(x, y); } protected: friend class KisRectIterator; friend class KisHLineIterator; friend class KisVLineIterator; }; #endif // KIS_DATAMANAGER_H_ diff --git a/libs/image/kis_fill_painter.h b/libs/image/kis_fill_painter.h index 4f1648a60e..79107704c3 100644 --- a/libs/image/kis_fill_painter.h +++ b/libs/image/kis_fill_painter.h @@ -1,281 +1,281 @@ /* * Copyright (c) 2004 Adrian Page * Copyright (c) 2004 Bart Coppens * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_FILL_PAINTER_H_ #define KIS_FILL_PAINTER_H_ #include #include "KoColor.h" #include "KoColorSpaceRegistry.h" #include "kis_painter.h" #include "kis_types.h" #include "kis_selection.h" #include class KoPattern; class KisFilterConfiguration; // XXX: Filling should set dirty rect. /** * This painter can be used to fill paint devices in different ways. This can also be used * for flood filling related operations. */ class KRITAIMAGE_EXPORT KisFillPainter : public KisPainter { public: /** * Construct an empty painter. Use the begin(KisPaintDeviceSP) method to attach * to a paint device */ KisFillPainter(); /** * Start painting on the specified paint device */ KisFillPainter(KisPaintDeviceSP device); KisFillPainter(KisPaintDeviceSP device, KisSelectionSP selection); private: void initFillPainter(); public: /** * Fill a rectangle with black transparent pixels (0, 0, 0, 0 for RGBA). */ void eraseRect(qint32 x1, qint32 y1, qint32 w, qint32 h); /** * Overloaded version of the above function. */ void eraseRect(const QRect& rc); /** * Fill current selection of KisPainter with a specified \p color. * * The filling rect is limited by \p rc to allow multithreaded * filling/processing. */ void fillSelection(const QRect &rc, const KoColor &color); /** * Fill a rectangle with a certain color. */ void fillRect(qint32 x, qint32 y, qint32 w, qint32 h, const KoColor& c); /** * Overloaded version of the above function. */ void fillRect(const QRect& rc, const KoColor& c); /** * Fill a rectangle with a certain color and opacity. */ void fillRect(qint32 x, qint32 y, qint32 w, qint32 h, const KoColor& c, quint8 opacity); /** * Overloaded version of the above function. */ void fillRect(const QRect& rc, const KoColor& c, quint8 opacity); /** * Fill a rectangle with a certain pattern. The pattern is repeated if it does not fit the * entire rectangle. */ void fillRect(qint32 x1, qint32 y1, qint32 w, qint32 h, const KoPattern * pattern, const QPoint &offset = QPoint()); /** * Fill a rectangle with a certain pattern. The pattern is repeated if it does not fit the * entire rectangle. */ void fillRect(qint32 x1, qint32 y1, qint32 w, qint32 h, const KisPaintDeviceSP device, const QRect& deviceRect); /** * Overloaded version of the above function. */ void fillRect(const QRect& rc, const KoPattern * pattern, const QPoint &offset = QPoint()); /** * Fill the specified area with the output of the generator plugin that is configured * in the generator parameter */ void fillRect(qint32 x1, qint32 y1, qint32 w, qint32 h, const KisFilterConfigurationSP generator); /** * Fills the enclosed area around the point with the set color. If * there is a selection, the whole selection is filled. Note that * you must have set the width and height on the painter if you * don't have a selection. * * @param startX the X position where the floodfill starts * @param startY the Y position where the floodfill starts * @param sourceDevice the sourceDevice that determines the area that * is floodfilled if sampleMerged is on */ void fillColor(int startX, int startY, KisPaintDeviceSP sourceDevice); /** * Fills the enclosed area around the point with the set pattern. * If there is a selection, the whole selection is filled. Note * that you must have set the width and height on the painter if * you don't have a selection. * * @param startX the X position where the floodfill starts * @param startY the Y position where the floodfill starts * @param sourceDevice the sourceDevice that determines the area that * is floodfilled if sampleMerged is on */ void fillPattern(int startX, int startY, KisPaintDeviceSP sourceDevice); /** * Returns a selection mask for the floodfill starting at the specified position. * * @param startX the X position where the floodfill starts * @param startY the Y position where the floodfill starts * @param sourceDevice the sourceDevice that determines the area that * is floodfilled if sampleMerged is on */ KisSelectionSP createFloodSelection(int startX, int startY, KisPaintDeviceSP sourceDevice); /** * Set the threshold for floodfill. The range is 0-255: 0 means the fill will only * fill parts that are the exact same color, 255 means anything will be filled */ void setFillThreshold(int threshold); /** Returns the fill threshold, see setFillThreshold for details */ int fillThreshold() const { return m_threshold; } bool useCompositioning() const { return m_useCompositioning; } void setUseCompositioning(bool useCompositioning) { m_useCompositioning = useCompositioning; } /** Sets the width of the paint device */ void setWidth(int w) { m_width = w; } /** Sets the height of the paint device */ void setHeight(int h) { m_height = h; } /** If true, floodfill doesn't fill outside the selected area of a layer */ bool careForSelection() const { return m_careForSelection; } /** Set caring for selection. See careForSelection for details */ void setCareForSelection(bool set) { m_careForSelection = set; } /** Sets the auto growth/shrinking radius */ void setSizemod(int sizemod) { m_sizemod = sizemod; } - /** Sets how much to auto-grow or shrink (if @param sizemod is negative) the selection + /** Sets how much to auto-grow or shrink (if @p sizemod is negative) the selection flood before painting, this affects every fill operation except fillRect */ int sizemod() { return m_sizemod; } /** Sets feathering radius */ void setFeather(int feather) { m_feather = feather; } /** defines the feathering radius for selection flood operations, this affects every fill operation except fillRect */ uint feather() { return m_feather; } private: // for floodfill void genericFillStart(int startX, int startY, KisPaintDeviceSP sourceDevice); void genericFillEnd(KisPaintDeviceSP filled); KisSelectionSP m_fillSelection; int m_feather; int m_sizemod; int m_threshold; int m_width, m_height; QRect m_rect; bool m_careForSelection; bool m_useCompositioning; }; inline void KisFillPainter::fillRect(qint32 x, qint32 y, qint32 w, qint32 h, const KoColor& c) { fillRect(x, y, w, h, c, OPACITY_OPAQUE_U8); } inline void KisFillPainter::fillRect(const QRect& rc, const KoColor& c) { fillRect(rc.x(), rc.y(), rc.width(), rc.height(), c, OPACITY_OPAQUE_U8); } inline void KisFillPainter::eraseRect(qint32 x1, qint32 y1, qint32 w, qint32 h) { const KoColorSpace * cs = KoColorSpaceRegistry::instance()->rgb8(); KoColor c(Qt::black, cs); fillRect(x1, y1, w, h, c, OPACITY_TRANSPARENT_U8); } inline void KisFillPainter::eraseRect(const QRect& rc) { const KoColorSpace * cs = KoColorSpaceRegistry::instance()->rgb8(); KoColor c(Qt::black, cs); fillRect(rc.x(), rc.y(), rc.width(), rc.height(), c, OPACITY_TRANSPARENT_U8); } inline void KisFillPainter::fillRect(const QRect& rc, const KoColor& c, quint8 opacity) { fillRect(rc.x(), rc.y(), rc.width(), rc.height(), c, opacity); } inline void KisFillPainter::setFillThreshold(int threshold) { m_threshold = threshold; } #endif //KIS_FILL_PAINTER_H_ diff --git a/libs/image/kis_image.h b/libs/image/kis_image.h index 20225814b5..c3f8da5f23 100644 --- a/libs/image/kis_image.h +++ b/libs/image/kis_image.h @@ -1,1123 +1,1130 @@ /* * Copyright (c) 2002 Patrick Julien * Copyright (c) 2007 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_IMAGE_H_ #define KIS_IMAGE_H_ #include #include #include #include #include #include #include #include "kis_paint_device.h" // msvc cannot handle forward declarations, so include kis_paint_device here #include "kis_types.h" #include "kis_shared.h" #include "kis_node_graph_listener.h" #include "kis_node_facade.h" #include "kis_image_interfaces.h" #include "kis_strokes_queue_undo_result.h" #include class KisDocument; class KoColorSpace; class KoColor; class KisCompositeProgressProxy; class KisUndoStore; class KisUndoAdapter; class KisImageSignalRouter; class KisPostExecutionUndoAdapter; class KisFilterStrategy; class KoColorProfile; class KisLayerComposition; class KisSpontaneousJob; class KisImageAnimationInterface; class KUndo2MagicString; class KisProofingConfiguration; namespace KisMetaData { class MergeStrategy; } /** * This is the image class, it contains a tree of KisLayer stack and * meta information about the image. And it also provides some * functions to manipulate the whole image. */ class KRITAIMAGE_EXPORT KisImage : public QObject, public KisStrokesFacade, public KisStrokeUndoFacade, public KisUpdatesFacade, public KisProjectionUpdateListener, public KisNodeFacade, public KisNodeGraphListener, public KisShared { Q_OBJECT public: - /// @param colorSpace can be null. in that case it will be initialised to a default color space. + /// @p colorSpace can be null. In that case, it will be initialised to a default color space. KisImage(KisUndoStore *undoStore, qint32 width, qint32 height, const KoColorSpace *colorSpace, const QString& name); ~KisImage() override; public: // KisNodeGraphListener implementation void aboutToAddANode(KisNode *parent, int index) override; void nodeHasBeenAdded(KisNode *parent, int index) override; void aboutToRemoveANode(KisNode *parent, int index) override; void nodeChanged(KisNode * node) override; void invalidateAllFrames() override; void notifySelectionChanged() override; void requestProjectionUpdate(KisNode *node, const QVector &rects, bool resetAnimationCache) override; void invalidateFrames(const KisTimeRange &range, const QRect &rect) override; void requestTimeSwitch(int time) override; KisNode* graphOverlayNode() const override; public: // KisProjectionUpdateListener implementation void notifyProjectionUpdated(const QRect &rc) override; public: /** * Set the number of threads used by the image's working threads */ void setWorkingThreadsLimit(int value); /** * Return the number of threads available to the image's working threads */ int workingThreadsLimit() const; /** * Makes a copy of the image with all the layers. If possible, shallow * copies of the layers are made. * * \p exactCopy shows if the copied image should look *exactly* the same as * the other one (according to it's .kra xml representation). It means that * the layers will have the same UUID keys and, therefore, you are not * expected to use the copied image anywhere except for saving. Don't use * this option if you plan to work with the copied image later. */ KisImage *clone(bool exactCopy = false); /** * Render the projection onto a QImage. */ QImage convertToQImage(qint32 x1, qint32 y1, qint32 width, qint32 height, const KoColorProfile * profile); /** * Render the projection onto a QImage. * (this is an overloaded function) */ QImage convertToQImage(QRect imageRect, const KoColorProfile * profile); /** * Render a thumbnail of the projection onto a QImage. */ QImage convertToQImage(const QSize& scaledImageSize, const KoColorProfile *profile); /** * [low-level] Lock the image without waiting for all the internal job queues are processed * * WARNING: Don't use it unless you really know what you are doing! Use barrierLock() instead! * * Waits for all the **currently running** internal jobs to complete and locks the image * for writing. Please note that this function does **not** wait for all the internal * queues to process, so there might be some non-finished actions pending. It means that * you just postpone these actions until you unlock() the image back. Until then, then image * might easily be frozen in some inconsistent state. * * The only sane usage for this function is to lock the image for **emergency** * processing, when some internal action or scheduler got hung up, and you just want * to fetch some data from the image without races. * * In all other cases, please use barrierLock() instead! */ void lock(); /** * Unlocks the image and starts/resumes all the pending internal jobs. If the image * has been locked for a non-readOnly access, then all the internal caches of the image * (e.g. lod-planes) are reset and regeneration jobs are scheduled. */ void unlock(); /** * @return return true if the image is in a locked state, i.e. all the internal * jobs are blocked from execution by calling wither lock() or barrierLock(). * * When the image is locked, the user can do some modifications to the image * contents safely without a perspective having race conditions with internal * image jobs. */ bool locked() const; /** * Sets the mask (it must be a part of the node hierarchy already) to be paited on * the top of all layers. This method does all the locking and syncing for you. It * is executed asynchronously. */ void setOverlaySelectionMask(KisSelectionMaskSP mask); /** * \see setOverlaySelectionMask */ KisSelectionMaskSP overlaySelectionMask() const; /** * \see setOverlaySelectionMask */ bool hasOverlaySelectionMask() const; /** * @return the global selection object or 0 if there is none. The * global selection is always read-write. */ KisSelectionSP globalSelection() const; /** * Retrieve the next automatic layername (XXX: fix to add option to return Mask X) */ QString nextLayerName(const QString &baseName = "") const; /** * Set the automatic layer name counter one back. */ void rollBackLayerName(); /** * @brief start asynchronous operation on resizing the image * * The method will resize the image to fit the new size without * dropping any pixel data. The GUI will get correct * notification with old and new sizes, so it adjust canvas origin * accordingly and avoid jumping of the canvas on screen * * @param newRect the rectangle of the image which will be visible * after operation is completed * * Please note that the actual operation starts asynchronously in * a background, so you cannot expect the image having new size * right after this call. */ void resizeImage(const QRect& newRect); /** * @brief start asynchronous operation on cropping the image * * The method will **drop** all the image data outside \p newRect * and resize the image to fit the new size. The GUI will get correct * notification with old and new sizes, so it adjust canvas origin * accordingly and avoid jumping of the canvas on screen * * @param newRect the rectangle of the image which will be cut-out * * Please note that the actual operation starts asynchronously in * a background, so you cannot expect the image having new size * right after this call. */ void cropImage(const QRect& newRect); /** * @brief start asynchronous operation on cropping a subtree of nodes starting at \p node * * The method will **drop** all the layer data outside \p newRect. Neither * image nor a layer will be moved anywhere * + * @param node node to crop * @param newRect the rectangle of the layer which will be cut-out * * Please note that the actual operation starts asynchronously in * a background, so you cannot expect the image having new size * right after this call. */ void cropNode(KisNodeSP node, const QRect& newRect); /** * @brief start asynchronous operation on scaling the image * @param size new image size in pixels * @param xres new image x-resolution pixels-per-pt * @param yres new image y-resolution pixels-per-pt * @param filterStrategy filtering strategy * * Please note that the actual operation starts asynchronously in * a background, so you cannot expect the image having new size * right after this call. */ void scaleImage(const QSize &size, qreal xres, qreal yres, KisFilterStrategy *filterStrategy); /** * @brief start asynchronous operation on scaling a subtree of nodes starting at \p node * @param node node to scale - * @param scaleX, @param scaleY scale coefficient to be applied to the node + * @param center the center of the scaling + * @param scaleX x-scale coefficient to be applied to the node + * @param scaleY y-scale coefficient to be applied to the node * @param filterStrategy filtering strategy + * @param selection the selection we based on * * Please note that the actual operation starts asynchronously in * a background, so you cannot expect the image having new size * right after this call. */ void scaleNode(KisNodeSP node, const QPointF ¢er, qreal scaleX, qreal scaleY, KisFilterStrategy *filterStrategy, KisSelectionSP selection); /** * @brief start asynchronous operation on rotating the image * * The image is resized to fit the rotated rectangle * * @param radians rotation angle in radians * * Please note that the actual operation starts asynchronously in * a background, so you cannot expect the operation being completed * right after the call */ void rotateImage(double radians); /** * @brief start asynchronous operation on rotating a subtree of nodes starting at \p node * * The image is not resized! * * @param node the root of the subtree to rotate * @param radians rotation angle in radians + * @param selection the selection we based on * * Please note that the actual operation starts asynchronously in * a background, so you cannot expect the operation being completed * right after the call */ void rotateNode(KisNodeSP node, double radians, KisSelectionSP selection); /** * @brief start asynchronous operation on shearing the image * * The image is resized to fit the sheared polygon * - * @param angleX, @param angleY are given in degrees. + * @p angleX, @p angleY are given in degrees. * * Please note that the actual operation starts asynchronously in * a background, so you cannot expect the operation being completed * right after the call */ void shear(double angleX, double angleY); /** * @brief start asynchronous operation on shearing a subtree of nodes starting at \p node * * The image is not resized! * * @param node the root of the subtree to rotate - * @param angleX, @param angleY are given in degrees. + * @param angleX x-shear given in degrees. + * @param angleY y-shear given in degrees. + * @param selection the selection we based on * * Please note that the actual operation starts asynchronously in * a background, so you cannot expect the operation being completed * right after the call */ void shearNode(KisNodeSP node, double angleX, double angleY, KisSelectionSP selection); /** * Convert the image and all its layers to the dstColorSpace */ void convertImageColorSpace(const KoColorSpace *dstColorSpace, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags); /** * Set the color space of the projection (and the root layer) * to dstColorSpace. No conversion is done for other layers, * their colorspace can differ. - * NOTE: Note conversion is done, only regeneration, so no rendering + * @note No conversion is done, only regeneration, so no rendering * intent needed */ void convertProjectionColorSpace(const KoColorSpace *dstColorSpace); // Get the profile associated with this image const KoColorProfile * profile() const; /** * Set the profile of the image to the new profile and do the same for * all layers that have the same colorspace and profile of the image. * It doesn't do any pixel conversion. * * This is essential if you have loaded an image that didn't * have an embedded profile to which you want to attach the right profile. * * This does not create an undo action; only call it when creating or * loading an image. * * @returns false if the profile could not be assigned */ bool assignImageProfile(const KoColorProfile *profile); /** * Returns the current undo adapter. You can add new commands to the * undo stack using the adapter. This adapter is used for a backward * compatibility for old commands created before strokes. It blocks * all the porcessing at the scheduler, waits until it's finished * and executes commands exclusively. */ KisUndoAdapter* undoAdapter() const; /** * This adapter is used by the strokes system. The commands are added * to it *after* redo() is done (in the scheduler context). They are * wrapped into a special command and added to the undo stack. redo() * in not called. */ KisPostExecutionUndoAdapter* postExecutionUndoAdapter() const override; /** * Replace current undo store with the new one. The old store * will be deleted. * This method is used by KisDocument for dropping all the commands * during file loading. */ void setUndoStore(KisUndoStore *undoStore); /** * Return current undo store of the image */ KisUndoStore* undoStore(); /** * Tell the image it's modified; this emits the sigImageModified * signal. This happens when the image needs to be saved */ void setModified(); /** * The default colorspace of this image: new layers will have this * colorspace and the projection will have this colorspace. */ const KoColorSpace * colorSpace() const; /** * X resolution in pixels per pt */ double xRes() const; /** * Y resolution in pixels per pt */ double yRes() const; /** * Set the resolution in pixels per pt. */ void setResolution(double xres, double yres); /** * Convert a document coordinate to a pixel coordinate. * * @param documentCoord PostScript Pt coordinate to convert. */ QPointF documentToPixel(const QPointF &documentCoord) const; /** * Convert a document coordinate to an integer pixel coordinate rounded down. * * @param documentCoord PostScript Pt coordinate to convert. */ QPoint documentToImagePixelFloored(const QPointF &documentCoord) const; /** * Convert a document rectangle to a pixel rectangle. * * @param documentRect PostScript Pt rectangle to convert. */ QRectF documentToPixel(const QRectF &documentRect) const; /** * Convert a pixel coordinate to a document coordinate. * * @param pixelCoord pixel coordinate to convert. */ QPointF pixelToDocument(const QPointF &pixelCoord) const; /** * Convert an integer pixel coordinate to a document coordinate. * The document coordinate is at the centre of the pixel. * * @param pixelCoord pixel coordinate to convert. */ QPointF pixelToDocument(const QPoint &pixelCoord) const; /** * Convert a document rectangle to an integer pixel rectangle. * * @param pixelCoord pixel coordinate to convert. */ QRectF pixelToDocument(const QRectF &pixelCoord) const; /** * Return the width of the image */ qint32 width() const; /** * Return the height of the image */ qint32 height() const; /** * Return the size of the image */ QSize size() const { return QSize(width(), height()); } /** * @return the root node of the image node graph */ KisGroupLayerSP rootLayer() const; /** * Return the projection; that is, the complete, composited * representation of this image. */ KisPaintDeviceSP projection() const; /** * Return the number of layers (not other nodes) that are in this * image. */ qint32 nlayers() const; /** * Return the number of layers (not other node types) that are in * this image and that are hidden. */ qint32 nHiddenLayers() const; /** * Merge all visible layers and discard hidden ones. */ void flatten(KisNodeSP activeNode); /** * Merge the specified layer with the layer * below this layer, remove the specified layer. */ void mergeDown(KisLayerSP l, const KisMetaData::MergeStrategy* strategy); /** * flatten the layer: that is, the projection becomes the layer * and all subnodes are removed. If this is not a paint layer, it will morph * into a paint layer. */ void flattenLayer(KisLayerSP layer); /** * Merges layers in \p mergedLayers and creates a new layer above * \p putAfter */ void mergeMultipleLayers(QList mergedLayers, KisNodeSP putAfter); /// @return the exact bounds of the image in pixel coordinates. QRect bounds() const; /** * Returns the actual bounds of the image, taking LevelOfDetail * into account. This value is used as a bounds() value of * KisDefaultBounds object. */ QRect effectiveLodBounds() const; /// use if the layers have changed _completely_ (eg. when flattening) void notifyLayersChanged(); /** * Sets the default color of the root layer projection. All the layers * will be merged on top of this very color */ void setDefaultProjectionColor(const KoColor &color); /** * \see setDefaultProjectionColor() */ KoColor defaultProjectionColor() const; void setRootLayer(KisGroupLayerSP rootLayer); /** * Add an annotation for this image. This can be anything: Gamma, EXIF, etc. * Note that the "icc" annotation is reserved for the color strategies. * If the annotation already exists, overwrite it with this one. */ void addAnnotation(KisAnnotationSP annotation); /** get the annotation with the given type, can return 0 */ KisAnnotationSP annotation(const QString& type); /** delete the annotation, if the image contains it */ void removeAnnotation(const QString& type); /** * Start of an iteration over the annotations of this image (including the ICC Profile) */ vKisAnnotationSP_it beginAnnotations(); /** end of an iteration over the annotations of this image */ vKisAnnotationSP_it endAnnotations(); /** * Called before the image is deleted and sends the sigAboutToBeDeleted signal */ void notifyAboutToBeDeleted(); KisImageSignalRouter* signalRouter(); /** * Returns whether we can reselect current global selection * * \see reselectGlobalSelection() */ bool canReselectGlobalSelection(); /** * Returns the layer compositions for the image */ QList compositions(); /** * Adds a new layer composition, will be saved with the image */ void addComposition(KisLayerCompositionSP composition); /** * Remove the layer compostion */ void removeComposition(KisLayerCompositionSP composition); /** * Permit or deny the wrap-around mode for all the paint devices * of the image. Note that permitting the wraparound mode will not * necessarily activate it right now. To be activated the wrap * around mode should be 1) permitted; 2) supported by the * currently running stroke. */ void setWrapAroundModePermitted(bool value); /** * \return whether the wrap-around mode is permitted for this * image. If the wrap around mode is permitted and the * currently running stroke supports it, the mode will be * activated for all paint devices of the image. * * \see setWrapAroundMode */ bool wrapAroundModePermitted() const; /** * \return whether the wraparound mode is activated for all the * devices of the image. The mode is activated when both * factors are true: the user permitted it and the stroke * supports it */ bool wrapAroundModeActive() const; /** * \return current level of detail which is used when processing the image. * Current working zoom = 2 ^ (- currentLevelOfDetail()). Default value is * null, which means we work on the original image. */ int currentLevelOfDetail() const; /** * Notify KisImage which level of detail should be used in the * lod-mode. Setting the mode does not guarantee the LOD to be * used. It will be activated only when the stokes supports it. */ void setDesiredLevelOfDetail(int lod); /** * Relative position of the mirror axis center * 0,0 - topleft corner of the image * 1,1 - bottomright corner of the image */ QPointF mirrorAxesCenter() const; /** * Sets the relative position of the axes center * \see mirrorAxesCenter() for details */ void setMirrorAxesCenter(const QPointF &value) const; public Q_SLOTS: /** * Explicitly start regeneration of LoD planes of all the devices * in the image. This call should be performed when the user is idle, * just to make the quality of image updates better. */ void explicitRegenerateLevelOfDetail(); public: /** * Blocks usage of level of detail functionality. After this method * has been called, no new strokes will use LoD. */ void setLevelOfDetailBlocked(bool value); /** * \see setLevelOfDetailBlocked() */ bool levelOfDetailBlocked() const; /** * Notifies that the node collapsed state has changed */ void notifyNodeCollpasedChanged(); KisImageAnimationInterface *animationInterface() const; /** * @brief setProofingConfiguration, this sets the image's proofing configuration, and signals * the proofingConfiguration has changed. * @param proofingConfig - the kis proofing config that will be used instead. */ void setProofingConfiguration(KisProofingConfigurationSP proofingConfig); /** * @brief proofingConfiguration * @return the proofing configuration of the image. */ KisProofingConfigurationSP proofingConfiguration() const; public Q_SLOTS: bool startIsolatedMode(KisNodeSP node); void stopIsolatedMode(); public: KisNodeSP isolatedModeRoot() const; Q_SIGNALS: /** * Emitted whenever an action has caused the image to be * recomposited. * * @param rc The rect that has been recomposited. */ void sigImageUpdated(const QRect &); /** Emitted whenever the image has been modified, so that it doesn't match with the version saved on disk. */ void sigImageModified(); /** * The signal is emitted when the size of the image is changed. * \p oldStillPoint and \p newStillPoint give the receiver the * hint about how the new and old rect of the image correspond to * each other. They specify the point of the image around which * the conversion was done. This point will stay still on the * user's screen. That is the \p newStillPoint of the new image * will be painted at the same screen position, where \p * oldStillPoint of the old image was painted. * * \param oldStillPoint is a still point represented in *old* * image coordinates * * \param newStillPoint is a still point represented in *new* * image coordinates */ void sigSizeChanged(const QPointF &oldStillPoint, const QPointF &newStillPoint); void sigProfileChanged(const KoColorProfile * profile); void sigColorSpaceChanged(const KoColorSpace* cs); void sigResolutionChanged(double xRes, double yRes); void sigRequestNodeReselection(KisNodeSP activeNode, const KisNodeList &selectedNodes); /** * Inform the model that a node was changed */ void sigNodeChanged(KisNodeSP node); /** * Inform that the image is going to be deleted */ void sigAboutToBeDeleted(); /** * The signal is emitted right after a node has been connected * to the graph of the nodes. * * WARNING: you must not request any graph-related information * about the node being run in a not-scheduler thread. If you need * information about the parent/siblings of the node connect * with Qt::DirectConnection, get needed information and then * emit another Qt::AutoConnection signal to pass this information * to your thread. See details of the implementation * in KisDummiesfacadeBase. */ void sigNodeAddedAsync(KisNodeSP node); /** * This signal is emitted right before a node is going to removed * from the graph of the nodes. * * WARNING: you must not request any graph-related information * about the node being run in a not-scheduler thread. * * \see comment in sigNodeAddedAsync() */ void sigRemoveNodeAsync(KisNodeSP node); /** * Emitted when the root node of the image has changed. * It happens, e.g. when we flatten the image. When * this happens the receiver should reload information * about the image */ void sigLayersChangedAsync(); /** * Emitted when the UI has requested the undo of the last stroke's * operation. The point is, we cannot deal with the internals of * the stroke without its creator knowing about it (which most * probably cause a crash), so we just forward this request from * the UI to the creator of the stroke. * * If your tool supports undoing part of its work, just listen to * this signal and undo when it comes */ void sigUndoDuringStrokeRequested(); /** * Emitted when the UI has requested the cancellation of * the stroke. The point is, we cannot cancel the stroke * without its creator knowing about it (which most probably * cause a crash), so we just forward this request from the UI * to the creator of the stroke. * * If your tool supports cancelling of its work in the middle * of operation, just listen to this signal and cancel * the stroke when it comes */ void sigStrokeCancellationRequested(); /** * Emitted when the image decides that the stroke should better * be ended. The point is, we cannot just end the stroke * without its creator knowing about it (which most probably * cause a crash), so we just forward this request from the UI * to the creator of the stroke. * * If your tool supports long strokes that may involve multiple * mouse actions in one stroke, just listen to this signal and * end the stroke when it comes. */ void sigStrokeEndRequested(); /** * Same as sigStrokeEndRequested() but is not emitted when the active node * is changed. */ void sigStrokeEndRequestedActiveNodeFiltered(); /** * Emitted when the isolated mode status has changed. * * Can be used by the receivers to catch a fact of forcefully * stopping the isolated mode by the image when some complex * action was requested */ void sigIsolatedModeChanged(); /** * Emitted when one or more nodes changed the collapsed state * */ void sigNodeCollapsedChanged(); /** * Emitted when the proofing configuration of the image is being changed. * */ void sigProofingConfigChanged(); /** * Internal signal for asynchronously requesting isolated mode to stop. Don't use it * outside KisImage, use sigIsolatedModeChanged() instead. */ void sigInternalStopIsolatedModeRequested(); public Q_SLOTS: KisCompositeProgressProxy* compositeProgressProxy(); bool isIdle(bool allowLocked = false); /** * @brief Wait until all the queued background jobs are completed and lock the image. * * KisImage object has a local scheduler that executes long-running image * rendering/modifying jobs (we call them "strokes") in a background. Basically, * one should either access the image from the scope of such jobs (strokes) or * just lock the image before using. * * Calling barrierLock() will wait until all the queued operations are finished * and lock the image, so you can start accessing it in a safe way. * * @p readOnly tells the image if the caller is going to modify the image during * holding the lock. Locking with non-readOnly access will reset all * the internal caches of the image (lod-planes) when the lock status * will be lifted. */ void barrierLock(bool readOnly = false); /** * @brief Tries to lock the image without waiting for the jobs to finish * * Same as barrierLock(), but doesn't block execution of the calling thread * until all the background jobs are finished. Instead, in case of presence of * unfinished jobs in the queue, it just returns false * * @return whether the lock has been acquired * @see barrierLock */ bool tryBarrierLock(bool readOnly = false); /** * Wait for all the internal image jobs to complete and return without locking * the image. This function is handly for tests or other synchronous actions, * when one needs to wait for the result of his actions. */ void waitForDone(); KisStrokeId startStroke(KisStrokeStrategy *strokeStrategy) override; void addJob(KisStrokeId id, KisStrokeJobData *data) override; void endStroke(KisStrokeId id) override; bool cancelStroke(KisStrokeId id) override; /** * @brief blockUpdates block updating the image projection */ void blockUpdates() override; /** * @brief unblockUpdates unblock updating the image project. This * only restarts the scheduler and does not schedule a full refresh. */ void unblockUpdates() override; /** * Disables notification of the UI about the changes in the image. * This feature is used by KisProcessingApplicator. It is needed * when we change the size of the image. In this case, the whole * image will be reloaded into UI by sigSizeChanged(), so there is * no need to inform the UI about individual dirty rects. * * The last call to enableUIUpdates() will return the list of udpates * that were requested while they were blocked. */ void disableUIUpdates() override; /** * \see disableUIUpdates */ QVector enableUIUpdates() override; /** * Disables the processing of all the setDirty() requests that * come to the image. The incoming requests are effectively * *dropped*. * * This feature is used by KisProcessingApplicator. For many cases * it provides its own updates interface, which recalculates the * whole subtree of nodes. But while we change any particular * node, it can ask for an update itself. This method is a way of * blocking such intermediate (and excessive) requests. * * NOTE: this is a convenience function for setProjectionUpdatesFilter() * that installs a predefined filter that eats everything. Please * note that these calls are *not* recursive */ void disableDirtyRequests() override; /** * \see disableDirtyRequests() */ void enableDirtyRequests() override; /** * Installs a filter object that will filter all the incoming projection update * requests. If the filter return true, the incoming update is dropped. * * NOTE: you cannot set filters recursively! */ void setProjectionUpdatesFilter(KisProjectionUpdatesFilterSP filter) override; /** * \see setProjectionUpdatesFilter() */ KisProjectionUpdatesFilterSP projectionUpdatesFilter() const override; void refreshGraphAsync(KisNodeSP root = KisNodeSP()) override; void refreshGraphAsync(KisNodeSP root, const QRect &rc) override; void refreshGraphAsync(KisNodeSP root, const QRect &rc, const QRect &cropRect) override; /** * Triggers synchronous recomposition of the projection */ void refreshGraph(KisNodeSP root = KisNodeSP()); void refreshGraph(KisNodeSP root, const QRect& rc, const QRect &cropRect); void initialRefreshGraph(); /** * Initiate a stack regeneration skipping the recalculation of the * filthy node's projection. * * Works exactly as pseudoFilthy->setDirty() with the only * exception that pseudoFilthy::updateProjection() will not be * called. That is used by KisRecalculateTransformMaskJob to avoid * cyclic dependencies. */ void requestProjectionUpdateNoFilthy(KisNodeSP pseudoFilthy, const QRect &rc, const QRect &cropRect); /** * Adds a spontaneous job to the updates queue. * * A spontaneous job may do some trivial tasks in the background, * like updating the outline of selection or purging unused tiles * from the existing paint devices. */ void addSpontaneousJob(KisSpontaneousJob *spontaneousJob); /** * This method is called by the UI (*not* by the creator of the * stroke) when it thinks the current stroke should undo its last * action, for example, when the user presses Ctrl+Z while some * stroke is active. * * If the creator of the stroke supports undoing of intermediate * actions, it will be notified about this request and can undo * its last action. */ void requestUndoDuringStroke(); /** * This method is called by the UI (*not* by the creator of the * stroke) when it thinks current stroke should be cancelled. If * there is a running stroke that has already been detached from * its creator (ended or cancelled), it will be forcefully * cancelled and reverted. If there is an open stroke present, and * if its creator supports cancelling, it will be notified about * the request and the stroke will be cancelled */ void requestStrokeCancellation(); /** * This method requests the last stroke executed on the image to become undone. * If the stroke is not ended, or if all the Lod0 strokes are completed, the method * returns UNDO_FAIL. If the last Lod0 is going to be finished soon, then UNDO_WAIT * is returned and the caller should just wait for its completion and call global undo * instead. UNDO_OK means one unfinished stroke has been undone. */ UndoResult tryUndoUnfinishedLod0Stroke(); /** * This method is called when image or some other part of Krita * (*not* the creator of the stroke) decides that the stroke * should be ended. If the creator of the stroke supports it, it * will be notified and the stroke will be cancelled */ void requestStrokeEnd(); /** * Same as requestStrokeEnd() but is called by view manager when * the current node is changed. Use to distinguish * sigStrokeEndRequested() and * sigStrokeEndRequestedActiveNodeFiltered() which are used by * KisNodeJugglerCompressed */ void requestStrokeEndActiveNode(); private: KisImage(const KisImage& rhs, KisUndoStore *undoStore, bool exactCopy); KisImage& operator=(const KisImage& rhs); void emitSizeChanged(); void resizeImageImpl(const QRect& newRect, bool cropLayers); void rotateImpl(const KUndo2MagicString &actionName, KisNodeSP rootNode, double radians, bool resizeImage, KisSelectionSP selection); void shearImpl(const KUndo2MagicString &actionName, KisNodeSP rootNode, bool resizeImage, double angleX, double angleY, KisSelectionSP selection); void safeRemoveTwoNodes(KisNodeSP node1, KisNodeSP node2); void refreshHiddenArea(KisNodeSP rootNode, const QRect &preparedArea); void requestProjectionUpdateImpl(KisNode *node, const QVector &rects, const QRect &cropRect); friend class KisImageResizeCommand; void setSize(const QSize& size); friend class KisImageSetProjectionColorSpaceCommand; void setProjectionColorSpace(const KoColorSpace * colorSpace); friend class KisDeselectGlobalSelectionCommand; friend class KisReselectGlobalSelectionCommand; friend class KisSetGlobalSelectionCommand; friend class KisImageTest; friend class Document; // For libkis /** * Replaces the current global selection with globalSelection. If * \p globalSelection is empty, removes the selection object, so that * \ref globalSelection() will return 0 after that. */ void setGlobalSelection(KisSelectionSP globalSelection); /** * Deselects current global selection. * \ref globalSelection() will return 0 after that. */ void deselectGlobalSelection(); /** * Reselects current deselected selection * * \see deselectGlobalSelection() */ void reselectGlobalSelection(); private: class KisImagePrivate; KisImagePrivate * m_d; }; #endif // KIS_IMAGE_H_ diff --git a/libs/image/kis_paint_device.h b/libs/image/kis_paint_device.h index 99e91131a1..ce54957e41 100644 --- a/libs/image/kis_paint_device.h +++ b/libs/image/kis_paint_device.h @@ -1,880 +1,879 @@ /* * Copyright (c) 2002 patrick julien * Copyright (c) 2006 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_PAINT_DEVICE_IMPL_H_ #define KIS_PAINT_DEVICE_IMPL_H_ #include #include #include #include "kis_debug.h" #include #include "kis_types.h" #include "kis_shared.h" #include "kis_default_bounds_base.h" #include class KUndo2Command; class QRect; class QImage; class QPoint; class QString; class QColor; class QIODevice; class KoColor; class KoColorSpace; class KoColorProfile; class KisDataManager; class KisPaintDeviceWriter; class KisKeyframe; class KisRasterKeyframeChannel; class KisPaintDeviceFramesInterface; typedef KisSharedPtr KisDataManagerSP; namespace KritaUtils { enum DeviceCopyMode { CopySnapshot = 0, CopyAllFrames }; } /** * A paint device contains the actual pixel data and offers methods * to read and write pixels. A paint device has an integer x, y position * (it is not positioned on the image with sub-pixel accuracy). * A KisPaintDevice doesn't have any fixed size, the size changes dynamically * when pixels are accessed by an iterator. */ class KRITAIMAGE_EXPORT KisPaintDevice : public QObject , public KisShared { Q_OBJECT public: /** * Create a new paint device with the specified colorspace. * * @param colorSpace the colorspace of this paint device * @param name for debugging purposes */ explicit KisPaintDevice(const KoColorSpace * colorSpace, const QString& name = QString()); /** * Create a new paint device with the specified colorspace. The * parent node will be notified of changes to this paint device. * * @param parent the node that contains this paint device * @param colorSpace the colorspace of this paint device * @param defaultBounds boundaries of the device in case it is empty * @param name for debugging purposes */ KisPaintDevice(KisNodeWSP parent, const KoColorSpace * colorSpace, KisDefaultBoundsBaseSP defaultBounds = KisDefaultBoundsBaseSP(), const QString& name = QString()); /** * Creates a copy of this device. * * If \p copyMode is CopySnapshot, the newly created device clones the * current frame of \p rhs only (default and efficient * behavior). If \p copyFrames is CopyAllFrames, the new device is a deep * copy of the source with all the frames included. */ KisPaintDevice(const KisPaintDevice& rhs, KritaUtils::DeviceCopyMode copyMode = KritaUtils::CopySnapshot, KisNode *newParentNode = 0); ~KisPaintDevice() override; protected: /** * A special constructor for usage in KisPixelSelection. It allows * two paint devices to share a data manager. * * @param explicitDataManager data manager to use inside paint device * @param src source paint device to copy parameters from * @param name for debugging purposes */ KisPaintDevice(KisDataManagerSP explicitDataManager, KisPaintDeviceSP src, const QString& name = QString()); public: /** * Write the pixels of this paint device into the specified file store. */ bool write(KisPaintDeviceWriter &store); /** * Fill this paint device with the pixels from the specified file store. */ bool read(QIODevice *stream); public: /** * set the parent node of the paint device */ void setParentNode(KisNodeWSP parent); /** * set the default bounds for the paint device when * the default pixel is not completely transparent */ void setDefaultBounds(KisDefaultBoundsBaseSP bounds); /** * the default bounds rect of the paint device */ KisDefaultBoundsBaseSP defaultBounds() const; /** * Moves the device to these new coordinates (no incremental move) */ void moveTo(qint32 x, qint32 y); /** * Convenience method for the above. */ virtual void moveTo(const QPoint& pt); /** * Return an X,Y offset of the device in a convenient form */ QPoint offset() const; /** * The X offset of the paint device */ qint32 x() const; /** * The Y offset of the paint device */ qint32 y() const; /** * set the X offset of the paint device */ void setX(qint32 x); /** * set the Y offset of the paint device */ void setY(qint32 y); /** * Retrieve the bounds of the paint device. The size is not exact, * but may be larger if the underlying datamanager works that way. * For instance, the tiled datamanager keeps the extent to the nearest * multiple of 64. * * If default pixel is not transparent, then the actual extent * rect is united with the defaultBounds()->bounds() value * (the size of the image, usually). */ QRect extent() const; /// Convenience method for the above void extent(qint32 &x, qint32 &y, qint32 &w, qint32 &h) const; /** * Get the exact bounds of this paint device. The real solution is * very slow because it does a linear scanline search, but it * uses caching, so calling to this function without changing * the device is quite cheap. * * Exactbounds follows these rules: * *
    *
  • if default pixel is transparent, then exact bounds * of actual pixel data are returned *
  • if default pixel is not transparent, then the union * (defaultBounds()->bounds() | nonDefaultPixelArea()) is * returned *
* \see calculateExactBounds() */ QRect exactBounds() const; /** * Relaxed version of the exactBounds() that can be used in tight * loops. If the exact bounds value is present in the paint * device cache, returns this value. If the cache is invalidated, * returns extent() and tries to recalculate the exact bounds not * faster than once in 1000 ms. */ QRect exactBoundsAmortized() const; /** * Returns exact rectangle of the paint device that contains * non-default pixels. For paint devices with fully transparent * default pixel is equivalent to exactBounds(). * * nonDefaultPixelArea() follows these rules: * *
    *
  • if default pixel is transparent, then exact bounds * of actual pixel data are returned. The same as exactBounds() *
  • if default pixel is not transparent, then calculates the * rectangle of non-default pixels. May be smaller or greater * than image bounds *
* \see calculateExactBounds() */ QRect nonDefaultPixelArea() const; /** * Returns a rough approximation of region covered by device. * For tiled data manager, it region will consist of a number * of rects each corresponding to a tile. */ QRegion region() const; /** * The slow version of region() that searches for exact bounds of * each rectangle in the region */ QRegion regionExact() const; /** * Cut the paint device down to the specified rect. If the crop * area is bigger than the paint device, nothing will happen. */ void crop(qint32 x, qint32 y, qint32 w, qint32 h); /// Convenience method for the above void crop(const QRect & r); /** * Complete erase the current paint device. Its size will become 0. This * does not take the selection into account. */ virtual void clear(); /** * Clear the given rectangle to transparent black. The paint device will expand to * contain the given rect. */ void clear(const QRect & rc); /** * Frees the memory occupied by the pixels containing default * values. The extents() and exactBounds() of the image will * probably also shrink */ void purgeDefaultPixels(); /** * Sets the default pixel. New data will be initialised with this pixel. The pixel is copied: the * caller still owns the pointer and needs to delete it to avoid memory leaks. * If frame ID is given, set default pixel for that frame. Otherwise use active frame. */ void setDefaultPixel(const KoColor &defPixel); /** * Get a pointer to the default pixel. * If the frame parameter is given, get the default pixel of * specified frame. Otherwise use currently active frame. */ KoColor defaultPixel() const; /** * Fill the given rectangle with the given pixel. The paint device will expand to * contain the given rect. */ void fill(const QRect & rc, const KoColor &color); /** * Overloaded function. For legacy purposes only. * Please use fill(const QRect & rc, const KoColor &color) instead */ void fill(qint32 x, qint32 y, qint32 w, qint32 h, const quint8 *fillPixel); public: /** * Prepares the device for fastBitBlt operation. It clears * the device, switches x,y shifts and colorspace if needed. * After this call fastBitBltPossible will return true. * May be used for initialization of temporary devices. */ void prepareClone(KisPaintDeviceSP src); /** * Make this device to become a clone of \a src. It will have the same * x,y shifts, colorspace and will share pixels inside \a rect. * After calling this function: * (this->extent() >= this->exactBounds() == rect). * * Rule of thumb: * * "Use makeCloneFrom() or makeCloneFromRough() if and only if you * are the only owner of the destination paint device and you are * 100% sure no other thread has access to it" */ void makeCloneFrom(KisPaintDeviceSP src, const QRect &rect); /** * Make this device to become a clone of \a src. It will have the same * x,y shifts, colorspace and will share pixels inside \a rect. * Be careful, this function will copy *at least* \a rect * of pixels. Actual copy area will be a bigger - it will * be aligned by tiles borders. So after calling this function: * (this->extent() == this->exactBounds() >= rect). * * Rule of thumb: * * "Use makeCloneFrom() or makeCloneFromRough() if and only if you * are the only owner of the destination paint device and you are * 100% sure no other thread has access to it" */ void makeCloneFromRough(KisPaintDeviceSP src, const QRect &minimalRect); protected: friend class KisPaintDeviceTest; friend class DataReaderThread; /** * Checks whether a src paint device can be used as source * of fast bitBlt operation. The result of the check may * depend on whether color spaces coincide, whether there is * any shift of tiles between the devices and etc. * * WARNING: This check must be done before performing any * fast bitBlt operation! * * \see fastBitBlt * \see fastBitBltRough */ bool fastBitBltPossible(KisPaintDeviceSP src); /** * Clones rect from another paint device. The cloned area will be * shared between both paint devices as much as possible using * copy-on-write. Parts of the rect that cannot be shared * (cross tiles) are deep-copied, * * \see fastBitBltPossible * \see fastBitBltRough */ void fastBitBlt(KisPaintDeviceSP src, const QRect &rect); /** * The same as \ref fastBitBlt() but reads old data */ void fastBitBltOldData(KisPaintDeviceSP src, const QRect &rect); /** * Clones rect from another paint device in a rough and fast way. * All the tiles touched by rect will be shared, between both * devices, that means it will copy a bigger area than was * requested. This method is supposed to be used for bitBlt'ing * into temporary paint devices. * * \see fastBitBltPossible * \see fastBitBlt */ void fastBitBltRough(KisPaintDeviceSP src, const QRect &rect); /** * The same as \ref fastBitBltRough() but reads old data */ void fastBitBltRoughOldData(KisPaintDeviceSP src, const QRect &rect); public: /** * Read the bytes representing the rectangle described by x, y, w, h into * data. If data is not big enough, Krita will gladly overwrite the rest * of your precious memory. * * Since this is a copy, you need to make sure you have enough memory. * * Reading from areas not previously initialized will read the default * pixel value into data but not initialize that region. */ void readBytes(quint8 * data, qint32 x, qint32 y, qint32 w, qint32 h) const; /** * Read the bytes representing the rectangle rect into * data. If data is not big enough, Krita will gladly overwrite the rest * of your precious memory. * * Since this is a copy, you need to make sure you have enough memory. * * Reading from areas not previously initialized will read the default * pixel value into data but not initialize that region. * @param data The address of the memory to receive the bytes read * @param rect The rectangle in the paint device to read from */ void readBytes(quint8 * data, const QRect &rect) const; /** * Copy the bytes in data into the rect specified by x, y, w, h. If the * data is too small or uninitialized, Krita will happily read parts of * memory you never wanted to be read. * * If the data is written to areas of the paint device not previously initialized, * the paint device will grow. */ void writeBytes(const quint8 * data, qint32 x, qint32 y, qint32 w, qint32 h); /** * Copy the bytes in data into the rectangle rect. If the * data is too small or uninitialized, Krita will happily read parts of * memory you never wanted to be read. * * If the data is written to areas of the paint device not previously initialized, * the paint device will grow. * @param data The address of the memory to write bytes from * @param rect The rectangle in the paint device to write to */ void writeBytes(const quint8 * data, const QRect &rect); /** * Copy the bytes in the paint device into a vector of arrays of bytes, * where the number of arrays is the number of channels in the * paint device. If the specified area is larger than the paint * device's extent, the default pixel will be read. */ QVector readPlanarBytes(qint32 x, qint32 y, qint32 w, qint32 h) const; /** * Write the data in the separate arrays to the channes. If there * are less vectors than channels, the remaining channels will not * be copied. If any of the arrays points to 0, the channel in * that location will not be touched. If the specified area is * larger than the paint device, the paint device will be * extended. There are no guards: if the area covers more pixels * than there are bytes in the arrays, krita will happily fill * your paint device with areas of memory you never wanted to be * read. Krita may also crash. * * XXX: what about undo? */ void writePlanarBytes(QVector planes, qint32 x, qint32 y, qint32 w, qint32 h); /** * Converts the paint device to a different colorspace * * @return a command that can be used to undo the conversion. */ KUndo2Command* convertTo(const KoColorSpace * dstColorSpace, KoColorConversionTransformation::Intent renderingIntent = KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::ConversionFlags conversionFlags = KoColorConversionTransformation::internalConversionFlags()); /** * Changes the profile of the colorspace of this paint device to the given * profile. If the given profile is 0, nothing happens. */ bool setProfile(const KoColorProfile * profile); /** * Fill this paint device with the data from image; starting at (offsetX, offsetY) - * @param srcProfileName name of the RGB profile to interpret the image as. 0 is interpreted as sRGB + * @param profile name of the RGB profile to interpret the image as. 0 is interpreted as sRGB */ void convertFromQImage(const QImage& image, const KoColorProfile *profile, qint32 offsetX = 0, qint32 offsetY = 0); /** * Create an RGBA QImage from a rectangle in the paint device. * * @param x Left coordinate of the rectangle * @param y Top coordinate of the rectangle * @param w Width of the rectangle in pixels * @param h Height of the rectangle in pixels * @param dstProfile RGB profile to use in conversion. May be 0, in which * case it's up to the color strategy to choose a profile (most * like sRGB). */ QImage convertToQImage(const KoColorProfile *dstProfile, qint32 x, qint32 y, qint32 w, qint32 h, KoColorConversionTransformation::Intent renderingIntent = KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::ConversionFlags conversionFlags = KoColorConversionTransformation::internalConversionFlags()) const; /** * Overridden method for convenience */ QImage convertToQImage(const KoColorProfile *dstProfile, const QRect &rc, KoColorConversionTransformation::Intent renderingIntent = KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::ConversionFlags conversionFlags = KoColorConversionTransformation::internalConversionFlags()) const; /** * Create an RGBA QImage from a rectangle in the paint device. The * rectangle is defined by the parent image's bounds. * * @param dstProfile RGB profile to use in conversion. May be 0, in which * case it's up to the color strategy to choose a profile (most * like sRGB). */ QImage convertToQImage(const KoColorProfile * dstProfile, KoColorConversionTransformation::Intent renderingIntent = KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::ConversionFlags conversionFlags = KoColorConversionTransformation::internalConversionFlags()) const; /** * Creates a paint device thumbnail of the paint device, retaining * the aspect ratio. The width and height of the returned device * won't exceed \p maxw and \p maxw, but they may be smaller. * - * @param maxw: maximum width - * @param maxh: maximum height - * @param rect: only this rect will be used for the thumbnail + * @param w maximum width + * @param h maximum height + * @param rect only this rect will be used for the thumbnail + * @param outputRect output rectangle * */ KisPaintDeviceSP createThumbnailDevice(qint32 w, qint32 h, QRect rect = QRect(), QRect outputRect = QRect()) const; KisPaintDeviceSP createThumbnailDeviceOversampled(qint32 w, qint32 h, qreal oversample, QRect rect = QRect(), QRect outputRect = QRect()) const; /** * Creates a thumbnail of the paint device, retaining the aspect ratio. * The width and height of the returned QImage won't exceed \p maxw and \p maxw, but they may be smaller. * The colors are not corrected for display! * * @param maxw: maximum width * @param maxh: maximum height * @param rect: only this rect will be used for the thumbnail * @param oversample: ratio used for antialiasing */ QImage createThumbnail(qint32 maxw, qint32 maxh, QRect rect, qreal oversample = 1, KoColorConversionTransformation::Intent renderingIntent = KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::ConversionFlags conversionFlags = KoColorConversionTransformation::internalConversionFlags()); /** * Cached version of createThumbnail(qint32 maxw, qint32 maxh, const KisSelection *selection, QRect rect) */ QImage createThumbnail(qint32 maxw, qint32 maxh, qreal oversample = 1, KoColorConversionTransformation::Intent renderingIntent = KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::ConversionFlags conversionFlags = KoColorConversionTransformation::internalConversionFlags()); /** * Fill c and opacity with the values found at x and y. * * The color values will be transformed from the profile of * this paint device to the display profile. * * @return true if the operation was successful. */ bool pixel(qint32 x, qint32 y, QColor *c) const; /** * Fill kc with the values found at x and y. This method differs * from the above in using KoColor, which can be of any colorspace * * The color values will be transformed from the profile of * this paint device to the display profile. * * @return true if the operation was successful. */ bool pixel(qint32 x, qint32 y, KoColor * kc) const; /** * Set the specified pixel to the specified color. Note that this * bypasses KisPainter. the PaintDevice is here used as an equivalent * to QImage, not QPixmap. This means that this is not undoable; also, * there is no compositing with an existing value at this location. * * The color values will be transformed from the display profile to * the paint device profile. * * Note that this will use 8-bit values and may cause a significant * degradation when used on 16-bit or hdr quality images. * * @return true if the operation was successful */ bool setPixel(qint32 x, qint32 y, const QColor& c); /// Convenience method for the above bool setPixel(qint32 x, qint32 y, const KoColor& kc); /** * @return the colorspace of the pixels in this paint device */ const KoColorSpace* colorSpace() const; /** * There is quite a common technique in Krita. It is used in * cases, when we want to paint something over a paint device * using the composition, opacity or selection. E.g. painting a * dab in a paint op, filling the selection in the Fill Tool. * Such work is usually done in the following way: * * 1) Create a paint device * * 2) Fill it with the desired color or data * * 3) Create a KisPainter and set all the properties of the * transaction: selection, compositeOp, opacity and etc. * * 4) Paint a newly created paint device over the destination * device. * * The following two methods (createCompositionSourceDevice() or * createCompositionSourceDeviceFixed())should be used for the * accomplishing the step 1). The point is that the desired color * space of the temporary device may not coincide with the color * space of the destination. That is the case, for example, for * the alpha8() colorspace used in the selections. So for such * devices the temporary target would have a different (grayscale) * color space. * * So there are two rules of thumb: * * 1) If you need a temporary device which you are going to fill * with some data and then paint over the paint device, create * it with either createCompositionSourceDevice() or * createCompositionSourceDeviceFixed(). * * 2) Do *not* expect that the color spaces of the destination and * the temporary device would coincide. If you need to copy a * single pixel from one device to another, you can use * KisCrossDeviceColorPicker class, that will handle all the * necessary conversions for you. * * \see createCompositionSourceDeviceFixed() * \see compositionSourceColorSpace() * \see KisCrossDeviceColorPicker * \see KisCrossDeviceColorPickerInt */ KisPaintDeviceSP createCompositionSourceDevice() const; /** * The same as createCompositionSourceDevice(), but initializes the * newly created device with the content of \p cloneSource * * \see createCompositionSourceDevice() */ KisPaintDeviceSP createCompositionSourceDevice(KisPaintDeviceSP cloneSource) const; /** * The same as createCompositionSourceDevice(), but initializes * the newly created device with the *rough* \p roughRect of * \p cloneSource. * * "Rough rect" means that it may copy a bit more than * requested. It is expected that the caller will not use the area * outside \p roughRect. * * \see createCompositionSourceDevice() */ KisPaintDeviceSP createCompositionSourceDevice(KisPaintDeviceSP cloneSource, const QRect roughRect) const; /** * This is a convenience method for createCompositionSourceDevice() * * \see createCompositionSourceDevice() */ KisFixedPaintDeviceSP createCompositionSourceDeviceFixed() const; /** * This is a lowlevel method for the principle used in * createCompositionSourceDevice(). In most of the cases the paint * device creation methods should be used instead of this function. * * \see createCompositionSourceDevice() * \see createCompositionSourceDeviceFixed() */ virtual const KoColorSpace* compositionSourceColorSpace() const; /** * @return the internal datamanager that keeps the pixels. */ KisDataManagerSP dataManager() const; /** * Replace the pixel data, color strategy, and profile. */ void setDataManager(KisDataManagerSP data, const KoColorSpace * colorSpace = 0); /** * Return the number of bytes a pixel takes. */ quint32 pixelSize() const; /** * Return the number of channels a pixel takes */ quint32 channelCount() const; /** * Create a keyframe channel for the content on this device. * @param id identifier for the channel - * @param node the parent node for the channel * @return keyframe channel or 0 if there is not one */ KisRasterKeyframeChannel *createKeyframeChannel(const KoID &id); KisRasterKeyframeChannel* keyframeChannel() const; /** * An interface to modify/load/save frames stored inside this device */ KisPaintDeviceFramesInterface* framesInterface(); public: /** * Add the specified rect to the parent layer's set of dirty rects * (if there is a parent layer) */ void setDirty(const QRect & rc); /** * Add the specified region to the parent layer's dirty region * (if there is a parent layer) */ void setDirty(const QRegion & region); /** * Set the parent layer completely dirty, if this paint device has * as parent layer. */ void setDirty(); void setDirty(const QVector rects); /** * Called by KisTransactionData when it thinks current time should * be changed. And the requests is forwarded to the image if * needed. */ void requestTimeSwitch(int time); /** * \return a sequence number corresponding to the current paint * device state. Every time the paint device is changed, * the sequence number is increased */ int sequenceNumber() const; void estimateMemoryStats(qint64 &imageData, qint64 &temporaryData, qint64 &lodData) const; public: KisHLineIteratorSP createHLineIteratorNG(qint32 x, qint32 y, qint32 w); KisHLineConstIteratorSP createHLineConstIteratorNG(qint32 x, qint32 y, qint32 w) const; KisVLineIteratorSP createVLineIteratorNG(qint32 x, qint32 y, qint32 h); KisVLineConstIteratorSP createVLineConstIteratorNG(qint32 x, qint32 y, qint32 h) const; KisRandomAccessorSP createRandomAccessorNG(qint32 x, qint32 y); KisRandomConstAccessorSP createRandomConstAccessorNG(qint32 x, qint32 y) const; /** * Create an iterator that will "artificially" extend the paint device with the * value of the border when trying to access values outside the range of data. * - * @param rc indicates the rectangle that truly contains data + * @param _dataWidth indicates the rectangle that truly contains data */ KisRepeatHLineConstIteratorSP createRepeatHLineConstIterator(qint32 x, qint32 y, qint32 w, const QRect& _dataWidth) const; /** * Create an iterator that will "artificially" extend the paint device with the * value of the border when trying to access values outside the range of data. * - * @param rc indicates the rectangle that truly contains data + * @param _dataWidth indicates the rectangle that truly contains data */ KisRepeatVLineConstIteratorSP createRepeatVLineConstIterator(qint32 x, qint32 y, qint32 h, const QRect& _dataWidth) const; /** * This function create a random accessor which can easily access to sub pixel values. - * @param selection an up-to-date selection that has the same origin as the paint device */ KisRandomSubAccessorSP createRandomSubAccessor() const; /** Clear the selected pixels from the paint device */ void clearSelection(KisSelectionSP selection); Q_SIGNALS: void profileChanged(const KoColorProfile * profile); void colorSpaceChanged(const KoColorSpace *colorspace); public: friend class PaintDeviceCache; /** * Caclculates exact bounds of the device. Used internally * by a transparent caching system. The solution is very slow * because it does a linear scanline search. So the complexity * is n*n at worst. * * \see exactBounds(), nonDefaultPixelArea() */ QRect calculateExactBounds(bool nonDefaultOnly) const; public: struct MemoryReleaseObject : public QObject { ~MemoryReleaseObject() override; }; static MemoryReleaseObject* createMemoryReleaseObject(); public: struct LodDataStruct { virtual ~LodDataStruct(); }; QRegion regionForLodSyncing() const; LodDataStruct* createLodDataStruct(int lod); void updateLodDataStruct(LodDataStruct *dst, const QRect &srcRect); void uploadLodDataStruct(LodDataStruct *dst); void generateLodCloneDevice(KisPaintDeviceSP dst, const QRect &originalRect, int lod); void setProjectionDevice(bool value); void tesingFetchLodDevice(KisPaintDeviceSP targetDevice); private: KisPaintDevice& operator=(const KisPaintDevice&); void init(const KoColorSpace *colorSpace, KisDefaultBoundsBaseSP defaultBounds, KisNodeWSP parent, const QString& name); // Only KisPainter is allowed to have access to these low-level methods friend class KisPainter; /** * Return a vector with in order the size in bytes of the channels * in the colorspace of this paint device. */ QVector channelSizes() const; void emitColorSpaceChanged(); void emitProfileChanged(); private: friend class KisPaintDeviceFramesInterface; protected: friend class KisSelectionTest; KisNodeWSP parentNode() const; private: struct Private; Private * const m_d; }; #endif // KIS_PAINT_DEVICE_IMPL_H_ diff --git a/libs/image/kis_paint_device_frames_interface.h b/libs/image/kis_paint_device_frames_interface.h index bf5f6f33bb..78e4b744c2 100644 --- a/libs/image/kis_paint_device_frames_interface.h +++ b/libs/image/kis_paint_device_frames_interface.h @@ -1,154 +1,154 @@ /* * Copyright (c) 2015 Dmitry Kazakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __KIS_PAINT_DEVICE_FRAMES_INTERFACE_H #define __KIS_PAINT_DEVICE_FRAMES_INTERFACE_H #include "kis_types.h" #include "kritaimage_export.h" class KisPaintDeviceData; class KisPaintDeviceWriter; class KisDataManager; typedef KisSharedPtr KisDataManagerSP; class KRITAIMAGE_EXPORT KisPaintDeviceFramesInterface { public: KisPaintDeviceFramesInterface(KisPaintDevice *parentDevice); /** * Return a list of IDs for the frames contained in this paint device * @return list of frame IDs */ QList frames(); /** * Creates a new frame on the device and returns an identifier for it. * @return frame id of the newly created frame */ int createFrame(bool copy, int copySrc, const QPoint &offset, KUndo2Command *parentCommand); /** * Delete the frame with given id * @param frame frame ID */ void deleteFrame(int frame, KUndo2Command *parentCommand); /** * Copy the given frame into the target device * @param frameId ID of the frame to be copied * @param targetDevice paint device to copy to */ void fetchFrame(int frameId, KisPaintDeviceSP targetDevice); /** * Copy the given paint device contents into the specified frame - * @param dstFrameId ID of the frame to be overwritten (must exist) * @param srcFrameId ID of the frame to copy from (must exist) - * @param sourceDevice paint device to copy from + * @param dstFrameId ID of the frame to be overwritten (must exist) + * @param srcDevice paint device to copy from */ void uploadFrame(int srcFrameId, int dstFrameId, KisPaintDeviceSP srcDevice); /** * Copy the given paint device contents into the specified frame * @param dstFrameId ID of the frame to be overwritten (must exist) - * @param sourceDevice paint device to copy from + * @param srcDevice paint device to copy from */ void uploadFrame(int dstFrameId, KisPaintDeviceSP srcDevice); /** * @return extent() of \p frameId */ QRect frameBounds(int frameId); /** * @return offset of a data on \p frameId */ QPoint frameOffset(int frameId) const; /** * Sets default pixel for \p frameId */ void setFrameDefaultPixel(const KoColor &defPixel, int frameId); /** * @return default pixel for \p frameId */ KoColor frameDefaultPixel(int frameId) const; /** * Write a \p frameId onto \p store */ bool writeFrame(KisPaintDeviceWriter &store, int frameId); /** * Loads content of a \p frameId from \p stream. * * NOTE: the frame must be created manually with createFrame() * beforehand! */ bool readFrame(QIODevice *stream, int frameId); /** * Returns frameId of the currently active frame. * Should be used by Undo framework only! */ int currentFrameId() const; /** * Returns the data manager of the specified frame. * Should be used by Undo framework only! */ KisDataManagerSP frameDataManager(int frameId) const; /** * Resets the cache object associated with the frame. * Should be used by Undo framework only! */ void invalidateFrameCache(int frameId); /** * Sets the offset for \p frameId. * Should be used by Undo framework only! */ void setFrameOffset(int frameId, const QPoint &offset); struct TestingDataObjects { typedef KisPaintDeviceData Data; typedef QHash FramesHash; Data *m_data; Data *m_lodData; Data *m_externalFrameData; FramesHash m_frames; Data *m_currentData; }; TestingDataObjects testingGetDataObjects() const; QList testingGetDataObjectsList() const; private: KisPaintDevice *q; }; #endif /* __KIS_PAINT_DEVICE_FRAMES_INTERFACE_H */ diff --git a/libs/image/kis_painter.h b/libs/image/kis_painter.h index 46c02ccf7c..9f0ffbd27c 100644 --- a/libs/image/kis_painter.h +++ b/libs/image/kis_painter.h @@ -1,879 +1,880 @@ /* * Copyright (c) 2002 Patrick Julien * Copyright (c) 2004 Clarence Dang * Copyright (c) 2008-2010 Lukáš Tvrdý * Copyright (c) 2010 José Luis Vergara Toloza * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_PAINTER_H_ #define KIS_PAINTER_H_ #include #include #include #include #include "kundo2magicstring.h" #include "kis_types.h" #include #include class QPen; class KUndo2Command; class QRect; class QRectF; class QBitArray; class QPainterPath; class KoAbstractGradient; class KoUpdater; class KoColor; class KoCompositeOp; class KisUndoAdapter; class KisPostExecutionUndoAdapter; class KisTransaction; class KoPattern; class KisPaintInformation; class KisPaintOp; class KisDistanceInformation; struct KisRenderedDab; class KisRunnableStrokeJobsInterface; /** * KisPainter contains the graphics primitives necessary to draw on a * KisPaintDevice. This is the same kind of abstraction as used in Qt * itself, where you have QPainter and QPaintDevice. * * However, KisPainter works on a tiled image and supports different * color models, and that's a lot more complicated. * * KisPainter supports transactions that can group various paint operations * in one undoable step. * * For more complex operations, you might want to have a look at the subclasses * of KisPainter: KisConvolutionPainter, KisFillPainter and KisGradientPainter * * KisPainter sets a number of default values, like COMPOSITE_OVER for compositeop, * OPACITY_OPAQUE for opacity and no selection for selection. */ class KRITAIMAGE_EXPORT KisPainter { public: /// Construct painter without a device KisPainter(); /// Construct a painter, and begin painting on the device KisPainter(KisPaintDeviceSP device); /// Construct a painter, and begin painting on the device. All actions will be masked by the given selection. KisPainter(KisPaintDeviceSP device, KisSelectionSP selection); virtual ~KisPainter(); public: static void copyAreaOptimized(const QPoint &dstPt, KisPaintDeviceSP src, KisPaintDeviceSP dst, const QRect &originalSrcRect); static void copyAreaOptimizedOldData(const QPoint &dstPt, KisPaintDeviceSP src, KisPaintDeviceSP dst, const QRect &originalSrcRect); static void copyAreaOptimized(const QPoint &dstPt, KisPaintDeviceSP src, KisPaintDeviceSP dst, const QRect &originalSrcRect, KisSelectionSP selection); static KisPaintDeviceSP convertToAlphaAsAlpha(KisPaintDeviceSP src); static KisPaintDeviceSP convertToAlphaAsGray(KisPaintDeviceSP src); static bool checkDeviceHasTransparency(KisPaintDeviceSP dev); /** * Start painting on the specified device. Not undoable. */ void begin(KisPaintDeviceSP device); /** * Start painting on the specified paint device. All actions will be masked by the given selection. */ void begin(KisPaintDeviceSP device, KisSelectionSP selection); /** * Finish painting on the current device */ void end(); /** * If set, the painter action is cancelable, if the action supports that. */ void setProgress(KoUpdater * progressUpdater); /// Begin an undoable paint operation void beginTransaction(const KUndo2MagicString& transactionName = KUndo2MagicString(),int timedID = -1); /// Cancel all the changes made by the painter void revertTransaction(); /// Finish the undoable paint operation void endTransaction(KisUndoAdapter *undoAdapter); /** * Finish transaction and load it to a special adapter for strokes */ void endTransaction(KisPostExecutionUndoAdapter *undoAdapter); /** * Finishes a transaction and returns a pointer to its undo command */ KUndo2Command* endAndTakeTransaction(); /** * Finish the transaction and delete it's undo information. * NOTE: Be careful, because all the previous transactions * will become non-undoable after execution of this method. */ void deleteTransaction(); /// continue a transaction started somewhere else void putTransaction(KisTransaction* transaction); /// take transaction out of the reach of KisPainter KisTransaction* takeTransaction(); /// Returns the current paint device. const KisPaintDeviceSP device() const; KisPaintDeviceSP device(); /** * Blast a region of srcWidth @param srcWidth and srcHeight @param srcHeight from @param * srcDev onto the current paint device. @param srcX and @param srcY set the x and y * positions of the origin top-left corner, @param dstX and @param dstY those of * the destination. * Any pixel read outside the limits of @param srcDev will return the * default pixel, this is a property of \ref KisPaintDevice. * * @param dstX the destination x-coordinate * @param dstY the destination y-coordinate * @param srcDev the source device * @param srcX the source x-coordinate * @param srcY the source y-coordinate * @param srcWidth the width of the region to be manipulated * @param srcHeight the height of the region to be manipulated */ void bitBlt(qint32 dstX, qint32 dstY, const KisPaintDeviceSP srcDev, qint32 srcX, qint32 srcY, qint32 srcWidth, qint32 srcHeight); /** * Convenience method that uses QPoint and QRect. * - * @param pos the destination coordinate, it replaces @param dstX and @param dstY. + * @param pos the destination coordinate, it replaces @p dstX and @p dstY. * @param srcDev the source device. - * @param srcRect the rectangle describing the area to blast from @param srcDev into the current paint device. - * @param srcRect replaces @param srcX, @param srcY, @param srcWidth and @param srcHeight. + * @param srcRect the rectangle describing the area to blast from @p srcDev into the current paint device. + * @p srcRect replaces @p srcX, @p srcY, @p srcWidth and @p srcHeight. * */ void bitBlt(const QPoint & pos, const KisPaintDeviceSP srcDev, const QRect & srcRect); /** * The same as @ref bitBlt() but reads data from oldData() part of the device * * @param dstX the destination x-coordinate * @param dstY the destination y-coordinate * @param srcDev the source device * @param srcX the source x-coordinate * @param srcY the source y-coordinate * @param srcWidth the width of the region to be manipulated * @param srcHeight the height of the region to be manipulated */ void bitBltOldData(qint32 dstX, qint32 dstY, const KisPaintDeviceSP srcDev, qint32 srcX, qint32 srcY, qint32 srcWidth, qint32 srcHeight); /** * Convenience method that uses QPoint and QRect. * - * @param pos the destination coordinate, it replaces @param dstX and @param dstY. + * @param pos the destination coordinate, it replaces @p dstX and @p dstY. * @param srcDev the source device. * @param srcRect the rectangle describing the area to blast from @param srcDev into the current paint device. - * @param srcRect replaces @param srcX, @param srcY, @param srcWidth and @param srcHeight. + * @p srcRect replaces @p srcX, @p srcY, @p srcWidth and @p srcHeight. * */ void bitBltOldData(const QPoint & pos, const KisPaintDeviceSP srcDev, const QRect & srcRect); /** * Blasts a @param selection of srcWidth @param srcWidth and srcHeight @param srcHeight * of @param srcDev on the current paint device. There is parameters * to control where the area begins in each distinct device, explained below. * @param selection can be used as a mask to shape @param srcDev to * something interesting in the same step it is rendered to the current * paint device. @param selection 's colorspace must be alpha8 (the * colorspace for selections/transparency), the rectangle formed by * @param selX, @param selY, @param srcWidth and @param srcHeight must not go * beyond its limits, and they must be different from zero. * @param selection and KisPainter's selection (the user selection) are * fused together through the composite operation COMPOSITE_MULT. * Any pixel read outside the limits of @param srcDev will return the * default pixel, this is a property of \ref KisPaintDevice. * * @param dstX the destination x-coordinate * @param dstY the destination y-coordinate * @param srcDev the source device * @param selection the custom selection to apply on the source device * @param selX the selection x-coordinate * @param selY the selection y-coordinate * @param srcX the source x-coordinate * @param srcY the source y-coordinate * @param srcWidth the width of the region to be manipulated * @param srcHeight the height of the region to be manipulated * */ void bitBltWithFixedSelection(qint32 dstX, qint32 dstY, const KisPaintDeviceSP srcDev, const KisFixedPaintDeviceSP selection, qint32 selX, qint32 selY, qint32 srcX, qint32 srcY, qint32 srcWidth, qint32 srcHeight); /** - * Convenience method that assumes @param selX, @param selY, @param srcX and @param srcY are - * equal to 0. Best used when @param selection and the desired area of @param srcDev have exactly + * Convenience method that assumes @p selX, @p selY, @p srcX and @p srcY are + * equal to 0. Best used when @p selection and the desired area of @p srcDev have exactly * the same dimensions and are specially made for each other. * * @param dstX the destination x-coordinate * @param dstY the destination y-coordinate * @param srcDev the source device * @param selection the custom selection to apply on the source device * @param srcWidth the width of the region to be manipulated * @param srcHeight the height of the region to be manipulated */ void bitBltWithFixedSelection(qint32 dstX, qint32 dstY, const KisPaintDeviceSP srcDev, const KisFixedPaintDeviceSP selection, qint32 srcWidth, qint32 srcHeight); /** * Blast a region of srcWidth @param srcWidth and srcHeight @param srcHeight from @param srcDev onto the current * paint device. @param srcX and @param srcY set the x and y positions of the * origin top-left corner, @param dstX and @param dstY those of the destination. * @param srcDev is a \ref KisFixedPaintDevice: this means that @param srcDev must have the same * colorspace as the destination device. * * @param dstX the destination x-coordinate * @param dstY the destination y-coordinate * @param srcDev the source device * @param srcX the source x-coordinate * @param srcY the source y-coordinate * @param srcWidth the width of the region to be manipulated * @param srcHeight the height of the region to be manipulated */ void bltFixed(qint32 dstX, qint32 dstY, const KisFixedPaintDeviceSP srcDev, qint32 srcX, qint32 srcY, qint32 srcWidth, qint32 srcHeight); /** * Render the area \p rc from \p srcDevices on the destination device. * If \p rc doesn't cross the device's rect, then the device is not * rendered at all. */ void bltFixed(const QRect &rc, const QList allSrcDevices); /** * Convenience method that uses QPoint and QRect. * - * @param pos the destination coordinate, it replaces @param dstX and @param dstY. + * @param pos the destination coordinate, it replaces @p dstX and @p dstY. * @param srcDev the source device. - * @param srcRect the rectangle describing the area to blast from @param srcDev into the current paint device. - * @param srcRect replaces @param srcX, @param srcY, @param srcWidth and @param srcHeight. + * @param srcRect the rectangle describing the area to blast from @p srcDev into the current paint device. + * @param srcRect replaces @p srcX, @p srcY, @p srcWidth and @p srcHeight. * */ void bltFixed(const QPoint & pos, const KisFixedPaintDeviceSP srcDev, const QRect & srcRect); /** * Blasts a @param selection of srcWidth @param srcWidth and srcHeight @param srcHeight * of @param srcDev on the current paint device. There is parameters to control * the top-left corner of the area in each respective paint device (@param dstX, * @param dstY, @param srcX, @param srcY). * @param selection can be used as a mask to shape @param srcDev to something * interesting in the same step it is rendered to the current paint device. * @param srcDev is a \ref KisFixedPaintDevice: this means that @param srcDev * must have the same colorspace as the destination device. * @param selection 's colorspace must be alpha8 (the colorspace for * selections/transparency). * The rectangle formed by the respective top-left coordinates of each device * and @param srcWidth and @param srcHeight must not go beyond their limits, and * they must be different from zero. * @param selection and KisPainter's selection (the user selection) are * fused together through the composite operation COMPOSITE_MULT. * * @param dstX the destination x-coordinate * @param dstY the destination y-coordinate * @param srcDev the source device * @param selection the selection stored in fixed device * @param selX the selection x-coordinate * @param selY the selection y-coordinate * @param srcX the source x-coordinate * @param srcY the source y-coordinate * @param srcWidth the width of the region to be manipulated * @param srcHeight the height of the region to be manipulated */ void bltFixedWithFixedSelection(qint32 dstX, qint32 dstY, const KisFixedPaintDeviceSP srcDev, const KisFixedPaintDeviceSP selection, qint32 selX, qint32 selY, qint32 srcX, qint32 srcY, quint32 srcWidth, quint32 srcHeight); /** - * Convenience method that assumes @param selX, @param selY, @param srcX and @param srcY are - * equal to 0. Best used when @param selection and @param srcDev have exactly the same + * Convenience method that assumes @p selX, @p selY, @p srcX and @p srcY are + * equal to 0. Best used when @p selection and @p srcDev have exactly the same * dimensions and are specially made for each other. * * @param dstX the destination x-coordinate * @param dstY the destination y-coordinate * @param srcDev the source device * @param selection the custom selection to apply on the source device * @param srcWidth the width of the region to be manipulated * @param srcHeight the height of the region to be manipulated */ void bltFixedWithFixedSelection(qint32 dstX, qint32 dstY, const KisFixedPaintDeviceSP srcDev, const KisFixedPaintDeviceSP selection, quint32 srcWidth, quint32 srcHeight); /** - * fills a region of width @param width and height @param height of the current - * paint device with the color @param color. @param x and @param y set the x and y positions of the + * fills a region of width @p width and height @p height of the current + * paint device with the color @p color. @p x and @p y set the x and y positions of the * origin top-left corner. * * @param x the destination x-coordinate * @param y the destination y-coordinate * @param width the width of the region to be manipulated * @param height the height of the region to be manipulated * @param color the color the area is filled with */ void fill(qint32 x, qint32 y, qint32 width, qint32 height, const KoColor& color); /** * First you need to setup the painter with setMirrorInformation, * then these set of methods provide way to render the devices mirrored * according the axesCenter vertically or horizontally or both. * * @param rc rectangle area covered by dab * @param dab this device will be mirrored in-place, it means that it will be changed */ void renderMirrorMask(QRect rc, KisFixedPaintDeviceSP dab); void renderMirrorMask(QRect rc, KisFixedPaintDeviceSP dab, KisFixedPaintDeviceSP mask); void renderMirrorMask(QRect rc, KisPaintDeviceSP dab); void renderMirrorMask(QRect rc, KisPaintDeviceSP dab, int sx, int sy, KisFixedPaintDeviceSP mask); /** * Convenience method for renderMirrorMask(), allows to choose whether * we need to preserve out dab or do the transformations in-place. * * @param rc rectangle area covered by dab * @param dab the device to render * @param preserveDab states whether a temporary device should be * created to do the transformations */ void renderMirrorMaskSafe(QRect rc, KisFixedPaintDeviceSP dab, bool preserveDab); /** * Convenience method for renderMirrorMask(), allows to choose whether * we need to preserve our fixed mask or do the transformations in-place. * * @param rc rectangle area covered by dab * @param dab the device to render * @param mask mask to use for rendering * @param preserveMask states whether a temporary device should be * created to do the transformations */ void renderMirrorMaskSafe(QRect rc, KisPaintDeviceSP dab, int sx, int sy, KisFixedPaintDeviceSP mask, bool preserveMask); /** * A complex method that re-renders a dab on an \p rc area. * The \p rc area and all the dedicated mirroring areas are cleared * before the painting, so this method should be used by paintops * which do not update the canvas incrementally, but instead * regenerate some internal cache \p dab with the COMPOSITE_COPY op. * * \see KisExperimentPaintOp */ void renderDabWithMirroringNonIncremental(QRect rc, KisPaintDeviceSP dab); /** * @return true if the painter has some rects marked as dirty * @see takeDirtyRegion(), addDirtyRect() */ bool hasDirtyRegion() const; /** * The methods in this class do not tell the paintdevice to update, but they calculate the * dirty area. This method returns this dirty area and resets it. */ QVector takeDirtyRegion(); /** * Paint a line that connects the dots in points */ void paintPolyline(const QVector &points, int index = 0, int numPoints = -1); /** * Draw a line between pos1 and pos2 using the currently set brush and color. * If savedDist is less than zero, the brush is painted at pos1 before being * painted along the line using the spacing setting. * @return the drag distance, that is the remains of the distance between p1 and p2 not covered * because the currently set brush has a spacing greater than that distance. */ void paintLine(const KisPaintInformation &pi1, const KisPaintInformation &pi2, KisDistanceInformation *currentDistance); /** * Draw a Bezier curve between pos1 and pos2 using control points 1 and 2. * If savedDist is less than zero, the brush is painted at pos1 before being * painted along the curve using the spacing setting. * @return the drag distance, that is the remains of the distance between p1 and p2 not covered * because the currently set brush has a spacing greater than that distance. */ void paintBezierCurve(const KisPaintInformation &pi1, const QPointF &control1, const QPointF &control2, const KisPaintInformation &pi2, KisDistanceInformation *currentDistance); /** * Fill the given vector points with the points needed to draw the Bezier curve between * pos1 and pos2 using control points 1 and 2, excluding the final pos2. */ void getBezierCurvePoints(const QPointF &pos1, const QPointF &control1, const QPointF &control2, const QPointF &pos2, vQPointF& points) const; /** * Paint a rectangle. * @param rect the rectangle to paint. */ void paintRect(const QRectF &rect); /** * Paint a rectangle. * * @param x x coordinate of the top-left corner * @param y y coordinate of the top-left corner * @param w the rectangle width * @param h the rectangle height */ void paintRect(const qreal x, const qreal y, const qreal w, const qreal h); /** * Paint the ellipse that fills the given rectangle. * * @param rect the rectangle containing the ellipse to paint. */ void paintEllipse(const QRectF &rect); /** * Paint the ellipse that fills the given rectangle. * * @param x x coordinate of the top-left corner * @param y y coordinate of the top-left corner * @param w the rectangle width * @param h the rectangle height */ void paintEllipse(const qreal x, const qreal y, const qreal w, const qreal h); /** * Paint the polygon with the points given in points. It automatically closes the polygon * by drawing the line from the last point to the first. */ void paintPolygon(const vQPointF& points); /** Draw a spot at pos using the currently set paint op, brush and color */ void paintAt(const KisPaintInformation &pos, KisDistanceInformation *savedDist); /** * Stroke the given QPainterPath. */ void paintPainterPath(const QPainterPath& path); /** * Fills the area enclosed by the given QPainterPath * Convenience method for fillPainterPath(path, rect) */ void fillPainterPath(const QPainterPath& path); /** * Fills the portion of an area enclosed by the given QPainterPath * - * \param rect the portion of the path to fill + * \param path the portion of the path to fill + * \param requestedRect the rectangle containing the area */ void fillPainterPath(const QPainterPath& path, const QRect &requestedRect); /** * Draw the path using the Pen * * if \p requestedRect is null, the entire path is painted */ void drawPainterPath(const QPainterPath& path, const QPen& pen, const QRect &requestedRect); // convenience overload void drawPainterPath(const QPainterPath& path, const QPen& pen); /** * paint an unstroked one-pixel wide line from specified start position to the * specified end position. * */ void drawLine(const QPointF & start, const QPointF & end); /** * paint an unstroked line with thickness from specified start position to the * specified end position. Scanline algorithm is used. */ void drawLine(const QPointF &start, const QPointF &end, qreal width, bool antialias); /** * paints an unstroked, aliased one-pixel line using the DDA algorithm from specified start position to the * specified end position. * */ void drawDDALine(const QPointF & start, const QPointF & end); /** * Paint an unstroked, wobbly one-pixel wide line from the specified start to the specified * end position. * */ void drawWobblyLine(const QPointF & start, const QPointF & end); /** * Paint an unstroked, anti-aliased one-pixel wide line from the specified start to the specified * end position using the Wu algorithm */ void drawWuLine(const QPointF & start, const QPointF & end); /** * Paint an unstroked wide line from the specified start to the specified - * end position with width varying from @param w1 at the start to @param w2 at + * end position with width varying from @p start at the start to @p end at * the end. * * XXX: the width should be set in doubles, not integers. */ void drawThickLine(const QPointF & start, const QPointF & end, int startWidth, int endWidth); /** * Set the channelflags: a bit array where true means that the * channel corresponding in position with the bit will be read * by the operation, and false means that it will not be affected. * * An empty channelFlags parameter means that all channels are * affected. * - * @param the bit array that masks the source channels; only + * @param channelFlags the bit array that masks the source channels; only * the channels where the corresponding bit is true will will be * composited onto the destination device. */ void setChannelFlags(QBitArray channelFlags); /// @return the channel flags QBitArray channelFlags(); /** - * Set the paintop preset to use. If @param image is given, + * Set the paintop preset to use. If @p image is given, * the paintop will be created using this image as parameter. * Some paintops really want to know about the image they work * for, e.g. the clone paintop. */ void setPaintOpPreset(KisPaintOpPresetSP preset, KisNodeSP node, KisImageSP image); /// Return the paintop preset KisPaintOpPresetSP preset() const; /** * Return the active paintop (which is created based on the specified preset and * will be deleted as soon as the KisPainter instance dies). */ KisPaintOp* paintOp() const; void setMirrorInformation(const QPointF &axesCenter, bool mirrorHorizontally, bool mirrorVertically); void copyMirrorInformationFrom(const KisPainter *other); /** * Returns whether the mirroring methods will do any * work when called */ bool hasMirroring() const; /** * Indicates if horizontal mirroring mode is activated */ bool hasHorizontalMirroring() const; /** * Indicates if vertical mirroring mode is activated */ bool hasVerticalMirroring() const; /** * Mirror \p rc in the requested \p direction around the center point defined * in the painter. */ void mirrorRect(Qt::Orientation direction, QRect *rc) const; /** * Mirror \p dab in the requested direction around the center point defined * in the painter. The dab's offset is adjusted automatically. */ void mirrorDab(Qt::Orientation direction, KisRenderedDab *dab) const; /** * Calculate the list of the mirrored rects that will be painted on the * the canvas when calling renderMirrorMask() at al */ const QVector calculateAllMirroredRects(const QRect &rc); /// Set the current pattern void setPattern(const KoPattern * pattern); /// Returns the currently set pattern const KoPattern * pattern() const; /** * Set the color that will be used to paint with, and convert it * to the color space of the current paint device. */ void setPaintColor(const KoColor& color); /// Returns the color that will be used to paint with const KoColor &paintColor() const; /** * Set the current background color, and convert it * to the color space of the current paint device. */ void setBackgroundColor(const KoColor& color); /// Returns the current background color const KoColor &backgroundColor() const; /// Set the current generator (a generator can be used to fill an area void setGenerator(KisFilterConfigurationSP generator); /// @return the current generator configuration const KisFilterConfigurationSP generator() const; /// This enum contains the styles with which we can fill things like polygons and ellipses enum FillStyle { FillStyleNone, FillStyleForegroundColor, FillStyleBackgroundColor, FillStylePattern, FillStyleGradient, FillStyleStrokes, FillStyleGenerator, }; /// Set the current style with which to fill void setFillStyle(FillStyle fillStyle); /// Returns the current fill style FillStyle fillStyle() const; /// Set whether a polygon's filled area should be anti-aliased or not. The default is true. void setAntiAliasPolygonFill(bool antiAliasPolygonFill); /// Return whether a polygon's filled area should be anti-aliased or not bool antiAliasPolygonFill(); /// The style of the brush stroke around polygons and so enum StrokeStyle { StrokeStyleNone, StrokeStyleBrush }; /// Set the current brush stroke style void setStrokeStyle(StrokeStyle strokeStyle); /// Returns the current brush stroke style StrokeStyle strokeStyle() const; void setFlow(quint8 flow); quint8 flow() const; /** * Sets the opacity of the painting and recalculates the * mean opacity of the stroke. This mean value is used to * make ALPHA_DARKEN painting look correct */ void setOpacityUpdateAverage(quint8 opacity); /** * Sets average opacity, that is used to make ALPHA_DARKEN painting look correct */ void setAverageOpacity(qreal averageOpacity); /** * Calculate average opacity value after painting a single dab with \p opacity */ static qreal blendAverageOpacity(qreal opacity, qreal averageOpacity); /// Set the opacity which is used in painting (like filling polygons) void setOpacity(quint8 opacity); /// Returns the opacity that is used in painting quint8 opacity() const; /// Set the composite op for this painter void setCompositeOp(const KoCompositeOp * op); const KoCompositeOp * compositeOp(); /// Set the composite op for this painter by string. /// Note: the colorspace must be set previously! void setCompositeOp(const QString& op); /** * Add \p r to the current set of dirty rects */ void addDirtyRect(const QRect &r); /** * Add \p rects to the current set of dirty rects */ void addDirtyRects(const QVector &rects); /** * Reset the selection to the given selection. All painter actions will be * masked by the specified selection. */ void setSelection(KisSelectionSP selection); /** * @return the selection set on this painter. */ KisSelectionSP selection(); void setGradient(const KoAbstractGradient* gradient); const KoAbstractGradient* gradient() const; /** * Set the size of the tile in fillPainterPath, useful when optimizing the use of fillPainterPath * e.g. Spray paintop uses more small tiles, although selections uses bigger tiles. QImage::fill * is quite expensive so with smaller images you can save instructions * Default and maximum size is 256x256 image */ void setMaskImageSize(qint32 width, qint32 height); // /** // * If the alpha channel is locked, the alpha values of the paint device we are painting on // * will not change. // */ // void setLockAlpha(bool protect); // bool alphaLocked() const; /** * set the rendering intent in case pixels need to be converted before painting */ void setRenderingIntent(KoColorConversionTransformation::Intent intent); /** * set the conversion flags in case pixels need to be converted before painting */ void setColorConversionFlags(KoColorConversionTransformation::ConversionFlags conversionFlags); /** * Set interface for running asynchronous jobs by paintops. * * NOTE: the painter does *not* own the interface device. It is the responsibility * of the caller to ensure that the interface object is alive during the lifetime * of the painter. */ void setRunnableStrokeJobsInterface(KisRunnableStrokeJobsInterface *interface); /** * Get the interface for running asynchronous jobs. It is used by paintops mostly. */ KisRunnableStrokeJobsInterface* runnableStrokeJobsInterface() const; protected: /// Initialize, set everything to '0' or defaults void init(); /// Fill the polygon defined by points with the fillStyle void fillPolygon(const vQPointF& points, FillStyle fillStyle); private: KisPainter(const KisPainter&); KisPainter& operator=(const KisPainter&); float frac(float value) { float tmp = 0; return modff(value , &tmp); } float invertFrac(float value) { float tmp = 0; return 1.0f - modff(value , &tmp); } protected: KoUpdater * progressUpdater(); private: template void bitBltImpl(qint32 dstX, qint32 dstY, const KisPaintDeviceSP srcDev, qint32 srcX, qint32 srcY, qint32 srcWidth, qint32 srcHeight); inline void compositeOnePixel(quint8 *dst, const KoColor &color); private: struct Private; Private* const d; }; #endif // KIS_PAINTER_H_ diff --git a/libs/image/kis_repeat_iterators_pixel.h b/libs/image/kis_repeat_iterators_pixel.h index 1c0d18bcc3..1132185fae 100644 --- a/libs/image/kis_repeat_iterators_pixel.h +++ b/libs/image/kis_repeat_iterators_pixel.h @@ -1,268 +1,268 @@ /* * Copyright (c) 2008 Cyrille Berger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _KIS_REPEAT_ITERATORS_PIXEL_H_ #define _KIS_REPEAT_ITERATORS_PIXEL_H_ #include #include "kis_shared.h" #include "tiles3/kis_hline_iterator.h" #include "tiles3/kis_vline_iterator.h" template class KisRepeatHLineIteratorPixelBase; template class KisRepeatVLineIteratorPixelBase; /** * This iterator is an iterator that will "artificially" extend the paint device with the * value of the border when trying to access values outside the range of data. */ template class KisRepeatLineIteratorPixelBase : public KisShared { Q_DISABLE_COPY(KisRepeatLineIteratorPixelBase) public: friend class KisRepeatHLineIteratorPixelBase; friend class KisRepeatVLineIteratorPixelBase; /** - * @param rc indicates the rectangle that truly contains data + * @param _rc indicates the rectangle that truly contains data */ inline KisRepeatLineIteratorPixelBase(KisDataManager *dm, qint32 x, qint32 y, qint32 offsetx, qint32 offsety, const QRect& _rc, KisIteratorCompleteListener *completeListener); virtual inline ~KisRepeatLineIteratorPixelBase(); public: inline qint32 x() const { return m_realX; } inline qint32 y() const { return m_realY; } inline const quint8 * oldRawData() const { return m_iterator->oldRawData(); } private: KisDataManager* m_dm; qint32 m_realX, m_realY; qint32 m_offsetX, m_offsetY; QRect m_dataRect; T* m_iterator; KisIteratorCompleteListener *m_completeListener; }; /** * This iterator is an iterator that will "artificially" extend the paint device with the * value of the border when trying to access values outside the range of data. */ template class KisRepeatHLineIteratorPixelBase : public KisRepeatLineIteratorPixelBase { public: /** - * @param rc indicates the rectangle that truly contains data + * @param _rc indicates the rectangle that truly contains data */ inline KisRepeatHLineIteratorPixelBase(KisDataManager *dm, qint32 x, qint32 y, qint32 w, qint32 offsetx, qint32 offsety, const QRect& _rc, KisIteratorCompleteListener *completeListener); inline ~KisRepeatHLineIteratorPixelBase() override; inline bool nextPixel(); /** * Reach next row. */ inline void nextRow(); private: void createIterator(); private: qint32 m_startX; qint32 m_startIteratorX; qint32 m_width; }; /** * This iterator is an iterator that will "artificially" extend the paint device with the * value of the border when trying to access values outside the range of data. */ template class KisRepeatVLineIteratorPixelBase : public KisRepeatLineIteratorPixelBase { public: /** - * @param rc indicates the rectangle that truly contains data + * @param _rc indicates the rectangle that truly contains data */ inline KisRepeatVLineIteratorPixelBase(KisDataManager *dm, qint32 x, qint32 y, qint32 h, qint32 offsetx, qint32 offsety, const QRect& _rc, KisIteratorCompleteListener *completeListener); inline ~KisRepeatVLineIteratorPixelBase() override; inline KisRepeatVLineIteratorPixelBase & operator ++(); inline bool nextPixel(); /** * Reach next row. */ inline void nextColumn(); private: void createIterator(); private: qint32 m_startY; qint32 m_startIteratorY; qint32 m_height; }; //------------------------ Implementations ------------------------// //---------------- KisRepeatLineIteratorPixelBase -----------------// template KisRepeatLineIteratorPixelBase::KisRepeatLineIteratorPixelBase(KisDataManager *dm, qint32 x, qint32 y, qint32 offsetx, qint32 offsety, const QRect& _rc, KisIteratorCompleteListener *completeListener) : m_dm(dm), m_realX(x), m_realY(y), m_offsetX(offsetx), m_offsetY(offsety), m_dataRect(_rc), m_iterator(0), m_completeListener(completeListener) { } template KisRepeatLineIteratorPixelBase::~KisRepeatLineIteratorPixelBase() { delete m_iterator; } //---------------- KisRepeatHLineIteratorPixelBase ----------------// template KisRepeatHLineIteratorPixelBase::KisRepeatHLineIteratorPixelBase(KisDataManager *dm, qint32 x, qint32 y, qint32 w, qint32 offsetx, qint32 offsety, const QRect& _rc, KisIteratorCompleteListener *completeListener) : KisRepeatLineIteratorPixelBase(dm, x, y, offsetx, offsety , _rc, completeListener), m_startX(x), m_startIteratorX(x), m_width(w) { // Compute the startx value of the iterator if (m_startIteratorX < _rc.left()) { m_startIteratorX = _rc.left(); } createIterator(); } template KisRepeatHLineIteratorPixelBase::~KisRepeatHLineIteratorPixelBase() { } template inline bool KisRepeatHLineIteratorPixelBase::nextPixel() { Q_ASSERT(this->m_iterator); if (this->m_realX >= this->m_dataRect.x() && this->m_realX < this->m_dataRect.x() + this->m_dataRect.width() - 1) { this->m_iterator->nextPixel(); } ++this->m_realX; return (this->m_realX < m_startX + m_width); } template inline void KisRepeatHLineIteratorPixelBase::nextRow() { if (this->m_realY >= this->m_dataRect.y() && this->m_realY < this->m_dataRect.y() + this->m_dataRect.height() - 1) { this->m_iterator->nextRow(); } else { createIterator(); } this->m_realX = this->m_startX; ++this->m_realY; } template void KisRepeatHLineIteratorPixelBase::createIterator() { // Cleanup delete this->m_iterator; qint32 startY = this->m_realY; if (startY < this->m_dataRect.y()) { startY = this->m_dataRect.top(); } if (startY > (this->m_dataRect.y() + this->m_dataRect.height() - 1)) { startY = (this->m_dataRect.y() + this->m_dataRect.height() - 1); } int width = this->m_dataRect.x() + this->m_dataRect.width() - this->m_startIteratorX; this->m_iterator = new T(this->m_dm, this->m_startIteratorX, startY, width, this->m_offsetX, this->m_offsetY, false, this->m_completeListener); this->m_realX = this->m_startX; } //---------------- KisRepeatVLineIteratorPixelBase ----------------// template KisRepeatVLineIteratorPixelBase::KisRepeatVLineIteratorPixelBase(KisDataManager *dm, qint32 x, qint32 y, qint32 h, qint32 offsetx, qint32 offsety, const QRect& _rc, KisIteratorCompleteListener *completeListener) : KisRepeatLineIteratorPixelBase(dm, x, y, offsetx, offsety , _rc, completeListener), m_startY(y), m_startIteratorY(y), m_height(h) { // Compute the startx value of the iterator if (m_startIteratorY < _rc.top()) { m_startIteratorY = _rc.top(); } createIterator(); } template KisRepeatVLineIteratorPixelBase::~KisRepeatVLineIteratorPixelBase() { } template inline bool KisRepeatVLineIteratorPixelBase::nextPixel() { Q_ASSERT(this->m_iterator); if (this->m_realY >= this->m_dataRect.y() && this->m_realY < this->m_dataRect.y() + this->m_dataRect.height() - 1) { this->m_iterator->nextPixel(); } ++this->m_realY; return (this->m_realY < m_startY + m_height); } template inline void KisRepeatVLineIteratorPixelBase::nextColumn() { if (this->m_realX >= this->m_dataRect.x() && this->m_realX < this->m_dataRect.x() + this->m_dataRect.width() - 1) { this->m_iterator->nextColumn(); } else { createIterator(); } this->m_realY = this->m_startY; ++this->m_realX; } template void KisRepeatVLineIteratorPixelBase::createIterator() { // Cleanup delete this->m_iterator; qint32 startX = this->m_realX; if (startX < this->m_dataRect.x()) { startX = this->m_dataRect.x(); } if (startX > (this->m_dataRect.x() + this->m_dataRect.width() - 1)) { startX = (this->m_dataRect.x() + this->m_dataRect.width() - 1); } int height = this->m_dataRect.y() + this->m_dataRect.height() - this->m_startIteratorY; this->m_iterator = new T(this->m_dm, startX, this->m_startIteratorY, height, this->m_offsetX, this->m_offsetY, false, this->m_completeListener); this->m_realY = this->m_startY; } #endif diff --git a/libs/image/kis_transform_worker.h b/libs/image/kis_transform_worker.h index 4a9c6db520..5f849dbc9b 100644 --- a/libs/image/kis_transform_worker.h +++ b/libs/image/kis_transform_worker.h @@ -1,160 +1,160 @@ /* * Copyright (c) 2004 Michael Thaler * Copyright (c) 2005 C. Boemann * Copyright (c) 2010 Marc Pegon * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_TRANSFORM_WORKER_H_ #define KIS_TRANSFORM_WORKER_H_ #include "kis_types.h" #include "kritaimage_export.h" #include #include class KisPaintDevice; class KisFilterStrategy; class QTransform; class KRITAIMAGE_EXPORT KisTransformWorker { /* What are xshearOrigin, yshearOrigin : * * let's keep it simple and say we only have horizontal shearing (it's similar with vertical shearing) * that means we will apply the transformation : * x' = x + xshear * y and y' = y, where x,y are the old coordinates of the pixels, and x' y' the new coordinates * that means, the more we go down in the image (y++), the more x' is different from x * most of the times, we want to shear a part of the image centered at y = y0 != 0. * i.e. we want x' = x at y = y0 * in that case, it's good to apply instead x' = x + xshear * (y - yshearOrigin), y' = y. * please note that it's still possible to obtain the same result by copying the part you want to shear at * in another paintDevice at y = -y0 and use the transformWorker with yshearOrigin = 0. */ public: KisTransformWorker(KisPaintDeviceSP dev, double xscale, double yscale, double xshear, double yshear, double xshearOrigin, double yshearOrigin, double rotation, qint32 xtranslate, qint32 ytranslate, KoUpdaterPtr progress, KisFilterStrategy *filter); ~KisTransformWorker(); /** * Mirror the specified device along the X or Y axis at the * coordinate \p axis. */ static void mirror(KisPaintDeviceSP dev, qreal axis, Qt::Orientation orientation); /** * Convenience methods for mirror(dev, axis, orientation) */ static void mirrorX(KisPaintDeviceSP dev, qreal axis); static void mirrorY(KisPaintDeviceSP dev, qreal axis); /** * Mirror the device relative to the center of its exactBounds() */ static void mirrorX(KisPaintDeviceSP dev); static void mirrorY(KisPaintDeviceSP dev); /** * Offset the specified device with wrapping around edges of rect specified as QRect(0,0,wrapSize.width, wrapSize.height)* * @param device device to be offset * @param offsetPosition position where the new origin will be - * @param wrapSize width and height of the wrap edge, usual scenario is to use canvas width&height + * @param wrapRect width and height of the wrap edge, usual scenario is to use canvas width&height * **/ static void offset(KisPaintDeviceSP device, const QPoint &offsetPosition, const QRect &wrapRect); public: // returns false if interrupted bool run(); bool runPartial(const QRect &processRect); /** * Returns a matrix of the transformation executed by the worker. * Resulting transformation has the following form (in Qt's matrix * notation (all the matrices are transposed)): * * transform = TS.inverted() * S * TS * SC * R * T * * ,where: * TS - shear origin transpose * S - shear itself (shearX * shearY) * SC - scale * R - rotation (@rotation parameter) * T - transpose (@xtranslate, @ytranslate) * * WARNING: due to some rounding problems in the worker * the work it does does not correspond to the matrix exactly! * The result always differs 1-3 pixel. So be careful with it * (or fix it) */ QTransform transform() const; /** * Transforms the outline of the pixel selection (if it is valid) */ void transformPixelSelectionOutline(KisPixelSelectionSP pixelSelection) const; private: // XXX (BSAR): Why didn't we use the shared-pointer versions of the paint device classes? // CBR: because the template functions used within don't work if it's not true pointers template void transformPass(KisPaintDevice* src, KisPaintDevice* dst, double xscale, double shear, double dx, KisFilterStrategy *filterStrategy, int portion); friend class KisTransformWorkerTest; static QRect rotateRight90(KisPaintDeviceSP dev, QRect boundRect, KoUpdaterPtr progressUpdater, int portion); static QRect rotateLeft90(KisPaintDeviceSP dev, QRect boundRect, KoUpdaterPtr progressUpdater, int portion); static QRect rotate180(KisPaintDeviceSP dev, QRect boundRect, KoUpdaterPtr progressUpdater, int portion); private: KisPaintDeviceSP m_dev; double m_xscale, m_yscale; double m_xshear, m_yshear, m_rotation; double m_xshearOrigin, m_yshearOrigin; qint32 m_xtranslate, m_ytranslate; KoUpdaterPtr m_progressUpdater; KisFilterStrategy *m_filter; QRect m_boundRect; }; #endif // KIS_TRANSFORM_VISITOR_H_ diff --git a/libs/image/tiles3/swap/kis_memory_window.h b/libs/image/tiles3/swap/kis_memory_window.h index 8e4fa29190..7fa7689851 100644 --- a/libs/image/tiles3/swap/kis_memory_window.h +++ b/libs/image/tiles3/swap/kis_memory_window.h @@ -1,82 +1,82 @@ /* * Copyright (c) 2010 Dmitry Kazakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __KIS_MEMORY_WINDOW_H #define __KIS_MEMORY_WINDOW_H #include #include "kis_chunk_allocator.h" #define DEFAULT_WINDOW_SIZE (16*MiB) class KRITAIMAGE_EXPORT KisMemoryWindow { public: /** - * @param swapDir. If the dir doesn't exist, it'll be created, if it's empty QDir::tempPath will be used. + * @param swapDir If the dir doesn't exist, it'll be created, if it's empty QDir::tempPath will be used. */ KisMemoryWindow(const QString &swapDir, quint64 writeWindowSize = DEFAULT_WINDOW_SIZE); ~KisMemoryWindow(); inline quint8* getReadChunkPtr(KisChunk readChunk) { return getReadChunkPtr(readChunk.data()); } inline quint8* getWriteChunkPtr(KisChunk writeChunk) { return getWriteChunkPtr(writeChunk.data()); } quint8* getReadChunkPtr(const KisChunkData &readChunk); quint8* getWriteChunkPtr(const KisChunkData &writeChunk); private: struct MappingWindow { MappingWindow(quint64 _defaultSize) : chunk(0,0), window(0), defaultSize(_defaultSize) { } quint8* calculatePointer(const KisChunkData &other) const { return window + other.m_begin - chunk.m_begin; } KisChunkData chunk; quint8 *window; const quint64 defaultSize; }; private: bool adjustWindow(const KisChunkData &requestedChunk, MappingWindow *adjustingWindow, MappingWindow *otherWindow); private: QTemporaryFile m_file; bool m_valid; MappingWindow m_readWindowEx; MappingWindow m_writeWindowEx; }; #endif /* __KIS_MEMORY_WINDOW_H */ diff --git a/libs/libkis/Canvas.h b/libs/libkis/Canvas.h index e6329e2ab1..e143e6366d 100644 --- a/libs/libkis/Canvas.h +++ b/libs/libkis/Canvas.h @@ -1,126 +1,126 @@ /* * Copyright (c) 2016 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef LIBKIS_CANVAS_H #define LIBKIS_CANVAS_H #include #include "kritalibkis_export.h" #include "libkis.h" class KoCanvasBase; class KisDisplayColorConverter; /** * Canvas wraps the canvas inside a view on an image/document. * It is responsible for the view parameters of the document: * zoom, rotation, mirror, wraparound and instant preview. */ class KRITALIBKIS_EXPORT Canvas : public QObject { Q_OBJECT public: explicit Canvas(KoCanvasBase *canvas, QObject *parent = 0); ~Canvas() override; bool operator==(const Canvas &other) const; bool operator!=(const Canvas &other) const; public Q_SLOTS: /** * @return the current zoomlevel. 1.0 is 100%. */ qreal zoomLevel() const; /** - * @brief setZoomLevel set the zoomlevel to the given @param value. 1.0 is 100%. + * @brief setZoomLevel set the zoomlevel to the given @p value. 1.0 is 100%. */ void setZoomLevel(qreal value); /** * @brief resetZoom set the zoomlevel to 100% */ void resetZoom(); /** * @return the rotation of the canvas in degrees. */ qreal rotation() const; /** * @brief setRotation set the rotation of the canvas to the given @param angle in degrees. */ void setRotation(qreal angle); /** * @brief resetRotation reset the canvas rotation. */ void resetRotation(); /** * @return return true if the canvas is mirrored, false otherwise. */ bool mirror() const; /** * @brief setMirror turn the canvas mirroring on or off depending on @param value */ void setMirror(bool value); /** * @return true if the canvas is in wraparound mode, false if not. Only when OpenGL is enabled, * is wraparound mode available. */ bool wrapAroundMode() const; /** * @brief setWrapAroundMode set wraparound mode to @param enable */ void setWrapAroundMode(bool enable); /** * @return true if the canvas is in Instant Preview mode, false if not. Only when OpenGL is enabled, * is Instant Preview mode available. */ bool levelOfDetailMode() const; /** * @brief setLevelOfDetailMode sets Instant Preview to @param enable */ void setLevelOfDetailMode(bool enable); /** * @return the view that holds this canvas */ View *view() const; private: friend class ManagedColor; KisDisplayColorConverter *displayColorConverter() const; struct Private; Private *const d; }; #endif // LIBKIS_CANVAS_H diff --git a/libs/libkis/CloneLayer.h b/libs/libkis/CloneLayer.h index 7d523a8cbe..177be530ca 100644 --- a/libs/libkis/CloneLayer.h +++ b/libs/libkis/CloneLayer.h @@ -1,65 +1,65 @@ /* * Copyright (c) 2017 Wolthera van Hövell tot Westerflier * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef LIBKIS_CLONELAYER_H #define LIBKIS_CLONELAYER_H #include #include "Node.h" #include #include "kritalibkis_export.h" #include "libkis.h" /** * @brief The CloneLayer class * A clone layer is a layer that takes a reference inside the image * and shows the exact same pixeldata. * * If the original is updated, the clone layer will update too. */ class KRITALIBKIS_EXPORT CloneLayer : public Node { Q_OBJECT Q_DISABLE_COPY(CloneLayer) public: explicit CloneLayer(KisImageSP image, QString name, KisLayerSP source, QObject *parent = 0); /** * @brief CloneLayer * function for wrapping a preexisting node into a clonelayer object. - * @param clone - * @param parent + * @param layer the clone layer + * @param parent the parent QObject */ explicit CloneLayer(KisCloneLayerSP layer, QObject *parent = 0); ~CloneLayer() override; public Q_SLOTS: /** * @brief type Krita has several types of nodes, split in layers and masks. Group * layers can contain other layers, any layer can contain masks. * * @return clonelayer */ virtual QString type() const override; }; #endif // LIBKIS_PAINTLAYER_H diff --git a/libs/libkis/Document.h b/libs/libkis/Document.h index 4d6abccbc1..f2cfc0c9e4 100644 --- a/libs/libkis/Document.h +++ b/libs/libkis/Document.h @@ -1,851 +1,851 @@ /* * Copyright (c) 2016 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef LIBKIS_DOCUMENT_H #define LIBKIS_DOCUMENT_H #include #include "kritalibkis_export.h" #include "libkis.h" #include "GroupLayer.h" #include "CloneLayer.h" #include "FileLayer.h" #include "FilterLayer.h" #include "FillLayer.h" #include "VectorLayer.h" #include "FilterMask.h" #include "SelectionMask.h" class KisDocument; /** * The Document class encapsulates a Krita Document/Image. A Krita document is an Image with * a filename. Libkis does not differentiate between a document and an image, like Krita does * internally. */ class KRITALIBKIS_EXPORT Document : public QObject { Q_OBJECT Q_DISABLE_COPY(Document) public: explicit Document(KisDocument *document, QObject *parent = 0); ~Document() override; bool operator==(const Document &other) const; bool operator!=(const Document &other) const; /** * @brief horizontalGuides * The horizontal guides. * @return a list of the horizontal positions of guides. */ QList horizontalGuides() const; /** * @brief verticalGuides * The vertical guide lines. * @return a list of vertical guides. */ QList verticalGuides() const; /** * @brief guidesVisible * Returns guide visibility. * @return whether the guides are visible. */ bool guidesVisible() const; /** * @brief guidesLocked * Returns guide lockedness. * @return whether the guides are locked. */ bool guidesLocked() const; public Q_SLOTS: /** * @brief clone create a shallow clone of this document. * @return a new Document that should be identical to this one in every respect. */ Document *clone() const; /** * Batchmode means that no actions on the document should show dialogs or popups. * @return true if the document is in batchmode. */ bool batchmode() const; /** - * Set batchmode to @param value. If batchmode is true, then there should be no popups + * Set batchmode to @p value. If batchmode is true, then there should be no popups * or dialogs shown to the user. */ void setBatchmode(bool value); /** * @brief activeNode retrieve the node that is currently active in the currently active window * @return the active node. If there is no active window, the first child node is returned. */ Node* activeNode() const; /** * @brief setActiveNode make the given node active in the currently active view and window * @param value the node to make active. */ void setActiveNode(Node* value); /** * @brief toplevelNodes return a list with all top level nodes in the image graph */ QList topLevelNodes() const; /** * @brief nodeByName searches the node tree for a node with the given name and returns it * @param name the name of the node * @return the first node with the given name or 0 if no node is found */ Node *nodeByName(const QString &name) const; /** * colorDepth A string describing the color depth of the image: *
    *
  • U8: unsigned 8 bits integer, the most common type
  • *
  • U16: unsigned 16 bits integer
  • *
  • F16: half, 16 bits floating point. Only available if Krita was built with OpenEXR
  • *
  • F32: 32 bits floating point
  • *
* @return the color depth. */ QString colorDepth() const; /** * @brief colorModel retrieve the current color model of this document: *
    *
  • A: Alpha mask
  • *
  • RGBA: RGB with alpha channel (The actual order of channels is most often BGR!)
  • *
  • XYZA: XYZ with alpha channel
  • *
  • LABA: LAB with alpha channel
  • *
  • CMYKA: CMYK with alpha channel
  • *
  • GRAYA: Gray with alpha channel
  • *
  • YCbCrA: YCbCr with alpha channel
  • *
* @return the internal color model string. */ QString colorModel() const; /** * @return the name of the current color profile */ QString colorProfile() const; /** * @brief setColorProfile set the color profile of the image to the given profile. The profile has to * be registered with krita and be compatible with the current color model and depth; the image data * is not converted. * @param colorProfile * @return false if the colorProfile name does not correspond to to a registered profile or if assigning * the profile failed. */ bool setColorProfile(const QString &colorProfile); /** * @brief setColorSpace convert the nodes and the image to the given colorspace. The conversion is * done with Perceptual as intent, High Quality and No LCMS Optimizations as flags and no blackpoint * compensation. * * @param colorModel A string describing the color model of the image: *
    *
  • A: Alpha mask
  • *
  • RGBA: RGB with alpha channel (The actual order of channels is most often BGR!)
  • *
  • XYZA: XYZ with alpha channel
  • *
  • LABA: LAB with alpha channel
  • *
  • CMYKA: CMYK with alpha channel
  • *
  • GRAYA: Gray with alpha channel
  • *
  • YCbCrA: YCbCr with alpha channel
  • *
* @param colorDepth A string describing the color depth of the image: *
    *
  • U8: unsigned 8 bits integer, the most common type
  • *
  • U16: unsigned 16 bits integer
  • *
  • F16: half, 16 bits floating point. Only available if Krita was built with OpenEXR
  • *
  • F32: 32 bits floating point
  • *
* @param colorProfile a valid color profile for this color model and color depth combination. * @return false the combination of these arguments does not correspond to a colorspace. */ bool setColorSpace(const QString &colorModel, const QString &colorDepth, const QString &colorProfile); /** * @brief backgroundColor returns the current background color of the document. The color will * also include the opacity. * * @return QColor */ QColor backgroundColor(); /** * @brief setBackgroundColor sets the background color of the document. It will trigger a projection * update. * * @param color A QColor. The color will be converted from sRGB. * @return bool */ bool setBackgroundColor(const QColor &color); /** * @brief documentInfo creates and XML document representing document and author information. * @return a string containing a valid XML document with the right information about the document * and author. The DTD can be found here: * * https://phabricator.kde.org/source/krita/browse/master/krita/dtd/ * * @code * * * * * My Document * * * * * Unknown * 1 * 35 * 2017-02-27T20:15:09 * 2017-02-27T20:14:33 * * * * Boudewijn Rempt * * * * * * * * * * * * * * * @endcode * */ QString documentInfo() const; /** * @brief setDocumentInfo set the Document information to the information contained in document * @param document A string containing a valid XML document that conforms to the document-info DTD * that can be found here: * * https://phabricator.kde.org/source/krita/browse/master/krita/dtd/ */ void setDocumentInfo(const QString &document); /** * @return the full path to the document, if it has been set. */ QString fileName() const; /** * @brief setFileName set the full path of the document to @param value */ void setFileName(QString value); /** * @return the height of the image in pixels */ int height() const; /** * @brief setHeight resize the document to @param value height. This is a canvas resize, not a scale. */ void setHeight(int value); /** - * @return the name of the document. This is the title field in the @see documentInfo + * @return the name of the document. This is the title field in the @ref documentInfo */ QString name() const; /** - * @brief setName sets the name of the document to @param value. This is the title field in the @see documentInfo + * @brief setName sets the name of the document to @p value. This is the title field in the @ref documentInfo */ void setName(QString value); /** * @return the resolution in pixels per inch */ int resolution() const; /** * @brief setResolution set the resolution of the image; this does not scale the image * @param value the resolution in pixels per inch */ void setResolution(int value); /** * @brief rootNode the root node is the invisible group layer that contains the entire node * hierarchy. * @return the root of the image */ Node* rootNode() const; /** * @brief selection Create a Selection object around the global selection, if there is one. * @return the global selection or None if there is no global selection. */ Selection* selection() const; /** * @brief setSelection set or replace the global selection * @param value a valid selection object. */ void setSelection(Selection* value); /** * @return the width of the image in pixels. */ int width() const; /** * @brief setWidth resize the document to @param value width. This is a canvas resize, not a scale. */ void setWidth(int value); /** * @return the left edge of the canvas in pixels. */ int xOffset() const; /** - * @brief setXOffset sets the left edge of the canvas to @param x. + * @brief setXOffset sets the left edge of the canvas to @p x. */ void setXOffset(int x); /** * @return the top edge of the canvas in pixels. */ int yOffset() const; /** - * @brief setYOffset sets the top edge of the canvas to @param y. + * @brief setYOffset sets the top edge of the canvas to @p y. */ void setYOffset(int y); /** * @return xRes the horizontal resolution of the image in pixels per pt (there are 72 pts to an inch) */ double xRes() const; /** * @brief setXRes set the horizontal resolution of the image to xRes in pixels per pt. (there are 72 pts to an inch) */ void setXRes(double xRes) const; /** * @return yRes the vertical resolution of the image in pixels per pt (there are 72 pts to an inch) */ double yRes() const; /** * @brief setYRes set the vertical resolution of the image to yRes in pixels per pt. (there are 72 pts to an inch) */ void setYRes(double yRes) const; /** * @brief pixelData reads the given rectangle from the image projection and returns it as a byte * array. The pixel data starts top-left, and is ordered row-first. * * The byte array can be interpreted as follows: 8 bits images have one byte per channel, * and as many bytes as there are channels. 16 bits integer images have two bytes per channel, * representing an unsigned short. 16 bits float images have two bytes per channel, representing * a half, or 16 bits float. 32 bits float images have four bytes per channel, representing a * float. * * You can read outside the image boundaries; those pixels will be transparent black. * * The order of channels is: * *
    *
  • Integer RGBA: Blue, Green, Red, Alpha *
  • Float RGBA: Red, Green, Blue, Alpha *
  • LabA: L, a, b, Alpha *
  • CMYKA: Cyan, Magenta, Yellow, Key, Alpha *
  • XYZA: X, Y, Z, A *
  • YCbCrA: Y, Cb, Cr, Alpha *
* * The byte array is a copy of the original image data. In Python, you can use bytes, bytearray * and the struct module to interpret the data and construct, for instance, a Pillow Image object. * * @param x x position from where to start reading * @param y y position from where to start reading * @param w row length to read * @param h number of rows to read * @return a QByteArray with the pixel data. The byte array may be empty. */ QByteArray pixelData(int x, int y, int w, int h) const; /** * @brief close Close the document: remove it from Krita's internal list of documents and * close all views. If the document is modified, you should save it first. There will be * no prompt for saving. * * After closing the document it becomes invalid. * * @return true if the document is closed. */ bool close(); /** * @brief crop the image to rectangle described by @param x, @param y, * @param w and @param h */ void crop(int x, int y, int w, int h); /** * @brief exportImage export the image, without changing its URL to the given path. * @param filename the full path to which the image is to be saved * @param exportConfiguration a configuration object appropriate to the file format. * An InfoObject will used to that configuration. * * The supported formats have specific configurations that must be used when in * batchmode. They are described below: * *\b png *
    *
  • alpha: bool (True or False) *
  • compression: int (1 to 9) *
  • forceSRGB: bool (True or False) *
  • indexed: bool (True or False) *
  • interlaced: bool (True or False) *
  • saveSRGBProfile: bool (True or False) *
  • transparencyFillcolor: rgb (Ex:[255,255,255]) *
* *\b jpeg *
    *
  • baseline: bool (True or False) *
  • exif: bool (True or False) *
  • filters: bool (['ToolInfo', 'Anonymizer']) *
  • forceSRGB: bool (True or False) *
  • iptc: bool (True or False) *
  • is_sRGB: bool (True or False) *
  • optimize: bool (True or False) *
  • progressive: bool (True or False) *
  • quality: int (0 to 100) *
  • saveProfile: bool (True or False) *
  • smoothing: int (0 to 100) *
  • subsampling: int (0 to 3) *
  • transparencyFillcolor: rgb (Ex:[255,255,255]) *
  • xmp: bool (True or False) *
* @return true if the export succeeded, false if it failed. */ bool exportImage(const QString &filename, const InfoObject &exportConfiguration); /** * @brief flatten all layers in the image */ void flatten(); /** * @brief resizeImage resizes the canvas to the given left edge, top edge, width and height. * Note: This doesn't scale, use scale image for that. * @param x the new left edge * @param y the new top edge * @param w the new width * @param h the new height */ void resizeImage(int x, int y, int w, int h); /** * @brief scaleImage * @param w the new width * @param h the new height * @param xres the new xres * @param yres the new yres * @param strategy the scaling strategy. There's several ones amongst these that aren't available in the regular UI. * The list of filters is extensible and can be retrieved with Krita::filter *
    *
  • Hermite
  • *
  • Bicubic - Adds pixels using the color of surrounding pixels. Produces smoother tonal gradations than Bilinear.
  • *
  • Box - Replicate pixels in the image. Preserves all the original detail, but can produce jagged effects.
  • *
  • Bilinear - Adds pixels averaging the color values of surrounding pixels. Produces medium quality results when the image is scaled from half to two times the original size.
  • *
  • Bell
  • *
  • BSpline
  • *
  • Kanczos3 - Offers similar results than Bicubic, but maybe a little bit sharper. Can produce light and dark halos along strong edges.
  • *
  • Mitchell
  • *
*/ void scaleImage(int w, int h, int xres, int yres, QString strategy); /** * @brief rotateImage * Rotate the image by the given radians. * @param radians the amount you wish to rotate the image in radians */ void rotateImage(double radians); /** * @brief shearImage shear the whole image. * @param angleX the X-angle in degrees to shear by * @param angleY the Y-angle in degrees to shear by */ void shearImage(double angleX, double angleY); /** * @brief save the image to its currently set path. The modified flag of the * document will be reset * @return true if saving succeeded, false otherwise. */ bool save(); /** - * @brief saveAs save the document under the @param filename. The document's - * filename will be reset to @param filename. + * @brief saveAs save the document under the @p filename. The document's + * filename will be reset to @p filename. * @param filename the new filename (full path) for the document * @return true if saving succeeded, false otherwise. */ bool saveAs(const QString &filename); /** * @brief createNode create a new node of the given type. The node is not added * to the node hierarchy; you need to do that by finding the right parent node, * getting its list of child nodes and adding the node in the right place, then * calling Node::SetChildNodes * * @param name The name of the node * * @param nodeType The type of the node. Valid types are: *
    *
  • paintlayer *
  • grouplayer *
  • filelayer *
  • filterlayer *
  • filllayer *
  • clonelayer *
  • vectorlayer *
  • transparencymask *
  • filtermask *
  • transformmask *
  • selectionmask *
* * When relevant, the new Node will have the colorspace of the image by default; * that can be changed with Node::setColorSpace. * * The settings and selections for relevant layer and mask types can also be set * after the Node has been created. * @code d = Application.createDocument(1000, 1000, "Test", "RGBA", "U8", "", 120.0) root = d.rootNode(); print(root.childNodes()) l2 = d.createNode("layer2", "paintLayer") print(l2) root.addChildNode(l2, None) print(root.childNodes()) @endcode * * * @return the new Node. */ Node* createNode(const QString &name, const QString &nodeType); /** * @brief createGroupLayer * Returns a grouplayer object. Grouplayers are nodes that can have * other layers as children and have the passthrough mode. * @param name the name of the layer. * @return a GroupLayer object. */ GroupLayer* createGroupLayer(const QString &name); /** * @brief createFileLayer returns a layer that shows an external image. * @param name name of the file layer. * @param fileName the absolute filename of the file referenced. Symlinks will be resolved. * @param scalingMethod how the dimensions of the file are interpreted * can be either "None", "ImageToSize" or "ImageToPPI" * @return a FileLayer */ FileLayer* createFileLayer(const QString &name, const QString fileName, const QString scalingMethod); /** * @brief createFilterLayer creates a filter layer, which is a layer that represents a filter * applied non-destructively. * @param name name of the filterLayer * @param filter the filter that this filter layer will us. * @param selection the selection. * @return a filter layer object. */ FilterLayer* createFilterLayer(const QString &name, Filter &filter, Selection &selection); /** * @brief createFillLayer creates a fill layer object, which is a layer * @param name * @param generatorName - name of the generation filter. * @param configuration - the configuration for the generation filter. * @param selection - the selection. * @return a filllayer object. * * @code * from krita import * * d = Krita.instance().activeDocument() * i = InfoObject(); * i.setProperty("pattern", "Cross01.pat") * s = Selection(); * s.select(0, 0, d.width(), d.height(), 255) * n = d.createFillLayer("test", "pattern", i, s) * r = d.rootNode(); * c = r.childNodes(); * r.addChildNode(n, c[0]) * d.refreshProjection() * @endcode */ FillLayer* createFillLayer(const QString &name, const QString generatorName, InfoObject &configuration, Selection &selection); /** * @brief createCloneLayer * @param name * @param source * @return */ CloneLayer* createCloneLayer(const QString &name, const Node* source); /** * @brief createVectorLayer * Creates a vector layer that can contain vector shapes. * @param name the name of this layer. * @return a VectorLayer. */ VectorLayer* createVectorLayer(const QString &name); /** * @brief createFilterMask * Creates a filter mask object that much like a filterlayer can apply a filter non-destructively. * @param name the name of the layer. * @param filter the filter assigned. * @return a FilterMask */ FilterMask* createFilterMask(const QString &name, Filter &filter); /** * @brief createSelectionMask * Creates a selection mask, which can be used to store selections. * @param name - the name of the layer. * @return a SelectionMask */ SelectionMask* createSelectionMask(const QString &name); /** * @brief projection creates a QImage from the rendered image or * a cutout rectangle. */ QImage projection(int x = 0, int y = 0, int w = 0, int h = 0) const; /** * @brief thumbnail create a thumbnail of the given dimensions. * * If the requested size is too big a null QImage is created. * * @return a QImage representing the layer contents. */ QImage thumbnail(int w, int h) const; /** * Why this should be used, When it should be used, How it should be used, * and warnings about when not. */ void lock(); /** * Why this should be used, When it should be used, How it should be used, * and warnings about when not. */ void unlock(); /** * Why this should be used, When it should be used, How it should be used, * and warnings about when not. */ void waitForDone(); /** * Why this should be used, When it should be used, How it should be used, * and warnings about when not. */ bool tryBarrierLock(); /** * Why this should be used, When it should be used, How it should be used, * and warnings about when not. */ bool isIdle(); /** * Starts a synchronous recomposition of the projection: everything will * wait until the image is fully recomputed. */ void refreshProjection(); /** * @brief setHorizontalGuides * replace all existing horizontal guides with the entries in the list. - * @param list a list of floats containing the new guides. + * @param lines a list of floats containing the new guides. */ void setHorizontalGuides(const QList &lines); /** * @brief setVerticalGuides * replace all existing horizontal guides with the entries in the list. - * @param list a list of floats containing the new guides. + * @param lines a list of floats containing the new guides. */ void setVerticalGuides(const QList &lines); /** * @brief setGuidesVisible * set guides visible on this document. * @param visible whether or not the guides are visible. */ void setGuidesVisible(bool visible); /** * @brief setGuidesLocked * set guides locked on this document * @param locked whether or not to lock the guides on this document. */ void setGuidesLocked(bool locked); /** * @brief modified returns true if the document has unsaved modifications. */ bool modified() const; /** * @brief bounds return the bounds of the image * @return the bounds */ QRect bounds() const; /**** * Animation Related API *****/ /** * @brief Import an image sequence of files from a directory. This will grab all * images from the directory and import them with a potential offset (firstFrame) * and step (images on 2s, 3s, etc) * @returns whether the animation import was successful */ bool importAnimation(const QList &files, int firstFrame, int step); /** * @brief frames per second of document * @return the fps of the document */ int framesPerSecond(); /** * @brief set frames per second of document */ void setFramesPerSecond(int fps); /** * @brief set start time of animation */ void setFullClipRangeStartTime(int startTime); /** * @brief get the full clip range start time * @return full clip range start time */ int fullClipRangeStartTime(); /** * @brief set full clip range end time */ void setFullClipRangeEndTime(int endTime); /** * @brief get the full clip range end time * @return full clip range end time */ int fullClipRangeEndTime(); /** * @brief get total frame range for animation * @return total frame range for animation */ int animationLength(); /** * @brief set temporary playback range of document */ void setPlayBackRange(int start, int stop); /** * @brief get start time of current playback * @return start time of current playback */ int playBackStartTime(); /** * @brief get end time of current playback * @return end time of current playback */ int playBackEndTime(); /** * @brief get current frame selected of animation * @return current frame selected of animation */ int currentTime(); /** * @brief set current time of document's animation */ void setCurrentTime(int time); private: friend class Krita; friend class Window; friend class Filter; QPointer document() const; private: struct Private; Private *const d; }; #endif // LIBKIS_DOCUMENT_H diff --git a/libs/libkis/Extension.h b/libs/libkis/Extension.h index eb9502a953..911792901a 100644 --- a/libs/libkis/Extension.h +++ b/libs/libkis/Extension.h @@ -1,86 +1,86 @@ /* * Copyright (c) 2015 Cyrille Berger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef LIBKIS_EXTENSION_H #define LIBKIS_EXTENSION_H #include "kritalibkis_export.h" #include #include /** * An Extension is the base for classes that extend Krita. An Extension * is loaded on startup, when the setup() method will be executed. * * The extension instance should be added to the Krita Application object * using Krita.instance().addViewExtension or Application.addViewExtension * or Scripter.addViewExtension. * * Example: * * @code * import sys * from PyQt5.QtGui import * * from PyQt5.QtWidgets import * * from krita import * * class HelloExtension(Extension): * * def __init__(self, parent): * super().__init__(parent) * * def hello(self): * QMessageBox.information(QWidget(), "Test", "Hello! This is Krita " + Application.version()) * * def setup(self): * qDebug("Hello Setup") * * def createActions(self, window) * action = window.createAction("hello") * action.triggered.connect(self.hello) * * Scripter.addExtension(HelloExtension(Krita.instance())) * * @endcode */ class KRITALIBKIS_EXPORT Extension : public QObject { Q_OBJECT public: /** * Create a new extension. The extension will be - * owned by @param parent. + * owned by @p parent. */ explicit Extension(QObject *parent = 0); ~Extension() override; /** * Override this function to setup your Extension. You can use it to integrate * with the Krita application instance. */ virtual void setup() = 0; virtual void createActions(Window *window) = 0; }; #endif diff --git a/libs/libkis/InfoObject.h b/libs/libkis/InfoObject.h index 6330557424..20f911ca62 100644 --- a/libs/libkis/InfoObject.h +++ b/libs/libkis/InfoObject.h @@ -1,88 +1,88 @@ /* * Copyright (c) 2016 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef LIBKIS_INFOOBJECT_H #define LIBKIS_INFOOBJECT_H #include #include #include "kritalibkis_export.h" #include "libkis.h" /** * InfoObject wrap a properties map. These maps can be used to set the * configuration for filters. */ class KRITALIBKIS_EXPORT InfoObject : public QObject { Q_OBJECT public: InfoObject(KisPropertiesConfigurationSP configuration); /** * Create a new, empty InfoObject. */ explicit InfoObject(QObject *parent = 0); ~InfoObject() override; bool operator==(const InfoObject &other) const; bool operator!=(const InfoObject &other) const; /** * Return all properties this InfoObject manages. */ QMap properties() const; /** - * Add all properties in the @param propertyMap to this InfoObject + * Add all properties in the @p propertyMap to this InfoObject */ - void setProperties(QMap proprertyMap); + void setProperties(QMap propertyMap); public Q_SLOTS: /** * set the property identified by @key to @value * * If you want create a property that represents a color, you can use a QColor * or hex string, as defined in http://doc.qt.io/qt-5/qcolor.html#setNamedColor. * */ void setProperty(const QString &key, QVariant value); /** * return the value for the property identified by key, or None if there is no such key. */ QVariant property(const QString &key); private: friend class Filter; friend class Document; friend class Node; /** * @brief configuration gives access to the internal configuration object. Must * be used used internally in libkis * @return the internal configuration object. */ KisPropertiesConfigurationSP configuration() const; struct Private; Private *d; }; #endif // LIBKIS_INFOOBJECT_H diff --git a/libs/libkis/ManagedColor.h b/libs/libkis/ManagedColor.h index 190a7e00bd..5b5837ee17 100644 --- a/libs/libkis/ManagedColor.h +++ b/libs/libkis/ManagedColor.h @@ -1,212 +1,211 @@ /* * Copyright (C) 2017 Boudewijn Rempt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef MANAGEDCOLOR_H #define MANAGEDCOLOR_H #include #include #include #include "kritalibkis_export.h" #include "libkis.h" class KoColor; /** * @brief The ManagedColor class is a class to handle colors that are color managed. * A managed color is a color of which we know the model(RGB, LAB, CMYK, etc), the bitdepth and * the specific properties of its colorspace, such as the whitepoint, chromacities, trc, etc, as represented * by the color profile. * * Krita has two color management systems. LCMS and OCIO. * LCMS is the one handling the ICC profile stuff, and the major one handling that ManagedColor deals with. * OCIO support is only in the display of the colors. ManagedColor has some support for it in colorForCanvas() * * All colors in Krita are color managed. QColors are understood as RGB-type colors in the sRGB space. * * We recommend you make a color like this: * * @code * colorYellow = ManagedColor("RGBA", "U8", "") * QVector yellowComponents = colorYellow.components() * yellowComponents[0] = 1.0 * yellowComponents[1] = 1.0 * yellowComponents[2] = 0 * yellowComponents[3] = 1.0 * * colorYellow.setComponents(yellowComponents) * QColor yellow = colorYellow.colorForCanvas(canvas) * @endcode */ class KRITALIBKIS_EXPORT ManagedColor : public QObject { Q_OBJECT public: /** * @brief ManagedColor * Create a ManagedColor that is black and transparent. */ explicit ManagedColor(QObject *parent = 0); /** * @brief ManagedColor create a managed color with the given color space properties. * @see setColorModel() for more details. */ ManagedColor(const QString &colorModel, const QString &colorDepth, const QString &colorProfile, QObject *parent = 0); ManagedColor(KoColor color, QObject *parent = 0); ~ManagedColor() override; bool operator==(const ManagedColor &other) const; /** * @brief colorForCanvas * @param canvas the canvas whose color management you'd like to use. In Krita, different views have * separate canvasses, and these can have different OCIO configurations active. * @return the QColor as it would be displaying on the canvas. This result can be used to draw widgets with * the correct configuration applied. */ QColor colorForCanvas(Canvas *canvas) const; /** * colorDepth A string describing the color depth of the image: *
    *
  • U8: unsigned 8 bits integer, the most common type
  • *
  • U16: unsigned 16 bits integer
  • *
  • F16: half, 16 bits floating point. Only available if Krita was built with OpenEXR
  • *
  • F32: 32 bits floating point
  • *
* @return the color depth. */ QString colorDepth() const; /** * @brief colorModel retrieve the current color model of this document: *
    *
  • A: Alpha mask
  • *
  • RGBA: RGB with alpha channel (The actual order of channels is most often BGR!)
  • *
  • XYZA: XYZ with alpha channel
  • *
  • LABA: LAB with alpha channel
  • *
  • CMYKA: CMYK with alpha channel
  • *
  • GRAYA: Gray with alpha channel
  • *
  • YCbCrA: YCbCr with alpha channel
  • *
* @return the internal color model string. */ QString colorModel() const; /** * @return the name of the current color profile */ QString colorProfile() const; /** * @brief setColorProfile set the color profile of the image to the given profile. The profile has to * be registered with krita and be compatible with the current color model and depth; the image data * is not converted. * @param colorProfile * @return false if the colorProfile name does not correspond to to a registered profile or if assigning * the profile failed. */ bool setColorProfile(const QString &colorProfile); /** * @brief setColorSpace convert the nodes and the image to the given colorspace. The conversion is * done with Perceptual as intent, High Quality and No LCMS Optimizations as flags and no blackpoint * compensation. * * @param colorModel A string describing the color model of the image: *
    *
  • A: Alpha mask
  • *
  • RGBA: RGB with alpha channel (The actual order of channels is most often BGR!)
  • *
  • XYZA: XYZ with alpha channel
  • *
  • LABA: LAB with alpha channel
  • *
  • CMYKA: CMYK with alpha channel
  • *
  • GRAYA: Gray with alpha channel
  • *
  • YCbCrA: YCbCr with alpha channel
  • *
* @param colorDepth A string describing the color depth of the image: *
    *
  • U8: unsigned 8 bits integer, the most common type
  • *
  • U16: unsigned 16 bits integer
  • *
  • F16: half, 16 bits floating point. Only available if Krita was built with OpenEXR
  • *
  • F32: 32 bits floating point
  • *
* @param colorProfile a valid color profile for this color model and color depth combination. * @return false the combination of these arguments does not correspond to a colorspace. */ bool setColorSpace(const QString &colorModel, const QString &colorDepth, const QString &colorProfile); /** * @brief components * @return a QVector containing the channel/components of this color normalized. This includes the alphachannel. */ QVector components() const; /** * @brief componentsOrdered() * @return same as Components, except the values are ordered to the display. */ QVector componentsOrdered() const; /** * @brief setComponents * Set the channel/components with normalized values. For integer colorspace, this obviously means the limit * is between 0.0-1.0, but for floating point colorspaces, 2.4 or 103.5 are still meaningful (if bright) values. * @param values the QVector containing the new channel/component values. These should be normalized. */ void setComponents(const QVector &values); /** * Serialize this color following Create's swatch color specification available * at http://create.freedesktop.org/wiki/index.php/Swatches_-_colour_file_format */ QString toXML() const; /** * Unserialize a color following Create's swatch color specification available * at http://create.freedesktop.org/wiki/index.php/Swatches_-_colour_file_format * - * @param XXX + * @param xml an XML color * * @return the unserialized color, or an empty color object if the function failed * to unserialize the color */ void fromXML(const QString &xml); /** * @brief toQString create a user-visible string of the channel names and the channel values - * @param color the color to create the string from * @return a string that can be used to display the values of this color to the user. */ QString toQString(); private: friend class View; friend class PaletteView; friend class Swatch; KoColor color() const; struct Private; const QScopedPointer d; }; #endif // MANAGEDCOLOR_H diff --git a/libs/libkis/Palette.h b/libs/libkis/Palette.h index d6aa1d431d..2d853240b5 100644 --- a/libs/libkis/Palette.h +++ b/libs/libkis/Palette.h @@ -1,180 +1,180 @@ /* * Copyright (c) 2017 Wolthera van Hövell tot Westerflier * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef LIBKIS_PALETTE_H #define LIBKIS_PALETTE_H #include #include #include "kritalibkis_export.h" #include "libkis.h" #include "Resource.h" #include "KoColorSet.h" #include class ManagedColor; /** * @brief The Palette class * Palette is a resource object that stores organised color data. * It's purpose is to allow artists to save colors and store them. * * An example for printing all the palettes and the entries: * * @code import sys from krita import * resources = Application.resources("palette") for (k, v) in resources.items(): print(k) palette = Palette(v) for x in range(palette.numberOfEntries()): entry = palette.colorSetEntryByIndex(x) c = palette.colorForEntry(entry); print(x, entry.name(), entry.id(), entry.spotColor(), c.toQString()) * @endcode */ class KRITALIBKIS_EXPORT Palette : public QObject { public: Palette(Resource *resource); ~Palette() override; /** * @brief numberOfEntries * @return */ int numberOfEntries() const; /** * @brief columnCount * @return the amount of columns this palette is set to use. */ int columnCount(); /** * @brief setColumnCount * Set the amount of columns this palette should use. */ void setColumnCount(int columns); /** * @brief comment * @return the comment or description associated with the palette. */ QString comment(); /** * @brief setComment * set the comment or description associated with the palette. * @param comment */ void setComment(QString comment); /** * @brief groupNames * @return the list of group names. This is list is in the order these groups are in the file. */ QStringList groupNames() const; /** * @brief addGroup * @param name of the new group * @return whether adding the group was successful. */ bool addGroup(QString name); /** * @brief removeGroup * @param name the name of the group to remove. * @param keepColors whether or not to delete all the colors inside, or to move them to the default group. * @return */ bool removeGroup(QString name, bool keepColors = true); /** * @brief colorsCountTotal * @return the total amount of entries in the whole group */ int colorsCountTotal(); /** * @brief colorSetEntryByIndex * get the colorsetEntry from the global index. * @param index the global index * @return the colorset entry */ Swatch *colorSetEntryByIndex(int index); /** * @brief colorSetEntryFromGroup * @param index index in the group. * @param groupName the name of the group to get the color from. * @return the colorsetentry. */ Swatch *colorSetEntryFromGroup(int index, const QString &groupName); /** * @brief addEntry * add an entry to a group. Gets appended to the end. * @param entry the entry * @param groupName the name of the group to add to. */ void addEntry(Swatch entry, QString groupName = QString()); /** * @brief removeEntry - * remove the entry at @param index from the group @param groupName. + * remove the entry at @p index from the group @p groupName. */ void removeEntry(int index, const QString &groupName); /** * @brief changeGroupName * change the group name. * @param oldGroupName the old groupname to change. * @param newGroupName the new name to change it into. * @return whether successful. Reasons for failure include not knowing have oldGroupName */ bool changeGroupName(QString oldGroupName, QString newGroupName); /** * @brief moveGroup * move the group to before groupNameInsertBefore. * @param groupName group to move. * @param groupNameInsertBefore group to inset before. * @return whether successful. Reasons for failure include either group not existing. */ bool moveGroup(const QString &groupName, const QString &groupNameInsertBefore = QString()); /** * @brief save * save the palette * @return whether it was successful. */ bool save(); private: friend class PaletteView; struct Private; Private *const d; /** * @brief colorSet * @return gives qa KoColorSet object back */ KoColorSet *colorSet(); }; #endif // LIBKIS_PALETTE_H diff --git a/libs/libkis/Window.h b/libs/libkis/Window.h index b0b0bebf58..aab7b5d2a8 100644 --- a/libs/libkis/Window.h +++ b/libs/libkis/Window.h @@ -1,110 +1,110 @@ /* * Copyright (c) 2016 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef LIBKIS_WINDOW_H #define LIBKIS_WINDOW_H #include #include #include #include "kritalibkis_export.h" #include "libkis.h" #include /** * Window represents one Krita mainwindow. A window can have any number * of views open on any number of documents. */ class KRITALIBKIS_EXPORT Window : public QObject { Q_OBJECT public: explicit Window(KisMainWindow *window, QObject *parent = 0); ~Window() override; bool operator==(const Window &other) const; bool operator!=(const Window &other) const; public Q_SLOTS: /** * Return a handle to the QMainWindow widget. This is useful * to e.g. parent dialog boxes and message box. */ QMainWindow *qwindow() const; /** * @return a list of open views in this window */ QList views() const; /** * Open a new view on the given document in this window */ View *addView(Document *document); /** * Make the given view active in this window. If the view * does not belong to this window, nothing happens. */ void showView(View *view); /** * @return the currently active view or 0 if no view is active */ View *activeView() const; /** * @brief activate activates this Window. */ void activate(); /** * @brief close the active window and all its Views. If there * are no Views left for a given Document, that Document will * also be closed. */ void close(); /** * @brief createAction creates a QAction object and adds it to the action * manager for this Window. * @param id The unique id for the action. This will be used to * propertize the action if any .action file is present * @param text The user-visible text of the action. If empty, the text from the * .action file is used. - * @param menu a /-separated string that describes which menu the action should + * @param menuLocation a /-separated string that describes which menu the action should * be places in. Default is "tools/scripts" * @return the new action. */ QAction *createAction(const QString &id, const QString &text = QString(), const QString &menuLocation = QString("tools/scripts")); Q_SIGNALS: /// Emitted when the window is closed. void windowClosed(); private: struct Private; Private *const d; }; #endif // LIBKIS_WINDOW_H diff --git a/libs/odf/KoElementReference.h b/libs/odf/KoElementReference.h index 613a925db7..750c3406cf 100644 --- a/libs/odf/KoElementReference.h +++ b/libs/odf/KoElementReference.h @@ -1,131 +1,131 @@ /* * Copyright (c) 2011-2012 Boudewijn Rempt * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOELEMENTREFERENCE_H #define KOELEMENTREFERENCE_H #include #include #include #include "KoXmlReaderForward.h" #include "kritaodf_export.h" class KoXmlWriter; class KoElementReferenceData : public QSharedData { public: KoElementReferenceData() { xmlid = QUuid::createUuid().toString(); xmlid.remove('{'); xmlid.remove('}'); } KoElementReferenceData(const KoElementReferenceData &other) : QSharedData(other) , xmlid(other.xmlid) { } ~KoElementReferenceData() {} QString xmlid; }; /** * KoElementReference is used to store unique identifiers for elements in an odf document. * Element references are saved as xml:id and optionally for compatibility also as draw:id * and text:id. * * You can use element references wherever you would have used a QString to refer to the id * of an object. * * Element references are implicitly shared, so you can and should pass them along by value. */ class KRITAODF_EXPORT KoElementReference { public: enum GenerationOption { UUID = 0, Counter = 1 }; enum SaveOption { XmlId = 0x0, DrawId = 0x1, TextId = 0x2 }; Q_DECLARE_FLAGS(SaveOptions, SaveOption) KoElementReference(); explicit KoElementReference(const QString &prefix); KoElementReference(const QString &prefix, int counter); KoElementReference(const KoElementReference &other); KoElementReference &operator=(const KoElementReference &rhs); bool operator==(const KoElementReference &other) const; bool operator!=(const KoElementReference &other) const; /** * @return true if the xmlid is valid, i.e., not null */ bool isValid() const; /** * @brief loadOdf creates a new KoElementReference from the given element. If the element * does not have an xml:id, draw:id or text:id attribute, and invalid element reference * is returned. * @param element the element that may contain xml:id, text:id or draw:id. xml:id has * priority. * @return a new element reference */ KoElementReference loadOdf(const KoXmlElement &element); /** * @brief saveOdf saves this element reference into the currently open element in the xml writer. * @param writer the writer we save to - * @param saveOptions determines which attributes we save. We always save the xml:id. + * @param saveOption determines which attributes we save. We always save the xml:id. */ void saveOdf(KoXmlWriter *writer, SaveOption saveOption = XmlId) const; /** * @brief toString creates a QString from the element reference * @return a string that represents the element. Can be used in maps etc. */ QString toString() const; /** * Invalidate the reference */ void invalidate(); private: QSharedDataPointer d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KoElementReference::SaveOptions) #endif // KOELEMENTREFERENCE_H diff --git a/libs/pigment/KoColor.h b/libs/pigment/KoColor.h index 8db9b2aa88..c27339daa9 100644 --- a/libs/pigment/KoColor.h +++ b/libs/pigment/KoColor.h @@ -1,276 +1,276 @@ /* * Copyright (c) 2005 Boudewijn Rempt * Copyright (C) 2007 Thomas Zander * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOCOLOR_H #define KOCOLOR_H #include #include #include #include "kritapigment_export.h" #include "KoColorConversionTransformation.h" #include "KoColorSpaceRegistry.h" #include "KoColorSpaceTraits.h" #include class QDomDocument; class QDomElement; class KoColorProfile; class KoColorSpace; /** * A KoColor describes a color in a certain colorspace. The color is stored in a buffer * that can be manipulated by the function of the color space. */ class KRITAPIGMENT_EXPORT KoColor : public boost::equality_comparable { public: /// Create an empty KoColor. It will be valid, but also black and transparent KoColor(); /// Create a null KoColor. It will be valid, but all channels will be set to 0 explicit KoColor(const KoColorSpace * colorSpace); /// Create a KoColor from a QColor. The QColor is immediately converted to native. The QColor /// is assumed to have the current monitor profile. KoColor(const QColor & color, const KoColorSpace * colorSpace); /// Create a KoColor using a native color strategy. The data is copied. KoColor(const quint8 * data, const KoColorSpace * colorSpace); /// Create a KoColor by converting src into another colorspace KoColor(const KoColor &src, const KoColorSpace * colorSpace); /// Copy constructor -- deep copies the colors. KoColor(const KoColor & rhs) { *this = rhs; } /** * assignment operator to copy the data from the param color into this one. - * @param other the color we are going to copy + * @param rhs the color we are going to copy * @return this color */ inline KoColor &operator=(const KoColor &rhs) { if (&rhs == this) { return *this; } m_colorSpace = rhs.m_colorSpace; m_size = rhs.m_size; memcpy(m_data, rhs.m_data, m_size); assertPermanentColorspace(); return *this; } bool operator==(const KoColor &other) const { if (*colorSpace() != *other.colorSpace()) { return false; } if (m_size != other.m_size) { return false; } return memcmp(m_data, other.m_data, m_size) == 0; } /// return the current colorSpace const KoColorSpace * colorSpace() const { return m_colorSpace; } /// return the current profile const KoColorProfile *profile() const; /// Convert this KoColor to the specified colorspace. If the specified colorspace is the /// same as the original colorspace, do nothing void convertTo(const KoColorSpace * cs, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags); void convertTo(const KoColorSpace * cs); /// Copies this color and converts it to the specified colorspace. If the specified colorspace is the /// same as the original colorspace, just returns a copy KoColor convertedTo(const KoColorSpace * cs, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags) const; /// Copies this color and converts it to the specified colorspace. If the specified colorspace is the /// same as the original colorspace, just returns a copy KoColor convertedTo(const KoColorSpace * cs) const; /// assign new profile without converting pixel data void setProfile(const KoColorProfile *profile); /// Replace the existing color data, and colorspace with the specified data. /// The data is copied. void setColor(const quint8 * data, const KoColorSpace * colorSpace = 0); /// Convert the color from src and replace the value of the current color with the converted data. /// Don't convert the color if src and this have the same colorspace. void fromKoColor(const KoColor& src); /// a convenience method for the above. void toQColor(QColor *c) const; /// a convenience method for the above. QColor toQColor() const; /** * Convenient function to set the opacity of the color. */ void setOpacity(quint8 alpha); void setOpacity(qreal alpha); /** * Convenient function that return the opacity of the color */ quint8 opacityU8() const; qreal opacityF() const; /// Convenient function for converting from a QColor void fromQColor(const QColor& c); /** * @return the buffer associated with this color object to be used with the * transformation object created by the color space of this KoColor * or to copy to a different buffer from the same color space */ quint8 * data() { return m_data; } /** * @return the buffer associated with this color object to be used with the * transformation object created by the color space of this KoColor * or to copy to a different buffer from the same color space */ const quint8 * data() const { return m_data; } /** * Channelwise subtracts \p value from *this and stores the result in *this * * Throws a safe assert if the colorspaces of the two colors are different */ void subtract(const KoColor &value); /** * Channelwise subtracts \p value from a copy of *this and returns the result * * Throws a safe assert if the colorspaces of the two colors are different */ KoColor subtracted(const KoColor &value) const; /** * Channelwise adds \p value to *this and stores the result in *this * * Throws a safe assert if the colorspaces of the two colors are different */ void add(const KoColor &value); /** * Channelwise adds \p value to a copy of *this and returns the result * * Throws a safe assert if the colorspaces of the two colors are different */ KoColor added(const KoColor &value) const; /** * Serialize this color following Create's swatch color specification available * at http://create.freedesktop.org/wiki/index.php/Swatches_-_colour_file_format * * This function doesn't create the element but rather the , * , ... elements. It is assumed that colorElt is the * element. * * @param colorElt root element for the serialization, it is assumed that this * element is * @param doc is the document containing colorElt */ void toXML(QDomDocument& doc, QDomElement& colorElt) const; /** * Unserialize a color following Create's swatch color specification available * at http://create.freedesktop.org/wiki/index.php/Swatches_-_colour_file_format * * @param elt the element to unserialize (, , ) * @param bitDepthId the bit depth is unspecified by the spec, this allow to select * a preferred bit depth for creating the KoColor object (if that * bit depth isn't available, this function will randomly select * an other bit depth) * @return the unserialize color, or an empty color object if the function failed * to unserialize the color */ static KoColor fromXML(const QDomElement& elt, const QString & bitDepthId); /** * Unserialize a color following Create's swatch color specification available * at http://create.freedesktop.org/wiki/index.php/Swatches_-_colour_file_format * * @param elt the element to unserialize (, , ) * @param bitDepthId the bit depth is unspecified by the spec, this allow to select * a preferred bit depth for creating the KoColor object (if that * bit depth isn't available, this function will randomly select * an other bit depth) * @param ok If a an error occurs, *ok is set to false; otherwise it's set to true * @return the unserialize color, or an empty color object if the function failed * to unserialize the color */ static KoColor fromXML(const QDomElement& elt, const QString & bitDepthId, bool* ok); /** * @brief toQString create a user-visible string of the channel names and the channel values * @param color the color to create the string from * @return a string that can be used to display the values of this color to the user. */ static QString toQString(const KoColor &color); #ifndef NODEBUG /// use qDebug calls to print internal info void dump() const; #endif private: inline void assertPermanentColorspace() { #ifndef NODEBUG if (m_colorSpace) { Q_ASSERT(*m_colorSpace == *KoColorSpaceRegistry::instance()->permanentColorspace(m_colorSpace)); } #endif } const KoColorSpace *m_colorSpace; quint8 m_data[MAX_PIXEL_SIZE]; quint8 m_size; }; Q_DECLARE_METATYPE(KoColor) KRITAPIGMENT_EXPORT QDebug operator<<(QDebug dbg, const KoColor &color); #endif diff --git a/libs/pigment/KoColorSpace.h b/libs/pigment/KoColorSpace.h index 67fa12d938..0631892d6a 100644 --- a/libs/pigment/KoColorSpace.h +++ b/libs/pigment/KoColorSpace.h @@ -1,644 +1,640 @@ /* * Copyright (c) 2005 Boudewijn Rempt * Copyright (c) 2006-2007 Cyrille Berger * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOCOLORSPACE_H #define KOCOLORSPACE_H #include #include #include #include #include #include #include "KoColorSpaceConstants.h" #include "KoColorConversionTransformation.h" #include "KoColorProofingConversionTransformation.h" #include "KoCompositeOp.h" #include #include "kritapigment_export.h" class QDomDocument; class QDomElement; class KoChannelInfo; class KoColorProfile; class KoColorTransformation; class QBitArray; enum Deletability { OwnedByRegistryDoNotDelete, OwnedByRegistryRegistryDeletes, NotOwnedByRegistry }; enum ColorSpaceIndependence { FULLY_INDEPENDENT, TO_LAB16, TO_RGBA8, TO_RGBA16 }; class KoMixColorsOp; class KoConvolutionOp; /** * A KoColorSpace is the definition of a certain color space. * * A color model and a color space are two related concepts. A color * model is more general in that it describes the channels involved and * how they in broad terms combine to describe a color. Examples are * RGB, HSV, CMYK. * * A color space is more specific in that it also describes exactly how * the channels are combined. So for each color model there can be a * number of specific color spaces. So RGB is the model and sRGB, * adobeRGB, etc are colorspaces. * * In Pigment KoColorSpace acts as both a color model and a color space. * You can think of the class definition as the color model, but the * instance of the class as representing a colorspace. * * A third concept is the profile represented by KoColorProfile. It * represents the info needed to specialize a color model into a color * space. * * KoColorSpace is an abstract class serving as an interface. * * Subclasses implement actual color spaces * Some subclasses implement only some parts and are named Traits * */ class KRITAPIGMENT_EXPORT KoColorSpace : public boost::equality_comparable { friend class KoColorSpaceRegistry; friend class KoColorSpaceFactory; protected: /// Only for use by classes that serve as baseclass for real color spaces KoColorSpace(); public: /// Should be called by real color spaces KoColorSpace(const QString &id, const QString &name, KoMixColorsOp* mixColorsOp, KoConvolutionOp* convolutionOp); virtual bool operator==(const KoColorSpace& rhs) const; protected: virtual ~KoColorSpace(); public: //========== Gamut and other basic info ===================================// /* * @returns QPolygonF with 5*channel samples converted to xyY. * maybe convert to 3d space in future? */ QPolygonF gamutXYY() const; /* * @returns a polygon with 5 samples per channel converted to xyY, but unlike * gamutxyY it focuses on the luminance. This then can be used to visualise * the approximate trc of a given colorspace. */ QPolygonF estimatedTRCXYY() const; QVector lumaCoefficients() const; //========== Channels =====================================================// /// Return a list describing all the channels this color model has. The order /// of the channels in the list is the order of channels in the pixel. To find /// out the preferred display position, use KoChannelInfo::displayPosition. QList channels() const; /** * The total number of channels for a single pixel in this color model */ virtual quint32 channelCount() const = 0; /** * The total number of color channels (excludes alpha) for a single * pixel in this color model. */ virtual quint32 colorChannelCount() const = 0; /** * returns a QBitArray that contains true for the specified * channel types: * * @param color if true, set all color channels to true * @param alpha if true, set all alpha channels to true * * The order of channels is the colorspace descriptive order, * not the pixel order. */ QBitArray channelFlags(bool color = true, bool alpha = false) const; /** * The size in bytes of a single pixel in this color model */ virtual quint32 pixelSize() const = 0; /** * Return a string with the channel's value suitable for display in the gui. */ virtual QString channelValueText(const quint8 *pixel, quint32 channelIndex) const = 0; /** * Return a string with the channel's value with integer * channels normalised to the floating point range 0 to 1, if * appropriate. */ virtual QString normalisedChannelValueText(const quint8 *pixel, quint32 channelIndex) const = 0; /** * Return a QVector of floats with channels' values normalized * to floating point range 0 to 1. */ virtual void normalisedChannelsValue(const quint8 *pixel, QVector &channels) const = 0; /** * Write in the pixel the value from the normalized vector. */ virtual void fromNormalisedChannelsValue(quint8 *pixel, const QVector &values) const = 0; /** * Convert the value of the channel at the specified position into * an 8-bit value. The position is not the number of bytes, but * the position of the channel as defined in the channel info list. */ virtual quint8 scaleToU8(const quint8 * srcPixel, qint32 channelPos) const = 0; /** * Set dstPixel to the pixel containing only the given channel of srcPixel. The remaining channels * should be set to whatever makes sense for 'empty' channels of this color space, * with the intent being that the pixel should look like it only has the given channel. */ virtual void singleChannelPixel(quint8 *dstPixel, const quint8 *srcPixel, quint32 channelIndex) const = 0; //========== Identification ===============================================// /** * ID for use in files and internally: unchanging name. As the id must be unique * it is usually the concatenation of the id of the color model and of the color * depth, for instance "RGBA8" or "CMYKA16" or "XYZA32f". */ QString id() const; /** * User visible name which contains the name of the color model and of the color depth. * For instance "RGBA (8-bits)" or "CMYKA (16-bits)". */ QString name() const; /** * @return a string that identify the color model (for instance "RGB" or "CMYK" ...) * @see KoColorModelStandardIds.h */ virtual KoID colorModelId() const = 0; /** * @return a string that identify the bit depth (for instance "U8" or "F16" ...) * @see KoColorModelStandardIds.h */ virtual KoID colorDepthId() const = 0; /** * @return true if the profile given in argument can be used by this color space */ virtual bool profileIsCompatible(const KoColorProfile* profile) const = 0; /** * If false, images in this colorspace will degrade considerably by * functions, tools and filters that have the given measure of colorspace * independence. * * @param independence the measure to which this colorspace will suffer * from the manipulations of the tool or filter asking * @return false if no degradation will take place, true if degradation will * take place */ virtual bool willDegrade(ColorSpaceIndependence independence) const = 0; //========== Capabilities =================================================// /** * Tests if the colorspace offers the specific composite op. */ virtual bool hasCompositeOp(const QString & id) const; /** * Returns the list of user-visible composite ops supported by this colorspace. */ virtual QList compositeOps() const; /** * Retrieve a single composite op from the ones this colorspace offers. * If the requeste composite op does not exist, COMPOSITE_OVER is returned. */ const KoCompositeOp * compositeOp(const QString & id) const; /** * add a composite op to this colorspace. */ virtual void addCompositeOp(const KoCompositeOp * op); /** * Returns true if the colorspace supports channel values outside the * (normalised) range 0 to 1. */ virtual bool hasHighDynamicRange() const = 0; //========== Display profiles =============================================// /** * Return the profile of this color space. */ virtual const KoColorProfile * profile() const = 0; //================= Conversion functions ==================================// /** * The fromQColor methods take a given color defined as an RGB QColor * and fills a byte array with the corresponding color in the * the colorspace managed by this strategy. * * @param color the QColor that will be used to fill dst * @param dst a pointer to a pixel * @param profile the optional profile that describes the color values of QColor */ virtual void fromQColor(const QColor& color, quint8 *dst, const KoColorProfile * profile = 0) const = 0; /** * The toQColor methods take a byte array that is at least pixelSize() long * and converts the contents to a QColor, using the given profile as a source * profile and the optional profile as a destination profile. * * @param src a pointer to the source pixel * @param c the QColor that will be filled with the color at src * @param profile the optional profile that describes the color in c, for instance the monitor profile */ virtual void toQColor(const quint8 *src, QColor *c, const KoColorProfile * profile = 0) const = 0; /** * Convert the pixels in data to (8-bit BGRA) QImage using the specified profiles. * * @param data A pointer to a contiguous memory region containing width * height pixels * @param width in pixels * @param height in pixels * @param dstProfile destination profile * @param renderingIntent the rendering intent */ virtual QImage convertToQImage(const quint8 *data, qint32 width, qint32 height, const KoColorProfile * dstProfile, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags) const; /** * Convert the specified data to Lab (D50). All colorspaces are guaranteed to support this * * @param src the source data * @param dst the destination data * @param nPixels the number of source pixels */ virtual void toLabA16(const quint8 * src, quint8 * dst, quint32 nPixels) const; /** * Convert the specified data from Lab (D50). to this colorspace. All colorspaces are * guaranteed to support this. * * @param src the pixels in 16 bit lab format * @param dst the destination data * @param nPixels the number of pixels in the array */ virtual void fromLabA16(const quint8 * src, quint8 * dst, quint32 nPixels) const; /** * Convert the specified data to sRGB 16 bits. All colorspaces are guaranteed to support this * * @param src the source data * @param dst the destination data * @param nPixels the number of source pixels */ virtual void toRgbA16(const quint8 * src, quint8 * dst, quint32 nPixels) const; /** * Convert the specified data from sRGB 16 bits. to this colorspace. All colorspaces are * guaranteed to support this. * * @param src the pixels in 16 bit rgb format * @param dst the destination data * @param nPixels the number of pixels in the array */ virtual void fromRgbA16(const quint8 * src, quint8 * dst, quint32 nPixels) const; /** * Create a color conversion transformation. */ virtual KoColorConversionTransformation* createColorConverter(const KoColorSpace * dstColorSpace, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags) const; /** * Convert a byte array of srcLen pixels *src to the specified color space * and put the converted bytes into the prepared byte array *dst. * * Returns false if the conversion failed, true if it succeeded * * This function is not thread-safe. If you want to apply multiple conversion * in different threads at the same time, you need to create one color converter * per-thread using createColorConverter. */ virtual bool convertPixelsTo(const quint8 * src, quint8 * dst, const KoColorSpace * dstColorSpace, quint32 numPixels, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags) const; virtual KoColorConversionTransformation *createProofingTransform(const KoColorSpace * dstColorSpace, const KoColorSpace * proofingSpace, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::Intent proofingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags, quint8 *gamutWarning, double adaptationState) const; /** * @brief proofPixelsTo - * @param src - * @param dst - * @param dstColorSpace the colorspace to which we go to. - * @param proofingSpace the proofing space. + * @param src source + * @param dst destination * @param numPixels the amount of pixels. - * @param renderingIntent the rendering intent used for rendering. - * @param proofingIntent the intent used for proofing. - * @param conversionFlags the conversion flags. - * @param gamutWarning the data() of a KoColor. - * @param adaptationState the state of adaptation, only affects absolute colorimetric. + * @param proofingTransform the intent used for proofing. * @return */ virtual bool proofPixelsTo(const quint8 * src, quint8 * dst, quint32 numPixels, KoColorConversionTransformation *proofingTransform) const; //============================== Manipulation functions ==========================// // // The manipulation functions have default implementations that _convert_ the pixel // to a QColor and back. Reimplement these methods in your color strategy! // /** * Get the alpha value of the given pixel, downscaled to an 8-bit value. */ virtual quint8 opacityU8(const quint8 * pixel) const = 0; virtual qreal opacityF(const quint8 * pixel) const = 0; /** * Set the alpha channel of the given run of pixels to the given value. * * pixels -- a pointer to the pixels that will have their alpha set to this value * alpha -- a downscaled 8-bit value for opacity * nPixels -- the number of pixels * */ virtual void setOpacity(quint8 * pixels, quint8 alpha, qint32 nPixels) const = 0; virtual void setOpacity(quint8 * pixels, qreal alpha, qint32 nPixels) const = 0; /** * Multiply the alpha channel of the given run of pixels by the given value. * * pixels -- a pointer to the pixels that will have their alpha set to this value * alpha -- a downscaled 8-bit value for opacity * nPixels -- the number of pixels * */ virtual void multiplyAlpha(quint8 * pixels, quint8 alpha, qint32 nPixels) const = 0; /** * Applies the specified 8-bit alpha mask to the pixels. We assume that there are just * as many alpha values as pixels but we do not check this; the alpha values * are assumed to be 8-bits. */ virtual void applyAlphaU8Mask(quint8 * pixels, const quint8 * alpha, qint32 nPixels) const = 0; /** * Applies the inverted 8-bit alpha mask to the pixels. We assume that there are just * as many alpha values as pixels but we do not check this; the alpha values * are assumed to be 8-bits. */ virtual void applyInverseAlphaU8Mask(quint8 * pixels, const quint8 * alpha, qint32 nPixels) const = 0; /** * Applies the specified float alpha mask to the pixels. We assume that there are just * as many alpha values as pixels but we do not check this; alpha values have to be between 0.0 and 1.0 */ virtual void applyAlphaNormedFloatMask(quint8 * pixels, const float * alpha, qint32 nPixels) const = 0; /** * Applies the inverted specified float alpha mask to the pixels. We assume that there are just * as many alpha values as pixels but we do not check this; alpha values have to be between 0.0 and 1.0 */ virtual void applyInverseNormedFloatMask(quint8 * pixels, const float * alpha, qint32 nPixels) const = 0; /** * Create an adjustment object for adjusting the brightness and contrast * transferValues is a 256 bins array with values from 0 to 0xFFFF * This function is thread-safe, but you need to create one KoColorTransformation per thread. */ virtual KoColorTransformation *createBrightnessContrastAdjustment(const quint16 *transferValues) const = 0; /** * Create an adjustment object for adjusting individual channels * transferValues is an array of colorChannelCount number of 256 bins array with values from 0 to 0xFFFF * This function is thread-safe, but you need to create one KoColorTransformation per thread. * * The layout of the channels must be the following: * * 0..N-2 - color channels of the pixel; * N-1 - alpha channel of the pixel (if exists) */ virtual KoColorTransformation *createPerChannelAdjustment(const quint16 * const* transferValues) const = 0; /** * Darken all color channels with the given amount. If compensate is true, * the compensation factor will be used to limit the darkening. * */ virtual KoColorTransformation *createDarkenAdjustment(qint32 shade, bool compensate, qreal compensation) const = 0; /** * Invert color channels of the given pixels * This function is thread-safe, but you need to create one KoColorTransformation per thread. */ virtual KoColorTransformation *createInvertTransformation() const = 0; /** * Get the difference between 2 colors, normalized in the range (0,255). Only completely * opaque and completely transparent are taken into account when computing the difference; * other transparency levels are not regarded when finding the difference. */ virtual quint8 difference(const quint8* src1, const quint8* src2) const = 0; /** * Get the difference between 2 colors, normalized in the range (0,255). This function * takes the Alpha channel of the pixel into account. Alpha channel has the same * weight as Lightness channel. */ virtual quint8 differenceA(const quint8* src1, const quint8* src2) const = 0; /** * @return the mix color operation of this colorspace (do not delete it locally, it's deleted by the colorspace). */ virtual KoMixColorsOp* mixColorsOp() const; /** * @return the convolution operation of this colorspace (do not delete it locally, it's deleted by the colorspace). */ virtual KoConvolutionOp* convolutionOp() const; /** * Calculate the intensity of the given pixel, scaled down to the range 0-255. XXX: Maybe this should be more flexible */ virtual quint8 intensity8(const quint8 * src) const = 0; /* *increase luminosity by step */ virtual void increaseLuminosity(quint8 * pixel, qreal step) const; virtual void decreaseLuminosity(quint8 * pixel, qreal step) const; virtual void increaseSaturation(quint8 * pixel, qreal step) const; virtual void decreaseSaturation(quint8 * pixel, qreal step) const; virtual void increaseHue(quint8 * pixel, qreal step) const; virtual void decreaseHue(quint8 * pixel, qreal step) const; virtual void increaseRed(quint8 * pixel, qreal step) const; virtual void increaseGreen(quint8 * pixel, qreal step) const; virtual void increaseBlue(quint8 * pixel, qreal step) const; virtual void increaseYellow(quint8 * pixel, qreal step) const; virtual void toHSY(const QVector &channelValues, qreal *hue, qreal *sat, qreal *luma) const = 0; virtual QVector fromHSY(qreal *hue, qreal *sat, qreal *luma) const = 0; virtual void toYUV(const QVector &channelValues, qreal *y, qreal *u, qreal *v) const = 0; virtual QVector fromYUV(qreal *y, qreal *u, qreal *v) const = 0; /** * Compose two arrays of pixels together. If source and target * are not the same color model, the source pixels will be * converted to the target model. We're "dst" -- "dst" pixels are always in _this_ * colorspace. * * @param srcSpace the colorspace of the source pixels that will be composited onto "us" - * @param param the information needed for blitting e.g. the source and destination pixel data, + * @param params the information needed for blitting e.g. the source and destination pixel data, * the opacity and flow, ... * @param op the composition operator to use, e.g. COPY_OVER + * @param renderingIntent the rendering intent + * @param conversionFlags the conversion flags. * */ virtual void bitBlt(const KoColorSpace* srcSpace, const KoCompositeOp::ParameterInfo& params, const KoCompositeOp* op, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags) const; /** * Serialize this color following Create's swatch color specification available * at http://create.freedesktop.org/wiki/index.php/Swatches_-_colour_file_format * * This function doesn't create the element but rather the , * , ... elements. It is assumed that colorElt is the * element. * * @param pixel buffer to serialized * @param colorElt root element for the serialization, it is assumed that this * element is * @param doc is the document containing colorElt */ virtual void colorToXML(const quint8* pixel, QDomDocument& doc, QDomElement& colorElt) const = 0; /** * Unserialize a color following Create's swatch color specification available * at http://create.freedesktop.org/wiki/index.php/Swatches_-_colour_file_format * * @param pixel buffer where the color will be unserialized * @param elt the element to unserialize (, , ) * @return the unserialize color, or an empty color object if the function failed * to unserialize the color */ virtual void colorFromXML(quint8* pixel, const QDomElement& elt) const = 0; KoColorTransformation* createColorTransformation(const QString & id, const QHash & parameters) const; protected: /** * Use this function in the constructor of your colorspace to add the information about a channel. * @param ci a pointer to the information about a channel */ virtual void addChannel(KoChannelInfo * ci); const KoColorConversionTransformation* toLabA16Converter() const; const KoColorConversionTransformation* fromLabA16Converter() const; const KoColorConversionTransformation* toRgbA16Converter() const; const KoColorConversionTransformation* fromRgbA16Converter() const; /** * Returns the thread-local conversion cache. If it doesn't exist * yet, it is created. If it is currently too small, it is resized. */ QVector * threadLocalConversionCache(quint32 size) const; /** * This function defines the behavior of the bitBlt function * when the composition of pixels in different colorspaces is * requested, that is in case: * * srcCS == any * dstCS == this * * 1) preferCompositionInSourceColorSpace() == false, * * the source pixels are first converted to *this color space * and then composition is performed. * * 2) preferCompositionInSourceColorSpace() == true, * * the destination pixels are first converted into *srcCS color * space, then the composition is done, and the result is finally * converted into *this colorspace. * * This is used by alpha8() color space mostly, because it has * weaker representation of the color, so the composition * should be done in CS with richer functionality. */ virtual bool preferCompositionInSourceColorSpace() const; struct Private; Private * const d; }; inline QDebug operator<<(QDebug dbg, const KoColorSpace *cs) { if (cs) { dbg.nospace() << cs->name() << " (" << cs->colorModelId().id() << "," << cs->colorDepthId().id() << " )"; } else { dbg.nospace() << "0x0"; } return dbg.space(); } #endif // KOCOLORSPACE_H diff --git a/libs/pigment/resources/KisSwatchGroup.h b/libs/pigment/resources/KisSwatchGroup.h index de32624bdd..e98515edea 100644 --- a/libs/pigment/resources/KisSwatchGroup.h +++ b/libs/pigment/resources/KisSwatchGroup.h @@ -1,127 +1,127 @@ /* This file is part of the KDE project Copyright (c) 2005 Boudewijn Rempt Copyright (c) 2016 L. E. Segovia Copyright (c) 2018 Michael Zhou This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KISSWATCHGROUP_H #define KISSWATCHGROUP_H #include "KisSwatch.h" #include "kritapigment_export.h" #include #include #include #include /** * @brief The KisSwatchGroup class stores a matrix of color swatches * swatches can accessed using (x, y) coordinates. * x is the column number from left to right and y is the row number from top * to bottom. * Both x and y start at 0 * there could be empty entries, so the checkEntry(int, int) method must used * whenever you want to get an entry from the matrix */ class KRITAPIGMENT_EXPORT KisSwatchGroup { public /* struct */: struct SwatchInfo { QString group; KisSwatch swatch; int row; int column; }; public: KisSwatchGroup(); ~KisSwatchGroup(); KisSwatchGroup(const KisSwatchGroup &rhs); KisSwatchGroup &operator =(const KisSwatchGroup &rhs); public /* methods */: void setName(const QString &name); QString name() const; void setColumnCount(int columnCount); int columnCount() const; void setRowCount(int newRowCount); int rowCount() const; int colorCount() const; QList infoList() const; /** * @brief checkEntry - * checks if position x and y has a valid entry - * both x and y start from 0 - * @param x - * @param y - * @return true if there is a valid entry at position (x, y) + * checks if position @p column and @p row has a valid entry + * both @p column and @p row start from 0 + * @param column + * @param row + * @return true if there is a valid entry at position (column, row) */ bool checkEntry(int column, int row) const; /** * @brief setEntry - * sets the entry at position (x, y) to be e + * sets the entry at position (@p column, @p row) to be @p e * @param e - * @param x - * @param y + * @param column + * @param row */ void setEntry(const KisSwatch &e, int column, int row); /** * @brief getEntry - * used to get the swatch entry at position (x, y) + * used to get the swatch entry at position (@p column, @p row) * there is an assertion to make sure that this position isn't empty, * so checkEntry(int, int) must be used before this method to ensure * a valid entry can be found - * @param x - * @param y - * @return the swatch entry at position (x, y) + * @param column + * @param row + * @return the swatch entry at position (column, row) */ KisSwatch getEntry(int column, int row) const; /** * @brief removeEntry - * removes the entry at position (x, y) - * @param x - * @param y - * @return true if these is an entry at (x, y) + * removes the entry at position (@p column, @p row) + * @param column + * @param row + * @return true if these is an entry at (column, row) */ bool removeEntry(int column, int row); /** * @brief addEntry * adds the entry e to the right of the rightmost entry in the last row * if the rightmost entry in the last row is in the right most column, * add e to the leftmost column of a new row * * when column is set to 0, resize number of columns to default * @param e */ void addEntry(const KisSwatch &e); void clear(); private /* member variables */: struct Private; QScopedPointer d; }; #endif // KISSWATCHGROUP_H diff --git a/libs/pigment/resources/KoColorSet.h b/libs/pigment/resources/KoColorSet.h index 60ca58b30a..00b9df20cc 100644 --- a/libs/pigment/resources/KoColorSet.h +++ b/libs/pigment/resources/KoColorSet.h @@ -1,216 +1,218 @@ /* This file is part of the KDE project Copyright (c) 2005 Boudewijn Rempt Copyright (c) 2016 L. E. Segovia This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KOCOLORSET #define KOCOLORSET #include #include #include #include #include #include "KoColor.h" #include "KisSwatch.h" #include "KisSwatchGroup.h" /** * Also called palette. * Open Gimp, Photoshop or RIFF palette files. This is a straight port * from the Gimp. */ class KRITAPIGMENT_EXPORT KoColorSet : public QObject, public KoResource { Q_OBJECT public: static const QString GLOBAL_GROUP_NAME; static const QString KPL_VERSION_ATTR; static const QString KPL_GROUP_ROW_COUNT_ATTR; static const QString KPL_PALETTE_COLUMN_COUNT_ATTR; static const QString KPL_PALETTE_NAME_ATTR; static const QString KPL_PALETTE_COMMENT_ATTR; static const QString KPL_PALETTE_FILENAME_ATTR; static const QString KPL_PALETTE_READONLY_ATTR; static const QString KPL_COLOR_MODEL_ID_ATTR; static const QString KPL_COLOR_DEPTH_ID_ATTR; static const QString KPL_GROUP_NAME_ATTR; static const QString KPL_SWATCH_ROW_ATTR; static const QString KPL_SWATCH_COL_ATTR; static const QString KPL_SWATCH_NAME_ATTR; static const QString KPL_SWATCH_SPOT_ATTR; static const QString KPL_SWATCH_ID_ATTR; static const QString KPL_SWATCH_BITDEPTH_ATTR; static const QString KPL_PALETTE_PROFILE_TAG; static const QString KPL_SWATCH_POS_TAG; static const QString KPL_SWATCH_TAG; static const QString KPL_GROUP_TAG; static const QString KPL_PALETTE_TAG; public: enum PaletteType { UNKNOWN = 0, GPL, // GIMP RIFF_PAL, // RIFF ACT, // Photoshop binary PSP_PAL, // PaintShop Pro ACO, // Photoshop Swatches XML, // XML palette (Scribus) KPL, // KoColor-based XML palette SBZ // SwatchBooker }; /** * Load a color set from a file. This can be a Gimp * palette, a RIFF palette, a Photoshop palette, * a Krita palette, * a Scribus palette or a SwatchBooker palette. */ explicit KoColorSet(const QString &filename = QString()); // Explicit copy constructor (KoResource copy constructor is private) KoColorSet(const KoColorSet& rhs); public /* overridden methods */: // KoResource ~KoColorSet() override; bool load() override; bool loadFromDevice(QIODevice *dev) override; bool save() override; bool saveToDevice(QIODevice* dev) const override; QString defaultFileExtension() const override; public /* methods */: void setColumnCount(int columns); int columnCount() const; void setComment(QString comment); QString comment(); int rowCount() const; quint32 colorCount() const; PaletteType paletteType() const; void setPaletteType(PaletteType paletteType); /** * @brief isGlobal * A global color set is a set stored in the config directory * Such a color set would be opened every time Krita is launched. * * A non-global color set, on contrary, would be stored in a kra file, * and would only be opened when that file is opened by Krita. * @return */ bool isGlobal() const; void setIsGlobal(bool); bool isEditable() const; void setIsEditable(bool isEditable); QByteArray toByteArray() const; bool fromByteArray(QByteArray &data); /** * @brief add Add a color to the palette. * @param groupName color to add the group to. If empty, it will be added to the unsorted. */ void add(const KisSwatch &, const QString &groupName = GLOBAL_GROUP_NAME); void setEntry(const KisSwatch &e, int x, int y, const QString &groupName = GLOBAL_GROUP_NAME); /** * @brief getColorGlobal - * A function for getting a color based on a global index. Useful for itterating through all color entries. - * @param globalIndex the global index over the whole palette. + * A function for getting a color based on a global index. Useful for iterating through all color entries. + * @param x the global x index over the whole palette. + * @param y the global y index over the whole palette. * @return the entry. */ KisSwatch getColorGlobal(quint32 x, quint32 y) const; /** * @brief getColorGroup * A function for getting the color from a specific group. - * @param groupName the name of the group, will give unosrted when not defined. - * @param index the index within the group. + * @param x the x index over the group. + * @param y the y index over the group. + * @param groupName the name of the group, will give unsorted when not defined. * @return the entry */ KisSwatch getColorGroup(quint32 x, quint32 y, QString groupName); /** * @brief getGroupNames * @return returns a list of group names, excluding the unsorted group. */ QStringList getGroupNames(); /** * @brief getGroup * @param name * @return the group with the name given; global group if no parameter is given * null pointer if not found. */ KisSwatchGroup *getGroup(const QString &name); KisSwatchGroup *getGlobalGroup(); bool changeGroupName(const QString &oldGroupName, const QString &newGroupName); /** * @brief addGroup * Adds a new group. * @param groupName the name of the new group. When not specified, this will fail. * @return whether thegroup was made. */ bool addGroup(const QString &groupName); /** * @brief moveGroup * Move a group in the internal stringlist. * @param groupName the groupname to move. * @param groupNameInsertBefore the groupname to insert before. Empty means it will be added to the end. * @return */ bool moveGroup(const QString &groupName, const QString &groupNameInsertBefore = GLOBAL_GROUP_NAME); /** * @brief removeGroup * Remove a group from the KoColorSet * @param groupName the name of the group you want to remove. * @param keepColors Whether you wish to keep the colorsetentries. These will be added to the unsorted. * @return whether it could find the group to remove. */ bool removeGroup(const QString &groupName, bool keepColors = true); void clear(); /** * @brief getIndexClosestColor * function that matches the color to all colors in the colorset, and returns the index * of the closest match. - * @param color the color you wish to compare. + * @param compare the color you wish to compare. * @param useGivenColorSpace whether to use the color space of the color given * when the two colors' colorspaces don't match. Else it'll use the entry's colorspace. * @return returns the int of the closest match. */ KisSwatchGroup::SwatchInfo getClosestColorInfo(KoColor compare, bool useGivenColorSpace = true); private: class Private; const QScopedPointer d; }; #endif // KOCOLORSET diff --git a/libs/store/KoStore_p.h b/libs/store/KoStore_p.h index 75b5f6ef58..4a6c6e0ff4 100644 --- a/libs/store/KoStore_p.h +++ b/libs/store/KoStore_p.h @@ -1,107 +1,107 @@ /* This file is part of the KDE project Copyright 2004 Nicolas GOUTTE This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef __koStore_p_h_ #define __koStore_p_h_ #include "KoStore.h" #include #include #include class QWidget; class KoStorePrivate { public: explicit KoStorePrivate(KoStore *qq, KoStore::Mode _mode, bool _writeMimetype) : q(qq), window(0), mode(_mode), size(0), stream(0), isOpen(false), good(false), finalized(false), writeMimetype(_writeMimetype) { } /** * Conversion routine - * @param _internalNaming name used internally : "root", "tar:/0", ... + * @param internalNaming name used internally : "root", "tar:/0", ... * @return the name used in the file, more user-friendly ("maindoc.xml", * "part0/maindoc.xml", ...) * Examples: * * tar:/0 is saved as part0/maindoc.xml * tar:/0/1 is saved as part0/part1/maindoc.xml * tar:/0/1/pictures/picture0.png is saved as part0/part1/pictures/picture0.png * * see specification (calligra/lib/store/SPEC) for details. */ QString toExternalNaming(const QString &internalNaming) const; /** * Enter *one* single directory. Nothing like foo/bar/bleh allowed. * Performs some checking when in Read mode */ bool enterDirectoryInternal(const QString &directory); bool extractFile(const QString &sourceName, QIODevice &buffer); KoStore *q; /** * original URL of the remote file * (undefined for a local file) */ QUrl url; QString localFileName; QWidget *window; KoStore::Mode mode; /// Store the filenames (with full path inside the archive) when writing, to avoid duplicates QStringList filesList; /// The "current directory" (path) QStringList currentPath; /// Current filename (between an open() and a close()) QString fileName; /// Current size of the file named m_sName qint64 size; /// The stream for the current read or write operation QIODevice *stream; bool isOpen; /// Must be set by the constructor. bool good; bool finalized; QStack directoryStack; bool writeMimetype; ///< true if the backend is allowed to create "mimetype" automatically. }; #endif diff --git a/libs/ui/KisOpenPane.h b/libs/ui/KisOpenPane.h index 79c8d82aba..cb21f46a1c 100644 --- a/libs/ui/KisOpenPane.h +++ b/libs/ui/KisOpenPane.h @@ -1,108 +1,109 @@ /* This file is part of the KDE project Copyright (C) 2005 Peter Simonsson This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KISOPENPANE_H #define KISOPENPANE_H #include #include #include #include class KisDetailsPane; class KisDocument; class KisOpenPanePrivate; class KisTemplatesPane; class QPixmap; class QString; class QStringList; class QTreeWidgetItem; class QUrl; /// \internal class KisOpenPane : public QDialog { Q_OBJECT public: /** * Constructor - * @param parent the parent widget - * @param templateType the template-type (group) that should be selected on creation. + * @param parent the parent widget. + * @param mimeType the template-type (group) that should be selected on creation. + * @param templatesResourcePath the path to the templates. */ KisOpenPane(QWidget *parent, const QStringList& mimeFilter, const QString& templatesResourcePath = QString()); ~KisOpenPane() override; QTreeWidgetItem* addPane(const QString &title, const QString &iconName, QWidget *widget, int sortWeight); QTreeWidgetItem* addPane(const QString& title, const QPixmap& icon, QWidget* widget, int sortWeight); /** * If the application has a way to create a document not based on a template, but on user * provided settings, the widget showing these gets set here. * @see KisDocument::createCustomDocumentWidget() * @param widget the widget. * @param title the title shown in the sidebar * @param icon the icon shown in the sidebar */ void addCustomDocumentWidget(QWidget *widget, const QString& title = QString(), const QString& icon = QString()); Q_SIGNALS: /// this signal is emitted (as defined by KisDocument) the moment the document is 'ready' void documentSelected(KisDocument*); protected Q_SLOTS: void updateSelectedWidget(); void itemClicked(QTreeWidgetItem* item); /// Saves the splitter sizes for KisDetailsPaneBase based panes void saveSplitterSizes(KisDetailsPane* sender, const QList& sizes); private Q_SLOTS: /// when clicked "Open Existing Document" button void openFileDialog(); Q_SIGNALS: void openExistingFile(const QUrl&); void openTemplate(const QUrl&); /// Emitted when the always use template has changed void alwaysUseChanged(KisTemplatesPane* sender, const QString& alwaysUse); /// Emitted when one of the detail panes have changed it's splitter void splitterResized(KisDetailsPane* sender, const QList& sizes); void cancelButton(); protected: /** * Populate the list with all templates the user can choose. * @param templatesResourcePath the template-type (group) that should be selected on creation. */ void initTemplates(const QString& templatesResourcePath); // QWidget overrides void dragEnterEvent(QDragEnterEvent * event) override; void dropEvent(QDropEvent * event) override; private: QStringList m_mimeFilter; KisOpenPanePrivate * const d; }; #endif //KOOPENPANE_H diff --git a/libs/ui/KisPaletteEditor.h b/libs/ui/KisPaletteEditor.h index abda68e712..6573ff7fdd 100644 --- a/libs/ui/KisPaletteEditor.h +++ b/libs/ui/KisPaletteEditor.h @@ -1,148 +1,146 @@ /* * Copyright (c) 2018 Michael Zhou * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KISPALETTEMANAGER_H #define KISPALETTEMANAGER_H #include #include #include #include class KoColorSet; class KisPaletteModel; class KisViewManager; class KisSwatchGroup; class KisViewManager; /** * @brief The PaletteEditor class * this class manipulates a KisPaletteModel using GUI elements and communicate * with KisDocument * * Changes made in this class won't be done to the palette if the palette is * read only (not editable, isEditable() == false) */ class KRITAUI_EXPORT KisPaletteEditor : public QObject { Q_OBJECT public: struct PaletteInfo; public: explicit KisPaletteEditor(QObject *parent = Q_NULLPTR); ~KisPaletteEditor(); void setPaletteModel(KisPaletteModel *model); void setView(KisViewManager *view); void addPalette(); void importPalette(); void removePalette(KoColorSet *); /** * @brief rowNumberOfGroup * @param oriName the original name of a group at the creation of the instance * @return newest row number of the group */ int rowNumberOfGroup(const QString &oriName) const; /** * @brief oldNameFromNewName * @param newName the current name of a group * @return the name of the group at the creation of the instance */ QString oldNameFromNewName(const QString &newName) const; /** * @brief duplicateExistsFilename - * @param name + * @param filename the name of the file * @param global if this filename is going to be used for a global palette * @return true if the a palette in the resource system that has filename * name already exists else false */ bool duplicateExistsFilename(const QString &filename, bool global) const; QString relativePathFromSaveLocation() const; void rename(const QString &newName); void changeFilename(const QString &newName); void changeColCount(int); /** * @brief addGroup - * @param name original group name - * @param rowNumber - * @return new group's name if change accpeted, empty string if cancelled + * @return new group's name if change accepted, empty string if cancelled */ QString addGroup(); /** * @brief removeGroup * @param name original group name * @return true if change accepted, false if cancelled */ bool removeGroup(const QString &name); /** * @brief renameGroup * @param oldName * @return new name if change accpeted, empty string if cancelled */ QString renameGroup(const QString &oldName); void changeGroupRowCount(const QString &name, int newRowCount); void setGlobal(bool); void setReadOnly(bool); void setEntry(const KoColor &color, const QModelIndex &index); void removeEntry(const QModelIndex &index); void modifyEntry(const QModelIndex &index); void addEntry(const KoColor &color); bool isModified() const; /** * @brief getModifiedGroup * @param originalName name of the group at the creation of the instance * @return the modified group */ const KisSwatchGroup &getModifiedGroup(const QString &originalName) const; /** * @brief updatePalette * MUST be called to make the changes into the resource server */ void updatePalette(); private Q_SLOTS: void slotGroupNameChanged(const QString &newName); void slotPaletteChanged(); void slotSetDocumentModified(); private: QString newPaletteFileName(bool isGlobal); QString newGroupName() const; void setNonGlobal(); void setGlobal(); bool duplicateExistsGroupName(const QString &name) const; bool duplicateExistsOriginalGroupName(const QString &name) const; void uploadPaletteList() const; QString filenameFromPath(const QString &path) const; private: struct Private; QScopedPointer m_d; }; #endif // KISPALETTEMANAGER_H diff --git a/libs/ui/KisPrintJob.h b/libs/ui/KisPrintJob.h index d0ab757f04..0698448f15 100644 --- a/libs/ui/KisPrintJob.h +++ b/libs/ui/KisPrintJob.h @@ -1,95 +1,95 @@ /* This file is part of the KDE project * Copyright (C) 2007 Thomas Zander * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KISPRINTJOB_H #define KISPRINTJOB_H #include #include #include #include #include "kritaui_export.h" #include /** * A print job is an interface that the KisView uses to create an application-specific * class that can take care of printing. * The printjob should be able to print again after a print job has been completed, * using the same QPrinter to allow the user to alter settings on the QPrinter and * call print again. * The printjob can thus see startPrinting() called more than once, and the implementation * of that signal should honor the removePolicy passed to it. */ class KRITAUI_EXPORT KisPrintJob : public QObject { Q_OBJECT public: /** * Constructor. - * @param parent the parent qobject that is passed for memory management purposes. + * @param image the image that is passed for management purposes. */ explicit KisPrintJob(KisImageWSP image); ~KisPrintJob() override; /// A policy to allow the printjob to delete itself after its done printing. enum RemovePolicy { DeleteWhenDone, ///< Delete the job when its done with printing. DoNotDelete ///< Keep the job around so it can be started again. }; /// Returns the printer that is used for this print job so others can alter the details of the print-job. QPrinter &printer() { return m_printer; } int documentFirstPage() const { return 1; } int documentLastPage() const { return 1; } int documentCurrentPage() const { return 1; } QAbstractPrintDialog::PrintDialogOptions printDialogOptions() const; /** *@brief Check if the painter can print to the printer *@returns true if the print job can print to the given printer */ bool canPrint(); public Q_SLOTS: /** * This is called every time the job should be executed. * When called the document should be printed a new painter using the printer * of this printJob in order to honor the settings the user made on the printer. * canPrint() should be called before startPrinting to check if the painter can print * to the printer * @param removePolicy a policy that should be honored so the caller can make sure * this job doesn't leak memory after being used. */ void startPrinting(RemovePolicy removePolicy = DoNotDelete); private: KisImageWSP m_image; QPrinter m_printer; }; #endif diff --git a/libs/ui/KisResourceBundle.h b/libs/ui/KisResourceBundle.h index 3ffc188b26..f3d34ed23f 100644 --- a/libs/ui/KisResourceBundle.h +++ b/libs/ui/KisResourceBundle.h @@ -1,160 +1,161 @@ /* * Copyright (c) 2014 Victor Lafon metabolic.ewilan@hotmail.fr * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KORESOURCEBUNDLE_H #define KORESOURCEBUNDLE_H #include #include #include #include #include "KisResourceBundleManifest.h" #include "kritaui_export.h" class KoStore; /** * @brief The ResourceBundle class * @details Describe the resource bundles as KoResources */ class KRITAUI_EXPORT KisResourceBundle : public KoResource { public: /** - * @brief ResourceBundle : Ctor * @param bundlePath the path of the bundle + * @brief ResourceBundle : Ctor * + * @param bundlePath the path of the bundle */ KisResourceBundle(QString const& fileName); /** * @brief ~ResourceBundle : Dtor */ ~KisResourceBundle() override; /** * @brief defaultFileExtension * @return the default file extension which should be when saving the resource */ QString defaultFileExtension() const override; /** * @brief load : Load this resource. * @return true if succeed, false otherwise. */ bool load() override; bool loadFromDevice(QIODevice *dev) override; /** * @brief save : Save this resource. * @return true if succeed, false otherwise. */ bool save() override; bool saveToDevice(QIODevice* dev) const override; /** * @brief install : Install the contents of the resource bundle. */ bool install(); /** * @brief uninstall : Uninstall the resource bundle. */ bool uninstall(); /** * @brief addMeta : Add a Metadata to the resource * @param type type of the metadata * @param value value of the metadata */ void addMeta(const QString &type, const QString &value); const QString getMeta(const QString &type, const QString &defaultValue = QString()) const; /** * @brief addFile : Add a file to the bundle * @param fileType type of the resource file * @param filePath path of the resource file */ void addResource(QString fileType, QString filePath, QStringList fileTagList, const QByteArray md5sum); QList getTagsList(); /** * @brief isInstalled * @return true if the bundle is installed, false otherwise. */ bool isInstalled(); /** * @brief setInstalled * This allows you to set installed or uninstalled upon loading. This is used with blacklists. */ void setInstalled(bool install); void setThumbnail(QString); /** * @brief saveMetadata: saves bundle metadata * @param store bundle where to save the metadata */ void saveMetadata(QScopedPointer &store); /** * @brief saveManifest: saves bundle manifest * @param store bundle where to save the manifest */ void saveManifest(QScopedPointer &store); /** * @brief recreateBundle * It recreates the bundle by copying the old bundle information to a new store * and recalculating the md5 of each resource. * @param oldStore the old store to be recreated. */ void recreateBundle(QScopedPointer &oldStore); QStringList resourceTypes() const; QList resources(const QString &resType = QString()) const; int resourceCount() const; private: void writeMeta(const char *metaTag, const QString &metaKey, KoXmlWriter *writer); void writeUserDefinedMeta(const QString &metaKey, KoXmlWriter *writer); private: QImage m_thumbnail; KisResourceBundleManifest m_manifest; QMap m_metadata; QSet m_bundletags; bool m_installed; QList m_gradientsMd5Installed; QList m_patternsMd5Installed; QList m_brushesMd5Installed; QList m_palettesMd5Installed; QList m_workspacesMd5Installed; QList m_presetsMd5Installed; QList m_gamutMasksMd5Installed; QString m_bundleVersion; }; #endif // KORESOURCEBUNDLE_H diff --git a/libs/ui/KisResourceBundleManifest.h b/libs/ui/KisResourceBundleManifest.h index 3351b99dea..c854f88d51 100644 --- a/libs/ui/KisResourceBundleManifest.h +++ b/libs/ui/KisResourceBundleManifest.h @@ -1,100 +1,100 @@ /* This file is part of the KDE project Copyright (C) 2014, Victor Lafon This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef KOXMLRESOURCEBUNDLEMANIFEST_H #define KOXMLRESOURCEBUNDLEMANIFEST_H #include #include #include #include #include class QIODevice; class KRITAUI_EXPORT KisResourceBundleManifest { public: struct ResourceReference { ResourceReference(const QString &_resourcePath, const QList &_tagList, const QString &_fileTypeName, const QByteArray &_md5) { resourcePath = _resourcePath; tagList = _tagList; fileTypeName = _fileTypeName; md5sum = _md5; } QString resourcePath; QList tagList; QString fileTypeName; QByteArray md5sum; }; /** * @brief ResourceBundleManifest : Ctor - * @param xmlName the name of the XML file to be created */ KisResourceBundleManifest(); /** * @brief ~ResourceBundleManifest : Dtor */ virtual ~KisResourceBundleManifest(); /** * @brief load the ResourceBundleManifest from the given device */ bool load(QIODevice *device); /** * @brief save the ResourceBundleManifest to the given device */ bool save(QIODevice *device); /** * @brief addTag : Add a file tag as a child of the fileType tag. * @param fileType the type of the file to be added * @param fileName the name of the file to be added - * @param emptyFile true if the file is empty + * @param tagFileList list of the tags + * @param md5 MD5 checksum * @return the element corresponding to the created tag. */ void addResource(const QString &fileType, const QString &fileName, const QStringList &tagFileList, const QByteArray &md5); QStringList types() const; QStringList tags() const; QList files(const QString &type = QString()) const; /** * @brief removeFile : remove a file from the manifest * @param fileName : the name of the file to be removed * @return the list of resource tags to be removed from meta file. */ void removeFile(QString fileName); private: QMap > m_resources; }; #endif // KOXMLRESOURCEBUNDLEMANIFEST_H diff --git a/libs/ui/KisSaveGroupVisitor.h b/libs/ui/KisSaveGroupVisitor.h index 6e4323ec50..47fccb7d53 100644 --- a/libs/ui/KisSaveGroupVisitor.h +++ b/libs/ui/KisSaveGroupVisitor.h @@ -1,103 +1,103 @@ /* * Copyright (C) 2016 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KISSAVEGROUPVISITOR_H #define KISSAVEGROUPVISITOR_H #include "kritaui_export.h" #include #include #include #include #include #include #include #include /** * @brief The KisSaveGroupVisitor class saves the groups in * a Krita image to separate images. */ class KRITAUI_EXPORT KisSaveGroupVisitor : public KisNodeVisitor { public: /** * Create a KisSaveGroupVisitor * * @param image: the image to save * @param saveInvisible: also save invisible layers * @param saveTopLevelOnly: if true, only save the toplevel layers, otherwise * descend into groups and save the bottom-most groups (groups that do * not contain another group. - * @param url the base location where the images will be saved + * @param path the base location where the images will be saved * @param baseName the basename of the images * @param extension the file format extension * @param mimeFilter the export image type */ KisSaveGroupVisitor(KisImageWSP image, bool saveInvisible, bool saveTopLevelOnly, const QString &path, const QString &baseName, const QString &extension, const QString &mimeFilter); ~KisSaveGroupVisitor() override; public: bool visit(KisNode* ) override; bool visit(KisPaintLayer *) override; bool visit(KisAdjustmentLayer *) override; bool visit(KisExternalLayer *) override; bool visit(KisCloneLayer *) override; bool visit(KisFilterMask *) override; bool visit(KisTransformMask *) override; bool visit(KisTransparencyMask *) override; bool visit(KisGeneratorLayer * ) override; bool visit(KisSelectionMask* ) override; bool visit(KisColorizeMask* ) override; bool visit(KisGroupLayer *layer) override; private: KisImageWSP m_image; bool m_saveInvisible; bool m_saveTopLevelOnly; QString m_path; QString m_baseName; QString m_extension; QString m_mimeFilter; }; #endif // KISSAVEGROUPVISITOR_H diff --git a/libs/ui/KisViewManager.h b/libs/ui/KisViewManager.h index 030aeac59e..3fc1ca2a54 100644 --- a/libs/ui/KisViewManager.h +++ b/libs/ui/KisViewManager.h @@ -1,261 +1,261 @@ /* * Copyright (c) 2006 Boudewijn Rempt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_GUI_CLIENT_H #define KIS_GUI_CLIENT_H #include #include #include #include #include #include #include #include "kis_floating_message.h" class QPoint; class KisView; class KisCanvas2; class KisCanvasResourceProvider; class KisDocument; class KisFilterManager; class KisGridManager; class KisGuidesManager; class KisImageManager; class KisNodeManager; class KisDecorationsManager; class KisPaintopBox; class KisSelectionManager; class KisStatusBar; class KisUndoAdapter; class KisZoomManager; class KisPaintopBox; class KisActionManager; class KisInputManager; class KoUpdater; class KoProgressUpdater; /** * KisViewManager manages the collection of views shown in a single mainwindow. */ class KRITAUI_EXPORT KisViewManager : public QObject { Q_OBJECT public: /** * Construct a new view on the krita document. - * @param document the document we show. * @param parent a parent widget we show ourselves in. + * @param actionCollection an action collection. */ KisViewManager(QWidget *parent, KActionCollection *actionCollection); ~KisViewManager() override; /** * Retrieves the entire action collection. */ virtual KActionCollection* actionCollection() const; public: // Krita specific interfaces void setCurrentView(KisView *view); /// Return the image this view is displaying KisImageWSP image() const; KoZoomController *zoomController() const; /// The resource provider contains all per-view settings, such as /// current color, current paint op etc. KisCanvasResourceProvider *resourceProvider(); /// Return the canvasbase class KisCanvas2 *canvasBase() const; /// Return the actual widget that is displaying the current image QWidget* canvas() const; /// Return the wrapper class around the statusbar KisStatusBar *statusBar() const; KisPaintopBox* paintOpBox() const; /// create a new progress updater QPointer createUnthreadedUpdater(const QString &name); QPointer createThreadedUpdater(const QString &name); /// The selection manager handles everything action related to /// selections. KisSelectionManager *selectionManager(); /// The node manager handles everything about nodes KisNodeManager *nodeManager() const; KisActionManager *actionManager() const; /** * Convenience method to get at the active node, which may be * a layer or a mask or a selection */ KisNodeSP activeNode(); /// Convenience method to get at the active layer KisLayerSP activeLayer(); /// Convenience method to get at the active paint device KisPaintDeviceSP activeDevice(); /// The filtermanager handles everything action-related to filters KisFilterManager *filterManager(); /// The image manager handles everything action-related to the /// current image KisImageManager *imageManager(); /// Filters events and sends them to canvas actions KisInputManager *inputManager() const; /// Convenience method to get at the active selection (the /// selection of the current layer, or, if that does not exist, /// the global selection. KisSelectionSP selection(); /// Checks if the current global or local selection is editable bool selectionEditable(); /// The undo adapter is used to add commands to the undo stack KisUndoAdapter *undoAdapter(); KisDocument *document() const; int viewCount() const; /** * @brief blockUntilOperationsFinished blocks the GUI of the application until execution * of actions on \p image is finished * @param image the image which we should wait for * @return true if the image has finished execution of the actions, false if * the user cancelled operation */ bool blockUntilOperationsFinished(KisImageSP image); /** * @brief blockUntilOperationsFinished blocks the GUI of the application until execution * of actions on \p image is finished. Does *not* provide a "Cancel" button. So the * user is forced to wait. * @param image the image which we should wait for */ void blockUntilOperationsFinishedForced(KisImageSP image); public: KisGridManager * gridManager() const; KisGuidesManager * guidesManager() const; /// disable and enable toolbar controls. used for disabling them during painting. void enableControls(); void disableControls(); /// shows a floating message in the top right corner of the canvas void showFloatingMessage(const QString &message, const QIcon& icon, int timeout = 4500, KisFloatingMessage::Priority priority = KisFloatingMessage::Medium, int alignment = Qt::AlignCenter | Qt::TextWordWrap); /// @return the KoMaindow this view is in, or 0 KisMainWindow *mainWindow() const; /// The QMainWindow associated with this view. This is most likely going to be shell(), but /// when running as Gemini or Sketch, this will be set to the applications' own QMainWindow. /// This can be checked by qobject_casting to KisMainWindow to check the difference. QMainWindow* qtMainWindow() const; /// The mainWindow function will return the shell() value, unless this function is called /// with a non-null value. To make it return shell() again, simply pass null to this function. void setQtMainWindow(QMainWindow* newMainWindow); static void initializeResourceManager(KoCanvasResourceProvider *resourceManager); public Q_SLOTS: void switchCanvasOnly(bool toggled); void setShowFloatingMessage(bool show); void showHideScrollbars(); /// Visit all managers to update gui elements, e.g. enable / disable actions. /// This is heavy-duty call, so it uses a compressor. void updateGUI(); /// Update the style of all the icons void updateIcons(); void slotViewAdded(KisView *view); void slotViewRemoved(KisView *view); void slotActivateTransformTool(); // Change and update author void changeAuthorProfile(const QString &profileName); void slotUpdateAuthorProfileActions(); Q_SIGNALS: void floatingMessageRequested(const QString &message, const QString &iconName); /** * @brief viewChanged * sent out when the view has changed. */ void viewChanged(); private Q_SLOTS: void slotBlacklistCleanup(); void slotCreateTemplate(); void slotCreateCopy(); void slotDocumentSaved(); void slotSaveIncremental(); void slotSaveIncrementalBackup(); void showStatusBar(bool toggled); void toggleTabletLogger(); void openResourcesDirectory(); void initializeStatusBarVisibility(); void guiUpdateTimeout(); void slotUpdatePixelGridAction(); void slotSaveShowRulersState(bool value); void slotSaveRulersTrackMouseState(bool value); void slotToggleFgBg(); void slotResetFgBg(); private: void createActions(); void setupManagers(); /// The zoommanager handles everything action-related to zooming KisZoomManager * zoomManager(); private: class KisViewManagerPrivate; KisViewManagerPrivate * const d; }; #endif diff --git a/libs/ui/canvas/kis_projection_backend.h b/libs/ui/canvas/kis_projection_backend.h index 012062e0fb..3004c06046 100644 --- a/libs/ui/canvas/kis_projection_backend.h +++ b/libs/ui/canvas/kis_projection_backend.h @@ -1,100 +1,100 @@ /* * Copyright (c) 2009 Dmitry Kazakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_PROJECTION_BACKEND #define KIS_PROJECTION_BACKEND #include "kis_update_info.h" class KoColorProfile; class KisImagePatch; class KisDisplayFilter; #include /** * KisProjectionBackend is an abstract class representing * an object that can store a cache of KisImage projection. * More than that this object can perform some scaling operations * that are based on "patches" paradigm */ class KisProjectionBackend { public: virtual ~KisProjectionBackend(); /** * Those methods are related to KisPrescaledProjection's * equivalents */ virtual void setImage(KisImageWSP image) = 0; virtual void setImageSize(qint32 w, qint32 h) = 0; virtual void setMonitorProfile(const KoColorProfile* monitorProfile, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags) = 0; virtual void setChannelFlags(const QBitArray &channelFlags) = 0; virtual void setDisplayFilter(QSharedPointer displayFilter) = 0; /** * Updates the cache of the backend by reading from * an associated image. All data transfers with * KisImage should happen here */ virtual void updateCache(const QRect &dirtyImageRect) = 0; /** * Prescales the cache of the backend. It is intended to be * called from a separate thread where you can easily * do the calculations. No data transfers with KisImage * should happen during this phase */ virtual void recalculateCache(KisPPUpdateInfoSP info) = 0; /** * Some backends cannot work with arbitrary areas due to * scaling stuff. That's why KisPrescaledProjection asks * a backend to align an image rect before any operations. */ virtual void alignSourceRect(QRect& rect, qreal scale); /** * Gets a patch from a backend that can draw a info.imageRect on some * QPainter in future. info.scaleX and info.scaleY are the scales * of planned drawing, btw, it doesn't mean that an QImage inside * the patch will have these scales - it'll have the nearest suitable * scale or even original scale (e.g. KisProjectionCache) * * If info.borderWidth is non-zero, info.requestedRect will * be expended by info.borderWidth pixels to all directions and * image of this rect will actually be written to the patch's QImage. * That is done to eliminate border effects in smooth scaling. */ virtual KisImagePatch getNearestPatch(KisPPUpdateInfoSP info) = 0; /** - * Draws a piece of original image onto @gc's canvas + * Draws a piece of original image onto @p gc 's canvas * @param info.imageRect - area in KisImage pixels where to read from * @param info.viewportRect - area in canvas pixels where to write to * If info.imageRect and info.viewportRect don't agree, the image * will be scaled * @param info.borderWidth has the same meaning as in getNearestPatch * @param info.renderHints - hints, transmitted to QPainter during darwing */ virtual void drawFromOriginalImage(QPainter& gc, KisPPUpdateInfoSP info) = 0; }; #endif /* KIS_PROJECTION_BACKEND */ diff --git a/libs/ui/dialogs/kis_dlg_adjustment_layer.h b/libs/ui/dialogs/kis_dlg_adjustment_layer.h index 8c583f533f..9e25f33004 100644 --- a/libs/ui/dialogs/kis_dlg_adjustment_layer.h +++ b/libs/ui/dialogs/kis_dlg_adjustment_layer.h @@ -1,79 +1,80 @@ /* * Copyright (c) 2006 Boudewijn Rempt * Copyright (c) 2008 Cyrille Berger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KISDLGAdjustMENTLAYER_H #define KISDLGAdjustMENTLAYER_H #include #include class KisFilterConfiguration; class KisNodeFilterInterface; class KisViewManager; #include "kis_types.h" #include "ui_wdgfilternodecreation.h" /** * Create a new adjustment layer. */ class KisDlgAdjustmentLayer : public KoDialog { Q_OBJECT public: /** * Create a new adjustmentlayer dialog * - * @param layerName the name of the adjustment layer + * @param node the name of the adjustment node + * @param nfi filter interface * @param paintDevice the paint device that is used as source for the preview * @param caption the caption for the dialog -- create or properties * @param parent the widget parent of this dialog * @param name the QObject name, if any */ KisDlgAdjustmentLayer(KisNodeSP node, KisNodeFilterInterface* nfi, KisPaintDeviceSP paintDevice, const QString & layerName, const QString & caption, KisViewManager *view, QWidget *parent = 0); ~KisDlgAdjustmentLayer() override; KisFilterConfigurationSP filterConfiguration() const; QString layerName() const; public Q_SLOTS: void adjustSize(); protected Q_SLOTS: void slotNameChanged(const QString &); void slotConfigChanged(); void slotFilterWidgetSizeChanged(); private: KisNodeSP m_node; KisNodeFilterInterface *m_nodeFilterInterface; Ui::WdgFilterNodeCreation wdgFilterNodeCreation; KisFilterConfigurationSP m_currentFilter; bool m_customName; QString m_layerName; }; #endif diff --git a/libs/ui/input/config/kis_input_button.h b/libs/ui/input/config/kis_input_button.h index b9ae279778..31d91b8583 100644 --- a/libs/ui/input/config/kis_input_button.h +++ b/libs/ui/input/config/kis_input_button.h @@ -1,143 +1,143 @@ /* * This file is part of the KDE project * Copyright (C) 2013 Arjen Hiemstra * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KISINPUTBUTTON_H #define KISINPUTBUTTON_H #include #include "input/kis_shortcut_configuration.h" /** * \brief A button that can detect input and will store its value. * * This button, when pressed, will detect input based on what type has been set. * It is mainly intended for shortcut configuration, that is, picking some input that is * later reused for shortcuts or similar. * */ class KisInputButton : public QPushButton { Q_OBJECT public: /** * The type of button. */ enum ButtonType { MouseType, ///< Detect and store any combination of pressed mouse buttons. KeyType, ///< Detect and store any combination of key presses. WheelType, ///< Detect and store mouse wheel movement. }; /** * Constructor. */ explicit KisInputButton(QWidget *parent = 0); /** * Destructor. */ ~KisInputButton() override; /** * \return The type of input this button detects. */ ButtonType type() const; /** * Set the type of input this button should detect. * * \param newType The type of input to detect. */ void setType(ButtonType newType); /** * \return The list of keys that was detected. Only applicable when type is `KeyType`. */ QList keys() const; /** * Set the list of keys to display. * * This is mostly intended to make sure the button displays the right keys when viewed * in a dialog or similar UI. * * Only applicable when type is `KeyType`. * * \param newKeys The list of keys to display. */ void setKeys(const QList &newKeys); /** * \return The mouse buttons that were detected. Only applicable when type is `MouseType`. */ Qt::MouseButtons buttons() const; /** * Set the mouse buttons to display. * * This is mostly intended to make sure the button displays the right buttons when viewed * in a dialog or similar UI. * * Only applicable when type is `MouseType`. * * \param newButtons The mouse buttons to display. */ void setButtons(Qt::MouseButtons newButtons); /** * \return The mouse wheel movement that was detected. Only applicable when type is `WheelType`. */ KisShortcutConfiguration::MouseWheelMovement wheel() const; /** * Set the mouse wheel movement to display. * * This is mostly intended to make sure the button displays the right wheel movement when * viewed in a dialog or similar UI. * * Only applicable when type is `WheelType`. * - * \param newButtons The wheel movement to display. + * \param wheel The wheel movement to display. */ void setWheel(KisShortcutConfiguration::MouseWheelMovement wheel); public Q_SLOTS: /** * Clear all detected input and reset the button to an empty state. */ void clear(); Q_SIGNALS: /** * Emitted whenever one of the values (keys, buttons, wheel) changes. */ void dataChanged(); protected: void mousePressEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *) override; void wheelEvent(QWheelEvent *event) override; void keyPressEvent(QKeyEvent *event) override; void keyReleaseEvent(QKeyEvent *event) override; private Q_SLOTS: void reset(); private: class Private; Private *const d; }; #endif // KISINPUTBUTTON_H diff --git a/libs/ui/kis_paintop_option.h b/libs/ui/kis_paintop_option.h index 925e24c2cc..e04d32bea7 100644 --- a/libs/ui/kis_paintop_option.h +++ b/libs/ui/kis_paintop_option.h @@ -1,133 +1,133 @@ /* This file is part of the KDE project * Copyright (C) Boudewijn Rempt , (C) 2008 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KIS_PAINTOP_OPTION_H #define KIS_PAINTOP_OPTION_H #include #include #include #include #include class QWidget; class QString; class KisPaintopLodLimitations; /** * Base interface for paintop options. A paintop option * can be enabled/disabled, has a configuration page * (for example, a curve), a user-visible name and can * be serialized and deserialized into KisPaintOpPresets * * Because KisPaintOpOption classes create a QWidget in * their constructor (the configuration page) you CANNOT * create those objects in a KisPaintOp. KisPaintOps are * created in non-gui threads. * * Options are disabled by default. */ class KRITAUI_EXPORT KisPaintOpOption : public QObject { Q_OBJECT public: enum PaintopCategory { GENERAL, COLOR, TEXTURE, FILTER, MASKING_BRUSH }; KisPaintOpOption(KisPaintOpOption::PaintopCategory category, bool checked); ~KisPaintOpOption() override; KisPaintOpOption::PaintopCategory category() const; virtual bool isCheckable() const; virtual bool isChecked() const; virtual void setChecked(bool checked); void setLocked(bool value); bool isLocked() const; /** * Reimplement this to use the image in the option widget */ virtual void setImage(KisImageWSP image); virtual void setNode(KisNodeWSP node); void startReadOptionSetting(const KisPropertiesConfigurationSP setting); void startWriteOptionSetting(KisPropertiesConfigurationSP setting) const; QWidget *configurationPage() const; virtual void lodLimitations(KisPaintopLodLimitations *l) const; protected: void setConfigurationPage(QWidget *page); protected: /** * Re-implement this to save the configuration to the paint configuration. */ virtual void writeOptionSetting(KisPropertiesConfigurationSP setting) const { Q_UNUSED(setting); } /** - * Re-implement this to set te widgets with the values in @param setting. + * Re-implement this to set te widgets with the values in @p setting. */ virtual void readOptionSetting(const KisPropertiesConfigurationSP setting) { Q_UNUSED(setting); } protected Q_SLOTS: void emitSettingChanged(); void emitCheckedChanged(); Q_SIGNALS: /** * emit this whenever a setting has changed. It will update the preview */ void sigSettingChanged(); /** * emit this whenever a checked state of the option has changed. It as always * emitted *before* sigSettingChanged() */ void sigCheckedChanged(bool value); protected: bool m_checkable; bool m_locked; private: struct Private; Private* const m_d; }; #endif diff --git a/libs/ui/kis_png_converter.h b/libs/ui/kis_png_converter.h index a8f0ddfd0b..de6261193a 100644 --- a/libs/ui/kis_png_converter.h +++ b/libs/ui/kis_png_converter.h @@ -1,142 +1,142 @@ /* * Copyright (c) 2005, 2007 Cyrille Berger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef _KIS_PNG_CONVERTER_H_ #define _KIS_PNG_CONVERTER_H_ #include #include #include #include "kis_types.h" #include "kis_global.h" #include "kis_annotation.h" #include #include class KoStore; class KisDocument; class KoColorSpace; namespace KisMetaData { class Filter; class Store; } struct KisPNGOptions { KisPNGOptions() : compression(0) , interlace(false) , alpha(true) , exif(true) , iptc(true) , xmp(true) , tryToSaveAsIndexed(true) , saveSRGBProfile(false) , forceSRGB(false) , storeMetaData(false) , storeAuthor(false) , transparencyFillColor(Qt::white) {} int compression; bool interlace; bool alpha; bool exif; bool iptc; bool xmp; bool tryToSaveAsIndexed; bool saveSRGBProfile; bool forceSRGB; bool storeMetaData; bool storeAuthor; QList filters; QColor transparencyFillColor; }; /** * This class allows to import/export a PNG from either a file or a QIODevice. */ // XXX_PROGRESS (pass KoUpdater to the png converter) class KRITAUI_EXPORT KisPNGConverter : public QObject { Q_OBJECT public: /** * Initialize the converter. * @param doc the KisDocument related to the image, can be null if you don't have a KisDocument - * @param adapter the undo adapter to be used by the image, can be null if you don't want to use an undo adapter + * @param batchMode whether to use the batch mode */ KisPNGConverter(KisDocument *doc, bool batchMode = false); ~KisPNGConverter() override; public: /** * Load an image from an URL. If the image is not on a local drive, the image is first downloaded to a * temporary location. - * @param uri the url of the image + * @param filename the file name of the image */ KisImageBuilder_Result buildImage(const QString &filename); /** * Load an image from a QIODevice. * @param iod device to access the data */ KisImageBuilder_Result buildImage(QIODevice* iod); /** * Save a layer to a PNG - * @param uri the url of the destination file + * @param filename the name of the destination file * @param device the paint device to save * @param annotationsStart an iterator on the first annotation * @param annotationsEnd an iterator on the last annotation * @param compression a number between 0 and 9 to specify the compression rate (9 is most compressed) * @param interlace set to true if you want to generate an interlaced png * @param alpha set to true if you want to save the alpha channel */ KisImageBuilder_Result buildFile(const QString &filename, const QRect &imageRect, const qreal xRes, const qreal yRes, KisPaintDeviceSP device, vKisAnnotationSP_it annotationsStart, vKisAnnotationSP_it annotationsEnd, KisPNGOptions options, KisMetaData::Store* metaData); KisImageBuilder_Result buildFile(QIODevice*, const QRect &imageRect, const qreal xRes, const qreal yRes, KisPaintDeviceSP device, vKisAnnotationSP_it annotationsStart, vKisAnnotationSP_it annotationsEnd, KisPNGOptions options, KisMetaData::Store* metaData); /** * Retrieve the constructed image */ KisImageSP image(); /** * @brief saveDeviceToStore saves the given paint device to the KoStore. If the device is not 8 bits sRGB, it will be converted to 8 bits sRGB. * @return true if the saving succeeds */ static bool saveDeviceToStore(const QString &filename, const QRect &imageRect, const qreal xRes, const qreal yRes, KisPaintDeviceSP dev, KoStore *store, KisMetaData::Store* metaData = 0); static bool isColorSpaceSupported(const KoColorSpace *cs); public Q_SLOTS: virtual void cancel(); private: void progress(png_structp png_ptr, png_uint_32 row_number, int pass); private: png_uint_32 m_max_row; KisImageSP m_image; KisDocument *m_doc; bool m_stop; bool m_batchMode; QString m_path; }; #endif diff --git a/libs/ui/opengl/kis_opengl_image_textures.h b/libs/ui/opengl/kis_opengl_image_textures.h index 32a915536e..53f071559a 100644 --- a/libs/ui/opengl/kis_opengl_image_textures.h +++ b/libs/ui/opengl/kis_opengl_image_textures.h @@ -1,204 +1,204 @@ /* * Copyright (c) 2005-2007 Adrian Page * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_OPENGL_IMAGE_TEXTURES_H_ #define KIS_OPENGL_IMAGE_TEXTURES_H_ #include #include #include #include "kritaui_export.h" #include "kis_shared.h" #include "canvas/kis_update_info.h" #include "opengl/kis_texture_tile.h" #include "KisOpenGLUpdateInfoBuilder.h" class KisOpenGLImageTextures; typedef KisSharedPtr KisOpenGLImageTexturesSP; class KoColorProfile; class KisTextureTileUpdateInfoPoolCollection; typedef QSharedPointer KisTextureTileInfoPoolSP; class KisProofingConfiguration; typedef QSharedPointer KisProofingConfigurationSP; /** * A set of OpenGL textures that contains the projection of a KisImage. */ class KRITAUI_EXPORT KisOpenGLImageTextures : public KisShared { public: /** * Obtain a KisOpenGLImageTextures object for the given image. * @param image The image * @param monitorProfile The profile of the display device */ static KisOpenGLImageTexturesSP getImageTextures(KisImageWSP image, const KoColorProfile *monitorProfile, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags); /** * Default constructor. */ KisOpenGLImageTextures(); /** * Destructor. */ virtual ~KisOpenGLImageTextures(); /** * \return the image associated with the textures */ KisImageSP image() const; /** * Set the color profile of the display device. - * @param profile The color profile of the display device + * @param monitorProfile The color profile of the display device */ void setMonitorProfile(const KoColorProfile *monitorProfile, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags); /** * Complete initialization can only happen once an OpenGL context has been created. - * @param f Pointer to OpenGL functions. They must already be ininitialized. + * @param f Pointer to OpenGL functions. They must already be initialized. */ void initGL(QOpenGLFunctions *f); void setChannelFlags(const QBitArray &channelFlags); void setProofingConfig(KisProofingConfigurationSP); bool internalColorManagementActive() const; bool setInternalColorManagementActive(bool value); /** * The background checkers texture. */ static const int BACKGROUND_TEXTURE_CHECK_SIZE = 32; static const int BACKGROUND_TEXTURE_SIZE = BACKGROUND_TEXTURE_CHECK_SIZE * 2; /** * Generate a background texture from the given QImage. This is used for the checker * pattern on which the image is rendered. */ void generateCheckerTexture(const QImage & checkImage); GLuint checkerTexture(); void updateConfig(bool useBuffer, int NumMipmapLevels); public: inline QRect storedImageBounds() { return m_storedImageBounds; } inline int xToCol(int x) { return x / m_texturesInfo.effectiveWidth; } inline int yToRow(int y) { return y / m_texturesInfo.effectiveHeight; } inline KisTextureTile* getTextureTileCR(int col, int row) { if (m_initialized) { int tile = row * m_numCols + col; KIS_ASSERT_RECOVER_RETURN_VALUE(m_textureTiles.size() > tile, 0); return m_textureTiles[tile]; } return 0; } inline qreal texelSize() const { Q_ASSERT(m_texturesInfo.width == m_texturesInfo.height); return 1.0 / m_texturesInfo.width; } KisOpenGLUpdateInfoSP updateCache(const QRect& rect, KisImageSP srcImage); KisOpenGLUpdateInfoSP updateCacheNoConversion(const QRect& rect); void recalculateCache(KisUpdateInfoSP info, bool blockMipmapRegeneration); void slotImageSizeChanged(qint32 w, qint32 h); KisOpenGLUpdateInfoBuilder& updateInfoBuilder(); protected: KisOpenGLImageTextures(KisImageWSP image, const KoColorProfile *monitorProfile, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags); void createImageTextureTiles(); void destroyImageTextureTiles(); static bool imageCanShareTextures(); private: void getTextureSize(KisGLTexturesInfo *texturesInfo); void updateTextureFormat(); KisOpenGLUpdateInfoSP updateCacheImpl(const QRect& rect, KisImageSP srcImage, bool convertColorSpace); private: KisImageWSP m_image; QRect m_storedImageBounds; const KoColorProfile *m_monitorProfile; KoColorConversionTransformation::Intent m_renderingIntent; KoColorConversionTransformation::ConversionFlags m_conversionFlags; /** * If the destination color space coincides with the one of the image, * then effectively, there is no conversion happens. That is used * for working with OCIO. */ const KoColorSpace *m_tilesDestinationColorSpace; /** * Shows whether the internal color management should be enabled or not. * Please note that if you disable color management, *but* your image color * space will not be supported (non-RGB), then it will be enabled anyway. * And this valiable will hold the real state of affairs! */ bool m_internalColorManagementActive; GLuint m_checkerTexture; KisGLTexturesInfo m_texturesInfo; int m_numCols; QVector m_textureTiles; QOpenGLFunctions *m_glFuncs; bool m_useOcio; bool m_initialized; KisOpenGLUpdateInfoBuilder m_updateInfoBuilder; private: typedef QMap ImageTexturesMap; static ImageTexturesMap imageTexturesMap; }; #endif // KIS_OPENGL_IMAGE_TEXTURES_H_ diff --git a/libs/ui/widgets/kis_curve_widget.h b/libs/ui/widgets/kis_curve_widget.h index a0301fbe78..96c6f8ee21 100644 --- a/libs/ui/widgets/kis_curve_widget.h +++ b/libs/ui/widgets/kis_curve_widget.h @@ -1,161 +1,161 @@ /* * Copyright (c) 2005 C. Boemann * Copyright (c) 2009 Dmitry Kazakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_CURVE_WIDGET_H #define KIS_CURVE_WIDGET_H // Qt includes. #include #include #include #include #include #include #include #include #include #include class QSpinBox; class KisCubicCurve; /** * KisCurveWidget is a widget that shows a single curve that can be edited * by the user. The user can grab the curve and move it; this creates * a new control point. Control points can be deleted by selecting a point * and pressing the delete key. * * (From: http://techbase.kde.org/Projects/Widgets_and_Classes#KisCurveWidget) * KisCurveWidget allows editing of spline based y=f(x) curves. Handy for cases * where you want the user to control such things as tablet pressure * response, color transformations, acceleration by time, aeroplane lift *by angle of attack. */ class KRITAUI_EXPORT KisCurveWidget : public QWidget { Q_OBJECT Q_PROPERTY(bool pointSelected READ pointSelected NOTIFY pointSelectedChanged); public: friend class CurveEditorItem; /** * Create a new curve widget with a default curve, that is a straight * line from bottom-left to top-right. */ KisCurveWidget(QWidget *parent = 0, Qt::WindowFlags f = 0); ~KisCurveWidget() override; /** * Reset the curve to the default shape */ void reset(void); /** * Enable the guide and set the guide color to the specified color. * * XXX: it seems that the guide feature isn't actually implemented yet? */ void setCurveGuide(const QColor & color); /** * Set a background pixmap. The background pixmap will be drawn under * the grid and the curve. * * XXX: or is the pixmap what is drawn to the left and bottom of the curve * itself? */ void setPixmap(const QPixmap & pix); QPixmap getPixmap(); void setBasePixmap(const QPixmap & pix); QPixmap getBasePixmap(); /** * Whether or not there is a point selected * This does NOT include the first and last points */ bool pointSelected() const; Q_SIGNALS: /** * Emitted whenever a control point has changed position. */ void modified(void); /** * Emitted whenever the status of whether a control point is selected or not changes */ void pointSelectedChanged(); protected Q_SLOTS: void inOutChanged(int); protected: void keyPressEvent(QKeyEvent *) override; void paintEvent(QPaintEvent *) override; void mousePressEvent(QMouseEvent * e) override; void mouseReleaseEvent(QMouseEvent * e) override; void mouseMoveEvent(QMouseEvent * e) override; void leaveEvent(QEvent *) override; void resizeEvent(QResizeEvent *e) override; public: /** * @return get a list with all defined points. If you want to know what the * y value for a given x is on the curve defined by these points, use getCurveValue(). * @see getCurveValue */ KisCubicCurve curve(); /** * Replace the current curve with a curve specified by the curve defined by the control - * points in @param inlist. + * points in @p inlist. */ void setCurve(KisCubicCurve inlist); /** * Connect/disconnect external spinboxes to the curve * @inMin/@inMax - is the range for input values * @outMin/@outMax - is the range for output values */ void setupInOutControls(QSpinBox *in, QSpinBox *out, int inMin, int inMax, int outMin, int outMax); void dropInOutControls(); /** * Handy function that creates new point in the middle * of the curve and sets focus on the m_intIn field, * so the user can move this point anywhere in a moment */ void addPointInTheMiddle(); private: class Private; Private * const d; }; #endif /* KIS_CURVE_WIDGET_H */ diff --git a/libs/ui/widgets/kis_custom_image_widget.h b/libs/ui/widgets/kis_custom_image_widget.h index e57f9ff2c6..694c1f2e57 100644 --- a/libs/ui/widgets/kis_custom_image_widget.h +++ b/libs/ui/widgets/kis_custom_image_widget.h @@ -1,101 +1,101 @@ /* This file is part of the Calligra project * Copyright (C) 2005 Thomas Zander * Copyright (C) 2005 C. Boemann * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_CUSTOM_IMAGE_WIDGET_H #define KIS_CUSTOM_IMAGE_WIDGET_H #include "kis_global.h" #include "KoUnit.h" #include "kis_properties_configuration.h" #include "KisOpenPane.h" #include class KisDocument; class KisDocument; enum CustomImageWidgetType { CUSTOM_DOCUMENT, NEW_IMG_FROM_CB }; class WdgNewImage : public QWidget, public Ui::WdgNewImage { Q_OBJECT public: WdgNewImage(QWidget *parent) : QWidget(parent) { setupUi(this); } }; /** * The 'Custom Document' widget in the Krita startup widget. * This class embeds the image size and colorspace to allow the user to select the image properties * for a new empty image document. */ class KisCustomImageWidget : public WdgNewImage { Q_OBJECT public: /** * Constructor. Please note that this class is being used/created by KisDoc. * @param parent the parent widget - * @param doc the document that wants to be altered + * @param imageName the document that wants to be altered */ KisCustomImageWidget(QWidget *parent, qint32 defWidth, qint32 defHeight, double resolution, const QString & defColorModel, const QString & defColorDepth, const QString & defColorProfile, const QString & imageName); ~KisCustomImageWidget() override; private Q_SLOTS: void widthUnitChanged(int index); void widthChanged(double value); void heightUnitChanged(int index); void heightChanged(double value); void resolutionChanged(double value); void clipboardDataChanged(); void predefinedClicked(int index); void saveAsPredefined(); void setLandscape(); void setPortrait(); void switchWidthHeight(); void createImage(); void switchPortraitLandscape(); void changeDocumentInfoLabel(); protected: KisDocument *createNewImage(); /// Set the number of layers that will be created void setNumberOfLayers(int layers); KisOpenPane *m_openPane; private: double m_width, m_height; quint8 backgroundOpacity() const; void setBackgroundOpacity(quint8 value); void fillPredefined(); void showEvent(QShowEvent *) override; KoUnit m_widthUnit, m_heightUnit; QList m_predefined; }; #endif diff --git a/libs/ui/widgets/kis_image_from_clipboard_widget.h b/libs/ui/widgets/kis_image_from_clipboard_widget.h index c0fa76975f..b550ab461e 100644 --- a/libs/ui/widgets/kis_image_from_clipboard_widget.h +++ b/libs/ui/widgets/kis_image_from_clipboard_widget.h @@ -1,53 +1,53 @@ /* This file is part of the Calligra project * Copyright (C) 2005 Thomas Zander * Copyright (C) 2005 C. Boemann * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KIS_IMAGE_FROM_CLIPBOARD_WIDGET_H #define KIS_IMAGE_FROM_CLIPBOARD_WIDGET_H #include "kis_global.h" #include "kis_properties_configuration.h" #include "kis_custom_image_widget.h" #include /** * The 'New image from clipboard' widget in the Krita startup widget. * This class is an exstension of the KisCustomImageWidget("Custom document" widget" */ class KisImageFromClipboard : public KisCustomImageWidget { Q_OBJECT public: /** * Constructor. Please note that this class is being used/created by KisDoc. * @param parent the parent widget - * @param doc the document that wants to be altered + * @param imageName the document that wants to be altered */ KisImageFromClipboard(QWidget *parent, qint32 defWidth, qint32 defHeight, double resolution, const QString & defColorModel, const QString & defColorDepth, const QString & defColorProfile, const QString & imageName); ~KisImageFromClipboard() override; private Q_SLOTS: void createImage(); void clipboardDataChanged(); private: void createClipboardPreview(); }; #endif diff --git a/libs/ui/widgets/kis_preset_live_preview_view.h b/libs/ui/widgets/kis_preset_live_preview_view.h index 4135851cfc..cb697b1f48 100644 --- a/libs/ui/widgets/kis_preset_live_preview_view.h +++ b/libs/ui/widgets/kis_preset_live_preview_view.h @@ -1,150 +1,150 @@ /* * Copyright (c) 2017 Scott Petrovic * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _KIS_PRESET_LIVE_PREVIEW_ #define _KIS_PRESET_LIVE_PREVIEW_ #include #include #include #include #include #include "kis_paintop_preset.h" #include "KoColorSpaceRegistry.h" #include "kis_paint_layer.h" #include "kis_painter.h" #include "kis_distance_information.h" #include "kis_painting_information_builder.h" #include #include #include /** * Widget for displaying a live brush preview of your * selected brush. It listens for signalsetting changes * that the brush preset outputs and updates the preview * accordingly. This class can be added to a UI file * similar to how a QGraphicsView is added */ class KisPresetLivePreviewView : public QGraphicsView { Q_OBJECT public: KisPresetLivePreviewView(QWidget *parent); ~KisPresetLivePreviewView(); /** * @brief one time setup for initialization of many variables. * This live preview might be in a UI file, so make sure to * call this before starting to use it */ void setup(); /** * @brief set the current preset from resource manager for the live preview to use. * Good to call this every stroke update in case the preset has changed - * @param the current preset from the resource manager + * @param preset the current preset from the resource manager */ void setCurrentPreset(KisPaintOpPresetSP preset); void updateStroke(); private: /// internally sets the image area for brush preview KisImageSP m_image; /// internally sets the layer area for brush preview KisLayerSP m_layer; /// internally sets the color space for brush preview const KoColorSpace *m_colorSpace; /// the color which is used for rendering the stroke KoColor m_paintColor; /// the scene that can add items like text and the brush stroke image QGraphicsScene *m_brushPreviewScene; /// holds the preview brush stroke data QGraphicsPixmapItem *m_sceneImageItem; /// holds the 'no preview available' text object QGraphicsTextItem *m_noPreviewText; /// holds the width and height of the image of the brush preview /// Probably can later add set functions to make this customizable /// It is hard-coded to 1200 x 400 for right now for image size QRect m_canvasSize; /// convenience variable used internally when positioning the objects /// and points in the scene QPointF m_canvasCenterPoint; /// internal variables for constructing the stroke start and end shape /// there are two points that construct the "S" curve with this KisDistanceInformation m_currentDistance; QPainterPath m_curvedLine; KisPaintInformation m_curvePointPI1; KisPaintInformation m_curvePointPI2; /// internally stores the current preset. /// See setCurrentPreset(KisPaintOpPresetSP preset) /// for setting this externally KisPaintOpPresetSP m_currentPreset; /// holds the current zoom(scale) level of scene float m_scaleFactor; /// internal reference for internal brush size /// used to check if our brush size has changed /// do zooming and other things internally if it has changed float m_currentBrushSize = 1.0; /// the range of brush sizes that will control zooming in/out const float m_minBrushVal = 10.0; const float m_maxBrushVal = 100.0; /// range of scale values. 1.0 == 100% const qreal m_minScale = 1.0; const qreal m_maxScale = 0.3; /// multiplier that is used for lengthening the brush stroke points const float m_minStrokeScale = 0.4; // for smaller brush stroke const float m_maxStrokeScale = 1.0; // for larger brush stroke /** * @brief works as both clearing the previous stroke, providing * striped backgrounds for smudging brushes, and text if there is no preview */ void paintBackground(); /** * @brief creates and performs the actual stroke that goes on top of the background * this is internally and should always be called after the paintBackground() */ void setupAndPaintStroke(); }; #endif diff --git a/libs/vectorimage/libemf/EmfOutput.h b/libs/vectorimage/libemf/EmfOutput.h index 33c63982e8..101d5dd1e5 100644 --- a/libs/vectorimage/libemf/EmfOutput.h +++ b/libs/vectorimage/libemf/EmfOutput.h @@ -1,554 +1,554 @@ /* Copyright 2008 Brad Hards Copyright 2009 Inge Wallin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef EMFOUTPUT_H #define EMFOUTPUT_H #include "kritavectorimage_export.h" #include #include #include // also provides QSize, QPoint #include #include #include "EmfEnums.h" #include "EmfHeader.h" #include "EmfRecords.h" /** \file Primary definitions for EMF output strategies */ /** Namespace for Enhanced Metafile (EMF) classes */ namespace Libemf { /** Abstract output strategy for EMF Parser */ class KRITAVECTORIMAGE_EXPORT AbstractOutput { public: AbstractOutput() {}; virtual ~AbstractOutput() {}; /** Initialisation routine \param header the EMF Header record */ virtual void init( const Header *header ) = 0; /** Cleanup routine This function is called when the painting is done. Any initializations that are done in init() can be undone here if necessary. \param header the EMF Header record */ virtual void cleanup( const Header *header ) = 0; /** Close-out routine */ virtual void eof() = 0; /** Handler for the EMR_SETPIXELV record type This fills a specified pixel with a particular color \param point the point to fill \param red the red component of the color \param green the green component of the color \param blue the blue component of the color \param reserved reserved component of the color */ virtual void setPixelV( QPoint &point, quint8 red, quint8 green, quint8 blue, quint8 reserved ) = 0; /** Handler for the EMR_CREATEPEN record type This creates a pen object (at position ihPen) using the specified parameters. \param ihPen the internal handle for the pen to be created \param penStyle the pen configuration (style, type) - see the PenStyle enumeration \param x the width of the pen \param y reserved value - ignore this \param red the red component of the pen color \param green the green component of the pen color \param blue the blue component of the pen color \param reserved reserved value - ignore this */ virtual void createPen( quint32 ihPen, quint32 penStyle, quint32 x, quint32 y, quint8 red, quint8 green, quint8 blue, quint8 reserved ) = 0; /** Handler for the EMR_CREATEBRUSHINDIRECT record type */ virtual void createBrushIndirect( quint32 ihBrush, quint32 BrushStyle, quint8 red, quint8 green, quint8 blue, quint8 reserved, quint32 BrushHatch ) = 0; virtual void createMonoBrush( quint32 ihBrush, Bitmap *bitmap ) = 0; /** Handler for the EMR_SETMAPMODE record type. From [MS-EMF]:\n The EMR_SETMAPMODE record specifies the mapping mode of the playback device context. The mapping mode specifies the unit of measure used to transform page-space units into device-space units, and also specifies the orientation of the device's x and y axes. The valid mapping modes are: - 0x01 (MM_TEXT): Each logical unit is mapped to one device pixel. - 0x02 (MM_LOMETRIC): Each logical unit is mapped to 0.1 millimeter - 0x03 (MM_HIMETRIC): Each logical unit is mapped to 0.01 millimeter. - 0x04 (MM_LOENGLISH): Each logical unit is mapped to 0.01 inch. - 0x05 (MM_HIENGLISH): Each logical unit is mapped to 0.001 inch. - 0x06 (MM_TWIPS): Each logical unit is mapped to one twentieth of a printer's point (1/1440 inch). - 0x07 (MM_ISOTROPIC): Logical units are mapped to arbitrary units with equally-scaled axes; that is, one unit along the x-axis is equal to one unit along the y-axis. - 0x08 (MM_ANISOTROPIC): Logical units are mapped to arbitrary units with arbitrarily scaled axes. Note that increasing x is to the right, and increasing y is up, except for MM_TEXT, where it is down. You can expect to get several calls to this function (e.g. MM_ANISOTROPIC, followed by MM_HIMETRIC). If you maintain state based on this call, you probably need to maintain the dimensions / direction separate from the isotropic / anisotropic state. \param mapMode the mapping mode value */ virtual void setMapMode( const quint32 mapMode ) = 0; /** Handler for the EMR_SETMETARGN record type */ virtual void setMetaRgn() = 0; /** Handler for the EMR_SETWINDOWORGEX record type \param origin the origin of the window in logical coordinates */ virtual void setWindowOrgEx( const QPoint &origin ) = 0; /** Handler for the EMR_SETWINDOWEXTEX record type \param size the size of the window in logical coordinates */ virtual void setWindowExtEx( const QSize &size ) = 0; /** Handler for the EMR_SETVIEWPORTORGEX record type \param origin the origin of the viewport in logical coordinates */ virtual void setViewportOrgEx( const QPoint &origin ) = 0; /** Handler for the EMR_SETVIEWPORTEXTEX record type \param size the size of the viewport in logical coordinates */ virtual void setViewportExtEx( const QSize &size ) = 0; /** Handler for the EMR_SETBKMODE record type \param backgroundMode the background fill mode */ virtual void setBkMode( const quint32 backgroundMode ) = 0; /** Handler for the EMR_SETPOLYFILLMODE record type \param polyFillMode the fill mode */ virtual void setPolyFillMode( const quint32 polyFillMode ) = 0; /** Handler for the EMR_SETLAYOUT record type \param layoutMode the layout mode */ virtual void setLayout( const quint32 layoutMode ) = 0; /** Handler for the EMR_MODIFYWORLDTRANSFORM record type There are a range of modes: - 0x01 (MWT_IDENTIFY): Reset current world transform to identity matrix - 0x02 (MWT_LEFTMULTIPLY): Left multiply this matrix with current matrix. - 0x03 (MWT_RIGHTMULTIPLY): Right multiply current matrix with this matrix. - 0x04 (MWT_SET): Set the world transform. \param mode the mode to use. \param M11 \param M12 \param M21 \param M22 \param Dx \param Dy */ virtual void modifyWorldTransform(quint32 mode, float M11, float M12, float M21, float M22, float Dx, float Dy ) = 0; /** Handler for the EMR_SETWORLDTRANSFORM record type \param M11 \param M12 \param M21 \param M22 \param Dx \param Dy */ virtual void setWorldTransform( float M11, float M12, float M21, float M22, float Dx, float Dy ) = 0; /** Select a previously created (or stock) object \param ihObject the reference number for the object to select */ virtual void selectObject( const quint32 ihObject ) = 0; /** Delete a previously created (or stock) object \param ihObject the reference number for the object to delete */ virtual void deleteObject( const quint32 ihObject ) = 0; /** Handler for the EMR_ARC record type \param box the bounding box \param start the coordinates of the point that defines the first radial end point \param end the coordinates of the point that defines the second radial end point */ virtual void arc( const QRect &box, const QPoint &start, const QPoint &end ) = 0; /** Handler for the EMR_CHORD record type \param box the bounding box \param start the coordinates of the point that defines the first radial end point \param end the coordinates of the point that defines the second radial end point */ virtual void chord( const QRect &box, const QPoint &start, const QPoint &end ) = 0; /** Handler for the EMR_PIE record type \param box the bounding box \param start the coordinates of the point that defines the first radial end point \param end the coordinates of the point that defines the second radial end point */ virtual void pie( const QRect &box, const QPoint &start, const QPoint &end ) = 0; /** Handler for the EMR_ELLIPSE record type \param box the bounding box for the ellipse */ virtual void ellipse( const QRect &box ) = 0; /** Handler for the EMR_RECTANGLE record type \param box the bounding box for the rectangle */ virtual void rectangle( const QRect &box ) = 0; /** Handler for the EMR_SETTEXTALIGN record type The textAlignMode is a bit mask, see [MS-WMF] Section 2.1.2.3 for values if the text has a horizontal baseline, [MS-WMF] Section 2.1.2.4 if the text has a vertical baseline. \param textAlignMode the text alignment mode */ virtual void setTextAlign( const quint32 textAlignMode ) = 0; /** Handler for the EMR_SETTEXTCOLOR record type \param red the red component of the text color \param green the blue component of the text color \param blue the blue component of the text color \param reserved an unused value - ignore this */ virtual void setTextColor( const quint8 red, const quint8 green, const quint8 blue, const quint8 reserved ) = 0; /** Handler for the EMR_SETBKCOLOR record type \param red the red component of the background color \param green the blue component of the background color \param blue the blue component of the background color \param reserved an unused value - ignore this */ virtual void setBkColor( const quint8 red, const quint8 green, const quint8 blue, const quint8 reserved ) = 0; /** Handler for the EMR_EXTCREATEFONTINDIRECTW record type - \param extCreateFontIndirectWRecord the contents of the + \param extCreateFontIndirectW the contents of the EMR_EXTCREATEFONTINDIRECTW record */ virtual void extCreateFontIndirectW( const ExtCreateFontIndirectWRecord &extCreateFontIndirectW ) = 0; /** Handler for text rendering, as described in the EMR_EXTTEXTOUTW and EMR_EXTTEXTOUTA record types. \param bounds the bounds used for e.g. clipping - \param texObject The object describing the text. + \param textObject The object describing the text. */ virtual void extTextOut( const QRect &bounds, const EmrTextObject &textObject ) = 0; /** Handler for the EMR_BEGINPATH record type */ virtual void beginPath() = 0; /** Handler for the EMR_CLOSEFIGURE record type */ virtual void closeFigure() = 0; /** Handler for the EMR_ENDPATH record type */ virtual void endPath() = 0; /** Handler for the EMR_MOVETOEX record type \param x the X coordinate of the point to move to \param y the Y coordinate of the point to move to */ virtual void moveToEx( const qint32 x, const qint32 y ) = 0; /** Handler for the EMR_SAVEDC record type */ virtual void saveDC() = 0; /** Handler for the EMR_RESTOREDC record type \param savedDC the device context to restore to (always negative) */ virtual void restoreDC( const qint32 savedDC ) = 0; /** Handler for the EMR_LINETO record type \param finishPoint the point to draw to */ virtual void lineTo( const QPoint &finishPoint ) = 0; /** Handler for the EMR_ARCTO record type \param box the bounding box \param start the coordinates of the point that defines the first radial end point \param end the coordinates of the point that defines the second radial end point */ virtual void arcTo( const QRect &box, const QPoint &start, const QPoint &end ) = 0; /** Handler for the EMR_POLYGON16 record type. This record type specifies how to output a multi-segment filled polygon. \param bounds the bounding rectangle for the line segment \param points the sequence of points that describe the polygon */ virtual void polygon16( const QRect &bounds, const QList points ) = 0; /** Handler for the EMR_POLYLINE record type. This record type specifies how to output a multi-segment line (unfilled polyline). \param bounds the bounding rectangle for the line segments \param points the sequence of points that describe the line \note the line is not meant to be closed (i.e. do not connect the last point to the first point) or filled. */ virtual void polyLine( const QRect &bounds, const QList points ) = 0; /** Handler for the EMR_POLYLINE16 record type. This record type specifies how to output a multi-segment line (unfilled polyline). \param bounds the bounding rectangle for the line segment \param points the sequence of points that describe the line \note the line is not meant to be closed (i.e. do not connect the last point to the first point) or filled. */ virtual void polyLine16( const QRect &bounds, const QList points ) = 0; /** Handler for the EMR_POLYPOLYLINE16 record type. This record type specifies how to output a set of multi-segment line (unfilled polylines). Each vector in the list is a separate polyline \param bounds the bounding rectangle for the line segments \param points the sequence of points that describe the line \note the lines are not meant to be closed (i.e. do not connect the last point to the first point) or filled. */ virtual void polyPolyLine16( const QRect &bounds, const QList< QVector< QPoint > > &points ) = 0; /** Handler for the EMR_POLYPOLYGON16 record type. This record type specifies how to output a set of multi-segment polygons. Each vector in the list is a separate filled polygon. \param bounds the bounding rectangle for the polygons \param points the sequence of points that describe the polygons */ virtual void polyPolygon16( const QRect &bounds, const QList< QVector< QPoint > > &points ) = 0; /** Handler for the EMR_POLYLINETO16 record type. This record type specifies how to output a multi-segment set of lines (unfilled). \param bounds the bounding rectangle for the bezier curves \param points the sequence of points that describe the curves \note the line is not meant to be closed (i.e. do not connect the last point to the first point) or filled. */ virtual void polyLineTo16( const QRect &bounds, const QList points ) = 0; /** Handler for the EMR_POLYBEZIERO16 record type. This record type specifies how to output a multi-segment set of bezier curves (unfilled). \param bounds the bounding rectangle for the bezier curves \param points the sequence of points that describe the curves \note the line is not meant to be closed (i.e. do not connect the last point to the first point) or filled. */ virtual void polyBezier16( const QRect &bounds, const QList points ) = 0; /** Handler for the EMR_POLYLINETO16 record type. This record type specifies how to output a multi-segment set of bezier curves (unfilled), starting at the current point. \param bounds the bounding rectangle for the bezier curves \param points the sequence of points that describe the curves \note the line is not meant to be closed (i.e. do not connect the last point to the first point) or filled. */ virtual void polyBezierTo16( const QRect &bounds, const QList points ) = 0; /** Handler for the EMR_FILLPATH record type. \param bounds the bounding rectangle for the region to be filled. */ virtual void fillPath( const QRect &bounds ) = 0; /** Handler for the EMR_STROKEANDFILLPATH record type. \param bounds the bounding rectangle for the region to be stroked / filled */ virtual void strokeAndFillPath( const QRect &bounds ) = 0; /** Handler for the EMR_STROKEPATH record type. \param bounds the bounding rectangle for the region to be stroked */ virtual void strokePath( const QRect &bounds ) = 0; /** Handler for the EMR_SETCLIPPATH record type. See [MS-EMF] Section 2.1.29 for valid ways to set the path. \param regionMode how to set the clipping path. */ virtual void setClipPath( const quint32 regionMode ) = 0; /** Handler for the EMR_BITBLT record type \param bitBltRecord contents of the record type */ virtual void bitBlt( BitBltRecord &bitBltRecord ) = 0; /** Handler for the EMR_STRETCHBLTMODE record type \param stretchMode the stretch mode */ virtual void setStretchBltMode( const quint32 stretchMode ) = 0; /** Handler for the EMR_STRETCHDIBITS record type \param stretchDiBitsRecord contents of the record type */ virtual void stretchDiBits( StretchDiBitsRecord &stretchDiBitsRecord ) = 0; }; } #endif diff --git a/libs/vectorimage/libsvm/SvmAbstractBackend.h b/libs/vectorimage/libsvm/SvmAbstractBackend.h index 6e6de55a51..d053b0c1de 100644 --- a/libs/vectorimage/libsvm/SvmAbstractBackend.h +++ b/libs/vectorimage/libsvm/SvmAbstractBackend.h @@ -1,105 +1,105 @@ /* Copyright 2009 Inge Wallin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef SVMABSTRACTBACKEND_H #define SVMABSTRACTBACKEND_H #include "kritavectorimage_export.h" #include "SvmEnums.h" #include "SvmStructs.h" #include "SvmGraphicsContext.h" class QPoint; class QRect; class QPolygon; class QString; /** \file Primary definitions for SVM output backend */ /** Namespace for StarView Metafile (SVM) classes */ namespace Libsvm { /** Abstract output strategy for SVM Parser */ class KRITAVECTORIMAGE_EXPORT SvmAbstractBackend { public: SvmAbstractBackend() {}; virtual ~SvmAbstractBackend() {}; /** Initialisation routine \param header the SVM Header record */ virtual void init(const SvmHeader &header) = 0; /** Cleanup routine This function is called when the parsing is done. Any initializations that are done in init() can be undone here if necessary. */ virtual void cleanup() = 0; /** Close-out routine */ virtual void eof() = 0; virtual void rect(SvmGraphicsContext &context, const QRect &rect) = 0; /** Handler META_POLYLINE_ACTION This action type specifies how to output a multi-segment line (unfilled polyline). \param context the graphics context to be used when drawing the polyline - \param polygon the sequence of points that describe the line + \param polyline the sequence of points that describe the line \note the line is not meant to be closed nor filled, i.e. do not connect the last point to the first point. */ virtual void polyLine(SvmGraphicsContext &context, const QPolygon &polyline) = 0; virtual void polygon(SvmGraphicsContext &context, const QPolygon &polygon) = 0; virtual void polyPolygon(SvmGraphicsContext &context, const QList &polyPolygon) = 0; virtual void textArray(SvmGraphicsContext &context, const QPoint &point, const QString &string, quint16 startIndex, quint16 len, quint32 dxArrayLen, qint32 *dxArray) = 0; }; } #endif diff --git a/libs/vectorimage/libsvm/SvmPainterBackend.h b/libs/vectorimage/libsvm/SvmPainterBackend.h index fc89b0b7d7..2d2e285113 100644 --- a/libs/vectorimage/libsvm/SvmPainterBackend.h +++ b/libs/vectorimage/libsvm/SvmPainterBackend.h @@ -1,116 +1,116 @@ /* Copyright 2009 Inge Wallin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef SVMPAINTERBACKEND_H #define SVMPAINTERBACKEND_H #include "SvmAbstractBackend.h" #include "kritavectorimage_export.h" #include #include #include "SvmEnums.h" #include "SvmStructs.h" #include "SvmGraphicsContext.h" class QRect; class QPolygon; class QPainter; /** \file Primary definitions for SVM output backend */ /** Namespace for StarView Metafile (SVM) classes */ namespace Libsvm { /** Painter output strategy for SVM Parser */ class KRITAVECTORIMAGE_EXPORT SvmPainterBackend : public SvmAbstractBackend { public: SvmPainterBackend(QPainter *painter, const QSize &outputSize); ~SvmPainterBackend() override; /** Initialisation routine \param header the SVM Header record */ void init(const SvmHeader &header) override; /** Cleanup routine This function is called when the painting is done. Any initializations that are done in init() can be undone here if necessary. */ void cleanup() override; /** Close-out routine */ void eof() override; void rect( SvmGraphicsContext &context, const QRect &rect ) override; /** Handler META_POLYLINE_ACTION This action type specifies how to output a multi-segment line (unfilled polyline). \param context the graphics context to be used when drawing the polyline - \param polygon the sequence of points that describe the line + \param polyline the sequence of points that describe the line \note the line is not meant to be closed (i.e. do not connect the last point to the first point) or filled. */ void polyLine(SvmGraphicsContext &context, const QPolygon &polyline) override; void polygon(SvmGraphicsContext &context, const QPolygon &polygon) override; void polyPolygon(SvmGraphicsContext &context, const QList &polyPolygon) override; void textArray(SvmGraphicsContext &context, const QPoint &point, const QString &string, quint16 startIndex, quint16 len, quint32 dxArrayLen, qint32 *dxArray) override; private: void updateFromGraphicscontext(SvmGraphicsContext &context); private: QPainter *m_painter; QSize m_outputSize; QTransform m_outputTransform; }; } #endif diff --git a/libs/widgets/KisDlgInternalColorSelector.h b/libs/widgets/KisDlgInternalColorSelector.h index f703182557..558095bff5 100644 --- a/libs/widgets/KisDlgInternalColorSelector.h +++ b/libs/widgets/KisDlgInternalColorSelector.h @@ -1,194 +1,195 @@ /* * Copyright (C) Wolthera van Hovell tot Westerflier , (C) 2016 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KISDLGINTERNALCOLORSELECTOR_H #define KISDLGINTERNALCOLORSELECTOR_H #include "kritawidgets_export.h" #include "KoColor.h" #include "KoColorSpace.h" #include "KoColorDisplayRendererInterface.h" #include "KoColorSet.h" #include #include "KisScreenColorPickerBase.h" #include "ui_WdgDlgInternalColorSelector.h" /** * @brief The KisInternalColorSelector class * * A non-modal color selector dialog that is not a plugin and can thus be used for filters. */ class KRITAWIDGETS_EXPORT KisDlgInternalColorSelector : public QDialog { Q_OBJECT static std::function s_screenColorPickerFactory; public: static void setScreenColorPickerFactory(std::function f) { s_screenColorPickerFactory = f; } struct Config { Config() : modal(true), visualColorSelector(true), paletteBox(true), screenColorPicker(true), prevNextButtons(true), hexInput(true), useAlpha(false){} bool modal; bool visualColorSelector; bool paletteBox; bool screenColorPicker; bool prevNextButtons; bool hexInput; bool useAlpha; }; KisDlgInternalColorSelector(QWidget* parent, KoColor color, Config config, const QString &caption, const KoColorDisplayRendererInterface *displayRenderer = KoDumbColorDisplayRenderer::instance()); ~KisDlgInternalColorSelector() override; /** * @brief slotColorSpaceChanged * Color space has changed, use this dialog to change the colorspace. */ void colorSpaceChanged(const KoColorSpace *cs); /** * @brief lockUsedColorSpace * Lock the used colorspace of this selector. * @param cs */ void lockUsedColorSpace(const KoColorSpace *cs); /** * @brief setDisplayRenderer * Set the display renderer. This is necessary for HDR color manage support. * @param displayRenderer */ void setDisplayRenderer(const KoColorDisplayRendererInterface *displayRenderer); /** * @brief getModalColorDialog * Execute this dialog modally. The function returns * the KoColor you want. * @param color - The current color. Make sure this is in the color space you want your * end color to be in. - * @param chooseAlpha - Whether or not the alpha-choosing functionality should be used. + * @param parent parent widget. + * @param caption the dialog caption. */ static KoColor getModalColorDialog(const KoColor color, QWidget* parent = Q_NULLPTR, QString caption = QString()); /** * @brief getCurrentColor * @return gives currently active color; */ KoColor getCurrentColor(); void chooseAlpha(bool chooseAlpha); Q_SIGNALS: /** * @brief signalForegroundColorChosen * The most important signal. This will sent out when a color has been picked from the selector. * There will be a small delay to make sure that the selector causes too many updates. * * Do not connect this to slotColorUpdated. * @param color The new color chosen */ void signalForegroundColorChosen(KoColor color); public Q_SLOTS: /** * @brief slotColorUpdated * Very important slot. Is connected to krita's resources to make sure it has * the currently active color. It's very important that this function is able to understand * when the signal came from itself. * @param newColor This is the new color. */ void slotColorUpdated(KoColor newColor); /** * @brief slotSetColorFromPatch * update current color from kocolorpatch. * @param patch */ void slotSetColorFromPatch(KoColorPatch* patch); /** * @brief setPreviousColor * set the previous color. */ void setPreviousColor(KoColor c); void reject() override; private Q_SLOTS: /** * @brief slotLockSelector * This slot will prevent the color from being updated. */ void slotLockSelector(); /** * @brief slotConfigurationChanged * Wrapper slot for changes to the colorspace. */ void slotConfigurationChanged(); void endUpdateWithNewColor(); /** * @brief slotFinishUp * This is called when the selector is closed, for saving the current palette. */ void slotFinishUp(); /** * @brief slotSetColorFromHex * Update from the hex color input. */ void slotSetColorFromHex(); void slotChangePalette(KoColorSet *set); protected: void showEvent(QShowEvent *event) override; private: void focusInEvent(QFocusEvent *) override; /** * @brief updateAllElements * Updates each widget with the new element, and if it's responsible for the update sents * a signal out that there's a new color. */ void updateAllElements(QObject *source); private: Ui_WdgDlgInternalColorSelector *m_ui; struct Private; //The private struct const QScopedPointer m_d; //the private pointer }; #endif // KISDLGINTERNALCOLORSELECTOR_H diff --git a/libs/widgets/KoResourceServer.h b/libs/widgets/KoResourceServer.h index 457097eb99..a2081680ca 100644 --- a/libs/widgets/KoResourceServer.h +++ b/libs/widgets/KoResourceServer.h @@ -1,760 +1,760 @@ /* This file is part of the KDE project Copyright (c) 1999 Matthias Elter Copyright (c) 2003 Patrick Julien Copyright (c) 2005 Sven Langkamp Copyright (c) 2007 Jan Hambrecht Copyright (C) 2011 Srikanth Tiyyagura Copyright (c) 2013 Sascha Suelzer This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KORESOURCESERVER_H #define KORESOURCESERVER_H #include #include #include #include #include #include #include #include #include "resources/KoResource.h" #include "KoResourceServerPolicies.h" #include "KoResourceServerObserver.h" #include "KoResourceTagStore.h" #include "KoResourcePaths.h" #include #include #include "kritawidgets_export.h" #include "WidgetsDebug.h" class KoResource; /** * KoResourceServerBase is the base class of all resource servers */ class KRITAWIDGETS_EXPORT KoResourceServerBase { public: /** * Constructs a KoResourceServerBase - * @param resource type, has to be the same as used by KoResourcePaths + * @param type type, has to be the same as used by KoResourcePaths * @param extensions the file extensions separate by ':', e.g. *.svg:*.ggr" */ KoResourceServerBase(const QString& type, const QString& extensions) : m_type(type) , m_extensions(extensions) { } virtual ~KoResourceServerBase() {} virtual int resourceCount() const = 0; virtual void loadResources(QStringList filenames) = 0; virtual QStringList blackListedFiles() = 0; virtual QStringList queryResources(const QString &query) const = 0; QString type() const { return m_type; } /** * File extensions for resources of the server * @returns the file extensions separated by ':', e.g. "*.svg:*.ggr" */ QString extensions() const { return m_extensions; } QStringList fileNames() { QStringList extensionList = m_extensions.split(':'); QStringList fileNames; foreach (const QString &extension, extensionList) { fileNames += KoResourcePaths::findAllResources(type().toLatin1(), extension, KoResourcePaths::Recursive); } return fileNames; } protected: QStringList m_blackListFileNames; friend class KoResourceTagStore; virtual KoResource *byMd5(const QByteArray &md5) const = 0; virtual KoResource *byFileName(const QString &fileName) const = 0; private: QString m_type; QString m_extensions; protected: QMutex m_loadLock; }; /** * KoResourceServer manages the resources of one type. It stores, * loads and saves the resources. To keep track of changes the server * can be observed with a KoResourceServerObserver * * The \p Policy template parameter defines the way how the lifetime * of a resource is handled. There are to predefined policies: * * o PointerStoragePolicy --- usual pointers with ownership over * the resource. * o SharedPointerStoragePolicy --- shared pointers. The server does no * extra handling for the lifetime of * the resource. * * Use the former for usual resources and the latter for shared pointer based * ones. */ template > class KoResourceServer : public KoResourceServerBase { public: typedef typename Policy::PointerType PointerType; typedef KoResourceServerObserver ObserverType; KoResourceServer(const QString& type, const QString& extensions) : KoResourceServerBase(type, extensions) { m_blackListFile = KoResourcePaths::locateLocal("data", type + ".blacklist"); m_blackListFileNames = readBlackListFile(); m_tagStore = new KoResourceTagStore(this); } ~KoResourceServer() override { if (m_tagStore) { delete m_tagStore; } Q_FOREACH (ObserverType* observer, m_observers) { observer->unsetResourceServer(); } Q_FOREACH (PointerType res, m_resources) { Policy::deleteResource(res); } m_resources.clear(); } int resourceCount() const override { return m_resources.size(); } /** * Loads a set of resources and adds them to the resource server. * If a filename appears twice the resource will only be added once. Resources that can't * be loaded or and invalid aren't added to the server. * @param filenames list of filenames to be loaded */ void loadResources(QStringList filenames) override { QStringList uniqueFiles; while (!filenames.empty()) { QString front = filenames.first(); filenames.pop_front(); // In the save location, people can use sub-folders... And then they probably want // to load both versions! See https://bugs.kde.org/show_bug.cgi?id=321361. QString fname; if (front.contains(saveLocation())) { fname = front.split(saveLocation())[1]; } else { fname = QFileInfo(front).fileName(); } // XXX: Don't load resources with the same filename. Actually, we should look inside // the resource to find out whether they are really the same, but for now this // will prevent the same brush etc. showing up twice. if (!uniqueFiles.contains(fname)) { m_loadLock.lock(); uniqueFiles.append(fname); QList resources = createResources(front); Q_FOREACH (PointerType resource, resources) { Q_CHECK_PTR(resource); if (resource->load() && resource->valid() && !resource->md5().isEmpty()) { addResourceToMd5Registry(resource); m_resourcesByFilename[resource->shortFilename()] = resource; if (resource->name().isEmpty()) { resource->setName(fname); } if (m_resourcesByName.contains(resource->name())) { resource->setName(resource->name() + "(" + resource->shortFilename() + ")"); } m_resourcesByName[resource->name()] = resource; notifyResourceAdded(resource); } else { warnWidgets << "Loading resource " << front << "failed." << type(); Policy::deleteResource(resource); } } m_loadLock.unlock(); } } m_resources = sortedResources(); Q_FOREACH (ObserverType* observer, m_observers) { observer->syncTaggedResourceView(); } // qDebug() << "done loading resources for type " << type(); } void loadTags() { m_tagStore->loadTags(); } void clearOldSystemTags() { m_tagStore->clearOldSystemTags(); } /// Adds an already loaded resource to the server bool addResource(PointerType resource, bool save = true, bool infront = false) { if (!resource->valid()) { warnWidgets << "Tried to add an invalid resource!"; return false; } if (save) { QFileInfo fileInfo(resource->filename()); QDir d(fileInfo.path()); if (!d.exists()) { d.mkdir(fileInfo.path()); } if (fileInfo.exists()) { QString filename = fileInfo.path() + "/" + fileInfo.baseName() + "XXXXXX" + "." + fileInfo.suffix(); debugWidgets << "fileName is " << filename; QTemporaryFile file(filename); if (file.open()) { debugWidgets << "now " << file.fileName(); resource->setFilename(file.fileName()); } } if (!resource->save()) { warnWidgets << "Could not save resource!"; return false; } } Q_ASSERT(!resource->filename().isEmpty() || !resource->name().isEmpty()); if (resource->filename().isEmpty()) { resource->setFilename(resource->name()); } else if (resource->name().isEmpty()) { resource->setName(resource->filename()); } m_resourcesByFilename[resource->shortFilename()] = resource; addResourceToMd5Registry(resource); m_resourcesByName[resource->name()] = resource; if (infront) { m_resources.insert(0, resource); } else { m_resources.append(resource); } notifyResourceAdded(resource); return true; } /** * Removes a given resource from the blacklist. */ bool removeFromBlacklist(PointerType resource) { if (m_blackListFileNames.contains(resource->filename())) { m_blackListFileNames.removeAll(resource->filename()); writeBlackListFile(); return true; } return false; } /// Remove a resource from Resource Server but not from a file bool removeResourceFromServer(PointerType resource){ if ( !m_resourcesByFilename.contains( resource->shortFilename() ) ) { return false; } removeResourceFromMd5Registry(resource); m_resourcesByName.remove(resource->name()); m_resourcesByFilename.remove(resource->shortFilename()); m_resources.removeAt(m_resources.indexOf(resource)); m_tagStore->removeResource(resource); notifyRemovingResource(resource); Policy::deleteResource(resource); return true; } /// Remove a resource from the resourceserver and blacklist it bool removeResourceAndBlacklist(PointerType resource) { if ( !m_resourcesByFilename.contains( resource->shortFilename() ) ) { return false; } removeResourceFromMd5Registry(resource); m_resourcesByName.remove(resource->name()); m_resourcesByFilename.remove(resource->shortFilename()); m_resources.removeAt(m_resources.indexOf(resource)); m_tagStore->removeResource(resource); notifyRemovingResource(resource); m_blackListFileNames.append(resource->filename()); writeBlackListFile(); Policy::deleteResource(resource); return true; } QList resources() { m_loadLock.lock(); QList resourceList = m_resources; Q_FOREACH (PointerType r, m_resourceBlackList) { resourceList.removeOne(r); } m_loadLock.unlock(); return resourceList; } /// Returns path where to save user defined and imported resources to virtual QString saveLocation() { return KoResourcePaths::saveLocation(type().toLatin1()); } /** * Creates a new resource from a given file and adds them to the resource server * The base implementation does only load one resource per file, override to implement collections * @param filename file name of the resource file to be imported * @param fileCreation decides whether to create the file in the saveLocation() directory */ virtual bool importResourceFile(const QString & filename , bool fileCreation=true) { QFileInfo fi(filename); if (!fi.exists()) return false; if ( fi.size() == 0) return false; PointerType resource = createResource( filename ); resource->load(); if (!resource->valid()) { warnWidgets << "Import failed! Resource is not valid"; Policy::deleteResource(resource); return false; } if (fileCreation) { Q_ASSERT(!resource->defaultFileExtension().isEmpty()); Q_ASSERT(!saveLocation().isEmpty()); QString newFilename = saveLocation() + fi.baseName() + resource->defaultFileExtension(); QFileInfo fileInfo(newFilename); int i = 1; while (fileInfo.exists()) { fileInfo.setFile(saveLocation() + fi.baseName() + QString("%1").arg(i) + resource->defaultFileExtension()); i++; } resource->setFilename(fileInfo.filePath()); } if(!addResource(resource)) { Policy::deleteResource(resource); } return true; } /// Removes the resource file from the resource server void removeResourceFile(const QString & filename) { QFileInfo fi(filename); PointerType resource = resourceByFilename(fi.fileName()); if (!resource) { warnWidgets << "Resource file do not exist "; return; } removeResourceFromServer(resource); } /** * Addes an observer to the server * @param observer the observer to be added * @param notifyLoadedResources determines if the observer should be notified about the already loaded resources */ void addObserver(ObserverType* observer, bool notifyLoadedResources = true) { m_loadLock.lock(); if(observer && !m_observers.contains(observer)) { m_observers.append(observer); if(notifyLoadedResources) { Q_FOREACH (PointerType resource, m_resourcesByFilename) { observer->resourceAdded(resource); } } } m_loadLock.unlock(); } /** * Removes an observer from the server * @param observer the observer to be removed */ void removeObserver(ObserverType* observer) { int index = m_observers.indexOf( observer ); if( index < 0 ) return; m_observers.removeAt( index ); } PointerType resourceByFilename(const QString& filename) const { if (m_resourcesByFilename.contains(filename)) { return m_resourcesByFilename[filename]; } return 0; } PointerType resourceByName( const QString& name ) const { if (m_resourcesByName.contains(name)) { return m_resourcesByName[name]; } return 0; } PointerType resourceByMD5(const QByteArray& md5) const { return m_resourcesByMd5.value(md5); } /** * Call after changing the content of a resource; * Notifies the connected views. */ void updateResource( PointerType resource ) { notifyResourceChanged(resource); } QStringList blackListedFiles() override { if (type() == "kis_resourcebundles") { KConfigGroup group = KSharedConfig::openConfig()->group("BundleHack"); if (group.readEntry("HideKrita3Bundle", true)) { Q_FOREACH(const QString &filename, fileNames()) { if (filename.endsWith("Krita_3_Default_Resources.bundle")) { if (!m_blackListFileNames.contains(filename)) { m_blackListFileNames.append(filename); } } } } // qDebug() << "blacklisted filenames" << m_blackListFileNames; } return m_blackListFileNames; } void removeBlackListedFiles() { QStringList remainingFiles; // Files that can't be removed e.g. no rights will stay blacklisted Q_FOREACH (const QString &filename, m_blackListFileNames) { QFile file( filename ); if( ! file.remove() ) { remainingFiles.append(filename); } } m_blackListFileNames = remainingFiles; writeBlackListFile(); } QStringList tagNamesList() const { return m_tagStore->tagNamesList(); } // don't use these method directly since it doesn't update views! void addTag( KoResource* resource,const QString& tag) { m_tagStore->addTag(resource,tag); } // don't use these method directly since it doesn't update views! void delTag( KoResource* resource,const QString& tag) { m_tagStore->delTag(resource, tag); } QStringList searchTag(const QString& lineEditText) { return m_tagStore->searchTag(lineEditText); } void tagCategoryAdded(const QString& tag) { m_tagStore->serializeTags(); Q_FOREACH (ObserverType* observer, m_observers) { observer->syncTagAddition(tag); } } void tagCategoryRemoved(const QString& tag) { m_tagStore->delTag(tag); m_tagStore->serializeTags(); Q_FOREACH (ObserverType* observer, m_observers) { observer->syncTagRemoval(tag); } } void tagCategoryMembersChanged() { m_tagStore->serializeTags(); Q_FOREACH (ObserverType* observer, m_observers) { observer->syncTaggedResourceView(); } } QStringList queryResources(const QString &query) const override { return m_tagStore->searchTag(query); } QStringList assignedTagsList(KoResource* resource) const { return m_tagStore->assignedTagsList(resource); } /** * Create one or more resources from a single file. By default one resource is created. * Override to create more resources from the file. * @param filename the filename of the resource or resource collection */ virtual QList createResources( const QString & filename ) { QList createdResources; createdResources.append(createResource(filename)); return createdResources; } virtual PointerType createResource( const QString & filename ) = 0; /// Return the currently stored resources in alphabetical order, overwrite for customized sorting virtual QList sortedResources() { QMap sortedNames; Q_FOREACH (const QString &name, m_resourcesByName.keys()) { sortedNames.insert(name.toLower(), m_resourcesByName[name]); } return sortedNames.values(); } protected: void notifyResourceAdded(PointerType resource) { Q_FOREACH (ObserverType* observer, m_observers) { observer->resourceAdded(resource); } } void notifyRemovingResource(PointerType resource) { Q_FOREACH (ObserverType* observer, m_observers) { observer->removingResource(resource); } } void notifyResourceChanged(PointerType resource) { Q_FOREACH (ObserverType* observer, m_observers) { observer->resourceChanged(resource); } } /// Reads the xml file and returns the filenames as a list QStringList readBlackListFile() { QStringList filenameList; QFile f(m_blackListFile); if (!f.open(QIODevice::ReadOnly)) { return filenameList; } QDomDocument doc; if (!doc.setContent(&f)) { warnWidgets << "The file could not be parsed."; return filenameList; } QDomElement root = doc.documentElement(); if (root.tagName() != "resourceFilesList") { warnWidgets << "The file doesn't seem to be of interest."; return filenameList; } QDomElement file = root.firstChildElement("file"); while (!file.isNull()) { QDomNode n = file.firstChild(); QDomElement e = n.toElement(); if (e.tagName() == "name") { // If the krita bundle has landed in the blacklist, skip it. if (type() == "kis_resourcebundles") { // qDebug() << "Checking for not reading bundle" << e.text(); if (e.text().endsWith("Krita_3_Default_Resources.bundle")) { file = file.nextSiblingElement("file"); } } filenameList.append(e.text().replace(QString("~"), QDir::homePath())); } file = file.nextSiblingElement("file"); } // if (type() == "kis_resourcebundles") { // qDebug() << "Read bundle blacklist" << filenameList; // } return filenameList; } /// write the blacklist file entries to an xml file void writeBlackListFile() { QFile f(m_blackListFile); if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) { warnWidgets << "Cannot write meta information to '" << m_blackListFile << "'." << endl; return; } QDomDocument doc; QDomElement root; QDomDocument docTemp("m_blackListFile"); doc = docTemp; doc.appendChild(doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"")); root = doc.createElement("resourceFilesList"); doc.appendChild(root); Q_FOREACH (QString filename, m_blackListFileNames) { // Don't write the krita3 bundle to the blacklist, since its location will change // when using the appimate. if (type() == "kis_resourcebundles") { // qDebug() << "Checking for Not writing krita 3 bundle" << filename; if (filename.endsWith("Krita_3_Default_Resources.bundle")) continue; } QDomElement fileEl = doc.createElement("file"); QDomElement nameEl = doc.createElement("name"); QDomText nameText = doc.createTextNode(filename.replace(QDir::homePath(), QString("~"))); nameEl.appendChild(nameText); fileEl.appendChild(nameEl); root.appendChild(fileEl); } QTextStream metastream(&f); metastream << doc.toString(); f.close(); } protected: KoResource* byMd5(const QByteArray &md5) const override { return Policy::toResourcePointer(resourceByMD5(md5)); } KoResource* byFileName(const QString &fileName) const override { return Policy::toResourcePointer(resourceByFilename(fileName)); } private: void addResourceToMd5Registry(PointerType resource) { const QByteArray md5 = resource->md5(); if (!md5.isEmpty()) { m_resourcesByMd5.insert(md5, resource); } } void removeResourceFromMd5Registry(PointerType resource) { const QByteArray md5 = resource->md5(); if (!md5.isEmpty()) { m_resourcesByMd5.remove(md5); } } private: QHash m_resourcesByName; QHash m_resourcesByFilename; QHash m_resourcesByMd5; QList m_resourceBlackList; QList m_resources; ///< list of resources in order of addition QList m_observers; QString m_blackListFile; KoResourceTagStore* m_tagStore; }; template > class KoResourceServerSimpleConstruction : public KoResourceServer { public: KoResourceServerSimpleConstruction(const QString& type, const QString& extensions) : KoResourceServer(type, extensions) { } typename KoResourceServer::PointerType createResource( const QString & filename ) override { return new T(filename); } }; #endif // KORESOURCESERVER_H diff --git a/libs/widgets/KoToolBox_p.h b/libs/widgets/KoToolBox_p.h index 7f0527ff3e..3835f0842b 100644 --- a/libs/widgets/KoToolBox_p.h +++ b/libs/widgets/KoToolBox_p.h @@ -1,113 +1,112 @@ /* * Copyright (c) 2005 Boudewijn Rempt * Copyright (c) 2005-2008 Thomas Zander * Copyright (c) 2009 Peter Simonsson * Copyright (c) 2010 Cyrille Berger * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef _KO_TOOLBOX_H_ #define _KO_TOOLBOX_H_ #include #include #include #include class KoCanvasController; class KoShapeLayer; class KoToolBoxLayout; /** * KoToolBox is a dock widget that can order tools according to type and * priority. * * The ToolBox is a container for tool buttons which are themselves * divided into sections. * * Adding buttons using addButton() will allow you to show those buttons. You should connect * the button to your handling method yourself. * * The unique property of this toolbox is that it can be shown horizontal as well as vertical, * rotating in a smart way to show the buttons optimally. * @see KoToolManager */ class KoToolBox : public QWidget { Q_OBJECT public: /// constructor explicit KoToolBox(); ~KoToolBox() override; public Q_SLOTS: /** * Using the buttongroup id passed in addButton() you can set the new active button. * If the id does not resolve to a visible button, this call is ignored. * @param canvas the currently active canvas. * @param id an id to identify the button to activate. */ void setActiveTool(KoCanvasController *canvas, int id); /** * Show only the dynamic buttons that have a code from parameter codes. * The toolbox allows buttons to be optionally registered with a visibilityCode. This code * can be passed here and all buttons that have that code are shown. All buttons that * have another visibility code registered are hidden. - * @param canvas the currently active canvas. * @param codes a list of all the codes to show. */ void setButtonsVisible(const QList &codes); /// Set the orientation of the layout to @p orientation void setOrientation(Qt::Orientation orientation); void setFloating(bool v); KoToolBoxLayout *toolBoxLayout() const; private: /** * Add a button to the toolbox. * The buttons should all be added before the first showing since adding will not really add * them to the UI until setup() is called. * * @param toolAction the action of the tool * @see setup() */ void addButton(KoToolAction *toolAction); private Q_SLOTS: void setCurrentLayer(const KoCanvasController *canvas, const KoShapeLayer* newLayer); /// add a tool post-initialization. The tool will also be activated. void toolAdded(KoToolAction *toolAction, KoCanvasController *canvas); /// set the icon size for all the buttons void slotContextIconSize(); protected: void paintEvent(QPaintEvent *event) override; void contextMenuEvent(QContextMenuEvent *event) override; private: class Private; Private * const d; }; #endif // _KO_TOOLBOX_H_ diff --git a/libs/widgets/KoZoomWidget.h b/libs/widgets/KoZoomWidget.h index ee676fdedd..8b88e915fd 100644 --- a/libs/widgets/KoZoomWidget.h +++ b/libs/widgets/KoZoomWidget.h @@ -1,83 +1,83 @@ /* Copyright (C) 2004 Ariya Hidayat Copyright (C) 2006 Peter Simonsson Copyright (C) 2006-2007 C. Boemann Copyright (C) 2014 Sven Langkamp This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KOZOOMWIDGET_H #define KOZOOMWIDGET_H #include #include "KoZoomAction.h" #include class KoZoomWidget : public QWidget { Q_OBJECT public: KoZoomWidget(QWidget* parent, int maxZoom); ~KoZoomWidget() override; Q_SIGNALS: /** * Signal sliderValueChanged is triggered when the user moves the slider * @param value value of the slider */ void sliderValueChanged(int value); /** * Signal zoomLevelChanged is triggered when the user changes the KoZoomInput combobox widget - * @param value value of the slider + * @param level value of the slider */ void zoomLevelChanged(const QString& level); /** * Signal aspectModeChanged is triggered when the user toggles the widget. * Nothing else happens except that this signal is emitted. * @param status Whether the special aspect mode is on */ void aspectModeChanged( bool status ); /** * Signal is triggered when the user clicks the zoom to selection button. * Nothing else happens except that this signal is emitted. */ void zoomedToSelection(); /** * Signal is triggered when the user clicks the zoom to all button. * Nothing else happens except that this signal is emitted. */ void zoomedToAll(); public Q_SLOTS: void setZoomLevels(const QStringList &values); void setCurrentZoomLevel(const QString &valueString); void setSliderValue(int value); /** * Change status of "Use same aspect as pixels" button */ void setAspectMode(bool status); private: class Private; QScopedPointer const d; }; #endif // KOZOOMWIDGET_H diff --git a/libs/widgetutils/config/kstandardaction.h b/libs/widgetutils/config/kstandardaction.h index e9c5609a10..9055e1614b 100644 --- a/libs/widgetutils/config/kstandardaction.h +++ b/libs/widgetutils/config/kstandardaction.h @@ -1,598 +1,598 @@ /* This file is part of the KDE libraries Copyright (C) 1999,2000 Kurt Granroth Copyright (C) 2001,2002 Ellis Whitehead This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KSTANDARDACTION_H #define KSTANDARDACTION_H #include #include #include class QObject; class QStringList; class QWidget; class QAction; class KRecentFilesAction; class KDualAction; class KToggleAction; class KToggleFullScreenAction; /** * Convenience methods to access all standard KDE actions. * * These actions should be used instead of hardcoding menubar and * toolbar items. Using these actions helps your application easily * conform to the KDE UI Style Guide * @see http://developer.kde.org/documentation/standards/kde/style/basics/index.html . * * All of the documentation for QAction holds for KStandardAction * also. When in doubt on how things work, check the QAction * documentation first. * Please note that calling any of these methods automatically adds the action * to the actionCollection() of the QObject given by the 'parent' parameter. * * Simple Example:\n * * In general, using standard actions should be a drop in replacement * for regular actions. For example, if you previously had: * * \code * QAction *newAct = new QAction(i18n("&New"), KisIconUtils::loadIcon("document-new"), * KStandardShortcut::shortcut(KStandardShortcut::New), this, * SLOT(fileNew()), actionCollection()); * \endcode * * You could drop that and replace it with: * * \code * QAction *newAct = KStandardAction::openNew(this, SLOT(fileNew()), * actionCollection()); * \endcode * * Non-standard Usages\n * * It is possible to use the standard actions in various * non-recommended ways. Say, for instance, you wanted to have a * standard action (with the associated correct text and icon and * accelerator, etc) but you didn't want it to go in the standard * place (this is not recommended, by the way). One way to do this is * to simply not use the XML UI framework and plug it into wherever * you want. If you do want to use the XML UI framework (good!), then * it is still possible. * * Basically, the XML building code matches names in the XML code with * the internal names of the actions. You can find out the internal * names of each of the standard actions by using the name * method like so: KStandardAction::name(KStandardAction::Cut) would return * 'edit_cut'. The XML building code will match 'edit_cut' to the * attribute in the global XML file and place your action there. * * However, you can change the internal name. In this example, just * do something like: * * \code * (void)KStandardAction::cut(this, SLOT(editCut()), actionCollection(), "my_cut"); * \endcode * * Now, in your local XML resource file (e.g., yourappui.rc), simply * put 'my_cut' where you want it to go. * * Another non-standard usage concerns getting a pointer to an * existing action if, say, you want to enable or disable the action. * You could do it the recommended way and just grab a pointer when * you instantiate it as in the 'openNew' example above... or you * could do it the hard way: * * \code * QAction *cut = actionCollection()->action(KStandardAction::name(KStandardAction::Cut)); * \endcode * * Another non-standard usage concerns instantiating the action in the * first place. Usually, you would use the member functions as * shown above (e.g., KStandardAction::cut(this, SLOT, parent)). You * may, however, do this using the enums provided. This author can't * think of a reason why you would want to, but, hey, if you do, * here's how: * * \code * (void)KStandardAction::action(KStandardAction::New, this, SLOT(fileNew()), actionCollection()); * (void)KStandardAction::action(KStandardAction::Cut, this, SLOT(editCut()), actionCollection()); * \endcode * * @author Kurt Granroth */ namespace KStandardAction { /** * The standard menubar and toolbar actions. */ enum StandardAction { ActionNone, // File Menu New, Open, OpenRecent, Save, SaveAs, Revert, Close, Print, PrintPreview, Mail, Quit, // Edit Menu Undo, Redo, Cut, Copy, Paste, SelectAll, Deselect, Find, FindNext, FindPrev, Replace, // View Menu ActualSize, FitToPage, FitToWidth, FitToHeight, ZoomIn, ZoomOut, Zoom, Redisplay, // Go Menu Up, Back, Forward, Home /*Home page*/, Prior, Next, Goto, GotoPage, GotoLine, FirstPage, LastPage, DocumentBack, DocumentForward, // Bookmarks Menu AddBookmark, EditBookmarks, // Tools Menu Spelling, // Settings Menu ShowMenubar, ShowToolbar, ShowStatusbar, SaveOptions, KeyBindings, Preferences, ConfigureToolbars, // Help Menu Help, HelpContents, WhatsThis, ReportBug, AboutApp, AboutKDE, TipofDay, // Other standard actions ConfigureNotifications, FullScreen, Clear, PasteText, SwitchApplicationLanguage }; /** * Creates an action corresponding to one of the * KStandardAction::StandardAction actions, which is connected to the given * object and @p slot, and is owned by @p parent. * * The signal that is connected to @p slot is triggered(bool), except for the case of * OpenRecent standard action, which uses the urlSelected(const QUrl &) signal of * KRecentFilesAction. * * @param id The StandardAction identifier to create a QAction for. * @param recvr The QObject to receive the signal, or 0 if no notification * is needed. * @param slot The slot to connect the signal to (remember to use the SLOT() macro). * @param parent The QObject that should own the created QAction, or 0 if no parent will * own the QAction returned (ensure you delete it manually in this case). */ KRITAWIDGETUTILS_EXPORT QAction *create(StandardAction id, const QObject *recvr, const char *slot, QObject *parent); /** * This will return the internal name of a given standard action. */ KRITAWIDGETUTILS_EXPORT const char *name(StandardAction id); /// @deprecated use name() #ifndef KDE_NO_DEPRECATED inline KRITAWIDGETUTILS_DEPRECATED const char *stdName(StandardAction act_enum) { return name(act_enum); } #endif /** * Returns a list of all standard names. Used by KAccelManager * to give those higher weight. */ KRITAWIDGETUTILS_EXPORT QStringList stdNames(); /** * Returns a list of all actionIds. * * @since 4.2 */ KRITAWIDGETUTILS_EXPORT QList actionIds(); /** * Returns the standardshortcut associated with @a actionId. * - * @param actionId The actionId whose associated shortcut is wanted. + * @param id The actionId whose associated shortcut is wanted. * * @since 4.2 */ KRITAWIDGETUTILS_EXPORT KStandardShortcut::StandardShortcut shortcutForActionId(StandardAction id); /** * Create a new document or window. */ KRITAWIDGETUTILS_EXPORT QAction *openNew(const QObject *recvr, const char *slot, QObject *parent); /** * Open an existing file. */ KRITAWIDGETUTILS_EXPORT QAction *open(const QObject *recvr, const char *slot, QObject *parent); /** * Open a recently used document. The signature of the slot being called * is of the form slotURLSelected( const QUrl & ). * @param recvr object to receive slot * @param slot The SLOT to invoke when a URL is selected. The slot's * signature is slotURLSelected( const QUrl & ). * @param parent parent widget */ KRITAWIDGETUTILS_EXPORT KRecentFilesAction *openRecent(const QObject *recvr, const char *slot, QObject *parent); /** * Save the current document. */ KRITAWIDGETUTILS_EXPORT QAction *save(const QObject *recvr, const char *slot, QObject *parent); /** * Save the current document under a different name. */ KRITAWIDGETUTILS_EXPORT QAction *saveAs(const QObject *recvr, const char *slot, QObject *parent); /** * Revert the current document to the last saved version * (essentially will undo all changes). */ KRITAWIDGETUTILS_EXPORT QAction *revert(const QObject *recvr, const char *slot, QObject *parent); /** * Close the current document. */ KRITAWIDGETUTILS_EXPORT QAction *close(const QObject *recvr, const char *slot, QObject *parent); /** * Print the current document. */ KRITAWIDGETUTILS_EXPORT QAction *print(const QObject *recvr, const char *slot, QObject *parent); /** * Show a print preview of the current document. */ KRITAWIDGETUTILS_EXPORT QAction *printPreview(const QObject *recvr, const char *slot, QObject *parent); /** * Mail this document. */ KRITAWIDGETUTILS_EXPORT QAction *mail(const QObject *recvr, const char *slot, QObject *parent); /** * Quit the program. * * Note that you probably want to connect this action to either QWidget::close() * or QApplication::closeAllWindows(), but not QApplication::quit(), so that * KMainWindow::queryClose() is called on any open window (to warn the user * about unsaved changes for example). */ KRITAWIDGETUTILS_EXPORT QAction *quit(const QObject *recvr, const char *slot, QObject *parent); /** * Undo the last operation. */ KRITAWIDGETUTILS_EXPORT QAction *undo(const QObject *recvr, const char *slot, QObject *parent); /** * Redo the last operation. */ KRITAWIDGETUTILS_EXPORT QAction *redo(const QObject *recvr, const char *slot, QObject *parent); /** * Cut selected area and store it in the clipboard. * Calls cut() on the widget with the current focus. */ KRITAWIDGETUTILS_EXPORT QAction *cut(QObject *parent); /** * Copy selected area and store it in the clipboard. * Calls copy() on the widget with the current focus. */ KRITAWIDGETUTILS_EXPORT QAction *copy(QObject *parent); /** * Paste the contents of clipboard at the current mouse or cursor * Calls paste() on the widget with the current focus. */ KRITAWIDGETUTILS_EXPORT QAction *paste(QObject *parent); /** * Clear selected area. Calls clear() on the widget with the current focus. * Note that for some widgets, this may not provide the intended behavior. For * example if you make use of the code above and a K3ListView has the focus, clear() * will clear all of the items in the list. If this is not the intened behavior * and you want to make use of this slot, you can subclass K3ListView and reimplement * this slot. For example the following code would implement a K3ListView without this * behavior: * * \code * class MyListView : public K3ListView { * Q_OBJECT * public: * MyListView( QWidget * parent = 0, const char * name = 0, WFlags f = 0 ) : K3ListView( parent, name, f ) {} * virtual ~MyListView() {} * public Q_SLOTS: * virtual void clear() {} * }; * \endcode */ KRITAWIDGETUTILS_EXPORT QAction *clear(QObject *parent); /** * Calls selectAll() on the widget with the current focus. */ KRITAWIDGETUTILS_EXPORT QAction *selectAll(QObject *parent); /** * Cut selected area and store it in the clipboard. */ KRITAWIDGETUTILS_EXPORT QAction *cut(const QObject *recvr, const char *slot, QObject *parent); /** * Copy the selected area into the clipboard. */ KRITAWIDGETUTILS_EXPORT QAction *copy(const QObject *recvr, const char *slot, QObject *parent); /** * Paste the contents of clipboard at the current mouse or cursor * position. */ KRITAWIDGETUTILS_EXPORT QAction *paste(const QObject *recvr, const char *slot, QObject *parent); /** * Paste the contents of clipboard at the current mouse or cursor * position. Provide a button on the toolbar with the clipboard history * menu if Klipper is running. */ KRITAWIDGETUTILS_EXPORT QAction *pasteText(const QObject *recvr, const char *slot, QObject *parent); /** * Clear the content of the focus widget */ KRITAWIDGETUTILS_EXPORT QAction *clear(const QObject *recvr, const char *slot, QObject *parent); /** * Select all elements in the current document. */ KRITAWIDGETUTILS_EXPORT QAction *selectAll(const QObject *recvr, const char *slot, QObject *parent); /** * Deselect any selected elements in the current document. */ KRITAWIDGETUTILS_EXPORT QAction *deselect(const QObject *recvr, const char *slot, QObject *parent); /** * Initiate a 'find' request in the current document. */ KRITAWIDGETUTILS_EXPORT QAction *find(const QObject *recvr, const char *slot, QObject *parent); /** * Find the next instance of a stored 'find'. */ KRITAWIDGETUTILS_EXPORT QAction *findNext(const QObject *recvr, const char *slot, QObject *parent); /** * Find a previous instance of a stored 'find'. */ KRITAWIDGETUTILS_EXPORT QAction *findPrev(const QObject *recvr, const char *slot, QObject *parent); /** * Find and replace matches. */ KRITAWIDGETUTILS_EXPORT QAction *replace(const QObject *recvr, const char *slot, QObject *parent); /** * View the document at its actual size. */ KRITAWIDGETUTILS_EXPORT QAction *actualSize(const QObject *recvr, const char *slot, QObject *parent); /** * Fit the document view to the size of the current window. */ KRITAWIDGETUTILS_EXPORT QAction *fitToPage(const QObject *recvr, const char *slot, QObject *parent); /** * Fit the document view to the width of the current window. */ KRITAWIDGETUTILS_EXPORT QAction *fitToWidth(const QObject *recvr, const char *slot, QObject *parent); /** * Fit the document view to the height of the current window. */ KRITAWIDGETUTILS_EXPORT QAction *fitToHeight(const QObject *recvr, const char *slot, QObject *parent); /** * Zoom in. */ KRITAWIDGETUTILS_EXPORT QAction *zoomIn(const QObject *recvr, const char *slot, QObject *parent); /** * Zoom out. */ KRITAWIDGETUTILS_EXPORT QAction *zoomOut(const QObject *recvr, const char *slot, QObject *parent); /** * Popup a zoom dialog. */ KRITAWIDGETUTILS_EXPORT QAction *zoom(const QObject *recvr, const char *slot, QObject *parent); /** * Redisplay or redraw the document. */ KRITAWIDGETUTILS_EXPORT QAction *redisplay(const QObject *recvr, const char *slot, QObject *parent); /** * Move up (web style menu). */ KRITAWIDGETUTILS_EXPORT QAction *up(const QObject *recvr, const char *slot, QObject *parent); /** * Move back (web style menu). */ KRITAWIDGETUTILS_EXPORT QAction *back(const QObject *recvr, const char *slot, QObject *parent); /** * Move forward (web style menu). */ KRITAWIDGETUTILS_EXPORT QAction *forward(const QObject *recvr, const char *slot, QObject *parent); /** * Go to the "Home" position or document. */ KRITAWIDGETUTILS_EXPORT QAction *home(const QObject *recvr, const char *slot, QObject *parent); /** * Scroll up one page. */ KRITAWIDGETUTILS_EXPORT QAction *prior(const QObject *recvr, const char *slot, QObject *parent); /** * Scroll down one page. */ KRITAWIDGETUTILS_EXPORT QAction *next(const QObject *recvr, const char *slot, QObject *parent); /** * Go to somewhere in general. */ KRITAWIDGETUTILS_EXPORT QAction *goTo(const QObject *recvr, const char *slot, QObject *parent); /** * Go to a specific page (dialog). */ KRITAWIDGETUTILS_EXPORT QAction *gotoPage(const QObject *recvr, const char *slot, QObject *parent); /** * Go to a specific line (dialog). */ KRITAWIDGETUTILS_EXPORT QAction *gotoLine(const QObject *recvr, const char *slot, QObject *parent); /** * Jump to the first page. */ KRITAWIDGETUTILS_EXPORT QAction *firstPage(const QObject *recvr, const char *slot, QObject *parent); /** * Jump to the last page. */ KRITAWIDGETUTILS_EXPORT QAction *lastPage(const QObject *recvr, const char *slot, QObject *parent); /** * Move back (document style menu). */ KRITAWIDGETUTILS_EXPORT QAction *documentBack(const QObject *recvr, const char *slot, QObject *parent); /** * Move forward (document style menu). */ KRITAWIDGETUTILS_EXPORT QAction *documentForward(const QObject *recvr, const char *slot, QObject *parent); /** * Add the current page to the bookmarks tree. */ KRITAWIDGETUTILS_EXPORT QAction *addBookmark(const QObject *recvr, const char *slot, QObject *parent); /** * Edit the application bookmarks. */ KRITAWIDGETUTILS_EXPORT QAction *editBookmarks(const QObject *recvr, const char *slot, QObject *parent); /** * Pop up the spell checker. */ KRITAWIDGETUTILS_EXPORT QAction *spelling(const QObject *recvr, const char *slot, QObject *parent); /** * Show/Hide the menubar. */ KRITAWIDGETUTILS_EXPORT KToggleAction *showMenubar(const QObject *recvr, const char *slot, QObject *parent); /** * Show/Hide the statusbar. */ KRITAWIDGETUTILS_EXPORT KToggleAction *showStatusbar(const QObject *recvr, const char *slot, QObject *parent); /** * Switch to/from full screen mode */ KRITAWIDGETUTILS_EXPORT KToggleFullScreenAction *fullScreen(const QObject *recvr, const char *slot, QWidget *window, QObject *parent); /** * Display the save options dialog. */ KRITAWIDGETUTILS_EXPORT QAction *saveOptions(const QObject *recvr, const char *slot, QObject *parent); /** * Display the configure key bindings dialog. * * Note that you might be able to use the pre-built KXMLGUIFactory's function: * KStandardAction::keyBindings(guiFactory(), SLOT(configureShortcuts()), actionCollection()); */ KRITAWIDGETUTILS_EXPORT QAction *keyBindings(const QObject *recvr, const char *slot, QObject *parent); /** * Display the preferences/options dialog. */ KRITAWIDGETUTILS_EXPORT QAction *preferences(const QObject *recvr, const char *slot, QObject *parent); /** * The Customize Toolbar dialog. */ KRITAWIDGETUTILS_EXPORT QAction *configureToolbars(const QObject *recvr, const char *slot, QObject *parent); /** * The Configure Notifications dialog. */ KRITAWIDGETUTILS_EXPORT QAction *configureNotifications(const QObject *recvr, const char *slot, QObject *parent); /** * Display the help. */ KRITAWIDGETUTILS_EXPORT QAction *help(const QObject *recvr, const char *slot, QObject *parent); /** * Display the help contents. */ KRITAWIDGETUTILS_EXPORT QAction *helpContents(const QObject *recvr, const char *slot, QObject *parent); /** * Trigger the What's This cursor. */ KRITAWIDGETUTILS_EXPORT QAction *whatsThis(const QObject *recvr, const char *slot, QObject *parent); /** * Display "Tip of the Day" */ KRITAWIDGETUTILS_EXPORT QAction *tipOfDay(const QObject *recvr, const char *slot, QObject *parent); /** * Open up the Report Bug dialog. */ KRITAWIDGETUTILS_EXPORT QAction *reportBug(const QObject *recvr, const char *slot, QObject *parent); /** * Display the application's About box. */ KRITAWIDGETUTILS_EXPORT QAction *aboutApp(const QObject *recvr, const char *slot, QObject *parent); /** * Display the About KDE dialog. */ KRITAWIDGETUTILS_EXPORT QAction *aboutKDE(const QObject *recvr, const char *slot, QObject *parent); } #endif // KSTDACTION_H diff --git a/libs/widgetutils/xmlgui/kactioncollection.h b/libs/widgetutils/xmlgui/kactioncollection.h index 8985661090..962aab2531 100644 --- a/libs/widgetutils/xmlgui/kactioncollection.h +++ b/libs/widgetutils/xmlgui/kactioncollection.h @@ -1,514 +1,514 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Reginald Stadlbauer (C) 1999 Simon Hausmann (C) 2000 Nicolas Hadacek (C) 2000 Kurt Granroth (C) 2000 Michael Koch (C) 2001 Holger Freyther (C) 2002 Ellis Whitehead (C) 2005-2006 Hamish Rodda This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KACTIONCOLLECTION_H #define KACTIONCOLLECTION_H #include "config-xmlgui.h" #include #include #include class QAction; class KXMLGUIClient; class KConfigGroup; class QActionGroup; class QString; class KActionCategory; /** * \short A container for a set of QAction objects. * * KActionCollection manages a set of QAction objects. It * allows them to be grouped for organized presentation of configuration to the user, * saving + loading of configuration, and optionally for automatic plugging into * specified widget(s). * * Additionally, KActionCollection provides several convenience functions for locating * named actions, and actions grouped by QActionGroup. * * \note If you create your own action collection and need to assign shortcuts * to the actions within, you have to call associateWidget() or * addAssociatedWidget() to have them working. */ class KRITAWIDGETUTILS_EXPORT KActionCollection : public QObject { friend class KXMLGUIClient; Q_OBJECT Q_PROPERTY(QString configGroup READ configGroup WRITE setConfigGroup) public: /** * Constructor. Allows specification of a component name other than the default * application name, where needed (remember to call setComponentDisplayName() too). */ explicit KActionCollection(QObject *parent, const QString &cName = QString()); /** * Destructor. */ ~KActionCollection() override; /** * Access the list of all action collections in existence for this app */ static const QList &allCollections(); /** * Clears the entire action collection, deleting all actions. */ void clear(); /** * Associate all actions in this collection to the given \a widget. * Unlike addAssociatedWidget, this method only adds all current actions * in the collection to the given widget. Any action added after this call * will not be added to the given widget automatically. * So this is just a shortcut for a foreach loop and a widget->addAction call. */ void associateWidget(QWidget *widget) const; /** * Associate all actions in this collection to the given \a widget, including any actions * added after this association is made. * * This does not change the action's shortcut context, so if you need to have the actions only * trigger when the widget has focus, you'll need to set the shortcut context on each action * to Qt::WidgetShortcut (or better still, Qt::WidgetWithChildrenShortcut with Qt 4.4+) */ void addAssociatedWidget(QWidget *widget); /** * Remove an association between all actions in this collection and the given \a widget, i.e. * remove those actions from the widget, and stop associating newly added actions as well. */ void removeAssociatedWidget(QWidget *widget); /** * Return a list of all associated widgets. */ QList associatedWidgets() const; /** * Clear all associated widgets and remove the actions from those widgets. */ void clearAssociatedWidgets(); /** * Returns the KConfig group with which settings will be loaded and saved. */ QString configGroup() const; /** * Sets \a group as the KConfig group with which settings will be loaded and saved. */ void setConfigGroup(const QString &group); /** * Read all key associations from @p config. * * If @p config is zero, read all key associations from the * application's configuration file KSharedConfig::openConfig(), * in the group set by setConfigGroup(). */ void readSettings(); /** * Update shortcuts from the KisActionRegistry. */ void updateShortcuts(); /** * Write the current configurable key associations. If @a is nonzero, use * that configuration group. * * Otherwise, the output file is determined as follows. If this action * collection belongs to a KXMLGuiClient the setting are saved to the * kxmlgui definition file. If not the settings are written to the * applications config file. * * \note oneAction() and writeDefaults() have no meaning for the kxmlgui * configuration file. * * \param config Config object to save to, or null (see above) * \param writeScheme set to true if we export all settings as new shortcut scheme * \param oneAction pass an action here if you just want to save the values for one action, eg. * if you know that action is the only one which has changed. */ void writeSettings(KConfigGroup *config = 0, bool writeScheme = false, QAction *oneAction = 0) const; /** * Returns the number of actions in the collection. * * This is equivalent to actions().count(). */ int count() const; /** * Returns whether the action collection is empty or not. */ bool isEmpty() const; /** * Return the QAction* at position "index" in the action collection. * * This is equivalent to actions().value(index); */ QAction *action(int index) const; /** * Get the action with the given \a name from the action collection. * * @param name Name of the QAction * @return A pointer to the QAction in the collection which matches the parameters or * null if nothing matches. */ QAction *action(const QString &name) const; /** * Returns the list of QActions which belong to this action collection. * * The list is guaranteed to be in the same order the action were put into * the collection. */ QList actions() const; /** * Returns the list of QActions without an QAction::actionGroup() which belong to this action collection. */ const QList actionsWithoutGroup() const; /** * Returns the list of all QActionGroups associated with actions in this action collection. */ const QList actionGroups() const; /** * Set the \a componentName associated with this action collection. * * \warning Don't call this method on a KActionCollection that contains * actions. This is not supported. * - * \param componentData the name which is to be associated with this action collection, + * \param componentName the name which is to be associated with this action collection, * or QString() to indicate the app name. This is used to load/save settings into XML files. * KXmlGuiClient::setComponentName takes care of calling this. */ void setComponentName(const QString &componentName); /** The component name with which this class is associated. */ QString componentName() const; /** * Set the component display name associated with this action collection. * (e.g. for the toolbar editor) * KXmlGuiClient::setComponentName takes care of calling this. */ void setComponentDisplayName(const QString &displayName); /** The display name for the associated component. */ QString componentDisplayName() const; /** * The parent KXMLGUIClient, or null if not available. */ const KXMLGUIClient *parentGUIClient() const; /** * Returns the KActionCategories inside this collection */ QList categories() const; /** * Gets a category with name @p name inside this collection. * * Creates a new category if one does not exist. */ KActionCategory *getCategory(const QString &categoryName); Q_SIGNALS: /** * Indicates that \a action was inserted into this action collection. */ void inserted(QAction *action); /** * Indicates that \a action was removed from this action collection. * @deprecated */ QT_MOC_COMPAT void removed(QAction *action); /** * Indicates that \a action was highlighted (hovered over). * @deprecated Replaced by actionHovered(QAction* action); */ QT_MOC_COMPAT void actionHighlighted(QAction *action); /** * Indicates that \a action was hovered. */ void actionHovered(QAction *action); /** * Indicates that \a action was triggered */ void actionTriggered(QAction *action); protected: /// Overridden to perform connections when someone wants to know whether an action was highlighted or triggered void connectNotify(const QMetaMethod &signal) override; protected Q_SLOTS: virtual void slotActionTriggered(); /** * @internal * @deprecated Replaced by slotActionHovered(); */ QT_MOC_COMPAT virtual void slotActionHighlighted(); private Q_SLOTS: void slotActionHovered(); public: /** * Add an action under the given name to the collection. * * Inserting an action that was previously inserted under a different name will replace the * old entry, i.e. the action will not be available under the old name anymore but only under * the new one. * * Inserting an action under a name that is already used for another action will replace * the other action in the collection (but will not delete it). * * If KAuthorized::authorizeKAction() reports that the action is not * authorized, it will be disabled and hidden. * * @param name The name by which the action be retrieved again from the collection. * @param action The action to add. * @return the same as the action given as parameter. This is just for convenience * (chaining calls) and consistency with the other addAction methods, you can also * simply ignore the return value. */ Q_INVOKABLE QAction *addAction(const QString &name, QAction *action); /** * Adds a new action to the collection in category @p category. * * The category will be created if it does not already exist. */ Q_INVOKABLE QAction *addCategorizedAction(const QString &name, QAction *action, const QString &categoryName); /** * Adds a list of actions to the collection. * * The objectName of the actions is used as their internal name in the collection. * * Uses addAction(QString, QAction*). * * @param actions the list of the actions to add. * * @see addAction() * @since 5.0 */ void addActions(const QList &actions); /** * Removes an action from the collection and deletes it. * @param action The action to remove. */ void removeAction(QAction *action); /** * Removes an action from the collection. * @param action the action to remove. */ QAction *takeAction(QAction *action); /** * Creates a new standard action, adds it to the collection and connects the * action's triggered(bool) signal to the specified receiver/member. The * newly created action is also returned. * * Note: Using KStandardAction::OpenRecent will cause a different signal than * triggered(bool) to be used, see KStandardAction for more information. * * The action can be retrieved later from the collection by its standard name as per * KStandardAction::stdName. * * @param actionType The standard action type of the action to create. * @param receiver The QObject to connect the triggered(bool) signal to. Leave 0 if no * connection is desired. * @param member The SLOT to connect the triggered(bool) signal to. Leave 0 if no * connection is desired. * @return new action of the given type ActionType. */ QAction *addAction(KStandardAction::StandardAction actionType, const QObject *receiver = 0, const char *member = 0); /** * Creates a new standard action, adds to the collection under the given name * and connects the action's triggered(bool) signal to the specified * receiver/member. The newly created action is also returned. * * Note: Using KStandardAction::OpenRecent will cause a different signal than * triggered(bool) to be used, see KStandardAction for more information. * * The action can be retrieved later from the collection by the specified name. * * @param actionType The standard action type of the action to create. * @param name The name by which the action be retrieved again from the collection. * @param receiver The QObject to connect the triggered(bool) signal to. Leave 0 if no * connection is desired. * @param member The SLOT to connect the triggered(bool) signal to. Leave 0 if no * connection is desired. * @return new action of the given type ActionType. */ QAction *addAction(KStandardAction::StandardAction actionType, const QString &name, const QObject *receiver = 0, const char *member = 0); /** * Creates a new action under the given name to the collection and connects * the action's triggered(bool) signal to the specified receiver/member. The * newly created action is returned. * * NOTE: KDE prior to 4.2 used the triggered() signal instead of the triggered(bool) * signal. * * Inserting an action that was previously inserted under a different name will replace the * old entry, i.e. the action will not be available under the old name anymore but only under * the new one. * * Inserting an action under a name that is already used for another action will replace * the other action in the collection. * * @param name The name by which the action be retrieved again from the collection. * @param receiver The QObject to connect the triggered(bool) signal to. Leave 0 if no * connection is desired. * @param member The SLOT to connect the triggered(bool) signal to. Leave 0 if no * connection is desired. * @return new action of the given type ActionType. */ QAction *addAction(const QString &name, const QObject *receiver = 0, const char *member = 0); /** * Creates a new action under the given name, adds it to the collection and connects the action's triggered(bool) * signal to the specified receiver/member. The receiver slot may accept either a bool or no * parameters at all (i.e. slotTriggered(bool) or slotTriggered() ). * The type of the action is specified by the template parameter ActionType. * * NOTE: KDE prior to 4.2 connected the triggered() signal instead of the triggered(bool) * signal. * * @param name The internal name of the action (e.g. "file-open"). * @param receiver The QObject to connect the triggered(bool) signal to. Leave 0 if no * connection is desired. * @param member The SLOT to connect the triggered(bool) signal to. Leave 0 if no * connection is desired. * @return new action of the given type ActionType. * * @see addAction() */ template ActionType *add(const QString &name, const QObject *receiver = 0, const char *member = 0) { ActionType *a = new ActionType(this); if (receiver && member) { connect(a, SIGNAL(triggered(bool)), receiver, member); } addAction(name, a); return a; } /** * Get the default primary shortcut for the given action. * * @param action the action for which the default primary shortcut should be returned. * @return the default primary shortcut of the given action * @since 5.0 */ QKeySequence defaultShortcut(QAction *action) const; /** * Get the default shortcuts for the given action. * * @param action the action for which the default shortcuts should be returned. * @return the default shortcuts of the given action * @since 5.0 */ QList defaultShortcuts(QAction *action) const; //TODO KF6: Make setDefaultShortcut static /** * Set the default shortcut for the given action. * Since 5.2, this also calls action->setShortcut(shortcut), i.e. the default shortcut is * made active initially. * * @param action the action for which the default shortcut should be set. * @param shortcut the shortcut to use for the given action in its specified shortcutContext() * @since 5.0 */ void setDefaultShortcut(QAction *action, const QKeySequence &shortcut); /** * Set the default shortcuts for the given action. * Since 5.2, this also calls action->setShortcuts(shortcuts), i.e. the default shortcut is * made active initially. * * @param action the action for which the default shortcut should be set. * @param shortcuts the shortcuts to use for the given action in its specified shortcutContext() * @since 5.0 */ Q_INVOKABLE void setDefaultShortcuts(QAction *action, const QList &shortcuts); /** * Returns true if the given action's shortcuts may be configured by the user. * * @param action the action for the hint should be verified. * @since 5.0 */ bool isShortcutsConfigurable(QAction *action) const; /** * Indicate whether the user may configure the action's shortcuts. * * @param action the action for the hint should be verified. * @param configurable set to true if the shortcuts of the given action may be configured by the user, otherwise false. * @since 5.0 */ void setShortcutsConfigurable(QAction *action, bool configurable); private: Q_PRIVATE_SLOT(d, void _k_actionDestroyed(QObject *)) Q_PRIVATE_SLOT(d, void _k_associatedWidgetDestroyed(QObject *)) KActionCollection(const KXMLGUIClient *parent); // used by KXMLGUIClient friend class KActionCollectionPrivate; class KActionCollectionPrivate *const d; }; #endif diff --git a/libs/widgetutils/xmlgui/kedittoolbar.h b/libs/widgetutils/xmlgui/kedittoolbar.h index 6ab950ed07..af06e473ae 100644 --- a/libs/widgetutils/xmlgui/kedittoolbar.h +++ b/libs/widgetutils/xmlgui/kedittoolbar.h @@ -1,158 +1,158 @@ /* This file is part of the KDE libraries Copyright (C) 2000 Kurt Granroth Copyright (C) 2006 Hamish Rodda This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KEDITTOOLBAR_H #define KEDITTOOLBAR_H #include #include class KActionCollection; class KEditToolBarPrivate; class KXMLGUIFactory; /** * @short A dialog used to customize or configure toolbars. * * This dialog only works if your application uses the XML UI * framework for creating menus and toolbars. It depends on the XML * files to describe the toolbar layouts and it requires the actions * to determine which buttons are active. * * Typically you do not need to use it directly as KXmlGuiWindow::setupGUI * takes care of it. * * If you use plugListAction you need to overload saveNewToolbarConfig() * to plug actions again: * * \code * void MyClass::saveNewToolbarConfig() * { * KXmlGuiWindow::saveNewToolbarConfig(); * plugActionList( "list1", list1Actions ); * plugActionList( "list2", list2Actions ); * } * \endcode * * When created, KEditToolBar takes a KXMLGUIFactory object, and uses it to * find all of the action collections and XML files (there is one of each for the * mainwindow, but there could be more, when adding other XMLGUI clients like * KParts or plugins). The editor aims to be semi-intelligent about where it * assigns any modifications. In other words, it will not write out part specific * changes to your application's main XML file. * * KXmlGuiWindow and KParts::MainWindow take care of creating KEditToolBar correctly * and connecting to its newToolBarConfig slot, but if you really really want to do it * yourself, see the KXmlGuiWindow::configureToolbars() and KXmlGuiWindow::saveNewToolbarConfig() code. * * \image html kedittoolbar.png "KDE Toolbar Editor (KWrite)" * * @author Kurt Granroth * @maintainer David Faure */ class KRITAWIDGETUTILS_EXPORT KEditToolBar : public QDialog { Q_OBJECT public: /** * Main constructor. * * The main parameter, @p factory, is a pointer to the * XML GUI factory object for your application. It contains a list * of all of the GUI clients (along with the action collections and * xml files) and the toolbar editor uses that. * * Use this like so: * \code * KEditToolBar edit(factory()); * if (edit.exec()) * ... * \endcode * * @param factory Your application's factory object * @param parent The usual parent for the dialog. */ explicit KEditToolBar(KXMLGUIFactory *factory, QWidget *parent = 0); /// destructor ~KEditToolBar() override; /** * Sets the default toolbar that will be selected when the dialog is shown. * If not set, or QString() is passed in, the global default tool bar name * will be used. * @param toolBarName the name of the tool bar * @see setGlobalDefaultToolBar */ void setDefaultToolBar(const QString &toolBarName); /** * The name (absolute or relative) of your application's UI resource file * is assumed to be share/apps/appname/appnameui.xmlgui though this can be * overridden by calling this method. * * The global parameter controls whether or not the * global resource file is used. If this is @p true, then you may * edit all of the actions in your toolbars -- global ones and * local one. If it is @p false, then you may edit only your * application's entries. The only time you should set this to * false is if your application does not use the global resource * file at all (very rare). * - * @param xmlfile The application's local resource file. + * @param file The application's local resource file. * @param global If @p true, then the global resource file will also * be parsed. */ void setResourceFile(const QString &file, bool global = true); /** * Sets the default toolbar which will be auto-selected for all * KEditToolBar instances. Can be overridden on a per-dialog basis * by calling setDefaultToolBar( const QString& ) on the dialog. - * @param toolbarName the name of the tool bar + * @param toolBarName the name of the tool bar */ static void setGlobalDefaultToolBar(const char *toolBarName); // TODO should be const QString& Q_SIGNALS: /** * Signal emitted when 'apply' or 'ok' is clicked or toolbars were reset. * Connect to it, to plug action lists and to call applyMainWindowSettings * (see sample code in this class's documentation) */ void newToolBarConfig(); QT_MOC_COMPAT void newToolbarConfig(); protected: void showEvent(QShowEvent *event) override; void hideEvent(QHideEvent *event) override; private: friend class KEditToolBarPrivate; KEditToolBarPrivate *const d; Q_PRIVATE_SLOT(d, void _k_slotButtonClicked(QAbstractButton *)) Q_PRIVATE_SLOT(d, void _k_acceptOK(bool)) Q_PRIVATE_SLOT(d, void _k_enableApply(bool)) Q_DISABLE_COPY(KEditToolBar) }; #endif // _KEDITTOOLBAR_H diff --git a/libs/widgetutils/xmlgui/kedittoolbar_p.h b/libs/widgetutils/xmlgui/kedittoolbar_p.h index 52f31c2a5e..56f9df7233 100644 --- a/libs/widgetutils/xmlgui/kedittoolbar_p.h +++ b/libs/widgetutils/xmlgui/kedittoolbar_p.h @@ -1,256 +1,255 @@ /* This file is part of the KDE libraries Copyright (C) 2000 Kurt Granroth Copyright (C) 2006 Hamish Rodda This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KEDITTOOLBARP_H #define KEDITTOOLBARP_H #include "kxmlguiclient.h" #include #include class QDialogButtonBox; class QLineEdit; class QCheckBox; namespace KDEPrivate { class ToolBarItem; class KEditToolBarWidgetPrivate; class ToolBarListWidget : public QListWidget { Q_OBJECT public: ToolBarListWidget(QWidget *parent = 0); void makeVisible(QListWidgetItem *item) { scrollTo(indexFromItem(item)); } ToolBarItem *currentItem() const; void setActiveList(bool isActiveList) { m_activeList = isActiveList; } Q_SIGNALS: void dropped(ToolBarListWidget *list, int index, ToolBarItem *item, bool sourceIsActiveList); protected: Qt::DropActions supportedDropActions() const override { return Qt::MoveAction; } QStringList mimeTypes() const override { return QStringList() << QStringLiteral("application/x-kde-action-list"); } QMimeData *mimeData(const QList items) const override; bool dropMimeData(int index, const QMimeData *data, Qt::DropAction action) override; // Skip internal dnd handling in QListWidget ---- how is one supposed to figure this out // without reading the QListWidget code !? void dropEvent(QDropEvent *ev) override { QAbstractItemView::dropEvent(ev); } private: bool m_activeList; }; class IconTextEditDialog : public QDialog { Q_OBJECT public: explicit IconTextEditDialog(QWidget *parent = 0); public: void setIconText(const QString &text); QString iconText() const; void setTextAlongsideIconHidden(bool hidden); bool textAlongsideIconHidden() const; private Q_SLOTS: void slotTextChanged(const QString &text); private: QLineEdit *m_lineEdit; QCheckBox *m_cbHidden; QDialogButtonBox *m_buttonBox; }; /** * @short A widget used to customize or configure toolbars * * This is the widget that does all of the work for the * KEditToolBar dialog. In most cases, you will want to use the * dialog instead of this widget directly. * * Typically, you would use this widget only if you wanted to embed * the toolbar editing directly into your existing configure or * preferences dialog. * * This widget only works if your application uses the XML UI * framework for creating menus and toolbars. It depends on the XML * files to describe the toolbar layouts and it requires the actions * to determine which buttons are active. * * @author Kurt Granroth * @internal */ class KEditToolBarWidget : public QWidget, virtual public KXMLGUIClient { Q_OBJECT public: /** * Old constructor for apps that do not use components. * This constructor is somewhat deprecated, since it doesn't work * with any KXMLGuiClient being added to the mainwindow. * You really want to use the other constructor. * * You @em must pass along your collection of actions (some of which appear in your toolbars). * Then call old-style load. * * @param collection The collection of actions to work on * @param parent This widget's parent */ explicit KEditToolBarWidget(KActionCollection *collection, QWidget *parent = 0L); /** * Main constructor. * * Use this like so: * \code * KEditToolBarWidget widget(this); * widget.load(factory()); * ... * \endcode * - * @param factory Your application's factory object * @param parent This widget's parent */ explicit KEditToolBarWidget(QWidget *parent = 0L); /** * Destructor. Note that any changes done in this widget will * @p NOT be saved in the destructor. You @p must call save() * to do that. */ ~KEditToolBarWidget() override; /** * Old-style load. * * Loads the toolbar configuration into the widget. Should be called before being shown. * * @param resourceFile the name (absolute or relative) of your application's UI * resource file. If it is left blank, then the resource file: share/apps/appname/appnameui.xmlgui * is used. This is the same resource file that is used by the * default createGUI function in KMainWindow so you're usually * pretty safe in leaving it blank. * * @param global controls whether or not the * global resource file is used. If this is true, then you may * edit all of the actions in your toolbars -- global ones and * local one. If it is false, then you may edit only your * application's entries. The only time you should set this to * false is if your application does not use the global resource * file at all (very rare) * * @param defaultToolBar the default toolbar that will be selected when the dialog is shown. * If not set, or QString() is passed in, the global default tool bar name * will be used. * * @see KEditToolBar */ void load(const QString &resourceFile, bool global = true, const QString &defaultToolBar = QString()); /** * Loads the toolbar configuration into the widget. Should be called before being shown. * * @param factory pointer to the XML GUI factory object for your application. * It contains a list of all of the GUI clients (along with the action * collections and xml files) and the toolbar editor uses that. * * @param defaultToolBar the default toolbar that will be selected when the dialog is shown. * If not set, or QString() is passed in, the global default tool bar name * will be used. * * @see KEditToolBar */ void load(KXMLGUIFactory *factory, const QString &defaultToolBar = QString()); /** * @internal Reimplemented for internal purposes. */ KActionCollection *actionCollection() const override; /** * Save any changes the user made. The file will be in the user's * local directory (usually $HOME/.kde/share/apps/\). The * filename will be the one specified in the constructor.. or the * made up one if the filename was NULL. * */ void save(); /** * Remove and readd all KMXLGUIClients to update the GUI */ void rebuildKXMLGUIClients(); Q_SIGNALS: /** * Emitted whenever any modifications are made by the user. */ void enableOk(bool); private: Q_PRIVATE_SLOT(d, void slotToolBarSelected(int index)) Q_PRIVATE_SLOT(d, void slotInactiveSelectionChanged()) Q_PRIVATE_SLOT(d, void slotActiveSelectionChanged()) Q_PRIVATE_SLOT(d, void slotInsertButton()) Q_PRIVATE_SLOT(d, void slotRemoveButton()) Q_PRIVATE_SLOT(d, void slotUpButton()) Q_PRIVATE_SLOT(d, void slotDownButton()) Q_PRIVATE_SLOT(d, void slotDropped(ToolBarListWidget *, int, ToolBarItem *, bool)) private: friend class KEditToolBarWidgetPrivate; KEditToolBarWidgetPrivate *const d; Q_DISABLE_COPY(KEditToolBarWidget) }; } #endif diff --git a/libs/widgetutils/xmlgui/kgesture_p.h b/libs/widgetutils/xmlgui/kgesture_p.h index 4f50c9e107..2889529315 100644 --- a/libs/widgetutils/xmlgui/kgesture_p.h +++ b/libs/widgetutils/xmlgui/kgesture_p.h @@ -1,246 +1,247 @@ /* This file is part of the KDE libraries Copyright (C) 2006,2007 Andreas Hartmetz (ahartmetz@gmail.com) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KGESTURE_H #define KGESTURE_H #include #include #include #include /* kinds of gestures: -shapes like triangle, right angle, line -"rocker" (i.e. two mouse button) gestures */ class KShapeGesturePrivate; //TODO: implement operator== for special situations like in KKeyChooser. class KRITAWIDGETUTILS_EXPORT KShapeGesture { public: /** * Create a new invalid shape gesture. */ KShapeGesture(); /** * Creates a new gesture consisting of given shape. * If the gesture belongs to a KAction, and the user draws approximately the same shape * on the screen while holding down the right mouse button, the action will trigger. * @p shape must be a "reasonable" polygon. It must contain at least two points * and it should contain at most 50 for performance reasons. No two consecutive points * are allowed to be at the same position. * @param shape shape to draw to trigger this gesture */ KShapeGesture(const QPolygon &shape); /** * Creates a new gesture from a string description. * @param description create gesture according to this */ KShapeGesture(const QString &description); /** * Copies the given gesture. * @param other gesture to copy */ KShapeGesture(const KShapeGesture &other); /** * Destructor. */ ~KShapeGesture(); /** * Set the shape to draw to trigger this gesture. */ void setShape(const QPolygon &shape); /** * set a user-visible name for this gesture's shape, like "triangle" or "line". */ void setShapeName(const QString &friendlyName); /** * Return the user-visible name for this gesture's shape, like "triangle" or "line". */ QString shapeName() const; /** * Return true if this gesture is valid. * */ bool isValid() const; /** * Return a string representation of this gesture. * Return empty string if invalid. * This function is mainly for use with config files. * * @see shapeName() */ QString toString() const; /** * Return an idealized SVG image of this gesture. * Return an empty image if invalid. * @param attributes SVG attributes to apply to the SVG "path" element that * makes up the drawing of the gesture. By default, only a 'fill="none"' * attribute will be set. */ QByteArray toSvg(const QString &attributes = QString()) const; /** * Return a difference measurement betwenn this gesture and the @p other * gesture. Abort comparison if difference is larger than @p abortThreshold * and return a very large difference in that case. * Usual return values range from x to y //TODO: fill in x and y */ float distance(const KShapeGesture &other, float abortThreshold) const; /** * Set this gesture to the other gesture. */ KShapeGesture &operator=(const KShapeGesture &other); /** * Return whether this gesture is equal to the other gesture. */ bool operator==(const KShapeGesture &other) const; /** * Return the opposite of operator==() */ bool operator!=(const KShapeGesture &other) const; /** * Return an opaque value for use in hash tables */ uint hashable() const; private: KShapeGesturePrivate *const d; }; inline uint qHash(const KShapeGesture &key) { return qHash(key.hashable()); } class KRockerGesturePrivate; class KRITAWIDGETUTILS_EXPORT KRockerGesture { public: /** * Create a new invalid rocker gesture. */ KRockerGesture(); /** * Creates a new gesture consisting of given buttons. - * @param description create gesture according to this + * @param hold create gesture according to this hold + * @param thenPush create gesture according to this push */ KRockerGesture(enum Qt::MouseButton hold, enum Qt::MouseButton thenPush); /** * Creates a new gesture from a string description. * @param description create gesture according to this */ KRockerGesture(const QString &description); /** * Copies the given gesture. * @param other gesture to copy */ KRockerGesture(const KRockerGesture &other); /** * Destructor. */ ~KRockerGesture(); /** * set button combination to trigger */ void setButtons(Qt::MouseButton hold, Qt::MouseButton thenPush); /** * Write the button combination to hold and thenPush */ void getButtons(Qt::MouseButton *hold, Qt::MouseButton *thenPush) const; /** * Return a user-friendly name of the button combination. */ QString rockerName() const; /** * Return a user-friendly name for the mouse button button */ static QString mouseButtonName(Qt::MouseButton button); /** * Return true if this gesture is valid. */ bool isValid() const; /** * Return a string representation of this gesture. * Return an empty string if invalid. * This function is mainly for use with config files. * * @see rockerName() */ QString toString() const; /** * Set this gesture to the other gesture. */ KRockerGesture &operator=(const KRockerGesture &other); /** * Return whether this gesture is equal to the other gesture. */ bool operator==(const KRockerGesture &other) const; /** * Return the opposite of operator==() */ bool operator!=(const KRockerGesture &other) const; /** * Return an opaque value for use in hash tables */ uint hashable() const; private: KRockerGesturePrivate *const d; }; inline uint qHash(const KRockerGesture &key) { return qHash(key.hashable()); } //KGESTURE_H #endif diff --git a/libs/widgetutils/xmlgui/kswitchlanguagedialog_p.h b/libs/widgetutils/xmlgui/kswitchlanguagedialog_p.h index 573198b5e1..92880eeeca 100644 --- a/libs/widgetutils/xmlgui/kswitchlanguagedialog_p.h +++ b/libs/widgetutils/xmlgui/kswitchlanguagedialog_p.h @@ -1,94 +1,89 @@ /* * This file is part of the KDE Libraries * Copyright (C) 2007 Krzysztof Lichota (lichota@mimuw.edu.pl) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef _KSWITCHLANGUAGEDIALOG_H_ #define _KSWITCHLANGUAGEDIALOG_H_ #include namespace KDEPrivate { class KSwitchLanguageDialogPrivate; /** * @short Standard "switch application language" dialog box. * * This class provides "switch application language" dialog box that is used * in KHelpMenu * * @author Krzysztof Lichota (lichota@mimuw.edu.pl) * @internal */ class KSwitchLanguageDialog : public QDialog { Q_OBJECT public: /** * Constructor. Creates a fully featured "Switch application language" dialog box. * Note that this dialog is made modeless in the KHelpMenu class so * the users may expect a modeless dialog. * * @param parent The parent of the dialog box. You should use the * toplevel window so that the dialog becomes centered. - * @param name Internal name of the widget. This name in not used in the - * caption. - * @param modal If false, this widget will be modeless and must be - * made visible using QWidget::show(). Otherwise it will be - * modal and must be made visible using QWidget::exec() */ KSwitchLanguageDialog(QWidget *parent = 0); ~KSwitchLanguageDialog() override; protected Q_SLOTS: /** * Activated when the Ok button has been clicked. */ virtual void slotOk(); void slotDefault(); /** Called when one of language buttons changes state. */ virtual void languageOnButtonChanged(const QString &); /** Called to add one language button to dialog. */ virtual void slotAddLanguageButton(); /** Called when "Remove" language button is clicked. */ virtual void removeButtonClicked(); private: KSwitchLanguageDialogPrivate *const d; friend class KSwitchLanguageDialogPrivate; }; } #endif diff --git a/libs/widgetutils/xmlgui/ktoggletoolbaraction.h b/libs/widgetutils/xmlgui/ktoggletoolbaraction.h index 63653ef29f..c95aff09b9 100644 --- a/libs/widgetutils/xmlgui/ktoggletoolbaraction.h +++ b/libs/widgetutils/xmlgui/ktoggletoolbaraction.h @@ -1,95 +1,96 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Reginald Stadlbauer (C) 1999 Simon Hausmann (C) 2000 Nicolas Hadacek (C) 2000 Kurt Granroth (C) 2000 Michael Koch (C) 2001 Holger Freyther (C) 2002 Ellis Whitehead (C) 2003 Andras Mantia (C) 2005-2006 Hamish Rodda This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KTOGGLETOOLBARACTION_H #define KTOGGLETOOLBARACTION_H #include #include class KToolBar; /** * An action that takes care of everything associated with * showing or hiding a toolbar by a menu action. It will * show or hide the toolbar with the given name when * activated, and check or uncheck itself if the toolbar * is manually shown or hidden. * * If you need to perform some additional action when the * toolbar is shown or hidden, connect to the toggled(bool) * signal. It will be emitted after the toolbar's * visibility has changed, whenever it changes. */ class KRITAWIDGETUTILS_EXPORT KToggleToolBarAction : public KToggleAction { Q_OBJECT public: /** * Create a KToggleToolbarAction that manages the toolbar * named toolBarName. This can be either the name of a * toolbar in an xml ui file, or a toolbar programmatically * created with that name. * - * @param The action's parent object. + * @param parent The action's parent object. */ KToggleToolBarAction(const char *toolBarName, const QString &text, QObject *parent); /** - * Create a KToggleToolbarAction that manages the @param toolBar. + * Create a KToggleToolbarAction that manages the @p toolBar. * This can be either the name of a toolbar in an xml ui file, * or a toolbar programmatically created with that name. * * @param toolBar the toolbar to be managed + * @param text The action's text * @param parent The action's parent object. */ KToggleToolBarAction(KToolBar *toolBar, const QString &text, QObject *parent); /** * Destroys toggle toolbar action. */ ~KToggleToolBarAction() override; /** * Returns a pointer to the tool bar it manages. */ KToolBar *toolBar(); /** * Reimplemented from @see QObject. */ bool eventFilter(QObject *watched, QEvent *event) override; private Q_SLOTS: void slotToggled(bool checked) override; private: class Private; Private *const d; }; #endif diff --git a/libs/widgetutils/xmlgui/ktoolbar.h b/libs/widgetutils/xmlgui/ktoolbar.h index 447a03f7cf..6931e61243 100644 --- a/libs/widgetutils/xmlgui/ktoolbar.h +++ b/libs/widgetutils/xmlgui/ktoolbar.h @@ -1,215 +1,215 @@ /* This file is part of the KDE libraries Copyright (C) 2000 Reginald Stadlbauer (reggie@kde.org) (C) 1997, 1998 Stephan Kulow (coolo@kde.org) (C) 1997, 1998 Sven Radej (radej@kde.org) (C) 1997, 1998 Mark Donohoe (donohoe@kde.org) (C) 1997, 1998 Matthias Ettrich (ettrich@kde.org) (C) 1999, 2000 Kurt Granroth (granroth@kde.org) (C) 2005-2006 Hamish Rodda (rodda@kde.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KTOOLBAR_H #define KTOOLBAR_H #include #include class QDomElement; class KConfigGroup; class KConfig; class KMainWindow; class KXMLGUIClient; /** * @short Floatable toolbar with auto resize. * * A KDE-style toolbar. * * KToolBar can be used as a standalone widget, but KMainWindow * provides easy factories and management of one or more toolbars. * * KToolBar uses a global config group to load toolbar settings on * construction. It will reread this config group on a * KApplication::appearanceChanged() signal. * * KToolBar respects Kiosk settings (see the KAuthorized namespace in the * KConfig framework). In particular, system administrators can prevent users * from moving toolbars with the "movable_toolbars" action, and from showing or * hiding toolbars with the "options_show_toolbar" action. For example, to * disable both, add the following the application or global configuration: * @verbatim [KDE Action Restrictions][$i] movable_toolbars=false options_show_toolbar=false @endverbatim * * @note If you can't depend on KXmlGui but you want to integrate with KDE, you can use QToolBar with: * Set ToolButtonStyle to Qt::ToolButtonFollowStyle, this will make QToolBar use the settings for "Main Toolbar" * Additionally set QToolBar::setProperty("otherToolbar", true) to use settings for "Other toolbars" * Settings from "Other toolbars" will only work on widget styles derived from KStyle * @author Reginald Stadlbauer , Stephan Kulow , Sven Radej , Hamish Rodda . */ class KRITAWIDGETUTILS_EXPORT KToolBar : public QToolBar { Q_OBJECT public: /** * Constructor. * * This constructor takes care of adding the toolbar to the mainwindow, * if @p parent is a QMainWindow. * * Normally KDE applications do not call this directly, they either * call KMainWindow::toolBar(name), or they use XML-GUI and specify * toolbars using XML. * * @param objectName The QObject name of this toolbar, required so that QMainWindow can save and load the toolbar position, * and so that KToolBar can find out if it's the main toolbar. * @param parent The standard toolbar parent (usually a KMainWindow) * @param readConfig whether to apply the configuration (global and application-specific) */ explicit KToolBar(const QString &objectName, QWidget *parent, bool readConfig = true); /** * Destroys the toolbar. */ ~KToolBar() override; /** * Returns the main window that this toolbar is docked with. */ KMainWindow *mainWindow() const; /** * Convenience function to set icon size */ void setIconDimensions(int size); /** * Returns the default size for this type of toolbar. * * @return the default size for this type of toolbar. */ int iconSizeDefault() const; // KDE5: hide from public API. Doesn't make sense to export this, and it isn't used. /** * Save the toolbar settings to group @p configGroup in @p config. */ void saveSettings(KConfigGroup &cg); /** * Read the toolbar settings from group @p configGroup in @p config * and apply them. */ void applySettings(const KConfigGroup &cg); /** * Adds an XML gui client that uses this toolbar * @since 4.8.1 */ void addXMLGUIClient(KXMLGUIClient *client); /** * Removes an XML gui client that uses this toolbar * @since 4.8.5 */ void removeXMLGUIClient(KXMLGUIClient *client); /** - * Load state from an XML @param element, called by KXMLGUIBuilder. + * Load state from an XML @p element, called by KXMLGUIBuilder. */ void loadState(const QDomElement &element); /** - * Save state into an XML @param element, called by KXMLGUIBuilder. + * Save state into an XML @p element, called by KXMLGUIBuilder. */ void saveState(QDomElement &element) const; /** * Reimplemented to support context menu activation on disabled tool buttons. */ bool eventFilter(QObject *watched, QEvent *event) override; /** * Returns whether the toolbars are currently editable (drag & drop of actions). */ static bool toolBarsEditable(); /** * Enable or disable toolbar editing via drag & drop of actions. This is * called by KEditToolbar and should generally be set to disabled whenever * KEditToolbar is not active. */ static void setToolBarsEditable(bool editable); /** * Returns whether the toolbars are locked (i.e., moving of the toobars disallowed). */ static bool toolBarsLocked(); /** * Allows you to lock and unlock all toolbars (i.e., disallow/allow moving of the toobars). */ static void setToolBarsLocked(bool locked); /** * Emits a dbus signal to tell all toolbars in all applications, that the user settings have * changed. * @since 5.0 */ static void emitToolbarStyleChanged(); protected Q_SLOTS: virtual void slotMovableChanged(bool movable); protected: void contextMenuEvent(QContextMenuEvent *) override; void actionEvent(QActionEvent *) override; // Draggable toolbar configuration void dragEnterEvent(QDragEnterEvent *) override; void dragMoveEvent(QDragMoveEvent *) override; void dragLeaveEvent(QDragLeaveEvent *) override; void dropEvent(QDropEvent *) override; void mousePressEvent(QMouseEvent *) override; void mouseMoveEvent(QMouseEvent *) override; void mouseReleaseEvent(QMouseEvent *) override; private: class Private; Private *const d; Q_PRIVATE_SLOT(d, void slotAppearanceChanged()) Q_PRIVATE_SLOT(d, void slotContextAboutToShow()) Q_PRIVATE_SLOT(d, void slotContextAboutToHide()) Q_PRIVATE_SLOT(d, void slotContextLeft()) Q_PRIVATE_SLOT(d, void slotContextRight()) Q_PRIVATE_SLOT(d, void slotContextShowText()) Q_PRIVATE_SLOT(d, void slotContextTop()) Q_PRIVATE_SLOT(d, void slotContextBottom()) Q_PRIVATE_SLOT(d, void slotContextIcons()) Q_PRIVATE_SLOT(d, void slotContextText()) Q_PRIVATE_SLOT(d, void slotContextTextRight()) Q_PRIVATE_SLOT(d, void slotContextTextUnder()) Q_PRIVATE_SLOT(d, void slotContextIconSize()) Q_PRIVATE_SLOT(d, void slotLockToolBars(bool)) }; #endif diff --git a/libs/widgetutils/xmlgui/ktoolbarhandler_p.h b/libs/widgetutils/xmlgui/ktoolbarhandler_p.h index 7899b05635..9e67d1598c 100644 --- a/libs/widgetutils/xmlgui/ktoolbarhandler_p.h +++ b/libs/widgetutils/xmlgui/ktoolbarhandler_p.h @@ -1,72 +1,72 @@ /* This file is part of the KDE libraries Copyright (C) 2002 Simon Hausmann This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KTOOLBARHANDLER_H #define KTOOLBARHANDLER_H #include #include #include #include class KXmlGuiWindow; namespace KDEPrivate { class ToolBarHandler : public QObject, public KXMLGUIClient { Q_OBJECT public: /** * Creates a new tool bar handler for the supplied - * @param mainWindow. + * @p mainWindow. */ explicit ToolBarHandler(KXmlGuiWindow *mainWindow); /** * Creates a new tool bar handler for the supplied * @param mainWindow and with the supplied parent. */ ToolBarHandler(KXmlGuiWindow *mainWindow, QObject *parent); /** * Destroys the tool bar handler. */ ~ToolBarHandler() override; /** * Returns the action which is responsible for the tool bar menu. */ QAction *toolBarMenuAction(); public Q_SLOTS: void setupActions(); private: class Private; Private *const d; Q_PRIVATE_SLOT(d, void clientAdded(KXMLGUIClient *)) }; } // namespace KDEPrivate #endif // KTOOLBARHANDLER_H diff --git a/libs/widgetutils/xmlgui/kxmlguibuilder.h b/libs/widgetutils/xmlgui/kxmlguibuilder.h index 274d425238..ca88bd8820 100644 --- a/libs/widgetutils/xmlgui/kxmlguibuilder.h +++ b/libs/widgetutils/xmlgui/kxmlguibuilder.h @@ -1,94 +1,94 @@ /* This file is part of the KDE project Copyright (C) 2000 Simon Hausmann David Faure This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef kxmlguibuilder_h #define kxmlguibuilder_h #include class KXMLGUIBuilderPrivate; class KXMLGUIClient; class QAction; class QDomElement; class QStringList; class QWidget; /** * Implements the creation of the GUI (menubar, menus and toolbars) * as requested by the GUI factory. * * The virtual methods are mostly for historical reasons, there isn't really * a need to derive from KXMLGUIBuilder anymore. */ class KRITAWIDGETUTILS_EXPORT KXMLGUIBuilder { public: explicit KXMLGUIBuilder(QWidget *widget); virtual ~KXMLGUIBuilder(); /* @internal */ KXMLGUIClient *builderClient() const; /* @internal */ void setBuilderClient(KXMLGUIClient *client); /* @internal */ QWidget *widget(); virtual QStringList containerTags() const; /** * Creates a container (menubar/menu/toolbar/statusbar/separator/...) * from an element in the XML file * * @param parent The parent for the container * @param index The index where the container should be inserted * into the parent container/widget * @param element The element from the DOM tree describing the * container (use it to access container specified * attributes or child elements) - * @param action The action created for this container; used for e.g. passing to removeContainer. + * @param containerAction The action created for this container; used for e.g. passing to removeContainer. */ virtual QWidget *createContainer(QWidget *parent, int index, const QDomElement &element, QAction *&containerAction); /** * Removes the given (and previously via createContainer ) * created container. * */ virtual void removeContainer(QWidget *container, QWidget *parent, QDomElement &element, QAction *containerAction); virtual QStringList customTags() const; virtual QAction *createCustomElement(QWidget *parent, int index, const QDomElement &element); virtual void removeCustomElement(QWidget *parent, QAction *action); virtual void finalizeGUI(KXMLGUIClient *client); protected: virtual void virtual_hook(int id, void *data); private: KXMLGUIBuilderPrivate *const d; }; #endif diff --git a/plugins/flake/textshape/kotext/KoAnnotationManager.h b/plugins/flake/textshape/kotext/KoAnnotationManager.h index accb285011..9d3df698a2 100644 --- a/plugins/flake/textshape/kotext/KoAnnotationManager.h +++ b/plugins/flake/textshape/kotext/KoAnnotationManager.h @@ -1,81 +1,81 @@ /* This file is part of the KDE project * Copyright (C) 2007 Fredy Yanardi * Copyright (C) 2012 Inge Wallin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOANNOTATIONMANAGER_H #define KOANNOTATIONMANAGER_H #include "kritatext_export.h" #include #include class KoAnnotation; class KoAnnotationManagerPrivate; /** * A manager for all annotations in a document. Every annotation is identified by a unique name. * Note that only SinglePosition and StartAnnotation annotations can be retrieved from this * manager. An end annotation should be retrieved from it's parent (StartAnnotation) using * KoAnnotation::endAnnotation() * This class also maintains a list of annotation names so that it can be easily used to * show all available annotation. */ class KRITATEXT_EXPORT KoAnnotationManager : public QObject { Q_OBJECT public: /// constructor KoAnnotationManager(); ~KoAnnotationManager() override; /// @return an annotation with the specified name, or 0 if there is none KoAnnotation *annotation(const QString &name) const; /// @return a list of QString containing all annotation names QList annotationNameList() const; public Q_SLOTS: /** * Insert a new annotation to this manager. The name of the annotation - * will be set to @param name, no matter what name has been set on + * will be set to @p name, no matter what name has been set on * it. * @param name the name of the annotation * @param annotation the annotation object to insert */ void insert(const QString &name, KoAnnotation *annotation); /** * Remove an annotation from this manager. * @param name the name of the annotation to remove */ void remove(const QString &name); /** * Rename an annotation * @param oldName the old name of the annotation * @param newName the new name of the annotation */ void rename(const QString &oldName, const QString &newName); private: KoAnnotationManagerPrivate * const d; }; #endif diff --git a/plugins/flake/textshape/kotext/KoBookmarkManager.h b/plugins/flake/textshape/kotext/KoBookmarkManager.h index 2e85445f63..5ec4a2efde 100644 --- a/plugins/flake/textshape/kotext/KoBookmarkManager.h +++ b/plugins/flake/textshape/kotext/KoBookmarkManager.h @@ -1,82 +1,82 @@ /* This file is part of the KDE project * Copyright (C) 2007 Fredy Yanardi * Copyright (C) 2012 C. Boemann * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOBOOKMARKMANAGER_H #define KOBOOKMARKMANAGER_H #include "kritatext_export.h" #include #include #include class KoBookmark; class KoBookmarkManagerPrivate; /** * A manager for all bookmarks in a document. Every bookmark is identified by a unique name. * Note that only SinglePosition and StartBookmark bookmarks can be retrieved from this * manager. An end bookmark should be retrieved from it's parent (StartBookmark) using * KoBookmark::endBookmark() * This class also maintains a list of bookmark names so that it can be easily used to * show all available bookmark. */ class KRITATEXT_EXPORT KoBookmarkManager : public QObject { Q_OBJECT public: /// constructor KoBookmarkManager(); ~KoBookmarkManager() override; /// @return a bookmark with the specified name, or 0 if there is none KoBookmark *bookmark(const QString &name) const; /// @return a list of QString containing all bookmark names QList bookmarkNameList() const; public Q_SLOTS: /** * Insert a new bookmark to this manager. The name of the bookmark - * will be set to @param name, no matter what name has been set on + * will be set to @p name, no matter what name has been set on * it. * @param name the name of the bookmark * @param bookmark the bookmark object to insert */ void insert(const QString &name, KoBookmark *bookmark); /** * Remove a bookmark from this manager. * @param name the name of the bookmark to remove */ void remove(const QString &name); /** * Rename a bookmark * @param oldName the old name of the bookmark * @param newName the new name of the bookmark */ void rename(const QString &oldName, const QString &newName); private: KoBookmarkManagerPrivate * const d; }; #endif diff --git a/plugins/flake/textshape/kotext/KoInlineObjectFactoryBase.h b/plugins/flake/textshape/kotext/KoInlineObjectFactoryBase.h index 755d0ea726..0dd1339ac0 100644 --- a/plugins/flake/textshape/kotext/KoInlineObjectFactoryBase.h +++ b/plugins/flake/textshape/kotext/KoInlineObjectFactoryBase.h @@ -1,107 +1,107 @@ /* This file is part of the KDE project * Copyright (C) 2006 Thomas Zander * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOINLINEOBJECTFACTORY_H #define KOINLINEOBJECTFACTORY_H #include #include "kritatext_export.h" class KoInlineObject; class InlineObjectFactoryPrivate; class KoProperties; /// A template used in the KoInlineObjectFactoryBase struct KRITATEXT_EXPORT KoInlineObjectTemplate { QString id; ///< The id of the inlineObject QString name; ///< The name to be shown for this template /** * The properties which, when passed to the KoInlineObjectFactoryBase::createInlineObject() method * result in the object this template represents. */ const KoProperties *properties; }; /** * A factory for inline text objects. There should be one for each plugin type to * allow the creation of the inlineObject from that plugin. * The factory additionally has information to allow showing a menu entry for user * access to the object-type. * @see KoInlineObjectRegistry */ class KRITATEXT_EXPORT KoInlineObjectFactoryBase { public: /// The type of inlineObject this factory creates. enum ObjectType { TextVariable, ///< The factory creates KoVariable inherting objects. Other = 0x100 ///< The factory creates objects that should not be shown in any menu }; /** * Create the new factory - * @param parent the parent QObject for memory management usage. * @param id a string that will be used internally for referencing the variable-type. + * @param type the object type for the new factory. */ KoInlineObjectFactoryBase(const QString &id, ObjectType type); virtual ~KoInlineObjectFactoryBase(); /** * Create a new instance of an inline object. */ virtual KoInlineObject *createInlineObject(const KoProperties *properties = 0) const = 0; /** * return the id for the variable this factory creates. * @return the id for the variable this factory creates. */ QString id() const; /** * Returns the type of object this factory creates. * The main purpose is to group plugins per type in, for example, a menu. */ ObjectType type() const; /** * Return all the templates this factory knows about. * Each template shows a different way to create an object this factory is specialized in. */ QList templates() const; QStringList odfElementNames() const; QString odfNameSpace() const; void setOdfElementNames(const QString &nameSpace, const QStringList &names); protected: /** * Add a template with the properties of a specific type of object this factory can generate * using the createInlineObject() method. * @param params The new template this factory knows to produce */ void addTemplate(const KoInlineObjectTemplate ¶ms); private: InlineObjectFactoryPrivate * const d; }; #endif diff --git a/plugins/flake/textshape/kotext/KoInlineTextObjectManager.h b/plugins/flake/textshape/kotext/KoInlineTextObjectManager.h index 75500f0d24..64f1c83bb9 100644 --- a/plugins/flake/textshape/kotext/KoInlineTextObjectManager.h +++ b/plugins/flake/textshape/kotext/KoInlineTextObjectManager.h @@ -1,186 +1,186 @@ /* This file is part of the KDE project * Copyright (C) 2006-2009 Thomas Zander * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOINLINETEXTOBJECTMANAGER_H #define KOINLINETEXTOBJECTMANAGER_H #include "KoInlineObject.h" #include "KoVariableManager.h" #include "kritatext_export.h" // Qt + kde #include #include class KoCanvasBase; class KoTextLocator; class KoInlineNote; class KoInlineCite; class QTextCharFormat; class QAction; /** * A container to register all the inlineTextObjects with. * Inserting an inline-object in a QTextDocument should be done via this manager which will * insert a placeholder in the text and you should add the KoInlineTextObjectManager to the * KoTextDocument. */ class KRITATEXT_EXPORT KoInlineTextObjectManager : public QObject { Q_OBJECT public: enum Properties { InlineInstanceId = 577297549 // If you change this, don't forget to change KoCharacterStyle.h }; /// Constructor explicit KoInlineTextObjectManager(QObject *parent = 0); ~KoInlineTextObjectManager() override; /** * Retrieve a formerly added inline object based on the format. * @param format the textCharFormat */ KoInlineObject *inlineTextObject(const QTextCharFormat &format) const; /** * Retrieve a formerly added inline object based on the cursor position. * @param cursor the cursor which position is used. The anchor is ignored. */ KoInlineObject *inlineTextObject(const QTextCursor &cursor) const; /** * Retrieve a formerly added inline object based on the KoInlineObject::id() of the object. * @param id the id assigned to the inline text object when it was added. */ KoInlineObject *inlineTextObject(int id) const; QList inlineTextObjects() const; /** * Insert a new inline object into the manager as well as the document. * This method will cause a placeholder to be inserted into the text at cursor position, * possibly replacing a selection. The object will then be used as an inline * character and painted at the specified location in the text. * @param cursor the cursor which indicated the document and the position in that document * where the inline object will be inserted. * @param object the inline object to insert. */ void insertInlineObject(QTextCursor &cursor, KoInlineObject *object); /** * Add inline object into the manager. * * This methods add the inline object into the manager. This is useful if you have a command * that removes and adds a inline object to the manager. If the object already was inserted before * (the object id is already set) it keeps the old id, otherwise a new id will be generated. * * @param object the inline object to insert. */ void addInlineObject(KoInlineObject* object); /** * Remove an inline object from this manager. The object will also be removed from * the bookmarkmanager if it is a bookmark. This is not done smart: you might end up * with dangling start or end bookmarks. * Should really only be called by KoTextEditor's delete commands - * @param the object to be removed + * @param object the object to be removed */ void removeInlineObject(KoInlineObject *object); /** * Set a property that may have changed which will be forwarded to all registered textObjects. * If the key has changed then all registered InlineObject instances that have stated to want * updates will get called with the change. * The property will be stored to allow it to be retrieved via the intProperty() and friends. * @see KoInlineObject::propertyChangeListener() */ void setProperty(KoInlineObject::Property key, const QVariant &value); /// retrieve a property QVariant property(KoInlineObject::Property key) const; /// retrieve an int property int intProperty(KoInlineObject::Property key) const; /// retrieve a bool property bool boolProperty(KoInlineObject::Property key) const; /// retrieve a string property QString stringProperty(KoInlineObject::Property key) const; /// remove a property from the store. void removeProperty(KoInlineObject::Property key); /** * Return the variableManager. */ const KoVariableManager *variableManager() const; /** * Return the variableManager. */ KoVariableManager *variableManager(); /** * Create a list of actions that can be used to plug into a menu, for example. * This method internally uses KoInlineObjectRegistry::createInsertVariableActions() but extends * the list with all registered variable-names. * Each of these actions, when executed, will insert the relevant variable in the current text-position. * The actions assume that the text tool is selected, if that's not the case then they will silently fail. * @param host the canvas for which these actions are created. Note that the actions will get these * actions as a parent (for memory management purposes) as well. * @see KoVariableManager */ QList createInsertVariableActions(KoCanvasBase *host) const; QList textLocators() const; /** * It returns a list of all end notes in the document */ QList endNotes() const; QMap citations(bool duplicatesEnabled = true) const; QList citationsSortedByPosition(bool duplicatesEnabled = true, QTextBlock block = QTextBlock()) const; public Q_SLOTS: void documentInformationUpdated(const QString &info, const QString &data); Q_SIGNALS: /** * Emitted whenever a property is set and it turns out to be changed. */ void propertyChanged(int, const QVariant &variant); private: void insertObject(KoInlineObject *object); QHash m_objects; QHash m_deletedObjects; QList m_listeners; // holds objects also in m_objects, but which want propertyChanges int m_lastObjectId; QHash m_properties; KoVariableManager m_variableManager; }; Q_DECLARE_METATYPE(KoInlineTextObjectManager*) #endif diff --git a/plugins/flake/textshape/kotext/KoTextDebug.h b/plugins/flake/textshape/kotext/KoTextDebug.h index 063bc39056..04407cc806 100644 --- a/plugins/flake/textshape/kotext/KoTextDebug.h +++ b/plugins/flake/textshape/kotext/KoTextDebug.h @@ -1,293 +1,293 @@ /* This file is part of the KDE project * Copyright (C) 2008 Girish Ramakrishnan * Copyright (C) 2009 Elvis Stansvik * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOTEXTDEBUG_H #define KOTEXTDEBUG_H #include "kritatext_export.h" class QTextDocument; class QTextFrame; class QTextBlock; class QTextTable; class QTextTableCell; class QTextFragment; class QTextCharFormat; class QTextListFormat; class QTextTableFormat; class QTextTableCellFormat; class QTextFrameFormat; class QTextBlockFormat; class QTextStream; class KoParagraphStyle; class KoCharacterStyle; class KoTableStyle; class KoTableCellStyle; #include #include /** * @brief KoText debugging class. * * This class provides a set of public static functions for debugging the structure of * QTextDocument text documents. The functions will dump the structure of the document * along with any formats in a human-friendly pseudo-XML format. * * To most top level function is dumpDocument(), which can be used to dump an entire * document. In addition to that, there's a set of functions for dumping certain * parts of a document , such as dumpFrame(), dumpBlock() et.c. * * For example, the following code * * @code * QTextDocument doc; * QTextCursor cursor(&doc); * cursor.insertText("Hello!\n"); * cursor.insertHtml("World!"); * * QTextStream out(stdout); * KoTextDebug::dumpDocument(&doc, out); * @endcode * * will result in this output: * *
  * 
  *   
  *     
  *       
  *         |Hello!|
  *       
  *     
  *
  *     
  *       
  *         |World!|
  *       
  *     
  *   
  * 
  * 
* * @sa dumpDocument(), dumpFrame(), dumpBlock() */ class KRITATEXT_EXPORT KoTextDebug { public: /** * Dump the structure of the specified document. * * @param document a pointer to the document that should be dumped. * @param out output stream to dump to. */ static void dumpDocument(const QTextDocument *document, QTextStream &out); /** * Dump the structure of the specified frame. * * @sa frameAttributes() * * @param frame a pointer to the frame that should be dumped. * @param out output stream to dump to. */ static void dumpFrame(const QTextFrame *frame, QTextStream &out); /** * Dump the structure of the specified block. * * @param block the block that should be dumped. * @param out output stream to dump to. */ static void dumpBlock(const QTextBlock &block, QTextStream &out); /** * Dump the structure of the specified table. * * @sa tableAttributes() * - * @param a pointer to the table that should be dumped. + * @param table pointer to the table that should be dumped. * @param out output stream to dump to. */ static void dumpTable(const QTextTable *table, QTextStream &out); /** * Dump the structure of the specified table cell. * * @sa tableCellAttributes() * * @param cell the cell that should be dumped. * @param out output stream to dump to. */ static void dumpTableCell(const QTextTableCell &cell, QTextStream &out); /** * Dump the contents of the specified text fragment. * * @note { The fragment content will be enclosed in '|' characters. } * * @param fragment the fragment which content should be dumped. * @param out output stream to dump to. */ static void dumpFragment(const QTextFragment &fragment, QTextStream &out); /** * Get the properties of the given text character format. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* * @param format the text character format from which properties should be fetched. * @return the formatted attribute string. */ static QString textAttributes(const QTextCharFormat &format); /** * Get the properties of the given character style. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* * @param style the character style from which properties should be fetched. * @return the formatted attribute string. */ static QString textAttributes(const KoCharacterStyle &style); /** * Get the properties of the given text block format. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* * @param format the text block format from which properties should be fetched. * @return the formatted attribute string. */ static QString paraAttributes(const QTextBlockFormat &format); /** * Get the properties of the given paragraph style. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* * @param style the paragraph style from which properties should be fetched. * @return the formatted attribute string. */ static QString paraAttributes(const KoParagraphStyle &style); /** * Get the properties of the given list format. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* * @param format the list format from which properties should be fetched. * @return the formatted attribute string. */ static QString listAttributes(const QTextListFormat &format); /** * Get the properties of the given table style. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* * @param tableStyle the table style from which properties should be fetched. * @return the formatted attribute string. */ static QString tableAttributes(const KoTableStyle &tableStyle); /** * Get the properties of the given table format. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* * @param tableFormat the table format from which properties should be fetched. * @return the formatted attribute string. */ static QString tableAttributes(const QTextTableFormat &tableFormat); /** * Get the properties of the given table cell style. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* - * @param tableStyle the table cell style from which properties should be fetched. + * @param tableCellStyle the table cell style from which properties should be fetched. * @return the formatted attribute string. */ static QString tableCellAttributes(const KoTableCellStyle &tableCellStyle); /** * Get the properties of the given table cell format. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* * @param tableCellFormat the table cell format from which properties should be fetched. * @return the formatted attribute string. */ static QString tableCellAttributes(const QTextTableCellFormat &tableCellFormat); /** * Get the properties of the given text frame format. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* - * @param format the text frame format from which properties should be fetched. + * @param frameFormat the text frame format from which properties should be fetched. * @return the formatted attribute string. */ static QString frameAttributes(const QTextFrameFormat &frameFormat); /** * Get the inline object properties of the object with the given text character format. * * The returned string will be formatted in XML-like attribute list format: * *
"key=value key2=value2 ..."
* - * @param format the character format of the object from which properties should be fetched. + * @param textFormat the character format of the object from which properties should be fetched. * @return the formatted attribute string. */ static QString inlineObjectAttributes(const QTextCharFormat &textFormat); private: KoTextDebug(); KoTextDebug(const KoTextDebug&); KoTextDebug operator=(const KoTextDebug&); static const QTextDocument *document; /**< Pointer to the debugged document. */ static int depth; /**< Current indentation depth. */ static const int INDENT; /**< Indentation value. */ }; #endif /* KOTEXTDEBUG_H */ diff --git a/plugins/flake/textshape/kotext/KoTextEditor.h b/plugins/flake/textshape/kotext/KoTextEditor.h index 33a4de7453..c08292387e 100644 --- a/plugins/flake/textshape/kotext/KoTextEditor.h +++ b/plugins/flake/textshape/kotext/KoTextEditor.h @@ -1,561 +1,561 @@ /* This file is part of the KDE project * Copyright (C) 2009 Pierre Stirnweiss * Copyright (C) 2009 Thomas Zander * Copyright (C) 2011 Boudewijn Rempt * Copyright (C) 2011-2012 C. Boemann * Copyright (C) 2014 Denis Kuplyakov * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOTEXTEDITOR_H #define KOTEXTEDITOR_H #include "kritatext_export.h" #include #include #include #include #include #include #include class KoListLevelProperties; class KoCharacterStyle; class KoInlineObject; class KoParagraphStyle; class KoInlineNote; class KoInlineCite; class KoBibliographyInfo; class KoCanvasBase; class KoTableOfContentsGeneratorInfo; class KoShapeAnchor; class KoShape; class KoBookmark; class KoAnnotation; class KoTextRangeManager; class KoTextVisitor; class KUndo2Command; class QTextBlock; class QTextCharFormat; class QTextBlockFormat; class QTextDocument; class QTextDocumentFragment; class QString; class QMimeData; /** * KoTextEditor is a wrapper around QTextCursor. It handles undo/redo and change * tracking for all editing commands. */ class KRITATEXT_EXPORT KoTextEditor: public QObject { Q_OBJECT public: enum ChangeListFlag { NoFlags = 0, ModifyExistingList = 1, MergeWithAdjacentList = 2, MergeExactly = 4, CreateNumberedParagraph = 8, AutoListStyle = 16, DontUnsetIfSame = 32 /// do not unset the current list style if it is already been set the same }; Q_DECLARE_FLAGS(ChangeListFlags, ChangeListFlag) explicit KoTextEditor(QTextDocument *document); ~KoTextEditor() override; /** * Retrieves the texteditor for the document of the first text shape in the current * set of selected shapes on the given canvas. * * @param canvas the canvas we will check for a suitable selected shape. * @returns a texteditor, or 0 if there is no shape active that has a QTextDocument as * userdata */ static KoTextEditor *getTextEditorFromCanvas(KoCanvasBase *canvas); public: // KoToolSelection overloads /// returns true if the wrapped QTextCursor has a selection. bool hasSelection() const; /** returns true if the current cursor position is protected from editing - * @param cached use cached value if available. + * @param useCached use cached value if available. */ bool isEditProtected(bool useCached = false) const; public: bool operator!=(const QTextCursor &other) const; bool operator<(const QTextCursor &other) const; bool operator<=(const QTextCursor &other) const; bool operator==(const QTextCursor &other) const; bool operator>(const QTextCursor &other) const; bool operator>=(const QTextCursor &other) const; const QTextCursor constCursor() const; private: // for the call to KoTextLoader::loadBody, which has a QTextCursor friend class KoTextPaste; // from KoTextEditor_p.h friend class CharFormatVisitor; // our commands can have access to us friend class DeleteTableRowCommand; friend class DeleteTableColumnCommand; friend class InsertTableRowCommand; friend class InsertTableColumnCommand; friend class ChangeTrackedDeleteCommand; friend class DeleteCommand; friend class InsertInlineObjectCommand; friend class InsertNoteCommand; friend class ParagraphFormattingCommand; friend class RenameSectionCommand; friend class NewSectionCommand; friend class SplitSectionsCommand; // for unittests friend class TestKoInlineTextObjectManager; // temporary... friend class TextShape; friend class TextTool; /** * This should be used only as read-only cursor or within a KUndo2Command sub-class which * will be added to the textEditor with addCommand. For examples of proper implementation of * such undoCommands, see the TextShape commands. */ QTextCursor* cursor(); public Q_SLOTS: /// This adds the \ref command to the calligra undo stack. /// /// From this point forward all text manipulation is placed in the qt text systems internal /// undostack while also adding representative subcommands to \ref command. /// /// The \ref command is not redone as part of this process. /// /// Note: Be aware that many KoTextEditor methods start their own commands thus terminating /// the recording of this \ref command. Only use QTextCursor manipulation (with all the issues /// that brings) or only use KoTextEditor methods that don't start their own command. /// /// The recording is automatically terminated when another command is added, which as mentioned /// can happen by executing some of the KoTextEditor methods. void addCommand(KUndo2Command *command); /// This instantly "redo" the command thus placing all the text manipulation the "redo" does /// (should be implemented with a "first redo" pattern) in the qt text systems internal /// undostack while also adding representative subcommands to \ref command. /// /// When \ref command is done "redoing" no further text manipulation is added as subcommands. /// /// \ref command is not put on the calligra undo stack. That is the responsibility of the /// caller, or the caller can choose to quickly undo and then delete the \ref command. void instantlyExecuteCommand(KUndo2Command *command); void registerTrackedChange(QTextCursor &selection, KoGenChange::Type changeType, const KUndo2MagicString &title, QTextFormat &format, QTextFormat &prevFormat, bool applyToWholeBlock = false); void bold(bool bold); void italic(bool italic); void underline(bool underline); void strikeOut(bool strikeOut); void setHorizontalTextAlignment(Qt::Alignment align); void setVerticalTextAlignment(Qt::Alignment align); void increaseIndent(); void decreaseIndent(); void increaseFontSize(); void decreaseFontSize(); void setFontFamily(const QString &font); void setFontSize(qreal size); void setTextColor(const QColor &color); void setTextBackgroundColor(const QColor &color); void setStyle(KoParagraphStyle *style); void setStyle(KoCharacterStyle *style); void mergeAutoStyle(const QTextCharFormat &deltaCharFormat); void applyDirectFormatting(const QTextCharFormat &deltaCharFormat, const QTextBlockFormat &deltaBlockFormat, const KoListLevelProperties &llp); /** * Insert an inlineObject (such as a variable) at the current cursor position. Possibly replacing the selection. * @param inliner the object to insert. - * @param cmd a parent command for the commands created by this methods. If present, the commands + * @param parent a parent command for the commands created by this methods. If present, the commands * will not be added to the document's undo stack automatically. */ void insertInlineObject(KoInlineObject *inliner, KUndo2Command *parent = 0); /** * update the position of all inline objects from the given start point to the given end point. * @param start start position for updating. If 0, we update from the start of the document * @param end end position for updating. If -1, we update to the end of the document */ void updateInlineObjectPosition(int start = 0, int end = -1); /** * Remove the KoShapeAnchor objects from the document. * * NOTE: Call this method only when the shapes belonging to the anchors have been deleted. */ void removeAnchors(const QList &anchors, KUndo2Command *parent); /** * Remove the KoAnnotation objects from the document. * * NOTE: Call this method only when the shapes belonging to the annotations have been deleted. * This is not the way to delete annotations directly - instead delete the shape or * delete the text containing the annotation */ void removeAnnotations(const QList &annotations, KUndo2Command *parent); /** * At the current cursor position, insert a marker that marks the next word as being part of the index. * @returns returns the index marker when successful, or 0 if failed. Failure can be because there is no word * at the cursor position or there already is an index marker available. */ KoInlineObject *insertIndexMarker(); /// add a bookmark on current cursor location or current selection KoBookmark *addBookmark(const QString &name); /// Add an annotation at the current cursor location or the current selection. KoAnnotation *addAnnotation(KoShape *annotationShape); KoTextRangeManager *textRangeManager() const; /** * Insert a frame break at the cursor position, moving the rest of the text to the next frame. */ void insertFrameBreak(); /** * paste the given mimedata object at the current position * @param canvas the canvas we used when placing the shape. * @param mimeData: the mimedata containing text, html or odf * @param pasteAsText: if true, paste without formatting */ void paste(KoCanvasBase *canvas, const QMimeData *mimeData, bool pasteAsText=false); /** * @param numberingEnabled when true, we will enable numbering for the current paragraph (block). */ void toggleListNumbering(bool numberingEnabled); /** * change the current block's list properties */ void setListProperties(const KoListLevelProperties &llp, ChangeListFlags flags = ChangeListFlags(ModifyExistingList | MergeWithAdjacentList), KUndo2Command *parent = 0); // ------------------------------------------------------------- // Wrapped QTextCursor methods // ------------------------------------------------------------- int anchor() const; bool atBlockEnd() const; bool atBlockStart() const; bool atEnd() const; bool atStart() const; QTextBlock block() const; QTextCharFormat blockCharFormat() const; QTextBlockFormat blockFormat() const; int blockNumber() const; QTextCharFormat charFormat() const; void clearSelection(); int columnNumber() const; void deleteChar(); void deletePreviousChar(); QTextDocument *document() const; /// Same as Qt, only to be used inside KUndo2Commands KUndo2Command *beginEditBlock(const KUndo2MagicString &title = KUndo2MagicString()); void endEditBlock(); /** * Delete one character in the specified direction or a selection. * Warning: From the outside this method should only be used with a parent command * and only if there is a selection * @param previous should be true if act like backspace */ void deleteChar(bool previous, KUndo2Command *parent = 0); bool hasComplexSelection() const; /** * Insert a table at the current cursor position. * @param rows the number of rows in the created table. * @param columns the number of columns in the created table. */ void insertTable(int rows, int columns); /** * Insert a table row above the current cursor position (if in a table). */ void insertTableRowAbove(); /** * Insert a table row below the current cursor position (if in a table). */ void insertTableRowBelow(); /** * Insert a table column to the left of the current cursor position (if in a table). */ void insertTableColumnLeft(); /** * Insert a table column to the right of the current cursor position (if in a table). */ void insertTableColumnRight(); /** * Delete a table column where the cursor is (if in a table). */ void deleteTableColumn(); /** * Delete a table row where the cursor is (if in a table). */ void deleteTableRow(); /** * Merge table cells (selected by the cursor). */ void mergeTableCells(); /** * Split table cells (selected by the cursor) that were previously merged. */ void splitTableCells(); /** * Sets the width of a table column. * @param table is the table to be adjusted. * @param column the column that is to be adjusted. */ void adjustTableColumnWidth(QTextTable *table, int column, qreal width, KUndo2Command *parentCommand = 0); /** * Sets the height of a table row. * @param table is the table to be adjusted. * @param row the row that is to be adjusted. */ void adjustTableRowHeight(QTextTable *table, int row, qreal height, KUndo2Command *parentCommand = 0); /** * Changes the width of a table by adjusting the margins. * @param table is the table to be adjusted. * @param dLeft delta value for the left margin. * @param dRight delta value for the right margin. */ void adjustTableWidth(QTextTable *table, qreal dLeft, qreal dRight); /** * Sets the border formatting of a side in a table cell. * @param table is the table to be adjusted. * @param column the column coordinate of the cell that is to be adjusted. * @param row the row coordinate of the cell that is to be adjusted. */ void setTableBorderData(QTextTable *table, int row, int column, KoBorder::BorderSide cellSide, const KoBorder::BorderData &data); /** * Insert a footnote at the current cursor position * @return a pointer to the inserted footnote */ KoInlineNote *insertFootNote(); /** * Insert an endnote at the current cursor position * @return a pointer to the inserted endnote */ KoInlineNote *insertEndNote(); /** * Insert a table of Contents at the current cursor position. */ void insertTableOfContents(KoTableOfContentsGeneratorInfo *info); /** * Configures various values of a ToC to the one passed in info */ void setTableOfContentsConfig(KoTableOfContentsGeneratorInfo *info, const QTextBlock &block); void insertBibliography(KoBibliographyInfo *info); KoInlineCite *insertCitation(); /** * Inserts the supplied text at the current cursor position. If the second argument is * supplied, a link is inserted at the current cursor position with the hRef as given * by the user. To test whether the supplied link destination is a web url or a bookmark, * a regular expression ( \\S+://\\S+ ) is used. * @param text is the text to be inserted * @param hRef if supplied is the Hypertext reference */ void insertText(const QString &text, const QString &hRef = QString()); void insertHtml(const QString &html); void mergeBlockFormat( const QTextBlockFormat &modifier); bool movePosition(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode = QTextCursor::MoveAnchor, int n = 1); /** * Inserts a new paragraph and warps it to new section * Source: * some|textP * Result: * someP * [|textP] * * [] -- section bounds * | -- cursor зщышешщт * P -- paragraph sign */ void newSection(); /** * Splits sections startings and inserts paragraph between them. * Source: {sectionIdToInsertBefore == 1} * [[[sometext... * ^ * 012 * Result: * [P * [[sometext... * * [] -- section bounds * P -- paragraph sign */ void splitSectionsStartings(int sectionIdToInsertBefore); /** * Splits section endings and insert paragraph between them. * Source: {sectionIdToInsertAfter == 1} * sometext]]] * ^ * 012 * Result: * sometext]]P * P] * * [] -- section bounds * P -- paragraph sign */ void splitSectionsEndings(int sectionIdToInsertAfter); void renameSection(KoSection *section, const QString &newName); void newLine(); bool isWithinSelection(int position) const; int position() const; void select(QTextCursor::SelectionType selection); QString selectedText() const; QTextDocumentFragment selection() const; int selectionEnd() const; int selectionStart() const; void setBlockFormat(const QTextBlockFormat &format); void setCharFormat(const QTextCharFormat &format); void setPosition(int pos, QTextCursor::MoveMode mode = QTextCursor::MoveAnchor); void setVisualNavigation(bool on); bool visualNavigation() const; const QTextFrame *currentFrame () const; const QTextList *currentList () const; const QTextTable *currentTable () const; Q_SIGNALS: void cursorPositionChanged(); void textFormatChanged(); void characterStyleApplied(KoCharacterStyle *style); void paragraphStyleApplied(KoParagraphStyle *style); protected: void recursivelyVisitSelection(QTextFrame::iterator it, KoTextVisitor &visitor) const; private: Q_PRIVATE_SLOT(d, void documentCommandAdded()) class Private; friend class Private; Private* const d; }; Q_DECLARE_METATYPE(KoTextEditor*) Q_DECLARE_METATYPE(bool *) Q_DECLARE_OPERATORS_FOR_FLAGS(KoTextEditor::ChangeListFlags) #endif // KOTEXTEDITOR_H diff --git a/plugins/flake/textshape/kotext/KoTextEditor_p.h b/plugins/flake/textshape/kotext/KoTextEditor_p.h index d57122b9d2..18c3a53c1c 100644 --- a/plugins/flake/textshape/kotext/KoTextEditor_p.h +++ b/plugins/flake/textshape/kotext/KoTextEditor_p.h @@ -1,264 +1,264 @@ /* This file is part of the KDE project * Copyright (C) 2009 Pierre Stirnweiss * Copyright (C) 2009 Thomas Zander * Copyright (C) 2015 Soma Schliszka * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOTEXTEDITOR_P_H #define KOTEXTEDITOR_P_H #include "KoTextEditor.h" #include "KoTextDocument.h" #include "styles/KoParagraphStyle.h" #include "styles/KoStyleManager.h" #include "changetracker/KoChangeTracker.h" #include #include #include #include #include #include #include class KUndo2Command; class Q_DECL_HIDDEN KoTextEditor::Private { public: enum State { NoOp, KeyPress, Delete, Format, Custom }; explicit Private(KoTextEditor *qq, QTextDocument *document); ~Private() {} void documentCommandAdded(); void updateState(State newState, const KUndo2MagicString &title = KUndo2MagicString()); void newLine(KUndo2Command *parent); void clearCharFormatProperty(int propertyId); void emitTextFormatChanged(); KoTextEditor *q; QTextCursor caret; QTextDocument *document; QStack commandStack; bool addNewCommand; bool dummyMacroAdded; int customCommandCount; KUndo2MagicString commandTitle; State editorState; bool editProtected; bool editProtectionCached; }; class KoTextVisitor { public: /// The ObjectVisitingMode enum marks how was the visited object selected. enum ObjectVisitingMode { Partly, /// The visited object (table, cell, ...) is just @b partly selected. (Eg. just one cell is selected in the visited table) Entirely, /// The visited object (table, cell, ...) is @b entirely selected. }; explicit KoTextVisitor(KoTextEditor *editor) : m_abortVisiting(false) , m_editor(editor) { } virtual ~KoTextVisitor() {} // called whenever a visit was prevented by editprotection virtual void nonVisit() {} virtual void visitFragmentSelection(QTextCursor &) { } /** * This method allows to perform custom operation when the visitor reaches a QTextTable * @param visitedTable pointer to the currently visited table object * @param visitingMode flag, marks if the table is just partly visited or entirely */ virtual void visitTable(QTextTable *visitedTable, ObjectVisitingMode visitingMode) { Q_UNUSED(visitedTable); Q_UNUSED(visitingMode); } /** * This method allows to perform custom operation when the visitor reaches a QTextTableCell - * @param visitedTable pointer to the currently visited cell object + * @param visitedCell pointer to the currently visited cell object * @param visitingMode flag, marks if the cell is just partly visited or entirely */ virtual void visitTableCell(QTextTableCell *visitedCell, ObjectVisitingMode visitingMode) { Q_UNUSED(visitedCell); Q_UNUSED(visitingMode); } // The default implementation calls visitFragmentSelection on each fragment.intersect.selection virtual void visitBlock(QTextBlock &block, const QTextCursor &caret) { for (QTextBlock::iterator it = block.begin(); it != block.end(); ++it) { QTextCursor fragmentSelection(caret); fragmentSelection.setPosition(qMax(caret.selectionStart(), it.fragment().position())); fragmentSelection.setPosition(qMin(caret.selectionEnd(), it.fragment().position() + it.fragment().length()), QTextCursor::KeepAnchor); if (fragmentSelection.anchor() >= fragmentSelection.position()) { continue; } visitFragmentSelection(fragmentSelection); } } bool abortVisiting() { return m_abortVisiting;} void setAbortVisiting(bool abort) {m_abortVisiting = abort;} KoTextEditor * editor() const {return m_editor;} private: bool m_abortVisiting; KoTextEditor *m_editor; }; class BlockFormatVisitor { public: BlockFormatVisitor() {} virtual ~BlockFormatVisitor() {} virtual void visit(QTextBlock &block) const = 0; static void visitSelection(KoTextEditor *editor, const BlockFormatVisitor &visitor, const KUndo2MagicString &title = kundo2_i18n("Format"), bool resetProperties = false, bool registerChange = true) { int start = qMin(editor->position(), editor->anchor()); int end = qMax(editor->position(), editor->anchor()); QTextBlock block = editor->block(); if (block.position() > start) block = block.document()->findBlock(start); // now loop over all blocks that the selection contains and alter the text fragments where applicable. while (block.isValid() && block.position() <= end) { QTextBlockFormat prevFormat = block.blockFormat(); if (resetProperties) { if (KoTextDocument(editor->document()).styleManager()) { KoParagraphStyle *old = KoTextDocument(editor->document()).styleManager()->paragraphStyle(block.blockFormat().intProperty(KoParagraphStyle::StyleId)); if (old) old->unapplyStyle(block); } } visitor.visit(block); QTextCursor cursor(block); QTextBlockFormat format = cursor.blockFormat(); if (registerChange) editor->registerTrackedChange(cursor, KoGenChange::FormatChange, title, format, prevFormat, true); block = block.next(); } } }; class CharFormatVisitor { public: CharFormatVisitor() {} virtual ~CharFormatVisitor() {} virtual void visit(QTextCharFormat &format) const = 0; static void visitSelection(KoTextEditor *editor, const CharFormatVisitor &visitor, const KUndo2MagicString &title = kundo2_i18n("Format"), bool registerChange = true) { int start = qMin(editor->position(), editor->anchor()); int end = qMax(editor->position(), editor->anchor()); if (start == end) { // just set a new one. QTextCharFormat format = editor->charFormat(); visitor.visit(format); if (registerChange && KoTextDocument(editor->document()).changeTracker() && KoTextDocument(editor->document()).changeTracker()->recordChanges()) { QTextCharFormat prevFormat(editor->charFormat()); int changeId = KoTextDocument(editor->document()).changeTracker()->getFormatChangeId(title, format, prevFormat, editor->charFormat().property( KoCharacterStyle::ChangeTrackerId ).toInt()); format.setProperty(KoCharacterStyle::ChangeTrackerId, changeId); } editor->cursor()->setCharFormat(format); return; } QTextBlock block = editor->block(); if (block.position() > start) block = block.document()->findBlock(start); QList cursors; QList formats; // now loop over all blocks that the selection contains and alter the text fragments where applicable. while (block.isValid() && block.position() < end) { QTextBlock::iterator iter = block.begin(); while (! iter.atEnd()) { QTextFragment fragment = iter.fragment(); if (fragment.position() > end) break; if (fragment.position() + fragment.length() <= start) { ++iter; continue; } QTextCursor cursor(block); cursor.setPosition(fragment.position() + 1); QTextCharFormat format = cursor.charFormat(); // this gets the format one char after the position. visitor.visit(format); if (registerChange && KoTextDocument(editor->document()).changeTracker() && KoTextDocument(editor->document()).changeTracker()->recordChanges()) { QTextCharFormat prevFormat(cursor.charFormat()); int changeId = KoTextDocument(editor->document()).changeTracker()->getFormatChangeId(title, format, prevFormat, cursor.charFormat().property( KoCharacterStyle::ChangeTrackerId ).toInt()); format.setProperty(KoCharacterStyle::ChangeTrackerId, changeId); } cursor.setPosition(qMax(start, fragment.position())); int to = qMin(end, fragment.position() + fragment.length()); cursor.setPosition(to, QTextCursor::KeepAnchor); cursors.append(cursor); formats.append(format); QTextCharFormat prevFormat(cursor.charFormat()); if (registerChange) editor->registerTrackedChange(cursor,KoGenChange::FormatChange,title, format, prevFormat, false); //this will lead to every fragment having a different change until the change merging in registerTrackedChange checks also for formatChange or not? ++iter; } block = block.next(); } QList::Iterator iter = formats.begin(); Q_FOREACH (QTextCursor cursor, cursors) { cursor.setCharFormat(*iter); ++iter; } } }; #endif //KOTEXTEDITOR_P_H diff --git a/plugins/flake/textshape/kotext/commands/ChangeListCommand.h b/plugins/flake/textshape/kotext/commands/ChangeListCommand.h index 2f2cfaffe8..0aacc97fc4 100644 --- a/plugins/flake/textshape/kotext/commands/ChangeListCommand.h +++ b/plugins/flake/textshape/kotext/commands/ChangeListCommand.h @@ -1,106 +1,107 @@ /* This file is part of the KDE project * Copyright (C) 2007 Thomas Zander * Copyright (C) 2008 Girish Ramakrishnan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef CHANGELISTCOMMAND #define CHANGELISTCOMMAND #include "KoTextCommandBase.h" #include "KoListStyle.h" #include "KoTextEditor.h" #include "KoListLevelProperties.h" #include #include #include class KoList; /** * This command is useful to alter the list-association of a single textBlock. */ class ChangeListCommand : public KoTextCommandBase { public: - //FIXME: following comments seems to describe another function /** - * Change the list property of 'block'. - * @param block the paragraph to change the list property of - * @param style indicates which style to use. + * Change the list command. + * @param cursor text cursor properties. + * @param levelProperties level properties. + * @param flags the list flags. * @param parent the parent undo command for macro functionality */ ChangeListCommand(const QTextCursor &cursor, const KoListLevelProperties &levelProperties, KoTextEditor::ChangeListFlags flags, KUndo2Command *parent = 0); /** - * Change the list property of 'block'. - * @param block the paragraph to change the list property of - * @param style the style to apply - * @param exact if true then the actual style 'style' should be set, if false we possibly merge with another similar style that is near the block + * Change the list command. + * @param cursor text cursor properties. + * @param style the style to apply. + * @param level the level in the list. + * @param flags the list flags. * @param parent the parent undo command for macro functionality */ ChangeListCommand(const QTextCursor &cursor, KoListStyle *style, int level, KoTextEditor::ChangeListFlags flags, KUndo2Command *parent = 0); ~ChangeListCommand() override; /// redo the command void redo() override; /// revert the actions done in redo void undo() override; /// reimplemented from KUndo2Command int id() const override { return 58450687; } /// reimplemented from KUndo2Command bool mergeWith(const KUndo2Command *other) override; private: enum CommandAction { CreateNew, ModifyExisting, ReparentList, MergeList, RemoveList }; bool extractTextBlocks(const QTextCursor &cursor, int level, KoListStyle::Style newStyle = KoListStyle::None); int detectLevel(const QTextBlock &block, int givenLevel); void initList(KoListStyle *style); bool formatsEqual(const KoListLevelProperties &llp, const QTextListFormat &format); int m_flags; bool m_first; bool m_alignmentMode; QList m_blocks; QHash m_formerProperties; QHash m_newProperties; QHash m_levels; QHash m_list; QHash m_oldList; QHash m_actions; }; #endif diff --git a/plugins/flake/textshape/kotext/styles/KoTableCellStyle.h b/plugins/flake/textshape/kotext/styles/KoTableCellStyle.h index af96603da3..f8dadfd088 100644 --- a/plugins/flake/textshape/kotext/styles/KoTableCellStyle.h +++ b/plugins/flake/textshape/kotext/styles/KoTableCellStyle.h @@ -1,376 +1,376 @@ /* This file is part of the KDE project * Copyright (C) 2006-2010 Thomas Zander * Copyright (C) 2008 Thorsten Zachmann * Copyright (C) 2008 Girish Ramakrishnan * Copyright (C) 2009 KO GmbH * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOTABLECELLSTYLE_H #define KOTABLECELLSTYLE_H #include "KoText.h" #include "kritatext_export.h" #include #include #include #include #include struct Property; class QTextTableCell; class QRectF; class KoStyleStack; class KoGenStyle; class KoParagraphStyle; class KoShapeLoadingContext; class KoShapeSavingContext; class KoTableCellStylePrivate; class QString; class QVariant; /** * A container for all properties for the table cell style. * Each tablecell in the main text either is based on a table cell style, or its not. Where * it is based on a table cell style this is indecated that it has a property 'StyleId' * with an integer as value. The integer value corresponds to the styleId() output of * a specific KoTableCellStyle. * @see KoStyleManager */ class KRITATEXT_EXPORT KoTableCellStyle : public QObject { Q_OBJECT public: enum CellProtectionFlag { NoProtection, HiddenAndProtected, Protected, FormulaHidden, ProtectedAndFormulaHidden }; enum CellTextDirection { Default = 0, LeftToRight, TopToBottom }; enum RotationAlignment { RAlignNone, RAlignBottom, RAlignTop, RAlignCenter }; enum Property { StyleId = QTextTableCellFormat::UserProperty + 7001, ShrinkToFit, ///< Shrink the cell content to fit the size Wrap, ///< Wrap the text within the cell CellProtection, ///< The cell protection when the table is protected PrintContent, ///< Should the content of this cell be printed RepeatContent, ///< Display the cell content as many times as possible DecimalPlaces, ///< Count the maximum number of decimal places to display AlignFromType, ///< Should the alignment property be respected or should the alignment be based on the value type RotationAngle, ///< Rotation angle of the cell content, in degrees Direction, ///< The direction of the text in the cell. This is a CellTextDirection. RotationAlign, ///< How the edge of the text is aligned after rotation. This is a RotationAlignment TextWritingMode, ///< KoText::Direction, the direction for writing text in the cell VerticalGlyphOrientation, ///< bool, specify whether this feature is enabled or not CellBackgroundBrush, ///< the cell background brush, as QTextFormat::BackgroundBrush is used by paragraphs VerticalAlignment, ///< the vertical alignment oinside the cell MasterPageName, ///< Optional name of the master-page InlineRdf, ///< Optional KoTextInlineRdf object Borders, ///< KoBorder, the borders of this cell Shadow, ///< KoShadowStyle, the shadow of this cell CellIsProtected ///< boolean, if true, the cell is protected against edits /// It's not really a property of KoTableCellStyle but defined here for convenience ,LastCellStyleProperty }; /// Constructor explicit KoTableCellStyle(QObject *parent = 0); /// Creates a KoTableCellStyle with the given table cell format, and \a parent explicit KoTableCellStyle(const QTextTableCellFormat &tableCellFormat, QObject *parent = 0); KoTableCellStyle(const KoTableCellStyle &other); KoTableCellStyle& operator=(const KoTableCellStyle &other); /// Destructor ~KoTableCellStyle() override; /// Creates a KoTableCellStyle that represents the formatting of \a block. static KoTableCellStyle *fromTableCell(const QTextTableCell &table, QObject *parent = 0); /// Creates a clean QTextCharFormat, but keeps all the table cell properties. /// This is needed since block.charformat doubles as the QTextTableCellFormat /// This method works even if \a charFormat is not a QTextTableCellFormat static QTextCharFormat cleanCharFormat(const QTextCharFormat &charFormat); /// creates a clone of this style with the specified parent KoTableCellStyle *clone(QObject *parent = 0); /** - * Adjust the bounding rectangle \boundingRect according to the paddings and margins + * Adjust the bounding rectangle \p boundingRect according to the paddings and margins * of this border data. The inverse of this function is boundingRect(). * * \sa boundingRect() * - * @param the bounding rectangle. + * @param boundingRect the bounding rectangle. * @return the adjusted rectangle. */ QRectF contentRect(const QRectF &boundingRect) const; /** * Get the bounding rect given a content rect, this is the inverse of contentRect(). * * \sa contentRect() * * @param contentRect the content rectangle. * @return the bounding rectangle. */ QRectF boundingRect(const QRectF &contentRect) const; void setBackground(const QBrush &brush); /// See similar named method on QTextBlockFormat QBrush background() const; /// See similar named method on QTextBlockFormat void clearBackground(); /** * Get the paragraph style for this cell style * * @return the paragraph style */ KoParagraphStyle *paragraphStyle() const; bool shrinkToFit() const; void setShrinkToFit(bool state); bool repeatContent() const; void setRepeatContent(bool state); void setLeftPadding(qreal padding); void setTopPadding(qreal padding); void setRightPadding(qreal padding); void setBottomPadding(qreal padding); void setPadding(qreal padding); qreal leftPadding() const; qreal rightPadding() const; qreal topPadding() const; qreal bottomPadding() const; void setAlignment(Qt::Alignment alignment); Qt::Alignment alignment() const; KoText::Direction textDirection() const; void setTextDirection (KoText::Direction value); void setWrap(bool state); bool wrap() const; CellProtectionFlag cellProtection() const; void setCellProtection (CellProtectionFlag protection); void setPrintContent(bool state); bool printContent() const; void setDecimalPlaces(int places); int decimalPlaces() const; void setAlignFromType(bool state); bool alignFromType() const; void setRotationAngle(qreal value); qreal rotationAngle() const; void setDirection(CellTextDirection direction); CellTextDirection direction() const; void setRotationAlignment(RotationAlignment align); RotationAlignment rotationAlignment () const; void setVerticalGlyphOrientation(bool state); bool verticalGlyphOrientation() const; void setBorders(const KoBorder &borders); KoBorder borders() const; void setShadow (const KoShadowStyle &shadow); KoShadowStyle shadow() const; /// set the parent style this one inherits its unset properties from. void setParentStyle(KoTableCellStyle *parent); /// return the parent style KoTableCellStyle *parentStyle() const; /// return the name of the style. QString name() const; /// set a user-visible name on the style. void setName(const QString &name); /// each style has a unique ID (non persistent) given out by the styleManager int styleId() const; /// each style has a unique ID (non persistent) given out by the styleManager void setStyleId(int id); /// return the optional name of the master-page or a QString() if this paragraph isn't attached to a master-page. QString masterPageName() const; /// Set the name of the master-page. void setMasterPageName(const QString &name); /// copy all the properties from the other style to this style, effectively duplicating it. void copyProperties(const KoTableCellStyle *style); /** * Apply this style to a textTableCellFormat by copying all properties from this, and parent * styles to the target textTableCellFormat. Note that the paragraph format will not be applied * using this method, use the other method for that. * No default values are applied. */ void applyStyle(QTextTableCellFormat &format) const; void applyStyle(QTextTableCell &cell) const; void remove(int key); /// Compare the paragraph, character and list properties of this style with the other bool operator==(const KoTableCellStyle &other) const; void removeDuplicates(const KoTableCellStyle &other); /** * Load the style form the element * * @param context the odf loading context * @param element the element containing the */ void loadOdf(const KoXmlElement *element, KoShapeLoadingContext &context); void saveOdf(KoGenStyle &style, KoShapeSavingContext &context); /** * Returns true if this paragraph style has the property set. * Note that this method does not delegate to the parent style. * @param key the key as found in the Property enum */ bool hasProperty(int key) const; /** * Set a property with key to a certain value, overriding the value from the parent style. * If the value set is equal to the value of the parent style, the key will be removed instead. * @param key the Property to set. * @param value the new value to set on this style. * @see hasProperty(), value() */ void setProperty(int key, const QVariant &value); /** * Return the value of key as represented on this style, taking into account parent styles. * You should consider using the direct accessors for individual properties instead. * @param key the Property to request. * @returns a QVariant which holds the property value. */ QVariant value(int key) const; /** * Set the properties of an edge. * * @param side defines which edge this is for. * @param style the border style for this side. * @param totalWidth the thickness of the border. Sum of outerwidth, spacing and innerwidth for double borders * @param color the color of the border line(s). */ void setEdge(KoBorder::BorderSide side, KoBorder::BorderStyle style, qreal totalWidth, const QColor &color); /** * Set the properties of a double border. * Note: you need to set the edge first or that would overwrite these values. * * The values will not be set if the border doesn't have a double style * * @param side defines which edge this is for. * @param space the amount of spacing between the outer border and the inner border in case of style being double * @param innerWidth the thickness of the inner border line in case of style being double */ void setEdgeDoubleBorderValues(KoBorder::BorderSide side, qreal innerWidth, qreal space); /** * Check if the border data has any borders. * * @return true if there has been at least one border set. */ bool hasBorders() const; qreal leftBorderWidth() const; qreal rightBorderWidth() const; qreal topBorderWidth() const; qreal bottomBorderWidth() const; qreal leftInnerBorderWidth() const; qreal rightInnerBorderWidth() const; qreal topInnerBorderWidth() const; qreal bottomInnerBorderWidth() const; qreal leftOuterBorderWidth() const; qreal rightOuterBorderWidth() const; qreal topOuterBorderWidth() const; qreal bottomOuterBorderWidth() const; KoBorder::BorderData getEdge(KoBorder::BorderSide side) const; KoBorder::BorderStyle getBorderStyle(KoBorder::BorderSide side) const; Q_SIGNALS: void nameChanged(const QString &newName); protected: KoTableCellStylePrivate * const d_ptr; private: /** * Load the style from the \a KoStyleStack style stack using the * OpenDocument format. */ void loadOdfProperties(KoShapeLoadingContext &context, KoStyleStack &styleStack); qreal propertyDouble(int key) const; QPen propertyPen(int key) const; int propertyInt(int key) const; bool propertyBoolean(int key) const; QColor propertyColor(int key) const; /** * Set the format properties from an Edge structure * * @param side defines which edge this is for. * @param style the border style for this side. * @param edge the Edge that hold the properties values */ void setEdge(KoBorder::BorderSide side, const KoBorder::BorderData &edge, KoBorder::BorderStyle style); Q_DECLARE_PRIVATE(KoTableCellStyle) }; Q_DECLARE_METATYPE(KoTableCellStyle *) #endif diff --git a/plugins/flake/textshape/textlayout/KoTextShapeData.h b/plugins/flake/textshape/textlayout/KoTextShapeData.h index ffdbca958d..35edead9f5 100644 --- a/plugins/flake/textshape/textlayout/KoTextShapeData.h +++ b/plugins/flake/textshape/textlayout/KoTextShapeData.h @@ -1,147 +1,145 @@ /* This file is part of the KDE project * Copyright (C) 2006, 2009-2010 Thomas Zander * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KOTEXTSHAPEDATA_H #define KOTEXTSHAPEDATA_H #include "KoText.h" #include "kritatextlayout_export.h" #include #include class QTextDocument; class KoShapeLoadingContext; class KoShapeSavingContext; class KoTextShapeDataPrivate; class KoDocumentRdfBase; class KoTextLayoutRootArea; /** * The data store that is held by each TextShape instance. * This is a separate object to allow Words proper to use this class' API and * access the internals of the text shape. * * This class holds a QTextDocument pointer and is built so multiple shapes (and thus * multiple instances of this shape data) can share one QTextDocument by providing a * different view on (a different part of) the QTextDocument. */ class KRITATEXTLAYOUT_EXPORT KoTextShapeData : public KoTextShapeDataBase { Q_OBJECT public: /// constructor KoTextShapeData(); ~KoTextShapeData() override; KoShapeUserData* clone() const override; /** * Replace the QTextDocument this shape will render. * @param document the new document. If there was an old document owned, it will be deleted. - * @param transferOwnership if true then the document will be considered the responsibility - * of this data and the doc will be deleted when this shapeData dies. */ void setDocument(QTextDocument *document); /** * return the amount of points into the document (y) this shape will display. */ qreal documentOffset() const; /// mark shape as dirty triggering a re-layout of its text. void setDirty(); /// return if the shape is marked dirty and its text content needs to be relayout bool isDirty() const; /// Set the rootArea that is associated to the textshape void setRootArea(KoTextLayoutRootArea *rootArea); /// the rootArea that is associated to the textshape KoTextLayoutRootArea *rootArea(); void setLeftPadding(qreal padding); qreal leftPadding() const; void setTopPadding(qreal padding); qreal topPadding() const; void setRightPadding(qreal padding); qreal rightPadding() const; void setBottomPadding(qreal padding); qreal bottomPadding() const; void setPadding(qreal padding); /** * Load the TextShape from ODF. * * @see the @a TextShape::loadOdf() method which calls this method. * @see the @a KoTextLoader::loadBody() method which got called by this method * to load the ODF. */ bool loadOdf(const KoXmlElement &element, KoShapeLoadingContext &context, KoDocumentRdfBase *rdfData, KoShape *shape = 0); /** * Load the TextShape from ODF. * Overloaded method provided for your convenience. */ bool loadOdf(const KoXmlElement &element, KoShapeLoadingContext &context) override { return loadOdf(element, context, 0); } /** * Store the TextShape data as ODF. * @see TextShape::saveOdf() */ void saveOdf(KoShapeSavingContext &context, KoDocumentRdfBase *rdfData, int from = 0, int to = -1) const; /** * Store the TextShape data as ODF. * Overloaded method provided for your convenience. */ void saveOdf(KoShapeSavingContext &context, int from = 0, int to = -1) const override { saveOdf(context, 0, from, to); } // reimplemented void loadStyle(const KoXmlElement &element, KoShapeLoadingContext &context) override; // reimplemented void saveStyle(KoGenStyle &style, KoShapeSavingContext &context) const override; /** * Set the page direction. * The page direction will determine behavior on the insertion of new text and those * new paragraphs default direction. */ void setPageDirection(KoText::Direction direction); /** * Return the direction set on the page. * The page direction will determine behavior on the insertion of new text and those * new paragraphs default direction. */ KoText::Direction pageDirection() const; private: KoTextShapeData(KoTextShapeDataPrivate *dd); private: Q_DECLARE_PRIVATE(KoTextShapeData) }; #endif diff --git a/plugins/paintops/libpaintop/kis_dab_cache_base.h b/plugins/paintops/libpaintop/kis_dab_cache_base.h index 3dff16df20..3c0d6bc0ba 100644 --- a/plugins/paintops/libpaintop/kis_dab_cache_base.h +++ b/plugins/paintops/libpaintop/kis_dab_cache_base.h @@ -1,128 +1,123 @@ /* * Copyright (c) 2012 Dmitry Kazakov * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __KIS_DAB_CACHE_BASE_H #define __KIS_DAB_CACHE_BASE_H #include "kritapaintop_export.h" #include "kis_brush.h" #include "KisDabCacheUtils.h" class KisColorSource; class KisPressureSharpnessOption; class KisTextureProperties; class KisPressureMirrorOption; class KisPrecisionOption; struct MirrorProperties; /** * @brief The KisDabCacheBase class provides caching for dabs into the brush paintop * * This class adds caching of the dabs to the paintop system of Krita. * Such cache makes the execution of the benchmarks up to 2 times faster. * Subjectively, the real painting becomes much faster, especially with * huge brushes. Artists report up to 20% speed gain while painting. * * Of course, such caching makes the painting a bit less precise: we need * to tolerate subpixel differences to allow the cache to work. Sometimes * small difference in the size of a dab can also be acceptable. That is * why I introduced levels of precision. They are graded from 1 to 5: from * the fastest and less precise to the slowest, but with the best quality. * You can see the slider in the paintop settings dialog. The ToolTip text * explains which features of the brush are sacrificed on each precision * level. * * The texturing and mirroring problems are solved. */ class PAINTOP_EXPORT KisDabCacheBase { public: KisDabCacheBase(); ~KisDabCacheBase(); void setMirrorPostprocessing(KisPressureMirrorOption *option); void setPrecisionOption(KisPrecisionOption *option); /** * Disables handling of the subPixelX and subPixelY values, this * is needed at least for the Color Smudge paint op, which reads * aligned areas from image, so additional offsets generated by * the subpixel precision should be avoided */ void disableSubpixelPrecision(); /** * Return true if the dab needs postprocessing by special options * like 'texture' or 'sharpness' */ bool needSeparateOriginal(KisTextureProperties *textureOption, KisPressureSharpnessOption *sharpnessOption) const; protected: /** * Fetches all the necessary information for dab generation and * tells if the caller must should reuse the preciously returned dab. * * Please note that KisDabCacheBase has an internal state, that keeps the * parameters of the previously generated (on a cache-miss) dab. This function * automatically updates this state when 'shouldUseCache == false'. Therefore, the * caller *must* generate the dab if and only if when 'shouldUseCache == false'. * Otherwise the internal state will become inconsistent. * * @param hasDabInCache shows if the caller has something in its cache * @param resources rendering resources available for this dab - * @param color current painting color - * @param cursorPoint cursor point at which the dab should be painted - * @param shape dab shape requested by the caller. It will be modified before - * generation to accommodate the mirroring and rotation options. - * @param info painting info associated with the dab - * @param softnessFactor softness factor + * @param request the request information * @param di (OUT) calculated dab generation information * @param shouldUseCache (OUT) shows whether the caller *must* use cache or not */ void fetchDabGenerationInfo(bool hasDabInCache, KisDabCacheUtils::DabRenderingResources *resources, const KisDabCacheUtils::DabRequestInfo &request, /* out */ KisDabCacheUtils::DabGenerationInfo *di, bool *shouldUseCache); private: struct SavedDabParameters; struct DabPosition; private: inline SavedDabParameters getDabParameters(KisBrushSP brush, const KoColor& color, KisDabShape const&, const KisPaintInformation& info, double subPixelX, double subPixelY, qreal softnessFactor, MirrorProperties mirrorProperties); inline KisDabCacheBase::DabPosition calculateDabRect(KisBrushSP brush, const QPointF &cursorPoint, KisDabShape, const KisPaintInformation& info, const MirrorProperties &mirrorProperties, KisPressureSharpnessOption *sharpnessOption); private: struct Private; Private * const m_d; }; #endif /* __KIS_DAB_CACHE_BASE_H */