File indexing completed on 2024-05-19 04:26:16

0001 /*
0002  *  SPDX-FileCopyrightText: 2002 Patrick Julien <freak@codepimps.org>
0003  *  SPDX-FileCopyrightText: 2007 Boudewijn Rempt <boud@valdyas.org>
0004  *
0005  *  SPDX-License-Identifier: GPL-2.0-or-later
0006  */
0007 #ifndef KIS_IMAGE_H_
0008 #define KIS_IMAGE_H_
0009 
0010 #include <QObject>
0011 #include <QString>
0012 #include <QPainter>
0013 #include <QRect>
0014 #include <QBitArray>
0015 
0016 #include <KoColorConversionTransformation.h>
0017 
0018 #include "kis_types.h"
0019 #include "kis_shared.h"
0020 #include "kis_node_graph_listener.h"
0021 #include "kis_node_facade.h"
0022 #include "kis_image_interfaces.h"
0023 #include "kis_strokes_queue_undo_result.h"
0024 #include "KisLodPreferences.h"
0025 #include "KisWraparoundAxis.h"
0026 
0027 #include <kritaimage_export.h>
0028 
0029 class KoColorSpace;
0030 class KoColor;
0031 
0032 class KisCompositeProgressProxy;
0033 class KisUndoStore;
0034 class KisUndoAdapter;
0035 class KisImageSignalRouter;
0036 class KisPostExecutionUndoAdapter;
0037 class KisFilterStrategy;
0038 class KoColorProfile;
0039 class KisLayerComposition;
0040 class KisSpontaneousJob;
0041 class KisImageAnimationInterface;
0042 class KUndo2MagicString;
0043 class KisProofingConfiguration;
0044 class KisPaintDevice;
0045 class KisImageGlobalSelectionManagementInterface;
0046 
0047 namespace KisMetaData
0048 {
0049 class MergeStrategy;
0050 }
0051 
0052 /**
0053  * This is the image class, it contains a tree of KisLayer stack and
0054  * meta information about the image. And it also provides some
0055  * functions to manipulate the whole image.
0056  */
0057 class KRITAIMAGE_EXPORT KisImage : public QObject,
0058         public KisStrokesFacade,
0059         public KisStrokeUndoFacade,
0060         public KisUpdatesFacade,
0061         public KisProjectionUpdateListener,
0062         public KisNodeFacade,
0063         public KisNodeGraphListener,
0064         public KisShared
0065 {
0066 
0067     Q_OBJECT
0068 
0069 public:    
0070     /// @p colorSpace can be null. In that case, it will be initialised to a default color space.
0071     KisImage(KisUndoStore *undoStore, qint32 width, qint32 height, const KoColorSpace *colorSpace, const QString& name);
0072     ~KisImage() override;
0073 
0074     static KisImageSP fromQImage(const QImage &image, KisUndoStore *undoStore);
0075 
0076 public: // KisNodeGraphListener implementation
0077 
0078     void aboutToAddANode(KisNode *parent, int index) override;
0079     void nodeHasBeenAdded(KisNode *parent, int index) override;
0080     void aboutToRemoveANode(KisNode *parent, int index) override;
0081     void nodeChanged(KisNode * node) override;
0082     void nodeCollapsedChanged(KisNode *node) override;
0083     void invalidateAllFrames() override;
0084     void notifySelectionChanged() override;
0085     void requestProjectionUpdate(KisNode *node, const QVector<QRect> &rects, bool resetAnimationCache) override;
0086     void invalidateFrames(const KisTimeSpan &range, const QRect &rect) override;
0087     void requestTimeSwitch(int time) override;
0088     KisNode* graphOverlayNode() const override;
0089 
0090     void keyframeChannelHasBeenAdded(KisNode *node, KisKeyframeChannel *channel) override;
0091     void keyframeChannelAboutToBeRemoved(KisNode *node, KisKeyframeChannel *channel) override;
0092 
0093 public: // KisProjectionUpdateListener implementation
0094     void notifyProjectionUpdated(const QRect &rc) override;
0095 
0096 public:
0097 
0098     /**
0099      * Set the number of threads used by the image's working threads
0100      */
0101     void setWorkingThreadsLimit(int value);
0102 
0103     /**
0104      * Return the number of threads available to the image's working threads
0105      */
0106     int workingThreadsLimit() const;
0107 
0108     /**
0109      * Makes a copy of the image with all the layers. If possible, shallow
0110      * copies of the layers are made.
0111      *
0112      * \p exactCopy shows if the copied image should look *exactly* the same as
0113      * the other one (according to it's .kra xml representation). It means that
0114      * the layers will have the same UUID keys and, therefore, you are not
0115      * expected to use the copied image anywhere except for saving. Don't use
0116      * this option if you plan to work with the copied image later.
0117      */
0118     KisImage *clone(bool exactCopy = false);
0119 
0120     void copyFromImage(const KisImage &rhs);
0121 
0122 private:
0123 
0124     // must specify exactly one from CONSTRUCT or REPLACE.
0125     enum CopyPolicy {
0126         CONSTRUCT = 1, ///< we are copy-constructing a new KisImage
0127         REPLACE = 2, ///< we are replacing the current KisImage with another
0128         EXACT_COPY = 4, /// we need an exact copy of the original image
0129     };
0130 
0131     void copyFromImageImpl(const KisImage &rhs, int policy);
0132 
0133 public:
0134 
0135     /**
0136      * Render the projection onto a QImage.
0137      */
0138     QImage convertToQImage(qint32 x1,
0139                            qint32 y1,
0140                            qint32 width,
0141                            qint32 height,
0142                            const KoColorProfile * profile);
0143 
0144     /**
0145      * Render the projection onto a QImage.
0146      * (this is an overloaded function)
0147      */
0148     QImage convertToQImage(QRect imageRect,
0149                            const KoColorProfile * profile);
0150 
0151 
0152     /**
0153      * Render a thumbnail of the projection onto a QImage.
0154      */
0155     QImage convertToQImage(const QSize& scaledImageSize, const KoColorProfile *profile);
0156 
0157     /**
0158      * [low-level] Lock the image without waiting for all the internal job queues are processed
0159      *
0160      * WARNING: Don't use it unless you really know what you are doing! Use barrierLock() instead!
0161      *
0162      * Waits for all the **currently running** internal jobs to complete and locks the image
0163      * for writing. Please note that this function does **not** wait for all the internal
0164      * queues to process, so there might be some non-finished actions pending. It means that
0165      * you just postpone these actions until you unlock() the image back. Until then, then image
0166      * might easily be frozen in some inconsistent state.
0167      *
0168      * The only sane usage for this function is to lock the image for **emergency**
0169      * processing, when some internal action or scheduler got hung up, and you just want
0170      * to fetch some data from the image without races.
0171      *
0172      * In all other cases, please use barrierLock() instead!
0173      */
0174     void immediateLockForReadOnly();
0175 
0176     /**
0177      * Unlocks the image and starts/resumes all the pending internal jobs. If the image
0178      * has been locked for a non-readOnly access, then all the internal caches of the image
0179      * (e.g. lod-planes) are reset and regeneration jobs are scheduled.
0180      */
0181     void unlock();
0182 
0183     /**
0184      * @return return true if the image is in a locked state, i.e. all the internal
0185      *         jobs are blocked from execution by calling either lock() or barrierLock().
0186      *
0187      *         When the image is locked, the user can do some modifications to the image
0188      *         contents safely without a perspective having race conditions with internal
0189      *         image jobs.
0190      */
0191     bool locked() const;
0192 
0193     /**
0194      * Sets the mask (it must be a part of the node hierarchy already) to be painted on
0195      * the top of all layers. This method does all the locking and syncing for you. It
0196      * is executed asynchronously.
0197      */
0198     void setOverlaySelectionMask(KisSelectionMaskSP mask);
0199 
0200     /**
0201      * \see setOverlaySelectionMask
0202      */
0203     KisSelectionMaskSP overlaySelectionMask() const;
0204 
0205     /**
0206      * \see setOverlaySelectionMask
0207      */
0208     bool hasOverlaySelectionMask() const;
0209 
0210     /**
0211      * @return the global selection object or 0 if there is none. The
0212      * global selection is always read-write.
0213      */
0214     KisSelectionSP globalSelection() const;
0215 
0216     /**
0217      * Retrieve the next automatic layername (XXX: fix to add option to return Mask X)
0218      */
0219     QString nextLayerName(const QString &baseName = "") const;
0220 
0221     /**
0222      * @brief start asynchronous operation on resizing the image
0223      *
0224      * The method will resize the image to fit the new size without
0225      * dropping any pixel data. The GUI will get correct
0226      * notification with old and new sizes, so it adjust canvas origin
0227      * accordingly and avoid jumping of the canvas on screen
0228      *
0229      * @param newRect the rectangle of the image which will be visible
0230      *        after operation is completed
0231      *
0232      * Please note that the actual operation starts asynchronously in
0233      * a background, so you cannot expect the image having new size
0234      * right after this call.
0235      */
0236     void resizeImage(const QRect& newRect);
0237 
0238     /**
0239      * @brief start asynchronous operation on cropping the image
0240      *
0241      * The method will **drop** all the image data outside \p newRect
0242      * and resize the image to fit the new size. The GUI will get correct
0243      * notification with old and new sizes, so it adjust canvas origin
0244      * accordingly and avoid jumping of the canvas on screen
0245      *
0246      * @param newRect the rectangle of the image which will be cut-out
0247      *
0248      * Please note that the actual operation starts asynchronously in
0249      * a background, so you cannot expect the image having new size
0250      * right after this call.
0251      */
0252     void cropImage(const QRect& newRect);
0253 
0254     /**
0255      * @brief purge all pixels that have default pixel to free up memory
0256      * @param isCancellable if true, the scheduler is allower to stop and
0257      * cancel purging operation as soon as the user starts any action.
0258      * If \p isCancellable is false, then the user will not be allowed to do
0259      * anything until purging operation is completed.
0260      */
0261     void purgeUnusedData(bool isCancellable);
0262 
0263     /**
0264      * @brief start asynchronous operation on cropping a subtree of nodes starting at \p node
0265      *
0266      * The method will **drop** all the layer data outside \p newRect. Neither
0267      * image nor a layer will be moved anywhere
0268      *
0269      * @param node node to crop
0270      * @param newRect the rectangle of the layer which will be cut-out
0271      * @param activeFrameOnly whether to crop every animation frame or just the current one.
0272      *
0273      * Please note that the actual operation starts asynchronously in
0274      * a background, so you cannot expect the image having new size
0275      * right after this call.
0276      */
0277     void cropNode(KisNodeSP node, const QRect& newRect, const bool activeFrameOnly = false);
0278     void cropNodes(KisNodeList nodes, const QRect& newRect, const bool activeFrameOnly = false);
0279 
0280     /**
0281      * @brief start asynchronous operation on scaling the image
0282      * @param size new image size in pixels
0283      * @param xres new image x-resolution pixels-per-pt
0284      * @param yres new image y-resolution pixels-per-pt
0285      * @param filterStrategy filtering strategy
0286      *
0287      * Please note that the actual operation starts asynchronously in
0288      * a background, so you cannot expect the image having new size
0289      * right after this call.
0290      */
0291     void scaleImage(const QSize &size, qreal xres, qreal yres, KisFilterStrategy *filterStrategy);
0292 
0293     /**
0294      * @brief start asynchronous operation on scaling a subtree of nodes starting at \p node
0295      * @param node node to scale
0296      * @param center the center of the scaling
0297      * @param scaleX x-scale coefficient to be applied to the node
0298      * @param scaleY y-scale coefficient to be applied to the node
0299      * @param filterStrategy filtering strategy
0300      * @param selection the selection we based on
0301      *
0302      * Please note that the actual operation starts asynchronously in
0303      * a background, so you cannot expect the image having new size
0304      * right after this call.
0305      */
0306     void scaleNode(KisNodeSP node, const QPointF &center, qreal scaleX, qreal scaleY, KisFilterStrategy *filterStrategy, KisSelectionSP selection);
0307     void scaleNodes(KisNodeList nodes, const QPointF &center, qreal scaleX, qreal scaleY, KisFilterStrategy *filterStrategy, KisSelectionSP selection);
0308 
0309     /**
0310      * @brief start asynchronous operation on rotating the image
0311      *
0312      * The image is resized to fit the rotated rectangle
0313      *
0314      * @param radians rotation angle in radians
0315      *
0316      * Please note that the actual operation starts asynchronously in
0317      * a background, so you cannot expect the operation being completed
0318      * right after the call
0319      */
0320     void rotateImage(double radians);
0321 
0322     /**
0323      * @brief start asynchronous operation on rotating a subtree of nodes starting at \p node
0324      *
0325      * The image is not resized!
0326      *
0327      * @param node the root of the subtree to rotate
0328      * @param radians rotation angle in radians
0329      * @param selection the selection we based on
0330      *
0331      * Please note that the actual operation starts asynchronously in
0332      * a background, so you cannot expect the operation being completed
0333      * right after the call
0334      */
0335     void rotateNode(KisNodeSP node, double radians, KisSelectionSP selection);
0336     void rotateNodes(KisNodeList nodes, double radians, KisSelectionSP selection);
0337 
0338     /**
0339      * @brief start asynchronous operation on shearing the image
0340      *
0341      * The image is resized to fit the sheared polygon
0342      *
0343      * @p angleX, @p angleY are given in degrees.
0344      *
0345      * Please note that the actual operation starts asynchronously in
0346      * a background, so you cannot expect the operation being completed
0347      * right after the call
0348      */
0349     void shear(double angleX, double angleY);
0350 
0351     /**
0352      * @brief start asynchronous operation on shearing a subtree of nodes starting at \p node
0353      *
0354      * The image is not resized!
0355      *
0356      * @param node the root of the subtree to rotate
0357      * @param angleX x-shear given in degrees.
0358      * @param angleY y-shear given in degrees.
0359      * @param selection the selection we based on
0360      *
0361      * Please note that the actual operation starts asynchronously in
0362      * a background, so you cannot expect the operation being completed
0363      * right after the call
0364      */
0365     void shearNode(KisNodeSP node, double angleX, double angleY, KisSelectionSP selection);
0366     void shearNodes(KisNodeList nodes, double angleX, double angleY, KisSelectionSP selection);
0367 
0368     /**
0369      * Convert image projection to \p dstColorSpace, keeping all the layers intouched.
0370      */
0371     void convertImageProjectionColorSpace(const KoColorSpace *dstColorSpace);
0372 
0373     /**
0374      * Convert the image and all its layers to the dstColorSpace
0375      */
0376     void convertImageColorSpace(const KoColorSpace *dstColorSpace,
0377                                 KoColorConversionTransformation::Intent renderingIntent,
0378                                 KoColorConversionTransformation::ConversionFlags conversionFlags);
0379 
0380     /**
0381      * Convert layer and all its child layers to dstColorSpace
0382      */
0383     void convertLayerColorSpace(KisNodeSP node,
0384                                 const KoColorSpace *dstColorSpace,
0385                                 KoColorConversionTransformation::Intent renderingIntent,
0386                                 KoColorConversionTransformation::ConversionFlags conversionFlags);
0387 
0388 
0389     // Get the profile associated with this image
0390     const KoColorProfile *  profile() const;
0391 
0392     /**
0393      * Set the profile of the layer and all its children to the new profile.
0394      * It doesn't do any pixel conversion.
0395      *
0396      * This is essential if you have loaded an image that didn't
0397      * have an embedded profile to which you want to attach the right profile.
0398      *
0399      * @returns false if the profile could not be assigned
0400      */
0401     bool assignLayerProfile(KisNodeSP node, const KoColorProfile *profile);
0402 
0403     /**
0404      * Set the profile of the image to the new profile and do the same for
0405      * all layers that have the same colorspace and profile of the image.
0406      * It doesn't do any pixel conversion.
0407      *
0408      * This is essential if you have loaded an image that didn't
0409      * have an embedded profile to which you want to attach the right profile.
0410      *
0411      * @returns false if the profile could not be assigned
0412      */
0413     bool assignImageProfile(const KoColorProfile *profile, bool blockAllUpdates = false);
0414 
0415     /**
0416      * Returns the current undo adapter. You can add new commands to the
0417      * undo stack using the adapter. This adapter is used for a backward
0418      * compatibility for old commands created before strokes. It blocks
0419      * all the processing at the scheduler, waits until it's finished
0420      * and executes commands exclusively.
0421      */
0422     KisUndoAdapter* undoAdapter() const;
0423 
0424     /**
0425      * This adapter is used by the strokes system. The commands are added
0426      * to it *after* redo() is done (in the scheduler context). They are
0427      * wrapped into a special command and added to the undo stack. redo()
0428      * in not called.
0429      */
0430     KisPostExecutionUndoAdapter* postExecutionUndoAdapter() const override;
0431 
0432     /**
0433      * Return the lastly executed LoD0 command. It is effectively the same
0434      * as to call undoAdapter()->presentCommand();
0435      */
0436     const KUndo2Command* lastExecutedCommand() const override;
0437 
0438     /**
0439      * Replace current undo store with the new one. The old store
0440      * will be deleted.
0441      * This method is used by KisDocument for dropping all the commands
0442      * during file loading.
0443      */
0444     void setUndoStore(KisUndoStore *undoStore);
0445 
0446     /**
0447      * Return current undo store of the image
0448      */
0449     KisUndoStore* undoStore();
0450 
0451     /**
0452      * Tell the image it's modified without creation of an undo command.
0453      * It may happen when e.g. layer visibility has changed.
0454      *
0455      * This function emits both, sigImageModified() and
0456      * sigImageModifiedWithoutUndo()
0457      *
0458      * For normal modifications with undo information the signal
0459      * emission is triggered by the undo stack
0460      */
0461     void setModifiedWithoutUndo();
0462 
0463     /**
0464      * The default colorspace of this image: new layers will have this
0465      * colorspace and the projection will have this colorspace.
0466      */
0467     const KoColorSpace * colorSpace() const;
0468 
0469     /**
0470      * X resolution in pixels per pt
0471      */
0472     double xRes() const;
0473 
0474     /**
0475      * Y resolution in pixels per pt
0476      */
0477     double yRes() const;
0478 
0479     /**
0480      * Set the resolution in pixels per pt.
0481      */
0482     void setResolution(double xres, double yres);
0483 
0484     /**
0485      * Convert a document coordinate to a pixel coordinate.
0486      *
0487      * @param documentCoord PostScript Pt coordinate to convert.
0488      */
0489     QPointF documentToPixel(const QPointF &documentCoord) const;
0490 
0491     /**
0492      * Convert a document coordinate to an integer pixel coordinate rounded down.
0493      *
0494      * @param documentCoord PostScript Pt coordinate to convert.
0495      */
0496     QPoint documentToImagePixelFloored(const QPointF &documentCoord) const;
0497 
0498     /**
0499      * Convert a document rectangle to a pixel rectangle.
0500      *
0501      * @param documentRect PostScript Pt rectangle to convert.
0502      */
0503     QRectF documentToPixel(const QRectF &documentRect) const;
0504 
0505     /**
0506      * Convert a pixel coordinate to a document coordinate.
0507      *
0508      * @param pixelCoord pixel coordinate to convert.
0509      */
0510     QPointF pixelToDocument(const QPointF &pixelCoord) const;
0511 
0512     /**
0513      * Convert an integer pixel coordinate to a document coordinate.
0514      * The document coordinate is at the centre of the pixel.
0515      *
0516      * @param pixelCoord pixel coordinate to convert.
0517      */
0518     QPointF pixelToDocument(const QPoint &pixelCoord) const;
0519 
0520     /**
0521      * Convert a document rectangle to an integer pixel rectangle.
0522      *
0523      * @param pixelCoord pixel coordinate to convert.
0524      */
0525     QRectF pixelToDocument(const QRectF &pixelCoord) const;
0526 
0527     /**
0528      * Return the width of the image
0529      */
0530     qint32 width() const;
0531 
0532     /**
0533      * Return the height of the image
0534      */
0535     qint32 height() const;
0536 
0537     /**
0538      * Return the size of the image
0539      */
0540     QSize size() const {
0541         return QSize(width(), height());
0542     }
0543 
0544     /**
0545      * @return the root node of the image node graph
0546      */
0547     KisGroupLayerSP rootLayer() const;
0548 
0549     /**
0550      * Return the projection; that is, the complete, composited
0551      * representation of this image.
0552      */
0553     KisPaintDeviceSP projection() const;
0554 
0555     /**
0556      * Return the number of layers (not other nodes) that are in this
0557      * image.
0558      */
0559     qint32 nlayers() const;
0560 
0561     /**
0562      * Return the number of layers (not other node types) that are in
0563      * this image and that are hidden.
0564      */
0565     qint32 nHiddenLayers() const;
0566 
0567     /*
0568      * Return the number of layers (not other node types) that are
0569      * descendants of the rootLayer in this image.
0570      */
0571     qint32 nChildLayers() const;
0572 
0573     /**
0574      * Merge all visible layers and discard hidden ones.
0575      */
0576     void flatten(KisNodeSP activeNode);
0577 
0578     /**
0579      * Merge the specified layer with the layer
0580      * below this layer, remove the specified layer.
0581      */
0582     void mergeDown(KisLayerSP l, const KisMetaData::MergeStrategy* strategy);
0583 
0584     /**
0585      * flatten the layer: that is, the projection becomes the layer
0586      * and all subnodes are removed. If this is not a paint layer, it will morph
0587      * into a paint layer.
0588      */
0589     void flattenLayer(KisLayerSP layer);
0590 
0591     /**
0592      * Merges layers in \p mergedLayers and creates a new layer above
0593      * \p putAfter
0594      */
0595     void mergeMultipleLayers(QList<KisNodeSP> mergedLayers, KisNodeSP putAfter);
0596 
0597     /// @return the exact bounds of the image in pixel coordinates.
0598     QRect bounds() const override;
0599 
0600     /**
0601      * Returns the actual bounds of the image, taking LevelOfDetail
0602      * into account.  This value is used as a bounds() value of
0603      * KisDefaultBounds object.
0604      */
0605     QRect effectiveLodBounds() const;
0606 
0607     /// use if the layers have changed _completely_ (eg. when flattening)
0608     void notifyLayersChanged();
0609 
0610     /**
0611      * Sets the default color of the root layer projection. All the layers
0612      * will be merged on top of this very color
0613      */
0614     void setDefaultProjectionColor(const KoColor &color);
0615 
0616     /**
0617      * \see setDefaultProjectionColor()
0618      */
0619     KoColor defaultProjectionColor() const;
0620 
0621     void setRootLayer(KisGroupLayerSP rootLayer);
0622 
0623     /**
0624      * Add an annotation for this image. This can be anything: Gamma, EXIF, etc.
0625      * Note that the "icc" annotation is reserved for the color strategies.
0626      * If the annotation already exists, overwrite it with this one.
0627      */
0628     void addAnnotation(KisAnnotationSP annotation);
0629 
0630     /** get the annotation with the given type, can return 0 */
0631     KisAnnotationSP annotation(const QString& type);
0632 
0633     /** delete the annotation, if the image contains it */
0634     void removeAnnotation(const QString& type);
0635 
0636     /**
0637      * Start of an iteration over the annotations of this image (including the ICC Profile)
0638      */
0639     vKisAnnotationSP_it beginAnnotations();
0640 
0641     /** end of an iteration over the annotations of this image */
0642     vKisAnnotationSP_it endAnnotations();
0643 
0644     /**
0645      * Called before the image is deleted and sends the sigAboutToBeDeleted signal
0646      */
0647     void notifyAboutToBeDeleted();
0648 
0649     KisImageSignalRouter* signalRouter();
0650 
0651     /**
0652      * Returns whether we can reselect current global selection
0653      *
0654      * \see reselectGlobalSelection()
0655      */
0656     bool canReselectGlobalSelection();
0657 
0658     /**
0659      * Returns the layer compositions for the image
0660      */
0661     QList<KisLayerCompositionSP> compositions();
0662 
0663     /**
0664      * Adds a new layer composition, will be saved with the image
0665      */
0666     void addComposition(KisLayerCompositionSP composition);
0667 
0668     /**
0669      * Remove the layer composition
0670      */
0671     void removeComposition(KisLayerCompositionSP composition);
0672 
0673     /**
0674      * Move a composition up in the composition list
0675      */
0676     void moveCompositionUp(KisLayerCompositionSP composition);
0677 
0678     /**
0679      * Move a composition down in the composition list
0680      */
0681     void moveCompositionDown(KisLayerCompositionSP composition);
0682 
0683     /**
0684      * Permit or deny the wrap-around mode for all the paint devices
0685      * of the image. Note that permitting the wraparound mode will not
0686      * necessarily activate it right now. To be activated the wrap
0687      * around mode should be 1) permitted; 2) supported by the
0688      * currently running stroke.
0689      */
0690     void setWrapAroundModePermitted(bool value);
0691 
0692     /**
0693      * \return whether the wrap-around mode is permitted for this
0694      *         image. If the wrap around mode is permitted and the
0695      *         currently running stroke supports it, the mode will be
0696      *         activated for all paint devices of the image.
0697      *
0698      * \see setWrapAroundMode
0699      */
0700     bool wrapAroundModePermitted() const;
0701 
0702     /**
0703      * Set which axis to use for wraparound mode
0704      */
0705     void setWrapAroundModeAxis(WrapAroundAxis value);
0706     /**
0707      * \return the axis being used for wraparound mode
0708      *
0709      * \see setWrapAroundModeAxis
0710      */
0711     WrapAroundAxis wrapAroundModeAxis() const;
0712 
0713 
0714     /**
0715      * \return whether the wraparound mode is activated for all the
0716      *         devices of the image. The mode is activated when both
0717      *         factors are true: the user permitted it and the stroke
0718      *         supports it
0719      */
0720     bool wrapAroundModeActive() const;
0721 
0722     /**
0723      * \return current level of detail which is used when processing the image.
0724      * Current working zoom = 2 ^ (- currentLevelOfDetail()). Default value is
0725      * null, which means we work on the original image.
0726      */
0727     int currentLevelOfDetail() const;
0728 
0729     /**
0730      * Relative position of the mirror axis center
0731      *     0,0 - topleft corner of the image
0732      *     1,1 - bottomright corner of the image
0733      */
0734     QPointF mirrorAxesCenter() const;
0735 
0736     /**
0737      * Sets the relative position of the axes center
0738      * \see mirrorAxesCenter() for details
0739      */
0740     void setMirrorAxesCenter(const QPointF &value) const;
0741 
0742     /**
0743      * Configure the image to allow masks on the root not (as reported by
0744      * root()->allowAsChild()). By default it is not allowed (because it
0745      * looks weird from GUI point of view)
0746      */
0747     void setAllowMasksOnRootNode(bool value);
0748 
0749     /**
0750      * \see setAllowMasksOnRootNode()
0751      */
0752     bool allowMasksOnRootNode() const;
0753 
0754 public Q_SLOTS:
0755 
0756     /**
0757      * Explicitly start regeneration of LoD planes of all the devices
0758      * in the image. This call should be performed when the user is idle,
0759      * just to make the quality of image updates better.
0760      */
0761     void explicitRegenerateLevelOfDetail();
0762 
0763 public:
0764 
0765     /**
0766      * Set preferences for the level-of-detail functionality.
0767      * Due to multithreading considerations they may be applied
0768      * not immediately, but some time later.
0769      */
0770     void setLodPreferences(const KisLodPreferences &value);
0771 
0772     /**
0773      * Return current lod-preferences used by the strokes queue. They
0774      * may differ from the preferences that has been assigned before
0775      * due to multi-stage application process (due to multithreading
0776      * considerations)
0777      */
0778     KisLodPreferences lodPreferences() const;
0779 
0780     KisImageAnimationInterface *animationInterface() const;
0781 
0782     /**
0783      * @brief setProofingConfiguration, this sets the image's proofing configuration, and signals
0784      * the proofingConfiguration has changed.
0785      * @param proofingConfig - the kis proofing config that will be used instead.
0786      */
0787     void setProofingConfiguration(KisProofingConfigurationSP proofingConfig);
0788     /**
0789      * @brief proofingConfiguration
0790      * @return the proofing configuration of the image.
0791      */
0792     KisProofingConfigurationSP proofingConfiguration() const;
0793 
0794 public Q_SLOTS:
0795     bool startIsolatedMode(KisNodeSP node, bool isolateLayer, bool isolateGroup);
0796     void stopIsolatedMode();
0797 
0798 public:
0799     KisNodeSP isolationRootNode() const;
0800     bool isIsolatingLayer() const;
0801     bool isIsolatingGroup() const;
0802 
0803 Q_SIGNALS:
0804 
0805     /**
0806      *  Emitted whenever an action has caused the image to be
0807      *  recomposited. Parameter is the rect that has been recomposited.
0808      */
0809     void sigImageUpdated(const QRect &);
0810 
0811     /**
0812        Emitted whenever the image has been modified, so that it
0813        doesn't match with the version saved on disk.
0814      */
0815     void sigImageModified();
0816 
0817     /**
0818        Emitted whenever the image has been modified without creation
0819        of an undo command
0820      */
0821     void sigImageModifiedWithoutUndo();
0822 
0823     /**
0824      * The signal is emitted when the size of the image is changed.
0825      * \p oldStillPoint and \p newStillPoint give the receiver the
0826      * hint about how the new and old rect of the image correspond to
0827      * each other. They specify the point of the image around which
0828      * the conversion was done. This point will stay still on the
0829      * user's screen. That is the \p newStillPoint of the new image
0830      * will be painted at the same screen position, where \p
0831      * oldStillPoint of the old image was painted.
0832      *
0833      * \param oldStillPoint is a still point represented in *old*
0834      *                      image coordinates
0835      *
0836      * \param newStillPoint is a still point represented in *new*
0837      *                      image coordinates
0838      */
0839     void sigSizeChanged(const QPointF &oldStillPoint, const QPointF &newStillPoint);
0840 
0841     void sigProfileChanged(const KoColorProfile *  profile);
0842     void sigColorSpaceChanged(const KoColorSpace*  cs);
0843     void sigResolutionChanged(double xRes, double yRes);
0844     void sigRequestNodeReselection(KisNodeSP activeNode, const KisNodeList &selectedNodes);
0845 
0846     /**
0847      * Inform the model that a node was changed
0848      */
0849     void sigNodeChanged(KisNodeSP node);
0850 
0851     /**
0852      * Inform that the image is going to be deleted
0853      */
0854     void sigAboutToBeDeleted();
0855 
0856     /**
0857      * The signal is emitted right after a node has been connected
0858      * to the graph of the nodes.
0859      *
0860      * WARNING: you must not request any graph-related information
0861      * about the node being run in a not-scheduler thread. If you need
0862      * information about the parent/siblings of the node connect
0863      * with Qt::DirectConnection, get needed information and then
0864      * emit another Qt::AutoConnection signal to pass this information
0865      * to your thread. See details of the implementation
0866      * in KisDummiesfacadeBase.
0867      */
0868     void sigNodeAddedAsync(KisNodeSP node);
0869 
0870     /**
0871      * This signal is emitted right before a node is going to removed
0872      * from the graph of the nodes.
0873      *
0874      * WARNING: you must not request any graph-related information
0875      * about the node being run in a not-scheduler thread.
0876      *
0877      * \see comment in sigNodeAddedAsync()
0878      */
0879     void sigRemoveNodeAsync(KisNodeSP node);
0880 
0881     /**
0882      * Emitted when the root node of the image has changed.
0883      * It happens, e.g. when we flatten the image. When
0884      * this happens the receiver should reload information
0885      * about the image
0886      */
0887     void sigLayersChangedAsync();
0888 
0889     /**
0890      * Emitted when the UI has requested the undo of the last stroke's
0891      * operation. The point is, we cannot deal with the internals of
0892      * the stroke without its creator knowing about it (which most
0893      * probably cause a crash), so we just forward this request from
0894      * the UI to the creator of the stroke.
0895      *
0896      * If your tool supports undoing part of its work, just listen to
0897      * this signal and undo when it comes
0898      */
0899     void sigUndoDuringStrokeRequested();
0900 
0901     /**
0902      * Emitted when the UI has requested the redo of the last undo
0903      * operation.
0904      *
0905      * If your tool supports undoing/redoing part of its work, just listen
0906      * to this signal and undo when it comes
0907      */
0908     void sigRedoDuringStrokeRequested();
0909 
0910     /**
0911      * Emitted when the UI has requested the cancellation of
0912      * the stroke. The point is, we cannot cancel the stroke
0913      * without its creator knowing about it (which most probably
0914      * cause a crash), so we just forward this request from the UI
0915      * to the creator of the stroke.
0916      *
0917      * If your tool supports cancelling of its work in the middle
0918      * of operation, just listen to this signal and cancel
0919      * the stroke when it comes
0920      */
0921     void sigStrokeCancellationRequested();
0922 
0923     /**
0924      * Emitted when the image decides that the stroke should better
0925      * be ended. The point is, we cannot just end the stroke
0926      * without its creator knowing about it (which most probably
0927      * cause a crash), so we just forward this request from the UI
0928      * to the creator of the stroke.
0929      *
0930      * If your tool supports long  strokes that may involve multiple
0931      * mouse actions in one stroke, just listen to this signal and
0932      * end the stroke when it comes.
0933      */
0934     void sigStrokeEndRequested();
0935 
0936     /**
0937      * Same as sigStrokeEndRequested() but is not emitted when the active node
0938      * is changed.
0939      */
0940     void sigStrokeEndRequestedActiveNodeFiltered();
0941 
0942     /**
0943      * Emitted when the isolated mode status has changed.
0944      *
0945      * Can be used by the receivers to catch a fact of forcefully
0946      * stopping the isolated mode by the image when some complex
0947      * action was requested
0948      */
0949     void sigIsolatedModeChanged();
0950 
0951     /**
0952      * Emitted when one or more nodes changed the collapsed state
0953      *
0954      */
0955     void sigNodeCollapsedChanged();
0956 
0957     /**
0958      * Emitted when the proofing configuration of the image is being changed.
0959      *
0960      */
0961     void sigProofingConfigChanged();
0962 
0963     /**
0964      * Internal signal for asynchronously requesting isolated mode to stop. Don't use it
0965      * outside KisImage, use sigIsolatedModeChanged() instead.
0966      */
0967     void sigInternalStopIsolatedModeRequested();
0968 
0969 public Q_SLOTS:
0970     KisCompositeProgressProxy* compositeProgressProxy();
0971 
0972     bool isIdle(bool allowLocked = false);
0973 
0974     /**
0975      * @brief Wait until all the queued background jobs are completed and lock the image.
0976      *
0977      * KisImage object has a local scheduler that executes long-running image
0978      * rendering/modifying jobs (we call them "strokes") in a background. Basically,
0979      * one should either access the image from the scope of such jobs (strokes) or
0980      * just lock the image before using.
0981      *
0982      * Calling barrierLock() will wait until all the queued operations are finished
0983      * and lock the image, so you can start accessing it in a safe way.
0984      *
0985      * @p readOnly tells the image if the caller is going to modify the image during
0986      *             holding the lock. Locking with non-readOnly  access will reset all
0987      *             the internal caches of the image (lod-planes) when the lock status
0988      *             will be lifted.
0989      */
0990     void barrierLock(bool readOnly = false);
0991 
0992     /**
0993      * @brief Tries to lock the image without waiting for the jobs to finish
0994      *
0995      * Same as barrierLock(), but doesn't block execution of the calling thread
0996      * until all the background jobs are finished. Instead, in case of presence of
0997      * unfinished jobs in the queue, it just returns false
0998      *
0999      * @return whether the lock has been acquired
1000      * @see barrierLock
1001      */
1002     bool tryBarrierLock(bool readOnly = false);
1003 
1004     /**
1005      * Wait for all the internal image jobs to complete and return without locking
1006      * the image. This function is handy for tests or other synchronous actions,
1007      * when one needs to wait for the result of his actions.
1008      */
1009     void waitForDone();
1010 
1011     KisStrokeId startStroke(KisStrokeStrategy *strokeStrategy) override;
1012     void addJob(KisStrokeId id, KisStrokeJobData *data) override;
1013     void endStroke(KisStrokeId id) override;
1014     bool cancelStroke(KisStrokeId id) override;
1015 
1016     /**
1017      * @brief blockUpdates block updating the image projection
1018      */
1019     void blockUpdates() override;
1020 
1021     /**
1022      * @brief unblockUpdates unblock updating the image project. This
1023      * only restarts the scheduler and does not schedule a full refresh.
1024      */
1025     void unblockUpdates() override;
1026 
1027     /**
1028      * Disables notification of the UI about the changes in the image.
1029      * This feature is used by KisProcessingApplicator. It is needed
1030      * when we change the size of the image. In this case, the whole
1031      * image will be reloaded into UI by sigSizeChanged(), so there is
1032      * no need to inform the UI about individual dirty rects.
1033      *
1034      * The last call to enableUIUpdates() will return the list of updates
1035      * that were requested while they were blocked.
1036      */
1037     void disableUIUpdates() override;
1038 
1039     /**
1040      * Notify GUI about a bunch of updates planned. GUI is expected to wait
1041      * until all the updates are completed, and render them on screen only
1042      * in the very and of the batch.
1043      */
1044     void notifyBatchUpdateStarted() override;
1045 
1046     /**
1047      * Notify GUI that batch update has been completed. Now GUI can start
1048      * showing all of them on screen.
1049      */
1050     void notifyBatchUpdateEnded() override;
1051 
1052     /**
1053      * Notify GUI that rect \p rc is now prepared in the image and
1054      * GUI can read data from it.
1055      *
1056      * WARNING: GUI will read the data right in the handler of this
1057      *          signal, so exclusive access to the area must be guaranteed
1058      *          by the caller.
1059      */
1060     void notifyUIUpdateCompleted(const QRect &rc) override;
1061 
1062     /**
1063      * \see disableUIUpdates
1064      */
1065     QVector<QRect> enableUIUpdates() override;
1066 
1067     /**
1068      * Disables the processing of all the setDirty() requests that
1069      * come to the image. The incoming requests are effectively
1070      * *dropped*.
1071      *
1072      * This feature is used by KisProcessingApplicator. For many cases
1073      * it provides its own updates interface, which recalculates the
1074      * whole subtree of nodes. But while we change any particular
1075      * node, it can ask for an update itself. This method is a way of
1076      * blocking such intermediate (and excessive) requests.
1077      *
1078      * NOTE: this is a convenience function for addProjectionUpdatesFilter()
1079      *       that installs a predefined filter that eats everything. Please
1080      *       note that these calls are *not* recursive.
1081      *
1082      * WARNING: The calls to enable/disable must be balanced.
1083      */
1084     void disableDirtyRequests() override;
1085 
1086     /**
1087      * \see disableDirtyRequests()
1088      */
1089     void enableDirtyRequests() override;
1090 
1091     /**
1092      * Installs a filter object that will filter all the incoming projection update
1093      * requests. If the filter return true, the incoming update is dropped.
1094      *
1095      * NOTE: you can add multiple filters to the image, **but** the calls to add/remove
1096      *       must be nested and balanced. E.g.
1097      *
1098      *       \code{.cpp}
1099      *
1100      *       auto cookie1 = image->addProjectionUpdatesFilter(filter1);
1101      *       auto cookie2 = image->addProjectionUpdatesFilter(filter2);
1102      *
1103      *       /// ...do something...
1104      *
1105      *       /// correct:
1106      *       image->removeProjectionUpdatesFilter(cookie2)
1107      *       image->removeProjectionUpdatesFilter(cookie1)
1108      *
1109      *       /// incorrect:
1110      *       // image->removeProjectionUpdatesFilter(cookie1)
1111      *       // image->removeProjectionUpdatesFilter(cookie2)
1112      *       \endcode
1113      */
1114     KisProjectionUpdatesFilterCookie addProjectionUpdatesFilter(KisProjectionUpdatesFilterSP filter) override;
1115 
1116     /**
1117      * @brief removes already installed filter from the stack of updates filers
1118      * @param cookie a cookie object returned by addProjectionUpdatesFilter() on installation
1119      * @return the installed filter. If the cookie is invalid, or nesting rule has been
1120      *         broken, then removeProjectionUpdatesFilter() may safe-assert and return nullptr.
1121      *
1122      * NOTE: some weird code (e.g. KisRegenerateFrameStrokeStrategy) needs to temporary remove
1123      * all the filters and then install them back. Current implementation ensures that after removal
1124      * and the following installation, cookies will be preserved. So this operation is considered
1125      * safe.
1126      *
1127      * \see addProjectionUpdatesFilter()
1128      */
1129     KisProjectionUpdatesFilterSP removeProjectionUpdatesFilter(KisProjectionUpdatesFilterCookie cookie) override;
1130 
1131     /**
1132      * Return the cookie of the lastly-installed filter
1133      *
1134      * \see addProjectionUpdatesFilter()
1135      */
1136     KisProjectionUpdatesFilterCookie currentProjectionUpdatesFilter() const override;
1137 
1138 
1139     void refreshGraphAsync(KisNodeSP root = KisNodeSP(), UpdateFlags flags = None) override;
1140     void refreshGraphAsync(KisNodeSP root, const QRect &rc, UpdateFlags flags = None) override;
1141     void refreshGraphAsync(KisNodeSP root, const QRect &rc, const QRect &cropRect, UpdateFlags flags = None) override;
1142     void refreshGraphAsync(KisNodeSP root, const QVector<QRect> &rects, const QRect &cropRect, UpdateFlags flags = None) override;
1143 
1144     /**
1145      * Triggers synchronous recomposition of the projection
1146      */
1147     void refreshGraph(KisNodeSP root = KisNodeSP());
1148     void refreshGraph(KisNodeSP root, const QRect& rc, const QRect &cropRect);
1149     void initialRefreshGraph();
1150 
1151     /**
1152      * Initiate a stack regeneration skipping the recalculation of the
1153      * filthy node's projection.
1154      *
1155      * Works exactly as pseudoFilthy->setDirty() with the only
1156      * exception that pseudoFilthy::updateProjection() will not be
1157      * called. That is used by KisRecalculateTransformMaskJob to avoid
1158      * cyclic dependencies.
1159      */
1160     void requestProjectionUpdateNoFilthy(KisNodeSP pseudoFilthy, const QRect &rc, const QRect &cropRect);
1161 
1162     void requestProjectionUpdateNoFilthy(KisNodeSP pseudoFilthy, const QRect &rc, const QRect &cropRect, const bool notifyFrameChange );
1163 
1164     void requestProjectionUpdateNoFilthy(KisNodeSP pseudoFilthy, const QVector<QRect> &rects, const QRect &cropRect, const bool resetAnimationCache);
1165 
1166     /**
1167      * Adds a spontaneous job to the updates queue.
1168      *
1169      * A spontaneous job may do some trivial tasks in the background,
1170      * like updating the outline of selection or purging unused tiles
1171      * from the existing paint devices.
1172      */
1173     void addSpontaneousJob(KisSpontaneousJob *spontaneousJob);
1174 
1175     /**
1176      * \return true if there are some updates in the updates queue.
1177      * Please note, that is doesn't guarantee that there are no updates
1178      * running in the updater context at the very moment. To guarantee that
1179      * there are no updates left at all, please use barrier jobs instead.
1180      */
1181     bool hasUpdatesRunning() const override;
1182 
1183     /**
1184      * This method is called by the UI (*not* by the creator of the
1185      * stroke) when it thinks the current stroke should undo its last
1186      * action, for example, when the user presses Ctrl+Z while some
1187      * stroke is active.
1188      *
1189      * If the creator of the stroke supports undoing of intermediate
1190      * actions, it will be notified about this request and can undo
1191      * its last action.
1192      */
1193     void requestUndoDuringStroke();
1194 
1195     /**
1196      * This method is called by the UI (*not* by the creator of the
1197      * stroke) when it thinks the current stroke should redo its last
1198      * undo, for example, when the user presses Ctrl+Shift+Z while some
1199      * stroke is active.
1200      *
1201      * If the creator of the stroke supports undoing/redoing of an
1202      * intermediate actions, it will be notified about this request and
1203      * can undo its last action.
1204      */
1205     void requestRedoDuringStroke();
1206 
1207     /**
1208      * This method is called by the UI (*not* by the creator of the
1209      * stroke) when it thinks current stroke should be cancelled. If
1210      * there is a running stroke that has already been detached from
1211      * its creator (ended or cancelled), it will be forcefully
1212      * cancelled and reverted. If there is an open stroke present, and
1213      * if its creator supports cancelling, it will be notified about
1214      * the request and the stroke will be cancelled
1215      */
1216     void requestStrokeCancellation();
1217 
1218     /**
1219      * This method requests the last stroke executed on the image to become undone.
1220      * If the stroke is not ended, or if all the Lod0 strokes are completed, the method
1221      * returns UNDO_FAIL. If the last Lod0 is going to be finished soon, then UNDO_WAIT
1222      * is returned and the caller should just wait for its completion and call global undo
1223      * instead. UNDO_OK means one unfinished stroke has been undone.
1224      */
1225     UndoResult tryUndoUnfinishedLod0Stroke();
1226 
1227     /**
1228      * This method is called when image or some other part of Krita
1229      * (*not* the creator of the stroke) decides that the stroke
1230      * should be ended. If the creator of the stroke supports it, it
1231      * will be notified and the stroke will be cancelled
1232      */
1233     void requestStrokeEnd();
1234 
1235     /**
1236      * Same as requestStrokeEnd() but is called by view manager when
1237      * the current node is changed. Use to distinguish
1238      * sigStrokeEndRequested() and
1239      * sigStrokeEndRequestedActiveNodeFiltered() which are used by
1240      * KisNodeJugglerCompressed
1241      */
1242     void requestStrokeEndActiveNode();
1243 
1244     /**
1245      * A special interface that commands use to modify image's global selection
1246      */
1247     KisImageGlobalSelectionManagementInterface* globalSelectionManagementInterface() const;
1248 
1249 private:
1250 
1251     KisImage(const KisImage& rhs, KisUndoStore *undoStore, bool exactCopy);
1252     KisImage& operator=(const KisImage& rhs);
1253 
1254     void emitSizeChanged();
1255 
1256     void resizeImageImpl(const QRect& newRect, bool cropLayers);
1257     void rotateImpl(const KUndo2MagicString &actionName, KisNodeSP rootNode, double radians,
1258                     bool resizeImage, KisSelectionSP selection);
1259     void rotateImpl(const KUndo2MagicString &actionName, KisNodeList nodes, double radians,
1260                     bool resizeImage, KisSelectionSP selection);
1261     void shearImpl(const KUndo2MagicString &actionName, KisNodeSP rootNode,
1262                    bool resizeImage, double angleX, double angleY, KisSelectionSP selection);
1263     void shearImpl(const KUndo2MagicString &actionName, KisNodeList nodes,
1264                    bool resizeImage, double angleX, double angleY, KisSelectionSP selection);
1265 
1266     void safeRemoveTwoNodes(KisNodeSP node1, KisNodeSP node2);
1267 
1268     void refreshHiddenArea(KisNodeSP rootNode, const QRect &preparedArea);
1269 
1270     void requestProjectionUpdateImpl(KisNode *node,
1271                                      const QVector<QRect> &rects,
1272                                      const QRect &cropRect);
1273 
1274     friend class KisImageResizeCommand;
1275     void setSize(const QSize& size);
1276 
1277     void setProjectionColorSpace(const KoColorSpace * colorSpace);
1278 
1279     friend class KisImageGlobalSelectionManagementInterface;
1280 
1281 private:
1282     class KisImagePrivate;
1283     KisImagePrivate * m_d;
1284 };
1285 
1286 #endif // KIS_IMAGE_H_