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) 2023 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 : #include <cfloat>
23 : #include <unordered_set>
24 :
25 : #include "systemlayout.h"
26 :
27 : #include "realfn.h"
28 :
29 : #include "style/defaultstyle.h"
30 :
31 : #include "dom/barline.h"
32 : #include "dom/beam.h"
33 : #include "dom/box.h"
34 : #include "dom/bracket.h"
35 : #include "dom/bracketitem.h"
36 : #include "dom/chord.h"
37 : #include "dom/dynamic.h"
38 : #include "dom/factory.h"
39 : #include "dom/guitarbend.h"
40 : #include "dom/instrumentname.h"
41 : #include "dom/layoutbreak.h"
42 : #include "dom/lyrics.h"
43 : #include "dom/measure.h"
44 : #include "dom/measurenumber.h"
45 : #include "dom/mmrest.h"
46 : #include "dom/mmrestrange.h"
47 : #include "dom/note.h"
48 : #include "dom/ornament.h"
49 : #include "dom/page.h"
50 : #include "dom/pagelockindicator.h"
51 : #include "dom/part.h"
52 : #include "dom/parenthesis.h"
53 : #include "dom/pedal.h"
54 : #include "dom/playcounttext.h"
55 : #include "dom/rest.h"
56 : #include "dom/score.h"
57 : #include "dom/slur.h"
58 : #include "dom/spacer.h"
59 : #include "dom/staff.h"
60 : #include "dom/stafflines.h"
61 : #include "dom/system.h"
62 : #include "dom/systemlockindicator.h"
63 : #include "dom/tie.h"
64 : #include "dom/timesig.h"
65 : #include "dom/tremolosinglechord.h"
66 : #include "dom/tremolotwochord.h"
67 : #include "dom/tuplet.h"
68 : #include "dom/volta.h"
69 : #include "dom/whammybar.h"
70 :
71 : #include "tlayout.h"
72 : #include "alignmentlayout.h"
73 : #include "autoplace.h"
74 : #include "beamlayout.h"
75 : #include "beamtremololayout.h"
76 : #include "boxlayout.h"
77 : #include "chordlayout.h"
78 : #include "guitarbendlayout.h"
79 : #include "guitardivelayout.h"
80 : #include "harmonylayout.h"
81 : #include "lyricslayout.h"
82 : #include "measurelayout.h"
83 : #include "mmrestlayout.h"
84 : #include "tupletlayout.h"
85 : #include "restlayout.h"
86 : #include "slurtielayout.h"
87 : #include "horizontalspacing.h"
88 : #include "dynamicslayout.h"
89 : #include "stavesharinglayout.h"
90 : #include "systemheaderlayout.h"
91 :
92 : #include "defer.h"
93 : #include "log.h"
94 :
95 : using namespace mu::engraving;
96 : using namespace mu::engraving::rendering::score;
97 :
98 : //---------------------------------------------------------
99 : // collectSystem
100 : //---------------------------------------------------------
101 :
102 14397 : System* SystemLayout::collectSystem(LayoutContext& ctx)
103 : {
104 14412 : TRACEFUNC;
105 :
106 14397 : if (!ctx.state().curMeasure()) {
107 3982 : return nullptr;
108 : }
109 :
110 10415 : const MeasureBase* measure = ctx.dom().systems().empty() ? 0 : ctx.dom().systems().back()->measures().back();
111 10415 : if (measure) {
112 6137 : measure = measure->mbWithPrecedingSectionBreak();
113 : }
114 :
115 10415 : bool firstSysLongName = ctx.conf().styleV(Sid::firstSystemInstNameVisibility).value<InstrumentLabelVisibility>()
116 10415 : == InstrumentLabelVisibility::LONG;
117 10415 : if (measure) {
118 3650 : ctx.mutState().setFirstSystem(measure->sectionBreak() && !ctx.conf().isFloatMode());
119 3650 : if (const LayoutBreak* layoutBreak = measure->sectionBreakElement()) {
120 116 : ctx.mutState().setFirstSystemIndent(ctx.state().firstSystem()
121 58 : && ctx.conf().firstSystemIndent()
122 116 : && layoutBreak->firstSystemIndentation());
123 116 : ctx.mutState().setStartWithLongNames(
124 58 : ctx.state().firstSystem() && firstSysLongName && layoutBreak->startWithLongNames());
125 : }
126 : } else {
127 6765 : ctx.mutState().setStartWithLongNames(ctx.state().firstSystem() && firstSysLongName);
128 : }
129 :
130 10415 : System* system = getNextSystem(ctx);
131 23141 : for (SysStaff* staff : system->staves()) {
132 12726 : staff->skyline().clear();
133 : }
134 :
135 : LAYOUT_CALL() << LAYOUT_ITEM_INFO(system);
136 :
137 10415 : double curSysWidth = 0.0;
138 10415 : double leadingHBoxesWidth = 0.0;
139 10415 : double targetSystemWidth = ctx.conf().styleD(Sid::pagePrintableWidth) * DPI;
140 10415 : system->setWidth(targetSystemWidth);
141 :
142 : // save state of measure
143 10415 : MeasureBase* breakMeasure = nullptr;
144 :
145 10415 : System* oldSystem = nullptr;
146 :
147 10415 : MeasureState prevMeasureState;
148 10415 : prevMeasureState.curHeader = ctx.state().curMeasure()->header();
149 10415 : prevMeasureState.curTrailer = ctx.state().curMeasure()->trailer();
150 :
151 10415 : const RangeLock* systemLock = ctx.conf().viewMode() == LayoutMode::PAGE || ctx.conf().viewMode() == LayoutMode::SYSTEM
152 10415 : ? ctx.dom().systemLocks()->lockStartingAt(ctx.state().curMeasure()) : nullptr;
153 :
154 10415 : if (systemLock) {
155 79 : StaveSharingLayout::updateStaveSharingForFullSystem(systemLock->startMB(), systemLock->endMB(), ctx);
156 : }
157 :
158 38177 : while (ctx.state().curMeasure()) { // collect measure for system
159 38177 : oldSystem = ctx.mutState().curMeasure()->system();
160 38177 : system->appendMeasure(ctx.mutState().curMeasure());
161 :
162 38177 : bool sharedTrackMapChanged = false;
163 38177 : if (!systemLock) {
164 87883 : for (Part* p : ctx.dom().parts()) {
165 50048 : if (p->isSharedPart()) {
166 659 : SharedPart* sp = toSharedPart(p);
167 659 : prevMeasureState.staveSharingStates[sp] = sp->exactStaveSharingStateAtTick(ctx.mutState().curMeasure()->tick());
168 : }
169 : }
170 :
171 37835 : sharedTrackMapChanged = StaveSharingLayout::updateStaveSharingForLastAddedMeasure(system, ctx);
172 : }
173 :
174 38177 : MeasureLayout::layoutMeasure(ctx.mutState().curMeasure(), ctx);
175 :
176 38177 : if (ctx.state().curMeasure()->isMeasure()) {
177 35554 : Measure* m = toMeasure(ctx.mutState().curMeasure());
178 35554 : if (!(oldSystem && oldSystem->page() && oldSystem->page() != ctx.state().page())) {
179 35541 : MeasureLayout::computePreSpacingItems(m, ctx);
180 : }
181 :
182 35554 : if (measureHasCrossStuffOrModifiedBeams(m)) {
183 13 : updateCrossBeams(system, ctx);
184 : }
185 :
186 35554 : if (m->isFirstInSystem()) {
187 7933 : leadingHBoxesWidth = curSysWidth;
188 7933 : SystemLayout::layoutSystem(system, ctx, curSysWidth);
189 7933 : MeasureLayout::addSystemHeader(m, ctx.state().firstSystem(), ctx);
190 : } else {
191 27621 : bool createHeader = ctx.state().prevMeasure()->isHBox() && toHBox(ctx.state().prevMeasure())->createSystemHeader();
192 27621 : if (createHeader) {
193 47 : MeasureLayout::addSystemHeader(m, false, ctx);
194 27574 : } else if (m->header()) {
195 812 : MeasureLayout::removeSystemHeader(m);
196 : }
197 : }
198 :
199 35554 : MeasureLayout::createEndBarLines(m, true, ctx);
200 :
201 35554 : if (m->noBreak() || systemLock) {
202 429 : MeasureLayout::removeSystemTrailer(m, ctx);
203 : } else {
204 35125 : MeasureLayout::addSystemTrailer(m, m->nextMeasure(), ctx);
205 : }
206 :
207 35554 : MeasureLayout::setRepeatCourtesiesAndParens(m, ctx);
208 :
209 35554 : MeasureLayout::updateGraceNotes(m, ctx);
210 :
211 35554 : if (!systemLock) {
212 35217 : curSysWidth = HorizontalSpacing::updateSpacingForLastAddedMeasure(system);
213 : }
214 2623 : } else if (ctx.state().curMeasure()->isHBox()) {
215 149 : if (!systemLock) {
216 144 : curSysWidth = HorizontalSpacing::updateSpacingForLastAddedMeasure(system);
217 : }
218 : } else {
219 : // vbox:
220 2474 : MeasureLayout::getNextMeasure(ctx);
221 2474 : SystemLayout::layout2(system, ctx); // compute staff distances
222 2474 : return system;
223 : }
224 :
225 35361 : bool doBreak = !systemLock && system->measures().size() > 1 && curSysWidth > targetSystemWidth
226 71064 : && !ctx.state().prevMeasure()->noBreak();
227 35703 : if (doBreak) {
228 1877 : breakMeasure = ctx.mutState().curMeasure();
229 1877 : system->removeLastMeasure();
230 1877 : ctx.mutState().curMeasure()->setSystem(oldSystem);
231 1877 : while (ctx.state().prevMeasure() && ctx.state().prevMeasure()->noBreak() && system->measures().size() > 1) {
232 0 : ctx.mutState().setTick(ctx.state().tick() - ctx.state().curMeasure()->ticks());
233 0 : if (ctx.state().curMeasure()->isMeasure()) {
234 0 : ctx.mutState().setMeasureNumber(toMeasure(ctx.state().curMeasure())->measureNumber());
235 : }
236 :
237 0 : ctx.mutState().setNextMeasure(ctx.mutState().curMeasure());
238 0 : ctx.mutState().setCurMeasure(ctx.mutState().prevMeasure());
239 0 : ctx.mutState().setPrevMeasure(ctx.mutState().curMeasure()->prev());
240 :
241 0 : system->removeLastMeasure();
242 0 : ctx.mutState().curMeasure()->setSystem(oldSystem);
243 : }
244 : // re-align voice offsets for the evicted measures' real system, in case it never gets rebuilt in this pass
245 4934 : for (staff_idx_t staffIdx = 0; staffIdx < ctx.dom().nstaves(); ++staffIdx) {
246 3057 : ChordLayout::layoutVoiceOffsets(oldSystem, staffIdx, ctx);
247 : }
248 :
249 1877 : if (sharedTrackMapChanged) {
250 : // The last added measure caused sharedTrackMap to change. Now we are removing that measure so we must restore it.
251 : // If this causes another change to the track map, relayout measures within the system
252 12 : if (StaveSharingLayout::updateStaveSharingForFullSystem(system->first(), system->last(), ctx)) {
253 0 : StaveSharingLayout::relayoutMeasuresOnTrackMapChanged(system, ctx);
254 : }
255 : }
256 :
257 1877 : break;
258 : }
259 :
260 33826 : if (oldSystem && system != oldSystem && muse::contains(ctx.state().systemList(), oldSystem)) {
261 48 : oldSystem->clear();
262 : }
263 :
264 33826 : if (ctx.state().prevMeasure() && ctx.state().prevMeasure()->isMeasure() && ctx.state().prevMeasure()->system() == system) {
265 25770 : Measure* m = toMeasure(ctx.mutState().prevMeasure());
266 :
267 25770 : MeasureLayout::createEndBarLines(m, false, ctx);
268 :
269 25770 : if (m->trailer()) {
270 400 : MeasureLayout::removeSystemTrailer(m, ctx);
271 : }
272 :
273 25770 : MeasureLayout::setRepeatCourtesiesAndParens(m, ctx);
274 :
275 25770 : MeasureLayout::updateGraceNotes(m, ctx);
276 :
277 25770 : if (!systemLock) {
278 25511 : curSysWidth = HorizontalSpacing::updateSpacingForLastAddedMeasure(system);
279 : }
280 :
281 25770 : if (ctx.state().curMeasure()->isMeasure()) {
282 25701 : MeasureLayout::updateKeySignatures(toMeasure(ctx.state().curMeasure()), ctx);
283 : }
284 : }
285 :
286 33826 : const MeasureBase* mb = ctx.state().curMeasure();
287 33826 : const MeasureBase* next = mb->nextMM();
288 33826 : bool lineBreak = false;
289 33826 : switch (ctx.conf().viewMode()) {
290 33826 : case LayoutMode::PAGE:
291 : case LayoutMode::SYSTEM:
292 67628 : lineBreak = mb->pageBreak() || mb->lineBreak() || mb->sectionBreak() || mb->isEndOfSystemLock() || mb->isEndOfPageLock()
293 67628 : || (next && next->isStartOfSystemLock()) || (next && next->isStartOfPageLock());
294 33826 : break;
295 0 : case LayoutMode::FLOAT:
296 : case LayoutMode::LINE:
297 : case LayoutMode::HORIZONTAL_FIXED:
298 0 : lineBreak = false;
299 0 : break;
300 : }
301 :
302 : // preserve state of next measure (which is about to become current measure)
303 33826 : if (ctx.state().nextMeasure()) {
304 29644 : MeasureBase* nmb = ctx.mutState().nextMeasure();
305 29644 : if (nmb->isMeasure() && ctx.conf().styleB(Sid::createMultiMeasureRests)) {
306 441 : Measure* nm = toMeasure(nmb);
307 441 : if (nm->hasMMRest()) {
308 86 : nmb = nm->mmRest();
309 : }
310 : }
311 29644 : if (nmb->isMeasure()) {
312 29491 : prevMeasureState.clear();
313 29491 : prevMeasureState.measure = toMeasure(nmb);
314 29491 : prevMeasureState.measurePos = nmb->x();
315 29491 : prevMeasureState.measureWidth = nmb->width();
316 105807 : for (Segment& seg : toMeasure(nmb)->segments()) {
317 76316 : prevMeasureState.elementPositions.emplace(&seg, seg.ldata()->pos());
318 76316 : prevMeasureState.elementWidths.emplace(&seg, seg.width());
319 81074 : for (EngravingItem* item : seg.annotations()) {
320 4758 : if (item->isHarmony() || item->isFretDiagram()) {
321 2323 : prevMeasureState.elementPositions.emplace(item, item->ldata()->pos());
322 : }
323 : }
324 : }
325 : }
326 29644 : if (!ctx.state().curMeasure()->noBreak()) {
327 : // current measure is not a nobreak,
328 : // so next measure could possibly start a system
329 29552 : prevMeasureState.curHeader = nmb->header();
330 : }
331 29644 : if (!nmb->noBreak()) {
332 : // next measure is not a nobreak
333 : // so it could possibly end a system
334 29552 : prevMeasureState.curTrailer = nmb->trailer();
335 : }
336 : }
337 :
338 33826 : MeasureLayout::getNextMeasure(ctx);
339 :
340 : // ElementType nt = lc.curMeasure ? lc.curMeasure->type() : ElementType::INVALID;
341 33826 : mb = ctx.state().curMeasure();
342 33826 : if (lineBreak || !mb || mb->isVBoxBase()) {
343 6064 : break;
344 : }
345 : }
346 :
347 7941 : assert(ctx.state().prevMeasure());
348 :
349 7941 : if (ctx.state().endTick() < ctx.state().prevMeasure()->tick()) {
350 : // we've processed the entire range
351 : // but we need to continue layout until we reach a system whose last measure is the same as previous layout
352 496 : MeasureBase* curMB = ctx.mutState().curMeasure();
353 496 : Measure* m = curMB && curMB->isMeasure() ? toMeasure(curMB) : nullptr;
354 496 : bool curMeasureMayHaveJoinedBeams = m && BeamLayout::measureMayHaveBeamsJoinedIntoNext(m);
355 496 : if (ctx.state().prevMeasure() == ctx.state().systemOldMeasure() && !curMeasureMayHaveJoinedBeams) {
356 : // If current measure has possible beams joining to the next, we need to continue layout. This needs a better solution in future. [M.S.]
357 : // this system ends in the same place as the previous layout
358 : // ok to stop
359 431 : if (m) {
360 : // we may have previously processed first measure(s) of next system
361 : // so now we must restore to original state
362 214 : if (m->repeatStart()) {
363 3 : Segment* s = m->findSegmentR(SegmentType::StartRepeatBarLine, Fraction(0, 1));
364 3 : if (!s->enabled()) {
365 0 : s->setEnabled(true);
366 : }
367 : }
368 214 : const MeasureBase* pbmb = ctx.state().prevMeasure()->mbWithPrecedingSectionBreak();
369 214 : bool localFirstSystem = pbmb->sectionBreak() && !ctx.conf().isMode(LayoutMode::FLOAT);
370 214 : MeasureBase* nm = breakMeasure ? breakMeasure : m;
371 214 : if (prevMeasureState.curHeader) {
372 214 : MeasureLayout::addSystemHeader(m, localFirstSystem, ctx);
373 : } else {
374 0 : MeasureLayout::removeSystemHeader(m);
375 : }
376 : for (;;) {
377 : // TODO: what if the nobreak group takes the entire system - is this correct?
378 214 : if (prevMeasureState.curTrailer && !m->noBreak()) {
379 0 : MeasureLayout::addSystemTrailer(m, m->nextMeasure(), ctx);
380 : } else {
381 214 : MeasureLayout::removeSystemTrailer(m, ctx);
382 : }
383 :
384 214 : MeasureLayout::setRepeatCourtesiesAndParens(m, ctx);
385 :
386 214 : MeasureLayout::updateGraceNotes(m, ctx);
387 :
388 214 : prevMeasureState.restoreMeasure(ctx);
389 214 : MeasureLayout::layoutMeasureElements(m, ctx);
390 214 : BeamLayout::restoreBeams(m, ctx);
391 214 : SystemLayout::restoreOldSystemLayout(m->system(), ctx);
392 :
393 214 : if (m == nm || !m->noBreak()) {
394 214 : break;
395 : }
396 0 : m = m->nextMeasure();
397 : }
398 : }
399 431 : ctx.mutState().setRangeDone(true);
400 : }
401 : }
402 :
403 7941 : if (ctx.dom().allStavesInvisible()) {
404 : // Edge case. Can only happen if all instruments have been deleted.
405 4 : return system;
406 : }
407 :
408 : /*************************************************************
409 : * SYSTEM NOW HAS A COMPLETE SET OF MEASURES
410 : * Now perform all operation to finalize system.
411 : * **********************************************************/
412 :
413 : // Break cross-measure beams
414 7937 : if (ctx.state().prevMeasure() && ctx.state().prevMeasure()->isMeasure()) {
415 7905 : Measure* pm = toMeasure(ctx.mutState().prevMeasure());
416 7905 : BeamLayout::breakCrossMeasureBeams(pm, ctx);
417 : }
418 :
419 : // Hide empty staves
420 7937 : hideEmptyStaves(system, ctx, ctx.state().firstSystem());
421 :
422 : // Re-create shapes to account for newly hidden/unhidden staves
423 : // (and for potential forgotten shape updates, for example in MeasureLayout::setRepeatCourtesiesAndParens)
424 41663 : for (MeasureBase* mb : system->measures()) {
425 33726 : if (mb->isMeasure()) {
426 163029 : for (Segment& seg : toMeasure(mb)->segments()) {
427 129450 : seg.createShapes();
428 : }
429 : }
430 : }
431 :
432 : // Relayout system to account for newly hidden/unhidden staves
433 7937 : SystemLayout::layoutSystem(system, ctx, leadingHBoxesWidth);
434 :
435 : // Create end barlines and system trailer if needed (cautionary time/key signatures etc)
436 7937 : Measure* lm = system->lastMeasure();
437 7937 : if (lm) {
438 7929 : MeasureLayout::createEndBarLines(lm, true, ctx);
439 7929 : Measure* nm = lm->nextMeasure();
440 7929 : if (nm) {
441 3735 : MeasureLayout::addSystemTrailer(lm, nm, ctx);
442 : }
443 : }
444 :
445 7937 : updateTimeSigAboveStavesXPos(system, ctx);
446 :
447 : // Recompute spacing to account for the last changes (barlines, hidden staves, etc)
448 7937 : curSysWidth = HorizontalSpacing::computeSpacingForFullSystem(system);
449 :
450 7937 : if (curSysWidth > targetSystemWidth) {
451 3 : HorizontalSpacing::squeezeSystemToFit(system, curSysWidth, targetSystemWidth);
452 : }
453 :
454 7937 : if (shouldBeJustified(system, curSysWidth, targetSystemWidth, ctx)) {
455 6831 : HorizontalSpacing::justifySystem(system, curSysWidth, targetSystemWidth);
456 : }
457 :
458 7937 : clearBigTimeSigNotShown(system, ctx);
459 :
460 : // LAYOUT MEASURES
461 7937 : bool createBrackets = false;
462 41663 : for (MeasureBase* mb : system->measures()) {
463 33726 : if (mb->isMeasure()) {
464 33579 : mb->setSystem(system);
465 33579 : Measure* m = toMeasure(mb);
466 33579 : MeasureLayout::layoutMeasureElements(m, ctx);
467 33579 : MeasureLayout::layoutStaffLines(m, ctx);
468 33579 : if (createBrackets) {
469 99 : SystemHeaderLayout::addBrackets(system, toMeasure(mb), ctx);
470 99 : createBrackets = false;
471 : }
472 147 : } else if (mb->isHBox()) {
473 147 : HBox* curHBox = toHBox(mb);
474 147 : TLayout::layoutMeasureBase(curHBox, ctx);
475 147 : createBrackets = curHBox->createSystemHeader();
476 : }
477 : }
478 :
479 : // re-align voice offsets now that the system's final measure set is known
480 20505 : for (staff_idx_t staffIdx = 0; staffIdx < ctx.dom().nstaves(); ++staffIdx) {
481 12568 : ChordLayout::layoutVoiceOffsets(system, staffIdx, ctx);
482 : }
483 :
484 7937 : layoutSystemElements(system, ctx);
485 7937 : SystemLayout::layout2(system, ctx); // compute staff distances
486 :
487 8368 : if (ctx.state().rangeDone() && oldSystem && !oldSystem->measures().empty() && oldSystem->measures().front()->tick() >= system->endTick()
488 8368 : && !(oldSystem->page() && oldSystem->page() != ctx.state().page())) {
489 : // We may have unfinished layouts of certain elements in the next system
490 : // - ties & bends (in LayoutChords::updateLineAttachPoints())
491 : // - fret diagrams & harmony (in layoutMeasure)
492 : // Restore them to the correct state.
493 88 : SystemLayout::restoreOldSystemLayout(oldSystem, ctx);
494 : }
495 :
496 7937 : return system;
497 14397 : }
498 :
499 7937 : bool SystemLayout::shouldBeJustified(System* system, double curSysWidth, double targetSystemWidth, LayoutContext& ctx)
500 : {
501 7937 : bool shouldJustify = true;
502 :
503 7937 : MeasureBase* lm = system->measures().back();
504 7937 : if ((curSysWidth / targetSystemWidth) < ctx.conf().styleD(Sid::lastSystemFillLimit)) {
505 1350 : shouldJustify = false;
506 1350 : const MeasureBase* lastMb = ctx.state().curMeasure();
507 :
508 : // For systems with a section break, don't justify
509 1350 : if (lm && lm->sectionBreak()) {
510 6 : lastMb = nullptr;
511 : }
512 :
513 : // Justify if system is followed by a measure or HBox
514 1379 : while (lastMb) {
515 273 : if (lastMb->isMeasure() || lastMb->isHBox()) {
516 244 : shouldJustify = true;
517 244 : break;
518 : }
519 : // Frames can contain section breaks too, account for that here
520 29 : if (lastMb->sectionBreak()) {
521 0 : shouldJustify = false;
522 0 : break;
523 : }
524 29 : lastMb = lastMb->nextMeasure();
525 : }
526 : }
527 :
528 7937 : return shouldJustify && !MScore::noHorizontalStretch;
529 : }
530 :
531 11516 : void SystemLayout::layoutSystemLockIndicators(System* system, LayoutContext& ctx)
532 : {
533 : UNUSED(ctx);
534 :
535 11516 : const std::vector<SystemLockIndicator*> lockIndicators = system->systemLockIndicators();
536 : // In PAGE view, at most ONE lock indicator can exist per system.
537 11516 : assert(lockIndicators.size() <= 1);
538 11516 : system->deleteSystemLockIndicators();
539 :
540 11516 : const RangeLock* lock = system->systemLock();
541 11516 : if (!lock) {
542 11417 : return;
543 : }
544 :
545 99 : SystemLockIndicator* lockIndicator = Factory::createSystemLockIndicator(system, lock);
546 99 : lockIndicator->setTrack(0);
547 99 : system->addSystemLockIndicator(lockIndicator);
548 :
549 99 : TLayout::layoutSystemIndicatorIcon(lockIndicator, lockIndicator->mutldata());
550 11516 : }
551 :
552 11516 : void SystemLayout::layoutPageLockIndicators(System* system)
553 : {
554 11516 : Page* page = system->page();
555 11516 : system->deletePageLockIndicator();
556 :
557 11516 : IF_ASSERT_FAILED(!page->systems().empty()) {
558 0 : return;
559 : }
560 :
561 11516 : const RangeLock* lock = page->pageLock();
562 11516 : if (!lock || page->systems().back() != system) {
563 11460 : return;
564 : }
565 :
566 56 : PageLockIndicator* lockIndicator = Factory::createPageLockIndicator(system, lock);
567 56 : lockIndicator->setTrack(0);
568 56 : system->setPageLockIndicator(lockIndicator);
569 :
570 56 : TLayout::layoutPageLockIndicator(lockIndicator, lockIndicator->mutldata());
571 : }
572 :
573 : //---------------------------------------------------------
574 : // getNextSystem
575 : //---------------------------------------------------------
576 :
577 10415 : System* SystemLayout::getNextSystem(LayoutContext& ctx)
578 : {
579 10415 : bool isVBox = ctx.state().curMeasure()->isVBox();
580 10415 : System* system = nullptr;
581 10415 : if (ctx.state().systemList().empty()) {
582 8956 : system = Factory::createSystem(ctx.mutDom().score());
583 8956 : ctx.mutState().setSystemOldMeasure(nullptr);
584 : } else {
585 1459 : system = muse::takeFirst(ctx.mutState().systemList());
586 1459 : ctx.mutState().setSystemOldMeasure(system->measures().empty() ? 0 : system->measures().back());
587 1459 : system->clear(); // remove measures from system
588 : }
589 10415 : ctx.mutDom().systems().push_back(system);
590 10415 : if (!isVBox) {
591 8084 : size_t nstaves = ctx.dom().nstaves();
592 8084 : system->adjustStavesNumber(nstaves);
593 20807 : for (staff_idx_t i = 0; i < nstaves; ++i) {
594 12723 : system->staff(i)->setShow(ctx.dom().staff(i)->show());
595 : }
596 : }
597 10415 : return system;
598 : }
599 :
600 : enum class StaffHideMode {
601 : HIDE_WHEN_STAFF_EMPTY,
602 : HIDE_WHEN_INSTRUMENT_EMPTY,
603 : ALWAYS_SHOW
604 : };
605 :
606 6693 : static StaffHideMode computeHideMode(const System* system, const Staff* staff, const staff_idx_t staffIdx, const bool globalHideIfEmpty,
607 : bool& hasSystemSpecificOverrides)
608 : {
609 6693 : if (Part* part = staff->part(); part && part->isSharedPart() && staff != part->staves().front()) {
610 241 : return StaffHideMode::HIDE_WHEN_STAFF_EMPTY;
611 : }
612 :
613 : // Check for system-specific overrides
614 6452 : bool hasSystemSpecificOverrideHide = false;
615 6452 : bool hasSystemSpecificOverrideDontHide = false;
616 :
617 32960 : for (const MeasureBase* mb : system->measures()) {
618 26508 : if (!mb->isMeasure()) {
619 94 : continue;
620 : }
621 :
622 26414 : const Measure* measure = toMeasure(mb);
623 26414 : const AutoOnOff hideIfEmpty = measure->hideStaffIfEmpty(staffIdx);
624 :
625 26414 : hasSystemSpecificOverrideHide |= (hideIfEmpty == AutoOnOff::ON);
626 26414 : hasSystemSpecificOverrideDontHide |= (hideIfEmpty == AutoOnOff::OFF);
627 : }
628 :
629 6452 : if (hasSystemSpecificOverrideDontHide) {
630 0 : hasSystemSpecificOverrides = true;
631 0 : return StaffHideMode::ALWAYS_SHOW;
632 6452 : } else if (hasSystemSpecificOverrideHide) {
633 0 : hasSystemSpecificOverrides = true;
634 0 : return StaffHideMode::HIDE_WHEN_STAFF_EMPTY;
635 : }
636 :
637 : // Consider staff setting
638 6452 : AutoOnOff staffHideMode = staff->hideWhenEmpty();
639 6452 : switch (staffHideMode) {
640 9 : case AutoOnOff::ON:
641 9 : return StaffHideMode::HIDE_WHEN_STAFF_EMPTY;
642 6 : case AutoOnOff::OFF:
643 6 : return StaffHideMode::ALWAYS_SHOW;
644 6437 : case AutoOnOff::AUTO:
645 6437 : break;
646 : }
647 :
648 : // Consider part setting
649 6437 : AutoOnOff partHideMode = staff->part()->hideWhenEmpty();
650 6437 : switch (partHideMode) {
651 6 : case AutoOnOff::ON:
652 6 : break;
653 6 : case AutoOnOff::OFF:
654 6 : return StaffHideMode::ALWAYS_SHOW;
655 6425 : case AutoOnOff::AUTO:
656 : // Consider global setting
657 6425 : if (!globalHideIfEmpty) {
658 6381 : return StaffHideMode::ALWAYS_SHOW;
659 : }
660 : }
661 :
662 50 : return staff->part()->hideStavesWhenIndividuallyEmpty()
663 50 : ? StaffHideMode::HIDE_WHEN_STAFF_EMPTY
664 50 : : StaffHideMode::HIDE_WHEN_INSTRUMENT_EMPTY;
665 : }
666 :
667 6693 : static bool computeShowSysStaff(const System* system, const Staff* staff, const staff_idx_t staffIdx,
668 : const Fraction& stick, const SpannerMap::IntervalList& spanners,
669 : const StaffHideMode hideMode)
670 : {
671 6693 : if (hideMode == StaffHideMode::ALWAYS_SHOW) {
672 6393 : return true;
673 : }
674 :
675 : // Check if there are spanners
676 304 : for (const auto& spanner : spanners) {
677 4 : if (spanner.value->staff() == staff
678 0 : && !spanner.value->systemFlag()
679 4 : && !(spanner.stop == stick.ticks() && !spanner.value->isSlur())) {
680 0 : return true;
681 : }
682 : }
683 :
684 : // Check if the staff is empty in the system
685 881 : for (const MeasureBase* m : system->measures()) {
686 637 : if (!m->isMeasure()) {
687 0 : continue;
688 : }
689 637 : const Measure* measure = toMeasure(m);
690 637 : if (!measure->isEmpty(staffIdx)) {
691 56 : return true;
692 : }
693 : }
694 :
695 : // check if notes moved into this staff
696 244 : Part* part = staff->part();
697 244 : const size_t n = part->nstaves();
698 244 : if (n > 1) {
699 235 : staff_idx_t idx = part->staves().front()->idx();
700 729 : for (staff_idx_t i = 0; i < n; ++i) {
701 494 : staff_idx_t st = idx + i;
702 :
703 1644 : for (MeasureBase* mb : system->measures()) {
704 1150 : if (!mb->isMeasure()) {
705 0 : continue;
706 : }
707 :
708 1150 : const Measure* m = toMeasure(mb);
709 1150 : bool empty = m->isEmpty(st);
710 1150 : if (hideMode == StaffHideMode::HIDE_WHEN_INSTRUMENT_EMPTY && !empty) {
711 0 : return true;
712 1150 : } else if (empty) {
713 867 : continue;
714 : }
715 :
716 1575 : for (Segment* s = m->first(SegmentType::ChordRest); s; s = s->next(SegmentType::ChordRest)) {
717 6460 : for (voice_idx_t voice = 0; voice < VOICES; ++voice) {
718 5168 : ChordRest* cr = s->cr(st * VOICES + voice);
719 5168 : int staffMove = cr ? cr->staffMove() : 0;
720 5168 : if (!cr || cr->isRest() || cr->staffMove() == 0) {
721 : // The case staffMove == 0 has already been checked by measure->isEmpty()
722 5168 : continue;
723 : }
724 0 : if (staffIdx == st + staffMove) {
725 0 : return true;
726 : }
727 : }
728 : }
729 : }
730 : }
731 : }
732 :
733 244 : return false;
734 : }
735 :
736 7937 : void SystemLayout::hideEmptyStaves(System* system, LayoutContext& ctx, bool isFirstSystem)
737 : {
738 7937 : if (ctx.dom().nstaves() == 0) {
739 : // No staves, nothing to hide
740 5344 : return;
741 : }
742 :
743 7937 : if (ctx.dom().nstaves() == 1) {
744 : // One staff, show if not manually hidden score-wide
745 5344 : const bool show = ctx.dom().staves().front()->show();
746 5344 : system->staves().front()->setShow(show);
747 5344 : system->setHasStaffVisibilityIndicator(false);
748 5344 : return;
749 : }
750 :
751 2593 : const Fraction stick = system->first()->tick();
752 2593 : const Fraction etick = system->last()->endTick();
753 2593 : const auto& spanners = ctx.dom().spannerMap().findOverlapping(stick.ticks(), etick.ticks() - 1);
754 :
755 2593 : const bool globalHideIfEmpty = ctx.conf().styleB(Sid::hideEmptyStaves)
756 2593 : && !(isFirstSystem && ctx.conf().styleB(Sid::dontHideStavesInFirstSystem));
757 :
758 2593 : bool hasSystemSpecificOverrides = false;
759 2593 : bool hasHiddenStaves = false;
760 2593 : bool systemIsEmpty = true;
761 2593 : staff_idx_t staffIdx = 0;
762 :
763 9817 : for (const Staff* staff : ctx.dom().staves()) {
764 7224 : SysStaff* ss = system->staff(staffIdx);
765 :
766 7224 : DEFER {
767 7224 : ++staffIdx;
768 7224 : };
769 :
770 7224 : if (!staff->show()) {
771 531 : ss->setShow(false);
772 531 : continue;
773 : }
774 :
775 6693 : const StaffHideMode hideMode = computeHideMode(system, staff, staffIdx, globalHideIfEmpty, hasSystemSpecificOverrides);
776 6693 : const bool show = computeShowSysStaff(system, staff, staffIdx, stick, spanners, hideMode);
777 6693 : ss->setShow(show);
778 6693 : if (show) {
779 6449 : systemIsEmpty = false;
780 : } else {
781 244 : hasHiddenStaves = true;
782 : }
783 7224 : }
784 :
785 2593 : system->setHasStaffVisibilityIndicator(hasSystemSpecificOverrides || hasHiddenStaves);
786 :
787 : // If the system is empty, unhide the staves with `showIfEntireSystemEmpty` set to true, if any
788 2593 : const Staff* firstVisible = nullptr;
789 2593 : if (systemIsEmpty) {
790 7 : for (const Staff* staff : ctx.dom().staves()) {
791 6 : SysStaff* ss = system->staff(staff->idx());
792 6 : if (staff->showIfEntireSystemEmpty() && !ss->show()) {
793 0 : ss->setShow(true);
794 0 : systemIsEmpty = false;
795 6 : } else if (!firstVisible && staff->show()) {
796 1 : firstVisible = staff;
797 : }
798 : }
799 : }
800 :
801 : // If there are no such staves, unhide the first one
802 2593 : if (systemIsEmpty) {
803 1 : const Staff* staff = firstVisible ? firstVisible : ctx.dom().staves().front();
804 1 : SysStaff* ss = system->staff(staff->idx());
805 1 : ss->setShow(true);
806 : }
807 : }
808 :
809 0 : bool SystemLayout::canChangeSysStaffVisibility(const System* system, const staff_idx_t staffIdx)
810 : {
811 0 : if (system->staves().size() <= 1) {
812 : // Only one staff; always visible
813 0 : return false;
814 : }
815 :
816 0 : const Staff* staff = system->score()->staff(staffIdx);
817 :
818 0 : if (system->staff(staffIdx)->show()) {
819 : // SysStaff is visible; check if can hide
820 0 : const Fraction stick = system->first()->tick();
821 0 : const Fraction etick = system->last()->endTick();
822 0 : const auto& spanners = system->score()->spannerMap().findOverlapping(stick.ticks(), etick.ticks() - 1);
823 :
824 0 : return !computeShowSysStaff(system, staff, staffIdx, system->first()->tick(), spanners, StaffHideMode::HIDE_WHEN_STAFF_EMPTY);
825 : }
826 :
827 : // SysStaff is hidden; check if can show
828 0 : if (!staff->show()) {
829 0 : return false;
830 : }
831 :
832 0 : return true;
833 : }
834 :
835 7937 : void SystemLayout::updateTimeSigAboveStavesXPos(System* system, LayoutContext& ctx)
836 : {
837 7937 : if (ctx.conf().styleV(Sid::timeSigPlacement).value<TimeSigPlacement>() != TimeSigPlacement::ABOVE_STAVES) {
838 7937 : return;
839 : }
840 :
841 0 : staff_idx_t nstaves = ctx.dom().nstaves();
842 0 : bool centerOnBarline = ctx.conf().styleB(Sid::timeSigCenterOnBarline);
843 :
844 0 : for (MeasureBase* mb : system->measures()) {
845 0 : if (!mb->isMeasure()) {
846 0 : continue;
847 : }
848 0 : Measure* measure = toMeasure(mb);
849 0 : for (Segment& seg : measure->segments()) {
850 0 : if (!seg.isType(SegmentType::TimeSigTypes)) {
851 0 : continue;
852 : }
853 :
854 0 : std::set<TimeSig*> timeSigToKeep;
855 0 : for (staff_idx_t staffIdx = 0; staffIdx < nstaves; ++staffIdx) {
856 0 : TimeSig* timeSig = toTimeSig(seg.element(staff2track(staffIdx)));
857 0 : if (!timeSig || !timeSig->showOnThisStaff()) {
858 0 : continue;
859 : }
860 :
861 0 : timeSigToKeep.insert(timeSig);
862 0 : if (system->staff(staffIdx)->show()) {
863 0 : continue;
864 : }
865 :
866 0 : staff_idx_t nextVisStaff = system->nextVisibleStaff(staffIdx);
867 0 : if (nextVisStaff == muse::nidx) {
868 0 : continue;
869 : }
870 :
871 0 : TimeSig* nextVisTimeSig = toTimeSig(seg.element(staff2track(nextVisStaff)));
872 0 : if (nextVisTimeSig) {
873 0 : timeSigToKeep.insert(nextVisTimeSig);
874 : }
875 : }
876 :
877 0 : Segment* prevBarlineSeg = nullptr;
878 0 : Segment* prevRepeatAnnounceTimeSigSeg = nullptr;
879 0 : if (centerOnBarline) {
880 0 : for (Segment* prevSeg = seg.prev1(); prevSeg && prevSeg->tick() == seg.tick(); prevSeg = prevSeg->prev1()) {
881 0 : if (prevSeg->isEndBarLineType()) {
882 0 : prevBarlineSeg = prevSeg;
883 0 : } else if (prevSeg->isTimeSigRepeatAnnounceType()) {
884 0 : prevRepeatAnnounceTimeSigSeg = prevSeg;
885 : }
886 : }
887 : }
888 :
889 0 : for (staff_idx_t staffIdx = 0; staffIdx < nstaves; ++staffIdx) {
890 0 : TimeSig* timeSig = toTimeSig(seg.element(staff2track(staffIdx)));
891 0 : if (!timeSig) {
892 0 : continue;
893 : }
894 0 : Parenthesis* leftParen = timeSig->leftParen();
895 0 : Parenthesis* rightParen = timeSig->rightParen();
896 0 : if (!muse::contains(timeSigToKeep, timeSig)) {
897 0 : timeSig->mutldata()->reset(); // Eliminates the shape
898 0 : if (leftParen) {
899 0 : leftParen->mutldata()->reset();
900 : }
901 0 : if (rightParen) {
902 0 : rightParen->mutldata()->reset();
903 : }
904 0 : continue;
905 : }
906 :
907 0 : if (prevBarlineSeg && prevBarlineSeg->system() == system && !prevRepeatAnnounceTimeSigSeg) {
908 : // Center timeSig on its segment
909 0 : RectF bbox = timeSig->ldata()->bbox();
910 0 : double newXPos = -0.5 * (bbox.right() + bbox.left());
911 0 : timeSig->mutldata()->setPosX(newXPos);
912 0 : } else if (!seg.isTimeSigRepeatAnnounceType()) {
913 : // Left-align to parenthesis if present
914 0 : double xLeftParens = DBL_MAX;
915 0 : if (leftParen) {
916 0 : xLeftParens = leftParen->x() + leftParen->ldata()->bbox().left();
917 : }
918 0 : if (xLeftParens != DBL_MAX) {
919 0 : timeSig->mutldata()->moveX(-xLeftParens);
920 : }
921 : } else {
922 : // TimeSigRepeatAnnounce: right-align to segment
923 0 : double xRight = -DBL_MAX;
924 0 : xRight = std::max(xRight, timeSig->shape().right() + timeSig->x());
925 0 : if (leftParen) {
926 0 : xRight = std::max(xRight, leftParen->ldata()->bbox().right() + leftParen->x());
927 : }
928 0 : if (rightParen) {
929 0 : xRight = std::max(xRight, rightParen->ldata()->bbox().right() + rightParen->x());
930 : }
931 0 : if (xRight != -DBL_MAX) {
932 0 : timeSig->mutldata()->moveX(-xRight);
933 : }
934 : }
935 : }
936 :
937 0 : seg.createShapes();
938 0 : }
939 : }
940 : }
941 :
942 7937 : void SystemLayout::clearBigTimeSigNotShown(System* system, LayoutContext& ctx)
943 : {
944 7937 : if (ctx.conf().styleV(Sid::timeSigPlacement).value<TimeSigPlacement>() == TimeSigPlacement::NORMAL) {
945 7925 : return;
946 : }
947 :
948 78 : for (MeasureBase* mb : system->measures()) {
949 66 : if (!mb->isMeasure()) {
950 0 : continue;
951 : }
952 238 : for (Segment& seg : toMeasure(mb)->segments()) {
953 172 : if (!seg.isType(SegmentType::TimeSigTypes)) {
954 168 : continue;
955 : }
956 38 : for (staff_idx_t staffIdx = 0; staffIdx < ctx.dom().nstaves(); ++staffIdx) {
957 34 : TimeSig* ts = toTimeSig(seg.element(staff2track(staffIdx)));
958 34 : if (!ts) {
959 0 : continue;
960 : }
961 34 : if (!ts->showOnThisStaff() || ts->effectiveStaffIdx() == muse::nidx) {
962 22 : ts->mutldata()->reset(); // Deletes shape
963 : }
964 : }
965 : }
966 : }
967 : }
968 :
969 8231 : void SystemLayout::layoutSticking(const std::vector<Sticking*> stickings, System* system, LayoutContext& ctx)
970 : {
971 8231 : if (stickings.empty()) {
972 8220 : return;
973 : }
974 :
975 142 : for (Sticking* sticking : stickings) {
976 131 : TLayout::layoutItem(sticking, ctx);
977 : }
978 :
979 11 : std::vector<EngravingItem*> stickingItems(stickings.begin(), stickings.end());
980 11 : AlignmentLayout::alignItemsForSystem(stickingItems, system);
981 11 : }
982 :
983 8231 : void SystemLayout::layoutLyrics(const ElementsToLayout& elements, LayoutContext& ctx)
984 : {
985 8231 : System* system = elements.system;
986 : // NOTE: in continuous view, this means we layout spanners for the entire score.
987 : // TODO: find way to optimize this and only layout where necessary.
988 8231 : Fraction stick = system->measures().front()->tick();
989 8231 : Fraction etick = system->measures().back()->endTick();
990 :
991 8240 : for (Spanner* sp : elements.partialLyricsLines) {
992 9 : TLayout::layoutSystem(sp, system, ctx);
993 : }
994 :
995 : //-------------------------------------------------------------
996 : // Lyric
997 : //-------------------------------------------------------------
998 : // Layout lyrics dashes and melisma
999 : // NOTE: loop on a *copy* of unmanagedSpanners because in some cases
1000 : // the underlying operation may invalidate some of the iterators.
1001 : // TODO: figure out why lyrics lines are in this "unmanagedSpanners" container
1002 8231 : bool dashOnFirstNoteSyllable = ctx.conf().style().styleB(Sid::lyricsShowDashIfSyllableOnFirstNote);
1003 8231 : std::set<Spanner*> unmanagedSpanners = ctx.dom().unmanagedSpanners();
1004 8742 : for (Spanner* sp : unmanagedSpanners) {
1005 511 : if (!sp->systemFlag() && sp->staff() && !sp->staff()->show()) {
1006 0 : continue;
1007 : }
1008 511 : bool dashOnFirst = dashOnFirstNoteSyllable && !toLyricsLine(sp)->isEndMelisma();
1009 511 : if (sp->tick() >= etick || sp->tick2() < stick || (sp->tick2() == stick && !dashOnFirst)) {
1010 156 : continue;
1011 : }
1012 355 : TLayout::layoutSystem(sp, system, ctx);
1013 : }
1014 8231 : LyricsLayout::computeVerticalPositions(system, ctx);
1015 8231 : }
1016 :
1017 8231 : void SystemLayout::layoutVoltas(const ElementsToLayout& elementsToLayout, LayoutContext& ctx)
1018 : {
1019 8231 : System* system = elementsToLayout.system;
1020 :
1021 8231 : processLines(system, ctx, elementsToLayout.voltas);
1022 :
1023 8231 : std::set<Volta*> alignedVoltas;
1024 8607 : for (size_t i = 0; i < elementsToLayout.voltas.size(); ++i) {
1025 376 : Volta* volta1 = toVolta(elementsToLayout.voltas[i]);
1026 376 : if (alignedVoltas.count(volta1)) {
1027 180 : continue;
1028 : }
1029 :
1030 196 : std::vector<EngravingItem*> voltasToAlign;
1031 196 : voltasToAlign.push_back(volta1->backSegment());
1032 :
1033 409 : for (size_t j = i + 1; j < elementsToLayout.voltas.size(); ++j) {
1034 213 : Volta* volta2 = toVolta(elementsToLayout.voltas[j]);
1035 213 : if (volta2->staffIdx() == volta1->staffIdx() && volta2->tick() == volta1->tick2()) {
1036 180 : voltasToAlign.push_back(volta2->frontSegment());
1037 180 : volta1 = volta2;
1038 : }
1039 : }
1040 :
1041 196 : if (voltasToAlign.size() > 1) {
1042 155 : AlignmentLayout::alignItemsGroup(voltasToAlign, system);
1043 490 : for (EngravingItem* vs : voltasToAlign) {
1044 335 : alignedVoltas.insert(toVoltaSegment(vs)->volta());
1045 : }
1046 : }
1047 196 : }
1048 8231 : }
1049 :
1050 8231 : void SystemLayout::layoutDynamicExpressionAndHairpins(const ElementsToLayout& elementsToLayout, LayoutContext& ctx)
1051 : {
1052 8231 : System* system = elementsToLayout.system;
1053 :
1054 8231 : std::vector<EngravingItem*> dynamicsExprAndHairpinsToAlign;
1055 :
1056 9372 : for (Dynamic* dynamic : elementsToLayout.dynamics) {
1057 1141 : TLayout::layoutItem(dynamic, ctx);
1058 1141 : if (dynamic->autoplace()) {
1059 1141 : Autoplace::autoplaceSegmentElement(dynamic, dynamic->mutldata());
1060 1141 : dynamicsExprAndHairpinsToAlign.push_back(dynamic);
1061 : }
1062 : }
1063 :
1064 8265 : for (Expression* e : elementsToLayout.expressions) {
1065 34 : TLayout::layoutItem(e, ctx);
1066 34 : if (e->addToSkyline()) {
1067 34 : dynamicsExprAndHairpinsToAlign.push_back(e);
1068 : }
1069 : }
1070 :
1071 8231 : processLines(system, ctx, elementsToLayout.hairpins);
1072 :
1073 13184 : for (SpannerSegment* spannerSegment : system->spannerSegments()) {
1074 4953 : if (spannerSegment->isHairpinSegment()) {
1075 483 : dynamicsExprAndHairpinsToAlign.push_back(spannerSegment);
1076 : }
1077 : }
1078 :
1079 8231 : AlignmentLayout::alignItemsWithTheirSnappingChain(dynamicsExprAndHairpinsToAlign, system);
1080 8231 : }
1081 :
1082 8231 : void SystemLayout::layoutParenthesisAndBigTimeSigs(const ElementsToLayout& elementsToLayout)
1083 : {
1084 8231 : System* system = elementsToLayout.system;
1085 :
1086 8231 : for (Parenthesis* e : elementsToLayout.parenthesis) {
1087 0 : Segment* s = e->segment();
1088 0 : if (s->isType(SegmentType::TimeSigTypes)) {
1089 0 : EngravingItem* el = s->element(e->track());
1090 0 : TimeSig* timeSig = el ? toTimeSig(el) : nullptr;
1091 0 : if (!timeSig) {
1092 0 : continue;
1093 : }
1094 0 : TimeSigPlacement timeSigPlacement = timeSig->style().styleV(Sid::timeSigPlacement).value<TimeSigPlacement>();
1095 0 : if (timeSigPlacement == TimeSigPlacement::ACROSS_STAVES) {
1096 0 : if (!timeSig->showOnThisStaff()) {
1097 0 : e->mutldata()->reset();
1098 : }
1099 0 : continue;
1100 : }
1101 : }
1102 :
1103 0 : staff_idx_t si = e->staffIdx();
1104 0 : Measure* m = s->measure();
1105 0 : system->staff(si)->skyline().add(e->shape().translate(e->pos() + s->pos() + m->pos() + e->staffOffset()));
1106 : }
1107 :
1108 8231 : for (TimeSig* timeSig : elementsToLayout.timeSigAboveStaves) {
1109 0 : Autoplace::autoplaceSegmentElement(timeSig, timeSig->mutldata());
1110 : }
1111 8231 : }
1112 :
1113 2514 : static void autoplaceHarmony(EngravingItem* harmony)
1114 : {
1115 2514 : FretDiagram* fdParent = harmony->parent()->isFretDiagram() ? toFretDiagram(harmony->parent()) : nullptr;
1116 2514 : if (fdParent && !fdParent->visible()) {
1117 0 : harmony->mutldata()->moveY(-fdParent->pos().y());
1118 : }
1119 2514 : Autoplace::autoplaceSegmentElement(harmony, harmony->mutldata());
1120 2514 : }
1121 :
1122 8201 : void SystemLayout::layoutHarmonies(const std::vector<Harmony*> harmonies, System* system, LayoutContext& ctx)
1123 : {
1124 8201 : if (!ctx.conf().styleB(Sid::verticallyAlignChordSymbols)) {
1125 4926 : for (Harmony* harmony : harmonies) {
1126 1650 : autoplaceHarmony(harmony);
1127 : }
1128 3276 : return;
1129 : }
1130 :
1131 : // Only vertically align one chord symbol per tick & staff
1132 4925 : std::set<std::pair<Fraction, staff_idx_t> > harmonyPositions;
1133 4925 : std::vector<EngravingItem*> harmonyItemsAlign;
1134 4925 : std::vector<EngravingItem*> harmonyItemsNoAlign;
1135 :
1136 5765 : for (Harmony* h : harmonies) {
1137 840 : if (muse::contains(harmonyPositions, { h->tick(), h->staffIdx() })) {
1138 3 : harmonyItemsNoAlign.push_back(h);
1139 3 : continue;
1140 : }
1141 :
1142 837 : TLayout::layoutHarmony(h, h->mutldata(), ctx);
1143 837 : autoplaceHarmony(h);
1144 837 : harmonyItemsAlign.push_back(h);
1145 837 : harmonyPositions.insert({ h->tick(), h->staffIdx() });
1146 : }
1147 :
1148 4925 : AlignmentLayout::alignItemsForSystem(harmonyItemsAlign, system);
1149 :
1150 4928 : for (EngravingItem* harmony : harmonyItemsNoAlign) {
1151 3 : autoplaceHarmony(harmony);
1152 : }
1153 4925 : }
1154 :
1155 103 : void SystemLayout::layoutFretDiagrams(const ElementsToLayout& elements, System* system, LayoutContext& ctx)
1156 : {
1157 103 : if (!ctx.conf().styleB(Sid::verticallyAlignChordSymbols)) {
1158 89 : for (FretDiagram* fretDiag : elements.fretDiagrams) {
1159 59 : Autoplace::autoplaceSegmentElement(fretDiag, fretDiag->mutldata());
1160 : }
1161 :
1162 54 : for (Harmony* harmony : elements.harmonies) {
1163 24 : autoplaceHarmony(harmony);
1164 : }
1165 :
1166 89 : for (FretDiagram* fretDiag : elements.fretDiagrams) {
1167 59 : if (Harmony* harmony = fretDiag->harmony()) {
1168 20 : SkylineLine& skl = system->staff(fretDiag->staffIdx())->skyline().north();
1169 20 : Segment* s = fretDiag->segment();
1170 20 : Shape harmShape = harmony->ldata()->shape().translated(harmony->pos() + fretDiag->pos() + s->pos() + s->measure()->pos());
1171 20 : skl.add(harmShape);
1172 20 : }
1173 : }
1174 :
1175 30 : return;
1176 : }
1177 :
1178 : // Only vertically align one fd per tick & staff
1179 73 : std::set<std::pair<Fraction, staff_idx_t> > fretHarmonyPositions;
1180 73 : std::vector<EngravingItem*> fretItemsAlign;
1181 73 : std::vector<EngravingItem*> fretOrHarmonyItemsNoAlign;
1182 73 : std::vector<Harmony*> harmonyItemsAlign(elements.harmonies.begin(), elements.harmonies.end());
1183 :
1184 354 : for (FretDiagram* fd : elements.fretDiagrams) {
1185 281 : if (muse::contains(fretHarmonyPositions, { fd->tick(), fd->staffIdx() })) {
1186 0 : fretOrHarmonyItemsNoAlign.push_back(fd);
1187 0 : if (fd->harmony()) {
1188 0 : harmonyItemsAlign.erase(std::remove(harmonyItemsAlign.begin(), harmonyItemsAlign.end(), fd->harmony()));
1189 0 : fretOrHarmonyItemsNoAlign.push_back(fd->harmony());
1190 : }
1191 0 : continue;
1192 : }
1193 :
1194 281 : TLayout::layoutFretDiagram(fd, fd->mutldata(), ctx);
1195 281 : Autoplace::autoplaceSegmentElement(fd, fd->mutldata());
1196 281 : fretItemsAlign.push_back(fd);
1197 281 : fretHarmonyPositions.insert({ fd->tick(), fd->staffIdx() });
1198 : }
1199 :
1200 : // Find harmony with no fret diagram at the same tick as a fret diagram
1201 292 : for (Harmony* h : elements.harmonies) {
1202 219 : if (h->getParentFretDiagram()) {
1203 215 : continue;
1204 : }
1205 4 : if (muse::contains(fretHarmonyPositions, { h->tick(), h->staffIdx() })) {
1206 0 : harmonyItemsAlign.erase(std::remove(harmonyItemsAlign.begin(), harmonyItemsAlign.end(), h));
1207 0 : fretOrHarmonyItemsNoAlign.push_back(h);
1208 0 : continue;
1209 : }
1210 :
1211 4 : Autoplace::autoplaceSegmentElement(h, h->mutldata());
1212 4 : fretHarmonyPositions.insert({ h->tick(), h->staffIdx() });
1213 : }
1214 :
1215 : // align 1 fret diagram per tick & staff
1216 73 : AlignmentLayout::alignItemsForSystem(fretItemsAlign, system);
1217 :
1218 73 : layoutHarmonies(harmonyItemsAlign, system, ctx);
1219 :
1220 : // autoplace everything else
1221 73 : for (EngravingItem* item : fretOrHarmonyItemsNoAlign) {
1222 0 : if (item->isFretDiagram()) {
1223 0 : Autoplace::autoplaceSegmentElement(item, item->mutldata());
1224 0 : Harmony* harmony = toFretDiagram(item)->harmony();
1225 0 : if (harmony) {
1226 0 : autoplaceHarmony(harmony);
1227 : }
1228 0 : } else if (item->isHarmony()) {
1229 0 : autoplaceHarmony(item);
1230 : }
1231 : }
1232 73 : }
1233 :
1234 8239 : void SystemLayout::layoutSystemElements(System* system, LayoutContext& ctx)
1235 : {
1236 8254 : TRACEFUNC;
1237 :
1238 8239 : if (ctx.dom().nstaves() == 0) {
1239 0 : return;
1240 : }
1241 :
1242 : // Continuous view does not center items between staves (it collects no pages and doesn't call centerPendingSystems)
1243 8239 : if (!ctx.conf().isLinearMode()) {
1244 8239 : ctx.mutState().addSystemNeedingCentering(system);
1245 : }
1246 :
1247 8239 : ElementsToLayout elementsToLayout(system);
1248 :
1249 43880 : for (MeasureBase* mb : system->measures()) {
1250 35641 : if (!mb->isMeasure()) {
1251 148 : continue;
1252 : }
1253 35493 : if (ctx.conf().isLinearMode() && (mb->tick() < ctx.state().startTick() || mb->tick() > ctx.state().endTick())) {
1254 : // in continuous view, entire score is one system but we only need to process the range
1255 0 : continue;
1256 : }
1257 :
1258 35493 : Measure* measure = toMeasure(mb);
1259 :
1260 35493 : MeasureLayout::layoutMeasureNumber(measure, ctx);
1261 35493 : MMRestLayout::layoutMMRestRange(measure, ctx);
1262 35493 : MeasureLayout::layoutPlayCountText(measure, ctx);
1263 35493 : MeasureLayout::layoutTimeTickAnchors(measure, ctx);
1264 :
1265 35493 : collectElementsToLayout(measure, elementsToLayout, ctx);
1266 : }
1267 :
1268 8239 : const std::vector<Segment*>& sl = elementsToLayout.segments;
1269 8239 : if (sl.empty()) {
1270 8 : return;
1271 : }
1272 :
1273 61327 : for (Chord* chord : elementsToLayout.chords) {
1274 53096 : GraceNotesGroup& graceBefore = chord->graceNotesBefore();
1275 53096 : GraceNotesGroup& graceAfter = chord->graceNotesAfter();
1276 53096 : TLayout::layoutGraceNotesGroup2(&graceBefore, graceBefore.mutldata());
1277 53096 : TLayout::layoutGraceNotesGroup2(&graceAfter, graceAfter.mutldata());
1278 53096 : if (TabDurationSymbol* symbol = chord->tabDur()) {
1279 24 : TLayout::layoutTabDurationSymbol2(symbol, symbol->mutldata());
1280 24 : ChordLayout::fillShape(chord, chord->mutldata());
1281 : }
1282 : }
1283 :
1284 107359 : for (ChordRest* cr : elementsToLayout.chordRests) {
1285 99128 : BeamLayout::layoutNonCrossBeams(cr, ctx);
1286 : }
1287 :
1288 8231 : RestLayout::alignRests(elementsToLayout.system, ctx);
1289 8231 : RestLayout::checkFullMeasureRestCollisions(elementsToLayout.system, ctx);
1290 :
1291 67119 : for (BarLine* bl : elementsToLayout.barlines) {
1292 58888 : TLayout::updateBarlineShape(bl, bl->mutldata(), ctx);
1293 : }
1294 :
1295 8231 : createSkylines(elementsToLayout, ctx);
1296 :
1297 : /* The skyline grows as elements are laid out, so whatever is laid out first ends up closest to the
1298 : * staff. We changed the stacking order of lyrics, from after pedals to before dynamics, so we use
1299 : * this style to keep compatibility for <5.0 scores. This will no longer be necessary if we implement
1300 : * a proper customisable stacking order. */
1301 8231 : const LyricsStackingOrder lyricsStackingOrder = ctx.conf().styleV(Sid::lyricsStackingOrder).value<LyricsStackingOrder>();
1302 :
1303 8231 : layoutTiesAndBends(elementsToLayout, ctx);
1304 :
1305 8231 : if (ctx.conf().isLinearMode()) {
1306 : // TODO: get rid of this
1307 0 : doLayoutNoteSpannersLinear(system, ctx);
1308 : }
1309 :
1310 61327 : for (Chord* c : elementsToLayout.chords) {
1311 53096 : ChordLayout::layoutArticulations(c, ctx);
1312 53096 : ChordLayout::layoutArticulations2(c, ctx);
1313 53096 : ChordLayout::layoutChordBaseFingering(c, system, ctx);
1314 53096 : ChordLayout::layoutJianpuDurationLines(c, ctx);
1315 : }
1316 :
1317 8231 : layoutTuplets(elementsToLayout.chordRests, ctx);
1318 :
1319 8231 : collectSpannersToLayout(elementsToLayout, ctx);
1320 :
1321 8231 : processLines(system, ctx, elementsToLayout.slurs);
1322 :
1323 9120 : for (Spanner* sp : elementsToLayout.slurs) {
1324 889 : Slur* slur = toSlur(sp);
1325 889 : ChordRest* scr = toChordRest(slur->startElement());
1326 889 : ChordRest* ecr = toChordRest(slur->endElement());
1327 889 : if (scr && scr->isChord()) {
1328 889 : ChordLayout::layoutArticulations3(toChord(scr), slur, ctx);
1329 : }
1330 889 : if (ecr && ecr->isChord()) {
1331 876 : ChordLayout::layoutArticulations3(toChord(ecr), slur, ctx);
1332 : }
1333 889 : if (slur->isHammerOnPullOff()) {
1334 62 : StaffType* staffType = slur->staff()->staffType(slur->tick());
1335 72 : if ((staffType->isTabStaff() && ctx.conf().styleB(Sid::hopoAlignLettersTabStaves))
1336 72 : || (!staffType->isTabStaff() && ctx.conf().styleB(Sid::hopoAlignLettersStandardStaves))) {
1337 62 : AlignmentLayout::alignHopoLetters(toHammerOnPullOff(slur), system);
1338 : }
1339 : }
1340 : }
1341 :
1342 8231 : processLines(system, ctx, elementsToLayout.trills);
1343 :
1344 8231 : layoutSticking(elementsToLayout.stickings, system, ctx);
1345 :
1346 8560 : for (EngravingItem* item : elementsToLayout.fermatasAndTremoloBars) {
1347 329 : TLayout::layoutItem(item, ctx);
1348 : }
1349 :
1350 8392 : for (FiguredBass* item : elementsToLayout.figuredBass) {
1351 161 : TLayout::layoutItem(item, ctx);
1352 161 : if (item->autoplace()) {
1353 161 : Autoplace::autoplaceSegmentElement(item, item->mutldata(), true);
1354 : }
1355 : }
1356 :
1357 8231 : if (lyricsStackingOrder == LyricsStackingOrder::LYRICS_BEFORE_DYNAMICS) {
1358 5535 : layoutLyrics(elementsToLayout, ctx);
1359 : }
1360 :
1361 8231 : layoutDynamicExpressionAndHairpins(elementsToLayout, ctx);
1362 :
1363 8231 : processLines(system, ctx, elementsToLayout.allOtherSpanners);
1364 :
1365 12488 : for (MeasureNumber* mno : elementsToLayout.measureNumbers) {
1366 4257 : if (!mno->visible()) {
1367 0 : continue;
1368 : }
1369 4257 : Autoplace::autoplaceMeasureElement(mno, mno->mutldata());
1370 12771 : system->staff(mno->staffIdx())->skyline().add(mno->ldata()->bbox().translated(mno->measure()->pos() + mno->pos()
1371 12771 : + mno->staffOffset()), mno);
1372 : }
1373 :
1374 8231 : for (MMRestRange* mmrr : elementsToLayout.mmrRanges) {
1375 0 : Autoplace::autoplaceMeasureElement(mmrr, mmrr->mutldata());
1376 0 : system->staff(mmrr->staffIdx())->skyline().add(mmrr->ldata()->bbox().translated(mmrr->measure()->pos() + mmrr->pos()), mmrr);
1377 : }
1378 :
1379 8231 : processLines(system, ctx, elementsToLayout.ottavas);
1380 8231 : processLines(system, ctx, elementsToLayout.pedal, /*align=*/ true);
1381 :
1382 8231 : if (lyricsStackingOrder == LyricsStackingOrder::LYRICS_AFTER_PEDALS) {
1383 2696 : layoutLyrics(elementsToLayout, ctx);
1384 : }
1385 :
1386 8263 : for (HarpPedalDiagram* hpd : elementsToLayout.harpDiagrams) {
1387 32 : TLayout::layoutItem(hpd, ctx);
1388 : }
1389 :
1390 8231 : bool hasFretDiagram = elementsToLayout.fretDiagrams.size() > 0;
1391 8231 : if (!hasFretDiagram) {
1392 8128 : layoutHarmonies(elementsToLayout.harmonies, system, ctx);
1393 : }
1394 :
1395 9331 : for (StaffTextBase* st : elementsToLayout.staffText) {
1396 1100 : TLayout::layoutItem(st, ctx);
1397 : }
1398 :
1399 8325 : for (InstrumentChange* ic : elementsToLayout.instrChanges) {
1400 94 : TLayout::layoutItem(ic, ctx);
1401 : }
1402 :
1403 8381 : for (EngravingItem* item : elementsToLayout.playTechCapoStringTunTripletFeel) {
1404 150 : TLayout::layoutItem(item, ctx);
1405 : }
1406 :
1407 8231 : if (hasFretDiagram) {
1408 103 : layoutFretDiagrams(elementsToLayout, system, ctx);
1409 : }
1410 :
1411 8356 : for (SystemText* systemText : elementsToLayout.systemText) {
1412 125 : TLayout::layoutSystemText(systemText, systemText->mutldata());
1413 : }
1414 :
1415 8231 : layoutVoltas(elementsToLayout, ctx);
1416 :
1417 8358 : for (RehearsalMark* rm : elementsToLayout.rehMarks) {
1418 127 : TLayout::layoutItem(rm, ctx);
1419 : }
1420 :
1421 8231 : std::vector<EngravingItem*> tempoElementsToAlign;
1422 9425 : for (TempoText* tt : elementsToLayout.tempoText) {
1423 1194 : TLayout::layoutItem(tt, ctx);
1424 1194 : tempoElementsToAlign.push_back(tt);
1425 : }
1426 :
1427 8231 : processLines(system, ctx, elementsToLayout.tempoChangeLines);
1428 14121 : for (SpannerSegment* spannerSeg : system->spannerSegments()) {
1429 5890 : if (spannerSeg->isGradualTempoChangeSegment()) {
1430 22 : tempoElementsToAlign.push_back(spannerSeg);
1431 : }
1432 : }
1433 :
1434 8237 : for (PlayCountText* pt : elementsToLayout.playCountText) {
1435 6 : TLayout::layoutPlayCountText(pt, pt->mutldata());
1436 6 : if (pt->autoplace()) {
1437 6 : Autoplace::autoplaceSegmentElement(pt, pt->mutldata());
1438 : }
1439 : }
1440 :
1441 8231 : AlignmentLayout::alignItemsWithTheirSnappingChain(tempoElementsToAlign, system);
1442 :
1443 8358 : for (RehearsalMark* rehearsMark : elementsToLayout.rehMarks) {
1444 127 : Autoplace::autoplaceSegmentElement(rehearsMark, rehearsMark->mutldata());
1445 : }
1446 :
1447 8756 : for (EngravingItem* item : elementsToLayout.markersAndJumps) {
1448 525 : TLayout::layoutItem(item, ctx);
1449 : }
1450 :
1451 8231 : for (Image* image : elementsToLayout.images) {
1452 0 : TLayout::layoutItem(image, ctx);
1453 : }
1454 :
1455 8284 : for (StaveSharingChange* ssc : elementsToLayout.staveSharingChanges) {
1456 53 : TLayout::layoutItem(ssc, ctx);
1457 : }
1458 :
1459 8231 : layoutParenthesisAndBigTimeSigs(elementsToLayout);
1460 8247 : }
1461 :
1462 35493 : void SystemLayout::collectElementsToLayout(Measure* measure, ElementsToLayout& elements, const LayoutContext& ctx)
1463 : {
1464 35493 : elements.measures.push_back(measure);
1465 :
1466 35493 : System* system = elements.system;
1467 88897 : for (size_t staffIdx = 0; staffIdx < ctx.dom().nstaves(); ++staffIdx) {
1468 53404 : if (measure->showMeasureNumberOnStaff(staffIdx)) {
1469 4257 : if (MeasureNumber* mno = measure->measureNumber(staffIdx)) {
1470 4257 : elements.measureNumbers.push_back(mno);
1471 : }
1472 : }
1473 :
1474 53404 : if (!system->staff(staffIdx)->show()) {
1475 1848 : continue;
1476 : }
1477 :
1478 51556 : MMRestRange* mmrr = measure->mmRangeText(staffIdx);
1479 51556 : if (mmrr && mmrr->addToSkyline()) {
1480 0 : elements.mmrRanges.push_back(mmrr);
1481 : }
1482 :
1483 54656 : for (EngravingItem* item : measure->el()) {
1484 3100 : if (item->effectiveStaffIdx() == staffIdx && (item->isMarker() || item->isJump())) {
1485 525 : elements.markersAndJumps.push_back(item);
1486 : }
1487 : }
1488 : }
1489 :
1490 35493 : track_idx_t nTracks = ctx.dom().ntracks();
1491 169955 : for (Segment* s = measure->first(); s; s = s->next()) {
1492 134462 : if (s->isChordRestType() || !s->annotations().empty()) {
1493 72924 : elements.segments.push_back(s);
1494 : }
1495 :
1496 741499 : for (track_idx_t track = 0; track < nTracks; /* intentionally empty*/ ) {
1497 607037 : if (s->hasTimeSigAboveStaves()) {
1498 0 : TimeSig* timeSig = toTimeSig(s->element(track));
1499 0 : if (timeSig && timeSig->showOnThisStaff()) {
1500 0 : elements.timeSigAboveStaves.push_back(timeSig);
1501 : }
1502 0 : track += VOICES;
1503 0 : continue;
1504 0 : }
1505 :
1506 607037 : if (!system->staff(track2staff(track))->show()) {
1507 9557 : track += VOICES;
1508 9557 : continue;
1509 : }
1510 :
1511 597480 : if (s->isType(SegmentType::BarLineTypes)) {
1512 58888 : if (BarLine* bl = toBarLine(s->element(track))) {
1513 58888 : elements.barlines.push_back(bl);
1514 : }
1515 58888 : track += VOICES;
1516 58888 : continue;
1517 58888 : }
1518 :
1519 538592 : if (s->isChordRestType()) {
1520 404048 : if (ChordRest* cr = toChordRest(s->element(track))) {
1521 99128 : elements.chordRests.push_back(cr);
1522 99128 : if (cr->isChord()) {
1523 53096 : elements.chords.push_back(toChord(cr));
1524 :
1525 54009 : auto collectBends = [&elements, system] (Chord* chord) {
1526 115575 : for (Note* note : chord->notes()) {
1527 62215 : for (Spanner* sp : note->spannerBack()) {
1528 649 : if (sp->isGuitarBend()) {
1529 409 : elements.guitarBends.push_back(toGuitarBend(sp));
1530 : }
1531 : }
1532 :
1533 62215 : for (Spanner* sp : note->spannerFor()) {
1534 649 : if (sp->isGuitarBend()) {
1535 409 : GuitarBend* bend = toGuitarBend(sp);
1536 409 : Note* endNote = bend->endNote();
1537 409 : if (bend->bendType() == GuitarBendType::SLIGHT_BEND
1538 409 : || (endNote && endNote->tick() >= system->endTick())) {
1539 17 : elements.guitarBends.push_back(bend);
1540 : }
1541 : }
1542 : }
1543 : }
1544 54009 : };
1545 :
1546 53096 : Chord* chord = toChord(cr);
1547 53779 : for (Chord* grace : chord->graceNotesBefore()) {
1548 683 : collectBends(grace);
1549 : }
1550 53096 : collectBends(chord);
1551 53326 : for (Chord* grace : chord->graceNotesAfter()) {
1552 230 : collectBends(grace);
1553 : }
1554 : }
1555 : }
1556 404048 : ++track;
1557 404048 : continue;
1558 404048 : }
1559 :
1560 134544 : ++track;
1561 : }
1562 :
1563 141794 : for (EngravingItem* item : s->annotations()) {
1564 7332 : if (!item->systemFlag() && !system->staff(item->staffIdx())->show()) {
1565 13 : continue;
1566 : }
1567 7319 : switch (item->type()) {
1568 131 : case ElementType::STICKING:
1569 131 : elements.stickings.push_back(toSticking(item));
1570 131 : break;
1571 329 : case ElementType::FERMATA:
1572 : case ElementType::TREMOLOBAR:
1573 329 : elements.fermatasAndTremoloBars.push_back(item);
1574 329 : break;
1575 161 : case ElementType::FIGURED_BASS:
1576 161 : elements.figuredBass.push_back(toFiguredBass(item));
1577 161 : break;
1578 1141 : case ElementType::DYNAMIC:
1579 1141 : elements.dynamics.push_back(toDynamic(item));
1580 1141 : break;
1581 34 : case ElementType::EXPRESSION:
1582 34 : elements.expressions.push_back(toExpression(item));
1583 34 : break;
1584 32 : case ElementType::HARP_DIAGRAM:
1585 32 : elements.harpDiagrams.push_back(toHarpPedalDiagram(item));
1586 32 : break;
1587 340 : case ElementType::FRET_DIAGRAM:
1588 340 : elements.fretDiagrams.push_back(toFretDiagram(item));
1589 340 : if (Harmony* h = toFretDiagram(item)->harmony()) {
1590 235 : elements.harmonies.push_back(h);
1591 : }
1592 340 : break;
1593 1100 : case ElementType::STAFF_TEXT:
1594 : case ElementType::STAVE_SHARING_LABEL:
1595 1100 : elements.staffText.push_back(toStaffTextBase(item));
1596 1100 : break;
1597 53 : case ElementType::STAVE_SHARING_CHANGE:
1598 53 : elements.staveSharingChanges.push_back(toStaveSharingChange(item));
1599 53 : break;
1600 94 : case ElementType::INSTRUMENT_CHANGE:
1601 94 : elements.instrChanges.push_back(toInstrumentChange(item));
1602 94 : break;
1603 150 : case ElementType::PLAYTECH_ANNOTATION:
1604 : case ElementType::CAPO:
1605 : case ElementType::STRING_TUNINGS:
1606 : case ElementType::TRIPLET_FEEL:
1607 150 : elements.playTechCapoStringTunTripletFeel.push_back(item);
1608 150 : break;
1609 125 : case ElementType::SYSTEM_TEXT:
1610 125 : elements.systemText.push_back(toSystemText(item));
1611 125 : break;
1612 127 : case ElementType::REHEARSAL_MARK:
1613 127 : elements.rehMarks.push_back(toRehearsalMark(item));
1614 127 : break;
1615 1194 : case ElementType::TEMPO_TEXT:
1616 1194 : elements.tempoText.push_back(toTempoText(item));
1617 1194 : break;
1618 0 : case ElementType::IMAGE:
1619 0 : elements.images.push_back(toImage(item));
1620 0 : break;
1621 0 : case ElementType::PARENTHESIS:
1622 0 : elements.parenthesis.push_back(toParenthesis(item));
1623 0 : break;
1624 2279 : case ElementType::HARMONY:
1625 2279 : elements.harmonies.push_back(toHarmony(item));
1626 2279 : break;
1627 6 : case ElementType::PLAY_COUNT_TEXT:
1628 6 : elements.playCountText.push_back(toPlayCountText(item));
1629 6 : break;
1630 23 : default:
1631 23 : break;
1632 : }
1633 : }
1634 : }
1635 35493 : }
1636 :
1637 8231 : void SystemLayout::collectSpannersToLayout(ElementsToLayout& elements, const LayoutContext& ctx)
1638 : {
1639 8231 : const System* system = elements.system;
1640 :
1641 : // NOTE: in continuous view, this means we layout spanners for the entire score.
1642 : // TODO: find way to optimize this and only layout where necessary.
1643 8231 : Fraction stick = system->measures().front()->tick();
1644 8231 : Fraction etick = system->measures().back()->endTick();
1645 :
1646 8231 : auto spanners = ctx.dom().spannerMap().findOverlapping(stick.ticks(), etick.ticks());
1647 8231 : std::sort(spanners.begin(), spanners.end(), [](const auto& sp1, const auto& sp2) {
1648 3441 : return sp1.value->tick() < sp2.value->tick();
1649 : });
1650 :
1651 8231 : std::vector<Spanner*> allSpanners;
1652 8231 : allSpanners.reserve(spanners.size());
1653 10753 : for (auto item : spanners) {
1654 2522 : allSpanners.push_back(item.value);
1655 : }
1656 :
1657 10753 : for (Spanner* spanner : allSpanners) {
1658 2522 : if (!spanner->systemFlag() && !system->staff(spanner->staffIdx())->show()) {
1659 4 : continue;
1660 : }
1661 2518 : if (spanner->tick() >= etick || spanner->tick2() < stick) {
1662 102 : continue;
1663 : }
1664 :
1665 2416 : if (spanner->tick2() == stick) {
1666 : // Only these two spanner types are laid out if at the end of the previous system
1667 : // TODO: pedal makes sense, but slur doesn't... to figure out
1668 61 : if (spanner->isSlur() && !toSlur(spanner)->isCrossStaff() && !toSlur(spanner)->hasCrossBeams()) {
1669 8 : elements.slurs.push_back(spanner);
1670 53 : } else if (spanner->isPedal() && toPedal(spanner)->connect45HookToNext()) {
1671 0 : elements.pedal.push_back(spanner);
1672 : }
1673 : } else {
1674 2355 : switch (spanner->type()) {
1675 905 : case ElementType::SLUR:
1676 : case ElementType::HAMMER_ON_PULL_OFF:
1677 905 : if (!toSlur(spanner)->isCrossStaff() && !toSlur(spanner)->hasCrossBeams()) {
1678 881 : elements.slurs.push_back(spanner);
1679 : }
1680 905 : break;
1681 119 : case ElementType::PEDAL:
1682 119 : elements.pedal.push_back(spanner);
1683 119 : break;
1684 116 : case ElementType::TRILL:
1685 116 : elements.trills.push_back(spanner);
1686 116 : break;
1687 376 : case ElementType::VOLTA:
1688 376 : elements.voltas.push_back(spanner);
1689 376 : break;
1690 483 : case ElementType::HAIRPIN:
1691 483 : elements.hairpins.push_back(spanner);
1692 483 : break;
1693 22 : case ElementType::GRADUAL_TEMPO_CHANGE:
1694 22 : elements.tempoChangeLines.push_back(spanner);
1695 22 : break;
1696 9 : case ElementType::PARTIAL_LYRICSLINE:
1697 9 : elements.partialLyricsLines.push_back(spanner);
1698 9 : break;
1699 162 : case ElementType::OTTAVA:
1700 162 : if (!spanner->staff()->staffType()->isTabStaff()) {
1701 161 : elements.ottavas.push_back(spanner);
1702 : }
1703 162 : break;
1704 163 : default:
1705 163 : elements.allOtherSpanners.push_back(spanner);
1706 163 : break;
1707 : }
1708 : }
1709 : }
1710 8231 : }
1711 :
1712 8231 : void SystemLayout::createSkylines(const ElementsToLayout& elementsToLayout, LayoutContext& ctx)
1713 : {
1714 8231 : System* system = elementsToLayout.system;
1715 21227 : for (size_t staffIdx = 0; staffIdx < ctx.dom().nstaves(); ++staffIdx) {
1716 12996 : SysStaff* ss = system->staff(staffIdx);
1717 12996 : Skyline& skyline = ss->skyline();
1718 12996 : skyline.clear();
1719 66400 : for (Measure* m : elementsToLayout.measures) {
1720 53404 : if (m->staffLines(staffIdx)->addToSkyline()) {
1721 53386 : ss->skyline().add(m->staffLines(staffIdx)->ldata()->bbox().translated(m->pos()), m->staffLines(staffIdx));
1722 : }
1723 256497 : for (Segment& s : m->segments()) {
1724 203093 : if (!s.enabled()) {
1725 2276 : continue;
1726 : }
1727 200817 : PointF p(s.pos() + m->pos());
1728 200817 : if (s.isType(SegmentType::BarLineTypes)) {
1729 60376 : BarLine* bl = toBarLine(s.element(staffIdx * VOICES));
1730 60376 : if (bl && bl->addToSkyline()) {
1731 60359 : skyline.add(bl->shape().translated(bl->pos() + p + bl->staffOffset()));
1732 : }
1733 140441 : } else if (s.isType(SegmentType::TimeSigTypes)) {
1734 7154 : TimeSig* ts = toTimeSig(s.element(staffIdx * VOICES));
1735 7154 : if (ts && ts->addToSkyline() && ts->showOnThisStaff()) {
1736 6980 : TimeSigPlacement timeSigPlacement = ts->style().styleV(Sid::timeSigPlacement).value<TimeSigPlacement>();
1737 6980 : if (timeSigPlacement != TimeSigPlacement::ACROSS_STAVES) {
1738 6968 : skyline.add(ts->shape().translate(ts->pos() + p + ts->staffOffset()));
1739 : }
1740 : }
1741 : } else {
1742 133287 : track_idx_t strack = staffIdx * VOICES;
1743 133287 : track_idx_t etrack = strack + VOICES;
1744 1626011 : for (EngravingItem* e : s.elist()) {
1745 1492724 : if (!e) {
1746 1136885 : continue;
1747 : }
1748 355839 : track_idx_t effectiveTrack = e->vStaffIdx() * VOICES + e->voice();
1749 355839 : if (effectiveTrack < strack || effectiveTrack >= etrack) {
1750 226369 : continue;
1751 : }
1752 :
1753 : // add element to skyline
1754 129470 : if (e->addToSkyline()) {
1755 129196 : const PointF offset = e->staffOffset();
1756 129196 : Shape shape = e->shape();
1757 : // add grace notes to skyline
1758 129196 : if (e->isChord()) {
1759 55302 : Chord* chord = toChord(e);
1760 55302 : GraceNotesGroup& graceBefore = chord->graceNotesBefore();
1761 55302 : GraceNotesGroup& graceAfter = chord->graceNotesAfter();
1762 55302 : if (!graceBefore.empty()) {
1763 523 : skyline.add(graceBefore.shape().translate(graceBefore.pos() + p + offset));
1764 : }
1765 55302 : if (!graceAfter.empty()) {
1766 180 : skyline.add(graceAfter.shape().translate(graceAfter.pos() + p + offset));
1767 : }
1768 :
1769 : // If present, add ornament cue note to skyline
1770 55302 : Ornament* ornament = chord->findOrnament();
1771 55302 : if (ornament) {
1772 386 : Chord* cue = ornament->cueNoteChord();
1773 386 : if (cue && cue->upNote()->visible()) {
1774 16 : skyline.add(cue->shape().translate(cue->pos() + p + cue->staffOffset()));
1775 : }
1776 : }
1777 :
1778 : // Don't include cross-staff arpeggios
1779 55302 : shape.remove_if([chord](ShapeElement& s) {
1780 145754 : return (s.item()->isArpeggio() || s.item()->isChordBracket()) && toArpeggio(
1781 145754 : s.item()) == chord->spanArpeggio();
1782 : });
1783 55302 : Arpeggio* arp = chord->spanArpeggio();
1784 55302 : if (arp) {
1785 311 : RectF staffBbox = ss->bbox();
1786 311 : RectF arpBbox = arp->ldata()->bbox().translated(e->pos() + p + offset);
1787 311 : if (chord->track() == arp->track()) {
1788 233 : staffBbox.setTop(arpBbox.top());
1789 78 : } else if (chord->track() == arp->endTrack()) {
1790 74 : staffBbox.setBottom(arpBbox.bottom());
1791 : }
1792 311 : shape.add(arpBbox & staffBbox, arp);
1793 : }
1794 : }
1795 129196 : skyline.add(shape.translate(e->pos() + p + offset));
1796 129196 : }
1797 :
1798 : // add tremolo to skyline
1799 129470 : if (e->isChord()) {
1800 55306 : Chord* ch = item_cast<Chord*>(e);
1801 : // tremoloSingleChord is added directly to chord shape
1802 55306 : if (ch->tremoloTwoChord()) {
1803 220 : TremoloTwoChord* t = ch->tremoloTwoChord();
1804 220 : Chord* c1 = t->chord1();
1805 220 : Chord* c2 = t->chord2();
1806 220 : if (c1 && !c1->staffMove() && c2 && !c2->staffMove()) {
1807 220 : if (t->chord() == e && t->addToSkyline()) {
1808 110 : skyline.add(t->shape().translate(t->pos() + e->pos() + p));
1809 : }
1810 : }
1811 : }
1812 : }
1813 :
1814 : // add beams to skline
1815 129470 : if (e->isChordRest()) {
1816 102677 : ChordRest* cr = toChordRest(e);
1817 102677 : if (BeamLayout::isStartOfNonCrossBeam(cr)) {
1818 4900 : Beam* b = cr->beam();
1819 4900 : b->addSkyline(skyline);
1820 : }
1821 : }
1822 : }
1823 : }
1824 : }
1825 : }
1826 : }
1827 8231 : }
1828 :
1829 0 : void SystemLayout::doLayoutTies(System* system, const std::vector<Segment*>& sl, const Fraction& stick, const Fraction& etick,
1830 : LayoutContext& ctx)
1831 : {
1832 : UNUSED(etick);
1833 :
1834 0 : for (Segment* s : sl) {
1835 0 : for (EngravingItem* e : s->elist()) {
1836 0 : if (!e || !e->isChord()) {
1837 0 : continue;
1838 : }
1839 0 : Chord* c = toChord(e);
1840 0 : for (Chord* ch : c->graceNotes()) {
1841 0 : layoutTies(ch, system, stick, ctx);
1842 : }
1843 0 : layoutTies(c, system, stick, ctx);
1844 : }
1845 : }
1846 0 : }
1847 :
1848 8231 : void SystemLayout::layoutTuplets(const std::vector<ChordRest*>& chordRests, LayoutContext& ctx)
1849 : {
1850 8231 : std::set<Tuplet*> laidoutTuplets;
1851 107359 : for (auto revIter = chordRests.rbegin(); revIter != chordRests.rend(); ++revIter) {
1852 99128 : ChordRest* cr = *revIter;
1853 99128 : Tuplet* tuplet = cr->topTuplet();
1854 :
1855 99128 : if (!tuplet || muse::contains(laidoutTuplets, tuplet)) {
1856 97634 : continue;
1857 : }
1858 :
1859 1494 : TupletLayout::layoutTupletAndNestedTuplets(tuplet, ctx); // this lays out also the inner tuplets
1860 1494 : laidoutTuplets.insert(tuplet);
1861 : }
1862 8231 : }
1863 :
1864 8231 : void SystemLayout::layoutTiesAndBends(const ElementsToLayout& elementsToLayout, LayoutContext& ctx)
1865 : {
1866 8231 : System* system = elementsToLayout.system;
1867 8231 : if (elementsToLayout.measures.empty()) {
1868 0 : return;
1869 : }
1870 8231 : Fraction stick = elementsToLayout.measures.front()->tick();
1871 :
1872 61327 : for (Chord* chord : elementsToLayout.chords) {
1873 53779 : for (Chord* grace : chord->graceNotesBefore()) {
1874 683 : layoutTies(grace, system, stick, ctx);
1875 : }
1876 53096 : layoutTies(chord, system, stick, ctx);
1877 53326 : for (Chord* grace : chord->graceNotesAfter()) {
1878 230 : layoutTies(grace, system, stick, ctx);
1879 : }
1880 : }
1881 :
1882 8231 : GuitarDiveLayout::updateDiveSequences(elementsToLayout.guitarBends, ctx);
1883 :
1884 8657 : for (GuitarBend* bend : elementsToLayout.guitarBends) {
1885 : /* Bends which cross a system break are collected by both systems they touch, so we
1886 : * lay out only the segment which belongs to this one: */
1887 426 : TLayout::layoutGuitarBend(bend, ctx, system);
1888 : }
1889 : }
1890 :
1891 0 : void SystemLayout::layoutNoteAnchoredSpanners(System* system, Chord* chord)
1892 : {
1893 : // Add all spanners attached to notes, otherwise these will be removed if outside of the layout range
1894 0 : for (Note* note : chord->notes()) {
1895 0 : for (Spanner* spanner : note->spannerFor()) {
1896 0 : for (SpannerSegment* spannerSeg : spanner->spannerSegments()) {
1897 0 : spannerSeg->moveToSystem(system);
1898 : }
1899 : }
1900 : }
1901 0 : }
1902 :
1903 0 : void SystemLayout::doLayoutNoteSpannersLinear(System* system, LayoutContext& ctx)
1904 : {
1905 0 : constexpr Fraction start = Fraction(0, 1);
1906 0 : for (Measure* measure = system->firstMeasure(); measure; measure = measure->nextMeasure()) {
1907 0 : for (Segment* segment = measure->first(); segment; segment = segment->next()) {
1908 0 : if (!segment->isChordRestType()) {
1909 0 : continue;
1910 : }
1911 0 : for (EngravingItem* e : segment->elist()) {
1912 0 : if (!e || !e->isChord()) {
1913 0 : continue;
1914 : }
1915 0 : Chord* c = toChord(e);
1916 0 : for (Chord* ch : c->graceNotes()) {
1917 0 : layoutTies(ch, system, start, ctx);
1918 0 : layoutNoteAnchoredSpanners(system, ch);
1919 : }
1920 0 : layoutTies(c, system, start, ctx);
1921 0 : layoutNoteAnchoredSpanners(system, c);
1922 : }
1923 : }
1924 : }
1925 0 : }
1926 :
1927 65848 : void SystemLayout::processLines(System* system, LayoutContext& ctx, const std::vector<Spanner*>& lines, bool align)
1928 : {
1929 65848 : std::vector<SpannerSegment*> segments;
1930 68177 : for (Spanner* sp : lines) {
1931 2329 : SpannerSegment* ss = TLayout::layoutSystem(sp, system, ctx); // create/layout spanner segment for this system
1932 2329 : if (ss->autoplace()) {
1933 2323 : segments.push_back(ss);
1934 : }
1935 : }
1936 :
1937 65848 : if (align && segments.size() > 1) {
1938 19 : const size_t nstaves = system->staves().size();
1939 19 : const double defaultY = segments[0]->ldata()->pos().y();
1940 19 : std::vector<double> yAbove(nstaves, -DBL_MAX);
1941 19 : std::vector<double> yBelow(nstaves, -DBL_MAX);
1942 :
1943 87 : for (SpannerSegment* ss : segments) {
1944 68 : if (ss->visible()) {
1945 66 : double& staffY = ss->spanner() && ss->spanner()->placeAbove() ? yAbove[ss->staffIdx()] : yBelow[ss->staffIdx()];
1946 66 : staffY = std::max(staffY, ss->ldata()->pos().y());
1947 : }
1948 : }
1949 87 : for (SpannerSegment* ss : segments) {
1950 68 : const double& staffY = ss->spanner() && ss->spanner()->placeAbove() ? yAbove[ss->staffIdx()] : yBelow[ss->staffIdx()];
1951 68 : if (staffY > -DBL_MAX) {
1952 68 : ss->mutldata()->setPosY(staffY);
1953 : } else {
1954 0 : ss->mutldata()->setPosY(defaultY);
1955 : }
1956 : }
1957 19 : }
1958 :
1959 65848 : if (segments.size() > 0 && segments.front()->isSlurSegment()) {
1960 400 : SlurTieLayout::adjustOverlappingSlurs(system->spannerSegments());
1961 : }
1962 :
1963 : //
1964 : // Fix harmonic marks and vibrato overlaps
1965 : //
1966 65848 : SpannerSegment* prevSegment = nullptr;
1967 65848 : bool fixed = false;
1968 :
1969 68171 : for (SpannerSegment* ss : segments) {
1970 2323 : if (fixed) {
1971 6 : fixed = false;
1972 6 : prevSegment = ss;
1973 6 : continue;
1974 : }
1975 2317 : if (prevSegment) {
1976 1182 : if (prevSegment->visible()
1977 1180 : && ss->visible()
1978 1172 : && prevSegment->isHarmonicMarkSegment()
1979 16 : && ss->isVibratoSegment()
1980 2362 : && muse::RealIsEqual(prevSegment->x(), ss->x())) {
1981 2 : double diff = ss->ldata()->bbox().bottom() - prevSegment->ldata()->bbox().bottom()
1982 2 : + prevSegment->ldata()->bbox().top();
1983 2 : prevSegment->mutldata()->moveY(diff);
1984 2 : fixed = true;
1985 : }
1986 1182 : if (prevSegment->visible()
1987 1180 : && ss->visible()
1988 1172 : && prevSegment->isVibratoSegment()
1989 21 : && ss->isHarmonicMarkSegment()
1990 2362 : && muse::RealIsEqual(prevSegment->x(), ss->x())) {
1991 4 : double diff = prevSegment->ldata()->bbox().bottom() - ss->ldata()->bbox().bottom()
1992 4 : + ss->ldata()->bbox().top();
1993 4 : ss->mutldata()->moveY(diff);
1994 4 : fixed = true;
1995 : }
1996 : }
1997 :
1998 2317 : prevSegment = ss;
1999 : }
2000 :
2001 : //
2002 : // add shapes to skyline
2003 : //
2004 68171 : for (SpannerSegment* ss : segments) {
2005 2323 : if (ss->addToSkyline()) {
2006 2281 : staff_idx_t stfIdx = ss->effectiveStaffIdx();
2007 2281 : if (stfIdx == muse::nidx) {
2008 0 : continue;
2009 : }
2010 2281 : system->staff(stfIdx)->skyline().add(ss->shape().translate(ss->pos()));
2011 2281 : if (ss->isHammerOnPullOffSegment()) {
2012 62 : TLayout::layoutHammerOnPullOffSegment(toHammerOnPullOffSegment(ss), ctx);
2013 : }
2014 : }
2015 : }
2016 65848 : }
2017 :
2018 54009 : void SystemLayout::layoutTies(Chord* ch, System* system, const Fraction& stick, LayoutContext& ctx)
2019 : {
2020 54009 : SysStaff* staff = system->staff(ch->staffIdx());
2021 54009 : if (!staff->show()) {
2022 0 : return;
2023 : }
2024 54009 : std::vector<TieSegment*> stackedForwardTies;
2025 54009 : std::vector<TieSegment*> stackedBackwardTies;
2026 115575 : for (Note* note : ch->notes()) {
2027 61566 : Tie* t = note->tieFor();
2028 61566 : if (t && !t->isLaissezVib()) {
2029 2237 : TieSegment* ts = SlurTieLayout::layoutTieFor(t, system);
2030 2237 : if (ts && ts->addToSkyline()) {
2031 2227 : staff->skyline().add(ts->shape().translate(ts->pos()));
2032 2227 : stackedForwardTies.push_back(ts);
2033 : }
2034 : }
2035 61566 : t = note->tieBack();
2036 61566 : if (t) {
2037 2311 : if (note->incomingPartialTie() || t->startNote()->tick() < stick) {
2038 167 : TieSegment* ts = SlurTieLayout::layoutTieBack(t, system, ctx);
2039 167 : if (ts && ts->addToSkyline()) {
2040 167 : staff->skyline().add(ts->shape().translate(ts->pos()));
2041 167 : stackedBackwardTies.push_back(ts);
2042 : }
2043 : }
2044 : }
2045 : }
2046 :
2047 54009 : SlurTieLayout::layoutLaissezVibChord(ch, ctx);
2048 :
2049 54009 : if (!ch->staffType()->isTabStaff()) {
2050 53187 : SlurTieLayout::resolveVerticalTieCollisions(stackedForwardTies);
2051 53187 : SlurTieLayout::resolveVerticalTieCollisions(stackedBackwardTies);
2052 : }
2053 54009 : }
2054 :
2055 35554 : bool SystemLayout::measureHasCrossStuffOrModifiedBeams(const Measure* measure)
2056 : {
2057 147233 : for (const Segment& seg : measure->segments()) {
2058 111692 : if (!seg.isChordRestType()) {
2059 36785 : continue;
2060 : }
2061 511843 : for (const EngravingItem* e : seg.elist()) {
2062 436949 : if (!e || !e->isChordRest()) {
2063 331305 : continue;
2064 : }
2065 105644 : const Beam* beam = toChordRest(e)->beam();
2066 105644 : if (beam && (beam->cross() || beam->userModified())) {
2067 13 : return true;
2068 : }
2069 105631 : const Chord* c = e->isChord() ? toChord(e) : nullptr;
2070 105631 : if (c && c->tremoloTwoChord()) {
2071 228 : const TremoloTwoChord* trem = c->tremoloTwoChord();
2072 228 : const Chord* c1 = trem->chord1();
2073 228 : const Chord* c2 = trem->chord2();
2074 228 : if (trem->userModified() || c1->staffMove() != c2->staffMove()) {
2075 0 : return true;
2076 : }
2077 : }
2078 105631 : if (e->isChord() && !toChord(e)->graceNotes().empty()) {
2079 1581 : for (const Chord* grace : toChord(e)->graceNotes()) {
2080 918 : if (grace->beam() && (grace->beam()->cross() || grace->beam()->userModified())) {
2081 0 : return true;
2082 : }
2083 : }
2084 : }
2085 : }
2086 : }
2087 :
2088 35541 : return false;
2089 : }
2090 :
2091 13 : void SystemLayout::updateCrossBeams(System* system, LayoutContext& ctx)
2092 : {
2093 : LAYOUT_CALL() << LAYOUT_ITEM_INFO(system);
2094 :
2095 13 : SystemLayout::layout2(system, ctx); // Computes staff distances, essential for the rest of the calculations
2096 : // Update grace cross beams
2097 38 : for (MeasureBase* mb : system->measures()) {
2098 25 : if (!mb->isMeasure()) {
2099 0 : continue;
2100 : }
2101 379 : for (Segment& seg : toMeasure(mb)->segments()) {
2102 354 : if (!seg.isChordRestType()) {
2103 52 : continue;
2104 : }
2105 2622 : for (EngravingItem* e : seg.elist()) {
2106 2320 : if (!e || !e->isChord()) {
2107 1967 : continue;
2108 : }
2109 353 : for (Chord* grace : toChord(e)->graceNotes()) {
2110 0 : if (grace->beam() && (grace->beam()->cross() || grace->beam()->userModified())
2111 0 : && grace->beam()->elements().front() == grace) {
2112 0 : BeamLayout::layout(grace->beam(), ctx);
2113 : }
2114 : }
2115 : }
2116 : }
2117 : }
2118 : // Update normal chords cross beams and respective segments
2119 38 : for (MeasureBase* mb : system->measures()) {
2120 25 : if (!mb->isMeasure()) {
2121 0 : continue;
2122 : }
2123 25 : bool somethingChanged = false;
2124 379 : for (Segment& seg : toMeasure(mb)->segments()) {
2125 354 : if (!seg.isChordRestType()) {
2126 52 : continue;
2127 : }
2128 2622 : for (EngravingItem* e : seg.elist()) {
2129 2320 : if (!e || !e->isChord()) {
2130 1967 : continue;
2131 : }
2132 353 : Chord* chord = toChord(e);
2133 647 : if (chord->beam() && (chord->beam()->cross() || chord->beam()->userModified())
2134 647 : && chord->beam()->elements().front() == chord) {
2135 30 : bool prevUp = chord->up();
2136 30 : Stem* stem = chord->stem();
2137 30 : double prevStemLength = stem ? stem->length() : 0.0;
2138 30 : BeamLayout::layout(chord->beam(), ctx);
2139 30 : if (chord->up() != prevUp || (stem && stem->length() != prevStemLength)) {
2140 : // If the chord has changed direction needs to be re-laid out
2141 21 : ChordLayout::layoutChords1(ctx, &seg, chord->vStaffIdx());
2142 21 : somethingChanged = true;
2143 : }
2144 323 : } else if (chord->tremoloTwoChord()) {
2145 0 : TremoloTwoChord* t = chord->tremoloTwoChord();
2146 0 : Chord* c1 = t->chord1();
2147 0 : Chord* c2 = t->chord2();
2148 0 : if (t->userModified() || (c1->staffMove() != 0 || c2->staffMove() != 0)) {
2149 0 : bool prevUp = chord->up();
2150 0 : ChordLayout::computeUp(chord, ctx);
2151 0 : if (chord->up() != prevUp) {
2152 0 : ChordLayout::layoutChords1(ctx, &seg, chord->vStaffIdx());
2153 0 : somethingChanged = true;
2154 : }
2155 : }
2156 : }
2157 : }
2158 302 : if (somethingChanged) {
2159 125 : seg.createShapes();
2160 : }
2161 : }
2162 : }
2163 13 : }
2164 :
2165 302 : void SystemLayout::restoreOldSystemLayout(System* system, LayoutContext& ctx)
2166 : {
2167 302 : layoutSystemElements(system, ctx);
2168 302 : }
2169 :
2170 15870 : void SystemLayout::layoutSystem(System* system, LayoutContext& ctx, double leadingHBoxesWidth)
2171 : {
2172 15870 : SystemHeaderLayout::updateSystemHeaderWidth(system, ctx);
2173 :
2174 15870 : size_t nstaves = system->staves().size();
2175 :
2176 40999 : for (size_t staffIdx = 0; staffIdx < nstaves; ++staffIdx) {
2177 25129 : SysStaff* s = system->staves().at(staffIdx);
2178 25129 : const Staff* staff = ctx.dom().staff(staffIdx);
2179 25129 : if (!staff->show() || !s->show()) {
2180 1306 : s->setbbox(RectF());
2181 1306 : continue;
2182 : }
2183 :
2184 23823 : double staffMag = staff->staffMag(Fraction(0, 1)); // ??? TODO
2185 23823 : int staffLines = staff->lines(Fraction(0, 1));
2186 23823 : if (staffLines <= 1) {
2187 226 : double h = staff->lineDistance(Fraction(0, 1)) * staffMag * system->spatium();
2188 226 : s->setbbox(system->leftMargin() + leadingHBoxesWidth, -h, 0.0, 2 * h);
2189 : } else {
2190 23597 : double h = (staffLines - 1) * staff->lineDistance(Fraction(0, 1));
2191 23597 : h = h * staffMag * system->spatium();
2192 23597 : s->setbbox(system->leftMargin() + leadingHBoxesWidth, 0.0, 0.0, h);
2193 : }
2194 : }
2195 :
2196 : //---------------------------------------------------
2197 : // layout brackets
2198 : //---------------------------------------------------
2199 :
2200 15870 : SystemHeaderLayout::setBracketsXPosition(system, system->leftMargin() + leadingHBoxesWidth);
2201 :
2202 15870 : SystemHeaderLayout::setInstrumentNamesHorizontalPos(system);
2203 15870 : SystemHeaderLayout::setGroupBracketsHorizontalPos(system);
2204 :
2205 57585 : for (MeasureBase* mb : system->measures()) {
2206 41715 : if (!mb->isMeasure()) {
2207 203 : continue;
2208 : }
2209 41512 : Measure* m = toMeasure(mb);
2210 41512 : if (m == system->measures().front() || (m->prev() && m->prev()->isHBox())) {
2211 15907 : MeasureLayout::createSystemBeginBarLine(m, ctx);
2212 : }
2213 : }
2214 15870 : }
2215 :
2216 : //---------------------------------------------------------
2217 : // layout2
2218 : // called after measure layout
2219 : // adjusts staff distance
2220 : //---------------------------------------------------------
2221 :
2222 10424 : void SystemLayout::layout2(System* system, LayoutContext& ctx)
2223 : {
2224 10439 : TRACEFUNC;
2225 : LAYOUT_CALL() << LAYOUT_ITEM_INFO(system);
2226 :
2227 10424 : Box* vb = system->vbox();
2228 10424 : if (vb) {
2229 2474 : BoxLayout::layoutBox(vb, vb->mutldata(), ctx);
2230 2474 : system->setbbox(vb->ldata()->bbox());
2231 2474 : return;
2232 : }
2233 :
2234 7950 : system->setPos(0.0, 0.0);
2235 7950 : std::vector<std::pair<size_t, SysStaff*> > visibleStaves;
2236 :
2237 20541 : for (size_t i = 0; i < system->staves().size(); ++i) {
2238 12591 : const Staff* s = ctx.dom().staff(i);
2239 12591 : SysStaff* ss = system->staves().at(i);
2240 12591 : if (s->show() && ss->show()) {
2241 11817 : visibleStaves.push_back(std::pair<size_t, SysStaff*>(i, ss));
2242 : } else {
2243 774 : ss->setbbox(RectF()); // already done in layout() ?
2244 : }
2245 : }
2246 :
2247 7950 : double _spatium = system->spatium();
2248 7950 : double y = 0.0;
2249 7950 : double minVerticalDistance = ctx.conf().styleAbsolute(Sid::minVerticalDistance);
2250 7950 : double staffDistance = ctx.conf().styleAbsolute(Sid::staffDistance);
2251 7950 : double akkoladeDistance = ctx.conf().styleAbsolute(Sid::akkoladeDistance);
2252 7950 : if (ctx.conf().isVerticalSpreadEnabled()) {
2253 5793 : staffDistance = ctx.conf().styleAbsolute(Sid::minStaffSpread);
2254 5793 : akkoladeDistance = ctx.conf().styleAbsolute(Sid::minStaffSpread);
2255 : }
2256 :
2257 7950 : if (visibleStaves.empty()) {
2258 0 : return;
2259 : }
2260 :
2261 7950 : for (auto i = visibleStaves.begin();; ++i) {
2262 11817 : SysStaff* ss = i->second;
2263 11817 : staff_idx_t si1 = i->first;
2264 11817 : const Staff* staff = ctx.dom().staff(si1);
2265 11817 : auto ni = std::next(i);
2266 :
2267 11817 : double dist = staff->staffHeight();
2268 : double yOffset;
2269 : double h;
2270 11817 : if (staff->lines(Fraction(0, 1)) == 1) {
2271 22 : yOffset = _spatium * BARLINE_SPAN_1LINESTAFF_TO * 0.5;
2272 22 : h = _spatium * (BARLINE_SPAN_1LINESTAFF_TO - BARLINE_SPAN_1LINESTAFF_FROM) * 0.5;
2273 : } else {
2274 11795 : yOffset = 0.0;
2275 11795 : h = staff->staffHeight();
2276 : }
2277 11817 : if (ni == visibleStaves.end()) {
2278 7950 : ss->setYOff(yOffset);
2279 7950 : ss->setbbox(system->leftMargin(), y - yOffset, system->width() - system->leftMargin(), h);
2280 7950 : ss->saveLayout();
2281 7950 : break;
2282 : }
2283 :
2284 3867 : staff_idx_t si2 = ni->first;
2285 3867 : const Staff* staff2 = ctx.dom().staff(si2);
2286 :
2287 3867 : if (staff->part() == staff2->part()) {
2288 1368 : Measure* m = system->firstMeasure();
2289 1368 : double mag = m ? staff->staffMag(m->tick()) : 1.0;
2290 1368 : dist += akkoladeDistance * mag;
2291 : } else {
2292 2499 : dist += staffDistance;
2293 : }
2294 3867 : dist += staff2->absoluteFromSpatium(staff2->userDist());
2295 3867 : bool fixedSpace = false;
2296 18806 : for (const MeasureBase* mb : system->measures()) {
2297 14939 : if (!mb->isMeasure()) {
2298 47 : continue;
2299 : }
2300 14892 : const Measure* m = toMeasure(mb);
2301 14892 : Spacer* sp = m->vspacerDown(si1);
2302 14892 : if (sp) {
2303 0 : if (sp->spacerType() == SpacerType::FIXED) {
2304 0 : dist = staff->staffHeight(m->tick()) + sp->absoluteGap();
2305 0 : fixedSpace = true;
2306 0 : break;
2307 : } else {
2308 0 : dist = std::max(dist, staff->staffHeight(m->tick()) + sp->absoluteGap());
2309 : }
2310 : }
2311 14892 : sp = m->vspacerUp(si2);
2312 14892 : if (sp) {
2313 0 : dist = std::max(dist, staff->staffHeight(m->tick()) + sp->absoluteGap());
2314 : }
2315 : }
2316 3867 : if (!fixedSpace) {
2317 : // check minimum distance to next staff
2318 : // note that in continuous view, we normally only have a partial skyline for the system
2319 : // a full one is only built when triggering a full layout
2320 : // therefore, we don't know the value we get from minDistance will actually be enough
2321 : // so we remember the value between layouts and increase it when necessary
2322 : // (the first layout on switching to continuous view gives us good initial values)
2323 : // the result is space is good to start and grows as needed
2324 : // it does not, however, shrink when possible - only by trigger a full layout
2325 : // (such as by toggling to page view and back)
2326 3867 : const double minHorizontalClearance = ctx.conf().styleAbsolute(Sid::skylineMinHorizontalClearance);
2327 3867 : double d = ss->skyline().minDistance(system->System::staff(si2)->skyline(), minHorizontalClearance);
2328 3867 : if (ctx.conf().isLineMode()) {
2329 0 : double previousDist = ss->continuousDist();
2330 0 : if (d > previousDist) {
2331 0 : ss->setContinuousDist(d);
2332 : } else {
2333 0 : d = previousDist;
2334 : }
2335 : }
2336 3867 : dist = std::max(dist, d + minVerticalDistance);
2337 3867 : dist = std::max(dist, minVertSpaceForCrossStaffBeams(system, si1, si2, ctx));
2338 : }
2339 3867 : ss->setYOff(yOffset);
2340 3867 : ss->setbbox(system->leftMargin(), y - yOffset, system->width() - system->leftMargin(), h);
2341 3867 : ss->saveLayout();
2342 3867 : y += dist;
2343 3867 : }
2344 :
2345 7950 : system->setSystemHeight(system->staff(visibleStaves.back().first)->bbox().bottom());
2346 7950 : system->setHeight(system->systemHeight());
2347 :
2348 7950 : SystemLayout::setMeasureHeight(system, system->systemHeight(), ctx);
2349 :
2350 : //---------------------------------------------------
2351 : // layout brackets vertical position
2352 : //---------------------------------------------------
2353 :
2354 7950 : SystemHeaderLayout::layoutBracketsVertical(system, ctx);
2355 :
2356 : //---------------------------------------------------
2357 : // layout instrument names
2358 : //---------------------------------------------------
2359 :
2360 7950 : SystemHeaderLayout::setInstrumentNamesVerticalPos(system, ctx);
2361 10424 : }
2362 :
2363 3867 : double SystemLayout::minVertSpaceForCrossStaffBeams(System* system, staff_idx_t staffIdx1, staff_idx_t staffIdx2, LayoutContext& ctx)
2364 : {
2365 3867 : double minSpace = -DBL_MAX;
2366 3867 : track_idx_t startTrack = staffIdx1 * VOICES;
2367 3867 : track_idx_t endTrack = staffIdx2 * VOICES + VOICES;
2368 18806 : for (MeasureBase* mb : system->measures()) {
2369 14939 : if (!mb->isMeasure()) {
2370 47 : continue;
2371 : }
2372 71525 : for (Segment& segment : toMeasure(mb)->segments()) {
2373 56633 : if (!segment.isChordRestType()) {
2374 29422 : continue;
2375 : }
2376 248551 : for (track_idx_t track = startTrack; track < endTrack; ++track) {
2377 221340 : EngravingItem* item = segment.element(track);
2378 221340 : if (!item || !item->isChord()) {
2379 221324 : continue;
2380 : }
2381 23849 : Beam* beam = toChord(item)->beam();
2382 23849 : if (!beam || !beam->autoplace() || beam->elements().front() != item) {
2383 22466 : continue;
2384 : }
2385 1383 : if (beam->ldata()->crossStaffBeamPos != BeamBase::CrossStaffBeamPosition::BETWEEN) {
2386 1367 : continue;
2387 : }
2388 16 : const Chord* limitingChordAbove = nullptr;
2389 16 : const Chord* limitingChordBelow = nullptr;
2390 16 : double limitFromAbove = -DBL_MAX;
2391 16 : double limitFromBelow = DBL_MAX;
2392 70 : for (const ChordRest* cr : beam->elements()) {
2393 54 : if (!cr->isChord()) {
2394 0 : continue;
2395 : }
2396 54 : const Chord* chord = toChord(cr);
2397 54 : double minStemLength = BeamTremoloLayout::minStemLength(chord, beam->ldata()) * (chord->spatium() / 4);
2398 54 : bool isUnderCrossBeam = cr->isBelowCrossBeam(beam);
2399 54 : if (isUnderCrossBeam && chord->vStaffIdx() == staffIdx2) {
2400 26 : const Note* topNote = chord->upNote();
2401 26 : double noteLimit = topNote->y() - minStemLength;
2402 26 : if (noteLimit < limitFromBelow) {
2403 18 : limitFromBelow = noteLimit;
2404 18 : limitingChordBelow = chord;
2405 : }
2406 26 : limitFromBelow = std::min(limitFromBelow, noteLimit);
2407 28 : } else if (!isUnderCrossBeam && chord->vStaffIdx() == staffIdx1) {
2408 28 : const Note* bottomNote = chord->downNote();
2409 28 : double noteLimit = bottomNote->y() + minStemLength;
2410 28 : if (noteLimit > limitFromAbove) {
2411 22 : limitFromAbove = noteLimit;
2412 22 : limitingChordAbove = chord;
2413 : }
2414 : }
2415 : }
2416 16 : if (limitingChordAbove && limitingChordBelow) {
2417 16 : double minSpaceRequired = limitFromAbove - limitFromBelow;
2418 16 : beam->mutldata()->limitingChordAbove = limitingChordAbove;
2419 16 : beam->mutldata()->limitingChordBelow = limitingChordBelow;
2420 :
2421 16 : const BeamSegment* topBeamSegmentForChordAbove = beam->topLevelSegmentForElement(limitingChordAbove);
2422 16 : const BeamSegment* topBeamSegmentForChordBelow = beam->topLevelSegmentForElement(limitingChordBelow);
2423 16 : if (topBeamSegmentForChordAbove->above == topBeamSegmentForChordBelow->above) {
2424 : // In this case the two opposing stems overlap the beam height, so we must subtract it
2425 16 : int strokeCount = std::min(BeamTremoloLayout::strokeCount(beam->ldata(), limitingChordAbove),
2426 16 : BeamTremoloLayout::strokeCount(beam->ldata(), limitingChordBelow));
2427 16 : double beamHeight = ctx.conf().styleAbsolute(Sid::beamWidth) + beam->beamDist() * (strokeCount - 1);
2428 16 : minSpaceRequired -= beamHeight;
2429 : }
2430 16 : minSpace = std::max(minSpace, minSpaceRequired);
2431 : }
2432 : }
2433 : }
2434 : }
2435 :
2436 3867 : return minSpace;
2437 : }
2438 :
2439 11516 : void SystemLayout::restoreLayout2(System* system, LayoutContext& ctx)
2440 : {
2441 11531 : TRACEFUNC;
2442 11516 : if (system->vbox()) {
2443 2566 : return;
2444 : }
2445 :
2446 22753 : for (SysStaff* s : system->staves()) {
2447 13803 : s->restoreLayout();
2448 : }
2449 :
2450 8950 : system->setHeight(system->systemHeight());
2451 8950 : SystemLayout::setMeasureHeight(system, system->systemHeight(), ctx);
2452 :
2453 : // Reused systems can move across pages during partial relayout.
2454 : // Refresh geometry derived from SysStaff vertical positions.
2455 8950 : SystemHeaderLayout::layoutBracketsVertical(system, ctx);
2456 8950 : SystemHeaderLayout::setInstrumentNamesVerticalPos(system, ctx);
2457 11516 : }
2458 :
2459 23007 : void SystemLayout::setMeasureHeight(System* system, double height, const LayoutContext& ctx)
2460 : {
2461 23007 : double spatium = system->spatium();
2462 122166 : for (MeasureBase* m : system->measures()) {
2463 99159 : MeasureBase::LayoutData* mldata = m->mutldata();
2464 99159 : if (m->isMeasure()) {
2465 : // note that the factor 2 * _spatium must be corrected for when exporting
2466 : // system distance in MusicXML (issue #24733)
2467 98782 : mldata->setBbox(0.0, -spatium, m->width(), height + 2.0 * spatium);
2468 377 : } else if (m->isHBox()) {
2469 377 : mldata->setBbox(m->absoluteFromSpatium(toHBox(m)->topGap()), 0.0, m->width(), height);
2470 377 : BoxLayout::layoutHBox2(toHBox(m), ctx);
2471 0 : } else if (m->isTBox()) {
2472 0 : BoxLayout::layoutTBox(toTBox(m), toTBox(m)->mutldata(), ctx);
2473 0 : } else if (m->isFBox()) {
2474 0 : BoxLayout::layoutFBox(toFBox(m), toFBox(m)->mutldata(), ctx);
2475 : } else {
2476 0 : LOGD("unhandled measure type %s", m->typeName());
2477 : }
2478 : }
2479 23007 : }
2480 :
2481 : //---------------------------------------------------------
2482 : // minDistance
2483 : // Return the minimum distance between this system and s2
2484 : // without any element collisions.
2485 : //
2486 : // top - top system
2487 : // bottom - bottom system
2488 : //---------------------------------------------------------
2489 :
2490 13787 : double SystemLayout::minDistance(const System* top, const System* bottom, const LayoutContext& ctx)
2491 : {
2492 13800 : TRACEFUNC;
2493 :
2494 13787 : const LayoutConfiguration& conf = ctx.conf();
2495 13787 : const DomAccessor& dom = ctx.dom();
2496 :
2497 13787 : const VBox* topVBox = static_cast<VBox*>(top->vbox());
2498 13787 : const VBox* bottomVBox = static_cast<VBox*>(bottom->vbox());
2499 :
2500 13787 : if (topVBox && !bottomVBox) {
2501 4796 : return std::max(topVBox->absoluteFromSpatium(topVBox->bottomGap()),
2502 9592 : bottom->minTop() + topVBox->absoluteFromSpatium(topVBox->paddingToNotationBelow()));
2503 8991 : } else if (!topVBox && bottomVBox) {
2504 109 : return std::max(bottomVBox->absoluteFromSpatium(bottomVBox->topGap()),
2505 218 : top->minBottom() + bottomVBox->absoluteFromSpatium(bottomVBox->paddingToNotationAbove()));
2506 8882 : } else if (topVBox && bottomVBox) {
2507 167 : const double topToBottomGap = topVBox->absoluteFromSpatium(topVBox->bottomGap());
2508 167 : const double bottomToTopGap = bottomVBox->absoluteFromSpatium(bottomVBox->topGap());
2509 167 : if (topToBottomGap >= 0 && bottomToTopGap >= 0) {
2510 167 : double largestGap = std::max(bottomToTopGap, topToBottomGap);
2511 167 : return largestGap;
2512 : } else {
2513 0 : return topToBottomGap + bottomToTopGap;
2514 : }
2515 : }
2516 :
2517 8715 : if (top->staves().empty() || bottom->staves().empty()) {
2518 0 : return 0.0;
2519 : }
2520 :
2521 8715 : double minVerticalDistance = conf.styleAbsolute(Sid::minVerticalDistance);
2522 8715 : double dist = conf.isVerticalSpreadEnabled() ? conf.styleAbsolute(Sid::minSystemSpread) : conf.styleAbsolute(Sid::minSystemDistance);
2523 8715 : size_t firstStaff = 0;
2524 8715 : size_t lastStaff = 0;
2525 :
2526 8769 : for (firstStaff = 0; firstStaff < top->staves().size() - 1; ++firstStaff) {
2527 2878 : if (dom.staff(firstStaff)->show() && bottom->staff(firstStaff)->show()) {
2528 2824 : break;
2529 : }
2530 : }
2531 9588 : for (lastStaff = top->staves().size() - 1; lastStaff > 0; --lastStaff) {
2532 3418 : if (dom.staff(lastStaff)->show() && top->staff(lastStaff)->show()) {
2533 2545 : break;
2534 : }
2535 : }
2536 :
2537 8715 : const Staff* staff = dom.staff(firstStaff);
2538 8715 : double userDist = staff ? staff->absoluteFromSpatium(staff->userDist()) : 0.0;
2539 8715 : dist = std::max(dist, userDist);
2540 8715 : top->setFixedDownDistance(false);
2541 :
2542 8715 : const SysStaff* sysStaff = top->staff(lastStaff);
2543 8715 : const double minHorizontalClearance = conf.styleAbsolute(Sid::skylineMinHorizontalClearance);
2544 8715 : double sld = sysStaff ? sysStaff->skyline().minDistance(bottom->staff(firstStaff)->skyline(), minHorizontalClearance) : 0;
2545 8715 : sld -= sysStaff ? sysStaff->bbox().height() - minVerticalDistance : 0;
2546 :
2547 8715 : if (conf.isFloatMode()) {
2548 0 : return std::max(dist, sld);
2549 : }
2550 :
2551 58286 : for (const MeasureBase* mb1 : top->measures()) {
2552 49575 : if (mb1->isMeasure()) {
2553 49435 : const Measure* m = toMeasure(mb1);
2554 49435 : const Spacer* sp = m->vspacerDown(lastStaff);
2555 49435 : if (sp) {
2556 4 : if (sp->spacerType() == SpacerType::FIXED) {
2557 4 : dist = sp->absoluteGap();
2558 4 : top->setFixedDownDistance(true);
2559 4 : break;
2560 : } else {
2561 0 : dist = std::max(dist, sp->absoluteGap());
2562 : }
2563 : }
2564 : }
2565 : }
2566 8715 : if (!top->hasFixedDownDistance()) {
2567 52089 : for (const MeasureBase* mb2 : bottom->measures()) {
2568 43378 : if (mb2->isMeasure()) {
2569 43248 : const Measure* m = toMeasure(mb2);
2570 43248 : const Spacer* sp = m->vspacerUp(firstStaff);
2571 43248 : if (sp) {
2572 0 : dist = std::max(dist, sp->absoluteGap());
2573 : }
2574 : }
2575 : }
2576 :
2577 8711 : dist = std::max(dist, sld);
2578 : }
2579 8715 : return dist;
2580 13787 : }
2581 :
2582 4797 : static bool itemIsPlacedAbove(const EngravingItem* item)
2583 : {
2584 4797 : if (item->isArticulationFamily()) {
2585 2 : return toArticulation(item)->up();
2586 : }
2587 4795 : if (item->isLyricsLineSegment()) {
2588 0 : return toLyricsLineSegment(item)->lyricsPlaceAbove();
2589 : }
2590 4795 : return item->placeAbove();
2591 : }
2592 :
2593 0 : void SystemLayout::removeElementFromSkyline(EngravingItem* element, const System* system)
2594 : {
2595 0 : Skyline& skyline = system->staff(element->staffIdx())->skyline();
2596 0 : SkylineLine& skylineLine = itemIsPlacedAbove(element) ? skyline.north() : skyline.south();
2597 :
2598 0 : skylineLine.remove_if([element](ShapeElement& shapeEl) {
2599 0 : return shapeEl.item() && (element == shapeEl.item() || element == shapeEl.item()->ownershipParent());
2600 : });
2601 0 : }
2602 :
2603 4797 : void SystemLayout::updateSkylineForElement(EngravingItem* element, const System* system, double yMove)
2604 : {
2605 4797 : Skyline& skyline = system->staff(element->staffIdx())->skyline();
2606 4797 : SkylineLine& skylineLine = itemIsPlacedAbove(element) ? skyline.north() : skyline.south();
2607 142613 : for (ShapeElement& shapeEl : skylineLine.elements()) {
2608 137816 : const EngravingItem* itemInSkyline = shapeEl.item();
2609 137816 : if (itemInSkyline && itemInSkyline->isText()) {
2610 0 : const EngravingItem* owner = itemInSkyline->ownershipParentItem();
2611 0 : if (owner && owner->isSLineSegment()) {
2612 0 : itemInSkyline = owner;
2613 : }
2614 : }
2615 137816 : if (itemInSkyline == element) {
2616 8614 : shapeEl.translate(0.0, yMove);
2617 : }
2618 : }
2619 4797 : }
2620 :
2621 11519 : void SystemLayout::centerElementsBetweenStaves(const System* system)
2622 : {
2623 11519 : std::vector<Gap> gaps; // populated by collectCenterableItems
2624 11519 : std::vector<MMRest*> mmRestsToCenter; // populated by collectCenterableItems
2625 :
2626 11519 : collectCenterableItems(system, gaps, mmRestsToCenter);
2627 :
2628 11533 : for (MMRest* mmrest : mmRestsToCenter) {
2629 14 : centerMMRestBetweenStaves(mmrest, system);
2630 : }
2631 :
2632 11519 : const double minHorizontalClearance = system->style().styleAbsolute(Sid::skylineMinHorizontalClearance);
2633 :
2634 15606 : for (const Gap& gap : gaps) {
2635 4087 : if (!gap.items.empty()) {
2636 129 : centerItemsInGap(gap, system, minHorizontalClearance);
2637 : }
2638 : }
2639 11519 : }
2640 :
2641 4413 : void SystemLayout::centerPendingSystems(LayoutContext& ctx)
2642 : {
2643 4416 : for (System* system : ctx.state().systemsNeedingCentering()) {
2644 3 : centerElementsBetweenStaves(system);
2645 : }
2646 :
2647 4413 : ctx.mutState().clearSystemsNeedingCentering();
2648 4413 : }
2649 :
2650 257 : static Shape shapeRelativeToStaff(const EngravingItem* item, double systemX)
2651 : {
2652 : // Offsets are applied after centering, so measure from the non-offset position
2653 257 : const double x = item->pageX() - systemX - item->offset().x();
2654 257 : const double y = item->isLyrics() ? toLyrics(item)->yRelativeToStaff() - item->offset().y() : item->ldata()->pos().y();
2655 257 : return item->ldata()->shape().translated(PointF(x, y));
2656 : }
2657 :
2658 11519 : void SystemLayout::collectCenterableItems(const System* system, std::vector<Gap>& gaps, std::vector<MMRest*>& mmRestsToCenter)
2659 : {
2660 11519 : const size_t nStaves = system->staves().size();
2661 11519 : if (nStaves < 2) {
2662 8698 : return;
2663 : }
2664 :
2665 : struct GapsOfStaff {
2666 : size_t forItemsBelow = muse::nidx;
2667 : size_t forItemsAbove = muse::nidx;
2668 : };
2669 2821 : std::vector<GapsOfStaff> gapsOfStaff(nStaves);
2670 2821 : gaps.reserve(nStaves - 1);
2671 :
2672 2821 : staff_idx_t upperStaffIdx = system->firstVisibleStaff();
2673 2821 : staff_idx_t lowerStaffIdx = muse::nidx;
2674 6908 : for (; upperStaffIdx < nStaves; upperStaffIdx = lowerStaffIdx) {
2675 6908 : lowerStaffIdx = system->nextVisibleStaff(upperStaffIdx);
2676 6908 : if (lowerStaffIdx == muse::nidx) {
2677 2821 : break; // the last visible staff of the system
2678 : }
2679 :
2680 4087 : gapsOfStaff[upperStaffIdx].forItemsBelow = gaps.size();
2681 4087 : gapsOfStaff[lowerStaffIdx].forItemsAbove = gaps.size();
2682 4087 : gaps.emplace_back(upperStaffIdx, lowerStaffIdx, system->staff(lowerStaffIdx)->y() - system->staff(upperStaffIdx)->y());
2683 : }
2684 :
2685 2821 : const double systemX = system->pageX();
2686 :
2687 258 : auto addItem = [&](EngravingItem* item, bool above, bool isLyrics) {
2688 258 : const staff_idx_t staffIdx = item->staffIdx();
2689 258 : if (staffIdx >= nStaves) {
2690 1 : return;
2691 : }
2692 258 : const size_t gapIdx = above ? gapsOfStaff[staffIdx].forItemsAbove : gapsOfStaff[staffIdx].forItemsBelow;
2693 258 : if (gapIdx == muse::nidx) {
2694 : // The staff is hidden, or there is no staff on that side to center against
2695 1 : return;
2696 : }
2697 :
2698 257 : Shape shape = shapeRelativeToStaff(item, systemX);
2699 702 : shape.remove_if([](ShapeElement& shapeEl) { return shapeEl.ignoreForLayout(); });
2700 :
2701 : // Items left out of the skyline (e.g. invisible) must not take up space in the gap
2702 257 : const bool takesSpace = item->isLyricsLineSegment() ? toLyricsLineSegment(item)->lyricsAddToSkyline()
2703 257 : : item->addToSkyline();
2704 257 : if (!takesSpace) {
2705 0 : shape.clear();
2706 : }
2707 :
2708 257 : Gap& gap = gaps[gapIdx];
2709 257 : if (above) {
2710 : // Inside a gap, everything is expressed relative to its upper staff
2711 20 : shape.translate(PointF(0.0, gap.yStaffDiff));
2712 : }
2713 257 : gap.items.push_back(CenterableItem { item, std::move(shape), isLyrics, !above });
2714 257 : };
2715 :
2716 5306 : for (SpannerSegment* spannerSeg : system->spannerSegments()) {
2717 2739 : if ((spannerSeg->isHairpinSegment() && snapChainShouldBeCenteredBetweenStaves(spannerSeg, system))
2718 2739 : || (spannerSeg->isWhammyBarSegment() && whammyBarShouldBeCenteredBetweenStaves(toWhammyBarSegment(spannerSeg), system))) {
2719 114 : addItem(spannerSeg, spannerSeg->placeAbove(), false);
2720 2371 : } else if (spannerSeg->isLyricsLineSegment()) {
2721 185 : bool above = toLyricsLineSegment(spannerSeg)->lyricsPlaceAbove();
2722 185 : if (elementShouldBeCenteredBetweenStaves(spannerSeg, system, above)) {
2723 0 : addItem(spannerSeg, above, true);
2724 : }
2725 : }
2726 : }
2727 :
2728 16016 : for (const MeasureBase* mb : system->measures()) {
2729 13195 : if (!mb->isMeasure()) {
2730 54 : continue;
2731 : }
2732 60080 : for (const Segment& seg : toMeasure(mb)->segments()) {
2733 46939 : if (seg.isChordRestType()) {
2734 249776 : for (EngravingItem* item : seg.elist()) {
2735 226632 : if (!item) {
2736 175436 : continue;
2737 : }
2738 51196 : if (item->isMMRest() && mmRestShouldBeCenteredBetweenStaves(toMMRest(item), system)) {
2739 14 : mmRestsToCenter.push_back(toMMRest(item));
2740 51182 : } else if (item->isChordRest()) {
2741 52619 : for (Lyrics* lyrics : toChordRest(item)->lyrics()) {
2742 1437 : bool above = lyrics->placeAbove();
2743 1437 : if (elementShouldBeCenteredBetweenStaves(lyrics, system, above)) {
2744 0 : addItem(lyrics, above, true);
2745 : }
2746 : }
2747 : }
2748 : }
2749 : }
2750 49171 : for (EngravingItem* item : seg.annotations()) {
2751 2232 : if ((item->isDynamic() || item->isExpression()) && snapChainShouldBeCenteredBetweenStaves(item, system)) {
2752 144 : addItem(item, item->placeAbove(), false);
2753 : }
2754 : }
2755 : }
2756 : }
2757 2821 : }
2758 :
2759 188 : bool SystemLayout::shapesStackVertically(const Shape& shape1, const Shape& shape2, double minHorizontalClearance)
2760 : {
2761 434 : for (const ShapeElement& shapeEl1 : shape1.elements()) {
2762 260 : if (shapeEl1.height() <= 0.0) {
2763 0 : continue;
2764 : }
2765 748 : for (const ShapeElement& shapeEl2 : shape2.elements()) {
2766 502 : if (shapeEl2.height() <= 0.0) {
2767 0 : continue;
2768 : }
2769 502 : if (intersects(shapeEl1.left(), shapeEl1.right(), shapeEl2.left(), shapeEl2.right(), minHorizontalClearance)) {
2770 14 : return true;
2771 : }
2772 : }
2773 : }
2774 :
2775 174 : return false;
2776 : }
2777 :
2778 0 : void SystemLayout::centerBigTimeSigsAcrossStaves(const System* system)
2779 : {
2780 0 : staff_idx_t nstaves = system->score()->nstaves();
2781 0 : for (MeasureBase* mb : system->measures()) {
2782 0 : if (!mb->isMeasure()) {
2783 0 : continue;
2784 : }
2785 0 : for (Segment& segment : toMeasure(mb)->segments()) {
2786 0 : if (!segment.isType(SegmentType::TimeSigTypes)) {
2787 0 : continue;
2788 : }
2789 0 : for (staff_idx_t staffIdx = 0; staffIdx < nstaves; ++staffIdx) {
2790 0 : TimeSig* timeSig = toTimeSig(segment.element(staff2track(staffIdx)));
2791 0 : if (!timeSig || !timeSig->showOnThisStaff()) {
2792 0 : continue;
2793 : }
2794 0 : staff_idx_t thisStaffIdx = timeSig->effectiveStaffIdx();
2795 0 : if (thisStaffIdx == muse::nidx) {
2796 0 : continue;
2797 : }
2798 0 : staff_idx_t nextStaffIdx = thisStaffIdx;
2799 0 : for (staff_idx_t idx = thisStaffIdx + 1; idx < nstaves; ++idx) {
2800 0 : TimeSig* nextTimeSig = toTimeSig(segment.element(staff2track(idx)));
2801 0 : if (nextTimeSig && nextTimeSig->showOnThisStaff()) {
2802 0 : staff_idx_t nextTimeSigStave = nextTimeSig->effectiveStaffIdx();
2803 0 : if (nextTimeSigStave != muse::nidx) {
2804 0 : nextStaffIdx = system->prevVisibleStaff(nextTimeSigStave);
2805 0 : break;
2806 : }
2807 : }
2808 0 : if (idx == nstaves - 1) {
2809 0 : nextStaffIdx = system->prevVisibleStaff(nstaves);
2810 0 : break;
2811 : }
2812 : }
2813 0 : double yTop = system->staff(thisStaffIdx)->y() + system->score()->staff(thisStaffIdx)->staffHeight(segment.tick());
2814 0 : double yBottom = system->staff(nextStaffIdx)->y() + system->score()->staff(nextStaffIdx)->staffHeight(segment.tick());
2815 0 : double newYPos = 0.5 * (yBottom - yTop);
2816 0 : timeSig->mutldata()->setPosY(newYPos);
2817 : }
2818 : }
2819 : }
2820 0 : }
2821 :
2822 773 : bool SystemLayout::snapChainShouldBeCenteredBetweenStaves(EngravingItem* item, const System* system)
2823 : {
2824 : // Snapped items are centered as one, so if any of them cannot be centered, none of them can
2825 773 : bool allCenterable = true;
2826 773 : item->ldata()->scanConnectedItemsInSnappingChain(system, [&allCenterable, system](EngravingItem* chainItem) {
2827 953 : allCenterable = allCenterable && elementShouldBeCenteredBetweenStaves(chainItem, system, chainItem->placeAbove());
2828 953 : });
2829 :
2830 773 : return allCenterable;
2831 : }
2832 :
2833 2495 : bool SystemLayout::elementShouldBeCenteredBetweenStaves(const EngravingItem* item, const System* system, bool placeAbove)
2834 : {
2835 2495 : const Part* itemPart = item->part();
2836 2495 : IF_ASSERT_FAILED(itemPart) {
2837 0 : return false;
2838 : }
2839 :
2840 2495 : const Staff* otherStaff = item->staffToCenterAgainst(placeAbove, system);
2841 2495 : if (!otherStaff) {
2842 1809 : return false;
2843 : }
2844 :
2845 686 : const bool sameInstrument = otherStaff->part() == itemPart;
2846 :
2847 : Sid centerStyleId;
2848 686 : if (item->isLyrics() || item->isLyricsLineSegment()) {
2849 212 : centerStyleId = sameInstrument ? Sid::lyricsAutoCenterOnGrandStaff : Sid::lyricsAutoCenterOnVocalStaves;
2850 474 : } else if (item->isDynamic() || item->isExpression() || item->isHairpinSegment()) {
2851 474 : centerStyleId = sameInstrument ? Sid::dynamicsHairpinsAutoCenterOnGrandStaff : Sid::dynamicsHairpinsAutoCenterOnVocalStaves;
2852 : } else {
2853 0 : return false;
2854 : }
2855 :
2856 : AutoOnOff centerProperty;
2857 686 : if (item->isLyricsLineSegment() && !item->isPartialLyricsLineSegment()) {
2858 : // A dash or melisma line belonging to a lyric has no setting of its own: it always
2859 : // follows that lyric. Only partial lyrics lines are configurable individually.
2860 49 : const Lyrics* lyrics = toLyricsLineSegment(item)->lyrics();
2861 49 : centerProperty = lyrics ? lyrics->centerBetweenStaves() : AutoOnOff::AUTO;
2862 : } else {
2863 637 : centerProperty = item->getProperty(Pid::CENTER_BETWEEN_STAVES).value<AutoOnOff>();
2864 : }
2865 :
2866 686 : const bool centerStyle = item->style().styleB(centerStyleId);
2867 686 : if (centerProperty == AutoOnOff::OFF || (!centerStyle && centerProperty != AutoOnOff::ON)) {
2868 261 : return false;
2869 : }
2870 :
2871 425 : if (sameInstrument && centerProperty != AutoOnOff::ON && !itemPart->instrument()->isNormallyMultiStaveInstrument()) {
2872 65 : return false;
2873 : }
2874 :
2875 360 : if (item->isDynamic() || item->isExpression() || item->isHairpinSegment()) {
2876 360 : if (!(centerProperty == AutoOnOff::ON || item->appliesToAllVoicesInInstrument())) {
2877 2 : return false;
2878 : }
2879 : }
2880 :
2881 358 : return true;
2882 : }
2883 :
2884 62 : bool SystemLayout::mmRestShouldBeCenteredBetweenStaves(const MMRest* mmRest, const System* system)
2885 : {
2886 62 : if (!mmRest->style().styleB(Sid::mmRestBetweenStaves)) {
2887 0 : return false;
2888 : }
2889 :
2890 62 : const Part* itemPart = mmRest->part();
2891 62 : if (itemPart->nstaves() <= 1) {
2892 34 : return false;
2893 : }
2894 :
2895 28 : staff_idx_t thisStaffIdx = mmRest->staffIdx();
2896 28 : staff_idx_t prevStaffIdx = system->prevVisibleStaff(thisStaffIdx);
2897 :
2898 28 : return prevStaffIdx != muse::nidx && mmRest->score()->staff(prevStaffIdx)->part() == itemPart;
2899 : }
2900 :
2901 0 : bool SystemLayout::whammyBarShouldBeCenteredBetweenStaves(const WhammyBarSegment* wbar, const System* system)
2902 : {
2903 0 : staff_idx_t staffIdx = wbar->staffIdx();
2904 0 : Staff* thisStaff = wbar->staff();
2905 0 : Staff* nextStaff = wbar->score()->staff(staffIdx + 1);
2906 0 : bool nextIsLinkedTab = nextStaff && nextStaff->isTabStaff(wbar->tick()) && thisStaff->isLinked(nextStaff);
2907 0 : SysStaff* nextSysStaff = system->staff(staffIdx + 1);
2908 0 : return wbar->placeBelow() && nextIsLinkedTab && nextSysStaff && nextSysStaff->show();
2909 : }
2910 :
2911 257 : bool SystemLayout::elementHasAnotherStackedOutside(const EngravingItem* element, const Shape& elementShape, const SkylineLine& skylineLine)
2912 : {
2913 257 : double elemShapeLeft = elementShape.left();
2914 257 : double elemShapeRight = elementShape.right();
2915 257 : double elemShapeTop = elementShape.top();
2916 257 : double elemShapeBottom = elementShape.bottom();
2917 :
2918 15637 : for (const ShapeElement& skylineElement : skylineLine.elements()) {
2919 15380 : const EngravingItem* skylineItem = skylineElement.item();
2920 15380 : if (!skylineItem || skylineItem == element || skylineItem->parent() == element || skylineItem->isAccidental()
2921 30760 : || Autoplace::itemsShouldIgnoreEachOther(element, skylineItem)) {
2922 360 : continue;
2923 : }
2924 15020 : bool intersectHorizontally = elemShapeRight > skylineElement.left() && elemShapeLeft < skylineElement.right();
2925 15020 : if (!intersectHorizontally) {
2926 12765 : continue;
2927 : }
2928 4472 : bool skylineElementIsStackedOnIt = skylineLine.isNorth() ? skylineElement.bottom() <= elemShapeTop
2929 2217 : : skylineElement.top() >= elemShapeBottom;
2930 2255 : if (skylineElementIsStackedOnIt) {
2931 0 : return true;
2932 : }
2933 : }
2934 :
2935 257 : return false;
2936 : }
2937 :
2938 258 : static SkylineLine skylineFacingGap(const System* system, staff_idx_t staffIdx, bool isUpperStaffOfGap, double yShift,
2939 : const std::unordered_set<const EngravingItem*>& itemsToIgnore)
2940 : {
2941 129 : const SkylineLine& skyline = isUpperStaffOfGap ? system->staff(staffIdx)->skyline().south()
2942 258 : : system->staff(staffIdx)->skyline().north();
2943 :
2944 516 : SkylineLine filteredSkyline = skyline.getFilteredCopy([&itemsToIgnore](const ShapeElement& shapeEl) {
2945 7809 : const EngravingItem* shapeItem = shapeEl.item();
2946 15177 : return shapeItem && (muse::contains(itemsToIgnore, shapeItem)
2947 15177 : || muse::contains(itemsToIgnore, const_cast<const EngravingItem*>(shapeItem->ownershipParentItem())));
2948 258 : });
2949 :
2950 258 : if (yShift != 0.0) {
2951 129 : filteredSkyline.translateY(yShift);
2952 : }
2953 :
2954 258 : return filteredSkyline;
2955 0 : }
2956 :
2957 129 : void SystemLayout::centerItemsInGap(const Gap& gap, const System* system, double minHorizontalClearance)
2958 : {
2959 : /* Nothing which is itself centered in this gap may take part in measuring it */
2960 129 : std::unordered_set<const EngravingItem*> movableItems;
2961 386 : for (const CenterableItem& gapItem : gap.items) {
2962 257 : movableItems.insert(gapItem.item);
2963 : }
2964 :
2965 0 : auto getVerse = [](const EngravingItem* item) {
2966 0 : if (item->isLyrics()) {
2967 0 : return toLyrics(item)->verse();
2968 0 : } else if (item->isLyricsLineSegment()) {
2969 0 : return toLyricsLineSegment(item)->verse();
2970 : }
2971 0 : return -1;
2972 : };
2973 :
2974 : /* An item with something non-centered stacked outside it has no gap to be centered in: it
2975 : * stays where it is and joins the skyline, so that it constrains the items which do move */
2976 129 : while (!movableItems.empty()) {
2977 129 : const SkylineLine upperSkyline = skylineFacingGap(system, gap.upperStaffIdx, true, 0.0, movableItems);
2978 129 : const SkylineLine lowerSkyline = skylineFacingGap(system, gap.lowerStaffIdx, false, gap.yStaffDiff, movableItems);
2979 :
2980 129 : std::vector<const CenterableItem*> itemsToCenter;
2981 129 : bool canCenterGroup = true;
2982 386 : for (const CenterableItem& gapItem : gap.items) {
2983 257 : const EngravingItem* item = gapItem.item;
2984 257 : if (!muse::contains(movableItems, item)) {
2985 0 : continue;
2986 : }
2987 :
2988 257 : const Shape itemShape = gapItem.shape.adjusted(-minHorizontalClearance, 0.0, minHorizontalClearance, 0.0);
2989 257 : const SkylineLine& ownSkyline = gapItem.onUpperGapStaff ? upperSkyline : lowerSkyline;
2990 257 : if (!itemShape.empty() && elementHasAnotherStackedOutside(item, itemShape, ownSkyline)) {
2991 0 : movableItems.erase(item);
2992 0 : canCenterGroup = false;
2993 :
2994 : // Snapped items stay together:
2995 0 : gapItem.item->ldata()->scanConnectedItemsInSnappingChain(system, [&movableItems](EngravingItem* chainItem) {
2996 0 : movableItems.erase(chainItem);
2997 0 : });
2998 :
2999 : // A lyrics verse stays together:
3000 0 : if (gapItem.isLyrics) {
3001 0 : int verse = getVerse(item);
3002 0 : for (const CenterableItem& i : gap.items) {
3003 0 : if (i.isLyrics && i.onUpperGapStaff == gapItem.onUpperGapStaff && getVerse(i.item) == verse) {
3004 0 : movableItems.erase(i.item);
3005 : }
3006 : }
3007 : }
3008 : } else {
3009 257 : itemsToCenter.push_back(&gapItem);
3010 : }
3011 257 : }
3012 :
3013 129 : if (!canCenterGroup) {
3014 0 : continue;
3015 : }
3016 :
3017 328 : for (const std::vector<const CenterableItem*>& group : groupItemsToCenterTogether(itemsToCenter, minHorizontalClearance)) {
3018 199 : centerItemGroup(group, system, upperSkyline, lowerSkyline, gap.yStaffDiff, minHorizontalClearance);
3019 129 : }
3020 129 : return;
3021 387 : }
3022 129 : }
3023 :
3024 129 : std::vector<std::vector<const SystemLayout::CenterableItem*> > SystemLayout::groupItemsToCenterTogether(
3025 : const std::vector<const CenterableItem*>& items, double minHorizontalClearance)
3026 : {
3027 : /* We center lyrics as a single block so that the verses will not lose their alignment (separating the ones
3028 : * below the upper staff from the ones above the lower staff if they don't overlap). Other centerable items
3029 : * join the group if they overlap horizontally, or if they are snapped to each other, so that they will
3030 : * preserve their relative positions. */
3031 129 : const size_t nItems = items.size();
3032 129 : std::vector<size_t> groupIds(nItems, muse::nidx);
3033 129 : size_t nGroupIds = 0;
3034 :
3035 386 : for (size_t i = 0; i < nItems; ++i) {
3036 257 : if (groupIds[i] == muse::nidx) {
3037 201 : groupIds[i] = nGroupIds++;
3038 : }
3039 488 : for (size_t j = i + 1; j < nItems; ++j) {
3040 231 : const bool areVersesOfTheSameBlock = items[i]->isLyrics && items[j]->isLyrics
3041 231 : && items[i]->onUpperGapStaff == items[j]->onUpperGapStaff;
3042 231 : const bool areSnappedTogether = items[i]->item->ldata()->itemSnappedBefore() == items[j]->item
3043 231 : || items[i]->item->ldata()->itemSnappedAfter() == items[j]->item;
3044 231 : const bool mustMoveTogether = areVersesOfTheSameBlock || areSnappedTogether
3045 462 : || shapesStackVertically(items[i]->shape, items[j]->shape, minHorizontalClearance);
3046 231 : if (!mustMoveTogether) {
3047 173 : continue;
3048 : }
3049 58 : if (groupIds[j] == muse::nidx) {
3050 56 : groupIds[j] = groupIds[i];
3051 2 : } else if (groupIds[j] != groupIds[i]) {
3052 2 : const size_t idToMerge = groupIds[j];
3053 2 : const size_t idToKeep = groupIds[i];
3054 12 : for (size_t& groupId : groupIds) {
3055 10 : if (groupId == idToMerge) {
3056 4 : groupId = idToKeep;
3057 : }
3058 : }
3059 : }
3060 : }
3061 : }
3062 :
3063 129 : std::vector<size_t> groupIdToIndex(nGroupIds, muse::nidx);
3064 129 : std::vector<std::vector<const CenterableItem*> > groups;
3065 :
3066 386 : for (size_t i = 0; i < nItems; ++i) {
3067 257 : size_t& index = groupIdToIndex[groupIds[i]];
3068 257 : if (index == muse::nidx) {
3069 199 : index = groups.size();
3070 199 : groups.emplace_back();
3071 : }
3072 257 : groups[index].push_back(items[i]);
3073 : }
3074 :
3075 129 : return groups;
3076 129 : }
3077 :
3078 : // How far an item moves when its group is converged: only the half sitting above the lower staff moves to meet the upper one
3079 257 : double SystemLayout::convergenceMoveFor(const CenterableItem* centerableItem, double convergeDistance)
3080 : {
3081 257 : return centerableItem->onUpperGapStaff ? 0.0 : -convergeDistance;
3082 : }
3083 :
3084 199 : double SystemLayout::gapConvergeDistance(const std::vector<const CenterableItem*>& group, double yStaffDiff, double minHorizontalClearance)
3085 : {
3086 : /* A group that has items below the upper staff and above the lower one, spreads over the whole gap and
3087 : * has no space left to center the items, so we bring the items together into the middle of the gap. This
3088 : * function calculates how much slack there is for the lower items to converge towards the upper ones
3089 : * before centering, so that they will be centered together. */
3090 :
3091 199 : double slack = DBL_MAX;
3092 456 : for (const CenterableItem* upper : group) {
3093 257 : if (!upper->onUpperGapStaff || upper->shape.empty()) {
3094 20 : continue;
3095 : }
3096 :
3097 588 : for (const CenterableItem* lower : group) {
3098 351 : if (lower->onUpperGapStaff || lower->shape.empty()) {
3099 343 : continue;
3100 : }
3101 8 : if (!shapesStackVertically(upper->shape, lower->shape, minHorizontalClearance)) {
3102 1 : continue;
3103 : }
3104 :
3105 7 : const EngravingItem* upperItem = upper->item;
3106 7 : const EngravingItem* lowerItem = lower->item;
3107 7 : const Lyrics* upperLyrics = upperItem->isLyrics() ? toLyrics(upperItem) : nullptr;
3108 7 : const Lyrics* lowerLyrics = lowerItem->isLyrics() ? toLyrics(lowerItem) : nullptr;
3109 :
3110 7 : if (upperLyrics && lowerLyrics) {
3111 : // The distance between the top-staff and bottom-staff lyrics blocks will be like between verses:
3112 0 : const double verseSpace = std::max(upperLyrics->lineSpacing(), lowerLyrics->lineSpacing())
3113 0 : * upperItem->style().styleD(Sid::lyricsLineHeight);
3114 0 : const double spaceBetweenLyrics = (lowerLyrics->yRelativeToStaff() - lowerLyrics->offset().y()) + yStaffDiff
3115 0 : - (upperLyrics->yRelativeToStaff() - upperLyrics->offset().y());
3116 0 : slack = std::min(slack, spaceBetweenLyrics - verseSpace);
3117 0 : continue;
3118 0 : }
3119 :
3120 : // If it's not lyrics, we just use the items' min distance
3121 7 : const double minDist = std::max(upperItem->absoluteFromSpatium(upperItem->minDistance()),
3122 7 : lowerItem->absoluteFromSpatium(lowerItem->minDistance()));
3123 7 : slack = std::min(slack, upper->shape.verticalClearance(lower->shape, minHorizontalClearance) - minDist);
3124 : }
3125 : }
3126 :
3127 : // Nothing to do for a group that is on one staff only, or whose halves are already as close as possible
3128 199 : return slack == DBL_MAX ? 0.0 : std::max(slack, 0.0);
3129 : }
3130 :
3131 199 : void SystemLayout::centerItemGroup(const std::vector<const CenterableItem*>& group, const System* system,
3132 : const SkylineLine& upperSkyline, const SkylineLine& lowerSkyline, double yStaffDiff,
3133 : double minHorizontalClearance)
3134 : {
3135 : // The least space each half has on either side
3136 199 : double upperHalfSpaceAbove = DBL_MAX;
3137 199 : double upperHalfSpaceBelow = DBL_MAX;
3138 199 : double lowerHalfSpaceAbove = DBL_MAX;
3139 199 : double lowerHalfSpaceBelow = DBL_MAX;
3140 :
3141 456 : for (const CenterableItem* centerableItem : group) {
3142 257 : const Shape itemShape = centerableItem->shape.adjusted(-minHorizontalClearance, 0.0, minHorizontalClearance, 0.0);
3143 257 : if (itemShape.empty()) {
3144 0 : continue;
3145 : }
3146 :
3147 257 : const bool onUpperStaff = centerableItem->onUpperGapStaff;
3148 : const SkylineLine ownSkyline
3149 257 : = (onUpperStaff ? upperSkyline : lowerSkyline).getFilteredCopy([centerableItem](const ShapeElement& shapeEl) {
3150 15380 : const EngravingItem* shapeItem = shapeEl.item();
3151 15380 : return shapeItem && (shapeItem->isAccidental() || Autoplace::itemsShouldIgnoreEachOther(centerableItem->item, shapeItem));
3152 257 : });
3153 :
3154 257 : const double minDist = centerableItem->item->absoluteFromSpatium(centerableItem->item->minDistance());
3155 257 : const double spaceAbove = (onUpperStaff ? ownSkyline : upperSkyline).verticalClearanceBelow(itemShape) - minDist;
3156 257 : const double spaceBelow = (onUpperStaff ? lowerSkyline : ownSkyline).verticalClearanceAbove(itemShape) - minDist;
3157 :
3158 257 : if (onUpperStaff) {
3159 237 : upperHalfSpaceAbove = std::min(upperHalfSpaceAbove, spaceAbove);
3160 237 : upperHalfSpaceBelow = std::min(upperHalfSpaceBelow, spaceBelow);
3161 : } else {
3162 20 : lowerHalfSpaceAbove = std::min(lowerHalfSpaceAbove, spaceAbove);
3163 20 : lowerHalfSpaceBelow = std::min(lowerHalfSpaceBelow, spaceBelow);
3164 : }
3165 257 : }
3166 :
3167 199 : double convergeDistance = gapConvergeDistance(group, yStaffDiff, minHorizontalClearance);
3168 199 : if (lowerHalfSpaceAbove != DBL_MAX && upperHalfSpaceBelow != DBL_MAX) {
3169 : /* Convergence only measures the items of the two halves, but there might be other non-centered
3170 : * items in the gap, so we cap it at the space the group actually has in the gap */
3171 7 : convergeDistance = std::min(convergeDistance, std::max(lowerHalfSpaceAbove + upperHalfSpaceBelow, 0.0));
3172 : }
3173 :
3174 : // Space left above and below the entire group once converged, i.e. how far it can move as one rigid unit
3175 199 : const double groupSpaceAbove = std::min(upperHalfSpaceAbove, lowerHalfSpaceAbove - convergeDistance);
3176 199 : const double groupSpaceBelow = std::min(upperHalfSpaceBelow, lowerHalfSpaceBelow + convergeDistance);
3177 :
3178 199 : if (groupSpaceAbove == DBL_MAX || groupSpaceBelow == DBL_MAX) {
3179 0 : return;
3180 : }
3181 :
3182 199 : const double yMove = 0.5 * (groupSpaceBelow - groupSpaceAbove);
3183 :
3184 : // Move the items
3185 456 : for (const CenterableItem* centerableItem : group) {
3186 257 : const double itemMove = yMove + convergenceMoveFor(centerableItem, convergeDistance);
3187 257 : centerableItem->item->mutldata()->moveY(itemMove);
3188 257 : updateSkylineForElement(centerableItem->item, system, itemMove);
3189 : }
3190 : }
3191 :
3192 14 : void SystemLayout::centerMMRestBetweenStaves(MMRest* mmRest, const System* system)
3193 : {
3194 14 : staff_idx_t thisIdx = mmRest->staffIdx();
3195 14 : IF_ASSERT_FAILED(thisIdx > 0) {
3196 0 : return;
3197 : }
3198 :
3199 14 : staff_idx_t prevIdx = system->prevVisibleStaff(thisIdx);
3200 14 : IF_ASSERT_FAILED(prevIdx != muse::nidx) {
3201 0 : return;
3202 : }
3203 :
3204 14 : SysStaff* thisStaff = system->staff(thisIdx);
3205 14 : SysStaff* prevStaff = system->staff(prevIdx);
3206 14 : double prevStaffHeight = system->score()->staff(prevIdx)->staffHeight(mmRest->tick());
3207 14 : double yStaffDiff = prevStaff->y() + prevStaffHeight - thisStaff->y();
3208 :
3209 14 : PointF mmRestDefaultNumberPosition = mmRest->numberPos() - PointF(0.0, mmRest->absoluteFromSpatium(mmRest->numberOffset()));
3210 14 : RectF numberBbox = mmRest->numberRect().translated(mmRestDefaultNumberPosition + mmRest->pos());
3211 14 : double yBaseLine = 0.5 * (yStaffDiff - numberBbox.height());
3212 14 : double yDiff = yBaseLine - numberBbox.top();
3213 :
3214 14 : mmRest->mutldata()->yNumberPos += yDiff;
3215 : }
3216 :
3217 29491 : void SystemLayout::MeasureState::clear()
3218 : {
3219 29491 : measure = nullptr;
3220 29491 : measureWidth = 0.0;
3221 29491 : measurePos = 0.0;
3222 29491 : elementPositions.clear();
3223 29491 : elementWidths.clear();
3224 29491 : staveSharingStates.clear();
3225 29491 : }
3226 :
3227 214 : void SystemLayout::MeasureState::restoreMeasure(LayoutContext& ctx)
3228 : {
3229 214 : bool mapChanged = false;
3230 214 : Fraction tick = measure->tick();
3231 214 : for (auto& [sharedPart, savedState] : staveSharingStates) {
3232 0 : std::optional<StaveSharingState> curState = sharedPart->exactStaveSharingStateAtTick(tick);
3233 0 : if (curState == savedState) {
3234 0 : continue;
3235 : }
3236 0 : if (savedState) {
3237 0 : sharedPart->setStaveSharingStateAtTick(*savedState, tick);
3238 : } else {
3239 0 : sharedPart->removeStaveSharingStateAtTick(tick);
3240 : }
3241 0 : mapChanged = true;
3242 0 : }
3243 214 : if (mapChanged) {
3244 0 : StaveSharingLayout::updateNotationWithoutRecomputingTrackMap(measure, ctx);
3245 : }
3246 :
3247 214 : measure->mutldata()->setPosX(measurePos);
3248 214 : measure->setWidth(measureWidth);
3249 1260 : for (auto pair : elementPositions) {
3250 1046 : pair.first->setPos(pair.second);
3251 : }
3252 1258 : for (auto pair : elementWidths) {
3253 1044 : pair.first->setWidth(pair.second);
3254 : }
3255 214 : }
|