LCOV - code coverage report
Current view: top level - src/engraving/editing - noteinput.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 30.6 % 1035 317
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) 2026 MuseScore Limited
       9              :  *
      10              :  * This program is free software: you can redistribute it and/or modify
      11              :  * it under the terms of the GNU General Public License version 3 as
      12              :  * published by the Free Software Foundation.
      13              :  *
      14              :  * This program is distributed in the hope that it will be useful,
      15              :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      16              :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
      17              :  * GNU General Public License for more details.
      18              :  *
      19              :  * You should have received a copy of the GNU General Public License
      20              :  * along with this program. If not, see <https://www.gnu.org/licenses/>.
      21              :  */
      22              : 
      23              : #include "noteinput.h"
      24              : 
      25              : #include <algorithm>
      26              : #include <iterator>
      27              : #include <tuple>
      28              : 
      29              : #include "translation.h"
      30              : 
      31              : #include "editmeasures.h"
      32              : #include "editnote.h"
      33              : #include "inserttime.h"
      34              : #include "mscoreview.h"
      35              : #include "regroup.h"
      36              : #include "transaction/transaction.h"
      37              : #include "transpose.h"
      38              : 
      39              : #include "../dom/accidental.h"
      40              : #include "../dom/chord.h"
      41              : #include "../dom/chordline.h"
      42              : #include "../dom/drumset.h"
      43              : #include "../dom/durationtype.h"
      44              : #include "../dom/excerpt.h"
      45              : #include "../dom/factory.h"
      46              : #include "../dom/input.h"
      47              : #include "../dom/masterscore.h"
      48              : #include "../dom/measure.h"
      49              : #include "../dom/measurerepeat.h"
      50              : #include "../dom/note.h"
      51              : #include "../dom/noteval.h"
      52              : #include "../dom/part.h"
      53              : #include "../dom/range.h"
      54              : #include "../dom/rest.h"
      55              : #include "../dom/score.h"
      56              : #include "../dom/segment.h"
      57              : #include "../dom/select.h"
      58              : #include "../dom/slur.h"
      59              : #include "../dom/staff.h"
      60              : #include "../dom/stafftype.h"
      61              : #include "../dom/stringdata.h"
      62              : #include "../dom/tie.h"
      63              : #include "../dom/tremolotwochord.h"
      64              : #include "../dom/tuplet.h"
      65              : #include "../dom/utils.h"
      66              : 
      67              : #include "navigation.h"
      68              : 
      69              : #include "log.h"
      70              : 
      71              : using namespace muse;
      72              : using namespace mu;
      73              : using namespace mu::engraving;
      74              : 
      75              : //---------------------------------------------------------
      76              : //   resolveNoteInputParams
      77              : //---------------------------------------------------------
      78              : 
      79            0 : bool NoteInput::resolveNoteInputParams(const Score* score, int note, bool addFlag, NoteInputParams& out)
      80              : {
      81            0 :     const InputState& is = score->inputState();
      82              : 
      83              :     //! NOTE: Drumset params should be defined explicitly (see NotationViewInputController::tryPercussionShortcut)
      84            0 :     if (!is.isValid() || is.drumset()) {
      85            0 :         return false;
      86              :     }
      87              : 
      88            0 :     int octave = 4;
      89              : 
      90              :     static const int tab[] = { 0, 2, 4, 5, 7, 9, 11 };
      91              : 
      92              :     // if adding notes, add above the upNote of the current chord
      93            0 :     EngravingItem* el = score->selection().element();
      94            0 :     if (addFlag && el && el->isNote()) {
      95            0 :         Chord* chord = toNote(el)->chord();
      96            0 :         Note* n      = chord->upNote();
      97            0 :         int tpc = n->tpc();
      98            0 :         octave = (n->epitch() - int(tpc2alter(tpc))) / PITCH_DELTA_OCTAVE;
      99            0 :         if (note <= tpc2step(tpc)) {
     100            0 :             octave++;
     101              :         }
     102              :     } else {
     103            0 :         int curPitch = 60;
     104            0 :         if (is.segment()) {
     105            0 :             const Staff* staff = score->staff(is.track() / VOICES);
     106            0 :             Segment* seg = is.segment()->prev1(SegmentType::ChordRest | SegmentType::Clef | SegmentType::HeaderClef);
     107            0 :             while (seg) {
     108            0 :                 if (seg->isChordRestType()) {
     109            0 :                     EngravingItem* p = seg->element(is.track());
     110            0 :                     if (p && p->isChord()) {
     111            0 :                         Note* n = toChord(p)->downNote();
     112              :                         // forget any accidental and/or adjustment due to key signature
     113            0 :                         curPitch = n->epitch() - static_cast<int>(tpc2alter(n->tpc()));
     114            0 :                         break;
     115              :                     }
     116            0 :                 } else if (seg->isClefType() || seg->isHeaderClefType()) {
     117            0 :                     EngravingItem* p = seg->element(trackZeroVoice(is.track()));                  // clef on voice 1
     118            0 :                     if (p && p->isClef()) {
     119            0 :                         Clef* clef = toClef(p);
     120              :                         // check if it's an actual change or just a courtesy
     121            0 :                         ClefType ctb = staff->clef(clef->tick() - Fraction::eps());
     122            0 :                         if (ctb != clef->clefType() || clef->tick().isZero()) {
     123            0 :                             curPitch = line2pitch(4, clef->clefType(), Key::C);                     // C 72 for treble clef
     124            0 :                             break;
     125              :                         }
     126              :                     }
     127              :                 }
     128            0 :                 seg = seg->prev1MM(SegmentType::ChordRest | SegmentType::Clef | SegmentType::HeaderClef);
     129              :             }
     130            0 :             octave = curPitch / 12;
     131              :         }
     132              : 
     133            0 :         int delta = octave * 12 + tab[note] - curPitch;
     134            0 :         if (delta > 6) {
     135            0 :             --octave;
     136            0 :         } else if (delta < -6) {
     137            0 :             ++octave;
     138              :         }
     139              :     }
     140              : 
     141            0 :     out.step = octave * 7 + note;
     142            0 :     return true;
     143              : }
     144              : 
     145              : //---------------------------------------------------------
     146              : //   noteVal
     147              : //---------------------------------------------------------
     148              : 
     149            0 : NoteVal NoteInput::noteVal(const Score* score, int pitch, staff_idx_t staffIdx, bool allowTransposition)
     150              : {
     151            0 :     NoteVal nval(pitch);
     152              : 
     153            0 :     const Staff* st = score->staff(staffIdx);
     154            0 :     if (!st) {
     155            0 :         return nval;
     156              :     }
     157              : 
     158            0 :     bool concertPitch = score->style().styleB(Sid::concertPitch);
     159            0 :     Interval v = st->part()->instrument(score->inputState().tick())->transpose();
     160              : 
     161              :     // If an accidental is set in the input state, use it as a hint for the pitch spelling
     162            0 :     if (AccidentalType at = score->inputState().accidentalType(); at == AccidentalType::FLAT || at == AccidentalType::SHARP) {
     163            0 :         Prefer prefer = at == AccidentalType::SHARP ? Prefer::SHARPS : Prefer::FLATS;
     164            0 :         if (concertPitch || v.isZero()) {
     165              :             // Note: using Key::C always and ignoring actual key signature. Otherwise, flat mode would still use sharps
     166              :             // sometimes if they're in the key, and vice versa, which seems contrary to the intent of the hint.
     167            0 :             nval.tpc1 = pitch2tpc(nval.pitch, Key::C, prefer);
     168            0 :             Interval vFlipped = v;
     169            0 :             vFlipped.flip();
     170            0 :             nval.tpc2 = Transpose::transposeTpc(nval.tpc1, vFlipped, true);
     171              :         } else {
     172              :             // Spell the transposed pitch first, then convert to concert pitch
     173            0 :             int writtenPitch = nval.pitch;
     174            0 :             if (!allowTransposition) {
     175            0 :                 writtenPitch -= v.chromatic;
     176              :             }
     177            0 :             nval.tpc2 = pitch2tpc(writtenPitch, Key::C, prefer);
     178            0 :             nval.tpc1 = Transpose::transposeTpc(nval.tpc2, v, true);
     179              :         }
     180              :     }
     181              : 
     182              :     // if transposing, interpret MIDI pitch as representing desired written pitch
     183              :     // set pitch based on corresponding sounding pitch
     184            0 :     if (!concertPitch && allowTransposition) {
     185            0 :         nval.pitch += v.chromatic;
     186              :     }
     187              : 
     188            0 :     return nval;
     189              : }
     190              : 
     191              : //---------------------------------------------------------
     192              : //   noteValForPosition
     193              : //---------------------------------------------------------
     194              : 
     195           63 : NoteVal NoteInput::noteValForPosition(const Score* score, Position pos, AccidentalType at, bool& error)
     196              : {
     197           63 :     const InputState& is = score->inputState();
     198              : 
     199           63 :     error           = false;
     200           63 :     const Segment* s = pos.segment;
     201           63 :     int line        = pos.line;
     202           63 :     Fraction tick   = s->tick();
     203           63 :     staff_idx_t staffIdx = pos.staffIdx;
     204           63 :     const Staff* st = score->staff(staffIdx);
     205           63 :     ClefType clef   = st->clef(tick);
     206           63 :     const Instrument* instr = st->part()->instrument(s->tick());
     207           63 :     NoteVal nval;
     208           63 :     const StringData* stringData = nullptr;
     209              : 
     210              :     // pitched/unpitched note entry depends on instrument (override StaffGroup)
     211           63 :     StaffGroup staffGroup = st->staffType(tick)->group();
     212           63 :     if (staffGroup != StaffGroup::TAB) {
     213           62 :         staffGroup = instr->useDrumset() ? StaffGroup::PERCUSSION : StaffGroup::STANDARD;
     214              :     }
     215              : 
     216           63 :     if (staffGroup != StaffGroup::PERCUSSION) {
     217           63 :         stringData = st->part()->stringData(s->tick(), st->idx());
     218              :     }
     219              : 
     220           63 :     switch (staffGroup) {
     221            0 :     case StaffGroup::PERCUSSION: {
     222            0 :         if (is.rest()) {
     223            0 :             break;
     224              :         }
     225            0 :         const Drumset* ds = instr->drumset();
     226            0 :         nval.pitch = is.drumNote();
     227            0 :         if (!ds->isValid(nval.pitch) || ds->line(nval.pitch) != line) {
     228              :             // Drum note from input state is not valid - fall back to the first valid pitch for this line...
     229            0 :             const int defaultPitch = ds->defaultPitchForLine(line);
     230            0 :             if (ds->isValid(defaultPitch)) {
     231            0 :                 nval.pitch = defaultPitch;
     232              :             }
     233              :         }
     234            0 :         if (nval.pitch < 0) {
     235            0 :             error = true;
     236            0 :             return nval;
     237              :         }
     238            0 :         nval.headGroup = ds->noteHead(nval.pitch);
     239            0 :         if (nval.headGroup == NoteHeadGroup::HEAD_INVALID) {
     240            0 :             error = true;
     241            0 :             return nval;
     242              :         }
     243            0 :         break;
     244              :     }
     245            1 :     case StaffGroup::TAB: {
     246            1 :         if (is.rest()) {
     247            0 :             return nval;
     248              :         }
     249            1 :         line = st->staffType(tick)->visualStringToPhys(line);
     250            1 :         if (line < 0 || line >= static_cast<int>(stringData->strings())) {
     251            0 :             error = true;
     252            0 :             return nval;
     253              :         }
     254              :         // build a default NoteVal for that string
     255            1 :         nval.string = line;
     256            1 :         if (pos.fret != INVALID_FRET_INDEX) {                  // if a fret is given, use it
     257            1 :             nval.fret = pos.fret;
     258              :         } else {                                      // if no fret, use 0 as default
     259            0 :             nval.fret = 0;
     260              :         }
     261              :         // reduce within fret limit
     262            1 :         if (nval.fret > stringData->frets()) {
     263            0 :             nval.fret = stringData->frets();
     264              :         }
     265              :         // for open strings, only accepts fret 0 (strings in StringData are from bottom to top)
     266            1 :         size_t strgDataIdx = stringData->strings() - line - 1;
     267            1 :         if (nval.fret > 0 && stringData->stringList().at(strgDataIdx).open) {
     268            0 :             nval.fret = 0;
     269              :         }
     270            1 :         nval.pitch = stringData->getPitch(line, nval.fret, st, pos.segment->tick());
     271            1 :         break;
     272              :     }
     273              : 
     274           62 :     case StaffGroup::STANDARD:
     275              :     case StaffGroup::JIANPU:
     276              :     {
     277              :         AccidentalVal acci
     278           62 :             = (at == AccidentalType::NONE ? s->measure()->findAccidental(s, staffIdx, line, error) : Accidental::subtype2value(at));
     279           62 :         if (error) {
     280           17 :             return nval;
     281              :         }
     282           45 :         int step           = absStep(line, clef);
     283           45 :         int octave         = step / 7;
     284           45 :         nval.pitch         = step2pitch(step) + octave * 12 + int(acci);
     285           45 :         if (score->style().styleB(Sid::concertPitch)) {
     286            0 :             nval.tpc1 = step2tpc(step % 7, acci);
     287              :         } else {
     288           45 :             nval.pitch += instr->transpose().chromatic;
     289           45 :             nval.tpc2 = step2tpc(step % 7, acci);
     290           45 :             Interval v = st->transpose(tick);
     291           45 :             if (v.isZero()) {
     292           44 :                 nval.tpc1 = nval.tpc2;
     293              :             } else {
     294            1 :                 nval.tpc1 = Transpose::transposeTpc(nval.tpc2, v, true);
     295              :             }
     296              :         }
     297           45 :         stringData->convertPitch(nval.pitch, st, pos.segment->tick(), &nval.string, &nval.fret);
     298              :     }
     299           45 :     break;
     300              :     }
     301           46 :     return nval;
     302              : }
     303              : 
     304              : //---------------------------------------------------------
     305              : //   addNote from NoteVal
     306              : //---------------------------------------------------------
     307              : 
     308           40 : Note* NoteInput::addNote(Transaction&, Score* score, Chord* chord, const NoteVal& noteVal, bool forceAccidental,
     309              :                          const std::set<SymId>& articulationIds, InputState* externalInputState)
     310              : {
     311           40 :     InputState& is = externalInputState ? (*externalInputState) : score->inputState();
     312              : 
     313           40 :     Note* note = Factory::createNote(chord);
     314           40 :     note->setTrack(chord->track());
     315           40 :     note->setNval(noteVal);
     316           40 :     score->undoAddElement(note);
     317           40 :     if (forceAccidental) {
     318            0 :         int tpc = score->style().styleB(Sid::concertPitch) ? noteVal.tpc1 : noteVal.tpc2;
     319            0 :         AccidentalVal alter = tpc2alter(tpc);
     320            0 :         AccidentalType at = Accidental::value2subtype(alter);
     321            0 :         Accidental* a = Factory::createAccidental(note);
     322            0 :         a->setAccidentalType(at);
     323            0 :         a->setRole(AccidentalRole::USER);
     324            0 :         score->undoAddElement(a);
     325              :     }
     326              : 
     327           40 :     if (!articulationIds.empty()) {
     328            0 :         chord->updateArticulations(articulationIds);
     329              :     }
     330              : 
     331           40 :     score->setPlayNote(true);
     332           40 :     score->setPlayChord(true);
     333              : 
     334           40 :     if (externalInputState) {
     335            0 :         is.setTrack(note->track());
     336            0 :         is.setLastSegment(is.segment());
     337            0 :         is.setSegment(note->chord()->segment());
     338              :     } else {
     339           40 :         score->select(note, SelectType::SINGLE, 0);
     340              :     }
     341              : 
     342           40 :     if (!chord->staff()->isTabStaff(chord->tick())) {
     343           40 :         NoteEntryMethod entryMethod = is.noteEntryMethod();
     344           40 :         if (entryMethod != NoteEntryMethod::REPITCH && entryMethod != NoteEntryMethod::REALTIME_AUTO
     345           40 :             && entryMethod != NoteEntryMethod::REALTIME_MANUAL) {
     346           40 :             is.moveToNextInputPos();
     347              :         }
     348              :     }
     349           40 :     return note;
     350              : }
     351              : 
     352            2 : Note* NoteInput::addNoteToTiedChord(Transaction& tx, Score* score, Chord* chord, const NoteVal& noteVal, bool forceAccidental,
     353              :                                     const std::set<SymId>& articulationIds)
     354              : {
     355            2 :     IF_ASSERT_FAILED(!chord->notes().empty()) {
     356            0 :         return nullptr;
     357              :     };
     358            2 :     Note* referenceNote = chord->notes().at(0);
     359              : 
     360              :     while (true) {
     361              :         // don't add note if it is already part of tied notes previously
     362            4 :         if (referenceNote->chord()->findNote(noteVal.pitch)) {
     363            2 :             return nullptr;
     364              :         }
     365            2 :         if (!referenceNote->tieBack() || referenceNote->incomingPartialTie()) {
     366            0 :             break;
     367              :         }
     368            2 :         referenceNote = referenceNote->tieBack()->startNote();
     369              :     }
     370              : 
     371            0 :     Tie* tie = nullptr;
     372            0 :     Note* newNote = nullptr;
     373              : 
     374            0 :     while (referenceNote->tieFor()) {
     375            0 :         chord = referenceNote->chord();
     376            0 :         newNote = addNote(tx, score, chord, noteVal, forceAccidental, articulationIds);
     377            0 :         if (!newNote) {
     378            0 :             return nullptr;
     379              :         }
     380            0 :         if (tie) {
     381            0 :             tie->setEndNote(newNote);
     382            0 :             tie->setTick2(newNote->tick());
     383            0 :             newNote->setTieBack(tie);
     384            0 :             score->undoAddElement(tie);
     385              :         }
     386              : 
     387            0 :         tie = Factory::createTie(newNote);
     388            0 :         tie->setStartNote(newNote);
     389            0 :         tie->setTick(newNote->tick());
     390            0 :         tie->setTrack(newNote->track());
     391            0 :         newNote->setTieFor(tie);
     392              : 
     393            0 :         if (!referenceNote->tieFor()->endNote()) {
     394            0 :             break;
     395              :         }
     396              : 
     397            0 :         referenceNote = referenceNote->tieFor()->endNote();
     398              :     }
     399              : 
     400            0 :     chord = referenceNote->chord();
     401            0 :     newNote = addNote(tx, score, chord, noteVal, forceAccidental, articulationIds);
     402              : 
     403            0 :     if (!newNote) {
     404            0 :         return nullptr;
     405              :     }
     406              : 
     407            0 :     if (tie) {
     408            0 :         tie->setEndNote(newNote);
     409            0 :         tie->setTick2(newNote->tick());
     410            0 :         newNote->setTieBack(tie);
     411            0 :         score->undoAddElement(tie);
     412              :     }
     413              : 
     414            0 :     score->connectTies();
     415              : 
     416            0 :     return newNote;
     417              : }
     418              : 
     419              : //---------------------------------------------------------
     420              : //   addPitch
     421              : //---------------------------------------------------------
     422              : 
     423          119 : Note* NoteInput::addPitch(Transaction& tx, Score* score, NoteVal& nval, bool addFlag, InputState* externalInputState)
     424              : {
     425          119 :     InputState& is = externalInputState ? (*externalInputState) : score->inputState();
     426              : 
     427          119 :     if (addFlag) {
     428           12 :         const Segment* lastSegment = is.lastSegment();
     429           12 :         IF_ASSERT_FAILED(lastSegment) {
     430            0 :             return nullptr;
     431              :         }
     432           12 :         ChordRest* c = toChordRest(lastSegment->element(is.track()));
     433           12 :         if (!c || !c->isChord()) {
     434            0 :             LOGD("NoteInput::addPitch: cr %s", c ? c->typeName() : "zero");
     435            0 :             return nullptr;
     436              :         }
     437           12 :         return addPitchToChord(tx, score, nval, toChord(c), externalInputState);
     438              :     }
     439              : 
     440          107 :     if (is.beyondScore()) {
     441            0 :         score->appendMeasures(1);
     442            0 :         is.moveToNextInputPos();
     443              :     }
     444              : 
     445          107 :     score->expandVoice(is.segment(), is.track());
     446              : 
     447              :     // insert note
     448          107 :     DirectionV stemDirection = DirectionV::AUTO;
     449          107 :     track_idx_t track = is.track();
     450          107 :     if (is.drumset()) {
     451            0 :         const Drumset* ds = is.drumset();
     452            0 :         if (!ds->isValid(nval.pitch)) {
     453            0 :             return nullptr;
     454              :         }
     455              : 
     456            0 :         nval.headGroup    = ds->noteHead(nval.pitch);
     457            0 :         stemDirection     = ds->stemDirection(nval.pitch);
     458            0 :         track             = ds->voice(nval.pitch) + (is.track() / VOICES) * VOICES;
     459            0 :         is.setTrack(track);
     460            0 :         score->expandVoice(is.segment(), is.track());
     461              :     }
     462              : 
     463          107 :     if (!is.cr()) {
     464            0 :         ChordRest* prevCr = is.segment()->nextChordRest(is.track(), /*backwards*/ true, /*stopAtMeasureBoundary*/ true);
     465            0 :         if (prevCr && prevCr->endTick() > is.tick()) {
     466            0 :             const InputState inputStateToRestore = is; // because truncateChordRest will alter the input state
     467            0 :             truncateChordRest(tx, score, prevCr, is.tick(), /*fillWithRest*/ true);
     468            0 :             is = inputStateToRestore;
     469            0 :         }
     470              :     }
     471              : 
     472          107 :     Measure* measure = is.segment()->measure();
     473          107 :     if (measure->isMeasureRepeatGroup(track2staff(track))) {
     474            0 :         MeasureRepeat* mr = measure->measureRepeatElement(track2staff(track));
     475            0 :         score->deleteItem(mr); // resets any measures related to mr
     476              :     }
     477          107 :     Fraction duration;
     478          107 :     if (is.usingNoteEntryMethod(NoteEntryMethod::REALTIME_AUTO) || is.usingNoteEntryMethod(NoteEntryMethod::REALTIME_MANUAL)) {
     479              :         // FIXME: truncate duration at barline in real-time modes.
     480              :         //   The user might try to enter a duration that is too long to fit in the remaining space in the measure.
     481              :         //   We could split the duration at the barline and continue into the next bar, but this would create extra
     482              :         //   notes, extra ties, and extra pain. Instead, we simply truncate the duration at the barline.
     483            0 :         Fraction ticks2measureEnd = is.segment()->measure()->ticks() - is.segment()->rtick();
     484            0 :         duration = is.duration().fraction() > ticks2measureEnd ? ticks2measureEnd : is.duration().fraction();
     485              :     } else {
     486          107 :         duration = is.duration().fraction();
     487              :     }
     488          107 :     Note* note = nullptr;
     489          107 :     Note* lastTiedNote = nullptr;
     490          107 :     if (is.usingNoteEntryMethod(NoteEntryMethod::REPITCH) && is.cr()->isChord()) {
     491            0 :         Chord* chord = toChord(is.cr());
     492            0 :         std::tie(note, lastTiedNote) = repitchReplaceNote(tx, score, chord, nval);  // the add (not replace) case was handled above
     493          107 :     } else if (!is.usingNoteEntryMethod(NoteEntryMethod::REPITCH)) {
     494          107 :         Segment* seg = score->setNoteRest(
     495              :             is.segment(), track, nval, duration, stemDirection, /* forceAccidental */ false, is.articulationIds(), /* rhythmic */ false,
     496              :             externalInputState);
     497          107 :         EngravingItem* chordItem = seg ? seg->element(track) : nullptr;
     498          107 :         if (chordItem && chordItem->isChord()) {
     499          107 :             note = toChord(chordItem)->upNote();
     500              :         }
     501              :     }
     502              : 
     503          107 :     if (is.slur()) {
     504              :         //
     505              :         // extend slur
     506              :         //
     507            0 :         ChordRest* e = score->searchNote(is.tick(), is.track());
     508            0 :         EngravingItem* ee = is.slur()->startElement();
     509            0 :         if (e && ee) {
     510            0 :             Fraction stick = Fraction(0, 1);
     511            0 :             if (ee->isChordRest()) {
     512            0 :                 stick = toChordRest(ee)->tick();
     513            0 :             } else if (ee->isNote()) {
     514            0 :                 stick = toNote(ee)->chord()->tick();
     515              :             }
     516            0 :             if (stick == e->tick()) {
     517            0 :                 is.slur()->setTick(stick);
     518            0 :                 is.slur()->setStartElement(e);
     519              :             } else {
     520            0 :                 is.slur()->setTick2(e->tick());
     521            0 :                 is.slur()->setEndElement(e);
     522              :             }
     523            0 :         } else {
     524            0 :             LOGD("addPitch: cannot find slur note");
     525              :         }
     526              :     }
     527          107 :     if (is.usingNoteEntryMethod(NoteEntryMethod::REPITCH)) {
     528              :         // move cursor to next note, but skip tied notes (they were already repitched above)
     529            0 :         ChordRest* next = lastTiedNote ? Navigation::nextChordRest(lastTiedNote->chord()) : Navigation::nextChordRest(is.cr());
     530            0 :         while (next && !next->isChord()) {
     531            0 :             next = Navigation::nextChordRest(next);
     532              :         }
     533            0 :         if (next) {
     534            0 :             is.moveInputPos(next->segment());
     535              :         }
     536              :     } else {
     537          107 :         NoteEntryMethod entryMethod = is.noteEntryMethod();
     538          107 :         if (entryMethod != NoteEntryMethod::REALTIME_AUTO && entryMethod != NoteEntryMethod::REALTIME_MANUAL) {
     539          107 :             is.moveToNextInputPos();
     540              :         }
     541              :     }
     542          107 :     return note;
     543              : }
     544              : 
     545           12 : Note* NoteInput::addPitchToChord(Transaction& tx, Score* score, NoteVal& nval, Chord* chord, InputState* externalInputState,
     546              :                                  bool forceAccidental)
     547              : {
     548           12 :     IF_ASSERT_FAILED(chord) {
     549            0 :         return nullptr;
     550              :     }
     551              : 
     552           12 :     InputState& is = externalInputState ? (*externalInputState) : score->inputState();
     553              : 
     554           12 :     auto isTied = [](const Chord* ch) {
     555           12 :         if (ch->notes().empty()) {
     556            0 :             return false;
     557              :         }
     558           12 :         Note* n = ch->notes().at(0);
     559           12 :         return (n->tieFor() && !n->tieFor()->isLaissezVib()) || n->tieBack();
     560              :     };
     561              : 
     562           12 :     Note* note = nullptr;
     563           12 :     if (isTied(chord)) {
     564            2 :         note = addNoteToTiedChord(tx, score, chord, nval, forceAccidental);
     565            2 :         if (!note) {
     566            2 :             note = addNote(tx, score, chord, nval, forceAccidental, /* articulationIds */ {}, externalInputState);
     567              :         }
     568              :     } else {
     569           10 :         note = addNote(tx, score, chord, nval, forceAccidental, /* articulationIds */ {}, externalInputState);
     570              :     }
     571              : 
     572           12 :     if (is.usingNoteEntryMethod(NoteEntryMethod::REPITCH)) {
     573              :         // move cursor to next note
     574            0 :         ChordRest* next = Navigation::nextChordRest(note->chord());
     575            0 :         while (next && !next->isChord()) {
     576            0 :             next = Navigation::nextChordRest(next);
     577              :         }
     578            0 :         if (next) {
     579            0 :             is.moveInputPos(next->segment());
     580              :         }
     581           12 :     } else if (is.lastSegment() == is.segment()) {
     582            0 :         NoteEntryMethod entryMethod = is.noteEntryMethod();
     583            0 :         if (entryMethod != NoteEntryMethod::REALTIME_AUTO && entryMethod != NoteEntryMethod::REALTIME_MANUAL) {
     584            0 :             is.moveToNextInputPos();
     585              :         }
     586              :     }
     587              : 
     588           12 :     return note;
     589              : }
     590              : 
     591              : //---------------------------------------------------------
     592              : //   addMidiPitch
     593              : //---------------------------------------------------------
     594              : 
     595            0 : Note* NoteInput::addMidiPitch(Transaction& tx, Score* score, int pitch, bool addFlag, bool allowTransposition)
     596              : {
     597            0 :     NoteVal nval = noteVal(score, pitch, score->inputState().staffIdx(), allowTransposition);
     598            0 :     return addPitch(tx, score, nval, addFlag);
     599              : }
     600              : 
     601              : //---------------------------------------------------------
     602              : //   addTiedMidiPitch
     603              : //---------------------------------------------------------
     604              : 
     605            0 : Note* NoteInput::addTiedMidiPitch(Transaction& tx, Score* score, int pitch, bool addFlag, Chord* prevChord, bool allowTransposition)
     606              : {
     607            0 :     Note* n = addMidiPitch(tx, score, pitch, addFlag, allowTransposition);
     608            0 :     if (prevChord) {
     609            0 :         Note* nn = prevChord->findNote(n->pitch());
     610            0 :         if (nn) {
     611            0 :             Tie* tie = Factory::createTie(nn);
     612            0 :             tie->setStartNote(nn);
     613            0 :             tie->setEndNote(n);
     614            0 :             tie->setTick(tie->startNote()->tick());
     615            0 :             tie->setTick2(tie->endNote()->tick());
     616            0 :             tie->setTrack(n->track());
     617            0 :             n->setTieBack(tie);
     618            0 :             nn->setTieFor(tie);
     619            0 :             score->undoAddElement(tie);
     620              :         }
     621              :     }
     622            0 :     return n;
     623              : }
     624              : 
     625              : //---------------------------------------------------------
     626              : //   repitchReplaceNote
     627              : //---------------------------------------------------------
     628              : 
     629            0 : std::pair<Note*, Note*> NoteInput::repitchReplaceNote(Transaction&, Score* score, Chord* chord, const NoteVal& nval,
     630              :                                                       bool forceAccidental)
     631              : {
     632            0 :     Note* note = Factory::createNote(chord);
     633            0 :     note->setTrack(chord->track());
     634            0 :     note->setNval(nval);
     635              : 
     636            0 :     Note* firstTiedNote = nullptr;
     637            0 :     Note* lastTiedNote = note;
     638            0 :     ChordLine* chordLine = nullptr;
     639            0 :     std::vector<Note*> notes = chord->notes();
     640              :     // break all ties into current chord
     641              :     // these will exist only if user explicitly moved cursor to a tied-into note
     642              :     // in ordinary use, cursor will automatically skip past these during note entry
     643            0 :     for (Note* n : notes) {
     644            0 :         if (n->tieBack()) {
     645            0 :             score->undoRemoveElement(n->tieBack());
     646              :         }
     647              :     }
     648              :     // Keep first chordline only
     649            0 :     chordLine = chord->chordLine() ? chord->chordLine()->clone() : nullptr;
     650            0 :     std::vector<EngravingItem*> chordEls = chord->el();
     651            0 :     for (EngravingItem* e : chordEls) {
     652            0 :         if (e->isChordLine()) {
     653            0 :             score->undoRemoveElement(e);
     654              :         }
     655              :     }
     656              :     // for the first note of the chord only, preserve ties by changing pitch of all forward notes
     657              :     // the tie forward itself will be added later
     658              :     // multi-note chords get reduced to single note chords anyhow since we remove the old notes below
     659            0 :     if (notes.front()->tieFor()) {
     660            0 :         Note* tn = notes.front()->tieFor()->endNote();
     661            0 :         while (tn) {
     662            0 :             Chord* tc = tn->chord();
     663            0 :             if (tc->notes().size() != 1) {
     664            0 :                 std::vector<Note*> notesToRemove;
     665            0 :                 for (Note* n : tc->notes()) {
     666            0 :                     if (n != tn) {
     667            0 :                         notesToRemove.push_back(n);
     668              :                     }
     669              :                 }
     670            0 :                 for (Note* n : notesToRemove) {
     671            0 :                     score->undoRemoveElement(n);
     672              :                 }
     673            0 :                 assert(tc->notes().size() == 1 && tc->notes().front() == tn);
     674            0 :             }
     675            0 :             if (!firstTiedNote) {
     676            0 :                 firstTiedNote = tn;
     677              :             }
     678            0 :             lastTiedNote = tn;
     679            0 :             EditNote::undoChangePitch(score, tn, note->pitch(), note->tpc1(), note->tpc2());
     680            0 :             if (tn->tieFor()) {
     681            0 :                 tn = tn->tieFor()->endNote();
     682              :             } else {
     683            0 :                 break;
     684              :             }
     685              :         }
     686              :     }
     687              :     // remove all notes from chord
     688              :     // the new note will be added below
     689            0 :     while (!chord->notes().empty()) {
     690            0 :         score->undoRemoveElement(chord->notes().front());
     691              :     }
     692            0 :     notes.clear();  // get rid of vector full of dangling pointers!
     693              : 
     694              :     // add new note to chord
     695            0 :     score->undoAddElement(note);
     696              : 
     697            0 :     if (chordLine) {
     698            0 :         chordLine->setNote(note);
     699            0 :         score->undoAddElement(chordLine);
     700              :     }
     701              : 
     702            0 :     if (forceAccidental) {
     703            0 :         int tpc = score->style().styleB(Sid::concertPitch) ? nval.tpc1 : nval.tpc2;
     704            0 :         AccidentalVal alter = tpc2alter(tpc);
     705            0 :         AccidentalType at = Accidental::value2subtype(alter);
     706            0 :         Accidental* a = Factory::createAccidental(note);
     707            0 :         a->setAccidentalType(at);
     708            0 :         a->setRole(AccidentalRole::USER);
     709            0 :         score->undoAddElement(a);
     710              :     }
     711            0 :     score->setPlayNote(true);
     712              :     // recreate tie forward if there is a note to tie to
     713              :     // one-sided ties will not be recreated
     714            0 :     if (firstTiedNote) {
     715            0 :         Tie* tie = Factory::createTie(note);
     716            0 :         tie->setStartNote(note);
     717            0 :         tie->setEndNote(firstTiedNote);
     718            0 :         tie->setTick(tie->startNote()->tick());
     719            0 :         tie->setTick2(tie->endNote()->tick());
     720            0 :         tie->setTrack(note->track());
     721            0 :         score->undoAddElement(tie);
     722              :     }
     723            0 :     score->select(lastTiedNote);
     724              : 
     725            0 :     return { note, lastTiedNote };
     726            0 : }
     727              : 
     728              : //---------------------------------------------------------
     729              : //   where the entry points enter the note
     730              : //    shared with the checks whether they remove a measure repeat
     731              : //---------------------------------------------------------
     732              : 
     733              : //! Where a click puts the note
     734            3 : static bool clickPosition(Score* score, const PointF& pos, Position& p)
     735              : {
     736            3 :     return score->getPosition(&p, pos, score->inputState().voice());
     737              : }
     738              : 
     739              : //! Whether a click repitches the note there, instead of putting one
     740            3 : static bool clickRepitches(const Position& p)
     741              : {
     742            3 :     Score* posScore = p.segment->score();
     743              :     // it is not safe to call repitchNote() if p is on a TAB staff
     744            3 :     bool isTablature = posScore->staff(p.staffIdx)->isTabStaff(p.segment->tick());
     745            3 :     return posScore->inputState().usingNoteEntryMethod(NoteEntryMethod::REPITCH) && !isTablature;
     746              : }
     747              : 
     748              : //! Where the notes are entered from the keyboard
     749           36 : static Position inputPosition(const InputState& is)
     750              : {
     751           36 :     Position pos;
     752           36 :     pos.segment = is.segment();
     753           36 :     pos.staffIdx = is.track() / VOICES;
     754           36 :     pos.beyondScore = is.beyondScore();
     755           36 :     return pos;
     756              : }
     757              : 
     758              : //! The note, to whose chord a note is added
     759           20 : static Note* selectedNote(const Score* score)
     760              : {
     761           20 :     EngravingItem* el = score->selection().element();
     762           20 :     return el && el->isNote() ? toNote(el) : nullptr;
     763              : }
     764              : 
     765              : //! Whether entering a note at `pos` removes the measure repeat there
     766            8 : static bool removesMeasureRepeat(const Position& pos)
     767              : {
     768            8 :     if (!pos.segment || pos.beyondScore) {
     769            0 :         return false;
     770              :     }
     771              : 
     772            8 :     const Measure* measure = pos.segment->measure();
     773            8 :     return measure && measure->isMeasureRepeatGroup(pos.staffIdx);
     774              : }
     775              : 
     776              : //---------------------------------------------------------
     777              : //   putNote
     778              : //    mouse click in state NoteType::ENTRY
     779              : //---------------------------------------------------------
     780              : 
     781            0 : Ret NoteInput::putNote(Transaction& tx, Score* score, const PointF& pos, bool replace, bool insert)
     782              : {
     783            0 :     Position p;
     784            0 :     if (!clickPosition(score, pos, p)) {
     785            0 :         LOGD("cannot put note here, get position failed");
     786            0 :         return make_ret(Ret::Code::UnknownError);
     787              :     }
     788              : 
     789            0 :     Score* posScore = p.segment->score();
     790              : 
     791              :     //  calculate actual clicked line from staffType offset and stepOffset
     792            0 :     Staff* ss = posScore->staff(p.staffIdx);
     793            0 :     int stepOffset = ss->staffType(p.segment->tick())->stepOffset();
     794            0 :     double stYOffset = ss->staffType(p.segment->tick())->yoffset().val();
     795            0 :     double lineDist = ss->staffType(p.segment->tick())->lineDistance().val();
     796            0 :     p.line -= stepOffset + 2 * stYOffset / lineDist;
     797              : 
     798            0 :     if (clickRepitches(p)) {
     799            0 :         return repitchNote(tx, posScore, p, replace);
     800              :     } else {
     801            0 :         if (insert || posScore->inputState().usingNoteEntryMethod(NoteEntryMethod::TIMEWISE)) {
     802            0 :             return insertChordByInsertingTime(tx, posScore, p);
     803              :         } else {
     804            0 :             return putNote(tx, posScore, p, replace);
     805              :         }
     806              :     }
     807              : }
     808              : 
     809           30 : Ret NoteInput::putNote(Transaction& tx, Score* score, const Position& p, bool replace)
     810              : {
     811           30 :     InputState& is = score->inputState();
     812              : 
     813           30 :     Staff* st   = score->staff(p.staffIdx);
     814           30 :     Segment* s  = p.segment;
     815              : 
     816           30 :     is.setTrack(p.staffIdx * VOICES + is.voice());
     817           30 :     is.setSegment(s);
     818              : 
     819           30 :     if (p.beyondScore) {
     820            0 :         score->appendMeasures(1);
     821            0 :         is.moveToNextInputPos();
     822              :     }
     823              : 
     824           30 :     if (mu::engraving::Excerpt* excerpt = score->excerpt()) {
     825            0 :         const TracksMap& tracks = excerpt->tracksMapping();
     826              : 
     827            0 :         if (!tracks.empty() && muse::key(tracks, is.track(), muse::nidx) == muse::nidx) {
     828            0 :             return make_ret(Ret::Code::UnknownError);
     829              :         }
     830              :     }
     831              : 
     832           30 :     DirectionV stemDirection = DirectionV::AUTO;
     833           30 :     bool error = false;
     834           30 :     NoteVal nval = noteValForPosition(score, p, is.accidentalType(), error);
     835           30 :     if (error) {
     836            2 :         return make_ret(Ret::Code::UnknownError);
     837              :     }
     838              : 
     839              :     // delete MeasureRepeat if necessary, the user is asked beforehand
     840           28 :     Measure* m = is.segment()->measure();
     841           28 :     staff_idx_t staffIdx = track2staff(is.track());
     842           28 :     if (m->isMeasureRepeatGroup(staffIdx)) {
     843            1 :         score->deleteItem(m->measureRepeatElement(staffIdx));
     844              :     }
     845              : 
     846           28 :     const StringData* stringData = 0;
     847              : 
     848              :     // pitched/unpitched note entry depends on instrument (override StaffGroup)
     849           28 :     StaffGroup staffGroup = st->staffType(s->tick())->group();
     850           28 :     if (staffGroup != StaffGroup::TAB) {
     851           27 :         staffGroup = st->part()->instrument(s->tick())->useDrumset() ? StaffGroup::PERCUSSION : StaffGroup::STANDARD;
     852              :     }
     853              : 
     854           28 :     switch (staffGroup) {
     855            0 :     case StaffGroup::PERCUSSION: {
     856            0 :         const Drumset* ds = st->part()->instrument(s->tick())->drumset();
     857            0 :         DO_ASSERT(ds);
     858              : 
     859            0 :         if (ds) {
     860            0 :             stemDirection = ds->stemDirection(nval.pitch);
     861            0 :             is.setVoice(ds->voice(nval.pitch));
     862              :         }
     863            0 :         break;
     864              :     }
     865            1 :     case StaffGroup::TAB:
     866            1 :         stringData = st->part()->stringData(s->tick(), st->idx());
     867            1 :         is.setDrumNote(-1);
     868            1 :         break;
     869           27 :     case StaffGroup::STANDARD:
     870              :     case StaffGroup::JIANPU:
     871           27 :         is.setDrumNote(-1);
     872           27 :         break;
     873              :     }
     874              : 
     875           28 :     score->expandVoice();
     876              : 
     877              :     // If there's an overlapping ChordRest at the current input position, shorten it...
     878           28 :     if (!is.cr()) {
     879            0 :         ChordRest* prevCr = is.segment()->nextChordRest(is.track(), /*backwards*/ true, /*stopAtMeasureBoundary*/ true);
     880            0 :         if (prevCr && prevCr->endTick() > is.tick()) {
     881            0 :             const InputState inputStateToRestore = is; // because truncateChordRest will alter the input state
     882            0 :             truncateChordRest(tx, score, prevCr, is.tick(), /*fillWithRest*/ true);
     883            0 :             is = inputStateToRestore;
     884            0 :         }
     885              :     }
     886              : 
     887           28 :     ChordRest* cr = is.cr();
     888              : 
     889           28 :     auto checkTied = [&]() {
     890           28 :         if (!cr || !cr->isChord()) {
     891           28 :             return false;
     892              :         }
     893            0 :         auto ch = toChord(cr);
     894            0 :         return (!ch->notes().empty() && !ch->notes()[0]->tieBack())
     895            0 :                && (ch->notes()[0]->tieFor() && !ch->notes()[0]->tieFor()->isLaissezVib());
     896           28 :     };
     897              : 
     898           28 :     bool addToChord = false;
     899           28 :     bool shouldAddAsTied = checkTied();
     900              : 
     901           28 :     if (cr) {
     902              :         // retrieve total duration of current chord
     903           28 :         TDuration d = cr->durationType();
     904              :         // if not in replace mode AND chord duration == input duration AND not rest input
     905              :         // we need to add to current chord (otherwise, we will need to replace it or create a new one)
     906           56 :         if (!replace
     907            2 :             && ((d == is.duration()) || shouldAddAsTied)
     908            0 :             && cr->isChord()
     909           30 :             && !is.rest()) {
     910            0 :             if (st->isTabStaff(cr->tick())) {            // TAB
     911              :                 // if a note on same string already exists, update to new pitch/fret
     912            0 :                 for (Note* note : toChord(cr)->notes()) {
     913            0 :                     if (note->string() == nval.string) {                 // if string is the same
     914              :                         // if adding a new digit will keep fret number within fret limit,
     915              :                         // add a digit to existing fret number
     916            0 :                         if (stringData) {
     917            0 :                             int fret = note->fret() * 10 + nval.fret;
     918            0 :                             if (fret <= stringData->frets()) {
     919            0 :                                 nval.fret = fret;
     920            0 :                                 nval.pitch = stringData->getPitch(nval.string, nval.fret, st);
     921              :                             } else {
     922            0 :                                 LOGD("can't increase fret to %d", fret);
     923              :                             }
     924              :                         }
     925              :                         // set fret number (original or combined) in all linked notes
     926            0 :                         int tpc1 = note->tpc1default(nval.pitch);
     927            0 :                         int tpc2 = note->tpc2default(nval.pitch);
     928            0 :                         EditNote::undoChangeFretting(score, note, nval.pitch, nval.string, nval.fret, tpc1, tpc2);
     929            0 :                         score->setPlayNote(true);
     930            0 :                         return muse::make_ok();
     931              :                     }
     932              :                 }
     933              :             } else {                            // not TAB
     934              :                 // if a note with the same pitch already exists in the chord, remove it
     935            0 :                 Chord* chord = toChord(cr);
     936            0 :                 Note* note = chord->findNote(nval.pitch);
     937            0 :                 if (note) {
     938            0 :                     if (chord->notes().size() > 1) {
     939            0 :                         score->undoRemoveElement(note);
     940              :                     }
     941            0 :                     return muse::make_ok();
     942              :                 }
     943              :             }
     944            0 :             addToChord = true;                  // if no special case, add note to chord
     945              :         }
     946              :     }
     947           28 :     bool forceAccidental = false;
     948           28 :     if (is.accidentalType() != AccidentalType::NONE) {
     949            0 :         NoteVal nval2 = noteValForPosition(score, p, AccidentalType::NONE, error);
     950            0 :         forceAccidental = (nval.pitch == nval2.pitch);
     951              :     }
     952              : 
     953           56 :     Ret ret = muse::make_ok();
     954              : 
     955           28 :     if (addToChord && cr->isChord()) {
     956              :         // if adding, add!
     957            0 :         Chord* chord = toChord(cr);
     958            0 :         if (shouldAddAsTied) {
     959            0 :             Note* n = addNoteToTiedChord(tx, score, chord, nval, forceAccidental, is.articulationIds());
     960            0 :             if (!n) {
     961            0 :                 ret = make_ret(Ret::Code::UnknownError);
     962              :             }
     963              : 
     964            0 :             is.setAccidentalType(AccidentalType::NONE);
     965            0 :             return ret;
     966              :         }
     967            0 :         Note* note = addNote(tx, score, chord, nval, forceAccidental, is.articulationIds());
     968            0 :         if (!note) {
     969            0 :             ret = make_ret(Ret::Code::UnknownError);
     970              :         }
     971              : 
     972            0 :         is.setAccidentalType(AccidentalType::NONE);
     973            0 :         return ret;
     974              :     } else {
     975              :         // if not adding, replace current chord (or create a new one)
     976           28 :         if (is.rest()) {
     977            0 :             nval.pitch = -1;
     978              :         }
     979              : 
     980           56 :         Segment* seg = score->setNoteRest(is.segment(), is.track(), nval,
     981           28 :                                           is.duration().fraction(), stemDirection, forceAccidental, is.articulationIds());
     982           28 :         if (!seg) {
     983            0 :             ret = make_ret(Ret::Code::UnknownError);
     984              :         }
     985              : 
     986           28 :         is.setAccidentalType(AccidentalType::NONE);
     987              :     }
     988              : 
     989           28 :     if (cr && !st->isTabStaff(cr->tick())) {
     990           27 :         is.moveToNextInputPos();
     991              :     }
     992              : 
     993           28 :     return ret;
     994              : }
     995              : 
     996              : //---------------------------------------------------------
     997              : //   repitchNote
     998              : //---------------------------------------------------------
     999              : 
    1000            0 : Ret NoteInput::repitchNote(Transaction& tx, Score* score, const Position& p, bool replace)
    1001              : {
    1002            0 :     InputState& is = score->inputState();
    1003              : 
    1004            0 :     Segment* s      = p.segment;
    1005            0 :     Fraction tick   = s->tick();
    1006            0 :     Staff* st       = score->staff(p.staffIdx);
    1007            0 :     ClefType clef   = st->clef(tick);
    1008              : 
    1009            0 :     NoteVal nval;
    1010            0 :     bool error = false;
    1011            0 :     AccidentalType at = is.accidentalType();
    1012            0 :     if (is.drumset() && is.drumNote() != -1) {
    1013            0 :         nval.pitch = is.drumNote();
    1014              :     } else {
    1015              :         AccidentalVal acci
    1016            0 :             = (at == AccidentalType::NONE ? s->measure()->findAccidental(s, p.staffIdx, p.line, error) : Accidental::subtype2value(at));
    1017            0 :         if (error) {
    1018            0 :             return make_ret(Ret::Code::UnknownError);
    1019              :         }
    1020              : 
    1021            0 :         int step   = absStep(p.line, clef);
    1022            0 :         int octave = step / 7;
    1023            0 :         nval.pitch = step2pitch(step) + octave * 12 + int(acci);
    1024              : 
    1025            0 :         if (score->style().styleB(Sid::concertPitch)) {
    1026            0 :             nval.tpc1 = step2tpc(step % 7, acci);
    1027              :         } else {
    1028            0 :             nval.pitch += st->part()->instrument(s->tick())->transpose().chromatic;
    1029            0 :             nval.tpc2 = step2tpc(step % 7, acci);
    1030              :         }
    1031              :     }
    1032              : 
    1033            0 :     if (!is.segment()) {
    1034            0 :         return make_ret(Ret::Code::UnknownError);
    1035              :     }
    1036              : 
    1037              :     Chord* chord;
    1038            0 :     ChordRest* cr = is.cr();
    1039            0 :     if (!cr) {
    1040            0 :         cr = is.segment()->nextChordRest(is.track());
    1041            0 :         if (!cr) {
    1042            0 :             return make_ret(Ret::Code::UnknownError);
    1043              :         }
    1044              :     }
    1045            0 :     if (cr->isRest()) {   //skip rests
    1046            0 :         ChordRest* next = Navigation::nextChordRest(cr);
    1047            0 :         while (next && !next->isChord()) {
    1048            0 :             next = Navigation::nextChordRest(next);
    1049              :         }
    1050            0 :         if (next) {
    1051            0 :             is.moveInputPos(next->segment());
    1052              :         }
    1053            0 :         return muse::make_ok();
    1054              :     } else {
    1055            0 :         chord = toChord(cr);
    1056              :     }
    1057              : 
    1058            0 :     bool forceAccidental = false;
    1059            0 :     if (is.accidentalType() != AccidentalType::NONE) {
    1060            0 :         NoteVal nval2 = noteValForPosition(score, p, AccidentalType::NONE, error);
    1061            0 :         forceAccidental = (nval.pitch == nval2.pitch);
    1062              :     }
    1063              : 
    1064              :     // Note: not sure this is ever called with replace == false, since add (not replace) case is handled already in cmdAddPitch
    1065            0 :     if (!replace) {
    1066            0 :         return addPitchToChord(tx, score, nval, chord, /* externalInputState */ nullptr, forceAccidental);
    1067              :     }
    1068              : 
    1069            0 :     auto [note, lastTiedNote] = repitchReplaceNote(tx, score, chord, nval, forceAccidental);
    1070            0 :     score->setPlayChord(true);
    1071              : 
    1072              :     // move to next Chord
    1073            0 :     ChordRest* next = Navigation::nextChordRest(lastTiedNote->chord());
    1074            0 :     while (next && !next->isChord()) {
    1075            0 :         next = Navigation::nextChordRest(next);
    1076              :     }
    1077            0 :     if (next) {
    1078            0 :         is.moveInputPos(next->segment());
    1079              :     }
    1080              : 
    1081            0 :     return muse::make_ok();
    1082              : }
    1083              : 
    1084              : //---------------------------------------------------------
    1085              : //   insertChordByInsertingTime
    1086              : //---------------------------------------------------------
    1087              : 
    1088            5 : Ret NoteInput::insertChordByInsertingTime(Transaction& tx, Score* score, const Position& pos)
    1089              : {
    1090              :     // insert by increasing measure length
    1091              :     //
    1092              :     // TODO:
    1093              :     //    - check voices
    1094              :     //    - split chord/rest
    1095              : 
    1096            5 :     EngravingItem* el = score->selection().element();
    1097            5 :     if (!el || !(el->isNote() || el->isRest())) {
    1098            0 :         return make_ret(Ret::Code::UnknownError);
    1099              :     }
    1100              : 
    1101            5 :     Segment* seg = pos.segment;
    1102            5 :     if (seg->splitsTuplet()) {
    1103            0 :         MScore::setError(MsError::CANNOT_INSERT_TUPLET);
    1104            0 :         return make_ret(Ret::Code::UnknownError);
    1105              :     }
    1106              : 
    1107              :     // remove all two-note tremolos that end on this tick
    1108           37 :     for (EngravingItem* e : seg->elist()) {
    1109           32 :         if (!e || !e->isChord()) {
    1110           24 :             continue;
    1111              :         }
    1112            8 :         Chord* c = toChord(e);
    1113            8 :         TremoloTwoChord* t = c->tremoloTwoChord();
    1114            8 :         if (t && t->chord2() == c) {
    1115              :             // we have to remove this tremolo because we are adding time in the middle of it
    1116              :             // (if c is chord1 then we're inserting before the trem so it's fine)
    1117            0 :             score->undoRemoveElement(t);
    1118              :         }
    1119              :     }
    1120              : 
    1121            5 :     const TDuration duration = score->inputState().duration();
    1122            5 :     const Fraction fraction  = duration.fraction();
    1123            5 :     const Fraction len       = fraction;
    1124            5 :     Fraction tick            = seg->tick();
    1125            5 :     Measure* measure         = seg->measure()->isMMRest() ? seg->measure()->mmRestFirst() : seg->measure();
    1126            5 :     const Fraction targetMeasureLen = measure->ticks() + fraction;
    1127              : 
    1128              :     // Shift spanners, enlarge the measure.
    1129              :     // The approach is similar to that in Measure::adjustToLen() but does
    1130              :     // insert time to the middle of the measure rather than to the end.
    1131            5 :     score->undoInsertTime(tick, len);
    1132              : 
    1133           10 :     for (Score* lscore : score->scoreList()) {
    1134            5 :         tx.push(new InsertTime(lscore, tick, len));
    1135            5 :         Measure* m = lscore->tick2measure(tick);
    1136            5 :         tx.push(new ChangeMeasureLen(m, targetMeasureLen));
    1137            5 :         Segment* scoreSeg = m->tick2segment(tick);
    1138              :         // tuplets store their tick: move those from the insertion on with their segments
    1139            5 :         std::set<Tuplet*> tuplets;
    1140           36 :         for (Segment* s = scoreSeg; s; s = s->next()) {
    1141           31 :             if (s->isChordRestType()) {
    1142          227 :                 for (EngravingItem* e : s->elist()) {
    1143          224 :                     for (Tuplet* t = e ? toChordRest(e)->tuplet() : nullptr; t && t->tick() >= tick; t = t->tuplet()) {
    1144              :                         // shared tuplets follow their origin
    1145           28 :                         if (t->originItems().empty()) {
    1146           25 :                             tuplets.insert(t);
    1147              :                         }
    1148              :                     }
    1149              :                 }
    1150              :             }
    1151           31 :             s->undoChangeProperty(Pid::TICK, s->rtick() + len);
    1152              :         }
    1153           12 :         for (Tuplet* t : tuplets) {
    1154            7 :             t->undoChangeProperty(Pid::TICK, t->tick() + len);
    1155              :         }
    1156           10 :     }
    1157              : 
    1158              :     // Fill the inserted time with rests.
    1159              :     // This is better to be done in master score to cover all staves.
    1160            5 :     MasterScore* ms = score->masterScore();
    1161            5 :     Measure* msMeasure = ms->tick2measure(tick);
    1162            5 :     const size_t msTracks = ms->ntracks();
    1163              : 
    1164            5 :     Segment* firstSeg = msMeasure->first(SegmentType::ChordRest);
    1165           37 :     for (track_idx_t track = 0; track < msTracks; ++track) {
    1166           32 :         EngravingItem* maybeRest = firstSeg->element(track);
    1167           32 :         bool measureIsFull = false;
    1168              : 
    1169              :         // I. Convert any measure rests into normal (non-measure) rest(s) of equivalent duration
    1170           32 :         if (maybeRest && maybeRest->isRest() && toRest(maybeRest)->durationType().isMeasure()) {
    1171            0 :             ms->undoRemoveElement(maybeRest);
    1172            0 :             Rest* measureRest = toRest(maybeRest);
    1173              :             // If measure rest is situated at measure start we will fill
    1174              :             // the whole measure with rests.
    1175            0 :             measureIsFull = measureRest->rtick().isZero();
    1176            0 :             const Fraction fillLen = measureIsFull ? targetMeasureLen : measureRest->ticks();
    1177            0 :             ms->setRest(measureRest->tick(), track, fillLen, /* useDots */ false, /* tuplet */ nullptr, /* useFullMeasureRest */ false);
    1178              :         }
    1179              : 
    1180              :         // II. Make chord or rest in other track longer if it crosses the insert area
    1181           32 :         if (!measureIsFull) {
    1182           32 :             ChordRest* cr = ms->findCR(tick, track);
    1183           32 :             if (cr && cr->tick() < tick && cr->endTick() > tick) {
    1184            0 :                 if (cr->isRest()) {
    1185            0 :                     const Fraction fillLen = cr->ticks() + fraction;
    1186            0 :                     ms->undoRemoveElement(cr);
    1187            0 :                     ms->setRest(cr->tick(), track, fillLen, /* useDots */ false, /* tuplet */ nullptr, /* useFullMeasureRest */ false);
    1188            0 :                 } else if (cr->isChord()) {
    1189            0 :                     Chord* chord = toChord(cr);
    1190            0 :                     std::vector<TDuration> durations = toDurationList(chord->ticks() + fraction, /* useDots */ true);
    1191            0 :                     Fraction p = chord->tick();
    1192            0 :                     ms->undoRemoveElement(chord);
    1193            0 :                     Chord* prevChord = nullptr;
    1194            0 :                     for (const TDuration& dur : durations) {
    1195            0 :                         Chord* prototype = prevChord ? prevChord : chord;
    1196            0 :                         const bool genTie = bool(prevChord);
    1197            0 :                         prevChord = ms->addChord(p, dur, prototype, genTie, /* tuplet */ nullptr);
    1198            0 :                         p += dur.fraction();
    1199              :                     }
    1200              :                     // TODO: reconnect ties if this chord was tied to other
    1201            0 :                 }
    1202            0 :                 measureIsFull = true;
    1203              :             }
    1204              :         }
    1205              : 
    1206              :         // III. insert rest(s) to fill the inserted space
    1207           32 :         if (!measureIsFull && msMeasure->hasVoice(track)) {
    1208            9 :             ms->setRest(tick, track, fraction, /* useDots */ false, /* tuplet */ nullptr);
    1209              :         }
    1210              :     }
    1211              : 
    1212              :     // Put the note itself.
    1213            5 :     Segment* s = measure->undoGetSegment(SegmentType::ChordRest, tick);
    1214            5 :     Position p(pos);
    1215            5 :     p.segment = s;
    1216            5 :     putNote(tx, score, p, true);
    1217              : 
    1218            5 :     return muse::make_ok();
    1219              : }
    1220              : 
    1221              : //---------------------------------------------------------
    1222              : //   truncateChordRest
    1223              : //---------------------------------------------------------
    1224              : 
    1225            0 : void NoteInput::truncateChordRest(Transaction&, Score* score, ChordRest* cr, const Fraction& tick, bool fillWithRest)
    1226              : {
    1227            0 :     MasterScore* ms = score->masterScore();
    1228            0 :     IF_ASSERT_FAILED(ms && cr && cr->endTick() > tick) {
    1229            0 :         return;
    1230              :     }
    1231              : 
    1232            0 :     const Fraction timeStretch = cr->staff()->timeStretch(cr->tick());
    1233            0 :     Tuplet* tuplet = cr->tuplet();
    1234            0 :     const Fraction overlapDuration = (cr->endTick() - tick) / actualTicks(Fraction(1, 1), tuplet, timeStretch);
    1235            0 :     const Fraction desiredDuration = cr->ticks() - overlapDuration;
    1236              : 
    1237            0 :     ms->changeCRlen(cr, desiredDuration, fillWithRest);
    1238              : 
    1239              :     // Fill the difference with tied notes if necessary...
    1240            0 :     const Fraction difference = desiredDuration - cr->ticks();
    1241            0 :     if (cr->isChord() && difference.isNotZero()) {
    1242            0 :         Fraction startTick = cr->endTick();
    1243            0 :         Chord* prevChord = toChord(cr);
    1244            0 :         const std::vector<TDuration> durationList = toDurationList(difference, true);
    1245            0 :         for (const TDuration& dur : durationList) {
    1246            0 :             prevChord = ms->addChord(startTick, dur, prevChord, /*genTie*/ bool(prevChord), prevChord->tuplet());
    1247            0 :             startTick += actualTicks(dur.fraction(), prevChord->tuplet(), prevChord->staff()->timeStretch(startTick));
    1248              :         }
    1249            0 :     }
    1250              : }
    1251              : 
    1252              : //---------------------------------------------------------
    1253              : //   nextInputPos
    1254              : //---------------------------------------------------------
    1255              : 
    1256           47 : void NoteInput::nextInputPos(Transaction&, Score* score, const ChordRest* cr, bool doSelect)
    1257              : {
    1258           47 :     InputState& is = score->inputState();
    1259              : 
    1260           47 :     ChordRest* ncr = Navigation::nextChordRest(cr);
    1261           47 :     if ((!ncr) && (is.track() % VOICES)) {
    1262            0 :         Segment* s = score->tick2segment(cr->endTick(), false, SegmentType::ChordRest);
    1263            0 :         ncr = s ? toChordRest(s->element(cr->staffIdx() * VOICES)) : nullptr;
    1264              :     }
    1265           47 :     if (ncr) {
    1266           47 :         is.setSegment(ncr->segment());
    1267           47 :         if (doSelect) {
    1268            0 :             score->select(ncr, SelectType::SINGLE, 0);
    1269              :         }
    1270           47 :         for (MuseScoreView* v : score->getViewer()) {
    1271            0 :             v->moveCursor();
    1272              :         }
    1273              :     }
    1274           47 : }
    1275              : 
    1276              : //---------------------------------------------------------
    1277              : //   addPitch
    1278              : ///   insert note or add note to chord
    1279              : //---------------------------------------------------------
    1280              : 
    1281            5 : void NoteInput::addPitch(Transaction& tx, Score* score, const NoteInputParams& params, bool addFlag, bool insert)
    1282              : {
    1283            5 :     InputState& is = score->inputState();
    1284            5 :     if (!is.isValid()) {
    1285            0 :         LOGD("cannot enter notes here (no chord rest at current position)");
    1286            0 :         return;
    1287              :     }
    1288              : 
    1289            5 :     is.setRest(false);
    1290              : 
    1291            5 :     const Drumset* ds = is.drumset();
    1292            5 :     if (ds) {
    1293            0 :         is.setDrumNote(params.drumPitch);
    1294            0 :         is.setVoice(ds->voice(params.drumPitch));
    1295              :     }
    1296              : 
    1297            5 :     addPitch(tx, score, params.step, addFlag, insert);
    1298              : }
    1299              : 
    1300           48 : void NoteInput::addPitch(Transaction& tx, Score* score, int step, bool addFlag, bool insert)
    1301              : {
    1302           48 :     InputState& is = score->inputState();
    1303              : 
    1304           48 :     insert = insert || is.usingNoteEntryMethod(NoteEntryMethod::TIMEWISE);
    1305           48 :     Position pos;
    1306           48 :     if (addFlag) {
    1307           20 :         if (Note* note = selectedNote(score)) {
    1308           19 :             Chord* chord  = note->chord();
    1309           19 :             Segment* seg  = chord->segment();
    1310           19 :             pos.segment   = seg;
    1311           19 :             pos.staffIdx  = chord->vStaffIdx();
    1312           19 :             ClefType clef = score->staff(pos.staffIdx)->clef(seg->tick());
    1313           19 :             pos.line      = relStep(step, clef);
    1314              :             bool error;
    1315           19 :             NoteVal nval = noteValForPosition(score, pos, is.accidentalType(), error);
    1316           19 :             if (error) {
    1317           15 :                 return;
    1318              :             }
    1319            4 :             bool forceAccidental = false;
    1320            4 :             if (is.accidentalType() != AccidentalType::NONE) {
    1321            0 :                 NoteVal nval2 = noteValForPosition(score, pos, AccidentalType::NONE, error);
    1322            0 :                 forceAccidental = (nval.pitch == nval2.pitch);
    1323              :             }
    1324            4 :             if (is.usingNoteEntryMethod(NoteEntryMethod::REPITCH)) {
    1325            0 :                 addPitchToChord(tx, score, nval, chord, /* externalInputState */ nullptr, forceAccidental);
    1326              :             } else {
    1327            4 :                 addNote(tx, score, chord, nval, forceAccidental, is.articulationIds());
    1328              :             }
    1329            4 :             is.setAccidentalType(AccidentalType::NONE);
    1330            4 :             return;
    1331              :         }
    1332              :     }
    1333              : 
    1334           29 :     pos           = inputPosition(is);
    1335           29 :     ClefType clef = score->staff(pos.staffIdx)->clef(pos.segment->tick());
    1336           29 :     pos.line      = relStep(step, clef);
    1337              : 
    1338           29 :     if (is.usingNoteEntryMethod(NoteEntryMethod::REPITCH)) {
    1339            0 :         repitchNote(tx, score, pos, !addFlag);
    1340              :     } else {
    1341           29 :         if (insert) {
    1342            5 :             insertChordByInsertingTime(tx, score, pos);
    1343              :         } else {
    1344           24 :             putNote(tx, score, pos, !addFlag);
    1345              :         }
    1346              :     }
    1347           29 :     is.setAccidentalType(AccidentalType::NONE);
    1348              : }
    1349              : 
    1350              : //---------------------------------------------------------
    1351              : //   addFret
    1352              : ///   insert note with given fret on current string
    1353              : //---------------------------------------------------------
    1354              : 
    1355            1 : void NoteInput::addFret(Transaction& tx, Score* score, int fret)
    1356              : {
    1357            1 :     InputState& is = score->inputState();
    1358            1 :     if (is.track() == muse::nidx) { // invalid state
    1359            0 :         return;
    1360              :     }
    1361            1 :     if (!is.segment()) {
    1362            0 :         LOGD("cannot enter notes here (no chord rest at current position)");
    1363            0 :         return;
    1364              :     }
    1365            1 :     is.setRest(false);
    1366            1 :     Position pos  = inputPosition(is);
    1367            1 :     pos.line      = score->staff(pos.staffIdx)->staffType(is.tick())->physStringToVisual(is.string());
    1368            1 :     pos.fret      = fret;
    1369            1 :     putNote(tx, score, pos, false);
    1370              : }
    1371              : 
    1372            3 : bool NoteInput::putNoteRemovesMeasureRepeat(Score* score, const PointF& pos)
    1373              : {
    1374            3 :     Position p;
    1375            3 :     if (!clickPosition(score, pos, p) || clickRepitches(p)) {
    1376            1 :         return false;
    1377              :     }
    1378              : 
    1379            2 :     return removesMeasureRepeat(p);
    1380              : }
    1381              : 
    1382            4 : bool NoteInput::addPitchRemovesMeasureRepeat(Score* score, bool addFlag)
    1383              : {
    1384            4 :     const InputState& is = score->inputState();
    1385            4 :     if (!is.isValid()) {
    1386            0 :         return false;
    1387              :     }
    1388              : 
    1389            4 :     if (addFlag && selectedNote(score)) {
    1390            0 :         return false; // added to the chord
    1391              :     }
    1392              : 
    1393            4 :     if (is.usingNoteEntryMethod(NoteEntryMethod::REPITCH)) {
    1394            1 :         return false;
    1395              :     }
    1396              : 
    1397            3 :     return removesMeasureRepeat(inputPosition(is));
    1398              : }
    1399              : 
    1400            3 : bool NoteInput::addFretRemovesMeasureRepeat(Score* score)
    1401              : {
    1402            3 :     const InputState& is = score->inputState();
    1403            3 :     if (is.track() == muse::nidx || !is.segment()) {
    1404            0 :         return false;
    1405              :     }
    1406              : 
    1407            3 :     return removesMeasureRepeat(inputPosition(is));
    1408              : }
    1409              : 
    1410              : //---------------------------------------------------------
    1411              : //   noteValueChangeAllowed
    1412              : //    Note value changes are disallowed while a trill cue note is selected outside note entry mode.
    1413              : //---------------------------------------------------------
    1414              : 
    1415            0 : bool NoteInput::noteValueChangeAllowed(const Score* score)
    1416              : {
    1417            0 :     if (score->noteEntryMode()) {
    1418            0 :         return true;
    1419              :     }
    1420              : 
    1421            0 :     for (const ChordRest* cr : score->getSelectedChordRests()) {
    1422            0 :         if (cr->isChord() && toChord(cr)->isTrillCueNote()) {
    1423            0 :             return false;
    1424              :         }
    1425            0 :     }
    1426              : 
    1427            0 :     return true;
    1428              : }
    1429              : 
    1430              : //---------------------------------------------------------
    1431              : //   durationTooShortForDots
    1432              : //    A duration cannot hold `dots` augmentation dots when it is one of the `dots` shortest
    1433              : //    representable durations (the shortest being V_1024TH).
    1434              : //---------------------------------------------------------
    1435              : 
    1436            0 : static bool durationTooShortForDots(const TDuration& duration, int dots)
    1437              : {
    1438              :     // Ordered shortest-first; a duration cannot hold `dots` dots if it is one of the `dots` shortest.
    1439              :     static constexpr DurationType shortestTypes[] = {
    1440              :         DurationType::V_1024TH,
    1441              :         DurationType::V_512TH,
    1442              :         DurationType::V_256TH,
    1443              :         DurationType::V_128TH,
    1444              :     };
    1445              : 
    1446            0 :     const int count = std::min(dots, int(std::size(shortestTypes)));
    1447            0 :     for (int i = 0; i < count; ++i) {
    1448            0 :         if (duration == shortestTypes[i]) {
    1449            0 :             return true;
    1450              :         }
    1451              :     }
    1452              : 
    1453            0 :     return false;
    1454              : }
    1455              : 
    1456              : //---------------------------------------------------------
    1457              : //   setDuration
    1458              : //    Set the note input duration (and apply it to the selection).
    1459              : //---------------------------------------------------------
    1460              : 
    1461            0 : void NoteInput::setDuration(Transaction& tx, Score* score, DurationType duration)
    1462              : {
    1463            0 :     if (!noteValueChangeAllowed(score)) {
    1464            0 :         return;
    1465              :     }
    1466              : 
    1467            0 :     InputState& is = score->inputState();
    1468              : 
    1469            0 :     const TDuration oldDuration = is.duration();
    1470            0 :     const bool oldRest = is.rest();
    1471            0 :     const AccidentalType oldAccidentalType = is.accidentalType();
    1472              : 
    1473            0 :     is.setDuration(duration);
    1474            0 :     is.setDots(0);
    1475              : 
    1476              :     //
    1477              :     // if in "note enter" mode, reset rest flag
    1478              :     //
    1479            0 :     if (score->noteEntryMode()) {
    1480            0 :         if (score->usingNoteEntryMethod(NoteEntryMethod::BY_DURATION) || score->usingNoteEntryMethod(NoteEntryMethod::RHYTHM)) {
    1481              :             // Preserve the number of dots from the previous duration
    1482            0 :             if (oldDuration.dots() > 0) {
    1483            0 :                 toggleDots(tx, score, oldDuration.dots());
    1484              :             }
    1485              : 
    1486            0 :             if (is.rest()) {
    1487              :                 // Enter a rest
    1488            0 :                 score->setNoteRest(is.segment(), is.track(), NoteVal(), is.duration().fraction());
    1489            0 :                 is.moveToNextInputPos();
    1490              :             } else {
    1491            0 :                 if (score->usingNoteEntryMethod(NoteEntryMethod::RHYTHM)) {
    1492            0 :                     const EngravingItem* selectedItem = score->selection().element();
    1493            0 :                     if (selectedItem && selectedItem->isNote()) {
    1494            0 :                         is.setNotes({ toNote(selectedItem)->noteVal() });
    1495              :                     }
    1496              :                 }
    1497              : 
    1498            0 :                 if (is.beyondScore()) {
    1499            0 :                     score->appendMeasures(1);
    1500            0 :                     is.moveToNextInputPos();
    1501              :                 }
    1502            0 :                 ChordRest* cr = is.cr();
    1503            0 :                 Chord* chord = nullptr;
    1504              : 
    1505            0 :                 if (cr && cr->isChord() && cr->durationType() == is.duration()) {
    1506            0 :                     chord = toChord(cr);
    1507              :                 }
    1508              : 
    1509            0 :                 for (const NoteVal& nval : is.notes()) {
    1510            0 :                     if (chord && chord->findNote(nval.pitch)) {
    1511            0 :                         is.moveToNextInputPos();
    1512            0 :                         continue;
    1513              :                     }
    1514              : 
    1515            0 :                     NoteVal copy(nval);
    1516            0 :                     const Note* note = nullptr;
    1517              : 
    1518            0 :                     if (chord) {
    1519            0 :                         note = addPitchToChord(tx, score, copy, chord);
    1520              :                     } else {
    1521            0 :                         note = addPitch(tx, score, copy, false /*addFlag*/);
    1522              :                     }
    1523              : 
    1524            0 :                     if (note) {
    1525            0 :                         chord = note->chord();
    1526              :                     }
    1527              :                 }
    1528              :             }
    1529              :         } else {
    1530            0 :             is.setRest(false);
    1531              :         }
    1532              :     }
    1533              : 
    1534            0 :     applyToSelection(score, oldDuration, oldRest, oldAccidentalType, false /*toggleForSelectionOnly*/, false /*restToggle*/);
    1535              : }
    1536              : 
    1537              : //---------------------------------------------------------
    1538              : //   toggleRest
    1539              : //    Toggle the note input rest flag (or turn the selection into rests).
    1540              : //---------------------------------------------------------
    1541              : 
    1542            0 : void NoteInput::toggleRest(Transaction& /*tx*/, Score* score)
    1543              : {
    1544            0 :     if (!noteValueChangeAllowed(score)) {
    1545            0 :         return;
    1546              :     }
    1547              : 
    1548            0 :     InputState& is = score->inputState();
    1549              : 
    1550            0 :     const TDuration oldDuration = is.duration();
    1551            0 :     const bool oldRest = is.rest();
    1552            0 :     const AccidentalType oldAccidentalType = is.accidentalType();
    1553              : 
    1554            0 :     if (score->noteEntryMode()) {
    1555            0 :         is.setRest(!is.rest());
    1556            0 :         is.setAccidentalType(AccidentalType::NONE);
    1557            0 :     } else if (score->selection().isNone()) {
    1558            0 :         is.setDuration(DurationType::V_QUARTER);
    1559            0 :         is.setRest(true);
    1560              :     } else {
    1561            0 :         for (ChordRest* cr : score->getSelectedChordRests()) {
    1562            0 :             if (!cr->isRest()) {
    1563            0 :                 score->setNoteRest(cr->segment(), cr->track(), NoteVal(), cr->durationTypeTicks(), DirectionV::AUTO, false,
    1564              :                                    is.articulationIds());
    1565              :             }
    1566            0 :         }
    1567              :     }
    1568              : 
    1569            0 :     applyToSelection(score, oldDuration, oldRest, oldAccidentalType, false /*toggleForSelectionOnly*/, true /*restToggle*/);
    1570              : }
    1571              : 
    1572              : //---------------------------------------------------------
    1573              : //   toggleDots
    1574              : //    Toggle `dots` augmentation dots (1..4) on the note input duration and the selection.
    1575              : //---------------------------------------------------------
    1576              : 
    1577            0 : void NoteInput::toggleDots(Transaction& /*tx*/, Score* score, int dots, bool toggleForSelectionOnly)
    1578              : {
    1579            0 :     IF_ASSERT_FAILED(dots >= 1 && dots <= 4) {
    1580            0 :         return;
    1581              :     }
    1582              : 
    1583            0 :     if (!noteValueChangeAllowed(score)) {
    1584            0 :         return;
    1585              :     }
    1586              : 
    1587            0 :     InputState& is = score->inputState();
    1588              : 
    1589            0 :     const TDuration oldDuration = is.duration();
    1590            0 :     const bool oldRest = is.rest();
    1591            0 :     const AccidentalType oldAccidentalType = is.accidentalType();
    1592              : 
    1593            0 :     if (is.duration().dots() == dots || durationTooShortForDots(is.duration(), dots)) {
    1594            0 :         is.setDots(0);
    1595              :     } else {
    1596            0 :         is.setDots(dots);
    1597              :     }
    1598              : 
    1599            0 :     applyToSelection(score, oldDuration, oldRest, oldAccidentalType, toggleForSelectionOnly, false /*restToggle*/);
    1600              : }
    1601              : 
    1602              : //---------------------------------------------------------
    1603              : //   applyToSelection
    1604              : //    Shared epilogue for setDuration/toggleRest/toggleDots: apply the (possibly changed) input state
    1605              : //    duration/dots to the current selection.
    1606              : //---------------------------------------------------------
    1607              : 
    1608            0 : void NoteInput::applyToSelection(Score* score, const TDuration& oldDuration, bool oldRest,
    1609              :                                  AccidentalType oldAccidentalType, bool toggleForSelectionOnly, bool restToggle)
    1610              : {
    1611            0 :     InputState& is = score->inputState();
    1612              : 
    1613            0 :     if (score->noteEntryMode()) {
    1614            0 :         if (!toggleForSelectionOnly || score->selection().isNone()) {
    1615            0 :             return;
    1616              :         }
    1617              :     }
    1618              : 
    1619            0 :     std::vector<ChordRest*> crs;
    1620            0 :     std::vector<EngravingItem*> elementsToSelect;
    1621              : 
    1622            0 :     if (score->selection().isSingle()) {
    1623            0 :         EngravingItem* e = score->selection().element();
    1624            0 :         ChordRest* cr = InputState::chordRest(e);
    1625              : 
    1626              :         // do not allow to add a dot on a full measure rest
    1627            0 :         if (cr && cr->isRest()) {
    1628            0 :             Rest* r = toRest(cr);
    1629            0 :             if (r->isFullMeasureRest()) {
    1630            0 :                 is.setDots(0);
    1631              :             }
    1632              :         }
    1633              : 
    1634              :         // on measure rest, select the first actual rest
    1635            0 :         if (cr && cr->isMMRest()) {
    1636            0 :             Measure* m = cr->measure()->mmRestFirst();
    1637            0 :             if (m) {
    1638            0 :                 cr = m->findChordRest(m->tick(), 0);
    1639              :             }
    1640              :         }
    1641              : 
    1642            0 :         if (cr) {
    1643            0 :             crs.push_back(cr);
    1644              :         } else {
    1645            0 :             score->deselect(e);
    1646              :         }
    1647            0 :     } else if (score->selection().isNone() && !restToggle) {
    1648            0 :         TDuration td = is.duration();
    1649            0 :         is.setDuration(td);
    1650            0 :         is.setAccidentalType(AccidentalType::NONE);
    1651              :     } else {
    1652            0 :         const auto elements = score->selection().uniqueElements();
    1653            0 :         for (EngravingItem* e : elements) {
    1654            0 :             if (score->selection().isList() || e->isRest() || e->isNote()) {
    1655            0 :                 elementsToSelect.push_back(e);
    1656            0 :                 score->deselect(e);
    1657              :             }
    1658              :         }
    1659            0 :         bool canAdjustLength = true;
    1660            0 :         for (EngravingItem* e : elements) {
    1661            0 :             ChordRest* cr = InputState::chordRest(e);
    1662            0 :             if (!cr) {
    1663            0 :                 continue;
    1664              :             }
    1665            0 :             if (cr->isMeasureRepeat() || cr->isMMRest()) {
    1666            0 :                 canAdjustLength = false;
    1667            0 :                 break;
    1668              :             }
    1669            0 :             crs.push_back(cr);
    1670              :         }
    1671              : 
    1672            0 :         if (canAdjustLength) {
    1673              :             // Change length from last to first chord/rest
    1674            0 :             std::sort(crs.begin(), crs.end(), [](const ChordRest* cr1, const ChordRest* cr2) {
    1675            0 :                 if (cr2->track() == cr1->track()) {
    1676            0 :                     return cr2->isBefore(cr1);
    1677              :                 }
    1678            0 :                 return cr2->track() < cr1->track();
    1679              :             });
    1680              :             // Remove duplicates from the list
    1681            0 :             crs.erase(std::unique(crs.begin(), crs.end()), crs.end());
    1682              :         } else {
    1683            0 :             crs.clear();
    1684              :         }
    1685            0 :     }
    1686              : 
    1687            0 :     const int dots = is.duration().dots();
    1688              : 
    1689            0 :     if (toggleForSelectionOnly && dots > 0 && !crs.empty()) {
    1690            0 :         bool shouldRemoveDots = true;
    1691            0 :         for (const ChordRest* cr : crs) {
    1692            0 :             if (dots != cr->dots()) {
    1693            0 :                 shouldRemoveDots = false;
    1694            0 :                 break;
    1695              :             }
    1696              :         }
    1697              : 
    1698            0 :         if (shouldRemoveDots) {
    1699            0 :             is.setDots(0);
    1700              :         }
    1701              :     }
    1702              : 
    1703            0 :     for (ChordRest* cr : crs) {
    1704            0 :         if (cr->isChord() && (toChord(cr)->isGrace())) {
    1705              :             //
    1706              :             // handle appoggiatura and acciaccatura
    1707              :             //
    1708            0 :             score->undoChangeChordRestLen(cr, is.duration());
    1709              :         } else {
    1710            0 :             score->changeCRlen(cr, is.duration());
    1711              :         }
    1712              :     }
    1713              : 
    1714            0 :     if (!elementsToSelect.empty()) {
    1715            0 :         std::vector<EngravingItem*> selectList;
    1716            0 :         for (EngravingItem* e : elementsToSelect) {
    1717            0 :             if (score->canReselectItem(e)) {
    1718            0 :                 selectList.push_back(e);
    1719              :             }
    1720              :         }
    1721              : 
    1722            0 :         score->select(selectList, SelectType::ADD, 0);
    1723            0 :         score->selection().updateSelectedElements();
    1724            0 :     }
    1725              : 
    1726            0 :     if (toggleForSelectionOnly) {
    1727            0 :         is.setDuration(oldDuration);
    1728            0 :         is.setRest(oldRest);
    1729            0 :         is.setAccidentalType(oldAccidentalType);
    1730              : 
    1731            0 :         if (score->noteEntryMode()) {
    1732            0 :             if (is.lastSegment() == is.segment()) {
    1733            0 :                 is.moveToNextInputPos();
    1734              :             }
    1735              :         }
    1736              :     }
    1737            0 : }
    1738              : 
    1739            0 : void NoteInput::increaseDuration(Transaction& tx, Score* score)
    1740              : {
    1741            0 :     switch (score->inputState().duration().type()) {
    1742              : // cycle back from longest to shortest?
    1743              : //          case TDuration::V_LONG:
    1744              : //                setDuration(tx, score, DurationType::V_128TH);
    1745              : //                break;
    1746            0 :     case DurationType::V_BREVE:
    1747            0 :         setDuration(tx, score, DurationType::V_LONG);
    1748            0 :         break;
    1749            0 :     case DurationType::V_WHOLE:
    1750            0 :         setDuration(tx, score, DurationType::V_BREVE);
    1751            0 :         break;
    1752            0 :     case DurationType::V_HALF:
    1753            0 :         setDuration(tx, score, DurationType::V_WHOLE);
    1754            0 :         break;
    1755            0 :     case DurationType::V_QUARTER:
    1756            0 :         setDuration(tx, score, DurationType::V_HALF);
    1757            0 :         break;
    1758            0 :     case DurationType::V_EIGHTH:
    1759            0 :         setDuration(tx, score, DurationType::V_QUARTER);
    1760            0 :         break;
    1761            0 :     case DurationType::V_16TH:
    1762            0 :         setDuration(tx, score, DurationType::V_EIGHTH);
    1763            0 :         break;
    1764            0 :     case DurationType::V_32ND:
    1765            0 :         setDuration(tx, score, DurationType::V_16TH);
    1766            0 :         break;
    1767            0 :     case DurationType::V_64TH:
    1768            0 :         setDuration(tx, score, DurationType::V_32ND);
    1769            0 :         break;
    1770            0 :     case DurationType::V_128TH:
    1771            0 :         setDuration(tx, score, DurationType::V_64TH);
    1772            0 :         break;
    1773            0 :     case DurationType::V_256TH:
    1774            0 :         setDuration(tx, score, DurationType::V_128TH);
    1775            0 :         break;
    1776            0 :     case DurationType::V_512TH:
    1777            0 :         setDuration(tx, score, DurationType::V_256TH);
    1778            0 :         break;
    1779            0 :     case DurationType::V_1024TH:
    1780            0 :         setDuration(tx, score, DurationType::V_512TH);
    1781            0 :         break;
    1782            0 :     default:
    1783            0 :         break;
    1784              :     }
    1785            0 : }
    1786              : 
    1787            0 : void NoteInput::decreaseDuration(Transaction& tx, Score* score)
    1788              : {
    1789            0 :     switch (score->inputState().duration().type()) {
    1790            0 :     case DurationType::V_LONG:
    1791            0 :         setDuration(tx, score, DurationType::V_BREVE);
    1792            0 :         break;
    1793            0 :     case DurationType::V_BREVE:
    1794            0 :         setDuration(tx, score, DurationType::V_WHOLE);
    1795            0 :         break;
    1796            0 :     case DurationType::V_WHOLE:
    1797            0 :         setDuration(tx, score, DurationType::V_HALF);
    1798            0 :         break;
    1799            0 :     case DurationType::V_HALF:
    1800            0 :         setDuration(tx, score, DurationType::V_QUARTER);
    1801            0 :         break;
    1802            0 :     case DurationType::V_QUARTER:
    1803            0 :         setDuration(tx, score, DurationType::V_EIGHTH);
    1804            0 :         break;
    1805            0 :     case DurationType::V_EIGHTH:
    1806            0 :         setDuration(tx, score, DurationType::V_16TH);
    1807            0 :         break;
    1808            0 :     case DurationType::V_16TH:
    1809            0 :         setDuration(tx, score, DurationType::V_32ND);
    1810            0 :         break;
    1811            0 :     case DurationType::V_32ND:
    1812            0 :         setDuration(tx, score, DurationType::V_64TH);
    1813            0 :         break;
    1814            0 :     case DurationType::V_64TH:
    1815            0 :         setDuration(tx, score, DurationType::V_128TH);
    1816            0 :         break;
    1817            0 :     case DurationType::V_128TH:
    1818            0 :         setDuration(tx, score, DurationType::V_256TH);
    1819            0 :         break;
    1820            0 :     case DurationType::V_256TH:
    1821            0 :         setDuration(tx, score, DurationType::V_512TH);
    1822            0 :         break;
    1823            0 :     case DurationType::V_512TH:
    1824            0 :         setDuration(tx, score, DurationType::V_1024TH);
    1825            0 :         break;
    1826              : // cycle back from shortest to longest?
    1827              : //          case DurationType::V_1024TH:
    1828              : //                setDuration(tx, score, DurationType::V_LONG);
    1829              : //                break;
    1830            0 :     default:
    1831            0 :         break;
    1832              :     }
    1833            0 : }
    1834              : 
    1835              : //---------------------------------------------------------
    1836              : //   realtimeAdvance
    1837              : //---------------------------------------------------------
    1838              : 
    1839            0 : void NoteInput::realtimeAdvance(Transaction& tx, Score* score, bool allowTransposition, const std::vector<int>& activeMidiPitches)
    1840              : {
    1841            0 :     InputState& is = score->inputState();
    1842            0 :     if (!is.noteEntryMode()) {
    1843            0 :         return;
    1844              :     }
    1845              : 
    1846            0 :     Fraction ticks2measureEnd = is.segment()->measure()->ticks() - is.segment()->rtick();
    1847            0 :     if (!is.cr() || (is.cr()->ticks() != is.duration().fraction() && is.duration() < ticks2measureEnd)) {
    1848            0 :         score->setNoteRest(is.segment(), is.track(), NoteVal(), is.duration().fraction(), DirectionV::AUTO);
    1849              :     }
    1850              : 
    1851            0 :     ChordRest* prevCR = toChordRest(is.cr());
    1852            0 :     if (is.beyondScore()) {
    1853            0 :         score->appendMeasures(1);
    1854              :     }
    1855              : 
    1856            0 :     is.moveToNextInputPos();
    1857              : 
    1858            0 :     if (activeMidiPitches.empty()) {
    1859            0 :         score->setNoteRest(is.segment(), is.track(), NoteVal(), is.duration().fraction(), DirectionV::AUTO);
    1860              :     } else {
    1861            0 :         Chord* prevChord = prevCR->isChord() ? toChord(prevCR) : 0;
    1862            0 :         bool partOfChord = false;
    1863            0 :         for (int pitch : activeMidiPitches) {
    1864            0 :             NoteInput::addTiedMidiPitch(tx, score, pitch, partOfChord, prevChord, allowTransposition);
    1865            0 :             partOfChord = true;
    1866              :         }
    1867              :     }
    1868              : 
    1869            0 :     if (prevCR->measure() != is.segment()->measure()) {
    1870              :         // just advanced across barline. Now simplify tied notes.
    1871            0 :         Regroup::regroupNotesAndRests(tx, score, prevCR->measure()->tick(), is.segment()->measure()->tick(), is.track());
    1872              :     }
    1873              : }
        

Generated by: LCOV version 2.0-1