LCOV - code coverage report
Current view: top level - src/engraving/editing - edit.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 60.6 % 3264 1978
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              : #include <map>
      24              : #include <set>
      25              : 
      26              : #include "../dom/accidental.h"
      27              : #include "../dom/arpeggio.h"
      28              : #include "../dom/articulation.h"
      29              : #include "../dom/barline.h"
      30              : #include "../dom/beam.h"
      31              : #include "../dom/box.h"
      32              : #include "../dom/bracket.h"
      33              : #include "../dom/breath.h"
      34              : #include "../dom/chord.h"
      35              : #include "../dom/chordbracket.h"
      36              : #include "../dom/chordline.h"
      37              : #include "../dom/clef.h"
      38              : #include "../dom/dynamic.h"
      39              : #include "../dom/excerpt.h"
      40              : #include "../dom/expression.h"
      41              : #include "../dom/factory.h"
      42              : #include "../dom/fingering.h"
      43              : #include "../dom/figuredbass.h"
      44              : #include "../dom/fret.h"
      45              : #include "../dom/glissando.h"
      46              : #include "../dom/guitarbend.h"
      47              : #include "../dom/hammeronpulloff.h"
      48              : #include "../dom/harmony.h"
      49              : #include "../dom/harppedaldiagram.h"
      50              : #include "../dom/hook.h"
      51              : #include "../dom/instrchange.h"
      52              : #include "../dom/instrumentname.h"
      53              : #include "../dom/key.h"
      54              : #include "../dom/keylist.h"
      55              : #include "../dom/keysig.h"
      56              : #include "../dom/laissezvib.h"
      57              : #include "../dom/layoutbreak.h"
      58              : #include "../dom/linkedobjects.h"
      59              : #include "../dom/lyrics.h"
      60              : #include "../dom/marker.h"
      61              : #include "../dom/masterscore.h"
      62              : #include "../dom/measure.h"
      63              : #include "../dom/measurerepeat.h"
      64              : #include "../dom/note.h"
      65              : #include "../dom/noteline.h"
      66              : #include "../dom/ottava.h"
      67              : #include "../dom/pagelockindicator.h"
      68              : #include "../dom/part.h"
      69              : #include "../dom/partialtie.h"
      70              : #include "../dom/playcounttext.h"
      71              : #include "../dom/range.h"
      72              : #include "../dom/rehearsalmark.h"
      73              : #include "../dom/rest.h"
      74              : #include "../dom/score.h"
      75              : #include "../dom/segment.h"
      76              : #include "../dom/sig.h"
      77              : #include "../dom/slur.h"
      78              : #include "../dom/staff.h"
      79              : #include "../dom/stafftext.h"
      80              : #include "../dom/stem.h"
      81              : #include "../dom/sticking.h"
      82              : #include "../dom/stringtunings.h"
      83              : #include "../dom/system.h"
      84              : #include "../dom/systemlockindicator.h"
      85              : #include "../dom/systemtext.h"
      86              : #include "../dom/tapping.h"
      87              : #include "../dom/tempotext.h"
      88              : #include "../dom/text.h"
      89              : #include "../dom/textline.h"
      90              : #include "../dom/tie.h"
      91              : #include "../dom/tiemap.h"
      92              : #include "../dom/timesig.h"
      93              : #include "../dom/tremolosinglechord.h"
      94              : #include "../dom/tremolotwochord.h"
      95              : #include "../dom/tuplet.h"
      96              : #include "../dom/tupletmap.h"
      97              : #include "../dom/utils.h"
      98              : #include "../dom/volta.h"
      99              : 
     100              : #include "addremoveelement.h"
     101              : #include "editstaffbrackets.h"
     102              : #include "editchord.h"
     103              : #include "editclef.h"
     104              : #include "editkeysig.h"
     105              : #include "editmeasures.h"
     106              : #include "editnote.h"
     107              : #include "editpagelocks.h"
     108              : #include "editpart.h"
     109              : #include "editproperty.h"
     110              : #include "editrehearsalmark.h"
     111              : #include "editscoreproperties.h"
     112              : #include "editspanner.h"
     113              : #include "editstaff.h"
     114              : #include "editstyle.h"
     115              : #include "editsystemlocks.h"
     116              : #include "editstavesharing.h"
     117              : #include "edittimesig.h"
     118              : #include "edittremolo.h"
     119              : #include "inserttime.h"
     120              : #include "mscoreview.h"
     121              : #include "navigation.h"
     122              : #include "splitjoinmeasure.h"
     123              : #include "transaction/transaction.h"
     124              : #include "transaction/undostack.h"
     125              : #include "transpose.h"
     126              : 
     127              : #include "log.h"
     128              : 
     129              : using namespace mu;
     130              : using namespace mu::engraving;
     131              : 
     132              : namespace mu::engraving {
     133            0 : static ChordRest* chordOrRest(EngravingItem* el)
     134              : {
     135            0 :     if (el) {
     136            0 :         if (el->isNote()) {
     137            0 :             return toNote(el)->chord();
     138            0 :         } else if (el->isRestFamily()) {
     139            0 :             return toRest(el);
     140            0 :         } else if (el->isChord()) {
     141            0 :             return toChord(el);
     142              :         }
     143              :     }
     144              : 
     145            0 :     return nullptr;
     146              : }
     147              : 
     148              : //---------------------------------------------------------
     149              : //   getSelectedNote
     150              : //---------------------------------------------------------
     151              : 
     152            0 : Note* Score::getSelectedNote()
     153              : {
     154            0 :     EngravingItem* el = selection().element();
     155            0 :     if (el && el->isNote()) {
     156            0 :         return toNote(el);
     157              :     }
     158            0 :     MScore::setError(MsError::NO_NOTE_SELECTED);
     159            0 :     return 0;
     160              : }
     161              : 
     162              : //---------------------------------------------------------
     163              : //   getSelectedChordRest
     164              : //---------------------------------------------------------
     165              : 
     166            0 : ChordRest* Score::getSelectedChordRest() const
     167              : {
     168            0 :     ChordRest* cr = chordOrRest(selection().element());
     169            0 :     if (!cr) {
     170            0 :         MScore::setError(MsError::NO_NOTE_REST_SELECTED);
     171              :     }
     172              : 
     173            0 :     return cr;
     174              : }
     175              : 
     176              : //---------------------------------------------------------
     177              : //   getSelectedChordRest2
     178              : //---------------------------------------------------------
     179              : 
     180            0 : void Score::getSelectedStartEndChordRests(ChordRest*& cr1, ChordRest*& cr2) const
     181              : {
     182            0 :     cr1 = 0;
     183            0 :     cr2 = 0;
     184            0 :     for (EngravingItem* e : selection().elements()) {
     185            0 :         if (e->isNote()) {
     186            0 :             e = toNote(e)->chord();
     187              :         }
     188            0 :         if (e->isChordRest()) {
     189            0 :             ChordRest* cr = toChordRest(e);
     190            0 :             if (cr1 == 0 || (cr1)->tick() > cr->tick()) {
     191            0 :                 cr1 = cr;
     192              :             }
     193            0 :             if (cr2 == 0 || (cr2)->tick() < cr->tick()) {
     194            0 :                 cr2 = cr;
     195              :             }
     196              :         }
     197              :     }
     198            0 :     if (cr1 == 0) {
     199            0 :         MScore::setError(MsError::NO_NOTE_REST_SELECTED);
     200              :     }
     201            0 :     if (cr1 == cr2) {
     202            0 :         cr2 = 0;
     203              :     }
     204            0 : }
     205              : 
     206              : //---------------------------------------------------------
     207              : //   getSelectedChordRests
     208              : //---------------------------------------------------------
     209              : 
     210          103 : std::set<ChordRest*> Score::getSelectedChordRests() const
     211              : {
     212          103 :     std::set<ChordRest*> set;
     213          448 :     for (EngravingItem* e : selection().elements()) {
     214          345 :         if (e->isNote()) {
     215          144 :             e = toNote(e)->chord();
     216              :         }
     217          345 :         if (e->isChordRest()) {
     218          204 :             set.insert(toChordRest(e));
     219              :         }
     220              :     }
     221          103 :     return set;
     222            0 : }
     223              : 
     224              : //---------------------------------------------------------
     225              : //   pos
     226              : //---------------------------------------------------------
     227              : 
     228            0 : Fraction Score::pos()
     229              : {
     230            0 :     EngravingItem* el = selection().element();
     231            0 :     if (selection().activeCR()) {
     232            0 :         el = selection().activeCR();
     233              :     }
     234            0 :     if (el) {
     235            0 :         switch (el->type()) {
     236            0 :         case ElementType::NOTE:
     237            0 :             el = toNote(el)->chord();
     238              :         // fall through
     239            0 :         case ElementType::MEASURE_REPEAT:
     240              :         case ElementType::REST:
     241              :         case ElementType::MMREST:
     242              :         case ElementType::CHORD:
     243            0 :             return toChordRest(el)->tick();
     244            0 :         default:
     245            0 :             break;
     246              :         }
     247              :     }
     248            0 :     return Fraction(0, 1);
     249              : }
     250              : 
     251           24 : Tuplet* Score::addTuplet(ChordRest* destinationChordRest, Fraction ratio, TupletNumberType numberType, TupletBracketType bracketType)
     252              : {
     253           24 :     if (destinationChordRest->durationType() < TDuration(DurationType::V_512TH)
     254           24 :         && destinationChordRest->durationType() != TDuration(DurationType::V_MEASURE)) {
     255            0 :         return nullptr;
     256              :     }
     257              : 
     258           24 :     Measure* measure = destinationChordRest->measure();
     259           24 :     if (measure && measure->isMMRest()) {
     260            0 :         return nullptr;
     261              :     }
     262              : 
     263           24 :     Fraction f(destinationChordRest->ticks());
     264              : 
     265           24 :     f.reduce();         //measure duration might not be reduced
     266              : 
     267           24 :     Fraction _ratio;
     268           24 :     _ratio.setNumerator(ratio.numerator() != -1 ? ratio.numerator() : f.numerator());
     269           24 :     _ratio.setDenominator(ratio.denominator() != -1 ? ratio.denominator() : f.numerator());
     270              : 
     271           24 :     Fraction fr = f * Fraction(1, _ratio.denominator());
     272           24 :     if (!TDuration::isValid(fr)) {
     273            1 :         LOGD() << "cannot create tuplet with ratio " << _ratio.toString() << " for duration " << f.toString();
     274            1 :         MScore::setError(MsError::TUPLET_RATIO_NOT_POSSIBLE);
     275            1 :         return nullptr;
     276              :     }
     277              : 
     278           23 :     return addTuplet(destinationChordRest, _ratio, TDuration(fr), numberType, bracketType);
     279              : }
     280              : 
     281          144 : static bool isValidTuplet(const Fraction& ratio, const TDuration& baseLen)
     282              : {
     283          144 :     return baseLen.isValid() && !baseLen.isMeasure() && ratio.numerator() > 0 && ratio.denominator() > 0;
     284              : }
     285              : 
     286          179 : static Fraction tupletEnd(const Staff* staff, const Fraction& tick, Tuplet* parent, const Fraction& ratio, const TDuration& baseLen)
     287              : {
     288          179 :     const Fraction ticks = baseLen.fraction() * ratio.denominator();
     289          179 :     return tick + actualTicks(ticks, parent, staff->timeStretch(tick));
     290              : }
     291              : 
     292              : // A tuplet must not cross a barline or the end of its parent tuplet
     293          136 : static Fraction tupletLimit(const Tuplet* parent, const Measure* measure)
     294              : {
     295          136 :     return parent ? parent->tick() + parent->actualTicks() : measure->endTick();
     296              : }
     297              : 
     298              : //---------------------------------------------------------
     299              : //   canAddTuplet
     300              : //    Whether addTuplet() can create a tuplet with this ratio
     301              : //    and base length at chordRest
     302              : //---------------------------------------------------------
     303              : 
     304          132 : bool Score::canAddTuplet(const ChordRest* chordRest, const Fraction& ratio, const TDuration& baseLen) const
     305              : {
     306          132 :     if (!chordRest || !isValidTuplet(ratio, baseLen)) {
     307            6 :         return false;
     308              :     }
     309              : 
     310          126 :     const Measure* measure = chordRest->measure();
     311          126 :     if (!measure || measure->isMMRest() || chordRest->isGrace()) {
     312            0 :         return false;
     313              :     }
     314              : 
     315              :     // changeCRlen() can't change the length of a measure repeat
     316          126 :     if (chordRest->isMeasureRepeat() && baseLen.fraction() * ratio.denominator() != chordRest->ticks()) {
     317            0 :         return false;
     318              :     }
     319              : 
     320          126 :     return tupletEndTick(chordRest, ratio, baseLen) <= tupletLimit(chordRest->tuplet(), measure);
     321              : }
     322              : 
     323              : //---------------------------------------------------------
     324              : //   canAddTuplet
     325              : //    The same at segment in track, where no chord/rest of
     326              : //    the track may start: an empty voice, or inside a
     327              : //    longer chord/rest
     328              : //---------------------------------------------------------
     329              : 
     330           25 : bool Score::canAddTuplet(const Segment* segment, track_idx_t track, const Fraction& ratio, const TDuration& baseLen) const
     331              : {
     332           25 :     if (!segment || track == muse::nidx) {
     333            1 :         return false;
     334              :     }
     335              : 
     336           24 :     if (const ChordRest* chordRest = segment->cr(track)) {
     337           13 :         return canAddTuplet(chordRest, ratio, baseLen);
     338              :     }
     339              : 
     340           11 :     const Measure* measure = segment->measure();
     341           11 :     const Staff* staff = this->staff(track2staff(track));
     342           11 :     if (!isValidTuplet(ratio, baseLen) || !measure || measure->isMMRest() || !staff) {
     343            1 :         return false;
     344              :     }
     345              : 
     346              :     // inside a longer chord/rest, the tuplet would be in that chord/rest's tuplet
     347           10 :     const ChordRest* previous = segment->nextChordRest(track, /*backwards*/ true, /*stopAtMeasureBoundary*/ true);
     348           10 :     Tuplet* parent = previous && previous->endTick() > segment->tick() ? previous->tuplet() : nullptr;
     349              : 
     350           10 :     return tupletEnd(staff, segment->tick(), parent, ratio, baseLen) <= tupletLimit(parent, measure);
     351              : }
     352              : 
     353              : //---------------------------------------------------------
     354              : //   tupletEndTick
     355              : //    Where a tuplet of ratio.denominator() * baseLen that
     356              : //    starts at chordRest ends
     357              : //---------------------------------------------------------
     358              : 
     359          169 : Fraction Score::tupletEndTick(const ChordRest* chordRest, const Fraction& ratio, const TDuration& baseLen) const
     360              : {
     361          169 :     return tupletEnd(chordRest->staff(), chordRest->tick(), chordRest->tuplet(), ratio, baseLen);
     362              : }
     363              : 
     364              : //---------------------------------------------------------
     365              : //   addTuplet
     366              : //    Create a tuplet of ratio.denominator() * baseLen, starting
     367              : //    at destinationChordRest and replacing everything in that
     368              : //    time in its track. The tuplet can be longer or shorter than
     369              : //    destinationChordRest, but must not cross a barline or the end
     370              : //    of a parent tuplet.
     371              : //---------------------------------------------------------
     372              : 
     373           61 : Tuplet* Score::addTuplet(ChordRest* destinationChordRest, const Fraction& ratio, const TDuration& baseLen,
     374              :                          TupletNumberType numberType, TupletBracketType bracketType)
     375              : {
     376           61 :     if (!canAddTuplet(destinationChordRest, ratio, baseLen)) {
     377            2 :         LOGD() << "cannot create tuplet with ratio " << ratio.toString()
     378            1 :                << " for duration " << (baseLen.fraction() * ratio.denominator()).toString();
     379            1 :         MScore::setError(isValidTuplet(ratio, baseLen) ? MsError::NO_SPACE_FOR_TUPLET : MsError::TUPLET_RATIO_NOT_POSSIBLE);
     380            1 :         return nullptr;
     381              :     }
     382              : 
     383           60 :     Measure* measure = destinationChordRest->measure();
     384           60 :     Tuplet* ot = destinationChordRest->tuplet();
     385           60 :     const Fraction f = baseLen.fraction() * ratio.denominator();
     386              : 
     387              :     // Shorten a longer chord/rest first, so that the remainder is filled with rests. Shorten it to
     388              :     // the base length, since changeCRlen() only shortens correctly to a single note value
     389           60 :     if (destinationChordRest->ticks() > f) {
     390            4 :         changeCRlen(destinationChordRest, baseLen.fraction());
     391              :     }
     392              : 
     393              :     // Clear the rest of the time the tuplet will take
     394           60 :     if (destinationChordRest->ticks() < f) {
     395           29 :         makeGap(destinationChordRest->segment(), destinationChordRest->track(), f, ot, /*keepChord*/ true);
     396              :     }
     397              : 
     398           60 :     Tuplet* tuplet = Factory::createTuplet(measure);
     399           60 :     tuplet->setRatio(ratio);
     400              : 
     401           60 :     tuplet->setNumberType(numberType);
     402           60 :     if (tuplet->numberType() == TupletNumberType(tuplet->style().styleI(Sid::tupletNumberType))) {
     403           60 :         tuplet->setPropertyFlags(Pid::NUMBER_TYPE, PropertyFlags::STYLED);
     404              :     } else {
     405            0 :         tuplet->setPropertyFlags(Pid::NUMBER_TYPE, PropertyFlags::UNSTYLED);
     406              :     }
     407              : 
     408           60 :     tuplet->setBracketType(bracketType);
     409           60 :     if (tuplet->bracketType() == TupletBracketType(tuplet->style().styleI(Sid::tupletBracketType))) {
     410           60 :         tuplet->setPropertyFlags(Pid::BRACKET_TYPE, PropertyFlags::STYLED);
     411              :     } else {
     412            0 :         tuplet->setPropertyFlags(Pid::BRACKET_TYPE, PropertyFlags::UNSTYLED);
     413              :     }
     414              : 
     415           60 :     tuplet->setTicks(f);
     416           60 :     tuplet->setBaseLen(baseLen);
     417              : 
     418           60 :     tuplet->setTrack(destinationChordRest->track());
     419           60 :     tuplet->setTick(destinationChordRest->tick());
     420              : 
     421           60 :     if (ot) {
     422           10 :         tuplet->setTuplet(ot);
     423              :     }
     424              : 
     425           60 :     cmdCreateTuplet(destinationChordRest, tuplet);
     426              : 
     427           60 :     return tuplet;
     428              : }
     429              : 
     430              : //---------------------------------------------------------
     431              : //   selectNewTuplet
     432              : //    Select where input continues in a new tuplet, and use
     433              : //    its base length as the input duration
     434              : //---------------------------------------------------------
     435              : 
     436            0 : void Score::selectNewTuplet(Tuplet* tuplet)
     437              : {
     438            0 :     const std::vector<DurationElement*>& elements = tuplet->elements();
     439            0 :     DurationElement* elementForSelect = nullptr;
     440            0 :     if (!elements.empty()) {
     441            0 :         DurationElement* firstElement = elements.front();
     442            0 :         if (firstElement->isRest()) {
     443            0 :             elementForSelect = firstElement;
     444            0 :         } else if (elements.size() > 1) {
     445            0 :             elementForSelect = elements[1];
     446              :         }
     447              :     }
     448              : 
     449            0 :     if (elementForSelect) {
     450            0 :         score()->select(elementForSelect, SelectType::SINGLE, 0);
     451            0 :         score()->inputState().setDuration(tuplet->baseLen());
     452              :     }
     453            0 : }
     454              : 
     455              : //---------------------------------------------------------
     456              : //   addRest
     457              : //    create one Rest at tick with duration d
     458              : //    create segment if necessary
     459              : //---------------------------------------------------------
     460              : 
     461         1286 : Rest* Score::addRest(const Fraction& tick, track_idx_t track, TDuration d, Tuplet* tuplet)
     462              : {
     463         1286 :     Measure* measure = tick2measure(tick);
     464         1286 :     Rest* rest = Factory::createRest(this->dummy(), d);
     465         1286 :     if (d.type() == DurationType::V_MEASURE) {
     466          898 :         rest->setTicks(measure->stretchedLen(staff(track2staff(track))));
     467              :     } else {
     468          388 :         rest->setTicks(d.fraction());
     469              :     }
     470         1286 :     rest->setTrack(track);
     471         1286 :     rest->setTuplet(tuplet);
     472         1286 :     undoAddCR(rest, measure, tick);
     473         1286 :     return rest;
     474              : }
     475              : 
     476              : //---------------------------------------------------------
     477              : //   addRest
     478              : //---------------------------------------------------------
     479              : 
     480           77 : Rest* Score::addRest(Segment* s, track_idx_t track, TDuration d, Tuplet* tuplet)
     481              : {
     482           77 :     Rest* rest = Factory::createRest(s, d);
     483           77 :     if (d.type() == DurationType::V_MEASURE) {
     484           44 :         rest->setTicks(s->measure()->stretchedLen(staff(track / VOICES)));
     485              :     } else {
     486           33 :         rest->setTicks(d.fraction());
     487              :     }
     488           77 :     rest->setTrack(track);
     489           77 :     rest->setTuplet(tuplet);
     490           77 :     undoAddCR(rest, tick2measure(s->tick()), s->tick());
     491           77 :     return rest;
     492              : }
     493              : 
     494              : //---------------------------------------------------------
     495              : //   addChord
     496              : //    Create one Chord at tick with duration d
     497              : //    - create segment if necessary.
     498              : //    - Use chord "oc" as prototype;
     499              : //    - if "genTie" then tie to chord "oc"
     500              : //---------------------------------------------------------
     501              : 
     502            1 : Chord* Score::addChord(const Fraction& tick, TDuration d, Chord* oc, bool genTie, Tuplet* tuplet)
     503              : {
     504            1 :     Measure* measure = tick2measure(tick);
     505            1 :     if (measure->endTick() <= tick) {
     506            0 :         LOGD("Score::addChord(): end of score?");
     507            0 :         return 0;
     508              :     }
     509              : 
     510            1 :     Chord* chord = Factory::createChord(this->dummy());
     511            1 :     chord->setTuplet(tuplet);
     512            1 :     chord->setTrack(oc->track());
     513            1 :     chord->setDurationType(d);
     514            1 :     chord->setTicks(d.fraction());
     515            1 :     chord->setStemDirection(oc->stemDirection());
     516              : 
     517            2 :     for (Note* n : oc->notes()) {
     518            1 :         Note* nn = Factory::createNote(chord);
     519            1 :         nn->setPitch(n->pitch());
     520            1 :         nn->setTpc1(n->tpc1());
     521            1 :         nn->setTpc2(n->tpc2());
     522            1 :         chord->add(nn);
     523              :     }
     524            1 :     undoAddCR(chord, measure, tick);
     525              : 
     526              :     //
     527              :     // now as both chords are in place
     528              :     // (have segments as parent) we can add ties:
     529              :     //
     530            1 :     if (genTie) {
     531            1 :         size_t n = oc->notes().size();
     532            2 :         for (size_t i = 0; i < n; ++i) {
     533            1 :             Note* n1  = oc->notes()[i];
     534            1 :             Note* n2 = chord->notes()[i];
     535            1 :             Tie* tie = Factory::createTie(n1);
     536            1 :             tie->setStartNote(n1);
     537            1 :             tie->setEndNote(n2);
     538            1 :             tie->setTick(tie->startNote()->tick());
     539            1 :             tie->setTick2(tie->endNote()->tick());
     540            1 :             tie->setTrack(n1->track());
     541            1 :             undoAddElement(tie);
     542              :         }
     543              :     }
     544              : 
     545            1 :     return chord;
     546              : }
     547              : 
     548              : //---------------------------------------------------------
     549              : //   addClone
     550              : //---------------------------------------------------------
     551              : 
     552          480 : ChordRest* Score::addClone(ChordRest* cr, const Fraction& tick, const TDuration& d)
     553              : {
     554              :     ChordRest* newcr;
     555              :     // change a MeasureRepeat into an Rest
     556          480 :     if (cr->isMeasureRepeat()) {
     557            0 :         newcr = Factory::copyRest(*toRest(cr));
     558            0 :         toRest(newcr)->hack_toRestType();
     559              :     } else {
     560          480 :         newcr = toChordRest(cr->clone());
     561              :     }
     562          480 :     newcr->mutldata()->setPosX(0.0);
     563          480 :     newcr->setDurationType(d);
     564          480 :     newcr->setTicks(d.isMeasure() ? cr->measure()->stretchedLen(cr->staff()) : d.fraction());
     565          480 :     newcr->setTuplet(cr->tuplet());
     566          480 :     newcr->setSelected(false);
     567          480 :     if (newcr->isChord()) {
     568            3 :         muse::DeleteAll(toChord(newcr)->graceNotes());
     569            3 :         toChord(newcr)->removeAllGraceNotes();
     570              :     }
     571              : 
     572          480 :     undoAddCR(newcr, cr->measure(), tick);
     573          480 :     return newcr;
     574              : }
     575              : 
     576              : //---------------------------------------------------------
     577              : //   setRest
     578              : //    sets rests and returns the first one
     579              : //    "l" is in local (stretched) time
     580              : //---------------------------------------------------------
     581              : 
     582          939 : Rest* Score::setRest(const Fraction& _tick, track_idx_t track, const Fraction& _l, bool useDots, Tuplet* tuplet, bool useFullMeasureRest)
     583              : {
     584          939 :     std::vector<Rest*> rests = setRests(_tick, track, _l, useDots, tuplet, useFullMeasureRest);
     585         1878 :     return rests.empty() ? nullptr : rests.front();
     586          939 : }
     587              : 
     588              : //---------------------------------------------------------
     589              : //   setRests
     590              : //    create one or more rests to fill "l"
     591              : //    "l" is in local (stretched) time
     592              : //---------------------------------------------------------
     593              : 
     594         1339 : std::vector<Rest*> Score::setRests(const Fraction& _tick, track_idx_t track, const Fraction& _l, bool useDots, Tuplet* tuplet,
     595              :                                    bool useFullMeasureRest)
     596              : {
     597         1339 :     Fraction l       = _l;
     598         1339 :     Fraction tick    = _tick;
     599         1339 :     Measure* measure = tick2measure(tick);
     600         1339 :     std::vector<Rest*> rests;
     601         1339 :     Staff* staff     = Score::staff(track / VOICES);
     602              : 
     603         2163 :     while (!l.isZero()) {
     604              :         //
     605              :         // divide into measures
     606              :         //
     607         1208 :         Fraction f;
     608         1208 :         if (tuplet) {
     609           75 :             f = tuplet->baseLen().fraction() * tuplet->ratio().numerator();
     610          156 :             for (DurationElement* de : tuplet->elements()) {
     611          119 :                 if (de->tick() >= tick) {
     612           38 :                     break;
     613              :                 }
     614           81 :                 f -= de->ticks();
     615              :             }
     616              :             //
     617              :             // restrict to tuplet len
     618              :             //
     619           75 :             if (f < l) {
     620            0 :                 l = f;
     621              :             }
     622              :         } else {
     623         1133 :             if (measure->tick() < tick) {
     624          185 :                 f = measure->endTick() - tick;
     625              :             } else {
     626          948 :                 f = measure->ticks();
     627              :             }
     628         1133 :             f *= staff->timeStretch(tick);
     629              :         }
     630              : 
     631         1208 :         if (f > l) {
     632          153 :             f = l;
     633              :         }
     634              : 
     635              :         // Don't fill a full measure with rests on a non-zero voice, *unless* it has links in voice zero
     636         1208 :         bool fullMeasure = tick == measure->tick() && f == measure->stretchedLen(staff);
     637         1208 :         bool emptyNonZeroVoice = track2voice(track) != 0 && !measure->hasVoice(track);
     638         1208 :         if (emptyNonZeroVoice && fullMeasure && !staff->trackHasLinksInVoiceZero(track)) {
     639           17 :             l -= f;
     640           17 :             measure = measure->nextMeasure();
     641           17 :             if (!measure) {
     642          384 :                 break;
     643              :             }
     644           17 :             tick = measure->tick();
     645           17 :             continue;
     646              :         }
     647              : 
     648         1191 :         if ((measure->timesig() == measure->ticks())       // not in pickup measure
     649         1177 :             && fullMeasure
     650          882 :             && !tuplet
     651         2368 :             && useFullMeasureRest) {
     652          882 :             Rest* rest = addRest(tick, track, TDuration(DurationType::V_MEASURE), tuplet);
     653          882 :             tick += rest->actualTicks();
     654          882 :             rests.push_back(rest);
     655              :         } else {
     656              :             //
     657              :             // compute list of durations which will fit l
     658              :             //
     659          309 :             std::vector<TDuration> dList;
     660          309 :             if (tuplet || f == Fraction(0, 1)) {
     661           75 :                 dList = toDurationList(l, useDots);
     662           75 :                 std::reverse(dList.begin(), dList.end());
     663              :             } else {
     664          234 :                 Fraction timeStretch = staff->timeStretch(tick);
     665          702 :                 dList = toRhythmicDurationList(f, true, (tick - measure->tick()) * timeStretch, sigmap()->timesig(
     666          702 :                                                    tick).nominal(), measure, useDots ? 1 : 0, timeStretch);
     667              :             }
     668          309 :             if (dList.empty()) {
     669            0 :                 return rests;
     670              :             }
     671              : 
     672          309 :             Rest* rest = 0;
     673          698 :             for (const TDuration& d : dList) {
     674          389 :                 rest = addRest(tick, track, d, tuplet);
     675              :                 // If we're filling an empty non-zero voice make these gaps
     676          389 :                 rest->setGap(emptyNonZeroVoice && !fullMeasure);
     677          389 :                 rests.push_back(rest);
     678          389 :                 tick += rest->actualTicks();
     679              :             }
     680          309 :         }
     681         1191 :         l -= f;
     682              : 
     683         1191 :         measure = measure->nextMeasure();
     684         1191 :         if (!measure) {
     685          384 :             break;
     686              :         }
     687          807 :         tick = measure->tick();
     688              :     }
     689         1339 :     return rests;
     690            0 : }
     691              : 
     692           13 : Slur* Score::addSlur(ChordRest* firstChordRest, ChordRest* secondChordRest, const Slur* slurTemplate)
     693              : {
     694           13 :     if (!secondChordRest) {
     695            6 :         ChordRestNavigateOptions options;
     696            6 :         options.disableOverRepeats = true;
     697            6 :         secondChordRest = Navigation::nextChordRest(firstChordRest, options);
     698              : 
     699            6 :         if (!secondChordRest || !secondChordRest->isChord()) {
     700            0 :             if (slurTemplate && slurTemplate->isHammerOnPullOff() && firstChordRest->isChord()) {
     701            0 :                 Note* endNote = GuitarBend::createEndNote(toChord(firstChordRest)->upNote());
     702            0 :                 if (endNote) {
     703            0 :                     secondChordRest = endNote->chord();
     704              :                 }
     705              :             }
     706            0 :             if (!secondChordRest) {
     707            0 :                 secondChordRest = firstChordRest;
     708              :             }
     709            6 :         } else if (secondChordRest->isChord()) {
     710           12 :             bool firstChordRestIsTiedToSecond = firstChordRest->isChord() && toChord(firstChordRest)->allNotesTiedToNext()
     711           12 :                                                 && toChord(firstChordRest)->upNote()->tieFor()->endNote()->parent() == secondChordRest;
     712              : 
     713              :             // Follow chain of tied notes and slur until the last
     714            6 :             if (firstChordRestIsTiedToSecond || !firstChordRest->isGrace()) {
     715            9 :                 while (toChord(secondChordRest)->allNotesTiedToNext()) {
     716            3 :                     secondChordRest = toChord(secondChordRest)->upNote()->tieFor()->endNote()->chord();
     717              :                 }
     718              :             }
     719              : 
     720              :             // If the first chord rest is also tied to this chain, slur to the next non-tied note
     721            6 :             if (firstChordRestIsTiedToSecond) {
     722            1 :                 ChordRest* nextCandidate = Navigation::nextChordRest(secondChordRest, options);
     723            1 :                 if (nextCandidate) {
     724            1 :                     secondChordRest = nextCandidate;
     725              :                 }
     726              :             }
     727              :         }
     728              :     }
     729              : 
     730           13 :     Slur* slur = slurTemplate ? slurTemplate->clone() : Factory::createSlur(score()->dummy());
     731           13 :     slur->setScore(firstChordRest->score());
     732           13 :     slur->setTick(firstChordRest->tick());
     733           13 :     slur->setTick2(secondChordRest->tick());
     734           13 :     slur->setTrack(firstChordRest->track());
     735           13 :     if (secondChordRest->staff()->part() == firstChordRest->staff()->part()
     736           13 :         && !secondChordRest->staff()->isLinked(firstChordRest->staff())) {
     737           13 :         slur->setTrack2(secondChordRest->track());
     738              :     } else {
     739            0 :         slur->setTrack2(firstChordRest->track());
     740              :     }
     741           13 :     slur->setStartElement(firstChordRest);
     742           13 :     slur->setEndElement(secondChordRest);
     743              : 
     744           13 :     firstChordRest->score()->undoAddElement(slur);
     745           13 :     SlurTieSegment* ss = slur->newSlurTieSegment();
     746           13 :     ss->setSpannerSegmentType(SpannerSegmentType::SINGLE);
     747           13 :     if (firstChordRest == secondChordRest && !(slur->isOutgoing() || slur->isIncoming())) {
     748            0 :         ss->setSlurOffset(Grip::END, PointF(3.0 * firstChordRest->style().spatium(), 0.0));
     749              :     }
     750           13 :     slur->add(ss);
     751              : 
     752           13 :     return slur;
     753              : }
     754              : 
     755              : /// The segment that holds the annotations of `chordRest`. For a multimeasure rest,
     756              : /// that is the corresponding segment of the first underlying measure.
     757            0 : static Segment* annotationSegment(const ChordRest* chordRest)
     758              : {
     759            0 :     const Measure* measure = chordRest->measure();
     760            0 :     if (measure && measure->isMMRest()) {
     761            0 :         return measure->mmRestFirst()->findSegmentR(SegmentType::ChordRest, Fraction(0, 1));
     762              :     }
     763              : 
     764            0 :     return chordRest->segment();
     765              : }
     766              : 
     767            1 : TextBase* Score::addText(TextStyleType type, EngravingItem* destinationElement)
     768              : {
     769            1 :     TextBase* textBox = nullptr;
     770              : 
     771            1 :     switch (type) {
     772            0 :     case TextStyleType::TITLE:
     773              :     case TextStyleType::SUBTITLE:
     774              :     case TextStyleType::COMPOSER:
     775              :     case TextStyleType::LYRICIST:
     776              :     case TextStyleType::INSTRUMENT_EXCERPT: {
     777            0 :         MeasureBase* frame = nullptr;
     778              : 
     779            0 :         if (destinationElement && destinationElement->isVBox()) {
     780            0 :             frame = toMeasureBase(destinationElement);
     781              :         } else {
     782            0 :             frame = first();
     783            0 :             if (!frame || !frame->isBox()) {
     784            0 :                 frame = insertBox(ElementType::VBOX, frame);
     785              :             }
     786              :         }
     787              : 
     788            0 :         textBox = Factory::createText(frame, type);
     789            0 :         undoAddElement(textBox);
     790            0 :         break;
     791              :     }
     792            0 :     case TextStyleType::FRAME: {
     793            0 :         if (!destinationElement) {
     794            0 :             break;
     795              :         }
     796            0 :         textBox = Factory::createText(destinationElement, type);
     797            0 :         undoAddElement(textBox);
     798            0 :         break;
     799              :     }
     800            0 :     case TextStyleType::REHEARSAL_MARK: {
     801            0 :         ChordRest* chordRest = chordOrRest(destinationElement);
     802            0 :         if (!chordRest) {
     803            0 :             break;
     804              :         }
     805            0 :         textBox = Factory::createRehearsalMark(annotationSegment(chordRest));
     806            0 :         textBox->setTrack(chordRest->track());
     807            0 :         RehearsalMark* r = toRehearsalMark(textBox);
     808            0 :         textBox->setXmlText(EditRehearsalMark::createRehearsalMarkText(this, r));
     809            0 :         undoAddElement(textBox);
     810            0 :         break;
     811              :     }
     812            0 :     case TextStyleType::STAFF: {
     813            0 :         ChordRest* chordRest = chordOrRest(destinationElement);
     814            0 :         if (!chordRest) {
     815            0 :             break;
     816              :         }
     817            0 :         textBox = Factory::createStaffText(annotationSegment(chordRest), TextStyleType::STAFF);
     818            0 :         textBox->setTrack(chordRest->track());
     819            0 :         undoAddElement(textBox);
     820            0 :         break;
     821              :     }
     822            0 :     case TextStyleType::SYSTEM: {
     823            0 :         ChordRest* chordRest = chordOrRest(destinationElement);
     824            0 :         if (!chordRest) {
     825            0 :             break;
     826              :         }
     827            0 :         textBox = Factory::createSystemText(annotationSegment(chordRest), TextStyleType::SYSTEM);
     828            0 :         textBox->setTrack(chordRest->track());
     829            0 :         undoAddElement(textBox);
     830            0 :         break;
     831              :     }
     832            0 :     case TextStyleType::DYNAMICS: {
     833            0 :         ChordRest* chordRest = chordOrRest(destinationElement);
     834            0 :         if (!chordRest) {
     835            0 :             break;
     836              :         }
     837            0 :         textBox = Factory::createDynamic(annotationSegment(chordRest));
     838            0 :         textBox->setTrack(chordRest->track());
     839            0 :         undoAddElement(textBox);
     840            0 :         break;
     841              :     }
     842            0 :     case TextStyleType::EXPRESSION: {
     843            0 :         ChordRest* chordRest = chordOrRest(destinationElement);
     844            0 :         if (!chordRest) {
     845            0 :             break;
     846              :         }
     847            0 :         textBox = Factory::createExpression(annotationSegment(chordRest));
     848            0 :         textBox->setTrack(chordRest->track());
     849            0 :         undoAddElement(textBox);
     850            0 :         break;
     851              :     }
     852            0 :     case TextStyleType::INSTRUMENT_CHANGE: {
     853            0 :         ChordRest* chordRest = chordOrRest(destinationElement);
     854            0 :         if (!chordRest) {
     855            0 :             break;
     856              :         }
     857            0 :         textBox = Factory::createInstrumentChange(annotationSegment(chordRest));
     858            0 :         textBox->setTrack(chordRest->track());
     859            0 :         undoAddElement(textBox);
     860            0 :         break;
     861              :     }
     862            0 :     case TextStyleType::STICKING: {
     863            0 :         ChordRest* chordRest = chordOrRest(destinationElement);
     864            0 :         if (!chordRest) {
     865            0 :             break;
     866              :         }
     867            0 :         textBox = Factory::createSticking(annotationSegment(chordRest));
     868            0 :         textBox->setTrack(chordRest->track());
     869            0 :         undoAddElement(textBox);
     870            0 :         break;
     871              :     }
     872            0 :     case TextStyleType::FINGERING:
     873              :     case TextStyleType::LH_GUITAR_FINGERING:
     874              :     case TextStyleType::RH_GUITAR_FINGERING:
     875              :     case TextStyleType::STRING_NUMBER: {
     876            0 :         if (!destinationElement || !destinationElement->isNote()) {
     877            0 :             break;
     878              :         }
     879              : 
     880            0 :         const Staff* staff = destinationElement->staff();
     881            0 :         bool isTablature = staff->isTabStaff(destinationElement->tick());
     882            0 :         bool tabFingering = staff->staffType(destinationElement->tick())->showTabFingering();
     883            0 :         if (isTablature && !tabFingering) {
     884            0 :             break;
     885              :         }
     886              : 
     887            0 :         textBox = Factory::createFingering(toNote(destinationElement), type);
     888            0 :         textBox->setTrack(destinationElement->track());
     889            0 :         undoAddElement(textBox);
     890            0 :         break;
     891              :     }
     892            1 :     case TextStyleType::HARMONY_A:
     893              :     case TextStyleType::HARMONY_ROMAN:
     894              :     case TextStyleType::HARMONY_NASHVILLE: {
     895            1 :         track_idx_t track = muse::nidx;
     896            1 :         DummyParentOr<Segment, FretDiagram> newParent = dummy();
     897            1 :         if (destinationElement && destinationElement->isFretDiagram()) {
     898            1 :             FretDiagram* fretDiagram = toFretDiagram(destinationElement);
     899            1 :             track = fretDiagram->track();
     900            1 :             if (fretDiagram->harmony()) {
     901            0 :                 newParent = parentOrDummy(fretDiagram->segment(), dummy());
     902              :             } else {
     903            1 :                 newParent = fretDiagram;
     904              :             }
     905              :         } else {
     906            0 :             ChordRest* chordRest = chordOrRest(destinationElement);
     907            0 :             if (chordRest) {
     908            0 :                 track = chordRest->track();
     909            0 :                 newParent = parentOrDummy(chordRest->segment(), dummy());
     910              :             }
     911              :         }
     912              : 
     913            1 :         if (track == muse::nidx || newParent == dummy()) {
     914            0 :             break;
     915              :         }
     916              : 
     917            1 :         Harmony* harmony = Factory::createHarmony(newParent);
     918            1 :         harmony->setTrack(track);
     919              : 
     920              :         static const std::map<TextStyleType, HarmonyType> harmonyTypes = {
     921              :             { TextStyleType::HARMONY_A, HarmonyType::STANDARD },
     922              :             { TextStyleType::HARMONY_ROMAN, HarmonyType::ROMAN },
     923              :             { TextStyleType::HARMONY_NASHVILLE, HarmonyType::NASHVILLE }
     924            3 :         };
     925            1 :         harmony->setHarmonyType(harmonyTypes.at(type));
     926              : 
     927            1 :         textBox = harmony;
     928            1 :         undoAddElement(textBox);
     929            1 :         break;
     930              :     }
     931            0 :     case TextStyleType::LYRICS_ODD: {
     932            0 :         if (!destinationElement || (!destinationElement->isNote() && !destinationElement->isLyrics() && !destinationElement->isRest())) {
     933            0 :             break;
     934              :         }
     935            0 :         ChordRest* chordRest = nullptr;
     936            0 :         if (destinationElement->isNote()) {
     937            0 :             chordRest = toNote(destinationElement)->chord();
     938            0 :             if (chordRest->isGrace()) {
     939            0 :                 chordRest = toChordRest(chordRest->ownershipParent());
     940              :             }
     941            0 :         } else if (destinationElement->isLyrics()) {
     942            0 :             chordRest = toLyrics(destinationElement)->chordRest();
     943            0 :         } else if (destinationElement->isRest()) {
     944            0 :             chordRest = toChordRest(destinationElement);
     945              :         } else {
     946            0 :             break;
     947              :         }
     948              : 
     949            0 :         int no = static_cast<int>(chordRest->lyrics().size());
     950            0 :         const auto& spanners = spannerMap().findOverlapping(chordRest->tick().ticks(), chordRest->endTick().ticks());
     951            0 :         for (auto& spanner : spanners) {
     952            0 :             if (!spanner.value->isPartialLyricsLine() || spanner.start != chordRest->tick().ticks()) {
     953            0 :                 continue;
     954              :             }
     955            0 :             const PartialLyricsLine* line = toPartialLyricsLine(spanner.value);
     956              : 
     957            0 :             no = std::max(no, line->verse() + 1);
     958              :         }
     959              : 
     960              :         // Also check how many partial lines there are
     961            0 :         Lyrics* lyrics = Factory::createLyrics(chordRest);
     962            0 :         lyrics->setTrack(chordRest->track());
     963            0 :         lyrics->setProperty(Pid::VERSE, no);
     964              : 
     965            0 :         textBox = lyrics;
     966            0 :         undoAddElement(textBox);
     967            0 :         break;
     968              :     }
     969            0 :     case TextStyleType::TEMPO: {
     970            0 :         ChordRest* chordRest = chordOrRest(destinationElement);
     971            0 :         if (!chordRest) {
     972            0 :             break;
     973              :         }
     974              : 
     975            0 :         SigEvent event = sigmap()->timesig(chordRest->tick());
     976            0 :         Fraction f = event.nominal();
     977            0 :         String text(u"<sym>metNoteQuarterUp</sym> = 80");
     978            0 :         switch (f.denominator()) {
     979            0 :         case 1:
     980            0 :             text = u"<sym>metNoteWhole</sym> = 80";
     981            0 :             break;
     982            0 :         case 2:
     983            0 :             text = u"<sym>metNoteHalfUp</sym> = 80";
     984            0 :             break;
     985            0 :         case 4:
     986            0 :             text = u"<sym>metNoteQuarterUp</sym> = 80";
     987            0 :             break;
     988            0 :         case 8:
     989            0 :             if (f.numerator() % 3 == 0) {
     990            0 :                 text = u"<sym>metNoteQuarterUp</sym><sym>space</sym><sym>metAugmentationDot</sym> = 80";
     991              :             } else {
     992            0 :                 text = u"<sym>metNote8thUp</sym> = 80";
     993              :             }
     994            0 :             break;
     995            0 :         case 16:
     996            0 :             if (f.numerator() % 3 == 0) {
     997            0 :                 text = u"<sym>metNote8thUp</sym><sym>space</sym><sym>metAugmentationDot</sym> = 80";
     998              :             } else {
     999            0 :                 text = u"<sym>metNote16thUp</sym> = 80";
    1000              :             }
    1001            0 :             break;
    1002            0 :         case 32:
    1003            0 :             if (f.numerator() % 3 == 0) {
    1004            0 :                 text = u"<sym>metNote16thUp</sym><sym>space</sym><sym>metAugmentationDot</sym> = 80";
    1005              :             } else {
    1006            0 :                 text = u"<sym>metNote32ndUp</sym> = 80";
    1007              :             }
    1008            0 :             break;
    1009            0 :         case 64:
    1010            0 :             if (f.numerator() % 3 == 0) {
    1011            0 :                 text = u"<sym>metNote32ndUp</sym><sym>space</sym><sym>metAugmentationDot</sym> = 80";
    1012              :             } else {
    1013            0 :                 text = u"<sym>metNote64thUp</sym> = 80";
    1014              :             }
    1015            0 :             break;
    1016            0 :         case 128:
    1017            0 :             if (f.numerator() % 3 == 0) {
    1018            0 :                 text = u"<sym>metNote64ndUp</sym><sym>space</sym><sym>metAugmentationDot</sym> = 80";
    1019              :             } else {
    1020            0 :                 text = u"<sym>metNote128thUp</sym> = 80";
    1021              :             }
    1022            0 :             break;
    1023            0 :         default:
    1024            0 :             break;
    1025              :         }
    1026              : 
    1027            0 :         TempoText* tempoText = Factory::createTempoText(chordRest->segment());
    1028            0 :         tempoText->setTrack(0);
    1029            0 :         tempoText->setXmlText(text);
    1030            0 :         tempoText->setFollowText(true);
    1031            0 :         tempoText->updateTempo();
    1032              : 
    1033            0 :         textBox = tempoText;
    1034            0 :         undoAddElement(textBox);
    1035            0 :         break;
    1036            0 :     }
    1037            0 :     case TextStyleType::HARP_PEDAL_DIAGRAM:
    1038              :     case TextStyleType::HARP_PEDAL_TEXT_DIAGRAM: {
    1039            0 :         ChordRest* chordRest = getSelectedChordRest();
    1040            0 :         if (!chordRest) {
    1041            0 :             break;
    1042              :         }
    1043            0 :         textBox = Factory::createHarpPedalDiagram(annotationSegment(chordRest));
    1044            0 :         textBox->setTrack(chordRest->track());
    1045            0 :         undoAddElement(textBox);
    1046            0 :         break;
    1047              :     }
    1048            0 :     default:
    1049            0 :         break;
    1050              :     }
    1051              : 
    1052            1 :     return textBox;
    1053              : }
    1054              : 
    1055              : //---------------------------------------------------------
    1056              : //   searchNote
    1057              : //    search for note or rest before or at tick position tick
    1058              : //    in staff
    1059              : //---------------------------------------------------------
    1060              : 
    1061            0 : ChordRest* Score::searchNote(const Fraction& tick, track_idx_t track) const
    1062              : {
    1063            0 :     ChordRest* ipe = 0;
    1064            0 :     SegmentType st = SegmentType::ChordRest;
    1065            0 :     for (Segment* segment = firstSegment(st); segment; segment = segment->next1(st)) {
    1066            0 :         ChordRest* cr = segment->cr(track);
    1067            0 :         if (!cr) {
    1068            0 :             continue;
    1069              :         }
    1070            0 :         if (cr->tick() == tick) {
    1071            0 :             return cr;
    1072              :         }
    1073            0 :         if (cr->tick() > tick) {
    1074            0 :             return ipe ? ipe : cr;
    1075              :         }
    1076            0 :         ipe = cr;
    1077              :     }
    1078            0 :     return 0;
    1079              : }
    1080              : 
    1081              : //---------------------------------------------------------
    1082              : //   cmdAddOttava
    1083              : //---------------------------------------------------------
    1084              : 
    1085            0 : void Score::cmdAddOttava(OttavaType type)
    1086              : {
    1087            0 :     const Selection sel = selection();   // copy selection state before the operation.
    1088              :     // add on each staff if possible
    1089            0 :     if (sel.isRange() && sel.staffStart() != sel.staffEnd() - 1) {
    1090            0 :         for (staff_idx_t staffIdx = sel.staffStart(); staffIdx < sel.staffEnd(); ++staffIdx) {
    1091            0 :             ChordRest* cr1 = sel.firstChordRest(staffIdx * VOICES);
    1092            0 :             ChordRest* cr2 = sel.lastChordRest(staffIdx * VOICES);
    1093            0 :             if (!cr1) {
    1094            0 :                 continue;
    1095              :             }
    1096            0 :             if (!cr2) {
    1097            0 :                 cr2 = cr1;
    1098              :             }
    1099            0 :             Ottava* ottava = Factory::createOttava(this->dummy());
    1100            0 :             ottava->setOttavaType(type);
    1101            0 :             if (type == OttavaType::OTTAVA_8VB /*|| type == OttavaType::OTTAVA_15MB || type == OttavaType::OTTAVA_22MB*/) {
    1102            0 :                 ottava->setPlacement(PlacementV::BELOW);
    1103            0 :                 ottava->styleChanged();
    1104              :             }
    1105            0 :             ottava->setTrack(cr1->track());
    1106            0 :             ottava->setTrack2(cr1->track());
    1107            0 :             ottava->setTick(cr1->tick());
    1108            0 :             ottava->setTick2(cr2->endTick());
    1109            0 :             undoAddElement(ottava);
    1110              :         }
    1111              :     } else {
    1112              :         ChordRest* cr1;
    1113              :         ChordRest* cr2;
    1114            0 :         getSelectedStartEndChordRests(cr1, cr2);
    1115            0 :         if (!cr1) {
    1116            0 :             return;
    1117              :         }
    1118            0 :         if (!cr2) {
    1119            0 :             cr2 = cr1;
    1120              :         }
    1121              : 
    1122            0 :         Ottava* ottava = Factory::createOttava(this->dummy());
    1123            0 :         ottava->setOttavaType(type);
    1124            0 :         if (type == OttavaType::OTTAVA_8VB /*|| type == OttavaType::OTTAVA_15MB || type == OttavaType::OTTAVA_22MB*/) {
    1125            0 :             ottava->setPlacement(PlacementV::BELOW);
    1126            0 :             ottava->styleChanged();
    1127              :         }
    1128            0 :         ottava->setTrack(cr1->track());
    1129            0 :         ottava->setTrack2(cr1->track());
    1130            0 :         ottava->setTick(cr1->tick());
    1131            0 :         ottava->setTick2(cr2->endTick());
    1132            0 :         undoAddElement(ottava);
    1133            0 :         if (!noteEntryMode()) {
    1134            0 :             select(ottava, SelectType::SINGLE, 0);
    1135              :         }
    1136              :     }
    1137            0 : }
    1138              : 
    1139              : //---------------------------------------------------------
    1140              : //   cmdAddNoteLine
    1141              : //---------------------------------------------------------
    1142              : 
    1143            0 : void Score::addNoteLine()
    1144              : {
    1145            0 :     std::vector<Note*> selectedNotes;
    1146              : 
    1147            0 :     if (selection().isRange()) {
    1148            0 :         track_idx_t startTrack = selection().staffStart() * VOICES;
    1149            0 :         track_idx_t endTrack = selection().staffEnd() * VOICES;
    1150              : 
    1151            0 :         for (track_idx_t track = startTrack; track < endTrack; ++track) {
    1152            0 :             std::vector<Note*> notes = selection().noteList(track);
    1153            0 :             selectedNotes.insert(selectedNotes.end(), notes.begin(), notes.end());
    1154            0 :         }
    1155              :     } else {
    1156            0 :         std::vector<Note*> notes = selection().noteList();
    1157            0 :         selectedNotes.insert(selectedNotes.end(), notes.begin(), notes.end());
    1158            0 :     }
    1159              : 
    1160            0 :     Note* startNote = nullptr;
    1161            0 :     Note* endNote  = nullptr;
    1162              : 
    1163            0 :     for (Note* note : selectedNotes) {
    1164            0 :         if (startNote == nullptr || startNote->chord()->tick() > note->chord()->tick()) {
    1165            0 :             startNote = note;
    1166              :         }
    1167            0 :         if (endNote == nullptr || endNote->chord()->tick() < note->chord()->tick()) {
    1168            0 :             endNote = note;
    1169              :         }
    1170              :     }
    1171              : 
    1172            0 :     if (!startNote) {
    1173            0 :         LOGD("addNoteLine: no first note %p", startNote);
    1174            0 :         return;
    1175              :     }
    1176              : 
    1177            0 :     if (startNote == endNote) {
    1178            0 :         endNote = SLine::guessFinalNote(startNote);
    1179              :     }
    1180              : 
    1181            0 :     if (!endNote) {
    1182            0 :         LOGD("addNoteLine: no last note note %p", endNote);
    1183            0 :         return;
    1184              :     }
    1185              : 
    1186            0 :     NoteLine* line = Factory::createNoteLine(startNote);
    1187            0 :     line->setStartElement(startNote);
    1188            0 :     line->setTick(startNote->chord()->tick());
    1189            0 :     line->setEndElement(endNote);
    1190              : 
    1191            0 :     undoAddElement(line);
    1192            0 : }
    1193              : 
    1194              : //---------------------------------------------------------
    1195              : //   deleteItem
    1196              : //---------------------------------------------------------
    1197              : 
    1198           81 : void Score::deleteItem(EngravingItem* el)
    1199              : {
    1200           81 :     if (!el) {
    1201            0 :         return;
    1202              :     }
    1203              : 
    1204           81 :     if (el->generated()) {
    1205           22 :         switch (el->type()) {
    1206              :         // These types can be removed, even if generated
    1207           16 :         case ElementType::BAR_LINE:
    1208              :         case ElementType::BRACKET:
    1209              :         case ElementType::CLEF:
    1210              :         case ElementType::INSTRUMENT_NAME:
    1211              :         case ElementType::KEYSIG:
    1212              :         case ElementType::MEASURE_NUMBER:
    1213              :         case ElementType::SYSTEM_LOCK_INDICATOR:
    1214              :         case ElementType::PAGE_LOCK_INDICATOR:
    1215              :         case ElementType::HAMMER_ON_PULL_OFF_TEXT:
    1216              :         case ElementType::PLAY_COUNT_TEXT:
    1217              :         case ElementType::LYRICSLINE_SEGMENT:
    1218              :         case ElementType::STAVE_SHARING_CHANGE:
    1219           16 :             break;
    1220              :         // All other types cannot be removed if generated
    1221            6 :         default:
    1222            6 :             return;
    1223              :         }
    1224              :     }
    1225              : //      LOGD("%s", el->typeName());
    1226              : 
    1227           75 :     Transaction& tx = transactionManager()->currentOrDummyTransaction();
    1228              : 
    1229           75 :     switch (el->type()) {
    1230            0 :     case ElementType::INSTRUMENT_NAME: {
    1231            0 :         Part* part = el->part();
    1232            0 :         InstrumentName* in = toInstrumentName(el);
    1233            0 :         if (in->instrumentNameType() == InstrumentNameType::LONG) {
    1234            0 :             tx.push(new ChangeInstrumentLong(Fraction(0, 1), part, String()));
    1235            0 :         } else if (in->instrumentNameType() == InstrumentNameType::SHORT) {
    1236            0 :             tx.push(new ChangeInstrumentShort(Fraction(0, 1), part, String()));
    1237              :         }
    1238              :     }
    1239            0 :     break;
    1240              : 
    1241            0 :     case ElementType::TIMESIG: {
    1242              :         // timesig might already be removed
    1243            0 :         TimeSig* ts = toTimeSig(el);
    1244            0 :         Segment* s = ts->segment();
    1245            0 :         Measure* m = s->measure();
    1246            0 :         Segment* ns = m->findSegment(s->segmentType(), s->tick());
    1247            0 :         if (!ns || (ns->element(ts->track()) != ts)) {
    1248            0 :             LOGD("deleteItem: not found");
    1249            0 :             break;
    1250              :         }
    1251            0 :         EditTimeSig::removeTimeSig(tx, this, ts);
    1252              :     }
    1253            0 :     break;
    1254              : 
    1255            2 :     case ElementType::KEYSIG:
    1256              :     {
    1257            2 :         KeySig* k = toKeySig(el);
    1258            2 :         Segment* nextCrSeg = k->segment()->next1(SegmentType::ChordRest);
    1259            2 :         const TrackRange trackRange = el->part()->trackRange();
    1260            4 :         bool ic = nextCrSeg && nextCrSeg->findAnnotation(ElementType::INSTRUMENT_CHANGE,
    1261            2 :                                                          trackRange.startTrack, trackRange.endTrack - 1);
    1262            2 :         undoRemoveElement(k);
    1263            2 :         if (ic) {
    1264            0 :             KeySigEvent ke = k->keySigEvent();
    1265            0 :             ke.setForInstrumentChange(true);
    1266            0 :             Key cKey = k->staff()->keySigEvent(k->tick()).concertKey();
    1267            0 :             Key tKey = cKey;
    1268            0 :             if (!style().styleB(Sid::concertPitch)) {
    1269            0 :                 Interval v = k->part()->instrument(k->tick())->transpose();
    1270            0 :                 v.flip();
    1271            0 :                 tKey = Transpose::transposeKey(cKey, v, k->part()->preferSharpFlat());
    1272              :             }
    1273            0 :             ke.setConcertKey(cKey);
    1274            0 :             ke.setKey(tKey);
    1275            0 :             EditKeySig::undoChangeKeySig(tx, this, k->staff(), k->tick(), ke);
    1276            0 :         }
    1277            4 :         for (size_t i = 0; i < k->part()->nstaves(); i++) {
    1278            6 :             for (Staff* staff : k->part()->staff(i)->staffList()) {
    1279            4 :                 KeySigEvent e = staff->keySigEvent(k->tick());
    1280            4 :                 staff->score()->updateInstrumentChangeTranspositions(e, staff, k->tick());
    1281            6 :             }
    1282              :         }
    1283              :     }
    1284            2 :     break;
    1285              : 
    1286            4 :     case ElementType::NOTE:
    1287              :     {
    1288            4 :         Chord* chord = toChord(el->ownershipParent());
    1289            4 :         if (chord->notes().size() > 1) {
    1290            0 :             undoRemoveElement(el);
    1291            0 :             select(chord->downNote(), SelectType::SINGLE, 0);
    1292            0 :             break;
    1293              :         }
    1294              :         // else fall through
    1295            4 :         el = chord;
    1296              :     }
    1297              :     // fall through
    1298              : 
    1299           11 :     case ElementType::CHORD:
    1300              :     {
    1301           11 :         Chord* chord = toChord(el);
    1302           11 :         removeChordRest(chord, false);
    1303              : 
    1304              :         // replace with rest
    1305           11 :         if (chord->noteType() == NoteType::NORMAL) {
    1306           10 :             Segment* segment = chord->segment();
    1307           10 :             Rest* rest = Factory::createRest(segment, chord->durationType());
    1308           10 :             rest->setTicks(chord->ticks());
    1309           10 :             rest->setTrack(el->track());
    1310              : 
    1311           10 :             undoAddCR(rest, segment->measure(), segment->tick());
    1312              : 
    1313           10 :             Tuplet* tuplet = chord->tuplet();
    1314           10 :             if (tuplet) {
    1315            0 :                 std::list<EngravingObject*> tl = tuplet->linkList();
    1316            0 :                 for (EngravingObject* e : rest->linkList()) {
    1317            0 :                     DurationElement* de = toDurationElement(e);
    1318            0 :                     for (EngravingObject* ee : tl) {
    1319            0 :                         Tuplet* t = toTuplet(ee);
    1320            0 :                         if (t->score() == de->score() && t->track() == de->track()) {
    1321            0 :                             de->setTuplet(t);
    1322            0 :                             t->add(de);
    1323            0 :                             break;
    1324              :                         }
    1325              :                     }
    1326            0 :                 }
    1327            0 :             }
    1328              :             //select(rest, SelectType::SINGLE, 0);
    1329              :         } else {
    1330              :             // remove segment if empty
    1331            1 :             Segment* seg = chord->segment();
    1332            1 :             if (seg->empty()) {
    1333            0 :                 undoRemoveElement(seg);
    1334              :             }
    1335              :         }
    1336              :     }
    1337           11 :     break;
    1338              : 
    1339            4 :     case ElementType::MEASURE_REPEAT:
    1340              :     {
    1341            4 :         MeasureRepeat* mr = toMeasureRepeat(el);
    1342            4 :         removeChordRest(mr, false);
    1343            4 :         Segment* segment = mr->segment();
    1344            4 :         Rest* rest = Factory::createRest(segment);
    1345            4 :         rest->setDurationType(DurationType::V_MEASURE);
    1346            4 :         rest->setTicks(mr->measure()->stretchedLen(mr->staff()));
    1347            4 :         rest->setTrack(mr->track());
    1348            4 :         undoAddCR(rest, segment->measure(), segment->tick());
    1349              : 
    1350              :         // tell measures they're not part of measure repeat group anymore
    1351            4 :         Measure* m = mr->firstMeasureOfGroup();
    1352           12 :         for (int i = 1; i <= mr->numMeasures(); ++i) {
    1353            8 :             undoChangeMeasureRepeatCount(m, 0, mr->staffIdx());
    1354              :             // don't remove grouping if within measure repeat group on another staff
    1355            8 :             bool otherStavesStillNeedGroup = false;
    1356           21 :             for (size_t staffIdx = 0; staffIdx < nstaves(); ++staffIdx) {
    1357           16 :                 if (m->isMeasureRepeatGroupWithNextM(staffIdx) && staffIdx != mr->staffIdx()) {
    1358            3 :                     otherStavesStillNeedGroup = true;
    1359            3 :                     break;
    1360              :                 }
    1361              :             }
    1362            8 :             if (!otherStavesStillNeedGroup) {
    1363            5 :                 m->undoSetNoBreak(false);
    1364              :             }
    1365            8 :             m = m->nextMeasure();
    1366              :         }
    1367              :     }
    1368              :     // fall through
    1369              :     case ElementType::MMREST:
    1370              :     case ElementType::REST:
    1371              :         //
    1372              :         // only allow for voices != 0
    1373              :         //    e.g. voice 0 rests cannot be removed
    1374              :         //
    1375              :     {
    1376            7 :         Rest* rest = toRest(el);
    1377            7 :         if (rest->tuplet() && rest->tuplet()->elements().empty()) {
    1378            0 :             undoRemoveElement(rest->tuplet());
    1379              :         }
    1380            7 :         if ((el->voice() != 0) && !rest->tuplet()) {
    1381            3 :             rest->undoChangeProperty(Pid::GAP, true);
    1382            3 :             rest->undoChangeProperty(Pid::BEAM_MODE, BeamMode::AUTO);
    1383            9 :             for (EngravingObject* r : el->linkList()) {
    1384            6 :                 Rest* rr = toRest(r);
    1385            6 :                 if (rr->track() % VOICES) {
    1386            6 :                     rr->undoChangeProperty(Pid::GAP, true);
    1387              :                 }
    1388            3 :             }
    1389              : 
    1390              :             // delete them really when only gap rests are in the actual measure.
    1391            3 :             Measure* m = toRest(el)->measure();
    1392            3 :             track_idx_t track = el->track();
    1393            3 :             if (m->isOnlyGapRests(track) && !el->staff()->trackHasLinksInVoiceZero(track)) {
    1394              :                 static const SegmentType st { SegmentType::ChordRest };
    1395            0 :                 for (const Segment* s = m->first(st); s; s = s->next(st)) {
    1396            0 :                     EngravingItem* del = s->element(track);
    1397            0 :                     if (s->segmentType() != st || !del) {
    1398            0 :                         continue;
    1399              :                     }
    1400            0 :                     if (toRest(del)->isGap()) {
    1401            0 :                         undoRemoveElement(del);
    1402              :                     }
    1403              :                 }
    1404            0 :                 checkSpanner(m->tick(), m->endTick());
    1405              :             } else {
    1406              :                 // check if the other rest could be combined
    1407            3 :                 Segment* s = toRest(el)->segment();
    1408              : 
    1409            3 :                 std::vector<Rest*> rests;
    1410              :                 // find previous segment with cr in this track
    1411            3 :                 EngravingItem* pe = 0;
    1412            3 :                 for (Segment* ps = s->prev(SegmentType::ChordRest); ps; ps = ps->prev(SegmentType::ChordRest)) {
    1413            2 :                     EngravingItem* elm = ps->element(track);
    1414            2 :                     if (elm && elm->isRest() && toRest(elm)->isGap()) {
    1415            0 :                         pe = el;
    1416            0 :                         rests.push_back(toRest(elm));
    1417            2 :                     } else if (elm) {
    1418            2 :                         break;
    1419              :                     }
    1420              :                 }
    1421              :                 // find next segment with cr in this track
    1422              :                 Segment* ns;
    1423            3 :                 EngravingItem* ne = 0;
    1424            4 :                 for (ns = s->next(SegmentType::ChordRest); ns; ns = ns->next(SegmentType::ChordRest)) {
    1425            4 :                     EngravingItem* elm = ns->element(track);
    1426            4 :                     if (elm && elm->isRest() && toRest(elm)->isGap()) {
    1427            1 :                         ne = elm;
    1428            1 :                         rests.push_back(toRest(elm));
    1429            3 :                     } else if (elm) {
    1430            3 :                         break;
    1431              :                     }
    1432              :                 }
    1433              : 
    1434            3 :                 Fraction stick = pe ? pe->tick() : s->tick();
    1435            3 :                 Fraction ticks = { 0, 1 };
    1436              : 
    1437            3 :                 if (ne) {
    1438            1 :                     ticks = ne->tick() - stick + toRest(ne)->actualTicks();
    1439            2 :                 } else if (ns) {
    1440            2 :                     ticks = ns->tick() - stick;
    1441              :                 } else {
    1442            0 :                     ticks = m->endTick() - stick;
    1443              :                 }
    1444              : 
    1445            3 :                 if (ticks != m->ticks() && ticks != s->ticks()) {
    1446            1 :                     undoRemoveElement(rest);
    1447            2 :                     for (Rest* r : rests) {
    1448            1 :                         undoRemoveElement(r);
    1449              :                     }
    1450              : 
    1451            1 :                     Fraction f = ticks * el->staff()->timeStretch(el->tick());
    1452              : 
    1453            1 :                     std::vector<TDuration> dList = toDurationList(f, true);
    1454            1 :                     if (dList.empty()) {
    1455            0 :                         break;
    1456              :                     }
    1457              : 
    1458            1 :                     Fraction curTick = stick;
    1459            2 :                     for (const TDuration& d : dList) {
    1460            1 :                         Rest* rr = Factory::createRest(this->dummy());
    1461            1 :                         rr->setTicks(d.fraction());
    1462            1 :                         rr->setDurationType(d);
    1463            1 :                         rr->setTrack(track);
    1464            1 :                         rr->setGap(true);
    1465            1 :                         undoAddCR(rr, m, curTick);
    1466            1 :                         curTick += rr->actualTicks();
    1467              :                     }
    1468            1 :                 }
    1469            3 :             }
    1470              :             // Set input position
    1471              :             // TODO If deleted element is last of a sequence, use prev?
    1472            3 :             if (noteEntryMode()) {
    1473            0 :                 Navigation::move(score(), u"prev-chord");
    1474              :             }
    1475              :         }
    1476              :     }
    1477            7 :     break;
    1478              : 
    1479            2 :     case ElementType::ACCIDENTAL:
    1480            2 :         if (el->ownershipParent()->isNote()) {
    1481            2 :             EditNote::changeAccidental(this, toNote(el->ownershipParent()), AccidentalType::NONE);
    1482              :         } else {
    1483            0 :             undoRemoveElement(el);
    1484              :         }
    1485            2 :         break;
    1486              : 
    1487           16 :     case ElementType::BAR_LINE: {
    1488           16 :         BarLine* bl = toBarLine(el);
    1489           16 :         Segment* s = bl->segment();
    1490           16 :         Measure* m = s->measure();
    1491           16 :         if (s->isBeginBarLineType() || s->isBarLineType()) {
    1492            0 :             undoRemoveElement(el);
    1493              :         } else {
    1494           16 :             if (bl->barLineType() == BarLineType::START_REPEAT) {
    1495            0 :                 Measure* m2 = m->isMMRest() ? m->mmRestFirst() : m;
    1496            0 :                 for (Score* lscore : score()->scoreList()) {
    1497            0 :                     Measure* lmeasure = lscore->tick2measure(m2->tick());
    1498            0 :                     if (lmeasure) {
    1499            0 :                         lmeasure->undoChangeProperty(Pid::REPEAT_START, false);
    1500            0 :                         lmeasure->undoChangeProperty(Pid::REPEAT_COUNT, 2);
    1501              :                     }
    1502            0 :                 }
    1503            0 :                 if (!bl->generated()) {
    1504            0 :                     undoRemoveElement(el);
    1505              :                 }
    1506           16 :             } else if (bl->barLineType() == BarLineType::END_REPEAT) {
    1507            0 :                 Measure* m2 = m->isMMRest() ? m->mmRestLast() : m;
    1508            0 :                 for (Score* lscore : score()->scoreList()) {
    1509            0 :                     Measure* lmeasure = lscore->tick2measure(m2->tick());
    1510            0 :                     if (lmeasure) {
    1511            0 :                         lmeasure->undoChangeProperty(Pid::REPEAT_END, false);
    1512            0 :                         lmeasure->undoChangeProperty(Pid::REPEAT_COUNT, 2);
    1513              :                     }
    1514            0 :                 }
    1515            0 :                 if (!bl->generated()) {
    1516            0 :                     undoRemoveElement(el);
    1517              :                 }
    1518              :             } else {
    1519           16 :                 bl->undoChangeProperty(Pid::BARLINE_TYPE, PropertyValue::fromValue(BarLineType::NORMAL));
    1520              :             }
    1521              :         }
    1522              :     }
    1523           16 :     break;
    1524              : 
    1525            2 :     case ElementType::TUPLET:
    1526            2 :         cmdDeleteTuplet(toTuplet(el), true);
    1527            2 :         break;
    1528              : 
    1529            0 :     case ElementType::MEASURE: {
    1530            0 :         Measure* m = toMeasure(el);
    1531            0 :         undoRemoveMeasures(m, m);
    1532            0 :         undoInsertTime(m->tick(), -(m->endTick() - m->tick()));
    1533              :     }
    1534            0 :     break;
    1535              : 
    1536            0 :     case ElementType::BRACKET:
    1537            0 :         EditStaffBrackets::undoRemoveBracket(this, toBracket(el));
    1538            0 :         break;
    1539            0 :     case ElementType::CLEF:
    1540              :     {
    1541            0 :         Clef* clef = toClef(el);
    1542            0 :         Measure* m = clef->measure();
    1543            0 :         if (clef->generated()) {
    1544              :             // find the real clef if this is a cautionary one
    1545            0 :             if (m && m->prevMeasure()) {
    1546            0 :                 Fraction tick = m->tick();
    1547            0 :                 m = m->prevMeasure();
    1548            0 :                 Segment* s = m->findSegment(SegmentType::Clef, tick);
    1549            0 :                 if (s && s->element(clef->track())) {
    1550            0 :                     clef = toClef(s->element(clef->track()));
    1551              :                 }
    1552              :             }
    1553              :         }
    1554            0 :         undoRemoveElement(clef);
    1555              :     }
    1556            0 :     break;
    1557              : 
    1558            0 :     case ElementType::MEASURE_NUMBER:
    1559              :     {
    1560            0 :         Measure* mea = toMeasure(el->ownershipParent());
    1561            0 :         switch (mea->measureNumberMode()) {
    1562              :         // If the user tries to remove an automatically generated measure number,
    1563              :         // we should force the measure not to show any measure number
    1564            0 :         case MeasureNumberMode::AUTO:
    1565            0 :             mea->undoChangeProperty(Pid::MEASURE_NUMBER_MODE, static_cast<int>(MeasureNumberMode::HIDE));
    1566            0 :             break;
    1567              : 
    1568              :         // If the user tries to remove a measure number that he added manually,
    1569              :         // then we should set the MeasureNumberMode to AUTO only if will not show if set to auto.
    1570              :         // If after setting the MeasureNumberMode to AUTO, the measure number still shows,
    1571              :         // We need to force the measure to hide its measure number.
    1572            0 :         case MeasureNumberMode::SHOW:
    1573            0 :             if (mea->showMeasureNumberInAutoMode()) {
    1574            0 :                 mea->undoChangeProperty(Pid::MEASURE_NUMBER_MODE, static_cast<int>(MeasureNumberMode::HIDE));
    1575              :             } else {
    1576            0 :                 mea->undoChangeProperty(Pid::MEASURE_NUMBER_MODE, static_cast<int>(MeasureNumberMode::AUTO));
    1577              :             }
    1578            0 :             break;
    1579            0 :         case MeasureNumberMode::HIDE:
    1580            0 :             break;
    1581              :         }
    1582              :     }
    1583            0 :     break;
    1584            0 :     case ElementType::LYRICSLINE_SEGMENT:
    1585              :     {
    1586            0 :         el = toLyricsLineSegment(el)->lyricsLine();
    1587            0 :         Lyrics* lyrics = toLyricsLine(el)->lyrics();
    1588            0 :         undoRemoveElement(el);
    1589            0 :         lyrics->undoResetProperty(Pid::LYRIC_TICKS);
    1590            0 :         lyrics->undoResetProperty(Pid::SYLLABIC);
    1591              : 
    1592            0 :         break;
    1593              :     }
    1594           10 :     case ElementType::OTTAVA_SEGMENT:
    1595              :     case ElementType::HAIRPIN_SEGMENT:
    1596              :     case ElementType::TRILL_SEGMENT:
    1597              :     case ElementType::VIBRATO_SEGMENT:
    1598              :     case ElementType::TEXTLINE_SEGMENT:
    1599              :     case ElementType::VOLTA_SEGMENT:
    1600              :     case ElementType::SLUR_SEGMENT:
    1601              :     case ElementType::TIE_SEGMENT:
    1602              :     case ElementType::LAISSEZ_VIB_SEGMENT:
    1603              :     case ElementType::PARTIAL_TIE_SEGMENT:
    1604              :     case ElementType::PARTIAL_LYRICSLINE_SEGMENT:
    1605              :     case ElementType::PEDAL_SEGMENT:
    1606              :     case ElementType::GLISSANDO_SEGMENT:
    1607              :     case ElementType::NOTELINE_SEGMENT:
    1608              :     case ElementType::LET_RING_SEGMENT:
    1609              :     case ElementType::GRADUAL_TEMPO_CHANGE_SEGMENT:
    1610              :     case ElementType::PALM_MUTE_SEGMENT:
    1611              :     case ElementType::WHAMMY_BAR_SEGMENT:
    1612              :     case ElementType::RASGUEADO_SEGMENT:
    1613              :     case ElementType::HARMONIC_MARK_SEGMENT:
    1614              :     case ElementType::PICK_SCRAPE_SEGMENT:
    1615              :     case ElementType::GUITAR_BEND_SEGMENT:
    1616              :     case ElementType::HAMMER_ON_PULL_OFF_SEGMENT:
    1617              :     {
    1618           10 :         el = toSpannerSegment(el)->spanner();
    1619           10 :         if (el->isTie()) {
    1620           10 :             Tie* tie = toTie(el);
    1621           10 :             if (tie->tieJumpPoints()) {
    1622            6 :                 tie->undoRemoveTiesFromJumpPoints();
    1623              :             }
    1624           10 :             if (tie->jumpPoint()) {
    1625            8 :                 tie->updateStartTieOnRemoval();
    1626              :             }
    1627              :         }
    1628           10 :         undoRemoveElement(el);
    1629              : 
    1630           10 :         if (el->isGuitarBend()) {
    1631            0 :             GuitarBend* bend = toGuitarBend(el);
    1632            0 :             if (bend->bendType() == GuitarBendType::PRE_BEND || bend->bendType() == GuitarBendType::PRE_DIVE) {
    1633            0 :                 deleteItem(bend->startNote());
    1634              :             }
    1635              :         }
    1636              :     }
    1637           10 :     break;
    1638              : 
    1639            0 :     case ElementType::TAPPING_HALF_SLUR_SEGMENT:
    1640              :     {
    1641            0 :         TappingHalfSlur* halfSlur = toTappingHalfSlur(toTappingHalfSlurSegment(el)->spanner());
    1642            0 :         Tapping* tapping = toTapping(halfSlur->parent());
    1643            0 :         undoRemoveElement(tapping);
    1644            0 :         break;
    1645              :     }
    1646              : 
    1647            0 :     case ElementType::HAMMER_ON_PULL_OFF_TEXT:
    1648            0 :         undoRemoveHopoText(toHammerOnPullOffText(el));
    1649            0 :         break;
    1650              : 
    1651            1 :     case ElementType::STEM_SLASH:                   // cannot delete this elements
    1652              :     case ElementType::HOOK:
    1653              :     case ElementType::GUITAR_BEND_TEXT:
    1654              :     case ElementType::GUITAR_BEND_HOLD_SEGMENT:
    1655            1 :         LOGD("cannot remove %s", el->typeName());
    1656            1 :         break;
    1657              : 
    1658            0 :     case ElementType::TEXT:
    1659            0 :         if ((el->ownershipParent() && el->ownershipParent()->isTBox()) || el->isTBox()) {
    1660            0 :             el->undoChangeProperty(Pid::TEXT, String());
    1661              :         } else {
    1662            0 :             undoRemoveElement(el);
    1663              :         }
    1664            0 :         break;
    1665            0 :     case ElementType::PLAY_COUNT_TEXT: {
    1666            0 :         PlayCountText* pct = toPlayCountText(el);
    1667            0 :         pct->barline()->undoChangeProperty(Pid::PLAY_COUNT_TEXT_SETTING, AutoCustomHide::HIDE);
    1668            0 :     } break;
    1669            1 :     case ElementType::INSTRUMENT_CHANGE:
    1670              :     {
    1671            1 :         InstrumentChange* ic = static_cast<InstrumentChange*>(el);
    1672            1 :         Fraction tickStart = ic->segment()->tick();
    1673            1 :         Part* part = ic->part();
    1674            1 :         Interval oldV = part->staff(0)->transpose(tickStart);
    1675            1 :         undoRemoveElement(el);
    1676            1 :         if (tickStart != Fraction(0, 1)) {
    1677            1 :             for (KeySig* keySig : ic->keySigs()) {
    1678            0 :                 deleteItem(keySig);
    1679            1 :             }
    1680              :         }
    1681            1 :         for (Clef* clef : ic->clefs()) {
    1682            0 :             deleteItem(clef);
    1683            1 :         }
    1684            1 :         if (part->staff(0)->transpose(tickStart) != oldV) {
    1685            1 :             auto i = part->instruments().upper_bound(tickStart.ticks());
    1686            1 :             Fraction tickEnd;
    1687            1 :             if (i == part->instruments().end()) {
    1688            1 :                 tickEnd = Fraction(-1, 1);
    1689              :             } else {
    1690            0 :                 tickEnd = Fraction::fromTicks(i->first);
    1691              :             }
    1692            1 :             Transpose::transpositionChanged(tx, this, part, oldV, tickStart, tickEnd);
    1693              :         }
    1694              :     }
    1695            1 :     break;
    1696            0 :     case ElementType::SYSTEM_LOCK_INDICATOR:
    1697              :     {
    1698            0 :         const RangeLock* systemLock = toSystemLockIndicator(el)->systemLock();
    1699            0 :         EditSystemLocks::undoRemoveSystemLock(tx, systemLock);
    1700              :     }
    1701            0 :     break;
    1702            0 :     case ElementType::PAGE_LOCK_INDICATOR:
    1703              :     {
    1704            0 :         const RangeLock* pageLock = toPageLockIndicator(el)->pageLock();
    1705            0 :         EditPageLocks::undoRemovePageLock(tx, pageLock);
    1706              :     }
    1707            0 :     break;
    1708            0 :     case ElementType::PARENTHESIS: {
    1709            0 :         Parenthesis* paren = toParenthesis(el);
    1710              :         // Use EditChord::removeChordParentheses when parent is a chord
    1711            0 :         if (el->parent() && el->parent()->isChord()) {
    1712            0 :             Chord* chord = toChord(el->parent());
    1713            0 :             NoteParenthesisInfo* parenInfo = chord->findNoteParenthesisInfo(paren);
    1714            0 :             IF_ASSERT_FAILED(parenInfo) {
    1715            0 :                 LOGD() << "deleteItem: This parenthesis does not belong to this chord";
    1716            0 :                 return;
    1717              :             }
    1718            0 :             for (Note* note : parenInfo->notes()) {
    1719            0 :                 note->undoChangeProperty(Pid::HIDE_GENERATED_PARENTHESES, true);
    1720            0 :                 note->undoChangeProperty(Pid::HAS_PARENTHESES, ParenthesesMode::NONE);
    1721              :             }
    1722            0 :             EditChord::removeChordParentheses(chord, parenInfo->notes());
    1723              :         } else {
    1724            0 :             undoRemoveElement(el);
    1725              :         }
    1726              :     }
    1727            0 :     break;
    1728            0 :     case ElementType::STAVE_SHARING_CHANGE:
    1729            0 :         EditStaveSharing::removeStaveSharingChange(tx, toStaveSharingChange(el));
    1730            0 :         break;
    1731           23 :     default:
    1732           23 :         undoRemoveElement(el);
    1733           23 :         break;
    1734              :     }
    1735              : }
    1736              : 
    1737              : //---------------------------------------------------------
    1738              : //   deleteMeasures
    1739              : //---------------------------------------------------------
    1740              : 
    1741           23 : void Score::deleteMeasures(MeasureBase* mbStart, MeasureBase* mbEnd, bool preserveTies)
    1742              : {
    1743           23 :     select(0, SelectType::SINGLE, 0);
    1744              : 
    1745           23 :     if (mbEnd->isMeasure()) {
    1746           23 :         Measure* mbEndMeasure = toMeasure(mbEnd);
    1747           23 :         if (mbEndMeasure->isMMRest()) {
    1748            0 :             mbEnd = mbEndMeasure->mmRestLast();
    1749              :         }
    1750              :     }
    1751              : 
    1752           23 :     if (!preserveTies) {
    1753              :         // we're not preserving slurs and ties where they are, so the endpoints need to be either
    1754              :         // moved or the slur has to be deleted
    1755           11 :         reconnectSlurs(mbStart, mbEnd);
    1756              :     }
    1757              : 
    1758              :     // get the last deleted timesig & keysig in order to restore after deletion
    1759           23 :     std::map<staff_idx_t, TimeSig*> lastDeletedTimeSigs;
    1760              : 
    1761           35 :     for (MeasureBase* mb = mbEnd;; mb = mb->prev()) {
    1762           35 :         if (mb->isMeasure()) {
    1763           35 :             Measure* m = toMeasure(mb);
    1764           35 :             Segment* sts = m->findSegment(SegmentType::TimeSig, m->tick());
    1765              : 
    1766           35 :             if (sts) {
    1767           23 :                 for (staff_idx_t staffIdx = 0; staffIdx < nstaves(); ++staffIdx) {
    1768           13 :                     if (!muse::contains(lastDeletedTimeSigs, staffIdx)) {
    1769           13 :                         if (TimeSig* ts = toTimeSig(sts->element(staffIdx * VOICES))) {
    1770           13 :                             lastDeletedTimeSigs.insert({ staffIdx, ts });
    1771              :                         }
    1772              :                     }
    1773              :                 }
    1774              :             }
    1775              : 
    1776           35 :             if (lastDeletedTimeSigs.size() == nstaves()) {
    1777           10 :                 break;
    1778              :             }
    1779              :         }
    1780           25 :         if (mb == mbStart) {
    1781           13 :             break;
    1782              :         }
    1783           12 :     }
    1784              : 
    1785           23 :     std::vector<KeySigEvent> lastDeletedKeySigEvents;
    1786              : 
    1787           55 :     for (Staff* staff : score()->staves()) {
    1788           32 :         KeySigEvent kse = staff->keySigEvent(mbEnd->tick());
    1789           32 :         lastDeletedKeySigEvents.push_back(kse);
    1790           32 :     }
    1791              : 
    1792           23 :     Fraction startTick = mbStart->tick();
    1793           23 :     Fraction endTick   = mbEnd->tick();
    1794              : 
    1795           46 :     for (Score* score : scoreList()) {
    1796           23 :         Measure* startMeasure = score->tick2measure(startTick);
    1797           23 :         Measure* endMeasure = score->tick2measure(endTick);
    1798              : 
    1799           23 :         score->undoRemoveMeasures(startMeasure, endMeasure, preserveTies);
    1800              : 
    1801              :         // adjust views
    1802           23 :         Measure* focusOn = startMeasure->prevMeasure() ? startMeasure->prevMeasure() : score->firstMeasure();
    1803           23 :         for (MuseScoreView* v : score->m_viewer) {
    1804            0 :             v->adjustCanvasPosition(focusOn);
    1805              :         }
    1806              : 
    1807              :         // insert correct timesig after deletion
    1808           23 :         Measure* mBeforeSel = startMeasure->prevMeasure();
    1809           23 :         Measure* mAfterSel  = mBeforeSel ? mBeforeSel->nextMeasure() : score->firstMeasure();
    1810           23 :         if (mAfterSel) {
    1811           17 :             Segment* s = mAfterSel->findSegment(SegmentType::TimeSig, mAfterSel->tick());
    1812              : 
    1813           43 :             for (staff_idx_t staffIdx = 0; staffIdx < score->nstaves(); ++staffIdx) {
    1814           26 :                 if (s && s->element(staffIdx * VOICES)) {
    1815            0 :                     continue;
    1816              :                 }
    1817              : 
    1818           26 :                 TimeSig* lastDeletedForThisStaff = muse::value(lastDeletedTimeSigs, staffIdx, nullptr);
    1819           26 :                 if (!lastDeletedForThisStaff) {
    1820           17 :                     continue;
    1821              :                 }
    1822              : 
    1823            9 :                 if (mBeforeSel) {
    1824            0 :                     const Staff* staff = this->staff(staffIdx);
    1825            0 :                     if (!staff) {
    1826            0 :                         continue;
    1827              :                     }
    1828              : 
    1829            0 :                     const TimeSig* timeSig = staff->timeSig(mBeforeSel->tick());
    1830            0 :                     if (!timeSig || timeSig->sig() == lastDeletedForThisStaff->sig()) {
    1831            0 :                         continue;
    1832              :                     }
    1833              :                 }
    1834              : 
    1835            9 :                 if (!s) {
    1836            6 :                     s = mAfterSel->undoGetSegment(SegmentType::TimeSig, mAfterSel->tick());
    1837              :                 }
    1838              : 
    1839            9 :                 TimeSig* nts = Factory::createTimeSig(s);
    1840            9 :                 nts->setTrack(staffIdx * VOICES);
    1841            9 :                 nts->setFrom(lastDeletedForThisStaff);
    1842            9 :                 nts->setStretch(nts->sig() / mAfterSel->timesig());
    1843            9 :                 score->undoAddElement(nts);
    1844              :             }
    1845              :         }
    1846              : 
    1847              :         // insert correct keysig if necessary
    1848           23 :         if (mAfterSel && !mBeforeSel) {
    1849            6 :             Segment* s = mAfterSel->undoGetSegment(SegmentType::KeySig, mAfterSel->tick());
    1850              : 
    1851            6 :             bool userCustomizedKeySig = false;
    1852           42 :             for (EngravingItem* e : s->elist()) {
    1853           36 :                 if (e && e->isKeySig() && !toKeySig(e)->generated()) {
    1854            0 :                     userCustomizedKeySig = true;
    1855            0 :                     break;
    1856              :                 }
    1857              :             }
    1858            6 :             if (userCustomizedKeySig) {
    1859            0 :                 continue;
    1860              :             }
    1861              : 
    1862            6 :             bool concertPitch = score->style().styleB(Sid::concertPitch);
    1863           15 :             for (Staff* staff : score->staves()) {
    1864            9 :                 Part* part = staff->part();
    1865            9 :                 Instrument* instrument = part->instrument(Fraction(0, 1));
    1866            9 :                 KeySigEvent nkse;
    1867            9 :                 staff_idx_t staffIdx = staff->idx();
    1868              : 
    1869            9 :                 if (instrument->useDrumset()) {
    1870            0 :                     nkse.setConcertKey(Key::C);
    1871            0 :                     nkse.setCustom(true);
    1872            0 :                     nkse.setMode(KeyMode::NONE);
    1873              :                 } else {
    1874            9 :                     nkse = lastDeletedKeySigEvents.at(staffIdx);
    1875            9 :                     if (!concertPitch && !nkse.isAtonal()) {
    1876            9 :                         Interval v = instrument->transpose();
    1877            9 :                         v.flip();
    1878            9 :                         nkse.setKey(Transpose::transposeKey(nkse.concertKey(), v, part->preferSharpFlat()));
    1879              :                     }
    1880              :                 }
    1881              : 
    1882            9 :                 KeySig* nks = (KeySig*)s->element(staff2track(staffIdx));
    1883            9 :                 if (!nks) {
    1884            5 :                     nks = Factory::createKeySig(s);
    1885            5 :                     nks->setTrack(staffIdx * VOICES);
    1886            5 :                     nks->setKeySigEvent(nkse);
    1887            5 :                     score->undoAddElement(nks);
    1888              :                 } else {
    1889            4 :                     nks->setGenerated(false);
    1890            4 :                     nks->setKeySigEvent(nkse);
    1891            4 :                     staff->setKey(mAfterSel->tick(), nkse);
    1892              :                 }
    1893            9 :             }
    1894              :         }
    1895           23 :     }
    1896              : 
    1897           23 :     undoInsertTime(mbStart->tick(), -(mbEnd->endTick() - mbStart->tick()));
    1898           23 :     m_is.setSegment(0);          // invalidate position
    1899           23 : }
    1900              : 
    1901           11 : void Score::reconnectSlurs(MeasureBase* mbStart, MeasureBase* mbEnd)
    1902              : {
    1903              :     // Reconnect or remove slurs that intersect with these deleted measures
    1904           11 :     Fraction sTick = mbStart->tick();
    1905           11 :     Fraction eTick = mbEnd->tick();
    1906           12 :     for (auto overlappingSlur : spannerMap().findOverlapping(sTick.ticks(), eTick.ticks())) {
    1907            1 :         Spanner* sp = overlappingSlur.value;
    1908            1 :         if (!sp->isSlur()) {
    1909            1 :             continue;
    1910              :         }
    1911            0 :         ChordRest* cr1 = sp->startCR();
    1912            0 :         ChordRest* cr2 = sp->endCR();
    1913            0 :         if (!cr1 || !cr2) {
    1914              :             // this is an invalid slur
    1915            0 :             continue;
    1916              :         }
    1917            0 :         MeasureBase* m = mbStart;
    1918            0 :         bool adjust1 = false;
    1919            0 :         bool adjust2 = false;
    1920            0 :         Measure* measure1 = cr1->measure();
    1921            0 :         Measure* measure2 = cr2->measure();
    1922              :         do {
    1923            0 :             adjust1 = adjust1 ? true : measure1 == m;
    1924            0 :             adjust2 = adjust2 ? true : measure2 == m;
    1925            0 :             if (m == mbEnd) {
    1926            0 :                 break;
    1927              :             } else {
    1928            0 :                 m = m->next();
    1929              :             }
    1930            0 :         } while (m && !(adjust1 && adjust2));
    1931            0 :         if (adjust1 && adjust2) {
    1932              :             // if both endpoints of this slur are inside this deleted range, remove the slur.
    1933            0 :             undoRemoveElement(sp);
    1934            0 :             continue;
    1935            0 :         } else if (adjust1) {
    1936              :             // endpoint 1 is in deleted range. move endpoint forward to first non-deleted CR after range
    1937            0 :             Measure* mNext = mbEnd->next() && mbEnd->next()->isMeasure() ? toMeasure(mbEnd->next()) : nullptr;
    1938            0 :             if (!mNext) {
    1939            0 :                 undoRemoveElement(sp);
    1940            0 :                 continue;
    1941              :             }
    1942            0 :             ChordRest* firstAvailableCr = nullptr;
    1943              :             // search for last cr in this voice
    1944            0 :             Segment* seg = mNext->first(SegmentType::ChordRest);
    1945            0 :             track_idx_t spTrack = sp->track();
    1946            0 :             ChordRest* spEndCr = sp->endCR();
    1947            0 :             Fraction spEndCrTick = spEndCr->tick();
    1948            0 :             while (seg) {
    1949            0 :                 firstAvailableCr = seg->cr(spTrack);
    1950            0 :                 if (!firstAvailableCr || !firstAvailableCr->isChord()) {
    1951            0 :                     seg = seg->next(SegmentType::ChordRest);
    1952            0 :                     continue;
    1953              :                 }
    1954            0 :                 auto gracesBefore = toChord(firstAvailableCr)->graceNotesBefore();
    1955            0 :                 if (firstAvailableCr->tick() > spEndCrTick) {
    1956              :                     // we would create a negative-length slur. remove it entirely.
    1957            0 :                     undoRemoveElement(sp);
    1958            0 :                     break;
    1959            0 :                 } else if (spEndCr == firstAvailableCr) {
    1960              :                     // this would be a zero-length slur, but a possibility exists that this cr has grace after
    1961            0 :                     if (gracesBefore.empty()) {
    1962            0 :                         undoRemoveElement(sp);
    1963            0 :                         break;
    1964              :                     }
    1965              :                 }
    1966            0 :                 if (!gracesBefore.empty()) {
    1967            0 :                     firstAvailableCr = gracesBefore.front();
    1968              :                 }
    1969            0 :                 Spanner* newSp = toSpanner(sp->clone());
    1970            0 :                 newSp->setStartElement(firstAvailableCr);
    1971            0 :                 newSp->setTick(firstAvailableCr->tick());
    1972            0 :                 undoChangeElement(sp, newSp);
    1973            0 :                 break;
    1974            0 :             }
    1975            0 :         } else if (adjust2) {
    1976              :             // endpoint 2 is in deleted range. move endpoint backward to last non-deleted CR before range
    1977            0 :             Measure* mPrev = mbStart->prev() && mbStart->prev()->isMeasure() ? toMeasure(mbStart->prev()) : nullptr;
    1978            0 :             if (!mPrev) {
    1979            0 :                 undoRemoveElement(sp);
    1980            0 :                 continue;
    1981              :             }
    1982            0 :             ChordRest* firstAvailableCr = nullptr;
    1983              :             // search for last cr in this voice
    1984            0 :             Segment* seg = mPrev->last();
    1985            0 :             if (seg->segmentType() != SegmentType::ChordRest) {
    1986            0 :                 seg = seg->prev(SegmentType::ChordRest);
    1987              :             }
    1988            0 :             ChordRest* spStartCr = sp->startCR();
    1989            0 :             Fraction spStartCrTick = spStartCr->tick();
    1990            0 :             while (seg) {
    1991            0 :                 firstAvailableCr = seg->cr(sp->track2());
    1992            0 :                 if (!firstAvailableCr || !firstAvailableCr->isChord()) {
    1993            0 :                     seg = seg->prev(SegmentType::ChordRest);
    1994            0 :                     continue;
    1995              :                 }
    1996            0 :                 auto gracesAfter = toChord(firstAvailableCr)->graceNotesAfter();
    1997            0 :                 if (firstAvailableCr->tick() < spStartCrTick) {
    1998              :                     // we would create a negative-length slur. remove it entirely.
    1999            0 :                     undoRemoveElement(sp);
    2000            0 :                     break;
    2001            0 :                 } else if (spStartCr == toChordRest(firstAvailableCr)) {
    2002              :                     // this would be a zero-length slur, but a possibility exists that this cr has grace after
    2003            0 :                     if (gracesAfter.empty()) {
    2004            0 :                         undoRemoveElement(sp);
    2005            0 :                         break;
    2006              :                     }
    2007              :                 }
    2008            0 :                 if (!gracesAfter.empty()) {
    2009            0 :                     firstAvailableCr = gracesAfter.back();
    2010              :                 }
    2011            0 :                 Spanner* newSp = toSpanner(sp->clone());
    2012            0 :                 newSp->setEndElement(firstAvailableCr);
    2013            0 :                 newSp->setTick2(firstAvailableCr->tick());
    2014            0 :                 undoChangeElement(sp, newSp);
    2015            0 :                 break;
    2016            0 :             }
    2017              :         } else {
    2018              :             // both of the endpoints are outside of the deleted range. there is no reason to change or delete anything
    2019              :         }
    2020              :     }
    2021           11 : }
    2022              : 
    2023              : //---------------------------------------------------------
    2024              : //   deleteSpannersFromRange
    2025              : ///   Deletes spanners in the given range that match the
    2026              : ///   given selection filter.
    2027              : //---------------------------------------------------------
    2028              : 
    2029           69 : void Score::deleteOrShortenOutSpannersFromRange(const Fraction& t1, const Fraction& t2, track_idx_t track1, track_idx_t track2,
    2030              :                                                 const SelectionFilter& filter)
    2031              : {
    2032              :     static const std::set<ElementType> SPANNER_TYPES_TO_SHORTEN_OUT {
    2033              :         ElementType::HAIRPIN,
    2034              :         ElementType::OTTAVA,
    2035              :         ElementType::TRILL,
    2036              :         ElementType::VIBRATO,
    2037           71 :     };
    2038              : 
    2039              :     // undoRemoveElement and undoChangeProperty also handle linked elements, so we need
    2040              :     // to make sure each linked group is handled only once if multiple elements per linked
    2041              :     // group are found in the range, for example in the case of linked staves.
    2042           69 :     std::unordered_set<EngravingObject*> handledMainElements;
    2043              : 
    2044           69 :     auto spanners = m_spanner.findOverlapping(t1.ticks(), t2.ticks() - 1);
    2045          102 :     for (auto i : spanners) {
    2046           33 :         Spanner* sp = i.value;
    2047           33 :         Fraction spStartTick = sp->tick();
    2048           33 :         Fraction spEndTick = sp->tick2();
    2049           33 :         const bool trackValid = sp->track() >= track1 && sp->track() < track2;
    2050           33 :         if (!trackValid || sp->isVolta() || sp->systemFlag()) {
    2051           15 :             continue;
    2052              :         }
    2053              : 
    2054           31 :         if (sp->links() && !handledMainElements.insert(sp->links()->mainElement()).second) {
    2055              :             // already handled this linked group
    2056            4 :             continue;
    2057              :         }
    2058              : 
    2059              :         // Special handling for grace notes...
    2060           27 :         const Chord* startChord = sp->startChord();
    2061           27 :         const bool startChordIsSelectableGrace = startChord && startChord->isGrace() && filter.canSelect(startChord);
    2062              : 
    2063           27 :         const Chord* endChord = sp->endChord();
    2064           27 :         const bool endChordIsSelectableGrace = endChord && endChord->isGrace() && filter.canSelect(endChord);
    2065              : 
    2066           27 :         if (startChordIsSelectableGrace || endChordIsSelectableGrace) {
    2067            6 :             undoRemoveElement(sp);
    2068            6 :             continue;
    2069              :         }
    2070              : 
    2071           21 :         if (!filter.canSelectVoice(sp->track()) || !filter.canSelect(sp)) {
    2072            3 :             continue;
    2073              :         }
    2074           29 :         if (spStartTick >= t1 && spStartTick < t2
    2075           29 :             && spEndTick > t1 && spEndTick <= t2) {
    2076            7 :             undoRemoveElement(sp);
    2077           14 :         } else if (sp->isSlur() && ((spStartTick >= t1 && spStartTick < t2)
    2078            3 :                                     || (spEndTick >= t1 && spEndTick < t2))) {
    2079            3 :             undoRemoveElement(sp);
    2080            8 :         } else if (muse::contains(SPANNER_TYPES_TO_SHORTEN_OUT, sp->type())) {
    2081            7 :             bool moveStart = spStartTick >= t1 && spStartTick < t2;
    2082            7 :             bool moveEnd = spEndTick > t1 && spEndTick <= t2;
    2083            7 :             if (moveStart) {
    2084            3 :                 Fraction tickDiff = t2 - spStartTick;
    2085            3 :                 sp->undoChangeProperty(Pid::SPANNER_TICK, t2);
    2086            3 :                 sp->undoChangeProperty(Pid::SPANNER_TICKS, sp->ticks() - tickDiff);
    2087            4 :             } else if (moveEnd) {
    2088            3 :                 Fraction tickDiff = spEndTick - t1;
    2089            3 :                 sp->undoChangeProperty(Pid::SPANNER_TICKS, sp->ticks() - tickDiff);
    2090              :             }
    2091              :         }
    2092              :     }
    2093           69 : }
    2094              : 
    2095         1152 : void Score::deleteSlursFromRange(const Fraction& t1, const Fraction& t2, track_idx_t trackStart, track_idx_t trackEnd,
    2096              :                                  const SelectionFilter& filter)
    2097              : {
    2098         1152 :     auto spanners = m_spanner.findOverlapping(t1.ticks(), t2.ticks() - 1);
    2099         1152 :     for (auto i : spanners) {
    2100            0 :         Spanner* sp = i.value;
    2101            0 :         Fraction spStartTick = sp->tick();
    2102            0 :         Fraction spEndTick = sp->tick2();
    2103            0 :         if (!sp->isSlur()) {
    2104            0 :             continue;
    2105              :         }
    2106            0 :         if (!filter.canSelectVoice(sp->track()) || !filter.canSelect(sp)) {
    2107            0 :             continue;
    2108              :         }
    2109              : 
    2110            0 :         if (sp->track() >= trackStart && sp->track() < trackEnd) {
    2111            0 :             if ((spStartTick >= t1 && spStartTick < t2)
    2112            0 :                 || (spEndTick >= t1 && spEndTick < t2)) {
    2113            0 :                 undoRemoveElement(sp);
    2114              :             }
    2115              :         }
    2116              :     }
    2117         1152 : }
    2118              : 
    2119              : //---------------------------------------------------------
    2120              : //   deleteAnnotationsFromRange
    2121              : ///   Deletes annotations in the given range that match the
    2122              : ///   given selection filter.
    2123              : //---------------------------------------------------------
    2124              : 
    2125           69 : void Score::deleteAnnotationsFromRange(Segment* s1, Segment* s2, track_idx_t track1, track_idx_t track2, const SelectionFilter& filter)
    2126              : {
    2127           69 :     if (!s1) {
    2128            0 :         return;
    2129              :     }
    2130           69 :     if (s2 && (*s2) < (*s1)) {
    2131            0 :         return;
    2132              :     }
    2133              : 
    2134          361 :     for (track_idx_t track = track1; track < track2; ++track) {
    2135          292 :         if (!filter.canSelectVoice(track)) {
    2136            2 :             continue;
    2137              :         }
    2138         3014 :         for (Segment* s = s1; s && s != s2; s = s->next1()) {
    2139         2724 :             const auto annotations = s->annotations(); // make a copy since we alter the list
    2140         2896 :             for (EngravingItem* annotation : annotations) {
    2141              :                 // skip if not included in selection (eg, filter)
    2142          172 :                 if (!filter.canSelect(annotation)) {
    2143          152 :                     continue;
    2144              :                 }
    2145           20 :                 if (!annotation->systemFlag() && annotation->track() == track) {
    2146            4 :                     deleteItem(annotation);
    2147              :                 }
    2148              :             }
    2149         2724 :         }
    2150              :     }
    2151              : }
    2152              : 
    2153          372 : void Score::deleteRangeAtTrack(std::vector<ChordRest*>& crsToSelect, const track_idx_t track, Segment* startSeg, const Fraction& endTick,
    2154              :                                Tuplet* currentTuplet, const SelectionFilter& filter, bool selectionContainsMultiNoteChords)
    2155              : {
    2156        12707 :     while (startSeg && !(startSeg->isChordRestType() && startSeg->cr(track))) {
    2157              :         // Range should always start at a ChordRest segment - find the next one for this track...
    2158        12335 :         startSeg = startSeg->next1(SegmentType::ChordRest);
    2159              :     }
    2160              : 
    2161          372 :     if (!startSeg) {
    2162          210 :         return;
    2163              :     }
    2164              : 
    2165          162 :     Fraction restStartTick = startSeg->tick();
    2166          162 :     Fraction restDuration;
    2167              : 
    2168              :     // When we find a deselected DurationElement - write rests up to the start of the deselected element (using the existing values for
    2169              :     // restStartTick and restDuration), skip the deselected element (move restStartTick forward), and reset restDuration...
    2170          238 :     const auto foundDeselected = [&](const DurationElement* deselectedElement) {
    2171          238 :         const std::vector<Rest*> rests = setRests(restStartTick, track, restDuration, /*useDots*/ !currentTuplet, currentTuplet);
    2172          238 :         crsToSelect.insert(crsToSelect.end(), rests.begin(), rests.end());
    2173          238 :         restStartTick = deselectedElement->endTick();
    2174          238 :         restDuration = Fraction();
    2175          238 :     };
    2176              : 
    2177         1134 :     for (Segment* s = startSeg; s && (s->tick() < endTick); s = s->next1()) {
    2178          972 :         EngravingItem* e = s->element(track);
    2179          972 :         if (!e) {
    2180          512 :             continue;
    2181              :         }
    2182              : 
    2183          858 :         if (s->isBreathType()) {
    2184            0 :             deleteItem(e);
    2185            0 :             continue;
    2186              :         }
    2187              : 
    2188          858 :         if (!s->isChordRestType()) {
    2189              :             // do not delete TimeSig/KeySig, it doesn't make sense to do it (except on full system)
    2190          236 :             if (!s->isTimeTickType() && !s->isTimeSigType() && !s->isKeySigType()
    2191          236 :                 && !s->isType(SegmentType::BarLineTypes) /*covers all barLine types*/) {
    2192            9 :                 undoRemoveElement(e);
    2193              :             }
    2194          118 :             continue;
    2195              :         }
    2196              : 
    2197          740 :         if (e->isMeasureRepeat()) {
    2198              :             // MeasureRepeat has its own special handling, so it is skipped here
    2199            0 :             foundDeselected(toDurationElement(e));
    2200            0 :             deleteItem(e);
    2201            0 :             continue;
    2202              :         }
    2203              : 
    2204          740 :         ChordRest* cr1 = toChordRest(e);
    2205              : 
    2206              :         // currentTuplet refers to the tuplet that we're currently performing a delete range "inside". It is possible that currentTuplet contains nested
    2207              :         // tuplets, in which case we should find the "top-most nested tuplet" (nextTuplet) and:
    2208              :         //      1. If it is selectable, delete it completely using cmdDeleteTuplet (deletes all elements contained in that tuplet)
    2209              :         //      2. If it is not selectable, call this method recursively "inside" that tuplet (nextTuplet becomes currentTuplet for the recursive call)
    2210              : 
    2211          740 :         Tuplet* nextTuplet = nullptr;
    2212          740 :         if (cr1->tuplet() && cr1->tuplet() != currentTuplet) {
    2213          102 :             nextTuplet = cr1->tuplet();
    2214          150 :             while (nextTuplet->tuplet() && nextTuplet->tuplet() != currentTuplet) {
    2215           48 :                 nextTuplet = nextTuplet->tuplet();
    2216              :             }
    2217              :         }
    2218              : 
    2219          740 :         if (nextTuplet) {
    2220              :             // The range of nextTuplet will be handled by cmdDeleteTuplet or the recursive call - skip it at this level of recursion...
    2221          102 :             const DurationElement* lastInTuplet = nextTuplet->elements().back();
    2222          123 :             while (lastInTuplet->isTuplet()) {
    2223           21 :                 lastInTuplet = toTuplet(lastInTuplet)->elements().back();
    2224              :             }
    2225          102 :             IF_ASSERT_FAILED(lastInTuplet->isChordRest()) {
    2226            0 :                 break;
    2227              :             }
    2228          102 :             s = toChordRest(lastInTuplet)->segment();
    2229              : 
    2230          102 :             if (filter.canSelectTuplet(nextTuplet, cr1->tick(), endTick, selectionContainsMultiNoteChords)) {
    2231           20 :                 restDuration += nextTuplet->ticks();
    2232           20 :                 cmdDeleteTuplet(nextTuplet, /*replaceWithRest*/ false);
    2233              :             } else {
    2234           82 :                 const Fraction recursionEnd = std::min(nextTuplet->endTick(), endTick);
    2235           82 :                 deleteRangeAtTrack(crsToSelect, track, cr1->segment(), recursionEnd, nextTuplet, filter, selectionContainsMultiNoteChords);
    2236           82 :                 foundDeselected(nextTuplet);
    2237              :             }
    2238              : 
    2239          102 :             if (!s) {
    2240            0 :                 break;
    2241              :             }
    2242              : 
    2243          102 :             continue;
    2244          102 :         }
    2245              : 
    2246          654 :         for (EngravingItem* elem : collectElementsAnchoredToChordRest(cr1)) {
    2247           16 :             if (!elem->isChord()) {
    2248            0 :                 if (filter.canSelect(elem)) {
    2249            0 :                     undoRemoveElement(elem);
    2250              :                 }
    2251            0 :                 continue;
    2252              :             }
    2253              :             // Special handling for grace notes...
    2254           16 :             const Chord* chord = toChord(elem);
    2255           16 :             IF_ASSERT_FAILED(chord->isGrace()) {
    2256            0 :                 continue;
    2257              :             }
    2258           16 :             std::unordered_set<EngravingItem*> anchoredToGrace = collectElementsAnchoredToChordRest(chord);
    2259           32 :             for (const Note* graceNote : chord->notes()) {
    2260           16 :                 const std::unordered_set<EngravingItem*> noteAnchored = collectElementsAnchoredToNote(graceNote, true, false);
    2261           16 :                 anchoredToGrace.insert(noteAnchored.begin(), noteAnchored.end());
    2262           16 :             }
    2263           16 :             for (EngravingItem* graceElem : anchoredToGrace) {
    2264            0 :                 if (filter.canSelect(graceElem)) {
    2265              :                     // Delete elements anchored to grace note...
    2266            0 :                     undoRemoveElement(graceElem);
    2267              :                 }
    2268              :             }
    2269           16 :             if (filter.canSelect(elem)) {
    2270              :                 // Delete grace note itself...
    2271            8 :                 undoRemoveElement(elem);
    2272              :             }
    2273          654 :         }
    2274              : 
    2275          638 :         if (cr1->isRestFamily()) {
    2276          178 :             if (cr1->selected()) {
    2277          178 :                 restDuration += cr1->ticks();
    2278          178 :                 removeChordRest(cr1, true);
    2279              :             } else {
    2280            0 :                 foundDeselected(cr1);
    2281              :             }
    2282          178 :             continue;
    2283              :         }
    2284              : 
    2285          460 :         Chord* chord = toChord(cr1);
    2286              : 
    2287          460 :         const std::vector<Note*> allNotes = chord->notes();
    2288          460 :         std::unordered_set<Note*> notesToRemove;
    2289         1219 :         for (size_t noteIdx = 0; noteIdx < allNotes.size(); ++noteIdx) {
    2290          759 :             Note* note = allNotes.at(noteIdx);
    2291          759 :             if (filter.canSelectNoteIdx(noteIdx, allNotes.size(), selectionContainsMultiNoteChords)) {
    2292          537 :                 notesToRemove.emplace(note);
    2293              :                 //! NOTE: Don't need to remove anchored elements - they won't survive the deletion of their parent note...
    2294          759 :                 continue;
    2295              :             }
    2296          222 :             for (EngravingItem* elem : collectElementsAnchoredToNote(note, true, false)) {
    2297            0 :                 if (!filter.canSelect(elem)) {
    2298            0 :                     continue;
    2299              :                 }
    2300            0 :                 if (!elem->isSpanner() || elem->isPartialTie() || elem->isLaissezVib()) {
    2301            0 :                     undoRemoveElement(elem);
    2302            0 :                     continue;
    2303              :                 }
    2304            0 :                 if (noteAnchoredSpannerIsInRange(toSpanner(elem), cr1->tick(), endTick)) {
    2305            0 :                     undoRemoveElement(elem);
    2306              :                 }
    2307          222 :             }
    2308          222 :             if (!filter.canSelectNoteIdx(noteIdx, allNotes.size(), selectionContainsMultiNoteChords)) {
    2309          222 :                 continue;
    2310              :             }
    2311            0 :             notesToRemove.emplace(note);
    2312              :         }
    2313              : 
    2314          460 :         if (notesToRemove.size() == allNotes.size()) {
    2315          304 :             restDuration += cr1->ticks();
    2316          304 :             removeChordRest(cr1, true);
    2317              :         } else {
    2318          314 :             for (Note* note : notesToRemove) {
    2319          158 :                 undoRemoveElement(note);
    2320              :             }
    2321          156 :             foundDeselected(cr1);
    2322              :         }
    2323          460 :     }
    2324              : 
    2325          162 :     const std::vector<Rest*> rests = setRests(restStartTick, track, restDuration, /*useDots*/ !currentTuplet, currentTuplet);
    2326          162 :     crsToSelect.insert(crsToSelect.end(), rests.begin(), rests.end());
    2327          162 : }
    2328              : 
    2329              : //---------------------------------------------------------
    2330              : //   deleteRange
    2331              : ///   Deletes elements in the given range that match the
    2332              : ///   given selection filter.
    2333              : ///   \return A chord/rest inside the selected range
    2334              : ///   that can be used to establish a selection after this
    2335              : ///   deletion operation.
    2336              : //---------------------------------------------------------
    2337              : 
    2338           69 : std::vector<ChordRest*> Score::deleteRange(Segment* s1, Segment* s2, track_idx_t track1, track_idx_t track2, const SelectionFilter& filter,
    2339              :                                            bool selectionContainsMultiNoteChords)
    2340              : {
    2341           69 :     std::vector<ChordRest*> crsForSelection;
    2342           69 :     IF_ASSERT_FAILED(s1) {
    2343            0 :         return crsForSelection;
    2344              :     }
    2345              : 
    2346              :     // delete content from measures underlying mmrests
    2347           69 :     if (s1->measure() && s1->measure()->isMMRest()) {
    2348            0 :         s1 = s1->measure()->mmRestFirst()->first();
    2349              :     }
    2350           69 :     if (s2 && s2->measure() && s2->measure()->isMMRest()) {
    2351            0 :         s2 = s2->measure()->mmRestLast()->last();
    2352              :     }
    2353              : 
    2354           69 :     const Fraction startTick = s1->tick();
    2355           69 :     const Fraction endTick = s2 ? s2->tick() : lastMeasure()->endTick();
    2356              : 
    2357           69 :     deleteOrShortenOutSpannersFromRange(startTick, endTick, track1, track2, filter);
    2358           69 :     deleteAnnotationsFromRange(s1, s2, track1, track2, filter);
    2359              : 
    2360          361 :     for (track_idx_t track = track1; track < track2; ++track) {
    2361          292 :         if (!filter.canSelectVoice(track)) {
    2362            2 :             continue;
    2363              :         }
    2364          290 :         deleteRangeAtTrack(crsForSelection, track, s1, endTick, /*currentTuplet*/ nullptr, filter, selectionContainsMultiNoteChords);
    2365              :     }
    2366              : 
    2367           69 :     return crsForSelection;
    2368            0 : }
    2369              : 
    2370              : //---------------------------------------------------------
    2371              : //   cmdDeleteSelection
    2372              : //---------------------------------------------------------
    2373              : 
    2374          102 : void Score::cmdDeleteSelection()
    2375              : {
    2376          102 :     std::vector<ChordRest*> crsSelectedAfterDeletion;              // select something after deleting notes
    2377          102 :     EngravingItem* elSelectedAfterDeletion = nullptr;
    2378              : 
    2379          102 :     if (selection().isRange()) {
    2380          207 :         crsSelectedAfterDeletion = deleteRange(selection().startSegment(), selection().endSegment(),
    2381          138 :                                                staff2track(selection().staffStart()), staff2track(selection().staffEnd()),
    2382          138 :                                                selectionFilter(), selection().rangeContainsMultiNoteChords());
    2383              :     } else {
    2384              :         // deleteItem modifies selection().elements() list,
    2385              :         // so we need a local copy:
    2386           33 :         std::vector<EngravingItem*> el = selection().elements();
    2387              : 
    2388              :         // keep track of linked elements that are deleted implicitly
    2389              :         // so we don't try to delete them twice if they are also in selection
    2390           33 :         std::set<EngravingObject*> deletedElements;
    2391              :         // Similarly, deleting one spanner segment, will delete all of them
    2392              :         // so we don't try to delete them twice if they are also in selection
    2393           33 :         std::set<Spanner*> deletedSpanners;
    2394              : 
    2395           45 :         auto selectCRAtTickAndTrack = [this, &crsSelectedAfterDeletion](Fraction tick, track_idx_t track) {
    2396           45 :             ChordRest* cr = findCR(tick, track);
    2397           45 :             if (cr) {
    2398           42 :                 crsSelectedAfterDeletion.push_back(cr);
    2399              :             }
    2400           45 :         };
    2401              : 
    2402           78 :         for (EngravingItem* e : el) {
    2403              :             // these are the linked elements we are about to delete
    2404           45 :             std::list<EngravingObject*> links;
    2405           45 :             if (e->links()) {
    2406           24 :                 links = *e->links();
    2407              :             }
    2408              : 
    2409              :             // find location of element to select after deleting notes
    2410              :             // get tick of element itself if that is valid
    2411              :             // or of spanner or parent if that is more valid
    2412           45 :             Fraction tick  = { -1, 1 };
    2413           45 :             track_idx_t track = muse::nidx;
    2414           45 :             if (e->isNote()) {
    2415            4 :                 tick = toNote(e)->chord()->tick();
    2416           41 :             } else if (e->isRest() || e->isMMRest()) {
    2417            3 :                 tick = toRest(e)->tick();
    2418           38 :             } else if (e->isMeasureRepeat()) { // may be attached in different measure than it appears
    2419            3 :                 tick = toMeasureRepeat(e)->firstMeasureOfGroup()->first()->tick();
    2420           35 :             } else if (e->isSpannerSegment()) {
    2421            0 :                 tick = toSpannerSegment(e)->spanner()->tick();
    2422           35 :             } else if (e->isBreath()) {
    2423              :                 // we want the tick of the ChordRest that precedes the breath mark (in the same track)
    2424            5 :                 for (Segment* s = toBreath(e)->segment()->prev(); s; s = s->prev()) {
    2425            5 :                     if (s->isChordRestType() && s->element(e->track())) {
    2426            5 :                         tick = s->tick();
    2427            5 :                         break;
    2428              :                     }
    2429              :                 }
    2430           30 :             } else if (e->isBarLine() && toBarLine(e)->barLineType() != BarLineType::START_REPEAT) {
    2431              :                 // we want the tick of the ChordRest that precedes the barline (in the same track)
    2432            0 :                 for (Segment* s = toBarLine(e)->segment()->prev(); s; s = s->prev()) {
    2433            0 :                     if (s->isChordRestType() && s->element(e->track())) {
    2434            0 :                         tick = s->tick();
    2435            0 :                         break;
    2436              :                     }
    2437              :                 }
    2438           30 :             } else if (e->isSoundFlag()) {
    2439            0 :                 tick = e->tick();
    2440           30 :             } else if (e->isTuplet()) {
    2441              :                 // the rests replacing the tuplet start at its tick
    2442            2 :                 tick = toTuplet(e)->tick();
    2443           28 :             } else if (e->ownershipParent()
    2444           30 :                        && (e->ownershipParent()->isSegment() || e->ownershipParent()->isChord() || e->ownershipParent()->isNote()
    2445            2 :                            || e->ownershipParent()->isRest())) {
    2446           25 :                 tick = e->ownershipParentItem()->tick();
    2447              :             }
    2448              :             //else tick < 0
    2449           45 :             track = e->track();
    2450              : 
    2451              :             // We should not allow deleting the very first keySig of the piece, because it is
    2452              :             // logically incorrect and leads to a state of undefined key/transposition.
    2453              :             // Also instrument change key signatures should be undeletable.
    2454              :             // The correct action is for the user to set an atonal/custom keySig as needed.
    2455           45 :             if (e->isKeySig()) {
    2456            2 :                 if (e->tick() == Fraction(0, 1) || toKeySig(e)->forInstrumentChange()) {
    2457            0 :                     MScore::setError(MsError::CANNOT_REMOVE_KEY_SIG);
    2458            0 :                     selectCRAtTickAndTrack(tick, track);
    2459            0 :                     continue;
    2460              :                 }
    2461              :             }
    2462              : 
    2463              :             // Don't allow deleting the trill cue note
    2464           45 :             if (e->isNote() && toNote(e)->isTrillCueNote()) {
    2465            0 :                 selectCRAtTickAndTrack(tick, track);
    2466            0 :                 continue;
    2467              :             }
    2468              : 
    2469           45 :             if (e->isFretDiagram() || e->isHarmony()) {
    2470            0 :                 FBox* fbox = toFBox(e->findAncestor(ElementType::FBOX));
    2471            0 :                 if (fbox) {
    2472              :                     // We can't delete elements inside fret box, instead we hide them
    2473            0 :                     if (FretDiagram* fretDiagram = e->isFretDiagram() ? toFretDiagram(e) : toFretDiagram(e->parent())) {
    2474            0 :                         fretDiagram->undoChangeProperty(Pid::VISIBLE, false);
    2475            0 :                         continue;
    2476              :                     }
    2477            0 :                 } else if (e->isFretDiagram()) {
    2478            0 :                     FretDiagram* fretDiagram = toFretDiagram(e);
    2479            0 :                     Harmony* harmony = fretDiagram->harmony();
    2480            0 :                     if (harmony) {
    2481            0 :                         undoChangeParent(harmony, fretDiagram->segment(), track2staff(fretDiagram->track()));
    2482            0 :                         elSelectedAfterDeletion = harmony;
    2483              :                     }
    2484            0 :                 } else if (e->isHarmony()) {
    2485            0 :                     Harmony* harmony = toHarmony(e);
    2486            0 :                     if (harmony->ownershipParentItem()->isFretDiagram()) {
    2487            0 :                         elSelectedAfterDeletion = harmony->ownershipParentItem();
    2488              :                     }
    2489              :                 }
    2490              :             }
    2491              : 
    2492              :             // delete element if we have not done so already
    2493           45 :             if (deletedElements.find(e) == deletedElements.end()) {
    2494              :                 // do not delete two spanner segments from the same spanner
    2495           45 :                 if (e->isSpannerSegment()) {
    2496            0 :                     Spanner* spanner = toSpannerSegment(e)->spanner();
    2497            0 :                     if (deletedSpanners.find(spanner) != deletedSpanners.end()) {
    2498            0 :                         continue;
    2499              :                     } else {
    2500            0 :                         std::list<EngravingObject*> linkedSpanners;
    2501            0 :                         if (spanner->links()) {
    2502            0 :                             linkedSpanners = *spanner->links();
    2503              :                         } else {
    2504            0 :                             linkedSpanners.push_back(spanner);
    2505              :                         }
    2506            0 :                         for (EngravingObject* se : linkedSpanners) {
    2507            0 :                             deletedSpanners.insert(toSpanner(se));
    2508              :                         }
    2509            0 :                     }
    2510              :                 }
    2511           45 :                 deleteItem(e);
    2512              :             }
    2513              : 
    2514           45 :             if (!elSelectedAfterDeletion) {
    2515           45 :                 selectCRAtTickAndTrack(tick, track);
    2516              :             }
    2517              : 
    2518              :             // add these linked elements to list of already-deleted elements
    2519           93 :             for (EngravingObject* se : links) {
    2520           48 :                 deletedElements.insert(se);
    2521              :             }
    2522           45 :         }
    2523           33 :     }
    2524              : 
    2525          102 :     deselectAll();
    2526              :     // make new selection if appropriate
    2527          102 :     if (noteEntryMode()) {
    2528            1 :         if (!crsSelectedAfterDeletion.empty()) {
    2529            1 :             m_is.setSegment(crsSelectedAfterDeletion.front()->segment());
    2530              :         } else {
    2531            0 :             crsSelectedAfterDeletion.push_back(m_is.cr());
    2532              :         }
    2533              :     }
    2534          102 :     if (elSelectedAfterDeletion) {
    2535            0 :         select(elSelectedAfterDeletion);
    2536          102 :     } else if (!crsSelectedAfterDeletion.empty()) {
    2537           94 :         std::vector<EngravingItem*> elementsToSelect;
    2538          411 :         for (ChordRest* cr : crsSelectedAfterDeletion) {
    2539          317 :             if (cr) {
    2540          317 :                 if (cr->isChord()) {
    2541           21 :                     elementsToSelect.push_back(dynamic_cast<EngravingItem*>(toChord(cr)->upNote()));
    2542              :                 }
    2543          317 :                 if (cr->isRest()) {
    2544          295 :                     elementsToSelect.push_back(dynamic_cast<EngravingItem*>(cr));
    2545              :                 }
    2546              :             }
    2547              :         }
    2548           94 :         select(elementsToSelect, SelectType::ADD, 0);
    2549           94 :     }
    2550          102 : }
    2551              : 
    2552              : //---------------------------------------------------------
    2553              : //   cmdFullMeasureRest
    2554              : //---------------------------------------------------------
    2555              : 
    2556            0 : void Score::cmdFullMeasureRest()
    2557              : {
    2558            0 :     Segment* s1     = nullptr;
    2559            0 :     Segment* s2     = nullptr;
    2560            0 :     Fraction stick1 = { -1, 1 };
    2561            0 :     Fraction stick2 = { -1, 1 };
    2562            0 :     track_idx_t track1 = muse::nidx;
    2563            0 :     track_idx_t track2 = muse::nidx;
    2564            0 :     Rest* r = nullptr;
    2565              : 
    2566            0 :     if (noteEntryMode()) {
    2567            0 :         s1 = inputState().segment();
    2568            0 :         if (!s1 || s1->rtick().isNotZero()) {
    2569            0 :             return;
    2570              :         }
    2571            0 :         Measure* m = s1->measure();
    2572            0 :         s2 = m->last();
    2573            0 :         stick1 = s1->tick();
    2574            0 :         stick2 = s2->tick();
    2575            0 :         track1 = inputState().track();
    2576            0 :         track2 = track1 + 1;
    2577            0 :     } else if (selection().isRange()) {
    2578            0 :         s1 = selection().startSegment();
    2579            0 :         s2 = selection().endSegment();
    2580            0 :         if (style().styleB(Sid::createMultiMeasureRests)) {
    2581              :             // use underlying measures
    2582            0 :             if (s1 && s1->measure()->isMMRest()) {
    2583            0 :                 s1 = tick2segment(stick1);
    2584              :             }
    2585            0 :             if (s2 && s2->measure()->isMMRest()) {
    2586            0 :                 s2 = tick2segment(stick2, true);
    2587              :             }
    2588              :         }
    2589            0 :         stick1 = selection().tickStart();
    2590            0 :         stick2 = selection().tickEnd();
    2591            0 :         Segment* ss1 = s1;
    2592            0 :         if (ss1 && ss1->segmentType() != SegmentType::ChordRest) {
    2593            0 :             ss1 = ss1->next1(SegmentType::ChordRest);
    2594              :         }
    2595            0 :         bool fullMeasure = ss1 && (ss1->measure()->first(SegmentType::ChordRest) == ss1)
    2596            0 :                            && (s2 == 0 || (s2->segmentType() == SegmentType::EndBarLine)
    2597            0 :                                || (s2->segmentType() == SegmentType::TimeSigAnnounce)
    2598            0 :                                || (s2->segmentType() == SegmentType::KeySigAnnounce));
    2599            0 :         if (!fullMeasure) {
    2600            0 :             return;
    2601              :         }
    2602            0 :         track1 = selection().staffStart() * VOICES;
    2603            0 :         track2 = selection().staffEnd() * VOICES;
    2604            0 :     } else if (selection().cr()) {
    2605            0 :         ChordRest* cr = selection().cr();
    2606            0 :         if (!cr || cr->rtick().isNotZero()) {
    2607            0 :             return;
    2608              :         }
    2609            0 :         Measure* m = cr->measure();
    2610            0 :         s1 = m->first();
    2611            0 :         s2 = m->last();
    2612            0 :         stick1 = s1->tick();
    2613            0 :         stick2 = s2->tick();
    2614            0 :         track1 = selection().cr()->track();
    2615            0 :         track2 = track1 + 1;
    2616              :     } else {
    2617            0 :         return;
    2618              :     }
    2619              : 
    2620            0 :     for (track_idx_t track = track1; track < track2; ++track) {
    2621            0 :         if (selection().isRange() && !selectionFilter().canSelectVoice(track)) {
    2622            0 :             continue;
    2623              :         }
    2624              :         // first pass - remove non-initial rests from empty measures/voices
    2625            0 :         for (Segment* s = s1; s != s2; s = s->next1()) {
    2626            0 :             if (!(s->measure()->isOnlyRests(track))) {     // Don't remove anything from measures that contain notes
    2627            0 :                 continue;
    2628              :             }
    2629            0 :             if (s->segmentType() != SegmentType::ChordRest || !s->element(track)) {
    2630            0 :                 continue;
    2631              :             }
    2632            0 :             ChordRest* cr = toChordRest(s->element(track));
    2633              :             // keep first rest of measure as placeholder (replaced in second pass)
    2634              :             // but delete all others
    2635            0 :             if (s->rtick().isNotZero()) {
    2636            0 :                 removeChordRest(cr, true);
    2637              :             }
    2638              :         }
    2639              :         // second pass - replace placeholders with full measure rests
    2640            0 :         for (Measure* m = s1->measure(); m; m = m->nextMeasure()) {
    2641            0 :             if (m->isOnlyRests(track)) {
    2642            0 :                 ChordRest* cr = m->findChordRest(m->tick(), track);
    2643            0 :                 if (cr) {
    2644            0 :                     removeChordRest(cr, true);
    2645            0 :                     r = addRest(m->tick(), track, TDuration(DurationType::V_MEASURE), 0);
    2646            0 :                 } else if (noteEntryMode()) {
    2647              :                     // might be no cr at input position
    2648            0 :                     r = addRest(m->tick(), track, TDuration(DurationType::V_MEASURE), 0);
    2649              :                 }
    2650              :             }
    2651            0 :             if (s2 && (m == s2->measure())) {
    2652            0 :                 break;
    2653              :             }
    2654              :         }
    2655              :     }
    2656              : 
    2657              :     // selected range is probably empty now and possibly subsumed by an mmrest
    2658              :     // so updating selection requires forcing mmrests to be updated first
    2659            0 :     s1 = tick2segmentMM(stick1);
    2660            0 :     s2 = tick2segmentMM(stick2, true);
    2661            0 :     if (selection().isRange() && s1 && s2) {
    2662            0 :         m_selection.setStartSegment(s1);
    2663            0 :         m_selection.setEndSegment(s2);
    2664            0 :         m_selection.updateSelectedElements();
    2665            0 :     } else if (r) {
    2666              :         // note entry mode
    2667            0 :         select(r, SelectType::SINGLE);
    2668              :     } else {
    2669            0 :         deselectAll();
    2670              :     }
    2671              : }
    2672              : 
    2673              : //---------------------------------------------------------
    2674              : //   cmdCreateTuplet
    2675              : //    replace cr with tuplet
    2676              : //---------------------------------------------------------
    2677              : 
    2678           62 : void Score::cmdCreateTuplet(ChordRest* ocr, Tuplet* tuplet)
    2679              : {
    2680           62 :     track_idx_t track = ocr->track();
    2681           62 :     Measure* measure = ocr->measure();
    2682           62 :     Fraction tick = ocr->tick();
    2683           62 :     Fraction an = (tuplet->ticks() * tuplet->ratio()) / tuplet->baseLen().fraction();
    2684           62 :     if (!an.denominator()) {
    2685            0 :         return;
    2686              :     }
    2687              : 
    2688           62 :     if (ocr->tuplet()) {
    2689           10 :         tuplet->setTuplet(ocr->tuplet());
    2690              :     }
    2691           62 :     removeChordRest(ocr, false);
    2692              : 
    2693              :     ChordRest* cr;
    2694           62 :     if (ocr->isChord()) {
    2695           50 :         cr = Factory::createChord(this->dummy());
    2696           50 :         toChord(cr)->setStemDirection(toChord(ocr)->stemDirection());
    2697          100 :         for (Note* oldNote : toChord(ocr)->notes()) {
    2698           50 :             Note* note = Factory::createNote(toChord(cr));
    2699           50 :             note->setPitch(oldNote->pitch());
    2700           50 :             note->setTpc1(oldNote->tpc1());
    2701           50 :             note->setTpc2(oldNote->tpc2());
    2702           50 :             note->setString(oldNote->string());
    2703           50 :             note->setFret(oldNote->fret());
    2704           50 :             cr->add(note);
    2705              :         }
    2706              :     } else {
    2707           12 :         cr = Factory::createRest(this->dummy());
    2708              :     }
    2709              : 
    2710           62 :     int actualNotes = an.numerator() / an.denominator();
    2711              : 
    2712           62 :     tuplet->setTrack(track);
    2713           62 :     cr->setTuplet(tuplet);
    2714           62 :     cr->setTrack(track);
    2715           62 :     cr->setDurationType(tuplet->baseLen());
    2716           62 :     cr->setTicks(tuplet->baseLen().fraction());
    2717              : 
    2718           62 :     undoAddCR(cr, measure, tick);
    2719              : 
    2720           62 :     Fraction ticks = cr->actualTicks();
    2721              : 
    2722          202 :     for (int i = 0; i < (actualNotes - 1); ++i) {
    2723          140 :         tick += ticks;
    2724          140 :         Rest* rest = Factory::createRest(this->dummy());
    2725          140 :         rest->setTuplet(tuplet);
    2726          140 :         rest->setTrack(track);
    2727          140 :         rest->setDurationType(tuplet->baseLen());
    2728          140 :         rest->setTicks(tuplet->baseLen().fraction());
    2729          140 :         undoAddCR(rest, measure, tick);
    2730              :     }
    2731              : }
    2732              : 
    2733              : //---------------------------------------------------------
    2734              : //   cmdEnterRest
    2735              : //---------------------------------------------------------
    2736              : 
    2737            1 : void Score::cmdEnterRest(const TDuration& d)
    2738              : {
    2739            1 :     if (m_is.track() == muse::nidx) {
    2740            0 :         LOGD("cmdEnterRest: track invalid");
    2741            0 :         return;
    2742              :     }
    2743            1 :     startCmd(TranslatableString("undoableAction", "Enter rest"));
    2744            1 :     enterRest(d);
    2745            1 :     endCmd();
    2746              : }
    2747              : 
    2748              : //---------------------------------------------------------
    2749              : //   enterRest
    2750              : //---------------------------------------------------------
    2751              : 
    2752            1 : void Score::enterRest(const TDuration& d, InputState* externalInputState)
    2753              : {
    2754            1 :     InputState& is = externalInputState ? (*externalInputState) : m_is;
    2755              : 
    2756            1 :     if (is.beyondScore()) {
    2757            0 :         appendMeasures(1);
    2758            0 :         is.moveToNextInputPos();
    2759              :     }
    2760              : 
    2761            1 :     expandVoice(is.segment(), is.track());
    2762              : 
    2763            1 :     if (!is.cr()) {
    2764            0 :         LOGD("cannot enter rest here");
    2765            0 :         return;
    2766              :     }
    2767              : 
    2768            1 :     const track_idx_t track = is.track();
    2769            1 :     NoteVal nval;
    2770            1 :     setNoteRest(is.segment(), track, nval,
    2771              :                 d.fraction(), DirectionV::AUTO, /* forceAccidental */ false, is.articulationIds(), /* rhythmic */ false,
    2772              :                 externalInputState);
    2773            1 :     is.moveToNextInputPos();
    2774            1 :     if (!is.noteEntryMode() || is.usingNoteEntryMethod(NoteEntryMethod::BY_NOTE_NAME)) {
    2775            1 :         is.setRest(false);  // continue with normal note entry
    2776              :     }
    2777              : }
    2778              : 
    2779              : //---------------------------------------------------------
    2780              : //   removeChordRest
    2781              : //    remove chord or rest
    2782              : //    remove associated segment if empty
    2783              : //    remove beam
    2784              : //    remove slurs
    2785              : //---------------------------------------------------------
    2786              : 
    2787          693 : void Score::removeChordRest(ChordRest* cr, bool clearSegment)
    2788              : {
    2789          693 :     std::set<Segment*> segments;
    2790         1434 :     for (EngravingObject* e : cr->linkList()) {
    2791          741 :         if (cr->isChord()) {
    2792          477 :             std::set<Spanner*> startingSpanners = toChord(e)->startingSpanners();
    2793          478 :             for (Spanner* spanner : startingSpanners) {
    2794            1 :                 if (spanner->isTrill() || spanner->isSlur()) {
    2795            0 :                     doUndoRemoveElement(spanner);
    2796              :                 }
    2797              :             }
    2798          477 :         }
    2799          741 :         doUndoRemoveElement(static_cast<EngravingItem*>(e));
    2800          741 :         if (clearSegment) {
    2801          658 :             Segment* s = toChordRest(e)->segment();
    2802          658 :             if (segments.find(s) == segments.end()) {
    2803          654 :                 segments.insert(s);
    2804              :             }
    2805              :         }
    2806          693 :     }
    2807         1347 :     for (Segment* s : segments) {
    2808          654 :         if (s->empty()) {
    2809          436 :             doUndoRemoveElement(s);
    2810              :         }
    2811              :     }
    2812          693 :     if (cr->beam()) {
    2813            0 :         Beam* beam = cr->beam();
    2814            0 :         if (beam->generated()) {
    2815            0 :             removeElement(beam);
    2816            0 :             delete beam;
    2817              :         } else {
    2818            0 :             undoRemoveElement(beam);
    2819              :         }
    2820              :     }
    2821          693 : }
    2822              : 
    2823              : //---------------------------------------------------------
    2824              : //   cmdDeleteTuplet
    2825              : //    remove tuplet and replace with rest
    2826              : //---------------------------------------------------------
    2827              : 
    2828           48 : void Score::cmdDeleteTuplet(Tuplet* tuplet, bool replaceWithRest)
    2829              : {
    2830           48 :     std::vector<DurationElement*> elements = tuplet->elements();
    2831          199 :     for (DurationElement* de : elements) {
    2832          151 :         if (de->isChordRest()) {
    2833          134 :             removeChordRest(toChordRest(de), true);
    2834              :         } else {
    2835           17 :             assert(de->isTuplet());
    2836           17 :             cmdDeleteTuplet(toTuplet(de), false);
    2837              :         }
    2838              :     }
    2839           48 :     if (replaceWithRest) {
    2840            7 :         setRest(tuplet->tick(), tuplet->track(), tuplet->ticks(), true, tuplet->tuplet());
    2841              :     }
    2842           48 : }
    2843              : 
    2844              : //---------------------------------------------------------
    2845              : //   insertMeasure
    2846              : //    if inserting Measure, act on master score
    2847              : //    (and add to all linked scores)
    2848              : //    if inserting Box, add to local score only
    2849              : //---------------------------------------------------------
    2850              : 
    2851          390 : MeasureBase* Score::insertMeasure(ElementType type, MeasureBase* beforeMeasure, const InsertMeasureOptions& options)
    2852              : {
    2853          390 :     MeasureBase* localInsertMeasureBase = nullptr;
    2854          390 :     if (type == ElementType::MEASURE) {
    2855          390 :         if (MeasureBase* masterInsertMeasure = masterScore()->insertMeasure(beforeMeasure, options)) {
    2856          390 :             localInsertMeasureBase = tick2measure(masterInsertMeasure->tick());
    2857              :         }
    2858              :     } else {
    2859            0 :         localInsertMeasureBase = insertBox(type, beforeMeasure, options);
    2860              :     }
    2861              : 
    2862          390 :     if (localInsertMeasureBase && options.needDeselectAll) {
    2863          390 :         deselectAll();
    2864              :     }
    2865              : 
    2866          390 :     return localInsertMeasureBase;
    2867              : }
    2868              : 
    2869              : //---------------------------------------------------------
    2870              : //   insertBox
    2871              : //---------------------------------------------------------
    2872              : 
    2873           96 : MeasureBase* Score::insertBox(ElementType type, MeasureBase* beforeMeasure, const InsertMeasureOptions& options)
    2874              : {
    2875           96 :     const bool isFrame = type == ElementType::FBOX || type == ElementType::HBOX || type == ElementType::TBOX || type == ElementType::VBOX;
    2876           96 :     if (!isFrame) {
    2877            0 :         return nullptr;
    2878              :     }
    2879              : 
    2880           96 :     return this->insertBox(toMeasureBase(Factory::createItem(type, dummy())), beforeMeasure, options);
    2881              : }
    2882              : 
    2883           96 : MeasureBase* Score::insertBox(MeasureBase* box, MeasureBase* beforeMeasure, const InsertMeasureOptions& options)
    2884              : {
    2885           96 :     IF_ASSERT_FAILED(box) {
    2886            0 :         return nullptr;
    2887              :     }
    2888              : 
    2889           96 :     ElementType type = box->type();
    2890           96 :     const bool isFrame = type == ElementType::FBOX || type == ElementType::HBOX || type == ElementType::TBOX || type == ElementType::VBOX;
    2891           96 :     if (!isFrame) {
    2892            0 :         return nullptr;
    2893              :     }
    2894              : 
    2895           96 :     if (box->score() != this) {
    2896            0 :         box->setScore(this);
    2897              :     }
    2898              : 
    2899           96 :     Fraction tick;
    2900           96 :     bool isTitleFrame = type == ElementType::VBOX && beforeMeasure && beforeMeasure == beforeMeasure->score()->first();
    2901           96 :     if (beforeMeasure) {
    2902           96 :         if (beforeMeasure->isMeasure()) {
    2903           96 :             Measure* m = toMeasure(beforeMeasure);
    2904           96 :             if (m->isMMRest()) {
    2905            0 :                 beforeMeasure = m->mmRestFirst();
    2906            0 :                 deselectAll();
    2907              :             }
    2908          220 :             for (size_t staffIdx = 0; staffIdx < nstaves(); ++staffIdx) {
    2909          124 :                 if (m->isMeasureRepeatGroupWithPrevM(staffIdx)) {
    2910            0 :                     MScore::setError(MsError::CANNOT_SPLIT_MEASURE_REPEAT);
    2911            0 :                     return nullptr;
    2912              :                 }
    2913              :             }
    2914              :         } else {
    2915            0 :             beforeMeasure = beforeMeasure->top(); // don't try to insert in front of nested frame
    2916              :         }
    2917           96 :         tick = beforeMeasure->tick();
    2918              :     } else {
    2919            0 :         tick = last() ? last()->endTick() : Fraction(0, 1);
    2920              :     }
    2921              : 
    2922           96 :     box->setTick(tick);
    2923           96 :     box->setNext(beforeMeasure);
    2924           96 :     box->setPrev(beforeMeasure ? beforeMeasure->prev() : last());
    2925           96 :     box->setSizeIsSpatiumDependent(!isTitleFrame);
    2926              : 
    2927           96 :     if (type == ElementType::FBOX) {
    2928            5 :         toFBox(box)->init();
    2929              :     }
    2930              : 
    2931           96 :     undo(new InsertMeasures(box, box));
    2932              : 
    2933           96 :     if (options.needDeselectAll) {
    2934           96 :         deselectAll();
    2935              :     }
    2936              : 
    2937           96 :     if (options.cloneBoxToAllParts) {
    2938           62 :         box->manageExclusionFromParts(/*exclude =*/ false);
    2939              :     }
    2940              : 
    2941           96 :     return box;
    2942              : }
    2943              : 
    2944           85 : void Score::restoreInitialKeySigAndTimeSig()
    2945              : {
    2946           85 :     bool concertPitch = style().styleB(Sid::concertPitch);
    2947              :     static constexpr Fraction startTick = Fraction(0, 1);
    2948              : 
    2949           85 :     Measure* firstMeas = firstMeasure();
    2950          233 :     for (Staff* staff : m_staves) {
    2951          148 :         Key concertKey = Key::C;
    2952          148 :         Key transposedKey = concertKey;
    2953          148 :         const Part* part = staff->part();
    2954          148 :         const Instrument* instrument = part->instrument();
    2955          148 :         int transpose = -instrument->transpose().chromatic;
    2956          148 :         if (!concertPitch) {
    2957          148 :             transposedKey = Transpose::transposeKey(transposedKey, transpose, part->preferSharpFlat());
    2958              :         }
    2959              : 
    2960          148 :         Segment* keySegment = firstMeas->undoGetSegment(SegmentType::KeySig, startTick);
    2961              : 
    2962          148 :         KeySigEvent keySigEvent;
    2963          148 :         keySigEvent.setConcertKey(concertKey);
    2964          148 :         keySigEvent.setKey(transposedKey);
    2965              :         // use atonal KS for drums
    2966          148 :         if (instrument->useDrumset()) {
    2967            2 :             keySigEvent.setCustom(true);
    2968            2 :             keySigEvent.setMode(KeyMode::NONE);
    2969              :         }
    2970              : 
    2971          148 :         KeySig* newKeySig = Factory::createKeySig(keySegment);
    2972          148 :         newKeySig->setTrack(staff->idx() * VOICES);
    2973          148 :         keySegment->add(newKeySig);
    2974          148 :         newKeySig->setKeySigEvent(keySigEvent);
    2975          148 :         undoAddElement(newKeySig);
    2976              : 
    2977          148 :         staff->setKey(Fraction(0, 1), keySigEvent);
    2978              : 
    2979          148 :         Segment* timeSegment = firstMeas->undoGetSegment(SegmentType::TimeSig, startTick);
    2980          148 :         TimeSig* newTimeSig = Factory::createTimeSig(timeSegment);
    2981          148 :         newTimeSig->setTrack(staff->idx() * VOICES);
    2982          148 :         newTimeSig->setSig(Fraction(4, 4));
    2983          148 :         timeSegment->add(newTimeSig);
    2984          148 :         undoAddElement(newTimeSig);
    2985          148 :     }
    2986              : 
    2987           85 :     firstMeas->setTimesig(Fraction(4, 4));
    2988           85 :     firstMeas->setTicks(Fraction(4, 4));
    2989           85 : }
    2990              : 
    2991              : //---------------------------------------------------------
    2992              : //   checkSpanner
    2993              : //    check if spanners are still valid as anchors may
    2994              : //    have changed or be removed.
    2995              : //    Spanners need to have a start anchor. Slurs need a
    2996              : //    start and end anchor.
    2997              : //---------------------------------------------------------
    2998              : 
    2999        12668 : void Score::checkSpanner(const Fraction& startTick, const Fraction& endTick, bool removeOrphans)
    3000              : {
    3001        12668 :     std::vector<Spanner*> spannersToRemove;
    3002        12668 :     std::vector<Spanner*> spannersToShorten;
    3003        12668 :     auto spanners = m_spanner.findOverlapping(startTick.ticks(), endTick.ticks());
    3004              : 
    3005              :     // DEBUG: check all spanner
    3006              :     //        there may be spanners outside of score bc. some measures were deleted
    3007              : 
    3008        12668 :     Fraction lastTick = lastMeasure()->endTick();
    3009              : 
    3010        16935 :     for (const auto& i : m_spanner.map()) {
    3011         4267 :         Spanner* s = i.second;
    3012              : 
    3013         4267 :         if (s->isSlur()) {
    3014         2297 :             Segment* seg = tick2segmentMM(s->tick(), false, SegmentType::ChordRest);
    3015         2297 :             if (!seg || !seg->element(s->track())) {
    3016            0 :                 spannersToRemove.push_back(s);
    3017              :             } else {
    3018         2297 :                 seg = tick2segmentMM(s->tick2(), false, SegmentType::ChordRest);
    3019         2297 :                 if (!seg || !seg->element(s->track2())) {
    3020            0 :                     spannersToRemove.push_back(s);
    3021              :                 }
    3022              :             }
    3023              :         } else {
    3024              :             // remove spanner if there is no start element
    3025         1970 :             s->computeStartElement();
    3026         1970 :             if (!s->startElement()) {
    3027            0 :                 spannersToRemove.push_back(s);
    3028            0 :                 LOGD("checkSpanner::remove (3)");
    3029              :             } else {
    3030         1970 :                 if (s->tick2() > lastTick) {
    3031            0 :                     spannersToShorten.push_back(s);              //s->undoChangeProperty(Pid::SPANNER_TICKS, lastTick - s->tick());
    3032              :                 } else {
    3033         1970 :                     s->computeEndElement();
    3034              :                 }
    3035              :             }
    3036              :         }
    3037              :     }
    3038        12668 :     if (removeOrphans) {
    3039            2 :         for (auto s : spannersToRemove) {       // actually remove scheduled spanners
    3040            0 :             doUndoRemoveElement(s);
    3041              :         }
    3042              :     }
    3043        12668 :     for (Spanner* s : spannersToShorten) {      // shorten spanners that extended past end of score
    3044            0 :         undo(new ChangeProperty(s, Pid::SPANNER_TICKS, lastTick - s->tick()));
    3045            0 :         s->computeEndElement();
    3046              :     }
    3047        12668 : }
    3048              : 
    3049              : //---------------------------------------------------------
    3050              : //   checkTimeDelete
    3051              : //---------------------------------------------------------
    3052              : 
    3053           15 : bool Score::checkTimeDelete(Segment* startSegment, Segment* endSegment)
    3054              : {
    3055           15 :     Measure* startMeasure = startSegment->measure();
    3056              :     Measure* endMeasure;
    3057              : 
    3058           15 :     if (endSegment) {
    3059           15 :         endMeasure = endSegment->prev() ? endSegment->measure() : endSegment->measure()->prevMeasure();
    3060              :     } else {
    3061            0 :         endMeasure = lastMeasure();
    3062              :     }
    3063              : 
    3064           15 :     Fraction endTick = endSegment ? endSegment->tick() : endMeasure->endTick();
    3065           15 :     Fraction tick = startSegment->tick();
    3066           15 :     Fraction etick = (startMeasure == endMeasure ? endTick : startMeasure->endTick());
    3067              : 
    3068              :     // check for MeasureRepeat
    3069           15 :     bool startsAtBeginningOfMeasure = (tick == startMeasure->tick());
    3070           15 :     bool endsAtEndOfMeasure = (endTick == endMeasure->endTick());
    3071           36 :     for (size_t staffIdx = 0; staffIdx < nstaves(); ++staffIdx) {
    3072           21 :         if ((startMeasure->isMeasureRepeatGroup(staffIdx) && !startsAtBeginningOfMeasure)
    3073           21 :             || (endMeasure->isMeasureRepeatGroup(staffIdx) && !endsAtEndOfMeasure)
    3074           21 :             || startMeasure->isMeasureRepeatGroupWithPrevM(staffIdx)
    3075           42 :             || endMeasure->isMeasureRepeatGroupWithNextM(staffIdx)) {
    3076            0 :             MScore::setError(MsError::CANNOT_REMOVE_TIME_MEASURE_REPEAT);
    3077            0 :             return false;
    3078              :         }
    3079              :     }
    3080              : 
    3081           15 :     bool canDeleteTime = true;
    3082           15 :     while (canDeleteTime) {
    3083           99 :         for (size_t track = 0; canDeleteTime && track < m_staves.size() * VOICES; ++track) {
    3084           84 :             if (startMeasure->hasVoice(track)) {
    3085           22 :                 Segment* fs = startMeasure->first(SegmentType::ChordRest);
    3086           78 :                 for (Segment* s = fs; s; s = s->next(SegmentType::ChordRest)) {
    3087           68 :                     if (s->element(track)) {
    3088           55 :                         ChordRest* cr       = toChordRest(s->element(track));
    3089           55 :                         Tuplet* t           = cr->tuplet();
    3090           55 :                         DurationElement* de = t ? toDurationElement(t) : toDurationElement(cr);
    3091           55 :                         Fraction f          = de->tick() + de->actualTicks();
    3092           55 :                         Fraction cetick     = f;
    3093           55 :                         if (cetick <= tick) {
    3094            0 :                             continue;
    3095              :                         }
    3096           55 :                         if (de->tick() >= etick) {
    3097           12 :                             break;
    3098              :                         }
    3099           43 :                         if (t && (t->tick() < tick || cetick > etick)) {
    3100            0 :                             canDeleteTime = false;
    3101            0 :                             break;
    3102              :                         }
    3103              :                     }
    3104              :                 }
    3105              :             }
    3106              :         }
    3107           15 :         if (startMeasure == endMeasure) {
    3108           15 :             break;
    3109              :         }
    3110            0 :         startMeasure = endMeasure;
    3111            0 :         tick  = startMeasure->tick();
    3112            0 :         etick = endTick;
    3113              :     }
    3114           15 :     if (!canDeleteTime) {
    3115            0 :         MScore::setError(MsError::CANNOT_REMOVE_TIME_TUPLET);
    3116            0 :         return false;
    3117              :     }
    3118           15 :     return true;
    3119              : }
    3120              : 
    3121              : //---------------------------------------------------------
    3122              : //   cmdTimeDelete
    3123              : ///    delete time by decreasing measure length if partial measures are selected
    3124              : //---------------------------------------------------------
    3125              : 
    3126           15 : void Score::cmdTimeDelete()
    3127              : {
    3128           15 :     Transaction& tx = transactionManager()->currentOrDummyTransaction();
    3129              : 
    3130           15 :     EngravingItem* e = selection().element();
    3131              : 
    3132           15 :     if (e && e->isBarLine() && toBarLine(e)->segment()->isEndBarLineType()) {
    3133            0 :         const Measure* m = toBarLine(e)->segment()->measure();
    3134            0 :         const Measure* next = m->nextMeasure();
    3135            0 :         if (next) {
    3136            0 :             SplitJoinMeasure::joinMeasures(tx, m_masterScore, m->tick(), next->tick());
    3137              :         }
    3138            0 :         return;
    3139              :     }
    3140              : 
    3141           15 :     Segment* startSegment = nullptr;
    3142           15 :     Segment* endSegment = nullptr;
    3143              : 
    3144           15 :     if (selection().state() != SelState::RANGE) {
    3145            6 :         if (!e) {
    3146            0 :             return;
    3147              :         }
    3148              : 
    3149            6 :         ChordRest* cr = nullptr;
    3150            6 :         if (e->isNote()) {
    3151            6 :             cr = toNote(e)->chord();
    3152            0 :         } else if (e->isChordRest()) {
    3153            0 :             cr = toChordRest(e);
    3154              :         } else {
    3155            0 :             return;
    3156              :         }
    3157              : 
    3158            6 :         startSegment     = cr->segment();
    3159            6 :         Fraction endTick = cr->endTick();
    3160            6 :         endSegment       = tick2measure(endTick)->findSegment(SegmentType::ChordRest, endTick);
    3161              :     } else {
    3162            9 :         startSegment = selection().startSegment();
    3163            9 :         endSegment   = selection().endSegment();
    3164              :     }
    3165              : 
    3166           15 :     if (!isMaster() && masterScore()) {
    3167            0 :         Fraction startTick = startSegment->tick();
    3168            0 :         Measure* masterStartMeas = masterScore()->tick2measure(startTick);
    3169            0 :         Segment* masterStartSeg = masterStartMeas->findSegment(startSegment->segmentType(), startSegment->tick());
    3170            0 :         Segment* masterEndSeg = nullptr;
    3171              : 
    3172            0 :         if (endSegment) {
    3173            0 :             Fraction endTick = endSegment->tick();
    3174            0 :             Measure* masterEndMeas = masterScore()->tick2measure(endTick);
    3175            0 :             if (endSegment->isEndBarLineType()) {
    3176            0 :                 Measure* prevMasterEndMeasure = masterEndMeas->prevMeasure();
    3177            0 :                 masterEndMeas = prevMasterEndMeasure ? prevMasterEndMeasure : masterEndMeas;
    3178              :             }
    3179            0 :             masterEndSeg = masterEndMeas->findSegment(endSegment->segmentType(), endSegment->tick());
    3180              :         }
    3181              : 
    3182            0 :         masterScore()->doTimeDelete(masterStartSeg, masterEndSeg);
    3183              :     } else {
    3184           15 :         doTimeDelete(startSegment, endSegment);
    3185              :     }
    3186              : 
    3187           15 :     if (noteEntryMode()) {
    3188            1 :         Segment* currentSegment = endSegment;
    3189            1 :         ChordRest* cr = nullptr;
    3190            1 :         if (!currentSegment && lastMeasureMM()) {
    3191              :             // deleted to end of score - get last cr on current track
    3192            0 :             currentSegment = lastMeasureMM()->last();
    3193            0 :             if (currentSegment) {
    3194            0 :                 cr = currentSegment->nextChordRest(m_is.track(), true);
    3195            0 :                 if (cr) {
    3196            0 :                     currentSegment = cr->segment();
    3197              :                 }
    3198              :             }
    3199              :         }
    3200            1 :         if (!currentSegment) {
    3201              :             // no cr found - append a new measure
    3202            0 :             appendMeasures(1);
    3203            0 :             currentSegment = lastMeasureMM()->first(SegmentType::ChordRest);
    3204              :         }
    3205            1 :         m_is.setSegment(currentSegment);
    3206            1 :         cr = m_is.cr();
    3207            1 :         if (cr) {
    3208            1 :             if (cr->isChord()) {
    3209            1 :                 select(toChord(cr)->upNote(), SelectType::SINGLE);
    3210              :             } else {
    3211            0 :                 select(cr, SelectType::SINGLE);
    3212              :             }
    3213              :         } else {
    3214              :             // could not find cr to select,
    3215              :             // may be that there is a "hole" in the current track
    3216            0 :             deselectAll();
    3217              :         }
    3218              :     } else {
    3219           14 :         deselectAll();
    3220              :     }
    3221              : }
    3222              : 
    3223           15 : void Score::doTimeDelete(Segment* startSegment, Segment* endSegment)
    3224              : {
    3225           15 :     if (!checkTimeDelete(startSegment, endSegment)) {
    3226            0 :         return;
    3227              :     }
    3228              : 
    3229           15 :     MeasureBase* mbStart = startSegment->measure();
    3230           15 :     if (mbStart->isMeasure() && toMeasure(mbStart)->isMMRest()) {
    3231            0 :         mbStart = toMeasure(mbStart)->mmRestFirst();
    3232              :     }
    3233              :     MeasureBase* mbEnd;
    3234              : 
    3235           15 :     if (endSegment) {
    3236           15 :         mbEnd = endSegment->prev(SegmentType::ChordRest) ? endSegment->measure() : endSegment->measure()->prevMeasure();
    3237              :     } else {
    3238            0 :         mbEnd = lastMeasure();
    3239              :     }
    3240              : 
    3241           15 :     Fraction endTick = endSegment ? endSegment->tick() : mbEnd->endTick();
    3242              : 
    3243              :     for (;;) {
    3244           15 :         if (mbStart->tick() != startSegment->tick()) {
    3245            0 :             Fraction tick = startSegment->tick();
    3246            0 :             Fraction len;
    3247            0 :             if (mbEnd == mbStart) {
    3248            0 :                 len = endTick - tick;
    3249              :             } else {
    3250            0 :                 len = mbStart->endTick() - tick;
    3251              :             }
    3252            0 :             doTimeDeleteForMeasure(toMeasure(mbStart), startSegment, len);
    3253            0 :             if (mbStart == mbEnd) {
    3254            0 :                 break;
    3255              :             }
    3256            0 :             mbStart = mbStart->next();
    3257              :         }
    3258           15 :         endTick = endSegment ? endSegment->tick() : mbEnd->endTick();
    3259           15 :         if (mbEnd->endTick() != endTick) {
    3260            6 :             Fraction len = endTick - mbEnd->tick();
    3261            6 :             doTimeDeleteForMeasure(toMeasure(mbEnd), toMeasure(mbEnd)->first(), len);
    3262            6 :             if (mbStart == mbEnd) {
    3263            6 :                 break;
    3264              :             }
    3265            0 :             mbEnd = mbEnd->prev();
    3266              :         }
    3267            9 :         deleteMeasures(mbStart, mbEnd);
    3268            9 :         break;
    3269              :     }
    3270              : }
    3271              : 
    3272            6 : void Score::doTimeDeleteForMeasure(Measure* m, Segment* startSegment, const Fraction& f)
    3273              : {
    3274            6 :     if (f.isZero()) {
    3275            0 :         return;
    3276              :     }
    3277              : 
    3278            6 :     const Fraction tick  = startSegment->rtick();
    3279            6 :     const Fraction len   = f;
    3280            6 :     const Fraction etick = tick + len;
    3281              : 
    3282            6 :     Segment* fs = m->first(SegmentType::ChordRest);
    3283              : 
    3284           54 :     for (size_t track = 0; track < m_staves.size() * VOICES; ++track) {
    3285           48 :         if (!m->hasVoice(track)) {
    3286           35 :             continue;
    3287              :         }
    3288              : 
    3289           26 :         for (Segment* s = fs; s; s = s->next(SegmentType::ChordRest)) {
    3290           26 :             if (!s->element(track)) {
    3291            0 :                 continue;
    3292              :             }
    3293           26 :             ChordRest* cr   = toChordRest(s->element(track));
    3294           26 :             Fraction cetick = cr->rtick() + cr->actualTicks();
    3295              : 
    3296           26 :             if (cetick <= tick) {
    3297            0 :                 continue;
    3298              :             }
    3299           26 :             if (s->rtick() >= etick) {
    3300           13 :                 break;
    3301              :             }
    3302              : 
    3303           13 :             if (cr->isFullMeasureRest()) {
    3304            1 :                 if (cr->rtick() >= tick) {
    3305              :                     // Move full-measure rest from the deleted area
    3306            1 :                     undoRemoveElement(cr);
    3307            1 :                     ChordRest* newCR = toChordRest(cr->clone());
    3308            1 :                     newCR->setTicks(cr->ticks() - f);
    3309            1 :                     undoAddCR(newCR, m, m->tick() + etick);
    3310              :                 } else {
    3311            0 :                     cr->undoChangeProperty(Pid::DURATION, cr->ticks() - f);
    3312              :                 }
    3313              :             }
    3314              :             // inside deleted area
    3315           12 :             else if (s->rtick() >= tick && cetick <= etick) {
    3316              :                 // inside
    3317           10 :                 undoRemoveElement(cr);
    3318            2 :             } else if (s->rtick() >= tick) {
    3319              :                 // running out
    3320            2 :                 Fraction ff = cetick - etick;
    3321            2 :                 undoRemoveElement(cr);
    3322            2 :                 createCRSequence(ff, cr, tick + len);
    3323            0 :             } else if (s->rtick() < tick && cetick <= etick) {
    3324              :                 // running in
    3325            0 :                 Fraction f1 = tick - s->rtick();
    3326            0 :                 changeCRlen(cr, f1, false);
    3327              :             } else {
    3328              :                 // running in/out
    3329            0 :                 Fraction f1 = cr->ticks() - f;
    3330            0 :                 changeCRlen(cr, f1, false);
    3331              :             }
    3332              :         }
    3333              :     }
    3334            6 :     const Fraction abstick = startSegment->tick();
    3335              : 
    3336              :     // Move the annotations left in the deleted range to the next segment, so the deleted segments are removed now
    3337           12 :     for (Score* score : masterScore()->scoreList()) {
    3338            6 :         Measure* localMeasure = score->tick2measure(abstick);
    3339              : 
    3340            6 :         std::vector<Segment*> deletedSegments;
    3341            8 :         for (Segment* s = localMeasure->first(SegmentType::ChordRest); s && s->rtick() < etick; s = s->next(SegmentType::ChordRest)) {
    3342            2 :             if (s->rtick() >= tick) {
    3343            2 :                 deletedSegments.push_back(s);
    3344              :             }
    3345              :         }
    3346              : 
    3347            8 :         for (Segment* s : deletedSegments) {
    3348            2 :             Segment* ns = s->next1(SegmentType::ChordRest);
    3349            2 :             while (ns && ns->tick() < abstick + len) {
    3350            0 :                 ns = ns->next1(SegmentType::ChordRest);
    3351              :             }
    3352              : 
    3353            2 :             const std::vector<EngravingItem*> annotations = s->annotations(); // make a copy since we alter the list
    3354            4 :             for (EngravingItem* a : annotations) {
    3355            2 :                 undoRemoveElement(a);
    3356            2 :                 if (ns && !a->generated()) {
    3357            1 :                     EngravingItem* a1 = a->clone();
    3358            1 :                     a1->setOwnershipParent(ns);
    3359            1 :                     undoAddElement(a1);
    3360              :                 }
    3361              :             }
    3362            2 :         }
    3363           12 :     }
    3364              : 
    3365            6 :     undoInsertTime(abstick, -len);
    3366              : 
    3367           12 :     for (Score* score : masterScore()->scoreList()) {
    3368            6 :         Measure* localMeasure = score->tick2measure(abstick);
    3369              : 
    3370            6 :         EditStaveSharing::removeStaveSharingStatesOnRemoveTime(transactionManager()->currentOrDummyTransaction(), score, abstick,
    3371            6 :                                                                abstick + len);
    3372            6 :         undo(new InsertTime(score, abstick, -len));
    3373              : 
    3374            6 :         Fraction updatedTick = tick;
    3375              :         // tuplets store their tick: move those after the removed time back with their segments
    3376            6 :         std::set<Tuplet*> tuplets;
    3377           43 :         for (Segment* s = localMeasure->first(SegmentType::ChordRest); s; s = s->next()) {
    3378           37 :             if (s->rtick() < etick || s->rtick() == updatedTick) {
    3379            0 :                 continue;
    3380              :             }
    3381              : 
    3382           37 :             if (s->isChordRestType()) {
    3383          311 :                 for (EngravingItem* e : s->elist()) {
    3384          297 :                     for (Tuplet* t = e ? toChordRest(e)->tuplet() : nullptr; t && t->tick() >= abstick + len; t = t->tuplet()) {
    3385              :                         // shared tuplets follow their origin
    3386           17 :                         if (t->originItems().empty()) {
    3387           14 :                             tuplets.insert(t);
    3388              :                         }
    3389              :                     }
    3390              :                 }
    3391              :             }
    3392           37 :             s->undoChangeProperty(Pid::TICK, updatedTick);
    3393           37 :             updatedTick += s->ticks();
    3394              :         }
    3395              : 
    3396           10 :         for (Tuplet* t : tuplets) {
    3397            4 :             t->undoChangeProperty(Pid::TICK, t->tick() - len);
    3398              :         }
    3399              : 
    3400            6 :         undo(new ChangeMeasureLen(localMeasure, localMeasure->ticks() - f));
    3401           12 :     }
    3402              : }
    3403              : 
    3404              : //---------------------------------------------------------
    3405              : //   undoPropertyChanged
    3406              : //    return true if an property was actually changed
    3407              : //---------------------------------------------------------
    3408              : 
    3409            0 : bool Score::undoPropertyChanged(EngravingItem* item, Pid propId, const PropertyValue& propValue, PropertyFlags propFlags)
    3410              : {
    3411            0 :     Transaction& tx = masterScore()->transactionManager()->currentOrDummyTransaction();
    3412              : 
    3413            0 :     bool changed = false;
    3414              : 
    3415            0 :     const PropertyValue currentPropValue = item->getProperty(propId);
    3416            0 :     const PropertyFlags currentPropFlags = item->propertyFlags(propId);
    3417              : 
    3418            0 :     if ((currentPropValue != propValue) || (currentPropFlags != propFlags)) {
    3419            0 :         item->setPropertyFlags(propId, propFlags);
    3420            0 :         tx.pushWithoutPerforming(new ChangeProperty(item, propId, propValue, propFlags));
    3421            0 :         changed = true;
    3422              :     }
    3423              : 
    3424            0 :     const std::list<EngravingObject*> linkedItems = item->linkListForPropertyPropagation();
    3425              : 
    3426            0 :     for (EngravingObject* linkedItem : linkedItems) {
    3427            0 :         if (linkedItem == item) {
    3428            0 :             continue;
    3429              :         }
    3430            0 :         PropertyPropagation propertyPropagate = item->propertyPropagation(toEngravingItem(linkedItem), propId);
    3431            0 :         switch (propertyPropagate) {
    3432            0 :         case PropertyPropagation::PROPAGATE:
    3433            0 :             if (linkedItem->getProperty(propId) != currentPropValue) {
    3434            0 :                 tx.push(new ChangeProperty(linkedItem, propId, currentPropValue, propFlags));
    3435            0 :                 changed = true;
    3436              :             }
    3437            0 :             break;
    3438            0 :         case PropertyPropagation::UNLINK:
    3439            0 :             item->unlinkPropertyFromMaster(propId);
    3440            0 :             break;
    3441            0 :         default:
    3442            0 :             break;
    3443              :         }
    3444              :     }
    3445              : 
    3446            0 :     return changed;
    3447            0 : }
    3448              : 
    3449            0 : void Score::undoPropertyChanged(EngravingObject* e, Pid t, const PropertyValue& st, PropertyFlags ps)
    3450              : {
    3451            0 :     if (e->getProperty(t) != st) {
    3452            0 :         Transaction& tx = masterScore()->transactionManager()->currentOrDummyTransaction();
    3453            0 :         tx.pushWithoutPerforming(new ChangeProperty(e, t, st, ps));
    3454              :     }
    3455            0 : }
    3456              : 
    3457          145 : void Score::undoChangeStyleVal(Sid idx, const PropertyValue& v)
    3458              : {
    3459          145 :     std::unordered_map<Sid, PropertyValue> map;
    3460          145 :     map.emplace(idx, v);
    3461              : 
    3462          145 :     undo(new ChangeStyleValues(this, std::move(map)));
    3463          145 : }
    3464              : 
    3465            1 : void Score::undoChangeStyleValues(std::unordered_map<Sid, PropertyValue> values)
    3466              : {
    3467            1 :     undo(new ChangeStyleValues(this, std::move(values)));
    3468            1 : }
    3469              : 
    3470            0 : void Score::undoChangePageNumberOffset(int po)
    3471              : {
    3472            0 :     undo(new ChangePageNumberOffset(this, po));
    3473            0 : }
    3474              : 
    3475          230 : void Score::undoChangeParent(EngravingItem* element, EngravingItem* parent, staff_idx_t staffIdx, bool changeLinksParents)
    3476              : {
    3477          230 :     if (!element || !parent) {
    3478            0 :         return;
    3479              :     }
    3480              : 
    3481          230 :     if (element->ownershipParent() == parent && staffIdx == element->staffIdx()) {
    3482            0 :         return;
    3483              :     }
    3484              : 
    3485          230 :     Staff* destStaff = staff(staffIdx);
    3486          230 :     bool recreateItemNeeded = false;
    3487              : 
    3488          230 :     const std::list<EngravingObject*> links = element->linkList();
    3489          531 :     for (EngravingObject* obj : links) {
    3490          301 :         EngravingItem* item = toEngravingItem(obj);
    3491          301 :         Score* linkedScore = item->score();
    3492          301 :         Staff* linkedOrigin = item->staff();
    3493          301 :         Staff* linkedDest = linkedScore != this && destStaff != element->staff() ? destStaff->findLinkedInScore(linkedScore) : linkedOrigin; // don't allow staff-change of linked elements within the same score
    3494          301 :         if (!linkedDest && element->systemFlag()) {
    3495            0 :             linkedDest = linkedScore->staff(0);
    3496              :         }
    3497              : 
    3498          301 :         if (!linkedScore || (!changeLinksParents && item != element)) {
    3499           71 :             continue;
    3500              :         }
    3501          230 :         if (item == element) {
    3502              :             // Master score
    3503          230 :             undo(new ChangeParent(element, parent, staffIdx));
    3504            0 :         } else if (linkedOrigin && linkedDest) {
    3505              :             // Part - origin and destination staves are in this part
    3506              :             EngravingItem* linkedParent;
    3507            0 :             if (parent->isSegment()) {
    3508              :                 // Get parent segment in linked score
    3509            0 :                 Segment* oldSeg = toSegment(parent);
    3510            0 :                 Measure* oldMeas = oldSeg->measure();
    3511            0 :                 Measure* newMeas = linkedScore->tick2measure(oldMeas->tick());
    3512            0 :                 linkedParent = newMeas->tick2segment(oldSeg->tick(), oldSeg->segmentType());
    3513            0 :                 if (!linkedParent && oldSeg->isType(SegmentType::Duration)) {
    3514              :                     // A ChordRest segment that exists in the score may not exist in the part.
    3515              :                     // In that case we create a TimeTick segment as new parent for the linked item.
    3516            0 :                     linkedParent = newMeas->getSegment(SegmentType::TimeTick, oldSeg->tick());
    3517              :                 }
    3518              :             } else {
    3519            0 :                 linkedParent = parent->findLinkedInStaff(linkedDest);
    3520              :             }
    3521            0 :             IF_ASSERT_FAILED(linkedParent) {
    3522            0 :                 continue;
    3523              :             }
    3524            0 :             linkedScore->undo(new ChangeParent(item, linkedParent, linkedScore->staffIdx(linkedDest)));
    3525            0 :         } else if (linkedOrigin && !linkedDest) {
    3526              :             // Part - move is to a different staff
    3527              :             // Remove original item
    3528            0 :             linkedScore->undoRemoveElement(item, false);
    3529            0 :             recreateItemNeeded = true;
    3530              :         }
    3531              :     }
    3532              : 
    3533          230 :     if (recreateItemNeeded) {
    3534              :         // Need to create item in some parts
    3535            0 :         const std::list<EngravingObject*> destStaffLinks = destStaff->linkList();
    3536            0 :         for (EngravingObject* obj : destStaffLinks) {
    3537            0 :             Staff* linkedDest = toStaff(obj);
    3538            0 :             Score* linkedScore = linkedDest->score();
    3539            0 :             if (linkedDest != destStaff && !element->findLinkedInScore(linkedScore)) {
    3540              :                 // Item should be in this score and isn't already
    3541            0 :                 EngravingItem* newItem = element->linkedClone();
    3542              :                 EngravingItem* linkedParent;
    3543              : 
    3544            0 :                 if (parent->isSegment()) {
    3545              :                     // Get parent segment in linked score
    3546            0 :                     Segment* oldSeg = toSegment(parent);
    3547            0 :                     Measure* m = linkedScore->tick2measure(oldSeg->tick());
    3548            0 :                     linkedParent = m->tick2segment(oldSeg->tick(), oldSeg->segmentType());
    3549              :                 } else {
    3550            0 :                     linkedParent = parent->findLinkedInScore(linkedScore);
    3551              :                 }
    3552              : 
    3553            0 :                 newItem->setOwnershipParent(linkedParent);
    3554            0 :                 newItem->setTrack(linkedScore->staffIdx(linkedDest) * VOICES);
    3555            0 :                 newItem->setOffset(PointF());
    3556            0 :                 linkedParent->undoAddElement(newItem, false);
    3557              :             }
    3558              :         }
    3559            0 :     }
    3560          230 : }
    3561              : 
    3562            0 : void Score::undoResetPlayCountTextSettings(BarLine* bl)
    3563              : {
    3564            0 :     if (!bl || !bl->segment()) {
    3565            0 :         return;
    3566              :     }
    3567            0 :     Segment* seg = bl->segment();
    3568              : 
    3569            0 :     for (staff_idx_t staffIdx = 0; staffIdx < nstaves(); ++staffIdx) {
    3570            0 :         BarLine* curBl = toBarLine(seg->element(staff2track(staffIdx)));
    3571              : 
    3572            0 :         if (!curBl) {
    3573            0 :             continue;
    3574              :         }
    3575              : 
    3576            0 :         curBl->undoResetProperty(Pid::PLAY_COUNT_TEXT_SETTING);
    3577            0 :         curBl->undoResetProperty(Pid::PLAY_COUNT_TEXT);
    3578              :     }
    3579              : }
    3580              : 
    3581          365 : void Score::undoUpdatePlayCountText(Measure* m)
    3582              : {
    3583          365 :     if (!m) {
    3584            0 :         return;
    3585              :     }
    3586          365 :     const MStyle& _style = style();
    3587          365 :     const bool showText = _style.styleB(Sid::repeatPlayCountShow);
    3588          365 :     const bool singleRepeats = _style.styleB(Sid::repeatPlayCountShowSingleRepeats);
    3589          365 :     const int playCount = m->repeatCount();
    3590          365 :     const bool showPlayCount = showText && (playCount == 2 ? singleRepeats : true) && m->repeatEnd();
    3591              : 
    3592          365 :     Segment* endBarSeg = m->last(SegmentType::BarLineTypes);
    3593          365 :     BarLine* topBl = endBarSeg ? toBarLine(endBarSeg->element(0)) : nullptr;
    3594          365 :     if (!topBl) {
    3595          144 :         return;
    3596              :     }
    3597              : 
    3598          221 :     PlayCountText* topPlayCountText = toPlayCountText(endBarSeg->findAnnotation(ElementType::PLAY_COUNT_TEXT, 0, 0));
    3599          221 :     if (showPlayCount) {
    3600            0 :         if (!topPlayCountText) {
    3601            0 :             topPlayCountText = Factory::createPlayCountText(endBarSeg);
    3602            0 :             topPlayCountText->setTrack(0);
    3603            0 :             topPlayCountText->setSelected(topBl->selected());
    3604            0 :             undoAddElement(topPlayCountText);
    3605              :         }
    3606              :     } else {
    3607          221 :         undoRemoveElement(topPlayCountText);
    3608          221 :         return;
    3609              :     }
    3610              : }
    3611              : 
    3612         1378 : Measure* Score::undoGetMeasure(const Fraction& tick)
    3613              : {
    3614         1378 :     Measure* last = lastMeasure();
    3615         1378 :     if (!last || last->endTick() <= tick) {
    3616          157 :         Fraction lastTick  = last ? last->endTick() : Fraction(0, 1);
    3617          314 :         while (tick >= lastTick) {
    3618          157 :             MeasureBase* m = score()->insertMeasure(ElementType::MEASURE);
    3619          157 :             lastTick += m->ticks();
    3620              :         }
    3621              :     }
    3622         1378 :     return tick2measure(tick);
    3623              : }
    3624              : 
    3625           29 : void Score::undoChangeBarLineType(BarLine* bl, BarLineType barType, bool allStaves, bool replace)
    3626              : {
    3627           29 :     if (barType == bl->barLineType()) {
    3628           16 :         return;
    3629              :     }
    3630              : 
    3631           13 :     Measure* m = bl->measure();
    3632           13 :     if (!m) {
    3633            0 :         return;
    3634              :     }
    3635              : 
    3636           13 :     bool keepStartRepeat = false;
    3637              : 
    3638           13 :     if (barType == BarLineType::START_REPEAT && bl->segment()->segmentType() != SegmentType::BeginBarLine) {
    3639            0 :         m = m->nextMeasure();
    3640            0 :         if (!m) {  // we were in last measure
    3641            0 :             return;
    3642              :         }
    3643           13 :     } else if (bl->barLineType() == BarLineType::START_REPEAT) {
    3644            3 :         if (m->system() && m->isFirstInSystem()) {
    3645            2 :             if (barType != BarLineType::END_REPEAT) {
    3646            4 :                 for (Score* lscore : m->score()->scoreList()) {
    3647            2 :                     Measure* lmeasure = lscore->tick2measure(m->tick());
    3648            2 :                     if (lmeasure) {
    3649            2 :                         lmeasure->undoChangeProperty(Pid::REPEAT_START, false);
    3650              :                     }
    3651            2 :                 }
    3652              :             }
    3653            2 :             return;
    3654              :         }
    3655              : 
    3656            1 :         m = m->prevMeasureMM();
    3657            1 :         if (!m) {
    3658            0 :             return;
    3659              :         }
    3660              : 
    3661            1 :         bl = const_cast<BarLine*>(m->endBarLine());
    3662            1 :         if (!bl) {
    3663            0 :             return;
    3664              :         }
    3665              : 
    3666            1 :         if (barType == BarLineType::END_REPEAT) {
    3667            0 :             keepStartRepeat = true;
    3668              :         }
    3669              :     }
    3670              : 
    3671              :     // when setting barline type on mmrest, set for underlying measure (and linked staves)
    3672              :     // createMMRest will then set for the mmrest directly
    3673           11 :     Measure* m2 = m->isMMRest() ? m->mmRestLast() : m;
    3674              : 
    3675           11 :     switch (barType) {
    3676            9 :     case BarLineType::END:
    3677              :     case BarLineType::NORMAL:
    3678              :     case BarLineType::DOUBLE:
    3679              :     case BarLineType::BROKEN:
    3680              :     case BarLineType::DOTTED:
    3681              :     case BarLineType::REVERSE_END:
    3682              :     case BarLineType::HEAVY:
    3683              :     case BarLineType::DOUBLE_HEAVY: {
    3684            9 :         if (m->nextMeasureMM() && m->nextMeasureMM()->system() && m->nextMeasureMM()->isFirstInSystem()) {
    3685            2 :             keepStartRepeat = true;
    3686              :         }
    3687              : 
    3688            9 :         Segment* segment = bl->segment();
    3689            9 :         SegmentType segmentType = segment->segmentType();
    3690              : 
    3691            9 :         if (segmentType == SegmentType::EndBarLine) {
    3692            9 :             bool generated = false;
    3693            9 :             if (bl->barLineType() == barType) {
    3694            1 :                 generated = bl->generated();                // no change: keep current status
    3695            8 :             } else if (!bl->generated() && (barType == BarLineType::NORMAL)) {
    3696            3 :                 generated = true;                           // currently non-generated, changing to normal: assume generated
    3697              :             }
    3698            9 :             if (allStaves) {
    3699              :                 // use all staves of master score; we will take care of parts in loop through linked staves below
    3700            9 :                 Score* mScore = bl->masterScore();
    3701            9 :                 if (mScore->style().styleB(Sid::createMultiMeasureRests)) {
    3702            0 :                     m2 = mScore->tick2measureMM(m2->tick());
    3703            0 :                     if (!m2) {
    3704            0 :                         return;
    3705              :                     }
    3706            0 :                     segment = m2->undoGetSegment(segment->segmentType(), segment->tick());
    3707            0 :                     m2 = m2->isMMRest() ? m2->mmRestLast() : m2;
    3708            0 :                     if (!m2) {
    3709            0 :                         return;
    3710              :                     }
    3711              :                 } else {
    3712            9 :                     m2 = mScore->tick2measure(m2->tick());
    3713            9 :                     if (!m2) {
    3714            0 :                         return;
    3715              :                     }
    3716            9 :                     segment = m2->undoGetSegment(segment->segmentType(), segment->tick());
    3717              :                 }
    3718              :             }
    3719            9 :             const std::vector<EngravingItem*>& elist = allStaves ? segment->elist() : std::vector<EngravingItem*> { bl };
    3720           45 :             for (EngravingItem* e : elist) {
    3721           36 :                 if (!e || !e->staff() || !e->isBarLine()) {
    3722           27 :                     continue;
    3723              :                 }
    3724              : 
    3725              :                 // handle linked staves/parts:
    3726              :                 // barlines themselves are not necessarily linked,
    3727              :                 // so use staffList to find linked staves
    3728            9 :                 BarLine* sbl = toBarLine(e);
    3729           18 :                 for (Staff* lstaff : sbl->staff()->staffList()) {
    3730            9 :                     Score* lscore = lstaff->score();
    3731            9 :                     track_idx_t ltrack = lstaff->idx() * VOICES;
    3732              : 
    3733              :                     // handle mmrests:
    3734              :                     // set the barline on the underlying measure
    3735              :                     // this will copied to the mmrest during layout, in createMMRest
    3736            9 :                     Measure* lmeasure = lscore->tick2measure(m2->tick());
    3737            9 :                     if (!lmeasure) {
    3738            0 :                         continue;
    3739              :                     }
    3740              : 
    3741            9 :                     lmeasure->undoChangeProperty(Pid::REPEAT_END, false);
    3742              : 
    3743            9 :                     Measure* nextMeasure = lmeasure->nextMeasure();
    3744            9 :                     if (nextMeasure && !keepStartRepeat) {
    3745            6 :                         nextMeasure->undoChangeProperty(Pid::REPEAT_START, false);
    3746              :                     }
    3747            9 :                     Segment* lsegment = lmeasure->undoGetSegmentR(SegmentType::EndBarLine, lmeasure->ticks());
    3748            9 :                     BarLine* lbl = toBarLine(lsegment->element(ltrack));
    3749            9 :                     if (!lbl) {
    3750            0 :                         lbl = Factory::createBarLine(lsegment);
    3751            0 :                         lbl->setTrack(ltrack);
    3752            0 :                         lbl->setSpanStaff(lstaff->barLineSpan());
    3753            0 :                         lbl->setSpanFrom(lstaff->barLineFrom());
    3754            0 :                         lbl->setSpanTo(lstaff->barLineTo());
    3755            0 :                         lbl->setBarLineType(barType);
    3756            0 :                         lbl->setGenerated(generated);
    3757            0 :                         lscore->addElement(lbl);
    3758            0 :                         if (!generated) {
    3759            0 :                             lbl->linkTo(sbl);
    3760              :                         }
    3761              :                     } else {
    3762            9 :                         lscore->undo(new ChangeProperty(lbl, Pid::GENERATED, generated, PropertyFlags::NOSTYLE));
    3763            9 :                         lscore->undo(new ChangeProperty(lbl, Pid::BARLINE_TYPE, PropertyValue::fromValue(barType), PropertyFlags::NOSTYLE));
    3764              :                         // set generated flag before and after so it sticks on type change and also works on undo/redo
    3765            9 :                         lscore->undo(new ChangeProperty(lbl, Pid::GENERATED, generated, PropertyFlags::NOSTYLE));
    3766            9 :                         if (lbl != sbl && !generated && !lbl->links()) {
    3767            0 :                             lscore->undo(new Link(lbl, sbl));
    3768            9 :                         } else if (lbl != sbl && generated && lbl->isLinked(sbl)) {
    3769            0 :                             lscore->undo(new Unlink(lbl));
    3770            0 :                             while (EngravingItem* linkedOnCoveringMMRest = sbl->findLinkedInScore(lscore)) {
    3771              :                                 // Edge case: an additional link of this barline exists on the covering mmRest of lbl's measure
    3772            0 :                                 lscore->undo(new Unlink(linkedOnCoveringMMRest));
    3773            0 :                                 lscore->doUndoRemoveElement(linkedOnCoveringMMRest);
    3774            0 :                             }
    3775              :                         }
    3776              :                     }
    3777            9 :                 }
    3778              :             }
    3779            9 :         } else if (segmentType == SegmentType::BeginBarLine) {
    3780            0 :             for (Score* lscore : m2->score()->scoreList()) {
    3781            0 :                 Measure* lmeasure = lscore->tick2measure(m2->tick());
    3782            0 :                 Segment* segment1 = lmeasure->undoGetSegmentR(SegmentType::BeginBarLine, Fraction(0, 1));
    3783            0 :                 for (EngravingItem* e : segment1->elist()) {
    3784            0 :                     if (e) {
    3785            0 :                         lscore->undo(new ChangeProperty(e, Pid::GENERATED, false, PropertyFlags::NOSTYLE));
    3786            0 :                         lscore->undo(new ChangeProperty(e, Pid::BARLINE_TYPE, PropertyValue::fromValue(barType), PropertyFlags::NOSTYLE));
    3787              :                         // set generated flag before and after so it sticks on type change and also works on undo/redo
    3788            0 :                         lscore->undo(new ChangeProperty(e, Pid::GENERATED, false, PropertyFlags::NOSTYLE));
    3789              :                     }
    3790              :                 }
    3791            0 :             }
    3792              :         }
    3793              :     }
    3794            9 :     break;
    3795            0 :     case BarLineType::START_REPEAT: {
    3796            0 :         for (size_t staffIdx = 0; staffIdx < m2->score()->nstaves(); ++staffIdx) {
    3797            0 :             if (m2->isMeasureRepeatGroupWithPrevM(staffIdx)) {
    3798            0 :                 MScore::setError(MsError::CANNOT_SPLIT_MEASURE_REPEAT);
    3799            0 :                 return;
    3800              :             }
    3801              :         }
    3802            0 :         for (Score* lscore : m2->score()->scoreList()) {
    3803            0 :             Measure* lmeasure = lscore->tick2measure(m2->tick());
    3804            0 :             if (lmeasure) {
    3805            0 :                 lmeasure->undoChangeProperty(Pid::REPEAT_START, true);
    3806            0 :                 lmeasure = lmeasure->prevMeasure();
    3807            0 :                 if (lmeasure && replace) {
    3808            0 :                     lmeasure->undoChangeProperty(Pid::REPEAT_END, false);
    3809              :                 }
    3810              :             }
    3811            0 :         }
    3812              :     }
    3813            0 :     break;
    3814            2 :     case BarLineType::END_REPEAT: {
    3815            5 :         for (size_t staffIdx = 0; staffIdx < m2->score()->nstaves(); ++staffIdx) {
    3816            3 :             if (m2->isMeasureRepeatGroupWithNextM(staffIdx)) {
    3817            0 :                 MScore::setError(MsError::CANNOT_SPLIT_MEASURE_REPEAT);
    3818            0 :                 return;
    3819              :             }
    3820              :         }
    3821            6 :         for (Score* lscore : m2->score()->scoreList()) {
    3822            4 :             Measure* lmeasure = lscore->tick2measure(m2->tick());
    3823            4 :             if (lmeasure) {
    3824            4 :                 lmeasure->undoChangeProperty(Pid::REPEAT_END, true);
    3825            4 :                 lmeasure = lmeasure->nextMeasure();
    3826            4 :                 if (lmeasure && replace) {
    3827            0 :                     lmeasure->undoChangeProperty(Pid::REPEAT_START, false);
    3828              :                 }
    3829              :             }
    3830            2 :         }
    3831              :     }
    3832            2 :     break;
    3833            0 :     case BarLineType::END_START_REPEAT: {
    3834            0 :         for (size_t staffIdx = 0; staffIdx < m2->score()->nstaves(); ++staffIdx) {
    3835            0 :             if (m2->isMeasureRepeatGroupWithNextM(staffIdx)) {
    3836            0 :                 MScore::setError(MsError::CANNOT_SPLIT_MEASURE_REPEAT);
    3837            0 :                 return;
    3838              :             }
    3839              :         }
    3840            0 :         for (Score* lscore : m2->score()->scoreList()) {
    3841            0 :             Measure* lmeasure = lscore->tick2measure(m2->tick());
    3842            0 :             if (lmeasure) {
    3843            0 :                 lmeasure->undoChangeProperty(Pid::REPEAT_END, true);
    3844            0 :                 lmeasure = lmeasure->nextMeasure();
    3845            0 :                 if (lmeasure) {
    3846            0 :                     lmeasure->undoChangeProperty(Pid::REPEAT_START, true);
    3847              :                 }
    3848              :             }
    3849            0 :         }
    3850              :     }
    3851            0 :     break;
    3852              :     }
    3853              : 
    3854           11 :     undoUpdatePlayCountText(m);
    3855              : }
    3856              : 
    3857              : //---------------------------------------------------------
    3858              : //   undoChangeElement
    3859              : //---------------------------------------------------------
    3860              : 
    3861          118 : void Score::undoChangeElement(EngravingItem* oldElement, EngravingItem* newElement)
    3862              : {
    3863          118 :     if (!oldElement) {
    3864            3 :         undoAddElement(newElement);
    3865              :     } else {
    3866          115 :         const std::list<EngravingObject*> links = oldElement->linkList();
    3867          230 :         for (EngravingObject* obj : links) {
    3868          115 :             EngravingItem* item = toEngravingItem(obj);
    3869          115 :             if (item == oldElement) {
    3870          115 :                 undo(new ChangeElement(oldElement, newElement));
    3871              :             } else {
    3872            0 :                 if (item->score()) {
    3873            0 :                     EngravingItem* newClone = newElement->clone();
    3874            0 :                     item->score()->undo(new ChangeElement(item, newClone));
    3875              :                 }
    3876              :             }
    3877              :         }
    3878          115 :     }
    3879          118 : }
    3880              : 
    3881           39 : void Score::updateInstrumentChangeTranspositions(KeySigEvent& key, Staff* staff, const Fraction& tick)
    3882              : {
    3883           39 :     DO_ASSERT(staff->score() == this);
    3884           39 :     if (!key.forInstrumentChange()) {
    3885           39 :         const KeyList& kl = staff->keyList();
    3886           39 :         int nextTick = kl.nextKeyTick(tick.ticks());
    3887              : 
    3888           47 :         while (nextTick != -1) {
    3889            8 :             KeySigEvent e = kl.key(nextTick);
    3890            8 :             if (e.forInstrumentChange()) {
    3891            8 :                 if (key.isAtonal() && !e.isAtonal()) {
    3892            0 :                     e.setMode(KeyMode::NONE);
    3893            0 :                     e.setConcertKey(Key::C);
    3894              :                 } else {
    3895            8 :                     e.setMode(key.mode());
    3896            8 :                     Interval transposeInterval = staff->part()->instrument(Fraction::fromTicks(nextTick))->transpose();
    3897            8 :                     transposeInterval.flip();
    3898            8 :                     Key ckey = key.concertKey();
    3899            8 :                     Key nkey = Transpose::transposeKey(ckey, transposeInterval, staff->part()->preferSharpFlat());
    3900            8 :                     e.setConcertKey(ckey);
    3901            8 :                     e.setKey(nkey);
    3902              :                 }
    3903            8 :                 Measure* m = tick2measure(Fraction::fromTicks(nextTick));
    3904            8 :                 Segment* s = m ? m->tick2segment(Fraction::fromTicks(nextTick), SegmentType::KeySig) : nullptr;
    3905            8 :                 track_idx_t track = staff->idx() * VOICES;
    3906            8 :                 KeySig* keySig = nullptr;
    3907            8 :                 EngravingItem* keySigElem = s ? s->element(track) : nullptr;
    3908            8 :                 if (keySigElem && keySigElem->isKeySig()) {
    3909            8 :                     keySig = toKeySig(keySigElem);
    3910              :                 }
    3911            8 :                 if (keySig) {
    3912            8 :                     undo(new ChangeKeySig(keySig, e, keySig->showCourtesy()));
    3913              :                 }
    3914            8 :                 nextTick = kl.nextKeyTick(nextTick);
    3915              :             } else {
    3916            0 :                 nextTick = -1;
    3917              :             }
    3918            8 :         }
    3919              :     }
    3920           39 : }
    3921              : 
    3922              : //---------------------------------------------------------
    3923              : //   findLinkedChord
    3924              : //---------------------------------------------------------
    3925              : 
    3926          551 : static Chord* findLinkedChord(Chord* c, Staff* nstaff)
    3927              : {
    3928          551 :     Excerpt* se = c->score()->excerpt();
    3929          551 :     Excerpt* de = nstaff->score()->excerpt();
    3930          551 :     track_idx_t strack = c->track();
    3931              : 
    3932          551 :     if (se) {
    3933            0 :         strack = muse::key(se->tracksMapping(), strack);
    3934              :     }
    3935          551 :     track_idx_t dtrack = nstaff->idx() * VOICES + strack % VOICES;
    3936              : 
    3937          551 :     if (de) {
    3938            0 :         std::vector<track_idx_t> l = muse::values(de->tracksMapping(), strack);
    3939            0 :         if (l.empty()) {
    3940              :             // simply return the first linked chord whose staff is equal to nstaff
    3941            0 :             for (EngravingObject* ee : c->linkList()) {
    3942            0 :                 Chord* ch = toChord(ee);
    3943            0 :                 if (ch->staff() == nstaff) {
    3944            0 :                     return ch;
    3945              :                 }
    3946            0 :             }
    3947            0 :             return nullptr;
    3948              :         }
    3949            0 :         for (track_idx_t i : l) {
    3950            0 :             if (nstaff->idx() * VOICES <= i && (nstaff->idx() + 1) * VOICES > i) {
    3951            0 :                 dtrack = i;
    3952            0 :                 break;
    3953              :             }
    3954              :         }
    3955            0 :     }
    3956              : 
    3957          551 :     Segment* s = c->segment();
    3958          551 :     Measure* nm = nstaff->score()->tick2measure(s->tick());
    3959          551 :     Segment* ns = nm->findSegment(s->segmentType(), s->tick());
    3960          551 :     EngravingItem* ne = ns ? ns->element(dtrack) : nullptr;
    3961          551 :     if (!ne || !ne->isChord()) {
    3962            0 :         return nullptr;
    3963              :     }
    3964          551 :     Chord* nc = toChord(ne);
    3965          551 :     if (c->isGrace()) {
    3966            3 :         Chord* pc = toChord(c->ownershipParent());
    3967            3 :         size_t index = 0;
    3968            3 :         for (Chord* gc : pc->graceNotes()) {
    3969            3 :             if (c == gc) {
    3970            3 :                 break;
    3971              :             }
    3972            0 :             index++;
    3973              :         }
    3974            3 :         if (index < nc->graceNotes().size()) {
    3975            3 :             nc = nc->graceNotes().at(index);
    3976              :         }
    3977              :     }
    3978          551 :     return nc;
    3979              : }
    3980              : 
    3981              : //---------------------------------------------------------
    3982              : //   undoChangeChordRestLen
    3983              : //---------------------------------------------------------
    3984              : 
    3985           71 : void Score::undoChangeChordRestLen(ChordRest* cr, const TDuration& d)
    3986              : {
    3987           71 :     cr->undoChangeProperty(Pid::DURATION_TYPE_WITH_DOTS, d.typeWithDots());
    3988           71 :     cr->undoChangeProperty(Pid::DURATION, d.fraction());
    3989           71 : }
    3990              : 
    3991              : //---------------------------------------------------------
    3992              : //   undoRemovePart
    3993              : //---------------------------------------------------------
    3994              : 
    3995           14 : void Score::undoRemovePart(Part* part, size_t partIdx)
    3996              : {
    3997           14 :     undo(new RemovePart(part, partIdx));
    3998           14 : }
    3999              : 
    4000              : //---------------------------------------------------------
    4001              : //   undoInsertPart
    4002              : //---------------------------------------------------------
    4003              : 
    4004          104 : void Score::undoInsertPart(Part* part, size_t targetPartIndex)
    4005              : {
    4006          104 :     undo(new InsertPart(part, targetPartIndex));
    4007          104 : }
    4008              : 
    4009              : //---------------------------------------------------------
    4010              : //   undoRemoveStaff
    4011              : //    idx - index of staff in part
    4012              : //---------------------------------------------------------
    4013              : 
    4014           34 : void Score::undoRemoveStaff(Staff* staff)
    4015              : {
    4016           34 :     const staff_idx_t staffIndex = staff->idx();
    4017           34 :     assert(staffIndex != muse::nidx);
    4018              : 
    4019           34 :     std::vector<Spanner*> spannersToRemove;
    4020              : 
    4021           48 :     for (auto it = m_spanner.cbegin(); it != m_spanner.cend(); ++it) {
    4022           14 :         Spanner* spanner = it->second;
    4023              : 
    4024           14 :         if (allowRemoveWhenRemovingStaves(spanner, staffIndex)) {
    4025           11 :             spannersToRemove.push_back(spanner);
    4026              :         }
    4027              :     }
    4028              : 
    4029           38 :     for (Spanner* spanner : m_unmanagedSpanner) {
    4030            4 :         if (allowRemoveWhenRemovingStaves(spanner, staffIndex)) {
    4031            4 :             spannersToRemove.push_back(spanner);
    4032              :         }
    4033              :     }
    4034              : 
    4035           49 :     for (Spanner* spanner : spannersToRemove) {
    4036           15 :         spanner->undoUnlink();
    4037           15 :         doUndoRemoveElement(spanner);
    4038              :     }
    4039              : 
    4040              :     //
    4041              :     //    adjust measures
    4042              :     //
    4043          331 :     for (Measure* m = staff->score()->firstMeasure(); m; m = m->nextMeasure()) {
    4044          297 :         m->cmdRemoveStaves(staffIndex, staffIndex + 1);
    4045          297 :         if (m->hasMMRest()) {
    4046            7 :             m->mmRest()->cmdRemoveStaves(staffIndex, staffIndex + 1);
    4047              :         }
    4048              :     }
    4049              : 
    4050           34 :     staff->undoUnlink();
    4051              : 
    4052           34 :     undo(new RemoveStaff(staff));
    4053           34 : }
    4054              : 
    4055              : //---------------------------------------------------------
    4056              : //   undoInsertStaff
    4057              : //    idx - index of staff in part
    4058              : //---------------------------------------------------------
    4059              : 
    4060          198 : void Score::undoInsertStaff(Staff* staff, staff_idx_t ridx, bool createRests)
    4061              : {
    4062          198 :     undo(new InsertStaff(staff, ridx));
    4063          198 :     staff_idx_t idx = staffIdx(staff->part()) + ridx;
    4064          826 :     for (Measure* m = firstMeasure(); m; m = m->nextMeasure()) {
    4065          628 :         m->cmdAddStaves(idx, idx + 1, createRests);
    4066          628 :         if (m->hasMMRest()) {
    4067            8 :             m->mmRest()->cmdAddStaves(idx, idx + 1, false);
    4068              :         }
    4069              :     }
    4070              :     // when newly adding an instrument,
    4071              :     // this was already set when we created the staff
    4072              :     // we don't have any better info at this point
    4073              :     // and it doesn't work to adjust bracket & barlines until all staves are added
    4074              :     // TODO: adjust brackets only when appropriate
    4075              :     //adjustBracketsIns(idx, idx+1);
    4076          198 : }
    4077              : 
    4078              : //---------------------------------------------------------
    4079              : //   undoAddElement
    4080              : //---------------------------------------------------------
    4081              : 
    4082         9949 : void Score::undoAddElement(EngravingItem* element, bool addToLinkedStaves, bool ctrlModifier, EngravingItem* elementToRelink)
    4083              : {
    4084         9949 :     Transaction& tx = transactionManager()->currentOrDummyTransaction();
    4085              : 
    4086         9949 :     Staff* ostaff = element->staff();
    4087         9949 :     track_idx_t strack = element->track();
    4088              : 
    4089         9949 :     ElementType et = element->type();
    4090              : 
    4091              :     //
    4092              :     // some elements are replicated for all parts regardless of
    4093              :     // linking:
    4094              :     //
    4095              : 
    4096         9949 :     bool isSystemLine = isSystemTextLine(element);
    4097              : 
    4098         9949 :     if ((et == ElementType::REHEARSAL_MARK)
    4099         9938 :         || (et == ElementType::SYSTEM_TEXT)
    4100         9923 :         || (et == ElementType::TRIPLET_FEEL)
    4101         9923 :         || (et == ElementType::JUMP)
    4102         9922 :         || (et == ElementType::MARKER)
    4103         9920 :         || (et == ElementType::TEMPO_TEXT)
    4104         9825 :         || (et == ElementType::PLAY_COUNT_TEXT)
    4105         9825 :         || isSystemLine
    4106              :         ) {
    4107          128 :         std::vector<Staff* > staffList;
    4108              : 
    4109          128 :         if (!addToLinkedStaves) {
    4110            3 :             staffList.push_back(element->staff());
    4111          125 :         } else if (ctrlModifier && isSystemLine) {
    4112            0 :             staffList = ostaff->staffList();
    4113            0 :             element->setSystemFlag(false);
    4114              :         } else {
    4115          251 :             for (Score* s : scoreList()) {
    4116          126 :                 staffList.push_back(s->staff(0)); // system objects always appear on the top staff
    4117          186 :                 for (Staff* staff : s->systemObjectStaves()) {
    4118           60 :                     IF_ASSERT_FAILED(staff->idx() != muse::nidx) {
    4119            0 :                         continue;
    4120              :                     }
    4121              : 
    4122           60 :                     staffList.push_back(staff);
    4123              :                 }
    4124          125 :             }
    4125              :         }
    4126              : 
    4127          128 :         if (elementToRelink) {
    4128            1 :             muse::remove(staffList, ostaff);
    4129              :         }
    4130              : 
    4131          128 :         bool originalAdded = false;
    4132          316 :         for (Staff* staff : staffList) {
    4133          188 :             if (!staff) {
    4134            0 :                 continue;
    4135              :             }
    4136              : 
    4137          188 :             Score* score  = staff->score();
    4138          188 :             staff_idx_t staffIdx = staff->idx();
    4139          188 :             size_t ntrack = staffIdx * VOICES;
    4140              :             EngravingItem* ne;
    4141              : 
    4142          188 :             if (ostaff && staff->score() == ostaff->score() && staff == staffList.front() && !originalAdded) {
    4143              :                 // add the element itself to the first system object staff in the score
    4144          127 :                 ne = element;
    4145          127 :                 originalAdded = true;
    4146              :             } else {
    4147              :                 // add linked clones to the other staves
    4148           61 :                 ne = element->linkedClone();
    4149           61 :                 ne->setScore(score);
    4150           61 :                 ne->setSelected(false);
    4151           61 :                 ne->setTrack(staffIdx * VOICES + element->voice());
    4152              :             }
    4153              : 
    4154          188 :             if (isSystemLine) {
    4155            5 :                 Spanner* nsp = toSpanner(ne);
    4156            5 :                 Spanner* sp = toSpanner(element);
    4157            5 :                 long long diff = sp->track2() - sp->track();
    4158            5 :                 nsp->setTrack2(nsp->track() + diff);
    4159            5 :                 nsp->computeStartElement();
    4160            5 :                 nsp->computeEndElement();
    4161            5 :                 doUndoAddElement(nsp);
    4162          183 :             } else if (et == ElementType::MARKER || et == ElementType::JUMP) {
    4163            3 :                 Measure* om = toMeasure(element->ownershipParent());
    4164            3 :                 Measure* m  = score->tick2measure(om->tick());
    4165            3 :                 ne->setTrack(ntrack);
    4166            3 :                 ne->setOwnershipParent(m);
    4167            3 :                 doUndoAddElement(ne);
    4168          183 :             } else if (et == ElementType::MEASURE_NUMBER) {
    4169            0 :                 toMeasure(element->ownershipParent())->undoChangeProperty(Pid::MEASURE_NUMBER_MODE,
    4170              :                                                                           static_cast<int>(MeasureNumberMode::SHOW));
    4171          180 :             } else if (et == ElementType::PLAY_COUNT_TEXT) {
    4172            0 :                 Segment* segment  = toSegment(element->ownershipParent());
    4173            0 :                 Fraction tick     = segment->tick();
    4174            0 :                 Measure* m        = score->tick2measure(tick - Fraction::eps());
    4175            0 :                 Segment* seg      = m->undoGetSegment(SegmentType::EndBarLine, tick);
    4176            0 :                 ne->setTrack(ntrack);
    4177            0 :                 ne->setOwnershipParent(seg);
    4178            0 :                 doUndoAddElement(ne);
    4179              :             } else {
    4180          180 :                 Segment* segment  = toSegment(element->ownershipParent());
    4181          180 :                 Fraction tick     = segment->tick();
    4182          180 :                 Measure* m        = score->tick2measure(tick);
    4183          180 :                 Segment* seg      = m->undoGetSegment(SegmentType::ChordRest, tick);
    4184          180 :                 ne->setTrack(ntrack);
    4185          180 :                 ne->setOwnershipParent(seg);
    4186          180 :                 doUndoAddElement(ne);
    4187              :             }
    4188              :         }
    4189              : 
    4190          128 :         return;
    4191          128 :     }
    4192              : 
    4193        19642 :     if (et == ElementType::FINGERING
    4194         9818 :         || (et == ElementType::IMAGE && !element->ownershipParent()->isSegment())
    4195         9815 :         || (et == ElementType::SYMBOL && !element->ownershipParent()->isSegment())
    4196         9812 :         || et == ElementType::NOTE
    4197         9712 :         || et == ElementType::TEXT
    4198         9712 :         || et == ElementType::GLISSANDO
    4199         9701 :         || et == ElementType::GUITAR_BEND
    4200         9409 :         || et == ElementType::NOTELINE
    4201         9409 :         || et == ElementType::BEND
    4202         9409 :         || (et == ElementType::CHORD && toChord(element)->isGrace())
    4203         9335 :         || et == ElementType::LAISSEZ_VIB
    4204         9317 :         || et == ElementType::PARTIAL_TIE
    4205        19639 :         || et == ElementType::PARENTHESIS
    4206              :         ) {
    4207          564 :         const EngravingObject* parent = element->ownershipParent();
    4208          564 :         const LinkedObjects* links = parent ? parent->links() : nullptr;
    4209              : 
    4210              :         // don't link part name
    4211          564 :         if (et == ElementType::TEXT) {
    4212            0 :             Text* t = toText(element);
    4213            0 :             if (t->textStyleType() == TextStyleType::INSTRUMENT_EXCERPT) {
    4214            0 :                 links = 0;
    4215              :             }
    4216              :         }
    4217          564 :         if (links == 0 || !addToLinkedStaves) {
    4218          547 :             doUndoAddElement(element);
    4219          547 :             return;
    4220              :         }
    4221           51 :         for (EngravingObject* ee : *links) {
    4222           34 :             EngravingItem* e = static_cast<EngravingItem*>(ee);
    4223              :             EngravingItem* ne;
    4224           34 :             if (e == parent) {
    4225           17 :                 ne = element;
    4226              :             } else {
    4227           17 :                 if (element->isGlissando() || element->isGuitarBend() || element->isNoteLine()) {            // and other spanners with Anchor::NOTE
    4228            2 :                     Note* newEnd = Spanner::endElementFromSpanner(toSpanner(element), e);
    4229            2 :                     if (newEnd) {
    4230            2 :                         ne = element->linkedClone();
    4231            2 :                         toSpanner(ne)->setNoteSpan(toNote(e), newEnd);
    4232            2 :                         if (element->isGuitarBend() && element->staffType()->isTabStaff()) {
    4233            0 :                             toGuitarBend(ne)->endNote()->setVisible(true);
    4234              :                         }
    4235              :                     } else {                    //couldn't find suitable start note
    4236            0 :                         continue;
    4237              :                     }
    4238           15 :                 } else if (element->isFingering()) {
    4239            3 :                     bool tabFingering = e->staff()->staffType(e->tick())->showTabFingering();
    4240            3 :                     if (e->staff()->isTabStaff(e->tick()) && !tabFingering) {
    4241            0 :                         continue;
    4242              :                     }
    4243            3 :                     ne = element->linkedClone();
    4244              :                 } else {
    4245           12 :                     ne = element->linkedClone();
    4246              :                 }
    4247              :             }
    4248           34 :             ne->setScore(e->score());
    4249           34 :             ne->setSelected(false);
    4250           34 :             ne->setOwnershipParent(e);
    4251           34 :             doUndoAddElement(ne);
    4252              :         }
    4253           17 :         return;
    4254              :     }
    4255              : 
    4256         9257 :     if (et == ElementType::LAYOUT_BREAK) {
    4257           30 :         LayoutBreak* lb = toLayoutBreak(element);
    4258           30 :         if (lb->layoutBreakType() == LayoutBreakType::SECTION) {
    4259            0 :             doUndoAddElement(lb);
    4260            0 :             MeasureBase* m = lb->measure();
    4261            0 :             if (m->isBox()) {
    4262              :                 // for frames, use linked frames
    4263            0 :                 LinkedObjects* links = m->links();
    4264            0 :                 if (links) {
    4265            0 :                     for (EngravingObject* lo : *links) {
    4266            0 :                         if (lo->isBox()) {
    4267            0 :                             Box* box = toBox(lo);
    4268            0 :                             Score* score = box->score();
    4269            0 :                             if (score != lb->score()) {
    4270            0 :                                 EngravingItem* e = lb->linkedClone();
    4271            0 :                                 e->setScore(score);
    4272            0 :                                 e->setOwnershipParent(box);
    4273            0 :                                 doUndoAddElement(e);
    4274              :                             }
    4275              :                         }
    4276              :                     }
    4277            0 :                     return;
    4278              :                 } else { // if thera are not linked frames, use previous measure
    4279            0 :                     m = m->prevMeasure();
    4280            0 :                     if (!m) {
    4281            0 :                         return;
    4282              :                     }
    4283              :                 }
    4284              :             }
    4285            0 :             for (Score* s : scoreList()) {
    4286            0 :                 if (s != lb->score()) {
    4287            0 :                     EngravingItem* e = lb->linkedClone();
    4288            0 :                     e->setScore(s);
    4289            0 :                     Measure* nm = s->tick2measure(m->tick());
    4290            0 :                     e->setOwnershipParent(nm);
    4291            0 :                     doUndoAddElement(e);
    4292              :                 }
    4293            0 :             }
    4294            0 :             return;
    4295              :         }
    4296              :     }
    4297              : 
    4298         9257 :     if (ostaff == 0 || (
    4299         3135 :             et != ElementType::ARTICULATION
    4300         3088 :             && et != ElementType::ORNAMENT
    4301         3085 :             && et != ElementType::TAPPING
    4302         3085 :             && et != ElementType::CHORDLINE
    4303         3082 :             && et != ElementType::LYRICS
    4304         3060 :             && et != ElementType::SLUR
    4305         3018 :             && et != ElementType::HAMMER_ON_PULL_OFF
    4306         3017 :             && et != ElementType::TIE
    4307         2751 :             && et != ElementType::NOTE
    4308         2751 :             && et != ElementType::INSTRUMENT_CHANGE
    4309         2746 :             && et != ElementType::HAIRPIN
    4310         2730 :             && et != ElementType::OTTAVA
    4311         2727 :             && et != ElementType::TRILL
    4312         2726 :             && et != ElementType::VIBRATO
    4313         2726 :             && et != ElementType::TEXTLINE
    4314         2726 :             && et != ElementType::PEDAL
    4315         2725 :             && et != ElementType::LET_RING
    4316         2725 :             && et != ElementType::PALM_MUTE
    4317         2725 :             && et != ElementType::WHAMMY_BAR
    4318         2725 :             && et != ElementType::PARTIAL_LYRICSLINE
    4319         2723 :             && et != ElementType::BREATH
    4320         2709 :             && et != ElementType::DYNAMIC
    4321         2684 :             && et != ElementType::EXPRESSION
    4322         2684 :             && et != ElementType::STAFF_TEXT
    4323         2654 :             && et != ElementType::STAVE_SHARING_LABEL
    4324         2622 :             && et != ElementType::SYSTEM_TEXT
    4325         2622 :             && et != ElementType::TRIPLET_FEEL
    4326         2622 :             && et != ElementType::PLAYTECH_ANNOTATION
    4327         2622 :             && et != ElementType::CAPO
    4328         2622 :             && et != ElementType::STRING_TUNINGS
    4329         2622 :             && et != ElementType::STICKING
    4330         2607 :             && et != ElementType::TREMOLO_SINGLECHORD
    4331         2589 :             && et != ElementType::TREMOLO_TWOCHORD
    4332         2589 :             && et != ElementType::ARPEGGIO
    4333         2589 :             && et != ElementType::CHORD_BRACKET
    4334         2589 :             && et != ElementType::SYMBOL
    4335         2589 :             && et != ElementType::IMAGE
    4336         2589 :             && et != ElementType::TREMOLOBAR
    4337         2589 :             && et != ElementType::FRET_DIAGRAM
    4338         2564 :             && et != ElementType::FERMATA
    4339         2562 :             && et != ElementType::HARMONY
    4340         2538 :             && et != ElementType::HARP_DIAGRAM
    4341         2533 :             && et != ElementType::FIGURED_BASS
    4342         2533 :             && et != ElementType::CLEF
    4343         2524 :             && et != ElementType::AMBITUS
    4344         2524 :             && et != ElementType::PLAY_COUNT_TEXT)
    4345              :         ) {
    4346         8646 :         doUndoAddElement(element);
    4347         8646 :         return;
    4348              :     }
    4349              : 
    4350          611 :     std::vector<Staff*> staves;
    4351          611 :     if (addToLinkedStaves) {
    4352          581 :         staves = ostaff->staffList();
    4353              :     } else {
    4354           30 :         staves.push_back(ostaff);
    4355              :     }
    4356              : 
    4357          611 :     if (elementToRelink) {
    4358            2 :         muse::remove(staves, ostaff);
    4359              :     }
    4360              : 
    4361         1243 :     for (Staff* staff : staves) {
    4362          632 :         Score* score = staff->score();
    4363          632 :         staff_idx_t staffIdx = staff->idx();
    4364              : 
    4365              :         // Some elements in voice 1 of a staff should be copied to every track which has a linked voice in this staff
    4366              :         static const std::set<ElementType> VOICE1_COPY_TYPES = {
    4367              :             ElementType::SYMBOL,
    4368              :             ElementType::IMAGE,
    4369              :             ElementType::TREMOLOBAR,
    4370              :             ElementType::DYNAMIC,
    4371              :             ElementType::EXPRESSION,
    4372              :             ElementType::STAFF_TEXT,
    4373              :             ElementType::PLAYTECH_ANNOTATION,
    4374              :             ElementType::CAPO,
    4375              :             ElementType::STRING_TUNINGS,
    4376              :             ElementType::STICKING,
    4377              :             ElementType::FRET_DIAGRAM,
    4378              :             ElementType::HARMONY,
    4379              :             ElementType::HAIRPIN,
    4380              :             ElementType::OTTAVA,
    4381              :             ElementType::TRILL,
    4382              :             ElementType::SLUR,
    4383              :             ElementType::HAMMER_ON_PULL_OFF,
    4384              :             ElementType::VIBRATO,
    4385              :             ElementType::TEXTLINE,
    4386              :             ElementType::PEDAL,
    4387              :             ElementType::LYRICS,
    4388              :             ElementType::PARTIAL_LYRICSLINE,
    4389              :             ElementType::CLEF,
    4390              :             ElementType::AMBITUS
    4391          636 :         };
    4392              : 
    4393          632 :         track_idx_t linkedTrack = ostaff->getLinkedTrackInStaff(staff, strack);
    4394          632 :         if (linkedTrack == muse::nidx) {
    4395            0 :             if (track2voice(strack) == 0 && muse::contains(VOICE1_COPY_TYPES, et)) {
    4396            0 :                 linkedTrack = staff2track(staffIdx);
    4397              :             } else {
    4398            0 :                 continue;
    4399              :             }
    4400              :         }
    4401              : 
    4402              :         EngravingItem* ne;
    4403          632 :         if (staff == ostaff) {
    4404          609 :             ne = element;
    4405              :         } else {
    4406           23 :             if (staff->rstaff() != ostaff->rstaff()) {
    4407            1 :                 switch (element->type()) {
    4408              :                 // exclude certain element types except on corresponding staff in part
    4409              :                 // this should be same list excluded in cloneStaff()
    4410            1 :                 case ElementType::STAFF_TEXT:
    4411              :                 case ElementType::SYSTEM_TEXT:
    4412              :                 case ElementType::TRIPLET_FEEL:
    4413              :                 case ElementType::PLAYTECH_ANNOTATION:
    4414              :                 case ElementType::CAPO:
    4415              :                 case ElementType::STRING_TUNINGS:
    4416              :                 case ElementType::FRET_DIAGRAM:
    4417              :                 case ElementType::HARMONY:
    4418              :                 case ElementType::FIGURED_BASS:
    4419              :                 case ElementType::DYNAMIC:
    4420              :                 case ElementType::EXPRESSION:
    4421              :                 case ElementType::LYRICS:                       // not normally segment-attached
    4422              :                 case ElementType::PARTIAL_LYRICSLINE:
    4423              :                 case ElementType::PLAY_COUNT_TEXT:
    4424              :                 case ElementType::WHAMMY_BAR:
    4425            1 :                     continue;
    4426            0 :                 default:
    4427            0 :                     break;
    4428              :                 }
    4429              :             }
    4430           22 :             ne = element->linkedClone();
    4431           22 :             ne->setScore(score);
    4432           22 :             ne->setSelected(false);
    4433           22 :             ne->setTrack(linkedTrack);
    4434              : 
    4435           22 :             if (ne->isFretDiagram()) {
    4436            0 :                 FretDiagram* fd = toFretDiagram(ne);
    4437            0 :                 Harmony* fdHarmony = fd->harmony();
    4438            0 :                 if (fdHarmony) {
    4439              :                     // TODO: this stuff should be done by overriding setScore setSelected and setTrack for FretDiagram [M.S.]
    4440            0 :                     fdHarmony->setScore(score);
    4441            0 :                     fdHarmony->setSelected(false);
    4442            0 :                     fdHarmony->setTrack(linkedTrack);
    4443              :                 }
    4444              :             }
    4445              :         }
    4446              : 
    4447          631 :         if (element->isArticulationFamily()) {
    4448           50 :             Articulation* a  = toArticulation(element);
    4449              :             Segment* segment;
    4450              :             SegmentType st;
    4451              :             Measure* m;
    4452           50 :             Fraction tick;
    4453           50 :             if (a->ownershipParent()->isChordRest()) {
    4454           50 :                 ChordRest* cr = a->chordRest();
    4455           50 :                 segment       = cr->segment();
    4456           50 :                 st            = SegmentType::ChordRest;
    4457           50 :                 tick          = segment->tick();
    4458           50 :                 m             = score->tick2measure(tick);
    4459              :             } else {
    4460            0 :                 segment  = toSegment(a->ownershipParent()->ownershipParent());
    4461            0 :                 st       = SegmentType::EndBarLine;
    4462            0 :                 tick     = segment->tick();
    4463            0 :                 m        = score->tick2measure(tick);
    4464            0 :                 if (m->tick() == tick) {
    4465            0 :                     m = m->prevMeasure();
    4466              :                 }
    4467              :             }
    4468           50 :             Segment* seg = m->findSegment(st, tick);
    4469           50 :             if (seg == 0) {
    4470            0 :                 LOGW("undoAddSegment: segment not found");
    4471            0 :                 break;
    4472              :             }
    4473           50 :             Articulation* na = toArticulation(ne);
    4474           50 :             na->setTrack(linkedTrack);
    4475           50 :             if (a->ownershipParent()->isChordRest()) {
    4476           50 :                 ChordRest* cr = a->chordRest();
    4477              :                 ChordRest* ncr;
    4478           50 :                 if (cr->isGrace()) {
    4479            1 :                     ncr = findLinkedChord(toChord(cr), score->staff(staffIdx));
    4480              :                 } else {
    4481           49 :                     ncr = toChordRest(seg->element(linkedTrack));
    4482              :                 }
    4483           50 :                 na->setOwnershipParent(ncr);
    4484              :             } else {
    4485            0 :                 BarLine* bl = toBarLine(seg->element(linkedTrack));
    4486            0 :                 na->setOwnershipParent(bl);
    4487              :             }
    4488           50 :             doUndoAddElement(na);
    4489          581 :         } else if (element->isChordLine() || element->isLyrics()) {
    4490           28 :             ChordRest* cr    = toChordRest(element->ownershipParent());
    4491           28 :             Segment* segment = cr->segment();
    4492           28 :             Fraction tick    = segment->tick();
    4493           28 :             Measure* m       = score->tick2measure(tick);
    4494           28 :             Segment* seg     = m->findSegment(SegmentType::ChordRest, tick);
    4495           28 :             if (seg == 0) {
    4496            0 :                 LOGW("undoAddSegment: segment not found");
    4497            0 :                 break;
    4498              :             }
    4499           28 :             ne->setTrack(linkedTrack);
    4500           28 :             ChordRest* ncr = toChordRest(seg->element(linkedTrack));
    4501           28 :             ne->setOwnershipParent(ncr);
    4502           28 :             if (element->isChordLine()) {
    4503            6 :                 if (cr->isGrace()) {
    4504            0 :                     ncr = findLinkedChord(toChord(cr), score->staff(staffIdx));
    4505            0 :                     ne->setOwnershipParent(ncr);
    4506              :                 }
    4507            6 :                 ChordLine* oldChordLine = toChordLine(element);
    4508            6 :                 ChordLine* newChordLine = toChordLine(ne);
    4509              :                 // Chordline also needs to know the new note
    4510            6 :                 Note* newNote = toChord(ncr)->findNote(oldChordLine->note()->pitch());
    4511            6 :                 newChordLine->setNote(newNote);
    4512              :             }
    4513           28 :             doUndoAddElement(ne);
    4514          553 :         } else if (element->isHarmony() && element->ownershipParent()->isFretDiagram()) {
    4515            1 :             EngravingItem* parentFd = element->ownershipParentItem();
    4516            1 :             if (parentFd->score() != score) {
    4517              :                 // Find linked fret diagram
    4518            0 :                 EngravingItem* linkedFd = parentFd->findLinkedInScore(score);
    4519            0 :                 ne->setOwnershipParent(linkedFd);
    4520              :             }
    4521            1 :             doUndoAddElement(ne);
    4522              :         }
    4523              :         //
    4524              :         // elements with Segment as parent
    4525              :         //
    4526          552 :         else if (element->isSymbol()
    4527          552 :                  || element->isImage()
    4528          552 :                  || element->isTremoloBar()
    4529          552 :                  || element->isDynamic()
    4530          526 :                  || element->isExpression()
    4531          526 :                  || element->isStaffText()
    4532          496 :                  || element->isStaveSharingLabel()
    4533          464 :                  || element->isPlayTechAnnotation()
    4534          464 :                  || element->isCapo()
    4535          464 :                  || element->isStringTunings()
    4536          464 :                  || element->isSticking()
    4537          449 :                  || element->isFretDiagram()
    4538          424 :                  || element->isFermata()
    4539          421 :                  || element->isHarmony() // Case with parent FretDiagram handled above, so we know it has parent Segment
    4540          397 :                  || element->isHarpPedalDiagram()
    4541          392 :                  || element->isFiguredBass()
    4542          392 :                  || element->isClef()
    4543         1104 :                  || element->isAmbitus()) {
    4544          171 :             Segment* segment = toSegment(element->ownershipParent());
    4545          171 :             Fraction tick    = segment->tick();
    4546          171 :             Measure* m       = score->tick2measure(tick);
    4547          171 :             bool addClefToPrevMeasure = segment->isType(SegmentType::Clef) && element->isClef() && !toClef(element)->isHeader();
    4548          171 :             bool addBlToPrevMeasure = segment->isType(SegmentType::EndBarLine);
    4549          171 :             if (m->tick() == tick && (addClefToPrevMeasure || addBlToPrevMeasure) && m->prevMeasure()) {
    4550            1 :                 m = m->prevMeasure();
    4551              :             }
    4552          171 :             Segment* seg     = m->undoGetSegment(segment->segmentType(), tick);
    4553          171 :             ne->setTrack(linkedTrack);
    4554          171 :             ne->setOwnershipParent(seg);
    4555              : 
    4556          171 :             if (ne->isStringTunings()) {
    4557            0 :                 StringTunings* stringTunings = toStringTunings(ne);
    4558            0 :                 if (stringTunings->stringData()->isNull()) {
    4559            0 :                     const StringData* stringData = stringTunings->originPart()->stringData(tick, staff->idx());
    4560            0 :                     int frets = stringData->frets();
    4561            0 :                     std::vector<mu::engraving::instrString> stringList = stringData->stringList();
    4562              : 
    4563            0 :                     stringTunings->setStringData(StringData(frets, stringList));
    4564            0 :                 }
    4565              :             }
    4566              : 
    4567          171 :             doUndoAddElement(ne);
    4568              :             // transpose harmony if necessary
    4569          171 :             if (element->isHarmony() && ne != element) {
    4570            1 :                 Harmony* h = toHarmony(ne);
    4571            1 :                 if (score->style().styleB(Sid::concertPitch) != element->style().styleB(Sid::concertPitch)) {
    4572            0 :                     Staff* staffDest = h->staff();
    4573            0 :                     Interval interval = staffDest->transpose(tick);
    4574            0 :                     if (!interval.isZero()) {
    4575            0 :                         if (!score->style().styleB(Sid::concertPitch)) {
    4576            0 :                             interval.flip();
    4577              :                         }
    4578            0 :                         Transpose::undoTransposeHarmony(tx, h, interval);
    4579              :                     }
    4580              :                 }
    4581              :             }
    4582              : 
    4583              :             // Match vertical align settings of exiting items
    4584          171 :             if (ne->isHarmony() || ne->isFretDiagram()) {
    4585           49 :                 bool exclude = ne->excludeVerticalAlign();
    4586           49 :                 for (EngravingItem* item : seg->annotations()) {
    4587           73 :                     if ((!item->isFretDiagram() && !item->isHarmony())
    4588           73 :                         || item->staffIdx() != ne->staffIdx()) {
    4589            0 :                         continue;
    4590              :                     }
    4591              : 
    4592           49 :                     exclude = item->excludeVerticalAlign();
    4593           49 :                     break;
    4594              :                 }
    4595           49 :                 if (exclude != ne->excludeVerticalAlign()) {
    4596            0 :                     ne->undoChangeProperty(Pid::EXCLUDE_VERTICAL_ALIGN, exclude);
    4597              :                 }
    4598              :             }
    4599          381 :         } else if (element->isSlur()
    4600          337 :                    || element->isHairpin()
    4601          320 :                    || element->isOttava()
    4602          316 :                    || element->isTrill()
    4603          314 :                    || element->isVibrato()
    4604          314 :                    || element->isTextLine()
    4605          314 :                    || element->isPedal()
    4606          312 :                    || element->isLetRing()
    4607          312 :                    || element->isPalmMute()
    4608          312 :                    || element->isWhammyBar()
    4609          718 :                    || element->isPartialLyricsLine()) {
    4610           71 :             Spanner* sp   = toSpanner(element);
    4611           71 :             Spanner* nsp  = toSpanner(ne);
    4612           71 :             track_idx_t tr2 = sp->effectiveTrack2();
    4613           71 :             int diff = static_cast<int>(tr2 - sp->track());
    4614           71 :             nsp->setTrack2(linkedTrack + diff);
    4615           71 :             nsp->setTrack(linkedTrack);
    4616              : 
    4617              :             // determine start/end element for slurs
    4618              :             // this is only necessary if start/end element is
    4619              :             //   a grace note, otherwise the element can be set to zero
    4620              :             //   and will later be calculated from tick/track values
    4621              :             //
    4622           71 :             if (element->isSlur() && sp != nsp) {
    4623            1 :                 if (sp->startElement()) {
    4624            1 :                     std::list<EngravingObject*> sel = sp->startElement()->linkList();
    4625            2 :                     for (EngravingObject* ee : sel) {
    4626            2 :                         EngravingItem* e = static_cast<EngravingItem*>(ee);
    4627            2 :                         if (e->score() == nsp->score() && e->track() == nsp->track()) {
    4628            1 :                             nsp->setStartElement(e);
    4629            1 :                             break;
    4630              :                         }
    4631              :                     }
    4632            1 :                 }
    4633            1 :                 if (sp->endElement()) {
    4634            1 :                     std::list<EngravingObject*> eel = sp->endElement()->linkList();
    4635            2 :                     for (EngravingObject* ee : eel) {
    4636            2 :                         EngravingItem* e = static_cast<EngravingItem*>(ee);
    4637            2 :                         if (e->score() == nsp->score() && e->track() == nsp->track2()) {
    4638            1 :                             nsp->setEndElement(e);
    4639            1 :                             break;
    4640              :                         }
    4641              :                     }
    4642            1 :                 }
    4643              :             }
    4644              : 
    4645           71 :             if (sp->isTextLine() && sp != nsp) {
    4646            0 :                 EngravingItem* parent = sp->ownershipParentItem();
    4647            0 :                 if (parent && parent->isNote()) {
    4648            0 :                     nsp->setOwnershipParent(parent->findLinkedInStaff(staff));
    4649              :                 }
    4650            0 :                 EngravingItem* endEl = sp->endElement();
    4651            0 :                 if (endEl && endEl->isNote()) {
    4652            0 :                     nsp->setEndElement(endEl->findLinkedInStaff(staff));
    4653              :                 }
    4654              :             }
    4655              : 
    4656           71 :             doUndoAddElement(nsp);
    4657          310 :         } else if (et == ElementType::GLISSANDO || et == ElementType::GUITAR_BEND || et == ElementType::NOTELINE) {
    4658            0 :             doUndoAddElement(toSpanner(ne));
    4659          310 :         } else if (element->isType(ElementType::TREMOLO_TWOCHORD)) {
    4660            0 :             TremoloTwoChord* tremolo = item_cast<TremoloTwoChord*>(element);
    4661            0 :             ChordRest* cr1 = toChordRest(tremolo->chord1());
    4662            0 :             ChordRest* cr2 = toChordRest(tremolo->chord2());
    4663            0 :             int diff = static_cast<int>(cr2->track() - cr1->track());
    4664            0 :             Segment* s1    = cr1->segment();
    4665            0 :             Segment* s2    = cr2->segment();
    4666            0 :             Measure* m1    = s1->measure();
    4667            0 :             Measure* m2    = s2->measure();
    4668            0 :             Measure* nm1   = score->tick2measure(m1->tick());
    4669            0 :             Measure* nm2   = score->tick2measure(m2->tick());
    4670            0 :             Segment* ns1   = nm1->findSegment(s1->segmentType(), s1->tick());
    4671            0 :             Segment* ns2   = nm2->findSegment(s2->segmentType(), s2->tick());
    4672            0 :             Chord* c1      = toChord(ns1->element(linkedTrack));
    4673            0 :             Chord* c2      = toChord(ns2->element(linkedTrack + diff));
    4674            0 :             TremoloTwoChord* ntremolo = item_cast<TremoloTwoChord*>(ne);
    4675            0 :             ntremolo->setChords(c1, c2);
    4676            0 :             ntremolo->setOwnershipParent(c1);
    4677            0 :             doUndoAddElement(ntremolo);
    4678          310 :         } else if (element->isType(ElementType::TREMOLO_SINGLECHORD)) {
    4679           18 :             Chord* cr = toChord(element->ownershipParent());
    4680           18 :             Chord* c1 = findLinkedChord(cr, score->staff(staffIdx));
    4681           18 :             ne->setOwnershipParent(c1);
    4682           18 :             doUndoAddElement(ne);
    4683          292 :         } else if (element->isArpeggio() || element->isChordBracket()) {
    4684            0 :             ChordRest* cr = toChordRest(element->ownershipParent());
    4685            0 :             Segment* s    = cr->segment();
    4686            0 :             Measure* m    = s->measure();
    4687            0 :             Measure* nm   = score->tick2measure(m->tick());
    4688            0 :             Segment* ns   = nm->findSegment(s->segmentType(), s->tick());
    4689            0 :             Chord* c1     = toChord(ns->element(linkedTrack));
    4690            0 :             ne->setOwnershipParent(c1);
    4691            0 :             doUndoAddElement(ne);
    4692          292 :         } else if (element->isTie()) {
    4693          266 :             Tie* tie       = toTie(element);
    4694          266 :             Note* n1       = tie->startNote();
    4695          266 :             Note* n2       = tie->endNote();
    4696          266 :             Chord* cr1     = n1->chord();
    4697          266 :             Chord* cr2     = n2 ? n2->chord() : 0;
    4698              : 
    4699              :             // find corresponding notes in linked staff
    4700              :             // accounting for grace notes and cross-staff notation
    4701          266 :             int sm = 0;
    4702          266 :             if (cr1->staffIdx() != cr2->staffIdx()) {
    4703            0 :                 sm = static_cast<int>(cr2->staffIdx() - cr1->staffIdx());
    4704              :             }
    4705          266 :             Chord* c1 = findLinkedChord(cr1, score->staff(staffIdx));
    4706          266 :             Chord* c2 = findLinkedChord(cr2, score->staff(staffIdx + sm));
    4707              : 
    4708          266 :             IF_ASSERT_FAILED(c1) {
    4709            0 :                 return;
    4710              :             }
    4711              : 
    4712          266 :             Note* nn1 = c1->findNote(n1->pitch(), n1->unisonIndex());
    4713          266 :             Note* nn2 = c2 ? c2->findNote(n2->pitch(), n2->unisonIndex()) : 0;
    4714              : 
    4715          266 :             const track_idx_t track1 = c1->track();
    4716          266 :             const track_idx_t track2 = c2 ? c2->track() : track1;
    4717              : 
    4718              :             // create tie
    4719          266 :             Tie* ntie = toTie(ne);
    4720          266 :             ntie->eraseSpannerSegments();
    4721          266 :             ntie->setTrack(track1);
    4722          266 :             ntie->setTrack2(track2);
    4723          266 :             ntie->setStartNote(nn1);
    4724          266 :             ntie->setEndNote(nn2);
    4725          266 :             doUndoAddElement(ntie);
    4726           26 :         } else if (element->isInstrumentChange()) {
    4727            6 :             InstrumentChange* is = toInstrumentChange(element);
    4728            6 :             Segment* s1    = is->segment();
    4729            6 :             Measure* m1    = s1->measure();
    4730            6 :             Measure* nm1   = score->tick2measure(m1->tick());
    4731            6 :             Segment* ns1   = nm1->findSegment(s1->segmentType(), s1->tick());
    4732            6 :             InstrumentChange* nis = toInstrumentChange(ne);
    4733            6 :             nis->setOwnershipParent(ns1);
    4734            6 :             Fraction tickStart = nis->segment()->tick();
    4735            6 :             Part* part = nis->part();
    4736            6 :             Interval oldV = nis->staff()->transpose(tickStart);
    4737              :             // ws: instrument should not be changed here
    4738            6 :             if (is->instrument()->channel().empty() || is->instrument()->channel(0)->program() == -1) {
    4739            1 :                 nis->setInstrument(*staff->part()->instrument(s1->tick()));
    4740            5 :             } else if (nis != is) {
    4741            1 :                 nis->setInstrument(*is->instrument());
    4742              :             }
    4743            6 :             doUndoAddElement(nis);
    4744              :             // transpose root score; parts will follow
    4745            6 :             if (score->isMaster() && nis->staff()->transpose(tickStart) != oldV) {
    4746            1 :                 auto i = part->instruments().upper_bound(tickStart.ticks());
    4747            1 :                 Fraction tickEnd = i == part->instruments().end() ? Fraction(-1, 1) : Fraction::fromTicks(i->first);
    4748            1 :                 Transpose::transpositionChanged(tx, this, part, oldV, tickStart, tickEnd);
    4749              :             }
    4750           20 :         } else if (element->isBreath()) {
    4751           20 :             Breath* breath   = toBreath(element);
    4752           20 :             Fraction tick    = breath->segment()->tick();
    4753           20 :             Measure* m       = score->tick2measure(tick);
    4754              :             // breath appears before barline
    4755           20 :             if (m->tick() == tick) {
    4756            6 :                 m = m->prevMeasure();
    4757              :             }
    4758           20 :             Segment* seg     = m->undoGetSegment(SegmentType::Breath, tick);
    4759           20 :             Breath* nbreath  = toBreath(ne);
    4760           20 :             nbreath->setScore(score);
    4761           20 :             nbreath->setTrack(linkedTrack);
    4762           20 :             nbreath->setOwnershipParent(seg);
    4763           20 :             doUndoAddElement(nbreath);
    4764              :         } else {
    4765            0 :             LOGW("undoAddElement: unhandled: <%s>", element->typeName());
    4766              :         }
    4767          631 :         ne->styleChanged();
    4768              : 
    4769          631 :         if (elementToRelink) {
    4770            2 :             LinkedObjects* links = ne->links();
    4771            2 :             if (!links) {
    4772            0 :                 ne->linkTo(elementToRelink);
    4773              :             } else {
    4774            2 :                 elementToRelink->setLinks(links);
    4775            2 :                 links->push_back(elementToRelink);
    4776              :             }
    4777              :         }
    4778              :     }
    4779          611 : }
    4780              : 
    4781           76 : FBox* Score::findFretBox() const
    4782              : {
    4783          309 :     for (MeasureBase* measure = first(); measure; measure = measure->next()) {
    4784          235 :         if (measure->isFBox()) {
    4785            2 :             return toFBox(measure);
    4786              :         }
    4787              :     }
    4788              : 
    4789           74 :     return nullptr;
    4790              : }
    4791              : 
    4792           76 : void Score::rebuildFretBox()
    4793              : {
    4794           76 :     FBox* fretBox = findFretBox();
    4795           76 :     if (!fretBox) {
    4796           74 :         return;
    4797              :     }
    4798              : 
    4799            2 :     fretBox->setNeedsRebuild(true);
    4800            2 :     fretBox->triggerLayout();
    4801              : }
    4802              : 
    4803              : //---------------------------------------------------------
    4804              : //   undoAddCR
    4805              : //---------------------------------------------------------
    4806              : 
    4807         6098 : void Score::undoAddCR(ChordRest* cr, Measure* measure, const Fraction& tick)
    4808              : {
    4809         6098 :     assert(!cr->isChord() || !(toChord(cr)->notes()).empty());
    4810         6098 :     if (!cr->lyrics().empty()) {
    4811              :         // Add chordrest and lyrics separately for correct
    4812              :         // handling of adding lyrics to linked staves.
    4813            1 :         std::vector<Lyrics*> lyrics;
    4814            1 :         std::swap(lyrics, cr->lyrics());
    4815            1 :         undoAddCR(cr, measure, tick);
    4816            2 :         for (Lyrics* l : lyrics) {
    4817            1 :             undoAddElement(l);
    4818              :         }
    4819            1 :         return;
    4820            1 :     }
    4821              : 
    4822         6097 :     Staff* ostaff = cr->staff();
    4823         6097 :     track_idx_t strack = cr->track();
    4824              : 
    4825         6097 :     SegmentType segmentType = SegmentType::ChordRest;
    4826              : 
    4827        12315 :     for (const Staff* staff : ostaff->staffList()) {
    4828         6218 :         track_idx_t linkedTrack = ostaff->getLinkedTrackInStaff(staff, strack);
    4829              : 
    4830         6218 :         if (linkedTrack == muse::nidx) {
    4831            2 :             continue;
    4832              :         }
    4833              : 
    4834         6216 :         const TrackRange trackRange = staff->part()->trackRange();
    4835         6216 :         if (linkedTrack < trackRange.startTrack || linkedTrack >= trackRange.endTrack) {
    4836            0 :             continue;
    4837              :         }
    4838              : 
    4839         6216 :         Score* score = staff->score();
    4840         6216 :         Measure* m   = (score == this) ? measure : score->tick2measure(tick);
    4841         6216 :         if (!m) {
    4842            0 :             LOGD("measure not found");
    4843            0 :             break;
    4844              :         }
    4845         6216 :         Segment* seg = m->undoGetSegment(segmentType, tick);
    4846              : 
    4847         6216 :         assert(seg->segmentType() == segmentType);
    4848              : 
    4849         6216 :         ChordRest* newcr = (staff == ostaff) ? cr : toChordRest(cr->linkedClone());
    4850         6216 :         newcr->setScore(score);
    4851              : 
    4852         6216 :         newcr->setTrack(linkedTrack);
    4853         6216 :         newcr->setOwnershipParent(seg);
    4854              : 
    4855              : #ifndef QT_NO_DEBUG
    4856         6216 :         if (newcr->isChord()) {
    4857         2002 :             Chord* chord = toChord(newcr);
    4858              :             // setTpcFromPitch needs to know the note tick position
    4859         6176 :             for (Note* note : chord->notes()) {
    4860              :                 // if (note->tpc() == Tpc::TPC_INVALID)
    4861              :                 //      note->setTpcFromPitch();
    4862         4174 :                 assert(note->tpc() != Tpc::TPC_INVALID);
    4863              :             }
    4864              :         }
    4865              : #endif
    4866              :         // Climb up the (possibly nested) tuplets from this chordRest
    4867              :         // Make sure all tuplets are cloned and correctly nested
    4868         6216 :         DurationElement* elementBelow = cr;
    4869         6216 :         Tuplet* tupletAbove = elementBelow->tuplet();
    4870         6225 :         while (tupletAbove) {
    4871          524 :             DurationElement* linkedElementBelow = (DurationElement*)elementBelow->findLinkedInStaff(staff);
    4872          524 :             if (!linkedElementBelow) {     // shouldn't happen
    4873          515 :                 break;
    4874              :             }
    4875            9 :             Tuplet* linkedTuplet = (Tuplet*)tupletAbove->findLinkedInStaff(staff);
    4876            9 :             if (!linkedTuplet) {
    4877            2 :                 linkedTuplet = toTuplet(tupletAbove->linkedClone());
    4878            2 :                 linkedTuplet->setScore(score);
    4879            2 :                 linkedTuplet->setTrack(newcr->track());
    4880            2 :                 linkedTuplet->setOwnershipParent(m);
    4881              :             }
    4882            9 :             linkedElementBelow->setTuplet(linkedTuplet);
    4883              : 
    4884            9 :             elementBelow = tupletAbove;
    4885            9 :             tupletAbove = tupletAbove->tuplet();
    4886              :         }
    4887              : 
    4888         6216 :         if (newcr->isRest() && (toRest(newcr)->isGap()) && !(toRest(newcr)->track() % VOICES)) {
    4889          575 :             toRest(newcr)->setGap(false);
    4890              :         }
    4891              : 
    4892         6216 :         doUndoAddElement(newcr);
    4893         6097 :     }
    4894              : }
    4895              : 
    4896              : //---------------------------------------------------------
    4897              : //   undoRemoveElement
    4898              : //---------------------------------------------------------
    4899              : 
    4900         7114 : void Score::undoRemoveElement(EngravingItem* element, bool removeLinked)
    4901              : {
    4902         7114 :     if (!element) {
    4903          221 :         return;
    4904              :     }
    4905         6893 :     std::vector<Segment*> segments;
    4906        13857 :     for (EngravingObject* ee : element->linkList()) {
    4907         6964 :         EngravingItem* e = static_cast<EngravingItem*>(ee);
    4908         6964 :         if (e == element || removeLinked) {
    4909         6958 :             doUndoRemoveElement(e);
    4910              : 
    4911         6958 :             if (e->ownershipParent() && (e->ownershipParent()->isSegment())) {
    4912         4152 :                 Segment* s = toSegment(e->ownershipParent());
    4913         4152 :                 if (!muse::contains(segments, s)) {
    4914         4149 :                     segments.push_back(s);
    4915              :                 }
    4916              :             }
    4917         6958 :             if (e->ownershipParent() && e->ownershipParent()->isSystem()) {
    4918            0 :                 e->setOwnershipParent(0);   // systems will be regenerated upon redo, so detach
    4919              :             }
    4920              :         }
    4921         6893 :     }
    4922              : 
    4923         6893 :     if (element->isMeasureRepeat()) {
    4924            0 :         const MeasureRepeat* repeat = toMeasureRepeat(element);
    4925            0 :         Measure* measure = repeat->firstMeasureOfGroup();
    4926            0 :         size_t staffIdx = repeat->staffIdx();
    4927              : 
    4928            0 :         if (measure) {
    4929            0 :             for (int i = 0; i < repeat->numMeasures(); ++i) {
    4930            0 :                 undoChangeMeasureRepeatCount(measure, 0, staffIdx);
    4931            0 :                 measure = measure->nextMeasure();
    4932              :             }
    4933              :         }
    4934              :     }
    4935              : 
    4936        11042 :     for (Segment* s : segments) {
    4937         4149 :         if (s->empty()) {
    4938         1765 :             if (s->header() || s->trailer()) {        // probably more segment types (system header)
    4939            8 :                 s->setEnabled(false);
    4940              :             } else {
    4941         1757 :                 doUndoRemoveElement(s);
    4942              :             }
    4943              :         }
    4944              :     }
    4945         6893 : }
    4946              : 
    4947            0 : void Score::undoRemoveHopoText(HammerOnPullOffText* hopoText)
    4948              : {
    4949            0 :     Chord* startChord = hopoText->startChord();
    4950            0 :     Chord* endChord = hopoText->endChord();
    4951            0 :     IF_ASSERT_FAILED(startChord && endChord) {
    4952            0 :         return;
    4953              :     }
    4954              : 
    4955            0 :     HammerOnPullOffSegment* hopoSegment = hopoText->hopoSegment();
    4956            0 :     HammerOnPullOff* hopo = hopoSegment ? hopoSegment->hammerOnPullOff() : nullptr;
    4957            0 :     IF_ASSERT_FAILED(hopo) {
    4958            0 :         return;
    4959              :     }
    4960              : 
    4961            0 :     Chord* hopoStartChord = toChord(hopo->startElement());
    4962            0 :     Chord* hopoEndChord = toChord(hopo->endElement());
    4963            0 :     IF_ASSERT_FAILED(hopoStartChord && hopoEndChord) {
    4964            0 :         return;
    4965              :     }
    4966              : 
    4967            0 :     if (startChord == hopoStartChord && endChord == hopoEndChord) {
    4968            0 :         undoRemoveElement(hopo);
    4969            0 :         return;
    4970              :     }
    4971              : 
    4972            0 :     Fraction hopoStartTick = hopo->tick();
    4973            0 :     Fraction hopoEndTick = hopo->tick2();
    4974            0 :     Fraction hopoTextStartTick = startChord->tick();
    4975            0 :     Fraction hopoTextEndTick = endChord->tick();
    4976              : 
    4977            0 :     bool shortenFromStart = (hopoTextStartTick - hopoStartTick) < (hopoEndTick - hopoTextEndTick);
    4978            0 :     if (shortenFromStart) {
    4979            0 :         Fraction newStartTick = hopoTextEndTick;
    4980            0 :         Fraction newTicks = hopoEndTick - newStartTick;
    4981            0 :         hopo->undoChangeProperty(Pid::SPANNER_TICK, newStartTick);
    4982            0 :         hopo->undoChangeProperty(Pid::SPANNER_TICKS, newTicks);
    4983            0 :         hopo->undoChangeStartEndElements(endChord, hopoEndChord);
    4984            0 :         if (startChord != hopoStartChord) {
    4985            0 :             HammerOnPullOff* newHopo = Factory::createHammerOnPullOff(score()->dummy());
    4986            0 :             newHopo->setTrack(hopo->track());
    4987            0 :             newHopo->setTick(hopoStartTick);
    4988            0 :             newHopo->setTick2(hopoTextStartTick);
    4989            0 :             newHopo->setStartElement(hopoStartChord);
    4990            0 :             newHopo->setEndElement(startChord);
    4991            0 :             score()->undoAddElement(newHopo);
    4992              :         }
    4993              :     } else {
    4994            0 :         Fraction newEndTick = hopoTextStartTick;
    4995            0 :         Fraction newTicks = newEndTick - hopoStartTick;
    4996            0 :         hopo->undoChangeProperty(Pid::SPANNER_TICKS, newTicks);
    4997            0 :         hopo->undoChangeStartEndElements(hopoStartChord, startChord);
    4998            0 :         if (endChord != hopoEndChord) {
    4999            0 :             HammerOnPullOff* newHopo = new HammerOnPullOff(score()->dummy());
    5000            0 :             newHopo->setTrack(hopo->track());
    5001            0 :             newHopo->setTick(hopoTextEndTick);
    5002            0 :             newHopo->setTick2(hopoEndTick);
    5003            0 :             newHopo->setStartElement(endChord);
    5004            0 :             newHopo->setEndElement(hopoEndChord);
    5005            0 :             score()->undoAddElement(newHopo);
    5006              :         }
    5007              :     }
    5008              : }
    5009              : 
    5010              : //---------------------------------------------------------
    5011              : //   undoChangeSpannerElements
    5012              : //---------------------------------------------------------
    5013              : 
    5014           70 : void Score::undoChangeSpannerElements(Spanner* spanner, EngravingItem* startElement, EngravingItem* endElement)
    5015              : {
    5016           70 :     EngravingItem* oldStartElement = spanner->startElement();
    5017           70 :     EngravingItem* oldEndElement = spanner->endElement();
    5018           70 :     track_idx_t startDeltaTrack = startElement && oldStartElement ? startElement->track() - oldStartElement->track() : 0;
    5019           70 :     track_idx_t endDeltaTrack = endElement && oldEndElement ? endElement->track() - oldEndElement->track() : 0;
    5020              :     // scan all spanners linked to this one
    5021          164 :     for (EngravingObject* el : spanner->linkList()) {
    5022           94 :         Spanner* sp = toSpanner(el);
    5023           94 :         EngravingItem* newStartElement = nullptr;
    5024           94 :         EngravingItem* newEndElement = nullptr;
    5025              :         // if not the current spanner, but one linked to it, determine its new start and end elements
    5026              :         // as modifications 'parallel' to the modifications of the current spanner's start and end elements
    5027           94 :         if (sp != spanner) {
    5028           24 :             if (startElement) {
    5029              :                 // determine the track where to expect the 'parallel' start element
    5030           12 :                 track_idx_t newTrack = sp->startElement() ? sp->startElement()->track() + startDeltaTrack : sp->track();
    5031              :                 // look in elements linked to new start element for an element with
    5032              :                 // same score as linked spanner and appropriate track
    5033           24 :                 for (EngravingObject* ee : startElement->linkList()) {
    5034           24 :                     EngravingItem* e = toEngravingItem(ee);
    5035           24 :                     if (e->score() == sp->score() && e->track() == newTrack) {
    5036           12 :                         newStartElement = e;
    5037           12 :                         break;
    5038              :                     }
    5039           12 :                 }
    5040              :             }
    5041              :             // similarly to determine the 'parallel' end element
    5042           24 :             if (endElement) {
    5043           12 :                 track_idx_t newTrack = sp->endElement() ? sp->endElement()->track() + endDeltaTrack : sp->track2();
    5044           24 :                 for (EngravingObject* ee : endElement->linkList()) {
    5045           24 :                     EngravingItem* e = toEngravingItem(ee);
    5046           24 :                     if (e->score() == sp->score() && e->track() == newTrack) {
    5047           12 :                         newEndElement = e;
    5048           12 :                         break;
    5049              :                     }
    5050           12 :                 }
    5051              :             }
    5052              :         }
    5053              :         // if current spanner, just use stored start and end elements
    5054              :         else {
    5055           70 :             newStartElement = startElement;
    5056           70 :             newEndElement = endElement;
    5057              :         }
    5058           94 :         sp->score()->undo(new ChangeSpannerElements(sp, newStartElement, newEndElement));
    5059              : 
    5060           94 :         if (sp->isTie()) {
    5061            0 :             toTie(sp)->updatePossibleJumpPoints();
    5062              :         }
    5063           70 :     }
    5064           70 : }
    5065              : 
    5066              : //---------------------------------------------------------
    5067              : //   undoInsertTime
    5068              : //   acts on the linked scores as well
    5069              : //---------------------------------------------------------
    5070              : 
    5071          596 : void Score::undoInsertTime(const Fraction& tick, const Fraction& len)
    5072              : {
    5073          596 :     if (len.isZero()) {
    5074            9 :         return;
    5075              :     }
    5076              : 
    5077          587 :     std::vector<Spanner*> spannersToAdjust;
    5078          702 :     for (const auto& i : m_spanner.map()) {
    5079          115 :         Spanner* s = i.second;
    5080          115 :         if (s->tick2() < tick) {
    5081           45 :             continue;
    5082              :         }
    5083           70 :         bool append = false;
    5084           70 :         if (len > Fraction(0, 1)) {
    5085           34 :             if (tick > s->tick() && tick < s->tick2()) {
    5086            5 :                 append = true;
    5087           29 :             } else if (tick <= s->tick()) {
    5088           20 :                 append = true;
    5089              :             }
    5090              :         } else {
    5091           36 :             Fraction tick2 = tick - len;
    5092           36 :             if (s->tick() >= tick2) {
    5093           15 :                 append = true;
    5094           21 :             } else if (s->tick() >= tick && s->tick2() <= tick2) {
    5095            6 :                 append = true;
    5096           15 :             } else if ((s->tick() <= tick) && (s->tick2() >= tick2)) {
    5097            8 :                 Fraction t2 = s->tick2() + len;
    5098            8 :                 if (t2 > s->tick()) {
    5099            8 :                     append = true;
    5100              :                 }
    5101            7 :             } else if (s->tick() > tick && s->tick2() > tick2) {
    5102            2 :                 append = true;
    5103            5 :             } else if (s->tick() < tick && s->tick2() < tick2) {
    5104            5 :                 append = true;
    5105              :             }
    5106              :         }
    5107          100 :         for (const Spanner* ss : spannersToAdjust) {
    5108           30 :             if (muse::contains(ss->linkList(), static_cast<EngravingObject*>(s))) {
    5109            0 :                 append = false;
    5110            0 :                 break;
    5111              :             }
    5112              :         }
    5113           70 :         if (append) {
    5114           61 :             spannersToAdjust.push_back(s);
    5115              :         }
    5116              :     }
    5117          648 :     for (Spanner* s : spannersToAdjust) {
    5118           61 :         if (len > Fraction(0, 1)) {
    5119           25 :             if (tick == s->tick() && s->isVolta()) {
    5120            0 :                 s->undoChangeProperty(Pid::SPANNER_TICKS, s->ticks() + len);
    5121           25 :             } else if (tick > s->tick() && tick < s->tick2()) {
    5122              :                 //
    5123              :                 //  case a:
    5124              :                 //  +----spanner--------+
    5125              :                 //    +---add---
    5126              :                 //
    5127            5 :                 s->undoChangeProperty(Pid::SPANNER_TICKS, s->ticks() + len);
    5128           20 :             } else if (tick <= s->tick()) {
    5129              :                 //
    5130              :                 //  case b:
    5131              :                 //       +----spanner--------
    5132              :                 //  +---add---
    5133              :                 // and
    5134              :                 //            +----spanner--------
    5135              :                 //  +---add---+
    5136           20 :                 EngravingItem* startElement = s->startElement();
    5137           20 :                 EngravingItem* endElement = s->endElement();
    5138           20 :                 undoChangeSpannerElements(s, nullptr, nullptr);
    5139           20 :                 s->undoChangeProperty(Pid::SPANNER_TICK, s->tick() + len);
    5140           20 :                 undoChangeSpannerElements(s, startElement, endElement);
    5141              :             }
    5142              :         } else {
    5143           36 :             Fraction tick2 = tick - len;
    5144           36 :             if (s->tick() >= tick2) {
    5145              :                 //
    5146              :                 //  case A:
    5147              :                 //  +----remove---+ +---spanner---+
    5148              :                 //
    5149           15 :                 Fraction t = s->tick() + len;
    5150           15 :                 if (t < Fraction(0, 1)) {
    5151            0 :                     t = Fraction(0, 1);
    5152              :                 }
    5153           15 :                 EngravingItem* startElement = s->startElement();
    5154           15 :                 EngravingItem* endElement = s->endElement();
    5155           15 :                 undoChangeSpannerElements(s, nullptr, nullptr);
    5156           15 :                 s->undoChangeProperty(Pid::SPANNER_TICK, t);
    5157           15 :                 undoChangeSpannerElements(s, startElement, endElement);
    5158           21 :             } else if (s->tick() >= tick && s->tick2() <= tick2) {
    5159              :                 //
    5160              :                 //  case B:
    5161              :                 //    +---spanner---+
    5162              :                 //  +----remove--------+
    5163              :                 //
    5164            6 :                 undoRemoveElement(s);
    5165           15 :             } else if ((s->tick() <= tick) && (s->tick2() >= tick2)) {
    5166              :                 //
    5167              :                 //  case C:
    5168              :                 //  +----spanner--------+
    5169              :                 //    +---remove---+
    5170              :                 //
    5171            8 :                 Fraction t2 = s->tick2() + len;
    5172            8 :                 if (t2 > s->tick()) {
    5173            8 :                     s->undoChangeProperty(Pid::SPANNER_TICKS, s->ticks() + len);
    5174              :                 }
    5175            7 :             } else if (s->tick() > tick && s->tick2() > tick2) {
    5176              :                 //
    5177              :                 //  case D:
    5178              :                 //       +----spanner--------+
    5179              :                 //  +---remove---+
    5180              :                 //
    5181            2 :                 Fraction d1 = s->tick() - tick;
    5182            2 :                 Fraction d2 = tick2 - s->tick();
    5183            2 :                 Fraction le = s->ticks() - d2;
    5184            2 :                 if (le.isZero()) {
    5185            0 :                     undoRemoveElement(s);
    5186              :                 } else {
    5187            2 :                     s->undoChangeProperty(Pid::SPANNER_TICK, s->tick() - d1);
    5188            2 :                     s->undoChangeProperty(Pid::SPANNER_TICKS, le);
    5189              :                 }
    5190            5 :             } else if (s->tick() < tick && s->tick2() < tick2) {
    5191              :                 //
    5192              :                 //  case E:
    5193              :                 //       +----spanner--------+
    5194              :                 //                     +---remove---+
    5195              :                 //
    5196            5 :                 Fraction d  = s->tick2() - tick;
    5197            5 :                 Fraction le = s->ticks() - d;
    5198            5 :                 if (le.isZero()) {
    5199            0 :                     undoRemoveElement(s);
    5200              :                 } else {
    5201            5 :                     s->undoChangeProperty(Pid::SPANNER_TICKS, le);
    5202              :                 }
    5203              :             }
    5204              :         }
    5205              :     }
    5206              : 
    5207          587 :     undo(new InsertTimeUnmanagedSpanner(this, tick, len));
    5208          587 : }
    5209              : 
    5210              : //---------------------------------------------------------
    5211              : //   undoRemoveMeasures
    5212              : //---------------------------------------------------------
    5213              : 
    5214           68 : void Score::undoRemoveMeasures(Measure* m1, Measure* m2, bool preserveTies, bool moveStaffTypeChanges)
    5215              : {
    5216           68 :     assert(m1 && m2);
    5217              : 
    5218           68 :     Transaction& tx = transactionManager()->currentOrDummyTransaction();
    5219              : 
    5220           68 :     const Fraction startTick = m1->tick();
    5221           68 :     const Fraction endTick = m2->endTick();
    5222           68 :     std::set<Spanner*> spannersToRemove;
    5223              : 
    5224              :     //
    5225              :     //  handle ties which start before m1 and end in (m1-m2)
    5226              :     //
    5227          740 :     for (Segment* s = m1->first(); s != m2->last(); s = s->next1()) {
    5228          672 :         IF_ASSERT_FAILED(s) {
    5229              :             // This score is corrupted; handle it without crashing,
    5230              :             // to help the user to fix corruptions by deleting the affected measures
    5231            0 :             LOGE() << "Missing segments detected while deleting measures " << m1->measureNumber() << " to " << m2->measureNumber()
    5232            0 :                    << ". This score (" << name() << ") is corrupted. Continuing without deleting measure contents.";
    5233            0 :             break;
    5234              :         }
    5235              : 
    5236          672 :         if (!s->isChordRestType()) {
    5237          259 :             continue;
    5238              :         }
    5239              : 
    5240              :         // Make sure annotations are removed once, even if this segment contains linked copies of the same annotation
    5241              :         // (the linked copy would be removed by undoRemoveElement)
    5242          438 :         while (!s->annotations().empty()) {
    5243           25 :             EngravingItem* annotation = s->annotations().front();
    5244           25 :             IF_ASSERT_FAILED(annotation) {
    5245            0 :                 continue;
    5246              :             }
    5247           25 :             undoRemoveElement(annotation);
    5248              :         }
    5249              : 
    5250         2957 :         for (track_idx_t track = 0; track < ntracks(); ++track) {
    5251         2544 :             EngravingItem* e = s->element(track);
    5252         2544 :             if (!e || !e->isChord()) {
    5253         2137 :                 continue;
    5254              :             }
    5255          407 :             Chord* c = toChord(e);
    5256          818 :             for (Note* n : c->notes()) {
    5257              :                 // Remove ties crossing measure range boundaries
    5258          411 :                 Tie* t = n->tieBackNonPartial();
    5259          411 :                 if (t && t->startNote() && (t->startNote()->chord()->tick() < startTick)) {
    5260            0 :                     if (preserveTies) {
    5261            0 :                         t->setEndNote(0);
    5262              :                     } else {
    5263            0 :                         undoRemoveElement(t);
    5264              :                     }
    5265              :                 }
    5266          411 :                 t = n->tieForNonPartial();
    5267          411 :                 if (t && t->endNote() && (t->endNote()->chord()->tick() >= endTick)) {
    5268            6 :                     undoRemoveElement(t);
    5269              :                 }
    5270              : 
    5271              :                 // Do the same for other note-anchored spanners (e.g. glissandi).
    5272              :                 // Delay actual removing to avoid modifying lists inside loops over them.
    5273          411 :                 for (Spanner* sb : n->spannerBack()) {
    5274            0 :                     if (sb->tick() < startTick) {
    5275            0 :                         spannersToRemove.insert(sb);
    5276              :                     }
    5277              :                 }
    5278          411 :                 for (Spanner* sf : n->spannerFor()) {
    5279            0 :                     if (sf->tick2() >= endTick) {
    5280            0 :                         spannersToRemove.insert(sf);
    5281              :                     }
    5282              :                 }
    5283              :             }
    5284              :         }
    5285              :     }
    5286              : 
    5287           68 :     for (Spanner* s : spannersToRemove) {
    5288            0 :         undoRemoveElement(s);
    5289              :     }
    5290              : 
    5291              :     // delete staffTypeChanges in removed measures
    5292           68 :     if (moveStaffTypeChanges) {
    5293          169 :         for (Measure* m = m1; m && m != m2->nextMeasure(); m = m->nextMeasure()) {
    5294          140 :             for (size_t i = m->el().size(); i > 0; --i) {
    5295           14 :                 EngravingItem* el = m->el().at(i - 1);
    5296           14 :                 if (el && el->isStaffTypeChange()) {
    5297            0 :                     deleteItem(el);
    5298              :                 }
    5299              :             }
    5300              :         }
    5301              :     }
    5302              : 
    5303           68 :     EditSystemLocks::removeSystemLocksOnRemoveMeasures(tx, this, m1, m2);
    5304           68 :     EditPageLocks::removePageLocksOnRemoveMeasures(tx, this, m1, m2);
    5305           68 :     EditStaveSharing::removeStaveSharingStatesOnRemoveTime(tx, this, startTick, endTick);
    5306              : 
    5307           68 :     undo(new RemoveMeasures(m1, m2, moveStaffTypeChanges));
    5308           68 : }
    5309              : 
    5310              : //---------------------------------------------------------
    5311              : //   undoChangeMeasureRepeatCount
    5312              : //---------------------------------------------------------
    5313              : 
    5314           35 : void Score::undoChangeMeasureRepeatCount(Measure* m, int newCount, staff_idx_t staffIdx)
    5315              : {
    5316          105 :     for (Staff* st : staff(staffIdx)->staffList()) {
    5317           70 :         Score* linkedScore = st->score();
    5318           70 :         staff_idx_t linkedStaffIdx = st->idx();
    5319           70 :         Measure* linkedMeasure = linkedScore->tick2measure(m->tick());
    5320              : 
    5321           70 :         int currCount = linkedMeasure->measureRepeatCount(linkedStaffIdx);
    5322           70 :         if (currCount != newCount) {
    5323           70 :             linkedScore->undo(new ChangeMeasureRepeatCount(linkedMeasure, newCount, linkedStaffIdx));
    5324              :         }
    5325           35 :     }
    5326           35 : }
    5327              : 
    5328         1121 : void Score::doUndoRemoveStaleTieJumpPoints(Tie* tie, bool undo)
    5329              : {
    5330            3 :     auto removeTie = [&](Tie* tie) {
    5331            3 :         if (undo) {
    5332            3 :             const size_t undoIdx = undoStack()->currentIndex();
    5333            3 :             startCmd(TranslatableString("engraving", "Remove stale partial tie"));
    5334            3 :             undoRemoveElement(tie);
    5335            3 :             endCmd();
    5336            3 :             if (undoIdx != undoStack()->currentIndex() && undoStack()->currentIndex() >= 2) {
    5337              :                 // These changes should be merged with the change in repeat structure which caused the ties to become invalid
    5338              :                 // currentIndex returns the next empty index for an undo command
    5339            2 :                 const size_t penultimateCmdIdx = undoStack()->currentIndex() - 2;
    5340            2 :                 undoStack()->mergeTransactions(penultimateCmdIdx);
    5341              :             }
    5342              :         } else {
    5343            0 :             removeElement(tie);
    5344              :         }
    5345            3 :     };
    5346              : 
    5347         1121 :     std::vector<Tie*> oldTies;
    5348         1121 :     if (!tie->tieJumpPoints()) {
    5349            0 :         return;
    5350              :     }
    5351         1165 :     for (TieJumpPoint* jumpPoint : *tie->tieJumpPoints()) {
    5352           44 :         if (jumpPoint->followingNote()) {
    5353            9 :             continue;
    5354              :         }
    5355           35 :         oldTies.push_back(jumpPoint->endTie());
    5356              :     }
    5357              : 
    5358              :     // Update jump points for linked ties
    5359         2276 :     for (EngravingObject* linkedTie : tie->linkList()) {
    5360         1155 :         if (!linkedTie || !linkedTie->isTie()) {
    5361            0 :             continue;
    5362              :         }
    5363         1155 :         toTie(linkedTie)->updatePossibleJumpPoints();
    5364         1121 :     }
    5365              : 
    5366         1156 :     for (Tie* oldTie : oldTies) {
    5367           47 :         auto findEndTie = [&oldTie](const TieJumpPoint* jumpPoint) {
    5368           47 :             return jumpPoint->endTie() == oldTie;
    5369           35 :         };
    5370           35 :         if (!oldTie) {
    5371           35 :             continue;
    5372              :         }
    5373              : 
    5374           34 :         if (std::find_if((*tie->tieJumpPoints()).begin(), (*tie->tieJumpPoints()).end(),
    5375           68 :                          findEndTie) != (*tie->tieJumpPoints()).end()) {
    5376           34 :             continue;
    5377              :         }
    5378            0 :         removeTie(oldTie);
    5379              :     }
    5380              : 
    5381         1121 :     if (tie->isPartialTie() && tie->allJumpPointsInactive() && tie->startNote() && tie->startNote()->tieFor() == tie) {
    5382            3 :         removeTie(tie);
    5383              :     }
    5384         1121 : }
    5385              : 
    5386          341 : void Score::doUndoResetPartialSlur(Slur* slur, bool undo)
    5387              : {
    5388          341 :     const size_t undoIdx = undoStack()->currentIndex();
    5389              : 
    5390          341 :     const ChordRest* startCR = slur ? slur->startCR() : nullptr;
    5391              :     // Slurs can only have the same start & end element when they are partial.
    5392              :     // If they are no longer partial, we should remove them
    5393          341 :     const bool shouldRemove = slur->startElement() == slur->endElement();
    5394          341 :     IF_ASSERT_FAILED(startCR) {
    5395            0 :         LOGE() << "Slur is corrupted";
    5396          341 :     } else if (!startCR->hasPrecedingJumpItem() && slur->isIncoming()) {
    5397            3 :         if (shouldRemove) {
    5398            3 :             if (undo) {
    5399            0 :                 startCmd(TranslatableString("engraving", "Remove invalid incoming partial slur"));
    5400            0 :                 undoRemoveElement(slur);
    5401            0 :                 endCmd();
    5402              :             } else {
    5403            3 :                 removeElement(slur);
    5404              :             }
    5405              :         } else {
    5406            0 :             if (undo) {
    5407            0 :                 startCmd(TranslatableString("engraving", "Reset incoming partial slur"));
    5408            0 :                 slur->undoSetIncoming(false);
    5409            0 :                 endCmd();
    5410              :             } else {
    5411            0 :                 slur->setIncoming(false);
    5412              :             }
    5413              :         }
    5414              :     }
    5415              : 
    5416          341 :     const ChordRest* endCR = slur ? slur->endCR() : nullptr;
    5417          341 :     IF_ASSERT_FAILED(endCR) {
    5418            0 :         LOGE() << "Slur is corrupted";
    5419          341 :     } else if (!endCR->hasFollowingJumpItem() && slur->isOutgoing()) {
    5420            1 :         if (shouldRemove) {
    5421            0 :             if (undo) {
    5422            0 :                 startCmd(TranslatableString("engraving", "Remove invalid outgoing partial slur"));
    5423            0 :                 undoRemoveElement(slur);
    5424            0 :                 endCmd();
    5425              :             } else {
    5426            0 :                 removeElement(slur);
    5427              :             }
    5428              :         } else {
    5429            1 :             if (undo) {
    5430            0 :                 startCmd(TranslatableString("engraving", "Reset outgoing partial slur"));
    5431            0 :                 slur->undoSetOutgoing(false);
    5432            0 :                 endCmd();
    5433              :             } else {
    5434            1 :                 slur->setOutgoing(false);
    5435              :             }
    5436              :         }
    5437              :     }
    5438              : 
    5439          341 :     if (!undo) {
    5440          341 :         return;
    5441              :     }
    5442              : 
    5443            0 :     if (undoIdx != undoStack()->currentIndex() && undoStack()->currentIndex() >= 2) {
    5444              :         // These changes should be merged with the change in repeat structure which caused the ties to become invalid
    5445              :         // currentIdx returns the next empty index for an undo command
    5446            0 :         const size_t penultimateCmdIdx = undoStack()->currentIndex() - 2;
    5447            0 :         undoStack()->mergeTransactions(penultimateCmdIdx);
    5448              :     }
    5449              : }
    5450              : 
    5451         1284 : void Score::undoRemoveStaleTieJumpPoints(bool undo)
    5452              : {
    5453         1284 :     size_t tracks = nstaves() * VOICES;
    5454         1284 :     Measure* m = firstMeasure();
    5455         1284 :     if (!m) {
    5456            1 :         return;
    5457              :     }
    5458              : 
    5459              :     // Copy, invalid slurs could be removed
    5460         1283 :     auto spannerMap = spanner();
    5461         2211 :     for (auto& interval : spannerMap) {
    5462          928 :         Spanner* sp = interval.second;
    5463          928 :         if (!sp || !sp->isSlur()) {
    5464          587 :             continue;
    5465              :         }
    5466          341 :         doUndoResetPartialSlur(toSlur(sp), undo);
    5467              :     }
    5468              : 
    5469         1283 :     std::set<PartialTie*> incomingPartialTies;
    5470         1283 :     SegmentType st = SegmentType::ChordRest;
    5471        28828 :     for (Segment* s = m->first(st); s; s = s->next1(st)) {
    5472       179869 :         for (track_idx_t i = 0; i < tracks; ++i) {
    5473       152324 :             EngravingItem* e = s->element(i);
    5474       152324 :             if (e == 0 || !e->isChordRest()) {
    5475       113918 :                 continue;
    5476              :             }
    5477              : 
    5478        38406 :             if (!toChordRest(e)->hasFollowingJumpItem()) {
    5479              :                 // Remove invalid lyrics dashes
    5480        39084 :                 for (Lyrics* lyrics : toChordRest(e)->lyrics()) {
    5481         1221 :                     LyricsLine* separator = lyrics->separator();
    5482         2442 :                     if ((lyrics->syllabic() == LyricsSyllabic::BEGIN || lyrics->syllabic() == LyricsSyllabic::MIDDLE) && separator
    5483         2442 :                         && !separator->nextLyrics() && !separator->isEndMelisma()) {
    5484            0 :                         lyrics->setNeedRemoveInvalidSegments();
    5485              :                     }
    5486              :                 }
    5487              :             }
    5488              : 
    5489        38406 :             if (!e->isChord()) {
    5490        17653 :                 continue;
    5491              :             }
    5492              : 
    5493        20753 :             Chord* c = toChord(e);
    5494        45289 :             for (Note* n : c->notes()) {
    5495        24536 :                 if (n->incomingPartialTie()) {
    5496           36 :                     incomingPartialTies.emplace(n->incomingPartialTie());
    5497              :                 }
    5498        24536 :                 if (!n->tieFor()) {
    5499        23415 :                     continue;
    5500              :                 }
    5501              : 
    5502         1121 :                 doUndoRemoveStaleTieJumpPoints(n->tieFor());
    5503              :             }
    5504              :         }
    5505              :     }
    5506              : 
    5507         1319 :     for (PartialTie* incomingPT : incomingPartialTies) {
    5508           36 :         if (incomingPT->jumpPoint() || incomingPT->note()->tieBack() != incomingPT) {
    5509           32 :             continue;
    5510              :         }
    5511            4 :         const size_t undoIdx = undoStack()->currentIndex();
    5512            4 :         if (undo) {
    5513            0 :             startCmd(TranslatableString("engraving", "Remove stale partial tie"));
    5514            0 :             undoRemoveElement(incomingPT);
    5515            0 :             endCmd();
    5516            0 :             if (undoIdx != undoStack()->currentIndex() && undoStack()->currentIndex() >= 2) {
    5517            0 :                 undoStack()->mergeTransactions(undoStack()->currentIndex() - 2);
    5518              :             }
    5519              :         } else {
    5520            4 :             removeElement(incomingPT);
    5521              :         }
    5522              :     }
    5523         1283 : }
    5524              : }
        

Generated by: LCOV version 2.0-1