LCOV - code coverage report
Current view: top level - src/engraving/editing - editpart.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 89.7 % 813 729
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) 2025 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              : #include "editpart.h"
      24              : 
      25              : #include <algorithm>
      26              : #include <map>
      27              : #include <unordered_set>
      28              : 
      29              : #include "containers.h"
      30              : #include "translation.h"
      31              : 
      32              : #include "addremoveelement.h"
      33              : #include "editexcerpt.h"
      34              : #include "editpagelocks.h"
      35              : #include "editscoreproperties.h"
      36              : #include "editstaff.h"
      37              : #include "editsystemlocks.h"
      38              : #include "transaction/transaction.h"
      39              : #include "transpose.h"
      40              : 
      41              : #include "../dom/excerpt.h"
      42              : #include "../dom/factory.h"
      43              : #include "../dom/instrchange.h"
      44              : #include "../dom/instrtemplate.h"
      45              : #include "../dom/scoreorder.h"
      46              : #include "../dom/masterscore.h"
      47              : #include "../dom/mscore.h"
      48              : #include "../dom/part.h"
      49              : #include "../dom/score.h"
      50              : #include "../dom/segment.h"
      51              : #include "../dom/staff.h"
      52              : #include "../dom/stafftype.h"
      53              : #include "../dom/stringtunings.h"
      54              : #include "../dom/utils.h"
      55              : 
      56              : #include "log.h"
      57              : 
      58              : using namespace mu::engraving;
      59              : 
      60              : //---------------------------------------------------------
      61              : //   InsertPart
      62              : //---------------------------------------------------------
      63              : 
      64          104 : InsertPart::InsertPart(Part* p, size_t targetPartIdx)
      65              : {
      66          104 :     m_part = p;
      67          104 :     m_targetPartIdx = targetPartIdx;
      68          104 : }
      69              : 
      70            7 : void InsertPart::undo()
      71              : {
      72            7 :     m_part->score()->removePart(m_part);
      73            7 : }
      74              : 
      75          105 : void InsertPart::redo()
      76              : {
      77          105 :     m_part->score()->insertPart(m_part, m_targetPartIdx);
      78          105 : }
      79              : 
      80          101 : void InsertPart::cleanup(bool wasDone)
      81              : {
      82          101 :     if (!wasDone) {
      83            6 :         delete m_part;
      84            6 :         m_part = nullptr;
      85              :     }
      86          101 : }
      87              : 
      88              : //---------------------------------------------------------
      89              : //   RemovePart
      90              : //---------------------------------------------------------
      91              : 
      92           14 : RemovePart::RemovePart(Part* p, size_t partIdx)
      93              : {
      94           14 :     m_part = p;
      95           14 :     m_partIdx = partIdx;
      96              : 
      97           14 :     if (m_partIdx == muse::nidx) {
      98            0 :         m_partIdx = muse::indexOf(m_part->score()->parts(), m_part);
      99              :     }
     100           14 : }
     101              : 
     102            5 : void RemovePart::undo()
     103              : {
     104            5 :     m_part->score()->insertPart(m_part, m_partIdx);
     105            5 : }
     106              : 
     107           14 : void RemovePart::redo()
     108              : {
     109           14 :     m_part->score()->removePart(m_part);
     110           14 : }
     111              : 
     112            9 : void RemovePart::cleanup(bool wasDone)
     113              : {
     114            9 :     if (wasDone) {
     115            4 :         delete m_part;
     116            4 :         m_part = nullptr;
     117              :     }
     118            9 : }
     119              : 
     120              : //---------------------------------------------------------
     121              : //   SetSoloist
     122              : //---------------------------------------------------------
     123              : 
     124            1 : SetSoloist::SetSoloist(Part* p, bool b)
     125              : {
     126            1 :     part = p;
     127            1 :     soloist  = b;
     128            1 : }
     129              : 
     130            0 : void SetSoloist::undo()
     131              : {
     132            0 :     part->setSoloist(!soloist);
     133            0 : }
     134              : 
     135            1 : void SetSoloist::redo()
     136              : {
     137            1 :     part->setSoloist(soloist);
     138            1 : }
     139              : 
     140              : //---------------------------------------------------------
     141              : //   ChangePart
     142              : //---------------------------------------------------------
     143              : 
     144           11 : ChangePart::ChangePart(Part* _part, Instrument* i)
     145              : {
     146           11 :     instrument = i;
     147           11 :     part       = _part;
     148           11 : }
     149              : 
     150           16 : void ChangePart::flip()
     151              : {
     152           16 :     Instrument* oi = part->instrument(); //tick?
     153           16 :     part->setInstrument(instrument);
     154              : 
     155           16 :     part->updateHarmonyChannels(false);
     156              : 
     157           16 :     Score* score = part->score();
     158           16 :     score->masterScore()->rebuildMidiMapping();
     159           16 :     score->setInstrumentsChanged(true);
     160              : 
     161              :     // check if notes need to be updated
     162              :     // true if changing into or away from TAB or from one TAB type to another
     163              : 
     164           16 :     score->setLayoutAll();
     165              : 
     166           16 :     instrument = oi;
     167           16 : }
     168              : 
     169           10 : void ChangePart::cleanup(bool)
     170              : {
     171           10 :     delete instrument;
     172           10 :     instrument = nullptr;
     173           10 : }
     174              : 
     175              : //---------------------------------------------------------
     176              : //   ChangeInstrumentLong
     177              : //---------------------------------------------------------
     178              : 
     179            3 : ChangeInstrumentLong::ChangeInstrumentLong(const Fraction& _tick, Part* p, const String& t)
     180            3 :     : part(p), tick(_tick), longName(t)
     181              : {
     182            3 : }
     183              : 
     184            4 : void ChangeInstrumentLong::flip()
     185              : {
     186            4 :     String s = part->longName(tick);
     187            4 :     part->setLongName(longName, tick);
     188            4 :     longName = s;
     189            4 :     part->score()->setLayoutAll();
     190            4 : }
     191              : 
     192              : //---------------------------------------------------------
     193              : //   ChangeInstrumentShort
     194              : //---------------------------------------------------------
     195              : 
     196            2 : ChangeInstrumentShort::ChangeInstrumentShort(const Fraction& _tick, Part* p, const String& t)
     197            2 :     : part(p), tick(_tick), shortName(t)
     198              : {
     199            2 : }
     200              : 
     201            3 : void ChangeInstrumentShort::flip()
     202              : {
     203            3 :     String s = part->shortName(tick);
     204            3 :     part->setShortName(shortName, tick);
     205            3 :     shortName = s;
     206            3 :     part->score()->setLayoutAll();
     207            3 : }
     208              : 
     209              : //---------------------------------------------------------
     210              : //   ChangeInstrumentLong
     211              : //---------------------------------------------------------
     212              : 
     213            1 : ChangeInstrumentGroupOptions::ChangeInstrumentGroupOptions(const Fraction& _tick, Part* p, bool useCustom, const String& longName,
     214            1 :                                                            const String& shortName)
     215            1 :     : part(p), tick(_tick), useCustom(useCustom), longName(longName), shortName(shortName)
     216              : {
     217            1 : }
     218              : 
     219            1 : void ChangeInstrumentGroupOptions::flip()
     220              : {
     221            1 :     InstrumentLabel& label = part->instrument(tick)->instrumentLabel();
     222              : 
     223            1 :     bool curUseCustom = label.useCustomGroupName();
     224            1 :     const String& curLong = label.customNameLongGroup();
     225            1 :     const String& curShort = label.customNameShortGroup();
     226              : 
     227            1 :     label.setUseCustomGroupName(useCustom);
     228            1 :     label.setCustomNameLongGroup(longName);
     229            1 :     label.setCustomNameShortGroup(shortName);
     230              : 
     231            1 :     useCustom = curUseCustom;
     232            1 :     longName = curLong;
     233            1 :     shortName = curShort;
     234              : 
     235            1 :     part->score()->setLayoutAll();
     236            1 : }
     237              : 
     238            2 : ChangeInstrumentNumber::ChangeInstrumentNumber(const Fraction& _tick, Part* p, int v)
     239            2 :     : part(p), tick(_tick), number(v)
     240              : {
     241            2 : }
     242              : 
     243            2 : void ChangeInstrumentNumber::flip()
     244              : {
     245            2 :     int v = part->number(tick);
     246            2 :     part->setNumber(number, tick);
     247            2 :     number = v;
     248            2 :     part->score()->setLayoutAll();
     249            2 : }
     250              : 
     251              : //---------------------------------------------------------
     252              : //   ChangeDrumset
     253              : //---------------------------------------------------------
     254              : 
     255            7 : void ChangeDrumset::flip()
     256              : {
     257            7 :     Drumset d = instrument->drumset() ? *instrument->drumset() : Drumset();
     258            7 :     instrument->setDrumset(&drumset);
     259            7 :     drumset = d;
     260              : 
     261            7 :     if (part->staves().size() > 0) {
     262            7 :         part->score()->setLayout(Fraction(0, 1), part->score()->endTick(), part->staves().front()->idx(), part->staves().back()->idx());
     263              :     }
     264            7 : }
     265              : 
     266              : //---------------------------------------------------------
     267              : //   ChangeStringData
     268              : //---------------------------------------------------------
     269              : 
     270            2 : void ChangeStringData::flip()
     271              : {
     272            2 :     const StringData* stringData =  m_stringTunings ? m_stringTunings->stringData() : m_instrument->stringData();
     273            2 :     int frets = stringData->frets();
     274            2 :     std::vector<instrString> stringList = stringData->stringList();
     275              : 
     276            2 :     if (m_stringTunings) {
     277            0 :         m_stringTunings->setStringData(m_stringData);
     278              :     } else {
     279            2 :         m_instrument->setStringData(m_stringData);
     280              :     }
     281              : 
     282            2 :     m_stringData.set(StringData(frets, stringList));
     283            2 : }
     284              : 
     285              : //---------------------------------------------------------
     286              : //   ChangePatch
     287              : //---------------------------------------------------------
     288              : 
     289            3 : void ChangePatch::flip()
     290              : {
     291            3 :     MidiPatch op;
     292            3 :     op.prog          = channel->program();
     293            3 :     op.bank          = channel->bank();
     294            3 :     op.synti         = channel->synti();
     295              : 
     296            3 :     channel->setProgram(patch.prog);
     297            3 :     channel->setBank(patch.bank);
     298            3 :     channel->setSynti(patch.synti);
     299              : 
     300            3 :     patch            = op;
     301              : 
     302              :     //! TODO Needs porting for MU4
     303              : //    if (MScore::seq == 0) {
     304              : //        LOGW("no seq");
     305              : //        return;
     306              : //    }
     307              : //
     308              : //    NPlayEvent event;
     309              : //    event.setType(ME_CONTROLLER);
     310              : //    event.setChannel(channel->channel());
     311              : //
     312              : //    int hbank = (channel->bank() >> 7) & 0x7f;
     313              : //    int lbank = channel->bank() & 0x7f;
     314              : //
     315              : //    event.setController(CTRL_HBANK);
     316              : //    event.setValue(hbank);
     317              : //    MScore::seq->sendEvent(event);
     318              : //
     319              : //    event.setController(CTRL_LBANK);
     320              : //    event.setValue(lbank);
     321              : //    MScore::seq->sendEvent(event);
     322              : //
     323              : //    event.setController(CTRL_PROGRAM);
     324              : //    event.setValue(channel->program());
     325              : //
     326            3 :     score->setInstrumentsChanged(true);
     327              : //
     328              : //    MScore::seq->sendEvent(event);
     329            3 : }
     330              : 
     331              : //---------------------------------------------------------
     332              : //   SetUserBankController
     333              : //---------------------------------------------------------
     334              : 
     335            2 : void SetUserBankController::flip()
     336              : {
     337            2 :     bool oldVal = channel->userBankController();
     338            2 :     channel->setUserBankController(val);
     339            2 :     val = oldVal;
     340            2 : }
     341              : 
     342              : //---------------------------------------------------------
     343              : //   findInstrumentChange
     344              : //   Helper function to find InstrumentChange element at a given tick
     345              : //---------------------------------------------------------
     346              : 
     347            3 : static InstrumentChange* findInstrumentChange(Score* score, const Part* part, const Fraction& tick)
     348              : {
     349            3 :     const Segment* segment = score->tick2segment(tick, true, SegmentType::ChordRest);
     350            3 :     if (!segment) {
     351            0 :         return nullptr;
     352              :     }
     353              : 
     354            3 :     const TrackRange trackRange = part->trackRange();
     355            3 :     EngravingItem* item = segment->findAnnotation(ElementType::INSTRUMENT_CHANGE, trackRange.startTrack, trackRange.endTrack - 1);
     356            3 :     return item ? toInstrumentChange(item) : nullptr;
     357              : }
     358              : 
     359           27 : static std::vector<Score*> excerptScores(const Score* score)
     360              : {
     361           27 :     std::vector<Score*> result;
     362           27 :     if (!score->isMaster()) {
     363            1 :         return result;
     364              :     }
     365              : 
     366           38 :     for (const Excerpt* excerpt : score->masterScore()->excerpts()) {
     367           12 :         if (Score* excerptScore = excerpt->excerptScore()) {
     368           12 :             result.push_back(excerptScore);
     369              :         }
     370              :     }
     371              : 
     372           26 :     return result;
     373            0 : }
     374              : 
     375            2 : static std::vector<Part*> partsIn(const Score* score, const std::vector<Part*>& parts)
     376              : {
     377            2 :     std::vector<Part*> result;
     378            4 :     for (const Part* part : parts) {
     379            2 :         if (Part* scorePart = score->partById(part->id())) {
     380            1 :             result.push_back(scorePart);
     381              :         }
     382              :     }
     383              : 
     384            2 :     return result;
     385            0 : }
     386              : 
     387            1 : static std::vector<Staff*> stavesIn(const Score* score, const std::vector<Staff*>& staves)
     388              : {
     389            1 :     std::vector<Staff*> result;
     390            2 :     for (const Staff* staff : staves) {
     391            1 :         if (Staff* scoreStaff = staff->findLinkedInScore(score)) {
     392            1 :             result.push_back(scoreStaff);
     393              :         }
     394              :     }
     395              : 
     396            1 :     return result;
     397            0 : }
     398              : 
     399            4 : EditPart::SetPartsResult EditPart::setParts(Score* score, const std::vector<PartEntry>& entries, const ScoreOrder& order)
     400              : {
     401            4 :     if (!score) {
     402            0 :         return {};
     403              :     }
     404              : 
     405            4 :     const KeyList keyList = score->keyList();
     406              : 
     407            4 :     SetPartsResult result;
     408              : 
     409            4 :     setScoreOrder(score, order);
     410            4 :     result.removedParts = removeMissingParts(score, entries);
     411            4 :     result.addedParts = insertNewParts(score, entries, keyList);
     412            4 :     updateSoloist(score, entries);
     413            4 :     sortParts(score, entries);
     414            4 :     score->setBracketsAndBarlines();
     415              : 
     416            4 :     return result;
     417            4 : }
     418              : 
     419            6 : void EditPart::setScoreOrder(Score* score, const ScoreOrder& order)
     420              : {
     421            6 :     if (!score) {
     422            0 :         return;
     423              :     }
     424              : 
     425            6 :     score->undo(new ChangeScoreOrder(score, order));
     426            6 :     ScoreOrder mutableOrder = order;
     427            6 :     mutableOrder.setBracketsAndBarlines(score);
     428            6 : }
     429              : 
     430           10 : void EditPart::setPartVisible(Score* score, Part* part, bool visible)
     431              : {
     432           10 :     if (!score || !part) {
     433            0 :         return;
     434              :     }
     435              : 
     436           10 :     part->undoChangeProperty(Pid::VISIBLE, visible);
     437              : 
     438           10 :     if (visible) {
     439            4 :         removeLocksContainingMMRests(score);
     440              :     }
     441              : }
     442              : 
     443            7 : bool EditPart::setVoiceVisible(Score* score, Staff* staff, int voiceIndex, bool visible)
     444              : {
     445            7 :     if (!score || !staff) {
     446            0 :         return false;
     447              :     }
     448              : 
     449            7 :     if (!score->excerpt()) {
     450            3 :         return false;
     451              :     }
     452              : 
     453            4 :     if (!visible && !staff->canDisableVoice()) {
     454            1 :         return false;
     455              :     }
     456              : 
     457            3 :     score->excerpt()->setVoiceVisible(staff, voiceIndex, visible);
     458            3 :     return true;
     459              : }
     460              : 
     461            3 : void EditPart::setStaffVisible(Score* score, Staff* staff, bool visible)
     462              : {
     463            3 :     if (!score || !staff) {
     464            0 :         return;
     465              :     }
     466              : 
     467            3 :     staff->undoChangeProperty(Pid::VISIBLE, visible);
     468              : }
     469              : 
     470            2 : void EditPart::setPartSharpFlat(Score* score, Part* part, PreferSharpFlat sharpFlat)
     471              : {
     472            2 :     if (!score || !part) {
     473            0 :         return;
     474              :     }
     475              : 
     476            2 :     Interval oldTransposition = part->staff(0)->transpose(Fraction(0, 1));
     477              : 
     478            2 :     part->undoChangeProperty(Pid::PREFER_SHARP_FLAT, int(sharpFlat));
     479              : 
     480            2 :     Transaction& tx = score->transactionManager()->currentOrDummyTransaction();
     481            2 :     Transpose::transpositionChanged(tx, score, part, oldTransposition);
     482              : }
     483              : 
     484            3 : void EditPart::setInstrumentName(Score* score, Part* part, const Fraction& tick, const String& name)
     485              : {
     486            3 :     if (!score || !part) {
     487            0 :         return;
     488              :     }
     489              : 
     490            3 :     score->undo(new ChangeInstrumentLong(tick, part, name));
     491              : }
     492              : 
     493            2 : void EditPart::setInstrumentAbbreviature(Score* score, Part* part, const Fraction& tick, const String& abbreviature)
     494              : {
     495            2 :     if (!score || !part) {
     496            0 :         return;
     497              :     }
     498              : 
     499            2 :     score->undo(new ChangeInstrumentShort(tick, part, abbreviature));
     500              : }
     501              : 
     502            2 : bool EditPart::setInstrumentGroupNameOptions(Score* score, Part* part, const Fraction& tick, bool useCustom, const String& longName,
     503              :                                              const String& shortName)
     504              : {
     505            2 :     if (!score || !part) {
     506            0 :         return false;
     507              :     }
     508              : 
     509            2 :     const Instrument* instrument = part->instrument(tick);
     510            2 :     if (!instrument) {
     511            0 :         return false;
     512              :     }
     513              : 
     514            2 :     const InstrumentLabel& label = instrument->instrumentLabel();
     515            3 :     if (label.useCustomGroupName() == useCustom && label.customNameLongGroup() == longName
     516            3 :         && label.customNameShortGroup() == shortName) {
     517            1 :         return false;
     518              :     }
     519              : 
     520            1 :     score->undo(new ChangeInstrumentGroupOptions(tick, part, useCustom, longName, shortName));
     521            1 :     return true;
     522              : }
     523              : 
     524            2 : void EditPart::setInstrumentNumber(Score* score, Part* part, const Fraction& tick, int number)
     525              : {
     526            2 :     if (!score || !part) {
     527            0 :         return;
     528              :     }
     529              : 
     530            2 :     score->undo(new ChangeInstrumentNumber(tick, part, number));
     531              : }
     532              : 
     533            3 : void EditPart::setStaffType(Score* score, Staff* staff, StaffTypes typeId)
     534              : {
     535            3 :     if (!score || !staff) {
     536            0 :         return;
     537              :     }
     538              : 
     539            3 :     const StaffType* staffType = StaffType::preset(typeId);
     540            3 :     if (!staffType) {
     541            0 :         return;
     542              :     }
     543              : 
     544            3 :     score->undo(new ChangeStaffType(staff, *staffType));
     545              : }
     546              : 
     547            2 : void EditPart::setStaffConfig(Score* score, Staff* staff, const StaffConfig& config, const Fraction& tick)
     548              : {
     549            2 :     if (!score || !staff || !staff->staffType(tick)) {
     550            0 :         return;
     551              :     }
     552              : 
     553            2 :     const bool becomesVisible = config.visible && !staff->visible();
     554              : 
     555            2 :     score->undo(new ChangeStaff(staff, config.visible, config.clefTypeList, config.userDistance, config.cutaway,
     556            2 :                                 config.hideSystemBarline, config.mergeMatchingRests, config.reflectTranspositionInLinkedTab));
     557              : 
     558            2 :     score->undo(new ChangeStaffType(staff, config.staffType, tick));
     559              : 
     560            2 :     if (becomesVisible) {
     561            1 :         removeLocksContainingMMRests(score);
     562              :     }
     563              : }
     564              : 
     565            1 : void EditPart::setSharedPartEnabled(Score* score, Part* part, bool enabled)
     566              : {
     567            1 :     if (!score || !part) {
     568            0 :         return;
     569              :     }
     570              : 
     571            1 :     part->undoChangeProperty(Pid::SHARED_PART_ENABLED, enabled);
     572              : }
     573              : 
     574            8 : void EditPart::removeParts(Score* score, const std::vector<Part*>& parts)
     575              : {
     576            8 :     if (!score || parts.empty()) {
     577            3 :         return;
     578              :     }
     579              : 
     580            5 :     doRemoveParts(score, parts);
     581              : 
     582            5 :     if (score->isMaster()) {
     583            4 :         deleteExcerptsOfParts(score->masterScore(), parts);
     584              :     }
     585              : 
     586            7 :     for (Score* excerptScore : excerptScores(score)) {
     587            2 :         const std::vector<Part*> excerptParts = partsIn(excerptScore, parts);
     588            2 :         if (!excerptParts.empty()) {
     589            1 :             doRemoveParts(excerptScore, excerptParts);
     590              :         }
     591            7 :     }
     592              : }
     593              : 
     594            2 : void EditPart::removeStaves(Score* score, const std::vector<Staff*>& staves)
     595              : {
     596            2 :     if (!score || staves.empty()) {
     597            0 :         return;
     598              :     }
     599              : 
     600            2 :     doRemoveStaves(score, staves);
     601              : 
     602            3 :     for (Score* excerptScore : excerptScores(score)) {
     603            1 :         const std::vector<Staff*> excerptStaves = stavesIn(excerptScore, staves);
     604            1 :         if (!excerptStaves.empty()) {
     605            1 :             doRemoveStaves(excerptScore, excerptStaves);
     606              :         }
     607            3 :     }
     608              : }
     609              : 
     610            4 : bool EditPart::reorderPartsChangesScore(const Score* score, const std::vector<Part*>& parts,
     611              :                                         const std::vector<SystemObjectsMove>& moves)
     612              : {
     613            4 :     if (!score || score->staves().empty()) {
     614            0 :         return false;
     615              :     }
     616              : 
     617            4 :     const std::vector<Part*>& scoreParts = score->parts();
     618            4 :     if (parts.size() == scoreParts.size() && !std::equal(parts.begin(), parts.end(), scoreParts.begin())) {
     619            1 :         return true;
     620              :     }
     621              : 
     622            3 :     if (moves.empty()) {
     623            1 :         return false;
     624              :     }
     625              : 
     626            2 :     const Staff* bottomStaff = score->staves().back();
     627            2 :     const bool currentBelowBottomStaff = score->style().styleB(Sid::systemObjectsBelowBottomStaff);
     628            2 :     bool belowBottomStaff = currentBelowBottomStaff;
     629              : 
     630            3 :     for (const SystemObjectsMove& move : moves) {
     631            2 :         if (move.staff != (move.belowBottomStaff ? bottomStaff : move.destination)) {
     632            1 :             return true;
     633              :         }
     634              : 
     635            1 :         if (move.staff == bottomStaff) {
     636            0 :             belowBottomStaff = move.belowBottomStaff;
     637              :         }
     638              :     }
     639              : 
     640            1 :     return (belowBottomStaff && bottomStaff->isSystemObjectStaff()) != currentBelowBottomStaff;
     641              : }
     642              : 
     643            4 : void EditPart::reorderParts(Score* score, const std::vector<Part*>& parts, const std::vector<SystemObjectsMove>& moves)
     644              : {
     645            4 :     if (!score || score->staves().empty()) {
     646            0 :         return;
     647              :     }
     648              : 
     649            4 :     doReorderParts(score, parts, moves);
     650              : 
     651            4 :     Staff* scoreBottomStaff = score->staves().back();
     652              : 
     653              :     // part scores keep their own instrument order, only the markings move
     654            5 :     for (Score* excerptScore : excerptScores(score)) {
     655            1 :         if (excerptScore->staves().empty()) {
     656            0 :             continue;
     657              :         }
     658              : 
     659            1 :         const Staff* bottomStaff = excerptScore->staves().back();
     660              : 
     661            1 :         std::vector<SystemObjectsMove> excerptMoves;
     662            1 :         for (const SystemObjectsMove& move : moves) {
     663            0 :             Staff* targetStaff = move.destination;
     664            0 :             if (!targetStaff && move.belowBottomStaff) {
     665            0 :                 targetStaff = scoreBottomStaff;
     666              :             }
     667              : 
     668            0 :             if (!move.staff || !targetStaff) {
     669            0 :                 continue;
     670              :             }
     671              : 
     672            0 :             Staff* staff = move.staff->findLinkedInScore(excerptScore);
     673            0 :             Staff* destination = targetStaff->findLinkedInScore(excerptScore);
     674            0 :             if (!staff || !destination) {
     675            0 :                 continue;
     676              :             }
     677              : 
     678            0 :             excerptMoves.push_back({ staff, destination, move.belowBottomStaff && destination == bottomStaff });
     679              :         }
     680              : 
     681            1 :         doReorderParts(excerptScore, excerptScore->parts(), excerptMoves);
     682            5 :     }
     683              : }
     684              : 
     685            3 : bool EditPart::reorderStavesChangesScore(const std::vector<Staff*>& staves)
     686              : {
     687            3 :     if (staves.empty() || !staves.front()) {
     688            0 :         return false;
     689              :     }
     690              : 
     691            3 :     const Part* part = staves.front()->part();
     692            3 :     const std::vector<Staff*>& partStaves = part->staves();
     693            3 :     if (staves.size() != partStaves.size()) {
     694            1 :         return false;
     695              :     }
     696              : 
     697            6 :     for (const Staff* staff : staves) {
     698            4 :         IF_ASSERT_FAILED_X(staff && staff->part() == part, "All staves must have the same part!") {
     699            0 :             return false;
     700              :         }
     701              :     }
     702              : 
     703            2 :     return !std::equal(staves.begin(), staves.end(), partStaves.begin());
     704              : }
     705              : 
     706            1 : void EditPart::reorderStaves(Score* score, const std::vector<Staff*>& staves)
     707              : {
     708            1 :     if (!score) {
     709            0 :         return;
     710              :     }
     711              : 
     712            1 :     std::vector<staff_idx_t> staffMapping;
     713            1 :     staffMapping.reserve(score->nstaves());
     714            4 :     for (const Staff* staff : score->staves()) {
     715            3 :         staffMapping.push_back(staff->idx());
     716              :     }
     717              : 
     718              :     // The part's staff slots get its staves in the new order
     719            1 :     const staff_idx_t firstStaffIdx = staves.front()->part()->staves().front()->idx();
     720            3 :     for (size_t i = 0; i < staves.size(); ++i) {
     721            2 :         staffMapping[firstStaffIdx + i] = staves[i]->idx();
     722              :     }
     723              : 
     724            1 :     score->undo(new SortStaves(score, staffMapping));
     725            1 :     score->setBracketsAndBarlines();
     726            1 : }
     727              : 
     728            3 : void EditPart::moveParts(Score* score, const std::vector<Part*>& sourceParts, Part* destinationPart, bool insertAfter)
     729              : {
     730            3 :     if (!score || sourceParts.empty() || !destinationPart) {
     731            0 :         return;
     732              :     }
     733              : 
     734              :     // Build new part order: remove source parts, then insert at destination
     735            3 :     std::vector<Part*> allParts(score->parts().begin(), score->parts().end());
     736              : 
     737              :     // Remove source parts from the list
     738            6 :     for (Part* srcPart : sourceParts) {
     739            3 :         allParts.erase(std::remove(allParts.begin(), allParts.end(), srcPart), allParts.end());
     740              :     }
     741              : 
     742              :     // Find destination index
     743            3 :     auto dstIt = std::find(allParts.begin(), allParts.end(), destinationPart);
     744            3 :     if (dstIt == allParts.end()) {
     745            0 :         return;
     746              :     }
     747              : 
     748            3 :     size_t dstIndex = std::distance(allParts.begin(), dstIt);
     749            3 :     if (insertAfter) {
     750            1 :         dstIndex++;
     751              :     }
     752              : 
     753              :     // Insert source parts at destination
     754            6 :     for (size_t i = 0; i < sourceParts.size(); ++i) {
     755            3 :         allParts.insert(allParts.begin() + dstIndex + i, sourceParts[i]);
     756              :     }
     757              : 
     758              :     // Build staff index mapping from the new part order
     759            3 :     std::vector<staff_idx_t> staffMapping;
     760            3 :     staffMapping.reserve(score->nstaves());
     761           11 :     for (Part* part : allParts) {
     762           17 :         for (Staff* staff : part->staves()) {
     763            9 :             staffMapping.push_back(staff->idx());
     764              :         }
     765              :     }
     766              : 
     767            3 :     score->undo(new SortStaves(score, staffMapping));
     768            3 :     score->setBracketsAndBarlines();
     769            3 : }
     770              : 
     771            2 : void EditPart::moveStaves(Score* score, const std::vector<Staff*>& sourceStaves, Staff* destinationStaff, bool insertAfter)
     772              : {
     773            2 :     if (!score || sourceStaves.empty() || !destinationStaff) {
     774            0 :         return;
     775              :     }
     776              : 
     777              :     // Build new staff order: remove source staves, then insert at destination
     778            2 :     std::vector<Staff*> allStaves(score->staves().begin(), score->staves().end());
     779              : 
     780              :     // Remove source staves from the list
     781            4 :     for (Staff* srcStaff : sourceStaves) {
     782            2 :         allStaves.erase(std::remove(allStaves.begin(), allStaves.end(), srcStaff), allStaves.end());
     783              :     }
     784              : 
     785              :     // Find destination index
     786            2 :     auto dstIt = std::find(allStaves.begin(), allStaves.end(), destinationStaff);
     787            2 :     if (dstIt == allStaves.end()) {
     788            0 :         return;
     789              :     }
     790              : 
     791            2 :     size_t dstIndex = std::distance(allStaves.begin(), dstIt);
     792            2 :     if (insertAfter) {
     793            0 :         dstIndex++;
     794              :     }
     795              : 
     796              :     // Insert source staves at destination
     797            4 :     for (size_t i = 0; i < sourceStaves.size(); ++i) {
     798            2 :         allStaves.insert(allStaves.begin() + dstIndex + i, sourceStaves[i]);
     799              :     }
     800              : 
     801              :     // Build index mapping
     802            2 :     std::vector<staff_idx_t> sortedIndexes;
     803            2 :     sortedIndexes.reserve(allStaves.size());
     804            7 :     for (const Staff* staff : allStaves) {
     805            5 :         sortedIndexes.push_back(staff->idx());
     806              :     }
     807              : 
     808            2 :     score->undo(new SortStaves(score, sortedIndexes));
     809            2 :     score->setBracketsAndBarlines();
     810            2 : }
     811              : 
     812            3 : Staff* EditPart::appendStaff(Score* score, Part* destinationPart)
     813              : {
     814            3 :     if (!score || !destinationPart) {
     815            0 :         return nullptr;
     816              :     }
     817              : 
     818            3 :     Staff* staff = Factory::createStaff(destinationPart);
     819            3 :     appendStaff(score, staff, destinationPart);
     820            3 :     return staff;
     821              : }
     822              : 
     823            3 : void EditPart::appendStaff(Score* score, Staff* staff, Part* destinationPart, bool createRests)
     824              : {
     825            3 :     if (!score || !staff || !destinationPart) {
     826            0 :         return;
     827              :     }
     828              : 
     829            3 :     doAppendStaff(score, staff, destinationPart, createRests);
     830              : 
     831            4 :     for (Score* excerptScore : excerptScores(score)) {
     832            1 :         if (Part* excerptPart = excerptScore->partById(destinationPart->id())) {
     833            1 :             Staff* excerptStaff = staff->clone();
     834            1 :             doAppendStaff(excerptScore, excerptStaff, excerptPart, false);
     835            1 :             excerptScore->undo(new Link(excerptStaff, staff));
     836            1 :             Excerpt::cloneStaff2(staff, excerptStaff, Fraction(0, 1), excerptScore->endTick());
     837              :         }
     838            3 :     }
     839              : }
     840              : 
     841            3 : Staff* EditPart::appendLinkedStaff(Score* score, Staff* sourceStaff, Part* destinationPart)
     842              : {
     843            3 :     if (!score || !sourceStaff || !destinationPart) {
     844            0 :         return nullptr;
     845              :     }
     846              : 
     847            3 :     Staff* staff = Factory::createStaff(destinationPart);
     848            3 :     appendLinkedStaff(score, staff, sourceStaff, destinationPart);
     849            3 :     return staff;
     850              : }
     851              : 
     852            3 : void EditPart::appendLinkedStaff(Score* score, Staff* staff, Staff* sourceStaff, Part* destinationPart)
     853              : {
     854            3 :     if (!score || !staff || !sourceStaff || !destinationPart) {
     855            0 :         return;
     856              :     }
     857              : 
     858            3 :     doAppendLinkedStaff(score, staff, sourceStaff, destinationPart);
     859              : 
     860            4 :     for (Score* excerptScore : excerptScores(score)) {
     861            1 :         Staff* excerptSourceStaff = sourceStaff->findLinkedInScore(excerptScore);
     862            1 :         Part* excerptPart = excerptScore->partById(destinationPart->id());
     863            1 :         if (excerptSourceStaff && excerptPart) {
     864            1 :             doAppendLinkedStaff(excerptScore, staff->clone(), excerptSourceStaff, excerptPart);
     865              :         }
     866            3 :     }
     867              : }
     868              : 
     869           82 : void EditPart::insertPart(Score* score, const InstrumentTemplate* templ, size_t index)
     870              : {
     871           82 :     if (!score || !templ) {
     872            0 :         return;
     873              :     }
     874              : 
     875           82 :     insertPart(score, *templ, index, score->keyList());
     876           82 :     score->masterScore()->rebuildMidiMapping();
     877              : }
     878              : 
     879            1 : void EditPart::insertPart(Score* score, Part* part, size_t index)
     880              : {
     881            1 :     if (!score || !part) {
     882            0 :         return;
     883              :     }
     884              : 
     885            1 :     removeLocksContainingMMRests(score);
     886            1 :     insertPartCopy(score, part, index);
     887              : }
     888              : 
     889            3 : void EditPart::replacePart(Score* score, Part* oldPart, const InstrumentTemplate* templ)
     890              : {
     891            3 :     if (!score || !oldPart || !templ) {
     892            0 :         return;
     893              :     }
     894              : 
     895            3 :     size_t partIndex = muse::indexOf(score->parts(), oldPart);
     896            3 :     score->cmdRemovePart(oldPart);
     897            3 :     insertPart(score, templ, partIndex);
     898              : }
     899              : 
     900            1 : void EditPart::replacePart(Score* score, Part* oldPart, Part* newPart)
     901              : {
     902            1 :     if (!score || !oldPart || !newPart) {
     903            0 :         return;
     904              :     }
     905              : 
     906            1 :     size_t partIndex = muse::indexOf(score->parts(), oldPart);
     907            1 :     score->cmdRemovePart(oldPart);
     908            1 :     insertPartCopy(score, newPart, partIndex);
     909              : }
     910              : 
     911            6 : bool EditPart::replaceInstrument(Score* score, Part* part, const Fraction& tick, const Instrument& newInstrument,
     912              :                                  const StaffType* newStaffType)
     913              : {
     914            6 :     if (!score || !part) {
     915            0 :         return false;
     916              :     }
     917              : 
     918            6 :     if (!score->isMaster()) {
     919            0 :         return doReplaceInstrument(score, part, tick, newInstrument, newStaffType);
     920              :     }
     921              : 
     922            6 :     const Interval oldTranspose = part->instrument()->transpose();
     923              : 
     924            6 :     const bool replaced = doReplaceInstrument(score, part, tick, newInstrument, newStaffType);
     925              : 
     926           10 :     for (Score* excerptScore : excerptScores(score)) {
     927            4 :         if (Part* excerptPart = excerptScore->partById(part->id())) {
     928            4 :             doReplaceInstrument(excerptScore, excerptPart, tick, newInstrument, newStaffType);
     929              :         }
     930            6 :     }
     931              : 
     932              :     // also transposes all linked parts
     933            6 :     if (newInstrument.transpose().reduced() != oldTranspose.reduced()) {
     934            1 :         Transaction& tx = score->transactionManager()->currentOrDummyTransaction();
     935            1 :         Transpose::transpositionChanged(tx, score, part, Part::MAIN_INSTRUMENT_TICK, oldTranspose);
     936              :     }
     937              : 
     938            6 :     if (tick == Part::MAIN_INSTRUMENT_TICK) {
     939            4 :         renameExcerptOfPart(score->masterScore(), part);
     940              :     }
     941              : 
     942            6 :     return replaced;
     943              : }
     944              : 
     945            8 : void EditPart::replacePartInstrument(Score* score, Part* part, const Instrument& newInstrument,
     946              :                                      const StaffType* newStaffType)
     947              : {
     948            8 :     if (!score || !part) {
     949            0 :         return;
     950              :     }
     951              : 
     952            8 :     score->undo(new ChangePart(part, new Instrument(newInstrument)));
     953              : 
     954              :     // Update clefs and staff type for all staves in the part
     955           16 :     for (staff_idx_t staffIdx = 0; staffIdx < part->nstaves(); ++staffIdx) {
     956            8 :         Staff* staff = part->staves().at(staffIdx);
     957            8 :         if (!staff) {
     958            0 :             continue;
     959              :         }
     960              : 
     961              :         // Get current staff properties
     962            8 :         bool visible = staff->visible();
     963            8 :         ClefTypeList currentClefType = staff->defaultClefType();
     964            8 :         Spatium userDist = staff->userDist();
     965            8 :         bool cutaway = staff->cutaway();
     966            8 :         bool hideSystemBarLine = staff->hideSystemBarLine();
     967            8 :         AutoOnOff mergeMatchingRests = staff->mergeMatchingRests();
     968            8 :         bool reflectTransposition = staff->reflectTranspositionInLinkedTab();
     969              : 
     970              :         // Get new clef type from the new instrument
     971            8 :         ClefTypeList newClefType = newInstrument.clefType(staffIdx);
     972              : 
     973              :         // Only update staff if clef type changes
     974            8 :         if (currentClefType != newClefType) {
     975            2 :             score->undo(new ChangeStaff(staff, visible, newClefType, userDist, cutaway,
     976            2 :                                         hideSystemBarLine, mergeMatchingRests, reflectTransposition));
     977              :         }
     978              : 
     979              :         // Apply new staff type if provided
     980            8 :         if (newStaffType) {
     981            2 :             score->undo(new ChangeStaffType(staff, *newStaffType));
     982              :         }
     983              :     }
     984              : }
     985              : 
     986            4 : void EditPart::replaceDrumset(Score* score, Part* part, const Fraction& tick, const Drumset& newDrumset, bool undoable)
     987              : {
     988            4 :     if (!score || !part) {
     989            0 :         return;
     990              :     }
     991              : 
     992            4 :     doReplaceDrumset(score, part, tick, newDrumset, undoable);
     993              : 
     994            6 :     for (Score* excerptScore : excerptScores(score)) {
     995            2 :         if (Part* excerptPart = excerptScore->partById(part->id())) {
     996            2 :             doReplaceDrumset(excerptScore, excerptPart, tick, newDrumset, undoable);
     997              :         }
     998            4 :     }
     999              : }
    1000              : 
    1001            5 : void EditPart::addSystemObjects(Score* score, const std::vector<Staff*>& staves)
    1002              : {
    1003            5 :     if (!score || staves.empty()) {
    1004            0 :         return;
    1005              :     }
    1006              : 
    1007            5 :     std::vector<EngravingItem*> topSystemObjects = collectSystemObjects(score);
    1008              : 
    1009           10 :     for (Staff* staff : staves) {
    1010            5 :         if (staff->isSystemObjectStaff()) {
    1011            0 :             continue;
    1012              :         }
    1013              : 
    1014            5 :         score->undo(new AddSystemObjectStaff(staff));
    1015              : 
    1016            5 :         const staff_idx_t staffIdx = staff->idx();
    1017            8 :         for (EngravingItem* obj : topSystemObjects) {
    1018            3 :             if (obj->isTimeSig()) {
    1019            0 :                 obj->triggerLayout();
    1020            0 :                 continue;
    1021              :             }
    1022            3 :             EngravingItem* copy = obj->linkedClone();
    1023            3 :             copy->setStaffIdx(staffIdx);
    1024            3 :             score->undoAddElement(copy, false /*addToLinkedStaves*/);
    1025              :         }
    1026              :     }
    1027            5 : }
    1028              : 
    1029            2 : void EditPart::removeSystemObjects(Score* score, const std::vector<Staff*>& staves)
    1030              : {
    1031            2 :     if (!score || staves.empty()) {
    1032            0 :         return;
    1033              :     }
    1034              : 
    1035            2 :     std::vector<EngravingItem*> systemObjects = collectSystemObjects(score, staves);
    1036              : 
    1037            4 :     for (Staff* staff : staves) {
    1038            2 :         if (!staff->isSystemObjectStaff()) {
    1039            0 :             continue;
    1040              :         }
    1041              : 
    1042            2 :         if (staff->hasSystemObjectsBelowBottomStaff()) {
    1043            1 :             score->undoChangeStyleVal(Sid::systemObjectsBelowBottomStaff, false);
    1044              :         }
    1045            2 :         score->undo(new RemoveSystemObjectStaff(staff));
    1046              :     }
    1047              : 
    1048            3 :     for (EngravingItem* obj : systemObjects) {
    1049            1 :         if (obj->isTimeSig()) {
    1050            0 :             obj->triggerLayout();
    1051            0 :             continue;
    1052              :         }
    1053            1 :         obj->undoUnlink();
    1054            1 :         score->undoRemoveElement(obj, false /*removeLinked*/);
    1055              :     }
    1056            2 : }
    1057              : 
    1058            3 : void EditPart::moveSystemObjects(Score* score, Staff* sourceStaff, Staff* destinationStaff)
    1059              : {
    1060            3 :     if (!score || !sourceStaff || !destinationStaff) {
    1061            0 :         return;
    1062              :     }
    1063              : 
    1064            3 :     if (!sourceStaff->isSystemObjectStaff()) {
    1065            0 :         return;
    1066              :     }
    1067              : 
    1068            6 :     const std::vector<EngravingItem*> systemObjects = collectSystemObjects(score, { sourceStaff, destinationStaff });
    1069            3 :     const staff_idx_t dstStaffIdx = destinationStaff->idx();
    1070              : 
    1071            3 :     score->undo(new RemoveSystemObjectStaff(sourceStaff));
    1072            3 :     if (!destinationStaff->isSystemObjectStaff() && dstStaffIdx != 0) {
    1073            3 :         score->undo(new AddSystemObjectStaff(destinationStaff));
    1074              :     } else {
    1075            0 :         score->undoChangeStyleVal(Sid::systemObjectsBelowBottomStaff, false);
    1076              :     }
    1077              : 
    1078            3 :     AutoOnOff showMeasNumOnSrcStaff = sourceStaff->getProperty(Pid::SHOW_MEASURE_NUMBERS).value<AutoOnOff>();
    1079            3 :     if (showMeasNumOnSrcStaff != AutoOnOff::AUTO) {
    1080            1 :         destinationStaff->undoChangeProperty(Pid::SHOW_MEASURE_NUMBERS, showMeasNumOnSrcStaff);
    1081            1 :         sourceStaff->undoResetProperty(Pid::SHOW_MEASURE_NUMBERS);
    1082              :     }
    1083              : 
    1084              :     // Remove items from destination first
    1085            4 :     for (EngravingItem* item : systemObjects) {
    1086            1 :         if (item->isTimeSig()) {
    1087            0 :             item->triggerLayout();
    1088            0 :             continue;
    1089              :         }
    1090              : 
    1091            1 :         if (item->staff() == sourceStaff) {
    1092            1 :             continue;
    1093              :         }
    1094            0 :         item->undoUnlink();
    1095            0 :         score->undoRemoveElement(item, false /*removeLinked*/);
    1096              :     }
    1097              : 
    1098              :     // Move items from source to destination
    1099            4 :     for (EngravingItem* item : systemObjects) {
    1100            1 :         if (item->isTimeSig()) {
    1101            0 :             continue;
    1102              :         }
    1103              : 
    1104            1 :         if (item->staff() == sourceStaff) {
    1105            1 :             item->undoChangeProperty(Pid::TRACK, staff2track(dstStaffIdx, item->voice()));
    1106              :         }
    1107              :     }
    1108            3 : }
    1109              : 
    1110           10 : bool EditPart::doReplaceInstrument(Score* score, Part* part, const Fraction& tick, const Instrument& newInstrument,
    1111              :                                    const StaffType* newStaffType)
    1112              : {
    1113           10 :     if (tick == Part::MAIN_INSTRUMENT_TICK) {
    1114            7 :         replacePartInstrument(score, part, newInstrument, newStaffType);
    1115            7 :         return true;
    1116              :     }
    1117              : 
    1118            3 :     InstrumentChange* instrumentChange = findInstrumentChange(score, part, tick);
    1119            3 :     if (!instrumentChange) {
    1120            1 :         return false;
    1121              :     }
    1122              : 
    1123            2 :     instrumentChange->setInit(true);
    1124            2 :     instrumentChange->setupInstrument(&newInstrument);
    1125            2 :     return true;
    1126              : }
    1127              : 
    1128            4 : void EditPart::renameExcerptOfPart(MasterScore* master, const Part* part)
    1129              : {
    1130            4 :     Excerpt* excerptOfPart = nullptr;
    1131            4 :     StringList allExcerptLowerNames;
    1132              : 
    1133            7 :     for (Excerpt* excerpt : master->excerpts()) {
    1134            3 :         if (excerpt->initialPartId() == part->id()) {
    1135            3 :             excerptOfPart = excerpt;
    1136            3 :             continue;
    1137              :         }
    1138            0 :         allExcerptLowerNames.push_back(excerpt->name().toLower());
    1139              :     }
    1140              : 
    1141            4 :     if (!excerptOfPart) {
    1142            1 :         return;
    1143              :     }
    1144              : 
    1145            3 :     const String newName = formatUniqueExcerptName(part->partName(), allExcerptLowerNames);
    1146            3 :     excerptOfPart->excerptScore()->undo(new ChangeExcerptTitle(excerptOfPart, newName));
    1147            4 : }
    1148              : 
    1149            6 : void EditPart::doRemoveParts(Score* score, const std::vector<Part*>& parts)
    1150              : {
    1151           12 :     for (Part* part : parts) {
    1152            6 :         score->cmdRemovePart(part);
    1153              :     }
    1154              : 
    1155            6 :     score->setBracketsAndBarlines();
    1156            6 : }
    1157              : 
    1158            3 : void EditPart::doRemoveStaves(Score* score, const std::vector<Staff*>& staves)
    1159              : {
    1160            6 :     for (Staff* staff : staves) {
    1161            3 :         score->cmdRemoveStaff(staff->idx());
    1162              :     }
    1163              : 
    1164            3 :     score->setBracketsAndBarlines();
    1165            3 : }
    1166              : 
    1167            5 : void EditPart::doReorderParts(Score* score, const std::vector<Part*>& parts, const std::vector<SystemObjectsMove>& moves)
    1168              : {
    1169              :     // Sorting keeps the markings at their staff positions, so their indexes are taken first
    1170            5 :     std::vector<std::pair<staff_idx_t, Staff*> > pendingMoves;
    1171            5 :     pendingMoves.reserve(moves.size());
    1172              : 
    1173            8 :     for (const SystemObjectsMove& move : moves) {
    1174            3 :         if (move.staff && move.staff->isSystemObjectStaff() && (move.destination || move.belowBottomStaff)) {
    1175            3 :             pendingMoves.emplace_back(move.staff->idx(), move.belowBottomStaff ? nullptr : move.destination);
    1176              :         }
    1177              :     }
    1178              : 
    1179            5 :     const Staff* staffWithMarkingsBelow = score->style().styleB(Sid::systemObjectsBelowBottomStaff)
    1180            5 :                                           ? score->staves().back() : nullptr;
    1181              : 
    1182            5 :     const std::vector<Part*>& scoreParts = score->parts();
    1183            5 :     if (parts.size() == scoreParts.size() && !std::equal(parts.begin(), parts.end(), scoreParts.begin())) {
    1184            1 :         std::vector<staff_idx_t> staffMapping;
    1185            1 :         staffMapping.reserve(score->nstaves());
    1186            3 :         for (const Part* part : parts) {
    1187            5 :             for (const Staff* staff : part->staves()) {
    1188            3 :                 staffMapping.push_back(staff->idx());
    1189              :             }
    1190              :         }
    1191              : 
    1192            1 :         score->undo(new SortStaves(score, staffMapping));
    1193            1 :         score->setBracketsAndBarlines();
    1194            1 :     }
    1195              : 
    1196            5 :     const bool belowBottomStaff = moveSystemObjects(score, pendingMoves, staffWithMarkingsBelow == score->staves().back());
    1197            5 :     if (belowBottomStaff != score->style().styleB(Sid::systemObjectsBelowBottomStaff)) {
    1198            2 :         score->undoChangeStyleVal(Sid::systemObjectsBelowBottomStaff, belowBottomStaff);
    1199              :     }
    1200            5 : }
    1201              : 
    1202            8 : void EditPart::doAppendStaff(Score* score, Staff* staff, Part* destinationPart, bool createRests)
    1203              : {
    1204            8 :     if (score->isMaster()) {
    1205              :         // assigned when added to the score, then shared with the part scores
    1206            6 :         staff->setId(INVALID_ID);
    1207              :     }
    1208              : 
    1209            8 :     staff_idx_t staffLocalIndex = destinationPart->nstaves();
    1210            8 :     Staff* lastStaff = staffLocalIndex > 0 ? destinationPart->staff(staffLocalIndex - 1) : nullptr;
    1211            8 :     KeyList keyList = lastStaff ? lastStaff->keyList() : score->keyList();
    1212              : 
    1213            8 :     staff->setScore(score);
    1214            8 :     staff->setPart(destinationPart);
    1215              : 
    1216            8 :     score->undoInsertStaff(staff, staffLocalIndex, createRests);
    1217              : 
    1218            8 :     staff_idx_t staffGlobalIndex = staff->idx();
    1219            8 :     score->adjustKeySigs(staffGlobalIndex, staffGlobalIndex + 1, keyList);
    1220              : 
    1221            8 :     score->updateBracesAndBarlines(destinationPart, staffLocalIndex);
    1222            8 :     score->setBracketsAndBarlines();
    1223              : 
    1224            8 :     destinationPart->instrument()->setClefType(staffLocalIndex, staff->defaultClefType());
    1225            8 : }
    1226              : 
    1227            4 : void EditPart::doAppendLinkedStaff(Score* score, Staff* staff, Staff* sourceStaff, Part* destinationPart)
    1228              : {
    1229            4 :     doAppendStaff(score, staff, destinationPart, false);
    1230              : 
    1231            4 :     staff->setLinks(nullptr);
    1232            4 :     Excerpt::cloneStaff(sourceStaff, staff);
    1233            4 : }
    1234              : 
    1235            6 : void EditPart::doReplaceDrumset(Score* score, Part* part, const Fraction& tick, const Drumset& newDrumset, bool undoable)
    1236              : {
    1237            6 :     Instrument* instrument = part->instrument(tick);
    1238            6 :     if (!instrument) {
    1239            0 :         return;
    1240              :     }
    1241              : 
    1242            6 :     if (undoable) {
    1243            4 :         score->undo(new ChangeDrumset(instrument, newDrumset, part));
    1244              :     } else {
    1245            2 :         instrument->setDrumset(&newDrumset);
    1246              :     }
    1247              : }
    1248              : 
    1249            6 : void EditPart::removeLocksContainingMMRests(Score* score)
    1250              : {
    1251            6 :     Transaction& tx = score->transactionManager()->currentOrDummyTransaction();
    1252            6 :     EditPageLocks::removePageLocksContainingMMRests(tx, score);
    1253            6 :     EditSystemLocks::removeSystemLocksContainingMMRests(tx, score);
    1254            6 : }
    1255              : 
    1256           85 : void EditPart::appendStaves(Score* score, Part* part, const InstrumentTemplate& templ, const KeyList& keyList)
    1257              : {
    1258           85 :     if (!score || !part) {
    1259            0 :         return;
    1260              :     }
    1261              : 
    1262           85 :     const StaffType* staffType = templ.staffTypePreset;
    1263           85 :     if (!staffType) {
    1264           83 :         staffType = StaffType::preset(StaffTypes::STANDARD);
    1265              :     }
    1266              : 
    1267          197 :     for (staff_idx_t staffIndex = 0; staffIndex < templ.staffCount; ++staffIndex) {
    1268          112 :         Staff* staff = Factory::createStaff(part);
    1269          112 :         score->undoInsertStaff(staff, staffIndex);
    1270          112 :         staff->init(&templ, staffType, staffIndex);
    1271              :     }
    1272              : 
    1273           85 :     if (!part->nstaves()) {
    1274            0 :         return;
    1275              :     }
    1276              : 
    1277           85 :     staff_idx_t firstStaffIndex = part->staff(0)->idx();
    1278           85 :     staff_idx_t endStaffIndex = firstStaffIndex + part->nstaves();
    1279           85 :     score->adjustKeySigs(firstStaffIndex, endStaffIndex, keyList);
    1280              : }
    1281              : 
    1282           85 : Part* EditPart::insertPart(Score* score, const InstrumentTemplate& templ, size_t index, const KeyList& keyList)
    1283              : {
    1284           85 :     if (!score) {
    1285            0 :         return nullptr;
    1286              :     }
    1287              : 
    1288           85 :     Instrument instrument = Instrument::fromTemplate(&templ);
    1289           85 :     const String& longName = instrument.longName();
    1290           85 :     const String& shortName = instrument.shortName();
    1291              : 
    1292           85 :     const Trait trait = instrument.trait();
    1293           85 :     const String& transposition = trait.type == TraitType::Transposition && !trait.isHiddenOnScore ? trait.name : String();
    1294              : 
    1295           85 :     Part* part = new Part(score);
    1296           85 :     part->setInstrument(instrument);
    1297              : 
    1298           85 :     part->setLongName(muse::mtrc("notation", longName));
    1299           85 :     part->setShortName(muse::mtrc("notation", shortName));
    1300           85 :     part->setTransposition(muse::mtrc("notation", transposition));
    1301              : 
    1302           85 :     doInsertPart(score, part, index);
    1303           85 :     appendStaves(score, part, templ, keyList);
    1304              : 
    1305           85 :     return part;
    1306           85 : }
    1307              : 
    1308           87 : void EditPart::doInsertPart(Score* score, Part* part, size_t index)
    1309              : {
    1310           87 :     if (Excerpt* excerpt = score->excerpt()) {
    1311            2 :         score->undo(new AddPartToExcerpt(excerpt, part, index));
    1312              :     } else {
    1313           85 :         score->undoInsertPart(part, index);
    1314              :     }
    1315           87 : }
    1316              : 
    1317            2 : void EditPart::insertPartCopy(Score* score, Part* part, size_t index)
    1318              : {
    1319            2 :     std::vector<Staff*> stavesCopy(part->staves());
    1320            2 :     part->clearStaves();
    1321              : 
    1322            2 :     InstrumentList instrumentsCopy = part->instruments();
    1323            2 :     part->setInstruments({});
    1324              : 
    1325            2 :     doInsertPart(score, part, index);
    1326              : 
    1327            4 :     for (auto it = instrumentsCopy.cbegin(); it != instrumentsCopy.cend(); ++it) {
    1328            2 :         part->setInstrument(new Instrument(*it->second), it->first);
    1329              :     }
    1330              : 
    1331            2 :     Fraction startTick = score->firstMeasure()->tick();
    1332            2 :     Fraction endTick = score->lastMeasure()->endTick();
    1333              : 
    1334            5 :     for (size_t staffIndex = 0; staffIndex < stavesCopy.size(); ++staffIndex) {
    1335            3 :         Staff* staff = stavesCopy[staffIndex];
    1336              : 
    1337            3 :         Staff* staffCopy = Factory::createStaff(part);
    1338            3 :         staffCopy->setId(staff->id());
    1339            3 :         staffCopy->setScore(score);
    1340            3 :         staffCopy->setPart(part);
    1341            3 :         staffCopy->init(staff);
    1342              : 
    1343            3 :         score->undoInsertStaff(staffCopy, staffIndex, /* createRests = */ false);
    1344            3 :         score->undo(new Link(staffCopy, staff));
    1345              : 
    1346            3 :         Excerpt::cloneStaff2(staff, staffCopy, startTick, endTick);
    1347              :     }
    1348              : 
    1349            2 :     score->remapBracketsAndBarlines();
    1350            2 : }
    1351              : 
    1352            4 : std::vector<Part*> EditPart::removeMissingParts(Score* score, const std::vector<PartEntry>& entries)
    1353              : {
    1354            4 :     std::unordered_set<Part*> keptParts;
    1355           12 :     for (const PartEntry& entry : entries) {
    1356            8 :         if (entry.part) {
    1357            5 :             keptParts.insert(entry.part);
    1358              :         }
    1359              :     }
    1360              : 
    1361            4 :     std::vector<Part*> partsToRemove;
    1362           10 :     for (Part* part : score->parts()) {
    1363            6 :         if (!muse::contains(keptParts, part)) {
    1364            1 :             partsToRemove.push_back(part);
    1365              :         }
    1366              :     }
    1367              : 
    1368            4 :     removeParts(score, partsToRemove);
    1369              : 
    1370            4 :     return partsToRemove;
    1371            4 : }
    1372              : 
    1373            4 : std::vector<Part*> EditPart::insertNewParts(Score* score, const std::vector<PartEntry>& entries, const KeyList& keyList)
    1374              : {
    1375            4 :     std::vector<Part*> newParts;
    1376            4 :     if (!score) {
    1377            0 :         return newParts;
    1378              :     }
    1379              : 
    1380            4 :     const std::vector<int> numbers = resolveInstrumentNumbers(entries);
    1381              : 
    1382           12 :     for (size_t i = 0; i < entries.size(); ++i) {
    1383            8 :         const PartEntry& entry = entries[i];
    1384            8 :         const int number = numbers.at(i);
    1385              : 
    1386            8 :         if (!entry.instrumentTemplate) {
    1387            5 :             if (entry.part && number >= 0 && entry.part->number() != number) {
    1388            1 :                 setInstrumentNumber(score, entry.part, Part::MAIN_INSTRUMENT_TICK, number);
    1389              :             }
    1390            5 :             continue;
    1391              :         }
    1392              : 
    1393            3 :         Part* part = insertPart(score, *entry.instrumentTemplate, i, keyList);
    1394            3 :         part->setSoloist(entry.isSoloist);
    1395            3 :         part->setNumber(std::max(number, 0));
    1396            3 :         newParts.push_back(part);
    1397              :     }
    1398              : 
    1399            4 :     return newParts;
    1400            4 : }
    1401              : 
    1402            4 : std::vector<int> EditPart::resolveInstrumentNumbers(const std::vector<PartEntry>& entries)
    1403              : {
    1404              :     // Kinds with an instrument being added are numbered in their (new) order, unless there's only one. Shared staves
    1405              :     // and instruments numbered in their name (e.g. "Violins 1") aren't numbered, though the latter still count.
    1406              :     // Returns the number for each instrument, or -1 to leave it as it is
    1407              :     struct Counter {
    1408              :         int count = 0;
    1409              :         size_t firstIndex = 0; // in entries / numbers: the first instrument of this kind
    1410              :     };
    1411              : 
    1412            4 :     std::map<String, Counter> counters;
    1413           12 :     for (const PartEntry& entry : entries) {
    1414            8 :         if (entry.instrumentTemplate) {
    1415            3 :             counters.try_emplace(entry.instrumentTemplate->id);
    1416              :         }
    1417              :     }
    1418              : 
    1419            4 :     std::vector<int> numbers;
    1420            4 :     numbers.reserve(entries.size());
    1421              : 
    1422           12 :     for (const PartEntry& entry : entries) {
    1423            8 :         Counter* counter = nullptr; // null: not renumbered
    1424            8 :         bool isNumberedInName = false;
    1425              : 
    1426            8 :         if (entry.instrumentTemplate) {
    1427            3 :             counter = &counters.at(entry.instrumentTemplate->id);
    1428            5 :         } else if (const Part* part = entry.part; part && !part->isSharedPart()) {
    1429            5 :             const Instrument* instrument = part->instrument();
    1430            5 :             auto it = counters.find(instrument->id());
    1431              : 
    1432            5 :             if (it != counters.end()) {
    1433            2 :                 const String& name = instrument->longName();
    1434              : 
    1435            2 :                 counter = &it->second;
    1436            2 :                 isNumberedInName = !name.empty() && name.back().isDigit();
    1437              :             }
    1438              :         }
    1439              : 
    1440            8 :         if (!counter) {
    1441            3 :             numbers.push_back(-1);
    1442            3 :             continue;
    1443              :         }
    1444              : 
    1445            5 :         if (counter->count == 0) {
    1446            3 :             counter->firstIndex = numbers.size();
    1447              :         }
    1448            5 :         ++counter->count;
    1449              : 
    1450            5 :         numbers.push_back(isNumberedInName ? 0 : counter->count);
    1451              :     }
    1452              : 
    1453              :     // An instrument that's the only one of its kind isn't numbered
    1454            7 :     for (const auto& [instrumentId, counter] : counters) {
    1455            3 :         if (counter.count == 1) {
    1456            1 :             numbers[counter.firstIndex] = 0;
    1457              :         }
    1458              :     }
    1459              : 
    1460            4 :     return numbers;
    1461            4 : }
    1462              : 
    1463            4 : void EditPart::updateSoloist(Score* score, const std::vector<PartEntry>& entries)
    1464              : {
    1465           12 :     for (const PartEntry& entry : entries) {
    1466            8 :         Part* part = entry.part;
    1467            8 :         if (part && !part->isSharedPart() && entry.isSoloist != part->soloist()) {
    1468            1 :             score->undo(new SetSoloist(part, entry.isSoloist));
    1469              :         }
    1470              :     }
    1471            4 : }
    1472              : 
    1473            4 : void EditPart::sortParts(Score* score, const std::vector<PartEntry>& entries)
    1474              : {
    1475            4 :     const std::vector<Part*>& scoreParts = score->parts();
    1476              : 
    1477            4 :     std::vector<Part*> orderedParts;
    1478            4 :     orderedParts.reserve(entries.size());
    1479              : 
    1480           12 :     for (size_t i = 0; i < entries.size(); ++i) {
    1481            8 :         const PartEntry& entry = entries[i];
    1482            8 :         Part* part = entry.instrumentTemplate ? muse::value(scoreParts, i) : entry.part;
    1483            8 :         if (part) {
    1484            8 :             orderedParts.push_back(part);
    1485              :         }
    1486              :     }
    1487              : 
    1488            4 :     sortStaves(score, orderedParts);
    1489            4 : }
    1490              : 
    1491            4 : void EditPart::sortStaves(Score* score, const std::vector<Part*>& orderedParts)
    1492              : {
    1493            4 :     std::vector<staff_idx_t> staffMapping;
    1494              : 
    1495           12 :     for (const Part* part : orderedParts) {
    1496           18 :         for (Staff* staff : part->staves()) {
    1497           10 :             staffMapping.push_back(muse::indexOf(score->staves(), staff));
    1498              :         }
    1499              :     }
    1500              : 
    1501            4 :     score->undo(new SortStaves(score, staffMapping));
    1502            4 : }
    1503              : 
    1504            4 : void EditPart::deleteExcerptsOfParts(MasterScore* master, const std::vector<Part*>& parts)
    1505              : {
    1506            4 :     const std::vector<Excerpt*> excerpts = master->excerpts();
    1507              : 
    1508            7 :     for (Excerpt* excerpt : excerpts) {
    1509            3 :         const muse::ID& initialPartId = excerpt->initialPartId();
    1510            3 :         if (!initialPartId.isValid()) {
    1511            1 :             continue;
    1512              :         }
    1513              : 
    1514            2 :         const bool isPartRemoved = std::find_if(parts.cbegin(), parts.cend(), [&initialPartId](const Part* part) {
    1515            2 :             return part->id() == initialPartId;
    1516            4 :         }) != parts.cend();
    1517              : 
    1518            2 :         if (isPartRemoved) {
    1519            1 :             master->deleteExcerpt(excerpt);
    1520              :         }
    1521              :     }
    1522            4 : }
    1523              : 
    1524            5 : bool EditPart::moveSystemObjects(Score* score, std::vector<std::pair<staff_idx_t, Staff*> > moves, bool belowBottomStaff)
    1525              : {
    1526            5 :     Staff* bottomStaff = score->staves().back();
    1527              : 
    1528            3 :     auto hasPendingMoveFrom = [&moves](staff_idx_t staffIdx) {
    1529            3 :         return std::any_of(moves.begin(), moves.end(), [staffIdx](const std::pair<staff_idx_t, Staff*>& move) {
    1530            3 :             return move.first == staffIdx;
    1531            3 :         });
    1532            5 :     };
    1533              : 
    1534              :     // Waits for the destination's own markings to move away, otherwise replaces them
    1535            5 :     bool moved = true;
    1536            8 :     while (!moves.empty() && moved) {
    1537            3 :         moved = false;
    1538              : 
    1539            6 :         for (auto it = moves.begin(); it != moves.end();) {
    1540            3 :             Staff* from = score->staff(it->first);
    1541            3 :             Staff* to = it->second ? it->second : bottomStaff;
    1542            3 :             if (!from || (from != to && hasPendingMoveFrom(to->idx()))) {
    1543            0 :                 ++it;
    1544            0 :                 continue;
    1545              :             }
    1546              : 
    1547            3 :             if (to == bottomStaff) {
    1548            3 :                 belowBottomStaff = !it->second;
    1549              :             }
    1550            3 :             if (from != to) {
    1551            3 :                 moveSystemObjects(score, from, to);
    1552              :             }
    1553              : 
    1554            3 :             it = moves.erase(it);
    1555            3 :             moved = true;
    1556              :         }
    1557              :     }
    1558              : 
    1559           10 :     return belowBottomStaff && bottomStaff->isSystemObjectStaff();
    1560              : }
        

Generated by: LCOV version 2.0-1