LCOV - code coverage report
Current view: top level - src/engraving/rendering/score - chordlayout.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 87.7 % 2308 2023
Test Date: 2026-11-19 04:14:36

            Line data    Source code
       1              : /*
       2              :  * SPDX-License-Identifier: GPL-3.0-only
       3              :  * MuseScore-Studio-CLA-applies
       4              :  *
       5              :  * MuseScore Studio
       6              :  * Music Composition & Notation
       7              :  *
       8              :  * Copyright (C) 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 <map>
      24              : 
      25              : #include "chordlayout.h"
      26              : 
      27              : #include "containers.h"
      28              : 
      29              : #include "dom/accidental.h"
      30              : #include "dom/arpeggio.h"
      31              : #include "dom/chordbracket.h"
      32              : #include "dom/beam.h"
      33              : #include "dom/chord.h"
      34              : #include "dom/factory.h"
      35              : #include "dom/fingering.h"
      36              : #include "dom/glissando.h"
      37              : #include "dom/guitarbend.h"
      38              : #include "dom/hook.h"
      39              : #include "dom/jianpudurationline.h"
      40              : #include "dom/jianpuoctavedot.h"
      41              : #include "dom/ledgerline.h"
      42              : #include "dom/lyrics.h"
      43              : #include "dom/measure.h"
      44              : #include "dom/note.h"
      45              : #include "dom/ornament.h"
      46              : #include "dom/page.h"
      47              : #include "dom/parenthesis.h"
      48              : #include "dom/part.h"
      49              : #include "dom/pitchspelling.h"
      50              : #include "dom/rest.h"
      51              : #include "dom/score.h"
      52              : #include "dom/segment.h"
      53              : #include "dom/slur.h"
      54              : #include "dom/staff.h"
      55              : #include "dom/stem.h"
      56              : #include "dom/stemslash.h"
      57              : #include "dom/system.h"
      58              : #include "dom/tie.h"
      59              : #include "dom/tremolosinglechord.h"
      60              : #include "dom/tremolotwochord.h"
      61              : #include "dom/utils.h"
      62              : #include "editing/editchord.h"
      63              : #include "editing/navigation.h"
      64              : 
      65              : #include "accidentalslayout.h"
      66              : #include "arpeggiolayout.h"
      67              : #include "autoplace.h"
      68              : #include "beamlayout.h"
      69              : #include "beamtremololayout.h"
      70              : #include "horizontalspacing.h"
      71              : #include "parenthesislayout.h"
      72              : #include "restlayout.h"
      73              : #include "slurtielayout.h"
      74              : #include "stemlayout.h"
      75              : #include "systemlayout.h"
      76              : #include "tlayout.h"
      77              : #include "tremololayout.h"
      78              : 
      79              : using namespace muse;
      80              : using namespace mu::engraving;
      81              : using namespace mu::engraving::rendering::score;
      82              : 
      83              : static constexpr Spatium STAFFTYPE_TAB_DEFAULTDOTDIST_X = 0.75_sp;
      84              : 
      85         5088 : static double jianpuBeamOffset(const Chord* chord, PlacementV placement, const LayoutContext& ctx)
      86              : {
      87         5088 :     const Beam* beam = chord->beam();
      88         5088 :     if (!beam || ctx.conf().styleV(Sid::jianpuDiminutionBeamPlacement).value<PlacementV>() != placement) {
      89         1673 :         return 0.0;
      90              :     }
      91              : 
      92         3415 :     const int lines = BeamTremoloLayout::strokeCount(beam->ldata(), chord);
      93         3415 :     const double distance = ctx.conf().styleAbsolute(Sid::jianpuDiminutionBeamDistance);
      94         3415 :     return (distance * lines) * chord->magS();
      95              : }
      96              : 
      97        54885 : void ChordLayout::layout(Chord* item, LayoutContext& ctx)
      98              : {
      99        54885 :     if (item->notes().empty()) {
     100            0 :         return;
     101              :     }
     102        54885 :     int gi = 0;
     103        55814 :     for (Chord* c : item->graceNotes()) {
     104              :         // HACK: graceIndex is not well-maintained on add & remove
     105              :         // so rebuild now
     106          929 :         c->setGraceIndex(gi++);
     107              :     }
     108              : 
     109        54885 :     if (item->onTabStaff()) {
     110          800 :         layoutTablature(item, ctx);
     111              :     } else {
     112        54085 :         layoutPitched(item, ctx);
     113              :     }
     114              : }
     115              : 
     116        54982 : void ChordLayout::layoutPitched(Chord* item, LayoutContext& ctx)
     117              : {
     118        55879 :     for (Chord* c : item->graceNotes()) {
     119          897 :         layoutPitched(c, ctx);
     120              :     }
     121              : 
     122        54982 :     double mag_             = item->staff() ? item->staff()->staffMag(item) : 1.0;      // palette elements do not have a staff
     123        54982 :     double dotNoteDistance  = ctx.conf().styleAbsolute(Sid::dotNoteDistance) * mag_;
     124              : 
     125        54982 :     double chordX           = (item->noteType() == NoteType::NORMAL) ? item->ldata()->pos().x() : 0.0;
     126              : 
     127        54982 :     double lll    = 0.0;           // space to leave at left of chord
     128        54982 :     double rrr    = 0.0;           // space to leave at right of chord
     129        54982 :     double lhead  = 0.0;           // amount of notehead to left of chord origin
     130        54982 :     Note* upnote = item->upNote();
     131        54982 :     Note* downnote = item->downNote();
     132        54982 :     Note* leftNote = nullptr;
     133              : 
     134        54982 :     delete item->tabDur();     // no TAB? no duration symbol! (may happen when converting a TAB into PITCHED)
     135        54982 :     item->setTabDur(nullptr);
     136              : 
     137              :     //-----------------------------------------
     138              :     //  process notes
     139              :     //-----------------------------------------
     140              : 
     141              :     // Keeps track if there are any accidentals in this chord.
     142              :     // Used to remove excess space in front of arpeggios.
     143              :     // See GitHub issue #8970 for more details.
     144              :     // https://github.com/musescore/MuseScore/issues/8970
     145        54982 :     std::vector<Accidental*> chordAccidentals;
     146              : 
     147        54982 :     const bool isJianpuStaff = item->onJianpuStaff();
     148              : 
     149        54982 :     std::vector<Note*> notes = item->notes();
     150        54982 :     if (isJianpuStaff) {
     151         1758 :         std::reverse(notes.begin(), notes.end()); // highest pitch on top
     152              :     }
     153              : 
     154              :     // Jianpu Y origin is at the center of the number.
     155              :     // It always starts half a spatium above, aligned with the middle of the measure line.
     156        54982 :     double jianpuOffsetY = upnote ? -upnote->spatium() * .5 * mag_ : 0.0;
     157              : 
     158              :     // Grace notes are placed above the main notehead, so start with an offset.
     159        54982 :     if (item->isGrace() && item->staff()) {
     160              :         // Use the staff scale (mag_) rather than the grace-note scale (item->mag()) so the
     161              :         // offset matches the normal note's box height, keeping the gap consistent.
     162          964 :         jianpuOffsetY -= item->staff()->staffTypeForElement(item)->jianpuBoxH() * mag_;
     163              :     }
     164              : 
     165        54982 :     const double itemMag = item->mag();
     166       117248 :     for (Note* note : notes) {
     167        62266 :         Note::LayoutData* ldata = note->mutldata();
     168        62266 :         TLayout::layoutNote(note, ldata);
     169              : 
     170        62266 :         if (isJianpuStaff) {
     171         1764 :             const std::vector<JianpuOctaveDot*>& dots = note->jianpuOctaveDots();
     172              :             // Jianpu spacing rules for octave dots, beams, and notes:
     173              :             // - Dot-to-note uses dot centerline to note boundary distance.
     174              :             // - Beam-to-note uses beam centerline to note boundary distance.
     175              :             // - Dot-to-dot and beam-to-dot/beam use centerline-to-centerline distance.
     176         1764 :             const double dotDistance = ctx.conf().styleAbsolute(Sid::jianpuOctaveDotDistance) * itemMag;
     177              : 
     178              :             // Move the current note down if it is has octave dots above it
     179         1764 :             if (note != upnote && !dots.empty() && dots.back()->ldata()->above) {
     180            6 :                 jianpuOffsetY += dots.size() * dotDistance;
     181              :             }
     182              : 
     183              :             // Jianpu digits in same chord will be vertically stacked
     184         1764 :             ldata->moveY(jianpuOffsetY);
     185              : 
     186              :             // Move the next note down if current note has octave dots in below
     187         1764 :             if (!dots.empty() && !dots.back()->ldata()->above) {
     188          169 :                 jianpuOffsetY += dots.size() * dotDistance;
     189              :             }
     190              : 
     191              :             // Add extra offset for beam if it is upnote
     192         1764 :             if (note == upnote) {
     193         1758 :                 jianpuOffsetY += jianpuBeamOffset(item, PlacementV::BELOW, ctx);
     194              :             }
     195              : 
     196         1764 :             jianpuOffsetY += ldata->bbox().height();
     197         1764 :             jianpuOffsetY += ctx.conf().styleAbsolute(Sid::jianpuNumberVerticalDistance) * itemMag;
     198              :         }
     199              : 
     200        62266 :         double x1 = note->pos().x() + chordX;
     201        62266 :         double x2 = x1 + note->headWidth();
     202        62266 :         lll      = std::max(lll, -x1);
     203        62266 :         rrr      = std::max(rrr, x2);
     204              :         // track amount of space due to notehead only
     205        62266 :         lhead    = std::max(lhead, -x1);
     206        62266 :         if (!leftNote || note->x() < leftNote->x()) {
     207        55036 :             leftNote = note;
     208              :         }
     209              : 
     210        62266 :         Accidental* accidental = note->accidental();
     211        62266 :         if (accidental && accidental->visible()) {
     212         4023 :             chordAccidentals.push_back(accidental);
     213              :         }
     214        62266 :         if (accidental && accidental->addToSkyline() && !note->fixed()) {
     215              :             // convert x position of accidental to segment coordinate system
     216         4018 :             double x = accidental->pos().x() + note->pos().x() + chordX;
     217              :             // distance from accidental to note already taken into account
     218              :             // but here perhaps we create more padding in *front* of accidental?
     219         4018 :             x -= ctx.conf().styleAbsolute(Sid::accidentalDistance) * mag_;
     220         4018 :             lll = std::max(lll, -x);
     221              :         }
     222              : 
     223              :         // clear layout for note-based fingerings
     224        62698 :         for (EngravingItem* e : note->el()) {
     225          432 :             if (e->isFingering()) {
     226          396 :                 Fingering* f = toFingering(e);
     227          396 :                 if (f->layoutType() == ElementType::NOTE) {
     228            8 :                     f->setPos(PointF());
     229            8 :                     f->setbbox(RectF());
     230              :                 }
     231              :             }
     232              :         }
     233              :     }
     234              : 
     235              :     // A chord can have its own arpeggio and also be part of another arpeggio's span.  We need to lay out both of these arpeggios properly
     236        54982 :     Arpeggio* oldSpanArp = item->spanArpeggio();
     237        54982 :     Arpeggio* newSpanArp = nullptr;
     238              : 
     239              :     // If item has an arpeggio: mark chords which are part of the arpeggio
     240        54982 :     if (item->arpeggio()) {
     241          212 :         item->arpeggio()->findAndAttachToChords();
     242          212 :         item->arpeggio()->mutldata()->maxChordPad = 0.0;
     243          212 :         item->arpeggio()->mutldata()->minChordX = DBL_MAX;
     244          212 :         TLayout::layoutItem(item->arpeggio(), ctx);
     245              :     }
     246              : 
     247        54982 :     if (item->spanArpeggio() != oldSpanArp) {
     248           13 :         newSpanArp = item->spanArpeggio();
     249              :     }
     250              :     // If item is within arpeggio span, keep track of largest space needed between glissando and chord across staves
     251        54982 :     double lllMax = lll;
     252       164946 :     for (Arpeggio* spanArp : { oldSpanArp, newSpanArp }) {
     253       109964 :         if (!spanArp || !spanArp->chord()) {
     254       109690 :             continue;
     255              :         }
     256              : 
     257          274 :         Arpeggio::LayoutData* arpldata = spanArp->mutldata();
     258              : 
     259          274 :         const Segment* seg = spanArp->chord()->segment();
     260          274 :         const EngravingItem* endItem = seg->element(spanArp->endTrack());
     261          274 :         const Chord* endChord = item;
     262          274 :         if (endItem && endItem->isChord()) {
     263          274 :             endChord = toChord(endItem);
     264              :         }
     265              : 
     266              :         // If a note is covered in the voice span but located outside the visual span of the arpeggio calculate accidental offset later
     267              :         bool aboveStart
     268          274 :             = std::make_pair(item->vStaffIdx(), item->downLine()) < std::make_pair(spanArp->vStaffIdx(), spanArp->chord()->upLine());
     269          274 :         bool belowEnd = std::make_pair(item->vStaffIdx(), item->upLine()) > std::make_pair(endChord->vStaffIdx(), endChord->downLine());
     270              : 
     271          274 :         if (!(aboveStart || belowEnd)) {
     272          274 :             ElementType elType = spanArp->type();
     273          274 :             const PaddingTable& paddingTable = item->score()->paddingTables().horizontalPaddingTable();
     274          274 :             double arpeggioNoteDistance = paddingTable.at(elType).at(ElementType::NOTE) * mag_;
     275          274 :             double arpeggioLedgerDistance = paddingTable.at(elType).at(ElementType::LEDGER_LINE) * mag_;
     276          274 :             int firstLedgerBelow = item->staff()->lines(item->downNote()->tick()) * 2 - 1;
     277          274 :             int firstLedgerAbove = -1;
     278              : 
     279          274 :             double gapSize = arpeggioNoteDistance;
     280              : 
     281          274 :             if (leftNote && muse::RealIsNull(leftNote->x())) {
     282          245 :                 if (downnote->line() > firstLedgerBelow || upnote->line() < firstLedgerAbove) {
     283           94 :                     gapSize = arpeggioLedgerDistance + ctx.conf().styleS(Sid::ledgerLineLength).val() * item->spatium();
     284              :                 }
     285           29 :             } else if (leftNote && (leftNote->line() > firstLedgerBelow || leftNote->line() < firstLedgerAbove)) {
     286           11 :                 gapSize = arpeggioLedgerDistance + ctx.conf().styleS(Sid::ledgerLineLength).val() * item->spatium();
     287              :             }
     288              : 
     289          274 :             double arpChordX = std::min(chordX, 0.0);
     290              : 
     291          274 :             if (!chordAccidentals.empty()) {
     292           18 :                 double arpeggioAccidentalDistance = paddingTable.at(elType).at(ElementType::ACCIDENTAL) * mag_;
     293           18 :                 double accidentalDistance = ctx.conf().styleAbsolute(Sid::accidentalDistance) * mag_;
     294           18 :                 gapSize = arpeggioAccidentalDistance - accidentalDistance;
     295           18 :                 gapSize -= ArpeggioLayout::insetDistance(spanArp, ctx, mag_, item, chordAccidentals);
     296              :             }
     297              : 
     298          274 :             double extraX = spanArp->width() + gapSize;
     299              : 
     300              :             // Track leftmost chord position, as we we always want the arpeggio to be to the left of this
     301          274 :             arpldata->minChordX = std::min(arpldata->minChordX, arpChordX);
     302              : 
     303              :             // Save this to arpeggio if largest
     304          274 :             arpldata->maxChordPad = std::max(arpldata->maxChordPad, lll + extraX);
     305              : 
     306              :             // If first chord in arpeggio set y
     307          274 :             if (item->arpeggio() && item->arpeggio() == spanArp) {
     308          212 :                 double y1 = upnote->pos().y() - upnote->headHeight() * .5;
     309          212 :                 item->arpeggio()->mutldata()->setPosY(y1);
     310              :             }
     311              : 
     312          274 :             Note* endDownNote = endChord->downNote();
     313              : 
     314              :             // If last chord in arpeggio, set x
     315          274 :             if (endDownNote->track() == item->track()) {
     316              :                 // Amount to move arpeggio from it's parent chord to factor in chords further to the left
     317          213 :                 double firstChordX = spanArp->chord()->ldata()->pos().x();
     318          213 :                 double xDiff = firstChordX - arpldata->minChordX;
     319              : 
     320          213 :                 double offset = -(xDiff + arpldata->maxChordPad);
     321          213 :                 spanArp->mutldata()->setPosX(offset);
     322          213 :                 if (spanArp->visible()) {
     323          211 :                     lllMax = std::max(lllMax, offset);
     324              :                 }
     325              :             }
     326              :         }
     327              :     }
     328              : 
     329        54982 :     lll = lllMax;
     330              : 
     331        54982 :     if (item->dots()) {
     332          925 :         double x = item->dotPosX() + dotNoteDistance
     333          925 :                    + double(item->dots() - 1) * ctx.conf().styleAbsolute(Sid::dotDotDistance) * mag_;
     334          925 :         x += item->symWidth(SymId::augmentationDot);
     335          925 :         rrr = std::max(rrr, x);
     336              :     }
     337              : 
     338        54982 :     if (item->hook()) {
     339         2148 :         if (item->beam()) {
     340           49 :             ctx.mutDom().undoRemoveElement(item->hook());
     341              :         } else {
     342         2099 :             TLayout::layoutHook(item->hook(), item->hook()->mutldata());
     343         2099 :             if (item->up() && item->stem()) {
     344              :                 // hook position is not set yet
     345          959 :                 double x = item->hook()->ldata()->bbox().right() + item->stem()->flagPosition().x() + chordX;
     346          959 :                 rrr = std::max(rrr, x);
     347              :             }
     348              :         }
     349              :     }
     350              : 
     351        54982 :     item->setSpaceLw(lll);
     352        54982 :     item->setSpaceRw(rrr);
     353              : 
     354       117248 :     for (Note* note : item->notes()) {
     355        62266 :         layoutNote2(note, ctx);
     356              :     }
     357              : 
     358        55134 :     for (EngravingItem* e : item->el()) {
     359              :         // Cannot layout slurs as chord positions are not fixed
     360              :         // Chord brackets should be the outermost element
     361          152 :         if (e->isSlur() || e->isChordBracket()) {
     362            0 :             continue;
     363              :         }
     364          152 :         TLayout::layoutItem(e, ctx);
     365          152 :         if (e->isChordLine()) {
     366          152 :             RectF tbbox = e->ldata()->bbox().translated(e->pos());
     367          152 :             double lx = tbbox.left() + chordX;
     368          152 :             double rx = tbbox.right() + chordX;
     369          152 :             if (-lx > item->spaceLw()) {
     370           65 :                 item->setSpaceLw(item->spaceLw() - lx);
     371              :             }
     372          152 :             if (rx > item->spaceRw()) {
     373           87 :                 item->setSpaceRw(rx);
     374              :             }
     375              :         }
     376              :     }
     377              : 
     378              :     // align note-based fingerings
     379        54982 :     std::vector<Fingering*> alignNote;
     380        54982 :     double xNote = DBL_MAX;
     381       117248 :     for (Note* note : item->notes()) {
     382        62266 :         bool leftFound = false;
     383        62698 :         for (EngravingItem* e : note->el()) {
     384          432 :             if (e->isFingering() && e->autoplace()) {
     385          396 :                 Fingering* f = toFingering(e);
     386          396 :                 if (f->layoutType() == ElementType::NOTE && f->textStyleType() == TextStyleType::LH_GUITAR_FINGERING) {
     387            8 :                     alignNote.push_back(f);
     388            8 :                     if (!leftFound) {
     389            8 :                         leftFound = true;
     390            8 :                         double xf = f->ldata()->pos().x();
     391            8 :                         xNote = std::min(xNote, xf);
     392              :                     }
     393              :                 }
     394              :             }
     395              :         }
     396              :     }
     397        54990 :     for (Fingering* f : alignNote) {
     398            8 :         f->mutldata()->setPosX(xNote);
     399              :     }
     400              : 
     401        54982 :     layoutLvArticulation(item, ctx);
     402              : 
     403        54982 :     createParenGroups(item);
     404        54982 :     ParenthesisLayout::layoutChordParentheses(item, ctx);
     405              : 
     406        54982 :     fillShape(item, item->mutldata(), ctx.conf());
     407        54982 : }
     408              : 
     409          832 : void ChordLayout::layoutTablature(Chord* item, LayoutContext& ctx)
     410              : {
     411          832 :     double _spatium          = item->spatium();
     412          832 :     double mag_ = item->staff() ? item->staff()->staffMag(item) : 1.0;    // palette elements do not have a staff
     413          832 :     double dotNoteDistance = ctx.conf().styleAbsolute(Sid::dotNoteDistance) * mag_;
     414          832 :     double minNoteDistance = ctx.conf().styleAbsolute(Sid::minNoteDistance) * mag_;
     415          832 :     double minTieLength = ctx.conf().styleAbsolute(Sid::minTieLength) * mag_;
     416              : 
     417          864 :     for (Chord* c : item->graceNotes()) {
     418           32 :         layoutTablature(c, ctx);
     419              :     }
     420              : 
     421          832 :     double lll         = 0.0;                    // space to leave at left of chord
     422          832 :     double rrr         = 0.0;                    // space to leave at right of chord
     423          832 :     Note* upnote       = item->upNote();
     424          832 :     double headWidth   = item->symWidth(SymId::noteheadBlack);
     425          832 :     const Staff* st    = item->staff();
     426          832 :     const StaffType* tab = st->staffTypeForElement(item);
     427          832 :     double lineDist    = tab->lineDistance().val() * _spatium;
     428          832 :     double stemX       = 0.5 * headWidth;
     429          832 :     int ledgerLines = 0;
     430          832 :     double llY         = 0.0;
     431              : 
     432          832 :     size_t numOfNotes  = item->notes().size();
     433          832 :     double minY        = 1000.0;                 // just a very large value
     434         1862 :     for (size_t i = 0; i < numOfNotes; ++i) {
     435         1030 :         Note* note = item->notes().at(i);
     436         1030 :         note->updateFrettingForTiesAndBends();
     437         1030 :         ChordLayout::setDotRelativeLine(note, 0, ctx);
     438         1030 :         TLayout::layoutNote(note, note->mutldata());
     439              :         // set headWidth to max fret text width
     440         1030 :         double fretWidth = note->ldata()->bbox().width();
     441         1030 :         if (headWidth < fretWidth) {
     442          117 :             headWidth = fretWidth;
     443              :         }
     444              :         // centre fret string on stem
     445         1030 :         double x = stemX - fretWidth * 0.5;
     446         1030 :         double y = note->fixed() ? note->line() * lineDist / 2 : tab->physStringToYOffset(note->string()).toAbsolute(_spatium);
     447         1030 :         note->setPos(x, y);
     448         1030 :         if (y < minY) {
     449         1011 :             minY  = y;
     450              :         }
     451         1030 :         int currLedgerLines   = tab->numOfTabLedgerLines(note->string());
     452         1030 :         if (currLedgerLines > ledgerLines) {
     453            0 :             ledgerLines = currLedgerLines;
     454            0 :             llY         = y;
     455              :         }
     456              : 
     457              :         // allow extra space for shortened ties; this code must be kept synchronized
     458              :         // with the tie positioning code in Tie::slurPos()
     459              :         // but the allocation of space needs to be performed here
     460              :         Tie* tie;
     461         1030 :         tie = note->tieBack();
     462         1030 :         if (tie && tie->addToSkyline()) {
     463           37 :             SlurTieLayout::calculateDirection(tie);
     464           37 :             double overlap = 0.0;                // how much tie can overlap start and end notes
     465           37 :             bool shortStart = false;            // whether tie should clear start note or not
     466           37 :             Note* startNote = tie->startNote();
     467           37 :             Chord* startChord = startNote ? startNote->chord() : nullptr;
     468           37 :             if (startChord && startChord->measure() == item->measure() && startChord == Navigation::prevChordRest(item)) {
     469           11 :                 double startNoteWidth = startNote->width();
     470              :                 // overlap into start chord?
     471              :                 // if in start chord, there are several notes or stem and tie in same direction
     472           11 :                 if (startChord->notes().size() > 1 || (startChord->stem() && startChord->up() == tie->up())) {
     473              :                     // clear start note (1/8 of fret mark width)
     474            2 :                     shortStart = true;
     475            2 :                     overlap -= startNoteWidth * 0.125;
     476              :                 } else {            // overlap start note (by ca. 1/3 of fret mark width)
     477            9 :                     overlap += startNoteWidth * 0.35;
     478              :                 }
     479              :                 // overlap into end chord (this)?
     480              :                 // if several notes or neither stem or tie are up
     481           11 :                 if (item->notes().size() > 1 || (item->stem() && !item->up() && !tie->up())) {
     482              :                     // for positive offset:
     483              :                     //    use available space
     484              :                     // for negative x offset:
     485              :                     //    space is allocated elsewhere, so don't re-allocate here
     486            2 :                     if (!RealIsNull(note->ldata()->pos().x())) {                      // this probably does not work for TAB, as
     487            2 :                         overlap += std::abs(note->ldata()->pos().x());              // _pos is used to centre the fret on the stem
     488              :                     } else {
     489            0 :                         overlap -= fretWidth * 0.125;
     490              :                     }
     491              :                 } else {
     492            9 :                     if (shortStart) {
     493            0 :                         overlap += fretWidth * 0.15;
     494              :                     } else {
     495            9 :                         overlap += fretWidth * 0.35;
     496              :                     }
     497              :                 }
     498           11 :                 double d = std::max(minTieLength - overlap, 0.0);
     499           11 :                 lll = std::max(lll, d);
     500              :             }
     501              :         }
     502              :     }
     503              : 
     504              :     // create ledger lines, if required (in some historic styles)
     505          832 :     if (ledgerLines > 0) {
     506            0 :         item->resizeLedgerLinesTo(ledgerLines);
     507            0 :         double extraLen    = 0;
     508            0 :         double llX         = stemX - (headWidth + extraLen) * 0.5;
     509            0 :         for (int i = 0; i < ledgerLines; i++) {
     510            0 :             LedgerLine* ldgLin = item->ledgerLines()[i];
     511            0 :             ldgLin->setTrack(item->track());
     512            0 :             ldgLin->setVisible(item->visible());
     513            0 :             ldgLin->setLen(headWidth + extraLen);
     514            0 :             ldgLin->setPos(llX, llY);
     515            0 :             TLayout::layoutLedgerLine(ldgLin, ctx);
     516            0 :             llY += lineDist / ledgerLines;
     517              :         }
     518            0 :         headWidth += extraLen;            // include ledger lines extra width in chord width
     519              :     }
     520              : 
     521              :     // horiz. spacing: leave half width at each side of the (potential) stem
     522          832 :     double halfHeadWidth = headWidth * 0.5;
     523          832 :     if (lll < stemX - halfHeadWidth) {
     524            0 :         lll = stemX - halfHeadWidth;
     525              :     }
     526          832 :     if (rrr < stemX + halfHeadWidth) {
     527          832 :         rrr = stemX + halfHeadWidth;
     528              :     }
     529              :     // align dots to the widest fret mark (not needed in all TAB styles, but harmless anyway)
     530          832 :     item->setDotPosX(headWidth);
     531              : 
     532          832 :     if (item->shouldHaveStem()) {
     533              :         // if stem is required but missing, add it;
     534              :         // set stem position (stem length is set in Chord:layoutStem() )
     535          117 :         if (!item->stem()) {
     536            0 :             Stem* stem = Factory::createStem(item);
     537            0 :             stem->setGenerated(true);
     538            0 :             ctx.mutDom().addElement(stem);
     539              :         }
     540          117 :         item->stem()->setPos(StemLayout::tabStemPos(item, tab) * _spatium);
     541          117 :         if (item->hook()) {
     542            3 :             if (item->beam()) {
     543            0 :                 ctx.mutDom().undoRemoveElement(item->hook());
     544              :             } else {
     545            3 :                 if (rrr < stemX + item->hook()->width()) {
     546            3 :                     rrr = stemX + item->hook()->width();
     547              :                 }
     548              : 
     549            3 :                 item->hook()->setPos(item->stem()->flagPosition());
     550              :             }
     551              :         }
     552              :     } else {
     553          715 :         if (item->stem()) {
     554            0 :             ctx.mutDom().doUndoRemoveElement(item->stem());
     555            0 :             item->remove(item->stem());
     556              :         }
     557          715 :         if (item->hook()) {
     558            0 :             ctx.mutDom().doUndoRemoveElement(item->hook());
     559            0 :             item->remove(item->hook());
     560              :         }
     561          715 :         if (item->beam()) {
     562            0 :             ctx.mutDom().doUndoRemoveElement(item->beam());
     563            0 :             item->remove(item->beam());
     564              :         }
     565              :     }
     566              : 
     567          832 :     if (!tab->genDurations()                           // if tab is not set for duration symbols
     568           24 :         || track2voice(item->track())                        // or not in first voice
     569          856 :         || (item->isGrace()                                  // no tab duration symbols if grace notes
     570            0 :             && item->beamMode() == BeamMode::AUTO)) {      // and beammode == AUTO
     571              :         //
     572          808 :         delete item->tabDur();       // delete an existing duration symbol
     573          808 :         item->setTabDur(nullptr);
     574              :     } else {
     575              :         //
     576              :         // tab duration symbols
     577              :         //
     578              :         // if no previous CR
     579              :         // OR symbol repeat set to ALWAYS
     580              :         // OR symbol repeat condition is triggered
     581              :         // OR duration type and/or number of dots is different from current CR
     582              :         // OR chord beam mode not AUTO
     583              :         // OR previous CR is a rest
     584              :         // AND no not-stem
     585              :         // set a duration symbol (trying to re-use existing symbols where existing to minimize
     586              :         // symbol creation and deletion)
     587           24 :         bool needTabDur = false;
     588           24 :         bool repeat = false;
     589           24 :         if (!item->noStem()) {
     590              :             // check duration of prev. CR segm
     591           24 :             ChordRest* prevCR = Navigation::prevChordRest(item);
     592           24 :             if (prevCR == 0) {
     593           13 :                 needTabDur = true;
     594           11 :             } else if (item->beamMode() != BeamMode::AUTO
     595            7 :                        || prevCR->durationType().type() != item->durationType().type()
     596            7 :                        || prevCR->dots() != item->dots()
     597            7 :                        || prevCR->tuplet() != item->tuplet()
     598           18 :                        || prevCR->isRest()) {
     599            4 :                 needTabDur = true;
     600            7 :             } else if (tab->symRepeat() == TablatureSymbolRepeat::ALWAYS
     601            7 :                        || ((tab->symRepeat() == TablatureSymbolRepeat::MEASURE
     602            0 :                             || tab->symRepeat() == TablatureSymbolRepeat::SYSTEM)
     603            0 :                            && item->measure() != prevCR->measure())) {
     604            7 :                 needTabDur = true;
     605            7 :                 repeat = true;
     606              :             }
     607              :         }
     608           24 :         if (needTabDur) {
     609              :             // symbol needed; if not exist, create; if exists, update duration
     610           24 :             if (!item->tabDur()) {
     611            5 :                 item->setTabDur(new TabDurationSymbol(item, tab, item->durationType().type(), item->dots()));
     612              :             } else {
     613           19 :                 item->tabDur()->setDuration(item->durationType().type(), item->dots(), tab);
     614              :             }
     615           24 :             item->tabDur()->setRepeat(repeat);
     616              : //                  _tabDur->setMag(mag());           // useless to set grace mag: graces have no dur. symbol
     617           24 :             TLayout::layoutTabDurationSymbol(item->tabDur(), item->tabDur()->mutldata());
     618           24 :             if (minY < 0) {                           // if some fret extends above tab body (like bass strings)
     619            0 :                 TabDurationSymbol::LayoutData* tdladata = item->tabDur()->mutldata();
     620            0 :                 tdladata->moveY(minY);             // raise duration symbol
     621            0 :                 tdladata->setBbox(tdladata->bbox().translated(0, minY));
     622              :             }
     623              :         } else {                                // symbol not needed: if exists, delete
     624            0 :             delete item->tabDur();
     625            0 :             item->setTabDur(nullptr);
     626              :         }
     627              :     }                                     // end of if(duration_symbols)
     628              : 
     629          832 :     if (item->arpeggio()) {
     630           21 :         item->arpeggio()->findAndAttachToChords();
     631           21 :         double y = upnote->pos().y() - upnote->headHeight() * .5;
     632           21 :         TLayout::layoutArpeggio(item->arpeggio(), item->arpeggio()->mutldata(), ctx.conf());
     633           21 :         lll += item->arpeggio()->width() + _spatium * .5;
     634           21 :         item->arpeggio()->setPos(-lll, y);
     635              : 
     636              :         // handle the special case of _arpeggio->span() > 1
     637              :         // in layoutArpeggio2() after page layout has done so we
     638              :         // know the y position of the next staves
     639              :     }
     640              : 
     641              :     // allocate enough room for glissandi
     642          832 :     if (item->endsNoteAnchoredLine()) {
     643           35 :         if (!item->rtick().isZero()) {                          // if not at beginning of measure
     644           28 :             lll += _spatium * 0.5 + minTieLength;
     645              :         }
     646              :         // special case of system-initial glissando final note is handled in Glissando::layout() itself
     647              :     }
     648              : 
     649          832 :     if (item->hook()) {
     650            3 :         if (item->beam()) {
     651            0 :             ctx.mutDom().undoRemoveElement(item->hook());
     652            3 :         } else if (tab == 0) {
     653            0 :             TLayout::layoutHook(item->hook(), item->hook()->mutldata());
     654            0 :             if (item->up()) {
     655              :                 // hook position is not set yet
     656            0 :                 double x = item->hook()->ldata()->bbox().right() + item->stem()->flagPosition().x();
     657            0 :                 rrr = std::max(rrr, x);
     658              :             }
     659              :         }
     660              :     }
     661              : 
     662          832 :     if (item->dots()) {
     663           16 :         double x = 0.0;
     664              :         // if stems are beside staff, dots are placed near to stem
     665           16 :         if (!tab->stemThrough()) {
     666              :             // if there is an unbeamed hook, dots should start after the hook
     667           15 :             if (item->hook() && !item->beam()) {
     668            0 :                 x = item->hook()->width() + dotNoteDistance;
     669              :             }
     670              :             // if not, dots should start at a fixed distance right after the stem
     671              :             else {
     672           15 :                 x = STAFFTYPE_TAB_DEFAULTDOTDIST_X.toAbsolute(_spatium);
     673              :             }
     674           15 :             item->setDotPosX(x);
     675              :         }
     676              :         // if stems are through staff, use dot position computed above on fret mark widths
     677              :         else {
     678            1 :             x = item->dotPosX() + dotNoteDistance
     679            1 :                 + (item->dots() - 1) * ctx.conf().styleS(Sid::dotDotDistance).val() * _spatium;
     680              :         }
     681           16 :         x += item->symWidth(SymId::augmentationDot);
     682           16 :         rrr = std::max(rrr, x);
     683              :     }
     684              : 
     685          832 :     item->setSpaceLw(lll);
     686          832 :     item->setSpaceRw(rrr);
     687              : 
     688          832 :     double graceMag = ctx.conf().styleD(Sid::graceNoteMag);
     689              : 
     690          832 :     std::vector<Chord*> graceNotesBefore = item->Chord::graceNotesBefore();
     691          832 :     size_t nb = graceNotesBefore.size();
     692          832 :     if (nb) {
     693           27 :         double xl = -(item->spaceLw() + minNoteDistance);
     694           56 :         for (int i = static_cast<int>(nb) - 1; i >= 0; --i) {
     695           29 :             Chord* c = graceNotesBefore.at(i);
     696           29 :             xl -= c->spaceRw() /* * 1.2*/;
     697           29 :             c->setPos(xl, 0);
     698           29 :             xl -= c->spaceLw() + minNoteDistance * graceMag;
     699              :         }
     700           27 :         if (-xl > item->spaceLw()) {
     701           27 :             item->setSpaceLw(item->spaceLw() - xl);
     702              :         }
     703              :     }
     704          832 :     std::vector<Chord*> gna = item->graceNotesAfter();
     705          832 :     size_t na = gna.size();
     706          832 :     if (na) {
     707              :         // get factor for start distance after main note. Values found by testing.
     708              :         double fc;
     709            2 :         switch (item->durationType().type()) {
     710            0 :         case DurationType::V_LONG:    fc = 3.8;
     711            0 :             break;
     712            0 :         case DurationType::V_BREVE:   fc = 3.8;
     713            0 :             break;
     714            0 :         case DurationType::V_WHOLE:   fc = 3.8;
     715            0 :             break;
     716            0 :         case DurationType::V_HALF:    fc = 3.6;
     717            0 :             break;
     718            2 :         case DurationType::V_QUARTER: fc = 2.1;
     719            2 :             break;
     720            0 :         case DurationType::V_EIGHTH:  fc = 1.4;
     721            0 :             break;
     722            0 :         case DurationType::V_16TH:    fc = 1.2;
     723            0 :             break;
     724            0 :         default: fc = 1;
     725              :         }
     726            2 :         double xr = fc * (item->spaceRw() + minNoteDistance);
     727            5 :         for (int i = 0; i <= static_cast<int>(na) - 1; i++) {
     728            3 :             Chord* c = gna.at(i);
     729            3 :             xr += c->spaceLw() * (i == 0 ? 1.3 : 1);
     730            3 :             c->setPos(xr, 0);
     731            3 :             xr += c->spaceRw() + minNoteDistance * graceMag;
     732              :         }
     733            2 :         if (xr > item->spaceRw()) {
     734            2 :             item->setSpaceRw(xr);
     735              :         }
     736              :     }
     737          848 :     for (EngravingItem* e : item->el()) {
     738           16 :         TLayout::layoutItem(e, ctx);
     739           16 :         if (e->isChordLine()) {
     740           16 :             RectF tbbox = e->ldata()->bbox().translated(e->pos());
     741           16 :             double lx = tbbox.left();
     742           16 :             double rx = tbbox.right();
     743           16 :             if (-lx > item->spaceLw()) {
     744           12 :                 item->setSpaceLw(item->spaceLw() - lx);
     745              :             }
     746           16 :             if (rx > item->spaceRw()) {
     747            4 :                 item->setSpaceRw(rx);
     748              :             }
     749              :         }
     750              :     }
     751              : 
     752         1862 :     for (size_t i = 0; i < numOfNotes; ++i) {
     753         1030 :         layoutNote2(item->notes().at(i), ctx);
     754              :     }
     755              : 
     756          832 :     if (item->stemSlash()) {
     757            1 :         TLayout::layoutStemSlash(item->stemSlash(), item->stemSlash()->mutldata(), ctx.conf());
     758              :     }
     759              : 
     760          832 :     layoutLvArticulation(item, ctx);
     761              : 
     762          832 :     createParenGroups(item);
     763          832 :     ParenthesisLayout::layoutChordParentheses(item, ctx);
     764              : 
     765          832 :     fillShape(item, item->mutldata(), ctx.conf());
     766          832 : }
     767              : 
     768        55814 : void ChordLayout::layoutLvArticulation(Chord* item, LayoutContext& ctx)
     769              : {
     770              :     // Laissez vib ties must be layed out with the rest of the note, as they need to be taken into account for horizontal spacing
     771        57522 :     for (Articulation* a : item->articulations()) {
     772         1708 :         if (a->isLaissezVib()) {
     773              :             // Must set direction before laying out
     774            0 :             if (item->measure()->hasVoices(a->staffIdx(), item->tick(), item->actualTicks()) && a->anchor() == ArticulationAnchor::AUTO) {
     775            0 :                 a->setUp(item->up());         // if there are voices place articulation at stem
     776            0 :             } else if (a->anchor() == ArticulationAnchor::AUTO) {
     777            0 :                 a->setUp(!item->up());         // place articulation at note head
     778              :             } else {
     779            0 :                 a->setUp(a->anchor() == ArticulationAnchor::TOP);
     780              :             }
     781              : 
     782            0 :             TLayout::layoutItem(a, ctx);
     783              : 
     784            0 :             const Articulation::LayoutData* ldata = a->ldata();
     785            0 :             const double sp = a->spatium();
     786            0 :             const Note* note = ldata->up() ? item->upNote() : item->downNote();
     787            0 :             const int upDir = ldata->up() ? -1 : 1;
     788            0 :             const double noteHeight = note->height();
     789              : 
     790            0 :             PointF result = note->pos() + item->pos();
     791            0 :             double center = SlurTieLayout::noteOpticalCenterForTie(note, ldata->up);
     792            0 :             Spatium visualInsetSp = 0.0_sp;
     793            0 :             if (note->headGroup() == NoteHeadGroup::HEAD_SLASH || note->shouldHideFret()) {
     794            0 :                 visualInsetSp = 0.2_sp;
     795            0 :             } else if (item->up() && ldata->up) {
     796            0 :                 visualInsetSp = 0.7_sp;
     797              :             } else {
     798            0 :                 visualInsetSp = 0.1_sp;
     799              :             }
     800            0 :             double visualInset = visualInsetSp.toAbsolute(sp);
     801              : 
     802            0 :             result.rx() += center + visualInset - ldata->bbox().left();
     803            0 :             result.ry() += (noteHeight / 2 + 0.2 * sp) * upDir;
     804              : 
     805            0 :             a->setPos(result);
     806              :         }
     807              :     }
     808        55814 : }
     809              : 
     810              : //---------------------------------------------------------
     811              : //   layoutNotesSpanners
     812              : //---------------------------------------------------------
     813              : 
     814        54798 : void ChordLayout::layoutSpanners(Chord* item, LayoutContext& ctx)
     815              : {
     816       117723 :     for (const Note* n : item->notes()) {
     817        62925 :         Tie* tie = n->tieFor();
     818        62925 :         if (tie) {
     819         2311 :             TLayout::layoutTie(tie, ctx);
     820              :         }
     821        63574 :         for (Spanner* sp : n->spannerBack()) {
     822          649 :             TLayout::layoutSpanner(sp, ctx);
     823              :         }
     824        63574 :         for (Spanner* sp : n->spannerFor()) {
     825          649 :             if ((sp->isGlissando() || sp->isGuitarBend()) && sp->tick2() >= ctx.state().page()->endTick()) {
     826            0 :                 TLayout::layoutSpanner(sp, ctx);
     827              :             }
     828              :         }
     829              :     }
     830        54798 : }
     831              : 
     832              : //---------------------------------------------------------
     833              : //   layoutArticulations
     834              : //    layout tenuto and staccato
     835              : //    called before layouting slurs
     836              : //---------------------------------------------------------
     837              : 
     838       112007 : void ChordLayout::layoutArticulations(Chord* item, LayoutContext& ctx)
     839              : {
     840       113837 :     for (Chord* gc : item->graceNotes()) {
     841         1830 :         layoutArticulations(gc, ctx);
     842              :     }
     843              : 
     844       112007 :     if (item->articulations().empty()) {
     845       108833 :         return;
     846              :     }
     847         3174 :     const Staff* st = item->staff();
     848         3174 :     const StaffType* staffType = st->staffTypeForElement(item);
     849         3174 :     double mag            = (staffType->isSmall() ? ctx.conf().styleD(Sid::smallStaffMag) : 1.0) * staffType->userMag();
     850         3174 :     double _spatium       = ctx.conf().spatium() * mag;
     851         3174 :     double _lineDist       = _spatium * staffType->lineDistance().val() / 2;
     852         3174 :     const double minDist = ctx.conf().styleAbsolute(Sid::articulationMinDistance) * mag;
     853         3174 :     const ArticulationStemSideAlign articulationHAlign = ctx.conf().styleV(Sid::articulationStemHAlign).value<ArticulationStemSideAlign>();
     854         3174 :     const bool keepArticsTogether = ctx.conf().styleB(Sid::articulationKeepTogether);
     855         3174 :     const double stemSideDistance = ctx.conf().styleAbsolute(Sid::propertyDistanceStem) * mag;
     856         3174 :     const double headSideDistance = ctx.conf().styleAbsolute(Sid::propertyDistanceHead) * mag;
     857         3174 :     const double tenutoAdditionalTieDistance = 0.6 * _spatium;
     858         3174 :     const double staccatoAdditionalTieDistance = 0.4 * _spatium;
     859              : 
     860         3174 :     int numCloseArtics = 0;
     861         3174 :     bool hasStaffArticsUp = false;
     862         3174 :     bool hasStaffArticsDown = false;
     863         3174 :     if (keepArticsTogether) {
     864              :         // find out how many close-to-note artics there are, and whether there is a staff-anchored artic to align to
     865         6627 :         for (Articulation* a : item->articulations()) {
     866         3454 :             if (!a->visible()) {
     867           50 :                 continue;
     868              :             }
     869         3404 :             if (a->layoutCloseToNote()) {
     870         1327 :                 ++numCloseArtics;
     871              :             } else {
     872         2077 :                 if (a->up()) {
     873         1823 :                     hasStaffArticsUp = true;
     874              :                 } else {
     875          254 :                     hasStaffArticsDown = true;
     876              :                 }
     877         2077 :                 if (hasStaffArticsDown && hasStaffArticsUp) {
     878            1 :                     break;           // nothing more to be learned now
     879              :                 }
     880              :             }
     881              :         }
     882              :     }
     883              : 
     884              :     //
     885              :     //    determine direction
     886              :     //    place tenuto and staccato
     887              :     //
     888              : 
     889         3174 :     Articulation* prevVisibleArticulation = nullptr;
     890         6628 :     for (Articulation* a : item->articulations()) {
     891         3454 :         if (item->measure()->hasVoices(a->staffIdx(), item->tick(), item->actualTicks()) && a->anchor() == ArticulationAnchor::AUTO) {
     892          220 :             a->setUp(item->up());         // if there are voices place articulation at stem
     893         3234 :         } else if (a->anchor() == ArticulationAnchor::AUTO) {
     894         2530 :             if (a->isOrnament()) {
     895          628 :                 bool oddVoice = item->track() % 2;
     896          628 :                 a->setUp(!oddVoice);
     897         1902 :             } else if (a->symId() >= SymId::articMarcatoAbove && a->symId() <= SymId::articMarcatoTenutoBelow) {
     898           93 :                 a->setUp(true);         // Gould, p. 117: strong accents above staff
     899              :             } else {
     900         1809 :                 a->setUp(!item->up());         // place articulation at note head
     901              :             }
     902              :         } else {
     903          704 :             a->setUp(a->anchor() == ArticulationAnchor::TOP);
     904              :         }
     905              : 
     906         3454 :         if (!a->layoutCloseToNote()) {
     907         2115 :             continue;
     908              :         }
     909              : 
     910         1339 :         bool bottom = !a->up();      // true: articulation is below chord;  false: articulation is above chord
     911         1339 :         TLayout::layoutItem(a, ctx);     // must be done after assigning direction, or else symId is not reliable
     912         1339 :         bool leaveTieSpace = leaveSpaceForTie(a);
     913              : 
     914         1339 :         bool headSide = bottom == item->up();
     915         1339 :         double y = 0.0;
     916              :         double x;
     917         1339 :         if ((!headSide || !a->isBasicArticulation()) && item->stem()) {
     918          170 :             switch (articulationHAlign) {
     919            0 :             case ArticulationStemSideAlign::STEM:
     920            0 :                 x = item->stem()->width() * .5;
     921            0 :                 break;
     922            0 :             case ArticulationStemSideAlign::NOTEHEAD:
     923            0 :                 x = item->up() ? item->downNote()->noteheadCenterX() : centerX(item);
     924            0 :                 break;
     925          170 :             case ArticulationStemSideAlign::AVERAGE:
     926              :             default:
     927          170 :                 x = item->up() ? (item->stem()->width() * .5 + item->downNote()->noteheadCenterX()) * .5
     928          105 :                     : (item->stem()->width() * .5 + centerX(item)) * .5;
     929          170 :                 break;
     930              :             }
     931          170 :             if (item->up()) {
     932           65 :                 x = item->downNote()->pos().x() + item->downNote()->bboxRightPos() - x;
     933              :             }
     934              :         } else {
     935         1169 :             x = centerX(item);
     936              :         }
     937              : 
     938         1339 :         if (bottom) {
     939          532 :             if (!headSide && item->stem()) {
     940          105 :                 double stemBottom = item->stem()->ldata()->bbox().translated(item->stem()->pos()).bottom();
     941              :                 // Check if there's a hook, because the tip of the hook always extends slightly past the end of the stem
     942          105 :                 if (item->hook()) {
     943           16 :                     y = item->hook()->ldata()->bbox().translated(item->hook()->pos()).bottom();
     944              :                 } else {
     945           89 :                     y = item->stem()->ldata()->bbox().translated(item->stem()->pos()).bottom();
     946              :                 }
     947          105 :                 int line   = round((y + _lineDist) / _lineDist);
     948          105 :                 int lines = 2 * (staffType->lines() - 1);
     949          105 :                 if (line < lines && !(line % 2)) {
     950            0 :                     line += 1;
     951              :                 }
     952          105 :                 double dist = (line * _lineDist) - stemBottom;
     953          105 :                 bool hasBeam = item->beam() || (item->tremoloTwoChord());
     954          105 :                 if (line < lines && hasBeam && dist < stemSideDistance) {
     955              :                     // beams can give stems weird unpredictable lengths, so we should enforce min
     956              :                     // distance even inside the staff
     957              : 
     958              :                     // adjust downwards a space but stop at the bottom of the staff
     959            0 :                     line = std::min(line + 2, lines);
     960              :                 }
     961          105 :                 if (line < lines) {        // align between staff lines
     962            0 :                     y = line * _lineDist;
     963            0 :                     y -= a->height() * .5;
     964          105 :                 } else if (line == lines) {
     965            0 :                     y = stemSideDistance + (lines * _lineDist);
     966              :                 } else {
     967          105 :                     y += stemSideDistance;
     968              :                 }
     969              :             } else {
     970          427 :                 x = centerX(item);
     971          427 :                 int lines = (staffType->lines() - 1) * 2;
     972          427 :                 int line = std::max(item->downLine(), -1);
     973          427 :                 bool adjustArtic = (a->up() && hasStaffArticsUp) || (!a->up() && hasStaffArticsDown);
     974          427 :                 if (keepArticsTogether && adjustArtic && numCloseArtics > 0) {
     975           17 :                     line = std::max(line, lines - (1 + (numCloseArtics * 2)));
     976              :                 }
     977          427 :                 if (line < lines - 1) {
     978          104 :                     if (leaveTieSpace && line % 2) {
     979            0 :                         line += 1;
     980              :                     }
     981          104 :                     y = ((line & ~1) + 3) * _lineDist;
     982          104 :                     y -= a->height() * .5;
     983              :                 } else {
     984          323 :                     y = item->downPos() + 0.5 * item->downNote()->headHeight() + headSideDistance;
     985          323 :                     if (leaveTieSpace) {
     986            0 :                         y += a->isStaccato() ? staccatoAdditionalTieDistance : tenutoAdditionalTieDistance;
     987              :                     }
     988              :                 }
     989              :             }
     990          532 :             if (prevVisibleArticulation && (prevVisibleArticulation->up() == a->up())) {
     991           74 :                 int staffBottom = (staffType->lines() - 2) * 2;
     992           66 :                 if ((headSide && item->downLine() < staffBottom)
     993          140 :                     || (!headSide && !muse::RealIsEqualOrMore(y, (staffBottom + 1) * _lineDist))) {
     994           12 :                     y += _spatium;
     995              :                 } else {
     996           62 :                     y += prevVisibleArticulation->height() + minDist;
     997              :                 }
     998              :             }
     999              :             // center symbol
    1000              :         } else { // topside
    1001          807 :             if (!headSide && item->stem()) {
    1002           65 :                 double stemTop = item->stem()->ldata()->bbox().translated(item->stem()->pos()).top();
    1003              :                 // Check if there's a hook, because the tip of the hook always extends slightly past the end of the stem
    1004           65 :                 if (item->hook()) {
    1005           12 :                     y = item->hook()->ldata()->bbox().translated(item->hook()->pos()).top();
    1006              :                 } else {
    1007           53 :                     y = item->stem()->ldata()->bbox().translated(item->stem()->pos()).top();
    1008              :                 }
    1009           65 :                 int line = round((y - _lineDist) / _lineDist);
    1010           65 :                 if (line > 0 && !(line % 2)) {
    1011            4 :                     line -= 1;
    1012              :                 }
    1013           65 :                 double dist = stemTop - (line * _lineDist);
    1014           65 :                 bool hasBeam = item->beam() || item->tremoloTwoChord();
    1015           65 :                 if (line > 0 && hasBeam && dist < stemSideDistance) {
    1016              :                     // beams can give stems weird unpredictable lengths, so we should enforce min
    1017              :                     // distance even inside the staff
    1018              : 
    1019              :                     // adjust upwards a space but stop at the top of the staff
    1020            0 :                     line = std::max(line - 2, 0);
    1021              :                 }
    1022              : 
    1023           65 :                 if (line > 0) {        // align between staff lines
    1024            6 :                     y = line * _lineDist;
    1025            6 :                     y += a->height() * .5;
    1026           59 :                 } else if (line == 0) {
    1027            0 :                     y = -stemSideDistance;
    1028              :                 } else {
    1029           59 :                     y -= stemSideDistance;
    1030              :                 }
    1031              :             } else {
    1032          742 :                 x = centerX(item);
    1033          742 :                 int lines = (staffType->lines() - 1) * 2;
    1034          742 :                 int line = std::min(item->upLine(), lines + 1);
    1035          742 :                 bool adjustArtic = (a->up() && hasStaffArticsUp) || (!a->up() && hasStaffArticsDown);
    1036          742 :                 if (keepArticsTogether && adjustArtic && numCloseArtics > 0) {
    1037           75 :                     line = std::min(line, 1 + (numCloseArtics * 2));
    1038              :                 }
    1039          742 :                 if (line > 1) {
    1040          408 :                     if (leaveTieSpace && line % 2) {
    1041            0 :                         line -= 1;
    1042              :                     }
    1043          408 :                     y = (((line + 1) & ~1) - 3) * _lineDist;
    1044          408 :                     y += a->height() * .5;
    1045              :                 } else {
    1046          334 :                     y = item->upPos() - 0.5 * item->downNote()->headHeight() - headSideDistance;
    1047          334 :                     if (leaveTieSpace) {
    1048            4 :                         y -= a->isStaccato() ? staccatoAdditionalTieDistance : tenutoAdditionalTieDistance;
    1049              :                     }
    1050              :                 }
    1051              :             }
    1052          807 :             if (prevVisibleArticulation && (prevVisibleArticulation->up() == a->up())) {
    1053           30 :                 if ((headSide && item->upLine() > 2) || (!headSide && !muse::RealIsEqualOrLess(y, 0.0))) {
    1054           26 :                     y -= item->spatium();
    1055              :                 } else {
    1056            4 :                     y -= prevVisibleArticulation->height() + minDist;
    1057              :                 }
    1058              :             }
    1059              :         }
    1060         1339 :         x -= a->ldata()->opticalCenter();
    1061         1339 :         a->setPos(x, y);
    1062         1339 :         if (a->visible()) {
    1063         1327 :             prevVisibleArticulation = a;
    1064              :         }
    1065              : //            measure()->system()->staff(a->staffIdx())->skyline().add(a->shape().translated(a->pos() + segment()->pos() + measure()->pos()));
    1066              :     }
    1067              : }
    1068              : 
    1069              : //---------------------------------------------------------
    1070              : //   layoutArticulations2
    1071              : //    Called after layouting systems
    1072              : //    Tentatively layout all articulations
    1073              : //    To be finished after laying out slurs
    1074              : //---------------------------------------------------------
    1075              : 
    1076       112007 : void ChordLayout::layoutArticulations2(Chord* item, LayoutContext& ctx, bool layoutOnCrossBeamSide)
    1077              : {
    1078       112007 :     ArticulationStemSideAlign articulationHAlign = ctx.conf().styleV(Sid::articulationStemHAlign).value<ArticulationStemSideAlign>();
    1079       113837 :     for (Chord* gc : item->graceNotes()) {
    1080         1830 :         layoutArticulations2(gc, ctx);
    1081              :     }
    1082              : 
    1083       112007 :     if (item->articulations().empty()) {
    1084       108833 :         return;
    1085              :     }
    1086         3174 :     double headSideX = centerX(item);
    1087         3174 :     double stemSideX = headSideX;
    1088         3174 :     if (item->stem()) {
    1089         3016 :         switch (articulationHAlign) {
    1090            0 :         case ArticulationStemSideAlign::STEM:
    1091            0 :             stemSideX = item->stem()->width() * .5;
    1092            0 :             break;
    1093            0 :         case ArticulationStemSideAlign::NOTEHEAD:
    1094            0 :             stemSideX = item->up() ? item->downNote()->noteheadCenterX() : centerX(item);
    1095            0 :             break;
    1096         3016 :         case ArticulationStemSideAlign::AVERAGE:
    1097              :         default:
    1098         3016 :             stemSideX = item->up() ? (item->stem()->width() * .5 + item->downNote()->noteheadCenterX()) * .5
    1099         1798 :                         : (item->stem()->width() * .5 + centerX(item)) * .5;
    1100         3016 :             break;
    1101              :         }
    1102         3016 :         if (item->up()) {
    1103         1218 :             stemSideX = item->downNote()->pos().x() + item->downNote()->bboxRightPos() - stemSideX;
    1104              :         }
    1105              :     }
    1106              : 
    1107         3174 :     double stacAccentKern = 0.2 * item->spatium();
    1108         3174 :     double mag = item->mag();
    1109         3174 :     double minDist = ctx.conf().styleAbsolute(Sid::articulationMinDistance) * mag;
    1110         3174 :     double staffDist = ctx.conf().styleAbsolute(Sid::propertyDistance) * mag;
    1111         3174 :     double stemDist = ctx.conf().styleAbsolute(Sid::propertyDistanceStem) * mag;
    1112         3174 :     double noteDist = ctx.conf().styleAbsolute(Sid::propertyDistanceHead) * mag;
    1113         3174 :     double yOffset = item->staffOffsetY();
    1114              : 
    1115         3174 :     double chordTopY = item->upPos() - 0.5 * item->upNote()->headHeight() + yOffset;       // note position of highest note
    1116         3174 :     double chordBotY = item->downPos() + 0.5 * item->upNote()->headHeight() + yOffset;     // note position of lowest note
    1117              : 
    1118         3174 :     double staffTopY = -staffDist + yOffset;
    1119         3174 :     double staffBotY = item->staff()->staffHeight(item->tick()) + staffDist + yOffset;
    1120              : 
    1121              :     // avoid collisions of staff articulations with chord notes:
    1122              :     // gap between note and staff articulation is distance0 + 0.5 spatium
    1123              : 
    1124         3174 :     if (item->stem()) {
    1125              :         // Check if there's a hook, because the tip of the hook always extends slightly past the end of the stem
    1126         3016 :         if (item->up()) {
    1127         1218 :             double tip = item->hook()
    1128         1218 :                          ? item->hook()->ldata()->bbox().translated(item->hook()->pos()).top()
    1129         1133 :                          : item->stem()->ldata()->bbox().translated(item->stem()->pos()).top();
    1130              : 
    1131         1218 :             chordTopY = tip + yOffset;
    1132              :         } else {
    1133         1798 :             double tip = item->hook()
    1134         1798 :                          ? item->hook()->ldata()->bbox().translated(item->hook()->pos()).bottom()
    1135         1734 :                          : item->stem()->ldata()->bbox().translated(item->stem()->pos()).bottom();
    1136              : 
    1137         1798 :             chordBotY = tip + yOffset;
    1138              :         }
    1139              :     }
    1140              : 
    1141              :     //
    1142              :     //    place all articulations with anchor at chord/rest
    1143              :     //
    1144         3174 :     chordTopY -= item->up() ? stemDist : noteDist;
    1145         3174 :     chordBotY += item->up() ? noteDist : stemDist;
    1146              :     // add space for staccato and tenuto marks which may have been previously laid out
    1147         6628 :     for (Articulation* a : item->articulations()) {
    1148         3454 :         ArticulationAnchor aa = a->anchor();
    1149         3454 :         if (a->layoutCloseToNote() && a->visible() && aa == ArticulationAnchor::AUTO) {
    1150         1241 :             if (a->up()) {
    1151          747 :                 chordTopY = a->y() - a->height() - minDist + yOffset;
    1152              :             } else {
    1153          494 :                 chordBotY = a->y() + a->height() + minDist + yOffset;
    1154              :             }
    1155              :         }
    1156              :     }
    1157              : 
    1158         6628 :     for (Articulation* a : item->articulations()) {
    1159         3454 :         if (layoutOnCrossBeamSide && !a->isOnCrossBeamSide()) {
    1160            0 :             continue;
    1161              :         }
    1162         3454 :         if (!a->layoutCloseToNote()) {
    1163         2115 :             continue;
    1164              :         }
    1165         1339 :         if (a->up()) {
    1166          807 :             if (a->visible()) {
    1167          803 :                 chordTopY = a->y() - a->height() - minDist + yOffset;
    1168              :             }
    1169              :         } else {
    1170          532 :             if (a->visible()) {
    1171          524 :                 chordBotY = a->y() + a->height() + minDist + yOffset;
    1172              :             }
    1173              :         }
    1174              :     }
    1175              :     //
    1176              :     //    now place all articulations with staff top or bottom anchor, or chord anchor for artics that don't layout close to note
    1177              :     //
    1178         3174 :     staffTopY = std::min(staffTopY, chordTopY);
    1179         3174 :     staffBotY = std::max(staffBotY, chordBotY);
    1180         3174 :     Articulation* stacc = nullptr;
    1181         6628 :     for (Articulation* a : item->articulations()) {
    1182         3454 :         double kearnHeight = 0.0;
    1183         3454 :         if ((layoutOnCrossBeamSide && !a->isOnCrossBeamSide()) || a->isLaissezVib()) {
    1184            0 :             continue;
    1185              :         }
    1186              : 
    1187         3454 :         if (a->isStaccato()) {
    1188          991 :             stacc = a;
    1189          208 :         } else if (stacc && a->isAccent() && stacc->up() == a->up()
    1190         2701 :                    && (muse::RealIsEqualOrLess(stacc->ldata()->pos().y(), 0.0)
    1191         2493 :                        || muse::RealIsEqualOrMore(stacc->ldata()->pos().y(), item->staff()->staffHeight(item->tick())))) {
    1192              :             // obviously, the accent doesn't have a cutout, so this value just artificially moves the stacc
    1193              :             // and accent closer to each other to simulate some kind of kerning. Looks great using all musescore fonts,
    1194              :             // though there is a possibility that a different font which has vertically-asymmetrical accents
    1195              :             // could make this look bad.
    1196           12 :             kearnHeight = stacAccentKern;
    1197           12 :             stacc = nullptr;
    1198              :         } else {
    1199         2451 :             stacc = nullptr;
    1200              :         }
    1201              : 
    1202         3454 :         if (!a->layoutCloseToNote()) {
    1203         2115 :             TLayout::layoutItem(a, ctx);
    1204         2115 :             if (a->up()) {
    1205         1621 :                 a->setPos(!item->up() || !a->isBasicArticulation() ? headSideX : stemSideX, staffTopY + kearnHeight - yOffset);
    1206         1621 :                 if (a->visible()) {
    1207         1589 :                     staffTopY = a->y() - a->height() - minDist + yOffset;
    1208              :                 }
    1209              :             } else {
    1210          494 :                 a->setPos(item->up() || !a->isBasicArticulation() ? headSideX : stemSideX, staffBotY - kearnHeight - yOffset);
    1211          494 :                 if (a->visible()) {
    1212          488 :                     staffBotY = a->y() + a->height() + minDist + yOffset;
    1213              :                 }
    1214              :             }
    1215         2115 :             a->mutldata()->moveX(-a->ldata()->opticalCenter());
    1216              :         }
    1217              : 
    1218         3454 :         if (!a->isOnCrossBeamSide()) {
    1219         3454 :             if (a->layoutCloseToNote()) {
    1220         1339 :                 Measure* meas = a->measure();
    1221         1339 :                 System* sys = meas->system();
    1222         1339 :                 if (sys) {
    1223         1339 :                     sys->staff(a->vStaffIdx())->skyline().add(a->shape().translate(a->systemPos() + item->staffOffset()));
    1224              :                 }
    1225              :             } else {
    1226         2115 :                 Autoplace::autoplaceSegmentElement(a, a->mutldata(), a->up(), true);
    1227              :             }
    1228         3454 :             if (a->addToSkyline()) {
    1229         3404 :                 a->segment()->staffShape(a->vStaffIdx()).add(a->shape().translated(a->pos() + item->pos() + item->staffOffset()));
    1230              :             }
    1231              :         }
    1232              :     }
    1233              : }
    1234              : 
    1235              : //---------------------------------------------------------
    1236              : //   layoutArticulations3
    1237              : //    Called after layouting slurs
    1238              : //    Fix up articulations that need to go outside the slur
    1239              : //---------------------------------------------------------
    1240              : 
    1241         1813 : void ChordLayout::layoutArticulations3(Chord* item, Slur* slur, LayoutContext& ctx)
    1242              : {
    1243              :     SlurSegment* ss;
    1244         1813 :     if (item == slur->startCR()) {
    1245          934 :         ss = slur->frontSegment();
    1246          879 :     } else if (item == slur->endCR()) {
    1247          879 :         ss = slur->backSegment();
    1248              :     } else {
    1249            0 :         return;
    1250              :     }
    1251         1813 :     Segment* s = item->segment();
    1252         1813 :     Measure* m = item->measure();
    1253         1813 :     SysStaff* itemStaff = m->system() ? m->system()->staff(item->vStaffIdx()) : nullptr;
    1254         1813 :     SysStaff* slurStaff = m->system() ? m->system()->staff(ss->vStaffIdx()) : nullptr;
    1255         1813 :     PointF itemStaffPos = itemStaff ? PointF(0.0, itemStaff->y()) : PointF();
    1256         1813 :     PointF slurStaffPos = itemStaff ? PointF(0.0, slurStaff->y()) : PointF();
    1257         1849 :     for (auto iter = item->articulations().begin(); iter != item->articulations().end(); ++iter) {
    1258           36 :         Articulation* a = *iter;
    1259           36 :         if (a->layoutCloseToNote() || !a->autoplace() || !slur->addToSkyline()) {
    1260           30 :             continue;
    1261              :         }
    1262              :         Shape aShape
    1263            6 :             = a->shape().translate(a->pos() + item->pos() + s->pos() + m->pos() + item->staffOffset() + itemStaffPos);
    1264            6 :         Shape sShape = ss->shape().translate(ss->pos() + slurStaffPos);
    1265           12 :         sShape.removeTypes({ ElementType::HAMMER_ON_PULL_OFF_TEXT });
    1266            6 :         double minDist = ctx.conf().styleAbsolute(Sid::articulationMinDistance);
    1267            6 :         bool slurBelowArticulation = a->up() && !(ss->vStaffIdx() < item->vStaffIdx());
    1268            6 :         double vertClearance = slurBelowArticulation ? aShape.verticalClearance(sShape) : sShape.verticalClearance(aShape);
    1269            6 :         if (vertClearance < minDist) {
    1270            2 :             minDist += slur->up()
    1271            4 :                        ? std::max(aShape.minVerticalDistance(sShape), 0.0)
    1272            2 :                        : std::max(sShape.minVerticalDistance(aShape), 0.0);
    1273            2 :             minDist *= slur->up() ? -1 : 1;
    1274            4 :             for (auto iter2 = iter; iter2 != item->articulations().end(); ++iter2) {
    1275            2 :                 Articulation* aa = *iter2;
    1276            2 :                 aa->mutldata()->moveY(minDist);
    1277            2 :                 if (itemStaff && aa->addToSkyline()) {
    1278            2 :                     SystemLayout::updateSkylineForElement(aa, m->system(), minDist);
    1279           22 :                     for (ShapeElement& sh : s->staffShape(item->vStaffIdx()).elements()) {
    1280           20 :                         if (sh.item() == aa) {
    1281           12 :                             sh.translate(0.0, minDist);
    1282              :                         }
    1283              :                     }
    1284              :                 }
    1285              :             }
    1286              :         }
    1287            6 :     }
    1288              : }
    1289              : 
    1290              : //! May be called again when the chord is added to or removed from a beam.
    1291       162434 : void ChordLayout::layoutStem(Chord* item, const LayoutContext& ctx)
    1292              : {
    1293       162448 :     TRACEFUNC;
    1294              : 
    1295              :     LAYOUT_CALL() << "chord: " << item->eid();
    1296              : 
    1297              :     // Stem needs to know hook's bbox and SMuFL anchors.
    1298              :     // This is done before calcDefaultStemLength because the presence or absence of a hook affects stem length
    1299       162434 :     if (item->hook()) {
    1300         3277 :         item->hook()->setHookType(item->up() ? item->durationType().hooks() : -item->durationType().hooks());
    1301         3277 :         TLayout::layoutHook(item->hook(), item->hook()->mutldata());
    1302              :     }
    1303              : 
    1304              :     // we should calculate default stem length for this chord even if it doesn't have a stem
    1305              :     // because this length is used for tremolos or other things that attach to where the stem WOULD be
    1306       162434 :     item->setDefaultStemLength(StemLayout::calcDefaultStemLength(item, ctx));
    1307              : 
    1308       162434 :     if (!item->stem()) {
    1309        18543 :         return;
    1310              :     }
    1311              : 
    1312       143891 :     item->stem()->mutldata()->setPosX(StemLayout::stemPosX(item));
    1313              : 
    1314       143891 :     item->stem()->setBaseLength(Spatium::fromAbsolute(item->defaultStemLength(), item->spatium()));
    1315       143891 :     TLayout::layoutStem(item->stem(), item->stem()->mutldata(), ctx.conf());
    1316              : 
    1317              :     // And now we need to set the position of the flag.
    1318       143891 :     if (item->hook()) {
    1319         3277 :         item->hook()->setPos(item->stem()->flagPosition());
    1320              :     }
    1321              : 
    1322              :     // Add Stem slash
    1323       143891 :     if ((item->showStemSlash()) && !(item->beam() && item->beam()->elements().front() != item)) {
    1324          554 :         if (!item->stemSlash()) {
    1325          142 :             item->add(Factory::createStemSlash(item));
    1326              :         }
    1327          554 :         TLayout::layoutStemSlash(item->stemSlash(), item->stemSlash()->mutldata(), ctx.conf());
    1328       143337 :     } else if (item->stemSlash()) {
    1329           11 :         item->remove(item->stemSlash());
    1330              :     }
    1331       162434 : }
    1332              : 
    1333        61298 : bool ChordLayout::computeUpBeamCase(const Chord* item, Beam* beam)
    1334              : {
    1335        61298 :     if (beam->cross()) {
    1336          124 :         return item->isBelowCrossBeam(beam);
    1337        61174 :     } else if (beam->userModified()) {
    1338          147 :         return isChordPosBelowBeam(item, beam);
    1339              :     }
    1340              : 
    1341        61027 :     return beam->up();
    1342              : }
    1343              : 
    1344        54915 : void ChordLayout::updateLedgerLines(Chord* item, LayoutContext& ctx)
    1345              : {
    1346              :     // initialize for palette
    1347        54915 :     track_idx_t track = 0;                     // the track lines belong to
    1348              :     // the line pos corresponding to the bottom line of the staff
    1349        54915 :     int lineBelow      = 8;                     // assuming 5-lined "staff"
    1350        54915 :     double lineDistance = 1;
    1351        54915 :     bool staffVisible  = true;
    1352        54915 :     int stepOffset = 0;                         // for staff type changes with a step offset
    1353        54915 :     bool isJianpu = false;
    1354              : 
    1355        54915 :     Segment* segment = item->segment();
    1356              : 
    1357        54915 :     if (segment) {   //not palette
    1358        54915 :         Fraction tick = segment->tick();
    1359        54915 :         staff_idx_t idx = item->staffIdx() + item->staffMove();
    1360        54915 :         track         = staff2track(idx);
    1361        54915 :         const Staff* st     = ctx.dom().staff(idx);
    1362        54915 :         lineBelow     = (st->lines(tick) - 1) * 2;
    1363        54915 :         lineDistance  = st->lineDistance(tick);
    1364        54915 :         staffVisible  = !st->isLinesInvisible(tick);
    1365        54915 :         stepOffset = st->staffType(tick)->stepOffset();
    1366        54915 :         isJianpu = st->isJianpuStaff(tick);
    1367              :     }
    1368              : 
    1369              :     // need ledger lines?
    1370        54915 :     if (isJianpu || (item->downLine() + stepOffset <= lineBelow + 1 && item->upLine() + stepOffset >= -1)) {
    1371        46941 :         muse::DeleteAll(item->ledgerLines());
    1372        46941 :         item->ledgerLines().clear();
    1373        46941 :         return;
    1374              :     }
    1375              : 
    1376              :     // the extra length of a ledger line to be added on each side of the notehead
    1377         7974 :     const double extraLen = ctx.conf().style().styleAbsolute(Sid::ledgerLineLength);
    1378              : 
    1379         7974 :     bool visible = false;
    1380              : 
    1381              :     struct LedgerLineData {
    1382              :         int line;
    1383              :         double minX, maxX;
    1384              :         bool visible;
    1385              :         bool accidental;
    1386              :     };
    1387         7974 :     std::vector<LedgerLineData> ledgerLineData;
    1388              : 
    1389              :     // scan chord notes, collecting visibility and x and y extrema
    1390              :     // NOTE: notes are sorted from bottom to top (line no. decreasing)
    1391              :     // notes are scanned twice from outside (bottom or top) toward the staff
    1392              :     // each pass stops at the first note without ledger lines
    1393         7974 :     int n = static_cast<int>(item->notes().size());
    1394              : 
    1395        23922 :     for (const bool topToBottom : { false, true }) {
    1396        15948 :         const int from = topToBottom ? n - 1 : 0;
    1397        15948 :         const int delta = topToBottom ? -1 : 1;
    1398        15948 :         std::vector<LedgerLineData> vecLines;
    1399        15948 :         double hw = 0.0;
    1400        15948 :         double minX = std::numeric_limits<double>::max();
    1401        15948 :         double maxX = std::numeric_limits<double>::min();
    1402        15948 :         int minLine = 0;
    1403        15948 :         int maxLine = lineBelow;
    1404              : 
    1405        25591 :         for (int i = from; i < n && i >= 0; i += delta) {
    1406        19286 :             const Note* note = item->notes().at(i);
    1407        19286 :             int l = note->line() + stepOffset;
    1408              : 
    1409              :             // if 1st pass and note not below staff or 2nd pass and note not above staff
    1410        19286 :             if ((!topToBottom && l <= lineBelow + 1)
    1411        16175 :                 || (topToBottom && l >= -1)) {
    1412              :                 break; // stop this pass
    1413              :             }
    1414              :             // round line number to even number toward 0
    1415         9643 :             if (l < 0) {
    1416         2484 :                 l = (l + 1) & ~1;
    1417              :             } else {
    1418         7159 :                 l = l & ~1;
    1419              :             }
    1420              : 
    1421         9643 :             if (note->visible()) { // if one note is visible,
    1422         9641 :                 visible = true;    // all lines between it and the staff are visible
    1423              :             }
    1424         9643 :             hw = std::max(hw, note->headWidth());
    1425              : 
    1426              :             // Experimental:
    1427              :             // shorten ledger line to avoid collisions with accidentals
    1428              :             // TODO: do something with the following `accid` flag
    1429              :             //
    1430              :             // bool accid = (note->accidental() && note->line() >= (l-1) && note->line() <= (l+1) );
    1431              : 
    1432              :             // ledger lines need the leftmost point of the notehead with a respect of bbox
    1433         9643 :             const double x = note->pos().x() + note->bboxXShift();
    1434         9643 :             if (x - extraLen * note->mag() < minX) {
    1435         8014 :                 minX = x - extraLen * note->mag();
    1436              :                 // increase width of all lines between this one and the staff
    1437         8023 :                 for (auto& d : vecLines) {
    1438            9 :                     if (!d.accidental && ((l < 0 && d.line >= l) || (l > 0 && d.line <= l))) {
    1439            4 :                         d.minX = minX;
    1440              :                     }
    1441              :                 }
    1442              :             }
    1443              :             // same for left side
    1444         9643 :             if (x + hw + extraLen * note->mag() > maxX) {
    1445         8040 :                 maxX = x + hw + extraLen * note->mag();
    1446         8149 :                 for (auto& d : vecLines) {
    1447          109 :                     if ((l < 0 && d.line >= l) || (l > 0 && d.line <= l)) {
    1448           30 :                         d.maxX = maxX;
    1449              :                     }
    1450              :                 }
    1451              :             }
    1452              : 
    1453              :             // check if note vert. pos. is outside current range
    1454              :             // and, if so, add data for new line(s)
    1455         9643 :             if (l < minLine) {
    1456       195862 :                 for (int i1 = l; i1 < minLine; i1 += 2) {
    1457       193910 :                     vecLines.emplace_back(LedgerLineData {
    1458              :                         /*line=*/ i1,
    1459              :                         /*minX=*/ minX,
    1460              :                         /*maxX=*/ maxX,
    1461              :                         /*visible=*/ visible,
    1462              :                         /*accidental=*/ false
    1463              :                     });
    1464              :                 }
    1465         1952 :                 minLine = l;
    1466              :             }
    1467         9643 :             if (l > maxLine) {
    1468        18183 :                 for (int i1 = maxLine + 2; i1 <= l; i1 += 2) {
    1469        12125 :                     vecLines.emplace_back(LedgerLineData {
    1470              :                         /*line=*/ i1,
    1471              :                         /*minX=*/ minX,
    1472              :                         /*maxX=*/ maxX,
    1473              :                         /*visible=*/ visible,
    1474              :                         /*accidental=*/ false
    1475              :                     });
    1476              :                 }
    1477         6058 :                 maxLine = l;
    1478              :             }
    1479              :         }
    1480        15948 :         if (minLine < 0 || maxLine > lineBelow) {
    1481         8010 :             ledgerLineData.insert(ledgerLineData.end(), vecLines.begin(), vecLines.end());
    1482              :         }
    1483        15948 :     }
    1484              : 
    1485         7974 :     double _spatium = item->spatium();
    1486         7974 :     double stepDistance = lineDistance * 0.5;
    1487         7974 :     item->resizeLedgerLinesTo(ledgerLineData.size());
    1488       214009 :     for (size_t i = 0; i < ledgerLineData.size(); ++i) {
    1489       206035 :         LedgerLineData lld = ledgerLineData[i];
    1490       206035 :         LedgerLine* h = item->ledgerLines()[i];
    1491       206035 :         h->setTrack(track);
    1492       206035 :         h->setVisible(lld.visible && staffVisible);
    1493       206035 :         h->setLen(lld.maxX - lld.minX);
    1494       206035 :         h->setPos(lld.minX, lld.line * _spatium * stepDistance);
    1495              :     }
    1496              : 
    1497       214009 :     for (LedgerLine* ll : item->ledgerLines()) {
    1498       206035 :         TLayout::layoutLedgerLine(ll, ctx);
    1499              :     }
    1500         7974 : }
    1501              : 
    1502          147 : bool ChordLayout::isChordPosBelowBeam(const Chord* item, Beam* beam)
    1503              : {
    1504          147 :     assert(!beam->beamFragments().empty());
    1505              : 
    1506          147 :     Note* baseNote = item->up() ? item->downNote() : item->upNote();
    1507          147 :     double noteY = baseNote->pagePos().y();
    1508              : 
    1509          147 :     PointF startAnchor = beam->startAnchor();
    1510          147 :     PointF endAnchor = beam->endAnchor();
    1511              : 
    1512          147 :     if (startAnchor.isNull() || endAnchor.isNull()) {
    1513           18 :         return beam->cross() ? item->isBelowCrossBeam(beam) : beam->up();
    1514              :     }
    1515              : 
    1516          129 :     if (item == beam->elements().front()) {
    1517           38 :         return noteY > startAnchor.y();
    1518              :     }
    1519              : 
    1520           91 :     if (item == beam->elements().back()) {
    1521           38 :         return noteY > endAnchor.y();
    1522              :     }
    1523              : 
    1524           53 :     PointF noteAnchor = BeamLayout::chordBeamAnchor(beam, item, ChordBeamAnchorType::Middle);
    1525           53 :     double noteX = noteAnchor.x();
    1526              : 
    1527              :     double proportionAlongX
    1528           53 :         = muse::RealIsEqual(startAnchor.x(), endAnchor.x()) ? 0.0 : (noteX - startAnchor.x()) / (endAnchor.x() - startAnchor.x());
    1529           53 :     double desiredY = proportionAlongX * (endAnchor.y() - startAnchor.y()) + startAnchor.y();
    1530           53 :     return noteY > desiredY;
    1531              : }
    1532              : 
    1533            0 : bool ChordLayout::isChordPosBelowTrem(const Chord* item, TremoloTwoChord* trem)
    1534              : {
    1535            0 :     if (!item || !trem || !trem->ldata()->isValid()) {
    1536            0 :         return true;
    1537              :     }
    1538            0 :     Note* baseNote = item->up() ? item->downNote() : item->upNote();
    1539            0 :     double noteY = baseNote->pagePos().y();
    1540              : 
    1541            0 :     PointF startAnchor = trem->startAnchor();
    1542            0 :     PointF endAnchor = trem->endAnchor();
    1543              : 
    1544            0 :     if (startAnchor.isNull() || endAnchor.isNull()) {
    1545            0 :         return trem->crossStaffBeamBetween() ? item->isBelowCrossBeam(trem) : trem->up();
    1546              :     }
    1547              : 
    1548            0 :     if (item == trem->chord1()) {
    1549            0 :         return noteY > startAnchor.y();
    1550              :     }
    1551              : 
    1552            0 :     return noteY > endAnchor.y();
    1553              : }
    1554              : 
    1555          190 : bool ChordLayout::computeUpTremoloCase(const Chord* item, TremoloTwoChord* tremolo, const LayoutContext& ctx)
    1556              : {
    1557          190 :     const Chord* c1 = tremolo->chord1();
    1558          190 :     const Chord* c2 = tremolo->chord2();
    1559          190 :     if (!c1 || !c2) {
    1560            0 :         return true;
    1561              :     }
    1562          190 :     bool cross = c1->staffMove() != c2->staffMove();
    1563          190 :     if (item == c1) {
    1564              :         // we have to lay out the tremolo because it hasn't been laid out at all yet, and we need its direction
    1565           95 :         TremoloLayout::layout(tremolo, ctx);
    1566              :     }
    1567              : 
    1568          190 :     const Measure* measure = item->findMeasure();
    1569          190 :     if (!cross && !tremolo->userModified()) {
    1570          190 :         return tremolo->up();
    1571              :     }
    1572              : 
    1573            0 :     if (!measure->system()) {
    1574              :         // this method will be called later (from Measure::layoutCrossStaff) after the
    1575              :         // system is completely laid out.
    1576              :         // this is necessary because otherwise there's no way to deal with cross-staff beams
    1577              :         // because we don't know how far apart the staves actually are
    1578            0 :         return item->ldata()->up;
    1579              :     }
    1580              : 
    1581            0 :     if (tremolo->userModified()) {
    1582            0 :         return ChordLayout::isChordPosBelowTrem(item, tremolo);
    1583              :     }
    1584              : 
    1585              :     // unmodified cross-staff trem, should be one note per staff
    1586            0 :     if (item->staffMove() != 0) {
    1587            0 :         return item->staffMove() > 0;
    1588              :     }
    1589              : 
    1590            0 :     int otherStaffMove = item->staffMove() == c1->staffMove() ? c2->staffMove() : c1->staffMove();
    1591            0 :     return otherStaffMove < 0;
    1592              : }
    1593              : 
    1594       107301 : void ChordLayout::computeUp(const Chord* item, Chord::LayoutData* ldata, const LayoutContext& ctx)
    1595              : {
    1596              :     LAYOUT_CALL() << LAYOUT_ITEM_INFO(item);
    1597              : 
    1598       107301 :     assert(!item->notes().empty());
    1599              : 
    1600              :     // Beams with one chord will be removed later, ignore
    1601       107301 :     const bool hasBeam = item->beam() && item->beam()->elements().size() > 1;
    1602              : 
    1603       107301 :     const StaffType* tab = item->staff() ? item->staff()->staffTypeForElement(item) : 0;
    1604       107301 :     bool isTabStaff = tab && tab->isTabStaff();
    1605       107301 :     if (isTabStaff) {
    1606          838 :         if (tab->stemless()) {
    1607          591 :             ldata->up = false;
    1608        74735 :             return;
    1609              :         }
    1610          247 :         if (!tab->stemThrough()) {
    1611          211 :             bool staffHasMultipleVoices = item->measure()->hasVoices(item->staffIdx(), item->tick(), item->actualTicks());
    1612          211 :             if (staffHasMultipleVoices) {
    1613            8 :                 bool isTrackEven = item->track() % 2 == 0;
    1614            8 :                 ldata->up = isTrackEven;
    1615            8 :                 return;
    1616              :             }
    1617          203 :             ldata->up = !tab->stemsDown();
    1618          203 :             return;
    1619              :         }
    1620              :     }
    1621              : 
    1622       106499 :     if (item->stemDirection() != DirectionV::AUTO
    1623         7907 :         && !hasBeam
    1624       114406 :         && !item->tremoloTwoChord()) {
    1625         6741 :         ldata->up = item->stemDirection() == DirectionV::UP;
    1626         6741 :         return;
    1627              :     }
    1628              : 
    1629        99758 :     if (item->isUiItem()) {
    1630            0 :         ldata->up = true;
    1631            0 :         return;
    1632              :     }
    1633              : 
    1634        99758 :     if (hasBeam) {
    1635        61298 :         ldata->up = computeUpBeamCase(item, item->beam());
    1636        61298 :         return;
    1637        38460 :     } else if (item->tremoloTwoChord()) {
    1638          190 :         ldata->up = computeUpTremoloCase(item, item->tremoloTwoChord(), ctx);
    1639          190 :         return;
    1640              :     }
    1641              : 
    1642        38270 :     bool staffHasMultipleVoices = item->measure()->hasVoices(item->staffIdx(), item->tick(), item->actualTicks());
    1643        38270 :     if (staffHasMultipleVoices) {
    1644         4865 :         bool isTrackEven = item->track() % 2 == 0;
    1645         4865 :         ldata->up = isTrackEven;
    1646         4865 :         return;
    1647              :     }
    1648              : 
    1649        33405 :     bool isGraceNote = item->noteType() != NoteType::NORMAL;
    1650        33405 :     if (isGraceNote) {
    1651          725 :         ldata->up = true;
    1652          725 :         return;
    1653              :     }
    1654              : 
    1655        32680 :     bool chordIsCrossStaff = item->staffMove() != 0;
    1656        32680 :     if (chordIsCrossStaff) {
    1657          114 :         ldata->up = item->staffMove() > 0;
    1658          114 :         return;
    1659              :     }
    1660              : 
    1661        32566 :     std::vector<int> distances = item->noteDistances();
    1662        32566 :     int direction = ChordLayout::computeAutoStemDirection(distances);
    1663        32566 :     ldata->up = direction > 0;
    1664        32566 : }
    1665              : 
    1666       108265 : void ChordLayout::computeUp(ChordRest* item, const LayoutContext& ctx)
    1667              : {
    1668       108265 :     if (item->isChord()) {
    1669       107301 :         Chord* ch = item_cast<Chord*>(item);
    1670       107301 :         computeUp(ch, ch->mutldata(), ctx);
    1671              :     } else {
    1672              :         // base ChordRest
    1673              :         // Beams with one chord will be removed later, ignore
    1674          964 :         const bool hasBeam = item->beam() && item->beam()->elements().size() > 1;
    1675          964 :         if (hasBeam) {
    1676          961 :             item->mutldata()->up = item->beam()->up();
    1677              :         } else {
    1678            3 :             item->mutldata()->up = true;
    1679              :         }
    1680              :     }
    1681       108265 : }
    1682              : 
    1683              : // return 1 means up, 0 means in the middle, -1 means down
    1684        36185 : int ChordLayout::computeAutoStemDirection(const std::vector<int>& noteDistances)
    1685              : {
    1686        36185 :     int left = 0;
    1687        36185 :     int right = static_cast<int>(noteDistances.size()) - 1;
    1688              : 
    1689        40778 :     while (left <= right) {
    1690        36276 :         int leftNote = noteDistances.at(left);
    1691        36276 :         int rightNote = noteDistances.at(right);
    1692        36276 :         int netDirecting = leftNote + rightNote;
    1693        36276 :         if (netDirecting == 0) {
    1694         4593 :             left++;
    1695         4593 :             right--;
    1696         4593 :             continue;
    1697              :         }
    1698        31683 :         return netDirecting > 0 ? 1 : -1;
    1699              :     }
    1700         4502 :     return 0;
    1701              : }
    1702              : 
    1703       107098 : void ChordLayout::layoutJianpuDurationLines(Chord* item, LayoutContext& ctx)
    1704              : {
    1705       107098 :     Segment* segment = item->segment();
    1706       107098 :     if (!segment) {
    1707       107092 :         return; // no segment, nothing to do
    1708              :     }
    1709       107098 :     Fraction tick = segment->tick();
    1710       107098 :     staff_idx_t idx = item->staffIdx() + item->staffMove();
    1711       107098 :     track_idx_t track = staff2track(idx);
    1712       107098 :     const Staff* staff = ctx.dom().staff(idx);
    1713       107098 :     bool staffVisible = !staff->isLinesInvisible(tick);
    1714       107098 :     bool isJianpu = staff->isJianpuStaff(tick);
    1715              : 
    1716       107098 :     if (!isJianpu) {
    1717       103681 :         muse::DeleteAll(item->jianpuDurationLines());
    1718       103681 :         item->jianpuDurationLines().clear();
    1719       103681 :         return;
    1720              :     }
    1721              : 
    1722         3417 :     int lines = jianpuAugmentationLinesForDuration(item->durationType());
    1723         3417 :     if (lines == 0) {
    1724         3411 :         muse::DeleteAll(item->jianpuDurationLines());
    1725         3411 :         item->jianpuDurationLines().clear();
    1726         3411 :         return;
    1727              :     }
    1728              : 
    1729            6 :     item->setJianpuDurationLineCount(lines);
    1730              : 
    1731            6 :     const Note* note = item->upNote();
    1732            6 :     if (!note) {
    1733            0 :         return;
    1734              :     }
    1735              : 
    1736            6 :     double hw = note->headWidth();
    1737            6 :     double hx = note->pos().x() + note->bboxXShift();
    1738            6 :     double lengtheningY = note->pos().y();
    1739           28 :     for (int i = 0; i < lines; ++i) {
    1740           22 :         JianpuDurationLine* dl = item->jianpuDurationLines()[i];
    1741           22 :         dl->setOwnershipParent(item);
    1742           22 :         dl->setTrack(track);
    1743           22 :         dl->setVisible(staffVisible);
    1744           22 :         dl->mutldata()->len = hw;
    1745           22 :         dl->setPos(hx + hw * 1.2 * (i + 1), lengtheningY);
    1746              :     }
    1747              : 
    1748           28 :     for (JianpuDurationLine* dl : item->jianpuDurationLines()) {
    1749           22 :         TLayout::layoutJianpuDurationLine(dl, ctx);
    1750              :     }
    1751              : }
    1752              : 
    1753        54899 : void ChordLayout::layoutJianpuOctaveDots(Chord* item, LayoutContext& ctx)
    1754              : {
    1755        54899 :     Segment* segment = item->segment();
    1756        54899 :     if (!segment) {
    1757        53141 :         return; // no segment, nothing to do
    1758              :     }
    1759        54899 :     Fraction tick = segment->tick();
    1760        54899 :     staff_idx_t idx = item->staffIdx() + item->staffMove();
    1761        54899 :     track_idx_t track = staff2track(idx);
    1762        54899 :     const Staff* staff = ctx.dom().staff(idx);
    1763        54899 :     bool staffVisible = !staff->isLinesInvisible(tick);
    1764        54899 :     bool isJianpu = staff->isJianpuStaff(tick);
    1765        54899 :     if (!isJianpu) {
    1766       113548 :         for (Note* note : item->notes()) {
    1767        60407 :             note->setJianpuOctaveDotCount(0);
    1768              :         }
    1769        53141 :         return;
    1770              :     }
    1771              : 
    1772         1758 :     const StaffType* st = staff->staffTypeForElement(item);
    1773         1758 :     double height = st->jianpuBoxH() * item->magS();
    1774         1758 :     KeySigEvent ks = staff->keySigEvent(tick);
    1775              :     KeyMode mode;
    1776              :     int tonicTpc;
    1777         1758 :     jianpuKeyMapping(ks, mode, tonicTpc);
    1778              : 
    1779         3522 :     for (Note* note : item->notes()) {
    1780         1764 :         const double distance = ctx.conf().styleAbsolute(Sid::jianpuOctaveDotDistance) * item->magS();
    1781         1764 :         const int octave = pitch2JianpuOctave(note->epitch(), note->tpc(), tonicTpc, mode);
    1782         1764 :         const int dots = abs(octave);
    1783         1764 :         double offsetY = 0;
    1784         1764 :         if (octave > 0) {
    1785         1185 :             offsetY = -(height * .5 + dots * distance);
    1786          579 :         } else if (octave < 0) {
    1787          169 :             offsetY = height * .5 + distance;
    1788          169 :             if (note == item->upNote()) {
    1789              :                 // The octave dot should be under the jianpu beam
    1790          169 :                 offsetY += jianpuBeamOffset(item, PlacementV::BELOW, ctx);
    1791              :             }
    1792              :         } else {
    1793          410 :             note->setJianpuOctaveDotCount(0);
    1794          410 :             continue;
    1795              :         }
    1796              : 
    1797         1354 :         double hw = note->headWidth();
    1798         1354 :         double minX = note->bboxXShift();
    1799         1354 :         double maxX = minX + hw;
    1800              : 
    1801         1354 :         note->setJianpuOctaveDotCount(dots);
    1802         3602 :         for (int i = 0; i < dots; ++i) {
    1803         2248 :             JianpuOctaveDot* dot = note->jianpuOctaveDots()[i];
    1804         2248 :             dot->setOwnershipParent(note);
    1805         2248 :             dot->setTrack(track);
    1806         2248 :             dot->setVisible(staffVisible);
    1807         2248 :             dot->mutldata()->above = octave > 0;
    1808         2248 :             dot->mutldata()->len = maxX - minX;
    1809         2248 :             dot->setPos(minX, offsetY + i * distance);
    1810              :         }
    1811              : 
    1812         3602 :         for (JianpuOctaveDot* od : note->jianpuOctaveDots()) {
    1813         2248 :             TLayout::layoutJianpuOctaveDot(od, ctx);
    1814              :         }
    1815              :     }
    1816         1758 : }
    1817              : 
    1818              : //---------------------------------------------------------
    1819              : //   layoutVoiceOffsets
    1820              : //    Stacks each voice's jianpu number column into its own vertical band (voice 1 on top),
    1821              : //    since jianpu doesn't use stem direction to separate voices. No-op for other staff types.
    1822              : //    Scoped to the whole system so band height stays consistent across the line.
    1823              : //---------------------------------------------------------
    1824              : 
    1825        15625 : void ChordLayout::layoutVoiceOffsets(System* system, staff_idx_t staffIdx, LayoutContext& ctx)
    1826              : {
    1827        15625 :     const Staff* staff = ctx.dom().staff(staffIdx);
    1828        15625 :     if (!staff || !staff->show()) {
    1829        15625 :         return;
    1830              :     }
    1831        15043 :     const Measure* firstMeasure = system ? system->firstMeasure() : nullptr;
    1832        15043 :     if (!firstMeasure || !staff->isJianpuStaff(firstMeasure->tick())) {
    1833        14952 :         return;
    1834              :     }
    1835              : 
    1836              :     // the note's own position, ignoring octave dots/beams - this is what every chord in a
    1837              :     // voice must be aligned to, so dots on some notes but not others don't throw off the line
    1838         1945 :     auto itemBaselineTop = [](EngravingItem* e) -> double {
    1839         1945 :         if (e->isChord()) {
    1840         1665 :             Note* upNote = toChord(e)->upNote();
    1841         1665 :             return upNote->ldata()->pos().y();
    1842              :         }
    1843          280 :         return e->ldata()->pos().y();
    1844              :     };
    1845              :     // slurs are laid out after this pass, so estimate their reach (mirrors slurPos/computeShoulderHeight)
    1846            0 :     auto crSystemX = [system](const ChordRest* cr, bool isStart) -> double {
    1847            0 :         if (cr->measure()->system() != system) {
    1848            0 :             return isStart ? 0.0 : system->width();
    1849              :         }
    1850            0 :         return cr->x() + cr->segment()->x() + cr->measure()->x();
    1851           91 :     };
    1852         3330 :     auto includeSlurExtents = [&ctx, &crSystemX](Chord* chord, double& top, double& bottom) {
    1853         3330 :         std::set<Slur*> slurs;
    1854         3330 :         for (Spanner* spanner : chord->startingSpanners()) {
    1855            0 :             if (spanner->isSlur()) {
    1856            0 :                 slurs.insert(toSlur(spanner));
    1857              :             }
    1858              :         }
    1859         3330 :         for (Spanner* spanner : chord->endingSpanners()) {
    1860            0 :             if (spanner->isSlur()) {
    1861            0 :                 slurs.insert(toSlur(spanner));
    1862              :             }
    1863              :         }
    1864              : 
    1865         3330 :         const double sp = chord->spatium();
    1866         3330 :         for (Slur* slur : slurs) {
    1867            0 :             if (!slur->startCR() || !slur->endCR() || !slur->addToSkyline()) {
    1868            0 :                 continue;
    1869              :             }
    1870            0 :             SlurTieLayout::computeUp(slur, ctx);
    1871            0 :             const double length = std::max(crSystemX(slur->endCR(), false) - crSystemX(slur->startCR(), true), 0.0);
    1872            0 :             const double arc = 0.75 * std::sqrt(length / sp / 4.0) * sp;
    1873            0 :             const double reach = 0.9 * sp * chord->intrinsicMag() + arc + ctx.conf().styleAbsolute(Sid::slurMidWidth);
    1874            0 :             if (slur->up()) {
    1875            0 :                 top -= reach;
    1876              :             } else {
    1877            0 :                 bottom += reach;
    1878              :             }
    1879              :         }
    1880         3330 :     };
    1881         1945 :     auto itemExtentTop = [&ctx, &includeSlurExtents](EngravingItem* e) -> double {
    1882         1945 :         if (e->isChord()) {
    1883         1665 :             Chord* chord = toChord(e);
    1884         1665 :             double top = DBL_MAX;
    1885         1665 :             double bottom = -DBL_MAX;
    1886         3334 :             for (Note* note : chord->notes()) {
    1887         1669 :                 const double y = note->ldata()->pos().y();
    1888         1669 :                 top = std::min(top, y + note->ldata()->bbox().top());
    1889         3702 :                 for (JianpuOctaveDot* dot : note->jianpuOctaveDots()) {
    1890         2033 :                     if (dot->ldata()->above) {
    1891         1855 :                         top = std::min(top, y + dot->ldata()->pos().y() + dot->ldata()->bbox().top());
    1892              :                     }
    1893              :                 }
    1894              :             }
    1895         1665 :             includeSlurExtents(chord, top, bottom);
    1896         1665 :             top -= jianpuBeamOffset(chord, PlacementV::ABOVE, ctx);
    1897         1665 :             return top;
    1898              :         }
    1899          280 :         return e->ldata()->pos().y() + e->ldata()->bbox().top();
    1900           91 :     };
    1901         1945 :     auto itemExtentBottom = [&ctx, &includeSlurExtents](EngravingItem* e) -> double {
    1902         1945 :         if (e->isChord()) {
    1903         1665 :             Chord* chord = toChord(e);
    1904         1665 :             double bottom = -DBL_MAX;
    1905         1665 :             double top = DBL_MAX;
    1906         1665 :             bool upNoteHasBelowDot = false;
    1907         3334 :             for (Note* note : chord->notes()) {
    1908         1669 :                 const double y = note->ldata()->pos().y();
    1909         1669 :                 bottom = std::max(bottom, y + note->ldata()->bbox().bottom());
    1910         3702 :                 for (JianpuOctaveDot* dot : note->jianpuOctaveDots()) {
    1911         2033 :                     if (!dot->ldata()->above) {
    1912          178 :                         bottom = std::max(bottom, y + dot->ldata()->pos().y() + dot->ldata()->bbox().bottom());
    1913          178 :                         if (note == chord->upNote()) {
    1914          178 :                             upNoteHasBelowDot = true;
    1915              :                         }
    1916              :                     }
    1917              :                 }
    1918              :             }
    1919         1665 :             includeSlurExtents(chord, top, bottom);
    1920              :             // a diminution beam placed below the chord needs extra clearance beneath it, unless
    1921              :             // the upnote's below-dot is already positioned under the beam (see layoutJianpuOctaveDots)
    1922         1665 :             if (!upNoteHasBelowDot) {
    1923         1496 :                 bottom += jianpuBeamOffset(chord, PlacementV::BELOW, ctx);
    1924              :             }
    1925         1665 :             return bottom;
    1926              :         }
    1927          280 :         return e->ldata()->pos().y() + e->ldata()->bbox().bottom();
    1928           91 :     };
    1929           91 :     std::set<SpannerSegment*> shiftedSlurSegments;
    1930            0 :     auto shiftChordSlurs = [&system, &shiftedSlurSegments](Chord* chord, double dy) {
    1931            0 :         for (const std::set<Spanner*>& spanners : { chord->startingSpanners(), chord->endingSpanners() }) {
    1932            0 :             for (Spanner* spanner : spanners) {
    1933            0 :                 if (!spanner->isSlur()) {
    1934            0 :                     continue;
    1935              :                 }
    1936            0 :                 for (SpannerSegment* segment : toSlur(spanner)->spannerSegments()) {
    1937            0 :                     if (segment->system() == system && shiftedSlurSegments.insert(segment).second) {
    1938            0 :                         segment->move(PointF(0.0, dy));
    1939              :                     }
    1940              :                 }
    1941              :             }
    1942            0 :         }
    1943            0 :     };
    1944            0 :     auto shiftItem = [&shiftChordSlurs](EngravingItem* e, double dy) {
    1945            0 :         if (e->isChord()) {
    1946            0 :             Chord* chord = toChord(e);
    1947            0 :             for (Note* note : chord->notes()) {
    1948            0 :                 note->mutldata()->moveY(dy);
    1949              :             }
    1950            0 :             shiftChordSlurs(chord, dy);
    1951            0 :             for (Chord* grace : chord->graceNotes()) {
    1952            0 :                 for (Note* note : grace->notes()) {
    1953            0 :                     note->mutldata()->moveY(dy);
    1954              :                 }
    1955            0 :                 shiftChordSlurs(grace, dy);
    1956              :                 // chord bbox is derived from its shape; slurPos() reads it later
    1957            0 :                 fillShape(grace, grace->mutldata());
    1958              :             }
    1959              :             // duration lines are positioned relative to the chord, not the note, so they
    1960              :             // don't follow the note shift above and need to be moved explicitly
    1961            0 :             for (JianpuDurationLine* dl : chord->jianpuDurationLines()) {
    1962            0 :                 dl->mutldata()->moveY(dy);
    1963              :             }
    1964            0 :             fillShape(chord, chord->mutldata());
    1965            0 :         } else if (e->isRest()) {
    1966            0 :             Rest* rest = toRest(e);
    1967            0 :             rest->mutldata()->moveY(dy);
    1968            0 :             for (JianpuDurationLine* dl : rest->jianpuDurationLines()) {
    1969            0 :                 dl->mutldata()->moveY(dy);
    1970              :             }
    1971              :         }
    1972            0 :     };
    1973              : 
    1974              :     // chord-rests belonging to a given voice, grouped by the segment they occur in
    1975           91 :     std::map<voice_idx_t, std::vector<std::vector<EngravingItem*> > > groupsByVoice;
    1976              :     // how far each voice's content can extend above/below its own baseline (octave dots, beams)
    1977           91 :     std::map<voice_idx_t, double> maxAbove;
    1978           91 :     std::map<voice_idx_t, double> maxBelow;
    1979              : 
    1980          317 :     for (MeasureBase* mb : system->measures()) {
    1981          226 :         if (!mb->isMeasure()) {
    1982            0 :             continue;
    1983              :         }
    1984         2639 :         for (Segment& segment : toMeasure(mb)->segments()) {
    1985         2413 :             if (!segment.isChordRestType()) {
    1986          468 :                 continue;
    1987              :             }
    1988              : 
    1989         1945 :             std::map<voice_idx_t, std::vector<EngravingItem*> > itemsByVoiceHere;
    1990         9725 :             for (EngravingItem* e : segment.elist()) {
    1991         7780 :                 if (e && e->isChordRest() && e->vStaffIdx() == staffIdx) {
    1992         1945 :                     itemsByVoiceHere[e->voice()].push_back(e);
    1993              :                 }
    1994              :             }
    1995              : 
    1996         3890 :             for (auto& pair : itemsByVoiceHere) {
    1997         1945 :                 double baseline = DBL_MAX;
    1998         1945 :                 double extentTop = DBL_MAX;
    1999         1945 :                 double extentBottom = -DBL_MAX;
    2000         3890 :                 for (EngravingItem* e : pair.second) {
    2001         1945 :                     baseline = std::min(baseline, itemBaselineTop(e));
    2002         1945 :                     extentTop = std::min(extentTop, itemExtentTop(e));
    2003         1945 :                     extentBottom = std::max(extentBottom, itemExtentBottom(e));
    2004              :                 }
    2005         1945 :                 if (baseline == DBL_MAX) {
    2006            0 :                     continue;
    2007              :                 }
    2008         1945 :                 maxAbove[pair.first] = std::max(maxAbove[pair.first], baseline - extentTop);
    2009         1945 :                 maxBelow[pair.first] = std::max(maxBelow[pair.first], extentBottom - baseline);
    2010         1945 :                 groupsByVoice[pair.first].push_back(std::move(pair.second));
    2011              :             }
    2012         1945 :         }
    2013              :     }
    2014              : 
    2015           91 :     if (groupsByVoice.size() < 2) {
    2016           91 :         return;
    2017              :     }
    2018              : 
    2019              :     // anchor absolute band positions to the topmost voice's natural (unshifted) baseline
    2020            0 :     double referenceTop = DBL_MAX;
    2021            0 :     for (EngravingItem* e : groupsByVoice.begin()->second.front()) {
    2022            0 :         referenceTop = std::min(referenceTop, itemBaselineTop(e));
    2023              :     }
    2024            0 :     if (referenceTop == DBL_MAX) {
    2025            0 :         return;
    2026              :     }
    2027              : 
    2028            0 :     const double voiceDist = ctx.conf().styleAbsolute(Sid::jianpuVoiceVerticalDistance);
    2029              : 
    2030              :     // each voice's baseline sits far enough below the previous one to clear both the previous
    2031              :     // voice's downward extent (dots/beam below) and this voice's own upward extent (dots above)
    2032            0 :     std::map<voice_idx_t, double> bandTargetTop;
    2033            0 :     double nextBaseline = referenceTop;
    2034            0 :     double prevBelow = 0.0;
    2035            0 :     bool firstVoice = true;
    2036            0 :     for (auto& pair : maxAbove) {
    2037            0 :         const voice_idx_t voice = pair.first;
    2038            0 :         if (!firstVoice) {
    2039            0 :             nextBaseline += prevBelow + voiceDist + pair.second;
    2040              :         }
    2041            0 :         bandTargetTop[voice] = nextBaseline;
    2042            0 :         prevBelow = maxBelow.at(voice);
    2043            0 :         firstVoice = false;
    2044              :     }
    2045              : 
    2046            0 :     std::set<Segment*> shiftedSegments;
    2047            0 :     for (auto& pair : groupsByVoice) {
    2048            0 :         const double targetTop = bandTargetTop.at(pair.first);
    2049            0 :         for (const std::vector<EngravingItem*>& segmentItems : pair.second) {
    2050            0 :             double top = DBL_MAX;
    2051            0 :             for (EngravingItem* e : segmentItems) {
    2052            0 :                 top = std::min(top, itemBaselineTop(e));
    2053              :             }
    2054            0 :             if (top == DBL_MAX) {
    2055            0 :                 continue;
    2056              :             }
    2057            0 :             const double dy = targetTop - top;
    2058            0 :             if (muse::RealIsNull(dy)) {
    2059            0 :                 continue;
    2060              :             }
    2061            0 :             for (EngravingItem* e : segmentItems) {
    2062            0 :                 shiftItem(e, dy);
    2063            0 :                 shiftedSegments.insert(toChordRest(e)->segment());
    2064              :             }
    2065              :         }
    2066              :     }
    2067              : 
    2068              :     // slur collision avoidance and skylines read the segment staff shape
    2069            0 :     for (Segment* segment : shiftedSegments) {
    2070            0 :         segment->createShape(staffIdx);
    2071              :     }
    2072          364 : }
    2073              : 
    2074              : //---------------------------------------------------------
    2075              : //   layoutSegmentElements
    2076              : //---------------------------------------------------------
    2077              : 
    2078       101325 : static void layoutSegmentElements(Segment* segment, track_idx_t startTrack, track_idx_t endTrack, staff_idx_t staffIdx, LayoutContext& ctx)
    2079              : {
    2080       620989 :     for (track_idx_t track = startTrack; track < endTrack; ++track) {
    2081       519664 :         if (EngravingItem* e = segment->element(track)) {
    2082       122655 :             if (e->vStaffIdx() == staffIdx) {
    2083        98468 :                 TLayout::layoutItem(e, ctx);
    2084              :             }
    2085              :         }
    2086              :     }
    2087       101325 : }
    2088              : 
    2089         3658 : void ChordLayout::skipAccidentals(Segment* segment, track_idx_t startTrack, track_idx_t endTrack)
    2090              : {
    2091        18290 :     for (track_idx_t track = startTrack; track < endTrack; ++track) {
    2092        14632 :         EngravingItem* item = segment->element(track);
    2093        14632 :         if (item && item->isChord()) {
    2094         5282 :             for (Note* note : toChord(item)->notes()) {
    2095         2740 :                 Accidental* acc = note->accidental();
    2096         2740 :                 if (acc) {
    2097            0 :                     acc->mutldata()->setIsSkipDraw(true);
    2098              :                 }
    2099              :             }
    2100              :         }
    2101              :     }
    2102         3658 : }
    2103              : 
    2104       100103 : ChordPosInfo ChordLayout::calculateChordPosInfo(Segment* segment, staff_idx_t staffIdx, track_idx_t partStartTrack,
    2105              :                                                 track_idx_t partEndTrack, LayoutContext& ctx)
    2106              : {
    2107       100103 :     const Staff* staff = ctx.dom().staff(staffIdx);
    2108              : 
    2109       100103 :     ChordPosInfo posInfo = ChordPosInfo();
    2110              : 
    2111       614879 :     for (track_idx_t track = partStartTrack; track < partEndTrack; ++track) {
    2112       514776 :         EngravingItem* e = segment->element(track);
    2113       514776 :         const bool calcChordPos = e && e->isChord() && toChord(e)->vStaffIdx() == staffIdx;
    2114       514776 :         if (!calcChordPos) {
    2115       460547 :             continue;
    2116              :         }
    2117              : 
    2118        54229 :         Chord* chord = toChord(e);
    2119        54229 :         posInfo.chords.push_back(chord);
    2120        54229 :         bool hasGraceBefore = false;
    2121        55128 :         for (Chord* c : chord->graceNotes()) {
    2122          899 :             if (c->isGraceBefore()) {
    2123          664 :                 hasGraceBefore = true;
    2124              :             }
    2125          899 :             layoutChords2(c->notes(), c->up(), ctx);     // layout grace note noteheads
    2126         2697 :             layoutChords3({ c }, c->notes(), staff, ctx);     // layout grace note chords
    2127              :         }
    2128        54229 :         if (chord->up()) {
    2129        28979 :             ++posInfo.upVoices;
    2130        28979 :             posInfo.upStemNotes.insert(posInfo.upStemNotes.end(), chord->notes().begin(), chord->notes().end());
    2131        28979 :             posInfo.upDots   = std::max(posInfo.upDots, chord->dots());
    2132        28979 :             posInfo.maxUpMag = std::max(posInfo.maxUpMag, chord->mag());
    2133        28979 :             if (!posInfo.upHooks && !chord->beam()) {
    2134        18350 :                 posInfo.upHooks = chord->hook();
    2135              :             }
    2136        28979 :             if (hasGraceBefore) {
    2137          306 :                 posInfo.upGrace = true;
    2138              :             }
    2139              :         } else {
    2140        25250 :             ++posInfo.downVoices;
    2141        25250 :             posInfo.downStemNotes.insert(posInfo.downStemNotes.end(), chord->notes().begin(), chord->notes().end());
    2142        25250 :             posInfo.downDots = std::max(posInfo.downDots, chord->dots());
    2143        25250 :             posInfo.maxDownMag = std::max(posInfo.maxDownMag, chord->mag());
    2144        25250 :             if (!posInfo.downHooks && !chord->beam()) {
    2145        17184 :                 posInfo.downHooks = chord->hook();
    2146              :             }
    2147        25250 :             if (hasGraceBefore) {
    2148          195 :                 posInfo.downGrace = true;
    2149              :             }
    2150              :         }
    2151              :     }
    2152              : 
    2153       100103 :     return posInfo;
    2154            0 : }
    2155              : 
    2156        51686 : void ChordLayout::calculateMaxNoteWidths(ChordPosInfo& posInfo, const Fraction& tick, const Staff* staff, LayoutContext& ctx)
    2157              : {
    2158        51686 :     double nominalWidth  = ctx.conf().noteHeadWidth() * staff->staffMag(tick);
    2159        51686 :     posInfo.maxUpWidth   = nominalWidth * posInfo.maxUpMag;
    2160        51686 :     posInfo.maxDownWidth = nominalWidth * posInfo.maxDownMag;
    2161              : 
    2162              :     // layout upstem noteheads
    2163        51686 :     if (posInfo.upVoices > 1) {
    2164          152 :         std::sort(posInfo.upStemNotes.begin(), posInfo.upStemNotes.end(),
    2165          232 :                   [](Note* n1, const Note* n2) ->bool { return n1->stringOrLine() > n2->stringOrLine(); });
    2166              :     }
    2167        51686 :     if (posInfo.upVoices) {
    2168        28820 :         double hw = layoutChords2(posInfo.upStemNotes, true, ctx);
    2169        28820 :         posInfo.maxUpWidth = std::max(posInfo.maxUpWidth, hw);
    2170              :     }
    2171              : 
    2172              :     // layout downstem noteheads
    2173        51686 :     if (posInfo.downVoices > 1) {
    2174           72 :         std::sort(posInfo.downStemNotes.begin(), posInfo.downStemNotes.end(),
    2175           99 :                   [](Note* n1, const Note* n2) ->bool { return n1->stringOrLine() > n2->stringOrLine(); });
    2176              :     }
    2177        51686 :     if (posInfo.downVoices) {
    2178        25178 :         double hw = layoutChords2(posInfo.downStemNotes, false, ctx);
    2179        25178 :         posInfo.maxDownWidth = std::max(posInfo.maxDownWidth, hw);
    2180              :     }
    2181        51686 : }
    2182              : 
    2183        51686 : void ChordLayout::applyChordOffsets(Segment* segment, staff_idx_t staffIdx, track_idx_t partStartTrack, track_idx_t partEndTrack,
    2184              :                                     OffsetInfo& offsetInfo, const ChordPosInfo& posInfo, LayoutContext& ctx)
    2185              : {
    2186        51686 :     const Staff* staff = ctx.dom().staff(staffIdx);
    2187        51686 :     const bool isTab = staff->isTabStaff(segment->tick());
    2188              : 
    2189              :     // apply chord offsets
    2190       311110 :     for (track_idx_t track = partStartTrack; track < partEndTrack; ++track) {
    2191       259424 :         EngravingItem* e = segment->element(track);
    2192       259424 :         const bool layoutChord = e && e->isChord() && toChord(e)->vStaffIdx() == staffIdx;
    2193       259424 :         if (!layoutChord) {
    2194       205195 :             continue;
    2195              :         }
    2196        54229 :         Chord* chord = toChord(e);
    2197        54229 :         Chord::LayoutData* chordLdata = chord->mutldata();
    2198              :         // only centre chords if we are separating voices and this voice has no collision
    2199        54229 :         const bool combineVoices = chord->shouldCombineVoice();
    2200        54229 :         if (!combineVoices && !muse::contains(offsetInfo.tracksToAdjust, track)) {
    2201            0 :             if (chord->up()) {
    2202            0 :                 chordLdata->moveX(offsetInfo.centerUp);
    2203              :             } else {
    2204            0 :                 chordLdata->moveX(offsetInfo.centerDown);
    2205              :             }
    2206            0 :             continue;
    2207              :         }
    2208              : 
    2209        54229 :         if (chord->up()) {
    2210        28979 :             if (!muse::RealIsNull(offsetInfo.upOffset)) {
    2211          393 :                 offsetInfo.oversizeUp = isTab ? offsetInfo.oversizeUp / 2 : offsetInfo.oversizeUp;
    2212          393 :                 chordLdata->moveX(offsetInfo.upOffset + offsetInfo.centerAdjustUp + offsetInfo.oversizeUp);
    2213          393 :                 if (posInfo.downDots && !posInfo.upDots) {
    2214            2 :                     chordLdata->moveX(offsetInfo.dotAdjust);
    2215              :                 }
    2216              :             } else {
    2217        28586 :                 chordLdata->moveX(offsetInfo.centerUp);
    2218              :             }
    2219              :         } else {
    2220        25250 :             if (!muse::RealIsNull(offsetInfo.downOffset)) {
    2221           55 :                 chordLdata->moveX(offsetInfo.downOffset + offsetInfo.centerAdjustDown);
    2222           55 :                 if (posInfo.upDots && !posInfo.downDots) {
    2223            0 :                     chordLdata->moveX(offsetInfo.dotAdjust);
    2224              :                 }
    2225              :             } else {
    2226        25195 :                 chordLdata->moveX(offsetInfo.centerDown);
    2227              :             }
    2228              :         }
    2229              :     }
    2230              : 
    2231              :     // layout chords
    2232        51686 :     std::vector<Note*> notes;
    2233        51686 :     if (posInfo.upVoices) {
    2234        28820 :         notes.insert(notes.end(), posInfo.upStemNotes.begin(), posInfo.upStemNotes.end());
    2235              :     }
    2236        51686 :     if (posInfo.downVoices) {
    2237        25178 :         notes.insert(notes.end(), posInfo.downStemNotes.begin(), posInfo.downStemNotes.end());
    2238              :     }
    2239        51686 :     if (posInfo.upVoices + posInfo.downVoices > 1) {
    2240         2394 :         std::sort(notes.begin(), notes.end(),
    2241        10437 :                   [](Note* n1, const Note* n2) ->bool { return n1->stringOrLine() > n2->stringOrLine(); });
    2242              :     }
    2243        51686 :     layoutChords3(posInfo.chords, notes, staff, ctx);
    2244        51686 : }
    2245              : 
    2246        51686 : OffsetInfo ChordLayout::centreChords(const Segment* segment, ChordPosInfo& posInfo, staff_idx_t staffIdx,
    2247              :                                      const Fraction& tick, LayoutContext& ctx)
    2248              : {
    2249        51686 :     const Staff* staff = ctx.dom().staff(staffIdx);
    2250        51686 :     const bool isTab = staff->isTabStaff(segment->tick());
    2251              : 
    2252        51686 :     OffsetInfo offsetInfo = OffsetInfo();
    2253              :     // only center chords on standard staves.  This is a simpler process for TAB and done elsewhere
    2254        51686 :     if (isTab) {
    2255          223 :         return offsetInfo;
    2256              :     }
    2257              : 
    2258        51463 :     double sp = staff->spatium(tick);
    2259        51463 :     double nominalWidth = ctx.conf().noteHeadWidth() * staff->staffMag(tick);
    2260              : 
    2261              :     // only center chords if they differ from nominal by at least this amount
    2262              :     // this avoids unnecessary centering on differences due only to floating point roundoff
    2263              :     // it also allows for the possibility of disabling centering
    2264              :     // for notes only "slightly" larger than nominal, like half notes
    2265              :     // but this will result in them not being aligned with each other between voices
    2266              :     // unless you change to left alignment as described in the comments below
    2267        51463 :     double centerThreshold = 0.01 * sp;
    2268              : 
    2269              :     // amount by which actual width exceeds nominal, adjusted for staff mag() only
    2270        51463 :     double headDiff = posInfo.maxUpWidth - nominalWidth;
    2271              :     // amount by which actual width exceeds nominal, adjusted for staff & chord/note mag()
    2272        51463 :     double headDiff2 = posInfo.maxUpWidth - nominalWidth * (posInfo.maxUpMag / staff->staffMag(tick));
    2273        51463 :     if (headDiff > centerThreshold && !isTab) {
    2274              :         // larger than nominal
    2275         3200 :         offsetInfo.centerUp = headDiff * -0.5;
    2276              :         // maxUpWidth is true width, but we no longer will care about that
    2277              :         // instead, we care only about portion to right of origin
    2278         3200 :         posInfo.maxUpWidth += offsetInfo.centerUp;
    2279              :         // to left align rather than center, delete both of the above
    2280         3200 :         if (headDiff2 > centerThreshold) {
    2281              :             // if max notehead is wider than nominal with chord/note mag() applied
    2282              :             // then noteheads extend to left of origin
    2283              :             // because stemPosX() is based on nominal width
    2284              :             // so we need to correct for that too
    2285         3200 :             offsetInfo.centerUp += headDiff2;
    2286         3200 :             offsetInfo.oversizeUp = headDiff2;
    2287              :         }
    2288        48263 :     } else if (-headDiff > centerThreshold) {
    2289              :         // smaller than nominal
    2290        22792 :         offsetInfo.centerUp = -headDiff * 0.5;
    2291        22792 :         if (headDiff2 > centerThreshold) {
    2292              :             // max notehead is wider than nominal with chord/note mag() applied
    2293              :             // perform same adjustment as above
    2294            7 :             offsetInfo.centerUp += headDiff2;
    2295            7 :             offsetInfo.oversizeUp = headDiff2;
    2296              :         }
    2297        22792 :         offsetInfo.centerAdjustDown = offsetInfo.centerUp;
    2298              :     }
    2299              : 
    2300        51463 :     headDiff = posInfo.maxDownWidth - nominalWidth;
    2301        51463 :     if (headDiff > centerThreshold) {
    2302              :         // larger than nominal
    2303         2728 :         offsetInfo.centerDown = headDiff * -0.5;
    2304              :         // to left align rather than center, change the above to
    2305              :         //centerAdjustUp = headDiff;
    2306         2728 :         posInfo.maxDownWidth = nominalWidth - offsetInfo.centerDown;
    2307        48735 :     } else if (-headDiff > centerThreshold && !isTab) {
    2308              :         // smaller than nominal
    2309        26648 :         offsetInfo.centerDown = -headDiff * 0.5;
    2310        26648 :         offsetInfo.centerAdjustUp = offsetInfo.centerDown;
    2311              :     }
    2312              : 
    2313        51463 :     return offsetInfo;
    2314            0 : }
    2315              : 
    2316        51686 : void ChordLayout::calculateChordOffsets(Segment* segment, staff_idx_t staffIdx, const Fraction& tick,
    2317              :                                         OffsetInfo& offsetInfo, ChordPosInfo& posInfo, LayoutContext& ctx)
    2318              : {
    2319              :     // handle conflict between upstem and downstem chords
    2320        51686 :     if (!posInfo.upVoices || !posInfo.downVoices) {
    2321        49374 :         return;
    2322              :     }
    2323         2312 :     const Staff* staff = ctx.dom().staff(staffIdx);
    2324         2312 :     double sp = staff->spatium(tick);
    2325         2312 :     const bool isTab = staff->isTabStaff(segment->tick());
    2326              : 
    2327         2312 :     Note* bottomUpNote = posInfo.upStemNotes.front();
    2328         2312 :     Note* topDownNote  = posInfo.downStemNotes.back();
    2329         2312 :     int separation = topDownNote->stringOrLine() - bottomUpNote->stringOrLine();
    2330              : 
    2331         2312 :     std::vector<Note*> overlapNotes;
    2332         2312 :     overlapNotes.reserve(8);
    2333              : 
    2334         2312 :     if (separation == 1) {
    2335              :         // second
    2336           34 :         if (posInfo.upDots && !posInfo.downDots) {
    2337            0 :             offsetInfo.upOffset = posInfo.maxDownWidth + 0.1 * sp;
    2338            0 :             offsetInfo.tracksToAdjust.insert(bottomUpNote->track());
    2339              :         } else {
    2340           34 :             offsetInfo.downOffset = posInfo.maxUpWidth;
    2341              :             // align stems if present
    2342           34 :             if (topDownNote->chord()->stem() && bottomUpNote->chord()->stem()) {
    2343           32 :                 const Stem* topDownStem = topDownNote->chord()->stem();
    2344           32 :                 offsetInfo.downOffset -= topDownStem->lineWidthMag();
    2345            2 :             } else if (topDownNote->chord()->durationType().headType() != NoteHeadType::HEAD_BREVIS
    2346            2 :                        && bottomUpNote->chord()->durationType().headType() != NoteHeadType::HEAD_BREVIS) {
    2347              :                 // stemless notes should be aligned as is they were stemmed
    2348              :                 // (except in case of brevis, cause the notehead has the side bars)
    2349            2 :                 offsetInfo.downOffset -= ctx.conf().styleAbsolute(Sid::stemWidth) * topDownNote->chord()->mag();
    2350              :             }
    2351           34 :             offsetInfo.tracksToAdjust.insert(topDownNote->track());
    2352              :         }
    2353         2278 :     } else if (separation < 1) {
    2354              :         // overlap (possibly unison)
    2355              : 
    2356              :         // build list of overlapping notes
    2357          821 :         for (size_t i = 0, n = posInfo.upStemNotes.size(); i < n; ++i) {
    2358          490 :             if (posInfo.upStemNotes[i]->stringOrLine() >= topDownNote->stringOrLine() - 1) {
    2359          421 :                 overlapNotes.push_back(posInfo.upStemNotes[i]);
    2360              :             } else {
    2361           69 :                 break;
    2362              :             }
    2363              :         }
    2364          809 :         for (size_t i = posInfo.downStemNotes.size(); i > 0; --i) {             // loop most probably needs to be in this reverse order
    2365          456 :             if (posInfo.downStemNotes[i - 1]->stringOrLine() <= bottomUpNote->stringOrLine() + 1) {
    2366          409 :                 overlapNotes.push_back(posInfo.downStemNotes[i - 1]);
    2367              :             } else {
    2368           47 :                 break;
    2369              :             }
    2370              :         }
    2371          400 :         std::sort(overlapNotes.begin(), overlapNotes.end(),
    2372          885 :                   [](Note* n1, const Note* n2) ->bool { return n1->stringOrLine() > n2->stringOrLine(); });
    2373              : 
    2374              :         // determine nature of overlap
    2375          400 :         bool shareHeads = true;                   // can all overlapping notes share heads?
    2376          400 :         bool matchPending = false;                // looking for a unison match
    2377          400 :         bool conflictUnison = false;              // unison found
    2378          400 :         bool conflictSecondUpHigher = false;                  // second found
    2379          400 :         bool conflictSecondDownHigher = false;                // second found
    2380          400 :         int lastLine = 1000;
    2381          400 :         track_idx_t lastTrack = muse::nidx;
    2382          400 :         Note* p = overlapNotes[0];
    2383         1230 :         for (size_t i = 0, count = overlapNotes.size(); i < count; ++i) {
    2384          830 :             Note* n = overlapNotes[i];
    2385              :             NoteHeadType nHeadType;
    2386              :             NoteHeadType pHeadType;
    2387          830 :             Chord* nchord = n->chord();
    2388          830 :             Chord* pchord = p->chord();
    2389          830 :             if (n->ldata()->mirror()) {
    2390            0 :                 if (separation < 0) {
    2391              :                     // don't try to share heads if there is any mirroring
    2392            0 :                     shareHeads = false;
    2393              :                     // don't worry about conflicts involving mirrored notes
    2394            0 :                     continue;
    2395              :                 }
    2396              :             }
    2397          830 :             track_idx_t track = n->track();
    2398          830 :             int line = n->stringOrLine();
    2399          830 :             int d = lastLine - line;
    2400          830 :             switch (d) {
    2401           71 :             case 0:
    2402              :                 // unison
    2403           71 :                 conflictUnison = true;
    2404           71 :                 matchPending = false;
    2405           71 :                 nHeadType = (n->headType() == NoteHeadType::HEAD_AUTO) ? n->chord()->durationType().headType() : n->headType();
    2406           71 :                 pHeadType = (p->headType() == NoteHeadType::HEAD_AUTO) ? p->chord()->durationType().headType() : p->headType();
    2407              :                 // the most important rules for sharing noteheads on unisons between voices are
    2408              :                 // that notes must be one same line with same tpc
    2409              :                 // noteheads must be unmirrored and of same group
    2410              :                 // and chords must be same size if notehead is anything other than HEAD_QUARTER
    2411          136 :                 if (n->headGroup() != p->headGroup() || n->tpc() != p->tpc() || n->ldata()->mirror()
    2412           58 :                     || p->ldata()->mirror()
    2413          136 :                     || (nchord->isSmall() != pchord->isSmall()
    2414            0 :                         && (nHeadType != NoteHeadType::HEAD_QUARTER || pHeadType != NoteHeadType::HEAD_QUARTER))) {
    2415           13 :                     shareHeads = false;
    2416              :                 } else {
    2417              :                     // noteheads are potentially shareable
    2418              :                     // it is more subjective at this point
    2419              :                     // current default is to require *either* of the following:
    2420              :                     //    1) both chords have same number of dots, both have stems, and both noteheads are same type and are full size (automatic match)
    2421              :                     // or 2) one or more of the noteheads is not of type AUTO, but is explicitly set to match the other (user-forced match)
    2422              :                     // or 3) exactly one of the noteheads is invisible (user-forced match)
    2423              :                     // thus user can force notes to be shared despite differing number of dots or either being stemless
    2424              :                     // by setting one of the notehead types to match the other or by making one notehead invisible
    2425              :                     // TODO: consider adding a style option, staff properties, or note property to control sharing
    2426          114 :                     if ((nchord->dots() != pchord->dots() || !nchord->stem() || !pchord->stem() || nHeadType != pHeadType
    2427           50 :                          || n->isSmall() || p->isSmall())
    2428            8 :                         && ((n->headType() == NoteHeadType::HEAD_AUTO && p->headType() == NoteHeadType::HEAD_AUTO)
    2429            0 :                             || nHeadType != pHeadType)
    2430          116 :                         && (n->visible() == p->visible())) {
    2431            8 :                         shareHeads = false;
    2432              :                     }
    2433              :                 }
    2434              : 
    2435           71 :                 break;
    2436           51 :             case 1:
    2437              :                 // second
    2438              :                 // trust that this won't be a problem for single unison
    2439           51 :                 if (separation < 0) {
    2440           51 :                     if (n->chord()->up()) {
    2441            1 :                         conflictSecondUpHigher = true;
    2442              :                     } else {
    2443           50 :                         conflictSecondDownHigher = true;
    2444              :                     }
    2445           51 :                     shareHeads = false;
    2446              :                 }
    2447           51 :                 break;
    2448          708 :             default:
    2449              :                 // no conflict
    2450          708 :                 if (matchPending) {
    2451          308 :                     shareHeads = false;
    2452              :                 }
    2453          708 :                 matchPending = true;
    2454              :             }
    2455          830 :             if (!shareHeads) {
    2456          389 :                 offsetInfo.tracksToAdjust.insert({ track, lastTrack });
    2457              :             }
    2458          830 :             p = n;
    2459          830 :             lastLine = line;
    2460          830 :             lastTrack = track;
    2461              :         }
    2462          400 :         if (matchPending) {
    2463          329 :             shareHeads = false;
    2464              :         }
    2465              : 
    2466          400 :         bool conflict = conflictUnison || conflictSecondDownHigher || conflictSecondUpHigher;
    2467          400 :         bool ledgerOverlapAbove = false;
    2468          400 :         bool ledgerOverlapBelow = false;
    2469              : 
    2470          400 :         double ledgerGap = 0.15 * sp;
    2471          400 :         double ledgerLen = ctx.conf().styleS(Sid::ledgerLineLength).val() * sp;
    2472          400 :         int firstLedgerBelow = staff->lines(bottomUpNote->tick()) * 2;
    2473          400 :         int topDownStemLen = 0;
    2474          400 :         if (!conflictUnison && topDownNote->chord()->stem()) {
    2475          316 :             topDownStemLen = std::round(topDownNote->chord()->stem()->ldata()->bbox().height() / sp * 2);
    2476          336 :             if (bottomUpNote->stringOrLine() > firstLedgerBelow - 1 && topDownNote->stringOrLine() < bottomUpNote->stringOrLine()
    2477          336 :                 && topDownNote->stringOrLine() + topDownStemLen >= firstLedgerBelow) {
    2478            5 :                 ledgerOverlapBelow = true;
    2479              :             }
    2480              :         }
    2481              : 
    2482          400 :         int firstLedgerAbove = -2;
    2483          400 :         int bottomUpStemLen = 0;
    2484          400 :         if (!conflictUnison && bottomUpNote->chord()->stem()) {
    2485          311 :             bottomUpStemLen = std::round(bottomUpNote->chord()->stem()->ldata()->bbox().height() / sp * 2);
    2486          328 :             if (topDownNote->stringOrLine() < -1 && topDownNote->stringOrLine() < bottomUpNote->stringOrLine()
    2487          328 :                 && bottomUpNote->stringOrLine() - bottomUpStemLen <= firstLedgerAbove) {
    2488           17 :                 ledgerOverlapAbove = true;
    2489              :             }
    2490              :         }
    2491              : 
    2492              :         // calculate offsets
    2493          400 :         if (shareHeads) {
    2494           82 :             for (int i = static_cast<int>(overlapNotes.size()) - 1; i >= 1; i -= 2) {
    2495           41 :                 Note* previousNote = overlapNotes[i - 1];
    2496           41 :                 Note* n = overlapNotes[i];
    2497           41 :                 const bool skipNote = previousNote->chord()->isNudged() || n->chord()->isNudged();
    2498           41 :                 if (skipNote) {
    2499            0 :                     continue;
    2500              :                 }
    2501           41 :                 const bool prevChordSmall = previousNote->chord()->isSmall();
    2502           41 :                 const bool nChordSmall = n->chord()->isSmall();
    2503           41 :                 if (previousNote->chord()->dots() == n->chord()->dots()) {
    2504              :                     // hide one set of dots
    2505              :                     // Hide the small augmentation dot if present
    2506           41 :                     bool onLine = !(previousNote->line() & 1);
    2507           41 :                     if (prevChordSmall) {
    2508            0 :                         previousNote->setDotsHidden(true);
    2509           41 :                     } else if (nChordSmall) {
    2510            0 :                         n->setDotsHidden(true);
    2511           41 :                     } else if (onLine) {
    2512              :                         // hide dots for lower voice
    2513           16 :                         if (previousNote->voice() & 1) {
    2514            9 :                             previousNote->setDotsHidden(true);
    2515              :                         } else {
    2516            7 :                             n->setDotsHidden(true);
    2517              :                         }
    2518              :                     } else {
    2519              :                         // hide dots for upper voice
    2520           25 :                         if (!(previousNote->voice() & 1)) {
    2521           11 :                             previousNote->setDotsHidden(true);
    2522              :                         } else {
    2523           14 :                             n->setDotsHidden(true);
    2524              :                         }
    2525              :                     }
    2526              :                 }
    2527              :                 // If either chord is small, adjust offset
    2528           41 :                 Chord* smallChord = prevChordSmall ? previousNote->chord() : nullptr;
    2529           41 :                 smallChord = nChordSmall ? n->chord() : smallChord;
    2530           41 :                 if (smallChord && !(prevChordSmall && nChordSmall)) {
    2531            0 :                     if (smallChord->up()) {
    2532            0 :                         offsetInfo.centerUp *= 2;
    2533              :                     } else {
    2534            0 :                         offsetInfo.centerDown = 0;
    2535              :                     }
    2536              :                 }
    2537              :                 // formerly we hid noteheads in an effort to fix playback
    2538              :                 // but this doesn't work for cases where noteheads cannot be shared
    2539              :                 // so better to solve the problem elsewhere
    2540              :             }
    2541          359 :         } else if (conflict && (posInfo.upDots && !posInfo.downDots)) {
    2542            2 :             offsetInfo.upOffset = posInfo.maxDownWidth + 0.1 * sp;
    2543          357 :         } else if (conflictUnison && separation == 0 && (!posInfo.downGrace || posInfo.upGrace)) {
    2544           19 :             offsetInfo.downOffset = posInfo.maxUpWidth + 0.15 * sp;
    2545          338 :         } else if (conflictUnison) {
    2546            9 :             offsetInfo.upOffset = posInfo.maxDownWidth + 0.15 * sp;
    2547          329 :         } else if (conflictSecondUpHigher) {
    2548            1 :             offsetInfo.upOffset = posInfo.maxDownWidth + 0.15 * sp;
    2549          328 :         } else if ((posInfo.downHooks && !posInfo.upHooks) && !(posInfo.upDots && !posInfo.downDots)) {
    2550              :             // Shift by ledger line length if ledger line conflict or just 0.3sp if no ledger lines
    2551            2 :             double adjSpace = (ledgerOverlapAbove || ledgerOverlapBelow) ? ledgerGap + ledgerLen : 0.3 * sp;
    2552            2 :             offsetInfo.downOffset = posInfo.maxUpWidth + adjSpace;
    2553          328 :         } else if (conflictSecondDownHigher) {
    2554           49 :             if (posInfo.downDots && !posInfo.upDots) {
    2555            0 :                 double adjSpace = (ledgerOverlapAbove || ledgerOverlapBelow) ? ledgerGap + ledgerLen : 0.2 * sp;
    2556            0 :                 offsetInfo.downOffset = posInfo.maxUpWidth + adjSpace;
    2557            0 :             } else {
    2558              :                 // Prevent ledger line & notehead collision
    2559              :                 double adjSpace
    2560           49 :                     = (topDownNote->stringOrLine() <= firstLedgerAbove
    2561           49 :                        || bottomUpNote->stringOrLine() >= firstLedgerBelow) ? ledgerLen - ledgerGap - 0.2 * sp : -0.2 * sp;
    2562           49 :                 offsetInfo.upOffset = posInfo.maxDownWidth + adjSpace;
    2563           49 :                 if (posInfo.downHooks) {
    2564            0 :                     bool needsHookSpace = (ledgerOverlapBelow || ledgerOverlapAbove);
    2565            0 :                     Hook* hook = topDownNote->chord()->hook();
    2566            0 :                     double hookSpace = hook ? hook->width() : 0.0;
    2567            0 :                     offsetInfo.upOffset = needsHookSpace ? hookSpace + ledgerLen + ledgerGap : offsetInfo.upOffset + 0.3 * sp;
    2568              :                 }
    2569              :             }
    2570              :         } else {
    2571              :             // no direct conflict, so parts can overlap (downstem on left)
    2572              :             // just be sure that stems clear opposing noteheads and ledger lines
    2573              :             // Stems are in the middle of fret marks on TAB staves
    2574          277 :             double clearLeft = isTab ? StemLayout::stemPosX(bottomUpNote->chord()) : 0.0;
    2575          277 :             double clearRight = isTab ? StemLayout::stemPosX(bottomUpNote->chord()) : 0.0;
    2576          277 :             double overlapPadding = (isTab ? 0 : 0.3) * sp;
    2577          277 :             if (const Stem* topDownStem = topDownNote->chord()->stem()) {
    2578          264 :                 if (ledgerOverlapBelow) {
    2579              :                     // Create space between stem and ledger line below staff
    2580            3 :                     clearLeft += ledgerLen + ledgerGap + topDownStem->lineWidthMag();
    2581              :                 } else {
    2582          261 :                     clearLeft += topDownStem->lineWidthMag() + overlapPadding;
    2583              :                 }
    2584              :             }
    2585          277 :             if (const Stem* bottomUpStem = bottomUpNote->chord()->stem()) {
    2586          259 :                 if (ledgerOverlapAbove) {
    2587              :                     // Create space between stem and ledger line above staff
    2588           34 :                     clearRight += posInfo.maxDownWidth + ledgerLen + ledgerGap - posInfo.maxUpWidth
    2589           17 :                                   + bottomUpStem->lineWidthMag();
    2590              :                 } else {
    2591          242 :                     clearRight += bottomUpStem->lineWidthMag()
    2592          242 :                                   + std::max(posInfo.maxDownWidth - posInfo.maxUpWidth, 0.0) + overlapPadding;
    2593              :                 }
    2594              :             } else {
    2595           18 :                 posInfo.downDots = 0;                 // no need to adjust for dots in this case
    2596              :             }
    2597          277 :             offsetInfo.upOffset = std::max(clearLeft, clearRight);
    2598              :             // Check if there's enough space to tuck under a flag
    2599          277 :             Note* topUpNote = posInfo.upStemNotes.back();
    2600              :             // Move notes out of the way of straight flags
    2601          277 :             int pad = ctx.conf().styleB(Sid::useStraightNoteFlags) ? 2 : 1;
    2602          277 :             bool overlapsFlag = topDownNote->stringOrLine() + topDownStemLen + pad > topUpNote->stringOrLine();
    2603          277 :             if (posInfo.downHooks && (ledgerOverlapBelow || overlapsFlag)) {
    2604              :                 // we will need more space to avoid collision with hook
    2605              :                 // but we won't need as much dot adjustment
    2606            1 :                 Hook* hook = topDownNote->chord()->hook();
    2607            1 :                 double hookWidth = hook ? hook->width() : 0.0;
    2608            1 :                 if (ledgerOverlapBelow) {
    2609            0 :                     offsetInfo.upOffset = hookWidth + ledgerLen + ledgerGap;
    2610              :                 }
    2611            1 :                 if (isTab) {
    2612            0 :                     offsetInfo.upOffset = hookWidth + posInfo.maxDownWidth;
    2613              :                 }
    2614            1 :                 offsetInfo.upOffset = std::max(offsetInfo.upOffset, posInfo.maxDownWidth + 0.1 * sp);
    2615            1 :                 offsetInfo.dotAdjustThreshold = posInfo.maxUpWidth - 0.3 * sp;
    2616              :             }
    2617              :             // if downstem chord is small, don't center
    2618              :             // and we might not need as much dot adjustment either
    2619          277 :             if (offsetInfo.centerDown > 0.0) {
    2620            0 :                 offsetInfo.centerDown = 0.0;
    2621            0 :                 offsetInfo.centerAdjustUp = 0.0;
    2622            0 :                 offsetInfo.dotAdjustThreshold = (offsetInfo.upOffset - posInfo.maxDownWidth) + posInfo.maxUpWidth - 0.3 * sp;
    2623              :             }
    2624              :         }
    2625              :     }
    2626              : 
    2627              :     // adjust for dots
    2628         2312 :     if ((posInfo.upDots && !posInfo.downDots) || (posInfo.downDots && !posInfo.upDots)) {
    2629              :         // only one sets of dots
    2630              :         // place between chords
    2631              :         int dots;
    2632              :         double mag;
    2633           97 :         if (posInfo.upDots) {
    2634           61 :             dots = posInfo.upDots;
    2635           61 :             mag = posInfo.maxUpMag;
    2636              :         } else {
    2637           36 :             dots = posInfo.downDots;
    2638           36 :             mag = posInfo.maxDownMag;
    2639              :         }
    2640           97 :         double dotWidth = segment->symWidth(SymId::augmentationDot);
    2641              :         // first dot
    2642           97 :         offsetInfo.dotAdjust = ctx.conf().styleAbsolute(Sid::dotNoteDistance) + dotWidth;
    2643              :         // additional dots
    2644           97 :         if (dots > 1) {
    2645            0 :             offsetInfo.dotAdjust += ctx.conf().styleAbsolute(Sid::dotDotDistance) * (dots - 1);
    2646              :         }
    2647           97 :         offsetInfo.dotAdjust *= mag;
    2648              :         // only by amount over threshold
    2649           97 :         offsetInfo.dotAdjust = std::max(offsetInfo.dotAdjust - offsetInfo.dotAdjustThreshold, 0.0);
    2650              :     }
    2651         2312 :     if (separation == 1) {
    2652           34 :         offsetInfo.dotAdjust += 0.1 * sp;
    2653              :     }
    2654         2312 : }
    2655              : 
    2656              : //---------------------------------------------------------
    2657              : //   layoutChords1
    2658              : //    - layout upstem and downstem chords
    2659              : //    - offset as necessary to avoid conflict
    2660              : //---------------------------------------------------------
    2661              : 
    2662       101325 : void ChordLayout::layoutChords1(LayoutContext& ctx, Segment* segment, staff_idx_t staffIdx)
    2663              : {
    2664       101340 :     TRACEFUNC;
    2665              :     LAYOUT_CALL() << LAYOUT_ITEM_INFO(segment);
    2666              : 
    2667       101325 :     const Staff* staff = ctx.dom().staff(staffIdx);
    2668       101325 :     const bool isTab = staff->isTabStaff(segment->tick());
    2669       101325 :     const bool isJianpu = staff->isJianpuStaff(segment->tick());
    2670       101325 :     const track_idx_t startTrack = staffIdx * VOICES;
    2671       101325 :     const track_idx_t endTrack   = startTrack + VOICES;
    2672       101325 :     const Fraction tick = segment->tick();
    2673       101325 :     const StaffType* staffType = staff->staffType(segment->tick());
    2674              : 
    2675              :     // we need to check all the notes in all the staves of the part so that we don't get weird collisions
    2676              :     // between accidentals etc with moved notes
    2677       101325 :     const Part* part = staff->part();
    2678       101325 :     const TrackRange partTrackRangeOrDefault = part ? part->trackRange() : TrackRange { startTrack, endTrack };
    2679       101325 :     const track_idx_t partStartTrack = partTrackRangeOrDefault.startTrack;
    2680       101325 :     const track_idx_t partEndTrack = partTrackRangeOrDefault.endTrack;
    2681              : 
    2682       101325 :     if (isTab || isJianpu) {
    2683              :         // Jianpu notes show their accidentals as part of the digit label instead
    2684              :         // of the standard Accidental glyph, so skip drawing the latter.
    2685         3658 :         skipAccidentals(segment, startTrack, endTrack);
    2686              :     }
    2687              : 
    2688       101325 :     const bool isSimpleTab = !staff->staffType() || (!staff->staffType()->stemThrough() && !staff->staffType()->isCommonTabStaff());
    2689       101325 :     if (staff && staff->isTabStaff(tick) && isSimpleTab) {
    2690              :         // Positions of notes should be reset in case we are changing from common or full tab with offsets to simple which should have none
    2691        10738 :         for (track_idx_t track = partStartTrack; track < partEndTrack; ++track) {
    2692         9516 :             EngravingItem* e = segment->element(track);
    2693         9516 :             if (e && e->isChord() && toChord(e)->vStaffIdx() == staffIdx) {
    2694          563 :                 Chord* chord = toChord(e);
    2695          563 :                 Chord::LayoutData* chordLdata = chord->mutldata();
    2696          563 :                 chordLdata->setPosX(0.0);
    2697              :             }
    2698              :         }
    2699              : 
    2700         1222 :         layoutSegmentElements(segment, startTrack, endTrack, staffIdx, ctx);
    2701         1222 :         return;
    2702              :     }
    2703              : 
    2704       100103 :     ChordPosInfo posInfo = calculateChordPosInfo(segment, staffIdx, partStartTrack, partEndTrack, ctx);
    2705              : 
    2706       100103 :     if (posInfo.upVoices + posInfo.downVoices && (staffType->stemThrough() || staffType->isCommonTabStaff())) {
    2707              :         // TODO: use track as secondary sort criteria?
    2708              :         // otherwise there might be issues with unisons between voices
    2709              :         // in some corner cases
    2710              : 
    2711        51686 :         calculateMaxNoteWidths(posInfo, tick, staff, ctx);
    2712              : 
    2713        51686 :         OffsetInfo offsetInfo = centreChords(segment, posInfo, staffIdx, tick, ctx);
    2714              : 
    2715        51686 :         calculateChordOffsets(segment, staffIdx, tick, offsetInfo, posInfo, ctx);
    2716              : 
    2717        51686 :         applyChordOffsets(segment, staffIdx, partStartTrack, partEndTrack, offsetInfo, posInfo, ctx);
    2718        51686 :     }
    2719              : 
    2720       100103 :     if (!isTab) {
    2721        99699 :         layoutLedgerLines(posInfo.chords, ctx);
    2722        99699 :         AccidentalsLayout::layoutAccidentals(posInfo.chords, ctx);
    2723       153701 :         for (Chord* chord : posInfo.chords) {
    2724        54899 :             for (Chord* grace : chord->graceNotes()) {
    2725         1794 :                 AccidentalsLayout::layoutAccidentals({ grace }, ctx);
    2726          897 :                 ChordLayout::layoutJianpuOctaveDots(grace, ctx);
    2727              :             }
    2728        54002 :             ChordLayout::layoutJianpuDurationLines(chord, ctx);
    2729        54002 :             ChordLayout::layoutJianpuOctaveDots(chord, ctx);
    2730              :         }
    2731              :     }
    2732              : 
    2733       100103 :     layoutSegmentElements(segment, partStartTrack, partEndTrack, staffIdx, ctx);
    2734              : 
    2735       154332 :     for (Chord* chord : posInfo.chords) {
    2736        54229 :         Ornament* ornament = chord->findOrnament();
    2737        54229 :         if (ornament && ornament->showCueNote()) {
    2738           16 :             TLayout::layoutOrnamentCueNote(ornament, ctx);
    2739              :         }
    2740              :     }
    2741       101325 : }
    2742              : 
    2743              : //---------------------------------------------------------
    2744              : //   layoutChords2
    2745              : //    - determine which notes need mirroring
    2746              : //    - this is called once for each stem direction
    2747              : //      eg, once for voices 1&3, once for 2&4
    2748              : //      with all notes combined and sorted to resemble one chord
    2749              : //    - return maximum non-mirrored notehead width
    2750              : //---------------------------------------------------------
    2751              : 
    2752        54897 : double ChordLayout::layoutChords2(std::vector<Note*>& notes, bool up, LayoutContext& ctx)
    2753              : {
    2754              :     int startIdx, endIdx, incIdx;
    2755        54897 :     double maxWidth = 0.0;
    2756              : 
    2757              :     // loop in correct direction so that first encountered notehead wins conflict
    2758        54897 :     if (up) {
    2759              :         // loop bottom up
    2760        29715 :         startIdx = 0;
    2761        29715 :         endIdx = int(notes.size());
    2762        29715 :         incIdx = 1;
    2763              :     } else {
    2764              :         // loop top down
    2765        25182 :         startIdx = int(notes.size()) - 1;
    2766        25182 :         endIdx = -1;
    2767        25182 :         incIdx = -1;
    2768              :     }
    2769              : 
    2770        54897 :     int prevLine = 1000;            // line of previous notehead
    2771              :                                     // hack: start high so first note won't show as conflict
    2772        54897 :     bool prevVisible = false;       // was last note visible?
    2773        54897 :     bool mirror = false;            // should current notehead be mirrored?
    2774              :                                     // value is retained and may be used on next iteration
    2775              :                                     // to track mirror status of previous note
    2776        54897 :     bool isLeft   = notes[startIdx]->chord()->up();               // is notehead on left?
    2777        54897 :     Chord* prevChord = notes[startIdx]->chord();
    2778        54897 :     staff_idx_t prevStaffIdx = prevChord->vStaffIdx();        // staff of last note (including staffMove)
    2779        54897 :     track_idx_t prevTrackIdx = prevChord->track();
    2780              : 
    2781       117397 :     for (int idx = startIdx; idx != endIdx; idx += incIdx) {
    2782        62500 :         Note* note    = notes[idx];                         // current note
    2783        62500 :         const int line      = note->stringOrLine();                       // line of current note
    2784        62500 :         Chord* chord  = note->chord();
    2785              : 
    2786        62500 :         const staff_idx_t staffIdx  = chord->vStaffIdx();                 // staff of current note
    2787        62500 :         const track_idx_t trackIdx = chord->track();
    2788        62500 :         const Staff* st = note->staff();
    2789        62500 :         const StaffType* tab = st->staffTypeForElement(note);
    2790        62500 :         const bool isTab = note->staff() && note->staff()->isTabStaff(note->chord()->tick());
    2791              : 
    2792        62500 :         if (isTab) {
    2793              :             // TAB notes need to be laid out to set the fret string so we can calulate their width
    2794              :             // Standard staves can get this information from the notehead symbol, so no need to lay out
    2795          329 :             TLayout::layoutNote(note, note->mutldata());
    2796              :         }
    2797              : 
    2798              :         // there is a conflict
    2799              :         // if this is same or adjacent line as previous note (and chords are on same staff!)
    2800              :         // but no need to do anything about it if either note is invisible
    2801        62500 :         bool sameTrack = trackIdx == prevTrackIdx;
    2802              : 
    2803          674 :         bool conflict = (std::abs(prevLine - line) < 2) && (prevStaffIdx == staffIdx) && note->visible() && prevVisible
    2804        63174 :                         && (sameTrack || Chord::combineVoice(chord, prevChord));
    2805              : 
    2806              :         // this note is on opposite side of stem as previous note
    2807              :         // if there is a conflict
    2808              :         // or if this the first note *after* a conflict
    2809        62500 :         if (conflict || (chord->up() != isLeft)) {
    2810          912 :             isLeft = !isLeft;
    2811              :         }
    2812              : 
    2813              :         // determine if we would need to mirror current note
    2814              :         // to get it to the correct side
    2815              :         // this would be needed to get a note to left or downstem or right of upstem
    2816              :         // whether or not we actually do this is determined later (based on user mirror property)
    2817        62500 :         bool nmirror = (chord->up() != isLeft);
    2818              : 
    2819              :         // by default, notes and dots are not hidden
    2820              :         // this may be changed later to allow unisons to share noteheads
    2821        62500 :         note->setHidden(false);
    2822        62500 :         note->setDotsHidden(false);
    2823              : 
    2824              :         // be sure chord position is initialized
    2825              :         // chord may be moved to the right later
    2826              :         // if there are conflicts between voices
    2827        62500 :         if (!chord->isGrace()) {
    2828        61489 :             chord->mutldata()->setPosX(0.0);
    2829              :         }
    2830              : 
    2831              :         // let user mirror property override the default we calculated
    2832        62500 :         if (note->userMirror() == DirectionH::AUTO) {
    2833        62500 :             mirror = nmirror;
    2834              :         } else {
    2835            0 :             mirror = note->chord()->up();
    2836            0 :             if (note->userMirror() == DirectionH::LEFT) {
    2837            0 :                 mirror = !mirror;
    2838              :             }
    2839              :         }
    2840        62500 :         note->mutldata()->mirror.set_value(mirror);
    2841        62500 :         if (chord->stem()) {
    2842        53845 :             chord->stem()->mutldata()->setPosX(StemLayout::stemPosX(chord));
    2843        53845 :             TLayout::layoutStem(chord->stem(), chord->stem()->mutldata(), ctx.conf()); // needed because mirroring can cause stem position to change
    2844              :         }
    2845              : 
    2846              :         // accumulate return value
    2847        62500 :         if (!mirror) {
    2848        61950 :             const double fretBackground = ctx.conf().styleS(Sid::tabFretPadding).val() * note->spatium();
    2849        61950 :             const double noteWidth = isTab ? note->tabHeadWidth(tab) + 2 * fretBackground : note->bboxRightPos();
    2850        61950 :             maxWidth = std::max(maxWidth, noteWidth);
    2851              :         }
    2852              : 
    2853              :         // prepare for next iteration
    2854        62500 :         prevChord = chord;
    2855        62500 :         prevVisible = note->visible();
    2856        62500 :         prevStaffIdx = staffIdx;
    2857        62500 :         prevTrackIdx = trackIdx;
    2858        62500 :         prevLine = line;
    2859              :     }
    2860              : 
    2861        54897 :     return maxWidth;
    2862              : }
    2863              : 
    2864        56070 : bool ChordLayout::chordHasDotsAllInvisible(Chord* chord)
    2865              : {
    2866        56070 :     if (!chord->dots()) {
    2867        54218 :         return false;
    2868              :     }
    2869              : 
    2870         1856 :     for (Note* note : chord->notes()) {
    2871         1856 :         for (NoteDot* dot : note->dots()) {
    2872         1852 :             if (dot->visible()) {
    2873         1848 :                 return false;
    2874              :             }
    2875              :         }
    2876              :     }
    2877              : 
    2878            4 :     return true;
    2879              : }
    2880              : 
    2881              : //---------------------------------------------------------
    2882              : //   centerX
    2883              : //    return x position for attributes
    2884              : //---------------------------------------------------------
    2885              : 
    2886         7899 : double ChordLayout::centerX(const Chord* chord)
    2887              : {
    2888              :     // TAB 'notes' are always centered on the stem
    2889         7899 :     const Staff* st = chord->staff();
    2890         7899 :     const StaffType* stt = st->staffTypeForElement(chord);
    2891         7899 :     if (stt->isTabStaff()) {
    2892           83 :         return rendering::score::StemLayout::tabStemPosX() * chord->spatium();
    2893              :     }
    2894              : 
    2895         7816 :     const Note* note = chord->up() ? chord->downNote() : chord->upNote();
    2896         7816 :     double x = note->pos().x() + note->noteheadCenterX();
    2897         7816 :     return x;
    2898              : }
    2899              : 
    2900              : //---------------------------------------------------------
    2901              : //   placeDots
    2902              : //---------------------------------------------------------
    2903              : 
    2904        52601 : void ChordLayout::placeDots(const std::vector<Chord*>& chords, const std::vector<Note*>& notes, LayoutContext& ctx)
    2905              : {
    2906        52601 :     Chord* chord = nullptr;
    2907       106802 :     for (Chord* c : chords) {
    2908        55090 :         if (c->dots() > 0) {
    2909          889 :             chord = c;
    2910          889 :             break;
    2911              :         } else {
    2912       115669 :             for (Note* note : c->notes()) {
    2913        61468 :                 ChordLayout::setDotRelativeLine(note, 0, ctx); // this manages the deletion of dots
    2914              :             }
    2915              :         }
    2916              :     }
    2917              : 
    2918        52601 :     Staff* staff = chord ? chord->staff() : nullptr;
    2919        52601 :     if (!staff || (staff->isTabStaff(chord->tick()) && !staff->staffType(chord->tick())->stemThrough())) {
    2920        51712 :         return;
    2921              :     }
    2922          889 :     std::vector<Note*> topDownNotes;
    2923          889 :     std::vector<Note*> bottomUpNotes;
    2924          889 :     std::vector<int> anchoredDots;
    2925              :     // construct combined chords using the notes from overlapping chords
    2926          889 :     getNoteListForDots(chord, topDownNotes, bottomUpNotes, anchoredDots);
    2927              : 
    2928         2042 :     for (Note* note : notes) {
    2929         1153 :         bool onLine = !(note->line() & 1) && !staff->isJianpuStaff(chord->tick());
    2930         1153 :         if (onLine) {
    2931          649 :             std::unordered_map<int, Note*> alreadyAdded;
    2932          649 :             bool finished = false;
    2933          666 :             for (Note* otherNote : bottomUpNotes) {
    2934              :                 // Make sure invisible dots have no effect on visible dots, but are still layed out sensibly
    2935           96 :                 if (otherNote->visible() != note->visible()) {
    2936            0 :                     continue;
    2937              :                 }
    2938           96 :                 int dotMove = otherNote->dotPosition() == DirectionV::UP ? -1 : 1;
    2939           96 :                 int otherDotLoc = otherNote->line() + dotMove;
    2940           96 :                 bool added = alreadyAdded.count(otherDotLoc);
    2941           96 :                 if (!added && muse::contains(anchoredDots, otherDotLoc)) {
    2942           15 :                     dotMove = -dotMove; // if the desired space is taken, adjust opposite
    2943           81 :                 } else if (added && alreadyAdded[otherDotLoc] != otherNote) {
    2944            0 :                     dotMove = -dotMove;
    2945              :                 }
    2946              :                 // set y for this note
    2947           96 :                 if (note == otherNote) {
    2948           79 :                     ChordLayout::setDotRelativeLine(note, dotMove, ctx);
    2949           79 :                     finished = true;
    2950           79 :                     anchoredDots.push_back(note->line() + dotMove);
    2951           79 :                     alreadyAdded[otherNote->line() + dotMove] = otherNote;
    2952           79 :                     break;
    2953              :                 }
    2954              :             }
    2955          649 :             if (!finished) {
    2956          570 :                 alreadyAdded.clear();
    2957          610 :                 for (Note* otherNote : topDownNotes) {
    2958          610 :                     if (otherNote->visible() != note->visible()) {
    2959            0 :                         continue;
    2960              :                     }
    2961          610 :                     int dotMove = otherNote->dotPosition() == DirectionV::DOWN ? 1 : -1;
    2962          610 :                     int otherDotLoc = otherNote->line() + dotMove;
    2963          610 :                     bool added = alreadyAdded.count(otherDotLoc);
    2964          610 :                     if (!added && muse::contains(anchoredDots, otherDotLoc)) {
    2965            0 :                         dotMove = -dotMove;
    2966          610 :                     } else if (added && alreadyAdded[otherDotLoc] != otherNote) {
    2967            0 :                         dotMove = -dotMove;
    2968              :                     }
    2969              :                     // set y for this note
    2970          610 :                     if (note == otherNote) {
    2971          570 :                         ChordLayout::setDotRelativeLine(note, dotMove, ctx);
    2972          570 :                         finished = true;
    2973          570 :                         anchoredDots.push_back(note->line() + dotMove);
    2974          570 :                         break;
    2975              :                     }
    2976           40 :                     if (!added) {
    2977           40 :                         alreadyAdded[otherNote->line() + dotMove] = otherNote;
    2978              :                     }
    2979              :                 }
    2980              :             }
    2981          649 :             IF_ASSERT_FAILED(finished) {
    2982              :                 // this should never happen
    2983              :                 // the note is on a line and topDownNotes and bottomUpNotes are all of the lined notes
    2984            0 :                 ChordLayout::setDotRelativeLine(note, 0, ctx);
    2985              :             }
    2986          649 :         } else {
    2987              :             // on a space; usually this means the dot is on this same line, but there is an exception
    2988              :             // for a unison within the same chord.
    2989          620 :             for (Note* otherNote : note->chord()->notes()) {
    2990          620 :                 if (note == otherNote) {
    2991          504 :                     ChordLayout::setDotRelativeLine(note, 0, ctx); // same space as notehead
    2992          504 :                     break;
    2993              :                 }
    2994          116 :                 if (note->line() == otherNote->line()) {
    2995            0 :                     bool adjustDown = (note->chord()->voice() & 1) && !note->chord()->up();
    2996            0 :                     ChordLayout::setDotRelativeLine(note, adjustDown ? 2 : -2, ctx);
    2997            0 :                     break;
    2998              :                 }
    2999              :             }
    3000              :         }
    3001              :     }
    3002          889 : }
    3003              : 
    3004        63652 : void ChordLayout::setDotRelativeLine(Note* note, int dotMove, LayoutContext& ctx)
    3005              : {
    3006        63652 :     double y = dotMove / 2.0;
    3007        63652 :     if (note->staff()->isTabStaff(note->chord()->tick())) {
    3008              :         // with TAB's, dotPosX is not set:
    3009              :         // get dot X from width of fret text and use TAB default spacing
    3010         1360 :         const Staff* st = note->staff();
    3011         1360 :         const StaffType* tab = st->staffTypeForElement(note);
    3012         1360 :         if (tab->stemThrough()) {
    3013              :             // if fret mark on lines, use standard processing
    3014           46 :             if (!tab->onLines()) {
    3015              :                 // if fret marks above lines, raise the dots by half line distance
    3016            0 :                 y = -0.5;
    3017           46 :             } else if (dotMove == 0) {
    3018           45 :                 bool oddVoice = note->voice() & 1;
    3019           45 :                 y = oddVoice ? 0.5 : -0.5;
    3020              :             } else {
    3021            1 :                 y = 0.5;
    3022              :             }
    3023              :         }
    3024              :         // if stems beside staff, do nothing
    3025              :         else {
    3026         1314 :             return;
    3027              :         }
    3028              :     }
    3029        62338 :     y *= note->spatium() * note->staff()->lineDistance(note->tick());
    3030              : 
    3031              :     // apply to dots
    3032              : 
    3033        62338 :     int cdots = static_cast<int>(note->chord()->dots());
    3034        62338 :     int ndots = static_cast<int>(note->dots().size());
    3035              : 
    3036              :     // remove dots for jianpu which already convert to lengthen duration lines
    3037        62338 :     int ddots = 0;
    3038        62338 :     if (note->staff()->isJianpuStaff(note->chord()->tick())) {
    3039         1764 :         if (note->chord()->upNote() == note) {
    3040         1758 :             TDuration durationType = note->chord()->durationType();
    3041         1758 :             if (durationType == DurationType::V_LONG) {
    3042            0 :                 ddots = 4;
    3043         1758 :             } else if (durationType == DurationType::V_BREVE) {
    3044            1 :                 ddots = 3;
    3045         1757 :             } else if (durationType == DurationType::V_WHOLE) {
    3046            1 :                 ddots = 2;
    3047         1756 :             } else if (durationType == DurationType::V_HALF) {
    3048            1 :                 ddots = 1;
    3049              :             }
    3050              :         } else {
    3051            6 :             cdots = 0; // only show dots for up note in jianpu
    3052              :         }
    3053              :     }
    3054        62338 :     cdots = std::max(0, cdots - ddots);
    3055              : 
    3056        62338 :     int n = cdots - ndots;
    3057        63010 :     for (int i = 0; i < n; ++i) {
    3058          672 :         NoteDot* dot = Factory::createNoteDot(note);
    3059          672 :         dot->setTrack(note->track());      // needed to know the staff it belongs to (and detect tablature)
    3060          672 :         dot->setVisible(note->visible());
    3061          672 :         ctx.mutDom().undoAddElement(dot);
    3062              :     }
    3063        62338 :     if (n < 0) {
    3064            2 :         for (int i = 0; i < -n; ++i) {
    3065            1 :             ctx.mutDom().undoRemoveElement(note->dots().back());
    3066              :         }
    3067              :     }
    3068              : 
    3069        63417 :     for (NoteDot* dot : note->dots()) {
    3070         1079 :         TLayout::layoutNoteDot(dot, dot->mutldata());
    3071         1079 :         dot->mutldata()->setPosY(y);
    3072              :     }
    3073              : }
    3074              : 
    3075        52601 : void ChordLayout::setDotX(const std::vector<Chord*>& chords, const std::array<double, 3 * VOICES>& dotPos, const Staff* staff,
    3076              :                           const double upDotPosX, const double downDotPosX)
    3077              : {
    3078              :     // Look for conflicts in up-stem and down-stemmed chords. If conflicts, all dots are aligned
    3079              :     // to the same vertical line. If no conflicts, each chords aligns the dots individually.
    3080              :     // Also check for conflicts between similarly stemmed voices where at least one voice is laid out independently
    3081        52601 :     std::set<track_idx_t> combineChordConflicts;
    3082        52601 :     std::set<track_idx_t> separateChordConflicts;
    3083       107745 :     for (Chord* chord1 : chords) {
    3084       115774 :         for (Chord* chord2 : chords) {
    3085        60630 :             if ((chord1 != chord2)
    3086         5486 :                 && ((chord1->up() && !chord2->up() && chord2->upNote()->line() - chord1->downNote()->line() < 2)
    3087         5034 :                     || (!chord1->up() && chord2->up() && chord1->upNote()->line() - chord2->downNote()->line() < 2))
    3088        66116 :                 && Chord::combineVoice(chord1, chord2)) {
    3089          904 :                 combineChordConflicts.insert({ chord1->track(), chord2->track() });
    3090        59726 :             } else if ((chord1 != chord2)
    3091         4582 :                        && ((chord1->up() && chord2->up() && chord1->upNote()->line() - chord2->downNote()->line() < 2)
    3092         4416 :                            || (!chord1->up() && !chord2->up() && chord1->upNote()->line() - chord2->downNote()->line() < 2))
    3093        64308 :                        && !Chord::combineVoice(chord1, chord2)) {
    3094            0 :                 separateChordConflicts.insert({ chord1->track(), chord2->track() });
    3095              :             }
    3096              :         }
    3097              :     }
    3098              : 
    3099        52601 :     const double maxPosX = std::max(upDotPosX, downDotPosX);
    3100       107745 :     for (Chord* chord : chords) {
    3101        55144 :         if (chordHasDotsAllInvisible(chord)) {
    3102            2 :             continue;
    3103              :         }
    3104        55142 :         const bool combineVoices = chord->shouldCombineVoice();
    3105        55142 :         const size_t idx = (VOICES * (chord->staffIdx() - staff->idx() + 1)) + chord->voice();
    3106        55142 :         if (!combineChordConflicts.empty()) {
    3107              :             // There are conflicts
    3108          994 :             if (muse::contains(combineChordConflicts, chord->track())) {
    3109              :                 // In this voice
    3110          886 :                 chord->setDotPosX(maxPosX);
    3111              :             } else {
    3112              :                 // Elsewhere
    3113              :                 // If combining voices, set to max pos, if separating set to own dot pos
    3114          108 :                 chord->setDotPosX(combineVoices ? maxPosX : dotPos.at(idx));
    3115              :             }
    3116              :         } else {
    3117              :             // There are no conflicts
    3118        54148 :             if (combineVoices) {
    3119        54148 :                 if (muse::contains(separateChordConflicts, chord->track())) {
    3120              :                     // Set to own dot pos if this is conflicting with a chord set to lay out independently
    3121            0 :                     chord->setDotPosX(dotPos.at(idx));
    3122              :                 } else {
    3123              :                     // Combine with other voices
    3124        54148 :                     if (chord->up()) {
    3125        29373 :                         chord->setDotPosX(upDotPosX);
    3126              :                     } else {
    3127        24775 :                         chord->setDotPosX(downDotPosX);
    3128              :                     }
    3129              :                 }
    3130              :             } else {
    3131              :                 // Separate
    3132            0 :                 chord->setDotPosX(dotPos.at(idx));
    3133              :             }
    3134              :         }
    3135              :     }
    3136        52601 : }
    3137              : 
    3138              : //---------------------------------------------------------
    3139              : //   layoutChords3
    3140              : //    - calculate positions of dots
    3141              : //---------------------------------------------------------
    3142              : 
    3143        52601 : void ChordLayout::layoutChords3(const std::vector<Chord*>& chords,
    3144              :                                 const std::vector<Note*>& notes, const Staff* staff, LayoutContext& ctx)
    3145              : {
    3146        52601 :     Fraction tick      =  notes.front()->chord()->segment()->tick();
    3147        52601 :     const MStyle& style = ctx.conf().style();
    3148        52601 :     double sp           = staff->spatium(tick);
    3149        52601 :     double stepDistance = sp * staff->lineDistance(tick) * .5;
    3150        52601 :     int stepOffset     = staff->staffType(tick)->stepOffset();
    3151              : 
    3152        52601 :     double upDotPosX    = 0.0;
    3153        52601 :     double downDotPosX  = 0.0;
    3154              :     // Track dot position of voices on this stave and possible cross voices from above & below
    3155        52601 :     std::array<double, 3 * VOICES> dotPos{};
    3156              : 
    3157        52601 :     bool isJianpu = staff->isJianpuStaff(tick);
    3158              : 
    3159        52601 :     int nNotes = int(notes.size());
    3160              : 
    3161       115117 :     for (int i = nNotes - 1; i >= 0; --i) {
    3162        62516 :         Note* note     = notes[i];
    3163        62516 :         DirectionV dotPosition = note->userDotPosition();
    3164        62516 :         const Chord* chord = note->chord();
    3165        62516 :         if (chord->dots()) {
    3166         1031 :             if (dotPosition == DirectionV::AUTO && nNotes > 1 && note->visible() && !note->dotsHidden()) {
    3167              :                 // resolve dot conflicts
    3168          344 :                 int line = isJianpu ? 0 : note->line();
    3169          344 :                 Note* above = (i < nNotes - 1) ? notes[i + 1] : nullptr;
    3170          344 :                 if (above
    3171          486 :                     && (!above->visible() || above->dotsHidden() || above->chord()->dots() == 0
    3172          142 :                         || !Chord::combineVoice(chord, above->chord()))) {
    3173           43 :                     above = nullptr;
    3174              :                 }
    3175          344 :                 int intervalAbove = above ? line - above->line() : 1000;
    3176          344 :                 Note* below = (i > 0) ? notes[i - 1] : nullptr;
    3177          344 :                 if (below
    3178          486 :                     && (!below->visible() || below->dotsHidden() || below->chord()->dots() == 0
    3179          142 :                         || !Chord::combineVoice(chord, below->chord()))) {
    3180           77 :                     below = nullptr;
    3181              :                 }
    3182          344 :                 int intervalBelow = below ? below->line() - line : 1000;
    3183          344 :                 if ((line & 1) == 0) {
    3184              :                     // line
    3185          147 :                     if (intervalAbove == 1 && intervalBelow != 1) {
    3186            0 :                         dotPosition = DirectionV::DOWN;
    3187          147 :                     } else if (intervalBelow == 1 && intervalAbove != 1) {
    3188            0 :                         dotPosition = DirectionV::UP;
    3189          147 :                     } else if (intervalAbove == 0 || intervalBelow == 0) {
    3190              :                         // unison
    3191            0 :                         dotPosition = DirectionV::AUTO; // unison conflicts taken care of later
    3192              :                     }
    3193              :                 } else {
    3194              :                     // space
    3195          197 :                     if (intervalAbove == 0 && above->chord()->dots()) {
    3196              :                         // unison
    3197            0 :                         if (!(note->voice() & 1)) {
    3198            0 :                             dotPosition = DirectionV::UP; // space, doesn't matter
    3199              :                         } else {
    3200            0 :                             if (!(above->voice() & 1)) {
    3201            0 :                                 above->setDotPosition(DirectionV::UP);
    3202              :                             } else {
    3203            0 :                                 dotPosition = DirectionV::DOWN;
    3204              :                             }
    3205              :                         }
    3206              :                     }
    3207              :                 }
    3208              :             }
    3209              :         }
    3210        62516 :         if (dotPosition == DirectionV::AUTO) {
    3211        62516 :             dotPosition = note->voice() & 1 ? DirectionV::DOWN : DirectionV::UP;
    3212              :         }
    3213        62516 :         note->setDotPosition(dotPosition);
    3214              :     }
    3215              : 
    3216              :     // Now, we can resolve note conflicts as a superchord
    3217        52601 :     placeDots(chords, notes, ctx);
    3218              : 
    3219              :     // Calculate the chords' dotPosX, and find the leftmost point for accidental layout
    3220       107745 :     for (Chord* chord : chords) {
    3221        55144 :         bool _up = chord->up();
    3222              : 
    3223        55144 :         if (chord->stemSlash()) {
    3224          223 :             TLayout::layoutStemSlash(chord->stemSlash(), chord->stemSlash()->mutldata(), ctx.conf());
    3225              :         }
    3226              : 
    3227              :         double overlapMirror;
    3228        55144 :         Stem* stem = chord->stem();
    3229        55144 :         if (stem) {
    3230        48666 :             overlapMirror = stem->lineWidthMag();
    3231         6478 :         } else if (chord->durationType().headType() == NoteHeadType::HEAD_WHOLE) {
    3232         4227 :             overlapMirror = style.styleAbsolute(Sid::stemWidth) * chord->mag();
    3233              :         } else {
    3234         2251 :             overlapMirror = 0.0;
    3235              :         }
    3236              : 
    3237        55144 :         double minDotPosX = 0.0;
    3238              : 
    3239        55144 :         std::vector<Note*> chordNotes = chord->notes();
    3240        55144 :         std::sort(chordNotes.begin(), chordNotes.end(),
    3241         7729 :                   [](Note* n1, const Note* n2) ->bool { return n1->line() < n2->line(); });
    3242       117660 :         for (Note* note : chordNotes) {
    3243        62516 :             double noteX = 0.0;
    3244        62516 :             if (!isJianpu) {
    3245        60752 :                 if (note->ldata()->mirror()) {
    3246          547 :                     if (_up) {
    3247          407 :                         noteX = StemLayout::stemPosX(chord) - overlapMirror;
    3248              :                     } else {
    3249          140 :                         noteX = -note->headBodyWidth() + overlapMirror;
    3250              :                     }
    3251        60205 :                 } else if (_up) {
    3252        32849 :                     noteX = chord->noteHeadWidth() - note->headBodyWidth();
    3253              :                 }
    3254              :             }
    3255              : 
    3256        62516 :             double ny = (isJianpu ? 0 : note->line() + stepOffset) * stepDistance;
    3257        62516 :             if (note->ldata()->pos().y() != ny) {
    3258         2179 :                 note->mutldata()->setPosY(ny);
    3259         2179 :                 if (stem) {
    3260          184 :                     TLayout::layoutStem(chord->stem(), chord->stem()->mutldata(), ctx.conf());
    3261          184 :                     if (chord->hook()) {
    3262            2 :                         chord->hook()->mutldata()->setPosY(chord->stem()->flagPosition().y());
    3263              :                     }
    3264              :                 }
    3265              :             }
    3266              : 
    3267        62516 :             const double dotX = noteX + note->headBodyWidth() + chord->pos().x();
    3268        62516 :             if (chord->dots()) {
    3269         1031 :                 const size_t idx = (VOICES * (chord->staffIdx() - staff->idx() + 1)) + chord->voice();
    3270         1031 :                 dotPos.at(idx) = std::max(dotPos.at(idx), dotX);
    3271              :             }
    3272              : 
    3273        62516 :             note->mutldata()->setPosX(noteX);
    3274        62516 :             minDotPosX = std::max(minDotPosX, dotX);
    3275              :         }
    3276              : 
    3277              :         //---------------------------------------------------
    3278              :         //    layout dots simply
    3279              :         //     we will check for conflicts after all the notes have been processed
    3280              :         //---------------------------------------------------
    3281              : 
    3282        55144 :         if (chord->dots()) {
    3283          926 :             if (chordHasDotsAllInvisible(chord)) {
    3284            2 :                 chord->setDotPosX(minDotPosX);
    3285          924 :             } else if (chord->up()) {
    3286          425 :                 upDotPosX = std::max(upDotPosX, minDotPosX);
    3287              :             } else {
    3288          499 :                 downDotPosX = std::max(downDotPosX, minDotPosX);
    3289              :             }
    3290              :         }
    3291        55144 :     }
    3292              : 
    3293        52601 :     setDotX(chords, dotPos, staff, upDotPosX, downDotPosX);
    3294        52601 : }
    3295              : 
    3296        99715 : void ChordLayout::layoutLedgerLines(const std::vector<Chord*>& chords, LayoutContext& ctx)
    3297              : {
    3298       153733 :     for (Chord* item : chords) {
    3299        54018 :         updateLedgerLines(item, ctx);
    3300        54915 :         for (Chord* grace : item->graceNotes()) {
    3301          897 :             updateLedgerLines(grace, ctx);
    3302              :         }
    3303              :     }
    3304        99715 : }
    3305              : 
    3306              : //---------------------------------------------------------
    3307              : //   getNoteListForDots
    3308              : //      This method populates three lists: one for chord notes that need to be checked from the top down,
    3309              : //      one for chords from the bottom up, and one for spaces (where the dot will be in that space)
    3310              : //---------------------------------------------------------
    3311              : 
    3312          889 : void ChordLayout::getNoteListForDots(Chord* c, std::vector<Note*>& topDownNotes, std::vector<Note*>& bottomUpNotes,
    3313              :                                      std::vector<int>& anchoredDots)
    3314              : {
    3315          889 :     Measure* measure = c->measure();
    3316          889 :     bool hasVoices = measure->hasVoices(c->vStaffIdx(), c->tick(), c->ticks(), true);
    3317          889 :     bool hasUpperCrossNotes = false;
    3318          889 :     bool hasLowerCrossNotes = false;
    3319          889 :     const TrackRange partTrackRange = c->part()->trackRange();
    3320          889 :     staff_idx_t partTopStaff = track2staff(partTrackRange.startTrack);
    3321          889 :     staff_idx_t partBottomStaff = track2staff(partTrackRange.endTrack);
    3322          889 :     track_idx_t startVoice = c->track() - c->voice();
    3323              :     // Get the last track we need to check for cross staff notes.
    3324              :     // Either 1 stave away from the stave we are laying out or the bottom staff of the part
    3325          889 :     track_idx_t lastVoice = std::min(c->vStaffIdx() + 2, partBottomStaff) * VOICES;
    3326              : 
    3327              :     // Check for cross staff notes on staff above without dots
    3328          889 :     if (partTopStaff != c->vStaffIdx()) {
    3329          317 :         for (size_t i = partTopStaff * VOICES; i < (partTopStaff + 1) * VOICES; ++i) {
    3330          254 :             if (Chord* voiceChord = measure->findChord(c->tick(), i)) {
    3331           65 :                 if (voiceChord->vStaffIdx() == c->vStaffIdx()) {
    3332            2 :                     hasUpperCrossNotes = true;
    3333            2 :                     startVoice = i;
    3334            2 :                     break;
    3335              :                 }
    3336              :             }
    3337              :         }
    3338              :     }
    3339              : 
    3340              :     // Check for cross staff notes on stave below
    3341          889 :     if (partBottomStaff != c->vStaffIdx()) {
    3342         1581 :         for (size_t i = (c->vStaffIdx() + 1) * VOICES; i < lastVoice; ++i) {
    3343          692 :             if (Chord* voiceChord = measure->findChord(c->tick(), i)) {
    3344          121 :                 if (voiceChord->vStaffIdx() == c->vStaffIdx()) {
    3345            0 :                     hasLowerCrossNotes = true;
    3346            0 :                     break;
    3347              :                 }
    3348              :             }
    3349              :         }
    3350              :     }
    3351              : 
    3352          889 :     if (!hasVoices && !(hasUpperCrossNotes || hasLowerCrossNotes)) {
    3353              :         // only this voice, so topDownNotes is just the notes in the chord
    3354         1477 :         for (Note* note : c->notes()) {
    3355          789 :             if (note->line() & 1) {
    3356          338 :                 int newOffset = 0;
    3357          338 :                 bool adjustDown = (c->voice() & 1) && !c->up();
    3358          338 :                 if (!anchoredDots.empty() && anchoredDots.back() == note->line()) {
    3359            0 :                     if (anchoredDots.size() >= 2 && anchoredDots[anchoredDots.size() - 2] == note->line() + (adjustDown ? 2 : -2)) {
    3360            0 :                         newOffset = adjustDown ? -2 : 2;
    3361              :                     } else {
    3362            0 :                         newOffset = adjustDown ? 2 : -2;
    3363              :                     }
    3364              :                 }
    3365          338 :                 anchoredDots.push_back(note->line() + newOffset);
    3366              :             } else {
    3367          451 :                 topDownNotes.push_back(note);
    3368              :             }
    3369              :         }
    3370          688 :     } else {
    3371              :         // Get a list of notes in this staff that adjust dots from top down,
    3372              :         // bottom up, and also start our locked-in dot list by adding all lines where dots are
    3373              :         // guaranteed
    3374          201 :         lastVoice = hasLowerCrossNotes ? lastVoice : (c->vStaffIdx() + 1) * VOICES;
    3375              :         // Check staves above and below for moved chords (If staff below is available)
    3376         1013 :         for (size_t i = startVoice; i < lastVoice; ++i) {
    3377          812 :             if (Chord* voiceChord = measure->findChord(c->tick(), i)) {
    3378              :                 // Skip chords on adjacent staves which have not been moved to this staff
    3379          361 :                 if (voiceChord->vStaffIdx() != c->vStaffIdx()) {
    3380            1 :                     continue;
    3381              :                 }
    3382          360 :                 bool startFromTop = !((voiceChord->voice() & 1) && !voiceChord->up()) && voiceChord->staffMove() != -1;
    3383          360 :                 if (startFromTop) {
    3384          459 :                     for (Note* note : voiceChord->notes()) {
    3385          230 :                         if (note->line() & 1) {
    3386          111 :                             anchoredDots.push_back(note->line());
    3387              :                         } else {
    3388          119 :                             topDownNotes.push_back(note);
    3389              :                         }
    3390              :                     }
    3391              :                 } else {
    3392          265 :                     for (Note* note : voiceChord->notes()) {
    3393          134 :                         if (note->line() & 1) {
    3394           55 :                             anchoredDots.push_back(note->line());
    3395              :                         } else {
    3396           79 :                             bottomUpNotes.push_back(note);
    3397              :                         }
    3398              :                     }
    3399              :                 }
    3400              :             }
    3401              :         }
    3402              :     }
    3403              :     // our two lists now contain only notes that are on lines
    3404          889 :     std::sort(topDownNotes.begin(), topDownNotes.end(),
    3405           35 :               [](Note* n1, Note* n2) { return n1->line() < n2->line(); });
    3406          889 :     std::sort(bottomUpNotes.begin(), bottomUpNotes.end(),
    3407            3 :               [](Note* n1, Note* n2) { return n1->line() > n2->line(); });
    3408          889 : }
    3409              : 
    3410         1010 : void ChordLayout::appendGraceNotes(Chord* chord)
    3411              : {
    3412         1010 :     Segment* segment = chord->segment();
    3413         1010 :     Measure* measure = chord->measure();
    3414         1010 :     track_idx_t track = chord->track();
    3415         1010 :     staff_idx_t staffIdx = chord->staffIdx();
    3416         1010 :     GraceNotesGroup& gnb = chord->graceNotesBefore();
    3417         1010 :     GraceNotesGroup& gna = chord->graceNotesAfter();
    3418              : 
    3419              :     //Attach graceNotesBefore of this chord to *this* segment
    3420         1010 :     if (!gnb.empty()) {
    3421              :         // If this segment already contains grace notes in the same voice (could happen if a
    3422              :         // previous chord has appended grace-notes-after here) put them in the same vector.
    3423          825 :         EngravingItem* item = segment->preAppendedItem(track);
    3424          825 :         if (item && item->isGraceNotesGroup()) {
    3425           21 :             GraceNotesGroup* gng = toGraceNotesGroup(item);
    3426           21 :             gng->insert(gng->end(), gnb.begin(), gnb.end());
    3427              :         } else {
    3428          804 :             gnb.setAppendedSegment(segment);
    3429          804 :             segment->preAppend(&gnb, track);
    3430              :         }
    3431              :     }
    3432              : 
    3433              :     //Attach graceNotesAfter of this chord to the *following* segment
    3434         1010 :     if (!gna.empty()) {
    3435          240 :         Segment* followingSeg = measure->tick2segment(chord->endTick(), SegmentType::All);
    3436          240 :         while (followingSeg
    3437          244 :                && (!followingSeg->hasElements(staff2track(staffIdx), staff2track(staffIdx + 1) - 1) || followingSeg->isTimeTickType())) {
    3438              :             // If there is nothing on this staff, go to next segment
    3439            4 :             followingSeg = followingSeg->next();
    3440              :         }
    3441          240 :         if (followingSeg) {
    3442          240 :             gna.setAppendedSegment(followingSeg);
    3443          240 :             followingSeg->preAppend(&gna, track);
    3444              :         }
    3445              :     }
    3446         1010 : }
    3447              : 
    3448              : /* Grace-notes-after have the special property of belonging to
    3449              : *  a segment but being pre-appended to another. This repositioning
    3450              : *  is needed and must be called AFTER horizontal spacing is calculated. */
    3451       129347 : void ChordLayout::repositionGraceNotesAfter(Segment* segment, size_t tracks)
    3452              : {
    3453       907119 :     for (track_idx_t track = 0; track < tracks; track++) {
    3454       777772 :         EngravingItem* item = segment->preAppendedItem(track);
    3455       777772 :         if (!item || !item->isGraceNotesGroup()) {
    3456       777085 :             continue;
    3457              :         }
    3458          687 :         GraceNotesGroup* gng = toGraceNotesGroup(item);
    3459         1601 :         for (Chord* chord : *gng) {
    3460          914 :             double offset = segment->ldata()->pos().x() - chord->layoutParent()->layoutParent()->ldata()->pos().x();
    3461              :             // Difference between the segment they "belong" and the segment they are "appended" to.
    3462          914 :             chord->setPos(chord->ldata()->pos().x() + offset, 0.0);
    3463              :         }
    3464              :     }
    3465       129347 : }
    3466              : 
    3467        35541 : void ChordLayout::clearLineAttachPoints(Measure* measure)
    3468              : {
    3469       147293 :     for (Segment& s : measure->segments()) {
    3470       111752 :         if (!s.isChordRestType()) {
    3471        36748 :             continue;
    3472              :         }
    3473       512732 :         for (EngravingItem* e : s.elist()) {
    3474       437728 :             if (!e || !e->isChord()) {
    3475       378662 :                 continue;
    3476              :             }
    3477        59066 :             Chord* c = toChord(e);
    3478       125714 :             for (Note* n : c->notes()) {
    3479        66648 :                 n->lineAttachPoints().clear();
    3480              :             }
    3481        59984 :             for (Chord* ch : c->graceNotes()) {
    3482         1948 :                 for (Note* n : ch->notes()) {
    3483         1030 :                     n->lineAttachPoints().clear();
    3484              :                 }
    3485              :             }
    3486              :         }
    3487              :     }
    3488        35541 : }
    3489              : 
    3490              : /* We perform a pre-layout of ties and glissandi to obtain the attach points and attach them to
    3491              :  * the notes of the chord. Will be needed for spacing calculation, particularly to
    3492              :  * enforce minTieLength. The true layout of ties and glissandi is done much later. */
    3493        57781 : void ChordLayout::updateLineAttachPoints(Chord* chord, bool isFirstInMeasure, LayoutContext& ctx)
    3494              : {
    3495        57781 :     if (chord->endsNoteAnchoredLine()) {
    3496         1300 :         for (Note* note : chord->notes()) {
    3497         1341 :             for (Spanner* sp : note->spannerBack()) {
    3498          667 :                 if (sp->isGlissando()) {
    3499          249 :                     TLayout::layoutGlissando(toGlissando(sp), ctx);
    3500          418 :                 } else if (sp->isGuitarBend()) {
    3501          415 :                     const StaffType* staffType = chord->staffType();
    3502          415 :                     bool isDiveOnTab = toGuitarBend(sp)->isDive() && staffType && staffType->isTabStaff();
    3503          415 :                     if (!isDiveOnTab) {
    3504          415 :                         TLayout::layoutGuitarBend(toGuitarBend(sp), ctx);
    3505              :                     }
    3506            3 :                 } else if (sp->isNoteLine()) {
    3507            3 :                     TLayout::layoutNoteLine(toNoteLine(sp), ctx);
    3508              :                 }
    3509              :             }
    3510              :         }
    3511              :     }
    3512        57781 :     if (isFirstInMeasure) {
    3513        38971 :         for (Note* note : chord->notes()) {
    3514        21340 :             Tie* tieBack = note->tieBack();
    3515        21340 :             if (tieBack && (note->incomingPartialTie() || tieBack->startNote()->findMeasure() != note->findMeasure())) {
    3516          658 :                 SlurTieLayout::layoutTieBack(tieBack, note->findMeasure()->system(), ctx);
    3517              :             }
    3518              :         }
    3519              :     }
    3520       123255 :     for (Note* note : chord->notes()) {
    3521        65474 :         Tie* tie = note->tieFor();
    3522        65474 :         if (tie) {
    3523         2316 :             if (tie->isPartialTie()) {
    3524           55 :                 SlurTieLayout::layoutTieFor(tie, note->findMeasure()->system());  // line attach points are updated here
    3525              :             }
    3526              : 
    3527         2316 :             Note* endNote = tie->endNote();
    3528         2316 :             if (!endNote) {
    3529           92 :                 continue;
    3530              :             }
    3531         2224 :             const Measure* endNoteMeasure = endNote->findMeasure();
    3532         2224 :             const Measure* noteMeasure = note->findMeasure();
    3533         2224 :             if (endNoteMeasure == noteMeasure || endNoteMeasure->system() != noteMeasure->system()) {
    3534         2224 :                 SlurTieLayout::layoutTieFor(tie, note->findMeasure()->system());  // line attach points are updated here
    3535              :             }
    3536              :         }
    3537              :     }
    3538              : 
    3539        57781 :     SlurTieLayout::layoutLaissezVibChord(chord, ctx);
    3540        57781 : }
    3541              : 
    3542        53096 : void ChordLayout::layoutChordBaseFingering(Chord* chord, System* system, LayoutContext&)
    3543              : {
    3544        53096 :     std::set<staff_idx_t> shapesToRecreate;
    3545        53096 :     std::vector<Note*> notes;
    3546        53096 :     Segment* segment = chord->segment();
    3547        54009 :     for (auto gc : chord->graceNotes()) {
    3548         1938 :         for (auto n : gc->notes()) {
    3549         1025 :             notes.push_back(n);
    3550              :         }
    3551              :     }
    3552       113637 :     for (auto n : chord->notes()) {
    3553        60541 :         notes.push_back(n);
    3554              :     }
    3555        53096 :     std::vector<Fingering*> fingerings;
    3556       114662 :     for (Note* note : notes) {
    3557        62020 :         for (EngravingItem* el : note->el()) {
    3558          454 :             if (el->isFingering()) {
    3559          408 :                 Fingering* f = toFingering(el);
    3560          408 :                 if (f->layoutType() == ElementType::CHORD && !f->isOnCrossBeamSide()) {
    3561              :                     // Fingering on top of cross-staff beams must be laid out later
    3562          370 :                     if (f->placeAbove()) {
    3563          270 :                         fingerings.push_back(f);
    3564              :                     } else {
    3565          100 :                         fingerings.insert(fingerings.begin(), f);
    3566              :                     }
    3567              :                 }
    3568              :             }
    3569              :         }
    3570              :     }
    3571        53466 :     for (Fingering* f : fingerings) {
    3572          370 :         TLayout::layoutFingering(f, f->mutldata());
    3573          370 :         if (f->addToSkyline()) {
    3574          359 :             Note* n = f->note();
    3575              :             RectF r
    3576          359 :                 = f->ldata()->bbox().translated(f->pos() + n->pos() + n->chord()->pos() + segment->pos() + segment->measure()->pos());
    3577          359 :             system->staff(f->note()->chord()->vStaffIdx())->skyline().add(r, f);
    3578              :         }
    3579          370 :         shapesToRecreate.insert(f->staffIdx());
    3580              :     }
    3581        53418 :     for (staff_idx_t staffIdx : shapesToRecreate) {
    3582          322 :         segment->createShape(staffIdx);
    3583              :     }
    3584        53096 : }
    3585              : 
    3586        53055 : void ChordLayout::crossMeasureSetup(Chord* chord, bool on, LayoutContext& ctx)
    3587              : {
    3588        53055 :     if (!on) {
    3589        53045 :         if (chord->crossMeasure() != CrossMeasure::UNKNOWN) {
    3590           10 :             chord->setCrossMeasure(CrossMeasure::UNKNOWN);
    3591           10 :             layoutStem(chord, ctx);
    3592              :         }
    3593        53045 :         return;
    3594              :     }
    3595           10 :     if (chord->crossMeasure() == CrossMeasure::UNKNOWN) {
    3596            5 :         CrossMeasure tempCross = CrossMeasure::NONE;      // assume no cross-measure modification
    3597              :         // if chord has only one note and note is tied forward
    3598            5 :         if (chord->notes().size() == 1 && chord->notes().at(0)->tieFor()) {
    3599            5 :             Chord* tiedChord = chord->notes().at(0)->tieFor()->endNote()->chord();
    3600              :             // if tied note belongs to another measure and to a single-note chord
    3601            5 :             if (tiedChord->measure() != chord->measure() && tiedChord->notes().size() == 1) {
    3602              :                 // get total duration
    3603              :                 std::vector<TDuration> durList = toDurationList(
    3604            5 :                     chord->actualDurationType().fraction()
    3605           10 :                     + tiedChord->actualDurationType().fraction(), true);
    3606              :                 // if duration can be expressed as a single duration
    3607              :                 // apply cross-measure modification
    3608            5 :                 if (durList.size() == 1) {
    3609            5 :                     tempCross = CrossMeasure::FIRST;
    3610            5 :                     chord->setCrossMeasure(tempCross);
    3611            5 :                     chord->setCrossMeasureDurationType(durList[0]);
    3612            5 :                     layoutStem(chord, ctx);
    3613              :                 }
    3614            5 :             }
    3615            5 :             chord->setCrossMeasure(tempCross);
    3616            5 :             tiedChord->setCrossMeasure(tempCross == CrossMeasure::FIRST
    3617              :                                        ? CrossMeasure::SECOND : CrossMeasure::NONE);
    3618              :         }
    3619              :     }
    3620              : }
    3621              : 
    3622              : // called after final position of note is set
    3623        63296 : void ChordLayout::layoutNote2(Note* item, LayoutContext& ctx)
    3624              : {
    3625        63296 :     Chord* chord = item->chord();
    3626        63296 :     const Staff* staff = item->staff();
    3627        63296 :     if (!staff) {
    3628            0 :         return;
    3629              :     }
    3630              : 
    3631        63296 :     Note::LayoutData* ldata = item->mutldata();
    3632        63296 :     const StaffType* staffType = staff->staffTypeForElement(item);
    3633              :     // for standard staves this is done in Score::layoutChords3()
    3634              :     // so that the results are available there
    3635        63296 :     const bool isTabStaff = staffType && staffType->isTabStaff();
    3636              :     // First, for tab staves that have show back-tied fret marks option, we add parentheses to the tied note if
    3637              :     // the tie spans a system boundary. This can't be done in layout as the system of each note is not decided yet
    3638        63296 :     const ShowTiedFret showTiedFret = item->style().value(Sid::tabShowTiedFret).value<ShowTiedFret>();
    3639         1030 :     const bool tieBackParen = isTabStaff && !item->fixed() && item->tieBack()
    3640        64326 :                               && (showTiedFret != ShowTiedFret::TIE_AND_FRET || item->isContinuationOfBend()) && !item->shouldHideFret();
    3641        63296 :     bool useParens =  (tieBackParen || item->ghost()) && !item->hideGeneratedParens();
    3642              : 
    3643        63296 :     if (item->harmonic() && item->displayFret() != Note::DisplayFretOption::NaturalHarmonic) {
    3644           71 :         useParens = false;
    3645              :     }
    3646              : 
    3647        63296 :     if (useParens) {
    3648           91 :         ldata->hasGeneratedParens = true;
    3649        63205 :     } else if (!item->ghost() || item->shouldHideFret() || item->hideGeneratedParens()) {
    3650        63205 :         ldata->hasGeneratedParens = false;
    3651              :     }
    3652              : 
    3653        63296 :     int dots = chord->dots();
    3654        63296 :     if (dots && !item->dots().empty()) {
    3655         1031 :         if (chord->slash() && !item->visible()) {
    3656            0 :             item->setDotsHidden(true);
    3657              :         }
    3658              :         // if chords have notes with different mag, dots must still  align
    3659         1031 :         double correctMag = chord->notes().size() > 1 ? chord->mag() : item->mag();
    3660         1031 :         double d  = ctx.conf().point(ctx.conf().styleS(Sid::dotNoteDistance)) * correctMag;
    3661         1031 :         double dd = ctx.conf().point(ctx.conf().styleS(Sid::dotDotDistance)) * correctMag;
    3662         1031 :         double x  = isTabStaff ? chord->dotPosX() - item->pos().x() : chord->dotPosX() - item->pos().x() - chord->pos().x();
    3663              :         // in case of dots with different size, center-align them
    3664         1031 :         if (item->mag() != chord->mag() && chord->notes().size() > 1) {
    3665            4 :             double relativeMag = item->mag() / chord->mag();
    3666            4 :             double centerAlignOffset = item->dot(0)->width() * (1 / relativeMag - 1) / 2;
    3667            4 :             x += centerAlignOffset;
    3668              :         }
    3669              :         // adjust dot distance for hooks
    3670         1031 :         Hook* hook = chord->hook();
    3671         1031 :         if (chord->up() && hook && hook->visible()) {
    3672           56 :             double hookRight = hook->width() + hook->x() + chord->pos().x();
    3673           56 :             double hookBottom = hook->height() + hook->y() + chord->pos().y()
    3674           56 :                                 + (0.25 * item->spatium());
    3675              :             // the top dot in the chord, not the dot for this particular note:
    3676           56 :             double dotY = chord->notes().back()->y() + chord->notes().back()->dots().front()->pos().y();
    3677           56 :             if (chord->dotPosX() < hookRight && dotY < hookBottom) {
    3678           56 :                 d = hook->width();
    3679              :             }
    3680              :         }
    3681              :         // if TAB and stems through staff
    3682         1031 :         if (isTabStaff && staffType->stemThrough()) {
    3683              :             // with TAB's, dot Y is not calculated during layoutChords3(),
    3684              :             // as layoutChords3() is not even called for TAB's;
    3685              :             // setDotRelativeLine() actually also manages creation/deletion of NoteDot's
    3686            1 :             ChordLayout::setDotRelativeLine(item, 0, ctx);
    3687              : 
    3688              :             // use TAB default note-to-dot spacing
    3689            1 :             dd = STAFFTYPE_TAB_DEFAULTDOTDIST_X.toAbsolute(item->spatium());
    3690            1 :             d = dd * 0.5;
    3691              :         }
    3692              : 
    3693              :         // apply to dots
    3694              :         // Invisible dots are laid out separately,
    3695              :         // with a distance of 0.1sp to distinguish from visible ones
    3696         1031 :         double visibleX = x + d;
    3697         1031 :         double invisibleX = x;
    3698              : 
    3699         2108 :         for (NoteDot* dot : item->dots()) {
    3700         1077 :             if (dot->visible()) {
    3701         1075 :                 dot->mutldata()->setPosX(visibleX);
    3702         1075 :                 visibleX += dd;
    3703              :             } else {
    3704            2 :                 invisibleX += (0.1 * item->spatium());
    3705            2 :                 dot->mutldata()->setPosX(invisibleX);
    3706            2 :                 invisibleX += item->symWidth(SymId::augmentationDot) * dot->mag();
    3707              :             }
    3708              :         }
    3709              :     }
    3710              : 
    3711              :     // layout elements attached to note
    3712        63751 :     for (EngravingItem* e : item->el()) {
    3713          455 :         if (e->isSymbol()) {
    3714           27 :             e->mutldata()->setMag(item->mag());
    3715           27 :             TLayout::layoutItem(e, ctx);
    3716          428 :         } else if (e->isFingering()) {
    3717              :             // don't set mag; fingerings should not scale with note
    3718          409 :             Fingering* f = toFingering(e);
    3719          409 :             if (f->propertyFlags(Pid::PLACEMENT) == PropertyFlags::STYLED) {
    3720          363 :                 f->setPlacement(f->calculatePlacement());
    3721              :             }
    3722              :             // layout fingerings that are placed relative to notehead
    3723              :             // fingerings placed relative to chord will be laid out later
    3724          409 :             if (f->layoutType() == ElementType::NOTE) {
    3725           13 :                 TLayout::layoutFingering(f, f->mutldata());
    3726              :             }
    3727              :         } else {
    3728           19 :             e->mutldata()->setMag(item->mag());
    3729           19 :             TLayout::layoutItem(e, ctx);
    3730              :         }
    3731              :     }
    3732              : 
    3733        63296 :     TLayout::fillNoteShape(item, ldata);
    3734              : }
    3735              : 
    3736        55814 : void ChordLayout::createParenGroups(Chord* chord)
    3737              : {
    3738        55814 :     std::vector<Note*> addParens;
    3739        55814 :     std::vector<Note*> removeParens;
    3740              : 
    3741       119110 :     for (Note* note : chord->notes()) {
    3742        63296 :         const NoteParenthesisInfo* noteParenInfo = note->parenthesisInfo();
    3743        63296 :         const Parenthesis* leftParen = noteParenInfo ? noteParenInfo->leftParen() : nullptr;
    3744        63296 :         bool parenGenerated = leftParen && leftParen->generated();
    3745              : 
    3746        63296 :         if (note->ldata()->hasGeneratedParens()) {
    3747           91 :             if (noteParenInfo) {
    3748           24 :                 if (parenGenerated) {
    3749           18 :                     EditChord::removeChordParentheses(chord, { note }, false, true);
    3750              :                 } else {
    3751           18 :                     continue;
    3752              :                 }
    3753              :             }
    3754           73 :             addParens.push_back(note);
    3755           73 :             note->undoChangeProperty(Pid::HAS_PARENTHESES, ParenthesesMode::BOTH);
    3756        63205 :         } else if (parenGenerated) {
    3757            0 :             removeParens.push_back(note);
    3758              :         }
    3759              :     }
    3760              : 
    3761        55814 :     EditChord::addChordParentheses(chord, addParens, false, true);
    3762        55814 :     EditChord::removeChordParentheses(chord, removeParens, false, true);
    3763        55814 : }
    3764              : 
    3765        56864 : void ChordLayout::checkStartEndSlurs(Chord* chord, LayoutContext& ctx)
    3766              : {
    3767        56864 :     chord->startEndSlurs().reset();
    3768        58767 :     for (Spanner* spanner : chord->startingSpanners()) {
    3769         1903 :         if (!spanner->isSlur()) {
    3770         1047 :             continue;
    3771              :         }
    3772          856 :         Slur* slur = toSlur(spanner);
    3773          856 :         SlurTieLayout::computeUp(slur, ctx);
    3774          856 :         if (slur->up()) {
    3775          373 :             chord->startEndSlurs().startUp = true;
    3776              :         } else {
    3777          483 :             chord->startEndSlurs().startDown = true;
    3778              :         }
    3779              :         // Check if end chord has been connected to this slur. If not, connect it.
    3780          856 :         if (!slur->endChord()) {
    3781           15 :             continue;
    3782              :         }
    3783          841 :         slur->endChord()->addEndingSpanner(slur);
    3784              :     }
    3785        58885 :     for (Spanner* spanner : chord->endingSpanners()) {
    3786         2021 :         if (!spanner->isSlur()) {
    3787          970 :             continue;
    3788              :         }
    3789         1051 :         if (toSlur(spanner)->up()) {
    3790          484 :             chord->startEndSlurs().endUp = true;
    3791              :         } else {
    3792          567 :             chord->startEndSlurs().endDown = true;
    3793              :         }
    3794              :     }
    3795        56864 : }
    3796              : 
    3797       489640 : void ChordLayout::checkAndFillShape(const ChordRest* item, ChordRest::LayoutData* ldata, const LayoutConfiguration& conf)
    3798              : {
    3799              : #ifdef MUE_ENABLE_ENGRAVING_LD_ACCESS
    3800              :     Shape origin = ldata->shape(LD_ACCESS::PASS);
    3801              : #endif
    3802              : 
    3803       489640 :     fillShape(item, ldata, conf);
    3804              : 
    3805              : #ifdef MUE_ENABLE_ENGRAVING_LD_ACCESS
    3806              :     Shape fixed = ldata->shape(LD_ACCESS::PASS);
    3807              :     if (!origin.equal(fixed)) {
    3808              :         LOGE() << "Shape not actual for item: " << item->typeName();
    3809              :     }
    3810              : #endif
    3811       489640 : }
    3812              : 
    3813       546307 : void ChordLayout::fillShape(const ChordRest* item, Chord::LayoutData* ldata, const LayoutConfiguration& conf)
    3814              : {
    3815       546307 :     switch (item->type()) {
    3816       282184 :     case ElementType::CHORD:
    3817       282184 :         fillShape(toChord(item), static_cast<Chord::LayoutData*>(ldata));
    3818       282184 :         break;
    3819          932 :     case ElementType::MEASURE_REPEAT:
    3820          932 :         fillShape(toMeasureRepeat(item), static_cast<MeasureRepeat::LayoutData*>(ldata), conf);
    3821          932 :         break;
    3822       263191 :     default:
    3823       263191 :         RestLayout::fillShape(toRest(item), static_cast<Rest::LayoutData*>(ldata), conf);
    3824       263191 :         break;
    3825              :     }
    3826       546307 : }
    3827              : 
    3828       612765 : Shape ChordLayout::chordRestShape(const ChordRest* item)
    3829              : {
    3830       612765 :     Shape shape;
    3831              :     {
    3832       625780 :         for (Lyrics* l : item->lyrics()) {
    3833        13015 :             if (!l || !l->addToSkyline() || l->xmlText().empty()) {
    3834          257 :                 continue;
    3835              :             }
    3836        12758 :             RectF bbox = l->ldata()->bbox().translated(l->pos());
    3837        12758 :             shape.addHorizontalSpacing(l, bbox.left(), bbox.right());
    3838              :         }
    3839              :     }
    3840              : 
    3841       612765 :     return shape;
    3842            0 : }
    3843              : 
    3844         1339 : bool ChordLayout::leaveSpaceForTie(const Articulation* item)
    3845              : {
    3846         1339 :     if (!item->ownershipParent() || !item->ownershipParent()->isChord()) {
    3847            0 :         return false;
    3848              :     }
    3849              : 
    3850         1339 :     Chord* chord = toChord(item->chordRest());
    3851         1339 :     bool up = item->ldata()->up;
    3852         1339 :     Note* note = up ? chord->upNote() : chord->downNote();
    3853         1339 :     Tie* tieFor = note->tieFor();
    3854         1339 :     Tie* tieBack = note->tieBack();
    3855              : 
    3856         1339 :     if (!tieFor && !tieBack) {
    3857         1329 :         return false;
    3858              :     }
    3859              : 
    3860            4 :     bool leaveSpace = (tieFor && tieFor->up() == up && tieFor->isOuterTieOfChord(Grip::START))
    3861           14 :                       || (tieBack && tieBack->up() == up && tieBack->isOuterTieOfChord(Grip::END));
    3862              : 
    3863           10 :     return leaveSpace;
    3864              : }
    3865              : 
    3866       282208 : void ChordLayout::fillShape(const Chord* item, ChordRest::LayoutData* ldata)
    3867              : {
    3868       282208 :     Shape shape(Shape::Type::Composite);
    3869              : 
    3870       282208 :     Hook* hook = item->hook();
    3871       282208 :     if (hook) {
    3872         9954 :         LD_CONDITION(hook->ldata()->isSetShape());
    3873              :     }
    3874              : 
    3875       282208 :     Stem* stem = item->stem();
    3876       282208 :     if (stem) {
    3877       246463 :         LD_CONDITION(stem->ldata()->isSetShape());
    3878              :     }
    3879              : 
    3880       282208 :     StemSlash* stemSlash = item->stemSlash();
    3881       282208 :     if (stemSlash) {
    3882          577 :         LD_CONDITION(stemSlash->ldata()->isSetShape());
    3883              :     }
    3884              : 
    3885       282208 :     TremoloSingleChord* tremolo = item->tremoloSingleChord();
    3886       282208 :     if (tremolo) {
    3887         1371 :         LD_CONDITION(tremolo->ldata()->isSetShape());
    3888              :     }
    3889              : 
    3890       282208 :     Arpeggio* arpeggio = item->arpeggio();
    3891       282208 :     if (arpeggio) {
    3892         1800 :         LD_CONDITION(arpeggio->ldata()->isSetShape());
    3893              :     }
    3894              : 
    3895       282208 :     Arpeggio* spanArpeggio = item->spanArpeggio();
    3896       282208 :     if (spanArpeggio) {
    3897         2354 :         LD_CONDITION(spanArpeggio->ldata()->isSetShape());
    3898              :     }
    3899              : 
    3900       282208 :     BeamSegment* beamlet = item->beamlet();
    3901              : 
    3902       282208 :     if (hook && hook->addToSkyline()) {
    3903         9932 :         shape.add(hook->shape().translate(hook->pos()));
    3904              :     }
    3905              : 
    3906       282208 :     if (stem && stem->addToSkyline()) {
    3907       246230 :         shape.add(stem->shape().translate(stem->pos()));
    3908              :     }
    3909              : 
    3910       282208 :     if (stemSlash && stemSlash->addToSkyline()) {
    3911          577 :         shape.add(stemSlash->shape().translate(stemSlash->pos()));
    3912              :     }
    3913              : 
    3914       282208 :     if (tremolo && tremolo->addToSkyline()) {
    3915         1371 :         shape.add(tremolo->shape().translate(tremolo->pos()));
    3916              :     }
    3917              : 
    3918       282208 :     if (arpeggio && arpeggio->addToSkyline()) {
    3919         1786 :         shape.add(arpeggio->shape().translate(arpeggio->pos()));
    3920              :     }
    3921              : 
    3922       282208 :     if (spanArpeggio && !arpeggio && spanArpeggio->vStaffIdx() != item->vStaffIdx() && spanArpeggio->addToSkyline()) {
    3923          188 :         PointF spanArpPos = spanArpeggio->pos() - (item->pagePos() - spanArpeggio->chord()->pagePos());
    3924          188 :         shape.add(spanArpeggio->shape().translate(spanArpPos));
    3925              :     }
    3926              : 
    3927       603631 :     for (Note* note : item->notes()) {
    3928       321423 :         shape.add(note->shape().translate(note->pos()));
    3929              :     }
    3930              : 
    3931       282208 :     if (item->tabDur() && item->tabDur()->addToSkyline()) {
    3932          144 :         shape.add(item->tabDur()->shape().translate(item->tabDur()->pos()));
    3933              :     }
    3934              : 
    3935       283443 :     for (const NoteParenthesisInfo* parenInfo : item->noteParentheses()) {
    3936         1235 :         Parenthesis* leftParen = parenInfo->leftParen();
    3937         1235 :         Parenthesis* rightParen = parenInfo->rightParen();
    3938              : 
    3939         1235 :         if (leftParen && leftParen->addToSkyline()) {
    3940         1214 :             shape.add(leftParen->shape().translate(leftParen->pos()));
    3941              :         }
    3942         1235 :         if (rightParen && rightParen->addToSkyline()) {
    3943         1214 :             shape.add(rightParen->shape().translate(rightParen->pos()));
    3944              :         }
    3945              :     }
    3946              : 
    3947       283239 :     for (EngravingItem* e : item->el()) {
    3948         1031 :         if (e->addToSkyline()) {
    3949         1031 :             shape.add(e->shape().translate(e->pos()));
    3950              :         }
    3951              :     }
    3952              : 
    3953       282208 :     shape.add(chordRestShape(item));      // add lyrics
    3954              : 
    3955       744147 :     for (const LedgerLine* l : item->ledgerLines()) {
    3956       461939 :         shape.add(l->shape().translate(l->pos()));
    3957              :     }
    3958              : 
    3959       282322 :     for (const JianpuDurationLine* line : item->jianpuDurationLines()) {
    3960          114 :         shape.add(line->shape().translate(line->pos()));
    3961              :     }
    3962              : 
    3963       282208 :     if (beamlet && stem) {
    3964         1653 :         double xPos = beamlet->line.p1().x() - stem->ldata()->pos().x();
    3965         1653 :         if (beamlet->isBefore && !item->up()) {
    3966          694 :             xPos -= stem->width();
    3967          959 :         } else if (!beamlet->isBefore && item->up()) {
    3968          192 :             xPos += stem->width();
    3969              :         }
    3970         1653 :         shape.add(beamlet->shape().translate(PointF(-xPos, 0.0)));
    3971              :     }
    3972              : 
    3973       290871 :     for (const Articulation* a : item->articulations()) {
    3974              :         // Only add lv to shape
    3975         8663 :         if (a->isLaissezVib()) {
    3976            0 :             shape.add(a->shape().translate(a->pos()));
    3977              :         }
    3978              :     }
    3979              : 
    3980       282208 :     const Parenthesis* leftParen = item->leftParen();
    3981       282208 :     if (leftParen && leftParen->addToSkyline()) {
    3982            0 :         shape.add(leftParen->ldata()->shape().translated(leftParen->pos()));
    3983              :     }
    3984       282208 :     const Parenthesis* rightParen = item->rightParen();
    3985       282208 :     if (rightParen && rightParen->addToSkyline()) {
    3986            0 :         shape.add(rightParen->ldata()->shape().translated(rightParen->pos()));
    3987              :     }
    3988              : 
    3989       282208 :     ldata->setShape(shape);
    3990       282208 : }
    3991              : 
    3992         1308 : void ChordLayout::fillShape(const MeasureRepeat* item, MeasureRepeat::LayoutData* ldata, const LayoutConfiguration&)
    3993              : {
    3994         1308 :     Shape shape(Shape::Type::Composite);
    3995              : 
    3996         1308 :     shape.add(item->numberRect(), item);
    3997         1308 :     shape.add(item->symBbox(ldata->symId), item);
    3998              : 
    3999         1308 :     ldata->setShape(shape);
    4000         1308 : }
    4001              : 
    4002          492 : void ChordLayout::addLineAttachPoints(Spanner* spanner)
    4003              : {
    4004          492 :     assert(spanner->anchor() == Spanner::Anchor::NOTE);
    4005              : 
    4006          492 :     const SpannerSegment* frontSeg = toSpannerSegment(spanner->frontSegment());
    4007          492 :     const SpannerSegment* backSeg = toSpannerSegment(spanner->backSegment());
    4008          492 :     Note* startNote = nullptr;
    4009          492 :     Note* endNote = nullptr;
    4010              : 
    4011          492 :     EngravingItem* startElement = spanner->startElement();
    4012          492 :     EngravingItem* endElement = spanner->endElement();
    4013          492 :     if (startElement && startElement->isNote()) {
    4014          492 :         startNote = toNote(startElement);
    4015              :     }
    4016          492 :     if (endElement && endElement->isNote()) {
    4017          492 :         endNote = toNote(endElement);
    4018              :     }
    4019          492 :     if (!frontSeg || !backSeg || !startNote || !endNote) {
    4020            0 :         return;
    4021              :     }
    4022          492 :     double startX = frontSeg->ldata()->pos().x();
    4023          492 :     double endX = backSeg->pos2().x() + backSeg->ldata()->pos().x(); // because pos2 is relative to ipos
    4024              :     // Here we don't pass y() because its value is unreliable during the first stages of layout.
    4025              :     // The y() is irrelevant anyway for horizontal spacing.
    4026          492 :     startNote->addStartLineAttachPoint(PointF(startX, 0.0), spanner);
    4027          492 :     endNote->addEndLineAttachPoint(PointF(endX, 0.0), spanner);
    4028              : }
        

Generated by: LCOV version 2.0-1