LCOV - code coverage report
Current view: top level - src/engraving/editing/transaction - undostack.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 78.8 % 241 190
Test Date: 2026-11-19 04:14:36

            Line data    Source code
       1              : /*
       2              :  * SPDX-License-Identifier: GPL-3.0-only
       3              :  * MuseScore-Studio-CLA-applies
       4              :  *
       5              :  * MuseScore Studio
       6              :  * Music Composition & Notation
       7              :  *
       8              :  * Copyright (C) 2021 MuseScore Limited and others
       9              :  *
      10              :  * This program is free software: you can redistribute it and/or modify
      11              :  * it under the terms of the GNU General Public License version 3 as
      12              :  * published by the Free Software Foundation.
      13              :  *
      14              :  * This program is distributed in the hope that it will be useful,
      15              :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      16              :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      17              :  * GNU General Public License for more details.
      18              :  *
      19              :  * You should have received a copy of the GNU General Public License
      20              :  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
      21              :  */
      22              : 
      23              : /**
      24              :  \file
      25              :  Implementation of undo functions.
      26              : 
      27              :  The undo system requires calling startUndo() when starting a GUI command
      28              :  and calling endUndo() when ending the command. All changes to a score
      29              :  in response to a GUI command must be undoable/redoable by executing
      30              :  a sequence of low-level undo operations. This sequence is built by the code
      31              :  handling the command, by calling one or more undoOp()'s
      32              :  between startUndo() and endUndo().
      33              : */
      34              : 
      35              : #include "undostack.h"
      36              : 
      37              : #include "containers.h"
      38              : 
      39              : #include "dom/box.h"
      40              : #include "dom/select.h"
      41              : 
      42              : #include "editing/editproperty.h"
      43              : #include "editing/editstyle.h"
      44              : #include "editing/textedit.h"
      45              : #include "editing/transaction/undoablecommand.h"
      46              : 
      47              : #include "log.h"
      48              : 
      49              : #define LOG_UNDO() if constexpr (false) LOGD()
      50              : 
      51              : using namespace mu::engraving;
      52              : 
      53              : namespace mu::engraving {
      54              : extern Measure* tick2measure(int tick);
      55              : 
      56              : static const std::unordered_map<CommandType, CommandType> COMMAND_TYPE_INVERSION {
      57              :     { CommandType::AddElement, CommandType::RemoveElement },
      58              :     { CommandType::RemoveElement, CommandType::AddElement },
      59              : 
      60              :     { CommandType::AddBracket, CommandType::RemoveBracket },
      61              :     { CommandType::RemoveBracket, CommandType::AddBracket },
      62              : 
      63              :     { CommandType::AddExcerpt, CommandType::RemoveExcerpt },
      64              :     { CommandType::RemoveExcerpt, CommandType::AddExcerpt },
      65              : 
      66              :     { CommandType::AddSystemObjectStaff, CommandType::RemoveSystemObjectStaff },
      67              :     { CommandType::RemoveSystemObjectStaff, CommandType::AddSystemObjectStaff },
      68              : 
      69              :     { CommandType::InsertMeasures, CommandType::RemoveMeasures },
      70              :     { CommandType::RemoveMeasures, CommandType::InsertMeasures },
      71              : 
      72              :     { CommandType::InsertStaff, CommandType::RemoveStaff },
      73              :     { CommandType::RemoveStaff, CommandType::InsertStaff },
      74              : 
      75              :     { CommandType::InsertPart, CommandType::RemovePart },
      76              :     { CommandType::RemovePart, CommandType::InsertPart },
      77              : 
      78              :     { CommandType::Link, CommandType::Unlink },
      79              :     { CommandType::Unlink, CommandType::Link },
      80              : 
      81              :     { CommandType::AddNoteParenthesesInfo, CommandType::RemoveNoteParenthesesInfo },
      82              :     { CommandType::RemoveNoteParenthesesInfo, CommandType::AddNoteParenthesesInfo },
      83              : 
      84              :     { CommandType::ConnectSharedPart, CommandType::DisconnectSharedPart },
      85              :     { CommandType::DisconnectSharedPart, CommandType::ConnectSharedPart },
      86              : };
      87              : 
      88              : //---------------------------------------------------------
      89              : //   UndoStack
      90              : //---------------------------------------------------------
      91              : 
      92         2553 : UndoStack::UndoStack()
      93              : {
      94         2553 :     m_activeTransaction = nullptr;
      95         2553 :     m_currentIndex = 0;
      96         2553 :     m_cleanState = 0;
      97         2553 :     m_states.push_back(m_cleanState);
      98         2553 :     m_nextState = 1;
      99         2553 : }
     100              : 
     101         2327 : UndoStack::~UndoStack()
     102              : {
     103         2327 :     size_t idx = 0;
     104         3168 :     for (auto c : m_transactions) {
     105          841 :         c->cleanup(idx++ < m_currentIndex);
     106              :     }
     107         2327 :     muse::DeleteAll(m_transactions);
     108         2327 : }
     109              : 
     110         3074 : bool UndoStack::isLocked() const
     111              : {
     112         3074 :     return m_isLocked;
     113              : }
     114              : 
     115            0 : void UndoStack::setLocked(bool locked)
     116              : {
     117            0 :     m_isLocked = locked;
     118            0 : }
     119              : 
     120         1530 : void UndoStack::beginTransaction(Score* score, const TranslatableString& actionName)
     121              : {
     122         1530 :     if (m_isLocked) {
     123            0 :         return;
     124              :     }
     125              : 
     126         1530 :     IF_ASSERT_FAILED(!m_activeTransaction) {
     127            0 :         LOGE() << "Transaction already in progress";
     128            0 :         return;
     129              :     }
     130              : 
     131         1530 :     m_activeTransaction = new UndoableTransaction(score, actionName);
     132              : }
     133              : 
     134            7 : void UndoStack::remove(size_t idx)
     135              : {
     136            7 :     assert(idx <= m_currentIndex);
     137            7 :     assert(m_currentIndex != muse::nidx);
     138              :     // remove redo stack
     139           14 :     while (m_transactions.size() > m_currentIndex) {
     140            0 :         UndoableTransaction* transaction = muse::takeLast(m_transactions);
     141            0 :         m_states.pop_back();
     142            0 :         transaction->cleanup(false); // delete elements for which UndoableCommand() holds ownership
     143            0 :         delete transaction;
     144              : //            --curIdx;
     145              :     }
     146           18 :     while (m_transactions.size() > idx) {
     147            4 :         UndoableTransaction* transaction = muse::takeLast(m_transactions);
     148            4 :         m_states.pop_back();
     149            4 :         transaction->cleanup(true);
     150            4 :         delete transaction;
     151              :     }
     152            7 :     m_currentIndex = idx;
     153            7 : }
     154              : 
     155            6 : void UndoStack::mergeTransactions(size_t startIdx)
     156              : {
     157            6 :     assert(startIdx <= m_currentIndex);
     158              : 
     159            6 :     if (startIdx >= m_transactions.size()) {
     160            0 :         return;
     161              :     }
     162              : 
     163            6 :     UndoableTransaction* startTransaction = m_transactions[startIdx];
     164              : 
     165           10 :     for (size_t idx = startIdx + 1; idx < m_currentIndex; ++idx) {
     166            4 :         startTransaction->append(std::move(*m_transactions[idx]));
     167              :     }
     168            6 :     remove(startIdx + 1);   // TODO: remove from startIdx to curIdx only
     169              : }
     170              : 
     171         1533 : void UndoStack::endTransaction(bool rollback)
     172              : {
     173         1533 :     if (m_isLocked) {
     174            0 :         return;
     175              :     }
     176              : 
     177         1533 :     IF_ASSERT_FAILED(m_activeTransaction) {
     178            0 :         LOGE() << "No transaction in progress";
     179            0 :         return;
     180              :     }
     181              : 
     182         1533 :     if (rollback) {
     183          518 :         delete m_activeTransaction;
     184              :     } else {
     185              :         // remove redo stack
     186         2079 :         while (m_transactions.size() > m_currentIndex) {
     187           49 :             UndoableTransaction* transaction = muse::takeLast(m_transactions);
     188           49 :             m_states.pop_back();
     189           49 :             transaction->cleanup(false); // delete elements for which UndoableCommand() holds ownership
     190           49 :             delete transaction;
     191              :         }
     192         1015 :         m_transactions.push_back(m_activeTransaction);
     193         1015 :         m_states.push_back(m_nextState++);
     194         1015 :         ++m_currentIndex;
     195              :     }
     196         1533 :     m_activeTransaction = nullptr;
     197              : }
     198              : 
     199            4 : void UndoStack::reopen()
     200              : {
     201            4 :     if (m_isLocked) {
     202            0 :         return;
     203              :     }
     204              : 
     205              :     LOG_UNDO() << "curIdx: " << m_currentIndex << ", size: " << m_transactions.size();
     206            4 :     assert(m_activeTransaction == nullptr);
     207            4 :     assert(m_currentIndex > 0);
     208            4 :     --m_currentIndex;
     209            4 :     m_activeTransaction = muse::takeAt(m_transactions, m_currentIndex);
     210            4 :     m_states.erase(m_states.begin() + m_currentIndex + 1);
     211            4 :     for (auto i : m_activeTransaction->commands()) {
     212              :         LOG_UNDO() << "   " << i->name();
     213              :     }
     214              : }
     215              : 
     216          235 : void UndoStack::undo(EditData* ed)
     217              : {
     218              :     LOG_UNDO() << "called";
     219              :     // Are we currently editing text?
     220          235 :     if (ed && ed->element && ed->element->isTextBase()) {
     221            0 :         TextEditData* ted = dynamic_cast<TextEditData*>(ed->getData(ed->element).get());
     222            0 :         if (ted && ted->startUndoIdx == m_currentIndex) {
     223              :             // No edits to undo, so do nothing
     224            0 :             return;
     225              :         }
     226              :     }
     227          235 :     if (m_currentIndex) {
     228          235 :         --m_currentIndex;
     229          235 :         assert(m_currentIndex < m_transactions.size());
     230          235 :         m_transactions[m_currentIndex]->undo();
     231              :     }
     232              : }
     233              : 
     234           40 : void UndoStack::redo()
     235              : {
     236              :     LOG_UNDO() << "called";
     237           40 :     if (canRedo()) {
     238           40 :         m_transactions[m_currentIndex++]->redo();
     239              :     }
     240           40 : }
     241              : 
     242              : //---------------------------------------------------------
     243              : //   UndoableTransaction
     244              : //---------------------------------------------------------
     245              : 
     246         1530 : UndoableTransaction::UndoableTransaction(Score* s, const TranslatableString& actionName)
     247         1530 :     : m_undoInputState(s->inputState()), m_actionName(actionName), m_score(s)
     248              : {
     249         1530 :     fillSelectionInfo(m_undoSelectionInfo, s->selection());
     250         1530 : }
     251              : 
     252         1412 : UndoableTransaction::~UndoableTransaction()
     253              : {
     254        22101 :     for (UndoableCommand* command : m_commands) {
     255        20689 :         delete command;
     256              :     }
     257         1412 : }
     258              : 
     259          894 : void UndoableTransaction::cleanup(bool wasDone)
     260              : {
     261        21583 :     for (UndoableCommand* command : m_commands) {
     262        20689 :         command->cleanup(wasDone);
     263              :     }
     264          894 : }
     265              : 
     266            4 : void UndoableTransaction::unwind(bool cleanUp)
     267              : {
     268              :     // Undo everything first, without freeing: commands pushed later (e.g. AddElement for a part's linked
     269              :     // clone) may still be referenced by earlier commands' undo() (e.g. Link::undo()):
     270            4 :     std::vector<UndoableCommand*> undoneCommands;
     271            4 :     undoneCommands.reserve(m_commands.size());
     272            7 :     while (!m_commands.empty()) {
     273            3 :         UndoableCommand* command = muse::takeLast(m_commands);
     274              :         LOG_UNDO() << "unwind: " << command->name();
     275            3 :         command->undo();
     276            3 :         undoneCommands.push_back(command);
     277              :     }
     278              :     // Now we can free everything:
     279            7 :     for (UndoableCommand* command : undoneCommands) {
     280            3 :         if (cleanUp) {
     281            3 :             command->cleanup(false);
     282              :         }
     283            3 :         delete command;
     284              :     }
     285            4 : }
     286              : 
     287            4 : void UndoableTransaction::appendCommands(UndoableTransaction& other)
     288              : {
     289            4 :     m_commands.insert(m_commands.end(), other.m_commands.cbegin(), other.m_commands.cend());
     290            4 :     other.m_commands.clear();
     291            4 : }
     292              : 
     293            0 : bool UndoableTransaction::hasCommandsMatchingFilter(UndoableCommandFilter f, const EngravingItem* target) const
     294              : {
     295            0 :     for (UndoableCommand* command : m_commands) {
     296            0 :         if (command->matchesFilter(f, target)) {
     297            0 :             return true;
     298              :         }
     299              :     }
     300            0 :     return false;
     301              : }
     302              : 
     303            0 : bool UndoableTransaction::hasCommandsNotMatchingFilters(const std::vector<UndoableCommandFilter>& filters,
     304              :                                                         const EngravingItem* target) const
     305              : {
     306            0 :     for (UndoableCommand* command : m_commands) {
     307            0 :         bool filtered = false;
     308            0 :         for (UndoableCommandFilter f : filters) {
     309            0 :             if (command->matchesFilter(f, target)) {
     310            0 :                 filtered = true;
     311            0 :                 break;
     312              :             }
     313              :         }
     314            0 :         if (!filtered) {
     315            0 :             return true;
     316              :         }
     317              :     }
     318            0 :     return false;
     319              : }
     320              : 
     321            4 : void UndoableTransaction::removeCommandsMatchingFilter(UndoableCommandFilter f, EngravingItem* target)
     322              : {
     323            4 :     std::vector<UndoableCommand*> acceptedList;
     324           10 :     for (UndoableCommand* command : m_commands) {
     325            6 :         if (command->matchesFilter(f, target)) {
     326            6 :             delete command;
     327              :         } else {
     328            0 :             acceptedList.push_back(command);
     329              :         }
     330              :     }
     331            4 :     m_commands = std::move(acceptedList);
     332            4 : }
     333              : 
     334          910 : bool UndoableTransaction::canRecordSelectedElement(const EngravingItem* e)
     335              : {
     336          910 :     if (e->generated()) {
     337            5 :         return false;
     338              :     }
     339              : 
     340         1531 :     return e->isNote() || (e->isChordRest() && !e->isChord())
     341          543 :            || (e->isTextBase() && !e->isInstrumentName() && !e->isHammerOnPullOffText())
     342         1531 :            || e->isFretDiagram() || e->isSoundFlag();
     343              : }
     344              : 
     345         1805 : void UndoableTransaction::fillSelectionInfo(SelectionInfo& info, const Selection& sel)
     346              : {
     347         1805 :     info.staffStart = info.staffEnd = muse::nidx;
     348         1805 :     info.startBox = info.endBox = nullptr;
     349         1805 :     info.elements.clear();
     350              : 
     351         1805 :     if (sel.isList()) {
     352         1199 :         for (EngravingItem* e : sel.elements()) {
     353          910 :             if (canRecordSelectedElement(e)) {
     354          858 :                 info.elements.push_back(e);
     355              :             } else {
     356              :                 // don't remember selection we are unable to restore
     357           52 :                 info.elements.clear();
     358           52 :                 return;
     359              :             }
     360              :         }
     361         1464 :     } else if (sel.isRange()) {
     362          148 :         info.staffStart = sel.staffStart();
     363          148 :         info.staffEnd = sel.staffEnd();
     364          148 :         info.tickStart = sel.tickStart();
     365          148 :         info.tickEnd = sel.tickEnd();
     366          148 :         info.startBox = sel.startBox();
     367          148 :         info.endBox = sel.endBox();
     368              :     }
     369              : }
     370              : 
     371           83 : void UndoableTransaction::applySelectionInfo(const SelectionInfo& info, Selection& sel)
     372              : {
     373           83 :     if (!info.elements.empty()) {
     374          130 :         for (EngravingItem* e : info.elements) {
     375           81 :             sel.add(e);
     376              :         }
     377           34 :     } else if (info.staffStart != muse::nidx) {
     378           34 :         sel.setRangeTicks(info.tickStart, info.tickEnd, info.staffStart, info.staffEnd, info.startBox, info.endBox);
     379              :     }
     380           83 : }
     381              : 
     382          235 : void UndoableTransaction::undo()
     383              : {
     384          235 :     m_redoInputState = m_score->inputState();
     385          235 :     fillSelectionInfo(m_redoSelectionInfo, m_score->selection());
     386          235 :     m_score->deselectAll();
     387              : 
     388         3765 :     for (auto it = m_commands.rbegin(); it != m_commands.rend(); ++it) {
     389              :         LOG_UNDO() << "<" << (*it)->name() << ">";
     390         3530 :         (*it)->undo();
     391              :     }
     392              : 
     393          235 :     m_score->setInputState(m_undoInputState);
     394          235 :     if (m_undoSelectionInfo.isValid()) {
     395           64 :         m_score->deselectAll();
     396           64 :         applySelectionInfo(m_undoSelectionInfo, m_score->selection());
     397              :     }
     398          235 : }
     399              : 
     400           40 : void UndoableTransaction::redo()
     401              : {
     402           40 :     m_undoInputState = m_score->inputState();
     403           40 :     fillSelectionInfo(m_undoSelectionInfo, m_score->selection());
     404           40 :     m_score->deselectAll();
     405              : 
     406          522 :     for (UndoableCommand* command : m_commands) {
     407              :         LOG_UNDO() << "<" << command->name() << ">";
     408          482 :         command->redo();
     409              :     }
     410              : 
     411           40 :     m_score->setInputState(m_redoInputState);
     412           40 :     if (m_redoSelectionInfo.isValid()) {
     413           19 :         m_score->deselectAll();
     414           19 :         applySelectionInfo(m_redoSelectionInfo, m_score->selection());
     415              :     }
     416           40 : }
     417              : 
     418            4 : void UndoableTransaction::append(UndoableTransaction&& other)
     419              : {
     420            4 :     appendCommands(other);
     421            4 :     if (m_score == other.m_score) {
     422            4 :         m_redoInputState = std::move(other.m_redoInputState);
     423            4 :         m_redoSelectionInfo = std::move(other.m_redoSelectionInfo);
     424              :     }
     425            4 : }
     426              : 
     427            0 : const InputState& UndoableTransaction::undoInputState() const
     428              : {
     429            0 :     return m_undoInputState;
     430              : }
     431              : 
     432            0 : const InputState& UndoableTransaction::redoInputState() const
     433              : {
     434            0 :     return m_redoInputState;
     435              : }
     436              : 
     437            0 : void UndoableTransaction::excludeElementFromSelectionInfo(EngravingItem* element)
     438              : {
     439            0 :     if (m_undoSelectionInfo.isValid()) {
     440            0 :         muse::remove(m_undoSelectionInfo.elements, element);
     441              :     }
     442              : 
     443            0 :     if (m_redoSelectionInfo.isValid()) {
     444            0 :         muse::remove(m_redoSelectionInfo.elements, element);
     445              :     }
     446            0 : }
     447              : 
     448            0 : const UndoableTransaction::SelectionInfo& UndoableTransaction::undoSelectionInfo() const
     449              : {
     450            0 :     return m_undoSelectionInfo;
     451              : }
     452              : 
     453            0 : const UndoableTransaction::SelectionInfo& UndoableTransaction::redoSelectionInfo() const
     454              : {
     455            0 :     return m_redoSelectionInfo;
     456              : }
     457              : 
     458         1777 : UndoableTransaction::ChangesInfo UndoableTransaction::changesInfo(bool undo) const
     459              : {
     460         1777 :     ChangesInfo result;
     461              : 
     462        29024 :     for (const UndoableCommand* command : commands()) {
     463        27247 :         CommandType type = command->type();
     464              : 
     465        27247 :         if (type == CommandType::ChangeProperty) {
     466         2600 :             auto changeProperty = static_cast<const ChangeProperty*>(command);
     467         2600 :             result.changedPropertyIdSet.insert(changeProperty->getId());
     468        24647 :         } else if (type == CommandType::ChangeStyleValues) {
     469           77 :             auto changeStyle = static_cast<const ChangeStyleValues*>(command);
     470          155 :             for (const auto& pair : changeStyle->values()) {
     471           78 :                 result.changedStyleIdSet.insert(pair.first);
     472              :             }
     473        24570 :         } else if (type == CommandType::ChangeStyle) {
     474            1 :             auto changeStyle = static_cast<const ChangeStyle*>(command);
     475            1 :             const StyleIdSet styleIds = changeStyle->changedIds();
     476            1 :             result.changedStyleIdSet.insert(styleIds.cbegin(), styleIds.cend());
     477        24570 :         } else if (type == CommandType::TextEdit) {
     478           12 :             result.isTextEditing |= static_cast<const TextEditUndoableCommand*>(command)->cursor().editing();
     479              :         }
     480              : 
     481        27247 :         if (undo) {
     482         2310 :             auto it = COMMAND_TYPE_INVERSION.find(type);
     483         2310 :             if (it != COMMAND_TYPE_INVERSION.end()) {
     484         1204 :                 type = it->second;
     485              :             }
     486              :         }
     487              : 
     488        69474 :         for (EngravingObject* object : command->objectItems()) {
     489        42227 :             if (!object) {
     490           41 :                 continue;
     491              :             }
     492              : 
     493        42186 :             result.changedObjectTypes.insert(object->type());
     494        42186 :             result.changedObjects[object].insert(type);
     495        27247 :         }
     496              :     }
     497              : 
     498         1777 :     return result;
     499            0 : }
     500              : 
     501            0 : const TranslatableString& UndoableTransaction::actionName() const
     502              : {
     503            0 :     return m_actionName;
     504              : }
     505              : }
        

Generated by: LCOV version 2.0-1