1 /*
2  *  Copyright (c) 2014 Dmitry Kazakov <dimula73@gmail.com>
3  *  Copyright (c) 2014 Mohit Goyal <mohit.bits2011@gmail.com>
4  *
5  *  This library is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU Lesser General Public License as published by
7  *  the Free Software Foundation; either version 2.1 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This library is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU Lesser General Public License for more details.
14  *
15  *  You should have received a copy of the GNU Lesser General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19 /****************************************************************************
20 **
21 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
22 ** All rights reserved.
23 ** Contact: Nokia Corporation (qt-info@nokia.com)
24 **
25 ** This file is part of the QtGui module of the Qt Toolkit.
26 **
27 ** $QT_BEGIN_LICENSE:LGPL$
28 ** No Commercial Usage
29 ** This file contains pre-release code and may not be distributed.
30 ** You may use this file in accordance with the terms and conditions
31 ** contained in the Technology Preview License Agreement accompanying
32 ** this package.
33 **
34 ** GNU Lesser General Public License Usage
35 ** Alternatively, this file may be used under the terms of the GNU Lesser
36 ** General Public License version 2.1 as published by the Free Software
37 ** Foundation and appearing in the file LICENSE.LGPL included in the
38 ** packaging of this file.  Please review the following information to
39 ** ensure the GNU Lesser General Public License version 2.1 requirements
40 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
41 **
42 ** In addition, as a special exception, Nokia gives you certain additional
43 ** rights.  These rights are described in the Nokia Qt LGPL Exception
44 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
45 **
46 ** If you have questions regarding the use of this file, please contact
47 ** Nokia at qt-info@nokia.com.
48 **
49 **
50 **
51 **
52 **
53 **
54 **
55 **
56 ** $QT_END_LICENSE$
57 **
58 ****************************************************************************/
59 
60 // clazy:excludeall=qstring-arg
61 #include <QDebug>
62 #include <klocalizedstring.h>
63 #include <kstandardaction.h>
64 #include <kactioncollection.h>
65 #include "kundo2stack.h"
66 #include "kundo2stack_p.h"
67 #include "kundo2group.h"
68 #include <KoIcon.h>
69 #include<QtGlobal>
70 
71 
72 #ifndef QT_NO_UNDOCOMMAND
73 
74 /*!
75     \class KUndo2Command
76     \brief The KUndo2Command class is the base class of all commands stored on a KUndo2QStack.
77     \since 4.2
78 
79     For an overview of Qt's Undo Framework, see the
80     \l{Overview of Qt's Undo Framework}{overview document}.
81 
82     A KUndo2Command represents a single editing action on a document; for example,
83     inserting or deleting a block of text in a text editor. KUndo2Command can apply
84     a change to the document with redo() and undo the change with undo(). The
85     implementations for these functions must be provided in a derived class.
86 
87     \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 0
88 
89     A KUndo2Command has an associated text(). This is a short string
90     describing what the command does. It is used to update the text
91     properties of the stack's undo and redo actions; see
92     KUndo2QStack::createUndoAction() and KUndo2QStack::createRedoAction().
93 
94     KUndo2Command objects are owned by the stack they were pushed on.
95     KUndo2QStack deletes a command if it has been undone and a new command is pushed. For example:
96 
97 \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 1
98 
99     In effect, when a command is pushed, it becomes the top-most command
100     on the stack.
101 
102     To support command compression, KUndo2Command has an id() and the virtual function
103     mergeWith(). These functions are used by KUndo2QStack::push().
104 
105     To support command macros, a KUndo2Command object can have any number of child
106     commands. Undoing or redoing the parent command will cause the child
107     commands to be undone or redone. A command can be assigned
108     to a parent explicitly in the constructor. In this case, the command
109     will be owned by the parent.
110 
111     The parent in this case is usually an empty command, in that it doesn't
112     provide its own implementation of undo() and redo(). Instead, it uses
113     the base implementations of these functions, which simply call undo() or
114     redo() on all its children. The parent should, however, have a meaningful
115     text().
116 
117     \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 2
118 
119     Another way to create macros is to use the convenience functions
120     KUndo2QStack::beginMacro() and KUndo2QStack::endMacro().
121 
122     \sa KUndo2QStack
123 */
124 
125 /*!
126     Constructs a KUndo2Command object with the given \a parent and \a text.
127 
128     If \a parent is not 0, this command is appended to parent's child list.
129     The parent command then owns this command and will delete it in its
130     destructor.
131 
132     \sa ~KUndo2Command()
133 */
134 
KUndo2Command(const KUndo2MagicString & text,KUndo2Command * parent)135 KUndo2Command::KUndo2Command(const KUndo2MagicString &text, KUndo2Command *parent):
136     m_hasParent(parent != 0),
137     m_timedID(0),
138     m_endOfCommand(QTime::currentTime())
139 {
140     d = new KUndo2CommandPrivate;
141     if (parent != 0) {
142         parent->d->child_list.append(this);
143     }
144     setText(text);
145     setTime();
146 }
147 
148 /*!
149     Constructs a KUndo2Command object with parent \a parent.
150 
151     If \a parent is not 0, this command is appended to parent's child list.
152     The parent command then owns this command and will delete it in its
153     destructor.
154 
155     \sa ~KUndo2Command()
156 */
157 
KUndo2Command(KUndo2Command * parent)158 KUndo2Command::KUndo2Command(KUndo2Command *parent):
159     m_hasParent(parent != 0),m_timedID(0)
160 {
161     d = new KUndo2CommandPrivate;
162     if (parent != 0)
163         parent->d->child_list.append(this);
164     setTime();
165 }
166 
167 /*!
168     Destroys the KUndo2Command object and all child commands.
169 
170     \sa KUndo2Command()
171 */
172 
~KUndo2Command()173 KUndo2Command::~KUndo2Command()
174 {
175     qDeleteAll(d->child_list);
176     delete d;
177 }
178 
179 /*!
180     Returns the ID of this command.
181 
182     A command ID is used in command compression. It must be an integer unique to
183     this command's class, or -1 if the command doesn't support compression.
184 
185     If the command supports compression this function must be overridden in the
186     derived class to return the correct ID. The base implementation returns -1.
187 
188     KUndo2QStack::push() will only try to merge two commands if they have the
189     same ID, and the ID is not -1.
190 
191     \sa mergeWith(), KUndo2QStack::push()
192 */
193 
id() const194 int KUndo2Command::id() const
195 {
196     return -1;
197 }
198 
199 /*!
200     Attempts to merge this command with \a command. Returns true on
201     success; otherwise returns false.
202 
203     If this function returns true, calling this command's redo() must have the same
204     effect as redoing both this command and \a command.
205     Similarly, calling this command's undo() must have the same effect as undoing
206     \a command and this command.
207 
208     KUndo2QStack will only try to merge two commands if they have the same id, and
209     the id is not -1.
210 
211     The default implementation returns false.
212 
213     \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 3
214 
215     \sa id() KUndo2QStack::push()
216 */
217 
mergeWith(const KUndo2Command * command)218 bool KUndo2Command::mergeWith(const KUndo2Command *command)
219 {
220     Q_UNUSED(command);
221     return false;
222 }
223 
224 /*!
225     Applies a change to the document. This function must be implemented in
226     the derived class. Calling KUndo2QStack::push(),
227     KUndo2QStack::undo() or KUndo2QStack::redo() from this function leads to
228     undefined behavior.
229 
230     The default implementation calls redo() on all child commands.
231 
232     \sa undo()
233 */
234 
redo()235 void KUndo2Command::redo()
236 {
237     for (int i = 0; i < d->child_list.size(); ++i)
238         d->child_list.at(i)->redo();
239 }
240 
241 /*!
242     Reverts a change to the document. After undo() is called, the state of
243     the document should be the same as before redo() was called. This function must
244     be implemented in the derived class. Calling KUndo2QStack::push(),
245     KUndo2QStack::undo() or KUndo2QStack::redo() from this function leads to
246     undefined behavior.
247 
248     The default implementation calls undo() on all child commands in reverse order.
249 
250     \sa redo()
251 */
252 
undo()253 void KUndo2Command::undo()
254 {
255     for (int i = d->child_list.size() - 1; i >= 0; --i)
256         d->child_list.at(i)->undo();
257 }
258 
259 /*!
260     Returns a short text string describing what this command does; for example,
261     "insert text".
262 
263     The text is used when the text properties of the stack's undo and redo
264     actions are updated.
265 
266     \sa setText(), KUndo2QStack::createUndoAction(), KUndo2QStack::createRedoAction()
267 */
268 
actionText() const269 QString KUndo2Command::actionText() const
270 {
271     if(d->actionText!=0)
272         return d->actionText;
273     else
274         return QString();
275 }
276 
277 /*!
278     Returns a short text string describing what this command does; for example,
279     "insert text".
280 
281     The text is used when the text properties of the stack's undo and redo
282     actions are updated.
283 
284     \sa setText(), KUndo2QStack::createUndoAction(), KUndo2QStack::createRedoAction()
285 */
286 
text() const287 KUndo2MagicString KUndo2Command::text() const
288 {
289     return d->text;
290 }
291 
292 /*!
293     Sets the command's text to be the \a text specified.
294 
295     The specified text should be a short user-readable string describing what this
296     command does.
297 
298     \sa text() KUndo2QStack::createUndoAction() KUndo2QStack::createRedoAction()
299 */
300 
setText(const KUndo2MagicString & undoText)301 void KUndo2Command::setText(const KUndo2MagicString &undoText)
302 {
303     d->text = undoText;
304     d->actionText = undoText.toSecondaryString();
305 }
306 
307 /*!
308     \since 4.4
309 
310     Returns the number of child commands in this command.
311 
312     \sa child()
313 */
314 
childCount() const315 int KUndo2Command::childCount() const
316 {
317     return d->child_list.count();
318 }
319 
320 /*!
321     \since 4.4
322 
323     Returns the child command at \a index.
324 
325     \sa childCount(), KUndo2QStack::command()
326 */
327 
child(int index) const328 const KUndo2Command *KUndo2Command::child(int index) const
329 {
330     if (index < 0 || index >= d->child_list.count())
331         return 0;
332     return d->child_list.at(index);
333 }
334 
hasParent()335 bool KUndo2Command::hasParent()
336 {
337     return m_hasParent;
338 }
timedId()339 int KUndo2Command::timedId()
340 {
341     return m_timedID;
342 }
setTimedID(int value)343 void KUndo2Command::setTimedID(int value)
344 {
345     m_timedID = value;
346 }
347 
timedMergeWith(KUndo2Command * other)348 bool KUndo2Command::timedMergeWith(KUndo2Command *other)
349 {
350     if(other->timedId() == this->timedId() && other->timedId()!=-1)
351         m_mergeCommandsVector.append(other);
352     else
353         return false;
354     return true;
355 }
setTime()356 void KUndo2Command::setTime()
357 {
358     m_timeOfCreation = QTime::currentTime();
359 }
time()360 QTime KUndo2Command::time()
361 {
362     return m_timeOfCreation;
363 }
setEndTime()364 void KUndo2Command::setEndTime()
365 {
366     m_endOfCommand  = QTime::currentTime();
367 }
endTime()368 QTime KUndo2Command::endTime()
369 {
370     return m_endOfCommand;
371 }
372 
undoMergedCommands()373 void KUndo2Command::undoMergedCommands()
374 {
375 
376     undo();
377     if (!mergeCommandsVector().isEmpty()) {
378         QVectorIterator<KUndo2Command*> it(mergeCommandsVector());
379         it.toFront();
380         while (it.hasNext()) {
381             KUndo2Command* cmd = it.next();
382             cmd->undoMergedCommands();
383         }
384     }
385 }
386 
redoMergedCommands()387 void KUndo2Command::redoMergedCommands()
388 {
389     if (!mergeCommandsVector().isEmpty()) {
390 
391         QVectorIterator<KUndo2Command*> it(mergeCommandsVector());
392         it.toBack();
393         while (it.hasPrevious()) {
394             KUndo2Command* cmd = it.previous();
395             cmd->redoMergedCommands();
396         }
397     }
398     redo();
399 }
mergeCommandsVector()400 QVector<KUndo2Command*> KUndo2Command::mergeCommandsVector()
401 {
402     return m_mergeCommandsVector;
403 }
isMerged()404 bool KUndo2Command::isMerged()
405 {
406     return !m_mergeCommandsVector.isEmpty();
407 }
408 
extraData() const409 KUndo2CommandExtraData* KUndo2Command::extraData() const
410 {
411     return d->extraData.data();
412 }
413 
setExtraData(KUndo2CommandExtraData * data)414 void KUndo2Command::setExtraData(KUndo2CommandExtraData *data)
415 {
416     d->extraData.reset(data);
417 }
418 
419 
420 #endif // QT_NO_UNDOCOMMAND
421 
422 #ifndef QT_NO_UNDOSTACK
423 
424 /*!
425     \class KUndo2QStack
426     \brief The KUndo2QStack class is a stack of KUndo2Command objects.
427     \since 4.2
428 
429     For an overview of Qt's Undo Framework, see the
430     \l{Overview of Qt's Undo Framework}{overview document}.
431 
432     An undo stack maintains a stack of commands that have been applied to a
433     document.
434 
435     New commands are pushed on the stack using push(). Commands can be
436     undone and redone using undo() and redo(), or by triggering the
437     actions returned by createUndoAction() and createRedoAction().
438 
439     KUndo2QStack keeps track of the \a current command. This is the command
440     which will be executed by the next call to redo(). The index of this
441     command is returned by index(). The state of the edited object can be
442     rolled forward or back using setIndex(). If the top-most command on the
443     stack has already been redone, index() is equal to count().
444 
445     KUndo2QStack provides support for undo and redo actions, command
446     compression, command macros, and supports the concept of a
447     \e{clean state}.
448 
449     \section1 Undo and Redo Actions
450 
451     KUndo2QStack provides convenient undo and redo QAction objects, which
452     can be inserted into a menu or a toolbar. When commands are undone or
453     redone, KUndo2QStack updates the text properties of these actions
454     to reflect what change they will trigger. The actions are also disabled
455     when no command is available for undo or redo. These actions
456     are returned by KUndo2QStack::createUndoAction() and KUndo2QStack::createRedoAction().
457 
458     \section1 Command Compression and Macros
459 
460     Command compression is useful when several commands can be compressed
461     into a single command that can be undone and redone in a single operation.
462     For example, when a user types a character in a text editor, a new command
463     is created. This command inserts the character into the document at the
464     cursor position. However, it is more convenient for the user to be able
465     to undo or redo typing of whole words, sentences, or paragraphs.
466     Command compression allows these single-character commands to be merged
467     into a single command which inserts or deletes sections of text.
468     For more information, see KUndo2Command::mergeWith() and push().
469 
470     A command macro is a sequence of commands, all of which are undone and
471     redone in one go. Command macros are created by giving a command a list
472     of child commands.
473     Undoing or redoing the parent command will cause the child commands to
474     be undone or redone. Command macros may be created explicitly
475     by specifying a parent in the KUndo2Command constructor, or by using the
476     convenience functions beginMacro() and endMacro().
477 
478     Although command compression and macros appear to have the same effect to the
479     user, they often have different uses in an application. Commands that
480     perform small changes to a document may be usefully compressed if there is
481     no need to individually record them, and if only larger changes are relevant
482     to the user.
483     However, for commands that need to be recorded individually, or those that
484     cannot be compressed, it is useful to use macros to provide a more convenient
485     user experience while maintaining a record of each command.
486 
487     \section1 Clean State
488 
489     KUndo2QStack supports the concept of a clean state. When the
490     document is saved to disk, the stack can be marked as clean using
491     setClean(). Whenever the stack returns to this state through undoing and
492     redoing commands, it emits the signal cleanChanged(). This signal
493     is also emitted when the stack leaves the clean state. This signal is
494     usually used to enable and disable the save actions in the application,
495     and to update the document's title to reflect that it contains unsaved
496     changes.
497 
498     \sa KUndo2Command, KUndo2View
499 */
500 
501 #ifndef QT_NO_ACTION
502 
KUndo2Action(const QString & textTemplate,const QString & defaultText,QObject * parent)503 KUndo2Action::KUndo2Action(const QString &textTemplate, const QString &defaultText, QObject *parent)
504     : QAction(parent)
505 {
506     m_textTemplate = textTemplate;
507     m_defaultText = defaultText;
508 
509 }
510 
setPrefixedText(const QString & text)511 void KUndo2Action::setPrefixedText(const QString &text)
512 {
513     if (text.isEmpty())
514         setText(m_defaultText);
515     else
516         setText(m_textTemplate.arg(text));
517 }
518 
519 #endif // QT_NO_ACTION
520 
521 /*! \internal
522     Sets the current index to \a idx, emitting appropriate signals. If \a clean is true,
523     makes \a idx the clean index as well.
524 */
525 
setIndex(int idx,bool clean)526 void KUndo2QStack::setIndex(int idx, bool clean)
527 {
528     bool was_clean = m_index == m_clean_index;
529     if (m_lastMergedIndex <= idx) {
530         m_lastMergedSetCount = idx - m_lastMergedIndex;
531 
532     } else {
533         m_lastMergedSetCount = 1;
534         m_lastMergedIndex = idx-1;
535     }
536     if(idx == 0){
537         m_lastMergedSetCount = 0;
538         m_lastMergedIndex = 0;
539     }
540     if (idx != m_index) {
541         m_index = idx;
542         emit indexChanged(m_index);
543         emit canUndoChanged(canUndo());
544         emit undoTextChanged(undoText());
545         emit canRedoChanged(canRedo());
546         emit redoTextChanged(redoText());
547     }
548 
549     if (clean)
550         m_clean_index = m_index;
551 
552     bool is_clean = m_index == m_clean_index;
553     if (is_clean != was_clean)
554         emit cleanChanged(is_clean);
555 }
556 
purgeRedoState()557 void KUndo2QStack::purgeRedoState()
558 {
559     bool macro = !m_macro_stack.isEmpty();
560     if (macro) return;
561 
562     bool redoStateChanged = false;
563     bool cleanStateChanged = false;
564 
565     while (m_index < m_command_list.size()) {
566         delete m_command_list.takeLast();
567         redoStateChanged = true;
568     }
569 
570     if (m_clean_index > m_index) {
571         m_clean_index = -1; // we've deleted the clean state
572         cleanStateChanged = true;
573     }
574 
575     if (redoStateChanged) {
576         emit canRedoChanged(canRedo());
577         emit redoTextChanged(redoText());
578     }
579 
580     if (cleanStateChanged) {
581         emit cleanChanged(isClean());
582     }
583 }
584 
585 /*! \internal
586     If the number of commands on the stack exceedes the undo limit, deletes commands from
587     the bottom of the stack.
588 
589     Returns true if commands were deleted.
590 */
591 
checkUndoLimit()592 bool KUndo2QStack::checkUndoLimit()
593 {
594     if (m_undo_limit <= 0 || !m_macro_stack.isEmpty() || m_undo_limit >= m_command_list.count())
595         return false;
596 
597     int del_count = m_command_list.count() - m_undo_limit;
598 
599     for (int i = 0; i < del_count; ++i)
600         delete m_command_list.takeFirst();
601 
602     m_index -= del_count;
603     if (m_clean_index != -1) {
604         if (m_clean_index < del_count)
605             m_clean_index = -1; // we've deleted the clean command
606         else
607             m_clean_index -= del_count;
608     }
609     return true;
610 }
611 
612 /*!
613     Constructs an empty undo stack with the parent \a parent. The
614     stack will initially be in the clean state. If \a parent is a
615     KUndo2Group object, the stack is automatically added to the group.
616 
617     \sa push()
618 */
619 
KUndo2QStack(QObject * parent)620 KUndo2QStack::KUndo2QStack(QObject *parent)
621     : QObject(parent), m_index(0), m_clean_index(0), m_group(0), m_undo_limit(0), m_useCumulativeUndoRedo(false), m_lastMergedSetCount(0), m_lastMergedIndex(0)
622 {
623     setTimeT1(5);
624     setTimeT2(1);
625     setStrokesN(2);
626 #ifndef QT_NO_UNDOGROUP
627     if (KUndo2Group *group = qobject_cast<KUndo2Group*>(parent))
628         group->addStack(this);
629 #endif
630 }
631 
632 /*!
633     Destroys the undo stack, deleting any commands that are on it. If the
634     stack is in a KUndo2Group, the stack is automatically removed from the group.
635 
636     \sa KUndo2QStack()
637 */
638 
~KUndo2QStack()639 KUndo2QStack::~KUndo2QStack()
640 {
641 #ifndef QT_NO_UNDOGROUP
642     if (m_group != 0)
643         m_group->removeStack(this);
644 #endif
645     clear();
646 }
647 
648 /*!
649     Clears the command stack by deleting all commands on it, and returns the stack
650     to the clean state.{
651 
652             }
653 
654     Commands are not undone or redone; the state of the edited object remains
655     unchanged.
656 
657     This function is usually used when the contents of the document are
658     abandoned.
659 
660     \sa KUndo2QStack()
661 */
662 
clear()663 void KUndo2QStack::clear()
664 {
665     if (m_command_list.isEmpty())
666         return;
667 
668     bool was_clean = isClean();
669 
670     m_macro_stack.clear();
671     qDeleteAll(m_command_list);
672     m_command_list.clear();
673 
674     m_index = 0;
675     m_clean_index = 0;
676 
677     emit indexChanged(0);
678     emit canUndoChanged(false);
679     emit undoTextChanged(QString());
680     emit canRedoChanged(false);
681     emit redoTextChanged(QString());
682 
683     if (!was_clean)
684         emit cleanChanged(true);
685 }
686 
687 /*!
688     Pushes \a cmd on the stack or merges it with the most recently executed command.
689     In either case, executes \a cmd by calling its redo() function.
690 
691     If \a cmd's id is not -1, and if the id is the same as that of the
692     most recently executed command, KUndo2QStack will attempt to merge the two
693     commands by calling KUndo2Command::mergeWith() on the most recently executed
694     command. If KUndo2Command::mergeWith() returns true, \a cmd is deleted and false
695     is returned.
696 
697     In all other cases \a cmd is simply pushed on the stack and true is returned.
698 
699     If commands were undone before \a cmd was pushed, the current command and
700     all commands above it are deleted. Hence \a cmd always ends up being the
701     top-most on the stack.
702 
703     Once a command is pushed, the stack takes ownership of it. There
704     are no getters to return the command, since modifying it after it has
705     been executed will almost always lead to corruption of the document's
706     state.
707 
708     \sa KUndo2Command::id() KUndo2Command::mergeWith()
709 */
710 
push(KUndo2Command * cmd)711 bool KUndo2QStack::push(KUndo2Command *cmd)
712 {
713     cmd->redoMergedCommands();
714     cmd->setEndTime();
715 
716     bool macro = !m_macro_stack.isEmpty();
717 
718     KUndo2Command *cur = 0;
719     if (macro) {
720         KUndo2Command *macro_cmd = m_macro_stack.last();
721         if (!macro_cmd->d->child_list.isEmpty())
722             cur = macro_cmd->d->child_list.last();
723     } else {
724         if (m_index > 0)
725             cur = m_command_list.at(m_index - 1);
726         while (m_index < m_command_list.size())
727             delete m_command_list.takeLast();
728         if (m_clean_index > m_index)
729             m_clean_index = -1; // we've deleted the clean state
730     }
731 
732     bool try_merge = cur != 0
733                      && cur->id() != -1
734                      && cur->id() == cmd->id()
735                      && (macro || m_index != m_clean_index);
736 
737     /*!
738      *Here we are going to try to merge several commands together using the QVector field in the commands using
739      *3 parameters. N : Number of commands that should remain individual at the top of the stack. T1 : Time lapsed between current command and previously merged command -- signal to
740      *merge throughout the stack. T2 : Time lapsed between two commands signalling both commands belong to the same set
741      *Whenever a KUndo2Command is initialized -- it consists of a start-time and when it is pushed --an end time.
742      *Every time a command is pushed -- it checks whether the command pushed was pushed after T1 seconds of the last merged command
743      *Then the merging begins with each group depending on the time in between each command (T2).
744      *
745      *@TODO : Currently it is not able to merge two merged commands together.
746     */
747     if (!macro && m_command_list.size() > 1 && cmd->timedId() != -1 && m_useCumulativeUndoRedo) {
748         KUndo2Command* lastcmd = m_command_list.last();
749         if (qAbs(cmd->time().msecsTo(lastcmd->endTime())) < m_timeT2 * 1000) {
750             m_lastMergedSetCount++;
751         } else {
752             m_lastMergedSetCount = 0;
753             m_lastMergedIndex = m_index-1;
754         }
755         if (lastcmd->timedId() == -1){
756             m_lastMergedSetCount = 0;
757             m_lastMergedIndex = m_index;
758         }
759         if (m_lastMergedSetCount > m_strokesN) {
760             KUndo2Command* toMerge = m_command_list.at(m_lastMergedIndex);
761             if (toMerge && m_command_list.size() >= m_lastMergedIndex + 1 && m_command_list.at(m_lastMergedIndex + 1)) {
762                 if(toMerge->timedMergeWith(m_command_list.at(m_lastMergedIndex + 1))){
763                     m_command_list.removeAt(m_lastMergedIndex + 1);
764                 }
765                 m_lastMergedSetCount--;
766                 m_lastMergedIndex = m_command_list.indexOf(toMerge);
767             }
768 
769         }
770         m_index = m_command_list.size();
771         if(m_lastMergedIndex<m_index){
772             if (cmd->time().msecsTo(m_command_list.at(m_lastMergedIndex)->endTime()) < -m_timeT1 * 1000) { //T1 time elapsed
773                 QListIterator<KUndo2Command*> it(m_command_list);
774                 it.toBack();
775                 m_lastMergedSetCount = 1;
776 
777                 while (it.hasPrevious()) {
778                     KUndo2Command* curr = it.previous();
779                     KUndo2Command* lastCmdInCurrent = curr;
780 
781                     if (!lastcmd->mergeCommandsVector().isEmpty()) {
782                         if (qAbs(lastcmd->mergeCommandsVector().constLast()->time().msecsTo(lastCmdInCurrent->endTime())) < int(m_timeT2 * 1000) && lastcmd != lastCmdInCurrent && lastcmd != curr) {
783                             if(lastcmd->timedMergeWith(curr)){
784                                 if (m_command_list.contains(curr)) {
785                                     m_command_list.removeOne(curr);
786                                 }
787                              }
788                         } else {
789                             lastcmd = curr; //end of a merge set
790                         }
791                     } else {
792                         if (qAbs(lastcmd->time().msecsTo(lastCmdInCurrent->endTime())) < int(m_timeT2 * 1000) && lastcmd != lastCmdInCurrent &&lastcmd!=curr) {
793                             if(lastcmd->timedMergeWith(curr)){
794                                 if (m_command_list.contains(curr)){
795                                     m_command_list.removeOne(curr);
796                                 }
797                             }
798                         } else {
799                             lastcmd = curr; //end of a merge set
800                         }
801                     }
802                 }
803                 m_lastMergedIndex = m_command_list.size()-1;
804             }
805         }
806         m_index = m_command_list.size();
807     }
808     if (try_merge && cur->mergeWith(cmd)) {
809         delete cmd;
810         cmd = 0;
811         if (!macro) {
812             emit indexChanged(m_index);
813             emit canUndoChanged(canUndo());
814             emit undoTextChanged(undoText());
815             emit canRedoChanged(canRedo());
816             emit redoTextChanged(redoText());
817         }
818     } else {
819         if (macro) {
820             m_macro_stack.last()->d->child_list.append(cmd);
821         } else {
822             m_command_list.append(cmd);
823             if(checkUndoLimit())
824             {
825                 m_lastMergedIndex = m_index - m_strokesN;
826             }
827             setIndex(m_index + 1, false);
828         }
829     }
830     return cmd;
831 }
832 
833 /*!
834     Marks the stack as clean and emits cleanChanged() if the stack was
835     not already clean.
836 
837     Whenever the stack returns to this state through the use of undo/redo
838     commands, it emits the signal cleanChanged(). This signal is also
839     emitted when the stack leaves the clean state.
840 
841     \sa isClean(), cleanIndex()
842 */
843 
setClean()844 void KUndo2QStack::setClean()
845 {
846     if (!m_macro_stack.isEmpty()) {
847         qWarning("KUndo2QStack::setClean(): cannot set clean in the middle of a macro");
848         return;
849     }
850 
851     setIndex(m_index, true);
852 }
853 
854 /*!
855     If the stack is in the clean state, returns true; otherwise returns false.
856 
857     \sa setClean() cleanIndex()
858 */
859 
isClean() const860 bool KUndo2QStack::isClean() const
861 {
862     if (!m_macro_stack.isEmpty())
863         return false;
864     return m_clean_index == m_index;
865 }
866 
867 /*!
868     Returns the clean index. This is the index at which setClean() was called.
869 
870     A stack may not have a clean index. This happens if a document is saved,
871     some commands are undone, then a new command is pushed. Since
872     push() deletes all the undone commands before pushing the new command, the stack
873     can't return to the clean state again. In this case, this function returns -1.
874 
875     \sa isClean() setClean()
876 */
877 
cleanIndex() const878 int KUndo2QStack::cleanIndex() const
879 {
880     return m_clean_index;
881 }
882 
883 /*!
884     Undoes the command below the current command by calling KUndo2Command::undo().
885     Decrements the current command index.
886 
887     If the stack is empty, or if the bottom command on the stack has already been
888     undone, this function does nothing.
889 
890     \sa redo() index()
891 */
892 
undo()893 void KUndo2QStack::undo()
894 {
895     if (m_index == 0)
896         return;
897 
898     if (!m_macro_stack.isEmpty()) {
899         qWarning("KUndo2QStack::undo(): cannot undo in the middle of a macro");
900         return;
901     }
902 
903     int idx = m_index - 1;
904     m_command_list.at(idx)->undoMergedCommands();
905     setIndex(idx, false);
906 }
907 
908 /*!
909     Redoes the current command by calling KUndo2Command::redo(). Increments the current
910     command index.
911 
912     If the stack is empty, or if the top command on the stack has already been
913     redone, this function does nothing.
914 
915     \sa undo() index()
916 */
917 
redo()918 void KUndo2QStack::redo()
919 {
920     if (m_index == m_command_list.size())
921         return;
922 
923     if (!m_macro_stack.isEmpty()) {
924         qWarning("KUndo2QStack::redo(): cannot redo in the middle of a macro");
925         return;
926     }
927 
928     m_command_list.at(m_index)->redoMergedCommands();
929     setIndex(m_index + 1, false);
930 }
931 
932 /*!
933     Returns the number of commands on the stack. Macro commands are counted as
934     one command.
935 
936     \sa index() setIndex() command()
937 */
938 
count() const939 int KUndo2QStack::count() const
940 {
941     return m_command_list.size();
942 }
943 
944 /*!
945     Returns the index of the current command. This is the command that will be
946     executed on the next call to redo(). It is not always the top-most command
947     on the stack, since a number of commands may have been undone.
948 
949     \sa undo() redo() count()
950 */
951 
index() const952 int KUndo2QStack::index() const
953 {
954     return m_index;
955 }
956 
957 /*!
958     Repeatedly calls undo() or redo() until the current command index reaches
959     \a idx. This function can be used to roll the state of the document forwards
960     of backwards. indexChanged() is emitted only once.
961 
962     \sa index() count() undo() redo()
963 */
964 
setIndex(int idx)965 void KUndo2QStack::setIndex(int idx)
966 {
967     if (!m_macro_stack.isEmpty()) {
968         qWarning("KUndo2QStack::setIndex(): cannot set index in the middle of a macro");
969         return;
970     }
971 
972     if (idx < 0)
973         idx = 0;
974     else if (idx > m_command_list.size())
975         idx = m_command_list.size();
976 
977     int i = m_index;
978     while (i < idx) {
979         m_command_list.at(i++)->redoMergedCommands();
980         notifySetIndexChangedOneCommand();
981     }
982     while (i > idx) {
983         m_command_list.at(--i)->undoMergedCommands();
984         notifySetIndexChangedOneCommand();
985     }
986 
987     setIndex(idx, false);
988 }
989 
990 
991 /**
992  * Called by setIndex after every command execution.  It is needed by
993  * Krita to insert barriers between different kind of commands
994  */
notifySetIndexChangedOneCommand()995 void KUndo2QStack::notifySetIndexChangedOneCommand()
996 {
997 }
998 
999 /*!
1000     Returns true if there is a command available for undo; otherwise returns false.
1001 
1002     This function returns false if the stack is empty, or if the bottom command
1003     on the stack has already been undone.
1004 
1005     Synonymous with index() == 0.
1006 
1007     \sa index() canRedo()
1008 */
1009 
canUndo() const1010 bool KUndo2QStack::canUndo() const
1011 {
1012     if (!m_macro_stack.isEmpty())
1013         return false;
1014     return m_index > 0;
1015 }
1016 
1017 /*!
1018     Returns true if there is a command available for redo; otherwise returns false.
1019 
1020     This function returns false if the stack is empty or if the top command
1021     on the stack has already been redone.
1022 
1023     Synonymous with index() == count().
1024 
1025     \sa index() canUndo()
1026 */
1027 
canRedo() const1028 bool KUndo2QStack::canRedo() const
1029 {
1030     if (!m_macro_stack.isEmpty())
1031         return false;
1032     return m_index < m_command_list.size();
1033 }
1034 
1035 /*!
1036     Returns the text of the command which will be undone in the next call to undo().
1037 
1038     \sa KUndo2Command::text() redoActionText() undoItemText()
1039 */
1040 
undoText() const1041 QString KUndo2QStack::undoText() const
1042 {
1043     if (!m_macro_stack.isEmpty())
1044         return QString();
1045     if (m_index > 0 && m_command_list.at(m_index-1)!=0)
1046 
1047         return m_command_list.at(m_index - 1)->actionText();
1048     return QString();
1049 }
1050 
1051 /*!
1052     Returns the text of the command which will be redone in the next call to redo().
1053 
1054     \sa KUndo2Command::text() undoActionText() redoItemText()
1055 */
1056 
redoText() const1057 QString KUndo2QStack::redoText() const
1058 {
1059     if (!m_macro_stack.isEmpty())
1060         return QString();
1061     if (m_index < m_command_list.size())
1062         return m_command_list.at(m_index)->actionText();
1063     return QString();
1064 }
1065 
1066 #ifndef QT_NO_ACTION
1067 
1068 /*!
1069     Creates an undo QAction object with the given \a parent.
1070 
1071     Triggering this action will cause a call to undo(). The text of this action
1072     is the text of the command which will be undone in the next call to undo(),
1073     prefixed by the specified \a prefix. If there is no command available for undo,
1074     this action will be disabled.
1075 
1076     If \a prefix is empty, the default prefix "Undo" is used.
1077 
1078     \sa createRedoAction(), canUndo(), KUndo2Command::text()
1079 */
1080 
createUndoAction(QObject * parent) const1081 QAction *KUndo2QStack::createUndoAction(QObject *parent) const
1082 {
1083     KUndo2Action *result = new KUndo2Action(i18n("Undo %1"), i18nc("Default text for undo action", "Undo"), parent);
1084     result->setEnabled(canUndo());
1085     result->setPrefixedText(undoText());
1086     connect(this, &KUndo2QStack::canUndoChanged,
1087             result, &QAction::setEnabled);
1088     connect(this, &KUndo2QStack::undoTextChanged,
1089             result, &KUndo2Action::setPrefixedText);
1090     connect(result, &QAction::triggered, this, &KUndo2QStack::undo);
1091     return result;
1092 }
1093 
1094 /*!
1095     Creates an redo QAction object with the given \a parent.
1096 
1097     Triggering this action will cause a call to redo(). The text of this action
1098     is the text of the command which will be redone in the next call to redo(),
1099     prefixed by the specified \a prefix. If there is no command available for redo,
1100     this action will be disabled.
1101 
1102     If \a prefix is empty, the default prefix "Redo" is used.
1103 
1104     \sa createUndoAction(), canRedo(), KUndo2Command::text()
1105 */
1106 
createRedoAction(QObject * parent) const1107 QAction *KUndo2QStack::createRedoAction(QObject *parent) const
1108 {
1109     KUndo2Action *result = new KUndo2Action(i18n("Redo %1"), i18nc("Default text for redo action", "Redo"), parent);
1110     result->setEnabled(canRedo());
1111     result->setPrefixedText(redoText());
1112     connect(this, &KUndo2QStack::canRedoChanged,
1113             result, &QAction::setEnabled);
1114     connect(this, &KUndo2QStack::redoTextChanged,
1115             result, &KUndo2Action::setPrefixedText);
1116     connect(result, &QAction::triggered, this, &KUndo2QStack::redo);
1117     return result;
1118 }
1119 
1120 #endif // QT_NO_ACTION
1121 
1122 /*!
1123     Begins composition of a macro command with the given \a text description.
1124 
1125     An empty command described by the specified \a text is pushed on the stack.
1126     Any subsequent commands pushed on the stack will be appended to the empty
1127     command's children until endMacro() is called.
1128 
1129     Calls to beginMacro() and endMacro() may be nested, but every call to
1130     beginMacro() must have a matching call to endMacro().
1131 
1132     While a macro is composed, the stack is disabled. This means that:
1133     \list
1134     \i indexChanged() and cleanChanged() are not emitted,
1135     \i canUndo() and canRedo() return false,
1136     \i calling undo() or redo() has no effect,
1137     \i the undo/redo actions are disabled.
1138     \endlist
1139 
1140     The stack becomes enabled and appropriate signals are emitted when endMacro()
1141     is called for the outermost macro.
1142 
1143     \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 4
1144 
1145     This code is equivalent to:
1146 
1147     \snippet doc/src/snippets/code/src_gui_util_qundostack.cpp 5
1148 
1149     \sa endMacro()
1150 */
1151 
beginMacro(const KUndo2MagicString & text)1152 void KUndo2QStack::beginMacro(const KUndo2MagicString &text)
1153 {
1154     KUndo2Command *cmd = new KUndo2Command();
1155     cmd->setText(text);
1156 
1157     if (m_macro_stack.isEmpty()) {
1158         while (m_index < m_command_list.size())
1159             delete m_command_list.takeLast();
1160         if (m_clean_index > m_index)
1161             m_clean_index = -1; // we've deleted the clean state
1162         m_command_list.append(cmd);
1163     } else {
1164         m_macro_stack.last()->d->child_list.append(cmd);
1165     }
1166     m_macro_stack.append(cmd);
1167 
1168     if (m_macro_stack.count() == 1) {
1169         emit canUndoChanged(false);
1170         emit undoTextChanged(QString());
1171         emit canRedoChanged(false);
1172         emit redoTextChanged(QString());
1173     }
1174 }
1175 
1176 /*!
1177     Ends composition of a macro command.
1178 
1179     If this is the outermost macro in a set nested macros, this function emits
1180     indexChanged() once for the entire macro command.
1181 
1182     \sa beginMacro()
1183 */
1184 
endMacro()1185 void KUndo2QStack::endMacro()
1186 {
1187     if (m_macro_stack.isEmpty()) {
1188         qWarning("KUndo2QStack::endMacro(): no matching beginMacro()");
1189         return;
1190     }
1191 
1192     m_macro_stack.removeLast();
1193 
1194     if (m_macro_stack.isEmpty()) {
1195         checkUndoLimit();
1196         setIndex(m_index + 1, false);
1197     }
1198 }
1199 
1200 /*!
1201   \since 4.4
1202 
1203   Returns a const pointer to the command at \a index.
1204 
1205   This function returns a const pointer, because modifying a command,
1206   once it has been pushed onto the stack and executed, almost always
1207   causes corruption of the state of the document, if the command is
1208   later undone or redone.
1209 
1210   \sa KUndo2Command::child()
1211 */
command(int index) const1212 const KUndo2Command *KUndo2QStack::command(int index) const
1213 {
1214     if (index < 0 || index >= m_command_list.count())
1215         return 0;
1216     return m_command_list.at(index);
1217 }
1218 
1219 /*!
1220     Returns the text of the command at index \a idx.
1221 
1222     \sa beginMacro()
1223 */
1224 
text(int idx) const1225 QString KUndo2QStack::text(int idx) const
1226 {
1227     if (idx < 0 || idx >= m_command_list.size())
1228         return QString();
1229     return m_command_list.at(idx)->text().toString();
1230 }
1231 
1232 /*!
1233     \property KUndo2QStack::undoLimit
1234     \brief the maximum number of commands on this stack.
1235     \since 4.3
1236 
1237     When the number of commands on a stack exceedes the stack's undoLimit, commands are
1238     deleted from the bottom of the stack. Macro commands (commands with child commands)
1239     are treated as one command. The default value is 0, which means that there is no
1240     limit.
1241 
1242     This property may only be set when the undo stack is empty, since setting it on a
1243     non-empty stack might delete the command at the current index. Calling setUndoLimit()
1244     on a non-empty stack prints a warning and does nothing.
1245 */
1246 
setUndoLimit(int limit)1247 void KUndo2QStack::setUndoLimit(int limit)
1248 {
1249     if (!m_command_list.isEmpty()) {
1250         qWarning("KUndo2QStack::setUndoLimit(): an undo limit can only be set when the stack is empty");
1251         return;
1252     }
1253 
1254     if (limit == m_undo_limit)
1255         return;
1256     m_undo_limit = limit;
1257     checkUndoLimit();
1258     emit undoLimitChanged(m_undo_limit);
1259 }
1260 
undoLimit() const1261 int KUndo2QStack::undoLimit() const
1262 {
1263     return m_undo_limit;
1264 }
1265 
1266 /*!
1267     \property KUndo2QStack::active
1268     \brief the active status of this stack.
1269 
1270     An application often has multiple undo stacks, one for each opened document. The active
1271     stack is the one associated with the currently active document. If the stack belongs
1272     to a KUndo2Group, calls to KUndo2Group::undo() or KUndo2Group::redo() will be forwarded
1273     to this stack when it is active. If the KUndo2Group is watched by a KUndo2View, the view
1274     will display the contents of this stack when it is active. If the stack does not belong to
1275     a KUndo2Group, making it active has no effect.
1276 
1277     It is the programmer's responsibility to specify which stack is active by
1278     calling setActive(), usually when the associated document window receives focus.
1279 
1280     \sa KUndo2Group
1281 */
1282 
setActive(bool active)1283 void KUndo2QStack::setActive(bool active)
1284 {
1285 #ifdef QT_NO_UNDOGROUP
1286     Q_UNUSED(active);
1287 #else
1288     bool prev = isActive();
1289     if (m_group != 0) {
1290         if (active)
1291             m_group->setActiveStack(this);
1292         else if (m_group->activeStack() == this)
1293             m_group->setActiveStack(0);
1294     }
1295     if (isActive() != prev) {
1296         emit activeChanged(!prev);
1297     }
1298 #endif
1299 }
1300 
isActive() const1301 bool KUndo2QStack::isActive() const
1302 {
1303 #ifdef QT_NO_UNDOGROUP
1304     return true;
1305 #else
1306     return m_group == 0 || m_group->activeStack() == this;
1307 #endif
1308 }
setUseCumulativeUndoRedo(bool value)1309 void KUndo2QStack::setUseCumulativeUndoRedo(bool value)
1310 {
1311     m_useCumulativeUndoRedo = value;
1312 }
1313 
useCumulativeUndoRedo()1314 bool KUndo2QStack::useCumulativeUndoRedo()
1315 {
1316     return m_useCumulativeUndoRedo;
1317 }
setTimeT1(double value)1318 void KUndo2QStack::setTimeT1(double value)
1319 {
1320     m_timeT1 = value;
1321 }
1322 
timeT1()1323 double KUndo2QStack::timeT1()
1324 {
1325     return m_timeT1;
1326 }
1327 
setTimeT2(double value)1328 void KUndo2QStack::setTimeT2(double value)
1329 {
1330     m_timeT2 = value;
1331 }
1332 
timeT2()1333 double KUndo2QStack::timeT2()
1334 {
1335     return m_timeT2;
1336 }
strokesN()1337 int KUndo2QStack::strokesN()
1338 {
1339     return m_strokesN;
1340 }
setStrokesN(int value)1341 void KUndo2QStack::setStrokesN(int value)
1342 {
1343     m_strokesN  = value;
1344 }
1345 
1346 
1347 
createRedoAction(KActionCollection * actionCollection,const QString & actionName)1348 QAction* KUndo2Stack::createRedoAction(KActionCollection* actionCollection, const QString& actionName)
1349 {
1350     QAction* action = KUndo2QStack::createRedoAction(actionCollection);
1351 
1352     if (actionName.isEmpty()) {
1353         action->setObjectName(KStandardAction::name(KStandardAction::Redo));
1354     } else {
1355         action->setObjectName(actionName);
1356     }
1357 
1358     action->setIcon(koIcon("edit-redo"));
1359     action->setIconText(i18n("Redo"));
1360     action->setShortcuts(KStandardShortcut::redo());
1361 
1362     actionCollection->addAction(action->objectName(), action);
1363 
1364     return action;
1365 }
1366 
createUndoAction(KActionCollection * actionCollection,const QString & actionName)1367 QAction* KUndo2Stack::createUndoAction(KActionCollection* actionCollection, const QString& actionName)
1368 {
1369     QAction* action = KUndo2QStack::createUndoAction(actionCollection);
1370 
1371     if (actionName.isEmpty()) {
1372         action->setObjectName(KStandardAction::name(KStandardAction::Undo));
1373     } else {
1374         action->setObjectName(actionName);
1375     }
1376 
1377     action->setIcon(koIcon("edit-undo"));
1378     action->setIconText(i18n("Undo"));
1379     action->setShortcuts(KStandardShortcut::undo());
1380 
1381     actionCollection->addAction(action->objectName(), action);
1382 
1383     return action;
1384 }
1385 
1386 /*!
1387     \fn void KUndo2QStack::indexChanged(int idx)
1388 
1389     This signal is emitted whenever a command modifies the state of the document.
1390     This happens when a command is undone or redone. When a macro
1391     command is undone or redone, or setIndex() is called, this signal
1392     is emitted only once.
1393 
1394     \a idx specifies the index of the current command, ie. the command which will be
1395     executed on the next call to redo().
1396 
1397     \sa index() setIndex()
1398 */
1399 
1400 /*!
1401     \fn void KUndo2QStack::cleanChanged(bool clean)
1402 
1403     This signal is emitted whenever the stack enters or leaves the clean state.
1404     If \a clean is true, the stack is in a clean state; otherwise this signal
1405     indicates that it has left the clean state.
1406 
1407     \sa isClean() setClean()
1408 */
1409 
1410 /*!
1411     \fn void KUndo2QStack::undoTextChanged(const QString &undoText)
1412 
1413     This signal is emitted whenever the value of undoText() changes. It is
1414     used to update the text property of the undo action returned by createUndoAction().
1415     \a undoText specifies the new text.
1416 */
1417 
1418 /*!
1419     \fn void KUndo2QStack::canUndoChanged(bool canUndo)
1420 
1421     This signal is emitted whenever the value of canUndo() changes. It is
1422     used to enable or disable the undo action returned by createUndoAction().
1423     \a canUndo specifies the new value.
1424 */
1425 
1426 /*!
1427     \fn void KUndo2QStack::redoTextChanged(const QString &redoText)
1428 
1429     This signal is emitted whenever the value of redoText() changes. It is
1430     used to update the text property of the redo action returned by createRedoAction().
1431     \a redoText specifies the new text.
1432 */
1433 
1434 /*!
1435     \fn void KUndo2QStack::canRedoChanged(bool canRedo)
1436 
1437     This signal is emitted whenever the value of canRedo() changes. It is
1438     used to enable or disable the redo action returned by createRedoAction().
1439     \a canRedo specifies the new value.
1440 */
1441 
KUndo2Stack(QObject * parent)1442 KUndo2Stack::KUndo2Stack(QObject *parent):
1443     KUndo2QStack(parent)
1444 {
1445 }
1446 
1447 #endif // QT_NO_UNDOSTACK
1448