LCOV - code coverage report
Current view: top level - src/engraving/editing - cmd.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 65.7 % 1051 690
Test Date: 2026-11-19 04:14:36

            Line data    Source code
       1              : /*
       2              :  * SPDX-License-Identifier: GPL-3.0-only
       3              :  * MuseScore-Studio-CLA-applies
       4              :  *
       5              :  * MuseScore Studio
       6              :  * Music Composition & Notation
       7              :  *
       8              :  * Copyright (C) 2021 MuseScore Limited and others
       9              :  *
      10              :  * This program is free software: you can redistribute it and/or modify
      11              :  * it under the terms of the GNU General Public License version 3 as
      12              :  * published by the Free Software Foundation.
      13              :  *
      14              :  * This program is distributed in the hope that it will be useful,
      15              :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      16              :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      17              :  * GNU General Public License for more details.
      18              :  *
      19              :  * You should have received a copy of the GNU General Public License
      20              :  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
      21              :  */
      22              : 
      23              : /**
      24              :  \file
      25              :  Handling of several GUI commands.
      26              : */
      27              : 
      28              : #include <assert.h>
      29              : #include <set>
      30              : 
      31              : #include "translation.h"
      32              : 
      33              : #include "style/style.h"
      34              : 
      35              : #include "rw/xmlreader.h"
      36              : 
      37              : #include "../dom/accidental.h"
      38              : #include "../dom/articulation.h"
      39              : #include "../dom/barline.h"
      40              : #include "../dom/box.h"
      41              : #include "../dom/chord.h"
      42              : #include "../dom/chordrest.h"
      43              : #include "../dom/clef.h"
      44              : #include "../dom/drumset.h"
      45              : #include "../dom/durationtype.h"
      46              : #include "../dom/dynamic.h"
      47              : #include "../dom/factory.h"
      48              : #include "../dom/glissando.h"
      49              : #include "../dom/guitarbend.h"
      50              : #include "../dom/hairpin.h"
      51              : #include "../dom/harmony.h"
      52              : #include "../dom/key.h"
      53              : #include "../dom/laissezvib.h"
      54              : #include "../dom/layoutbreak.h"
      55              : #include "../dom/linkedobjects.h"
      56              : #include "../dom/lyrics.h"
      57              : #include "../dom/masterscore.h"
      58              : #include "../dom/measure.h"
      59              : #include "../dom/measurerepeat.h"
      60              : #include "../dom/mscore.h"
      61              : #include "../dom/note.h"
      62              : #include "../dom/ornament.h"
      63              : #include "../dom/page.h"
      64              : #include "../dom/part.h"
      65              : #include "../dom/pitchspelling.h"
      66              : #include "../dom/rehearsalmark.h"
      67              : #include "../dom/rest.h"
      68              : #include "../dom/score.h"
      69              : #include "../dom/segment.h"
      70              : #include "../dom/sig.h"
      71              : #include "../dom/slur.h"
      72              : #include "../dom/spacer.h"
      73              : #include "../dom/staff.h"
      74              : #include "../dom/stafftype.h"
      75              : #include "../dom/stafftypechange.h"
      76              : #include "../dom/stem.h"
      77              : #include "../dom/stringdata.h"
      78              : #include "../dom/system.h"
      79              : #include "../dom/tapping.h"
      80              : #include "../dom/tie.h"
      81              : #include "../dom/timesig.h"
      82              : #include "../dom/tremolotwochord.h"
      83              : #include "../dom/tuplet.h"
      84              : #include "../dom/utils.h"
      85              : 
      86              : #include "editchord.h"
      87              : #include "editnote.h"
      88              : #include "noteinput.h"
      89              : #include "editpagelocks.h"
      90              : #include "editproperty.h"
      91              : #include "editspanner.h"
      92              : #include "editstaff.h"
      93              : #include "editsystemlocks.h"
      94              : #include "mscoreview.h"
      95              : #include "navigation.h"
      96              : #include "transaction/transaction.h"
      97              : #include "transaction/undostack.h"
      98              : #include "transpose.h"
      99              : 
     100              : #include "log.h"
     101              : 
     102              : using namespace muse::io;
     103              : using namespace mu::engraving;
     104              : 
     105              : namespace mu::engraving {
     106              : //---------------------------------------------------------
     107              : //   reset
     108              : //---------------------------------------------------------
     109              : 
     110         3408 : void CmdState::reset()
     111              : {
     112         3408 :     layoutFlags         = LayoutFlag::NO_FLAGS;
     113         3408 :     m_updateMode         = UpdateMode::DoNothing;
     114         3408 :     m_startTick          = Fraction(-1, 1);
     115         3408 :     m_endTick            = Fraction(-1, 1);
     116              : 
     117         3408 :     m_startStaff = muse::nidx;
     118         3408 :     m_endStaff = muse::nidx;
     119         3408 :     m_el = nullptr;
     120         3408 :     m_oneElement = true;
     121         3408 :     m_mb = nullptr;
     122         3408 :     m_oneMeasureBase = true;
     123         3408 :     m_locked = false;
     124         3408 : }
     125              : 
     126              : //---------------------------------------------------------
     127              : //   setTick
     128              : //---------------------------------------------------------
     129              : 
     130      1055905 : void CmdState::setTick(const Fraction& t)
     131              : {
     132      1055905 :     if (m_locked) {
     133       676211 :         return;
     134              :     }
     135              : 
     136       379694 :     if (m_startTick == Fraction(-1, 1) || t < m_startTick) {
     137         3689 :         m_startTick = t;
     138              :     }
     139       379694 :     if (m_endTick == Fraction(-1, 1) || t > m_endTick) {
     140        12372 :         m_endTick = t;
     141              :     }
     142       379694 :     setUpdateMode(UpdateMode::Layout);
     143              : }
     144              : 
     145              : //---------------------------------------------------------
     146              : //   setStaff
     147              : //---------------------------------------------------------
     148              : 
     149       986931 : void CmdState::setStaff(staff_idx_t st)
     150              : {
     151       986931 :     if (m_locked || st == muse::nidx) {
     152       896345 :         return;
     153              :     }
     154              : 
     155        90586 :     if (m_startStaff == muse::nidx || st < m_startStaff) {
     156         2646 :         m_startStaff = st;
     157              :     }
     158        90586 :     if (m_endStaff == muse::nidx || st > m_endStaff) {
     159         3218 :         m_endStaff = st;
     160              :     }
     161              : }
     162              : 
     163              : //---------------------------------------------------------
     164              : //   setMeasureBase
     165              : //---------------------------------------------------------
     166              : 
     167        16287 : void CmdState::setMeasureBase(const MeasureBase* mb)
     168              : {
     169        16287 :     if (!mb || m_mb == mb || m_locked) {
     170        11737 :         return;
     171              :     }
     172              : 
     173         4550 :     m_oneMeasureBase = !m_mb;
     174         4550 :     m_mb = mb;
     175              : }
     176              : 
     177              : //---------------------------------------------------------
     178              : //   setElement
     179              : //---------------------------------------------------------
     180              : 
     181       969731 : void CmdState::setElement(const EngravingItem* e)
     182              : {
     183       969731 :     if (!e || m_el == e || m_locked) {
     184       912534 :         return;
     185              :     }
     186              : 
     187        57197 :     m_oneElement = !m_el;
     188        57197 :     m_el = e;
     189              : 
     190        57197 :     if (m_oneMeasureBase) {
     191        16287 :         setMeasureBase(e->findMeasureBase());
     192              :     }
     193              : }
     194              : 
     195              : //---------------------------------------------------------
     196              : //   unsetElement
     197              : //---------------------------------------------------------
     198              : 
     199       235427 : void CmdState::unsetElement(const EngravingItem* e)
     200              : {
     201       235427 :     if (m_el == e) {
     202           79 :         m_el = nullptr;
     203              :     }
     204       235427 :     if (m_mb == e) {
     205            0 :         m_mb = nullptr;
     206              :     }
     207       235427 : }
     208              : 
     209              : //---------------------------------------------------------
     210              : //   element
     211              : //---------------------------------------------------------
     212              : 
     213            0 : const EngravingItem* CmdState::element() const
     214              : {
     215            0 :     if (m_oneElement) {
     216            0 :         return m_el;
     217              :     }
     218            0 :     if (m_oneMeasureBase) {
     219            0 :         return m_mb;
     220              :     }
     221            0 :     return nullptr;
     222              : }
     223              : 
     224              : //---------------------------------------------------------
     225              : //   setUpdateMode
     226              : //---------------------------------------------------------
     227              : 
     228         3545 : void CmdState::_setUpdateMode(UpdateMode m)
     229              : {
     230         3545 :     m_updateMode = m;
     231         3545 : }
     232              : 
     233       397309 : void CmdState::setUpdateMode(UpdateMode m)
     234              : {
     235       397309 :     if (int(m) > int(m_updateMode)) {
     236         3545 :         _setUpdateMode(m);
     237              :     }
     238       397309 : }
     239              : 
     240              : //---------------------------------------------------------
     241              : //   deleteLater
     242              : //---------------------------------------------------------
     243              : 
     244          156 : void CmdState::deleteLater(EngravingObject* e)
     245              : {
     246          156 :     m_postponedDeletions.push_back(e);
     247          156 : }
     248              : 
     249         1878 : std::vector<EngravingObject*> CmdState::takePostponedDeletions()
     250              : {
     251         1878 :     std::vector<EngravingObject*> result;
     252         1878 :     result.swap(m_postponedDeletions);
     253         1878 :     return result;
     254              : }
     255              : 
     256         1878 : static void deletePostponed(CmdState& cmdState)
     257              : {
     258         1970 :     for (EngravingObject* e : cmdState.takePostponedDeletions()) {
     259           92 :         if (e->isSystem()) {
     260           46 :             System* s = toSystem(e);
     261           46 :             std::list<SpannerSegment*> spanners = s->spannerSegments();
     262           48 :             for (SpannerSegment* ss : spanners) {
     263            2 :                 if (ss->system() == s) {
     264            2 :                     ss->moveToSystem(nullptr);
     265              :                 }
     266              :             }
     267           46 :         }
     268           92 :         delete e;
     269         1878 :     }
     270         1878 : }
     271              : 
     272              : //---------------------------------------------------------
     273              : //   startCmd
     274              : ///   Start a GUI command by clearing the redraw area
     275              : ///   and starting a user-visible undo.
     276              : //---------------------------------------------------------
     277              : 
     278          692 : void Score::startCmd(const TranslatableString& actionName)
     279              : {
     280          692 :     masterScore()->transactionManager()->beginTransaction(actionName);
     281          692 : }
     282              : 
     283              : //---------------------------------------------------------
     284              : //   undoRedo
     285              : //---------------------------------------------------------
     286              : 
     287          230 : void Score::undoRedo(bool undo, EditData* ed)
     288              : {
     289          230 :     masterScore()->transactionManager()->undoRedo(undo, ed);
     290          230 : }
     291              : 
     292              : //---------------------------------------------------------
     293              : //   endCmd
     294              : ///   End a GUI command by (if \a undo) ending a user-visible undo
     295              : ///   and (always) updating the redraw area.
     296              : //---------------------------------------------------------
     297              : 
     298          696 : void Score::endCmd(bool rollback, bool layoutAllParts, bool keepRolledBackElements)
     299              : {
     300          696 :     masterScore()->transactionManager()->endTransaction(rollback, layoutAllParts, keepRolledBackElements);
     301          696 : }
     302              : 
     303              : //---------------------------------------------------------
     304              : //   undo
     305              : //    Deprecated: use Transaction::push instead.
     306              : //---------------------------------------------------------
     307              : 
     308        42447 : void Score::undo(UndoableCommand* cmd) const
     309              : {
     310        42447 :     Transaction* tx = masterScore()->transactionManager()->currentTransaction();
     311        42447 :     if (!tx) {
     312              :         // this can happen for layout() outside of a transaction (load)
     313        18586 :         if (!ScoreLoad::loading()) {
     314         9247 :             LOGW() << "called outside of transaction";
     315              :         }
     316              : 
     317        18586 :         cmd->redo();
     318        18586 :         delete cmd;
     319        18586 :         return;
     320              :     }
     321              : 
     322        23861 :     tx->push(cmd);
     323              : }
     324              : 
     325              : #ifndef NDEBUG
     326              : //---------------------------------------------------------
     327              : //   CmdState::dump
     328              : //---------------------------------------------------------
     329              : 
     330            0 : void CmdState::dump()
     331              : {
     332            0 :     LOGD("CmdState: mode %d %d-%d", int(m_updateMode), m_startTick.ticks(), m_endTick.ticks());
     333              :     // bool _excerptsChanged     { false };
     334              :     // bool _instrumentsChanged  { false };
     335            0 : }
     336              : 
     337              : #endif
     338              : 
     339              : //---------------------------------------------------------
     340              : //   update
     341              : //    layout & update
     342              : //---------------------------------------------------------
     343              : 
     344           88 : void Score::update()
     345              : {
     346           88 :     masterScore()->update();
     347           88 : }
     348              : 
     349         1878 : void MasterScore::update(bool resetCmdState, bool layoutAllParts)
     350              : {
     351         1878 :     if (m_updatesLocked) {
     352            0 :         return;
     353              :     }
     354              : 
     355         1881 :     TRACEFUNC;
     356              : 
     357         1878 :     deletePostponed(m_cmdState);
     358              : 
     359         1878 :     bool updateAll = false;
     360         1878 :     if (m_cmdState.layoutRange()) {
     361         2896 :         for (Score* s : scoreList()) {
     362         1595 :             if (s != this && !s->isOpen() && scoreList().size() > 1 && !layoutAllParts) {
     363          264 :                 continue;
     364              :             }
     365         1331 :             s->doLayoutRange(m_cmdState.startTick(), m_cmdState.endTick());
     366         1301 :         }
     367         1301 :         updateAll = true;
     368              :     }
     369              : 
     370         1878 :     if (needUpdateTicksAndTimeSigMap()) {
     371          302 :         updateTicksAndTimeSigMap();
     372              :     }
     373              : 
     374         1878 :     if (updateAll || m_cmdState.updateAll()) {
     375         3004 :         for (Score* s : scoreList()) {
     376         1650 :             for (MuseScoreView* v : s->getViewer()) {
     377            0 :                 v->updateAll();
     378              :             }
     379         1354 :         }
     380          524 :     } else if (m_cmdState.updateRange()) {
     381              :         // Any score that accumulated a refresh rect via addRefresh() calls dataChanged() on its viewers.
     382           60 :         for (Score* s : scoreList()) {
     383           30 :             if (s->refreshRect().isNull()) {
     384            0 :                 continue;
     385              :             }
     386           30 :             const std::list<MuseScoreView*>& viewers = s->getViewer();
     387           30 :             if (!viewers.empty()) {
     388            0 :                 double d = s->style().spatium() * .5;
     389            0 :                 RectF rect = s->refreshRect().adjusted(-d, -d, 2 * d, 2 * d);
     390            0 :                 for (MuseScoreView* v : viewers) {
     391            0 :                     v->dataChanged(rect);
     392              :                 }
     393              :             }
     394           30 :             s->clearRefreshRect();
     395           30 :         }
     396              :     }
     397              : 
     398         1878 :     if (resetCmdState) {
     399           98 :         m_cmdState.reset();
     400              :     }
     401              : 
     402         4058 :     for (Score* score : scoreList()) {
     403         2180 :         Selection& sel = score->selection();
     404         2180 :         if (sel.isRange() && !sel.isLocked()) {
     405          238 :             sel.updateSelectedElements();
     406              :         }
     407         1878 :     }
     408         1878 : }
     409              : 
     410            0 : void MasterScore::lockUpdates(bool locked)
     411              : {
     412            0 :     m_updatesLocked = locked;
     413            0 : }
     414              : 
     415              : //---------------------------------------------------------
     416              : //   expandVoice
     417              : //    fills gaps in voice with rests,
     418              : //    from previous cr (or beginning of measure) to next cr (or end of measure)
     419              : //---------------------------------------------------------
     420              : 
     421          222 : void Score::expandVoice(Segment* s, track_idx_t track)
     422              : {
     423          222 :     if (!s || track == muse::nidx) {
     424            0 :         LOGD("expand voice: no segment or invalid track");
     425          177 :         return;
     426              :     }
     427          222 :     if (s->element(track)) {
     428          176 :         return;
     429              :     }
     430              : 
     431              :     // find previous segment with cr in this track
     432              :     Segment* ps;
     433           99 :     for (ps = s; ps; ps = ps->prev(SegmentType::ChordRest)) {
     434           54 :         if (ps->element(track)) {
     435            1 :             break;
     436              :         }
     437              :     }
     438           46 :     if (ps) {
     439            1 :         ChordRest* cr = toChordRest(ps->element(track));
     440            1 :         Fraction tick = cr->endTick();
     441            1 :         if (tick > s->tick()) {
     442              :             // previous cr extends past current segment
     443            1 :             LOGD("expandVoice: cannot insert element here");
     444            1 :             return;
     445              :         }
     446            0 :         if (cr->isChord()) {
     447              :             // previous cr ends on or before current segment
     448              :             // for chords, move ps to just after cr ends
     449              :             // so we can fill any gap that might exist
     450              :             // but don't move ps if previous cr is a rest
     451              :             // this will be combined with any new rests needed to fill up to s->tick() below
     452            0 :             ps = ps->measure()->undoGetSegment(SegmentType::ChordRest, tick);
     453              :         }
     454              :     }
     455              :     //
     456              :     // fill up to s->tick() with rests
     457              :     //
     458           45 :     Measure* m = s->measure();
     459           45 :     Fraction stick  = ps ? ps->tick() : m->tick();
     460              : 
     461           45 :     const Staff* currStaff = staff(track2staff(track));
     462           45 :     IF_ASSERT_FAILED(currStaff) {
     463            0 :         return;
     464              :     }
     465           45 :     const Fraction stretch = currStaff->timeStretch(stick);
     466              : 
     467           45 :     Fraction ticks  = s->tick() - stick;
     468           45 :     if (ticks.isNotZero()) {
     469            5 :         setRest(stick, track, ticks * stretch, false, 0);
     470              :     }
     471              : 
     472              :     //
     473              :     // fill from s->tick() until next chord/rest in measure
     474              :     //
     475              :     Segment* ns;
     476          204 :     for (ns = s->next(SegmentType::ChordRest); ns; ns = ns->next(SegmentType::ChordRest)) {
     477          161 :         if (ns->element(track)) {
     478            2 :             break;
     479              :         }
     480              :     }
     481           45 :     ticks  = ns ? (ns->tick() - s->tick()) : (m->ticks() - s->rtick());
     482           45 :     if (ticks == m->ticks()) {
     483           38 :         addRest(s, track, TDuration(DurationType::V_MEASURE), 0);
     484              :     } else {
     485            7 :         setRest(s->tick(), track, ticks * stretch, false, 0);
     486              :     }
     487              : }
     488              : 
     489           28 : void Score::expandVoice()
     490              : {
     491           28 :     Segment* s = m_is.segment();
     492           28 :     track_idx_t track = m_is.track();
     493           28 :     expandVoice(s, track);
     494           28 : }
     495              : 
     496              : //---------------------------------------------------------
     497              : //   addInterval
     498              : //---------------------------------------------------------
     499              : 
     500           40 : void Score::addInterval(int val, const std::vector<Note*>& nl)
     501              : {
     502              :     // Prepare note selection in case there are not selected tied notes and sort them
     503           40 :     std::vector<Note*> tmpnl;
     504           40 :     std::vector<Note*> _nl = nl;
     505           40 :     bool selIsList = selection().isList();
     506           40 :     bool selIsSingle = selIsList && _nl.size() == 1;
     507           40 :     bool shouldSelectFirstNote = selIsSingle && _nl.front()->tieFor();
     508              : 
     509           40 :     std::sort(_nl.begin(), _nl.end(), [](const Note* a, const Note* b) -> bool {
     510            0 :         return a->tick() < b->tick();
     511              :     });
     512              : 
     513           80 :     for (Note* currNote : _nl) {
     514           80 :         for (Note* n = currNote; n && !muse::contains(tmpnl, n); n = n->tieFor() ? n->tieFor()->endNote() : nullptr) {
     515           40 :             if (selIsList && n->selected()) {
     516           40 :                 deselect(n);
     517              :             }
     518           40 :             tmpnl.emplace_back(n);
     519              :         }
     520              :     }
     521              : 
     522           40 :     Note* prevTied = nullptr;
     523           40 :     std::vector<EngravingItem*> notesToSelect;
     524           40 :     int deltaLine = val < 0 ? val + 1 : val - 1;
     525           40 :     bool accidental = m_is.noteEntryMode() && m_is.accidentalType() != AccidentalType::NONE;
     526           40 :     bool useOctaveRule = (deltaLine % STEP_DELTA_OCTAVE == 0) && !accidental;  // Both octaves and unison
     527              : 
     528           80 :     for (Note* on : tmpnl) {
     529           40 :         Chord* chord = on->chord();
     530           40 :         Fraction tick = chord->tick();
     531           40 :         NoteVal nval;
     532           40 :         bool forceAccidental = false;
     533           40 :         bool noteValid = false;
     534           40 :         if (on->staff() && on->staff()->isDrumStaff(tick)) {
     535              :             // For drum staves: Don't calculate the new note based on pitch, but choose one using lines
     536            0 :             const Drumset* ds = on->staff()->part()->instrument(tick)->drumset();
     537            0 :             nval.pitch = ds->defaultPitchForLine(on->line() - deltaLine);
     538            0 :             nval.headGroup = ds->noteHead(nval.pitch);
     539            0 :             noteValid = ds->isValid(nval.pitch) && nval.headGroup != NoteHeadGroup::HEAD_INVALID;
     540              :         } else {
     541           40 :             if (useOctaveRule) {
     542           40 :                 int octaves = deltaLine / STEP_DELTA_OCTAVE;
     543           40 :                 nval.pitch = on->pitch() + octaves * PITCH_DELTA_OCTAVE;
     544           40 :                 nval.tpc1 = on->tpc1();
     545           40 :                 nval.tpc2 = on->tpc2();
     546              :             } else {
     547            0 :                 int line      = on->line() - deltaLine;
     548            0 :                 Staff* estaff = staff(chord->vStaffIdx());
     549            0 :                 ClefType clef = estaff->clef(tick);
     550            0 :                 Key key       = estaff->key(tick);
     551              :                 int ntpc;
     552            0 :                 if (accidental) {
     553            0 :                     AccidentalVal acci = Accidental::subtype2value(m_is.accidentalType());
     554            0 :                     int step = absStep(line, clef);
     555            0 :                     int octave = step / 7;
     556            0 :                     nval.pitch = step2pitch(step) + octave * PITCH_DELTA_OCTAVE + int(acci);
     557            0 :                     forceAccidental = (nval.pitch == line2pitch(line, clef, key));
     558            0 :                     ntpc = step2tpc(step % STEP_DELTA_OCTAVE, acci);
     559              :                 } else {
     560            0 :                     nval.pitch = line2pitch(line, clef, key);
     561            0 :                     ntpc = pitch2tpc(nval.pitch, key, Prefer::NEAREST);
     562              :                 }
     563              : 
     564            0 :                 Interval v = estaff->transpose(tick);
     565            0 :                 if (v.isZero()) {
     566            0 :                     nval.tpc1 = nval.tpc2 = ntpc;
     567              :                 } else {
     568            0 :                     if (style().styleB(Sid::concertPitch)) {
     569            0 :                         v.flip();
     570            0 :                         nval.tpc1 = ntpc;
     571            0 :                         nval.tpc2 = Transpose::transposeTpc(ntpc, v, true);
     572              :                     } else {
     573            0 :                         nval.pitch += v.chromatic;
     574            0 :                         nval.tpc2 = ntpc;
     575            0 :                         nval.tpc1 = Transpose::transposeTpc(ntpc, v, true);
     576              :                     }
     577              :                 }
     578              :             }
     579           40 :             noteValid = pitchIsValid(nval.pitch);
     580              :         }
     581              : 
     582           40 :         if (!noteValid) {
     583           30 :             notesToSelect.push_back(toEngravingItem(on));
     584           30 :             continue;
     585              :         }
     586              : 
     587           10 :         Note* note = Factory::createNote(chord);
     588           10 :         note->setTrack(chord->track());
     589           10 :         note->setNval(nval, tick);
     590           10 :         undoAddElement(note);
     591              : 
     592           10 :         if (forceAccidental) {
     593            0 :             Accidental* a = Factory::createAccidental(note);
     594            0 :             a->setAccidentalType(m_is.accidentalType());
     595            0 :             a->setRole(AccidentalRole::USER);
     596            0 :             undoAddElement(a);
     597              :         }
     598           10 :         if (on->tieBack() && prevTied) {
     599            0 :             Tie* tie = prevTied->tieFor();
     600            0 :             tie->setEndNote(note);
     601            0 :             tie->setTick2(note->tick());
     602            0 :             note->setTieBack(tie);
     603            0 :             undoAddElement(tie);
     604            0 :             prevTied = nullptr;
     605              :         }
     606              : 
     607           10 :         Tie* tieFor = on->tieFor();
     608           10 :         if (tieFor) {
     609            0 :             Tie* tie = tieFor->isLaissezVib() ? Factory::createLaissezVib(note) : Factory::createTie(note);
     610            0 :             tie->setStartNote(note);
     611            0 :             tie->setTick(note->tick());
     612            0 :             tie->setTrack(note->track());
     613            0 :             note->setTieFor(tie);
     614            0 :             prevTied = note;
     615              :         }
     616              : 
     617           10 :         setPlayNote(true);
     618           10 :         if (selIsList && note) {
     619           10 :             notesToSelect.push_back(toEngravingItem(note));
     620              :         }
     621              :     }
     622           40 :     if (m_is.noteEntryMode()) {
     623           40 :         m_is.setAccidentalType(AccidentalType::NONE);
     624              :     }
     625           40 :     if (notesToSelect.empty()) {
     626            0 :         return;
     627              :     }
     628           40 :     if (shouldSelectFirstNote) {
     629            0 :         select(notesToSelect.front(), SelectType::SINGLE, 0);
     630              :     } else {
     631           40 :         select(notesToSelect, SelectType::ADD, 0);
     632              :     }
     633           40 :     if (m_is.cr() == toChordRest(_nl.front()->chord()) && selIsSingle) {
     634            0 :         m_is.moveToNextInputPos();
     635              :     }
     636           40 : }
     637              : 
     638              : //---------------------------------------------------------
     639              : //   setGraceNote
     640              : ///   Create a grace note in front of a normal note.
     641              : ///   \arg ch is the chord of the normal note
     642              : ///   \arg pitch is the pitch of the grace note
     643              : ///   \arg is the grace note type
     644              : ///   \len is the visual duration of the grace note (1/16 or 1/32)
     645              : //---------------------------------------------------------
     646              : 
     647           74 : Note* Score::setGraceNote(Chord* ch, int pitch, NoteType type, int len)
     648              : {
     649           74 :     Chord* chord = Factory::createChord(this->dummy());
     650           74 :     Note* note = Factory::createNote(chord);
     651              : 
     652              :     // allow grace notes to be added to other grace notes
     653              :     // by really adding to parent chord
     654           74 :     if (ch->noteType() != NoteType::NORMAL) {
     655            0 :         ch = toChord(ch->ownershipParent());
     656              :     }
     657              : 
     658           74 :     chord->setTrack(ch->track());
     659           74 :     chord->setOwnershipParent(ch);
     660           74 :     chord->add(note);
     661              : 
     662              :     // find corresponding note within chord and use its tpc information
     663              :     // if no note with same pitch found, derive tpc from pitch / key
     664           74 :     if (Note* n = ch->findNote(pitch)) {
     665           69 :         note->setNval(n->noteVal(), ch->tick());
     666              :     } else {
     667            5 :         note->setPitch(pitch);
     668            5 :         note->setTpcFromPitch();
     669              :     }
     670              : 
     671           74 :     TDuration d;
     672           74 :     d.setVal(len);
     673           74 :     chord->setDurationType(d);
     674           74 :     chord->setTicks(d.fraction());
     675           74 :     chord->setNoteType(type);
     676           74 :     chord->setShowStemSlashInAdvance();
     677           74 :     chord->mutldata()->setMag(ch->staff()->staffMag(chord->tick()) * style().styleD(Sid::graceNoteMag));
     678              : 
     679           74 :     undoAddElement(chord);
     680           74 :     return note;
     681              : }
     682              : 
     683          292 : GuitarBend* Score::addGuitarBend(GuitarBendType type, Note* note, Note* endNote)
     684              : {
     685          292 :     if (note->isPreBendOrDiveStart()) {
     686            0 :         if (type == GuitarBendType::BEND && note->staffType()->isTabStaff()) {
     687            0 :             GuitarBend* preBend = note->bendFor();
     688            0 :             Note* mainNote = preBend ? preBend->endNote() : nullptr;
     689            0 :             if (mainNote) {
     690            0 :                 return addGuitarBend(type, mainNote, nullptr);
     691              :             }
     692              :         }
     693            0 :         return nullptr;
     694              :     }
     695              : 
     696          292 :     if (note->isGraceBendStart() && type != GuitarBendType::PRE_BEND) {
     697            0 :         return nullptr;
     698              :     }
     699              : 
     700          398 :     if (GuitarBend* bendBack = note->bendBack(); bendBack && !bendBack->isDive()
     701          398 :         && (type == GuitarBendType::PRE_BEND || type == GuitarBendType::GRACE_NOTE_BEND)) {
     702            0 :         return nullptr;
     703              :     }
     704              : 
     705          292 :     if (GuitarBend* bendFor = note->bendFor(); bendFor && !bendFor->isDive()
     706          292 :         && (type == GuitarBendType::BEND || type == GuitarBendType::SLIGHT_BEND)) {
     707            0 :         return nullptr;
     708              :     }
     709              : 
     710          292 :     if (type == GuitarBendType::DIP) {
     711            0 :         for (Note* n : note->chord()->notes()) {
     712            0 :             if (GuitarBend* bendFor = n->bendFor(); bendFor && bendFor->bendType() == GuitarBendType::DIP) {
     713            0 :                 return nullptr; // Only one dip per chord
     714              :             }
     715              :         }
     716              :     }
     717              : 
     718          292 :     Chord* chord = note->chord();
     719          292 :     bool isDive = static_cast<int>(type) >= static_cast<int>(GuitarBendType::DIVE)
     720          292 :                   && static_cast<int>(type) <= static_cast<int>(GuitarBendType::SCOOP);
     721              : 
     722          292 :     if (type == GuitarBendType::BEND || type == GuitarBendType::DIVE) {
     723          218 :         for (Spanner* sp : note->spannerFor()) {
     724            0 :             if ((sp->isGuitarBend() && toGuitarBend(sp)->isDive() == isDive) || sp->isGlissando()) {
     725            0 :                 return nullptr;
     726              :             }
     727              :         }
     728              : 
     729          218 :         if (!endNote) {
     730            0 :             endNote = SLine::guessFinalNote(note);
     731              :         }
     732              : 
     733          218 :         bool suitableEndNote = endNote;
     734          218 :         if (endNote) {
     735          218 :             for (Spanner* sp : endNote->spannerBack()) {
     736            0 :                 if (sp->isTie() || sp->isGlissando() || (sp->isGuitarBend() && toGuitarBend(sp)->isDive() == isDive)) {
     737            0 :                     suitableEndNote = false;
     738            0 :                     break;
     739              :                 }
     740              :             }
     741              :         }
     742              : 
     743          218 :         if (!suitableEndNote) {
     744            0 :             endNote = GuitarBend::createEndNote(note, type);
     745              :         }
     746              : 
     747          218 :         if (!endNote) {
     748            0 :             return nullptr;
     749              :         }
     750              :     }
     751              : 
     752          292 :     GuitarBend* bend = new GuitarBend(score()->dummy());
     753          292 :     bend->setTick(chord->tick());
     754          292 :     bend->setTrack(chord->track());
     755              : 
     756          292 :     if (type == GuitarBendType::BEND || type == GuitarBendType::DIVE) {
     757          218 :         bend->setBendType(chord->isGrace() && type == GuitarBendType::BEND ? GuitarBendType::GRACE_NOTE_BEND : type);
     758          218 :         bend->setStartElement(note);
     759          218 :         bend->setTick2(endNote->tick());
     760          218 :         bend->setTrack2(endNote->track());
     761          218 :         bend->setEndElement(endNote);
     762          218 :         bend->setOwnershipParent(note);
     763          218 :         if (type == GuitarBendType::BEND) {
     764          118 :             GuitarBend::fixNotesFrettingForStandardBend(note, endNote);
     765              :         }
     766              :     } else {
     767           74 :         bend->setBendType(type);
     768           74 :         bend->setTick2(chord->tick());
     769           74 :         bend->setTrack2(chord->track());
     770              : 
     771           74 :         if (type == GuitarBendType::PRE_BEND || type == GuitarBendType::GRACE_NOTE_BEND || type == GuitarBendType::PRE_DIVE) {
     772           66 :             const GraceNotesGroup& gracesBefore = chord->graceNotesBefore();
     773              : 
     774              :             // Add to existing grace chord only if it already has a bend/dive ghost.
     775           66 :             const bool hasGhostGrace = !gracesBefore.empty()
     776           71 :                                        && std::any_of(gracesBefore.back()->notes().begin(),
     777            5 :                                                       gracesBefore.back()->notes().end(),
     778            5 :                                                       [](const Note* n) {
     779            5 :                 return n->isPreBendOrDiveStart() || n->isGraceBendStart();
     780           66 :             });
     781              :             Note* graceNote = hasGhostGrace
     782           72 :                               ? NoteInput::addNote(transactionManager()->currentOrDummyTransaction(), this, gracesBefore.back(),
     783            3 :                                                    note->noteVal())
     784           66 :                               : setGraceNote(chord, note->pitch(), NoteType::APPOGGIATURA, Constants::DIVISION / 2);
     785           66 :             graceNote->transposeDiatonic(type == GuitarBendType::PRE_DIVE ? 1 : -1, true, false);
     786           66 :             GuitarBend::fixNotesFrettingForGraceBend(graceNote, note);
     787              : 
     788           66 :             Chord* graceChord = graceNote->chord();
     789          132 :             for (EngravingObject* item : graceChord->linkList()) {
     790           66 :                 Chord* linkedGrace = toChord(item);
     791           66 :                 linkedGrace->setNoStem(true);
     792           66 :                 linkedGrace->setBeamMode(BeamMode::NONE);
     793           66 :             }
     794              : 
     795              :             // Add bend
     796           66 :             bend->setOwnershipParent(graceNote);
     797           66 :             bend->setStartElement(graceNote);
     798           66 :             bend->setEndElement(note);
     799           74 :         } else if (type == GuitarBendType::SLIGHT_BEND || type == GuitarBendType::DIP || type == GuitarBendType::SCOOP) {
     800            8 :             bend->setOwnershipParent(note);
     801            8 :             bend->setStartElement(note);
     802              :             // Slight bends don't end on another note
     803            8 :             bend->setEndElement(note);
     804              :         }
     805              :     }
     806              : 
     807          292 :     Chord* startChord = bend->startNote()->chord();
     808          292 :     if (startChord->isGrace()) {
     809          202 :         for (EngravingObject* item : startChord->linkList()) {
     810          101 :             Chord* linkedGrace = toChord(item);
     811          101 :             if (linkedGrace->staffType()->isTabStaff()) {
     812            0 :                 linkedGrace->setNoStem(true);
     813            0 :                 linkedGrace->setBeamMode(BeamMode::NONE);
     814              :             }
     815          101 :         }
     816              :     }
     817              : 
     818          292 :     score()->undoAddElement(bend);
     819              : 
     820          292 :     if (GuitarBend* overlapping = bend->overlappingBendOrDive()) {
     821            0 :         int halfBendAmount = std::floor(overlapping->bendAmountInQuarterTones() / 2);
     822            0 :         if (bend->isDive()) {
     823            0 :             bend->undoChangeProperty(Pid::GUITAR_BEND_AMOUNT, halfBendAmount);
     824              :         } else {
     825            0 :             overlapping->undoChangeProperty(Pid::GUITAR_BEND_AMOUNT, halfBendAmount);
     826              :         }
     827              :     }
     828              : 
     829          292 :     return bend;
     830              : }
     831              : 
     832              : //---------------------------------------------------------
     833              : //   createCRSequence
     834              : //    Create a rest or chord of len f.
     835              : //    If f is not a basic len, create several rests or
     836              : //    tied chords.
     837              : //
     838              : //    f     total len of ChordRest
     839              : //    cr    prototype CR
     840              : //    tick  start position in measure
     841              : //---------------------------------------------------------
     842              : 
     843            2 : void Score::createCRSequence(const Fraction& f, ChordRest* cr, const Fraction& t)
     844              : {
     845            2 :     Fraction tick(t);
     846            2 :     Measure* measure = cr->measure();
     847            2 :     ChordRest* ocr = 0;
     848            4 :     for (TDuration d : toDurationList(f, true)) {
     849            2 :         ChordRest* ncr = toChordRest(cr->clone());
     850            2 :         ncr->setDurationType(d);
     851            2 :         ncr->setTicks(d.fraction());
     852            2 :         undoAddCR(ncr, measure, measure->tick() + tick);
     853            2 :         if (cr->isChord() && ocr) {
     854            0 :             Chord* nc = toChord(ncr);
     855            0 :             Chord* oc = toChord(ocr);
     856            0 :             for (unsigned int i = 0; i < oc->notes().size(); ++i) {
     857            0 :                 Note* on = oc->notes()[i];
     858            0 :                 Note* nn = nc->notes()[i];
     859            0 :                 Tie* tie = Factory::createTie(on);
     860            0 :                 tie->setStartNote(on);
     861            0 :                 tie->setEndNote(nn);
     862            0 :                 tie->setTick(tie->startNote()->tick());
     863            0 :                 tie->setTick2(tie->endNote()->tick());
     864            0 :                 tie->setTrack(cr->track());
     865            0 :                 on->setTieFor(tie);
     866            0 :                 nn->setTieBack(tie);
     867            0 :                 undoAddElement(tie);
     868              :             }
     869              :         }
     870              : 
     871            2 :         tick += ncr->actualTicks();
     872            2 :         ocr = ncr;
     873            2 :     }
     874            2 : }
     875              : 
     876              : //---------------------------------------------------------
     877              : //   setNoteRest
     878              : //    pitch == -1  -> set rest
     879              : //    "sd" is in local (stretched) time
     880              : //    return segment of last created note/rest
     881              : //---------------------------------------------------------
     882              : 
     883          625 : Segment* Score::setNoteRest(Segment* segment, track_idx_t track, NoteVal nval, Fraction sd, DirectionV stemDirection,
     884              :                             bool forceAccidental, const std::set<SymId>& articulationIds, bool rhythmic, InputState* externalInputState)
     885              : {
     886          625 :     assert(segment->segmentType() == SegmentType::ChordRest);
     887          625 :     InputState& is = externalInputState ? (*externalInputState) : m_is;
     888              : 
     889          625 :     bool isRest   = nval.isRest();
     890          625 :     Fraction tick = segment->tick();
     891          625 :     EngravingItem* nr   = nullptr;
     892          625 :     Tie* tie      = nullptr;
     893          625 :     ChordRest* cr = toChordRest(segment->element(track));
     894          625 :     Tuplet* tuplet = cr ? cr->tuplet() : nullptr;
     895          625 :     Measure* measure = nullptr;
     896          625 :     bool targetIsRest = cr && cr->isRest();
     897              : 
     898              :     // preserve lyrics before the ChordRest is removed or replaced
     899          625 :     std::vector<Lyrics*> lyricsToPreserve;
     900          625 :     bool shouldPreserveLyrics = false;
     901          625 :     if (!isRest && cr) {
     902          229 :         lyricsToPreserve = cr->lyrics();
     903          229 :         shouldPreserveLyrics = !lyricsToPreserve.empty();
     904              :     }
     905          625 :     bool lyricsPreserved = false;
     906              : 
     907              :     for (;;) {
     908          655 :         if (track % VOICES) {
     909           34 :             expandVoice(segment, track);
     910              :         }
     911          655 :         if (targetIsRest && !cr->isRest()) {
     912            0 :             undoRemoveElement(cr);
     913            0 :             segment = addRest(segment, track, cr->ticks(), cr->tuplet())->segment();
     914              :         }
     915              :         // the returned gap ends at the measure boundary or at tuplet end
     916          655 :         Fraction dd = makeGap(segment, track, sd, tuplet);
     917              : 
     918          655 :         if (dd.isZero()) {
     919            0 :             LOGD("cannot get gap at %d type: %d/%d", tick.ticks(), sd.numerator(),
     920              :                  sd.denominator());
     921            0 :             break;
     922              :         }
     923              : 
     924          655 :         measure = segment->measure();
     925          655 :         Fraction timeStretch = staff(track2staff(track))->timeStretch(tick);
     926          655 :         std::vector<TDuration> dl;
     927          655 :         if (rhythmic) {
     928         1146 :             dl = toRhythmicDurationList(dd, isRest, segment->rtick() * timeStretch, sigmap()->timesig(
     929         1146 :                                             tick).nominal(), measure, 1, timeStretch);
     930              :         } else {
     931          273 :             dl = toDurationList(dd, true);
     932              :         }
     933          655 :         size_t n = dl.size();
     934         1522 :         for (size_t i = 0; i < n; ++i) {
     935          867 :             const TDuration& d = dl[i];
     936          867 :             ChordRest* ncr = nullptr;
     937          867 :             Note* note = nullptr;
     938          867 :             Tie* addTie = nullptr;
     939          867 :             if (isRest) {
     940          590 :                 nr = ncr = Factory::createRest(this->dummy());
     941          590 :                 nr->setTrack(track);
     942          590 :                 ncr->setDurationType(d);
     943          590 :                 ncr->setTicks(d.isMeasure() ? measure->ticks() * timeStretch : d.fraction());
     944              :             } else {
     945          277 :                 nr = note = Factory::createNote(this->dummy());
     946              : 
     947          277 :                 if (tie) {
     948           39 :                     tie->setEndNote(note);
     949           39 :                     note->setTieBack(tie);
     950           39 :                     addTie = tie;
     951              :                 }
     952          277 :                 Chord* chord = Factory::createChord(this->dummy());
     953          277 :                 chord->setTrack(track);
     954          277 :                 chord->setDurationType(d);
     955          277 :                 chord->setTicks(d.fraction());
     956          277 :                 chord->setStemDirection(stemDirection);
     957          277 :                 chord->add(note);
     958          277 :                 if (cr && cr->isChord()) {
     959           26 :                     std::vector<Chord*> graceNotes = toChord(cr)->graceNotes();
     960           26 :                     for (Chord* grace : graceNotes) {
     961            0 :                         undoChangeParent(grace, chord, chord->staffIdx());
     962              :                     }
     963           26 :                 }
     964          277 :                 note->setNval(nval, tick);
     965          277 :                 if (forceAccidental) {
     966            0 :                     int tpc = style().styleB(Sid::concertPitch) ? nval.tpc1 : nval.tpc2;
     967            0 :                     AccidentalVal alter = tpc2alter(tpc);
     968            0 :                     AccidentalType at = Accidental::value2subtype(alter);
     969            0 :                     Accidental* a = Factory::createAccidental(note);
     970            0 :                     a->setAccidentalType(at);
     971            0 :                     a->setRole(AccidentalRole::USER);
     972            0 :                     note->add(a);
     973              :                 }
     974              : 
     975          277 :                 ncr = chord;
     976          277 :                 if (i + 1 < n) {
     977           13 :                     tie = Factory::createTie(note);
     978           13 :                     tie->setStartNote(note);
     979           13 :                     tie->setTick(tie->startNote()->tick());
     980           13 :                     tie->setTrack(track);
     981           13 :                     note->setTieFor(tie);
     982              :                 }
     983              :             }
     984          867 :             if (tuplet) {
     985           57 :                 ncr->setTuplet(tuplet);
     986              :             }
     987          867 :             undoAddCR(ncr, measure, tick);
     988              : 
     989          867 :             if (shouldPreserveLyrics && !lyricsPreserved) {
     990              :                 // reattach the preserved lyrics to the first replacement ChordRest
     991              :                 // to ensure they are not duplicated during subsequent operations
     992           10 :                 lyricsPreserved = true;
     993           26 :                 for (Lyrics* lyric : lyricsToPreserve) {
     994           16 :                     undoChangeParent(lyric, ncr, ncr->staffIdx());
     995              :                 }
     996              :             }
     997              : 
     998          867 :             if (addTie) {
     999           39 :                 undoAddElement(addTie);
    1000              :             }
    1001          867 :             setPlayNote(true);
    1002          867 :             segment = ncr->segment();
    1003          867 :             tick += ncr->actualTicks();
    1004              : 
    1005          867 :             if (!articulationIds.empty()) {
    1006            0 :                 if (ncr->isChord()) {
    1007            0 :                     toChord(ncr)->updateArticulations(articulationIds);
    1008              :                 }
    1009              :             }
    1010              :         }
    1011              : 
    1012          655 :         sd -= dd;
    1013          655 :         if (sd.isZero()) {
    1014          625 :             break;
    1015              :         }
    1016              : 
    1017           30 :         if (tick >= score()->endTick()) {
    1018            1 :             appendMeasures(1);
    1019              :         }
    1020           30 :         Segment* nseg = tick2segment(tick, false, SegmentType::ChordRest);
    1021           30 :         if (!nseg) {
    1022            0 :             break;
    1023              :         }
    1024           30 :         segment = nseg;
    1025              : 
    1026           30 :         cr = toChordRest(segment->element(track));
    1027              :         // if the cr was too big for the tuplet, get the next tuplet so we can spill into that one
    1028           30 :         tuplet = cr && cr->tuplet() ? cr->tuplet() : nullptr;
    1029           30 :         if (!cr) {
    1030            0 :             if (track % VOICES) {
    1031            0 :                 cr = addRest(segment, track, TDuration(DurationType::V_MEASURE), 0);
    1032              :             } else {
    1033            0 :                 LOGD("no rest in voice 0");
    1034            0 :                 break;
    1035              :             }
    1036              :         }
    1037              :         //
    1038              :         //  Note does not fit on current measure, create Tie to
    1039              :         //  next part of note
    1040           30 :         if (!isRest) {
    1041           26 :             tie = Factory::createTie((Note*)nr);
    1042           26 :             tie->setStartNote((Note*)nr);
    1043           26 :             tie->setTick(tie->startNote()->tick());
    1044           26 :             tie->setTrack(nr->track());
    1045           26 :             ((Note*)nr)->setTieFor(tie);
    1046              :         }
    1047          685 :     }
    1048          625 :     if (tie) {
    1049           18 :         connectTies();
    1050              :     }
    1051              : 
    1052          625 :     if (nr) {
    1053          625 :         if (is.slur() && nr->isNote()) {
    1054              :             // If the start element was the same as the end element when the slur was created,
    1055              :             // the end grip of the front slur segment was given an x-offset of 3.0 * spatium().
    1056              :             // Now that the slur is about to be given a new end element, this should be reset.
    1057            0 :             if (is.slur()->endElement() == is.slur()->startElement()) {
    1058            0 :                 is.slur()->frontSegment()->reset();
    1059              :             }
    1060              :             //
    1061              :             // extend slur
    1062              :             //
    1063            0 :             Chord* chord = toNote(nr)->chord();
    1064            0 :             is.slur()->undoChangeProperty(Pid::SPANNER_TICKS, chord->tick() - is.slur()->tick());
    1065            0 :             for (EngravingObject* se : is.slur()->linkList()) {
    1066            0 :                 Slur* slur = toSlur(se);
    1067            0 :                 for (EngravingObject* ee : chord->linkList()) {
    1068            0 :                     EngravingItem* e = static_cast<EngravingItem*>(ee);
    1069            0 :                     if (e->score() == slur->score() && e->track() == slur->track2()) {
    1070            0 :                         slur->score()->undo(new ChangeSpannerElements(slur, slur->startElement(), e));
    1071            0 :                         break;
    1072              :                     }
    1073            0 :                 }
    1074            0 :             }
    1075              :         }
    1076          625 :         if (externalInputState) {
    1077           75 :             is.setTrack(nr->track());
    1078           75 :             cr = nr->isRest() ? toChordRest(nr) : toNote(nr)->chord();
    1079           75 :             is.setLastSegment(is.segment());
    1080           75 :             is.setSegment(cr->segment());
    1081              :         } else {
    1082          550 :             select(nr, SelectType::SINGLE, 0);
    1083              :         }
    1084              :     }
    1085          625 :     return segment;
    1086          625 : }
    1087              : 
    1088              : //---------------------------------------------------------
    1089              : //   makeGap
    1090              : //    make time gap at tick by removing/shortening
    1091              : //    chord/rest
    1092              : //
    1093              : //    if keepChord, the chord at tick is not removed
    1094              : //
    1095              : //    "sd" is in local (stretched) time
    1096              : //
    1097              : //    gap does not exceed measure or scope of tuplet
    1098              : //
    1099              : //    return size of actual gap in local time
    1100              : //---------------------------------------------------------
    1101              : 
    1102         2218 : Fraction Score::makeGap(Segment* segment, track_idx_t track, const Fraction& _sd, Tuplet* tuplet, bool keepChord, bool deleteAnnotations)
    1103              : {
    1104         2218 :     assert(_sd.numerator());
    1105              : 
    1106         2218 :     Staff* stf = staff(track2staff(track));
    1107         2218 :     IF_ASSERT_FAILED(stf) {
    1108            0 :         return Fraction();
    1109              :     }
    1110              : 
    1111         2218 :     Measure* measure = segment->measure();
    1112         2218 :     Fraction accumulated;
    1113         2218 :     Fraction sd = _sd;
    1114              : 
    1115              :     //
    1116              :     // remember first segment which should
    1117              :     // not be deleted (it may contain other elements we want to preserve)
    1118              :     //
    1119         2218 :     Segment* firstSegment = segment;
    1120         2218 :     const Fraction firstSegmentEnd = firstSegment->tick() + firstSegment->ticks();
    1121         2218 :     Fraction nextTick = segment->tick();
    1122              : 
    1123         3916 :     for (Segment* seg = firstSegment; seg; seg = seg->next(SegmentType::ChordRest)) {
    1124              :         //
    1125              :         // voices != 0 may have gaps:
    1126              :         //
    1127         3903 :         ChordRest* cr = toChordRest(seg->element(track));
    1128         3903 :         Fraction timeStretch = stf->timeStretch(seg->tick());
    1129         3903 :         if (!cr) {
    1130           25 :             if (seg->tick() < nextTick) {
    1131           23 :                 continue;
    1132              :             }
    1133            2 :             Segment* seg1 = seg->next(SegmentType::ChordRest);
    1134            2 :             Fraction tick2 = seg1 ? seg1->tick() : seg->measure()->endTick();
    1135            2 :             Fraction td(tick2 - seg->tick());
    1136            2 :             td /= actualTicks(Fraction(1, 1), tuplet, timeStretch);
    1137            2 :             if (td > sd) {
    1138            1 :                 td = sd;
    1139              :             }
    1140            2 :             accumulated += td;
    1141            2 :             sd -= td;
    1142            2 :             if (sd.isZero()) {
    1143            2 :                 break;
    1144              :             }
    1145            0 :             nextTick = tick2;
    1146            0 :             continue;
    1147            0 :         }
    1148         3878 :         if (seg->tick() > nextTick) {
    1149              :             // there was a gap
    1150            0 :             Fraction td(seg->tick() - nextTick);
    1151            0 :             td /= actualTicks(Fraction(1, 1), tuplet, timeStretch);
    1152            0 :             if (td > sd) {
    1153            0 :                 td = sd;
    1154              :             }
    1155            0 :             accumulated += td;
    1156            0 :             sd -= td;
    1157            0 :             if (sd.isZero()) {
    1158            0 :                 break;
    1159              :             }
    1160              :         }
    1161              :         //
    1162              :         // limit to tuplet level
    1163              :         //
    1164         3878 :         if (tuplet) {
    1165          160 :             bool tupletEnd = true;
    1166          160 :             Tuplet* t = cr->tuplet();
    1167          174 :             while (t) {
    1168          150 :                 if (t == tuplet) {
    1169          136 :                     tupletEnd = false;
    1170          136 :                     break;
    1171              :                 }
    1172           14 :                 t = t->tuplet();
    1173              :             }
    1174          160 :             if (tupletEnd) {
    1175           24 :                 break;
    1176              :             }
    1177              :         }
    1178         3854 :         Fraction td(cr->ticks());
    1179              : 
    1180              :         // remove tremolo between 2 notes, if present
    1181         3854 :         if (cr->isChord()) {
    1182         1554 :             Chord* c = toChord(cr);
    1183         1554 :             if (c->tremoloTwoChord()) {
    1184            0 :                 undoRemoveElement(c->tremoloTwoChord());
    1185              :             }
    1186              :         }
    1187         3854 :         Tuplet* ltuplet = cr->tuplet();
    1188         3854 :         if (ltuplet != tuplet) {
    1189              :             //
    1190              :             // Current location points to the start of a (nested)tuplet.
    1191              :             // We have to remove the complete tuplet.
    1192              : 
    1193              :             // get the outermost tuplet inside the current one
    1194            4 :             while (ltuplet->tuplet() != tuplet) {
    1195            0 :                 ltuplet = ltuplet->tuplet();
    1196              :             }
    1197              : 
    1198              :             // get last segment of tuplet, drilling down to leaf nodes as necessary
    1199            4 :             Tuplet* t = ltuplet;
    1200            4 :             while (t->elements().back()->isTuplet()) {
    1201            0 :                 t = toTuplet(t->elements().back());
    1202              :             }
    1203            4 :             seg = toChordRest(t->elements().back())->segment();
    1204              : 
    1205              :             // now delete the full tuplet
    1206            4 :             td = ltuplet->ticks();
    1207            4 :             cmdDeleteTuplet(ltuplet, false);
    1208              :         } else {
    1209         3850 :             if (seg != firstSegment || !keepChord) {
    1210         3792 :                 undoRemoveElement(cr);
    1211              :             }
    1212              :             // even if there was a tuplet, we didn't remove it
    1213         3850 :             ltuplet = 0;
    1214              :         }
    1215         3854 :         nextTick += actualTicks(td, tuplet, timeStretch);
    1216         3854 :         if (sd < td) {
    1217              :             //
    1218              :             // we removed too much
    1219              :             //
    1220          310 :             accumulated = _sd;
    1221          310 :             Fraction rd = td - sd;
    1222          310 :             Fraction tick = cr->tick() + actualTicks(sd, tuplet, timeStretch);
    1223              : 
    1224          310 :             std::vector<TDuration> dList;
    1225          310 :             if (tuplet) {
    1226            5 :                 dList = toDurationList(rd, false);
    1227            5 :                 std::reverse(dList.begin(), dList.end());
    1228              :             } else {
    1229          305 :                 TimeSig* timeSig = stf->timeSig(tick);
    1230          305 :                 TimeSigFrac refTimeSig = timeSig ? timeSig->sig() : sigmap()->timesig(tick).nominal();
    1231          305 :                 Fraction rTickStart = (tick - measure->tick()) * stf->timeStretch(tick);
    1232          305 :                 dList = toRhythmicDurationList(rd, true, rTickStart, refTimeSig, measure, 0, stf->timeStretch(tick));
    1233              :             }
    1234          310 :             if (dList.empty()) {
    1235            0 :                 break;
    1236              :             }
    1237              : 
    1238          794 :             for (TDuration d : dList) {
    1239          484 :                 if (ltuplet) {
    1240              :                     // take care not to recreate tuplet we just deleted
    1241            4 :                     Rest* r = setRest(tick, track, d.fraction(), false, tuplet, false);
    1242            4 :                     tick += r->actualTicks();
    1243              :                 } else {
    1244          480 :                     tick += addClone(cr, tick, d)->actualTicks();
    1245              :                 }
    1246              :             }
    1247          310 :             break;
    1248          310 :         }
    1249         3544 :         accumulated += td;
    1250         3544 :         sd          -= td;
    1251         3544 :         if (sd.isZero()) {
    1252         1869 :             break;
    1253              :         }
    1254              :     }
    1255              : 
    1256         2218 :     const Fraction t1 = firstSegmentEnd;
    1257         2218 :     const Fraction t2 = firstSegment->tick() + actualTicks(accumulated, tuplet, stf->timeStretch(firstSegment->tick()));
    1258         2218 :     if (t1 < t2) {
    1259              :         // Delete annotations that require an anchor to the previous segment
    1260         1152 :         Segment* s1 = tick2rightSegment(t1);
    1261         1152 :         Segment* s2 = tick2rightSegment(t2);
    1262         1152 :         const bool segsValid = s1 && s2 && (*s2) > (*s1);
    1263         1152 :         if (segsValid && deleteAnnotations) {
    1264         1295 :             for (Segment* s = s1; s && s != s2; s = s->next1()) {
    1265          926 :                 const auto annotations = s->annotations(); // make a copy since we alter the list
    1266          929 :                 for (EngravingItem* annotation : annotations) {
    1267            3 :                     if (!annotation->systemFlag() && !annotation->allowTimeAnchor() && annotation->track() == track) {
    1268            0 :                         deleteItem(annotation);
    1269              :                     }
    1270              :                 }
    1271          926 :             }
    1272              :         }
    1273              : 
    1274         1152 :         SelectionFilter filter;
    1275         1152 :         deleteSlursFromRange(t1, t2, track, track + 1, filter);
    1276              :     }
    1277              : 
    1278         2218 :     return accumulated;
    1279              : }
    1280              : 
    1281          401 : bool Score::makeGapVoice(Segment* seg, track_idx_t track, Fraction len, const Fraction& tick, bool deleteAnnotations)
    1282              : {
    1283          401 :     ChordRest* cr = 0;
    1284          401 :     cr = toChordRest(seg->element(track));
    1285          401 :     if (!cr) {
    1286              :         // check if we are in the middle of a chord/rest
    1287           44 :         Segment* seg1 = seg->prev(SegmentType::ChordRest);
    1288              :         for (;;) {
    1289           50 :             if (seg1 == 0) {
    1290           30 :                 if (!(track % VOICES)) {
    1291            0 :                     LOGD("no segment before tick %d", tick.ticks());
    1292              :                 }
    1293              :                 // this happens only for voices other than voice 1
    1294           30 :                 expandVoice(seg, track);
    1295           30 :                 return makeGapVoice(seg, track, len, tick, deleteAnnotations);
    1296              :             }
    1297           20 :             if (seg1->element(track)) {
    1298           14 :                 break;
    1299              :             }
    1300            6 :             seg1 = seg1->prev(SegmentType::ChordRest);
    1301              :         }
    1302           14 :         ChordRest* cr1 = toChordRest(seg1->element(track));
    1303           14 :         Fraction srcF = cr1->ticks();
    1304           14 :         Fraction dstF = (tick - cr1->tick()) * cr1->staff()->timeStretch(cr1->tick());
    1305           14 :         std::vector<TDuration> dList = toDurationList(dstF, true);
    1306           14 :         if (dList.empty()) {
    1307            0 :             LOGD("Could not make durations for: %d/%d", dstF.numerator(), dstF.denominator());
    1308            0 :             return false;
    1309              :         }
    1310           14 :         size_t n = dList.size();
    1311           14 :         undoChangeChordRestLen(cr1, TDuration(dList[0]));
    1312           14 :         if (n > 1) {
    1313            1 :             Fraction crtick = cr1->endTick();
    1314            1 :             Measure* measure = tick2measure(crtick);
    1315            1 :             if (cr1->isChord()) {
    1316              :                 // split Chord
    1317            1 :                 Chord* c = toChord(cr1);
    1318            2 :                 for (size_t i = 1; i < n; ++i) {
    1319            1 :                     TDuration d = dList[i];
    1320            1 :                     Chord* c2 = addChord(crtick, d, c, true, c->tuplet());
    1321            1 :                     c = c2;
    1322            1 :                     seg1 = c->segment();
    1323            1 :                     crtick += c->actualTicks();
    1324              :                 }
    1325              :             } else {
    1326              :                 // split Rest
    1327            0 :                 Rest* r       = toRest(cr1);
    1328            0 :                 for (size_t i = 1; i < n; ++i) {
    1329            0 :                     TDuration d = dList[i];
    1330            0 :                     Rest* r2      = toRest(r->clone());
    1331            0 :                     r2->setTicks(d.fraction());
    1332            0 :                     r2->setDurationType(d);
    1333            0 :                     undoAddCR(r2, measure, crtick);
    1334            0 :                     seg1 = r2->segment();
    1335            0 :                     crtick += r2->actualTicks();
    1336              :                 }
    1337              :             }
    1338              :         }
    1339           14 :         setRest(tick, track, srcF - dstF, true, 0);
    1340              :         for (;;) {
    1341           14 :             seg1 = seg1->next1(SegmentType::ChordRest);
    1342           14 :             if (seg1 == 0) {
    1343            0 :                 LOGD("no segment");
    1344            0 :                 return false;
    1345              :             }
    1346           14 :             if (seg1->element(track)) {
    1347           14 :                 cr = toChordRest(seg1->element(track));
    1348           14 :                 break;
    1349              :             }
    1350              :         }
    1351           14 :     }
    1352              : 
    1353              :     for (;;) {
    1354          375 :         if (!cr) {
    1355            0 :             LOGD("cannot make gap");
    1356            0 :             return false;
    1357              :         }
    1358          375 :         Fraction l = makeGap(cr->segment(), cr->track(), len, nullptr, /*keepChord*/ false, deleteAnnotations);
    1359          375 :         if (l.isZero()) {
    1360            0 :             LOGD("returns zero gap");
    1361            0 :             return false;
    1362              :         }
    1363          375 :         len -= l;
    1364          375 :         if (len.isZero()) {
    1365          371 :             break;
    1366              :         }
    1367              :         // go to next cr
    1368            4 :         Measure* m = cr->measure()->nextMeasure();
    1369            4 :         if (!m) {
    1370            0 :             LOGD("EOS reached");
    1371            0 :             InsertMeasureOptions options;
    1372            0 :             options.createMeasureRests = false;
    1373            0 :             insertMeasure(ElementType::MEASURE, nullptr, options);
    1374            0 :             m = cr->measure()->nextMeasure();
    1375            0 :             if (!m) {
    1376            0 :                 LOGD("===EOS reached");
    1377            0 :                 return true;
    1378              :             }
    1379              :         }
    1380              :         // first segment in measure was removed, have to recreate it
    1381            4 :         Segment* s = m->undoGetSegment(SegmentType::ChordRest, m->tick());
    1382            4 :         track_idx_t t = cr->track();
    1383            4 :         cr = toChordRest(s->element(t));
    1384            4 :         if (!cr) {
    1385            2 :             addRest(s, t, TDuration(DurationType::V_MEASURE), 0);
    1386            2 :             cr = toChordRest(s->element(t));
    1387              :         }
    1388            4 :     }
    1389          371 :     return true;
    1390              : }
    1391              : 
    1392              : //---------------------------------------------------------
    1393              : //   splitGapToMeasureBoundaries
    1394              : //    cr  - start of gap
    1395              : //    gap - gap len in local (stretched) time
    1396              : //---------------------------------------------------------
    1397              : 
    1398           29 : std::vector<Fraction> Score::splitGapToMeasureBoundaries(ChordRest* cr, Fraction gap)
    1399              : {
    1400           29 :     std::vector<Fraction> flist;
    1401              : 
    1402           29 :     Tuplet* tuplet = cr->tuplet();
    1403           29 :     if (tuplet) {
    1404            1 :         Fraction rest = tuplet->elementsDuration();
    1405            3 :         for (DurationElement* de : tuplet->elements()) {
    1406            3 :             if (de == cr) {
    1407            1 :                 break;
    1408              :             }
    1409            2 :             rest -= de->ticks();
    1410              :         }
    1411            1 :         if (rest < gap) {
    1412            0 :             LOGD("does not fit in tuplet");
    1413              :         } else {
    1414            1 :             flist.push_back(gap);
    1415              :         }
    1416            1 :         return flist;
    1417              :     }
    1418              : 
    1419           28 :     Segment* s = cr->segment();
    1420           31 :     while (gap > Fraction(0, 1)) {
    1421           31 :         Measure* m    = s->measure();
    1422           31 :         Fraction timeStretch = cr->staff()->timeStretch(s->tick());
    1423           31 :         Fraction rest = (m->ticks() - s->rtick()) * timeStretch;
    1424           31 :         if (rest >= gap) {
    1425           28 :             flist.push_back(gap);
    1426           28 :             return flist;
    1427              :         }
    1428            3 :         flist.push_back(rest);
    1429            3 :         gap -= rest;
    1430            3 :         if (m->nextMeasure() != 0) {
    1431            3 :             m = m->nextMeasure();
    1432              :         }
    1433            3 :         s = m->first(SegmentType::ChordRest);
    1434              :     }
    1435            0 :     return flist;
    1436            0 : }
    1437              : 
    1438              : //---------------------------------------------------------
    1439              : //   changeCRlen
    1440              : //    - dstF is in local (stretched) time
    1441              : //---------------------------------------------------------
    1442              : 
    1443           52 : void Score::changeCRlen(ChordRest* cr, const TDuration& d)
    1444              : {
    1445           52 :     Fraction dstF;
    1446           52 :     if (d.type() == DurationType::V_MEASURE) {
    1447            0 :         dstF = cr->measure()->stretchedLen(cr->staff());
    1448              :     } else {
    1449           52 :         dstF = d.fraction();
    1450              :     }
    1451           52 :     changeCRlen(cr, dstF);
    1452           52 : }
    1453              : 
    1454           57 : void Score::changeCRlen(ChordRest* cr, const Fraction& dstF, bool fillWithRest)
    1455              : {
    1456           57 :     if (cr->isMeasureRepeat()) {
    1457              :         // it is not clear what should this
    1458              :         // operation mean for measure repeats.
    1459           28 :         return;
    1460              :     }
    1461           57 :     Fraction srcF(cr->ticks());
    1462           57 :     if (srcF == dstF) {
    1463            0 :         if (cr->isFullMeasureRest()) {
    1464            0 :             undoChangeChordRestLen(cr, dstF);
    1465              :         }
    1466            0 :         return;
    1467              :     }
    1468              : 
    1469              :     //keep selected element if any
    1470           57 :     EngravingItem* selElement = selection().isSingle() ? getSelectedElement() : 0;
    1471              : 
    1472           57 :     track_idx_t track = cr->track();
    1473           57 :     Tuplet* tuplet = cr->tuplet();
    1474              : 
    1475           57 :     if (srcF > dstF) {
    1476              :         //
    1477              :         // make shorter and fill with rest
    1478              :         //
    1479           28 :         deselectAll();
    1480           28 :         if (cr->isChord()) {
    1481              :             //
    1482              :             // remove ties and tremolo between 2 notes
    1483              :             //
    1484           25 :             Chord* c = toChord(cr);
    1485           25 :             if (c->tremoloTwoChord()) {
    1486            0 :                 undoRemoveElement(c->tremoloTwoChord());
    1487              :             }
    1488           50 :             for (Note* n : c->notes()) {
    1489           25 :                 if (Tie* tie = n->tieFor()) {
    1490            0 :                     if (tie->tieJumpPoints()) {
    1491            0 :                         tie->undoRemoveTiesFromJumpPoints();
    1492              :                     }
    1493            0 :                     undoRemoveElement(tie);
    1494              :                 }
    1495           25 :                 for (Spanner* sp : n->spannerFor()) {
    1496            0 :                     if (sp->isGlissando() || sp->isGuitarBend()) {
    1497            0 :                         undoRemoveElement(sp);
    1498              :                     }
    1499              :                 }
    1500              :             }
    1501              :         }
    1502           28 :         Fraction timeStretch = cr->staff()->timeStretch(cr->tick());
    1503           28 :         std::vector<TDuration> dList = toDurationList(dstF, true);
    1504           28 :         if (dList.empty()) {
    1505            0 :             LOGD("Could not make durations for: %d/%d", dstF.numerator(), dstF.denominator());
    1506            0 :             return;
    1507              :         }
    1508           28 :         undoChangeChordRestLen(cr, dList[0]);
    1509           28 :         Fraction tick2 = cr->tick();
    1510           28 :         for (unsigned i = 1; i < dList.size(); ++i) {
    1511            0 :             tick2 += actualTicks(dList[i - 1].ticks(), tuplet, timeStretch);
    1512            0 :             TDuration d = dList[i];
    1513            0 :             setRest(tick2, track, d.fraction(), (d.dots() > 0), tuplet);
    1514              :         }
    1515           28 :         if (fillWithRest) {
    1516           28 :             setRest(cr->endTick(), track, srcF - dstF, false, tuplet);
    1517              :         }
    1518              : 
    1519           28 :         if (selElement) {
    1520           21 :             select(selElement, SelectType::SINGLE, 0);
    1521              :         }
    1522           28 :         return;
    1523           28 :     }
    1524              : 
    1525              :     //
    1526              :     // make longer
    1527              :     //
    1528              :     // split required len into Measures
    1529           29 :     std::vector<Fraction> flist = splitGapToMeasureBoundaries(cr, dstF);
    1530           29 :     if (flist.empty()) {
    1531            0 :         return;
    1532              :     }
    1533              : 
    1534           29 :     deselectAll();
    1535           29 :     EngravingItem* elementToSelect = nullptr;
    1536              : 
    1537           29 :     Fraction tick  = cr->tick();
    1538           29 :     Fraction f     = dstF;
    1539           29 :     ChordRest* cr1 = cr;
    1540           29 :     Chord* oc      = 0;
    1541           29 :     Segment* s     = cr->segment();
    1542              : 
    1543           29 :     bool first = true;
    1544           59 :     for (const Fraction& f2 : flist) {
    1545           32 :         if (!cr1) {
    1546            0 :             expandVoice(s, track);
    1547            0 :             cr1 = toChordRest(s->element(track));
    1548              :         }
    1549              : 
    1550           32 :         f  -= f2;
    1551           32 :         makeGap(cr1->segment(), cr1->track(), f2, tuplet, first);
    1552              : 
    1553           32 :         if (cr->isRest()) {
    1554            4 :             Fraction timeStretch = cr1->staff()->timeStretch(cr1->tick());
    1555            4 :             Rest* r = toRest(cr);
    1556            4 :             if (first) {
    1557            1 :                 std::vector<TDuration> dList = toDurationList(f2, true);
    1558            1 :                 undoChangeChordRestLen(cr, dList[0]);
    1559            1 :                 Fraction tick2 = cr->tick();
    1560            1 :                 for (unsigned i = 1; i < dList.size(); ++i) {
    1561            0 :                     tick2 += actualTicks(dList[i - 1].ticks(), tuplet, timeStretch);
    1562            0 :                     TDuration d = dList[i];
    1563            0 :                     setRest(tick2, track, d.fraction(), (d.dots() > 0), tuplet);
    1564              :                 }
    1565            1 :             } else {
    1566            3 :                 r = setRest(tick, track, f2, false, tuplet);
    1567              :             }
    1568            4 :             if (first) {
    1569            1 :                 elementToSelect = r;
    1570            1 :                 first = false;
    1571              :             }
    1572            4 :             tick += actualTicks(f2, tuplet, timeStretch);
    1573              :         } else {
    1574           28 :             std::vector<TDuration> dList = toDurationList(f2, true);
    1575           28 :             Measure* measure             = tick2measure(tick);
    1576           28 :             Fraction etick                    = measure->tick();
    1577              : 
    1578           28 :             if (((tick - etick).ticks() % dList[0].ticks().ticks()) == 0) {
    1579           54 :                 for (TDuration du : dList) {
    1580           27 :                     Chord* cc = nullptr;
    1581           27 :                     if (oc) {
    1582            0 :                         cc = oc;
    1583            0 :                         oc = addChord(tick, du, cc, true, tuplet);
    1584              :                     } else {
    1585           27 :                         cc = toChord(cr);
    1586           27 :                         undoChangeChordRestLen(cr, du);
    1587           27 :                         oc = cc;
    1588              :                     }
    1589           27 :                     if (oc && first) {
    1590           27 :                         elementToSelect = selElement ? selElement : oc;
    1591           27 :                         first = false;
    1592              :                     }
    1593           27 :                     if (oc) {
    1594           27 :                         tick += oc->actualTicks();
    1595              :                     }
    1596              :                 }
    1597              :             } else {
    1598            2 :                 for (size_t i = dList.size(); i > 0; --i) {         // loop probably needs to be in this reverse order
    1599              :                     Chord* cc;
    1600            1 :                     if (oc) {
    1601            0 :                         cc = oc;
    1602            0 :                         oc = addChord(tick, dList[i - 1], cc, true, tuplet);
    1603              :                     } else {
    1604            1 :                         cc = toChord(cr);
    1605            1 :                         undoChangeChordRestLen(cr, dList[i - 1]);
    1606            1 :                         oc = cc;
    1607              :                     }
    1608            1 :                     if (first) {
    1609            1 :                         elementToSelect = selElement;
    1610            1 :                         first = false;
    1611              :                     }
    1612            1 :                     tick += oc->actualTicks();
    1613              :                 }
    1614              :             }
    1615           28 :         }
    1616           32 :         const Measure* m  = cr1->measure();
    1617           32 :         if (m->nextMeasure() == 0) {
    1618            2 :             if (f.isNotZero()) {
    1619            0 :                 appendMeasures(1);
    1620              :             }
    1621              :         }
    1622           32 :         const Measure* m1 = m->nextMeasure();
    1623           32 :         if (m1 == 0) {
    1624            2 :             break;
    1625              :         }
    1626           30 :         s = m1->first(SegmentType::ChordRest);
    1627           30 :         cr1 = toChordRest(s->element(track));
    1628              :     }
    1629           29 :     connectTies();
    1630              : 
    1631           29 :     if (elementToSelect) {
    1632           28 :         if (canReselectItem(elementToSelect)) {
    1633           22 :             select(elementToSelect, SelectType::SINGLE, 0);
    1634              :         }
    1635              :     }
    1636           29 : }
    1637              : 
    1638              : //---------------------------------------------------------
    1639              : //   cmdMoveRest
    1640              : //---------------------------------------------------------
    1641              : 
    1642            0 : void Score::cmdMoveRest(Rest* rest, DirectionV dir)
    1643              : {
    1644            0 :     PointF pos(rest->offset());
    1645            0 :     if (dir == DirectionV::UP) {
    1646            0 :         pos.ry() -= rest->spatium() * rest->staffType()->lineDistance().val();
    1647            0 :     } else if (dir == DirectionV::DOWN) {
    1648            0 :         pos.ry() += rest->spatium() * rest->staffType()->lineDistance().val();
    1649              :     }
    1650            0 :     rest->undoChangeProperty(Pid::OFFSET, pos);
    1651            0 : }
    1652              : 
    1653              : //---------------------------------------------------------
    1654              : //   cmdAddGrace
    1655              : ///   adds grace note of specified type to selected notes
    1656              : //---------------------------------------------------------
    1657              : 
    1658            0 : void Score::cmdAddGrace(NoteType graceType, int duration)
    1659              : {
    1660            0 :     const std::vector<EngravingItem*> copyOfElements = selection().elements();
    1661            0 :     for (EngravingItem* e : copyOfElements) {
    1662            0 :         if (e->isNote()) {
    1663            0 :             Note* n = toNote(e);
    1664            0 :             Note* graceNote = setGraceNote(n->chord(), n->pitch(), graceType, duration);
    1665            0 :             select(graceNote, SelectType::SINGLE, 0);
    1666              :         }
    1667              :     }
    1668            0 : }
    1669              : 
    1670              : //---------------------------------------------------------
    1671              : //   cmdRemoveEmptyTrailingMeasures
    1672              : //---------------------------------------------------------
    1673              : 
    1674            0 : void Score::cmdRemoveEmptyTrailingMeasures()
    1675              : {
    1676            0 :     Score* mScore = masterScore();
    1677            0 :     auto beginMeasure = mScore->firstTrailingMeasure();
    1678            0 :     if (beginMeasure) {
    1679            0 :         mScore->deleteMeasures(beginMeasure, mScore->lastMeasure());
    1680              :     }
    1681            0 : }
    1682              : 
    1683              : //---------------------------------------------------------
    1684              : //   cmdToggleLayoutBreak
    1685              : //---------------------------------------------------------
    1686              : 
    1687            0 : void Score::cmdToggleLayoutBreak(LayoutBreakType type)
    1688              : {
    1689              :     // find measure(s)
    1690            0 :     std::vector<MeasureBase*> mbl;
    1691            0 :     bool allNoBreaks = true; // NOBREAK is not removed unless every measure in selection already has one
    1692            0 :     if (selection().isRange()) {
    1693            0 :         MeasureBase* startMeasureBase = nullptr;
    1694            0 :         MeasureBase* endMeasureBase = nullptr;
    1695            0 :         if (!selection().measureBaseRange(&startMeasureBase, &endMeasureBase)) {
    1696            0 :             return;
    1697              :         }
    1698            0 :         if (!startMeasureBase || !endMeasureBase) {
    1699            0 :             return;
    1700              :         }
    1701            0 :         if (type == LayoutBreakType::NOBREAK) {
    1702              :             // add throughout the selection
    1703              :             // or remove if already on every measure
    1704            0 :             if (startMeasureBase == endMeasureBase) {
    1705            0 :                 mbl.push_back(startMeasureBase);
    1706            0 :                 allNoBreaks = startMeasureBase->noBreak();
    1707              :             } else {
    1708            0 :                 for (MeasureBase* m = startMeasureBase; m; m = m->nextMM()) {
    1709            0 :                     if (m == endMeasureBase) {
    1710            0 :                         break;
    1711              :                     }
    1712            0 :                     mbl.push_back(m);
    1713            0 :                     if (!toMeasureBase(m)->noBreak()) {
    1714            0 :                         allNoBreaks = false;
    1715              :                     }
    1716              :                 }
    1717              :             }
    1718              :         } else {
    1719              :             // toggle break on the last measure of the range
    1720            0 :             mbl.push_back(endMeasureBase);
    1721              :             // if more than one measure selected,
    1722              :             // also toggle break *before* the range (to try to fit selection on a single line)
    1723            0 :             if (startMeasureBase != endMeasureBase && startMeasureBase->prev()) {
    1724            0 :                 mbl.push_back(startMeasureBase->prev());
    1725              :             }
    1726              :         }
    1727              :     } else {
    1728            0 :         MeasureBase* mb = nullptr;
    1729            0 :         for (EngravingItem* el : selection().elements()) {
    1730            0 :             switch (el->type()) {
    1731            0 :             case ElementType::HBOX:
    1732              :             case ElementType::VBOX:
    1733              :             case ElementType::TBOX:
    1734              :             case ElementType::FBOX:
    1735            0 :                 mb = toMeasureBase(el);
    1736            0 :                 break;
    1737            0 :             default: {
    1738              :                 // find measure
    1739            0 :                 mb = toMeasure(el->findMeasure());
    1740              :                 // for start repeat, attach break to previous measure
    1741            0 :                 if (mb && el->isBarLine()) {
    1742            0 :                     BarLine* bl = toBarLine(el);
    1743            0 :                     if (bl->barLineType() == BarLineType::START_REPEAT) {
    1744            0 :                         mb = mb->prevMeasure();
    1745              :                     }
    1746              :                 }
    1747              : 
    1748            0 :                 if (mb) {
    1749            0 :                     allNoBreaks = mb->noBreak();
    1750              :                 }
    1751              :             }
    1752              :             }
    1753              :         }
    1754            0 :         if (mb) {
    1755            0 :             mbl.push_back(mb);
    1756              :         }
    1757              :     }
    1758              : 
    1759            0 :     if (type == LayoutBreakType::NOBREAK && !allNoBreaks) {
    1760            0 :         for (MeasureBase* mb : mbl) {
    1761            0 :             if (mb->systemLock()) {
    1762            0 :                 return;
    1763              :             }
    1764              :         }
    1765              :     }
    1766              : 
    1767              :     // toggle the breaks
    1768            0 :     Transaction& tx = transactionManager()->currentOrDummyTransaction();
    1769            0 :     for (MeasureBase* mb: mbl) {
    1770            0 :         bool val = false;
    1771            0 :         switch (type) {
    1772            0 :         case LayoutBreakType::LINE:
    1773            0 :             if (mb->isVBoxBase()) {
    1774            0 :                 break;
    1775              :             }
    1776            0 :             val = !mb->lineBreak();
    1777            0 :             if (val) {
    1778            0 :                 EditSystemLocks::removeSystemLocksOnAddLayoutBreak(tx, this, type, mb);
    1779            0 :                 EditPageLocks::removePageLocksOnAddLayoutBreak(tx, this, type, mb);
    1780              :             }
    1781            0 :             mb->undoSetBreak(val, type);
    1782              :             // remove page break if appropriate
    1783            0 :             if (val && mb->pageBreak()) {
    1784            0 :                 mb->undoSetBreak(false, LayoutBreakType::PAGE);
    1785              :             }
    1786            0 :             break;
    1787            0 :         case LayoutBreakType::PAGE:
    1788            0 :             val = !mb->pageBreak();
    1789            0 :             if (val) {
    1790            0 :                 EditSystemLocks::removeSystemLocksOnAddLayoutBreak(tx, this, type, mb);
    1791            0 :                 EditPageLocks::removePageLocksOnAddLayoutBreak(tx, this, type, mb);
    1792              :             }
    1793            0 :             mb->undoSetBreak(val, type);
    1794              :             // remove line break if appropriate
    1795            0 :             if (val && mb->lineBreak()) {
    1796            0 :                 mb->undoSetBreak(false, LayoutBreakType::LINE);
    1797              :             }
    1798            0 :             break;
    1799            0 :         case LayoutBreakType::SECTION:
    1800            0 :             val = !mb->sectionBreak();
    1801            0 :             if (val) {
    1802            0 :                 EditSystemLocks::removeSystemLocksOnAddLayoutBreak(tx, this, type, mb);
    1803            0 :                 EditPageLocks::removePageLocksOnAddLayoutBreak(tx, this, type, mb);
    1804              :             }
    1805            0 :             mb->undoSetBreak(val, type);
    1806            0 :             break;
    1807            0 :         case LayoutBreakType::NOBREAK:
    1808            0 :             mb->undoSetBreak(!allNoBreaks, type);
    1809              :             // remove other breaks if appropriate
    1810            0 :             if (!mb->noBreak()) {
    1811            0 :                 if (mb->pageBreak()) {
    1812            0 :                     mb->undoSetBreak(false, LayoutBreakType::PAGE);
    1813            0 :                 } else if (mb->lineBreak()) {
    1814            0 :                     mb->undoSetBreak(false, LayoutBreakType::LINE);
    1815            0 :                 } else if (mb->sectionBreak()) {
    1816            0 :                     mb->undoSetBreak(false, LayoutBreakType::SECTION);
    1817              :                 }
    1818              :             }
    1819            0 :             break;
    1820            0 :         default:
    1821            0 :             break;
    1822              :         }
    1823              :     }
    1824            0 : }
    1825              : 
    1826              : //---------------------------------------------------------
    1827              : //   cmdToggleMmrest
    1828              : //---------------------------------------------------------
    1829              : 
    1830            0 : void Score::cmdToggleMmrest()
    1831              : {
    1832            0 :     bool val = !style().styleB(Sid::createMultiMeasureRests);
    1833            0 :     deselectAll();
    1834            0 :     undoChangeStyleVal(Sid::createMultiMeasureRests, val);
    1835            0 : }
    1836              : 
    1837              : //---------------------------------------------------------
    1838              : //   cmdToggleHideEmpty
    1839              : //---------------------------------------------------------
    1840              : 
    1841            0 : void Score::cmdToggleHideEmpty()
    1842              : {
    1843            0 :     bool val = !style().styleB(Sid::hideEmptyStaves);
    1844            0 :     deselectAll();
    1845            0 :     undoChangeStyleVal(Sid::hideEmptyStaves, val);
    1846            0 : }
    1847              : 
    1848            0 : void Score::cmdSetHideStaffIfEmptyOverride(staff_idx_t staffIdx, System* system, engraving::AutoOnOff value)
    1849              : {
    1850            0 :     for (MeasureBase* mb : system->measures()) {
    1851            0 :         if (!mb->isMeasure()) {
    1852            0 :             continue;
    1853              :         }
    1854            0 :         undo(new ChangeMStaffHideIfEmpty(engraving::toMeasure(mb), staffIdx, value));
    1855              :     }
    1856            0 : }
    1857              : 
    1858              : //---------------------------------------------------------
    1859              : //   cmdToggleAutoplace
    1860              : //---------------------------------------------------------
    1861              : 
    1862            0 : void Score::cmdToggleAutoplace(bool all)
    1863              : {
    1864            0 :     if (all) {
    1865            0 :         bool val = !style().styleB(Sid::autoplaceEnabled);
    1866            0 :         undoChangeStyleVal(Sid::autoplaceEnabled, val);
    1867            0 :         setLayoutAll();
    1868              :     } else {
    1869            0 :         std::set<EngravingItem*> spanners;
    1870            0 :         for (EngravingItem* e : selection().elements()) {
    1871            0 :             if (e->isSpannerSegment()) {
    1872            0 :                 if (EngravingObject* ee = e->propertyDelegate(Pid::AUTOPLACE)) {
    1873            0 :                     e = toEngravingItem(ee);
    1874              :                 }
    1875              :                 // spanner segments may each have their own autoplace setting
    1876              :                 // but if they delegate to spanner, only toggle once
    1877            0 :                 if (e->isSpanner()) {
    1878            0 :                     if (muse::contains(spanners, e)) {
    1879            0 :                         continue;
    1880              :                     }
    1881            0 :                     spanners.insert(e);
    1882              :                 }
    1883              :             }
    1884            0 :             PropertyFlags pf = e->propertyFlags(Pid::AUTOPLACE);
    1885            0 :             if (pf == PropertyFlags::STYLED) {
    1886            0 :                 pf = PropertyFlags::UNSTYLED;
    1887              :             }
    1888            0 :             e->undoChangeProperty(Pid::AUTOPLACE, !e->getProperty(Pid::AUTOPLACE).toBool(), pf);
    1889              :         }
    1890            0 :     }
    1891            0 : }
    1892              : }
        

Generated by: LCOV version 2.0-1