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