Line data Source code
1 : /*
2 : * SPDX-License-Identifier: GPL-3.0-only
3 : * MuseScore-Studio-CLA-applies
4 : *
5 : * MuseScore Studio
6 : * Music Composition & Notation
7 : *
8 : * Copyright (C) 2021 MuseScore Limited and others
9 : *
10 : * This program is free software: you can redistribute it and/or modify
11 : * it under the terms of the GNU General Public License version 3 as
12 : * published by the Free Software Foundation.
13 : *
14 : * This program is distributed in the hope that it will be useful,
15 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 : * GNU General Public License for more details.
18 : *
19 : * You should have received a copy of the GNU General Public License
20 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 : */
22 :
23 : #include "notationinteraction.h"
24 :
25 : #include "log.h"
26 :
27 : #include <memory>
28 : #include <limits>
29 :
30 : #include <QApplication> // for QApplication::cursorFlashTime()
31 : #include <QClipboard>
32 : #include <QDrag>
33 : #include <QEventLoop>
34 : #include <QGuiApplication>
35 : #include <QKeyEvent>
36 : #include <QKeySequence>
37 : #include <QMimeData>
38 : #include <QPainter>
39 : #include <QRectF>
40 : #include <QRegularExpression>
41 : #include <QRegularExpressionMatch>
42 :
43 : #include "defer.h"
44 : #include "ptrutils.h"
45 : #include "containers.h"
46 :
47 : #include "draw/painter.h"
48 : #include "draw/types/pen.h"
49 :
50 : #include "engraving/iengravingconfiguration.h" // IWYU pragma: keep
51 :
52 : // TODO: Don't include from engraving/internal
53 : #include "engraving/internal/qmimedataadapter.h"
54 :
55 : #include "engraving/dom/accidental.h"
56 : #include "engraving/dom/actionicon.h"
57 : #include "engraving/dom/anchors.h"
58 : #include "engraving/dom/articulation.h"
59 : #include "engraving/dom/barline.h"
60 : #include "engraving/dom/box.h"
61 : #include "engraving/dom/bracket.h"
62 : #include "engraving/dom/chord.h"
63 : #include "engraving/dom/drumset.h"
64 : #include "engraving/dom/dummyparent.h"
65 : #include "engraving/dom/dynamic.h"
66 : #include "engraving/dom/elementgroup.h"
67 : #include "engraving/dom/factory.h"
68 : #include "engraving/dom/figuredbass.h"
69 : #include "engraving/dom/fret.h"
70 : #include "engraving/dom/gradualtempochange.h"
71 : #include "engraving/dom/guitarbend.h"
72 : #include "engraving/dom/hammeronpulloff.h"
73 : #include "engraving/dom/image.h"
74 : #include "engraving/dom/instrchange.h"
75 : #include "engraving/dom/keysig.h"
76 : #include "engraving/dom/lasso.h"
77 : #include "engraving/dom/layoutbreak.h"
78 : #include "engraving/dom/linkedobjects.h" // IWYU pragma: keep
79 : #include "engraving/dom/lyrics.h"
80 : #include "engraving/dom/masterscore.h"
81 : #include "engraving/dom/measure.h"
82 : #include "engraving/dom/measurerepeat.h"
83 : #include "engraving/dom/mscore.h"
84 : #include "engraving/dom/page.h"
85 : #include "engraving/dom/part.h"
86 : #include "engraving/dom/pitchspelling.h"
87 : #include "engraving/dom/realizedharmony.h"
88 : #include "engraving/dom/rest.h"
89 : #include "engraving/dom/shadownote.h"
90 : #include "engraving/dom/slur.h"
91 : #include "engraving/dom/soundflag.h"
92 : #include "engraving/dom/staff.h"
93 : #include "engraving/dom/stafflines.h"
94 : #include "engraving/dom/stafftype.h"
95 : #include "engraving/dom/stafftypechange.h"
96 : #include "engraving/dom/system.h"
97 : #include "engraving/dom/tuplet.h"
98 : #include "engraving/dom/utils.h"
99 : #include "engraving/editing/editbeam.h"
100 : #include "engraving/editing/editchord.h"
101 : #include "engraving/editing/editclef.h"
102 : #include "engraving/editing/editcrossstaff.h"
103 : #include "engraving/editing/editduration.h"
104 : #include "engraving/editing/editenharmonicspelling.h"
105 : #include "engraving/editing/edithairpin.h"
106 : #include "engraving/editing/editnote.h"
107 : #include "engraving/editing/editspanner.h"
108 : #include "engraving/editing/editaccidentalbrackets.h"
109 : #include "engraving/editing/editparentheses.h"
110 : #include "engraving/editing/editrehearsalmark.h"
111 : #include "engraving/editing/editvisibility.h"
112 : #include "engraving/editing/editvoice.h"
113 : #include "engraving/editing/paste.h"
114 : #include "engraving/editing/realizechordsymbols.h"
115 : #include "engraving/editing/regroup.h"
116 : #include "engraving/editing/reset.h"
117 : #include "engraving/editing/navigation.h"
118 : #include "engraving/editing/editmeasurerepeat.h"
119 : #include "engraving/editing/noteinput.h"
120 : #include "engraving/editing/editpart.h"
121 : #include "engraving/editing/editlyrics.h"
122 : #include "engraving/editing/editslashnotation.h"
123 : #include "engraving/editing/editslur.h"
124 : #include "engraving/editing/editstavesharing.h"
125 : #include "engraving/editing/editstretch.h"
126 : #include "engraving/editing/edittie.h"
127 : #include "engraving/editing/edittimesig.h"
128 : #include "engraving/editing/edittuplet.h"
129 : #include "engraving/editing/editpagelocks.h"
130 : #include "engraving/editing/editposition.h"
131 : #include "engraving/editing/editsystemlocks.h"
132 : #include "engraving/editing/flip.h"
133 : #include "engraving/editing/exchangevoices.h"
134 : #include "engraving/editing/implodeexplode.h"
135 : #include "engraving/editing/splitjoinmeasure.h"
136 : #include "engraving/editing/textedit.h"
137 : #include "engraving/editing/transaction/transaction.h"
138 : #include "engraving/editing/transpose.h"
139 : #include "engraving/rendering/iscorerenderer.h"
140 : #include "engraving/rw/rwregister.h"
141 : #include "engraving/rw/xmlreader.h"
142 :
143 : #include "inotationviewstate.h"
144 : #include "notationerrors.h"
145 : #include "notation.h"
146 : #include "notationnoteinput.h"
147 : #include "notationselection.h"
148 : #include "notationselectionfilter.h"
149 : #include "scorecallbacks.h"
150 : #include "inotationelements.h"
151 :
152 : #include "utilities/scorerangeutilities.h"
153 :
154 : #include "app_config.h"
155 :
156 : using namespace mu::notation;
157 : using namespace mu::engraving;
158 : using namespace muse;
159 : using namespace muse::draw;
160 : using namespace muse::io;
161 :
162 0 : static mu::engraving::KeyboardModifier keyboardModifier(Qt::KeyboardModifiers km)
163 : {
164 0 : return mu::engraving::KeyboardModifier(int(km));
165 : }
166 :
167 0 : static double nudgeDistance(const EngravingItem* item, bool quickly, double raster)
168 : {
169 0 : const double spatium = item->spatium();
170 :
171 0 : double distance = 0.0;
172 0 : if (item->isBeam()) {
173 0 : distance = quickly ? spatium : spatium * 0.25;
174 : } else {
175 0 : distance = spatium * (quickly ? mu::engraving::MScore::nudgeStep10 : mu::engraving::MScore::nudgeStep);
176 : }
177 :
178 0 : if (raster > 0) {
179 0 : distance = std::max(distance, spatium / raster);
180 : }
181 :
182 0 : return distance;
183 : }
184 :
185 0 : static PointF bindCursorPosToText(const PointF& cursorPos, const EngravingItem* text)
186 : {
187 0 : if (cursorPos.isNull() || !text || !text->isTextBase()) {
188 0 : return PointF();
189 : }
190 :
191 0 : muse::RectF bbox = text->canvasBoundingRect();
192 : muse::PointF boundPos = muse::PointF(
193 0 : cursorPos.x() < bbox.left() ? bbox.left()
194 0 : : cursorPos.x() >= bbox.right() ? bbox.right() - 1 : cursorPos.x(),
195 0 : cursorPos.y() < bbox.top() ? bbox.top()
196 0 : : cursorPos.y() >= bbox.bottom() ? bbox.bottom() - 1 : cursorPos.y());
197 :
198 0 : return boundPos;
199 : }
200 :
201 0 : static AccidentalType accidentalType(const InputState& is, const NoteVal& nval, int line)
202 : {
203 0 : if (is.rest()) {
204 0 : return AccidentalType::NONE;
205 : }
206 :
207 0 : AccidentalVal accVal = AccidentalVal::NATURAL;
208 0 : if (is.accidentalType() != AccidentalType::NONE) {
209 0 : accVal = Accidental::subtype2value(is.accidentalType());
210 : } else {
211 0 : accVal = mu::engraving::noteValToAccidentalVal(nval, is.staff(), is.tick());
212 : }
213 :
214 0 : bool error = false;
215 0 : const AccidentalVal existingAccVal = is.segment()->measure()->findAccidental(is.segment(), is.staffIdx(), line, error);
216 :
217 0 : if (!error && accVal != existingAccVal) {
218 0 : AccidentalType type = Accidental::value2subtype(accVal);
219 0 : if (type == AccidentalType::NONE) {
220 0 : type = AccidentalType::NATURAL;
221 : }
222 :
223 0 : return type;
224 : }
225 :
226 0 : return AccidentalType::NONE;
227 : }
228 :
229 0 : inline QString extractSyllable(const QString& text)
230 : {
231 0 : QString _text = text;
232 :
233 0 : static const QRegularExpression lineBreaks("(\r|\n)+");
234 0 : _text.replace(lineBreaks, "\n");
235 0 : if (_text.startsWith(u"\n")) {
236 0 : _text.remove("\n");
237 : }
238 :
239 0 : static const QRegularExpression nonWhitespace("\\S");
240 0 : int textPos = _text.indexOf(nonWhitespace);
241 0 : if (textPos == -1) {
242 0 : return QString();
243 : }
244 :
245 0 : static const QRegularExpression separators("(_| |-|\n)");
246 0 : QRegularExpressionMatch match;
247 0 : int splitPos = _text.indexOf(separators, textPos, &match);
248 0 : if (splitPos == -1) {
249 0 : splitPos = _text.size();
250 : } else {
251 0 : splitPos += match.capturedLength();
252 : }
253 :
254 0 : return _text.mid(textPos, splitPos - textPos);
255 0 : }
256 :
257 0 : NotationInteraction::NotationInteraction(Notation* notation, INotationUndoStackPtr undoStack)
258 0 : : muse::Contextable(notation->iocContext()), m_notation(notation), m_undoStack(undoStack), m_editData(&m_scoreCallbacks)
259 : {
260 0 : m_selection = std::make_shared<NotationSelection>(notation, this);
261 0 : m_noteInput = std::make_shared<NotationNoteInput>(notation, this, m_undoStack, iocContext());
262 :
263 0 : m_selectionFilter = std::make_shared<NotationSelectionFilter>(notation, [this]() {
264 0 : m_selection->notifyAboutSelectionChangedIfNeed();
265 0 : });
266 :
267 0 : m_errorsController = std::make_shared<MScoreErrorsController>(iocContext());
268 :
269 0 : m_noteInput->stateChanged().onNotify(this, [this]() {
270 0 : if (!m_noteInput->isNoteInputMode()) {
271 0 : hideShadowNote();
272 : }
273 0 : });
274 :
275 0 : m_undoStack->undoRedoNotification().onNotify(this, [this]() {
276 0 : if (!isTextEditingStarted()) {
277 0 : endEditElement();
278 : }
279 0 : });
280 :
281 0 : m_undoStack->stackChanged().onNotify(this, [this]() {
282 0 : m_selection->notifyAboutSelectionChangedIfNeed();
283 0 : notifyAboutNoteInputStateChanged();
284 0 : });
285 :
286 0 : m_selection->selectionChanged().onNotify(this, [this]() {
287 0 : if (noteInput()->isNoteInputMode()) {
288 0 : notifyAboutNoteInputStateChanged();
289 : }
290 0 : });
291 :
292 0 : m_dragData.ed = mu::engraving::EditData(&m_scoreCallbacks);
293 :
294 0 : m_scoreCallbacks.setNotationInteraction(this);
295 :
296 0 : m_notation->scoreInited().onNotify(this, [this]() {
297 0 : onScoreInited();
298 0 : });
299 :
300 0 : m_notation->viewModeChanged().onNotify(this, [this]() {
301 0 : onViewModeChanged();
302 0 : });
303 :
304 0 : QObject::connect(&m_textCursorBlinkTimer, &QTimer::timeout, [this]() { blinkTextCursor(); });
305 0 : textEditingChanged().onNotify(this, [this]() {
306 0 : onTextEditingChanged();
307 0 : });
308 0 : }
309 :
310 0 : mu::engraving::Score* NotationInteraction::score() const
311 : {
312 0 : return m_notation->score();
313 : }
314 :
315 0 : void NotationInteraction::onScoreInited()
316 : {
317 0 : if (!score()) {
318 0 : return;
319 : }
320 :
321 0 : m_previewMeasure.setScore(score());
322 0 : m_scoreCallbacks.setScore(score());
323 :
324 0 : score()->elementDestroyed().onReceive(this, [this](mu::engraving::EngravingItem* element) {
325 0 : onElementDestroyed(element);
326 0 : });
327 : }
328 :
329 0 : void NotationInteraction::onViewModeChanged()
330 : {
331 0 : if (!score()) {
332 0 : return;
333 : }
334 :
335 0 : if (!score()->isLayoutMode(LayoutMode::LINE) && !score()->isLayoutMode(LayoutMode::HORIZONTAL_FIXED)) {
336 0 : return;
337 : }
338 :
339 : // VBoxes are not included in horizontal layouts - deselect them (and their contents) when switching to horizontal mode...
340 0 : const std::vector<EngravingItem*> sel = selection()->elements();
341 0 : for (EngravingItem* item : sel) {
342 0 : if (!item->findAncestor(ElementType::VBOX) || !item->findAncestor(ElementType::FBOX)) {
343 0 : continue;
344 : }
345 0 : score()->deselect(item);
346 0 : if (item == m_editData.element) {
347 0 : endEditElement();
348 : }
349 : }
350 0 : }
351 :
352 0 : void NotationInteraction::transaction(const muse::TranslatableString& actionName, std::function<void(mu::engraving::Transaction&)> func)
353 : {
354 0 : m_undoStack->transaction(actionName, func);
355 0 : }
356 :
357 0 : void NotationInteraction::startEdit(const muse::TranslatableString& actionName)
358 : {
359 0 : m_notifyAboutDropChanged = false;
360 :
361 0 : m_undoStack->prepareChanges(actionName);
362 0 : }
363 :
364 0 : void NotationInteraction::apply()
365 : {
366 0 : m_undoStack->commitChanges();
367 :
368 0 : if (m_notifyAboutDropChanged) {
369 0 : notifyAboutDropChanged();
370 : } else {
371 0 : notifyAboutNotationChanged();
372 : }
373 0 : }
374 :
375 0 : void NotationInteraction::rollback()
376 : {
377 0 : m_undoStack->rollbackChanges();
378 0 : }
379 :
380 0 : void NotationInteraction::notifyAboutDragChanged()
381 : {
382 0 : m_dragChanged.notify();
383 0 : }
384 :
385 0 : void NotationInteraction::notifyAboutDropChanged()
386 : {
387 0 : m_dropChanged.notify();
388 0 : }
389 :
390 0 : void NotationInteraction::notifyAboutNotationChanged(const muse::RectF& updateRect)
391 : {
392 0 : TRACEFUNC;
393 :
394 0 : m_notation->notifyAboutNotationChanged(updateRect);
395 0 : }
396 :
397 0 : void NotationInteraction::notifyAboutTextEditingStarted()
398 : {
399 0 : m_textEditingStarted.notify();
400 0 : }
401 :
402 0 : void NotationInteraction::notifyAboutTextEditingChanged()
403 : {
404 0 : m_textEditingChanged.notify();
405 0 : }
406 :
407 0 : void NotationInteraction::notifyAboutTextEditingEnded(TextBase* text)
408 : {
409 0 : m_textEditingEnded.send(text);
410 0 : }
411 :
412 0 : void NotationInteraction::notifyAboutNoteInputStateChanged()
413 : {
414 0 : m_noteInput->stateChanged().notify();
415 0 : }
416 :
417 0 : void NotationInteraction::paint(Painter* painter, const engraving::rendering::PaintOptions& opt)
418 : {
419 0 : m_previewMeasure.paint(painter);
420 :
421 0 : if (shouldDrawInputPreview()) {
422 0 : drawInputPreview(painter, opt);
423 : }
424 :
425 0 : score()->renderer()->drawItem(score()->shadowNote(), painter, opt);
426 :
427 0 : drawAnchorLines(painter);
428 0 : drawTextEditMode(painter, opt);
429 0 : drawSelectionRange(painter);
430 0 : drawGripPoints(painter, opt);
431 0 : drawLasso(painter, opt);
432 0 : drawDrop(painter);
433 0 : }
434 :
435 0 : INotationNoteInputPtr NotationInteraction::noteInput() const
436 : {
437 0 : return m_noteInput;
438 : }
439 :
440 0 : mu::engraving::ShadowNote* NotationInteraction::shadowNote() const
441 : {
442 0 : return score()->shadowNote();
443 : }
444 :
445 0 : void NotationInteraction::showShadowNoteForPosition(const PointF& pos)
446 : {
447 0 : const mu::engraving::InputState& inputState = score()->inputState();
448 0 : mu::engraving::ShadowNote& shadowNote = *score()->shadowNote();
449 :
450 0 : ShadowNoteParams params;
451 0 : if (!score()->getPosition(¶ms.position, pos, inputState.voice())) {
452 0 : shadowNote.setVisible(false);
453 0 : m_shadowNoteChanged.send(/*visible*/ false);
454 0 : return;
455 : }
456 :
457 0 : params.duration = inputState.duration();
458 0 : params.accidentalType = inputState.accidentalType();
459 0 : params.articulationIds = inputState.articulationIds();
460 :
461 0 : const bool show = doShowShadowNote(shadowNote, params);
462 0 : m_shadowNoteChanged.send(show);
463 0 : }
464 :
465 0 : void NotationInteraction::showShadowNoteForMidiPitch(const uint8_t pitch)
466 : {
467 0 : const mu::engraving::InputState& inputState = score()->inputState();
468 0 : mu::engraving::ShadowNote& shadowNote = *score()->shadowNote();
469 :
470 0 : Segment* inputSegment = inputState.segment();
471 0 : const Staff* inputStaff = inputState.staff();
472 0 : const Fraction tick = inputSegment->tick();
473 0 : if (!inputSegment || !inputStaff || !tick.isValid() || inputStaff->isDrumStaff(tick) || inputStaff->isTabStaff(tick)) {
474 : //! NOTE: Not yet compatible with drum or tab staves...
475 0 : hideShadowNote();
476 0 : return;
477 : }
478 :
479 0 : const double mag = inputStaff->staffMag(tick);
480 0 : const double lineDist = inputStaff->staffType(tick)->lineDistance().val()
481 0 : * 0.5 * mag * score()->style().spatium();
482 :
483 0 : const int octave = pitch / 12;
484 0 : const int line = octave * 7 + mu::engraving::pitch2step(pitch);
485 0 : const ClefType clef = inputStaff->clef(tick);
486 0 : const int rLine = mu::engraving::relStep(line, clef);
487 :
488 0 : const double xPos = inputSegment->canvasPos().x();
489 0 : const double yPos = inputSegment->system()->staffCanvasYpage(inputStaff->idx()) + rLine * lineDist;
490 :
491 0 : const PointF point = { xPos, yPos };
492 :
493 0 : const Position position { inputSegment, inputStaff->idx(), rLine, INVALID_FRET_INDEX, point };
494 0 : ShadowNoteParams params { inputState.duration(), inputState.accidentalType(), inputState.articulationIds(), position };
495 :
496 0 : const bool show = doShowShadowNote(shadowNote, params);
497 0 : m_shadowNoteChanged.send(show);
498 0 : }
499 :
500 0 : bool NotationInteraction::doShowShadowNote(ShadowNote& shadowNote, ShadowNoteParams& params)
501 : {
502 0 : Position& position = params.position;
503 :
504 0 : const mu::engraving::InputState& inputState = score()->inputState();
505 0 : const Staff* staff = score()->staff(position.staffIdx);
506 :
507 0 : mu::engraving::Segment* segment = position.segment;
508 :
509 0 : mu::engraving::Segment* shadowNoteActualSegment = position.segment->prev1enabled();
510 0 : if (shadowNoteActualSegment) {
511 0 : segment = shadowNoteActualSegment;
512 : }
513 :
514 0 : Fraction tick = segment->tick();
515 0 : qreal mag = staff->staffMag(tick);
516 :
517 0 : const mu::engraving::Instrument* instr = staff->part()->instrument(tick);
518 :
519 0 : mu::engraving::NoteHeadGroup noteheadGroup = mu::engraving::NoteHeadGroup::HEAD_NORMAL;
520 0 : mu::engraving::NoteHeadType noteHead = params.duration.headType();
521 :
522 0 : int line = position.line;
523 0 : voice_idx_t voice = 0;
524 0 : int drumNotePitch = -1;
525 :
526 0 : if (instr->useDrumset()) {
527 0 : const Drumset* ds = instr->drumset();
528 :
529 0 : const int noteInputPitch = inputState.drumNote();
530 :
531 0 : if (ds->isValid(noteInputPitch) && ds->line(noteInputPitch) == line) {
532 0 : noteheadGroup = ds->noteHead(noteInputPitch);
533 0 : voice = ds->voice(noteInputPitch);
534 0 : drumNotePitch = noteInputPitch;
535 : } else {
536 0 : const int pitch = ds->defaultPitchForLine(line);
537 0 : if (ds->isValid(pitch)) {
538 0 : noteheadGroup = ds->noteHead(pitch);
539 0 : voice = ds->voice(pitch);
540 0 : drumNotePitch = pitch;
541 : }
542 0 : if (drumNotePitch < 0) {
543 0 : shadowNote.setVisible(false);
544 0 : return false;
545 : }
546 : }
547 : } else {
548 0 : voice = inputState.voice();
549 : }
550 :
551 0 : shadowNote.setVisible(true);
552 0 : shadowNote.mutldata()->setMag(mag);
553 0 : shadowNote.setTick(tick);
554 0 : shadowNote.setStaffIdx(position.staffIdx);
555 0 : shadowNote.setVoice(voice);
556 0 : shadowNote.setLineIndex(line);
557 :
558 0 : const Color color = configuration()->noteInputPreviewColor();
559 0 : if (color.isValid() && color != configuration()->selectionColor()) {
560 0 : shadowNote.setColor(color);
561 : } else {
562 0 : shadowNote.setColor(configuration()->highlightSelectionColor(voice));
563 : }
564 :
565 : mu::engraving::SymId symNotehead;
566 :
567 0 : if (inputState.rest()) {
568 0 : Score* s = score()->paletteScore() ? score()->paletteScore() : score();
569 0 : mu::engraving::Rest* rest = mu::engraving::Factory::createRest(s->dummy(), params.duration.type());
570 0 : rest->setTicks(params.duration.fraction());
571 0 : symNotehead = rest->getSymbol(params.duration.type(), 0, staff->lines(position.segment->tick()));
572 0 : shadowNote.setState(symNotehead, params.duration, true, params.position.beyondScore);
573 0 : delete rest;
574 : } else {
575 0 : if (mu::engraving::NoteHeadGroup::HEAD_CUSTOM == noteheadGroup) {
576 0 : symNotehead = instr->drumset()->noteHeads(drumNotePitch, noteHead);
577 : } else {
578 0 : symNotehead = Note::noteHead(0, noteheadGroup, noteHead);
579 : }
580 :
581 0 : shadowNote.setState(symNotehead, params.duration, false, params.position.beyondScore, params.accidentalType,
582 0 : params.articulationIds);
583 : }
584 :
585 : // if upscaled, note appears by default a distance away from the segment start,
586 : // as described in ChordLayout::centreChords
587 0 : if (mag > 1.0) {
588 0 : qreal xOffset = (mag - 1.0) * 0.5 * shadowNote.symWidth(symNotehead);
589 0 : if (shadowNote.computeUp()) {
590 0 : position.pos.rx() += xOffset;
591 : } else {
592 0 : position.pos.rx() -= xOffset;
593 : }
594 : }
595 :
596 : // in any empty measure, pos will be right next to barline
597 : // so pad this by barNoteDistance
598 0 : qreal relX = position.pos.x() - position.segment->measure()->canvasPos().x();
599 0 : position.pos.rx() -= qMin(relX - score()->style().styleAbsolute(mu::engraving::Sid::barNoteDistance), 0.0);
600 :
601 0 : score()->renderer()->layoutItem(&shadowNote);
602 :
603 0 : shadowNote.setPos(position.pos);
604 :
605 0 : return true;
606 : }
607 :
608 0 : void NotationInteraction::hideShadowNote()
609 : {
610 0 : score()->shadowNote()->setVisible(false);
611 0 : m_shadowNoteChanged.send(/*visible*/ false);
612 0 : }
613 :
614 0 : RectF NotationInteraction::shadowNoteRect() const
615 : {
616 0 : const ShadowNote* note = score()->shadowNote();
617 0 : if (!note) {
618 0 : return RectF();
619 : }
620 :
621 0 : RectF rect = note->canvasBoundingRect();
622 :
623 0 : double penWidth = note->style().styleAbsolute(Sid::stemWidth);
624 0 : if (note->ledgerLinesVisible()) {
625 0 : double w = note->style().styleAbsolute(Sid::ledgerLineWidth);
626 0 : penWidth = std::max(penWidth, w);
627 : }
628 :
629 0 : penWidth *= note->mag();
630 0 : rect.adjust(-penWidth, -penWidth, penWidth, penWidth);
631 :
632 0 : return rect;
633 : }
634 :
635 0 : RectF NotationInteraction::previewMeasureRect() const
636 : {
637 0 : return m_previewMeasure.rect();
638 : }
639 :
640 0 : muse::async::Channel<bool> NotationInteraction::shadowNoteChanged() const
641 : {
642 0 : return m_shadowNoteChanged;
643 : }
644 :
645 0 : void NotationInteraction::toggleVisible()
646 : {
647 0 : transaction(TranslatableString("undoableAction", "Toggle visible"), [this](Transaction& tx) {
648 0 : EditVisibility::toggleVisible(tx, score());
649 0 : });
650 0 : }
651 :
652 0 : void NotationInteraction::setSelectionVisible(bool visible)
653 : {
654 0 : if (visible) {
655 0 : transaction(TranslatableString("undoableAction", "Make element(s) visible"), [this](Transaction& tx) {
656 0 : EditVisibility::setSelectedElementsVisible(tx, score());
657 0 : });
658 : } else {
659 0 : transaction(TranslatableString("undoableAction", "Make element(s) invisible"), [this](Transaction& tx) {
660 0 : EditVisibility::setSelectedElementsInvisible(tx, score());
661 0 : });
662 : }
663 0 : }
664 :
665 0 : EngravingItem* NotationInteraction::hitElement(const PointF& pos, float width) const
666 : {
667 0 : std::vector<mu::engraving::EngravingItem*> elements = hitElements(pos, width);
668 0 : if (elements.empty()) {
669 0 : return nullptr;
670 : }
671 0 : m_selection->onElementHit(elements.back());
672 0 : return elements.back();
673 0 : }
674 :
675 0 : Staff* NotationInteraction::hitStaff(const PointF& pos) const
676 : {
677 0 : return hitMeasure(pos).staff;
678 : }
679 :
680 0 : mu::engraving::Page* NotationInteraction::point2page(const PointF& p, bool useNearestPage) const
681 : {
682 0 : if (score()->linearMode()) {
683 0 : return score()->pages().empty() ? nullptr : score()->pages().front();
684 : }
685 :
686 0 : double shortestDistance = std::numeric_limits<double>::max();
687 0 : Page* nearestPage = nullptr;
688 0 : for (mu::engraving::Page* page : score()->pages()) {
689 0 : auto pageRect = page->ldata()->bbox().translated(page->pos());
690 0 : if (pageRect.contains(p)) {
691 0 : return page;
692 0 : } else if (useNearestPage && pageRect.distanceTo(p) < shortestDistance) {
693 0 : shortestDistance = pageRect.distanceTo(p);
694 0 : nearestPage = page;
695 : }
696 : }
697 0 : return nearestPage;
698 : }
699 :
700 0 : std::vector<EngravingItem*> NotationInteraction::elementsAt(const PointF& p) const
701 : {
702 0 : mu::engraving::Page* page = point2page(p);
703 0 : if (!page) {
704 0 : return {};
705 : }
706 :
707 0 : std::vector<EngravingItem*> el = page->items(p - page->pos());
708 0 : if (el.empty()) {
709 0 : return {};
710 : }
711 :
712 0 : std::sort(el.begin(), el.end(), NotationInteraction::elementIsLess);
713 :
714 0 : return el;
715 0 : }
716 :
717 0 : EngravingItem* NotationInteraction::elementAt(const PointF& p) const
718 : {
719 0 : std::vector<EngravingItem*> el = elementsAt(p);
720 0 : return el.empty() || el.back()->isPage() ? nullptr : el.back();
721 0 : }
722 :
723 0 : std::vector<EngravingItem*> NotationInteraction::hitElements(const PointF& pos, float width) const
724 : {
725 0 : mu::engraving::Page* page = point2page(pos);
726 0 : if (!page) {
727 0 : return {};
728 : }
729 :
730 0 : std::vector<EngravingItem*> hitElements;
731 :
732 0 : PointF posOnPage = pos - page->pos();
733 :
734 0 : if (isTextEditingStarted() && page == m_editData.element->findAncestor(ElementType::PAGE)) {
735 0 : auto editW = width * 2;
736 0 : RectF editHitRect(posOnPage.x() - editW, posOnPage.y() - editW, 2.0 * editW, 2.0 * editW);
737 0 : if (m_editData.element->intersects(editHitRect)) {
738 0 : hitElements.push_back(m_editData.element);
739 0 : return hitElements;
740 : }
741 : }
742 :
743 0 : RectF hitRect(posOnPage.x() - width, posOnPage.y() - width, 3.0 * width, 3.0 * width);
744 :
745 0 : std::vector<EngravingItem*> potentiallyHitElements = page->items(hitRect);
746 :
747 0 : auto canHitElement = [](const EngravingItem* element) {
748 0 : if (!element->selectable() || element->isPage()) {
749 0 : return false;
750 : }
751 :
752 0 : if (element->isSoundFlag()) {
753 0 : return !toSoundFlag(element)->shouldHide();
754 0 : } else if (!element->isInteractionAvailable()) {
755 0 : return false;
756 : }
757 :
758 0 : return true;
759 : };
760 :
761 0 : for (EngravingItem* element : potentiallyHitElements) {
762 0 : element->itemDiscovered = 0;
763 :
764 0 : if (!canHitElement(element)) {
765 0 : continue;
766 : }
767 :
768 0 : if (element->hitShapeContains(posOnPage)) {
769 0 : hitElements.push_back(element);
770 : }
771 : }
772 :
773 0 : if (hitElements.empty() || (hitElements.size() == 1 && hitElements.front()->isMeasure())) {
774 : //
775 : // if no relevant element hit, look nearby
776 : //
777 0 : for (EngravingItem* element : potentiallyHitElements) {
778 0 : if (!canHitElement(element)) {
779 0 : continue;
780 : }
781 :
782 0 : if (element->hitShapeIntersects(hitRect)) {
783 0 : hitElements.push_back(element);
784 : }
785 : }
786 : }
787 :
788 0 : if (!hitElements.empty()) {
789 0 : std::sort(hitElements.begin(), hitElements.end(), NotationInteraction::elementIsLess);
790 : } else {
791 0 : Measure* measure = hitMeasure(pos).measure;
792 0 : if (measure) {
793 0 : hitElements.push_back(measure);
794 : }
795 : }
796 :
797 0 : return hitElements;
798 0 : }
799 :
800 0 : NotationInteraction::HitMeasureData NotationInteraction::hitMeasure(const PointF& pos) const
801 : {
802 0 : mu::engraving::staff_idx_t staffIndex = muse::nidx;
803 0 : mu::engraving::Segment* segment = nullptr;
804 0 : PointF offset;
805 :
806 0 : Measure* measure = score()->pos2measure(pos, &staffIndex, /*pitch*/ 0, &segment, &offset);
807 :
808 0 : HitMeasureData result;
809 0 : if (measure && measure->staffLines(staffIndex)->canvasHitShape().contains(pos)) {
810 0 : result.measure = measure;
811 0 : result.staff = score()->staff(staffIndex);
812 : }
813 :
814 0 : return result;
815 : }
816 :
817 0 : bool NotationInteraction::elementIsLess(const EngravingItem* e1, const EngravingItem* e2)
818 : {
819 0 : if (e1->selectable() && !e2->selectable()) {
820 0 : return false;
821 : }
822 0 : if (!e1->selectable() && e2->selectable()) {
823 0 : return true;
824 : }
825 0 : if (e1->isNote() && (e2->isStem() || e2->isHook())) {
826 0 : return false;
827 : }
828 0 : if (e2->isNote() && (e1->isStem() || e1->isHook())) {
829 0 : return true;
830 : }
831 0 : if (e1->isStem() && e2->isHook()) {
832 0 : return false;
833 : }
834 0 : if (e2->isStem() && e1->isHook()) {
835 0 : return true;
836 : }
837 0 : if (e1->isText() && e2->isBox()) {
838 0 : return false;
839 : }
840 0 : if (e1->isBox() && e2->isText()) {
841 0 : return true;
842 : }
843 0 : if (e1->isImage() && e2->isBox()) {
844 0 : return false;
845 : }
846 0 : if (e1->isBox() && e2->isImage()) {
847 0 : return true;
848 : }
849 0 : if ((e1->isHarmony() || e1->isFretDiagram()) && e2->isFBox()) {
850 0 : return false;
851 : }
852 0 : if (e1->isFBox() && (e2->isHarmony() || e2->isFretDiagram())) {
853 0 : return true;
854 : }
855 0 : if (e1->z() == e2->z()) {
856 : // same stacking order, prefer non-hidden elements
857 0 : if (e1->type() == e2->type()) {
858 0 : if (e1->isNoteDot()) {
859 0 : const NoteDot* n1 = toNoteDot(e1);
860 0 : const NoteDot* n2 = toNoteDot(e2);
861 0 : if (n1->note() && n1->note()->hidden()) {
862 0 : return false;
863 0 : } else if (n2->note() && n2->note()->hidden()) {
864 0 : return true;
865 : }
866 0 : } else if (e1->isNote()) {
867 0 : const Note* n1 = toNote(e1);
868 0 : const Note* n2 = toNote(e2);
869 0 : if (n1->hidden()) {
870 0 : return false;
871 0 : } else if (n2->hidden()) {
872 0 : return true;
873 : }
874 : }
875 : }
876 : // different types, or same type but nothing hidden - use track
877 0 : return e1->track() < e2->track();
878 : }
879 :
880 : // default case, use stacking order
881 0 : return e1->z() < e2->z();
882 : }
883 :
884 0 : const NotationInteraction::HitElementContext& NotationInteraction::hitElementContext() const
885 : {
886 0 : return m_hitElementContext;
887 : }
888 :
889 0 : void NotationInteraction::setHitElementContext(const HitElementContext& context)
890 : {
891 0 : m_hitElementContext = context;
892 0 : }
893 :
894 0 : EngravingItem* NotationInteraction::contextItem() const
895 : {
896 0 : EngravingItem* item = selection()->element();
897 0 : return item ? item : hitElementContext().element;
898 : }
899 :
900 0 : void NotationInteraction::findAndSelectChordRest(const Fraction& tick)
901 : {
902 0 : IF_ASSERT_FAILED(selection() && score()) {
903 0 : return;
904 : }
905 :
906 0 : Segment* startSeg = score()->tick2leftSegment(tick, /*useMMrest*/ false, SegmentType::ChordRest);
907 0 : IF_ASSERT_FAILED(startSeg && startSeg->isChordRestType()) {
908 0 : return;
909 : }
910 :
911 0 : staff_idx_t lastSelectedStaffIdx = 0;
912 0 : voice_idx_t lastSelectedVoiceIdx = 0;
913 0 : if (selection()->isRange()) {
914 0 : lastSelectedStaffIdx = selection()->range()->startStaffIndex();
915 0 : } else if (!selection()->elements().empty()) {
916 0 : const EngravingItem* lastSelectedItem = selection()->elements().back();
917 0 : if (lastSelectedItem) {
918 0 : lastSelectedStaffIdx = lastSelectedItem->staffIdx();
919 0 : lastSelectedVoiceIdx = lastSelectedItem->voice();
920 : }
921 : }
922 :
923 : // startSeg could be a CR segment in any staff. The idea of this method is to select the CR in the last selected
924 : // staff (or the top staff if none was selected). The following outer loop iterates backwards through previous CR
925 : // segments until a valid CR is found in the desired staff...
926 0 : EngravingItem* toSelect = nullptr;
927 0 : for (Segment* currSeg = startSeg; currSeg && !toSelect; currSeg = currSeg->prev(SegmentType::ChordRest)) {
928 0 : toSelect = currSeg->element(staff2track(lastSelectedStaffIdx, lastSelectedVoiceIdx));
929 0 : if (toSelect && toSelect->isChordRest()) {
930 0 : break;
931 : }
932 0 : toSelect = nullptr;
933 : // Inner loop: Couldn't find a valid CR in the last selected voice - try other voices in the same staff...
934 0 : for (voice_idx_t currVoice = 0; currVoice < VOICES; ++currVoice) {
935 0 : if (currVoice == lastSelectedVoiceIdx) {
936 : // Already tried this...
937 0 : continue;
938 : }
939 0 : toSelect = currSeg->element(staff2track(lastSelectedStaffIdx, currVoice));
940 0 : if (toSelect && toSelect->isChordRest()) {
941 0 : break;
942 : }
943 0 : toSelect = nullptr;
944 : }
945 : }
946 :
947 0 : IF_ASSERT_FAILED(toSelect) {
948 0 : return;
949 : }
950 :
951 0 : std::vector<EngravingItem*> itemsToSelect;
952 0 : if (toSelect->isChord()) {
953 0 : const std::vector<Note*>& notes = toChord(toSelect)->notes();
954 0 : itemsToSelect.insert(itemsToSelect.end(), notes.begin(), notes.end());
955 : } else {
956 0 : itemsToSelect = { toSelect };
957 : }
958 :
959 0 : select(itemsToSelect, SelectType::REPLACE);
960 0 : }
961 :
962 0 : muse::Ret NotationInteraction::select(const std::vector<EngravingItem*>& elements, SelectType type, staff_idx_t staffIndex)
963 : {
964 0 : if (needEndTextEditing(elements)) {
965 0 : endEditText();
966 0 : } else if (needEndElementEditing(elements)) {
967 0 : endEditElement();
968 : }
969 :
970 0 : return m_selection->select(elements, type, staffIndex);
971 : }
972 :
973 0 : muse::Ret NotationInteraction::select(SelectionTarget target)
974 : {
975 0 : return m_selection->select(target);
976 : }
977 :
978 0 : muse::Ret NotationInteraction::addToSelection(SelectionTarget target)
979 : {
980 0 : return m_selection->addToSelection(target);
981 : }
982 :
983 0 : void NotationInteraction::selectAndStartEditIfNeeded(EngravingItem* element)
984 : {
985 0 : if (element->isSpanner() && !toSpanner(element)->segmentsEmpty()) {
986 0 : element = toSpanner(element)->frontSegment();
987 : }
988 :
989 0 : select({ element }, SelectType::SINGLE);
990 :
991 0 : if (element->needStartEditingAfterSelecting()) {
992 0 : startEditElement(element);
993 : }
994 0 : }
995 :
996 0 : INotationSelectionPtr NotationInteraction::selection() const
997 : {
998 0 : return m_selection;
999 : }
1000 :
1001 0 : void NotationInteraction::clearSelection()
1002 : {
1003 0 : TRACEFUNC;
1004 :
1005 0 : if (isEditingElement()) {
1006 0 : endEditElement();
1007 : }
1008 :
1009 0 : if (isDragStarted()) {
1010 0 : doEndDrag();
1011 0 : rollback();
1012 0 : notifyAboutNotationChanged();
1013 : }
1014 :
1015 0 : if (selection()->isNone()) {
1016 0 : return;
1017 : }
1018 :
1019 0 : m_selection->clearSelection();
1020 :
1021 0 : setHitElementContext(HitElementContext());
1022 0 : }
1023 :
1024 0 : muse::async::Notification NotationInteraction::selectionChanged() const
1025 : {
1026 0 : return m_selection->selectionChanged();
1027 : }
1028 :
1029 0 : INotationSelectionFilterPtr NotationInteraction::selectionFilter() const
1030 : {
1031 0 : return m_selectionFilter;
1032 : }
1033 :
1034 0 : INotationElementsPtr NotationInteraction::elements() const
1035 : {
1036 0 : return m_notation->elements();
1037 : }
1038 :
1039 0 : bool NotationInteraction::isDragStarted() const
1040 : {
1041 0 : if (m_dragData.dragGroups.size() > 0) {
1042 0 : return true;
1043 : }
1044 :
1045 0 : if (m_lasso && !m_lasso->isEmpty()) {
1046 0 : return true;
1047 : }
1048 :
1049 0 : return false;
1050 : }
1051 :
1052 0 : void NotationInteraction::DragData::reset()
1053 : {
1054 0 : beginMove = QPointF();
1055 0 : elementOffset = QPointF();
1056 0 : ed = mu::engraving::EditData(ed.view());
1057 0 : dragGroups.clear();
1058 0 : }
1059 :
1060 0 : void NotationInteraction::startDrag(const std::vector<EngravingItem*>& elems,
1061 : const PointF& eoffset,
1062 : const IsDraggable& isDraggable)
1063 : {
1064 0 : m_dragData.reset();
1065 0 : m_dragData.elements = elems;
1066 0 : m_dragData.elementOffset = eoffset;
1067 0 : m_editData.modifiers = keyboardModifier(QGuiApplication::keyboardModifiers());
1068 :
1069 0 : for (EngravingItem* e : m_dragData.elements) {
1070 0 : bool draggable = isDraggable(e);
1071 :
1072 0 : if (!draggable && e->isSpanner()) {
1073 0 : Spanner* s = toSpanner(e);
1074 0 : draggable = !s->segmentsEmpty() && isDraggable(s->frontSegment());
1075 : }
1076 :
1077 0 : if (!draggable) {
1078 0 : continue;
1079 : }
1080 :
1081 0 : std::unique_ptr<mu::engraving::ElementGroup> g = e->getDragGroup(isDraggable);
1082 0 : if (g && g->enabled()) {
1083 0 : m_dragData.dragGroups.push_back(std::move(g));
1084 : }
1085 0 : }
1086 :
1087 0 : startEdit(TranslatableString("undoableAction", "Drag element(s)", nullptr, int(m_dragData.elements.size())));
1088 :
1089 0 : double scaling = m_notation->viewState()->matrix().m11();
1090 0 : double proximity = configuration()->selectionProximity() * 0.5 / scaling;
1091 0 : m_scoreCallbacks.setSelectionProximity(proximity);
1092 :
1093 0 : if (isGripEditStarted()) {
1094 0 : m_editData.element->startDragGrip(m_editData);
1095 0 : return;
1096 : }
1097 :
1098 0 : m_dragData.ed.modifiers = keyboardModifier(QGuiApplication::keyboardModifiers());
1099 0 : for (auto& group : m_dragData.dragGroups) {
1100 0 : group->startDrag(m_dragData.ed);
1101 : }
1102 : }
1103 :
1104 0 : void NotationInteraction::doDragLasso(const PointF& pt)
1105 : {
1106 0 : if (!m_lasso) {
1107 0 : m_lasso = new mu::engraving::Lasso(score());
1108 : }
1109 :
1110 0 : score()->addRefresh(m_lasso->canvasBoundingRect());
1111 0 : RectF r;
1112 0 : r.setCoords(m_dragData.beginMove.x(), m_dragData.beginMove.y(), pt.x(), pt.y());
1113 0 : m_lasso->setbbox(r.normalized());
1114 0 : score()->addRefresh(m_lasso->canvasBoundingRect());
1115 0 : score()->lassoSelect(m_lasso->ldata()->bbox());
1116 0 : score()->update();
1117 0 : }
1118 :
1119 0 : void NotationInteraction::endLasso()
1120 : {
1121 0 : if (!m_lasso) {
1122 0 : return;
1123 : }
1124 :
1125 0 : score()->addRefresh(m_lasso->canvasBoundingRect());
1126 0 : m_lasso->setbbox(RectF());
1127 0 : score()->lassoSelectEnd();
1128 0 : score()->update();
1129 : }
1130 :
1131 0 : void NotationInteraction::drag(const PointF& fromPos, const PointF& toPos, DragMode mode)
1132 : {
1133 0 : if (m_dragData.beginMove.isNull()) {
1134 0 : m_dragData.beginMove = fromPos;
1135 0 : m_dragData.ed.pos = fromPos;
1136 : }
1137 :
1138 0 : PointF normalizedBegin = m_dragData.beginMove - m_dragData.elementOffset;
1139 0 : PointF delta = toPos - normalizedBegin;
1140 0 : PointF evtDelta = toPos - m_dragData.ed.pos;
1141 0 : PointF moveDelta = delta - m_dragData.elementOffset;
1142 :
1143 0 : bool constrainDirection = !(isGripEditStarted() && m_editData.element && m_editData.element->isBarLine());
1144 0 : if (constrainDirection) {
1145 0 : switch (mode) {
1146 0 : case DragMode::BothXY:
1147 0 : break;
1148 0 : case DragMode::OnlyX:
1149 0 : delta.setY(m_dragData.ed.delta.y());
1150 0 : moveDelta.setY(m_dragData.ed.moveDelta.y());
1151 0 : evtDelta.setY(0.0);
1152 0 : break;
1153 0 : case DragMode::OnlyY:
1154 0 : delta.setX(m_dragData.ed.delta.x());
1155 0 : moveDelta.setX(m_dragData.ed.moveDelta.x());
1156 0 : evtDelta.setX(0.0);
1157 0 : break;
1158 : }
1159 : }
1160 :
1161 0 : m_dragData.ed.lastPos = m_dragData.ed.pos;
1162 :
1163 0 : m_dragData.ed.hRaster = configuration()->isSnappedToGrid(muse::Orientation::Horizontal);
1164 0 : m_dragData.ed.vRaster = configuration()->isSnappedToGrid(muse::Orientation::Vertical);
1165 0 : m_dragData.ed.delta = delta;
1166 0 : m_dragData.ed.moveDelta = moveDelta;
1167 0 : m_dragData.ed.evtDelta = evtDelta;
1168 0 : m_dragData.ed.pos = toPos;
1169 0 : m_dragData.ed.modifiers = keyboardModifier(QGuiApplication::keyboardModifiers());
1170 :
1171 0 : m_dragData.ed.isEditMode = isEditingElement();
1172 :
1173 0 : if (isTextEditingStarted()) {
1174 0 : m_editData.pos = toPos;
1175 0 : toTextBase(m_editData.element)->dragTo(m_editData);
1176 :
1177 0 : notifyAboutTextEditingChanged();
1178 0 : return;
1179 : }
1180 :
1181 0 : if (isGripEditStarted()) {
1182 0 : m_dragData.ed.curGrip = m_editData.curGrip;
1183 0 : m_dragData.ed.delta = evtDelta;
1184 0 : m_dragData.ed.moveDelta = m_dragData.ed.delta - m_dragData.elementOffset;
1185 0 : m_dragData.ed.addData(m_editData.getData(m_editData.element));
1186 0 : m_editData.element->dragGrip(m_dragData.ed);
1187 :
1188 0 : if (m_editData.element->isDynamic()) {
1189 : // When the dynamic has no left grip, the right grip will have index zero, a.k.a. Grip::LEFT.
1190 : // TODO: refactor all code that works with Grips, so that this is not necessary
1191 0 : Dynamic* dynamic = toDynamic(m_editData.element);
1192 0 : bool isLeftGrip = dynamic->hasLeftGrip() ? m_editData.curGrip == Grip::LEFT : false;
1193 0 : addHairpinOnGripDrag(m_editData, isLeftGrip);
1194 : }
1195 : } else {
1196 0 : for (auto& group : m_dragData.dragGroups) {
1197 0 : score()->addRefresh(group->drag(m_dragData.ed));
1198 : }
1199 : }
1200 :
1201 0 : score()->update();
1202 :
1203 0 : if (isGripEditStarted()) {
1204 0 : if (m_editData.element->isDynamic() && !m_editData.isStartEndGrip()) {
1205 0 : updateDragAnchorLines();
1206 : } else {
1207 0 : updateGripAnchorLines();
1208 : }
1209 : } else {
1210 0 : updateDragAnchorLines();
1211 : }
1212 :
1213 0 : if (m_dragData.elements.size() == 0) {
1214 0 : doDragLasso(toPos);
1215 : }
1216 :
1217 0 : notifyAboutDragChanged();
1218 : }
1219 :
1220 0 : void NotationInteraction::doEndDrag()
1221 : {
1222 0 : if (isGripEditStarted()) {
1223 0 : m_editData.element->endDragGrip(m_editData);
1224 0 : m_editData.element->endEdit(m_editData);
1225 : } else {
1226 0 : for (auto& group : m_dragData.dragGroups) {
1227 0 : group->endDrag(m_dragData.ed);
1228 : }
1229 0 : if (m_lasso && !m_lasso->isEmpty()) {
1230 0 : endLasso();
1231 : }
1232 : }
1233 :
1234 0 : m_dragData.reset();
1235 :
1236 0 : if (m_dropData.elementDropData.has_value()) {
1237 0 : setDropTarget(nullptr, false);
1238 : } else {
1239 0 : resetAnchorLines();
1240 : }
1241 0 : }
1242 :
1243 0 : void NotationInteraction::endDrag()
1244 : {
1245 0 : doEndDrag();
1246 0 : apply();
1247 :
1248 0 : if (m_editData.isHairpinDragCreatedFromDynamic) {
1249 : // Merge the two actions of hairpin creation + hairpin drag
1250 0 : assert(m_undoStack->currentStateIndex() >= 2);
1251 0 : if (m_undoStack->currentStateIndex() >= 2) {
1252 0 : m_undoStack->mergeTransactions(m_undoStack->currentStateIndex() - 2);
1253 : }
1254 0 : m_editData.isHairpinDragCreatedFromDynamic = false;
1255 : }
1256 :
1257 0 : notifyAboutDragChanged();
1258 0 : checkAndShowError();
1259 0 : }
1260 :
1261 0 : muse::async::Notification NotationInteraction::dragChanged() const
1262 : {
1263 0 : return m_dragChanged;
1264 : }
1265 :
1266 0 : bool NotationInteraction::isOutgoingDragElementAllowed(const EngravingItem* element) const
1267 : {
1268 0 : if (!element) {
1269 0 : return false;
1270 : }
1271 :
1272 0 : switch (element->type()) {
1273 0 : case ElementType::MEASURE:
1274 : case ElementType::NOTE:
1275 : case ElementType::VBOX:
1276 : case ElementType::HBOX:
1277 : case ElementType::TBOX:
1278 : case ElementType::FBOX:
1279 : // TODO: Bends & NoteLines can't be copy-dragged until corresponding SingleLayout::layout and SingleDraw::draw methods have been implemented
1280 : case ElementType::GUITAR_BEND:
1281 : case ElementType::GUITAR_BEND_SEGMENT:
1282 : case ElementType::GUITAR_BEND_HOLD:
1283 : case ElementType::GUITAR_BEND_HOLD_SEGMENT:
1284 : case ElementType::GUITAR_BEND_TEXT:
1285 : case ElementType::NOTELINE:
1286 : case ElementType::NOTELINE_SEGMENT:
1287 0 : return false;
1288 0 : default: return true;
1289 : }
1290 : }
1291 :
1292 : //! NOTE: Copied from ScoreView::cloneElement
1293 0 : void NotationInteraction::startOutgoingDragElement(const EngravingItem* element, QObject* dragSource, const PointF& hotSpot)
1294 : {
1295 0 : if (isDragStarted()) {
1296 0 : endOutgoingDrag();
1297 : }
1298 :
1299 0 : QMimeData* mimeData = new QMimeData();
1300 0 : if (element->isSpannerSegment()) {
1301 0 : Spanner* s = toSpannerSegment(element)->spanner();
1302 0 : mimeData->setData(mu::engraving::mimeSymbolFormat, s->mimeData().toQByteArray());
1303 : } else {
1304 0 : mimeData->setData(mu::engraving::mimeSymbolFormat, element->mimeData().toQByteArray());
1305 : }
1306 :
1307 0 : m_outgoingDrag = new QDrag(dragSource);
1308 0 : m_outgoingDrag->setMimeData(mimeData);
1309 :
1310 0 : QObject::connect(m_outgoingDrag, &QDrag::destroyed, [this]() {
1311 0 : m_outgoingDrag = nullptr;
1312 0 : });
1313 :
1314 0 : const QScreen* screen = QGuiApplication::primaryScreen();
1315 0 : const qreal physDpiRatio = screen->physicalDotsPerInch() / mu::engraving::DPI;
1316 0 : const qreal devicePixelRatio = screen->devicePixelRatio();
1317 :
1318 0 : const RectF bbox = element->ldata()->bbox().adjusted(-4.0, -4.0, 4.0, 4.0);
1319 0 : const double scaledWidth = bbox.width() * physDpiRatio;
1320 0 : const double scaledHeight = bbox.height() * physDpiRatio;
1321 :
1322 : QPixmap pixmap(qCeil(scaledWidth * devicePixelRatio),
1323 0 : qCeil(scaledHeight * devicePixelRatio));
1324 0 : pixmap.setDevicePixelRatio(devicePixelRatio);
1325 0 : pixmap.fill(Qt::transparent);
1326 :
1327 0 : QPainter qp(&pixmap);
1328 :
1329 0 : Painter p(&qp, "startOutgoingDragElement");
1330 0 : p.setAntialiasing(true);
1331 :
1332 0 : p.scale(physDpiRatio, physDpiRatio);
1333 0 : p.translate(qAbs(bbox.x()), qAbs(bbox.y()));
1334 :
1335 0 : mu::engraving::rendering::PaintOptions opt;
1336 0 : opt.invertColors = configuration()->shouldInvertScore();
1337 0 : engravingRenderer()->drawItem(element, &p, opt);
1338 :
1339 0 : m_outgoingDrag->setPixmap(pixmap);
1340 0 : m_outgoingDrag->setHotSpot((hotSpot * physDpiRatio).toQPoint());
1341 :
1342 0 : m_outgoingDrag->exec(Qt::CopyAction);
1343 0 : }
1344 :
1345 0 : void NotationInteraction::startOutgoingDragRange(QObject* dragSource)
1346 : {
1347 0 : if (isDragStarted()) {
1348 0 : endOutgoingDrag();
1349 : }
1350 :
1351 0 : if (!selection()->isRange() || !selection()->canCopy()) {
1352 0 : return;
1353 : }
1354 :
1355 0 : QMimeData* mimeData = selection()->qMimeData();
1356 0 : if (!mimeData) {
1357 0 : return;
1358 : }
1359 :
1360 0 : m_outgoingDrag = new QDrag(dragSource);
1361 0 : m_outgoingDrag->setMimeData(mimeData);
1362 :
1363 0 : QObject::connect(m_outgoingDrag, &QDrag::destroyed, [this]() {
1364 0 : m_outgoingDrag = nullptr;
1365 0 : });
1366 :
1367 0 : QPixmap pixmap(1, 1);
1368 0 : pixmap.fill(Qt::transparent);
1369 0 : m_outgoingDrag->setPixmap(pixmap);
1370 :
1371 0 : m_outgoingDrag->exec(Qt::MoveAction | Qt::CopyAction);
1372 0 : }
1373 :
1374 0 : bool NotationInteraction::isOutgoingDragStarted() const
1375 : {
1376 0 : return m_outgoingDrag != nullptr;
1377 : }
1378 :
1379 0 : void NotationInteraction::endOutgoingDrag()
1380 : {
1381 0 : if (m_outgoingDrag) {
1382 0 : delete m_outgoingDrag;
1383 0 : m_outgoingDrag = nullptr;
1384 : }
1385 0 : }
1386 :
1387 : //! NOTE Copied from ScoreView::dragEnterEvent
1388 0 : bool NotationInteraction::startDropSingle(const QByteArray& edata)
1389 : {
1390 0 : resetDropData();
1391 :
1392 0 : m_dropData.elementDropData = ElementDropData();
1393 0 : ElementDropData& edd = m_dropData.elementDropData.value();
1394 0 : edd.ed = mu::engraving::EditData(&m_scoreCallbacks);
1395 :
1396 0 : mu::engraving::XmlReader e(edata);
1397 0 : edd.ed.dragOffset = QPointF();
1398 0 : Fraction duration; // dummy
1399 0 : ElementType type = EngravingItem::readType(e, &edd.ed.dragOffset, &duration);
1400 :
1401 0 : EngravingItem* el = engraving::Factory::createItem(type, score()->dummy());
1402 0 : if (el) {
1403 0 : if (type == ElementType::BAR_LINE || type == ElementType::BRACKET) {
1404 0 : double spatium = score()->style().spatium();
1405 0 : el->setHeight(spatium * 5);
1406 : }
1407 0 : edd.ed.dropElement = el;
1408 :
1409 0 : rw::RWRegister::reader()->readItem(edd.ed.dropElement, e);
1410 :
1411 0 : engravingRenderer()->layoutItem(edd.ed.dropElement);
1412 0 : return true;
1413 : }
1414 :
1415 0 : resetDropData();
1416 0 : return false;
1417 0 : }
1418 :
1419 0 : bool NotationInteraction::startDropRange(const QByteArray& data)
1420 : {
1421 0 : resetDropData();
1422 :
1423 0 : m_dropData.rangeDropData = RangeDropData();
1424 0 : RangeDropData& rdd = m_dropData.rangeDropData.value();
1425 :
1426 0 : mu::engraving::XmlReader reader(data);
1427 0 : while (reader.readNextStartElement()) {
1428 0 : if (reader.name() == "StaffList") {
1429 0 : rdd.sourceTick = Fraction::fromString(reader.attribute("tick"));
1430 0 : rdd.tickLength = Fraction::fromString(reader.attribute("len"));
1431 0 : rdd.timeStretch = reader.hasAttribute("timeStretch") ? Fraction::fromString(reader.attribute("timeStretch")) : Fraction(1, 1);
1432 0 : rdd.sourceStaffIdx = static_cast<staff_idx_t>(reader.intAttribute("staff", -1));
1433 0 : rdd.numStaves = reader.intAttribute("staves", 0);
1434 0 : break;
1435 : }
1436 : }
1437 :
1438 0 : if (rdd.tickLength.isZero() || rdd.numStaves == 0) {
1439 0 : resetDropData();
1440 0 : return false;
1441 : }
1442 :
1443 0 : return true;
1444 0 : }
1445 :
1446 0 : bool NotationInteraction::startDropRange(const Fraction& sourceTick, const Fraction& tickLength,
1447 : engraving::staff_idx_t sourceStaffIdx, size_t numStaves, bool preserveMeasureAlignment)
1448 : {
1449 0 : if (tickLength.isZero() || numStaves == 0) {
1450 0 : return false;
1451 : }
1452 :
1453 0 : resetDropData();
1454 :
1455 0 : m_dropData.rangeDropData = RangeDropData();
1456 0 : RangeDropData& rdd = m_dropData.rangeDropData.value();
1457 :
1458 0 : rdd.sourceTick = sourceTick;
1459 0 : rdd.tickLength = tickLength;
1460 0 : rdd.timeStretch = score()->staff(sourceStaffIdx)->timeStretch(sourceTick);
1461 0 : rdd.sourceStaffIdx = sourceStaffIdx;
1462 0 : rdd.numStaves = numStaves;
1463 0 : rdd.preserveMeasureAlignment = preserveMeasureAlignment;
1464 :
1465 0 : return true;
1466 : }
1467 :
1468 0 : bool NotationInteraction::startDropImage(const QUrl& url)
1469 : {
1470 0 : if (url.scheme() != "file") {
1471 0 : return false;
1472 : }
1473 :
1474 0 : auto image = toImage(Factory::createItem(mu::engraving::ElementType::IMAGE, score()->dummy()));
1475 0 : if (!image->loadFromFile(url.toLocalFile())) {
1476 0 : return false;
1477 : }
1478 :
1479 0 : resetDropData();
1480 :
1481 0 : m_dropData.elementDropData = ElementDropData();
1482 0 : ElementDropData& edd = m_dropData.elementDropData.value();
1483 0 : edd.ed = mu::engraving::EditData(&m_scoreCallbacks);
1484 :
1485 0 : edd.ed.dropElement = image;
1486 0 : edd.ed.dragOffset = QPointF();
1487 0 : edd.ed.dropElement->setOwnershipParent(nullptr);
1488 :
1489 0 : engravingRenderer()->layoutItem(edd.ed.dropElement);
1490 :
1491 0 : return true;
1492 : }
1493 :
1494 : //! NOTE Copied from ScoreView::dragMoveEvent
1495 0 : bool NotationInteraction::updateDropSingle(const PointF& pos, Qt::KeyboardModifiers modifiers)
1496 : {
1497 0 : if (!m_dropData.elementDropData.has_value()) {
1498 0 : return false;
1499 : }
1500 :
1501 0 : ElementDropData& edd = m_dropData.elementDropData.value();
1502 :
1503 0 : EngravingItem* dropElem = edd.ed.dropElement;
1504 0 : if (!dropElem) {
1505 0 : return false;
1506 : }
1507 :
1508 0 : switch (dropElem->type()) {
1509 0 : case ElementType::BRACKET:
1510 : case ElementType::GRADUAL_TEMPO_CHANGE:
1511 : case ElementType::JUMP:
1512 : case ElementType::KEYSIG:
1513 : case ElementType::LAYOUT_BREAK:
1514 : case ElementType::MARKER:
1515 : case ElementType::MEASURE_REPEAT:
1516 : case ElementType::MEASURE_NUMBER:
1517 : case ElementType::TIMESIG:
1518 : case ElementType::SPACER:
1519 : case ElementType::STAFFTYPE_CHANGE:
1520 : case ElementType::STRING_TUNINGS:
1521 : case ElementType::VOLTA: {
1522 0 : edd.ed.modifiers = keyboardModifier(modifiers);
1523 0 : return prepareDropMeasureBaseAnchorElement(pos);
1524 : }
1525 0 : case ElementType::PEDAL:
1526 : case ElementType::LET_RING:
1527 : case ElementType::VIBRATO:
1528 : case ElementType::PALM_MUTE:
1529 : case ElementType::OTTAVA:
1530 : case ElementType::TRILL:
1531 : case ElementType::HAIRPIN:
1532 : case ElementType::TEXTLINE:
1533 : case ElementType::WHAMMY_BAR: {
1534 0 : edd.ed.modifiers = keyboardModifier(modifiers);
1535 0 : return prepareDropTimeAnchorElement(pos);
1536 : }
1537 0 : case ElementType::IMAGE:
1538 : case ElementType::SYMBOL:
1539 : case ElementType::FSYMBOL:
1540 : case ElementType::DYNAMIC:
1541 : case ElementType::CLEF:
1542 : case ElementType::BAR_LINE:
1543 : case ElementType::ARPEGGIO:
1544 : case ElementType::CHORD_BRACKET:
1545 : case ElementType::BREATH:
1546 : case ElementType::GLISSANDO:
1547 : case ElementType::ARTICULATION:
1548 : case ElementType::TAPPING:
1549 : case ElementType::FERMATA:
1550 : case ElementType::CHORDLINE:
1551 : case ElementType::BEND:
1552 : case ElementType::ACCIDENTAL:
1553 : case ElementType::TEXT:
1554 : case ElementType::FINGERING:
1555 : case ElementType::TEMPO_TEXT:
1556 : case ElementType::ORNAMENT:
1557 : case ElementType::EXPRESSION:
1558 : case ElementType::STAFF_TEXT:
1559 : case ElementType::STAVE_SHARING_LABEL:
1560 : case ElementType::SYSTEM_TEXT:
1561 : case ElementType::TRIPLET_FEEL:
1562 : case ElementType::PLAYTECH_ANNOTATION:
1563 : case ElementType::CAPO:
1564 : case ElementType::NOTEHEAD:
1565 : case ElementType::TREMOLO_SINGLECHORD:
1566 : case ElementType::TREMOLO_TWOCHORD:
1567 : case ElementType::STAFF_STATE:
1568 : case ElementType::INSTRUMENT_CHANGE:
1569 : case ElementType::REHEARSAL_MARK:
1570 : case ElementType::CHORD:
1571 : case ElementType::SLUR:
1572 : case ElementType::HAMMER_ON_PULL_OFF:
1573 : case ElementType::HARMONY:
1574 : case ElementType::BAGPIPE_EMBELLISHMENT:
1575 : case ElementType::AMBITUS:
1576 : case ElementType::TREMOLOBAR:
1577 : case ElementType::FIGURED_BASS:
1578 : case ElementType::LYRICS:
1579 : case ElementType::FRET_DIAGRAM:
1580 : case ElementType::HARP_DIAGRAM: {
1581 0 : return prepareDropStandardElement(pos, modifiers);
1582 : }
1583 : //! NOTE: See Measure::acceptDrop
1584 0 : case ElementType::ACTION_ICON: {
1585 0 : switch (toActionIcon(dropElem)->actionType()) {
1586 0 : case ActionIconType::VFRAME:
1587 : case ActionIconType::HFRAME:
1588 : case ActionIconType::TFRAME:
1589 : case ActionIconType::FFRAME:
1590 : case ActionIconType::MEASURE:
1591 : case ActionIconType::SYSTEM_LOCK:
1592 : case ActionIconType::PAGE_LOCK:
1593 : case ActionIconType::STAFF_TYPE_CHANGE: {
1594 0 : edd.ed.modifiers = keyboardModifier(modifiers);
1595 0 : return prepareDropMeasureBaseAnchorElement(pos);
1596 : }
1597 : // Other action icons (e.g parenthesis) can be dragged normally
1598 0 : default: return prepareDropStandardElement(pos, modifiers);
1599 : }
1600 : }
1601 0 : default:
1602 0 : break;
1603 : }
1604 :
1605 0 : return false;
1606 : }
1607 :
1608 0 : static Measure* rangeEndMeasure(Score* score, const Fraction& endTick)
1609 : {
1610 0 : Measure* endMeasure = score->tick2measure(endTick);
1611 0 : if (!endMeasure) {
1612 0 : endMeasure = score->lastMeasure();
1613 0 : if (!endMeasure) {
1614 0 : return nullptr;
1615 : }
1616 : }
1617 0 : if (endMeasure->tick() == endTick) {
1618 : // If the end tick is at the start of a measure, return the previous measure
1619 0 : return endMeasure->prevMeasure();
1620 : }
1621 0 : return endMeasure;
1622 : }
1623 :
1624 0 : static Segment* rangeEndSegment(Score* score, const Fraction& endTick)
1625 : {
1626 0 : Segment* endSegment = score->tick2rightSegment(endTick,
1627 : true,
1628 : SegmentType::Duration);
1629 :
1630 0 : if (endSegment && !endSegment->enabled()) {
1631 0 : endSegment = endSegment->next1MMenabled();
1632 : }
1633 :
1634 0 : return endSegment ? endSegment : score->lastSegmentMM();
1635 : }
1636 :
1637 0 : static bool dropRangePosition(Score* score, const PointF& pos,
1638 : Fraction sourceStartTick, Fraction tickLength, Fraction timeStretch,
1639 : staff_idx_t numStaves, staff_idx_t* targetStartStaffIdx,
1640 : Segment** targetStartSegment, const Segment** targetEndSegment = nullptr,
1641 : bool preserveMeasureAlignment = false,
1642 : ShowAnchors* showAnchors = nullptr)
1643 : {
1644 0 : IF_ASSERT_FAILED(score && targetStartStaffIdx && targetStartSegment) {
1645 0 : return false;
1646 : }
1647 :
1648 0 : Measure* targetStartMeasure = nullptr;
1649 0 : if (!dragPositionToMeasure(pos, score, &targetStartMeasure, targetStartStaffIdx)) {
1650 0 : return false;
1651 : }
1652 :
1653 0 : Fraction targetStartTick;
1654 0 : Fraction targetEndTick;
1655 :
1656 0 : if (preserveMeasureAlignment) {
1657 0 : Measure* sourceStartMeasure = score->tick2measure(sourceStartTick);
1658 0 : IF_ASSERT_FAILED(sourceStartMeasure) {
1659 0 : return false;
1660 : }
1661 :
1662 0 : Fraction startTickOffset = sourceStartTick - sourceStartMeasure->tick();
1663 0 : targetStartTick = targetStartMeasure->tick() + startTickOffset;
1664 0 : targetEndTick = targetStartTick + tickLength;
1665 :
1666 0 : if (targetStartTick >= targetStartMeasure->endTick()) {
1667 : // Target start tick is beyond the end of the measure, so cannot preserve alignment
1668 : // This can happen when the target measure is shorter than the source measure
1669 0 : preserveMeasureAlignment = false;
1670 : }
1671 : }
1672 0 : if (!preserveMeasureAlignment) {
1673 : // Assign temporary values until target segment is determined
1674 0 : targetStartTick = targetStartMeasure->tick();
1675 0 : targetEndTick = targetStartMeasure->endTick() - Fraction::fromTicks(1) + tickLength;
1676 : }
1677 :
1678 0 : Measure* targetEndMeasure = rangeEndMeasure(score, targetEndTick);
1679 0 : if (!targetEndMeasure) {
1680 0 : return false;
1681 : }
1682 :
1683 0 : IF_ASSERT_FAILED(targetStartMeasure == targetEndMeasure || targetStartMeasure->isBefore(targetEndMeasure)) {
1684 0 : return false;
1685 : }
1686 :
1687 0 : const staff_idx_t targetEndStaffIdx = std::min(*targetStartStaffIdx + numStaves, score->nstaves());
1688 :
1689 : // Add time tick anchors throughout these measures
1690 0 : for (Measure* m = targetStartMeasure; m && m->tick() <= targetEndMeasure->tick(); m = m->nextMeasure()) {
1691 0 : std::set<Fraction> additionalAnchorRelTicks;
1692 0 : if (preserveMeasureAlignment) {
1693 0 : if (m == targetStartMeasure) {
1694 0 : additionalAnchorRelTicks.insert(targetStartTick - m->tick());
1695 : }
1696 0 : if (m == targetEndMeasure) {
1697 0 : additionalAnchorRelTicks.insert(targetEndTick - m->tick());
1698 : }
1699 : }
1700 0 : for (staff_idx_t i = *targetStartStaffIdx; i < targetEndStaffIdx; ++i) {
1701 0 : EditTimeTickAnchors::updateAnchors(m, i, additionalAnchorRelTicks);
1702 : }
1703 0 : }
1704 :
1705 0 : if (preserveMeasureAlignment) {
1706 0 : *targetStartSegment = segmentOrChordRestSegmentAtSameTick(
1707 : targetStartMeasure->findSegment(SegmentType::Duration, targetStartTick));
1708 : } else {
1709 : static constexpr double spacingFactor = 0.5;
1710 : static constexpr bool useTimeAnchors = true;
1711 :
1712 : // Depends on time tick anchors that we just created
1713 0 : if (!dragPositionToSegment(pos, targetStartMeasure, *targetStartStaffIdx, targetStartSegment, spacingFactor, useTimeAnchors)) {
1714 0 : return false;
1715 : }
1716 :
1717 0 : targetStartTick = (*targetStartSegment)->tick();
1718 0 : targetEndTick = targetStartTick + tickLength;
1719 :
1720 0 : targetEndMeasure = rangeEndMeasure(score, targetEndTick);
1721 0 : if (!targetEndMeasure) {
1722 0 : return false;
1723 : }
1724 : }
1725 :
1726 0 : if (targetEndSegment) {
1727 0 : *targetEndSegment = rangeEndSegment(score, targetEndTick);
1728 0 : if (!*targetEndSegment) {
1729 0 : return false;
1730 : }
1731 : }
1732 :
1733 : // Check the time stretch for all measures overlapping the destination range.
1734 0 : for (Measure* m = targetStartMeasure; m && m->tick() <= targetEndMeasure->tick(); m = m->nextMeasure()) {
1735 0 : for (staff_idx_t staffIdx = *targetStartStaffIdx; staffIdx < targetEndStaffIdx; ++staffIdx) {
1736 0 : Fraction mTimeStretch = score->staff(staffIdx)->timeStretch(m->tick());
1737 0 : if (mTimeStretch != timeStretch) {
1738 0 : return false;
1739 : }
1740 : }
1741 : }
1742 :
1743 0 : if (showAnchors) {
1744 0 : *showAnchors = ShowAnchors(0, *targetStartStaffIdx, *targetStartStaffIdx + numStaves,
1745 : targetStartTick, targetEndTick,
1746 0 : targetStartMeasure->tick(), targetEndMeasure->endTick());
1747 : }
1748 :
1749 0 : return true;
1750 : }
1751 :
1752 0 : bool NotationInteraction::updateDropRange(const PointF& pos, std::optional<bool> preserveMeasureAlignment)
1753 : {
1754 0 : IF_ASSERT_FAILED(m_dropData.rangeDropData.has_value()) {
1755 0 : return false;
1756 : }
1757 :
1758 0 : RangeDropData& rdd = m_dropData.rangeDropData.value();
1759 :
1760 0 : if (preserveMeasureAlignment.has_value()) {
1761 0 : rdd.preserveMeasureAlignment = preserveMeasureAlignment.value();
1762 : }
1763 :
1764 0 : staff_idx_t staffIdx = muse::nidx;
1765 0 : Segment* segment = nullptr;
1766 0 : const Segment* endSegment = nullptr;
1767 0 : ShowAnchors showAnchors;
1768 :
1769 0 : const bool ok = dropRangePosition(score(), pos,
1770 : rdd.sourceTick, rdd.tickLength, rdd.timeStretch, rdd.numStaves,
1771 : &staffIdx, &segment, &endSegment,
1772 0 : rdd.preserveMeasureAlignment, &showAnchors);
1773 :
1774 0 : if (showAnchors != score()->showAnchors()) {
1775 0 : score()->setShowAnchors(showAnchors);
1776 :
1777 : // Invalidate BSP tree of affected pages
1778 0 : System* lastSeenSystem = nullptr;
1779 0 : Page* lastSeenPage = nullptr;
1780 0 : for (MeasureBase* mb = score()->tick2measure(showAnchors.startTickExtendedRegion);
1781 0 : mb && mb->tick() <= showAnchors.endTickExtendedRegion;
1782 0 : mb = mb->next()) {
1783 0 : System* s = mb->system();
1784 0 : if (!s || s == lastSeenSystem) {
1785 0 : continue;
1786 : }
1787 :
1788 0 : lastSeenSystem = s;
1789 :
1790 0 : Page* p = s->page();
1791 0 : if (!p || p == lastSeenPage) {
1792 0 : continue;
1793 : }
1794 :
1795 0 : lastSeenPage = p;
1796 :
1797 0 : p->invalidateBspTree();
1798 : }
1799 : }
1800 :
1801 0 : if (ok) {
1802 0 : rdd.targetSegment = segment;
1803 0 : rdd.targetStaffIdx = staffIdx;
1804 :
1805 0 : const staff_idx_t endStaffIdx = std::min(staffIdx + rdd.numStaves, score()->nstaves());
1806 :
1807 0 : rdd.dropRects = ScoreRangeUtilities::boundingArea(score(),
1808 : segment, endSegment,
1809 : staffIdx, endStaffIdx,
1810 0 : /*startBox*/ nullptr, /*endBox*/ nullptr);
1811 : } else {
1812 0 : rdd.targetSegment = nullptr;
1813 0 : rdd.targetStaffIdx = muse::nidx;
1814 0 : rdd.dropRects.clear();
1815 : }
1816 :
1817 0 : notifyAboutDragChanged();
1818 :
1819 0 : return ok;
1820 : }
1821 :
1822 : //! NOTE Copied from ScoreView::dropEvent
1823 0 : Ret NotationInteraction::canDropSingle(const PointF& pos)
1824 : {
1825 0 : if (!m_dropData.elementDropData.has_value()) {
1826 0 : return make_ok();
1827 : }
1828 :
1829 0 : ElementDropData& edd = m_dropData.elementDropData.value();
1830 :
1831 0 : const EngravingItem* dropElement = edd.ed.dropElement;
1832 0 : if (!dropElement || !dropElement->isMeasureRepeat()) {
1833 0 : return make_ok();
1834 : }
1835 :
1836 : // the same target as in dropSingle()
1837 0 : if (edd.ed.pos.isNull()) {
1838 0 : edd.ed.pos = pos;
1839 : }
1840 :
1841 0 : EngravingItem* target = edd.dropTarget ? edd.dropTarget : dropTarget(edd.ed);
1842 0 : if (EditMeasureRepeat::droppingReplacesContents(target, edd.ed.track, toMeasureRepeat(dropElement)->numMeasures())) {
1843 0 : return make_ret(notation::Err::MeasureRepeatReplacesContents);
1844 : }
1845 :
1846 0 : return make_ok();
1847 : }
1848 :
1849 0 : bool NotationInteraction::dropSingle(const PointF& pos, Qt::KeyboardModifiers modifiers)
1850 : {
1851 0 : if (!m_dropData.elementDropData.has_value()) {
1852 0 : return false;
1853 : }
1854 :
1855 0 : ElementDropData& edd = m_dropData.elementDropData.value();
1856 :
1857 0 : if (!edd.ed.dropElement) {
1858 0 : return false;
1859 : }
1860 :
1861 0 : IF_ASSERT_FAILED(edd.ed.dropElement->score() == score()) {
1862 0 : return false;
1863 : }
1864 :
1865 0 : bool accepted = false;
1866 :
1867 : // If the drop position hasn't been set already through isDropAccepted's helper methods, use the mouse position
1868 0 : if (edd.ed.pos.isNull()) {
1869 0 : edd.ed.pos = pos;
1870 : }
1871 :
1872 0 : edd.ed.modifiers = keyboardModifier(modifiers);
1873 0 : edd.ed.dropElement->styleChanged();
1874 :
1875 0 : bool systemStavesOnly = false;
1876 0 : bool applyUserOffset = false;
1877 :
1878 0 : startEdit(TranslatableString("undoableAction", "Drop element: %1").arg(edd.ed.dropElement->typeUserName()));
1879 0 : score()->addRefresh(edd.ed.dropElement->canvasBoundingRect());
1880 0 : engraving::Transaction& tx = score()->transactionManager()->currentOrDummyTransaction();
1881 0 : ElementType et = edd.ed.dropElement->type();
1882 0 : switch (et) {
1883 0 : case ElementType::VOLTA:
1884 : case ElementType::GRADUAL_TEMPO_CHANGE:
1885 : // voltas drop to system staves by default, or closest staff if Control is held
1886 0 : systemStavesOnly = !(edd.ed.modifiers & Qt::ControlModifier);
1887 : [[fallthrough]];
1888 0 : case ElementType::TEXTLINE:
1889 : case ElementType::OTTAVA:
1890 : case ElementType::TRILL:
1891 : case ElementType::PEDAL:
1892 : case ElementType::LET_RING:
1893 : case ElementType::VIBRATO:
1894 : case ElementType::PALM_MUTE:
1895 : case ElementType::HAIRPIN:
1896 : case ElementType::WHAMMY_BAR:
1897 : {
1898 0 : systemStavesOnly |= edd.ed.dropElement->systemFlag();
1899 0 : mu::engraving::Spanner* spanner = ptr::checked_cast<mu::engraving::Spanner>(edd.ed.dropElement);
1900 0 : EditSpanner::addSpanner(tx, score(), spanner, pos, systemStavesOnly);
1901 0 : score()->setUpdateAll();
1902 0 : accepted = true;
1903 : }
1904 0 : break;
1905 0 : case ElementType::SYMBOL:
1906 : case ElementType::FSYMBOL:
1907 : case ElementType::IMAGE:
1908 0 : applyUserOffset = true;
1909 : [[fallthrough]];
1910 0 : case ElementType::DYNAMIC:
1911 : case ElementType::HARMONY:
1912 0 : accepted = doDropTextBaseAndSymbols(tx, pos, applyUserOffset);
1913 0 : break;
1914 0 : case ElementType::FRET_DIAGRAM:
1915 0 : accepted = doDropTextBaseAndSymbols(tx, pos, applyUserOffset);
1916 0 : if (accepted) {
1917 0 : doFinishAddFretboardDiagram();
1918 : }
1919 0 : break;
1920 0 : case ElementType::HBOX:
1921 : case ElementType::VBOX:
1922 : case ElementType::KEYSIG:
1923 : case ElementType::CLEF:
1924 : case ElementType::TIMESIG:
1925 : case ElementType::BAR_LINE:
1926 : case ElementType::ARPEGGIO:
1927 : case ElementType::CHORD_BRACKET:
1928 : case ElementType::BREATH:
1929 : case ElementType::GLISSANDO:
1930 : case ElementType::MEASURE_NUMBER:
1931 : case ElementType::BRACKET:
1932 : case ElementType::ARTICULATION:
1933 : case ElementType::TAPPING:
1934 : case ElementType::FERMATA:
1935 : case ElementType::CHORDLINE:
1936 : case ElementType::BEND:
1937 : case ElementType::ACCIDENTAL:
1938 : case ElementType::TEXT:
1939 : case ElementType::FINGERING:
1940 : case ElementType::TEMPO_TEXT:
1941 : case ElementType::ORNAMENT:
1942 : case ElementType::EXPRESSION:
1943 : case ElementType::STAFF_TEXT:
1944 : case ElementType::STAVE_SHARING_LABEL:
1945 : case ElementType::SYSTEM_TEXT:
1946 : case ElementType::TRIPLET_FEEL:
1947 : case ElementType::PLAYTECH_ANNOTATION:
1948 : case ElementType::CAPO:
1949 : case ElementType::STRING_TUNINGS:
1950 : case ElementType::NOTEHEAD:
1951 : case ElementType::TREMOLO_SINGLECHORD:
1952 : case ElementType::TREMOLO_TWOCHORD:
1953 : case ElementType::LAYOUT_BREAK:
1954 : case ElementType::MARKER:
1955 : case ElementType::STAFF_STATE:
1956 : case ElementType::INSTRUMENT_CHANGE:
1957 : case ElementType::REHEARSAL_MARK:
1958 : case ElementType::JUMP:
1959 : case ElementType::MEASURE_REPEAT:
1960 : case ElementType::ACTION_ICON:
1961 : case ElementType::NOTE:
1962 : case ElementType::CHORD:
1963 : case ElementType::SPACER:
1964 : case ElementType::BAGPIPE_EMBELLISHMENT:
1965 : case ElementType::AMBITUS:
1966 : case ElementType::TREMOLOBAR:
1967 : case ElementType::FIGURED_BASS:
1968 : case ElementType::LYRICS:
1969 : case ElementType::HARP_DIAGRAM:
1970 : case ElementType::STAFFTYPE_CHANGE:
1971 0 : accepted = doDropStandard(tx);
1972 0 : break;
1973 0 : case ElementType::SLUR:
1974 : case ElementType::HAMMER_ON_PULL_OFF:
1975 : {
1976 0 : EngravingItem* el = dropTarget(edd.ed);
1977 0 : mu::engraving::Slur* dropElement = toSlur(edd.ed.dropElement);
1978 0 : if (toNote(el)->chord()) {
1979 0 : doAddSlur(tx, toNote(el)->chord(), nullptr, dropElement);
1980 0 : accepted = true;
1981 : }
1982 : }
1983 0 : break;
1984 0 : default:
1985 0 : resetDropData();
1986 0 : break;
1987 : }
1988 :
1989 0 : edd.ed.dropElement = nullptr;
1990 0 : edd.ed.pos = PointF();
1991 0 : edd.ed.modifiers = {};
1992 :
1993 0 : setDropTarget(nullptr); // this also resets dropRectangle and dropAnchor
1994 0 : apply();
1995 :
1996 0 : if (accepted) {
1997 0 : notifyAboutDropChanged();
1998 : }
1999 :
2000 0 : checkAndShowError();
2001 :
2002 0 : return accepted;
2003 : }
2004 :
2005 : //! NOTE: Helper method for NotationInteraction::drop. Handles drop logic for majority of elements (returns "accepted")
2006 0 : bool NotationInteraction::doDropStandard(engraving::Transaction& tx)
2007 : {
2008 0 : if (!m_dropData.elementDropData.has_value()) {
2009 0 : return false;
2010 : }
2011 :
2012 0 : ElementDropData& edd = m_dropData.elementDropData.value();
2013 :
2014 0 : EngravingItem* el = edd.dropTarget ? edd.dropTarget : dropTarget(edd.ed);
2015 0 : if (!el) {
2016 0 : if (!dropCanvas(edd.ed.dropElement)) {
2017 0 : LOGD("cannot drop %s(%p) to canvas", edd.ed.dropElement->typeName(), edd.ed.dropElement);
2018 0 : resetDropData();
2019 : }
2020 0 : return false;
2021 : }
2022 0 : score()->addRefresh(el->canvasBoundingRect());
2023 :
2024 0 : EngravingItem* dropElement = el->drop(tx, edd.ed);
2025 :
2026 0 : if (dropElement && dropElement->isInstrumentChange()) {
2027 0 : if (!selectInstrument(toInstrumentChange(dropElement))) {
2028 0 : rollback();
2029 0 : return true; // Really?
2030 : }
2031 : }
2032 :
2033 0 : score()->addRefresh(el->canvasBoundingRect());
2034 0 : if (dropElement) {
2035 0 : if (!score()->noteEntryMode()) {
2036 0 : selectAndStartEditIfNeeded(dropElement);
2037 : }
2038 0 : score()->addRefresh(dropElement->canvasBoundingRect());
2039 : }
2040 0 : return true;
2041 : }
2042 :
2043 : //! NOTE: Helper method for NotationInteraction::drop. Handles drop logic for text base items & symbols (returns "accepted")
2044 0 : bool NotationInteraction::doDropTextBaseAndSymbols(engraving::Transaction& tx, const PointF& pos, bool applyUserOffset)
2045 : {
2046 0 : IF_ASSERT_FAILED(m_dropData.elementDropData.has_value()) {
2047 0 : return false;
2048 : }
2049 :
2050 0 : ElementDropData& edd = m_dropData.elementDropData.value();
2051 :
2052 0 : EngravingItem* el = edd.dropTarget ? edd.dropTarget : elementAt(pos);
2053 0 : if (!el || el->isStaffLines()) {
2054 : mu::engraving::staff_idx_t staffIdx;
2055 : mu::engraving::Segment* seg;
2056 0 : PointF offset;
2057 0 : el = score()->pos2measure(pos, &staffIdx, /*pitch*/ 0, &seg, &offset);
2058 0 : if (el && el->isMeasure()) {
2059 0 : edd.ed.dropElement->setTrack(staff2track(staffIdx));
2060 0 : edd.ed.dropElement->setOwnershipParent(seg);
2061 :
2062 0 : if (applyUserOffset) {
2063 0 : edd.ed.dropElement->setOffset(offset);
2064 : }
2065 :
2066 0 : score()->undoAddElement(edd.ed.dropElement);
2067 : } else {
2068 0 : LOGD("cannot drop here");
2069 0 : resetDropData();
2070 : }
2071 : } else {
2072 0 : score()->addRefresh(el->canvasBoundingRect());
2073 0 : score()->addRefresh(edd.ed.dropElement->canvasBoundingRect());
2074 :
2075 0 : if (!el->acceptDrop(edd.ed)) {
2076 0 : LOGD("drop %s onto %s not accepted", edd.ed.dropElement->typeName(), el->typeName());
2077 0 : return false;
2078 : }
2079 0 : edd.ed.pos = pos;
2080 0 : EngravingItem* dropElement = el->drop(tx, edd.ed);
2081 0 : score()->addRefresh(el->canvasBoundingRect());
2082 0 : if (dropElement) {
2083 0 : selectAndStartEditIfNeeded(dropElement);
2084 0 : score()->addRefresh(dropElement->canvasBoundingRect());
2085 : }
2086 : }
2087 :
2088 0 : return true;
2089 : }
2090 :
2091 0 : bool NotationInteraction::dropRange(const QByteArray& data, const PointF& pos, bool deleteSourceMaterial)
2092 : {
2093 0 : IF_ASSERT_FAILED(m_dropData.rangeDropData.has_value()) {
2094 0 : return false;
2095 : }
2096 :
2097 0 : RangeDropData& rdd = m_dropData.rangeDropData.value();
2098 :
2099 0 : if (rdd.tickLength.isZero() || rdd.numStaves == 0) {
2100 0 : return false;
2101 : }
2102 :
2103 0 : staff_idx_t staffIdx = muse::nidx;
2104 0 : Segment* segment = nullptr;
2105 :
2106 0 : const bool ok = dropRangePosition(score(), pos,
2107 : rdd.sourceTick, rdd.tickLength, rdd.timeStretch, rdd.numStaves,
2108 0 : &staffIdx, &segment, nullptr, rdd.preserveMeasureAlignment);
2109 0 : if (!ok) {
2110 0 : return false;
2111 : }
2112 :
2113 0 : if (segment->isTupletSubdivisionOnStaff(staffIdx) || segment->isInsideTupletOnStaff(staffIdx)) {
2114 0 : endDrop();
2115 0 : notifyAboutDropChanged();
2116 : //MScore::setError(MsError::DEST_TUPLET);
2117 : // checkAndShowError();
2118 : // NOTE: if we show the error popup here it seems that the mouse-release event is missed
2119 : // so the dragged region stays sticked to the mouse and move around. Don't know how to fix it. [M.S.]
2120 0 : return false;
2121 : }
2122 :
2123 0 : rdd.targetSegment = segment;
2124 0 : rdd.targetStaffIdx = staffIdx;
2125 :
2126 0 : startEdit(deleteSourceMaterial
2127 0 : ? TranslatableString("undoableAction", "Move range")
2128 : : TranslatableString("undoableAction", "Copy range"));
2129 :
2130 0 : if (deleteSourceMaterial && rdd.sourceStaffIdx != muse::nidx) {
2131 0 : Segment* sourceStartSegment = score()->tick2leftSegmentMM(rdd.sourceTick);
2132 0 : if (sourceStartSegment && !sourceStartSegment->enabled()) {
2133 0 : sourceStartSegment = sourceStartSegment->next1MMenabled();
2134 : }
2135 :
2136 0 : Segment* sourceEndSegment = rangeEndSegment(score(), rdd.sourceTick + rdd.tickLength);
2137 :
2138 0 : if (sourceStartSegment && sourceEndSegment) {
2139 0 : score()->deleteRange(sourceStartSegment, sourceEndSegment,
2140 : engraving::staff2track(rdd.sourceStaffIdx),
2141 0 : engraving::staff2track(rdd.sourceStaffIdx + rdd.numStaves),
2142 0 : score()->selectionFilter(), score()->selection().rangeContainsMultiNoteChords());
2143 : }
2144 : }
2145 :
2146 0 : XmlReader e(data);
2147 0 : bool succeeded = Paste::pasteStaff(score()->transactionManager()->currentOrDummyTransaction(), score(), e, segment, staffIdx);
2148 :
2149 0 : endDrop();
2150 :
2151 0 : if (succeeded) {
2152 0 : apply();
2153 : } else {
2154 0 : rollback();
2155 : }
2156 :
2157 0 : checkAndShowError();
2158 :
2159 0 : return succeeded;
2160 0 : }
2161 :
2162 0 : bool NotationInteraction::selectInstrument(mu::engraving::InstrumentChange* instrumentChange)
2163 : {
2164 0 : if (!instrumentChange) {
2165 0 : return false;
2166 : }
2167 :
2168 : #ifdef MUE_CONFIGURATION_IS_APPWEB
2169 : interactive()->info("", muse::trc("notation", "Sorry, instrument change on the web is not supported at this time."));
2170 : return false;
2171 : #else
2172 :
2173 : //! HACK To remake the asynchronous mode, a lot of refactoring is needed,
2174 : //! so for now this is a hack
2175 0 : bool result = false;
2176 0 : QEventLoop loop;
2177 0 : async::Promise<InstrumentTemplate> templ = selectInstrumentScenario()->selectInstrument();
2178 0 : templ.onResolve(this, [this, instrumentChange, &loop, &result](const InstrumentTemplate& val) {
2179 0 : Instrument newInstrument = Instrument::fromTemplate(&val);
2180 :
2181 : // If switching back to the part's original instrument, restore its player number
2182 0 : if (Part* part = instrumentChange->part()) {
2183 0 : const Instrument* baseInstrument = part->instrument();
2184 0 : if (baseInstrument && baseInstrument->id() == newInstrument.id()) {
2185 0 : InstrumentLabel& newLabel = newInstrument.instrumentLabel();
2186 0 : const InstrumentLabel& baseLabel = baseInstrument->instrumentLabel();
2187 0 : newLabel.setNumber(baseLabel.number());
2188 0 : newLabel.setShowNumberLong(baseLabel.showNumberLong());
2189 0 : newLabel.setShowNumberShort(baseLabel.showNumberShort());
2190 : }
2191 : }
2192 :
2193 0 : instrumentChange->setInit(true);
2194 0 : instrumentChange->setupInstrument(&newInstrument);
2195 :
2196 0 : if (newInstrument.useDrumset()) {
2197 0 : cleanupDrumsetChanges(instrumentChange);
2198 : }
2199 :
2200 0 : result = true;
2201 0 : loop.quit();
2202 0 : }).onReject(this, [&loop, &result](int, const std::string&) {
2203 0 : result = false;
2204 0 : loop.quit();
2205 0 : });
2206 :
2207 0 : loop.exec();
2208 :
2209 0 : return result;
2210 : #endif
2211 0 : }
2212 :
2213 0 : void NotationInteraction::cleanupDrumsetChanges(mu::engraving::InstrumentChange* instrumentChange) const
2214 : {
2215 0 : Part* part = instrumentChange ? instrumentChange->part() : nullptr;
2216 0 : Instrument* newInstrument = instrumentChange ? instrumentChange->instrument() : nullptr;
2217 0 : if (!part || !newInstrument) {
2218 0 : return;
2219 : }
2220 :
2221 0 : for (auto pair : part->instruments()) {
2222 0 : const Instrument* otherInst = pair.second;
2223 0 : if (!otherInst || otherInst == newInstrument) {
2224 0 : continue;
2225 : }
2226 :
2227 : // If the following conditional is true, it means that we're trying to change to a drumset that already exists for this part. Due to the fact
2228 : // that we don't create new tracks for identical instruments in a given part, the knock-on effect is that the new drumset won't have a chance
2229 : // to load a MuseSampler patch (see usage of shouldLoadDrumset in PlaybackController). The following logic resolves this by copying the patch
2230 : // from the existing drumset into the new one...
2231 0 : if (otherInst->drumset() && newInstrument->id() == otherInst->id()) {
2232 0 : score()->undo(new engraving::ChangeDrumset(newInstrument, *otherInst->drumset(), part));
2233 0 : return;
2234 : }
2235 : }
2236 : }
2237 :
2238 : //! NOTE Copied from Palette::applyPaletteElement
2239 0 : Ret NotationInteraction::canApplyPaletteElement(EngravingItem* element) const
2240 : {
2241 0 : if (!element || !element->isMeasureRepeat()) {
2242 0 : return make_ok();
2243 : }
2244 :
2245 0 : const mu::engraving::Score* score = this->score();
2246 0 : if (!score) {
2247 0 : return make_ok();
2248 : }
2249 :
2250 : // the same targets as in applyPaletteElementToList() and applyPaletteElementToRange()
2251 0 : bool unique = false;
2252 0 : const int numMeasures = toMeasureRepeat(element)->numMeasures();
2253 0 : for (EngravingItem* target : mu::engraving::filterTargetElements(score->selection(), element, unique)) {
2254 0 : if (EditMeasureRepeat::droppingReplacesContents(target, target->track(), numMeasures)) {
2255 0 : return make_ret(notation::Err::MeasureRepeatReplacesContents);
2256 : }
2257 0 : }
2258 :
2259 0 : return make_ok();
2260 : }
2261 :
2262 0 : bool NotationInteraction::applyPaletteElement(mu::engraving::EngravingItem* element, Qt::KeyboardModifiers modifiers)
2263 : {
2264 0 : IF_ASSERT_FAILED(element) {
2265 0 : return false;
2266 : }
2267 :
2268 0 : mu::engraving::Score* score = this->score();
2269 0 : if (!score) {
2270 0 : return false;
2271 : }
2272 :
2273 0 : const mu::engraving::Selection sel = score->selection(); // make a copy of selection state before applying the operation.
2274 0 : if (sel.isNone()) {
2275 0 : return false;
2276 : }
2277 :
2278 0 : startEdit(TranslatableString("undoableAction", "Apply palette element: %1").arg(element->typeUserName()));
2279 :
2280 0 : if (sel.isList()) {
2281 0 : applyPaletteElementToList(element, score, sel, modifiers);
2282 0 : } else if (sel.isRange()) {
2283 0 : applyPaletteElementToRange(element, score, sel, modifiers);
2284 : } else {
2285 0 : LOGD("unknown selection state");
2286 : }
2287 :
2288 0 : m_notifyAboutDropChanged = true;
2289 0 : score->setSelectionChanged(true);
2290 0 : apply();
2291 :
2292 0 : setDropTarget(nullptr);
2293 :
2294 0 : checkAndShowError();
2295 :
2296 0 : return true;
2297 0 : }
2298 :
2299 0 : void NotationInteraction::applyPaletteElementToList(EngravingItem* element, mu::engraving::Score* score,
2300 : const mu::engraving::Selection& sel, Qt::KeyboardModifiers modifiers)
2301 : {
2302 0 : engraving::Transaction& tx = score->transactionManager()->currentOrDummyTransaction();
2303 :
2304 0 : const ElementType elementType = element->type();
2305 :
2306 0 : ChordRest* cr1 = sel.firstChordRest();
2307 0 : ChordRest* cr2 = sel.lastChordRest();
2308 0 : bool addSingle = false; // add a single line only
2309 0 : if (cr1 && cr2 == cr1) {
2310 : // one chordrest selected, ok to add line
2311 0 : addSingle = true;
2312 0 : } else if (sel.elements().size() == 2 && cr1 && cr2 && cr1 != cr2) {
2313 : // two chordrests selected
2314 : // must be on same staff in order to add line, except for slur
2315 0 : if (element->isSlur() || cr1->staffIdx() == cr2->staffIdx()) {
2316 0 : addSingle = true;
2317 0 : } else if (sel.element() && sel.element()->isSlurSegment() && element->isHammerOnPullOff()) {
2318 0 : addSingle = true;
2319 : }
2320 : }
2321 :
2322 0 : auto isEntryDrumStaff = [score]() {
2323 0 : const mu::engraving::InputState& is = score->inputState();
2324 0 : const mu::engraving::Staff* staff = score->staff(track2staff(is.track()));
2325 0 : return staff ? staff->staffType(is.tick())->group() == mu::engraving::StaffGroup::PERCUSSION : false;
2326 0 : };
2327 :
2328 0 : const bool elementIsStandardBend = element->isActionIcon() && (toActionIcon(element)->actionType() == ActionIconType::STANDARD_BEND
2329 0 : || toActionIcon(element)->actionType() == ActionIconType::DIVE);
2330 0 : const bool elementIsNoteLine = element->isActionIcon() && toActionIcon(element)->actionType() == ActionIconType::NOTE_ANCHORED_LINE;
2331 0 : const bool isLineNoteToNote = (element->isGlissando() || elementIsStandardBend || elementIsNoteLine)
2332 0 : && sel.isList() && sel.elements().size() == 2
2333 0 : && sel.elements()[0]->isNote() && sel.elements()[1]->isNote()
2334 0 : && sel.elements()[1]->tick() != sel.elements()[0]->tick();
2335 :
2336 0 : if (isEntryDrumStaff() && element->isChord()) {
2337 0 : mu::engraving::InputState& is = score->inputState();
2338 0 : EngravingItem* e = nullptr;
2339 0 : if (!(modifiers & Qt::ShiftModifier)) {
2340 : // shift+double-click: add note to "chord"
2341 : // use input position rather than selection if possible
2342 : // look for a cr in the voice predefined for the drum in the palette
2343 : // back up if necessary
2344 : // TODO: refactor this with similar code in putNote()
2345 0 : if (is.segment()) {
2346 0 : mu::engraving::Segment* seg = is.segment();
2347 0 : while (seg) {
2348 0 : if (seg->element(is.track())) {
2349 0 : break;
2350 : }
2351 0 : seg = seg->prev(mu::engraving::SegmentType::ChordRest);
2352 : }
2353 0 : if (seg) {
2354 0 : is.setSegment(seg);
2355 : } else {
2356 0 : is.setSegment(is.segment()->measure()->first(mu::engraving::SegmentType::ChordRest));
2357 : }
2358 : }
2359 0 : score->expandVoice();
2360 0 : e = is.cr();
2361 : }
2362 0 : if (!e) {
2363 0 : e = sel.elements().front();
2364 : }
2365 0 : if (e) {
2366 : // get note if selection was full chord
2367 0 : if (e->isChord()) {
2368 0 : e = toChord(e)->upNote();
2369 : }
2370 :
2371 0 : applyDropPaletteElement(score, e, element, modifiers);
2372 : // note has already been played (and what would play otherwise may be *next* input position)
2373 0 : score->setPlayNote(false);
2374 0 : score->setPlayChord(false);
2375 : // continue in same track
2376 0 : is.setTrack(e->track());
2377 : } else {
2378 0 : LOGD("nowhere to place drum note");
2379 : }
2380 0 : return;
2381 : }
2382 :
2383 0 : if (element->isLayoutBreak()) {
2384 0 : mu::engraving::LayoutBreak* breakElement = toLayoutBreak(element);
2385 0 : score->cmdToggleLayoutBreak(breakElement->layoutBreakType());
2386 0 : return;
2387 : }
2388 :
2389 0 : if (element->isActionIcon()) {
2390 0 : const ActionIcon* icon = toActionIcon(element);
2391 0 : switch (icon->actionType()) {
2392 0 : case ActionIconType::SYSTEM_LOCK: {
2393 0 : EditSystemLocks::toggleSystemLock(tx, score, score->selection().selectedSystems());
2394 0 : return;
2395 : }
2396 0 : case ActionIconType::PAGE_LOCK: {
2397 0 : EditPageLocks::togglePageLock(tx, score, score->selection().pagesContainingSelection());
2398 0 : return;
2399 : }
2400 0 : case ActionIconType::PARENTHESES: {
2401 0 : if (!sel.noteList().empty()) {
2402 0 : EditParentheses::addParenthesesToNotes(tx, score);
2403 0 : return;
2404 : }
2405 : }
2406 : default:
2407 0 : break;
2408 : }
2409 : }
2410 :
2411 0 : if (element->isSlur()) {
2412 0 : doAddSlur(tx, toSlur(element));
2413 0 : return;
2414 : }
2415 :
2416 0 : if (element->isSLine() && !element->isGlissando() && !element->isGuitarBend() && addSingle) {
2417 0 : mu::engraving::Segment* startSegment = cr1->segment();
2418 0 : mu::engraving::Segment* endSegment = cr2->segment();
2419 0 : if (elementType == mu::engraving::ElementType::PEDAL && cr2 != cr1) {
2420 0 : endSegment = endSegment->nextCR(cr2->track());
2421 : } else {
2422 : // Ensure that list-selection results in the same endSegment as range selection
2423 0 : endSegment = cr2->nextSegmentAfterCR(SegmentType::ChordRest | SegmentType::EndBarLine | SegmentType::Clef);
2424 : }
2425 0 : mu::engraving::Spanner* spanner = toSpanner(element->clone());
2426 0 : spanner->setScore(score);
2427 0 : spanner->styleChanged();
2428 0 : if (spanner->isHairpin()) {
2429 0 : EditHairpin::addHairpin(tx, score, toHairpin(spanner), cr1, cr2);
2430 0 : if (!spanner->segmentsEmpty() && !score->noteEntryMode()) {
2431 0 : SpannerSegment* frontSegment = spanner->frontSegment();
2432 0 : score->select(frontSegment);
2433 0 : startEditElement(frontSegment);
2434 : }
2435 : } else {
2436 0 : bool firstStaffOnly = isSystemTextLine(element) && !(modifiers & Qt::ControlModifier);
2437 0 : staff_idx_t targetStaff = firstStaffOnly ? 0 : cr1->staffIdx();
2438 0 : EditSpanner::addSpanner(tx, score, spanner, targetStaff, startSegment, endSegment, modifiers & Qt::ControlModifier);
2439 : }
2440 0 : if (spanner->hasVoiceAssignmentProperties()) {
2441 0 : spanner->setInitialTrackAndVoiceAssignment(cr1->track(), modifiers & ControlModifier);
2442 0 : } else if (spanner->isVoiceSpecific()) {
2443 0 : spanner->setTrack(cr1->track());
2444 : }
2445 0 : return;
2446 : }
2447 :
2448 0 : if (element->isArticulationFamily() && sel.elements().size() == 1) {
2449 : // understand adding an articulation to another articulation as adding it to the chord it's attached to
2450 0 : EngravingItem* e = sel.elements().front();
2451 0 : if (e->isArticulationFamily()) {
2452 0 : if (Chord* c = toChord(toArticulation(e)->ownershipParent())) {
2453 0 : applyDropPaletteElement(score, c->notes().front(), element, modifiers);
2454 : }
2455 : } else {
2456 0 : applyDropPaletteElement(score, e, element, modifiers);
2457 : }
2458 0 : return;
2459 : }
2460 :
2461 0 : if (isLineNoteToNote) {
2462 0 : applyLineNoteToNote(score, toNote(sel.elements()[0]), toNote(sel.elements()[1]), element);
2463 0 : return;
2464 : }
2465 :
2466 0 : if ((element->isClef() || element->isTimeSig() || element->isKeySig()) && score->noteEntryMode()) {
2467 : // in note input mode place clef / time sig / key sig before cursor
2468 0 : EngravingItem* e = score->inputState().cr();
2469 0 : if (!e) {
2470 0 : e = sel.elements().front();
2471 0 : } else if (e->isChord()) {
2472 0 : e = toChord(e)->notes().front();
2473 : }
2474 0 : applyDropPaletteElement(score, e, element, modifiers);
2475 0 : return;
2476 : }
2477 :
2478 : bool unique;
2479 0 : std::vector<EngravingItem*> targetElements = mu::engraving::filterTargetElements(sel, element, unique);
2480 :
2481 0 : for (EngravingItem* target : targetElements) {
2482 0 : applyDropPaletteElement(score, target, element, modifiers);
2483 : }
2484 : }
2485 :
2486 0 : void NotationInteraction::applyPaletteElementToRange(EngravingItem* element, mu::engraving::Score* score,
2487 : const mu::engraving::Selection& sel, Qt::KeyboardModifiers modifiers)
2488 : {
2489 0 : engraving::Transaction& tx = score->transactionManager()->currentOrDummyTransaction();
2490 0 : const ElementType elementType = element->type();
2491 :
2492 0 : bool isMeasureAnchoredElement = false;
2493 0 : std::vector<EngravingItem*> targetElements = mu::engraving::filterTargetElements(sel, element, isMeasureAnchoredElement);
2494 0 : if (isMeasureAnchoredElement) {
2495 0 : if (elementType == ElementType::BAR_LINE) {
2496 : // In a range selection, add barlines to all selected measures
2497 0 : for (EngravingItem* target : targetElements) {
2498 0 : applyDropPaletteElement(score, target->findMeasure(), element, modifiers, target->track());
2499 : }
2500 : } else {
2501 0 : for (EngravingItem* target : targetElements) {
2502 0 : applyDropPaletteElement(score, target, element, modifiers);
2503 : }
2504 : }
2505 0 : return;
2506 : }
2507 :
2508 0 : if (elementType == ElementType::LAYOUT_BREAK) {
2509 0 : LayoutBreak* breakElement = toLayoutBreak(element);
2510 0 : score->cmdToggleLayoutBreak(breakElement->layoutBreakType());
2511 0 : return;
2512 : }
2513 :
2514 0 : if (element->isClef() || element->isKeySig() || element->isTimeSig()) {
2515 0 : Measure* m1 = sel.startSegment()->measure();
2516 0 : Measure* m2 = sel.endSegment() ? sel.endSegment()->measure() : nullptr;
2517 0 : if (m2 == m1 && sel.startSegment()->rtick().isZero()) {
2518 0 : m2 = nullptr; // don't restore original if one full measure selected
2519 0 : } else if (m2) {
2520 0 : m2 = m2->nextMeasureMM();
2521 : }
2522 : // Clefs always apply to every selected staff, key and time signatures only when added locally
2523 0 : const bool applyToEachStaff = element->isClef() || (modifiers & Qt::ControlModifier);
2524 0 : staff_idx_t staffIdx1 = sel.staffStart();
2525 0 : staff_idx_t staffIdx2 = applyToEachStaff ? sel.staffEnd() : staffIdx1 + 1;
2526 0 : for (staff_idx_t i = staffIdx1; i < staffIdx2; ++i) {
2527 : // For clefs, use mid-measure changes if appropriate
2528 : // Mid-measure key signature changes are done via list selections
2529 0 : EngravingItem* e1 = nullptr;
2530 0 : EngravingItem* e2 = nullptr;
2531 0 : if (element->isClef()) {
2532 0 : if (sel.startSegment()->isChordRestType() && sel.startSegment()->rtick().isNotZero()) {
2533 0 : ChordRest* cr = toChordRest(sel.startSegment()->nextChordRest(staff2track(i)));
2534 0 : if (cr && cr->isChord()) {
2535 0 : e1 = toChord(cr)->upNote();
2536 : } else {
2537 0 : e1 = cr;
2538 : }
2539 : }
2540 0 : if (sel.endSegment() && sel.endSegment()->segmentType() == mu::engraving::SegmentType::ChordRest) {
2541 0 : ChordRest* cr = toChordRest(sel.endSegment()->nextChordRest(staff2track(i)));
2542 0 : if (cr && cr->isChord()) {
2543 0 : e2 = toChord(cr)->upNote();
2544 : } else {
2545 0 : e2 = cr;
2546 : }
2547 : }
2548 : }
2549 : // restore clef/keysig/timesig that was in effect at end of selection
2550 0 : if (m2 || e2) {
2551 0 : mu::engraving::Staff* staff = score->staff(i);
2552 0 : mu::engraving::Fraction tick2 = sel.endSegment()->tick();
2553 0 : mu::engraving::EngravingItem* oelement = nullptr;
2554 0 : switch (elementType) {
2555 0 : case mu::engraving::ElementType::CLEF:
2556 : {
2557 0 : mu::engraving::Clef* oclef = engraving::Factory::createClef(score->dummy());
2558 0 : oclef->setClefType(staff->clef(tick2));
2559 0 : oelement = oclef;
2560 0 : break;
2561 : }
2562 0 : case mu::engraving::ElementType::KEYSIG:
2563 : {
2564 0 : mu::engraving::KeySig* okeysig = engraving::Factory::createKeySig(score->dummy());
2565 0 : okeysig->setKeySigEvent(staff->keySigEvent(tick2));
2566 0 : Key ck = okeysig->concertKey();
2567 0 : okeysig->setKey(ck);
2568 0 : oelement = okeysig;
2569 0 : break;
2570 : }
2571 0 : case mu::engraving::ElementType::TIMESIG:
2572 : {
2573 0 : mu::engraving::TimeSig* otimesig = engraving::Factory::createTimeSig(score->dummy());
2574 0 : otimesig->setFrom(staff->timeSig(tick2));
2575 0 : oelement = otimesig;
2576 0 : break;
2577 : }
2578 0 : default:
2579 0 : break;
2580 : }
2581 0 : if (oelement) {
2582 0 : if (e2) {
2583 0 : applyDropPaletteElement(score, e2, oelement, modifiers);
2584 : } else {
2585 0 : applyDropPaletteElement(score, m2, oelement, modifiers, staff2track(i));
2586 : }
2587 0 : delete oelement;
2588 : }
2589 : }
2590 : // apply new clef/keysig/timesig
2591 0 : if (e1) {
2592 0 : applyDropPaletteElement(score, e1, element, modifiers);
2593 : } else {
2594 0 : applyDropPaletteElement(score, m1, element, modifiers, staff2track(i));
2595 : }
2596 : }
2597 0 : return;
2598 : }
2599 :
2600 0 : if (element->isSlur()) {
2601 0 : doAddSlur(tx, toSlur(element));
2602 0 : return;
2603 : }
2604 :
2605 0 : if (element->isSLine() && elementType != ElementType::GLISSANDO) {
2606 0 : Segment* startSegment = sel.startSegment();
2607 0 : Segment* endSegment = sel.endSegment();
2608 0 : bool firstStaffOnly = isSystemTextLine(element) && !(modifiers & Qt::ControlModifier);
2609 0 : staff_idx_t startStaff = firstStaffOnly ? 0 : sel.staffStart();
2610 0 : staff_idx_t endStaff = firstStaffOnly ? 1 : sel.staffEnd();
2611 0 : for (staff_idx_t i = startStaff; i < endStaff; ++i) {
2612 0 : Spanner* spanner = toSpanner(element->clone());
2613 0 : spanner->setScore(score);
2614 0 : spanner->styleChanged();
2615 0 : EditSpanner::addSpanner(tx, score, spanner, i, startSegment, endSegment, modifiers & Qt::ControlModifier);
2616 0 : if (spanner->hasVoiceAssignmentProperties()) {
2617 0 : spanner->setInitialTrackAndVoiceAssignment(staff2track(i), modifiers & ControlModifier);
2618 : }
2619 0 : selectAndStartEditIfNeeded(spanner);
2620 : }
2621 0 : return;
2622 : }
2623 :
2624 0 : if (element->isTextBase() && !element->isFingering() && !element->isSticking()) {
2625 0 : Segment* firstSegment = sel.startSegment();
2626 0 : staff_idx_t firstStaffIndex = sel.staffStart();
2627 0 : staff_idx_t lastStaffIndex = sel.staffEnd();
2628 :
2629 : // A text should only be added at the start of the selection
2630 : // There shouldn't be a text at each element
2631 0 : if (element->systemFlag()) {
2632 0 : applyDropPaletteElement(score, firstSegment->firstElementForNavigation(0), element, modifiers);
2633 : } else {
2634 0 : for (staff_idx_t staff = firstStaffIndex; staff < lastStaffIndex; staff++) {
2635 0 : applyDropPaletteElement(score, firstSegment->firstElementForNavigation(staff), element, modifiers);
2636 : }
2637 : }
2638 0 : return;
2639 : }
2640 :
2641 0 : if (element->isActionIcon()) {
2642 0 : const ActionIconType actionType = toActionIcon(element)->actionType();
2643 0 : switch (actionType) {
2644 0 : case ActionIconType::SYSTEM_LOCK: {
2645 0 : EditSystemLocks::toggleSystemLock(tx, score, score->selection().selectedSystems());
2646 0 : return;
2647 : }
2648 0 : case ActionIconType::PAGE_LOCK: {
2649 0 : EditPageLocks::togglePageLock(tx, score, score->selection().pagesContainingSelection());
2650 0 : return;
2651 : }
2652 0 : case ActionIconType::PARENTHESES: {
2653 0 : EditParentheses::addParenthesesToNotes(tx, score);
2654 0 : return;
2655 : }
2656 0 : case ActionIconType::STAVE_SHARING_CHANGE: {
2657 0 : EditStaveSharing::addStaveSharingChangeToRange(tx, sel.startSegment(), sel.endSegment(), sel.staffStart(),
2658 : sel.staffEnd(), false);
2659 0 : return;
2660 : }
2661 0 : case ActionIconType::RESET_STAVE_SHARING_CHANGE: {
2662 0 : EditStaveSharing::addStaveSharingChangeToRange(tx, sel.startSegment(), sel.endSegment(), sel.staffStart(),
2663 : sel.staffEnd(), true);
2664 0 : return;
2665 : }
2666 0 : case ActionIconType::STANDARD_BEND:
2667 : case ActionIconType::PRE_BEND:
2668 : case ActionIconType::GRACE_NOTE_BEND:
2669 : case ActionIconType::SLIGHT_BEND:
2670 : case ActionIconType::DIVE:
2671 : case ActionIconType::PRE_DIVE:
2672 : case ActionIconType::DIP:
2673 : case ActionIconType::SCOOP:
2674 : {
2675 : // Insertion of bend may alter the segment list, so collect the original list here and loop on this
2676 0 : std::vector<Segment*> segList;
2677 0 : for (Segment* seg = sel.startSegment(); seg && seg != sel.endSegment(); seg = seg->next1()) {
2678 0 : if (seg->isChordRestType()) {
2679 0 : segList.push_back(seg);
2680 : }
2681 : }
2682 0 : const track_idx_t track1 = staff2track(sel.staffStart());
2683 0 : const track_idx_t track2 = staff2track(sel.staffEnd());
2684 0 : for (Segment* seg : segList) {
2685 0 : for (track_idx_t track = track1; track < track2; ++track) {
2686 0 : EngravingItem* item = seg->element(track);
2687 0 : if (!item || !item->isChord()) {
2688 0 : continue;
2689 : }
2690 0 : for (Note* note : toChord(item)->notes()) {
2691 0 : applyDropPaletteElement(score, note, element, modifiers);
2692 : }
2693 : }
2694 : }
2695 0 : return;
2696 0 : }
2697 0 : default: break;
2698 : }
2699 : }
2700 :
2701 0 : const track_idx_t track1 = staff2track(sel.staffStart());
2702 0 : const track_idx_t track2 = staff2track(sel.staffEnd());
2703 0 : Segment* startSegment = sel.startSegment();
2704 0 : Segment* endSegment = sel.endSegment(); //keep it, it could change during the loop
2705 :
2706 0 : const bool rangeContainsMultiNoteChords = sel.rangeContainsMultiNoteChords();
2707 :
2708 0 : const auto applyDropPaletteElementToChord = [this, score, element, modifiers, rangeContainsMultiNoteChords](Chord* chord) {
2709 0 : const size_t totalNotesInChord = chord->notes().size();
2710 0 : for (size_t noteIdx = 0; noteIdx < totalNotesInChord; ++noteIdx) {
2711 0 : Note* note = chord->notes().at(noteIdx);
2712 0 : if (!note || !score->selectionFilter().canSelectNoteIdx(noteIdx, totalNotesInChord, rangeContainsMultiNoteChords)) {
2713 0 : continue;
2714 : }
2715 0 : applyDropPaletteElement(score, note, element, modifiers);
2716 0 : if (!element->isAccidental() && !element->isNoteHead() && !element->isGlissando() && !element->isChordLine()) {
2717 : // Only need to apply to one note...
2718 0 : break;
2719 : }
2720 : }
2721 0 : };
2722 :
2723 0 : for (Segment* s = startSegment; s && s != endSegment; s = s->next1()) {
2724 0 : for (track_idx_t track = track1; track < track2; ++track) {
2725 0 : EngravingItem* e = s->element(track);
2726 0 : if (!e || !score->selectionFilter().canSelect(e) || !score->selectionFilter().canSelectVoice(track)) {
2727 0 : continue;
2728 : }
2729 0 : if (!e->isChord()) {
2730 : // do not apply articulation or fermata to barline in a range selection
2731 0 : if (!e->isBarLine() || !element->isArticulationOrFermata()) {
2732 0 : applyDropPaletteElement(score, e, element, modifiers);
2733 : }
2734 0 : continue;
2735 : }
2736 :
2737 0 : Chord* chord = toChord(e);
2738 0 : applyDropPaletteElementToChord(chord);
2739 : }
2740 0 : if (!element->placeMultiple()) {
2741 0 : break;
2742 : }
2743 : }
2744 0 : }
2745 :
2746 : //! NOTE Copied from Palette applyDrop
2747 0 : void NotationInteraction::applyDropPaletteElement(mu::engraving::Score* score, mu::engraving::EngravingItem* target,
2748 : mu::engraving::EngravingItem* e, Qt::KeyboardModifiers modifiers,
2749 : track_idx_t track)
2750 : {
2751 0 : if (!target) {
2752 0 : return;
2753 : }
2754 :
2755 0 : mu::engraving::EditData newData(&m_scoreCallbacks);
2756 0 : mu::engraving::EditData* dropData = &newData;
2757 :
2758 0 : if (isTextEditingStarted()) {
2759 0 : dropData = &m_editData;
2760 : }
2761 :
2762 0 : dropData->modifiers = keyboardModifier(modifiers);
2763 0 : dropData->dropElement = e;
2764 0 : dropData->track = (track == muse::nidx) ? target->track() : track;
2765 0 : dropData->pos = target->pageBoundingRect().topLeft();
2766 :
2767 0 : if (target->acceptDrop(*dropData)) {
2768 : // use same code path as drag&drop
2769 :
2770 0 : ByteArray a = e->mimeData();
2771 :
2772 0 : mu::engraving::XmlReader n(a);
2773 :
2774 0 : Fraction duration; // dummy
2775 0 : PointF dragOffset;
2776 0 : ElementType type = EngravingItem::readType(n, &dragOffset, &duration);
2777 0 : dropData->dropElement = engraving::Factory::createItem(type, score->dummy());
2778 0 : rw::RWRegister::reader()->readItem(dropData->dropElement, n);
2779 0 : dropData->dropElement->styleChanged(); // update to local style
2780 :
2781 0 : engraving::Transaction& tx = score->transactionManager()->currentOrDummyTransaction();
2782 0 : EngravingItem* el = target->drop(tx, *dropData);
2783 :
2784 0 : if (el && el->isInstrumentChange()) {
2785 0 : if (!selectInstrument(toInstrumentChange(el))) {
2786 0 : rollback();
2787 0 : return;
2788 : }
2789 : }
2790 :
2791 0 : if (el && el->hasVoiceAssignmentProperties()) {
2792 : // If target has voice assignment properties, dropped element takes those and discards the default
2793 0 : if (!target->hasVoiceAssignmentProperties()) {
2794 0 : el->setInitialTrackAndVoiceAssignment(target->track(), modifiers & ControlModifier);
2795 : }
2796 : }
2797 :
2798 0 : if (el && !score->inputState().noteEntryMode()) {
2799 0 : selectAndStartEditIfNeeded(el);
2800 : }
2801 :
2802 0 : if (score->selection().elements().size() == 1) {
2803 0 : doFinishAddFretboardDiagram();
2804 : }
2805 :
2806 0 : dropData->dropElement = nullptr;
2807 :
2808 0 : m_notifyAboutDropChanged = true;
2809 0 : }
2810 0 : }
2811 :
2812 0 : void NotationInteraction::applyLineNoteToNote(Score* score, Note* note1, Note* note2, EngravingItem* line)
2813 : {
2814 0 : mu::engraving::EditData newData(&m_scoreCallbacks);
2815 0 : mu::engraving::EditData* dropData = &newData;
2816 :
2817 0 : Chord* chord1 = note1->chord();
2818 0 : Chord* chord2 = note2->chord();
2819 0 : bool swapNotes = chord2->tick() < chord1->tick() || chord2->graceIndex() > chord1->graceIndex()
2820 0 : || (chord2->isGraceBefore() && chord2->parent() == chord1)
2821 0 : || (chord1->isGraceAfter() && chord1->parent() == chord2);
2822 :
2823 0 : if (swapNotes) {
2824 0 : std::swap(note1, note2);
2825 : }
2826 :
2827 0 : if (line->isActionIcon() && (toActionIcon(line)->actionType() == ActionIconType::STANDARD_BEND
2828 0 : || toActionIcon(line)->actionType() == ActionIconType::DIVE)) {
2829 0 : score->addGuitarBend(toActionIcon(line)->actionType() == ActionIconType::STANDARD_BEND
2830 : ? GuitarBendType::BEND : GuitarBendType::DIVE, note1, note2);
2831 0 : } else if (line->isActionIcon() && toActionIcon(line)->actionType() == ActionIconType::NOTE_ANCHORED_LINE) {
2832 0 : score->addNoteLine();
2833 0 : } else if (line->isSLine()) {
2834 0 : SLine* dropLine = ((SLine*)line->clone());
2835 0 : dropData->dropElement = dropLine;
2836 0 : if (note1->acceptDrop(*dropData)) {
2837 0 : dropLine->setEndElement(note2);
2838 0 : dropLine->styleChanged();
2839 :
2840 0 : engraving::Transaction& tx = score->transactionManager()->currentOrDummyTransaction();
2841 0 : mu::engraving::EngravingItem* el = note1->drop(tx, *dropData);
2842 0 : if (el && !score->inputState().noteEntryMode()) {
2843 0 : m_selection->select({ el }, mu::engraving::SelectType::SINGLE, 0);
2844 : }
2845 :
2846 0 : dropData->dropElement = nullptr;
2847 :
2848 0 : m_notifyAboutDropChanged = true;
2849 : }
2850 : }
2851 0 : }
2852 :
2853 0 : void NotationInteraction::doAddSlur(Transaction& tx, const Slur* slurTemplate)
2854 : {
2855 0 : endEditSlurToReplace(slurTemplate);
2856 :
2857 0 : for (const EditSlur::AddedSlur& added : EditSlur::addSlurs(tx, score(), slurTemplate)) {
2858 0 : selectAddedSlur(added.slur, added.replacedSlur, added.toNextChord);
2859 0 : }
2860 0 : }
2861 :
2862 0 : void NotationInteraction::doAddSlur(Transaction& tx, EngravingItem* firstItem, EngravingItem* secondItem, const Slur* slurTemplate)
2863 : {
2864 0 : endEditSlurToReplace(slurTemplate);
2865 :
2866 0 : const EditSlur::AddedSlur added = EditSlur::addSlur(tx, score(), firstItem, secondItem, slurTemplate);
2867 0 : if (added.slur) {
2868 0 : selectAddedSlur(added.slur, added.replacedSlur, added.toNextChord);
2869 : }
2870 0 : }
2871 :
2872 : // A hammer-on/pull-off can replace the slur being edited
2873 0 : void NotationInteraction::endEditSlurToReplace(const Slur* slurTemplate)
2874 : {
2875 0 : if (slurTemplate && slurTemplate->isHammerOnPullOff() && m_editData.element && m_editData.element->isSlurSegment()) {
2876 0 : endEditElement();
2877 : }
2878 0 : }
2879 :
2880 0 : void NotationInteraction::selectAddedSlur(Slur* slur, bool replacedSlur, bool toNextChord)
2881 : {
2882 0 : if (replacedSlur || (toNextChord && !m_noteInput->isNoteInputMode())) {
2883 0 : SlurSegment* segment = slur->frontSegment();
2884 0 : select({ segment }, SelectType::SINGLE);
2885 0 : startEditGrip(segment, Grip::END);
2886 : }
2887 :
2888 0 : if (m_noteInput->isNoteInputMode()) {
2889 0 : m_noteInput->addSlur(slur);
2890 : }
2891 0 : }
2892 :
2893 0 : bool NotationInteraction::scoreHasMeasure() const
2894 : {
2895 0 : mu::engraving::Page* page = score()->pages().empty() ? nullptr : score()->pages().front();
2896 0 : const std::vector<mu::engraving::System*>* systems = page ? &page->systems() : nullptr;
2897 0 : if (systems == nullptr || systems->empty() || systems->front()->measures().empty()) {
2898 0 : return false;
2899 : }
2900 :
2901 0 : return true;
2902 : }
2903 :
2904 0 : bool NotationInteraction::notesHaveActiculation(const std::vector<Note*>& notes, SymbolId articulationSymbolId) const
2905 : {
2906 0 : for (Note* note: notes) {
2907 0 : Chord* chord = note->chord();
2908 :
2909 0 : std::set<SymbolId> chordArticulations = chord->articulationSymbolIds();
2910 0 : chordArticulations = mu::engraving::flipArticulations(chordArticulations, mu::engraving::PlacementV::ABOVE);
2911 0 : chordArticulations = mu::engraving::splitArticulations(chordArticulations);
2912 :
2913 0 : if (chordArticulations.find(articulationSymbolId) == chordArticulations.end()) {
2914 0 : return false;
2915 : }
2916 0 : }
2917 :
2918 0 : return true;
2919 : }
2920 :
2921 : //! NOTE Copied from ScoreView::dragLeaveEvent
2922 0 : void NotationInteraction::endDrop()
2923 : {
2924 0 : score()->hideAnchors();
2925 0 : score()->setUpdateAll();
2926 0 : setDropTarget(nullptr, /*notify=*/ false);
2927 0 : resetDropData();
2928 0 : score()->update();
2929 0 : notifyAboutDragChanged();
2930 0 : }
2931 :
2932 0 : muse::async::Notification NotationInteraction::dropChanged() const
2933 : {
2934 0 : return m_dropChanged;
2935 : }
2936 :
2937 : //! NOTE Copied from ScoreView::dropCanvas
2938 0 : bool NotationInteraction::dropCanvas(EngravingItem* e)
2939 : {
2940 0 : if (e->isActionIcon()) {
2941 0 : switch (mu::engraving::toActionIcon(e)->actionType()) {
2942 0 : case mu::engraving::ActionIconType::VFRAME
2943 0 : : score()->insertBox(ElementType::VBOX);
2944 0 : break;
2945 0 : case mu::engraving::ActionIconType::HFRAME:
2946 0 : score()->insertBox(ElementType::HBOX);
2947 0 : break;
2948 0 : case mu::engraving::ActionIconType::TFRAME:
2949 0 : score()->insertBox(ElementType::TBOX);
2950 0 : break;
2951 0 : case mu::engraving::ActionIconType::FFRAME:
2952 0 : score()->insertBox(ElementType::FBOX);
2953 0 : break;
2954 0 : case mu::engraving::ActionIconType::MEASURE:
2955 0 : score()->insertMeasure(ElementType::MEASURE);
2956 0 : break;
2957 0 : default:
2958 0 : return false;
2959 : }
2960 0 : delete e;
2961 0 : return true;
2962 : }
2963 0 : return false;
2964 : }
2965 :
2966 : //! NOTE Copied from ScoreView::getDropTarget
2967 0 : EngravingItem* NotationInteraction::dropTarget(mu::engraving::EditData& ed) const
2968 : {
2969 0 : std::vector<EngravingItem*> el = elementsAt(ed.pos);
2970 0 : mu::engraving::Measure* fallbackMeasure = nullptr;
2971 0 : for (EngravingItem* e : el) {
2972 0 : if (e->isStaffLines()) {
2973 0 : fallbackMeasure = mu::engraving::toStaffLines(e)->measure();
2974 0 : continue;
2975 : }
2976 0 : if (e->acceptDrop(ed)) {
2977 0 : return e;
2978 : }
2979 : }
2980 0 : if (fallbackMeasure && fallbackMeasure->acceptDrop(ed)) {
2981 0 : return fallbackMeasure;
2982 : }
2983 0 : return nullptr;
2984 0 : }
2985 :
2986 0 : bool NotationInteraction::prepareDropStandardElement(const PointF& pos, Qt::KeyboardModifiers modifiers)
2987 : {
2988 0 : IF_ASSERT_FAILED(m_dropData.elementDropData.has_value()) {
2989 0 : return false;
2990 : }
2991 :
2992 0 : ElementDropData& edd = m_dropData.elementDropData.value();
2993 :
2994 0 : Page* page = point2page(pos, true);
2995 0 : if (!page) {
2996 0 : return false;
2997 : }
2998 :
2999 : // Update the tree when starting a new drag (ed.pos hasn't been set yet), if the modifier changed, or when crossing a page
3000 0 : if (edd.ed.pos.isNull() || edd.ed.modifiers != modifiers || page != m_currentDropPage) {
3001 0 : m_currentDropPage = page;
3002 0 : edd.ed.modifiers = keyboardModifier(modifiers);
3003 :
3004 : // Where "m" is the number of page elements and "n" is the number of elements accepting a drop...
3005 : // O(log m) operation
3006 0 : m_droppableTree.initialize(page->pageBoundingRect(), static_cast<int>(page->elements().size()));
3007 :
3008 : // O(m log n) operation
3009 0 : for (EngravingItem* elem : page->elements()) {
3010 0 : if (elem->acceptDrop(edd.ed)) {
3011 0 : m_droppableTree.insert(elem);
3012 : }
3013 0 : }
3014 : }
3015 :
3016 0 : PointF posInPage(pos.x() - page->pos().x(), pos.y() - page->pos().y());
3017 : // O(log n) operation
3018 0 : EngravingItem* targetElem = m_droppableTree.nearestNeighbor(posInPage);
3019 0 : EngravingItem* dropElem = edd.ed.dropElement;
3020 :
3021 0 : if (!targetElem || !dropElem) {
3022 0 : return false;
3023 : }
3024 :
3025 : // Clefs are a special case somewhere between a measure anchored and standard element (hence why
3026 : // we handle it here instead of dragMeasureAnchorElement). They can be applied to individual items
3027 : // but we should switch targets to the whole measure if the target element is the first in the measure...
3028 0 : if (dropElem->isClef() && targetElem->rtick() == Fraction(0, 1)) {
3029 0 : Measure* targetMeasure = targetElem->findMeasure();
3030 0 : if (targetMeasure && dropElem->type() != targetElem->type()) {
3031 0 : setDropTarget(targetMeasure, true);
3032 :
3033 0 : RectF measureRect = targetMeasure->staffPageBoundingRect(targetElem->staffIdx());
3034 0 : measureRect.adjust(page->x(), page->y(), page->x(), page->y());
3035 0 : edd.ed.pos = measureRect.center();
3036 0 : edd.ed.track = trackZeroVoice(targetElem->track());
3037 0 : setAnchorLines({ LineF(pos, measureRect.topLeft()) });
3038 :
3039 0 : const bool dropAccepted = targetMeasure->acceptDrop(edd.ed);
3040 0 : if (dropAccepted) {
3041 0 : setDropRects(dropHighlightRects(dropElem, targetElem, edd.ed.modifiers));
3042 : }
3043 0 : return dropAccepted;
3044 : }
3045 : }
3046 :
3047 0 : setDropTarget(targetElem, true);
3048 0 : edd.ed.pos = targetElem->canvasBoundingRect().center();
3049 0 : setAnchorLines({ LineF(pos, targetElem->canvasBoundingRect().center()) });
3050 0 : setDropRects(dropHighlightRects(dropElem, targetElem, edd.ed.modifiers));
3051 :
3052 0 : return true;
3053 : }
3054 :
3055 : //! NOTE Copied from ScoreView::dragMeasureAnchorElement
3056 0 : bool NotationInteraction::prepareDropMeasureBaseAnchorElement(const PointF& pos)
3057 : {
3058 0 : IF_ASSERT_FAILED(m_dropData.elementDropData.has_value()) {
3059 0 : return false;
3060 : }
3061 :
3062 0 : ElementDropData& edd = m_dropData.elementDropData.value();
3063 :
3064 0 : EngravingItem* dropElem = edd.ed.dropElement;
3065 0 : Page* page = point2page(pos);
3066 0 : if (!dropElem || !page) {
3067 0 : return false;
3068 : }
3069 :
3070 : // "Measure anchored only" means we're dropping something can't anchor to other MeasureBase types (i.e. boxes)...
3071 0 : bool isMeasureAnchorOnly = !dropElem->isLayoutBreak();
3072 0 : if (dropElem->isActionIcon()) {
3073 0 : const ActionIconType actionType = toActionIcon(dropElem)->actionType();
3074 0 : isMeasureAnchorOnly = actionType != ActionIconType::PAGE_LOCK && actionType != ActionIconType::SYSTEM_LOCK;
3075 : }
3076 :
3077 0 : mu::engraving::staff_idx_t staffIdx = muse::nidx;
3078 0 : mu::engraving::MeasureBase* mb = score()->pos2measureBase(pos, /*scanMeasuresOnly*/ isMeasureAnchorOnly, &staffIdx, 0, nullptr, 0);
3079 :
3080 : //! NOTE: Should match Measure::acceptDrop / MeasureBase::acceptDrop
3081 0 : switch (dropElem->type()) {
3082 0 : case ElementType::VOLTA:
3083 : case ElementType::GRADUAL_TEMPO_CHANGE:
3084 : case ElementType::KEYSIG:
3085 : case ElementType::TIMESIG: {
3086 : // If ctrl is pressed, break and target a specific staff
3087 0 : if (edd.ed.modifiers & Qt::ControlModifier) {
3088 0 : break;
3089 : }
3090 : }
3091 : // fall through
3092 : case ElementType::JUMP:
3093 : case ElementType::LAYOUT_BREAK:
3094 : case ElementType::MARKER:
3095 : case ElementType::MEASURE_NUMBER:
3096 : case ElementType::VBOX:
3097 : case ElementType::TBOX:
3098 : case ElementType::FBOX:
3099 : case ElementType::HBOX:
3100 : // Target all staves
3101 0 : staffIdx = 0;
3102 : // fall through
3103 0 : default: break;
3104 : }
3105 :
3106 : // Apart from STAFF_TYPE_CHANGE, measure anchored action icons are applied to all staves
3107 0 : if (dropElem->isActionIcon() && toActionIcon(dropElem)->actionType() != ActionIconType::STAFF_TYPE_CHANGE) {
3108 0 : staffIdx = 0;
3109 : }
3110 :
3111 0 : if (mb) {
3112 0 : setDropTarget(mb, true);
3113 0 : edd.ed.track = staff2track(staffIdx);
3114 :
3115 0 : RectF mbRect = mb->isMeasure() ? toMeasure(mb)->staffPageBoundingRect(staffIdx) : mb->pageBoundingRect();
3116 0 : mbRect.adjust(page->x(), page->y(), page->x(), page->y());
3117 0 : edd.ed.pos = mbRect.center();
3118 :
3119 0 : const bool dropAccepted = mb->acceptDrop(edd.ed);
3120 0 : if (dropAccepted) {
3121 0 : setAnchorLines({ LineF(pos, mbRect.topLeft()) });
3122 :
3123 0 : StaffLines* staffLines = mb->isMeasure() ? toMeasure(mb)->staffLines(staffIdx) : nullptr;
3124 0 : const EngravingItem* targetElem = staffLines ? static_cast<const EngravingItem*>(staffLines)
3125 : : static_cast<const EngravingItem*>(mb);
3126 0 : setDropRects(dropHighlightRects(dropElem, targetElem, edd.ed.modifiers));
3127 : } else {
3128 0 : score()->addRefresh(mb->canvasBoundingRect());
3129 0 : setDropTarget(nullptr);
3130 : }
3131 :
3132 0 : return dropAccepted;
3133 : }
3134 0 : dropElem->score()->addRefresh(dropElem->canvasBoundingRect());
3135 0 : setDropTarget(nullptr);
3136 0 : return false;
3137 : }
3138 :
3139 0 : std::vector<RectF> NotationInteraction::dropHighlightRects(const EngravingItem* dropElem, const EngravingItem* targetElem,
3140 : KeyboardModifiers modifiers) const
3141 : {
3142 0 : const MeasureBase* targetMeasureBase = targetElem->findMeasureBase();
3143 0 : if (!targetMeasureBase) {
3144 0 : return {};
3145 : }
3146 :
3147 0 : const staff_idx_t staffIdx = targetElem->staffIdx() != muse::nidx ? targetElem->staffIdx() : 0;
3148 0 : RectF staffRect = targetMeasureBase->isMeasure() ? toMeasure(targetMeasureBase)->staffPageBoundingRect(staffIdx)
3149 0 : : targetMeasureBase->pageBoundingRect();
3150 0 : if (const System* sys = targetMeasureBase->system()) {
3151 0 : if (const Page* page = sys->page()) {
3152 0 : staffRect.adjust(page->x(), page->y(), page->x(), page->y());
3153 : }
3154 : }
3155 :
3156 0 : switch (dropElem->type()) {
3157 0 : case ElementType::VBOX:
3158 : case ElementType::TBOX:
3159 : case ElementType::FBOX:
3160 : case ElementType::HBOX:
3161 : case ElementType::MEASURE_NUMBER:
3162 : case ElementType::JUMP:
3163 : case ElementType::MARKER:
3164 : case ElementType::LAYOUT_BREAK:
3165 0 : return { targetMeasureBase->canvasBoundingRect() };
3166 :
3167 0 : case ElementType::VOLTA:
3168 : case ElementType::GRADUAL_TEMPO_CHANGE:
3169 : case ElementType::KEYSIG:
3170 : case ElementType::TIMESIG:
3171 0 : if (modifiers & ControlModifier) {
3172 0 : return { staffRect };
3173 : }
3174 0 : return { targetMeasureBase->canvasBoundingRect() };
3175 :
3176 0 : case ElementType::BRACKET:
3177 : case ElementType::MEASURE_REPEAT:
3178 : case ElementType::MEASURE:
3179 : case ElementType::SPACER:
3180 : case ElementType::IMAGE:
3181 : case ElementType::BAR_LINE:
3182 : case ElementType::SYMBOL:
3183 : case ElementType::CLEF:
3184 : case ElementType::STAFFTYPE_CHANGE:
3185 : case ElementType::STRING_TUNINGS:
3186 0 : return { staffRect };
3187 :
3188 0 : case ElementType::ACTION_ICON:
3189 0 : switch (toActionIcon(dropElem)->actionType()) {
3190 0 : case ActionIconType::VFRAME:
3191 : case ActionIconType::HFRAME:
3192 : case ActionIconType::TFRAME:
3193 : case ActionIconType::FFRAME:
3194 : case ActionIconType::MEASURE:
3195 0 : return { targetMeasureBase->canvasBoundingRect() };
3196 :
3197 0 : case ActionIconType::STAFF_TYPE_CHANGE:
3198 0 : return { staffRect };
3199 :
3200 0 : case ActionIconType::SYSTEM_LOCK: {
3201 0 : const System* sys = targetMeasureBase->system();
3202 0 : const MeasureBase* first = sys ? sys->first() : nullptr;
3203 0 : const PointF topLeft = first ? first->canvasBoundingRect().topLeft() : PointF(0.0, 0.0);
3204 0 : return { RectF(topLeft, targetMeasureBase->canvasBoundingRect().bottomRight()) };
3205 : }
3206 :
3207 0 : case ActionIconType::STAVE_SHARING_CHANGE:
3208 : case ActionIconType::RESET_STAVE_SHARING_CHANGE: {
3209 0 : const System* sys = targetMeasureBase->system();
3210 0 : const MeasureBase* last = sys ? sys->last() : nullptr;
3211 0 : const double right = last ? last->canvasBoundingRect().right() : staffRect.right();
3212 0 : const double left = targetElem->canvasBoundingRect().left();
3213 0 : return { RectF(PointF(left, staffRect.top()), PointF(right, staffRect.bottom())) };
3214 : }
3215 :
3216 0 : case ActionIconType::PAGE_LOCK: {
3217 0 : std::vector<RectF> dropRects;
3218 0 : for (System* sys : targetMeasureBase->page()->systems()) {
3219 0 : const bool lastSelectedSys = sys == targetMeasureBase->system();
3220 0 : const MeasureBase* first = sys ? sys->first() : nullptr;
3221 0 : const MeasureBase* last = sys ? sys->last() : nullptr;
3222 0 : if (lastSelectedSys) {
3223 0 : last = targetMeasureBase;
3224 : }
3225 0 : if (!first || !last) {
3226 0 : continue;
3227 : }
3228 0 : dropRects.push_back(RectF(first->canvasBoundingRect().topLeft(), last->canvasBoundingRect().bottomRight()));
3229 :
3230 0 : if (lastSelectedSys) {
3231 0 : break;
3232 : }
3233 : }
3234 0 : return dropRects;
3235 0 : }
3236 :
3237 0 : default:
3238 0 : return {};
3239 : }
3240 :
3241 0 : default:
3242 0 : return {};
3243 : }
3244 : }
3245 :
3246 : //! NOTE Copied from ScoreView::dragTimeAnchorElement
3247 0 : bool NotationInteraction::prepareDropTimeAnchorElement(const PointF& pos)
3248 : {
3249 0 : IF_ASSERT_FAILED(m_dropData.elementDropData.has_value()) {
3250 0 : return false;
3251 : }
3252 :
3253 0 : ElementDropData& edd = m_dropData.elementDropData.value();
3254 :
3255 0 : mu::engraving::staff_idx_t staffIdx = 0;
3256 0 : mu::engraving::Segment* seg = nullptr;
3257 0 : mu::engraving::Measure* measure = score()->pos2measure(pos, &staffIdx, /*pitch*/ 0, &seg, /*offset*/ 0);
3258 0 : mu::engraving::track_idx_t track = staff2track(staffIdx);
3259 :
3260 0 : if (measure && seg->element(track)) {
3261 0 : mu::engraving::System* s = measure->system();
3262 0 : qreal y = s->staff(staffIdx)->y() + s->pos().y() + s->page()->pos().y();
3263 0 : PointF anchor(seg->canvasBoundingRect().x(), y);
3264 0 : setAnchorLines({ LineF(pos, anchor) });
3265 0 : setDropRects(dropHighlightRects(edd.ed.dropElement, seg->element(track), edd.ed.modifiers));
3266 0 : edd.ed.dropElement->score()->addRefresh(edd.ed.dropElement->canvasBoundingRect());
3267 0 : edd.ed.dropElement->setTrack(track);
3268 0 : edd.ed.dropElement->score()->addRefresh(edd.ed.dropElement->canvasBoundingRect());
3269 0 : notifyAboutDragChanged();
3270 0 : return true;
3271 : }
3272 :
3273 0 : edd.ed.dropElement->score()->addRefresh(edd.ed.dropElement->canvasBoundingRect());
3274 0 : setDropTarget(nullptr);
3275 :
3276 0 : return false;
3277 : }
3278 :
3279 : //! NOTE Copied from ScoreView::setDropTarget
3280 0 : void NotationInteraction::setDropTarget(EngravingItem* item, bool notify)
3281 : {
3282 0 : if (!m_dropData.elementDropData.has_value()) {
3283 0 : return;
3284 : }
3285 :
3286 0 : ElementDropData& edd = m_dropData.elementDropData.value();
3287 :
3288 0 : if (edd.dropTarget != item) {
3289 0 : if (edd.dropTarget) {
3290 0 : edd.dropTarget->setDropTarget(false);
3291 0 : edd.ed.track = muse::nidx;
3292 0 : edd.dropTarget = nullptr;
3293 : }
3294 :
3295 0 : edd.dropTarget = item;
3296 0 : if (edd.dropTarget) {
3297 0 : edd.dropTarget->setDropTarget(true);
3298 0 : edd.ed.track = edd.dropTarget->track();
3299 : }
3300 : }
3301 :
3302 0 : resetAnchorLines();
3303 :
3304 0 : if (!edd.dropRects.empty()) {
3305 0 : edd.dropRects.clear();
3306 : }
3307 :
3308 0 : if (notify) {
3309 0 : notifyAboutDragChanged();
3310 : }
3311 : }
3312 :
3313 : //! NOTE: Copied from ScoreView::setDropRectangles
3314 0 : void NotationInteraction::setDropRects(const std::vector<RectF>& rects)
3315 : {
3316 0 : if (!m_dropData.elementDropData.has_value()) {
3317 0 : return;
3318 : }
3319 :
3320 0 : ElementDropData& edd = m_dropData.elementDropData.value();
3321 :
3322 0 : if (edd.dropRects == rects) {
3323 0 : return;
3324 : }
3325 :
3326 0 : edd.dropRects = rects;
3327 :
3328 0 : for (const RectF& rect : rects) {
3329 0 : if (rect.isValid()) {
3330 0 : score()->addRefresh(rect);
3331 : }
3332 : }
3333 :
3334 0 : if (edd.dropTarget) {
3335 0 : edd.dropTarget->setDropTarget(false);
3336 0 : score()->addRefresh(edd.dropTarget->canvasBoundingRect());
3337 0 : } else if (!m_anchorLines.empty()) {
3338 0 : RectF rf;
3339 0 : rf.setTopLeft(m_anchorLines.front().p1());
3340 0 : rf.setBottomRight(m_anchorLines.front().p2());
3341 0 : score()->addRefresh(rf.normalized());
3342 0 : resetAnchorLines();
3343 : }
3344 :
3345 0 : notifyAboutDragChanged();
3346 : }
3347 :
3348 0 : void NotationInteraction::resetDropData()
3349 : {
3350 0 : if (m_dropData.elementDropData.has_value()) {
3351 0 : delete m_dropData.elementDropData->ed.dropElement;
3352 : }
3353 :
3354 0 : m_dropData = {};
3355 0 : }
3356 :
3357 0 : void NotationInteraction::doFinishAddFretboardDiagram()
3358 : {
3359 0 : EngravingItem* selectedElement = score()->selection().element();
3360 0 : if (!selectedElement || !selectedElement->isFretDiagram()) {
3361 0 : return;
3362 : }
3363 :
3364 0 : FretDiagram* fretDiagram = toFretDiagram(selectedElement);
3365 0 : if (!fretDiagram->harmonyPlainText().empty()) {
3366 0 : return;
3367 : }
3368 :
3369 : //! first we need to apply changes
3370 0 : apply();
3371 :
3372 : //! then add harmony
3373 : // NOTE: needs to be done on a separate transaction because when text editing ends, if text is empty
3374 : // the last action is rolled back to remove the text, this ensures that only the text insertion is
3375 : // rolled back (and not the diagram insertion).
3376 0 : engraving::TextBase* text = nullptr;
3377 0 : transaction(TranslatableString("undoableAction", "Add chord symbol to fretboard diagram"), [&, this](engraving::Transaction&) {
3378 0 : text = score()->addText(TextStyleType::HARMONY_A, fretDiagram);
3379 0 : });
3380 :
3381 0 : m_selection->select({ text }, SelectType::SINGLE);
3382 0 : startEditElement(text);
3383 : }
3384 :
3385 0 : void NotationInteraction::setAnchorLines(const std::vector<LineF>& anchorList)
3386 : {
3387 0 : m_anchorLines = anchorList;
3388 0 : }
3389 :
3390 0 : void NotationInteraction::resetAnchorLines()
3391 : {
3392 0 : m_anchorLines.clear();
3393 0 : }
3394 :
3395 0 : double NotationInteraction::gridRaster(const EngravingItem* item, muse::Orientation orientation) const
3396 : {
3397 0 : if (item->isBeam()) {
3398 : // Always adjust by .25sp
3399 0 : return 4.0;
3400 : }
3401 :
3402 0 : if (!configuration()->isSnappedToGrid(orientation)) {
3403 0 : return 0.0;
3404 : }
3405 :
3406 0 : return orientation == muse::Orientation::Horizontal ? mu::engraving::MScore::hRaster() : mu::engraving::MScore::vRaster();
3407 : }
3408 :
3409 0 : double NotationInteraction::currentScaling(Painter* painter) const
3410 : {
3411 0 : qreal guiScaling = contextConfiguration()->guiScaling();
3412 0 : return painter->worldTransform().m11() / guiScaling;
3413 : }
3414 :
3415 0 : std::vector<NotationInteraction::ShadowNoteParams> NotationInteraction::previewNotes() const
3416 : {
3417 0 : std::vector<ShadowNoteParams> result;
3418 :
3419 0 : const InputState& is = score()->inputState();
3420 0 : if (!is.isValid()) {
3421 0 : return result;
3422 : }
3423 :
3424 0 : Segment* segment = is.segment();
3425 0 : const staff_idx_t staffIdx = is.staffIdx();
3426 0 : const Staff* staff = score()->staff(staffIdx);
3427 0 : const System* system = segment->system();
3428 0 : const SysStaff* sysStaff = system ? system->staff(staffIdx) : nullptr;
3429 0 : const Measure* measure = segment->measure();
3430 :
3431 0 : if (!staff || !sysStaff || !measure) {
3432 0 : return result;
3433 : }
3434 :
3435 0 : const Fraction tick = is.tick();
3436 0 : const PointF measurePos = measure->canvasPos();
3437 0 : const double lineDist = staff->staffType(tick)->lineDistance().val()
3438 0 : * (staff->isTabStaff(tick) ? 1 : .5)
3439 0 : * staff->staffMag(tick)
3440 0 : * score()->style().spatium();
3441 :
3442 0 : NoteValList nvals;
3443 0 : if (is.rest()) {
3444 0 : nvals.push_back(NoteVal());
3445 : } else {
3446 0 : nvals = is.notes();
3447 : }
3448 :
3449 0 : ShadowNoteParams params;
3450 0 : params.duration = is.rest() ? is.duration() : TDuration();
3451 0 : params.position.segment = segment;
3452 0 : params.position.staffIdx = staffIdx;
3453 :
3454 0 : result.reserve(nvals.size());
3455 :
3456 0 : for (const NoteVal& nval : nvals) {
3457 0 : const int line = mu::engraving::noteValToLine(nval, staff, tick);
3458 0 : const double y = sysStaff->y() + line * lineDist;
3459 :
3460 0 : params.accidentalType = accidentalType(is, nval, line);
3461 0 : params.position.line = line;
3462 :
3463 0 : if (is.beyondScore()) {
3464 0 : params.position.pos = PointF(measure->ldata()->bbox().width() + score()->style().spatium(), y) + measurePos;
3465 : } else {
3466 0 : params.position.pos = PointF(segment->x(), y) + measurePos;
3467 : }
3468 :
3469 0 : result.push_back(params);
3470 : }
3471 :
3472 0 : std::sort(result.begin(), result.end(), [](const ShadowNoteParams& p1, const ShadowNoteParams& p2) {
3473 0 : return p1.position.line < p2.position.line;
3474 : });
3475 :
3476 0 : return result;
3477 0 : }
3478 :
3479 0 : bool NotationInteraction::shouldDrawInputPreview() const
3480 : {
3481 0 : return m_noteInput->isNoteInputMode() && m_noteInput->usingNoteInputMethod(NoteInputMethod::BY_DURATION);
3482 : }
3483 :
3484 0 : void NotationInteraction::drawInputPreview(Painter* painter, const engraving::rendering::PaintOptions& opt)
3485 : {
3486 0 : std::vector<ShadowNoteParams> paramsList = previewNotes();
3487 0 : if (paramsList.empty()) {
3488 0 : return;
3489 : }
3490 :
3491 0 : std::vector<ShadowNote*> previewList;
3492 0 : previewList.reserve(paramsList.size());
3493 :
3494 0 : const InputState& is = score()->inputState();
3495 :
3496 0 : for (ShadowNoteParams& params : paramsList) {
3497 0 : ShadowNote* preview = new ShadowNote(score());
3498 0 : doShowShadowNote(*preview, params);
3499 0 : previewList.push_back(preview);
3500 : }
3501 :
3502 0 : const bool isUp = !is.rest() && previewList.front()->computeUp();
3503 0 : bool isLeft = isUp;
3504 0 : int prevLine = INT_MAX;
3505 :
3506 0 : auto correctNotePositionIfNeed = [&](ShadowNote* note) {
3507 0 : if (paramsList.size() == 1) {
3508 0 : return;
3509 : }
3510 :
3511 0 : const bool conflict = std::abs(prevLine - note->lineIndex()) < 2;
3512 0 : prevLine = note->lineIndex();
3513 :
3514 0 : if (conflict || (isUp != isLeft)) {
3515 0 : isLeft = !isLeft;
3516 : }
3517 :
3518 0 : if (isUp == isLeft) {
3519 0 : return;
3520 : }
3521 :
3522 0 : const RectF noteheadBbox = note->symBbox(note->noteheadSymbol());
3523 :
3524 0 : if (isLeft) {
3525 0 : note->move(PointF(-noteheadBbox.width(), 0.));
3526 : } else {
3527 0 : note->move(PointF(noteheadBbox.width(), 0.));
3528 : }
3529 0 : };
3530 :
3531 0 : if (isUp) {
3532 0 : for (auto it = previewList.rbegin(); it != previewList.rend(); ++it) {
3533 0 : correctNotePositionIfNeed(*it);
3534 0 : score()->renderer()->drawItem(*it, painter, opt);
3535 : }
3536 : } else {
3537 0 : for (auto it = previewList.begin(); it != previewList.end(); ++it) {
3538 0 : correctNotePositionIfNeed(*it);
3539 0 : score()->renderer()->drawItem(*it, painter, opt);
3540 : }
3541 : }
3542 :
3543 0 : DeleteAll(previewList);
3544 0 : }
3545 :
3546 0 : void NotationInteraction::drawAnchorLines(Painter* painter)
3547 : {
3548 0 : if (m_anchorLines.empty()) {
3549 0 : return;
3550 : }
3551 :
3552 0 : const auto dropAnchorColor = score()->configuration()->formattingColor();
3553 0 : Pen pen(dropAnchorColor, 2.0 / currentScaling(painter), PenStyle::DotLine);
3554 :
3555 0 : for (const LineF& anchor : m_anchorLines) {
3556 0 : painter->setPen(pen);
3557 0 : painter->drawLine(anchor);
3558 :
3559 0 : qreal d = 4.0 / currentScaling(painter);
3560 0 : RectF rect(-d, -d, 2 * d, 2 * d);
3561 :
3562 0 : painter->setBrush(Brush(dropAnchorColor));
3563 0 : painter->setNoPen();
3564 0 : rect.moveCenter(anchor.p1());
3565 0 : painter->drawEllipse(rect);
3566 0 : rect.moveCenter(anchor.p2());
3567 0 : painter->drawEllipse(rect);
3568 : }
3569 0 : }
3570 :
3571 0 : void NotationInteraction::drawTextEditMode(muse::draw::Painter* painter, const engraving::rendering::PaintOptions& opt)
3572 : {
3573 0 : if (!isTextEditingStarted()) {
3574 0 : return;
3575 : }
3576 :
3577 0 : editModeRenderer()->drawItem(m_editData.element, painter, m_editData, currentScaling(painter), opt);
3578 : }
3579 :
3580 0 : void NotationInteraction::drawSelectionRange(muse::draw::Painter* painter)
3581 : {
3582 : using namespace muse::draw;
3583 0 : if (!m_selection->isRange()) {
3584 0 : return;
3585 : }
3586 :
3587 0 : painter->setBrush(BrushStyle::NoBrush);
3588 :
3589 0 : Color selectionColor = configuration()->selectionColor();
3590 0 : double penWidth = 3.0 / currentScaling(painter);
3591 0 : double minPenWidth = 0.20 * m_selection->range()->measureBaseRange().startMeasureBase->spatium();
3592 0 : penWidth = std::max(penWidth, minPenWidth);
3593 :
3594 0 : Pen pen;
3595 0 : pen.setColor(selectionColor);
3596 0 : pen.setWidthF(penWidth);
3597 0 : pen.setStyle(PenStyle::SolidLine);
3598 0 : painter->setPen(pen);
3599 :
3600 0 : std::vector<RectF> rangeArea = m_selection->range()->boundingArea();
3601 0 : for (const RectF& rect: rangeArea) {
3602 0 : PainterPath path;
3603 0 : path.addRoundedRect(rect, 4, 4);
3604 :
3605 0 : Color fillColor = selectionColor;
3606 0 : fillColor.setAlpha(10);
3607 0 : painter->fillPath(path, fillColor);
3608 0 : painter->drawPath(path);
3609 0 : }
3610 0 : }
3611 :
3612 0 : void NotationInteraction::drawGripPoints(muse::draw::Painter* painter, const engraving::rendering::PaintOptions& opt)
3613 : {
3614 0 : if (isDragStarted() && !isGripEditStarted()) {
3615 0 : return;
3616 : }
3617 :
3618 0 : mu::engraving::EngravingItem* editedElement = m_editData.element;
3619 0 : if (!editedElement) {
3620 0 : EngravingItem* selectedElement = m_selection->element();
3621 0 : if (selectedElement && selectedElement->isDynamic()) {
3622 0 : editedElement = selectedElement;
3623 : }
3624 : }
3625 :
3626 0 : if (editedElement && editedElement->isDynamic()) {
3627 0 : toDynamic(editedElement)->findAdjacentHairpins();
3628 : }
3629 :
3630 0 : int gripsCount = editedElement ? editedElement->gripsCount() : 0;
3631 :
3632 0 : if (gripsCount == 0) {
3633 0 : return;
3634 : }
3635 :
3636 0 : m_editData.grips = gripsCount;
3637 0 : m_editData.grip.resize(m_editData.grips);
3638 :
3639 0 : constexpr qreal DEFAULT_GRIP_SIZE = 8;
3640 0 : qreal scaling = currentScaling(painter);
3641 0 : qreal gripSize = DEFAULT_GRIP_SIZE / scaling;
3642 0 : RectF newRect(-gripSize / 2, -gripSize / 2, gripSize, gripSize);
3643 :
3644 0 : const EngravingItem* page = editedElement->findAncestor(ElementType::PAGE);
3645 0 : PointF pageOffset = page ? page->pos() : editedElement->pos();
3646 :
3647 0 : for (RectF& gripRect: m_editData.grip) {
3648 0 : gripRect = newRect.translated(pageOffset);
3649 : }
3650 :
3651 0 : editedElement->updateGrips(m_editData);
3652 0 : editModeRenderer()->drawItem(editedElement, painter, m_editData, scaling, opt);
3653 : }
3654 :
3655 0 : void NotationInteraction::drawLasso(muse::draw::Painter* painter, const engraving::rendering::PaintOptions& opt)
3656 : {
3657 0 : if (!m_lasso || m_lasso->isEmpty()) {
3658 0 : return;
3659 : }
3660 :
3661 0 : score()->renderer()->drawItem(m_lasso, painter, opt);
3662 : }
3663 :
3664 0 : void NotationInteraction::drawDrop(muse::draw::Painter* painter)
3665 : {
3666 0 : if (m_dropData.elementDropData.has_value()) {
3667 0 : const ElementDropData& edd = m_dropData.elementDropData.value();
3668 :
3669 0 : for (const RectF& rect : edd.dropRects) {
3670 0 : if (rect.isValid()) {
3671 0 : painter->fillRect(rect, configuration()->dropRectColor());
3672 : }
3673 : }
3674 : }
3675 :
3676 0 : if (m_dropData.rangeDropData.has_value()) {
3677 0 : const RangeDropData& rdd = m_dropData.rangeDropData.value();
3678 :
3679 0 : Color selectionColor = configuration()->selectionColor();
3680 0 : double penWidth = 3.0 / currentScaling(painter);
3681 0 : double minPenWidth = 0.20 * score()->style().spatium();
3682 0 : penWidth = std::max(penWidth, minPenWidth);
3683 :
3684 0 : Pen pen;
3685 0 : pen.setColor(selectionColor);
3686 0 : pen.setWidthF(penWidth);
3687 0 : pen.setStyle(PenStyle::SolidLine);
3688 0 : painter->setPen(pen);
3689 :
3690 0 : for (const RectF& rect: rdd.dropRects) {
3691 0 : PainterPath path;
3692 0 : path.addRoundedRect(rect, 4, 4);
3693 :
3694 0 : Color fillColor = selectionColor;
3695 0 : fillColor.setAlpha(10);
3696 0 : painter->fillPath(path, fillColor);
3697 0 : painter->drawPath(path);
3698 0 : }
3699 0 : }
3700 0 : }
3701 :
3702 0 : bool NotationInteraction::moveSelectionAvailable(MoveSelectionType type) const
3703 : {
3704 0 : if (type != MoveSelectionType::EngravingItem) {
3705 0 : return !isEditingElement();
3706 : }
3707 :
3708 0 : EngravingItem* el = score()->selection().element();
3709 : const std::set<ElementType> allowedTextEditTypes = {
3710 : ElementType::STAFF_TEXT,
3711 : ElementType::SYSTEM_TEXT,
3712 : ElementType::EXPRESSION,
3713 : ElementType::REHEARSAL_MARK
3714 0 : };
3715 0 : if (isTextEditingStarted() && el && allowedTextEditTypes.find(el->type()) != allowedTextEditTypes.end()) {
3716 0 : return true;
3717 : }
3718 :
3719 0 : if (isGripEditStarted()) {
3720 0 : return true;
3721 : }
3722 :
3723 0 : return m_editData.element && m_editData.element->isTextBase() ? !isTextEditingStarted() : !isEditingElement();
3724 0 : }
3725 :
3726 0 : void NotationInteraction::moveSelectionDeprecated(MoveDirection d, MoveSelectionType type)
3727 : {
3728 0 : m_selection->moveSelection(d, type);
3729 0 : }
3730 :
3731 0 : static ChordRest* asChordRest(EngravingItem* e)
3732 : {
3733 0 : if (e && e->isNote()) {
3734 0 : return toNote(e)->chord();
3735 0 : } else if (e && e->isChordRest()) {
3736 0 : return toChordRest(e);
3737 : }
3738 0 : return nullptr;
3739 : }
3740 :
3741 0 : void NotationInteraction::moveChordRestToStaff(MoveDirection dir)
3742 : {
3743 0 : startEdit(TranslatableString("undoableAction", "Move chord/rest to staff"));
3744 :
3745 0 : engraving::Transaction& tx = score()->transactionManager()->currentOrDummyTransaction();
3746 0 : for (EngravingItem* e: score()->selection().uniqueElements()) {
3747 0 : ChordRest* cr = asChordRest(e);
3748 0 : if (cr != nullptr) {
3749 0 : if (dir == MoveDirection::Up) {
3750 0 : EditCrossStaff::moveUp(tx, score(), cr);
3751 0 : } else if (dir == MoveDirection::Down) {
3752 0 : EditCrossStaff::moveDown(tx, score(), cr);
3753 : }
3754 : }
3755 0 : }
3756 :
3757 0 : apply();
3758 0 : }
3759 :
3760 0 : void NotationInteraction::swapChordRest(MoveDirection direction)
3761 : {
3762 0 : ChordRest* cr = asChordRest(score()->getSelectedElement());
3763 0 : if (!cr) {
3764 0 : return;
3765 : }
3766 0 : QList<ChordRest*> crl;
3767 0 : if (cr->links()) {
3768 0 : for (auto* l : *cr->links()) {
3769 0 : crl.append(toChordRest(l));
3770 : }
3771 : } else {
3772 0 : crl.append(cr);
3773 : }
3774 0 : startEdit(TranslatableString("undoableAction", "Move chord/rest"));
3775 0 : for (ChordRest* cr1 : crl) {
3776 0 : if (cr1->isRest()) {
3777 0 : Measure* m = toRest(cr1)->measure();
3778 0 : if (m && m->isMMRest()) {
3779 0 : break;
3780 : }
3781 : }
3782 : ChordRest* cr2;
3783 : // ensures cr1 is the left chord, useful in SwapCR::flip()
3784 0 : if (direction == MoveDirection::Left) {
3785 0 : cr2 = cr1;
3786 0 : cr1 = engraving::Navigation::prevChordRest(cr2);
3787 : } else {
3788 0 : cr2 = engraving::Navigation::nextChordRest(cr1);
3789 : }
3790 0 : if (cr1 && cr2 && cr1->measure() == cr2->measure() && !cr1->tuplet() && !cr2->tuplet()
3791 0 : && cr1->durationType() == cr2->durationType() && cr1->ticks() == cr2->ticks()
3792 : // if two chords belong to different two-note tremolos, abort
3793 0 : && !(cr1->isChord() && toChord(cr1)->tremoloTwoChord()
3794 0 : && cr2->isChord() && toChord(cr2)->tremoloTwoChord()
3795 0 : && toChord(cr1)->tremoloTwoChord() != toChord(cr2)->tremoloTwoChord())) {
3796 0 : score()->undo(new mu::engraving::SwapCR(cr1, cr2));
3797 : }
3798 : }
3799 0 : apply();
3800 0 : }
3801 :
3802 0 : void NotationInteraction::toggleSnapToPrevious()
3803 : {
3804 0 : bool newSnapValue = false;
3805 :
3806 : // Collect items to toggle...
3807 0 : std::unordered_set<Hairpin*> hairpins;
3808 0 : for (EngravingItem* e : score()->selection().elements()) {
3809 0 : if (e->isHairpinSegment()) {
3810 0 : Hairpin* h = toHairpinSegment(e)->hairpin();
3811 : // If any item in the selection has a false snapping value, then we should
3812 : // toggle all to true (handles mixed/indeterminate state)
3813 0 : if (!h->snapToItemBefore() && !newSnapValue) {
3814 0 : newSnapValue = true;
3815 : }
3816 0 : hairpins.emplace(h);
3817 : }
3818 : }
3819 0 : if (hairpins.empty()) {
3820 0 : return;
3821 : }
3822 :
3823 : // Do toggle...
3824 0 : startEdit(TranslatableString("undoableAction", "Toggle snap to previous"));
3825 0 : for (Hairpin* h : hairpins) {
3826 0 : if (h->snapToItemBefore() == newSnapValue) {
3827 0 : continue;
3828 : }
3829 0 : h->undoChangeProperty(Pid::SNAP_BEFORE, PropertyValue(newSnapValue));
3830 : }
3831 0 : apply();
3832 0 : }
3833 :
3834 0 : void NotationInteraction::toggleSnapToNext()
3835 : {
3836 0 : bool newSnapValue = false;
3837 :
3838 : // Collect items to toggle...
3839 0 : std::unordered_set<Hairpin*> hairpins;
3840 0 : std::unordered_set<GradualTempoChange*> gradualTempoChanges;
3841 0 : for (EngravingItem* e : score()->selection().elements()) {
3842 0 : if (e->isHairpinSegment()) {
3843 0 : Hairpin* h = toHairpinSegment(e)->hairpin();
3844 : // If any item in the selection has a false snapping value, then we should
3845 : // toggle all to true (handles mixed/indeterminate state)
3846 0 : if (!h->snapToItemAfter() && !newSnapValue) {
3847 0 : newSnapValue = true;
3848 : }
3849 0 : hairpins.emplace(h);
3850 : }
3851 0 : if (e->isGradualTempoChangeSegment()) {
3852 0 : GradualTempoChange* gtc = toGradualTempoChangeSegment(e)->tempoChange();
3853 : // Same here (see above)
3854 0 : if (!gtc->snapToItemAfter() && !newSnapValue) {
3855 0 : newSnapValue = true;
3856 : }
3857 0 : gradualTempoChanges.emplace(gtc);
3858 : }
3859 : }
3860 0 : if (hairpins.empty() && gradualTempoChanges.empty()) {
3861 0 : return;
3862 : }
3863 :
3864 : // Do toggle...
3865 0 : startEdit(TranslatableString("undoableAction", "Toggle snap to next"));
3866 0 : for (Hairpin* h : hairpins) {
3867 0 : if (h->snapToItemAfter() == newSnapValue) {
3868 0 : continue;
3869 : }
3870 0 : h->undoChangeProperty(Pid::SNAP_AFTER, PropertyValue(newSnapValue));
3871 : }
3872 0 : for (GradualTempoChange* gtc : gradualTempoChanges) {
3873 0 : if (gtc->snapToItemAfter() == newSnapValue) {
3874 0 : continue;
3875 : }
3876 0 : gtc->undoChangeProperty(Pid::SNAP_AFTER, PropertyValue(newSnapValue));
3877 : }
3878 0 : apply();
3879 0 : }
3880 :
3881 0 : inline mu::engraving::DirectionV toDirection(MoveDirection d)
3882 : {
3883 0 : return d == MoveDirection::Up ? mu::engraving::DirectionV::UP : mu::engraving::DirectionV::DOWN;
3884 : }
3885 :
3886 0 : void NotationInteraction::movePitch(MoveDirection d, PitchMode mode)
3887 : {
3888 0 : IF_ASSERT_FAILED(MoveDirection::Up == d || MoveDirection::Down == d) {
3889 0 : return;
3890 : }
3891 :
3892 0 : const mu::engraving::Selection& selection = score()->selection();
3893 0 : const bool hasNotes = !selection.uniqueNotes().empty();
3894 :
3895 : // Range selections only transpose notes; rests are moved for list selections (without notes) only
3896 0 : std::vector<Rest*> rests;
3897 0 : if (!hasNotes && selection.isList()) {
3898 0 : for (EngravingItem* el : selection.elements()) {
3899 0 : if (el->isRest()) {
3900 0 : rests.push_back(toRest(el));
3901 : }
3902 : }
3903 : }
3904 :
3905 0 : if (rests.empty() && !hasNotes) {
3906 0 : return;
3907 : }
3908 :
3909 0 : startEdit(hasNotes ? TranslatableString("undoableAction", "Change pitch")
3910 : : TranslatableString("undoableAction", "Change vertical position"));
3911 :
3912 0 : if (hasNotes) {
3913 0 : EditNote::upDown(score(), MoveDirection::Up == d, mode);
3914 : } else {
3915 0 : for (Rest* rest : rests) {
3916 0 : if (rest->staff()->isTabStaff(rest->tick())) {
3917 : // The rest won't be visible - don't try to move it...
3918 0 : continue;
3919 : }
3920 0 : score()->cmdMoveRest(rest, toDirection(d));
3921 : }
3922 : }
3923 :
3924 0 : apply();
3925 0 : }
3926 :
3927 0 : void NotationInteraction::shiftLyricsVerses(Transaction& tx, MoveDirection d, const std::vector<EngravingItem*>& elements)
3928 : {
3929 0 : const bool up = d == MoveDirection::Up;
3930 :
3931 0 : std::vector<Lyrics*> lyrics;
3932 0 : std::set<const LinkedObjects*> movedLinks;
3933 0 : for (EngravingItem* el : elements) {
3934 0 : if (!el->isLyrics()) {
3935 0 : continue;
3936 : }
3937 :
3938 0 : Lyrics* l = toLyrics(el);
3939 :
3940 : // Move the selected lyrics as a block: if one can't move up, don't move any
3941 0 : if (up && l->verse() == 0) {
3942 0 : return;
3943 : }
3944 :
3945 0 : if (l->links() && !movedLinks.insert(l->links()).second) {
3946 0 : continue;
3947 : }
3948 :
3949 0 : lyrics.push_back(l);
3950 : }
3951 :
3952 : // Lyrics::undoChangeProperty swaps a lyric with the one already in its target verse,
3953 : // so we move the lyrics furthest in the direction of travel first. Otherwise, selected
3954 : // lyrics would swap with each other instead of moving together:
3955 0 : std::sort(lyrics.begin(), lyrics.end(), [up](const Lyrics* a, const Lyrics* b) {
3956 0 : return up ? a->verse() < b->verse() : a->verse() > b->verse();
3957 : });
3958 :
3959 0 : for (Lyrics* l : lyrics) {
3960 0 : EditLyrics::shiftLyricsVerse(tx, l, toDirection(d));
3961 : }
3962 0 : }
3963 :
3964 0 : void NotationInteraction::nudge(MoveDirection d, bool quickly, const std::vector<EngravingItem*>& elements)
3965 : {
3966 0 : const bool horizontal = d == MoveDirection::Left || d == MoveDirection::Right;
3967 0 : const muse::Orientation orientation = horizontal ? muse::Orientation::Horizontal : muse::Orientation::Vertical;
3968 :
3969 0 : for (EngravingItem* el : elements) {
3970 0 : const double step = nudgeDistance(el, quickly, gridRaster(el, orientation));
3971 :
3972 0 : switch (d) {
3973 0 : case MoveDirection::Undefined:
3974 0 : UNREACHABLE;
3975 : break;
3976 0 : case MoveDirection::Left:
3977 0 : el->undoChangeProperty(mu::engraving::Pid::OFFSET, el->offset() - PointF(step, 0.0), mu::engraving::PropertyFlags::UNSTYLED);
3978 0 : break;
3979 0 : case MoveDirection::Right:
3980 0 : el->undoChangeProperty(mu::engraving::Pid::OFFSET, el->offset() + PointF(step, 0.0), mu::engraving::PropertyFlags::UNSTYLED);
3981 0 : break;
3982 0 : case MoveDirection::Up:
3983 0 : el->undoChangeProperty(mu::engraving::Pid::OFFSET, el->offset() - PointF(0.0, step), mu::engraving::PropertyFlags::UNSTYLED);
3984 0 : break;
3985 0 : case MoveDirection::Down:
3986 0 : el->undoChangeProperty(mu::engraving::Pid::OFFSET, el->offset() + PointF(0.0, step), mu::engraving::PropertyFlags::UNSTYLED);
3987 0 : break;
3988 : }
3989 : }
3990 0 : }
3991 :
3992 0 : void NotationInteraction::nudgeAnchors(MoveDirection d)
3993 : {
3994 : // TODO: Refactor grip editing to allow multiple selection and nudging (without rebasing anchors)
3995 :
3996 0 : IF_ASSERT_FAILED(m_editData.element) {
3997 0 : return;
3998 : }
3999 :
4000 0 : const EngravingItem* element = m_editData.element;
4001 0 : const bool quickly = m_editData.modifiers & mu::engraving::ControlModifier;
4002 0 : const double hRaster = gridRaster(element, muse::Orientation::Horizontal);
4003 0 : const double vRaster = gridRaster(element, muse::Orientation::Vertical);
4004 :
4005 0 : switch (d) {
4006 0 : case MoveDirection::Left:
4007 0 : m_editData.delta = PointF(-nudgeDistance(element, quickly, hRaster), 0);
4008 0 : break;
4009 0 : case MoveDirection::Right:
4010 0 : m_editData.delta = PointF(nudgeDistance(element, quickly, hRaster), 0);
4011 0 : break;
4012 0 : case MoveDirection::Up:
4013 0 : m_editData.delta = PointF(0, -nudgeDistance(element, quickly, vRaster));
4014 0 : break;
4015 0 : case MoveDirection::Down:
4016 0 : m_editData.delta = PointF(0, nudgeDistance(element, quickly, vRaster));
4017 0 : break;
4018 0 : case MoveDirection::Undefined:
4019 0 : UNREACHABLE;
4020 : return;
4021 : }
4022 :
4023 0 : m_editData.evtDelta = m_editData.moveDelta = m_editData.delta;
4024 0 : m_editData.hRaster = hRaster;
4025 0 : m_editData.vRaster = vRaster;
4026 :
4027 0 : m_editData.isEditMode = isEditingElement();
4028 :
4029 0 : if (m_editData.curGrip != mu::engraving::Grip::NO_GRIP && int(m_editData.curGrip) < m_editData.grips) {
4030 0 : m_editData.pos = m_editData.grip[int(m_editData.curGrip)].center() + m_editData.delta;
4031 :
4032 0 : m_editData.element->startDragGrip(m_editData);
4033 0 : m_editData.element->dragGrip(m_editData);
4034 0 : m_editData.element->endDragGrip(m_editData);
4035 : } else {
4036 0 : m_editData.element->startDrag(m_editData);
4037 0 : m_editData.element->drag(m_editData);
4038 0 : m_editData.element->endDrag(m_editData);
4039 : }
4040 : }
4041 :
4042 0 : static bool isNudgeable(const EngravingItem* item)
4043 : {
4044 0 : return item->isTextBase()
4045 0 : || item->isArticulationFamily()
4046 0 : || item->isSymbol()
4047 0 : || item->isFermata()
4048 0 : || item->isBreath()
4049 : // Items whose default grip moves the item's offset (rather than resizing or reshaping it) when they are edited on their own:
4050 0 : || item->isTuplet()
4051 0 : || item->isImage()
4052 0 : || item->isArpeggio()
4053 0 : || item->isLineSegment()
4054 0 : || item->isSlurTieSegment();
4055 : }
4056 :
4057 0 : static bool followsLyrics(const LyricsLineSegment* segment, const std::set<const EngravingItem*>& lyrics, bool horizontal)
4058 : {
4059 0 : const LyricsLineSegment::LayoutData* ldata = segment->ldata();
4060 0 : if (horizontal) {
4061 0 : return lyrics.count(ldata->startXLyrics) > 0 || lyrics.count(ldata->endXLyrics) > 0;
4062 : }
4063 :
4064 0 : return lyrics.count(ldata->yLyrics) > 0;
4065 : }
4066 :
4067 0 : bool NotationInteraction::moveSelectedItems(MoveDirection d, bool quickly)
4068 : {
4069 0 : if (d == MoveDirection::Undefined) {
4070 0 : return false;
4071 : }
4072 :
4073 0 : const bool vertical = d == MoveDirection::Up || d == MoveDirection::Down;
4074 0 : const PitchMode pitchMode = quickly ? PitchMode::OCTAVE : PitchMode::CHROMATIC;
4075 0 : const mu::engraving::Selection& selection = score()->selection();
4076 :
4077 : // Range selections only transpose notes. In list selections, notes and rests take precedence over other items
4078 0 : const std::vector<EngravingItem*>& selectionElements = selection.elements();
4079 0 : const auto isNoteOrRest = [](const EngravingItem* el) { return el->isNote() || el->isRest(); };
4080 0 : if (selection.isRange() || std::any_of(selectionElements.begin(), selectionElements.end(), isNoteOrRest)) {
4081 0 : if (!vertical || (selection.isRange() && selection.uniqueNotes().empty())) {
4082 0 : return false;
4083 : }
4084 0 : movePitch(d, pitchMode);
4085 0 : return true;
4086 : }
4087 :
4088 0 : std::vector<EngravingItem*> lyrics;
4089 0 : std::vector<EngravingItem*> nudgeable;
4090 :
4091 0 : for (EngravingItem* el : selectionElements) {
4092 0 : if (vertical && !quickly && el->isLyrics()) {
4093 0 : lyrics.push_back(el);
4094 0 : } else if (isNudgeable(el)) {
4095 0 : nudgeable.push_back(el);
4096 : }
4097 : }
4098 :
4099 0 : if (lyrics.empty() && nudgeable.empty()) {
4100 0 : return false;
4101 : }
4102 :
4103 : // Lyrics only change verse when no other items are being nudged: otherwise, they're nudged with them
4104 0 : if (!lyrics.empty() && !nudgeable.empty()) {
4105 0 : nudgeable.insert(nudgeable.end(), lyrics.begin(), lyrics.end());
4106 0 : lyrics.clear();
4107 : }
4108 :
4109 : // Don't nudge lyrics lines that already follow the position of a nudged lyric (or they would move twice as much)
4110 0 : std::set<const EngravingItem*> nudgedLyrics;
4111 0 : for (const EngravingItem* el : nudgeable) {
4112 0 : if (el->isLyrics()) {
4113 0 : nudgedLyrics.insert(el);
4114 : }
4115 : }
4116 0 : if (!nudgedLyrics.empty()) {
4117 0 : std::erase_if(nudgeable, [&nudgedLyrics, vertical](const EngravingItem* el) {
4118 0 : return el->isLyricsLineSegment() && followsLyrics(toLyricsLineSegment(el), nudgedLyrics, !vertical);
4119 : });
4120 : }
4121 :
4122 0 : transaction(TranslatableString("undoableAction", "Move items"), [&](Transaction& tx) {
4123 0 : if (!lyrics.empty()) {
4124 0 : shiftLyricsVerses(tx, d, lyrics);
4125 : } else {
4126 0 : nudge(d, quickly, nudgeable);
4127 : }
4128 0 : });
4129 :
4130 0 : if (!nudgeable.empty()) {
4131 0 : notifyAboutDragChanged();
4132 : } else {
4133 0 : notifyAboutNotationChanged();
4134 : }
4135 :
4136 0 : return true;
4137 0 : }
4138 :
4139 0 : bool NotationInteraction::isTextSelected() const
4140 : {
4141 0 : EngravingItem* selectedElement = m_selection->element();
4142 0 : if (!selectedElement) {
4143 0 : return false;
4144 : }
4145 :
4146 0 : if (!selectedElement->isTextBase()) {
4147 0 : return false;
4148 : }
4149 :
4150 0 : return true;
4151 : }
4152 :
4153 0 : bool NotationInteraction::isTextEditingStarted() const
4154 : {
4155 0 : EngravingItem* element = m_editData.element;
4156 0 : return element && element->isTextBase() && toTextBase(element)->cursor() && toTextBase(element)->cursor()->editing();
4157 : }
4158 :
4159 0 : bool NotationInteraction::textEditingAllowed(const EngravingItem* element) const
4160 : {
4161 0 : return element && element->isEditable() && (element->isTextBase() || element->isTBox());
4162 : }
4163 :
4164 0 : void NotationInteraction::startEditText(EngravingItem* element, const PointF& cursorPos)
4165 : {
4166 0 : if (!element) {
4167 0 : return;
4168 : }
4169 :
4170 0 : if (element->isTBox()) {
4171 0 : element = toTBox(element)->text();
4172 : }
4173 :
4174 0 : if (element != m_selection->element()) {
4175 0 : select({ element }, SelectType::SINGLE);
4176 : }
4177 :
4178 0 : m_editData.clear();
4179 0 : m_editData.element = element;
4180 0 : m_editData.startMove = bindCursorPosToText(cursorPos, m_editData.element);
4181 :
4182 0 : m_editData.element->startEdit(m_editData);
4183 0 : startTextCursorBlinkTimer();
4184 :
4185 0 : m_isEditingElementChanged.notify();
4186 0 : notifyAboutTextEditingStarted();
4187 0 : notifyAboutTextEditingChanged();
4188 : }
4189 :
4190 : //! NOTE: Copied from TextBase::inputTransition
4191 0 : void NotationInteraction::editText(QInputMethodEvent* event)
4192 : {
4193 0 : if (!isTextEditingStarted()) {
4194 0 : return;
4195 : }
4196 :
4197 0 : mu::engraving::TextBase* text = mu::engraving::toTextBase(m_editData.element);
4198 0 : mu::engraving::TextCursor* cursor = text->cursor();
4199 0 : String& preeditString = m_editData.preeditString;
4200 :
4201 : // remove preedit string
4202 0 : size_t n = preeditString.size();
4203 0 : while (n--) {
4204 0 : if (cursor->movePosition(mu::engraving::TextCursor::MoveOperation::Left)) {
4205 0 : mu::engraving::TextBlock& curLine = cursor->curLine();
4206 0 : curLine.remove(static_cast<int>(cursor->column()), cursor);
4207 0 : text->triggerLayout();
4208 0 : text->setTextInvalid();
4209 : }
4210 : }
4211 :
4212 0 : if (!event->commitString().isEmpty()) {
4213 0 : score()->startCmd(TranslatableString("undoableAction", "Edit text"));
4214 0 : text->insertText(event->commitString());
4215 0 : score()->endCmd();
4216 0 : preeditString.clear();
4217 : } else {
4218 0 : preeditString = event->preeditString();
4219 :
4220 0 : if (!preeditString.isEmpty()) {
4221 0 : cursor->updateCursorFormat();
4222 0 : text->editInsertText(cursor, preeditString);
4223 0 : text->setTextInvalid();
4224 0 : score()->renderer()->layoutText1(text);
4225 0 : score()->update();
4226 : }
4227 : }
4228 :
4229 0 : event->accept();
4230 0 : notifyAboutTextEditingChanged();
4231 : }
4232 :
4233 0 : bool NotationInteraction::needStartEditGrip(QKeyEvent* event) const
4234 : {
4235 0 : if (!m_editData.element || !m_editData.element->hasGrips()) {
4236 0 : return false;
4237 : }
4238 :
4239 0 : if (isGripEditStarted()) {
4240 0 : return false;
4241 : }
4242 :
4243 : static const std::set<Qt::Key> arrows {
4244 : Qt::Key_Left,
4245 : Qt::Key_Right,
4246 : Qt::Key_Up,
4247 : Qt::Key_Down
4248 0 : };
4249 :
4250 0 : return muse::contains(arrows, static_cast<Qt::Key>(event->key()));
4251 : }
4252 :
4253 0 : bool NotationInteraction::handleKeyPress(QKeyEvent* event)
4254 : {
4255 0 : mu::engraving::EngravingItem* editElem = m_editData.element;
4256 0 : IF_ASSERT_FAILED(editElem) {
4257 0 : return false;
4258 : }
4259 :
4260 0 : if (editElem->isTextBase() && doTextEdit(event, toTextBase(editElem))) {
4261 0 : return true;
4262 : }
4263 :
4264 : //: Means: an editing operation triggered by a keystroke
4265 0 : startEdit(TranslatableString("undoableAction", "Keystroke edit"));
4266 :
4267 0 : if (editElem->edit(m_editData)) {
4268 0 : apply();
4269 0 : return true;
4270 : } else {
4271 0 : rollback();
4272 : }
4273 :
4274 0 : if (event->modifiers() & Qt::KeyboardModifier::AltModifier) {
4275 0 : return false;
4276 : }
4277 :
4278 0 : MoveDirection direction = MoveDirection::Undefined;
4279 :
4280 0 : switch (event->key()) {
4281 0 : case Qt::Key_Tab:
4282 0 : if (!editElem->hasGrips()) {
4283 0 : return false;
4284 : }
4285 0 : editElem->nextGrip(m_editData);
4286 0 : notifyAboutNotationChanged();
4287 0 : return true;
4288 0 : case Qt::Key_Backtab:
4289 0 : if (!editElem->hasGrips()) {
4290 0 : return false;
4291 : }
4292 0 : editElem->prevGrip(m_editData);
4293 0 : notifyAboutNotationChanged();
4294 0 : return true;
4295 0 : case Qt::Key_Left:
4296 0 : direction = MoveDirection::Left;
4297 0 : break;
4298 0 : case Qt::Key_Right:
4299 0 : direction = MoveDirection::Right;
4300 0 : break;
4301 0 : case Qt::Key_Up:
4302 0 : direction = MoveDirection::Up;
4303 0 : break;
4304 0 : case Qt::Key_Down:
4305 0 : direction = MoveDirection::Down;
4306 0 : break;
4307 0 : default:
4308 0 : return false;
4309 : }
4310 :
4311 : //: Means: an editing operation triggered by a keystroke
4312 0 : startEdit(TranslatableString("undoableAction", "Keystroke edit"));
4313 0 : nudgeAnchors(direction);
4314 0 : apply();
4315 :
4316 0 : return true;
4317 : }
4318 :
4319 0 : bool NotationInteraction::doTextEdit(QKeyEvent* event, TextBase* tb)
4320 : {
4321 0 : IF_ASSERT_FAILED(event && tb) {
4322 0 : return false;
4323 : }
4324 :
4325 : //: Means: an editing operation triggered by a keystroke
4326 0 : startEdit(TranslatableString("undoableAction", "Keystroke edit"));
4327 :
4328 0 : if (!tb->edit(m_editData)) {
4329 0 : rollback();
4330 0 : return false;
4331 : }
4332 :
4333 0 : apply();
4334 :
4335 : // Replace newly added straight quotes with curly ones in a separate undo action...
4336 0 : const bool isSingleQuoteInput = event->text() == u"\'";
4337 0 : const bool isDoubleQuoteInput = event->text() == u"\"";
4338 0 : if (!isSingleQuoteInput && !isDoubleQuoteInput) {
4339 0 : return true;
4340 : }
4341 :
4342 0 : TextCursor* cursor = tb->cursor();
4343 :
4344 0 : bool useCloseQuote = false; // Use close if there's a non-space before the newly inputted quote
4345 :
4346 0 : const int row = static_cast<int>(cursor->row());
4347 0 : const int col = static_cast<int>(cursor->column());
4348 0 : if (col > 1) {
4349 0 : const String prev = cursor->extractText(row, col - 2, row, col - 1);
4350 0 : useCloseQuote = !prev.isEmpty() && !prev.front().isSpace();
4351 0 : }
4352 :
4353 : //: Means: an editing operation triggered by a keystroke
4354 0 : startEdit(TranslatableString("undoableAction", "Keystroke edit"));
4355 :
4356 0 : cursor->movePosition(TextCursor::MoveOperation::Left);
4357 0 : score()->undo(new RemoveText(cursor, event->text()));
4358 :
4359 : //: Single open quotation mark
4360 0 : const String singleOpenQuote = muse::mtrc("notation", u"‘");
4361 : //: Single close quotation mark
4362 0 : const String singleCloseQuote = muse::mtrc("notation", u"’");
4363 : //: Double open quotation mark
4364 0 : const String doubleOpenQuote = muse::mtrc("notation", u"“");
4365 : //: Double close quotation mark
4366 0 : const String doubleCloseQuote = muse::mtrc("notation", u"”");
4367 :
4368 : const String replacement = isSingleQuoteInput
4369 : ? (useCloseQuote ? singleCloseQuote : singleOpenQuote)
4370 0 : : (useCloseQuote ? doubleCloseQuote : doubleOpenQuote);
4371 :
4372 0 : tb->insertText(replacement);
4373 0 : apply();
4374 :
4375 0 : return true;
4376 0 : }
4377 :
4378 0 : void NotationInteraction::endEditText()
4379 : {
4380 0 : if (!isTextEditingStarted()) {
4381 0 : return;
4382 : }
4383 :
4384 0 : stopTextCursorBlinkTimer();
4385 :
4386 0 : TextBase* editedElement = toTextBase(m_editData.element);
4387 0 : doEndEditElement();
4388 :
4389 0 : m_isEditingElementChanged.notify();
4390 0 : notifyAboutTextEditingEnded(editedElement);
4391 :
4392 0 : notifyAboutTextEditingChanged();
4393 0 : m_selection->notifyAboutSelectionChangedIfNeed();
4394 : }
4395 :
4396 0 : void NotationInteraction::blinkTextCursor()
4397 : {
4398 0 : if (!isTextEditingStarted()) {
4399 0 : stopTextCursorBlinkTimer();
4400 0 : return;
4401 : }
4402 :
4403 0 : const TextBase* editedElement = editedText();
4404 0 : IF_ASSERT_FAILED(editedElement) {
4405 0 : return;
4406 : }
4407 0 : TextCursor* cursor = editedElement->cursor();
4408 0 : IF_ASSERT_FAILED(cursor) {
4409 0 : return;
4410 : }
4411 0 : cursor->toggleVisible();
4412 :
4413 0 : muse::RectF cursorCanvasRect = cursor->cursorCanvasRect();
4414 0 : if (cursorCanvasRect.isValid()) {
4415 0 : notifyAboutNotationChanged(cursorCanvasRect);
4416 : }
4417 : }
4418 :
4419 0 : void NotationInteraction::startTextCursorBlinkTimer()
4420 : {
4421 0 : const int cursorFlashTime = QApplication::cursorFlashTime() / 2;
4422 0 : if (cursorFlashTime > 0) {
4423 0 : m_textCursorBlinkTimer.start(cursorFlashTime);
4424 : } else {
4425 : // text cursor flashing is disabled
4426 0 : stopTextCursorBlinkTimer();
4427 : }
4428 0 : }
4429 :
4430 0 : void NotationInteraction::stopTextCursorBlinkTimer()
4431 : {
4432 0 : if (m_textCursorBlinkTimer.isActive()) {
4433 0 : m_textCursorBlinkTimer.stop();
4434 : }
4435 0 : }
4436 :
4437 0 : void NotationInteraction::onTextEditingChanged()
4438 : {
4439 0 : updateTextCursorVisibility();
4440 0 : }
4441 :
4442 0 : void NotationInteraction::updateTextCursorVisibility()
4443 : {
4444 0 : if (!isTextEditingStarted()) {
4445 0 : return;
4446 : }
4447 :
4448 0 : const TextBase* editedElement = editedText();
4449 0 : IF_ASSERT_FAILED(editedElement) {
4450 0 : return;
4451 : }
4452 0 : TextCursor* cursor = editedElement->cursor();
4453 0 : IF_ASSERT_FAILED(cursor) {
4454 0 : return;
4455 : }
4456 :
4457 : // Whenever the cursor moves, we update its visibility.
4458 : // If it has to be visible, we display it immediately
4459 : // regardless of the blinking, and restart the blinking.
4460 0 : bool showCursor = !cursor->hasSelection();
4461 0 : cursor->setVisible(showCursor);
4462 0 : if (showCursor) {
4463 0 : startTextCursorBlinkTimer();
4464 : } else {
4465 0 : stopTextCursorBlinkTimer();
4466 : }
4467 : }
4468 :
4469 0 : void NotationInteraction::changeTextCursorPosition(const PointF& newCursorPos)
4470 : {
4471 0 : IF_ASSERT_FAILED(isTextEditingStarted() && m_editData.element) {
4472 0 : return;
4473 : }
4474 :
4475 0 : m_editData.startMove = bindCursorPosToText(newCursorPos, m_editData.element);
4476 :
4477 0 : mu::engraving::TextBase* textEl = mu::engraving::toTextBase(m_editData.element);
4478 :
4479 0 : textEl->mousePress(m_editData);
4480 0 : if (m_editData.buttons == mu::engraving::MiddleButton) {
4481 0 : QString txt = QGuiApplication::clipboard()->text();
4482 0 : textEl->paste(txt);
4483 0 : }
4484 :
4485 0 : notifyAboutTextEditingChanged();
4486 : }
4487 :
4488 0 : void NotationInteraction::selectText(mu::engraving::SelectTextType type)
4489 : {
4490 0 : if (!isTextEditingStarted()) {
4491 0 : return;
4492 : }
4493 :
4494 0 : mu::engraving::TextBase* text = mu::engraving::toTextBase(m_editData.element);
4495 0 : text->select(type);
4496 0 : text->endHexState();
4497 0 : text->setPrimed(false);
4498 :
4499 0 : notifyAboutTextEditingChanged();
4500 : }
4501 :
4502 0 : void NotationInteraction::selectAllText()
4503 : {
4504 0 : if (!isTextEditingStarted()) {
4505 0 : return;
4506 : }
4507 :
4508 0 : mu::engraving::TextBase* text = mu::engraving::toTextBase(m_editData.element);
4509 0 : text->selectAll();
4510 : }
4511 :
4512 0 : const TextBase* NotationInteraction::editedText() const
4513 : {
4514 0 : return mu::engraving::toTextBase(m_editData.element);
4515 : }
4516 :
4517 0 : void NotationInteraction::undo()
4518 : {
4519 0 : m_undoStack->undo(&m_editData);
4520 0 : }
4521 :
4522 0 : void NotationInteraction::redo()
4523 : {
4524 0 : m_undoStack->redo(&m_editData);
4525 0 : }
4526 :
4527 0 : void NotationInteraction::undoRedoToIndex(size_t idx)
4528 : {
4529 0 : endEditElement();
4530 0 : m_undoStack->undoRedoToIndex(idx, &m_editData);
4531 0 : }
4532 :
4533 0 : muse::async::Notification NotationInteraction::textEditingStarted() const
4534 : {
4535 0 : return m_textEditingStarted;
4536 : }
4537 :
4538 0 : muse::async::Notification NotationInteraction::textEditingChanged() const
4539 : {
4540 0 : return m_textEditingChanged;
4541 : }
4542 :
4543 0 : muse::async::Channel<TextBase*> NotationInteraction::textEditingEnded() const
4544 : {
4545 0 : return m_textEditingEnded;
4546 : }
4547 :
4548 0 : bool NotationInteraction::isGripEditStarted() const
4549 : {
4550 0 : return m_editData.element && m_editData.curGrip != mu::engraving::Grip::NO_GRIP;
4551 : }
4552 :
4553 0 : bool NotationInteraction::isStartEndGripSelected() const
4554 : {
4555 0 : return m_editData.element && (m_editData.curGrip == mu::engraving::Grip::START || m_editData.curGrip == mu::engraving::Grip::END);
4556 : }
4557 :
4558 0 : static int findGrip(const std::vector<muse::RectF>& grips, const muse::PointF& canvasPos)
4559 : {
4560 0 : if (grips.empty()) {
4561 0 : return -1;
4562 : }
4563 0 : qreal align = grips[0].width() / 2;
4564 0 : for (size_t i = 0; i < grips.size(); ++i) {
4565 0 : if (grips[i].adjusted(-align, -align, align, align).contains(canvasPos)) {
4566 0 : return static_cast<int>(i);
4567 : }
4568 : }
4569 0 : return -1;
4570 : }
4571 :
4572 0 : bool NotationInteraction::isHitGrip(const PointF& pos) const
4573 : {
4574 0 : return selection()->element() && findGrip(m_editData.grip, pos) != -1;
4575 : }
4576 :
4577 0 : void NotationInteraction::startEditGrip(const PointF& pos)
4578 : {
4579 0 : int grip = findGrip(m_editData.grip, pos);
4580 0 : if (grip == -1) {
4581 0 : return;
4582 : }
4583 0 : startEditGrip(selection()->element(), mu::engraving::Grip(grip));
4584 : }
4585 :
4586 0 : void NotationInteraction::startEditGrip(EngravingItem* element, mu::engraving::Grip grip)
4587 : {
4588 0 : if (m_editData.element == element && m_editData.curGrip == grip) {
4589 0 : return;
4590 : }
4591 :
4592 0 : m_editData.element = element;
4593 0 : m_editData.curGrip = grip;
4594 :
4595 0 : updateGripAnchorLines();
4596 0 : m_editData.element->startEdit(m_editData);
4597 :
4598 0 : notifyAboutNotationChanged();
4599 : }
4600 :
4601 0 : void NotationInteraction::endEditGrip()
4602 : {
4603 0 : if (m_editData.curGrip == Grip::NO_GRIP) {
4604 0 : return;
4605 : }
4606 :
4607 0 : m_editData.curGrip = Grip::NO_GRIP;
4608 0 : notifyAboutNotationChanged();
4609 : }
4610 :
4611 0 : void NotationInteraction::updateGripAnchorLines()
4612 : {
4613 0 : if (!m_editData.element) {
4614 0 : return;
4615 : }
4616 :
4617 0 : std::vector<LineF> lines;
4618 0 : mu::engraving::Grip anchorLinesGrip = m_editData.curGrip == mu::engraving::Grip::NO_GRIP
4619 0 : ? m_editData.element->defaultGrip() : m_editData.curGrip;
4620 0 : std::vector<LineF> anchorLines = m_editData.element->gripAnchorLines(anchorLinesGrip);
4621 :
4622 0 : if (!anchorLines.empty()) {
4623 0 : for (LineF& line : anchorLines) {
4624 0 : if (line.p1() != line.p2()) {
4625 0 : lines.push_back(line);
4626 : }
4627 : }
4628 : }
4629 :
4630 0 : setAnchorLines(lines);
4631 0 : }
4632 :
4633 0 : void NotationInteraction::updateDragAnchorLines()
4634 : {
4635 0 : std::vector<LineF> anchorLines;
4636 0 : for (const EngravingItem* e : selection()->elements()) {
4637 0 : std::vector<LineF> elAnchorLines = e->dragAnchorLines();
4638 0 : if (!elAnchorLines.empty()) {
4639 0 : for (LineF& l : elAnchorLines) {
4640 0 : anchorLines.push_back(l);
4641 : }
4642 : }
4643 0 : }
4644 :
4645 0 : setAnchorLines(anchorLines);
4646 0 : }
4647 :
4648 0 : bool NotationInteraction::isEditingElement() const
4649 : {
4650 0 : return m_editData.element != nullptr;
4651 : }
4652 :
4653 0 : void NotationInteraction::startEditElement(EngravingItem* element)
4654 : {
4655 0 : if (!element || !element->isEditable()) {
4656 0 : return;
4657 : }
4658 :
4659 0 : if (isEditingElement()) {
4660 0 : return;
4661 : }
4662 :
4663 0 : if (element->isTextBase()) {
4664 0 : startEditText(element);
4665 0 : } else if (element->hasGrips()) {
4666 0 : startEditGrip(element, element->defaultGrip());
4667 : } else {
4668 0 : element->startEdit(m_editData);
4669 0 : m_editData.element = element;
4670 : }
4671 :
4672 0 : m_isEditingElementChanged.notify();
4673 : }
4674 :
4675 0 : void NotationInteraction::changeEditElement(EngravingItem* newElement)
4676 : {
4677 0 : IF_ASSERT_FAILED(newElement) {
4678 0 : return;
4679 : }
4680 :
4681 0 : if (m_editData.element == newElement) {
4682 0 : return;
4683 : }
4684 :
4685 0 : mu::engraving::Grip currentGrip = m_editData.curGrip;
4686 0 : bool gripEditStarted = isGripEditStarted();
4687 :
4688 0 : doEndEditElement();
4689 :
4690 0 : if (gripEditStarted) {
4691 0 : startEditGrip(newElement, currentGrip);
4692 : } else {
4693 0 : startEditElement(newElement);
4694 : }
4695 : }
4696 :
4697 0 : bool NotationInteraction::isEditAllowed(QKeyEvent* event)
4698 : {
4699 0 : if (!m_editData.element) {
4700 0 : return false;
4701 : }
4702 :
4703 0 : mu::engraving::EditData editData = m_editData;
4704 0 : editData.modifiers = keyboardModifier(event->modifiers());
4705 0 : editData.key = event->key();
4706 0 : editData.s = event->text();
4707 :
4708 0 : if (editData.element->isEditAllowed(editData)) {
4709 0 : return true;
4710 : }
4711 :
4712 0 : if (event->modifiers() & Qt::KeyboardModifier::AltModifier) {
4713 0 : return false;
4714 : }
4715 :
4716 0 : if (editData.element->isTextBase()) {
4717 0 : return false;
4718 : }
4719 :
4720 : static QSet<int> navigationKeys = {
4721 : Qt::Key_Left,
4722 : Qt::Key_Right,
4723 : Qt::Key_Up,
4724 : Qt::Key_Down
4725 0 : };
4726 :
4727 0 : if (editData.element->hasGrips()) {
4728 0 : navigationKeys += { Qt::Key_Tab, Qt::Key_Backtab };
4729 : }
4730 :
4731 0 : return navigationKeys.contains(event->key());
4732 0 : }
4733 :
4734 0 : void NotationInteraction::editElement(QKeyEvent* event)
4735 : {
4736 : #if 0
4737 : static int index = 0;
4738 : LOGDA() << "[" << ++index << "] " << QKeySequence(event->keyCombination()).toString();
4739 : #endif
4740 :
4741 0 : if (!m_editData.element) {
4742 0 : return;
4743 : }
4744 :
4745 0 : m_editData.modifiers = keyboardModifier(event->modifiers());
4746 :
4747 0 : if (isDragStarted()) {
4748 0 : return; // ignore all key strokes while dragging
4749 : }
4750 :
4751 0 : m_editData.key = event->key();
4752 0 : m_editData.s = event->text();
4753 :
4754 : // Brackets get deleted during layout with their system, so the best we can do to maintain
4755 : // the bracket selected is to store their indices and use them to find the new ones
4756 0 : bool isBracket = m_editData.element->isBracket();
4757 0 : size_t bracketIndex = muse::nidx;
4758 0 : size_t systemIndex = muse::nidx;
4759 :
4760 0 : if (isBracket) {
4761 0 : const Bracket* bracket = toBracket(m_editData.element);
4762 0 : System* system = bracket->system();
4763 :
4764 0 : if (system) {
4765 0 : bracketIndex = muse::indexOf(system->brackets(), bracket);
4766 0 : systemIndex = muse::indexOf(score()->systems(), system);
4767 : }
4768 0 : } else if (m_editData.element->isHarmony()) {
4769 0 : if (isTextEditingStarted() && (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)) {
4770 0 : endEditText();
4771 0 : return;
4772 : }
4773 : }
4774 :
4775 0 : if (needStartEditGrip(event)) {
4776 0 : m_editData.curGrip = m_editData.element->defaultGrip();
4777 : }
4778 :
4779 0 : if (handleKeyPress(event)) {
4780 0 : if (isBracket && bracketIndex != muse::nidx && systemIndex != muse::nidx) {
4781 : // Try to restore selected bracket
4782 0 : System* system = systemIndex < score()->systems().size() ? score()->systems().at(systemIndex) : nullptr;
4783 0 : EngravingItem* bracket = system && bracketIndex < system->brackets().size() ? system->brackets().at(bracketIndex) : nullptr;
4784 0 : if (bracket) {
4785 0 : m_editData.element = bracket;
4786 0 : select({ bracket }, SelectType::SINGLE);
4787 : }
4788 : }
4789 :
4790 0 : if (isGripEditStarted()) {
4791 0 : updateGripAnchorLines();
4792 : }
4793 :
4794 0 : event->accept();
4795 : }
4796 :
4797 0 : if (isTextEditingStarted()) {
4798 0 : notifyAboutTextEditingChanged();
4799 : }
4800 : }
4801 :
4802 0 : void NotationInteraction::endEditElement()
4803 : {
4804 0 : if (!m_editData.element) {
4805 0 : return;
4806 : }
4807 :
4808 0 : if (isTextEditingStarted()) {
4809 0 : endEditText();
4810 0 : return;
4811 : }
4812 :
4813 0 : if (isDragStarted()) {
4814 0 : doEndDrag();
4815 0 : rollback();
4816 : }
4817 :
4818 0 : doEndEditElement();
4819 0 : resetAnchorLines();
4820 :
4821 0 : m_isEditingElementChanged.notify();
4822 0 : notifyAboutNotationChanged();
4823 : }
4824 :
4825 0 : muse::async::Notification NotationInteraction::isEditingElementChanged() const
4826 : {
4827 0 : return m_isEditingElementChanged;
4828 : }
4829 :
4830 0 : void NotationInteraction::updateTimeTickAnchors(QKeyEvent* event)
4831 : {
4832 0 : EngravingItem* selectedElement = m_selection->element();
4833 0 : if (selectedElement && selectedElement->allowTimeAnchor() && event->type() == QKeyEvent::Type::KeyPress && !isTextEditingStarted()) {
4834 0 : EditTimeTickAnchors::updateAnchors(selectedElement);
4835 0 : updateDragAnchorLines();
4836 0 : score()->update();
4837 : } else {
4838 0 : score()->hideAnchors();
4839 0 : resetAnchorLines();
4840 : }
4841 :
4842 0 : notifyAboutNotationChanged();
4843 0 : }
4844 :
4845 0 : void NotationInteraction::moveElementAnchors(QKeyEvent* event)
4846 : {
4847 0 : EngravingItem* element = selection()->element();
4848 0 : IF_ASSERT_FAILED(element) {
4849 0 : return;
4850 : }
4851 :
4852 0 : startEdit(TranslatableString("undoableAction", "Move element anchors"));
4853 :
4854 0 : MoveElementAnchors::moveElementAnchors(element, KeyboardKey(event->key()), keyboardModifier(event->modifiers()));
4855 :
4856 0 : apply();
4857 :
4858 0 : updateDragAnchorLines();
4859 : }
4860 :
4861 0 : void NotationInteraction::doEndEditElement()
4862 : {
4863 0 : if (m_editData.element) {
4864 0 : m_editData.element->endEdit(m_editData);
4865 : }
4866 0 : m_editData.clear();
4867 0 : }
4868 :
4869 0 : void NotationInteraction::onElementDestroyed(EngravingItem* element)
4870 : {
4871 0 : if (m_editData.element == element) {
4872 0 : m_editData.element = nullptr;
4873 : }
4874 :
4875 0 : if (m_hitElementContext.element == element) {
4876 0 : m_hitElementContext.element = nullptr;
4877 0 : m_hitElementContext.staff = nullptr;
4878 : }
4879 0 : }
4880 :
4881 0 : void NotationInteraction::splitSelectedMeasure()
4882 : {
4883 0 : EngravingItem* selectedElement = m_selection->element();
4884 0 : if (!selectedElement) {
4885 0 : return;
4886 : }
4887 :
4888 0 : if (!selectedElement->isNote() && !selectedElement->isRest()) {
4889 0 : return;
4890 : }
4891 :
4892 0 : if (selectedElement->isNote()) {
4893 0 : selectedElement = toNote(selectedElement)->chord();
4894 : }
4895 :
4896 0 : ChordRest* chordRest = toChordRest(selectedElement);
4897 :
4898 0 : transaction(TranslatableString("undoableAction", "Split measure"), [&](engraving::Transaction& tx) {
4899 0 : SplitJoinMeasure::splitMeasure(tx, score()->masterScore(), chordRest->tick());
4900 0 : });
4901 :
4902 0 : checkAndShowError();
4903 : }
4904 :
4905 0 : void NotationInteraction::joinSelectedMeasures()
4906 : {
4907 0 : if (!m_selection->isRange()) {
4908 0 : return;
4909 : }
4910 :
4911 0 : const INotationSelectionRange::MeasureBaseRange measureBaseRange = m_selection->range()->measureBaseRange();
4912 0 : const MeasureBase* startMeasureBase = measureBaseRange.startMeasureBase;
4913 0 : const MeasureBase* endMeasureBase = measureBaseRange.endMeasureBase;
4914 0 : if (!startMeasureBase || !endMeasureBase) {
4915 0 : return;
4916 : }
4917 :
4918 0 : const Measure* startMeasure = startMeasureBase->isMeasure() ? toMeasure(startMeasureBase) : startMeasureBase->nextMeasure();
4919 0 : const Measure* endMeasure = endMeasureBase->isMeasure() ? toMeasure(endMeasureBase) : endMeasureBase->prevMeasure();
4920 0 : if (!startMeasure || !endMeasure || endMeasure->tick() < startMeasure->tick()) {
4921 0 : return;
4922 : }
4923 :
4924 0 : transaction(TranslatableString("undoableAction", "Join measures"), [&](engraving::Transaction& tx) {
4925 0 : SplitJoinMeasure::joinMeasures(tx, score()->masterScore(), startMeasure->tick(), endMeasure->tick());
4926 0 : });
4927 :
4928 0 : checkAndShowError();
4929 : }
4930 :
4931 0 : void NotationInteraction::addBoxes(BoxType boxType, int count, AddBoxesTarget target)
4932 : {
4933 0 : int beforeBoxIndex = -1;
4934 0 : bool moveSignaturesClefs = (target != AddBoxesTarget::AfterSelection);
4935 0 : const EngravingItem* selectedItem = nullptr;
4936 0 : const MeasureBase* selectedItemMeasure = nullptr;
4937 :
4938 0 : switch (target) {
4939 0 : case AddBoxesTarget::AfterSelection:
4940 : case AddBoxesTarget::BeforeSelection: {
4941 0 : if (selection()->isNone()) {
4942 0 : MScore::setError(MsError::NO_MEASURE_SELECTED);
4943 0 : checkAndShowError();
4944 0 : return;
4945 : }
4946 :
4947 0 : if (selection()->isRange()) {
4948 0 : INotationSelectionRange::MeasureBaseRange range = selection()->range()->measureBaseRange();
4949 :
4950 0 : const int startMeasureIndex = range.startMeasureBase ? range.startMeasureBase->index() : 0;
4951 0 : const int endMeasureIndex = range.endMeasureBase ? range.endMeasureBase->index() + 1 : 0;
4952 :
4953 0 : beforeBoxIndex = target == AddBoxesTarget::BeforeSelection
4954 0 : ? startMeasureIndex
4955 : : endMeasureIndex;
4956 0 : break;
4957 : }
4958 :
4959 0 : const std::vector<EngravingItem*>& elements = selection()->elements();
4960 0 : IF_ASSERT_FAILED(!elements.empty()) {
4961 : // This would contradict the fact that selection()->isNone() == false at this point
4962 0 : MScore::setError(MsError::NO_MEASURE_SELECTED);
4963 0 : checkAndShowError();
4964 0 : return;
4965 : }
4966 :
4967 0 : for (const EngravingItem* item : elements) {
4968 0 : const MeasureBase* itemMeasure = item->findMeasureBase();
4969 0 : if (!itemMeasure) {
4970 0 : continue;
4971 : }
4972 :
4973 0 : int itemMeasureIndex = itemMeasure->index();
4974 0 : if (itemMeasureIndex < 0) {
4975 0 : continue;
4976 : }
4977 :
4978 0 : if (target == AddBoxesTarget::BeforeSelection) {
4979 0 : if (beforeBoxIndex < 0 || itemMeasureIndex < beforeBoxIndex) {
4980 0 : beforeBoxIndex = itemMeasureIndex;
4981 0 : selectedItem = item;
4982 0 : selectedItemMeasure = itemMeasure;
4983 : }
4984 : } else {
4985 0 : if (itemMeasureIndex + 1 > beforeBoxIndex) {
4986 0 : beforeBoxIndex = itemMeasureIndex + 1;
4987 0 : selectedItem = item;
4988 0 : selectedItemMeasure = itemMeasure;
4989 : }
4990 : }
4991 : }
4992 :
4993 0 : const bool selectedIsValid = selectedItem && selectedItemMeasure;
4994 0 : const ElementType selectedItemType = selectedIsValid ? selectedItem->type() : ElementType::INVALID;
4995 :
4996 : // special cases for "between measures elements"
4997 0 : switch (selectedItemType) {
4998 0 : case ElementType::CLEF:
4999 : case ElementType::BAR_LINE:
5000 : case ElementType::TIMESIG:
5001 : case ElementType::KEYSIG: {
5002 0 : const Fraction itemTick = selectedItem->tick();
5003 0 : const Fraction measureTick = selectedItemMeasure->tick();
5004 0 : const Fraction measureLastTick = measureTick + selectedItemMeasure->ticks();
5005 :
5006 0 : if (itemTick == measureTick) {
5007 0 : if (target == AddBoxesTarget::AfterSelection) {
5008 0 : beforeBoxIndex -= 1;
5009 : }
5010 0 : moveSignaturesClefs = (target == AddBoxesTarget::AfterSelection);
5011 0 : } else if (itemTick == measureLastTick) {
5012 0 : if (target == AddBoxesTarget::BeforeSelection) {
5013 0 : beforeBoxIndex += 1;
5014 : }
5015 0 : moveSignaturesClefs = (target == AddBoxesTarget::AfterSelection);
5016 : }
5017 : }
5018 0 : default: break;
5019 : }
5020 :
5021 0 : if (beforeBoxIndex < 0) {
5022 0 : MScore::setError(MsError::NO_MEASURE_SELECTED);
5023 0 : checkAndShowError();
5024 0 : return;
5025 : }
5026 0 : } break;
5027 0 : case AddBoxesTarget::AtStartOfScore: {
5028 0 : Measure* firstMeasure = score()->firstMeasure();
5029 0 : beforeBoxIndex = firstMeasure ? firstMeasure->index() : -1;
5030 0 : } break;
5031 0 : case AddBoxesTarget::AtEndOfScore:
5032 0 : beforeBoxIndex = -1;
5033 0 : break;
5034 : }
5035 :
5036 0 : addBoxes(boxType, count, beforeBoxIndex, moveSignaturesClefs);
5037 : }
5038 :
5039 0 : void NotationInteraction::addBoxes(BoxType boxType, int count, int beforeBoxIndex, bool moveSignaturesClef)
5040 : {
5041 0 : if (count < 1) {
5042 0 : return;
5043 : }
5044 :
5045 0 : auto boxTypeToElementType = [](BoxType boxType) {
5046 0 : switch (boxType) {
5047 0 : case BoxType::Horizontal: return mu::engraving::ElementType::HBOX;
5048 0 : case BoxType::Vertical: return mu::engraving::ElementType::VBOX;
5049 0 : case BoxType::Text: return mu::engraving::ElementType::TBOX;
5050 0 : case BoxType::Fret: return mu::engraving::ElementType::FBOX;
5051 0 : case BoxType::Measure: return mu::engraving::ElementType::MEASURE;
5052 0 : case BoxType::Unknown: return mu::engraving::ElementType::INVALID;
5053 : }
5054 :
5055 0 : return ElementType::INVALID;
5056 : };
5057 :
5058 0 : mu::engraving::ElementType elementType = boxTypeToElementType(boxType);
5059 0 : if (elementType == mu::engraving::ElementType::INVALID) {
5060 0 : return;
5061 : }
5062 :
5063 0 : auto boxTypeDescription = [count](BoxType boxType) -> TranslatableString {
5064 0 : switch (boxType) {
5065 0 : case BoxType::Horizontal: return TranslatableString("undoableAction", "Add horizontal frame");
5066 0 : case BoxType::Vertical: return TranslatableString("undoableAction", "Add vertical frame");
5067 0 : case BoxType::Text: return TranslatableString("undoableAction", "Add text frame");
5068 0 : case BoxType::Fret: return TranslatableString("undoableAction", "Add fretboard diagram legend");
5069 0 : case BoxType::Measure: return TranslatableString("undoableAction", "Add %Ln measure(s)", nullptr, count);
5070 0 : case BoxType::Unknown: break;
5071 : }
5072 :
5073 0 : return {};
5074 0 : };
5075 :
5076 0 : startEdit(boxTypeDescription(boxType));
5077 :
5078 0 : mu::engraving::MeasureBase* beforeBox = beforeBoxIndex >= 0 ? score()->measure(beforeBoxIndex) : nullptr;
5079 :
5080 0 : mu::engraving::Score::InsertMeasureOptions options;
5081 0 : options.createMeasureRests = false;
5082 0 : options.moveSignaturesClef = moveSignaturesClef;
5083 0 : options.needDeselectAll = false;
5084 0 : options.cloneBoxToAllParts = boxType != BoxType::Fret;
5085 :
5086 0 : for (int i = 0; i < count; ++i) {
5087 0 : score()->insertMeasure(elementType, beforeBox, options);
5088 : }
5089 :
5090 0 : apply();
5091 :
5092 0 : int indexOfFirstAddedMeasure = beforeBoxIndex >= 0 ? beforeBoxIndex : score()->measures()->size() - count;
5093 0 : MeasureBase* firstAddedMeasure = score()->measure(indexOfFirstAddedMeasure);
5094 0 : m_selection->select({ firstAddedMeasure }, SelectType::REPLACE);
5095 0 : showItem(firstAddedMeasure);
5096 :
5097 : // For other box types, it makes little sense to select them all
5098 0 : if (boxType == BoxType::Measure) {
5099 0 : m_selection->select({ score()->measure(indexOfFirstAddedMeasure + count - 1) }, SelectType::RANGE);
5100 : }
5101 :
5102 0 : m_selection->notifyAboutSelectionChangedIfNeed();
5103 : }
5104 :
5105 0 : void NotationInteraction::copySelection()
5106 : {
5107 0 : if (!selection()->canCopy()) {
5108 0 : checkAndShowError();
5109 0 : return;
5110 : }
5111 :
5112 0 : if (isTextEditingStarted()) {
5113 0 : m_editData.element->editCopy(m_editData);
5114 0 : mu::engraving::TextEditData* ted = static_cast<mu::engraving::TextEditData*>(m_editData.getData(m_editData.element).get());
5115 0 : if (!ted->selectedText.isEmpty()) {
5116 0 : QMimeData* mimeData = new QMimeData();
5117 0 : mimeData->setData(TextEditData::mimeRichTextFormat, ted->selectedText.toQString().toUtf8());
5118 0 : mimeData->setText(ted->selectedPlainText);
5119 0 : QGuiApplication::clipboard()->setMimeData(mimeData);
5120 : }
5121 : } else {
5122 0 : QMimeData* mimeData = selection()->qMimeData();
5123 0 : if (!mimeData) {
5124 0 : return;
5125 : }
5126 0 : QGuiApplication::clipboard()->setMimeData(mimeData);
5127 : }
5128 : }
5129 :
5130 0 : void NotationInteraction::repeatSelection()
5131 : {
5132 0 : const Selection& selection = score()->selection();
5133 0 : if (score()->noteEntryMode() && selection.isSingle()) {
5134 : // Single selections require special handling in note entry mode...
5135 0 : EngravingItem* el = selection.element();
5136 0 : if (!el) {
5137 0 : return;
5138 : }
5139 0 : Chord* c = nullptr;
5140 0 : if (el->isNote()) {
5141 0 : c = toNote(el)->chord();
5142 0 : } else if (el->isRest()) {
5143 0 : Segment* prevSegment = toRest(el)->segment()->prev1WithElemsOnTrack(el->track());
5144 :
5145 : // Looking for the previous Chord
5146 0 : while (prevSegment) {
5147 0 : if (prevSegment->element(el->track())->isChord()) {
5148 0 : c = toChord(prevSegment->element(el->track()));
5149 0 : break;
5150 : }
5151 0 : prevSegment = prevSegment->prev1WithElemsOnTrack(el->track());
5152 : }
5153 : }
5154 0 : if (c) {
5155 0 : transaction(TranslatableString("undoableAction", "Repeat selection"), [&](engraving::Transaction& tx) {
5156 0 : for (Note* note : c->notes()) {
5157 0 : NoteVal nval = note->noteVal();
5158 0 : NoteInput::addPitch(tx, score(), nval, note != c->notes()[0]);
5159 : }
5160 0 : });
5161 : }
5162 0 : return;
5163 : }
5164 :
5165 : //! NOTE: Ideally we would use our copy-paste logic for this case, but this isn't
5166 : //! fully compatible with list selections right now...
5167 0 : if (selection.isList() && !selection.noteList().empty()) {
5168 0 : const Fraction& firstTick = selection.tickStart();
5169 0 : const Fraction& lastTick = selection.tickEnd();
5170 : // Only "single-tick" list selections are currently supported...
5171 0 : if (firstTick != lastTick) {
5172 0 : MScore::setError(MsError::CANNOT_REPEAT_SELECTION);
5173 0 : checkAndShowError();
5174 0 : return;
5175 : }
5176 0 : startEdit(TranslatableString("undoableAction", "Repeat selection"));
5177 0 : if (!Paste::repeatListSelection(score()->transactionManager()->currentOrDummyTransaction(), score())) {
5178 0 : rollback();
5179 0 : MScore::setError(MsError::CANNOT_REPEAT_SELECTION);
5180 0 : return;
5181 : }
5182 0 : apply();
5183 0 : return;
5184 : }
5185 :
5186 : // If a list selection with no notes is a rest, convert to a range selection
5187 0 : if (selection.isList()) {
5188 0 : ChordRest* cr = score()->getSelectedChordRest();
5189 0 : if (!cr) {
5190 0 : MScore::setError(MsError::CANNOT_REPEAT_SELECTION);
5191 0 : checkAndShowError();
5192 0 : return;
5193 : }
5194 0 : score()->select(cr, SelectType::RANGE);
5195 : }
5196 :
5197 : // Use copy-paste logic for range selections...
5198 0 : if (!selection.isRange() || !m_selection->canCopy()) {
5199 0 : MScore::setError(MsError::CANNOT_REPEAT_SELECTION);
5200 0 : checkAndShowError();
5201 0 : return;
5202 : }
5203 :
5204 0 : XmlReader xml(selection.mimeData());
5205 0 : staff_idx_t dStaff = selection.staffStart();
5206 0 : mu::engraving::Segment* endSegment = selection.endSegment();
5207 :
5208 0 : startEdit(TranslatableString("undoableAction", "Repeat selection"));
5209 0 : if (endSegment && endSegment->segmentType() != SegmentType::ChordRest) {
5210 0 : if (!endSegment->next1(SegmentType::ChordRest)) {
5211 0 : score()->appendMeasures(1);
5212 : }
5213 0 : endSegment = endSegment->next1(SegmentType::ChordRest);
5214 : }
5215 0 : if (!endSegment) {
5216 0 : return;
5217 : }
5218 0 : for (track_idx_t track = staff2track(dStaff); track < staff2track(dStaff + 1); ++track) {
5219 0 : EngravingItem* e = endSegment->element(track);
5220 0 : if (!e) {
5221 0 : continue;
5222 : }
5223 :
5224 0 : ChordRest* cr = toChordRest(e);
5225 0 : if (!Paste::pasteStaff(score()->transactionManager()->currentOrDummyTransaction(), score(), xml, cr->segment(), cr->staffIdx())) {
5226 0 : rollback();
5227 0 : checkAndShowError();
5228 0 : return;
5229 : }
5230 0 : apply();
5231 :
5232 0 : showItem(cr);
5233 0 : break;
5234 : }
5235 0 : }
5236 :
5237 0 : void NotationInteraction::copyLyrics()
5238 : {
5239 0 : QString text = score()->extractLyrics();
5240 0 : QGuiApplication::clipboard()->setText(text);
5241 0 : }
5242 :
5243 0 : void NotationInteraction::pasteSelection(const Fraction& scale)
5244 : {
5245 0 : startEdit(TranslatableString("undoableAction", "Paste"));
5246 :
5247 0 : bool succeeded = true;
5248 0 : if (isTextEditingStarted()) {
5249 0 : pasteIntoTextEdit();
5250 : } else {
5251 0 : const QMimeData* mimeData = QGuiApplication::clipboard()->mimeData();
5252 0 : QMimeDataAdapter ma(mimeData);
5253 0 : succeeded = Paste::paste(score()->transactionManager()->currentOrDummyTransaction(), score(), &ma, nullptr, scale);
5254 0 : m_editData.element = nullptr;
5255 0 : }
5256 :
5257 0 : if (succeeded) {
5258 0 : apply();
5259 0 : if (EngravingItem* pastedElement = selection()->element()) {
5260 0 : selectAndStartEditIfNeeded(pastedElement);
5261 : }
5262 : } else {
5263 0 : rollback();
5264 : }
5265 :
5266 0 : checkAndShowError();
5267 0 : }
5268 :
5269 0 : void NotationInteraction::pasteIntoTextEdit()
5270 : {
5271 0 : const QMimeData* mimeData = QGuiApplication::clipboard()->mimeData();
5272 0 : if (mimeData->hasFormat(TextEditData::mimeRichTextFormat)) {
5273 0 : const QString txt = QString::fromUtf8(mimeData->data(TextEditData::mimeRichTextFormat));
5274 0 : toTextBase(m_editData.element)->paste(txt);
5275 0 : notifyAboutTextEditingChanged();
5276 0 : return;
5277 0 : }
5278 :
5279 0 : QString clipboardText = mimeData->text();
5280 0 : QString textForPaste = clipboardText;
5281 0 : if ((!clipboardText.startsWith('<') || !clipboardText.contains('>')) && m_editData.element->isLyrics()) {
5282 0 : textForPaste = extractSyllable(clipboardText);
5283 : }
5284 :
5285 0 : toTextBase(m_editData.element)->paste(textForPaste);
5286 0 : notifyAboutTextEditingChanged();
5287 :
5288 0 : if (textForPaste.isEmpty() || !m_editData.element->isLyrics()) {
5289 0 : return;
5290 : }
5291 :
5292 0 : if (textForPaste.endsWith('-')) {
5293 0 : navigateToNextSyllable();
5294 0 : } else if (textForPaste.endsWith('_')) {
5295 0 : addMelisma();
5296 : } else {
5297 0 : navigateToLyrics(false, false, false);
5298 : }
5299 :
5300 0 : const QString textForNextPaste = clipboardText.remove(0, clipboardText.indexOf(textForPaste) + textForPaste.size());
5301 0 : QGuiApplication::clipboard()->setText(textForNextPaste);
5302 0 : }
5303 :
5304 0 : void NotationInteraction::swapSelection()
5305 : {
5306 0 : if (!selection()->canCopy()) {
5307 0 : return;
5308 : }
5309 :
5310 : // Store the old selection...
5311 0 : mu::engraving::Selection& selection = score()->selection();
5312 0 : QByteArray oldSelection = selection.mimeData().toQByteArray();
5313 :
5314 : // Paste using contents of clipboard...
5315 0 : pasteSelection();
5316 :
5317 : // Save old selection to clipboard...
5318 0 : QMimeData* mimeData = new QMimeData();
5319 0 : mimeData->setData(selection.mimeType(), oldSelection);
5320 0 : QGuiApplication::clipboard()->setMimeData(mimeData);
5321 0 : }
5322 :
5323 0 : void NotationInteraction::deleteSelection()
5324 : {
5325 0 : if (selection()->isNone()) {
5326 0 : return;
5327 : }
5328 :
5329 0 : startEdit(TranslatableString("undoableAction", "Delete"));
5330 :
5331 0 : if (isTextEditingStarted()) {
5332 0 : mu::engraving::TextBase* textBase = toTextBase(m_editData.element);
5333 0 : if (!textBase->deleteSelectedText()) {
5334 0 : m_editData.key = Qt::Key_Backspace;
5335 0 : m_editData.modifiers = {};
5336 0 : if (textBase->edit(m_editData)) {
5337 0 : notifyAboutTextEditingChanged();
5338 : }
5339 : } else {
5340 0 : notifyAboutTextEditingChanged();
5341 : }
5342 : } else {
5343 0 : doEndEditElement();
5344 0 : resetGripEdit();
5345 0 : score()->cmdDeleteSelection();
5346 : }
5347 :
5348 0 : checkAndShowError();
5349 0 : apply();
5350 0 : resetHitElementContext();
5351 : }
5352 :
5353 0 : void NotationInteraction::flipSelection()
5354 : {
5355 0 : if (selection()->isNone()) {
5356 0 : return;
5357 : }
5358 :
5359 0 : transaction(TranslatableString("undoableAction", "Flip direction"), [&](auto& tx) {
5360 0 : Flip::flip(tx, score());
5361 0 : });
5362 :
5363 0 : updateGripAnchorLines();
5364 : }
5365 :
5366 0 : void NotationInteraction::flipSelectionHorizontally()
5367 : {
5368 0 : if (selection()->isNone()) {
5369 0 : return;
5370 : }
5371 :
5372 0 : transaction(TranslatableString("undoableAction", "Flip horizontally"), [&](auto& tx) {
5373 0 : Flip::flipHorizontally(tx, score());
5374 0 : });
5375 : }
5376 :
5377 0 : void NotationInteraction::mirrorNotes()
5378 : {
5379 0 : if (selection()->isNone()) {
5380 0 : return;
5381 : }
5382 :
5383 0 : transaction(TranslatableString("undoableAction", "Mirror notehead"), [&](auto& tx) {
5384 0 : Flip::mirrorNoteHead(tx, score());
5385 0 : });
5386 :
5387 0 : notifyAboutNotationChanged();
5388 : }
5389 :
5390 0 : void NotationInteraction::toggleTieForSelection()
5391 : {
5392 : // Calls `startEdit` internally
5393 0 : Tie* newTie = mu::engraving::EditTie::cmdToggleTie(score());
5394 :
5395 0 : notifyAboutNotationChanged();
5396 0 : m_selection->selectionChanged().notify();
5397 :
5398 0 : if (newTie && newTie->tieJumpPoints() && newTie->tieJumpPoints()->size() > 1) {
5399 0 : selectAndStartEditIfNeeded(newTie);
5400 : }
5401 0 : }
5402 :
5403 0 : void NotationInteraction::addLaissezVibToSelection()
5404 : {
5405 : // Calls `startEdit` internally
5406 0 : mu::engraving::EditTie::cmdToggleLaissezVib(score());
5407 :
5408 0 : notifyAboutNotationChanged();
5409 0 : m_selection->selectionChanged().notify();
5410 0 : }
5411 :
5412 0 : void NotationInteraction::addSlurToSelection()
5413 : {
5414 0 : if (selection()->isNone()) {
5415 0 : return;
5416 : }
5417 :
5418 0 : transaction(TranslatableString("undoableAction", "Add slur"), [&](Transaction& tx) {
5419 0 : doAddSlur(tx);
5420 0 : });
5421 0 : notifyAboutDropChanged();
5422 0 : m_selection->selectionChanged().notify();
5423 : }
5424 :
5425 0 : void NotationInteraction::addHammerOnPullOffToSelection()
5426 : {
5427 0 : if (selection()->isNone()) {
5428 0 : return;
5429 : }
5430 :
5431 0 : HammerOnPullOff* hopo = Factory::createHammerOnPullOff(score()->dummy());
5432 0 : transaction(TranslatableString("undoableAction", "Add slur"), [&](Transaction& tx) {
5433 0 : doAddSlur(tx, hopo);
5434 0 : });
5435 0 : notifyAboutDropChanged();
5436 : }
5437 :
5438 0 : void NotationInteraction::addOttavaToSelection(OttavaType type)
5439 : {
5440 0 : if (selection()->isNone()) {
5441 0 : return;
5442 : }
5443 :
5444 0 : transaction(TranslatableString("undoableAction", "Add ottava"), [&](auto&) {
5445 0 : score()->cmdAddOttava(type);
5446 0 : });
5447 : }
5448 :
5449 0 : void NotationInteraction::addHairpinOnGripDrag(EditData& ed, bool isLeftGrip)
5450 : {
5451 0 : startEdit(TranslatableString("undoableAction", "Add hairpin"));
5452 :
5453 0 : Dynamic* dynamic = toDynamic(ed.element);
5454 :
5455 0 : const PointF pos = m_dragData.ed.pos;
5456 0 : Transaction& tx = score()->transactionManager()->currentOrDummyTransaction();
5457 0 : Hairpin* hairpin = EditHairpin::addHairpinToDynamicOnGripDrag(tx, score(), dynamic, isLeftGrip, pos);
5458 :
5459 0 : if (!hairpin) {
5460 0 : rollback();
5461 0 : return;
5462 : }
5463 :
5464 0 : apply();
5465 :
5466 : // Reset grip offset to zero after drawing the hairpin
5467 0 : dynamic->resetRightDragOffset();
5468 :
5469 0 : IF_ASSERT_FAILED(!hairpin->segmentsEmpty()) {
5470 0 : return;
5471 : }
5472 :
5473 0 : if (isLeftGrip) {
5474 0 : LineSegment* segment = hairpin->frontSegment();
5475 0 : select({ segment });
5476 0 : startEditGrip(segment, Grip::START);
5477 : } else {
5478 0 : LineSegment* segment = hairpin->backSegment();
5479 0 : select({ segment });
5480 0 : startEditGrip(segment, Grip::END);
5481 : }
5482 :
5483 0 : ed.isHairpinDragCreatedFromDynamic = true;
5484 : }
5485 :
5486 0 : void NotationInteraction::addHairpinsToSelection(HairpinType type)
5487 : {
5488 0 : if (selection()->isNone()) {
5489 0 : return;
5490 : }
5491 :
5492 0 : std::vector<mu::engraving::Hairpin*> hairpins;
5493 0 : transaction(TranslatableString("undoableAction", "Add hairpin"), [&](Transaction& tx) {
5494 0 : hairpins = EditHairpin::addHairpins(tx, score(), type);
5495 0 : });
5496 :
5497 0 : if (!noteInput()->isNoteInputMode() && hairpins.size() == 1) {
5498 0 : mu::engraving::LineSegment* segment = hairpins.front()->frontSegment();
5499 0 : select({ segment });
5500 0 : startEditGrip(segment, mu::engraving::Grip::END);
5501 : }
5502 0 : }
5503 :
5504 0 : void NotationInteraction::putRestToSelection()
5505 : {
5506 0 : mu::engraving::InputState& is = score()->inputState();
5507 0 : if (!is.duration().isValid() || is.duration().isZero() || is.duration().isMeasure()) {
5508 0 : is.setDuration(DurationType::V_QUARTER);
5509 : }
5510 :
5511 0 : if (!m_noteInput->isNoteInputMode()) {
5512 0 : m_noteInput->startNoteInput(configuration()->defaultNoteInputMethod());
5513 : }
5514 :
5515 0 : if (is.usingNoteEntryMethod(NoteEntryMethod::BY_DURATION) || is.usingNoteEntryMethod(NoteEntryMethod::RHYTHM)) {
5516 0 : m_noteInput->toggleRest();
5517 0 : } else if (is.usingNoteEntryMethod(NoteEntryMethod::REPITCH)) {
5518 0 : ChordRest* cr = is.cr();
5519 0 : if (cr) {
5520 0 : TDuration duration = cr->durationType();
5521 0 : if (duration.isValid() && !duration.isZero()) {
5522 0 : if (duration.isMeasure()) {
5523 0 : is.moveToNextInputPos();
5524 : } else {
5525 0 : putRest(duration);
5526 : }
5527 : }
5528 : }
5529 : } else {
5530 0 : putRest(is.duration());
5531 : }
5532 0 : }
5533 :
5534 0 : void NotationInteraction::putRest(Duration duration)
5535 : {
5536 0 : if (selection()->isNone()) {
5537 0 : return;
5538 : }
5539 :
5540 : // Calls `startEdit` internally
5541 0 : score()->cmdEnterRest(duration);
5542 :
5543 0 : notifyAboutNotationChanged();
5544 : }
5545 :
5546 0 : void NotationInteraction::addBracketsToSelection(BracketsType type)
5547 : {
5548 0 : if (selection()->isNone()) {
5549 0 : return;
5550 : }
5551 :
5552 0 : switch (type) {
5553 0 : case BracketsType::Brackets:
5554 0 : transaction(TranslatableString("undoableAction", "Add brackets"), [&](auto& tx) {
5555 0 : EditAccidentalBrackets::addBracket(tx, score());
5556 0 : });
5557 0 : break;
5558 0 : case BracketsType::Braces:
5559 0 : transaction(TranslatableString("undoableAction", "Add braces"), [&](auto& tx) {
5560 0 : EditAccidentalBrackets::addBraces(tx, score());
5561 0 : });
5562 0 : break;
5563 0 : case BracketsType::Parentheses:
5564 0 : transaction(TranslatableString("undoableAction", "Add parentheses"), [&](auto& tx) {
5565 0 : EditParentheses::toggleParentheses(tx, score());
5566 0 : });
5567 0 : break;
5568 : }
5569 : }
5570 :
5571 0 : void NotationInteraction::toggleAccidentalForSelection(AccidentalType type)
5572 : {
5573 0 : if (selection()->isNone()) {
5574 0 : return;
5575 : }
5576 :
5577 0 : bool accidentalAlreadyAdded = false;
5578 0 : for (const EngravingItem* item : score()->selection().elements()) {
5579 0 : if (!item->isNote()) {
5580 0 : continue;
5581 : }
5582 :
5583 0 : if (toNote(item)->accidentalType() != type) {
5584 0 : accidentalAlreadyAdded = false;
5585 0 : break;
5586 : }
5587 :
5588 0 : accidentalAlreadyAdded = true;
5589 : }
5590 :
5591 0 : transaction(TranslatableString("undoableAction", "Toggle accidental"), [&](auto&) {
5592 0 : if (accidentalAlreadyAdded) {
5593 0 : mu::engraving::EditNote::changeAccidental(score(), AccidentalType::NONE);
5594 : } else {
5595 0 : mu::engraving::EditNote::changeAccidental(score(), type);
5596 : }
5597 0 : });
5598 : }
5599 :
5600 0 : void NotationInteraction::toggleArticulationForSelection(SymbolId articulationSymbolId)
5601 : {
5602 0 : if (selection()->isNone()) {
5603 0 : return;
5604 : }
5605 :
5606 0 : std::vector<mu::engraving::Note*> notes = score()->selection().noteList();
5607 0 : if (notes.empty()) {
5608 : // no notes, but maybe they have an articulation selected. we should use that chord
5609 0 : EngravingItem* e = score()->selection().element();
5610 0 : if (e && e->isArticulationFamily()) {
5611 0 : Chord* c = toChord(toArticulation(e)->ownershipParent());
5612 0 : if (c) {
5613 0 : notes.insert(notes.begin(), c->notes().begin(), c->notes().end());
5614 : }
5615 : }
5616 : }
5617 :
5618 0 : auto updateMode = notesHaveActiculation(notes, articulationSymbolId)
5619 0 : ? mu::engraving::ArticulationsUpdateMode::Remove : mu::engraving::ArticulationsUpdateMode::Insert;
5620 :
5621 0 : std::set<Chord*> chords;
5622 0 : for (Note* note: notes) {
5623 0 : if (note->isTrillCueNote()) {
5624 0 : return;
5625 : }
5626 0 : Chord* chord = note->chord();
5627 0 : if (chords.find(chord) == chords.end()) {
5628 0 : chords.insert(chord);
5629 : }
5630 : }
5631 :
5632 0 : startEdit(TranslatableString("undoableAction", "Toggle articulation"));
5633 0 : for (Chord* chord: chords) {
5634 0 : chord->updateArticulations({ articulationSymbolId }, updateMode);
5635 : }
5636 0 : apply();
5637 0 : }
5638 :
5639 0 : void NotationInteraction::toggleDotsForSelection(int dots)
5640 : {
5641 0 : IF_ASSERT_FAILED(dots >= 1 && dots <= 4) {
5642 0 : return;
5643 : }
5644 :
5645 0 : if (selection()->isNone()) {
5646 0 : return;
5647 : }
5648 :
5649 0 : transaction(TranslatableString("undoableAction", "Toggle augmentation dots"), [&](auto& tx) {
5650 0 : NoteInput::toggleDots(tx, score(), dots, true /*toggleForSelectionOnly*/);
5651 0 : });
5652 :
5653 0 : notifyAboutNotationChanged();
5654 : }
5655 :
5656 0 : void NotationInteraction::addGraceNotesToSelectedNotes(GraceNoteType type)
5657 : {
5658 0 : if (selection()->isNone()) {
5659 0 : return;
5660 : }
5661 :
5662 0 : int denominator = 1;
5663 :
5664 0 : switch (type) {
5665 0 : case GraceNoteType::GRACE4:
5666 : case GraceNoteType::INVALID:
5667 : case GraceNoteType::NORMAL:
5668 0 : denominator = 1;
5669 0 : break;
5670 0 : case GraceNoteType::ACCIACCATURA:
5671 : case GraceNoteType::APPOGGIATURA:
5672 : case GraceNoteType::GRACE8_AFTER:
5673 0 : denominator = 2;
5674 0 : break;
5675 0 : case GraceNoteType::GRACE16:
5676 : case GraceNoteType::GRACE16_AFTER:
5677 0 : denominator = 4;
5678 0 : break;
5679 0 : case GraceNoteType::GRACE32:
5680 : case GraceNoteType::GRACE32_AFTER:
5681 0 : denominator = 8;
5682 0 : break;
5683 : }
5684 :
5685 0 : startEdit(TranslatableString("undoableAction", "Add grace note"));
5686 0 : score()->cmdAddGrace(type, mu::engraving::Constants::DIVISION / denominator);
5687 0 : apply();
5688 : }
5689 :
5690 0 : bool NotationInteraction::canAddTupletToSelectedChordRests() const
5691 : {
5692 0 : for (ChordRest* chordRest : score()->getSelectedChordRests()) {
5693 0 : if (chordRest->isGrace() || (chordRest->isChord() && toChord(chordRest)->isTrillCueNote())) {
5694 0 : continue;
5695 : }
5696 :
5697 0 : if (chordRest->durationType() < mu::engraving::TDuration(mu::engraving::DurationType::V_512TH)
5698 0 : && chordRest->durationType() != mu::engraving::TDuration(mu::engraving::DurationType::V_MEASURE)) {
5699 0 : return false;
5700 : }
5701 0 : }
5702 :
5703 0 : return true;
5704 : }
5705 :
5706 0 : void NotationInteraction::addTupletToSelectedChordRests(const TupletOptions& options)
5707 : {
5708 0 : if (selection()->isNone()) {
5709 0 : return;
5710 : }
5711 :
5712 0 : if (options.selectedDurationAs == TupletSelectedDuration::SUBDIVISION) {
5713 0 : if (!EditTuplet::checkAddTupletsWithSelectedDurations(score(), options.ratio)) {
5714 0 : checkAndShowError();
5715 0 : return;
5716 : }
5717 0 : } else if (!canAddTupletToSelectedChordRests()) {
5718 0 : MScore::setError(MsError::TUPLET_NOTE_VALUE_TOO_SHORT);
5719 0 : checkAndShowError();
5720 0 : return;
5721 : }
5722 :
5723 0 : transaction(TranslatableString("undoableAction", "Add tuplet"), [&](mu::engraving::Transaction& tx) {
5724 0 : EditTuplet::addTuplets(tx, score(), options.ratio, options.numberType, options.bracketType, options.autoBaseLen,
5725 0 : options.selectedDurationAs);
5726 0 : });
5727 0 : notifyAboutNotationChanged();
5728 :
5729 0 : checkAndShowError();
5730 : }
5731 :
5732 0 : void NotationInteraction::addBeamToSelectedChordRests(BeamMode mode)
5733 : {
5734 0 : if (selection()->isNone()) {
5735 0 : return;
5736 : }
5737 :
5738 0 : transaction(TranslatableString("undoableAction", "Set beam type"), [&](Transaction& tx) {
5739 0 : EditBeam::setBeamMode(tx, score(), mode);
5740 0 : });
5741 0 : notifyAboutNotationChanged();
5742 : }
5743 :
5744 0 : void NotationInteraction::beamSelectedRange()
5745 : {
5746 0 : if (selection()->isNone()) {
5747 0 : return;
5748 : }
5749 :
5750 0 : transaction(TranslatableString("undoableAction", "Beam selected"), [&](Transaction& tx) {
5751 0 : EditBeam::beamSelectedRange(tx, score());
5752 0 : });
5753 0 : notifyAboutNotationChanged();
5754 : }
5755 :
5756 0 : void NotationInteraction::increaseDecreaseDuration(int steps, bool stepByDots)
5757 : {
5758 0 : if (selection()->isNone()) {
5759 0 : return;
5760 : }
5761 :
5762 0 : m_undoStack->transaction(steps > 0 // negative: increase, positive: decrease
5763 0 : ? TranslatableString("undoableAction", "Decrease duration")
5764 : : TranslatableString("undoableAction", "Increase duration"),
5765 0 : [&](Transaction& tx) {
5766 0 : EditDuration::incDecDuration(tx, score(), steps, stepByDots);
5767 0 : });
5768 0 : notifyAboutNotationChanged();
5769 : }
5770 :
5771 0 : void NotationInteraction::increaseDecreaseSelectedDynamicsValues(int delta)
5772 : {
5773 0 : if (selection()->isNone()) {
5774 0 : return;
5775 : }
5776 :
5777 0 : const auto inRange = [](DynamicType type) {
5778 0 : return type >= DynamicType::PPPPP && type <= DynamicType::FFFFF;
5779 : };
5780 :
5781 0 : std::map<Dynamic*, /*newType*/ DynamicType> dynamicsMap;
5782 :
5783 : // Collect valid dynamics before trying anything (avoid unnecessary calls to startEdit etc)...
5784 0 : for (EngravingItem* item : selection()->elements()) {
5785 0 : if (!item->isDynamic()) {
5786 0 : continue;
5787 : }
5788 0 : Dynamic* dynamic = toDynamic(item);
5789 0 : DynamicType newType = static_cast<DynamicType>(static_cast<int>(dynamic->dynamicType()) + delta);
5790 0 : if (inRange(newType)) {
5791 0 : dynamicsMap.emplace(dynamic, newType);
5792 : }
5793 : }
5794 :
5795 0 : if (dynamicsMap.empty()) {
5796 0 : return;
5797 : }
5798 :
5799 0 : startEdit(delta > 0 // positive: increase dynamics, negative: decrease dynamics
5800 0 : ? TranslatableString("undoableAction", "Increase dynamics")
5801 : : TranslatableString("undoableAction", "Decrease dynamics"));
5802 :
5803 0 : for (const auto& [dynamic, newType] : dynamicsMap) {
5804 0 : dynamic->undoChangeProperty(Pid::DYNAMIC_TYPE, newType);
5805 0 : dynamic->undoChangeProperty(Pid::TEXT, Dynamic::dynamicText(newType));
5806 0 : doAutoFlipHairpinsType(dynamic);
5807 : }
5808 :
5809 0 : apply();
5810 0 : }
5811 :
5812 0 : void NotationInteraction::autoFlipHairpinsType(Dynamic* dynamic)
5813 : {
5814 0 : if (!dynamic || dynamic->dynamicType() == DynamicType::OTHER || dynamic->dynamicType() >= DynamicType::FP) {
5815 0 : return;
5816 : }
5817 0 : startEdit(TranslatableString("undoableAction", "Change hairpin type"));
5818 0 : doAutoFlipHairpinsType(dynamic);
5819 0 : apply();
5820 : }
5821 :
5822 0 : void NotationInteraction::doAutoFlipHairpinsType(Dynamic* dynamic)
5823 : {
5824 0 : dynamic->findAdjacentHairpins();
5825 0 : if (Hairpin* leftHp = dynamic->leftHairpin()) {
5826 0 : const Dynamic* startDyn = leftHp->dynamicSnappedBefore();
5827 0 : if (startDyn
5828 0 : && !(startDyn->dynamicType() == DynamicType::OTHER || startDyn->dynamicType() >= DynamicType::FP)
5829 0 : && !leftHp->isLineType()) {
5830 0 : if (int(startDyn->dynamicType()) > int(dynamic->dynamicType())) {
5831 0 : leftHp->undoChangeProperty(Pid::HAIRPIN_TYPE, int(HairpinType::DIM_HAIRPIN));
5832 : } else {
5833 0 : leftHp->undoChangeProperty(Pid::HAIRPIN_TYPE, int(HairpinType::CRESC_HAIRPIN));
5834 : }
5835 : }
5836 : }
5837 0 : if (Hairpin* rightHp = dynamic->rightHairpin()) {
5838 0 : const Dynamic* endDyn = rightHp->dynamicSnappedAfter();
5839 0 : if (endDyn
5840 0 : && !(endDyn->dynamicType() == DynamicType::OTHER || endDyn->dynamicType() >= DynamicType::FP)
5841 0 : && !rightHp->isLineType()) {
5842 0 : if (int(endDyn->dynamicType()) > int(dynamic->dynamicType())) {
5843 0 : rightHp->undoChangeProperty(Pid::HAIRPIN_TYPE, int(HairpinType::CRESC_HAIRPIN));
5844 : } else {
5845 0 : rightHp->undoChangeProperty(Pid::HAIRPIN_TYPE, int(HairpinType::DIM_HAIRPIN));
5846 : }
5847 : }
5848 : }
5849 0 : }
5850 :
5851 0 : void NotationInteraction::toggleDynamicPopup()
5852 : {
5853 0 : EngravingItem* el = selection()->element();
5854 0 : if (!el) {
5855 0 : return;
5856 : }
5857 0 : if (!el->isHairpinSegment()) {
5858 0 : addTextToItem(TextStyleType::DYNAMICS, el);
5859 0 : return;
5860 : }
5861 :
5862 0 : HairpinSegment* hairpinSeg = toHairpinSegment(el);
5863 0 : Hairpin* hairpin = hairpinSeg->hairpin();
5864 :
5865 0 : auto addDynamic = [this](Fraction tick, track_idx_t track, VoiceAssignment voiceAssignment) {
5866 0 : endEditElement();
5867 0 : startEdit(TranslatableString("undoableAction", "Add dynamic"));
5868 0 : Measure* measure = score()->tick2measure(tick);
5869 0 : Segment* segment = measure->undoGetChordRestOrTimeTickSegment(tick);
5870 0 : Dynamic* dynamic = Factory::createDynamic(segment);
5871 0 : dynamic->setOwnershipParent(segment);
5872 0 : dynamic->setTrack(track);
5873 0 : dynamic->setVoiceAssignment(voiceAssignment);
5874 0 : score()->undoAddElement(dynamic);
5875 0 : apply();
5876 0 : startEditText(dynamic);
5877 0 : };
5878 : // if the selected grip is at the left end, place the dynamic at the start
5879 0 : if (m_editData.curGrip == Grip::START || (m_editData.curGrip == Grip::APERTURE && hairpin->isDecrescendo())) {
5880 0 : if (EngravingItem* startDynOrExp = hairpinSeg->findElementToSnapBefore()) {
5881 : // If there is already a dynamic, select it instead of opening an empty popup
5882 0 : select({ startDynOrExp });
5883 0 : if (startDynOrExp->isDynamic()) {
5884 0 : autoFlipHairpinsType(toDynamic(startDynOrExp));
5885 : }
5886 : } else {
5887 0 : addDynamic(hairpin->tick(), hairpin->track(), hairpin->voiceAssignment());
5888 : }
5889 : } else {
5890 0 : if (EngravingItem* endDynOrExp = hairpinSeg->findElementToSnapAfter()) {
5891 : // If there is already a dynamic, select it instead of opening an empty popup
5892 0 : select({ endDynOrExp });
5893 0 : if (endDynOrExp->isDynamic()) {
5894 0 : autoFlipHairpinsType(toDynamic(endDynOrExp));
5895 : }
5896 : } else {
5897 0 : addDynamic(hairpin->tick2(), hairpin->track2(), hairpin->voiceAssignment());
5898 : }
5899 : }
5900 : }
5901 :
5902 0 : bool NotationInteraction::toggleLayoutBreakAvailable() const
5903 : {
5904 0 : return !selection()->isNone() && !isTextEditingStarted();
5905 : }
5906 :
5907 0 : void NotationInteraction::toggleLayoutBreak(LayoutBreakType breakType)
5908 : {
5909 0 : transaction(TranslatableString("undoableAction", "Toggle layout break"), [&](auto&) {
5910 0 : score()->cmdToggleLayoutBreak(breakType);
5911 0 : });
5912 0 : }
5913 :
5914 0 : void NotationInteraction::moveMeasureToPrevSystem()
5915 : {
5916 0 : MeasureBase* m = score()->selection().endMeasureBase();
5917 0 : if (!m) {
5918 0 : return;
5919 : }
5920 0 : transaction(TranslatableString("undoableAction", "Move measure to previous system"), [&](auto& tx) {
5921 0 : EditSystemLocks::moveMeasureToPrevSystem(tx, score(), m);
5922 0 : });
5923 : }
5924 :
5925 0 : void NotationInteraction::moveMeasureToNextSystem()
5926 : {
5927 0 : MeasureBase* m = score()->selection().startMeasureBase();
5928 0 : if (!m) {
5929 0 : return;
5930 : }
5931 0 : transaction(TranslatableString("undoableAction", "Move measure to next system"), [&](auto& tx) {
5932 0 : EditSystemLocks::moveMeasureToNextSystem(tx, score(), m);
5933 0 : });
5934 : }
5935 :
5936 0 : void NotationInteraction::toggleSystemLock()
5937 : {
5938 0 : transaction(TranslatableString("undoableAction", "Lock/unlock selected system(s)"), [&](auto& tx) {
5939 0 : EditSystemLocks::toggleSystemLock(tx, score(), selection()->selectedSystems());
5940 0 : });
5941 0 : }
5942 :
5943 0 : void NotationInteraction::toggleScoreLock()
5944 : {
5945 0 : transaction(TranslatableString("undoableAction", "Lock/unlock all systems"), [&](auto& tx) {
5946 0 : EditSystemLocks::toggleScoreLock(tx, score());
5947 0 : });
5948 0 : }
5949 :
5950 0 : void NotationInteraction::makeIntoSystem()
5951 : {
5952 0 : MeasureBase* first = score()->selection().startMeasureBase();
5953 0 : MeasureBase* last = score()->selection().endMeasureBase();
5954 0 : if (!first || !last) {
5955 0 : return;
5956 : }
5957 :
5958 0 : transaction(TranslatableString("undoableAction", "Create system from selection"), [&](auto& tx) {
5959 0 : EditSystemLocks::makeIntoSystem(tx, score(), first, last);
5960 0 : });
5961 : }
5962 :
5963 0 : void NotationInteraction::applySystemLock()
5964 : {
5965 0 : transaction(TranslatableString("undoableAction", "Apply system lock to selection"), [&](auto& tx) {
5966 0 : EditSystemLocks::applyLockToSelection(tx, score());
5967 0 : });
5968 0 : }
5969 :
5970 0 : void NotationInteraction::moveSystemToPrevPage()
5971 : {
5972 0 : MeasureBase* firstMeas = score()->selection().startMeasureBase();
5973 0 : MeasureBase* endMeas = score()->selection().endMeasureBase();
5974 0 : System* startSys = firstMeas ? firstMeas->system() : nullptr;
5975 0 : System* endSys = endMeas ? endMeas->system() : nullptr;
5976 0 : if (!startSys || !endSys) {
5977 0 : return;
5978 : }
5979 0 : MeasureBase* firstMb = startSys->first();
5980 0 : MeasureBase* lastMb = endSys->last();
5981 0 : transaction(TranslatableString("undoableAction", "Move system to previous page"), [&](auto& tx) {
5982 0 : EditPageLocks::moveMeasuresToPrevPage(tx, score(), firstMb, lastMb);
5983 0 : });
5984 : }
5985 :
5986 0 : void NotationInteraction::moveSystemToNextPage()
5987 : {
5988 0 : MeasureBase* firstMeas = score()->selection().startMeasureBase();
5989 0 : MeasureBase* endMeas = score()->selection().endMeasureBase();
5990 0 : System* startSys = firstMeas ? firstMeas->system() : nullptr;
5991 0 : System* endSys = endMeas ? endMeas->system() : nullptr;
5992 0 : if (!startSys || !endSys) {
5993 0 : return;
5994 : }
5995 0 : MeasureBase* firstMb = startSys->first();
5996 0 : MeasureBase* lastMb = endSys->last();
5997 0 : transaction(TranslatableString("undoableAction", "Move system to next page"), [&](auto& tx) {
5998 0 : EditPageLocks::moveMeasuresToNextPage(tx, score(), firstMb, lastMb);
5999 0 : });
6000 : }
6001 :
6002 0 : void NotationInteraction::togglePageLock()
6003 : {
6004 0 : transaction(TranslatableString("undoableAction", "Lock/unlock selected page(s)"), [&](auto& tx) {
6005 0 : EditPageLocks::togglePageLock(tx, score(), selection()->pagesContainingSelection());
6006 0 : });
6007 0 : }
6008 :
6009 0 : void NotationInteraction::makeIntoPage()
6010 : {
6011 0 : MeasureBase* first = score()->selection().startMeasureBase();
6012 0 : MeasureBase* last = score()->selection().endMeasureBase();
6013 0 : if (!first || !last) {
6014 0 : return;
6015 : }
6016 :
6017 0 : transaction(TranslatableString("undoableAction", "Create page from selection"), [&](auto& tx) {
6018 0 : EditPageLocks::makeIntoPage(tx, score(), first, last);
6019 0 : });
6020 : }
6021 :
6022 0 : void NotationInteraction::applyPageLock()
6023 : {
6024 0 : transaction(TranslatableString("undoableAction", "Apply page lock to selection"), [&](auto& tx) {
6025 0 : EditPageLocks::applyLockToSelection(tx, score());
6026 0 : });
6027 0 : }
6028 :
6029 0 : void NotationInteraction::addRemoveSystemLocks(AddRemoveSystemLockType intervalType, int interval)
6030 : {
6031 0 : interval = intervalType == AddRemoveSystemLockType::MeasuresInterval ? interval : 0;
6032 0 : bool afterEachSystem = intervalType == AddRemoveSystemLockType::AfterEachSystem;
6033 :
6034 0 : transaction(TranslatableString("undoableAction", "Measures per system"), [&](auto& tx) {
6035 0 : EditSystemLocks::addRemoveSystemLocks(tx, score(), interval, afterEachSystem);
6036 0 : });
6037 0 : }
6038 :
6039 0 : bool NotationInteraction::transpose(const TransposeOptions& options)
6040 : {
6041 0 : bool ok = false;
6042 :
6043 0 : transaction(TranslatableString("undoableAction", "Transposition"), [&](auto& tx) {
6044 0 : ok = Transpose::transpose(tx, score(), options.mode, options.direction, options.key, options.interval,
6045 0 : options.needTransposeKeys, options.needTransposeChordNames, options.needTransposeDoubleSharpsFlats);
6046 0 : });
6047 :
6048 0 : return ok;
6049 : }
6050 :
6051 0 : void NotationInteraction::swapVoices(voice_idx_t voiceIndex1, voice_idx_t voiceIndex2)
6052 : {
6053 0 : if (selection()->isNone()) {
6054 0 : return;
6055 : }
6056 :
6057 0 : if (voiceIndex1 == voiceIndex2) {
6058 0 : return;
6059 : }
6060 :
6061 0 : if (!isVoiceIndexValid(voiceIndex1) || !isVoiceIndexValid(voiceIndex2)) {
6062 0 : return;
6063 : }
6064 :
6065 0 : startEdit(TranslatableString("undoableAction", "Swap voices"));
6066 0 : ExchangeVoices::exchangeVoicesInSelection(score(), voiceIndex1, voiceIndex2);
6067 0 : apply();
6068 : }
6069 :
6070 0 : void NotationInteraction::addIntervalToSelectedNotes(int interval)
6071 : {
6072 0 : if (!isNotesIntervalValid(interval)) {
6073 0 : return;
6074 : }
6075 :
6076 0 : std::vector<Note*> notes;
6077 :
6078 0 : if (score()->selection().isRange()) {
6079 0 : const bool hasMultiNoteChords = score()->selection().rangeContainsMultiNoteChords();
6080 0 : for (const ChordRest* chordRest : score()->getSelectedChordRests()) {
6081 0 : if (!chordRest->isChord()) {
6082 0 : continue;
6083 : }
6084 0 : const Chord* chord = toChord(chordRest);
6085 0 : const std::vector<Note*> nl = chord->notes();
6086 0 : if (interval > 0) {
6087 0 : for (size_t noteIdx = nl.size(); noteIdx > 0; --noteIdx) {
6088 0 : if (score()->selectionFilter().canSelectNoteIdx(noteIdx - 1, nl.size(), hasMultiNoteChords)) {
6089 0 : notes.push_back(nl.at(noteIdx - 1));
6090 0 : break;
6091 : }
6092 : }
6093 : } else {
6094 0 : for (size_t noteIdx = 0; noteIdx < nl.size(); ++noteIdx) {
6095 0 : if (score()->selectionFilter().canSelectNoteIdx(noteIdx, nl.size(), hasMultiNoteChords)) {
6096 0 : notes.push_back(nl.at(noteIdx));
6097 0 : break;
6098 : }
6099 : }
6100 : }
6101 0 : }
6102 : } else {
6103 0 : notes = score()->selection().noteList();
6104 : }
6105 :
6106 0 : if (notes.empty()) {
6107 0 : MScore::setError(MsError::NO_NOTE_SELECTED);
6108 0 : checkAndShowError();
6109 0 : return;
6110 : }
6111 :
6112 0 : startEdit(TranslatableString("undoableAction", "Add interval"));
6113 0 : score()->addInterval(interval, notes);
6114 0 : apply();
6115 0 : }
6116 :
6117 0 : Ret NotationInteraction::canAddFret() const
6118 : {
6119 0 : if (NoteInput::addFretRemovesMeasureRepeat(score())) {
6120 0 : return make_ret(notation::Err::NoteInputRemovesMeasureRepeat);
6121 : }
6122 :
6123 0 : return make_ok();
6124 : }
6125 :
6126 0 : void NotationInteraction::addFret(int fretIndex)
6127 : {
6128 0 : transaction(TranslatableString("undoableAction", "Enter note at fret %1").arg(fretIndex), [&](auto& tx) {
6129 0 : NoteInput::addFret(tx, score(), fretIndex);
6130 0 : });
6131 :
6132 0 : notifyAboutNotationChanged();
6133 0 : }
6134 :
6135 0 : void NotationInteraction::changeSelectedElementsVoice(voice_idx_t voiceIndex)
6136 : {
6137 0 : if (selection()->isNone()) {
6138 0 : return;
6139 : }
6140 :
6141 0 : if (!isVoiceIndexValid(voiceIndex)) {
6142 0 : return;
6143 : }
6144 :
6145 0 : startEdit(TranslatableString("undoableAction", "Change voice"));
6146 0 : EditVoice::changeSelectedElementsVoice(score()->transactionManager()->currentOrDummyTransaction(), score(), voiceIndex);
6147 0 : apply();
6148 : }
6149 :
6150 0 : void NotationInteraction::changeSelectedElementsVoiceAssignment(VoiceAssignment voiceAssignment)
6151 : {
6152 0 : if (selection()->isNone()) {
6153 0 : return;
6154 : }
6155 :
6156 0 : startEdit(TranslatableString("undoableAction", "Change voice assignment"));
6157 0 : EditVoice::changeSelectedElementsVoiceAssignment(score()->transactionManager()->currentOrDummyTransaction(), score(),
6158 : voiceAssignment);
6159 0 : apply();
6160 : }
6161 :
6162 0 : void NotationInteraction::addAnchoredLineToSelectedNotes()
6163 : {
6164 0 : if (selection()->isNone()) {
6165 0 : return;
6166 : }
6167 :
6168 0 : startEdit(TranslatableString("undoableAction", "Add note-anchored line"));
6169 0 : score()->addNoteLine();
6170 0 : apply();
6171 : }
6172 :
6173 0 : void NotationInteraction::addText(TextStyleType type)
6174 : {
6175 0 : EngravingItem* item = nullptr;
6176 :
6177 0 : const INotationSelectionPtr sel = selection();
6178 0 : if (sel->isRange()) {
6179 0 : const INotationSelectionRangePtr range = sel->range();
6180 0 : item = range->rangeStartSegment()->firstElementForNavigation(range->startStaffIndex());
6181 0 : } else {
6182 0 : item = contextItem();
6183 : }
6184 :
6185 0 : if (!item) {
6186 0 : return;
6187 : }
6188 :
6189 0 : if (isVerticalBoxTextStyle(type)) {
6190 0 : if (!item->isVBox()) {
6191 0 : addTextToTopFrame(type);
6192 0 : return;
6193 : }
6194 : }
6195 :
6196 0 : addTextToItem(type, item);
6197 0 : }
6198 :
6199 0 : void NotationInteraction::addTextToTopFrame(TextStyleType type)
6200 : {
6201 0 : doAddText(type);
6202 0 : }
6203 :
6204 0 : bool NotationInteraction::canAddTextToItem(TextStyleType type, const EngravingItem* item) const
6205 : {
6206 0 : if (isVerticalBoxTextStyle(type)) {
6207 0 : return item && item->isVBox();
6208 : }
6209 :
6210 0 : if (type == TextStyleType::FRAME) {
6211 0 : return item && item->isBox() ? muse::make_ok() : make_ret(Err::EmptySelection);
6212 : }
6213 :
6214 : static const std::set<TextStyleType> harmonyTypes {
6215 : TextStyleType::HARMONY_A,
6216 : TextStyleType::HARMONY_ROMAN,
6217 : TextStyleType::HARMONY_NASHVILLE,
6218 0 : };
6219 :
6220 0 : const bool isHarmony = muse::contains(harmonyTypes, type);
6221 0 : if (isHarmony && item && item->isFretDiagram()) {
6222 0 : return true;
6223 : }
6224 :
6225 : static const std::set<TextStyleType> needSelectNoteOrRestTypes {
6226 : TextStyleType::SYSTEM,
6227 : TextStyleType::STAFF,
6228 : TextStyleType::DYNAMICS,
6229 : TextStyleType::EXPRESSION,
6230 : TextStyleType::REHEARSAL_MARK,
6231 : TextStyleType::INSTRUMENT_CHANGE,
6232 : TextStyleType::FINGERING,
6233 : TextStyleType::LH_GUITAR_FINGERING,
6234 : TextStyleType::RH_GUITAR_FINGERING,
6235 : TextStyleType::STRING_NUMBER,
6236 : TextStyleType::STICKING,
6237 : TextStyleType::HARMONY_A,
6238 : TextStyleType::HARMONY_ROMAN,
6239 : TextStyleType::HARMONY_NASHVILLE,
6240 : TextStyleType::LYRICS_ODD,
6241 : TextStyleType::TEMPO,
6242 0 : };
6243 :
6244 0 : if (muse::contains(needSelectNoteOrRestTypes, type)) {
6245 : static const std::set<ElementType> requiredElementTypes {
6246 : ElementType::NOTE,
6247 : ElementType::REST,
6248 : ElementType::MMREST,
6249 : ElementType::MEASURE_REPEAT,
6250 : ElementType::CHORD,
6251 0 : };
6252 :
6253 0 : return item && muse::contains(requiredElementTypes, item->type());
6254 : }
6255 :
6256 0 : return true;
6257 : }
6258 :
6259 0 : void NotationInteraction::addTextToItem(TextStyleType type, EngravingItem* item)
6260 : {
6261 0 : if (!scoreHasMeasure()) {
6262 0 : LOGE() << "Need to create measure";
6263 0 : return;
6264 : }
6265 :
6266 0 : if (!canAddTextToItem(type, item)) {
6267 0 : MScore::setError(MsError::NO_NOTE_REST_SELECTED);
6268 0 : checkAndShowError();
6269 0 : return;
6270 : }
6271 :
6272 0 : doAddText(type, item);
6273 : }
6274 :
6275 0 : void NotationInteraction::doAddText(TextStyleType type, EngravingItem* item)
6276 : {
6277 0 : if (m_noteInput->isNoteInputMode()) {
6278 0 : m_noteInput->endNoteInput();
6279 : }
6280 :
6281 0 : startEdit(TranslatableString("undoableAction", "Add text"));
6282 0 : mu::engraving::TextBase* text = score()->addText(type, item);
6283 :
6284 0 : if (!text) {
6285 0 : rollback();
6286 0 : return;
6287 : }
6288 :
6289 0 : if (text->isInstrumentChange()) {
6290 0 : if (!selectInstrument(toInstrumentChange(text))) {
6291 0 : rollback();
6292 0 : return;
6293 : }
6294 : }
6295 :
6296 0 : if (text->hasVoiceAssignmentProperties()) {
6297 0 : text->setInitialTrackAndVoiceAssignment(item->track(), false);
6298 : }
6299 :
6300 0 : apply();
6301 0 : showItem(text);
6302 :
6303 0 : if (!text->isInstrumentChange()) {
6304 0 : startEditText(text);
6305 : }
6306 :
6307 0 : if (text->isRehearsalMark() || text->isTempoText()) {
6308 0 : text->cursor()->selectWord();
6309 : }
6310 : }
6311 :
6312 0 : Ret NotationInteraction::canAddImageToItem(const EngravingItem* item) const
6313 : {
6314 0 : return item && item->isMeasureBase();
6315 : }
6316 :
6317 0 : void NotationInteraction::addImageToItem(const muse::io::path_t& imagePath, EngravingItem* item)
6318 : {
6319 0 : if (imagePath.empty() || !item) {
6320 0 : return;
6321 : }
6322 :
6323 : static const std::map<muse::io::path_t, ImageType> suffixToType {
6324 0 : { "svg", ImageType::SVG },
6325 0 : { "svgz", ImageType::SVG },
6326 0 : { "jpg", ImageType::RASTER },
6327 0 : { "jpeg", ImageType::RASTER },
6328 0 : { "png", ImageType::RASTER },
6329 0 : { "bmp", ImageType::RASTER },
6330 0 : { "tif", ImageType::RASTER },
6331 0 : { "tiff", ImageType::RASTER },
6332 0 : };
6333 :
6334 0 : muse::io::path_t suffix = io::suffix(imagePath);
6335 :
6336 0 : ImageType type = muse::value(suffixToType, suffix, ImageType::NONE);
6337 0 : if (type == ImageType::NONE) {
6338 0 : return;
6339 : }
6340 :
6341 0 : Image* image = Factory::createImage(item);
6342 0 : image->setImageType(type);
6343 :
6344 0 : if (!image->loadFromFile(imagePath)) {
6345 0 : delete image;
6346 0 : return;
6347 : }
6348 :
6349 0 : startEdit(TranslatableString("undoableAction", "Add image"));
6350 0 : score()->undoAddElement(image);
6351 0 : apply();
6352 0 : }
6353 :
6354 0 : void NotationInteraction::addFiguredBass()
6355 : {
6356 : static const ElementTypeSet REQUIRED_TYPES {
6357 : ElementType::NOTE,
6358 : ElementType::FIGURED_BASS,
6359 : ElementType::REST
6360 0 : };
6361 :
6362 0 : if (!m_selection->elementsSelected(REQUIRED_TYPES)) {
6363 0 : MScore::setError(MsError::NO_NOTE_FIGUREDBASS_SELECTED);
6364 0 : checkAndShowError();
6365 0 : return;
6366 : }
6367 :
6368 0 : startEdit(TranslatableString("undoableAction", "Add figured bass"));
6369 0 : mu::engraving::FiguredBass* figuredBass = score()->addFiguredBass();
6370 :
6371 0 : if (figuredBass) {
6372 0 : apply();
6373 0 : startEditText(figuredBass, PointF());
6374 0 : m_selection->notifyAboutSelectionChangedIfNeed();
6375 : } else {
6376 0 : rollback();
6377 : }
6378 : }
6379 :
6380 0 : void NotationInteraction::addStretch(qreal value)
6381 : {
6382 0 : TranslatableString name = value >= 0
6383 0 : ? TranslatableString("undoableAction", "Increase layout stretch")
6384 0 : : TranslatableString("undoableAction", "Decrease layout stretch");
6385 0 : transaction(name, [&](Transaction& tx) {
6386 0 : mu::engraving::EditStretch::addStretch(tx, score(), value);
6387 0 : });
6388 0 : }
6389 :
6390 0 : Measure* NotationInteraction::selectedMeasure() const
6391 : {
6392 0 : INotationInteraction::HitElementContext context = hitElementContext();
6393 0 : mu::engraving::Measure* measure = context.element && context.element->isMeasure() ? mu::engraving::toMeasure(context.element) : nullptr;
6394 0 : if (measure) {
6395 0 : return measure;
6396 : }
6397 :
6398 0 : INotationSelectionPtr selection = this->selection();
6399 0 : if (selection->isRange()) {
6400 0 : MeasureBase* mb = selection->range()->measureBaseRange().endMeasureBase;
6401 0 : if (!mb) {
6402 0 : return nullptr;
6403 : }
6404 0 : return mb->isMeasure() ? toMeasure(mb) : mb->prevMeasure();
6405 : }
6406 :
6407 0 : if (selection->element()) {
6408 0 : return selection->element()->findMeasure();
6409 : }
6410 :
6411 0 : return nullptr;
6412 0 : }
6413 :
6414 0 : void NotationInteraction::addTimeSignature(Measure* measure, staff_idx_t staffIndex, TimeSignature* timeSignature)
6415 : {
6416 0 : startEdit(TranslatableString("undoableAction", "Add time signature"));
6417 0 : Transaction& tx = score()->transactionManager()->currentOrDummyTransaction();
6418 0 : EditTimeSig::addTimeSig(tx, score(), measure, staffIndex, timeSignature, true);
6419 0 : apply();
6420 0 : }
6421 :
6422 0 : void NotationInteraction::explodeSelectedStaff()
6423 : {
6424 0 : if (!selection()->isRange()) {
6425 0 : return;
6426 : }
6427 :
6428 0 : startEdit(TranslatableString("undoableAction", "Explode"));
6429 0 : if (ImplodeExplode::explode(score())) {
6430 0 : apply();
6431 : } else {
6432 0 : rollback();
6433 : }
6434 :
6435 0 : checkAndShowError();
6436 : }
6437 :
6438 0 : void NotationInteraction::implodeSelectedStaff()
6439 : {
6440 0 : if (!selection()->isRange()) {
6441 0 : return;
6442 : }
6443 :
6444 0 : startEdit(TranslatableString("undoableAction", "Implode"));
6445 0 : if (ImplodeExplode::implode(score())) {
6446 0 : apply();
6447 : } else {
6448 0 : rollback();
6449 : }
6450 :
6451 0 : checkAndShowError();
6452 : }
6453 :
6454 0 : void NotationInteraction::realizeSelectedChordSymbols(bool literal, Voicing voicing, HDuration durationType)
6455 : {
6456 0 : if (selection()->isNone()) {
6457 0 : return;
6458 : }
6459 :
6460 0 : startEdit(TranslatableString("undoableAction", "Realize chord symbols"));
6461 0 : RealizeChordSymbols::realizeChordSymbols(score()->transactionManager()->currentOrDummyTransaction(), score(), literal, voicing,
6462 : durationType);
6463 0 : apply();
6464 : }
6465 :
6466 0 : void NotationInteraction::extendToNextNote()
6467 : {
6468 0 : if (selection()->isNone()) {
6469 0 : return;
6470 : }
6471 :
6472 0 : m_undoStack->transaction(TranslatableString("undoableAction", "Extend to next note"), [&](mu::engraving::Transaction& tx) {
6473 0 : EditDuration::extendToNextNote(tx, score());
6474 0 : });
6475 0 : notifyAboutNotationChanged();
6476 : }
6477 :
6478 0 : void NotationInteraction::removeSelectedMeasures()
6479 : {
6480 0 : if (selection()->isNone()) {
6481 0 : return;
6482 : }
6483 :
6484 0 : mu::engraving::MeasureBase* firstMeasureBase = nullptr;
6485 0 : mu::engraving::MeasureBase* lastMeasureBase = nullptr;
6486 :
6487 0 : if (selection()->isRange()) {
6488 0 : INotationSelectionRange::MeasureBaseRange measureBaseRange = selection()->range()->measureBaseRange();
6489 0 : firstMeasureBase = measureBaseRange.startMeasureBase;
6490 0 : lastMeasureBase = measureBaseRange.endMeasureBase;
6491 : } else {
6492 0 : const std::vector<EngravingItem*>& elements = selection()->elements();
6493 0 : if (elements.empty()) {
6494 0 : return;
6495 : }
6496 :
6497 0 : for (EngravingItem* element : elements) {
6498 0 : mu::engraving::MeasureBase* elementMeasure = element->findMeasureBase();
6499 :
6500 0 : if (!firstMeasureBase || firstMeasureBase->index() > elementMeasure->index()) {
6501 0 : firstMeasureBase = elementMeasure;
6502 : }
6503 :
6504 0 : if (!lastMeasureBase || lastMeasureBase->index() < elementMeasure->index()) {
6505 0 : lastMeasureBase = elementMeasure;
6506 : }
6507 : }
6508 : }
6509 :
6510 0 : IF_ASSERT_FAILED(firstMeasureBase && lastMeasureBase) {
6511 0 : return;
6512 : }
6513 :
6514 0 : m_selection->select({ firstMeasureBase }, SelectType::REPLACE);
6515 0 : m_selection->select({ lastMeasureBase }, SelectType::RANGE);
6516 :
6517 : // Slight hack because measureIndex is only meaningful for Measure types (perhaps this property shouldn't
6518 : // exist on MeasureBase in the first place)...
6519 0 : const Measure* firstMeasure = firstMeasureBase->isMeasure() ? toMeasure(firstMeasureBase) : firstMeasureBase->nextMeasure();
6520 0 : const Measure* lastMeasure = lastMeasureBase->isMeasure() ? toMeasure(lastMeasureBase) : lastMeasureBase->prevMeasure();
6521 :
6522 0 : int numDeletedMeasures = 0;
6523 0 : if (firstMeasure && lastMeasure && firstMeasure->measureIndex() <= lastMeasure->measureIndex()) {
6524 0 : numDeletedMeasures = 1 + lastMeasure->measureIndex() - firstMeasure->measureIndex();
6525 : }
6526 :
6527 0 : startEdit(TranslatableString("undoableAction", "Delete %Ln measure(s)", nullptr, numDeletedMeasures));
6528 0 : score()->cmdTimeDelete();
6529 0 : apply();
6530 : }
6531 :
6532 0 : void NotationInteraction::removeSelectedRange()
6533 : {
6534 0 : if (selection()->isNone()) {
6535 0 : return;
6536 : }
6537 :
6538 0 : startEdit(TranslatableString("undoableAction", "Delete range"));
6539 0 : score()->cmdTimeDelete();
6540 0 : apply();
6541 : }
6542 :
6543 0 : void NotationInteraction::removeEmptyTrailingMeasures()
6544 : {
6545 0 : startEdit(TranslatableString("undoableAction", "Remove empty trailing measures"));
6546 0 : score()->cmdRemoveEmptyTrailingMeasures();
6547 0 : apply();
6548 0 : }
6549 :
6550 0 : void NotationInteraction::fillSelectionWithSlashes()
6551 : {
6552 0 : if (selection()->isNone()) {
6553 0 : return;
6554 : }
6555 :
6556 0 : transaction(TranslatableString("undoableAction", "Fill with slashes"), [&](auto& tx) {
6557 0 : EditSlashNotation::slashFill(tx, score());
6558 0 : });
6559 :
6560 0 : notifyAboutNotationChanged();
6561 : }
6562 :
6563 0 : void NotationInteraction::replaceSelectedNotesWithSlashes()
6564 : {
6565 0 : if (selection()->isNone()) {
6566 0 : return;
6567 : }
6568 :
6569 0 : transaction(TranslatableString("undoableAction", "Toggle rhythmic slash notation"), [&](auto& tx) {
6570 0 : EditSlashNotation::slashRhythm(tx, score());
6571 0 : });
6572 :
6573 0 : notifyAboutNotationChanged();
6574 : }
6575 :
6576 0 : void NotationInteraction::changeEnharmonicSpelling(bool both)
6577 : {
6578 0 : transaction(TranslatableString("undoableAction", "Change enharmonic spelling"), [&](auto&) {
6579 0 : EditEnharmonicSpelling::changeEnharmonicSpelling(score(), both);
6580 0 : });
6581 :
6582 0 : notifyAboutNotationChanged();
6583 0 : }
6584 :
6585 0 : void NotationInteraction::spellPitches()
6586 : {
6587 0 : transaction(TranslatableString("undoableAction", "Optimize enharmonic spelling"), [&](auto&) {
6588 0 : EditEnharmonicSpelling::spell(score());
6589 0 : });
6590 :
6591 0 : notifyAboutNotationChanged();
6592 0 : }
6593 :
6594 0 : void NotationInteraction::spellPitchesWithSharps()
6595 : {
6596 0 : transaction(TranslatableString("undoableAction", "Respell pitches with sharps"), [&](auto&) {
6597 0 : EditEnharmonicSpelling::spellWithSharpsOrFlats(score(), Prefer::SHARPS);
6598 0 : });
6599 :
6600 0 : notifyAboutNotationChanged();
6601 0 : }
6602 :
6603 0 : void NotationInteraction::spellPitchesWithFlats()
6604 : {
6605 0 : transaction(TranslatableString("undoableAction", "Respell pitches with flats"), [&](auto&) {
6606 0 : EditEnharmonicSpelling::spellWithSharpsOrFlats(score(), Prefer::FLATS);
6607 0 : });
6608 :
6609 0 : notifyAboutNotationChanged();
6610 0 : }
6611 :
6612 0 : void NotationInteraction::regroupNotesAndRests()
6613 : {
6614 0 : transaction(TranslatableString("undoableAction", "Regroup rhythms"), [&](Transaction& tx) {
6615 0 : Regroup::regroupNotesAndRestsInSelection(tx, score());
6616 0 : });
6617 :
6618 0 : notifyAboutNotationChanged();
6619 0 : }
6620 :
6621 0 : void NotationInteraction::resequenceRehearsalMarks()
6622 : {
6623 0 : transaction(TranslatableString("undoableAction", "Resequence rehearsal marks"), [&](Transaction& tx) {
6624 0 : EditRehearsalMark::resequenceRehearsalMarks(tx, score());
6625 0 : });
6626 :
6627 0 : notifyAboutNotationChanged();
6628 0 : }
6629 :
6630 0 : void NotationInteraction::resetStretch()
6631 : {
6632 0 : transaction(TranslatableString("undoableAction", "Reset layout stretch"), [&](Transaction& tx) {
6633 0 : mu::engraving::EditStretch::resetUserStretch(tx, score());
6634 0 : });
6635 0 : }
6636 :
6637 0 : void NotationInteraction::resetTextStyleOverrides()
6638 : {
6639 0 : startEdit(TranslatableString("undoableAction", "Reset text style overrides"));
6640 0 : Reset::resetTextStyleOverrides(score());
6641 0 : apply();
6642 0 : }
6643 :
6644 0 : void NotationInteraction::resetBeamMode()
6645 : {
6646 0 : transaction(TranslatableString("undoableAction", "Reset beams"), [&](Transaction& tx) {
6647 0 : EditBeam::resetBeamMode(tx, score());
6648 0 : });
6649 0 : notifyAboutNotationChanged();
6650 0 : }
6651 :
6652 0 : void NotationInteraction::resetShapesAndPosition()
6653 : {
6654 0 : auto resetItem = [](EngravingItem* item) {
6655 0 : item->reset();
6656 :
6657 0 : if (item->isSpanner()) {
6658 0 : for (mu::engraving::SpannerSegment* spannerSegment : toSpanner(item)->spannerSegments()) {
6659 0 : spannerSegment->reset();
6660 : }
6661 : }
6662 0 : };
6663 :
6664 0 : startEdit(TranslatableString("undoableAction", "Reset shapes and positions"));
6665 :
6666 0 : DEFER {
6667 0 : apply();
6668 0 : };
6669 :
6670 0 : if (selection()->element()) {
6671 0 : resetItem(selection()->element());
6672 0 : return;
6673 : }
6674 :
6675 0 : for (EngravingItem* item : selection()->elements()) {
6676 0 : resetItem(item);
6677 : }
6678 0 : }
6679 :
6680 0 : void NotationInteraction::freezeSelectionPosition()
6681 : {
6682 0 : std::vector<EngravingItem*> items = selection()->elements();
6683 0 : if (items.empty()) {
6684 0 : return;
6685 : }
6686 :
6687 0 : transaction(TranslatableString("undoableAction", "Freeze current placement"), [&](mu::engraving::Transaction& tx) {
6688 0 : EditPosition::freezeItemsPositions(tx, items);
6689 0 : });
6690 :
6691 0 : notifyAboutNotationChanged();
6692 0 : }
6693 :
6694 0 : void NotationInteraction::resetToDefaultLayout()
6695 : {
6696 0 : TRACEFUNC;
6697 :
6698 0 : startEdit(TranslatableString("undoableAction", "Reset to default layout"));
6699 0 : Reset::resetToDefaultLayout(score()->transactionManager()->currentOrDummyTransaction(), score());
6700 0 : apply();
6701 0 : }
6702 :
6703 0 : ScoreConfig NotationInteraction::scoreConfig() const
6704 : {
6705 0 : ScoreConfig config;
6706 0 : config.setShown(ScoreConfigType::ShowInvisibleElements, score()->isShowInvisible());
6707 0 : config.setShown(ScoreConfigType::ShowUnprintableElements, score()->showUnprintable());
6708 0 : config.setShown(ScoreConfigType::ShowFrames, score()->showFrames());
6709 0 : config.setShown(ScoreConfigType::ShowPageMargins, score()->showPageborders());
6710 0 : config.setShown(ScoreConfigType::ShowSoundFlags, score()->showSoundFlags());
6711 0 : config.setShown(ScoreConfigType::MarkIrregularMeasures, score()->markIrregularMeasures());
6712 0 : return config;
6713 0 : }
6714 :
6715 0 : void NotationInteraction::setScoreConfig(const ScoreConfig& config)
6716 : {
6717 0 : const ScoreConfig oldConfig = scoreConfig();
6718 0 : if (oldConfig == config) {
6719 0 : return;
6720 : }
6721 :
6722 : // TODO: refactor together with `NotationActionController::toggleScoreConfig`
6723 : // to be able to give a more precise name
6724 0 : startEdit(TranslatableString("undoableAction", "Set score view settings"));
6725 0 : score()->setShowInvisible(config.isShown(ScoreConfigType::ShowInvisibleElements));
6726 0 : score()->setShowUnprintable(config.isShown(ScoreConfigType::ShowUnprintableElements));
6727 0 : score()->setShowFrames(config.isShown(ScoreConfigType::ShowFrames));
6728 0 : score()->setShowPageborders(config.isShown(ScoreConfigType::ShowPageMargins));
6729 0 : score()->setShowSoundFlags(config.isShown(ScoreConfigType::ShowSoundFlags));
6730 0 : score()->setMarkIrregularMeasures(config.isShown(ScoreConfigType::MarkIrregularMeasures));
6731 :
6732 0 : EngravingItem* selectedElement = selection()->element();
6733 0 : if (selectedElement && !selectedElement->isInteractionAvailable()) {
6734 0 : clearSelection();
6735 : }
6736 :
6737 0 : apply();
6738 :
6739 0 : for (const auto& p : oldConfig.config) {
6740 0 : if (p.second != config.isShown(p.first)) {
6741 0 : m_scoreConfigChanged.send(p.first);
6742 : }
6743 : }
6744 0 : }
6745 :
6746 0 : muse::async::Channel<ScoreConfigType> NotationInteraction::scoreConfigChanged() const
6747 : {
6748 0 : return m_scoreConfigChanged;
6749 : }
6750 :
6751 0 : bool NotationInteraction::needEndTextEditing(const std::vector<EngravingItem*>& newSelectedElements) const
6752 : {
6753 0 : if (!isTextEditingStarted()) {
6754 0 : return false;
6755 : }
6756 :
6757 0 : if (newSelectedElements.empty()) {
6758 0 : return false;
6759 : }
6760 :
6761 0 : if (newSelectedElements.size() > 1) {
6762 0 : return true;
6763 : }
6764 :
6765 0 : if (m_editData.element && m_editData.element->isStaffText()) {
6766 0 : EngravingItem* element = newSelectedElements.front();
6767 0 : if (element && element->isSoundFlag() && element->ownershipParent() == m_editData.element) {
6768 0 : return false;
6769 : }
6770 : }
6771 :
6772 0 : return newSelectedElements.front() != m_editData.element;
6773 : }
6774 :
6775 0 : bool NotationInteraction::needEndElementEditing(const std::vector<EngravingItem*>& newSelectedElements) const
6776 : {
6777 0 : if (!isEditingElement()) {
6778 0 : return false;
6779 : }
6780 :
6781 0 : if (newSelectedElements.size() != 1) {
6782 0 : return true;
6783 : }
6784 :
6785 0 : if (m_editData.element && m_editData.element->isStaffText()) {
6786 0 : EngravingItem* element = newSelectedElements.front();
6787 0 : if (element && element->isSoundFlag() && element->ownershipParent() == m_editData.element) {
6788 0 : return false;
6789 : }
6790 : }
6791 :
6792 0 : return newSelectedElements.front() != score()->selection().element();
6793 : }
6794 :
6795 0 : void NotationInteraction::resetGripEdit()
6796 : {
6797 0 : m_editData.grips = 0;
6798 0 : m_editData.curGrip = mu::engraving::Grip::NO_GRIP;
6799 0 : m_editData.grip.clear();
6800 :
6801 0 : resetAnchorLines();
6802 0 : }
6803 :
6804 0 : void NotationInteraction::resetHitElementContext()
6805 : {
6806 0 : setHitElementContext(HitElementContext());
6807 0 : }
6808 :
6809 0 : void NotationInteraction::navigateToLyrics(bool back, bool moveOnly, bool end)
6810 : {
6811 0 : if (!m_editData.element || !m_editData.element->isLyrics()) {
6812 0 : LOGW("nextLyric called with invalid current element");
6813 0 : return;
6814 : }
6815 0 : const EditLyrics::InitialState state = EditLyrics::initialState(toLyrics(m_editData.element));
6816 0 : if (!EditLyrics::canNavigateToLyrics(state, back)) {
6817 0 : return;
6818 : }
6819 :
6820 0 : endEditText();
6821 :
6822 0 : EditLyrics::NavigatedLyrics navigated;
6823 0 : transaction(TranslatableString("undoableAction", "Navigate to lyrics"), [&](Transaction& tx) {
6824 0 : navigated = EditLyrics::navigateToLyrics(tx, score(), state, back, moveOnly);
6825 0 : });
6826 0 : Lyrics* nextLyrics = navigated.lyrics;
6827 0 : if (!nextLyrics) {
6828 0 : return;
6829 : }
6830 :
6831 0 : score()->select(nextLyrics, SelectType::SINGLE, 0);
6832 0 : score()->setLayoutAll();
6833 :
6834 0 : startEditText(nextLyrics, PointF());
6835 :
6836 0 : if (end) {
6837 0 : nextLyrics->selectAll();
6838 0 : } else if (!navigated.isNew) {
6839 0 : mu::engraving::TextCursor* cursor = nextLyrics->cursor();
6840 0 : cursor->movePosition(mu::engraving::TextCursor::MoveOperation::End, mu::engraving::TextCursor::MoveMode::MoveAnchor);
6841 0 : cursor->movePosition(mu::engraving::TextCursor::MoveOperation::Start, mu::engraving::TextCursor::MoveMode::KeepAnchor);
6842 : }
6843 :
6844 0 : showItem(nextLyrics);
6845 : }
6846 :
6847 0 : void NotationInteraction::navigateToLyrics(MoveDirection direction, bool moveOnly)
6848 : {
6849 0 : navigateToLyrics(direction == MoveDirection::Left, moveOnly, false);
6850 0 : }
6851 :
6852 0 : void NotationInteraction::navigateToNextSyllable()
6853 : {
6854 0 : if (!m_editData.element || !m_editData.element->isLyrics()) {
6855 0 : LOGW("nextSyllable called with invalid current element");
6856 0 : return;
6857 : }
6858 0 : const EditLyrics::InitialState state = EditLyrics::initialState(toLyrics(m_editData.element));
6859 0 : if (!EditLyrics::canNavigateToNextSyllable(state)) {
6860 0 : return;
6861 : }
6862 :
6863 0 : endEditText();
6864 :
6865 0 : Lyrics* toLyrics = nullptr;
6866 0 : transaction(TranslatableString("undoableAction", "Navigate to next syllable"), [&](Transaction& tx) {
6867 0 : toLyrics = EditLyrics::navigateToNextSyllable(tx, score(), state);
6868 0 : });
6869 0 : if (!toLyrics) {
6870 0 : return;
6871 : }
6872 :
6873 0 : score()->select(toLyrics, SelectType::SINGLE, 0);
6874 0 : score()->setLayoutAll();
6875 0 : startEditText(toLyrics, PointF());
6876 0 : toLyrics->selectAll();
6877 0 : showItem(toLyrics);
6878 : }
6879 :
6880 0 : void NotationInteraction::navigateToLyricsVerse(MoveDirection direction)
6881 : {
6882 0 : if (!m_editData.element || !m_editData.element->isLyrics()) {
6883 0 : LOGW("nextLyricVerse called with invalid current element");
6884 0 : return;
6885 : }
6886 0 : const EditLyrics::InitialState state = EditLyrics::initialState(toLyrics(m_editData.element));
6887 0 : const int verse = direction == MoveDirection::Up ? state.verse - 1 : state.verse + 1;
6888 0 : if (verse < 0 || verse > state.chordRest->lastVerse(state.placement)) {
6889 0 : return;
6890 : }
6891 :
6892 0 : endEditText();
6893 :
6894 0 : Lyrics* lyrics = nullptr;
6895 0 : transaction(TranslatableString("undoableAction", "Navigate to verse"), [&](Transaction& tx) {
6896 0 : lyrics = EditLyrics::navigateToVerse(tx, score(), state, verse);
6897 0 : });
6898 :
6899 0 : score()->select(lyrics, SelectType::SINGLE, 0);
6900 0 : startEditText(lyrics, PointF());
6901 :
6902 0 : lyrics = toLyrics(m_editData.element);
6903 :
6904 0 : score()->setLayoutAll();
6905 0 : score()->update();
6906 :
6907 0 : lyrics->selectAll();
6908 0 : showItem(lyrics);
6909 : }
6910 :
6911 : //! NOTE: Copied from ScoreView::harmonyBeatsTab
6912 0 : void NotationInteraction::navigateToNearHarmony(MoveDirection direction, bool nearNoteOrRest)
6913 : {
6914 0 : Harmony* harmony = editedHarmony();
6915 0 : if (!harmony) {
6916 0 : return;
6917 : }
6918 :
6919 0 : Segment* segment = harmonySegment(harmony);
6920 0 : if (!segment) {
6921 0 : LOGD("no segment");
6922 0 : return;
6923 : }
6924 :
6925 0 : Measure* measure = segment->measure();
6926 0 : Fraction tick = segment->tick();
6927 0 : engraving::track_idx_t track = harmony->track();
6928 0 : bool backDirection = direction == MoveDirection::Left;
6929 :
6930 0 : if (backDirection && tick == measure->tick()) {
6931 : // previous bar, if any
6932 0 : measure = measure->prevMeasure();
6933 0 : if (!measure) {
6934 0 : LOGD("no previous measure");
6935 0 : return;
6936 : }
6937 : }
6938 :
6939 0 : Fraction f = measure->ticks();
6940 0 : int ticksPerBeat = f.ticks()
6941 0 : / ((f.numerator() > 3 && (f.numerator() % 3) == 0 && f.denominator() > 4) ? f.numerator() / 3 : f.numerator());
6942 0 : Fraction tickInBar = tick - measure->tick();
6943 0 : Fraction newTick = measure->tick()
6944 0 : + Fraction::fromTicks((
6945 0 : (tickInBar.ticks() + (backDirection ? -1 : ticksPerBeat)) / ticksPerBeat
6946 : )
6947 0 : * ticksPerBeat);
6948 :
6949 0 : endEditText();
6950 :
6951 0 : startEdit(TranslatableString("undoableAction", "Navigate to next chord symbol"));
6952 :
6953 : // look for next/prev beat, note, rest or chord
6954 : for (;;) {
6955 0 : segment = backDirection ? segment->prev1(mu::engraving::SegmentType::ChordRest) : segment->next1(
6956 : mu::engraving::SegmentType::ChordRest);
6957 :
6958 0 : if (!segment || (backDirection ? (segment->tick() < newTick) : (segment->tick() > newTick))) {
6959 : // no segment or moved past the beat - create new segment
6960 0 : if (!backDirection && newTick >= measure->tick() + f) {
6961 : // next bar, if any
6962 0 : measure = measure->nextMeasure();
6963 0 : if (!measure) {
6964 0 : LOGD("no next measure");
6965 0 : rollback();
6966 0 : return;
6967 : }
6968 : }
6969 :
6970 0 : segment = measure->undoGetSegment(SegmentType::ChordRest, newTick);
6971 0 : break;
6972 : }
6973 :
6974 0 : if (segment->tick() == newTick) {
6975 0 : break;
6976 : }
6977 :
6978 0 : if (nearNoteOrRest) {
6979 0 : track_idx_t minTrack = trackZeroVoice(track);
6980 0 : track_idx_t maxTrack = minTrack + VOICES - 1;
6981 0 : if (segment->hasAnnotationOrElement(ElementType::HARMONY, minTrack, maxTrack)) {
6982 0 : break;
6983 : }
6984 : }
6985 0 : }
6986 :
6987 0 : mu::engraving::Harmony* nextHarmony = findHarmonyInSegment(segment, track, harmony->textStyleType());
6988 0 : if (!nextHarmony) {
6989 0 : nextHarmony = createHarmony(segment, track, harmony->harmonyType());
6990 0 : score()->undoAddElement(nextHarmony);
6991 : }
6992 :
6993 0 : apply();
6994 0 : startEditText(nextHarmony);
6995 0 : showItem(nextHarmony);
6996 : }
6997 :
6998 : //! NOTE: Copied from ScoreView::harmonyTab
6999 0 : void NotationInteraction::navigateToHarmonyInNearMeasure(MoveDirection direction)
7000 : {
7001 0 : Harmony* harmony = editedHarmony();
7002 0 : if (!harmony) {
7003 0 : return;
7004 : }
7005 :
7006 0 : Segment* segment = harmonySegment(harmony);
7007 0 : if (!segment) {
7008 0 : LOGD("harmonyTicksTab: no segment");
7009 0 : return;
7010 : }
7011 :
7012 : // moving to next/prev measure
7013 0 : Measure* measure = segment->measure();
7014 0 : if (measure) {
7015 0 : if (direction == MoveDirection::Left) {
7016 0 : measure = measure->prevMeasure();
7017 : } else {
7018 0 : measure = measure->nextMeasure();
7019 : }
7020 : }
7021 :
7022 0 : if (!measure) {
7023 0 : LOGD("no prev/next measure");
7024 0 : return;
7025 : }
7026 :
7027 0 : segment = measure->findSegment(mu::engraving::SegmentType::ChordRest, measure->tick());
7028 0 : if (!segment) {
7029 0 : LOGD("no ChordRest segment as measure");
7030 0 : return;
7031 : }
7032 :
7033 0 : track_idx_t track = harmony->track();
7034 :
7035 0 : doEndEditElement();
7036 :
7037 0 : mu::engraving::Harmony* nextHarmony = findHarmonyInSegment(segment, track, harmony->textStyleType());
7038 0 : if (!nextHarmony) {
7039 0 : nextHarmony = createHarmony(segment, track, harmony->harmonyType());
7040 :
7041 0 : startEdit(TranslatableString("undoableAction", "Navigate to next chord symbol"));
7042 0 : score()->undoAddElement(nextHarmony);
7043 0 : apply();
7044 : }
7045 :
7046 0 : startEditText(nextHarmony);
7047 0 : showItem(nextHarmony);
7048 : }
7049 :
7050 : //! NOTE: Copied from ScoreView::harmonyBeatsTab
7051 0 : void NotationInteraction::navigateToHarmony(const Fraction& ticks)
7052 : {
7053 0 : Harmony* harmony = editedHarmony();
7054 0 : if (!harmony) {
7055 0 : return;
7056 : }
7057 :
7058 0 : Segment* segment = harmonySegment(harmony);
7059 0 : if (!segment) {
7060 0 : LOGD("no segment");
7061 0 : return;
7062 : }
7063 :
7064 0 : Measure* measure = segment->measure();
7065 :
7066 0 : Fraction newTick = segment->tick() + ticks;
7067 :
7068 : // find the measure containing the target tick
7069 0 : while (newTick >= measure->endTick()) {
7070 0 : measure = measure->nextMeasure();
7071 0 : if (!measure) {
7072 0 : LOGD("no next measure");
7073 0 : return;
7074 : }
7075 : }
7076 :
7077 : // look for a segment at this tick; if none, create one
7078 0 : while (segment && segment->tick() < newTick) {
7079 0 : segment = segment->next1(mu::engraving::SegmentType::ChordRest);
7080 : }
7081 :
7082 0 : doEndEditElement();
7083 :
7084 0 : startEdit(TranslatableString("undoableAction", "Navigate to chord symbol"));
7085 :
7086 0 : if (!segment || segment->tick() > newTick) { // no ChordRest segment at this tick
7087 0 : segment = measure->undoGetSegment(SegmentType::ChordRest, newTick);
7088 : }
7089 :
7090 0 : engraving::track_idx_t track = harmony->track();
7091 :
7092 0 : mu::engraving::Harmony* nextHarmony = findHarmonyInSegment(segment, track, harmony->textStyleType());
7093 0 : if (!nextHarmony) {
7094 0 : nextHarmony = createHarmony(segment, track, harmony->harmonyType());
7095 0 : score()->undoAddElement(nextHarmony);
7096 : }
7097 :
7098 0 : apply();
7099 0 : startEditText(nextHarmony);
7100 0 : showItem(nextHarmony);
7101 : }
7102 :
7103 : //! NOTE: Copied from ScoreView::figuredBassTab
7104 0 : void NotationInteraction::navigateToNearFiguredBass(MoveDirection direction)
7105 : {
7106 0 : mu::engraving::FiguredBass* fb = mu::engraving::toFiguredBass(m_editData.element);
7107 0 : mu::engraving::Segment* segm = fb->segment();
7108 0 : track_idx_t track = fb->track();
7109 0 : bool backDirection = direction == MoveDirection::Left;
7110 :
7111 0 : if (!segm) {
7112 0 : LOGD("figuredBassTab: no segment");
7113 0 : return;
7114 : }
7115 :
7116 : // search next chord segment in same staff
7117 0 : mu::engraving::Segment* nextSegm = backDirection ? segm->prev1(mu::engraving::SegmentType::ChordRest) : segm->next1(
7118 0 : mu::engraving::SegmentType::ChordRest);
7119 0 : track_idx_t minTrack = trackZeroVoice(track);
7120 0 : track_idx_t maxTrack = minTrack + VOICES - 1;
7121 :
7122 0 : while (nextSegm) { // look for a ChordRest in the compatible track range
7123 0 : if (nextSegm->hasAnnotationOrElement(ElementType::FIGURED_BASS, minTrack, maxTrack)) {
7124 0 : break;
7125 : }
7126 0 : nextSegm = backDirection ? nextSegm->prev1(mu::engraving::SegmentType::ChordRest) : nextSegm->next1(
7127 : mu::engraving::SegmentType::ChordRest);
7128 : }
7129 :
7130 0 : if (!nextSegm) {
7131 0 : LOGD("figuredBassTab: no prev/next segment");
7132 0 : return;
7133 : }
7134 :
7135 0 : doEndEditElement();
7136 :
7137 0 : bool bNew = false;
7138 : // add a (new) FB element, using chord duration as default duration
7139 0 : mu::engraving::FiguredBass* fbNew = mu::engraving::FiguredBass::addFiguredBassToSegment(nextSegm, track, Fraction(0, 1), &bNew);
7140 0 : if (bNew) {
7141 0 : startEdit(TranslatableString("undoableAction", "Navigate to next figured bass"));
7142 0 : score()->undoAddElement(fbNew);
7143 0 : apply();
7144 : }
7145 :
7146 0 : startEditText(fbNew);
7147 0 : showItem(fbNew);
7148 : }
7149 :
7150 : //! NOTE: Copied from ScoreView::figuredBassTab
7151 0 : void NotationInteraction::navigateToFiguredBassInNearMeasure(MoveDirection direction)
7152 : {
7153 0 : mu::engraving::FiguredBass* fb = mu::engraving::toFiguredBass(m_editData.element);
7154 0 : mu::engraving::Segment* segm = fb->segment();
7155 :
7156 0 : if (!segm) {
7157 0 : LOGD("figuredBassTab: no segment");
7158 0 : return;
7159 : }
7160 :
7161 : // if moving to next/prev measure
7162 0 : Measure* meas = segm->measure();
7163 0 : if (meas) {
7164 0 : if (direction == MoveDirection::Left) {
7165 0 : meas = meas->prevMeasure();
7166 : } else {
7167 0 : meas = meas->nextMeasure();
7168 : }
7169 : }
7170 0 : if (!meas) {
7171 0 : LOGD("figuredBassTab: no prev/next measure");
7172 0 : return;
7173 : }
7174 : // find initial ChordRest segment
7175 0 : mu::engraving::Segment* nextSegm = meas->findSegment(mu::engraving::SegmentType::ChordRest, meas->tick());
7176 0 : if (!nextSegm) {
7177 0 : LOGD("figuredBassTab: no ChordRest segment at measure");
7178 0 : return;
7179 : }
7180 :
7181 0 : doEndEditElement();
7182 :
7183 0 : bool bNew = false;
7184 : // add a (new) FB element, using chord duration as default duration
7185 0 : mu::engraving::FiguredBass* fbNew = mu::engraving::FiguredBass::addFiguredBassToSegment(nextSegm, fb->track(), Fraction(0, 1), &bNew);
7186 0 : if (bNew) {
7187 0 : startEdit(TranslatableString("undoableAction", "Navigate to next figured bass"));
7188 0 : score()->undoAddElement(fbNew);
7189 0 : apply();
7190 : }
7191 :
7192 0 : startEditText(fbNew);
7193 0 : showItem(fbNew);
7194 : }
7195 :
7196 : //! NOTE: Copied from ScoreView::figuredBassTicksTab
7197 0 : void NotationInteraction::navigateToFiguredBass(const Fraction& ticks)
7198 : {
7199 0 : mu::engraving::FiguredBass* fb = mu::engraving::toFiguredBass(m_editData.element);
7200 0 : track_idx_t track = fb->track();
7201 0 : mu::engraving::Segment* segm = fb->segment();
7202 0 : if (!segm) {
7203 0 : LOGD("figuredBassTicksTab: no segment");
7204 0 : return;
7205 : }
7206 0 : Measure* measure = segm->measure();
7207 :
7208 0 : Fraction nextSegTick = segm->tick() + ticks;
7209 :
7210 : // find the measure containing the target tick
7211 0 : while (nextSegTick >= measure->endTick()) {
7212 0 : measure = measure->nextMeasure();
7213 0 : if (!measure) {
7214 0 : LOGD("figuredBassTicksTab: no next measure");
7215 0 : return;
7216 : }
7217 : }
7218 :
7219 : // look for a segment at this tick; if none, create one
7220 0 : mu::engraving::Segment* nextSegm = segm;
7221 0 : while (nextSegm && nextSegm->tick() < nextSegTick) {
7222 0 : nextSegm = nextSegm->next1(mu::engraving::SegmentType::ChordRest);
7223 : }
7224 :
7225 0 : if (!nextSegm || nextSegm->tick() > nextSegTick) { // no ChordRest segm at this tick
7226 0 : nextSegm = measure->undoGetSegment(SegmentType::ChordRest, nextSegTick);
7227 0 : if (!nextSegm) {
7228 0 : LOGD("figuredBassTicksTab: no next segment");
7229 0 : return;
7230 : }
7231 : }
7232 :
7233 0 : doEndEditElement();
7234 :
7235 0 : startEdit(TranslatableString("undoableAction", "Navigate to figured bass"));
7236 :
7237 0 : bool bNew = false;
7238 0 : mu::engraving::FiguredBass* fbNew = mu::engraving::FiguredBass::addFiguredBassToSegment(nextSegm, track, ticks, &bNew);
7239 0 : if (bNew) {
7240 0 : score()->undoAddElement(fbNew);
7241 : }
7242 :
7243 0 : apply();
7244 0 : startEditText(fbNew);
7245 0 : showItem(fbNew);
7246 : }
7247 :
7248 : //! NOTE: Copied from ScoreView::textTab
7249 0 : void NotationInteraction::navigateToNearText(MoveDirection direction)
7250 : {
7251 0 : mu::engraving::EngravingItem* oe = m_editData.element;
7252 0 : if (!oe || !oe->isTextBase()) {
7253 0 : return;
7254 : }
7255 :
7256 0 : mu::engraving::EngravingItem* op = toEngravingItem(oe->parent());
7257 0 : if (!op || !(op->isSegment() || op->isNote())) {
7258 0 : LOGD("navigateToNearText: parent not note or segment.");
7259 0 : return;
7260 : }
7261 :
7262 0 : TextBase* ot = mu::engraving::toTextBase(oe);
7263 0 : mu::engraving::TextStyleType textStyleType = ot->textStyleType();
7264 0 : ElementType type = ot->type();
7265 0 : mu::engraving::staff_idx_t staffIdx = ot->staffIdx();
7266 0 : bool back = direction == MoveDirection::Left;
7267 0 : int minTrack = static_cast<int>(trackZeroVoice(oe->track()));
7268 0 : int maxTrack = minTrack + VOICES - 1;
7269 :
7270 0 : mu::engraving::EngravingItem* el = nullptr;
7271 :
7272 0 : if (op->isNote()) {
7273 : // go to next/prev note in same chord, or go to next/prev chord, which may be in another voice
7274 0 : Note* origNote = toNote(op);
7275 0 : Chord* ch = origNote->chord();
7276 0 : const std::vector<Note*>& notes = ch->notes();
7277 :
7278 : // first, try going to prev/next note in the current chord
7279 0 : if (origNote != (back ? notes.back() : notes.front())) {
7280 0 : auto it = std::find(notes.begin(), notes.end(), origNote);
7281 0 : if (it != notes.end()) {
7282 0 : el = back ? *std::next(it) : *std::prev(it);
7283 : }
7284 : }
7285 :
7286 : // next, try going to next/prev grace note chord in the same group as the current
7287 0 : const std::vector<Chord*> chordList = ch->allGraceChordsOfMainChord();
7288 :
7289 0 : if (!el && ch != (back ? chordList.front() : chordList.back())) {
7290 0 : auto it = std::find(chordList.begin(), chordList.end(), ch);
7291 0 : if (it != chordList.end()) {
7292 0 : if (back) {
7293 0 : const Chord* targetChord = *std::prev(it);
7294 0 : el = targetChord->notes().front();
7295 : } else {
7296 0 : const Chord* targetChord = *std::next(it);
7297 0 : el = targetChord->notes().back();
7298 : }
7299 : }
7300 : }
7301 :
7302 : // next, try going to prev/next chord in another voice
7303 0 : if (!el) {
7304 0 : Segment* seg = ch->segment();
7305 0 : if (!seg) {
7306 0 : LOGD("navigateToNearText: no segment");
7307 0 : return;
7308 : }
7309 0 : int inc = back ? -1 : 1;
7310 0 : int sTrack = int(oe->track()) + inc;
7311 0 : int eTrack = back ? minTrack : maxTrack;
7312 0 : for (int track = sTrack; back ? (track >= eTrack) : (track <= eTrack); track += inc) {
7313 0 : EngravingItem* e = seg->element(track);
7314 0 : if (e && e->isChord()) {
7315 0 : const std::vector<Chord*> targetChordList = toChord(e)->allGraceChordsOfMainChord();
7316 0 : if (back) {
7317 0 : Chord* targetChord = targetChordList.back();
7318 0 : el = targetChord->notes().front();
7319 : } else {
7320 0 : Chord* targetChord = targetChordList.front();
7321 0 : el = targetChord->notes().back();
7322 : }
7323 0 : break;
7324 0 : }
7325 : }
7326 : }
7327 :
7328 : // finally, try going to chord in prev/next segments
7329 0 : if (!el) {
7330 0 : Segment* seg = ch->segment();
7331 0 : seg = back ? seg->prev1(SegmentType::ChordRest) : seg->next1(SegmentType::ChordRest);
7332 0 : int sTrack = back ? maxTrack : minTrack;
7333 0 : int eTrack = back ? minTrack : maxTrack;
7334 0 : int inc = back ? -1 : 1;
7335 0 : while (seg) {
7336 0 : for (int track = sTrack; back ? (track >= eTrack) : (track <= eTrack); track += inc) {
7337 0 : EngravingItem* e = seg->element(track);
7338 0 : if (e && e->isChord()) {
7339 0 : const std::vector<Chord*> targetChordList = toChord(e)->allGraceChordsOfMainChord();
7340 0 : if (back) {
7341 0 : Chord* targetChord = targetChordList.back();
7342 0 : el = targetChord->notes().front();
7343 : } else {
7344 0 : Chord* targetChord = targetChordList.front();
7345 0 : el = targetChord->notes().back();
7346 : }
7347 0 : break;
7348 0 : }
7349 : }
7350 :
7351 0 : if (el) {
7352 0 : break;
7353 : }
7354 :
7355 0 : seg = back ? seg->prev1(SegmentType::ChordRest) : seg->next1(SegmentType::ChordRest);
7356 : }
7357 : }
7358 0 : } else if (op->isSegment()) {
7359 0 : Segment* seg = toSegment(op);
7360 0 : seg = back ? seg->prev1(SegmentType::ChordRest) : seg->next1(SegmentType::ChordRest);
7361 :
7362 : // go to first segment with a chord or an existing text
7363 0 : while (seg) {
7364 0 : for (int track = minTrack; track <= maxTrack; ++track) {
7365 0 : EngravingItem* e = seg->element(track);
7366 0 : if (e && e->isChord()) {
7367 0 : el = e;
7368 0 : break;
7369 : }
7370 : }
7371 0 : if (el) {
7372 0 : break;
7373 : }
7374 :
7375 : // this segment only contains rests, check for existing text
7376 0 : for (EngravingItem* e : seg->annotations()) {
7377 0 : if (e->staffIdx() != staffIdx || e->type() != type) {
7378 0 : continue;
7379 : }
7380 0 : TextBase* nt = mu::engraving::toTextBase(e);
7381 0 : if (nt->textStyleType() == textStyleType) {
7382 0 : el = seg->firstElement(staffIdx);
7383 0 : break;
7384 : }
7385 : }
7386 0 : if (el) {
7387 0 : break;
7388 : }
7389 :
7390 0 : seg = back ? seg->prev1(SegmentType::ChordRest) : seg->next1(SegmentType::ChordRest);
7391 : }
7392 : }
7393 :
7394 0 : if (!el) {
7395 0 : return;
7396 : }
7397 :
7398 : // get existing text to edit
7399 0 : EngravingItem* textEl = nullptr;
7400 0 : if (op->isNote()) {
7401 0 : if (!el->isNote()) {
7402 0 : LOGD("navigateToNearText: new element is not Note.");
7403 0 : return;
7404 : }
7405 : // check element list of new note
7406 0 : for (mu::engraving::EngravingItem* e : toNote(el)->el()) {
7407 0 : if (e->type() != type) {
7408 0 : continue;
7409 : }
7410 0 : TextBase* nt = mu::engraving::toTextBase(e);
7411 0 : if (nt->textStyleType() == textStyleType) {
7412 0 : textEl = e;
7413 0 : break;
7414 : }
7415 : }
7416 0 : } else if (op->isSegment()) {
7417 0 : if (!el->isChordRest()) {
7418 0 : LOGD("navigateToNearText: new element is not ChordRest.");
7419 0 : return;
7420 : }
7421 : // check annotation list of new segment
7422 0 : mu::engraving::Segment* ns = toChordRest(el)->segment();
7423 0 : for (mu::engraving::EngravingItem* e : ns->annotations()) {
7424 0 : if (e->staffIdx() != staffIdx || e->type() != type) {
7425 0 : continue;
7426 : }
7427 0 : TextBase* nt = mu::engraving::toTextBase(e);
7428 0 : if (nt->textStyleType() == textStyleType) {
7429 0 : textEl = e;
7430 0 : break;
7431 : }
7432 : }
7433 : }
7434 :
7435 0 : doEndEditElement();
7436 :
7437 0 : if (textEl) {
7438 : // edit existing text
7439 0 : TextBase* text = toTextBase(textEl);
7440 :
7441 0 : if (text) {
7442 0 : startEditText(text);
7443 0 : text->selectAll();
7444 0 : showItem(text);
7445 : }
7446 : } else {
7447 : // add new text if no existing element to edit
7448 : // TODO: for tempo text, would be better to create empty tempo element
7449 0 : if (type != ElementType::TEMPO_TEXT) {
7450 0 : addTextToItem(textStyleType, el);
7451 : }
7452 : }
7453 : }
7454 :
7455 0 : void NotationInteraction::addMelisma()
7456 : {
7457 0 : if (!m_editData.element || !m_editData.element->isLyrics()) {
7458 0 : LOGW("addMelisma called with invalid current element");
7459 0 : return;
7460 : }
7461 0 : const EditLyrics::InitialState state = EditLyrics::initialState(toLyrics(m_editData.element));
7462 :
7463 0 : endEditText();
7464 :
7465 0 : const TranslatableString actionName("undoableAction", "Enter lyrics extension line");
7466 0 : EditLyrics::MelismaEnds ends;
7467 0 : transaction(actionName, [&](Transaction& tx) {
7468 0 : ends = EditLyrics::addMelisma(tx, score(), state);
7469 0 : });
7470 :
7471 0 : if (ends.isNewNextLyrics) {
7472 0 : transaction(actionName, [&](Transaction&) {
7473 0 : score()->undoAddElement(ends.nextLyrics);
7474 0 : });
7475 : }
7476 :
7477 0 : if (ends.nextLyrics) {
7478 0 : score()->select(ends.nextLyrics, SelectType::SINGLE, 0);
7479 0 : startEditText(ends.nextLyrics, PointF());
7480 0 : ends.nextLyrics->selectAll();
7481 0 : } else if (ends.fromLyrics) {
7482 0 : score()->select(ends.fromLyrics, SelectType::SINGLE, 0);
7483 : }
7484 0 : }
7485 :
7486 0 : void NotationInteraction::addLyricsVerse()
7487 : {
7488 0 : if (!m_editData.element || !m_editData.element->isLyrics()) {
7489 0 : LOGW("nextLyricVerse called with invalid current element");
7490 0 : return;
7491 : }
7492 0 : const EditLyrics::InitialState state = EditLyrics::initialState(toLyrics(m_editData.element));
7493 :
7494 0 : endEditText();
7495 :
7496 0 : Lyrics* lyrics = nullptr;
7497 0 : transaction(TranslatableString("undoableAction", "Add lyrics verse"), [&](Transaction& tx) {
7498 0 : lyrics = EditLyrics::addVerse(tx, score(), state);
7499 0 : });
7500 :
7501 0 : score()->select(lyrics, SelectType::SINGLE, 0);
7502 0 : startEditText(lyrics, PointF());
7503 : }
7504 :
7505 0 : void NotationInteraction::addGuitarBend(GuitarBendType bendType)
7506 : {
7507 0 : Score* score = this->score();
7508 0 : IF_ASSERT_FAILED(score) {
7509 0 : MScore::setError(MsError::NO_NOTE_SELECTED);
7510 0 : checkAndShowError();
7511 0 : return;
7512 : }
7513 :
7514 0 : const Selection& selection = score->selection();
7515 0 : const std::vector<Note*>& noteList = selection.noteList();
7516 0 : if (selection.isNone() || noteList.empty()) {
7517 0 : MScore::setError(MsError::NO_NOTE_SELECTED);
7518 0 : checkAndShowError();
7519 0 : return;
7520 : }
7521 :
7522 0 : startEdit(TranslatableString("undoableAction", "Enter guitar bend"));
7523 :
7524 0 : Note* startNote = nullptr;
7525 0 : Note* endNote = nullptr;
7526 0 : bool noteToNote = false;
7527 0 : if (selection.isList() && noteList.size() == 2) {
7528 0 : startNote = noteList.front();
7529 0 : endNote = noteList.back();
7530 0 : if (endNote->tick() > startNote->tick()) {
7531 0 : noteToNote = true;
7532 : }
7533 : }
7534 :
7535 0 : mu::engraving::GuitarBend* guitarBend = nullptr;
7536 0 : if (noteToNote) {
7537 0 : guitarBend = score->addGuitarBend(bendType, startNote, endNote);
7538 : } else {
7539 0 : for (Note* note : noteList) {
7540 : // (will select the last one)
7541 0 : guitarBend = score->addGuitarBend(bendType, note, nullptr);
7542 : }
7543 : }
7544 :
7545 0 : if (guitarBend) {
7546 0 : apply();
7547 0 : select({ guitarBend });
7548 : } else {
7549 0 : rollback();
7550 : }
7551 0 : }
7552 :
7553 0 : void NotationInteraction::addFretboardDiagram()
7554 : {
7555 0 : Score* score = this->score();
7556 0 : IF_ASSERT_FAILED(score) {
7557 0 : MScore::setError(MsError::NO_NOTE_REST_HARMONY_SELECTED);
7558 0 : checkAndShowError();
7559 0 : return;
7560 : };
7561 :
7562 0 : auto selection = this->selection();
7563 0 : std::vector<EngravingItem*> filteredElements;
7564 :
7565 0 : if (selection && !selection->isNone()) {
7566 0 : std::vector<EngravingItem*> selectedElements;
7567 :
7568 0 : if (EngravingItem* element = selection->element()) {
7569 0 : selectedElements = { element };
7570 : } else {
7571 0 : selectedElements = selection->elements();
7572 : }
7573 :
7574 0 : for (EngravingItem* element : selectedElements) {
7575 0 : if (!element || !element->isHarmony()) {
7576 0 : continue;
7577 : }
7578 :
7579 0 : if (!element->ownershipParent()->isFretDiagram()) {
7580 0 : filteredElements.emplace_back(element);
7581 : }
7582 : }
7583 0 : }
7584 :
7585 0 : if (filteredElements.empty()) {
7586 0 : MScore::setError(MsError::NO_NOTE_REST_HARMONY_SELECTED);
7587 0 : checkAndShowError();
7588 0 : return;
7589 : }
7590 :
7591 0 : startEdit(TranslatableString("undoableAction", "Add fretboard diagram"));
7592 :
7593 0 : engraving::FretDiagram* lastAddedDiagram = nullptr;
7594 0 : std::vector<engraving::FretDiagram*> created;
7595 :
7596 0 : for (EngravingItem* element : filteredElements) {
7597 0 : engraving::FretDiagram* diagram = engraving::Factory::createFretDiagram(score->dummy());
7598 0 : diagram->setTrack(element->track());
7599 :
7600 0 : Harmony* harmony = toHarmony(element);
7601 0 : diagram->updateDiagram(harmony->harmonyName());
7602 :
7603 0 : diagram->setOwnershipParent(parentOrDummy(harmony->getParentSeg(), score->dummy()));
7604 0 : score->undoAddElement(diagram);
7605 0 : created.push_back(diagram);
7606 0 : lastAddedDiagram = diagram;
7607 : }
7608 :
7609 0 : for (int i = int(created.size()) - 1; i >= 0; --i) {
7610 0 : FretDiagram* diagram = created[i];
7611 0 : Harmony* harmony = toHarmony(filteredElements[i]);
7612 :
7613 0 : harmony->undoResetProperty(Pid::OFFSET);
7614 0 : harmony->undoChangeProperty(Pid::ALIGN, Align(AlignH::HCENTER, AlignV::BASELINE));
7615 0 : if (harmony->propertyFlags(Pid::ALIGN) == PropertyFlags::STYLED) {
7616 0 : harmony->setPropertyFlags(Pid::ALIGN, PropertyFlags::UNSTYLED);
7617 : }
7618 :
7619 0 : score->undoChangeParent(harmony, diagram,
7620 0 : track2staff(filteredElements[i]->track()));
7621 : }
7622 :
7623 0 : apply();
7624 :
7625 0 : if (lastAddedDiagram) {
7626 0 : select({ lastAddedDiagram });
7627 : }
7628 0 : }
7629 :
7630 0 : Harmony* NotationInteraction::editedHarmony() const
7631 : {
7632 0 : Harmony* harmony = toHarmony(m_editData.element);
7633 0 : if (!harmony) {
7634 0 : return nullptr;
7635 : }
7636 :
7637 0 : if (!harmony->parent() || (!harmony->parent()->isSegment()
7638 0 : && !harmony->parent()->isFretDiagram())) {
7639 0 : LOGD("no segment parent");
7640 0 : return nullptr;
7641 : }
7642 :
7643 0 : return harmony;
7644 : }
7645 :
7646 0 : Segment* NotationInteraction::harmonySegment(const Harmony* harmony) const
7647 : {
7648 0 : if (!harmony || !harmony->parent()) {
7649 0 : return nullptr;
7650 : }
7651 :
7652 0 : EngravingObject* parent = harmony->parent();
7653 0 : Segment* segment = parent->isSegment() ? toSegment(parent) : nullptr;
7654 0 : if (!segment && parent->isFretDiagram()) {
7655 0 : segment = toFretDiagram(parent)->segment();
7656 : }
7657 :
7658 0 : return segment;
7659 : }
7660 :
7661 0 : mu::engraving::Harmony* NotationInteraction::findHarmonyInSegment(const mu::engraving::Segment* segment, track_idx_t track,
7662 : mu::engraving::TextStyleType textStyleType) const
7663 : {
7664 0 : for (mu::engraving::EngravingItem* e : segment->annotations()) {
7665 0 : if (!e->isHarmony() && !e->isFretDiagram()) {
7666 0 : continue;
7667 : }
7668 :
7669 0 : Harmony* harmony = e->isHarmony() ? toHarmony(e) : nullptr;
7670 0 : if (e->isFretDiagram()) {
7671 0 : harmony = toFretDiagram(e)->harmony();
7672 : }
7673 :
7674 0 : if (!harmony) {
7675 0 : continue;
7676 : }
7677 :
7678 0 : if (harmony->track() == track && harmony->textStyleType() == textStyleType) {
7679 0 : return harmony;
7680 : }
7681 : }
7682 :
7683 0 : return nullptr;
7684 : }
7685 :
7686 0 : mu::engraving::Harmony* NotationInteraction::createHarmony(mu::engraving::Segment* segment, track_idx_t track,
7687 : mu::engraving::HarmonyType type) const
7688 : {
7689 0 : mu::engraving::Harmony* harmony = Factory::createHarmony(segment);
7690 0 : harmony->setScore(score());
7691 0 : harmony->setTrack(track);
7692 0 : harmony->setHarmonyType(type);
7693 :
7694 0 : return harmony;
7695 : }
7696 :
7697 0 : void NotationInteraction::startEditText(mu::engraving::TextBase* text)
7698 : {
7699 0 : doEndEditElement();
7700 0 : select({ text }, SelectType::SINGLE);
7701 :
7702 : //! NOTE: Copied from ScoreView::cmdAddText
7703 0 : Measure* measure = text->findMeasure();
7704 0 : if (measure && measure->hasMMRest() && text->links()) {
7705 0 : Measure* mmRest = measure->mmRest();
7706 0 : for (EngravingObject* link : *text->links()) {
7707 0 : TextBase* linkedText = toTextBase(link);
7708 0 : if (text != linkedText && linkedText->findMeasure() == mmRest) {
7709 0 : text = linkedText;
7710 0 : break;
7711 : }
7712 : }
7713 : }
7714 :
7715 0 : startEditText(text, PointF());
7716 0 : text->cursor()->moveCursorToEnd();
7717 0 : }
7718 :
7719 0 : bool NotationInteraction::needEndTextEdit() const
7720 : {
7721 0 : if (isTextEditingStarted()) {
7722 0 : const mu::engraving::TextBase* text = mu::engraving::toTextBase(m_editData.element);
7723 0 : return !text || !text->cursor()->editing();
7724 : }
7725 :
7726 0 : return false;
7727 : }
7728 :
7729 0 : void NotationInteraction::toggleFontStyle(mu::engraving::FontStyle style)
7730 : {
7731 0 : if (!m_editData.element || !m_editData.element->isTextBase()) {
7732 0 : LOGW("toggleFontStyle called with invalid current element");
7733 0 : return;
7734 : }
7735 0 : mu::engraving::TextBase* text = toTextBase(m_editData.element);
7736 0 : int currentStyle = text->getProperty(mu::engraving::Pid::FONT_STYLE).toInt();
7737 0 : score()->startCmd(TranslatableString("undoableAction", "Format text"));
7738 0 : text->undoChangeProperty(mu::engraving::Pid::FONT_STYLE, PropertyValue::fromValue(
7739 0 : currentStyle ^ static_cast<int>(style)), mu::engraving::PropertyFlags::UNSTYLED);
7740 0 : score()->endCmd();
7741 0 : notifyAboutTextEditingChanged();
7742 : }
7743 :
7744 0 : void NotationInteraction::toggleVerticalAlignment(VerticalAlignment align)
7745 : {
7746 0 : if (!m_editData.element || !m_editData.element->isTextBase()) {
7747 0 : LOGW("toggleVerticalAlignment called with invalid current element");
7748 0 : return;
7749 : }
7750 0 : mu::engraving::TextBase* text = toTextBase(m_editData.element);
7751 0 : int ialign = static_cast<int>(align);
7752 0 : int currentAlign = text->getProperty(mu::engraving::Pid::TEXT_SCRIPT_ALIGN).toInt();
7753 :
7754 0 : TranslatableString actionName = [align]() {
7755 0 : switch (align) {
7756 0 : case VerticalAlignment::AlignSubScript:
7757 0 : return TranslatableString("undoableAction", "Toggle subscript");
7758 0 : case VerticalAlignment::AlignSuperScript:
7759 0 : return TranslatableString("undoableAction", "Toggle superscript");
7760 0 : default:
7761 0 : return TranslatableString("undoableAction", "Toggle subscript/superscript");
7762 : }
7763 0 : }();
7764 :
7765 0 : score()->startCmd(actionName);
7766 0 : text->undoChangeProperty(mu::engraving::Pid::TEXT_SCRIPT_ALIGN, PropertyValue::fromValue(
7767 0 : (currentAlign == ialign) ? static_cast<int>(VerticalAlignment::AlignNormal) : ialign),
7768 : mu::engraving::PropertyFlags::UNSTYLED);
7769 0 : score()->endCmd();
7770 0 : notifyAboutTextEditingChanged();
7771 0 : }
7772 :
7773 0 : void NotationInteraction::toggleBold()
7774 : {
7775 0 : toggleFontStyle(mu::engraving::FontStyle::Bold);
7776 0 : }
7777 :
7778 0 : void NotationInteraction::toggleItalic()
7779 : {
7780 0 : toggleFontStyle(mu::engraving::FontStyle::Italic);
7781 0 : }
7782 :
7783 0 : void NotationInteraction::toggleUnderline()
7784 : {
7785 0 : toggleFontStyle(mu::engraving::FontStyle::Underline);
7786 0 : }
7787 :
7788 0 : void NotationInteraction::toggleStrike()
7789 : {
7790 0 : toggleFontStyle(mu::engraving::FontStyle::Strike);
7791 0 : }
7792 :
7793 0 : void NotationInteraction::toggleSubScript()
7794 : {
7795 0 : toggleVerticalAlignment(VerticalAlignment::AlignSubScript);
7796 0 : }
7797 :
7798 0 : void NotationInteraction::toggleSuperScript()
7799 : {
7800 0 : toggleVerticalAlignment(VerticalAlignment::AlignSuperScript);
7801 0 : }
7802 :
7803 : template<typename P>
7804 0 : void NotationInteraction::execute(void (mu::engraving::Score::* function)(P), P param, const TranslatableString& actionName)
7805 : {
7806 0 : startEdit(actionName);
7807 0 : (score()->*function)(param);
7808 0 : apply();
7809 0 : }
7810 :
7811 0 : void NotationInteraction::toggleArticulation(mu::engraving::SymId symId)
7812 : {
7813 0 : startEdit(TranslatableString("undoableAction", "Toggle articulation"));
7814 0 : mu::engraving::EditChord::toggleArticulation(score(), symId);
7815 0 : apply();
7816 0 : }
7817 :
7818 0 : void NotationInteraction::toggleOrnament(OrnamentType type)
7819 : {
7820 0 : startEdit(TranslatableString("undoableAction", "Toggle ornament"));
7821 0 : SymId symId = static_cast<SymId>(type);
7822 0 : mu::engraving::EditNote::toggleOrnament(score(), symId);
7823 0 : apply();
7824 0 : }
7825 :
7826 0 : void NotationInteraction::toggleAutoplace(bool all)
7827 : {
7828 0 : execute(&mu::engraving::Score::cmdToggleAutoplace, all, TranslatableString("undoableAction", "Toggle automatic placement"));
7829 0 : }
7830 :
7831 0 : bool NotationInteraction::canInsertClef(ClefType type) const
7832 : {
7833 0 : const Score* score = this->score();
7834 0 : return score && mu::engraving::EditClef::canInsertClef(score, type);
7835 : }
7836 :
7837 0 : void NotationInteraction::insertClef(ClefType type)
7838 : {
7839 0 : transaction(TranslatableString("undoableAction", "Add clef"), [&](Transaction& tx) {
7840 0 : mu::engraving::EditClef::insertClef(tx, score(), type);
7841 0 : });
7842 0 : }
7843 :
7844 0 : void NotationInteraction::changeAccidental(mu::engraving::AccidentalType accidental)
7845 : {
7846 0 : transaction(TranslatableString("undoableAction", "Add accidental"), [&](auto& ) {
7847 0 : mu::engraving::EditNote::changeAccidental(score(), accidental);
7848 0 : });
7849 0 : }
7850 :
7851 0 : void NotationInteraction::transposeSemitone(int steps)
7852 : {
7853 0 : transaction(TranslatableString("undoableAction", "Transpose semitone"), [&](auto& tx) {
7854 0 : Transpose::transposeSemitone(tx, score(), steps);
7855 0 : });
7856 0 : }
7857 :
7858 0 : void NotationInteraction::transposeDiatonicAlterations(mu::engraving::TransposeDirection direction)
7859 : {
7860 0 : transaction(TranslatableString("undoableAction", "Transpose diatonically"), [&](auto& tx) {
7861 0 : Transpose::transposeDiatonicAlterations(tx, score(), direction);
7862 0 : });
7863 0 : }
7864 :
7865 0 : void NotationInteraction::showLocation()
7866 : {
7867 0 : auto* e = score()->selection().element();
7868 0 : if (!e) {
7869 : // no current selection - restore lost selection
7870 0 : e = score()->selection().currentCR();
7871 0 : if (e && e->isChord()) {
7872 0 : e = toChord(e)->upNote();
7873 : }
7874 : }
7875 0 : if (!e) {
7876 0 : e = Navigation::firstElement(score(), false);
7877 : }
7878 0 : if (e) {
7879 0 : if (e->isNote() || e->isHarmony()) {
7880 0 : score()->setPlayNote(true);
7881 : }
7882 0 : select({ e }, SelectType::SINGLE);
7883 0 : showItem(e);
7884 : }
7885 0 : }
7886 :
7887 0 : void NotationInteraction::execute(void (mu::engraving::Score::* function)(), const TranslatableString& actionName)
7888 : {
7889 0 : startEdit(actionName);
7890 0 : (score()->*function)();
7891 0 : apply();
7892 0 : }
7893 :
7894 : //! NOTE: Copied from ScoreView::adjustCanvasPosition
7895 0 : void NotationInteraction::showItem(const mu::engraving::EngravingItem* el, int staffIndex)
7896 : {
7897 0 : if (!el) {
7898 0 : return;
7899 : }
7900 :
7901 0 : if (!configuration()->isAutomaticallyPanEnabled()) {
7902 0 : return;
7903 : }
7904 :
7905 0 : const mu::engraving::MeasureBase* m = nullptr;
7906 :
7907 0 : if (el->isNote()) {
7908 0 : m = toNote(el)->chord()->measure();
7909 0 : } else if (el->isRest()) {
7910 0 : m = toRest(el)->measure();
7911 0 : } else if (el->isChord()) {
7912 0 : m = toChord(el)->measure();
7913 0 : } else if (el->isSegment()) {
7914 0 : m = toSegment(el)->measure();
7915 0 : } else if (el->isLyrics()) {
7916 0 : m = toLyrics(el)->measure();
7917 0 : } else if ((el->isHarmony() || el->isFiguredBass()) && el->parent()->isSegment()) {
7918 0 : m = toSegment(el->parent())->measure();
7919 0 : } else if (el->isHarmony() && el->parent()->isFretDiagram() && el->parent()->parent()->isSegment()) {
7920 0 : m = toSegment(el->parent()->parent())->measure();
7921 0 : } else if (el->isMeasureBase()) {
7922 0 : m = toMeasureBase(el);
7923 0 : } else if (el->isSpannerSegment()) {
7924 0 : EngravingItem* se = toSpannerSegment(el)->spanner()->startElement();
7925 0 : m = se->findMeasure();
7926 0 : } else if (el->isSpanner()) {
7927 0 : EngravingItem* se = toSpanner(el)->startElement();
7928 0 : m = se->findMeasure();
7929 0 : } else if (el->isPage()) {
7930 0 : const mu::engraving::Page* p = toPage(el);
7931 0 : mu::engraving::System* s = !p->systems().empty() ? p->systems().front() : nullptr;
7932 0 : m = s && !s->measures().empty() ? s->measures().front() : nullptr;
7933 : } else {
7934 : // attempt to find measure
7935 0 : mu::engraving::EngravingObject* e = el->parent();
7936 0 : while (e && !e->isMeasureBase()) {
7937 0 : e = e->parent();
7938 : }
7939 0 : if (e) {
7940 0 : m = toMeasureBase(e);
7941 : } else {
7942 0 : return;
7943 : }
7944 : }
7945 0 : if (!m) {
7946 0 : return;
7947 : }
7948 :
7949 0 : mu::engraving::System* sys = m->system();
7950 0 : if (!sys) {
7951 0 : return;
7952 : }
7953 :
7954 0 : RectF mRect(m->canvasBoundingRect());
7955 0 : RectF sysRect = mRect;
7956 :
7957 0 : double _spatium = score()->style().spatium();
7958 0 : const qreal border = _spatium * 3;
7959 0 : RectF showRect;
7960 0 : if (staffIndex == -1) {
7961 0 : showRect = RectF(mRect.x(), sysRect.y(), mRect.width(), sysRect.height())
7962 0 : .adjusted(-border, -border, border, border);
7963 : } else {
7964 : // find a box for the individual stave in a system
7965 0 : RectF stave = RectF(sys->canvasBoundingRect().left(),
7966 : sys->staffCanvasYpage(staffIndex),
7967 : sys->width(),
7968 0 : sys->staff(staffIndex)->bbox().height());
7969 0 : showRect = mRect.intersected(stave).adjusted(-border, -border, border, border);
7970 : }
7971 :
7972 0 : ShowItemRequest request;
7973 0 : request.item = el;
7974 0 : request.showRect = showRect;
7975 :
7976 0 : m_showItemRequested.send(request);
7977 : }
7978 :
7979 0 : void NotationInteraction::toggleDebugShowGapRests()
7980 : {
7981 : // Doesn't perform any action on the score, just triggers the necessary relayout
7982 0 : startEdit(TranslatableString("debugOption", "Toggle show gap rests"));
7983 0 : score()->setLayoutAll();
7984 0 : apply();
7985 0 : }
7986 :
7987 0 : muse::async::Channel<NotationInteraction::ShowItemRequest> NotationInteraction::showItemRequested() const
7988 : {
7989 0 : return m_showItemRequested;
7990 : }
7991 :
7992 0 : void NotationInteraction::setGetViewRectFunc(const std::function<RectF()>& func)
7993 : {
7994 0 : static_cast<NotationNoteInput*>(m_noteInput.get())->setGetViewRectFunc(func);
7995 0 : }
7996 :
7997 0 : void NotationInteraction::checkAndShowError()
7998 : {
7999 0 : IF_ASSERT_FAILED(m_errorsController) {
8000 0 : return;
8001 : }
8002 0 : m_errorsController->checkAndShowMScoreError();
8003 : }
|