LCOV - code coverage report
Current view: top level - src/engraving/rendering/score - slurtielayout.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 86.3 % 1998 1725
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 "slurtielayout.h"
      23              : 
      24              : #include "iengravingconfiguration.h" // IWYU pragma: keep
      25              : #include "iengravingfont.h"
      26              : 
      27              : #include "dom/slur.h"
      28              : #include "dom/chord.h"
      29              : #include "dom/clef.h"
      30              : #include "dom/score.h"
      31              : #include "dom/system.h"
      32              : #include "dom/staff.h"
      33              : #include "dom/stafftype.h"
      34              : #include "dom/ledgerline.h"
      35              : #include "dom/note.h"
      36              : #include "dom/hook.h"
      37              : #include "dom/stem.h"
      38              : #include "dom/tremolotwochord.h"
      39              : #include "dom/tie.h"
      40              : #include "dom/engravingitem.h"
      41              : #include "dom/measure.h"
      42              : #include "dom/guitarbend.h"
      43              : #include "dom/laissezvib.h"
      44              : #include "dom/jianpuoctavedot.h"
      45              : #include "dom/parenthesis.h"
      46              : #include "dom/partialtie.h"
      47              : 
      48              : #include "editing/editchord.h"
      49              : 
      50              : #include "tlayout.h"
      51              : #include "chordlayout.h"
      52              : #include "stemlayout.h"
      53              : #include "tremololayout.h"
      54              : 
      55              : #include "draw/types/transform.h"
      56              : #include "global/stringutils.h"
      57              : 
      58              : using namespace muse::draw;
      59              : using namespace mu::engraving;
      60              : using namespace mu::engraving::rendering::score;
      61              : 
      62          945 : SpannerSegment* SlurTieLayout::layoutSystem(Slur* item, System* system, LayoutContext& ctx)
      63              : {
      64          945 :     const double horizontalTieClearance = 0.35 * item->spatium();
      65          945 :     const double tieClearance = 0.65 * item->spatium();
      66          945 :     const double continuedSlurOffsetY = item->spatium() * .4;
      67          945 :     const double continuedSlurMaxDiff = 2.5 * item->spatium();
      68          945 :     Fraction stick = system->firstMeasure()->tick();
      69          945 :     Fraction etick = system->lastMeasure()->endTick();
      70              : 
      71          945 :     SlurSegment* slurSegment = toSlurSegment(TLayout::getNextLayoutSystemSegment(item, system, [item]() {
      72          473 :         return item->newSlurTieSegment();
      73              :     }));
      74              : 
      75              :     SpannerSegmentType sst;
      76          945 :     if (item->tick() >= stick) {
      77              :         //
      78              :         // this is the first call to layoutSystem,
      79              :         // processing the first line segment
      80              :         //
      81          927 :         if (item->track2() == muse::nidx) {
      82            8 :             item->setTrack2(item->track());
      83              :         }
      84          927 :         if (item->startCR() == 0 || item->startCR()->measure() == 0) {
      85            0 :             LOGD("Slur::layout(): track %zu-%zu  %p - %p tick %d-%d null start anchor",
      86            0 :                  item->track(), item->track2(), item->startCR(), item->endCR(), item->tick().ticks(), item->tick2().ticks());
      87            0 :             return slurSegment;
      88              :         }
      89         1016 :         if (item->ticks().isZero() && !(item->startCR() && item->startCR()->isGrace()) && !(item->endCR() && item->endCR()->isGrace())
      90         1016 :             && !item->isIncoming() && !item->isOutgoing() && !item->isTappingHalfSlur()) {
      91            0 :             LOGD("Slur::layout(): track %zu tick %d zero-length slur, skipping",
      92            0 :                  item->track(), item->tick().ticks());
      93            0 :             return slurSegment;
      94              :         }
      95          927 :         if (item->endCR() == 0) {         // sanity check
      96            0 :             item->setEndElement(item->startCR());
      97            0 :             item->setTick2(item->tick());
      98              :         }
      99          927 :         computeUp(item, ctx);
     100          927 :         sst = item->tick2() < etick ? SpannerSegmentType::SINGLE : SpannerSegmentType::BEGIN;
     101           18 :     } else if (item->tick() < stick && item->tick2() >= etick) {
     102            0 :         sst = SpannerSegmentType::MIDDLE;
     103              :     } else {
     104           18 :         sst = SpannerSegmentType::END;
     105              :     }
     106          945 :     slurSegment->setSpannerSegmentType(sst);
     107              : 
     108          945 :     SlurTiePos sPos;
     109          945 :     slurPos(item, &sPos, ctx);
     110          945 :     PointF p1, p2;
     111              :     // adjust for ties
     112          945 :     p1 = sPos.p1;
     113          945 :     p2 = sPos.p2;
     114          945 :     bool constrainLeftAnchor = false;
     115              : 
     116          945 :     const bool incomingPartialSlur = item->isIncoming();
     117          945 :     const bool outgoingPartialSlur = item->isOutgoing();
     118              : 
     119              :     // start anchor, either on the start chordrest or at the beginning of the system
     120          945 :     if ((sst == SpannerSegmentType::SINGLE || sst == SpannerSegmentType::BEGIN) && !incomingPartialSlur) {
     121          903 :         Chord* sc = item->startCR()->isChord() ? toChord(item->startCR()) : nullptr;
     122              : 
     123              :         // on chord
     124          903 :         if (sc) {
     125          903 :             Tie* tie = (item->up() ? sc->upNote() : sc->downNote())->tieFor();
     126          903 :             PointF endPoint = PointF();
     127          903 :             if (tie && (tie->isInside() || tie->up() != item->up() || tieSegmentShouldBeSkipped(tie))) {
     128              :                 // there is a tie that starts on this chordrest
     129            4 :                 tie = nullptr;
     130              :             }
     131          903 :             if (tie && !tie->segmentsEmpty()) {
     132            8 :                 endPoint = tie->segmentAt(0)->ups(Grip::START).pos();
     133              :             }
     134          903 :             bool adjustedVertically = false;
     135          903 :             if (tie) {
     136            8 :                 if (item->up() && tie->up()) {
     137            0 :                     if (endPoint.y() - p1.y() < tieClearance) {
     138            0 :                         p1.ry() = endPoint.y() - tieClearance;
     139            0 :                         adjustedVertically = true;
     140              :                     }
     141            8 :                 } else if (!item->up() && !tie->up()) {
     142            8 :                     if (p1.y() - endPoint.y() < tieClearance) {
     143            8 :                         p1.ry() = endPoint.y() + tieClearance;
     144            8 :                         adjustedVertically = true;
     145              :                     }
     146              :                 }
     147              :             }
     148          903 :             Tie* tieBack = sc->upNote()->tieBack();
     149          895 :             if (!adjustedVertically && tieBack && (!tieBack->isInside() || tieBack->isPartialTie())
     150         1798 :                 && tieBack->up() == item->up() && !tieSegmentShouldBeSkipped(tieBack)) {
     151              :                 // there is a tie that ends on this chordrest
     152            7 :                 tie = tieBack;
     153            7 :                 if (!tie->segmentsEmpty()) {
     154            7 :                     endPoint = tie->segmentAt(static_cast<int>(tie->nsegments()) - 1)->ups(Grip::END).pos();
     155            7 :                     if (std::abs(endPoint.y() - p1.y()) < tieClearance) {
     156            6 :                         p1.rx() += horizontalTieClearance;
     157              :                     }
     158              :                 }
     159              :             }
     160              :         }
     161          945 :     } else if (sst == SpannerSegmentType::END || sst == SpannerSegmentType::MIDDLE || incomingPartialSlur) {
     162              :         // beginning of system
     163           42 :         Measure* measure = item->startCR()->measure();
     164           42 :         ChordRest* firstCr = incomingPartialSlur ? measure->firstChordRest(item->track()) : system->firstChordRest(item->track2());
     165           42 :         const bool sameStaff = firstCr && firstCr->vStaffIdx() == slurSegment->vStaffIdx();
     166           42 :         double y = p1.y();
     167           42 :         if (firstCr && firstCr == item->endCR()) {
     168           21 :             constrainLeftAnchor = true;
     169              :         }
     170           42 :         if (firstCr && firstCr->isChord() && sameStaff) {
     171           41 :             Chord* chord = toChord(firstCr);
     172           41 :             Shape chordShape = chord->shape();
     173           82 :             chordShape.removeTypes({ ElementType::ACCIDENTAL });
     174           41 :             y = item->up() ? chordShape.top() : chordShape.bottom();
     175           41 :             bool isAboveStem = chord->stem() && chord->up() == item->up();
     176           41 :             if (!isAboveStem) {
     177           40 :                 y += continuedSlurOffsetY * (item->up() ? -1 : 1);
     178              :             }
     179           41 :         }
     180              : 
     181           42 :         double segmentX = incomingPartialSlur ? measure->firstNoteRestSegmentX(true) : system->firstNoteRestSegmentX(true);
     182           42 :         p1 = PointF(segmentX, y);
     183              : 
     184              :         // adjust for ties at the start of the system
     185           42 :         ChordRest* cr = incomingPartialSlur ? measure->firstChordRest(item->track()) : system->firstChordRest(item->track());
     186           42 :         const bool tieSameStaff = cr && cr->vStaffIdx() == item->staffIdx();
     187           42 :         if (cr && cr->isChord() && cr->tick() >= stick && cr->tick() <= etick && tieSameStaff) {
     188           41 :             Chord* c = toChord(cr);
     189           41 :             Tie* tie = nullptr;
     190           41 :             PointF endPoint;
     191           41 :             Tie* tieBack = c->upNote()->tieBack();
     192           24 :             if (tieBack && (tieBack->isPartialTie() || !tieBack->isInside()) && tieBack->up() == item->up()
     193           65 :                 && !tieSegmentShouldBeSkipped(tieBack)) {
     194              :                 // there is a tie that ends on this chordrest
     195           24 :                 if (!tieBack->segmentsEmpty()) { //Checks for spanner segment esxists
     196           24 :                     tie = tieBack;
     197           24 :                     endPoint = tie->backSegment()->ups(Grip::START).pos();
     198              :                 }
     199              :             }
     200           41 :             if (tie) {
     201           24 :                 if (tie->isPartialTie()) {
     202           24 :                     p1.rx() = endPoint.rx();
     203              :                 }
     204           24 :                 if (item->up() && tie->up()) {
     205            2 :                     if (endPoint.y() - p1.y() < tieClearance) {
     206            2 :                         p1.ry() = endPoint.y() - tieClearance;
     207              :                     }
     208           22 :                 } else if (!item->up() && !tie->up()) {
     209           22 :                     if (p1.y() - endPoint.y() < tieClearance) {
     210           21 :                         p1.ry() = endPoint.y() + tieClearance;
     211              :                     }
     212              :                 }
     213              :             }
     214              :         }
     215              :     }
     216              : 
     217              :     // end anchor
     218          945 :     if ((sst == SpannerSegmentType::SINGLE || sst == SpannerSegmentType::END) && !outgoingPartialSlur) {
     219          894 :         Chord* ec = item->endCR()->isChord() ? toChord(item->endCR()) : nullptr;
     220              : 
     221              :         // on chord
     222          894 :         if (ec) {
     223          881 :             Tie* tie = (item->up() ? ec->upNote() : ec->downNote())->tieBack();
     224          881 :             PointF endPoint;
     225          881 :             if (tie && (tie->isInside() || tie->up() != item->up() || tieSegmentShouldBeSkipped(tie))) {
     226            4 :                 tie = nullptr;
     227              :             }
     228          881 :             bool adjustedVertically = false;
     229          881 :             if (tie && !tie->segmentsEmpty()) {
     230           28 :                 endPoint = tie->segmentAt(0)->ups(Grip::END).pos();
     231           28 :                 if (item->up() && tie->up()) {
     232            0 :                     if (endPoint.y() - p2.y() < tieClearance) {
     233            0 :                         p2.ry() = endPoint.y() - tieClearance;
     234            0 :                         adjustedVertically = true;
     235              :                     }
     236           28 :                 } else if (!item->up() && !tie->up()) {
     237           28 :                     if (p2.y() - endPoint.y() < tieClearance) {
     238           28 :                         p2.ry() = endPoint.y() + tieClearance;
     239           28 :                         adjustedVertically = true;
     240              :                     }
     241              :                 }
     242              :             }
     243          881 :             Tie* tieFor = ec->upNote()->tieFor();
     244          853 :             if (!adjustedVertically && tieFor && (tieFor->isPartialTie() || !tieFor->isInside()) && tieFor->up() == item->up()
     245         1734 :                 && !tieSegmentShouldBeSkipped(tieFor)) {
     246              :                 // there is a tie that starts on this chordrest
     247            6 :                 if (!tieFor->segmentsEmpty() && std::abs(tieFor->frontSegment()->ups(Grip::START).pos().y() - p2.y()) < tieClearance) {
     248            6 :                     p2.rx() -= horizontalTieClearance;
     249              :                 }
     250              :             }
     251              :         }
     252          894 :     } else {
     253              :         // at end of system
     254           51 :         Measure* measure = item->endCR()->measure();
     255           51 :         ChordRest* lastCr = outgoingPartialSlur ? measure->lastChordRest(item->track()) : system->lastChordRest(item->track());
     256           51 :         double y = p1.y();
     257           51 :         const bool sameStaff = lastCr && lastCr->vStaffIdx() == slurSegment->vStaffIdx();
     258           51 :         if (lastCr && lastCr == item->startCR()) {
     259            2 :             y += 0.25 * item->spatium() * (item->up() ? -1 : 1);
     260           49 :         } else if (lastCr && lastCr->isChord() && sameStaff) {
     261           42 :             Chord* chord = toChord(lastCr);
     262           42 :             Shape chordShape = chord->shape();
     263           84 :             chordShape.removeTypes({ ElementType::ACCIDENTAL });
     264           42 :             y = item->up() ? chordShape.top() : chordShape.bottom();
     265           42 :             bool isAboveStem = chord->stem() && chord->up() == item->up();
     266           42 :             if (!isAboveStem) {
     267           42 :                 y += continuedSlurOffsetY * (item->up() ? -1 : 1);
     268              :             }
     269           42 :             double diff = item->up() ? y - p1.y() : p1.y() - y;
     270           42 :             if (diff > continuedSlurMaxDiff) {
     271            0 :                 y = p1.y() + (y > p1.y() ? continuedSlurMaxDiff : -continuedSlurMaxDiff);
     272              :             }
     273           42 :         }
     274              : 
     275           51 :         double endingX = endingXForOpenEndedSlurTie(outgoingPartialSlur ? measure : system->lastMeasure(), item->startCR()->vStaffIdx());
     276           51 :         p2 = PointF(endingX, y);
     277              : 
     278              :         // adjust for ties at the end of the system
     279           51 :         ChordRest* cr = outgoingPartialSlur ? measure->lastChordRest(item->track()) : system->lastChordRest(item->track());
     280           51 :         const bool tieSameStaff = cr && cr->vStaffIdx() == item->staffIdx();
     281              : 
     282           51 :         if (cr && cr->isChord() && cr->tick() >= stick && cr->tick() <= etick && tieSameStaff) {
     283           44 :             Chord* c = toChord(cr);
     284           44 :             Tie* tie = nullptr;
     285           44 :             PointF endPoint;
     286           44 :             Tie* tieFor = c->upNote()->tieFor();
     287           26 :             if (tieFor && (tieFor->isPartialTie() || !tieFor->isInside()) && tieFor->up() == item->up()
     288           70 :                 && !tieSegmentShouldBeSkipped(tieFor)) {
     289              :                 // there is a tie that starts on this chordrest
     290           26 :                 if (!tieFor->segmentsEmpty()) { //Checks is spanner segment exists
     291           26 :                     tie = tieFor;
     292           26 :                     endPoint = tie->segmentAt(0)->ups(Grip::END).pos();
     293              :                 }
     294              : 
     295           26 :                 if (outgoingPartialSlur && tie->type() == ElementType::TIE && tie->nsegments() == 1) {
     296              :                     // For partial slurs ending midway through a tie, get top of the tie shape at the slur's end X
     297            0 :                     const TieSegment* tieSeg = tie->frontSegment();
     298            0 :                     const Shape tieShape = tieSeg->shape().translate(tieSeg->pos());
     299            0 :                     if (item->up() && tie->up()) {
     300            0 :                         endPoint.ry() = p2.y() + tieShape.topDistance(p2);
     301            0 :                     } else if (!item->up() && !tie->up()) {
     302            0 :                         endPoint.ry() = p2.y() - tieShape.bottomDistance(p2);
     303              :                     }
     304            0 :                 }
     305              :             }
     306           44 :             if (tie) {
     307           26 :                 if (item->up() && tie->up()) {
     308            0 :                     if (endPoint.y() - p2.y() < tieClearance) {
     309            0 :                         p2.ry() = endPoint.y() - tieClearance;
     310              :                     }
     311           26 :                 } else if (!item->up() && !tie->up()) {
     312           26 :                     if (p2.y() - endPoint.y() < tieClearance) {
     313           26 :                         p2.ry() = endPoint.y() + tieClearance;
     314              :                     }
     315              :                 }
     316              :             }
     317              :         }
     318              :     }
     319          945 :     if (constrainLeftAnchor) {
     320           21 :         p1.ry() = p2.y() + (0.25 * item->spatium() * (item->up() ? -1 : 1));
     321              :     }
     322              : 
     323          945 :     if (item->isTappingHalfSlur()) {
     324           32 :         p1 = p2 - PointF(2.5 * item->spatium(), 0.0);
     325              :     }
     326              : 
     327          927 :     bool isHangingSlur = sst == SpannerSegmentType::BEGIN || sst == SpannerSegmentType::END || incomingPartialSlur
     328         1872 :                          || outgoingPartialSlur;
     329          945 :     if (isHangingSlur && ctx.conf().styleB(Sid::angleHangingSlursAwayFromStaff)) {
     330            0 :         adjustSlurFloatingEndPointAngles(slurSegment, p1, p2, incomingPartialSlur, outgoingPartialSlur);
     331              :     }
     332              : 
     333          945 :     layoutSegment(slurSegment,  p1, p2);
     334              : 
     335          945 :     return slurSegment;
     336              : }
     337              : 
     338            0 : void SlurTieLayout::adjustSlurFloatingEndPointAngles(SlurSegment* slurSeg, PointF& p1, PointF& p2, bool incomingPartial,
     339              :                                                      bool outgoingPartial)
     340              : {
     341            0 :     bool startIsHanging = slurSeg->spannerSegmentType() == SpannerSegmentType::END || incomingPartial;
     342            0 :     bool endIsHanging = slurSeg->spannerSegmentType() == SpannerSegmentType::BEGIN || outgoingPartial;
     343              : 
     344            0 :     IF_ASSERT_FAILED(startIsHanging != endIsHanging) {
     345            0 :         return;
     346              :     }
     347              : 
     348            0 :     bool up = slurSeg->slur()->up();
     349            0 :     const double heightDiff = 1.0 * slurSeg->spatium();
     350              : 
     351            0 :     if (startIsHanging) {
     352            0 :         double yCur = p1.y();
     353            0 :         p1.setY(up ? std::min(yCur, p2.y() - heightDiff) : std::max(yCur, p2.y() + heightDiff));
     354            0 :     } else if (endIsHanging) {
     355            0 :         double yCur = p2.y();
     356            0 :         p2.setY(up ? std::min(yCur, p1.y() - heightDiff) : std::max(yCur, p1.y() + heightDiff));
     357              :     }
     358              : }
     359              : 
     360          625 : double SlurTieLayout::endingXForOpenEndedSlurTie(const Measure* measure, staff_idx_t staffIdx)
     361              : {
     362          625 :     double endingX = measure->endingXForOpenEndedLines();
     363              : 
     364          625 :     const SegmentType segmentTypesToAvoid = SegmentType::TimeSigTypes | SegmentType::KeySigTypes | SegmentType::ClefTypes;
     365              : 
     366              :     // Find the first segment at the end of the measure which meets the criteria for the SlurTie to stop before it:
     367          625 :     const Segment* endSegment = measure->findSegmentR(segmentTypesToAvoid, measure->ticks());
     368          625 :     const EngravingItem* endItem = nullptr;
     369          627 :     while (endSegment) {
     370            2 :         if (endSegment->isType(segmentTypesToAvoid) && endSegment->enabled()) {
     371            0 :             endItem = endSegment->element(staff2track(staffIdx));
     372            0 :             if (endItem && endItem->visible() && endItem->addToSkyline()) {
     373            0 :                 break;
     374              :             }
     375              :         }
     376            2 :         endSegment = endSegment->next();
     377              :     }
     378              : 
     379          625 :     if (!endSegment || !endItem) {
     380          625 :         return endingX;
     381              :     }
     382              : 
     383            0 :     const double margin = endItem->style().styleAbsolute(Sid::lineEndToBarlineDistance);
     384            0 :     const double itemLeftX = measure->x() + endSegment->x() + endItem->ldata()->shape().translated(endItem->pos()).left();
     385              : 
     386            0 :     return std::min(endingX, itemLeftX - margin);
     387              : }
     388              : 
     389              : //---------------------------------------------------------
     390              : //   slurPos
     391              : //    calculate position of start- and endpoint of slur
     392              : //    relative to System() position
     393              : //---------------------------------------------------------
     394              : 
     395          945 : void SlurTieLayout::slurPos(Slur* item, SlurTiePos* sp, LayoutContext& ctx)
     396              : {
     397          945 :     item->stemFloated().reset();
     398          945 :     double _spatium = (item->staffType() ? item->staffType()->lineDistance().val() : 1.0) * item->spatium();
     399          945 :     const double stemSideInset = 0.5;
     400          945 :     const double stemOffsetX = 0.35;
     401          945 :     const double beamClearance = 0.35;
     402          945 :     const double beamAnchorInset = 0.15;
     403          945 :     const double straightStemXOffset = 0.5; // how far down a straight stem a slur attaches (percent)
     404          945 :     const double minOffset = 0.2;
     405              :     // hack alert!! -- fakeCutout
     406              :     // The fakeCutout const describes the slope of a line from the top of the stem to the full width of the hook.
     407              :     // this is necessary because hooks don't have SMuFL cutouts
     408              :     // Gonville and MuseJazz have really weirdly-shaped hooks compared to Leland and Bravura and Emmentaler,
     409              :     // so we need to adjust the slope of our hook-avoidance line. this will be unnecessary when hooks have
     410              :     // SMuFL anchors
     411          945 :     const std::string fontName = muse::strings::toLower(ctx.engravingFont()->name());
     412          945 :     bool bulkyHook = fontName == "gonville" || fontName == "musejazz";
     413          945 :     const double fakeCutoutSlope = bulkyHook ? 1.5 : 1.0;
     414              : 
     415          945 :     if (item->endCR() == 0) {
     416            0 :         sp->p1 = item->startCR()->pagePos();
     417            0 :         sp->p1.rx() += item->startCR()->width();
     418            0 :         sp->p2 = sp->p1;
     419            0 :         sp->p2.rx() += 5 * _spatium;
     420            0 :         sp->system1 = item->startCR()->measure()->system();
     421            0 :         sp->system2 = sp->system1;
     422            0 :         return;
     423              :     }
     424              : 
     425          945 :     bool useTablature = item->staff() && item->staff()->isTabStaff(item->endCR()->tick());
     426          945 :     bool useJianpu = item->onJianpuStaff();
     427          945 :     bool staffHasStems = useJianpu ? false : true; // assume staff uses stems except jianpu
     428          945 :     const StaffType* stt = 0;
     429          945 :     if (useTablature) {
     430           31 :         stt = item->staff()->staffType(item->tick());
     431           31 :         staffHasStems = stt->stemThrough();       // if tab with stems beside, stems do not count for slur pos
     432              :     }
     433              : 
     434              :     // start and end cr, chord, and note
     435          945 :     ChordRest* scr = item->startCR();
     436          945 :     ChordRest* ecr = item->endCR();
     437          945 :     Chord* sc = 0;
     438          945 :     Note* note1 = 0;
     439          945 :     if (scr->isChord()) {
     440          945 :         sc = toChord(scr);
     441          945 :         note1 = item->up() || useJianpu ? sc->upNote() : sc->downNote();
     442              :     }
     443          945 :     Chord* ec = 0;
     444          945 :     Note* note2 = 0;
     445          945 :     if (ecr->isChord()) {
     446          932 :         ec = toChord(ecr);
     447          932 :         note2 = item->up() || useJianpu ? ec->upNote() : ec->downNote();
     448              :     }
     449              : 
     450          945 :     sp->system1 = scr->measure()->system();
     451          945 :     sp->system2 = ecr->measure()->system();
     452              : 
     453          945 :     if (sp->system1 == 0) {
     454            0 :         LOGD("no system1");
     455            0 :         return;
     456              :     }
     457              : 
     458          945 :     sp->p1 = scr->pos() + scr->segment()->pos() + scr->measure()->pos();
     459          945 :     sp->p2 = ecr->pos() + ecr->segment()->pos() + ecr->measure()->pos();
     460          945 :     if (scr->isGrace()) {
     461           49 :         sp->p1 += scr->layoutParent()->pos();
     462              :     }
     463          945 :     if (ecr->isGrace()) {
     464           38 :         sp->p2 += ecr->layoutParent()->pos();
     465              :     }
     466              : 
     467              :     // adjust for cross-staff
     468          945 :     if (scr->vStaffIdx() != item->vStaffIdx() && sp->system1) {
     469            9 :         double diff = sp->system1->staff(scr->vStaffIdx())->y() - sp->system1->staff(item->vStaffIdx())->y();
     470            9 :         sp->p1.ry() += diff;
     471              :     }
     472          945 :     if (ecr->vStaffIdx() != item->vStaffIdx() && sp->system2) {
     473           21 :         double diff = sp->system2->staff(ecr->vStaffIdx())->y() - sp->system2->staff(item->vStaffIdx())->y();
     474           21 :         sp->p2.ry() += diff;
     475              :     }
     476              : 
     477              :     // account for centering or other adjustments (other than mirroring)
     478          945 :     if (note1 && !note1->ldata()->mirror.value()) {
     479          945 :         sp->p1.rx() += note1->x();
     480              :     }
     481          945 :     if (note2 && !note2->ldata()->mirror.value()) {
     482          932 :         sp->p2.rx() += note2->x();
     483              :     }
     484              : 
     485          945 :     PointF po = PointF();
     486              : 
     487          945 :     Stem* stem1 = sc && staffHasStems ? sc->stem() : 0;
     488          945 :     Stem* stem2 = ec && staffHasStems ? ec->stem() : 0;
     489              : 
     490              :     enum class SlurAnchor : char {
     491              :         NONE, STEM
     492              :     };
     493          945 :     SlurAnchor sa1 = SlurAnchor::NONE;
     494          945 :     SlurAnchor sa2 = SlurAnchor::NONE;
     495          945 :     if (staffHasStems) {
     496          915 :         if (sc && sc->hook() && sc->up() == item->up()) {
     497            6 :             sa1 = SlurAnchor::STEM;
     498              :         }
     499          915 :         if (scr->up() == ecr->up() && scr->up() == item->up()) {
     500          121 :             if (stem1 && !stemSideStartForBeam(item)) {
     501           93 :                 sa1 = SlurAnchor::STEM;
     502              :             }
     503          121 :             if (stem2 && !stemSideEndForBeam(item)) {
     504           93 :                 sa2 = SlurAnchor::STEM;
     505              :             }
     506          794 :         } else if (ecr->segment()->system() != scr->segment()->system()) {
     507              :             // in the case of continued slurs, we anchor to stem when necessary
     508           34 :             if (scr->up() == item->up() && stem1 && !scr->beam()) {
     509           12 :                 sa1 = SlurAnchor::STEM;
     510              :             }
     511           34 :             if (ecr->up() == item->up() && stem2 && !ecr->beam()) {
     512            0 :                 sa2 = SlurAnchor::STEM;
     513              :             }
     514              :         }
     515              :     }
     516              : 
     517          945 :     double __up = item->up() ? -1.0 : 1.0;
     518          945 :     double hw1 = note1 ? note1->tabHeadWidth(stt) : scr->width() * scr->mag();        // if stt == 0, tabHeadWidth()
     519          945 :     double hw2 = note2 ? note2->tabHeadWidth(stt) : ecr->width() * ecr->mag();        // defaults to headWidth()
     520          945 :     PointF pt;
     521          945 :     switch (sa1) {
     522          110 :     case SlurAnchor::STEM:                //sc can't be null
     523              :     {
     524              :         // place slur starting point at stem end point
     525          110 :         pt = StemLayout::stemPos(sc) - sc->pagePos() + sc->stem()->ldata()->line.p2();
     526          110 :         if (useTablature) {                           // in tabs, stems are centred on note:
     527            0 :             pt.rx() = hw1 * 0.5 + (note1 ? note1->bboxXShift() : 0.0);                      // skip half notehead to touch stem, anatoly-os: incorrect. half notehead width is not always the stem position
     528              :         }
     529              :         // clear the stem (x)
     530              :         // allow slight overlap (y)
     531              :         // don't allow overlap with hook if not disabling the autoplace checks against start/end segments in SlurSegment::layoutSegment()
     532          110 :         double yadj = -stemSideInset* sc->intrinsicMag();
     533          110 :         yadj *= _spatium * __up;
     534          110 :         double offset = std::max(stemOffsetX * sc->intrinsicMag(), minOffset);
     535          110 :         pt += PointF(offset * _spatium, yadj);
     536              :         // account for articulations
     537          110 :         fixArticulations(item, pt, sc, __up, true);
     538              :         // adjust for hook
     539          110 :         double fakeCutout = 0.0;
     540          110 :         if (!ctx.conf().styleB(Sid::useStraightNoteFlags)) {
     541          110 :             Hook* hook = sc->hook();
     542              :             // regular flags
     543              : 
     544          110 :             if (hook && hook->ldata()->bbox().translated(hook->pos()).contains(pt)) {
     545              :                 // TODO: in the utopian far future where all hooks have SMuFL cutouts, this fakeCutout business will no
     546              :                 // longer be used. for the time being fakeCutout describes a point on the line y=mx+b, out from the top of the stem
     547              :                 // where y = yadj, m = fakeCutoutSlope, and x = y/m + fakeCutout
     548            6 :                 fakeCutout = std::min(0.0, std::abs(yadj) - (hook->width() / fakeCutoutSlope));
     549            6 :                 pt.rx() = StemLayout::stemPosX(sc) - fakeCutout;
     550              :             }
     551              :         } else {
     552            0 :             Hook* hook = sc->hook();
     553              :             // straight flags
     554            0 :             if (hook && hook->ldata()->bbox().translated(hook->pos()).contains(pt)) {
     555            0 :                 double hookWidth = hook->width() * hook->mag();
     556            0 :                 pt.rx() = (hookWidth * straightStemXOffset) + (hook->pos().x() + sc->x());
     557            0 :                 if (item->up()) {
     558            0 :                     pt.ry() = sc->downNote()->pos().y() - stem1->height() - (beamClearance * _spatium * .7);
     559              :                 } else {
     560            0 :                     pt.ry() = sc->upNote()->pos().y() + stem1->height() + (beamClearance * _spatium * .7);
     561              :                 }
     562              :             }
     563              :         }
     564          110 :         sp->p1 += pt;
     565              :     }
     566          110 :     break;
     567          835 :     case SlurAnchor::NONE:
     568          835 :         break;
     569              :     }
     570          945 :     switch (sa2) {
     571           93 :     case SlurAnchor::STEM:                //ec can't be null
     572              :     {
     573           93 :         pt = StemLayout::stemPos(ec) - ec->pagePos() + ec->stem()->ldata()->line.p2();
     574           93 :         if (useTablature) {
     575            0 :             pt.rx() = hw2 * 0.5;
     576              :         }
     577              :         // don't allow overlap with beam
     578              :         double yadj;
     579           93 :         if (ec->beam() && ec->beam()->elements().front() != ec) {
     580            0 :             yadj = 0.75;
     581           93 :         } else if (ec->tremoloTwoChord() && ec->tremoloTwoChord()->chord2() == ec) {
     582            0 :             yadj = 0.75;
     583              :         } else {
     584           93 :             yadj = -stemSideInset;
     585              :         }
     586           93 :         yadj *= _spatium * __up;
     587           93 :         double offset = std::max(stemOffsetX * ec->intrinsicMag(), minOffset);
     588           93 :         pt += PointF(-offset * _spatium, yadj);
     589              :         // account for articulations
     590           93 :         fixArticulations(item, pt, ec, __up, true);
     591           93 :         sp->p2 += pt;
     592              :     }
     593           93 :     break;
     594          852 :     case SlurAnchor::NONE:
     595          852 :         break;
     596              :     }
     597              : 
     598              :     // Slur for jianpu is always horizontal
     599          945 :     double jianpuY = 0.0;
     600          945 :     if (useJianpu) {
     601            0 :         if (item->up()) {
     602            0 :             jianpuY = std::min(scr->ldata()->bbox().top(), ecr->ldata()->bbox().top());
     603              :         } else {
     604            0 :             jianpuY = std::max(scr->ldata()->bbox().bottom(), ecr->ldata()->bbox().bottom());
     605              :         }
     606              :     }
     607              : 
     608              :     //
     609              :     // default position:
     610              :     //    horizontal: middle of notehead
     611              :     //    vertical:   _spatium * .4 above/below notehead
     612              :     //
     613              :     //------p1
     614              :     // Compute x0, y0 and stemPos
     615          945 :     if (sa1 == SlurAnchor::NONE || sa2 == SlurAnchor::NONE) {   // need stemPos if sa2 == SlurAnchor::NONE
     616          854 :         bool stemPos = false;       // p1 starts at chord stem side
     617              : 
     618              :         // default positions
     619          854 :         po.rx() = hw1 * .5 + (note1 ? note1->bboxXShift() : 0.0);
     620          854 :         if (useJianpu) {
     621            0 :             po.ry() = jianpuY;
     622          854 :         } else if (note1) {
     623          854 :             po.ry() = note1->pos().y();
     624            0 :         } else if (item->up()) {
     625            0 :             po.ry() = scr->ldata()->bbox().top();
     626              :         } else {
     627            0 :             po.ry() = scr->ldata()->bbox().top() + scr->height();
     628              :         }
     629          854 :         double offset = useTablature ? 0.75 : 0.9;
     630          854 :         po.ry() += scr->intrinsicMag() * _spatium * offset * __up;
     631              : 
     632              :         // adjustments for stem and/or beam
     633          854 :         TremoloTwoChord* trem = sc ? sc->tremoloTwoChord() : nullptr;
     634          854 :         if (stem1 || trem) {     //sc not null
     635          780 :             Beam* beam1 = sc->beam();
     636          780 :             if (stem1 && beam1 && (beam1->elements().back() != sc) && (sc->up() == item->up())) {
     637           34 :                 TLayout::layoutBeam(beam1, ctx);
     638              :                 // start chord is beamed but not the last chord of beam group
     639              :                 // and slur direction is same as start chord (stem side)
     640              : 
     641              :                 // in these cases, layout start of slur to stem
     642           34 :                 double beamWidthSp = ctx.conf().styleS(Sid::beamWidth).val() * beam1->magS();
     643           34 :                 double offset2 = std::max(beamClearance * sc->intrinsicMag(), minOffset) * _spatium;
     644           34 :                 double sh = stem1->length() + (beamWidthSp / 2) + offset2;
     645           34 :                 if (item->up()) {
     646           27 :                     po.ry() = StemLayout::stemPos(sc).y() - sc->pagePos().y() - sh;
     647              :                 } else {
     648            7 :                     po.ry() = StemLayout::stemPos(sc).y() - sc->pagePos().y() + sh;
     649              :                 }
     650           34 :                 po.rx() = StemLayout::stemPosX(sc) + (beamAnchorInset * _spatium * sc->intrinsicMag()) + (stem1->lineWidthMag() / 2 * __up);
     651              : 
     652              :                 // account for articulations
     653           34 :                 fixArticulations(item, po, sc, __up, true);
     654              : 
     655              :                 // force end of slur to layout to stem as well,
     656              :                 // if start and end chords have same stem direction
     657           34 :                 stemPos = true;
     658          746 :             } else if (trem && trem->chord2() != sc && sc->up() == item->up()) {
     659            0 :                 TremoloLayout::layout(trem, ctx);
     660            0 :                 Note* note = item->up() ? sc->upNote() : sc->downNote();
     661            0 :                 double stemHeight = stem1 ? stem1->length() : defaultStemLengthStart(trem);
     662            0 :                 double offset2 = std::max(beamClearance * sc->intrinsicMag(), minOffset) * _spatium;
     663            0 :                 double sh = stemHeight + offset2;
     664              : 
     665            0 :                 if (item->up()) {
     666            0 :                     po.ry() = StemLayout::stemPos(sc).y() - sc->pagePos().y() - sh;
     667              :                 } else {
     668            0 :                     po.ry() = StemLayout::stemPos(sc).y() - sc->pagePos().y() + sh;
     669              :                 }
     670            0 :                 if (!stem1) {
     671            0 :                     po.rx() = note->noteheadCenterX();
     672              :                 } else {
     673            0 :                     po.rx() = StemLayout::stemPosX(sc) + (beamAnchorInset * _spatium * sc->intrinsicMag())
     674            0 :                               + (stem1->lineWidthMag() / 2. * __up);
     675              :                 }
     676            0 :                 fixArticulations(item, po, sc, __up, true);
     677              : 
     678            0 :                 stemPos = true;
     679              :             } else {
     680              :                 // start chord is not beamed or is last chord of beam group
     681              :                 // or slur direction is opposite that of start chord
     682              : 
     683              :                 // at this point slur is in default position relative to note on slur side
     684              :                 // but we may need to make further adjustments
     685              : 
     686              :                 // if stem and slur are both up
     687              :                 // we need to clear stem horizontally
     688          746 :                 double stemOffsetMag = stemOffsetX * sc->intrinsicMag();
     689          746 :                 if (sc->up() && item->up()) {
     690              :                     // stems in tab staves come from the middle of the head, which means it's much easier
     691              :                     // to just subtract an offset from the notehead center (which po already is)
     692           57 :                     if (useTablature) {
     693            0 :                         po.rx() += stemOffsetMag * _spatium;
     694              :                     } else {
     695           57 :                         po.rx() = hw1 + _spatium * stemOffsetMag;
     696              :                     }
     697              :                 }
     698              : 
     699              :                 //
     700              :                 // handle case: stem up   - stem down
     701              :                 //              stem down - stem up
     702              :                 //
     703          746 :                 if ((sc->up() != ecr->up()) && (sc->up() == item->up())) {
     704           59 :                     item->stemFloated().left = true;
     705              :                     // start and end chord have opposite direction
     706              :                     // and slur direction is same as start chord
     707              :                     // (so slur starts on stem side)
     708              : 
     709              :                     // float the start point along the stem to follow direction of movement
     710              :                     // see for example Gould p. 111
     711              : 
     712              :                     // get position of note on slur side for start & end chords
     713           59 :                     Note* n1  = sc->up() ? sc->upNote() : sc->downNote();
     714           59 :                     Note* n2  = 0;
     715           59 :                     if (ec) {
     716           59 :                         n2 = ec->up() ? ec->upNote() : ec->downNote();
     717              :                     }
     718              : 
     719              :                     // differential in note positions
     720           59 :                     double yd  = (n2 ? n2->pos().y() : ecr->pos().y()) - n1->pos().y();
     721           59 :                     yd *= .5;
     722              : 
     723              :                     // float along stem according to differential
     724           59 :                     double sh = stem1 ? stem1->height() : 0.0;
     725           59 :                     if (item->up() && yd < 0.0) {
     726           45 :                         po.ry() = std::max(po.y() + yd, sc->downNote()->pos().y() - sh - _spatium);
     727           14 :                     } else if (!item->up() && yd > 0.0) {
     728            0 :                         po.ry() = std::min(po.y() + yd, sc->upNote()->pos().y() + sh + _spatium);
     729              :                     }
     730              : 
     731              :                     // account for articulations
     732           59 :                     fixArticulations(item, po, sc, __up, true);
     733              : 
     734              :                     // we may wish to force end to align to stem as well,
     735              :                     // if it is in same direction
     736              :                     // (but it won't be, so this assignment should have no effect)
     737           59 :                     stemPos = true;
     738              :                 } else {
     739              :                     // avoid articulations
     740          687 :                     fixArticulations(item, po, sc, __up, sc->up() == item->up());
     741              :                 }
     742              :             }
     743          854 :         } else if (sc) {
     744              :             // avoid articulations
     745           74 :             fixArticulations(item, po, sc, __up, sc->up() == item->up());
     746              :         }
     747              : 
     748              :         // TODO: offset start position if there is another slur ending on this cr
     749              : 
     750          854 :         if (sa1 == SlurAnchor::NONE) {
     751          835 :             sp->p1 += po;
     752              :         }
     753              : 
     754              :         //------p2
     755          854 :         if (sa2 == SlurAnchor::NONE) {
     756              :             // default positions
     757          852 :             po.rx() = hw2 * .5 + (note2 ? note2->bboxXShift() : 0.0);
     758          852 :             if (useJianpu) {
     759            0 :                 po.ry() = jianpuY;
     760          852 :             } else if (note2) {
     761          839 :                 po.ry() = note2->pos().y();
     762           13 :             } else if (item->up()) {
     763            0 :                 po.ry() = item->endCR()->ldata()->bbox().top();
     764              :             } else {
     765           13 :                 po.ry() = item->endCR()->ldata()->bbox().top() + item->endCR()->height();
     766              :             }
     767          852 :             double offset2 = useTablature ? 0.75 : 0.9;
     768          852 :             po.ry() += ecr->intrinsicMag() * _spatium * offset2 * __up;
     769              : 
     770              :             // adjustments for stem and/or beam
     771          852 :             TremoloTwoChord* trem2 = ec ? ec->tremoloTwoChord() : nullptr;
     772          852 :             if (stem2 || trem2) {       //ec can't be null
     773          752 :                 Beam* beam2 = ec->beam();
     774           89 :                 if ((stemPos && (scr->up() == ec->up()))
     775          728 :                     || (beam2
     776          219 :                         && (!beam2->elements().empty())
     777          219 :                         && (beam2->elements().front() != ec)
     778          136 :                         && (ec->up() == item->up())
     779            4 :                         && sc && (sc->noteType() == NoteType::NORMAL)
     780              :                         )
     781         1504 :                     || (trem2 && ec->up() == item->up())
     782              :                     ) {
     783           28 :                     if (beam2) {
     784           28 :                         TLayout::layoutBeam(beam2, ctx);
     785              :                     }
     786           28 :                     if (trem2) {
     787            0 :                         TremoloLayout::layout(trem2, ctx);
     788              :                     }
     789              :                     // slur start was laid out to stem and start and end have same direction
     790              :                     // OR
     791              :                     // end chord is beamed but not the first chord of beam group
     792              :                     // and slur direction is same as end chord (stem side)
     793              :                     // and start chordrest is not a grace chord
     794              : 
     795              :                     // in these cases, layout end of slur to stem
     796           28 :                     double beamWidthSp = beam2 ? ctx.conf().styleS(Sid::beamWidth).val() : 0;
     797           28 :                     Note* note = item->up() ? ec->upNote() : ec->downNote();
     798           28 :                     double stemHeight = stem2 ? stem2->length() + (beamWidthSp / 2) : defaultStemLengthEnd(trem2);
     799           28 :                     double offset3 = std::max(beamClearance * ec->intrinsicMag(), minOffset) * _spatium;
     800           28 :                     double sh = stemHeight + offset3;
     801              : 
     802           28 :                     if (item->up()) {
     803           21 :                         po.ry() = StemLayout::stemPos(ec).y() - ec->pagePos().y() - sh;
     804              :                     } else {
     805            7 :                         po.ry() = StemLayout::stemPos(ec).y() - ec->pagePos().y() + sh;
     806              :                     }
     807           28 :                     if (!stem2) {
     808              :                         // tremolo whole notes
     809            0 :                         po.setX(note->noteheadCenterX());
     810              :                     } else {
     811           28 :                         po.setX(StemLayout::stemPosX(ec) + (stem2->lineWidthMag() / 2 * __up)
     812           28 :                                 - (beamAnchorInset * _spatium * ec->intrinsicMag()));
     813              :                     }
     814              : 
     815              :                     // account for articulations
     816           28 :                     fixArticulations(item, po, ec, __up, true);
     817              :                 } else {
     818              :                     // slur was not aligned to stem or start and end have different direction
     819              :                     // AND
     820              :                     // end chord is not beamed or is first chord of beam group
     821              :                     // or slur direction is opposite that of end chord
     822              : 
     823              :                     // if stem and slur are both down,
     824              :                     // we need to clear stem horizontally
     825          724 :                     double stemOffsetMag = stemOffsetX * ec->intrinsicMag();
     826          724 :                     if (!ec->up() && !item->up()) {
     827              :                         // stems in tab staves come from the middle of the head, which means it's much easier
     828              :                         // to just subtract an offset from the notehead center (which po already is)
     829           17 :                         if (useTablature) {
     830            0 :                             po.rx() -= stemOffsetMag * _spatium;
     831              :                         } else {
     832           17 :                             po.rx() = -_spatium * stemOffsetMag + note2->x();
     833              :                         }
     834          707 :                     } else if (useTablature && item->up() && ec->up()) {
     835              :                         // same as above
     836            0 :                         po.rx() -= _spatium * stemOffsetMag;
     837              :                     }
     838              : 
     839              :                     //
     840              :                     // handle case: stem up   - stem down
     841              :                     //              stem down - stem up
     842              :                     //
     843          724 :                     if ((scr->up() != ec->up()) && (ec->up() == item->up())) {
     844           46 :                         item->stemFloated().right = true;
     845              :                         // start and end chord have opposite direction
     846              :                         // and slur direction is same as end chord
     847              :                         // (so slur end on stem side)
     848              : 
     849              :                         // float the end point along the stem to follow direction of movement
     850              :                         // see for example Gould p. 111
     851              : 
     852           46 :                         Note* n1 = 0;
     853           46 :                         if (sc) {
     854           46 :                             n1 = sc->up() ? sc->upNote() : sc->downNote();
     855              :                         }
     856           46 :                         Note* n2 = ec->up() ? ec->upNote() : ec->downNote();
     857              : 
     858           46 :                         double yd = n2->pos().y() - (n1 ? n1->pos().y() : item->startCR()->pos().y());
     859           46 :                         yd *= .5;
     860              : 
     861           46 :                         double mh = stem2 ? stem2->height() : 0.0;
     862           46 :                         if (item->up() && yd > 0.0) {
     863           26 :                             po.ry() = std::max(po.y() - yd, ec->downNote()->pos().y() - mh - _spatium);
     864           20 :                         } else if (!item->up() && yd < 0.0) {
     865           15 :                             po.ry() = std::min(po.y() - yd, ec->upNote()->pos().y() + mh + _spatium);
     866              :                         }
     867              : 
     868              :                         // account for articulations
     869           46 :                         fixArticulations(item, po, ec, __up, true);
     870              :                     } else {
     871              :                         // avoid articulations
     872          678 :                         fixArticulations(item, po, ec, __up, ec->up() == item->up());
     873              :                     }
     874              :                 }
     875          852 :             } else if (ec) {
     876              :                 // avoid articulations
     877           87 :                 fixArticulations(item, po, ec, __up, ec->up() == item->up());
     878              :             }
     879              :             // TODO: offset start position if there is another slur ending on this cr
     880          852 :             sp->p2 += po;
     881              :         }
     882              :     }
     883              : 
     884          945 :     if (item->staffType()->isTabStaff()) {
     885           31 :         SlurTieLayout::avoidPreBendsOnTab(sc, ec, sp);
     886              :     }
     887              : 
     888          945 :     if (item->isTappingHalfSlur()) {
     889           32 :         adjustForTappingHalfSlurs(toTappingHalfSlur(item), sp, note2);
     890              :     }
     891          945 : }
     892              : 
     893           32 : void SlurTieLayout::adjustForTappingHalfSlurs(TappingHalfSlur* item, SlurTiePos* sp, Note* endNote)
     894              : {
     895           32 :     if (item->staffType()->isTabStaff()) {
     896           16 :         return;
     897              :     }
     898              : 
     899           16 :     int staffLines = endNote->staff()->lines(endNote->tick());
     900           16 :     bool noteIsInsideStaff = endNote->line() > 1 && endNote->line() < 2 * (staffLines - 1) - 1;
     901           16 :     bool noteIsOnSpace = endNote->line() % 2 != 0;
     902           16 :     if (noteIsInsideStaff && noteIsOnSpace) {
     903            0 :         sp->p2.ry() += (item->up() ? 0.2 : -0.2) * item->spatium();
     904              :     }
     905              : }
     906              : 
     907         1896 : void SlurTieLayout::fixArticulations(Slur* item, PointF& pt, Chord* c, double up, bool stemSide)
     908              : {
     909              :     //
     910              :     // handle special case of tenuto and staccato
     911              :     // yo = current offset of slur from chord position
     912              :     // return unchanged position, or position of outmost "close" articulation
     913              :     //
     914         1896 :     double slurTipToArticVertDist = c->spatium() * 0.5 * up;
     915         1896 :     double slurTipInwardAdjust = 0.1 * item->spatium();
     916         1896 :     bool start = item->startCR() && item->startCR() == c;
     917         1896 :     bool end = item->endCR() && item->endCR() == c;
     918         1996 :     for (Articulation* a : c->articulations()) {
     919          100 :         if (!a->layoutCloseToNote() || !a->addToSkyline()) {
     920           70 :             continue;
     921              :         }
     922              :         // skip if articulation on stem side but slur is not or vice versa
     923           30 :         if ((a->up() == c->up()) != stemSide) {
     924            0 :             continue;
     925              :         }
     926              :         // Correct x-position inwards
     927           30 :         Note* note = c->up() ? c->downNote() : c->upNote();
     928           30 :         pt.rx() = a->x() + 0.5 * a->width() - note->x();
     929           30 :         if (start) {
     930           13 :             pt.rx() += slurTipInwardAdjust;
     931           17 :         } else if (end) {
     932           17 :             pt.rx() -= slurTipInwardAdjust;
     933              :         }
     934              :         // Adjust y-position
     935           30 :         if (a->up()) {
     936           12 :             pt.ry() = std::min(pt.y(), a->y() + a->height() / 2 * up + slurTipToArticVertDist);
     937              :         } else {
     938           18 :             pt.ry() = std::max(pt.y(), a->y() + a->height() / 2 * up + slurTipToArticVertDist);
     939              :         }
     940              :     }
     941         1896 : }
     942              : 
     943         1932 : void SlurTieLayout::adjustEndPoints(SlurSegment* slurSeg)
     944              : {
     945         1932 :     double spatium = slurSeg->spatium();
     946         1932 :     double lw = (slurSeg->staffType() ? slurSeg->staffType()->lineDistance().val() : 1.0) * spatium;
     947         1932 :     const double staffLineMargin = 0.175 + (0.5 * slurSeg->style().styleS(Sid::staffLineWidth).val() * (spatium / lw));
     948         1932 :     PointF p1 = slurSeg->ups(Grip::START).p;
     949         1932 :     PointF p2 = slurSeg->ups(Grip::END).p;
     950              : 
     951         1932 :     double y1sp = p1.y() / lw;
     952         1932 :     double y2sp = p2.y() / lw;
     953              : 
     954              :     // point 1
     955         1932 :     const Staff* staff = slurSeg->staff();
     956         1932 :     int lines = staff ? staff->lines(slurSeg->tick()) : 0;
     957         1874 :     auto adjustPoint = [staffLineMargin](bool up, double ysp) {
     958         1874 :         double y1offset = ysp - floor(ysp);
     959         1874 :         double adjust = 0;
     960         1874 :         if (up) {
     961          966 :             if (y1offset < staffLineMargin) {
     962              :                 // endpoint too close to the line above
     963          174 :                 adjust = -(y1offset + staffLineMargin);
     964          792 :             } else if (y1offset > 1 - staffLineMargin) {
     965              :                 // endpoint too close to the line below
     966           81 :                 adjust = -(y1offset - (1 - staffLineMargin));
     967              :             }
     968              :         } else {
     969          908 :             if (y1offset < staffLineMargin) {
     970              :                 // endpoint too close to the line above
     971          241 :                 adjust = staffLineMargin - y1offset;
     972              :             }
     973          908 :             if (y1offset > 1 - staffLineMargin) {
     974              :                 // endpoint too close to the line below
     975          238 :                 adjust = (1 - y1offset) + staffLineMargin;
     976              :             }
     977              :         }
     978         1874 :         return adjust;
     979         1932 :     };
     980         1932 :     if (y1sp > -staffLineMargin && y1sp < (lines - 1) + staffLineMargin) {
     981          984 :         slurSeg->ups(Grip::START).p.ry() += adjustPoint(slurSeg->slur()->up(), y1sp) * lw;
     982              :     }
     983         1932 :     if (y2sp > -staffLineMargin && y2sp < (lines - 1) + staffLineMargin) {
     984          890 :         slurSeg->ups(Grip::END).p.ry() += adjustPoint(slurSeg->slur()->up(), y2sp) * lw;
     985              :     }
     986         1932 : }
     987              : 
     988          931 : void SlurTieLayout::avoidCollisions(SlurSegment* slurSeg, PointF& pp1, PointF& p2, PointF& p3, PointF& p4,
     989              :                                     Transform& toSystemCoordinates, double& slurAngle)
     990              : {
     991          940 :     TRACEFUNC;
     992          931 :     Slur* slur = slurSeg->slur();
     993          931 :     double spatium = slurSeg->spatium();
     994          931 :     double slurLength = std::abs(p2.x() / spatium);
     995          931 :     bool slurUp = slur->up();
     996          931 :     int upSign = slurUp ? -1 : 1;
     997              : 
     998          931 :     ChordRest* startCR = slur->startCR();
     999          931 :     ChordRest* endCR = slur->endCR();
    1000              : 
    1001          931 :     if (!startCR || !endCR) {
    1002            0 :         return;
    1003              :     }
    1004              : 
    1005          931 :     Shape segShapes = getSegmentShapes(slurSeg, startCR, endCR); // Shape of the music under this slur
    1006          931 :     addMinClearanceToShapes(segShapes, spatium, slurUp, startCR, endCR);
    1007              : 
    1008          931 :     if (segShapes.empty()) {
    1009           30 :         return;
    1010              :     }
    1011              : 
    1012          901 :     const double arcClearance = -upSign* computeArcClearance(spatium, slurLength, slurAngle);  // Collision clearance at the center of the slur
    1013              : 
    1014              :     // balance: determines how much endpoint adjustment VS shape adjustment we will do.
    1015              :     // 0 = end point is fixed, only the shape can be adjusted,
    1016              :     // 1 = shape is fixed, only end the point can be adjusted.
    1017          901 :     double leftBalance = 0.0;
    1018          901 :     double rightBalance = 0.0;
    1019          901 :     computeAdjustmentBalance(slurSeg, startCR, endCR, leftBalance, rightBalance);
    1020              : 
    1021              :     static constexpr unsigned MAX_ITER = 30;     // Max iterations allowed
    1022              : 
    1023          901 :     double step = computeAdjustmentStep(upSign, spatium, slurLength);
    1024              : 
    1025              :     // Divide slur in several rectangles to localize collisions
    1026          901 :     const unsigned npoints = 20;
    1027          901 :     std::vector<RectF> slurRects;
    1028          901 :     slurRects.reserve(npoints);
    1029              : 
    1030              :     // Define separate collision areas (left-mid-center)
    1031              :     struct SlurCollision
    1032              :     {
    1033              :         bool left = false;
    1034              :         bool mid = false;
    1035              :         bool right = false;
    1036              : 
    1037         2106 :         void reset()
    1038              :         {
    1039         2106 :             left = false;
    1040         2106 :             mid = false;
    1041         2106 :             right = false;
    1042         2106 :         }
    1043              :     };
    1044          901 :     SlurCollision collision;
    1045              : 
    1046              :     // CHECK FOR COLLISIONS
    1047          901 :     unsigned iter = 0;
    1048              :     do {
    1049         2106 :         collision.reset();
    1050              :         // Update tranform because pp1 may change
    1051         2106 :         toSystemCoordinates.reset();
    1052         2106 :         toSystemCoordinates.translate(pp1.x(), pp1.y());
    1053         2106 :         toSystemCoordinates.rotateRadians(slurAngle);
    1054              :         // Create rectangles
    1055         2106 :         slurRects.clear();
    1056         2106 :         CubicBezier clearanceBezier(PointF(0, 0), p3 + PointF(0.0, arcClearance), p4 + PointF(0.0, arcClearance), p2);
    1057        42120 :         for (unsigned i = 0; i < npoints - 1; i++) {
    1058        40014 :             PointF clearancePoint1 = clearanceBezier.pointAtPercent(double(i) / double(npoints));
    1059        40014 :             PointF clearancePoint2 = clearanceBezier.pointAtPercent(double(i + 1) / double(npoints));
    1060        40014 :             clearancePoint1 = toSystemCoordinates.map(clearancePoint1);
    1061        40014 :             clearancePoint2 = toSystemCoordinates.map(clearancePoint2);
    1062        40014 :             slurRects.push_back(RectF(clearancePoint1, clearancePoint2));
    1063              :         }
    1064              :         // Check collisions
    1065        42120 :         for (unsigned i=0; i < slurRects.size(); i++) {
    1066        40014 :             bool leftSection = i < slurRects.size() / 3;
    1067        40014 :             bool midSection = i >= slurRects.size() / 3 && i < 2 * slurRects.size() / 3;
    1068        40014 :             bool rightSection = i >= 2 * slurRects.size() / 3;
    1069        40014 :             if ((leftSection && collision.left)
    1070        38529 :                 || (midSection && collision.mid)
    1071        36353 :                 || (rightSection && collision.right)) {         // If a collision is already found in this section, no need to check again
    1072         7399 :                 continue;
    1073              :             }
    1074        47251 :             bool intersection = slur->up() ? !Shape(slurRects[i]).clearsVertically(segShapes)
    1075        32615 :                                 : !segShapes.clearsVertically(slurRects[i]);
    1076        32615 :             if (intersection) {
    1077         1967 :                 if (leftSection) {
    1078          556 :                     collision.left = true;
    1079              :                 }
    1080         1967 :                 if (midSection) {
    1081          597 :                     collision.mid = true;
    1082              :                 }
    1083         1967 :                 if (rightSection) {
    1084          814 :                     collision.right = true;
    1085              :                 }
    1086              :             }
    1087              :         }
    1088              : 
    1089              :         // In the even iterations, adjust the shape
    1090         2106 :         if (iter % 2 == 0) {
    1091              :             static constexpr double SHAPE_PREFER_CENTER_FACTOR = 2.0;
    1092         1471 :             if (collision.left) {
    1093          290 :                 double shapeLeftStep = (1 - leftBalance) * step / SHAPE_PREFER_CENTER_FACTOR;
    1094              :                 // Move left Bezier point up(/down) and outwards
    1095          290 :                 p3 += PointF(-abs(shapeLeftStep), shapeLeftStep);
    1096              :                 // and a bit also the right point to compensate asymmetry
    1097          290 :                 p4 += PointF(std::abs(shapeLeftStep), shapeLeftStep) / 2.0;
    1098              :             }
    1099         1471 :             if (collision.mid) {     // Move both Bezier points up(/down)
    1100          322 :                 double shapeLeftStep = (1 - leftBalance) * step;
    1101          322 :                 double shapeRightStep = (1 - rightBalance) * step;
    1102          322 :                 p3 += PointF(0.0, (shapeLeftStep + shapeRightStep) / 2);
    1103          322 :                 p4 += PointF(0.0, (shapeLeftStep + shapeRightStep) / 2);
    1104              :             }
    1105         1471 :             if (collision.right) {
    1106          428 :                 double shapeRightStep = (1 - rightBalance) * step / SHAPE_PREFER_CENTER_FACTOR;
    1107              :                 // Move right Bezier point up(/down) and outwards
    1108          428 :                 p4 += PointF(std::abs(shapeRightStep), shapeRightStep);
    1109              :                 // and a bit also the left point to compensate asymmetry
    1110          428 :                 p3 += PointF(-abs(shapeRightStep), shapeRightStep) / 2.0;
    1111              :             }
    1112          635 :         } else if (!slurSeg->isEndPointsEdited()) {
    1113              :             // In the odd iterations, adjust the end points
    1114              :             // Slurs steeper than 45° are gently compensated
    1115              :             static constexpr double STEEP_LIMIT = M_PI / 4;
    1116              :             // If the collision is in mid region, move more the endpoint which reduces the slur slant
    1117              :             static constexpr double SLANT_REDUCTION_ANGLE = 5 * M_PI / 180;
    1118              :             static constexpr double SLANT_REDUCTION_LENGTH = 8;
    1119          635 :             PointF p2SysCoords = toSystemCoordinates.map(p2);
    1120          635 :             double curSlant = (p2SysCoords.y() - pp1.y()) / (p2SysCoords.x() - pp1.x());
    1121          635 :             if (collision.left || collision.mid || slurAngle < -STEEP_LIMIT) {
    1122          407 :                 double endPointLeftStep = leftBalance * step;
    1123          141 :                 if (!collision.left && collision.mid && std::abs(curSlant) > SLANT_REDUCTION_ANGLE
    1124          548 :                     && slurLength > SLANT_REDUCTION_LENGTH) {
    1125           46 :                     double slantReductionRatio = std::abs(curSlant) / SLANT_REDUCTION_ANGLE;
    1126           46 :                     bool leftIsOuter = (slurUp && curSlant > 0) || (!slurUp && curSlant < 0);
    1127           46 :                     endPointLeftStep *= leftIsOuter ? (1 / slantReductionRatio) : slantReductionRatio;
    1128              :                 }
    1129              :                 // Lift the left end point, i.e. tilt the slur around p2
    1130          407 :                 double stepX = sin(slurAngle) * endPointLeftStep;
    1131          407 :                 double stepY = cos(slurAngle) * endPointLeftStep;
    1132          407 :                 PointF pp1delta = PointF(stepX, stepY);
    1133          407 :                 pp1 += PointF(0.0, endPointLeftStep);
    1134          407 :                 p3 += pp1delta * (p2.x() - p3.x()) / p2.x();
    1135          407 :                 p4 += pp1delta * (p2.x() - p4.x()) / p2.x();
    1136              :                 // All points are expressed with respect to pp1, so we need
    1137              :                 // to subtract pp1delta to avoid the whole slur moving up
    1138          407 :                 p2 -= pp1delta;
    1139          407 :                 p3 -= pp1delta;
    1140          407 :                 p4 -= pp1delta;
    1141              :             }
    1142          635 :             if (collision.right || collision.mid || slurAngle > STEEP_LIMIT) {
    1143          483 :                 double endPointRightStep = rightBalance * step;
    1144           97 :                 if (!collision.right && collision.mid && std::abs(curSlant) > SLANT_REDUCTION_ANGLE
    1145          580 :                     && slurLength > SLANT_REDUCTION_LENGTH) {
    1146           30 :                     double slantReductionRatio = std::abs(curSlant) / SLANT_REDUCTION_ANGLE;
    1147           30 :                     bool rightIsOuter = (slurUp && curSlant < 0) || (!slurUp && curSlant > 0);
    1148           30 :                     endPointRightStep *= rightIsOuter ? (1 / slantReductionRatio) : slantReductionRatio;
    1149              :                 }
    1150              :                 // Lift the right end point, i.e. tilt the slur around p1
    1151          483 :                 double stepX = sin(slurAngle) * endPointRightStep;
    1152          483 :                 double stepY = cos(slurAngle) * endPointRightStep;
    1153          483 :                 PointF p2delta = PointF(stepX, stepY);
    1154          483 :                 p2 += p2delta;
    1155          483 :                 p3 += p2delta * p3.x() / p2.x();
    1156          483 :                 p4 += p2delta * p4.x() / p2.x();
    1157              :             }
    1158              :         }
    1159              :         // Enforce non-ugliness rules
    1160              :         // 1) Slur cannot be taller than it is wide
    1161         2106 :         const double maxRelativeHeight = std::abs(p2.x());
    1162         2106 :         p3 = slur->up() ? PointF(p3.x(), std::max(p3.y(), -maxRelativeHeight)) : PointF(p3.x(), std::min(p3.y(), maxRelativeHeight));
    1163         2106 :         p4 = slur->up() ? PointF(p4.x(), std::max(p4.y(), -maxRelativeHeight)) : PointF(p4.x(), std::min(p4.y(), maxRelativeHeight));
    1164              :         // 2) Tangent rule: p3 and p4 cannot be further left than p1 nor further right than p2
    1165         2106 :         PointF p3SysCoord = toSystemCoordinates.map(p3);
    1166         2106 :         PointF p4SysCoord = toSystemCoordinates.map(p4);
    1167         2106 :         PointF p2SysCoord = toSystemCoordinates.map(p2);
    1168         2106 :         p3SysCoord = PointF(std::max(pp1.x(), p3SysCoord.x()), p3SysCoord.y());
    1169         2106 :         p3SysCoord = PointF(std::min(p2SysCoord.x(), p3SysCoord.x()), p3SysCoord.y());
    1170         2106 :         p4SysCoord = PointF(std::max(pp1.x(), p4SysCoord.x()), p4SysCoord.y());
    1171         2106 :         p4SysCoord = PointF(std::min(p2SysCoord.x(), p4SysCoord.x()), p4SysCoord.y());
    1172         2106 :         p3 = toSystemCoordinates.inverted().map(p3SysCoord);
    1173         2106 :         p4 = toSystemCoordinates.inverted().map(p4SysCoord);
    1174              : 
    1175         2106 :         ++iter;
    1176         2106 :     } while ((collision.left || collision.mid || collision.right) && iter < MAX_ITER);
    1177          961 : }
    1178              : 
    1179          931 : Shape SlurTieLayout::getSegmentShapes(SlurSegment* slurSeg, ChordRest* startCR, ChordRest* endCR)
    1180              : {
    1181          931 :     Shape segShapes;
    1182              : 
    1183              :     // Determine start and end segments for collision checks
    1184          931 :     Segment* startSeg = nullptr;
    1185          931 :     if (slurSeg->isSingleBeginType()) {
    1186          917 :         if (startCR->isChord() && toChord(startCR)->isGraceAfter()) {
    1187              :             // if this is a grace-note-after, the shape is stored the *appended* segment
    1188            4 :             Chord* parent = toChord(startCR->ownershipParent());
    1189            4 :             if (parent) {
    1190            4 :                 startSeg = parent->graceNotesAfter().appendedSegment();
    1191              :             }
    1192              :         } else {
    1193          913 :             startSeg = startCR->segment(); // first of the slur
    1194              :         }
    1195              :     } else {
    1196           14 :         startSeg = slurSeg->system()->firstMeasure()->findFirstR(SegmentType::ChordRest, Fraction(0, 0)); // first of the system
    1197              :     }
    1198              : 
    1199          931 :     Segment* endSeg = nullptr;
    1200          931 :     if (slurSeg->isSingleEndType()) {
    1201          915 :         if (endCR->isChord() && toChord(endCR)->isGraceAfter()) {
    1202              :             // if this is a grace-note-after, the shape is stored the *appended* segment
    1203           17 :             Chord* parent = toChord(endCR->ownershipParent());
    1204           17 :             if (parent) {
    1205           17 :                 endSeg = parent->graceNotesAfter().appendedSegment();
    1206              :             }
    1207              :         } else {
    1208          898 :             endSeg = endCR->segment(); // last of the slur
    1209              :         }
    1210              :     } else {
    1211           16 :         endSeg = slurSeg->system()->lastMeasure()->last(); // last of the system
    1212              :     }
    1213              : 
    1214          931 :     if (!startSeg || !endSeg) {
    1215            0 :         return segShapes;
    1216              :     }
    1217              : 
    1218         4484 :     for (Segment* seg = startSeg; seg && (seg->isBefore(endSeg) || seg == endSeg); seg = seg->next1enabled()) {
    1219         3553 :         if (seg->isType(SegmentType::BarLineTypes) || seg->isBreathType() || seg->hasTimeSigAboveStaves() || seg->isTimeTickType()) {
    1220          261 :             continue;
    1221              :         }
    1222         3292 :         segShapes.add(getSegmentShape(slurSeg, seg, startCR, endCR));
    1223              :     }
    1224              : 
    1225          931 :     return segShapes;
    1226            0 : }
    1227              : 
    1228         3292 : Shape SlurTieLayout::getSegmentShape(SlurSegment* slurSeg, Segment* seg, ChordRest* startCR, ChordRest* endCR)
    1229              : {
    1230         3292 :     Slur* slur = slurSeg->slur();
    1231         3292 :     staff_idx_t startStaffIdx = startCR->staffIdx();
    1232         3292 :     staff_idx_t endStaffIdx = endCR->staffIdx();
    1233         3292 :     Shape segShape = seg->staffShape(startStaffIdx).translated(seg->pos() + seg->measure()->pos());
    1234              : 
    1235         3292 :     bool crossStaffSlur = slur->isCrossStaff() && seg != startCR->segment();
    1236              : 
    1237              :     // If cross-staff, also add the shape of second staff
    1238         3292 :     if (crossStaffSlur) {
    1239          140 :         endStaffIdx = (endCR->staffIdx() != startStaffIdx) ? endCR->staffIdx() : endCR->vStaffIdx();
    1240          140 :         SysStaff* startStaff = slurSeg->system()->staves().at(startStaffIdx);
    1241          140 :         SysStaff* endStaff = slurSeg->system()->staves().at(endStaffIdx);
    1242          140 :         double dist = endStaff->y() - startStaff->y();
    1243          140 :         Shape secondStaffShape = seg->staffShape(endStaffIdx).translated(seg->pos() + seg->measure()->pos()); // translate horizontally
    1244          140 :         secondStaffShape.translate(PointF(0.0, dist)); // translate vertically
    1245          140 :         segShape.add(secondStaffShape);
    1246          140 :     }
    1247              : 
    1248        16688 :     for (track_idx_t track = staff2track(startStaffIdx); track < staff2track(endStaffIdx, VOICES); ++track) {
    1249        13396 :         EngravingItem* e = seg->element(track);
    1250        13396 :         if (!e || !e->isChordRest()) {
    1251        10003 :             continue;
    1252              :         }
    1253         3393 :         if (e->vStaffIdx() != slurSeg->vStaffIdx() && !crossStaffSlur) {
    1254           41 :             continue;
    1255              :         }
    1256              :         // Gets tie and 2 note tremolo shapes
    1257         3352 :         if (e->isChord()) {
    1258         3238 :             Chord* chord = toChord(e);
    1259         3238 :             if (chord->tremoloTwoChord()) {
    1260           40 :                 segShape.add(chord->tremoloTwoChord()->shape());
    1261              :             }
    1262         6698 :             for (Note* note : toChord(e)->notes()) {
    1263         3460 :                 Tie* tieFor = note->tieFor();
    1264         3460 :                 Tie* tieBack = note->tieBack();
    1265         3460 :                 if (tieFor && tieFor->up() == slur->up() && !tieFor->segmentsEmpty()) {
    1266           77 :                     TieSegment* tieSegment = tieFor->frontSegment();
    1267           77 :                     if (tieSegment->isSingleBeginType()) {
    1268           77 :                         segShape.add(tieSegment->shape());
    1269              :                     }
    1270              :                 }
    1271         3460 :                 if (tieBack && tieBack->up() == slur->up() && !tieBack->segmentsEmpty()) {
    1272           76 :                     TieSegment* tieSegment = tieBack->backSegment();
    1273           76 :                     if (tieSegment->isEndType()) {
    1274            2 :                         segShape.add(tieSegment->shape());
    1275              :                     }
    1276              :                 }
    1277              :             }
    1278              :         }
    1279              :     }
    1280              : 
    1281              :     // Remove items that the slur shouldn't try to avoid
    1282         3292 :     segShape.remove_if([&](ShapeElement& shapeEl) {
    1283        11560 :         if (!shapeEl.item() || !shapeEl.item()->ownershipParent() || !shapeEl.item()->visible()) {
    1284          104 :             return true;
    1285              :         }
    1286        11456 :         const EngravingItem* item = shapeEl.item();
    1287        11456 :         const EngravingObject* parent = item->ownershipParent();
    1288              :         // Don't remove arpeggio starting on a different voice and ending on the same voice as endCR when slur is on the outside
    1289        22912 :         if ((item->isArpeggio() || item->isChordBracket()) && (endCR->track() == toArpeggio(item)->endTrack())
    1290            0 :             && endCR->tick() == item->tick()
    1291        22912 :             && (!slur->up() && toArpeggio(item)->span() > 1)) {
    1292            0 :             return false;
    1293              :         }
    1294              : 
    1295              :         // Its own startCR or items belonging to it, lyrics, fingering, ledger lines, articulation on endCR
    1296        11456 :         if (item == startCR || parent == startCR || item->isTextBase() || item->isLedgerLine()
    1297        22912 :             || (item->isArticulationFamily() && parent == endCR) || item->isBend() || item->isTappingHalfSlurSegment()) {
    1298         3125 :             return true;
    1299              :         }
    1300              :         // Ornament accidentals on start or end chord
    1301         8331 :         if (item->isAccidental() && parent->isOrnament()) {
    1302            0 :             const EngravingObject* parentParent = parent->ownershipParent();
    1303            0 :             if (parentParent && (parentParent == startCR || parentParent == endCR)) {
    1304            0 :                 return true;
    1305              :             }
    1306              :         }
    1307              :         // Items that are on the start segment but in a different voice
    1308         9225 :         if ((item->tick() == startCR->tick() && item->track() != startCR->track())
    1309         9225 :             || (item->tick() == endCR->tick() && item->track() != endCR->track())) {
    1310          427 :             return true;
    1311              :         }
    1312              :         // Edge-case: multiple voices and slur is on the inside
    1313         7904 :         if (item->vStaffIdx() == startCR->staffIdx()
    1314        15520 :             && ((!slur->up() && item->track() > startCR->track()) // slur-down: ignore lower voices
    1315         7616 :                 || (slur->up() && item->track() < startCR->track()))) { // slur-up: ignore higher voices
    1316           22 :             return true;
    1317              :         }
    1318              :         // Remove arpeggios spanning more than 1 voice starting on endCR's voice when the slur is on the inside
    1319        15764 :         if ((item->isArpeggio() || item->isChordBracket())
    1320        15764 :             && (endCR->track() != item->track() || (!slur->up() && toArpeggio(item)->span() > 1))) {
    1321            0 :             return true;
    1322              :         }
    1323              :         // Ignore big time signatures
    1324         7882 :         if (item->isTimeSig() && toTimeSig(item)->timeSigPlacement() != TimeSigPlacement::NORMAL) {
    1325            0 :             return true;
    1326              :         }
    1327              :         // Ignore fermatas
    1328         7882 :         if (item->isFermata()) {
    1329           17 :             return true;
    1330              :         }
    1331              :         // Ignore fret diagrams
    1332         7865 :         if (item->isFretDiagram()) {
    1333            0 :             return true;
    1334              :         }
    1335              : 
    1336         7865 :         if (item->isNote() && toNote(item)->shouldHideFret()) {
    1337            0 :             return true;
    1338              :         }
    1339              : 
    1340              :         // Ignore octave dots
    1341         7865 :         if (item->isJianpuOctaveDot()) {
    1342            0 :             return true;
    1343              :         }
    1344              : 
    1345         7865 :         return false;
    1346              :     });
    1347              : 
    1348         3292 :     return segShape;
    1349            0 : }
    1350              : 
    1351          931 : void SlurTieLayout::addMinClearanceToShapes(Shape& segShapes, double spatium, bool slurUp, const ChordRest* startCR, const ChordRest* endCR)
    1352              : {
    1353          931 :     const double noteClearance = 0.4 * spatium;
    1354          931 :     const double articulationClearance = 0.20 * spatium;
    1355          931 :     const double itemClearance = 0.1 * spatium;
    1356              : 
    1357         8796 :     for (ShapeElement& shapeEl : segShapes.elements()) {
    1358         7865 :         const EngravingItem* item = shapeEl.item();
    1359         7865 :         if (!item || item->parent() == startCR || item->parent() == endCR) {
    1360         1812 :             continue;
    1361              :         }
    1362              : 
    1363         6053 :         double clearance = 0.0;
    1364         6053 :         switch (item->type()) {
    1365         1572 :         case ElementType::NOTE:
    1366         1572 :             clearance = noteClearance;
    1367         1572 :             break;
    1368           74 :         case ElementType::ARTICULATION:
    1369              :         case ElementType::ORNAMENT:
    1370              :         case ElementType::TAPPING:
    1371           74 :             clearance = articulationClearance;
    1372           74 :             break;
    1373         4407 :         default:
    1374         4407 :             clearance = itemClearance;
    1375         4407 :             break;
    1376              :         }
    1377              : 
    1378         6053 :         slurUp ? shapeEl.adjust(0.0, -clearance, 0.0, 0.0) : shapeEl.adjust(0.0, 0.0, 0.0, clearance);
    1379              :     }
    1380          931 : }
    1381              : 
    1382          901 : double SlurTieLayout::computeArcClearance(double spatium, double slurLength, double slurAngle)
    1383              : {
    1384              :     static constexpr double CLEARANCE_TO_LENGTH_RATIO = 0.04;
    1385              :     static constexpr double MAX_CLEARANCE = 0.5;
    1386              :     static constexpr double MIN_CLEARANCE = 0.1;
    1387              : 
    1388          901 :     double clearance = CLEARANCE_TO_LENGTH_RATIO * slurLength * std::pow(cos(slurAngle), 2);
    1389          901 :     clearance = std::clamp(clearance, MIN_CLEARANCE, MAX_CLEARANCE);
    1390              : 
    1391          901 :     return clearance * spatium;
    1392              : }
    1393              : 
    1394          901 : void SlurTieLayout::computeAdjustmentBalance(SlurSegment* slurSeg, const ChordRest* startCR, const ChordRest* endCR,  double& leftBalance,
    1395              :                                              double& rightBalance)
    1396              : {
    1397          901 :     Slur* slur = slurSeg->slur();
    1398          901 :     if (slurSeg->isSingleBeginType() && !slur->stemFloated().left) {
    1399          836 :         if (slurSeg->isBeginType() || hasArticulationAbove(slurSeg, startCR) || slur->isCrossStaff()) {
    1400           30 :             leftBalance = 0.1;
    1401              :         } else {
    1402          806 :             leftBalance = 0.4;
    1403              :         }
    1404              :     } else {
    1405           65 :         leftBalance = 0.9;
    1406              :     }
    1407              : 
    1408          901 :     if (slurSeg->isSingleEndType() && !slur->stemFloated().right) {
    1409          841 :         if (slurSeg->isEndType() || hasArticulationAbove(slurSeg, endCR) || slur->isCrossStaff()) {
    1410           32 :             rightBalance = 0.1;
    1411              :         } else {
    1412          809 :             rightBalance = 0.4;
    1413              :         }
    1414              :     } else {
    1415           60 :         rightBalance = 0.9;
    1416              :     }
    1417          901 : }
    1418              : 
    1419         1651 : bool SlurTieLayout::hasArticulationAbove(SlurSegment* slurSeg, const ChordRest* chordRest)
    1420              : {
    1421         1651 :     IF_ASSERT_FAILED(chordRest) {
    1422            0 :         return false;
    1423              :     }
    1424              : 
    1425         1651 :     if (!chordRest->isChord()) {
    1426           12 :         return false;
    1427              :     }
    1428              : 
    1429         1639 :     const Chord* chord = toChord(chordRest);
    1430              : 
    1431         1639 :     bool slurUp = slurSeg->slur()->up();
    1432         1673 :     for (const Articulation* artic : chord->articulations()) {
    1433           36 :         if (!artic->layoutCloseToNote() && artic->up() == slurUp) {
    1434            2 :             return true;
    1435              :         }
    1436              :     }
    1437              : 
    1438         1637 :     if (Ornament* ornament = chord->findOrnament()) {
    1439            0 :         if (ornament->up() == slurUp) {
    1440            0 :             return true;
    1441              :         }
    1442              :     }
    1443              : 
    1444         1637 :     return false;
    1445              : }
    1446              : 
    1447          901 : double SlurTieLayout::computeAdjustmentStep(int upSign, double spatium, double slurLength)
    1448              : {
    1449          901 :     double step = upSign * 0.30 * spatium;
    1450              : 
    1451              :     static constexpr double LONG_SLUR_LIMIT = 16.0; // in spaces
    1452          901 :     if (slurLength > LONG_SLUR_LIMIT) {
    1453          218 :         step *= slurLength / LONG_SLUR_LIMIT;
    1454          218 :         step = std::min(step, 1.5 * spatium);
    1455              :     }
    1456              : 
    1457          901 :     return step;
    1458              : }
    1459              : 
    1460          238 : bool SlurTieLayout::stemSideForBeam(Slur* slur, bool start)
    1461              : {
    1462              :     // determines if the anchor point is exempted from the stem inset due to beams or tremolos.
    1463          238 :     if (!slur) {
    1464            0 :         return false;
    1465              :     }
    1466              : 
    1467          238 :     ChordRest* cr = start ? slur->startCR() : slur->endCR();
    1468          238 :     Chord* c = toChord(cr);
    1469          238 :     bool adjustForBeam = cr && cr->beam() && cr->up() == slur->up();
    1470          238 :     if (start) {
    1471          119 :         adjustForBeam = adjustForBeam && cr->beam()->elements().back() != cr;
    1472              :     } else {
    1473          119 :         adjustForBeam = adjustForBeam && cr->beam()->elements().front() != cr;
    1474              :     }
    1475          238 :     if (adjustForBeam) {
    1476           52 :         return true;
    1477              :     }
    1478              : 
    1479          186 :     bool adjustForTrem = false;
    1480          186 :     TremoloTwoChord* trem = c ? c->tremoloTwoChord() : nullptr;
    1481          186 :     adjustForTrem = trem && trem->up() == slur->up();
    1482          186 :     if (start) {
    1483           93 :         adjustForTrem = adjustForTrem && trem->chord2() != c;
    1484              :     } else {
    1485           93 :         adjustForTrem = adjustForTrem && trem->chord1() != c;
    1486              :     }
    1487          186 :     return adjustForTrem;
    1488              : }
    1489              : 
    1490          937 : bool SlurTieLayout::isOverBeams(Slur* slur)
    1491              : {
    1492              :     // returns true if all the chords spanned by the slur are beamed, and all beams are on the same side of the slur
    1493          937 :     const ChordRest* startCR = slur->startCR();
    1494          937 :     const ChordRest* endCR = slur->endCR();
    1495          937 :     if (!startCR || !endCR) {
    1496            0 :         return false;
    1497              :     }
    1498          937 :     if (startCR->track() != endCR->track()
    1499          937 :         || startCR->tick() >= endCR->tick()) {
    1500           81 :         return false;
    1501              :     }
    1502          856 :     size_t track = startCR->track();
    1503          856 :     Segment* seg = startCR->segment();
    1504         1052 :     while (seg && seg->tick() <= endCR->tick()) {
    1505         1037 :         if (!seg->isChordRestType()
    1506         1035 :             || !seg->elist().at(track)
    1507         2072 :             || !seg->elist().at(track)->isChordRest()) {
    1508            9 :             return false;
    1509              :         }
    1510         1028 :         ChordRest* cr = toChordRest(seg->elist().at(track));
    1511         1028 :         bool hasBeam = cr->beam() && cr->up() == slur->up();
    1512         1028 :         bool hasTrem = false;
    1513         1028 :         if (cr->isChord()) {
    1514         1028 :             Chord* c = toChord(cr);
    1515         1028 :             hasTrem = c->tremoloTwoChord() && c->up() == slur->up();
    1516              :         }
    1517         1028 :         if (!(hasBeam || hasTrem)) {
    1518          832 :             return false;
    1519              :         }
    1520          196 :         if ((!seg->next() || seg->next()->isEndBarLineType()) && seg->measure()->nextMeasure()) {
    1521           10 :             seg = seg->measure()->nextMeasure()->first();
    1522              :         } else {
    1523          186 :             seg = seg->next();
    1524              :         }
    1525              :     }
    1526           15 :     return true;
    1527              : }
    1528              : 
    1529           31 : void SlurTieLayout::avoidPreBendsOnTab(const Chord* sc, const Chord* ec, SlurTiePos* sp)
    1530              : {
    1531           31 :     GuitarBend* bendOnStart = nullptr;
    1532           31 :     GuitarBend* bendOnEnd = nullptr;
    1533           31 :     if (sc) {
    1534           64 :         for (Note* note : sc->notes()) {
    1535           33 :             GuitarBend* bf = note->bendFor();
    1536           33 :             GuitarBend* bb = note->bendBack();
    1537           33 :             if (bf && !bf->segmentsEmpty() && bf->bendType() == GuitarBendType::PRE_BEND && !bf->angledPreBend()) {
    1538            0 :                 bendOnStart = bf;
    1539           33 :             } else if (bb && !bb->segmentsEmpty() && bb->bendType() == GuitarBendType::PRE_BEND && !bb->angledPreBend()) {
    1540            0 :                 bendOnStart = bb;
    1541              :             }
    1542           33 :             if (bendOnStart) {
    1543            0 :                 break;
    1544              :             }
    1545              :         }
    1546              :     }
    1547           31 :     if (ec) {
    1548           64 :         for (Note* note : ec->notes()) {
    1549           33 :             GuitarBend* bf = note->bendFor();
    1550           33 :             GuitarBend* bb = note->bendBack();
    1551           33 :             if (bf && !bf->segmentsEmpty() && bf->bendType() == GuitarBendType::PRE_BEND && !bf->angledPreBend()) {
    1552            0 :                 bendOnEnd = bf;
    1553           33 :             } else if (bb && !bb->segmentsEmpty() && bb->bendType() == GuitarBendType::PRE_BEND && !bb->angledPreBend()) {
    1554            0 :                 bendOnEnd = bb;
    1555              :             }
    1556           33 :             if (bendOnEnd) {
    1557            0 :                 break;
    1558              :             }
    1559              :         }
    1560              :     }
    1561              : 
    1562           31 :     if (bendOnStart) {
    1563            0 :         sp->p1.rx() = std::max(sp->p1.x(), bendOnStart->frontSegment()->pos().x() + 0.33 * sc->spatium());
    1564              :     }
    1565           31 :     if (bendOnEnd) {
    1566            0 :         sp->p2.rx() = std::min(sp->p2.x(), bendOnEnd->frontSegment()->pos().x() - 0.33 * ec->spatium());
    1567              :     }
    1568           31 : }
    1569              : 
    1570         5444 : bool SlurTieLayout::tieSegmentShouldBeSkipped(const Tie* item)
    1571              : {
    1572         5444 :     Note* startNote = item->startNote();
    1573         5444 :     StaffType* st = item->staff()->staffType(startNote ? startNote->tick() : Fraction(0, 1));
    1574         5444 :     if (!st || !st->isTabStaff()) {
    1575         5391 :         return false;
    1576              :     }
    1577              : 
    1578           53 :     if (startNote && startNote->isContinuationOfBend()) {
    1579            4 :         return true;
    1580              :     }
    1581              : 
    1582           49 :     ShowTiedFret showTiedFret = item->style().value(Sid::tabShowTiedFret).value<ShowTiedFret>();
    1583              : 
    1584           49 :     return showTiedFret == ShowTiedFret::NONE;
    1585              : }
    1586              : 
    1587         4520 : TieSegment* SlurTieLayout::layoutTieFor(Tie* item, System* system)
    1588              : {
    1589         4520 :     item->setPos(0, 0);
    1590              : 
    1591         4520 :     if (!item->startNote()) {
    1592            0 :         LOGD("no start note");
    1593            0 :         return nullptr;
    1594              :     }
    1595              : 
    1596              :     // do not layout ties in tablature if not showing back-tied fret marks
    1597         4520 :     if (tieSegmentShouldBeSkipped(item)) {
    1598            4 :         if (!item->segmentsEmpty()) {
    1599            0 :             item->eraseSpannerSegments();
    1600              :         }
    1601              : 
    1602            4 :         return nullptr;
    1603              :     }
    1604              : 
    1605         4516 :     if (item->isPartialTie()) {
    1606          110 :         return layoutPartialTie(toPartialTie(item));
    1607              :     }
    1608              : 
    1609         4406 :     calculateDirection(item);
    1610         4406 :     calculateIsInside(item);
    1611              : 
    1612         4406 :     SlurTiePos sPos;
    1613         4406 :     sPos.p1 = computeDefaultStartOrEndPoint(item, Grip::START);
    1614              : 
    1615         4406 :     computeStartAndEndSystem(item, sPos);
    1616              : 
    1617         4406 :     int segmentCount = sPos.system1 == sPos.system2 ? 1 : 2;
    1618         4406 :     if (segmentCount == 2) {
    1619          574 :         sPos.p2 = PointF(endingXForOpenEndedSlurTie(system->lastMeasure(), item->startNote()->vStaffIdx()), sPos.p1.y());
    1620              :     } else {
    1621         3832 :         sPos.p2 = computeDefaultStartOrEndPoint(item, Grip::END);
    1622              :     }
    1623              : 
    1624         4406 :     correctForCrossStaff(item, sPos, sPos.system1 != sPos.system2 ? SpannerSegmentType::BEGIN : SpannerSegmentType::SINGLE);
    1625         4406 :     forceHorizontal(item, sPos);
    1626         4406 :     correctForJianpu(item, sPos);
    1627              : 
    1628         4406 :     item->fixupSegments(segmentCount);
    1629         4406 :     TieSegment* segment = item->segmentAt(0);
    1630         4406 :     segment->setTrack(item->track());
    1631         4406 :     segment->setSpannerSegmentType(sPos.system1 != sPos.system2 ? SpannerSegmentType::BEGIN : SpannerSegmentType::SINGLE);
    1632         4406 :     segment->moveToSystem(system);   // Needed to populate System.spannerSegments
    1633         4406 :     segment->resetAdjustmentOffset();
    1634         4406 :     segment->mutldata()->allJumpPointsInactive = item->allJumpPointsInactive();
    1635              : 
    1636         4406 :     const Chord* startChord = item->startNote()->chord();
    1637         4406 :     item->setTick(startChord->tick()); // Why is this here?? (M.S.)
    1638              : 
    1639         4406 :     if (segment->autoplace() && !segment->isEdited()) {
    1640         4406 :         adjustX(segment, sPos, Grip::START);
    1641         4406 :         if (segment->isSingleType()) {
    1642         3832 :             adjustX(segment, sPos, Grip::END);
    1643              :         }
    1644              :     }
    1645              : 
    1646         4406 :     adjustYforLedgerLines(segment, sPos);
    1647              : 
    1648         4406 :     segment->ups(Grip::START).p = sPos.p1;
    1649         4406 :     segment->ups(Grip::END).p = sPos.p2;
    1650              : 
    1651         4406 :     if (segment->autoplace() && !segment->isEdited()) {
    1652         4406 :         adjustY(segment);
    1653              :     } else {
    1654            0 :         computeBezier(segment);
    1655              :     }
    1656              : 
    1657         4406 :     addLineAttachPoints(segment); // add attach points to start and end note
    1658         4406 :     return segment;
    1659              : }
    1660              : 
    1661         4406 : void SlurTieLayout::correctForJianpu(Tie* item, SlurTiePos& sPos)
    1662              : {
    1663         4406 :     if (!item->startNote() || !item->endNote()) {
    1664         4406 :         return;
    1665              :     }
    1666              : 
    1667         4406 :     if (!item->staff()->isJianpuStaff(item->startNote()->tick())) {
    1668         4406 :         return;
    1669              :     }
    1670              : 
    1671            0 :     Chord* chord1 = item->startNote()->chord();
    1672            0 :     Chord* chord2 = item->endNote()->chord();
    1673            0 :     if (!chord1 || !chord2) {
    1674            0 :         return;
    1675              :     }
    1676              : 
    1677            0 :     double y1 = chord1->ldata()->bbox().top();
    1678            0 :     double y2 = chord2->ldata()->bbox().top();
    1679            0 :     double minY = std::min(y1, y2);
    1680            0 :     sPos.p1 += PointF(0, minY);
    1681            0 :     sPos.p2 += PointF(0, minY);
    1682              : }
    1683              : 
    1684          825 : TieSegment* SlurTieLayout::layoutTieBack(Tie* item, System* system, LayoutContext& ctx)
    1685              : {
    1686          825 :     Chord* chord = item->endNote() ? item->endNote()->chord() : nullptr;
    1687              : 
    1688          825 :     if (item->staffType() && item->staffType()->isTabStaff()) {
    1689              :         // On TAB, the presence of this tie may require to add a parenthesis
    1690           10 :         ChordLayout::layout(chord, ctx);
    1691              :     }
    1692              :     // do not layout ties in tablature if not showing back-tied fret marks
    1693          825 :     if (tieSegmentShouldBeSkipped(item)) {
    1694            0 :         if (!item->segmentsEmpty()) {
    1695            0 :             item->eraseSpannerSegments();
    1696              :         }
    1697              : 
    1698            0 :         return nullptr;
    1699              :     }
    1700              : 
    1701          825 :     if (item->isPartialTie()) {
    1702          230 :         return layoutPartialTie(toPartialTie(item));
    1703              :     }
    1704              : 
    1705          595 :     SlurTiePos sPos;
    1706          595 :     computeStartAndEndSystem(item, sPos);
    1707          595 :     sPos.p2 = computeDefaultStartOrEndPoint(item, Grip::END);
    1708              : 
    1709          595 :     double x = system ? system->firstNoteRestSegmentX(true) : 0;
    1710          595 :     double y = sPos.p2.y();
    1711          595 :     sPos.p1 = PointF(x, y);
    1712              : 
    1713          595 :     item->fixupSegments(2);
    1714          595 :     TieSegment* segment = item->segmentAt(1);
    1715          595 :     segment->setTrack(item->track());
    1716          595 :     segment->moveToSystem(system);
    1717          595 :     segment->resetAdjustmentOffset();
    1718              : 
    1719          595 :     if (chord) {
    1720          595 :         segment->setStaffMove(static_cast<int>(chord->vStaffIdx() - segment->staffIdx()));
    1721              :     }
    1722              : 
    1723          595 :     adjustY(segment);
    1724          595 :     segment->setSpannerSegmentType(SpannerSegmentType::END);
    1725              : 
    1726          595 :     if (segment->autoplace() && !segment->isEdited()) {
    1727          595 :         adjustX(segment, sPos, Grip::END);
    1728              :     }
    1729              : 
    1730          595 :     adjustYforLedgerLines(segment, sPos);
    1731              : 
    1732          595 :     segment->ups(Grip::START).p = sPos.p1;
    1733          595 :     segment->ups(Grip::END).p = sPos.p2;
    1734              : 
    1735          595 :     if (segment->autoplace() && !segment->isEdited()) {
    1736          595 :         adjustY(segment);
    1737              :     } else {
    1738            0 :         computeBezier(segment);
    1739              :     }
    1740              : 
    1741          595 :     addLineAttachPoints(segment);
    1742          595 :     return segment;
    1743              : }
    1744              : 
    1745         5415 : void SlurTieLayout::computeStartAndEndSystem(Tie* item, SlurTiePos& slurTiePos)
    1746              : {
    1747         5415 :     Chord* startChord = item->startNote() ? item->startNote()->chord() : nullptr;
    1748         5415 :     Chord* endChord = item->endNote() ? item->endNote()->chord() : nullptr;
    1749              : 
    1750         5415 :     System* startSystem = startChord ? startChord->measure()->system() : nullptr;
    1751              : 
    1752         5415 :     System* endSystem = endChord ? endChord->measure()->system() : startSystem;
    1753              : 
    1754         5415 :     if (!startSystem && !endSystem) {
    1755            0 :         if (startChord) {
    1756            0 :             Measure* m = startChord->measure();
    1757            0 :             LOGD("No system: measure is %d has %d count %d", m->isMMRest(), m->hasMMRest(), m->mmRestCount());
    1758              :         } else {
    1759            0 :             LOGD("No start or end system for tie at ") << item->tick().toString();
    1760              :         }
    1761              :     }
    1762              : 
    1763         5415 :     slurTiePos.system1 = startSystem;
    1764         5415 :     slurTiePos.system2 = endSystem;
    1765         5415 : }
    1766              : 
    1767         9247 : PointF SlurTieLayout::computeDefaultStartOrEndPoint(const Tie* tie, Grip startOrEnd)
    1768              : {
    1769         9247 :     if (startOrEnd != Grip::START && startOrEnd != Grip::END) {
    1770            0 :         return PointF();
    1771              :     }
    1772              : 
    1773         9247 :     bool start = startOrEnd == Grip::START;
    1774              : 
    1775         9247 :     Note* note = start ? tie->startNote() : tie->endNote();
    1776         9247 :     Chord* chord = note ? note->chord() : nullptr;
    1777              : 
    1778         9247 :     if (!chord) {
    1779            0 :         return PointF();
    1780              :     }
    1781              : 
    1782         9247 :     PointF result = note->pos() + chord->pos() + chord->segment()->pos() + chord->measure()->pos();
    1783              : 
    1784         9247 :     const bool up = tie->up();
    1785         9247 :     const bool inside = tie->isInside();
    1786         9247 :     const bool noteIsHiddenFret = note->shouldHideFret();
    1787         9247 :     const int upSign = up ? -1 : 1;
    1788         9247 :     const int leftRightSign = start ? +1 : -1;
    1789         9247 :     const double noteWidth = note->width();
    1790         9247 :     const double noteHeight = note->height();
    1791         9247 :     const double spatium = tie->spatium();
    1792              : 
    1793         9247 :     double baseX = (inside && !noteIsHiddenFret) ? (start ? noteWidth : 0.0) : noteOpticalCenterForTie(note, up);
    1794         9247 :     double baseY = inside ? 0.0 : upSign * noteHeight / 2;
    1795              : 
    1796         9247 :     result += PointF(baseX, baseY);
    1797              : 
    1798         9247 :     double visualInsetSp = 0.0;
    1799         9247 :     if (inside || note->headGroup() == NoteHeadGroup::HEAD_SLASH || noteIsHiddenFret) {
    1800           24 :         visualInsetSp = 0.2;
    1801         9223 :     } else if (note->hasAnotherStraightAboveOrBelow(up)) {
    1802          386 :         visualInsetSp = 0.45;
    1803              :     } else {
    1804         8837 :         visualInsetSp = 0.1;
    1805              :     }
    1806              : 
    1807         9247 :     double visualInset = visualInsetSp * spatium * leftRightSign;
    1808         9247 :     const double yOffset = 0.20 * spatium * upSign; // TODO: style
    1809              : 
    1810         9247 :     result += PointF(visualInset, yOffset);
    1811              : 
    1812         9247 :     return result;
    1813              : }
    1814              : 
    1815         9247 : double SlurTieLayout::noteOpticalCenterForTie(const Note* note, bool up)
    1816              : {
    1817         9247 :     if (note->headGroup() == NoteHeadGroup::HEAD_SLASH) {
    1818           24 :         double singleSlashWidth = note->symBbox(SymId::noteheadSlashHorizontalEnds).width();
    1819           24 :         double noteWidth = note->headWidth();
    1820           24 :         double center = 0.20 * note->spatium() + 0.5 * (noteWidth - singleSlashWidth);
    1821           24 :         return up ? note->ldata()->bbox().right() - center : note->ldata()->bbox().left() + center;
    1822              :     }
    1823         9223 :     SymId symId = note->ldata()->cachedNoteheadSym.value();
    1824         9223 :     PointF cutOutLeft = note->symSmuflAnchor(symId, up ? SmuflAnchorId::cutOutNW : SmuflAnchorId::cutOutSW);
    1825         9223 :     PointF cutOutRight = note->symSmuflAnchor(symId, up ? SmuflAnchorId::cutOutNE : SmuflAnchorId::cutOutSE);
    1826              : 
    1827         9223 :     if (cutOutLeft.isNull() || cutOutRight.isNull()) {
    1828         5959 :         return 0.5 * note->width();
    1829              :     }
    1830              : 
    1831         3264 :     return 0.5 * (cutOutLeft.x() + cutOutRight.x());
    1832              : }
    1833              : 
    1834            0 : void SlurTieLayout::createSlurSegments(Slur* item, LayoutContext& ctx)
    1835              : {
    1836            0 :     const ChordRest* startCR = item->startCR();
    1837            0 :     const ChordRest* endCR = item->endCR();
    1838            0 :     assert(startCR && endCR);
    1839              : 
    1840            0 :     const System* startSys = startCR->measure()->system();
    1841            0 :     const System* endSys = endCR->measure()->system();
    1842              : 
    1843            0 :     const std::vector<System*>& systems = ctx.dom().systems();
    1844            0 :     system_idx_t startSysIdx = muse::indexOf(systems, startSys);
    1845            0 :     system_idx_t endSysIdx = muse::indexOf(systems, endSys);
    1846            0 :     if (startSysIdx == muse::nidx || endSysIdx == muse::nidx) {
    1847            0 :         return;
    1848              :     }
    1849              : 
    1850            0 :     int segmentsNeeded = 0;
    1851            0 :     for (system_idx_t i = startSysIdx; i <= endSysIdx; ++i) {
    1852            0 :         if (systems.at(i)->vbox()) {
    1853            0 :             continue;
    1854              :         }
    1855            0 :         ++segmentsNeeded;
    1856              :     }
    1857            0 :     int currentSegments = int(item->spannerSegments().size());
    1858              : 
    1859            0 :     if (currentSegments != segmentsNeeded) {
    1860            0 :         item->fixupSegments(segmentsNeeded);
    1861              :     }
    1862              : 
    1863            0 :     int segIdx = 0;
    1864            0 :     for (system_idx_t i = startSysIdx; i <= endSysIdx; ++i) {
    1865            0 :         System* system = systems.at(i);
    1866            0 :         if (system->vbox()) {
    1867            0 :             continue;
    1868              :         }
    1869            0 :         SlurSegment* lineSegm = item->segmentAt(segIdx++);
    1870            0 :         lineSegm->moveToSystem(system);
    1871            0 :         if (startSysIdx == endSysIdx) {
    1872            0 :             lineSegm->setSpannerSegmentType(SpannerSegmentType::SINGLE);
    1873            0 :         } else if (i == startSysIdx) {
    1874            0 :             lineSegm->setSpannerSegmentType(SpannerSegmentType::BEGIN);
    1875            0 :         } else if (i > 0 && i != endSysIdx) {
    1876            0 :             lineSegm->setSpannerSegmentType(SpannerSegmentType::MIDDLE);
    1877            0 :         } else if (i == endSysIdx) {
    1878            0 :             lineSegm->setSpannerSegmentType(SpannerSegmentType::END);
    1879              :         }
    1880              :     }
    1881              : }
    1882              : 
    1883          400 : void SlurTieLayout::adjustOverlappingSlurs(const std::list<SpannerSegment*>& spannerSegments)
    1884              : {
    1885          400 :     std::vector<SlurSegment*> segments;
    1886         1684 :     for (SpannerSegment* seg : spannerSegments) {
    1887         1284 :         if (seg->isSlurSegment()) {
    1888          887 :             segments.push_back(toSlurSegment(seg));
    1889              :         }
    1890              :     }
    1891          400 :     if (segments.size() <= 1) {
    1892          219 :         return;
    1893              :     }
    1894              : 
    1895              :     //how far vertically an endpoint should adjust to avoid other slur endpoints:
    1896          181 :     const double spatium = segments.front()->spatium();
    1897          181 :     const double slurCollisionVertOffset = 0.65 * spatium;
    1898          181 :     const double slurCollisionHorizOffset = 0.2 * spatium;
    1899          181 :     const double fuzzyHorizCompare = 0.25 * spatium;
    1900          179 :     auto compare = [fuzzyHorizCompare](double x1, double x2) { return std::abs(x1 - x2) < fuzzyHorizCompare; };
    1901          849 :     for (SlurSegment* slur1 : segments) {
    1902         4146 :         for (SlurSegment* slur2 : segments) {
    1903         3478 :             if (slur2 == slur1) {
    1904          668 :                 continue;
    1905              :             }
    1906         2810 :             if (slur1->slur()->endChord() == slur2->slur()->startChord()
    1907         2810 :                 && compare(slur1->ups(Grip::END).p.y(), slur2->ups(Grip::START).p.y())) {
    1908            8 :                 slur1->ups(Grip::END).p.rx() -= slurCollisionHorizOffset;
    1909            8 :                 slur2->ups(Grip::START).p.rx() += slurCollisionHorizOffset;
    1910            8 :                 SlurTieLayout::computeBezier(slur1);
    1911            8 :                 SlurTieLayout::computeBezier(slur2);
    1912            8 :                 continue;
    1913              :             }
    1914              : 
    1915         2802 :             SlurTieSegment* slurTie2 = toSlurTieSegment(slur2);
    1916              : 
    1917              :             // slurs don't collide with themselves or slurs on other staves
    1918         2802 :             if (slur1->vStaffIdx() != slurTie2->vStaffIdx()) {
    1919          922 :                 continue;
    1920              :             }
    1921              :             // slurs which don't overlap don't need to be checked
    1922         1880 :             if (slur1->ups(Grip::END).p.x() < slurTie2->ups(Grip::START).p.x()
    1923         1017 :                 || slurTie2->ups(Grip::END).p.x() < slur1->ups(Grip::START).p.x()
    1924         2897 :                 || slur1->slur()->up() != slurTie2->slurTie()->up()) {
    1925         1802 :                 continue;
    1926              :             }
    1927              :             // START POINT
    1928           78 :             if (compare(slur1->ups(Grip::START).p.x(), slurTie2->ups(Grip::START).p.x())) {
    1929           28 :                 if (slur1->ups(Grip::END).p.x() > slurTie2->ups(Grip::END).p.x() || slurTie2->isTieSegment()) {
    1930              :                     // slur1 is the "outside" slur
    1931            5 :                     slur1->ups(Grip::START).p.ry() += slurCollisionVertOffset * (slur1->slur()->up() ? -1 : 1);
    1932            5 :                     SlurTieLayout::computeBezier(slur1);
    1933              :                 }
    1934              :             }
    1935              :             // END POINT
    1936           78 :             if (compare(slur1->ups(Grip::END).p.x(), slurTie2->ups(Grip::END).p.x())) {
    1937              :                 // slurs have the same endpoint
    1938           24 :                 if (slur1->ups(Grip::START).p.x() < slurTie2->ups(Grip::START).p.x() || slurTie2->isTieSegment()) {
    1939              :                     // slur1 is the "outside" slur
    1940            3 :                     slur1->ups(Grip::END).p.ry() += slurCollisionVertOffset * (slur1->slur()->up() ? -1 : 1);
    1941            3 :                     SlurTieLayout::computeBezier(slur1);
    1942              :                 }
    1943              :             }
    1944              :         }
    1945              :     }
    1946          400 : }
    1947              : 
    1948           74 : LaissezVibSegment* SlurTieLayout::createLaissezVibSegment(LaissezVib* item)
    1949              : {
    1950           74 :     Chord* startChord = item->startNote()->chord();
    1951           74 :     item->setTick(startChord->tick());
    1952              : 
    1953           74 :     calculateDirection(item);
    1954           74 :     calculateIsInside(item);
    1955              : 
    1956           74 :     item->fixupSegments(1);
    1957           74 :     LaissezVibSegment* segment = item->segmentAt(0);
    1958           74 :     segment->setSpannerSegmentType(SpannerSegmentType::SINGLE);
    1959           74 :     segment->setTrack(item->track());
    1960           74 :     segment->moveToSystem(item->startNote()->chord()->segment()->measure()->system());
    1961           74 :     segment->resetAdjustmentOffset();
    1962              : 
    1963           74 :     return segment;
    1964              : }
    1965              : 
    1966           74 : void SlurTieLayout::calculateLaissezVibX(LaissezVibSegment* segment, SlurTiePos& sPos, bool smufl)
    1967              : {
    1968           74 :     LaissezVib* lv = segment->laissezVib();
    1969              : 
    1970           74 :     computeStartAndEndSystem(lv, sPos);
    1971           74 :     sPos.p1 = computeDefaultStartOrEndPoint(lv, Grip::START);
    1972              : 
    1973           74 :     correctForCrossStaff(lv, sPos, SpannerSegmentType::SINGLE);
    1974              : 
    1975           74 :     if (segment->autoplace() && !segment->isEdited()) {
    1976           74 :         adjustX(segment, sPos, Grip::START);
    1977              :     }
    1978              : 
    1979           74 :     if (smufl) {
    1980            0 :         LaissezVibSegment::LayoutData* ldata = segment->mutldata();
    1981            0 :         ldata->symbol = lv->symId();
    1982            0 :         ldata->setBbox(segment->symBbox(ldata->symbol));
    1983            0 :         ldata->setShape(Shape(ldata->bbox(), segment));
    1984            0 :         ldata->setMag(segment->laissezVib()->startNote()->mag());
    1985              :     }
    1986              : 
    1987           74 :     const double width = smufl ? segment->width() : lv->absoluteFromSpatium(lv->minLength());
    1988              : 
    1989           74 :     sPos.p2 = PointF(sPos.p1.x() + width, sPos.p1.y());
    1990           74 : }
    1991              : 
    1992           74 : void SlurTieLayout::calculateLaissezVibY(LaissezVibSegment* segment, SlurTiePos& sPos)
    1993              : {
    1994           74 :     LaissezVib* lv = segment->laissezVib();
    1995              : 
    1996           74 :     adjustYforLedgerLines(segment, sPos);
    1997              : 
    1998           74 :     Note* note = lv->startNote();
    1999           74 :     Chord* chord = note->chord();
    2000              : 
    2001           74 :     const NoteParenthesisInfo* noteParenInfo = chord->findNoteParenthesisInfo(note);
    2002              : 
    2003           74 :     Parenthesis* paren = nullptr;
    2004           74 :     if (noteParenInfo) {
    2005            0 :         paren = noteParenInfo->leftParen();
    2006              :     }
    2007              : 
    2008           74 :     const bool avoidStem = chord->stem() && chord->stem()->visible() && chord->up() == lv->up();
    2009           74 :     if (paren && (!lv->isOuterTieOfChord(Grip::START) || avoidStem)) {
    2010            0 :         RectF parenBbox = paren->ldata()->bbox().translated(paren->systemPos());
    2011            0 :         double adj = sPos.p1.y() - (lv->up() ? parenBbox.top() : parenBbox.bottom());
    2012            0 :         const double PAREN_LV_PADDING = 0.1 * segment->spatium();
    2013            0 :         adj += PAREN_LV_PADDING * (lv->up() ? 1.0 : -1.0);
    2014            0 :         sPos.p1.ry() -= adj;
    2015            0 :         sPos.p2.ry() -= adj;
    2016              :     }
    2017              : 
    2018           74 :     segment->ups(Grip::START).p = sPos.p1;
    2019           74 :     segment->ups(Grip::END).p = sPos.p2;
    2020              : 
    2021           74 :     if (segment->autoplace() && !segment->isEdited()) {
    2022           74 :         adjustY(segment);
    2023              :     } else {
    2024            0 :         computeBezier(segment);
    2025              :     }
    2026           74 : }
    2027              : 
    2028          340 : PartialTieSegment* SlurTieLayout::createPartialTieSegment(PartialTie* item)
    2029              : {
    2030          340 :     Chord* chord = item->isOutgoing() ? item->startNote()->chord() : item->endNote()->chord();
    2031          340 :     item->setTick(chord->tick());
    2032              : 
    2033          340 :     calculateDirection(item);
    2034          340 :     calculateIsInside(item);
    2035              : 
    2036          340 :     item->fixupSegments(1);
    2037          340 :     PartialTieSegment* segment = item->segmentAt(0);
    2038          340 :     segment->setSpannerSegmentType(SpannerSegmentType::SINGLE);
    2039          340 :     segment->moveToSystem(chord->segment()->measure()->system());
    2040          340 :     segment->setTrack(item->track());
    2041          340 :     segment->resetAdjustmentOffset();
    2042          340 :     segment->mutldata()->allJumpPointsInactive = item->allJumpPointsInactive();
    2043              : 
    2044          340 :     return segment;
    2045              : }
    2046              : 
    2047          340 : PartialTieSegment* SlurTieLayout::layoutPartialTie(PartialTie* item)
    2048              : {
    2049          340 :     const bool outgoing = item->isOutgoing();
    2050          340 :     PartialTieSegment* segment = createPartialTieSegment(item);
    2051          340 :     SlurTiePos sPos;
    2052              : 
    2053          340 :     computeStartAndEndSystem(item, sPos);
    2054          340 :     if (outgoing) {
    2055          110 :         sPos.p1 = computeDefaultStartOrEndPoint(item, Grip::START);
    2056              :     } else {
    2057          230 :         sPos.p2 = computeDefaultStartOrEndPoint(item, Grip::END);
    2058              :     }
    2059              : 
    2060          340 :     if (segment->autoplace() && !segment->isEdited()) {
    2061          340 :         adjustX(segment, sPos, outgoing ? Grip::START : Grip::END);
    2062              :     }
    2063              : 
    2064          340 :     setPartialTieEndPos(item, sPos);
    2065              : 
    2066          340 :     correctForCrossStaff(item, sPos, SpannerSegmentType::SINGLE);
    2067              : 
    2068          340 :     adjustYforLedgerLines(segment, sPos);
    2069              : 
    2070          340 :     segment->ups(Grip::START).p = sPos.p1;
    2071          340 :     segment->ups(Grip::END).p = sPos.p2;
    2072              : 
    2073          340 :     if (segment->autoplace() && !segment->isEdited()) {
    2074          340 :         adjustY(segment);
    2075              :     } else {
    2076            0 :         computeBezier(segment);
    2077              :     }
    2078              : 
    2079          340 :     addLineAttachPoints(segment);
    2080              : 
    2081          340 :     return segment;
    2082              : }
    2083              : 
    2084          340 : void SlurTieLayout::setPartialTieEndPos(PartialTie* item, SlurTiePos& sPos)
    2085              : {
    2086          340 :     const bool outgoing = item->isOutgoing();
    2087              : 
    2088          340 :     const Chord* chord = item->parentNote()->chord();
    2089          340 :     const Segment* seg = chord->segment();
    2090          340 :     const Measure* measure = seg->measure();
    2091          340 :     const System* system = measure->system();
    2092              : 
    2093          340 :     if (seg->measure()->isFirstInSystem() && !outgoing) {
    2094           98 :         sPos.p1 = PointF((system ? system->firstNoteRestSegmentX(true) : 0), sPos.p2.y());
    2095           98 :         return;
    2096              :     }
    2097              : 
    2098          243 :     auto shouldSkipSegment = [](const Segment* adjSeg, staff_idx_t staff) {
    2099          482 :         bool inactiveOrInvisible = !adjSeg->isActive() || !adjSeg->enabled() || adjSeg->allElementsInvisible()
    2100          482 :                                    || !adjSeg->hasElements(staff);
    2101          243 :         bool isAboveStaff = adjSeg->isBreathType() || adjSeg->hasTimeSigAboveStaves();
    2102          243 :         return inactiveOrInvisible || isAboveStaff;
    2103              :     };
    2104              : 
    2105          242 :     const Segment* adjSeg = outgoing ? seg->next1() : seg->prev1();
    2106          246 :     while (adjSeg && shouldSkipSegment(adjSeg, item->vStaffIdx())) {
    2107            4 :         adjSeg = outgoing ? adjSeg->next1() : adjSeg->prev1();
    2108              :     }
    2109              : 
    2110          242 :     double widthToSegment = 0.0;
    2111          242 :     if (adjSeg) {
    2112          239 :         EngravingItem* element = adjSeg->element(staff2track(item->vStaffIdx()));
    2113          239 :         double elPos = 0.0;
    2114          239 :         double elementWidth = 0.0;
    2115          239 :         if (element) {
    2116          239 :             const Shape& elemShape = element->shape();
    2117          239 :             elPos = element->pos().x() + elemShape.bbox().x();
    2118          239 :             elementWidth = elemShape.bbox().width();
    2119          239 :         }
    2120              : 
    2121          239 :         const double elPosInSystemCoords = adjSeg->xPosInSystemCoords() + elPos;
    2122          239 :         widthToSegment = outgoing ? elPosInSystemCoords - sPos.p1.x() : sPos.p2.x() - (elPosInSystemCoords + elementWidth);
    2123          132 :         bool incomingFromBarline = !outgoing && element && element->isBarLine()
    2124          371 :                                    && toBarLine(element)->barLineType() != BarLineType::START_REPEAT;
    2125              :         widthToSegment
    2126          239 :             -= item->style().styleAbsolute(incomingFromBarline ? Sid::barlineToLineStartDistance : Sid::lineEndToBarlineDistance);
    2127              :     }
    2128              : 
    2129          242 :     if (outgoing) {
    2130          110 :         sPos.p2 = PointF(sPos.p1.x() + widthToSegment, sPos.p1.y());
    2131              :     } else {
    2132          132 :         sPos.p1 = PointF(sPos.p2.x() - widthToSegment, sPos.p2.y());
    2133              :     }
    2134              : }
    2135              : 
    2136       111790 : void SlurTieLayout::layoutLaissezVibChord(Chord* chord, LayoutContext& ctx)
    2137              : {
    2138              :     // Laissez vib ties should all end at the same rightmost point while honouring each tie's minimum length
    2139              :     // Ties drawn by MuseScore can start at differing points
    2140              :     // SMuFL symbols will also start at the same point because they are of fixed length
    2141       111790 :     double chordLvEndPoint = -DBL_MAX;
    2142       111790 :     std::map<LaissezVibSegment*, SlurTiePos> lvSegmentsWithPositions;
    2143       111790 :     const bool smuflLayout = ctx.conf().styleB(Sid::laissezVibUseSmuflSym);
    2144              : 
    2145       238830 :     for (const Note* note : chord->notes()) {
    2146       127040 :         LaissezVib* lv = note->laissezVib();
    2147       127040 :         if (!lv) {
    2148       126966 :             continue;
    2149              :         }
    2150           74 :         SlurTiePos sPos;
    2151           74 :         LaissezVibSegment* lvSeg = createLaissezVibSegment(lv);
    2152              : 
    2153           74 :         calculateLaissezVibX(lvSeg, sPos, smuflLayout);
    2154              : 
    2155           74 :         chordLvEndPoint = std::max(chordLvEndPoint, sPos.p2.x());
    2156              : 
    2157           74 :         lvSegmentsWithPositions.insert({ lvSeg, sPos });
    2158              :     }
    2159              : 
    2160       111864 :     for (auto& segWithPos : lvSegmentsWithPositions) {
    2161           74 :         LaissezVibSegment* lvSeg = segWithPos.first;
    2162           74 :         Note* note = lvSeg->laissezVib()->startNote();
    2163           74 :         SlurTiePos sPos = segWithPos.second;
    2164           74 :         const double xDiff = chordLvEndPoint - sPos.p2.x();
    2165           74 :         sPos.p2.setX(chordLvEndPoint);
    2166           74 :         if (smuflLayout) {
    2167            0 :             sPos.p1.setX(sPos.p1.x() + xDiff);
    2168              :         }
    2169              : 
    2170           74 :         calculateLaissezVibY(lvSeg, sPos);
    2171              : 
    2172           74 :         LaissezVibSegment::LayoutData* ldata = lvSeg->mutldata();
    2173           74 :         if (smuflLayout) {
    2174            0 :             ldata->setBbox(lvSeg->symBbox(ldata->symbol));
    2175            0 :             ldata->setShape(Shape(ldata->bbox(), lvSeg));
    2176            0 :             ldata->setPos(sPos.p1);
    2177              :         }
    2178              : 
    2179           74 :         double yOrigin = sPos.system1->staff(chord->staffIdx())->y();
    2180           74 :         double yMoved = sPos.system1->staff(chord->vStaffIdx())->y();
    2181           74 :         double yDiff = yMoved - yOrigin;
    2182              : 
    2183           74 :         const PointF chordPos = chord->pos() + chord->segment()->pos() + chord->measure()->pos() + PointF(0.0, yDiff);
    2184           74 :         const PointF notePos = chordPos + note->pos();
    2185           74 :         ldata->posRelativeToNote = sPos.p1 - notePos;
    2186              : 
    2187           74 :         TLayout::fillNoteShape(note, note->mutldata());
    2188              :     }
    2189       111790 : }
    2190              : 
    2191         4820 : void SlurTieLayout::correctForCrossStaff(Tie* tie, SlurTiePos& sPos, SpannerSegmentType type)
    2192              : {
    2193         4820 :     Chord* startChord = tie->startNote() ? tie->startNote()->chord() : nullptr;
    2194         4820 :     Chord* endChord = tie->endNote() ? tie->endNote()->chord() : nullptr;
    2195              : 
    2196         4820 :     if (!startChord) {
    2197           16 :         return;
    2198              :     }
    2199              : 
    2200         4804 :     bool startStaffDiff = startChord->vStaffIdx() != tie->staffIdx();
    2201         4804 :     bool endStaffDiff = endChord ? endChord->vStaffIdx() != tie->staffIdx() : false;
    2202         4804 :     double curY1 = sPos.p1.y();
    2203         4804 :     double curY2 = sPos.p2.y();
    2204              : 
    2205         4804 :     if (type == SpannerSegmentType::BEGIN) {
    2206              :         // Cross-system start tie
    2207          574 :         if (startStaffDiff && sPos.system1) {
    2208            0 :             double yOrigin = sPos.system1->staff(tie->staffIdx())->y();
    2209            0 :             double yMoved = sPos.system1->staff(startChord->vStaffIdx())->y();
    2210            0 :             double yDiff = yMoved - yOrigin;
    2211            0 :             sPos.p1.setY(curY1 + yDiff);
    2212            0 :             sPos.p2.setY(curY2 + yDiff);
    2213              :         }
    2214         4230 :     } else if (type == SpannerSegmentType::SINGLE) {
    2215              :         // Same system single tie
    2216         4230 :         if (startStaffDiff && sPos.system1) {
    2217            0 :             double yOrigin = sPos.system1->staff(tie->staffIdx())->y();
    2218            0 :             double yMoved = sPos.system1->staff(startChord->vStaffIdx())->y();
    2219            0 :             double yDiff = yMoved - yOrigin;
    2220            0 :             sPos.p1.setY(curY1 + yDiff);
    2221            0 :             if (tie->isLaissezVib()) {
    2222            0 :                 sPos.p2.setY(curY2 + yDiff);
    2223            0 :                 return;
    2224              :             }
    2225              :         }
    2226         4230 :         if (!endChord) {
    2227          184 :             return;
    2228              :         }
    2229         4046 :         if (endStaffDiff && sPos.system2) {
    2230            6 :             double yOrigin = sPos.system2->staff(tie->staffIdx())->y();
    2231            6 :             double yMoved = sPos.system2->staff(endChord->vStaffIdx())->y();
    2232            6 :             double yDiff = yMoved - yOrigin;
    2233            6 :             sPos.p2.setY(curY2 + yDiff);
    2234              :         }
    2235              :     }
    2236              : }
    2237              : 
    2238         4406 : void SlurTieLayout::forceHorizontal(Tie* tie, SlurTiePos& sPos)
    2239              : {
    2240         4406 :     Note* startNote = tie->startNote();
    2241         4406 :     Note* endNote = tie->endNote();
    2242              : 
    2243         4406 :     if (startNote && endNote
    2244         4406 :         && startNote->line() == endNote->line()
    2245         8812 :         && startNote->vStaffIdx() == endNote->vStaffIdx()) {
    2246         4067 :         double y1 = sPos.p1.y();
    2247         4067 :         double y2 = sPos.p2.y();
    2248         4067 :         double outerY = tie->up() ? std::min(y1, y2) : std::max(y1, y2);
    2249         4067 :         sPos.p1.setY(outerY);
    2250         4067 :         sPos.p2.setY(outerY);
    2251              :     }
    2252         4406 : }
    2253              : 
    2254         9247 : void SlurTieLayout::adjustX(TieSegment* tieSegment, SlurTiePos& sPos, Grip startOrEnd)
    2255              : {
    2256         9247 :     bool start = startOrEnd == Grip::START;
    2257              : 
    2258         9247 :     PointF& tiePoint = start ? sPos.p1 : sPos.p2;
    2259         9247 :     double resultingX = tiePoint.x();
    2260              : 
    2261         9247 :     Tie* tie = tieSegment->tie();
    2262         9247 :     Note* note = start ? tie->startNote() : tie->endNote();
    2263         9247 :     const Note* otherNote = start ? tie->endNote() : tie->startNote();
    2264         9247 :     if (!note || note->shouldHideFret()) {
    2265         7620 :         return;
    2266              :     }
    2267              : 
    2268         9247 :     Chord* chord = note->chord();
    2269         9247 :     const Chord* otherChord = otherNote ? otherNote->chord() : nullptr;
    2270         9247 :     const Segment* chordSeg = chord->segment();
    2271         9247 :     const double spatium = tieSegment->spatium();
    2272         9247 :     const double padding = 0.20 * spatium * (start ? 1 : -1); // TODO: style
    2273         9247 :     const bool isGrace = (chord && chord->isGrace())
    2274        18494 :                          || ((otherChord && otherChord->isGrace()) && chord->segment() == otherChord->segment());
    2275              : 
    2276         9247 :     PointF systemPos = chordSeg->pos() + chord->measure()->pos() + (isGrace ? chord->pos() : PointF());
    2277         9247 :     if (chord->vStaffIdx() != tieSegment->vStaffIdx()) {
    2278            6 :         System* system = tieSegment->system();
    2279            6 :         double yDiff = system->staff(chord->vStaffIdx())->y() - system->staff(tie->staffIdx())->y();
    2280            6 :         systemPos += PointF(0.0, yDiff);
    2281              :     }
    2282              : 
    2283         9247 :     const bool isOuterTieOfChord = tie->isOuterTieOfChord(startOrEnd);
    2284              : 
    2285         9247 :     TieDotsPlacement dotsPlacement = tie->style().styleV(Sid::tieDotsPlacement).value<TieDotsPlacement>();
    2286         4590 :     bool clearAllDots = start && dotsPlacement == TieDotsPlacement::AFTER_DOTS && !isOuterTieOfChord
    2287        13837 :                         && chord->dots() > 0 && !ChordLayout::chordHasDotsAllInvisible(chord);
    2288         9247 :     if (clearAllDots) {
    2289            0 :         double dotsOuterEdge = -DBL_MAX;
    2290            0 :         for (const Note* n : chord->notes()) {
    2291            0 :             for (const NoteDot* dot : n->dots()) {
    2292            0 :                 dotsOuterEdge = std::max(dotsOuterEdge, dot->x() + dot->width() + n->x());
    2293              :             }
    2294              :         }
    2295            0 :         dotsOuterEdge += systemPos.x();
    2296            0 :         resultingX = dotsOuterEdge + padding;
    2297            0 :         tieSegment->addAdjustmentOffset(PointF(resultingX - tiePoint.x(), 0.0), startOrEnd);
    2298            0 :         tiePoint.setX(resultingX);
    2299            0 :         return;
    2300              :     }
    2301              : 
    2302         9247 :     if (isOuterTieOfChord) {
    2303         8708 :         Tie* otherTie = start ? note->tieBack() : note->tieFor();
    2304         8708 :         bool avoidOtherTie = otherTie && otherTie->up() == tie->up() && !otherTie->isInside();
    2305         8708 :         if (avoidOtherTie) {
    2306         3188 :             resultingX += 0.1 * spatium * (start ? 1 : -1);
    2307              :         }
    2308              :     }
    2309              : 
    2310         9247 :     const bool avoidStem = chord->stem() && chord->stem()->visible() && chord->up() == tie->up();
    2311              : 
    2312         9247 :     if (isOuterTieOfChord && !avoidStem) {
    2313         7620 :         tieSegment->addAdjustmentOffset(PointF(resultingX - tiePoint.x(), 0.0), startOrEnd);
    2314         7620 :         tiePoint.setX(resultingX);
    2315         7620 :         return;
    2316              :     }
    2317              : 
    2318         1627 :     Shape shape = isGrace ? chord->shape().translate(systemPos) : chordSeg->staffShape(chord->vStaffIdx()).translated(systemPos);
    2319         1627 :     bool ignoreDot = start && (isOuterTieOfChord || dotsPlacement == TieDotsPlacement::BEFORE_DOTS);
    2320         1627 :     bool ignoreLvSeg = tieSegment->isLaissezVibSegment();
    2321         1627 :     bool ignoreArpeggio = note == chord->downNote() && !tie->up();
    2322         1627 :     bool ignoreParen = tieSegment->isLaissezVibSegment() && start;
    2323          771 :     auto ignoreAccidental = [&](const Accidental* acc) {
    2324          771 :         bool accIsInwardOfTie = tie->up() ? acc->line() >= note->line() : acc->line() <= note->line();
    2325          771 :         return !start && isOuterTieOfChord && accIsInwardOfTie;
    2326         1627 :     };
    2327              : 
    2328              :     static const std::set<ElementType> IGNORED_TYPES = {
    2329              :         ElementType::HOOK,
    2330              :         ElementType::STEM_SLASH,
    2331              :         ElementType::LEDGER_LINE,
    2332              :         ElementType::LYRICS,
    2333              :         ElementType::HARMONY,
    2334              :         ElementType::FRET_DIAGRAM
    2335         1643 :     };
    2336         1627 :     shape.remove_if([&](ShapeElement& s) {
    2337        22364 :         bool remove =  !s.item() || s.item() == note || muse::contains(IGNORED_TYPES, s.item()->type())
    2338         6625 :                       || (s.item()->isNoteDot() && ignoreDot)
    2339         6565 :                       || (s.item()->isAccidental() && ignoreAccidental(toAccidental(s.item())))
    2340         6545 :                       || (s.item()->isLaissezVibSegment() && ignoreLvSeg)
    2341         6345 :                       || ((s.item()->isArpeggio() || s.item()->isChordBracket()) && ignoreArpeggio)
    2342         6339 :                       || (s.item()->isParenthesis() && ignoreParen)
    2343        22364 :                       || !s.item()->addToSkyline();
    2344        11182 :         return remove;
    2345              :     });
    2346              : 
    2347         1627 :     const double arcSideMargin = 0.3 * spatium;
    2348         1627 :     const double pointsSideMargin = 0.15 * spatium;
    2349         1627 :     const double yBelow = tiePoint.y() - (tie->up() ? arcSideMargin : pointsSideMargin);
    2350         1627 :     const double yAbove = tiePoint.y() + (tie->up() ? pointsSideMargin : arcSideMargin);
    2351         1627 :     double pointToClear = start ? shape.rightMostEdgeAtHeight(yBelow, yAbove)
    2352          812 :                           : shape.leftMostEdgeAtHeight(yBelow, yAbove);
    2353              : 
    2354         1627 :     pointToClear += padding;
    2355              : 
    2356         1627 :     resultingX = start ? std::max(resultingX, pointToClear) : std::min(resultingX, pointToClear);
    2357              : 
    2358         1627 :     adjustXforLedgerLines(tieSegment, start, chord, note, systemPos, padding, resultingX);
    2359              : 
    2360         1627 :     tieSegment->addAdjustmentOffset(PointF(resultingX - tiePoint.x(), 0.0), startOrEnd);
    2361         1627 :     tiePoint.setX(resultingX);
    2362         1627 : }
    2363              : 
    2364         1627 : void SlurTieLayout::adjustXforLedgerLines(TieSegment* tieSegment, bool start, Chord* chord, Note* note,
    2365              :                                           const PointF& chordSystemPos, double padding, double& resultingX)
    2366              : {
    2367         1627 :     if (tieSegment->tie()->isInside() || chord->ledgerLines().empty()) {
    2368         1442 :         return;
    2369              :     }
    2370              : 
    2371          758 :     bool isOuterNote = note == chord->upNote() || note == chord->downNote();
    2372          758 :     if (isOuterNote) {
    2373          325 :         return;
    2374              :     }
    2375              : 
    2376          433 :     bool ledgersAbove = false;
    2377          433 :     bool ledgersBelow = false;
    2378         2016 :     for (LedgerLine* ledger : chord->ledgerLines()) {
    2379         1591 :         if (ledger->y() < 0.0) {
    2380          456 :             ledgersAbove = true;
    2381              :         } else {
    2382         1135 :             ledgersBelow = true;
    2383              :         }
    2384         1591 :         if (ledgersAbove && ledgersBelow) {
    2385            8 :             break;
    2386              :         }
    2387              :     }
    2388              : 
    2389          433 :     int noteLine = note->line();
    2390          433 :     bool isOddLine = noteLine % 2 != 0;
    2391          433 :     bool isAboveStaff = noteLine <= 0;
    2392          433 :     bool isBelowStaff = noteLine >= 2 * (note->staff()->lines(note->tick()) - 1);
    2393          433 :     bool isInsideStaff = !isAboveStaff && !isBelowStaff;
    2394          433 :     if (isOddLine || isInsideStaff || (isAboveStaff && !ledgersAbove) || (isBelowStaff && !ledgersBelow)) {
    2395          248 :         return;
    2396              :     }
    2397              : 
    2398          185 :     Shape noteShape = note->shape();
    2399          185 :     noteShape.remove_if([&](ShapeElement& s) {
    2400          237 :         return !s.item()->addToSkyline() || s.item()->isNoteDot() || (tieSegment->isLaissezVibSegment() && s.item()->isLaissezVibSegment());
    2401              :     });
    2402          185 :     noteShape.translate(note->pos() + chordSystemPos);
    2403          185 :     double xNoteEdge = (start ? noteShape.right() : noteShape.left()) + padding;
    2404              : 
    2405          185 :     resultingX = start ? std::max(resultingX, xNoteEdge) : std::min(resultingX, xNoteEdge);
    2406          185 : }
    2407              : 
    2408         5415 : void SlurTieLayout::adjustYforLedgerLines(TieSegment* tieSegment, SlurTiePos& sPos)
    2409              : {
    2410         5415 :     Tie* tie = tieSegment->tie();
    2411         5415 :     Note* note = tieSegment->isSingleBeginType() ? tie->startNote() : tie->endNote();
    2412         5415 :     if (!note) {
    2413         4507 :         return;
    2414              :     }
    2415              : 
    2416         5399 :     Chord* chord = note->chord();
    2417         5399 :     if (chord->ledgerLines().empty()) {
    2418         4491 :         return;
    2419              :     }
    2420          908 :     PointF chordSystemPos = chord->pos() + chord->segment()->pos() + chord->segment()->measure()->pos();
    2421          908 :     PointF& tiePoint = tieSegment->isSingleBeginType() ? sPos.p1 : sPos.p2;
    2422          908 :     double spatium = tie->spatium();
    2423          908 :     int upSign = tie->up() ? -1 : 1;
    2424          908 :     double margin = 0.4 * spatium;
    2425              : 
    2426         3119 :     for (LedgerLine* ledger : chord->ledgerLines()) {
    2427         2284 :         PointF ledgerPos = ledger->pos() + chordSystemPos;
    2428         2284 :         double yDiff = upSign * (ledgerPos.y() - tiePoint.y());
    2429         2284 :         bool collision = yDiff > 0 && yDiff < margin;
    2430         2284 :         if (collision) {
    2431           73 :             sPos.p1 += PointF(0.0, -upSign * (margin - yDiff));
    2432           73 :             sPos.p2 += PointF(0.0, -upSign * (margin - yDiff));
    2433           73 :             computeBezier(tieSegment);
    2434           73 :             break;
    2435              :         }
    2436              :     }
    2437              : }
    2438              : 
    2439         6010 : void SlurTieLayout::adjustY(TieSegment* tieSegment)
    2440              : {
    2441         6010 :     Staff* staff = tieSegment->score() ? tieSegment->score()->staff(tieSegment->vStaffIdx()) : nullptr;
    2442         6010 :     if (!staff) {
    2443         2805 :         return;
    2444              :     }
    2445              : 
    2446         6010 :     const double spatium = tieSegment->spatium();
    2447         6010 :     TieSegment::LayoutData* ldata = tieSegment->mutldata();
    2448              : 
    2449         6010 :     ldata->setPos(PointF());
    2450         6010 :     ldata->moveY(tieSegment->staffOffsetY());
    2451              : 
    2452         6010 :     Fraction tick = tieSegment->tick();
    2453              : 
    2454         6010 :     computeBezier(tieSegment);
    2455              : 
    2456         6010 :     bool up = tieSegment->tie()->up();
    2457         6010 :     int upSign = up ? -1 : 1;
    2458              : 
    2459         6010 :     const double staffLineDist = staff->lineDistance(tick) * spatium;
    2460         6010 :     const double staffLineThickness = tieSegment->style().styleAbsolute(Sid::staffLineWidth) * staff->staffMag(tick);
    2461              : 
    2462              :     // 1. Check for bad end point protrusion
    2463              : 
    2464         6010 :     const double endPointY = tieSegment->ups(Grip::START).p.y();
    2465         6010 :     const int closestLineToEndpoints = up ? floor(endPointY / staffLineDist) : ceil(endPointY / staffLineDist);
    2466         6010 :     const bool isEndInsideStaff = closestLineToEndpoints >= 0 && closestLineToEndpoints < staff->lines(tick);
    2467         6010 :     const bool isEndInsideLedgerLines = !isEndInsideStaff && !tieSegment->tie()->isOuterTieOfChord(Grip::START);
    2468              : 
    2469         6010 :     const double halfLineThicknessCorrection = 0.5 * staffLineThickness * upSign;
    2470         6010 :     const double protrusion = std::abs(endPointY - (closestLineToEndpoints * spatium - halfLineThicknessCorrection));
    2471         6010 :     const double badIntersectionLimit = 0.15 * spatium; // TODO: style
    2472              : 
    2473         6010 :     bool badIntersection = protrusion < badIntersectionLimit && (isEndInsideStaff || isEndInsideLedgerLines);
    2474         6010 :     if (badIntersection) {
    2475          388 :         double correctedY = closestLineToEndpoints * spatium + halfLineThicknessCorrection + badIntersectionLimit * upSign;
    2476          388 :         tieSegment->addAdjustmentOffset(PointF(0.0, correctedY - endPointY), Grip::START);
    2477          388 :         tieSegment->addAdjustmentOffset(PointF(0.0, correctedY - endPointY), Grip::END);
    2478          388 :         tieSegment->ups(Grip::START).p.setY(correctedY);
    2479          388 :         tieSegment->ups(Grip::END).p.setY(correctedY);
    2480          388 :         computeBezier(tieSegment);
    2481              :     }
    2482              : 
    2483              :     // 2. Check for bad arc protrusion
    2484              : 
    2485         6010 :     RectF tieSegmentBBox = tieSegment->ldata()->bbox();
    2486         6010 :     double tieLength = tieSegmentBBox.width();
    2487         6010 :     double tieHeight = tieSegmentBBox.height();
    2488         6010 :     double midThickness = tieSegment->ldata()->midThickness() * 2;
    2489         6010 :     double yOuterApogee = up ? tieSegmentBBox.top() : tieSegmentBBox.bottom();
    2490         6010 :     double yInnerApogee = yOuterApogee - midThickness * upSign;
    2491         6010 :     double yMidApogee = 0.5 * (yOuterApogee + yInnerApogee);
    2492              : 
    2493         6010 :     int closestLineToArc = round(yMidApogee / staffLineDist);
    2494         6010 :     bool isArcInsideStaff =  closestLineToArc >= 0 && closestLineToArc < staff->lines(tick);
    2495         6010 :     if (!isArcInsideStaff) {
    2496         1304 :         return;
    2497              :     }
    2498              : 
    2499         4706 :     double outwardMargin = -upSign * (yOuterApogee - (closestLineToArc * staffLineDist - halfLineThicknessCorrection));
    2500         4706 :     double inwardMargin = upSign * (yInnerApogee - (closestLineToArc * staffLineDist + halfLineThicknessCorrection));
    2501         4706 :     const double badArcIntersectionLimit = tieLength < 3 * spatium ? 0.1 * spatium : 0.15 * spatium;
    2502              : 
    2503         4706 :     bool increaseArc = outwardMargin - 0.5 * badArcIntersectionLimit < inwardMargin;
    2504         4706 :     bool correctOutwards = inwardMargin < badArcIntersectionLimit && increaseArc;
    2505         4706 :     bool correctInwards = outwardMargin < badArcIntersectionLimit && !increaseArc;
    2506              : 
    2507         4706 :     if (!correctInwards && !correctOutwards) {
    2508         1441 :         return;
    2509              :     }
    2510              : 
    2511         3265 :     bool isSmallTie = tieLength < 2.0 * spatium && tieHeight < 0.7 * spatium;
    2512              :     // For ties this small, try to fit them within a staff space before changing their arc
    2513         3265 :     if (isSmallTie) {
    2514         2366 :         Tie* tie2 = tieSegment->tie();
    2515         2366 :         bool isInside = tie2->isInside();
    2516         2366 :         bool isOuterOfChord = tie2->isOuterTieOfChord(Grip::START) || tie2->isOuterTieOfChord(Grip::END);
    2517         2366 :         bool hasTiedSecondInside = tie2->hasTiedSecondInside();
    2518         2366 :         if (!isInside && !isOuterOfChord && !hasTiedSecondInside && !hasEndPointAboveNote(tieSegment)) {
    2519           60 :             double currentY = tieSegment->ups(Grip::START).p.y();
    2520           60 :             double yCorrection = -upSign * (badArcIntersectionLimit - outwardMargin);
    2521           60 :             tieSegment->addAdjustmentOffset(PointF(0.0, yCorrection), Grip::START);
    2522           60 :             tieSegment->addAdjustmentOffset(PointF(0.0, yCorrection), Grip::END);
    2523           60 :             tieSegment->ups(Grip::START).p.setY(currentY + yCorrection);
    2524           60 :             tieSegment->ups(Grip::END).p.setY(currentY + yCorrection);
    2525           60 :             computeBezier(tieSegment);
    2526           60 :             return;
    2527              :         } else {
    2528         2306 :             correctOutwards = true;
    2529              :         }
    2530              :     }
    2531              : 
    2532         3205 :     double arcCorrection = correctOutwards ? (badArcIntersectionLimit - inwardMargin) : (badArcIntersectionLimit - outwardMargin);
    2533         3205 :     double maxArcCorrection = 0.75 * tieHeight;
    2534         3205 :     double rest = arcCorrection > maxArcCorrection ? arcCorrection - maxArcCorrection : 0.0;
    2535         3205 :     arcCorrection = std::min(arcCorrection, maxArcCorrection);
    2536         3205 :     if (correctOutwards) {
    2537         2867 :         if (rest > 0) {
    2538         1952 :             rest *= upSign;
    2539         1952 :             double currentY = tieSegment->ups(Grip::START).p.y();
    2540         1952 :             tieSegment->addAdjustmentOffset(PointF(0.0, rest), Grip::START);
    2541         1952 :             tieSegment->addAdjustmentOffset(PointF(0.0, rest), Grip::END);
    2542         1952 :             tieSegment->ups(Grip::START).p.setY(currentY + rest);
    2543         1952 :             tieSegment->ups(Grip::END).p.setY(currentY + rest);
    2544              :         }
    2545         2867 :         computeBezier(tieSegment, PointF(0.0, -arcCorrection));
    2546          338 :     } else if (correctInwards) {
    2547          338 :         computeBezier(tieSegment, PointF(0.0, arcCorrection));
    2548              :     }
    2549              : }
    2550              : 
    2551          147 : bool SlurTieLayout::hasEndPointAboveNote(TieSegment* tieSegment)
    2552              : {
    2553          147 :     Note* startNote = tieSegment->tie()->startNote();
    2554          147 :     Note* endNote = tieSegment->tie()->endNote();
    2555              : 
    2556          147 :     if ((tieSegment->isSingleBeginType() && !startNote) || (tieSegment->isSingleEndType() && !endNote)) {
    2557            0 :         return false;
    2558              :     }
    2559              : 
    2560          147 :     Chord* startChord = startNote->chord();
    2561          147 :     PointF startNotePos = startNote->pos() + startChord->pos() + startChord->segment()->pos() + startChord->measure()->pos();
    2562              : 
    2563          147 :     Chord* endChord = endNote->chord();
    2564          147 :     PointF endNotePos = endNote->pos() + endChord->pos() + endChord->segment()->pos() + endChord->measure()->pos();
    2565              : 
    2566          147 :     PointF tieStartPos = tieSegment->ups(Grip::START).pos();
    2567          147 :     PointF tieEndPos = tieSegment->ups(Grip::END).pos();
    2568              : 
    2569          227 :     return (tieStartPos.x() < startNotePos.x() + startNote->width() && !startNote->shouldHideFret())
    2570          227 :            || (tieEndPos.x() > endNotePos.x() && !endNote->shouldHideFret());
    2571              : }
    2572              : 
    2573       106374 : void SlurTieLayout::resolveVerticalTieCollisions(const std::vector<TieSegment*>& stackedTies)
    2574              : {
    2575       106374 :     if (stackedTies.size() < 2) {
    2576       106273 :         return;
    2577              :     }
    2578              : 
    2579          101 :     std::list<TieSegment*> downwardTies;
    2580          101 :     std::list<TieSegment*> upwardTies;
    2581          412 :     for (TieSegment* tieSegment : stackedTies) {
    2582          311 :         if (!tieSegment->tie()->up()) {
    2583          161 :             downwardTies.push_front(tieSegment);
    2584              :         } else {
    2585          150 :             upwardTies.push_back(tieSegment);
    2586              :         }
    2587              :     }
    2588              : 
    2589          110 :     auto fixTieCollision = [](TieSegment* thisTie, TieSegment* nextTie) {
    2590          110 :         double spatium = thisTie->spatium();
    2591          110 :         bool up = thisTie->tie()->up();
    2592          110 :         int upSign = up ? -1 : 1;
    2593              : 
    2594          110 :         double thisTieOuterY = up ? thisTie->ldata()->bbox().top() : thisTie->ldata()->bbox().bottom();
    2595          110 :         double nextTieInnerY = (up ? nextTie->ldata()->bbox().top() : nextTie->ldata()->bbox().bottom())
    2596          110 :                                - upSign * 2 * nextTie->ldata()->midThickness();
    2597          110 :         double clearanceMargin = 0.15 * spatium;
    2598          110 :         bool collision = upSign * (nextTieInnerY - thisTieOuterY) < clearanceMargin;
    2599          110 :         if (!collision) {
    2600          110 :             return;
    2601              :         }
    2602              : 
    2603            0 :         if (!thisTie->score()) {
    2604            0 :             return;
    2605              :         }
    2606            0 :         Staff* staff = thisTie->score() ? thisTie->score()->staff(thisTie->vStaffIdx()) : nullptr;
    2607            0 :         if (!staff) {
    2608            0 :             return;
    2609              :         }
    2610              : 
    2611            0 :         Fraction tick = thisTie->tick();
    2612            0 :         double yMidPoint = 0.5 * (thisTieOuterY + nextTieInnerY);
    2613            0 :         double halfLineDist = 0.5 * staff->lineDistance(tick) * spatium;
    2614            0 :         int midLine = round(yMidPoint / halfLineDist);
    2615            0 :         bool insideStaff = midLine >= -1 && midLine <= 2 * (staff->lines(tick) - 1) + 1;
    2616            0 :         if (insideStaff) {
    2617            0 :             yMidPoint = midLine * halfLineDist;
    2618              :         }
    2619              : 
    2620            0 :         double thisTieYCorrection = yMidPoint - upSign * 0.5 * clearanceMargin - thisTieOuterY;
    2621            0 :         double nextTieYCorrection = yMidPoint + upSign * 0.5 * clearanceMargin - nextTieInnerY;
    2622              : 
    2623            0 :         double thisShoulderOff = thisTie->adjustmentOffset(Grip::BEZIER1).y();
    2624            0 :         double nextShoulderOff = nextTie->adjustmentOffset(Grip::BEZIER1).y();
    2625              :         // Subtract it otherwise it gets summed twice
    2626            0 :         thisTie->addAdjustmentOffset(PointF(0.0, -thisShoulderOff), Grip::BEZIER1);
    2627            0 :         thisTie->addAdjustmentOffset(PointF(0.0, -thisShoulderOff), Grip::BEZIER2);
    2628            0 :         nextTie->addAdjustmentOffset(PointF(0.0, -nextShoulderOff), Grip::BEZIER1);
    2629            0 :         nextTie->addAdjustmentOffset(PointF(0.0, -nextShoulderOff), Grip::BEZIER2);
    2630              : 
    2631            0 :         computeBezier(thisTie, PointF(0.0, -upSign * (thisShoulderOff + thisTieYCorrection)));
    2632            0 :         computeBezier(nextTie, PointF(0.0, -upSign * (nextShoulderOff + nextTieYCorrection)));
    2633              :     };
    2634              : 
    2635          101 :     if (upwardTies.size() >= 2) {
    2636          180 :         for (auto it = upwardTies.begin(); std::next(it, 1) != upwardTies.end(); ++it) {
    2637           49 :             TieSegment* thisTie = *it;
    2638           49 :             TieSegment* nextTie = *(std::next(it, 1));
    2639           49 :             fixTieCollision(thisTie, nextTie);
    2640              :         }
    2641              :     }
    2642              : 
    2643          101 :     if (downwardTies.size() >= 2) {
    2644          218 :         for (auto it = downwardTies.begin(); std::next(it, 1) != downwardTies.end(); ++it) {
    2645           61 :             TieSegment* thisTie = *it;
    2646           61 :             TieSegment* nextTie = *(std::next(it, 1));
    2647           61 :             fixTieCollision(thisTie, nextTie);
    2648              :         }
    2649              :     }
    2650          101 : }
    2651              : 
    2652         1783 : void SlurTieLayout::computeUp(Slur* slur, LayoutContext& ctx)
    2653              : {
    2654         1783 :     switch (slur->slurDirection()) {
    2655           97 :     case DirectionV::UP:
    2656           97 :         slur->setUp(true);
    2657           97 :         break;
    2658           89 :     case DirectionV::DOWN:
    2659           89 :         slur->setUp(false);
    2660           89 :         break;
    2661         1597 :     case DirectionV::AUTO:
    2662              :     {
    2663              :         //
    2664              :         // assumption:
    2665              :         // slurs have only chords or rests as start/end elements
    2666              :         //
    2667         1597 :         ChordRest* chordRest1 = slur->startCR();
    2668         1597 :         ChordRest* chordRest2 = slur->endCR();
    2669         1597 :         if (chordRest1 == 0 || chordRest2 == 0) {
    2670            0 :             slur->setUp(true);
    2671            0 :             break;
    2672              :         }
    2673         1597 :         Chord* chord1 = slur->startCR()->isChord() ? toChord(slur->startCR()) : 0;
    2674         1597 :         Chord* chord2 = slur->endCR()->isChord() ? toChord(slur->endCR()) : 0;
    2675         1575 :         if (chord2 && !chord2->staff()->isDrumStaff(chord2->tick())
    2676         3172 :             && slur->startCR()->measure()->system() != slur->endCR()->measure()->system()) {
    2677              :             // HACK: if the end chord is in a different system, it may have never been laid out yet.
    2678              :             // But we need to know its direction to decide slur direction, so need to compute it here.
    2679          437 :             for (Note* note : chord2->notes()) {
    2680          219 :                 note->updateLine(); // because chord direction is based on note lines
    2681              :             }
    2682              : 
    2683          218 :             ChordLayout::computeUp(chord2, ctx);
    2684              :         }
    2685              : 
    2686         1597 :         if (chord1 && chord1->beam() && chord1->beam()->cross()) {
    2687              :             // TODO: stem direction is not finalized, so we cannot use it here
    2688            0 :             slur->setUp(true);
    2689            0 :             break;
    2690              :         }
    2691              : 
    2692         1597 :         if (chord1 && chord1->onJianpuStaff()) {
    2693              :             // In Jianpu mode, slurs follow the opposite side of the diminution beams.
    2694            0 :             slur->setUp(ctx.conf().style().styleV(Sid::jianpuDiminutionBeamPlacement).value<PlacementV>() != PlacementV::ABOVE);
    2695            0 :             break;
    2696              :         }
    2697              : 
    2698         1597 :         slur->setUp(!(chordRest1->up()));
    2699              : 
    2700              :         // Check if multiple voices
    2701         1597 :         bool multipleVoices = false;
    2702         1597 :         Measure* m1 = chordRest1->measure();
    2703         3280 :         while (m1 && m1->tick() <= chordRest2->tick()) {
    2704         1955 :             if ((m1->hasVoices(chordRest1->staffIdx(), slur->tick(), slur->ticks() + chordRest2->ticks()))
    2705         1955 :                 && chord1) {
    2706          272 :                 multipleVoices = true;
    2707          272 :                 break;
    2708              :             }
    2709         1683 :             m1 = m1->nextMeasure();
    2710              :         }
    2711         1597 :         if (multipleVoices) {
    2712              :             // slurs go on the stem side
    2713          272 :             if (chordRest1->voice() > 0 || chordRest2->voice() > 0) {
    2714          183 :                 slur->setUp(false);
    2715              :             } else {
    2716           89 :                 slur->setUp(true);
    2717              :             }
    2718         1325 :         } else if (chord1 && chord2 && !chord1->isGrace() && isDirectionMixture(chord1, chord2, ctx)) {
    2719              :             // slurs go above if there are mixed direction stems between c1 and c2
    2720              :             // but grace notes are exceptions
    2721          161 :             slur->setUp(true);
    2722         1164 :         } else if (chord1 && chord2 && chord1->isGrace() && chord2 != chord1->parent() && isDirectionMixture(chord1, chord2, ctx)) {
    2723            0 :             slur->setUp(true);
    2724              :         }
    2725              :     }
    2726         1597 :     break;
    2727              :     }
    2728         1783 : }
    2729              : 
    2730         9736 : void SlurTieLayout::computeBezier(TieSegment* tieSeg, PointF shoulderOffset)
    2731              : {
    2732         9736 :     const PointF tieStart = tieSeg->ups(Grip::START).p + tieSeg->ups(Grip::START).off;
    2733         9736 :     const PointF tieEnd = tieSeg->ups(Grip::END).p + tieSeg->ups(Grip::END).off;
    2734         9736 :     if (!muse::RealIsEqualOrMore(tieEnd.x(), tieStart.x())) {
    2735         4480 :         return;
    2736              :     }
    2737              : 
    2738         6384 :     PointF tieEndNormalized = tieEnd - tieStart;  // normalize to zero
    2739         6384 :     if (muse::RealIsNull(tieEndNormalized.x())) {
    2740         1128 :         return;
    2741              :     }
    2742              : 
    2743         5256 :     const double tieAngle = atan(tieEndNormalized.y() / tieEndNormalized.x()); // angle required from tie start to tie end--zero if horizontal
    2744         5256 :     Transform t;
    2745         5256 :     t.rotateRadians(-tieAngle);  // rotate so that we are working with horizontal ties regardless of endpoint height difference
    2746         5256 :     tieEndNormalized = t.map(tieEndNormalized);  // apply that rotation
    2747         5256 :     shoulderOffset = t.map(shoulderOffset);  // also apply to shoulderOffset
    2748              : 
    2749         5256 :     const double _spatium = tieSeg->spatium();
    2750         5256 :     double tieLengthInSp = tieEndNormalized.x() / _spatium;
    2751              : 
    2752         5256 :     const double minShoulderHeight = tieSeg->minShoulderHeight();
    2753         5256 :     const double maxShoulderHeight = tieSeg->maxShoulderHeight();
    2754         5256 :     double shoulderH = minShoulderHeight + _spatium * 0.3 * sqrt(std::abs(tieLengthInSp - 1));
    2755         5256 :     shoulderH = std::clamp(shoulderH, minShoulderHeight, maxShoulderHeight);
    2756              : 
    2757         5256 :     shoulderH -= shoulderOffset.y();
    2758              : 
    2759         5256 :     PointF shoulderAdjustOffset = tieSeg->tie()->up() ? PointF(0.0, shoulderOffset.y()) : PointF(0.0, -shoulderOffset.y());
    2760         5256 :     tieSeg->addAdjustmentOffset(shoulderAdjustOffset, Grip::BEZIER1);
    2761         5256 :     tieSeg->addAdjustmentOffset(shoulderAdjustOffset, Grip::BEZIER2);
    2762              : 
    2763         5256 :     if (!tieSeg->tie()->up()) {
    2764         1531 :         shoulderH = -shoulderH;
    2765              :     }
    2766              : 
    2767         5256 :     double shoulderW = 0.6; // TODO: style
    2768              : 
    2769         5256 :     const double tieWidth = tieEndNormalized.x();
    2770         5256 :     const double bezier1X = (tieWidth - tieWidth * shoulderW) * .5 + shoulderOffset.x();
    2771         5256 :     const double bezier2X = bezier1X + tieWidth * shoulderW + shoulderOffset.x();
    2772              : 
    2773         5256 :     const PointF tieDrag = PointF(tieWidth * .5, 0.0);
    2774              : 
    2775         5256 :     const PointF bezier1(bezier1X, -shoulderH);
    2776         5256 :     const PointF bezier2(bezier2X, -shoulderH);
    2777              : 
    2778         5256 :     computeMidThickness(tieSeg, tieLengthInSp);
    2779              : 
    2780         5256 :     PointF tieThickness(0.0, 0.0);
    2781         5256 :     if (tieSeg->tie()->styleType() == SlurStyleType::Solid) {
    2782         5228 :         tieThickness.setY(tieSeg->ldata()->midThickness());
    2783              :     }
    2784              : 
    2785         5256 :     const PointF bezier1Offset = t.map(tieSeg->ups(Grip::BEZIER1).off);
    2786         5256 :     const PointF bezier2Offset = t.map(tieSeg->ups(Grip::BEZIER2).off);
    2787              : 
    2788              :     //-----------------------------------calculate p6
    2789         5256 :     const PointF bezier1Final = bezier1 + bezier1Offset;
    2790         5256 :     const PointF bezier2Final = bezier2 + bezier2Offset;
    2791              : 
    2792         5256 :     const PointF tieShoulder = 0.5 * (bezier1Final + bezier2Final);
    2793              :     //-----------------------------------
    2794              : 
    2795         5256 :     PainterPath path = PainterPath();
    2796         5256 :     path.moveTo(PointF());
    2797         5256 :     path.cubicTo(bezier1 + bezier1Offset - tieThickness, bezier2 + bezier2Offset - tieThickness, tieEndNormalized);
    2798         5256 :     if (tieSeg->tie()->styleType() == SlurStyleType::Solid) {
    2799         5228 :         path.cubicTo(bezier2 + bezier2Offset + tieThickness, bezier1 + bezier1Offset + tieThickness, PointF());
    2800              :     }
    2801              : 
    2802              :     // translate back
    2803         5256 :     t.reset();
    2804         5256 :     t.translate(tieStart.x(), tieStart.y());
    2805         5256 :     t.rotateRadians(tieAngle);
    2806         5256 :     path = t.map(path);
    2807         5256 :     tieSeg->mutldata()->path.set_value(path);
    2808              : 
    2809         5256 :     tieSeg->ups(Grip::BEZIER1).p = t.map(bezier1);
    2810         5256 :     tieSeg->ups(Grip::BEZIER2).p = t.map(bezier2);
    2811         5256 :     tieSeg->ups(Grip::END).p = t.map(tieEndNormalized) - tieSeg->ups(Grip::END).off;
    2812         5256 :     tieSeg->ups(Grip::DRAG).p = t.map(tieDrag);
    2813         5256 :     tieSeg->ups(Grip::SHOULDER).p = t.map(tieShoulder);
    2814              : 
    2815         5256 :     fillShape(tieSeg, tieLengthInSp);
    2816         5256 : }
    2817              : 
    2818          969 : void SlurTieLayout::computeBezier(SlurSegment* slurSeg, PointF shoulderOffset)
    2819              : {
    2820              :     /* ************************************************
    2821              :      * LEGEND: pp1 = start point
    2822              :      *         pp2 = end point
    2823              :      *         p2 = end point (in slur coordinates)
    2824              :      *         p3 = first bezier point (in slur coord.)
    2825              :      *         p4 = second bezier point (in slur coord.)
    2826              :      *         p5 = whole slur drag point (in slur coord.)
    2827              :      *         p6 = shoulder drag point (in slur coord.)
    2828              :      * REMEMBER! ups().pos() = ups().p + ups().off
    2829              :      * ***********************************************/
    2830              :     // Avoid bad staff line intersections
    2831          969 :     if (slurSeg->autoplace()) {
    2832          963 :         adjustEndPoints(slurSeg);
    2833              :     }
    2834              :     // If end point adjustment is locked, restore the endpoints to
    2835              :     // where they were before
    2836          969 :     if (slurSeg->isEndPointsEdited()) {
    2837            4 :         slurSeg->ups(Grip::START).off += slurSeg->endPointOff1();
    2838            4 :         slurSeg->ups(Grip::END).off += slurSeg->endPointOff2();
    2839              :     }
    2840              :     // Get start and end points (have been calculated before)
    2841          969 :     PointF pp1 = slurSeg->ups(Grip::START).p + slurSeg->ups(Grip::START).off;
    2842          969 :     PointF pp2 = slurSeg->ups(Grip::END).p + slurSeg->ups(Grip::END).off;
    2843              :     // Keep track of the original value before it gets changed
    2844          969 :     PointF oldp1 = pp1;
    2845          969 :     PointF oldp2 = pp2;
    2846              : 
    2847              :     // Set up coordinate transforms
    2848              :     // CAUTION: transform operations are applies in reverse order to how
    2849              :     // they are added to the transformation.
    2850          969 :     double slurAngle = atan((pp2.y() - pp1.y()) / (pp2.x() - pp1.x()));
    2851          969 :     Transform rotate;
    2852          969 :     rotate.rotateRadians(-slurAngle);
    2853          969 :     Transform toSlurCoordinates;
    2854          969 :     toSlurCoordinates.rotateRadians(-slurAngle);
    2855          969 :     toSlurCoordinates.translate(-pp1.x(), -pp1.y());
    2856          969 :     Transform toSystemCoordinates = toSlurCoordinates.inverted();
    2857              :     // Transform p2 and shoulder offset
    2858          969 :     PointF p2 = toSlurCoordinates.map(pp2);
    2859          969 :     shoulderOffset = rotate.map(shoulderOffset);
    2860              : 
    2861              :     // COMPUTE DEFAULT SLUR SHAPE
    2862              :     // Compute default shoulder height and width
    2863          969 :     double _spatium  = slurSeg->spatium();
    2864              :     double shoulderW; // expressed as fraction of slur-length
    2865          969 :     double d = p2.x() / _spatium;
    2866              : 
    2867          969 :     if (d < 0) {
    2868              :         //! NOTE A negative d means that end point is before the start point.
    2869              :         //! This only exists as a temporary state when horizontal spacing hasn't yet been computed,
    2870              :         //! and it makes no sense for any of the following calculations
    2871            0 :         return;
    2872              :     }
    2873              : 
    2874          969 :     if (d < 2) {
    2875           28 :         shoulderW = 0.60;
    2876          941 :     } else if (d < 10) {
    2877          489 :         shoulderW = 0.5;
    2878          452 :     } else if (d < 18) {
    2879          282 :         shoulderW = 0.6;
    2880              :     } else {
    2881          170 :         shoulderW = 0.7;
    2882              :     }
    2883              : 
    2884          969 :     double shoulderH = computeShoulderHeight(slurSeg, d, shoulderOffset);
    2885              : 
    2886          969 :     double c    = p2.x();
    2887          969 :     double c1   = (c - c * shoulderW) * .5 + shoulderOffset.x();
    2888          969 :     double c2   = c1 + c * shoulderW + shoulderOffset.x();
    2889          969 :     PointF p3(c1, -shoulderH);
    2890          969 :     PointF p4(c2, -shoulderH);
    2891              :     // Set Bezier points default position
    2892          969 :     slurSeg->ups(Grip::BEZIER1).p  = toSystemCoordinates.map(p3);
    2893          969 :     slurSeg->ups(Grip::BEZIER2).p  = toSystemCoordinates.map(p4);
    2894              :     // Add offsets
    2895          969 :     p3 += shoulderOffset + rotate.map(slurSeg->ups(Grip::BEZIER1).off);
    2896          969 :     p4 += shoulderOffset + rotate.map(slurSeg->ups(Grip::BEZIER2).off);
    2897          969 :     slurSeg->ups(Grip::BEZIER1).off += rotate.inverted().map(shoulderOffset);
    2898          969 :     slurSeg->ups(Grip::BEZIER2).off += rotate.inverted().map(shoulderOffset);
    2899              : 
    2900              :     // ADAPT SLUR SHAPE AND ENDPOINT POSITION
    2901              :     // to clear collisions with underlying items
    2902          969 :     if (slurSeg->autoplace() && !slurSeg->isTappingHalfSlurSegment()) {
    2903          931 :         avoidCollisions(slurSeg, pp1, p2, p3, p4, toSystemCoordinates, slurAngle);
    2904              :     }
    2905              : 
    2906              :     // Re-check end points for bad staff line collisions
    2907          969 :     slurSeg->ups(Grip::START).p = pp1 - slurSeg->ups(Grip::START).off;
    2908          969 :     slurSeg->ups(Grip::END).p = toSystemCoordinates.map(p2) - slurSeg->ups(Grip::END).off;
    2909          969 :     adjustEndPoints(slurSeg);
    2910          969 :     PointF newpp1 = slurSeg->ups(Grip::START).p + slurSeg->ups(Grip::START).off;
    2911          969 :     PointF difference = rotate.map(newpp1 - pp1);
    2912          969 :     pp1 = newpp1;
    2913          969 :     pp2 = slurSeg->ups(Grip::END).p + slurSeg->ups(Grip::END).off;
    2914          969 :     p3 -= difference;
    2915          969 :     p4 -= difference;
    2916              :     // Keep track of how much the end points position has changed
    2917          969 :     if (!slurSeg->isEndPointsEdited()) {
    2918          965 :         slurSeg->setEndPointOff1(pp1 - oldp1);
    2919          965 :         slurSeg->setEndPointOff2(pp2 - oldp2);
    2920              :     } else {
    2921            4 :         slurSeg->setEndPointOff1(PointF());
    2922            4 :         slurSeg->setEndPointOff2(PointF());
    2923              :     }
    2924              :     // Recompute the transformation because pp1 and pp1 may have changed
    2925          969 :     toSlurCoordinates.reset();
    2926          969 :     toSlurCoordinates.rotateRadians(-slurAngle);
    2927          969 :     toSlurCoordinates.translate(-pp1.x(), -pp1.y());
    2928          969 :     toSystemCoordinates = toSlurCoordinates.inverted();
    2929          969 :     p2 = toSlurCoordinates.map(pp2);
    2930              : 
    2931              :     // Calculate p5 and p6
    2932          969 :     PointF p5 = 0.5 * p2; // mid-point between pp1 and p2
    2933          969 :     PointF p6 = 0.5 * (p3 + p4); // mid-point between p3 and p4
    2934              : 
    2935              :     // Update all slur points after collision avoidance
    2936          969 :     slurSeg->ups(Grip::BEZIER1).p  = toSystemCoordinates.map(p3) - slurSeg->ups(Grip::BEZIER1).off;
    2937          969 :     slurSeg->ups(Grip::BEZIER2).p  = toSystemCoordinates.map(p4) - slurSeg->ups(Grip::BEZIER2).off;
    2938          969 :     slurSeg->ups(Grip::DRAG).p     = toSystemCoordinates.map(p5);
    2939          969 :     slurSeg->ups(Grip::SHOULDER).p = toSystemCoordinates.map(p6);
    2940              : 
    2941              :     // Set slur thickness
    2942          969 :     computeMidThickness(slurSeg, p2.x() / slurSeg->spatium());
    2943              : 
    2944          969 :     PointF thick(0.0, 0.0);
    2945          969 :     if (slurSeg->slur()->styleType() == SlurStyleType::Solid) {
    2946          940 :         thick.setY(slurSeg->ldata()->midThickness());
    2947              :     }
    2948              : 
    2949              :     // Set path
    2950          969 :     PainterPath path = PainterPath();
    2951          969 :     path.moveTo(PointF());
    2952          969 :     path.cubicTo(p3 - thick, p4 - thick, p2);
    2953          969 :     if (slurSeg->slur()->styleType() == SlurStyleType::Solid) {
    2954          940 :         path.cubicTo(p4 + thick, p3 + thick, PointF());
    2955              :     }
    2956              : 
    2957          969 :     path = toSystemCoordinates.map(path);
    2958          969 :     slurSeg->mutldata()->path.set_value(path);
    2959              : 
    2960          969 :     fillShape(slurSeg, p2.x() / slurSeg->spatium());
    2961          969 : }
    2962              : 
    2963          969 : double SlurTieLayout::computeShoulderHeight(SlurSegment* slurSeg, double slurLengthInSp, PointF shoulderOffset)
    2964              : {
    2965          969 :     double spatium = slurSeg->spatium();
    2966              : 
    2967          969 :     if (slurSeg->isTappingHalfSlurSegment()) {
    2968           32 :         double shoulderH = (slurSeg->staffType()->isTabStaff() ? 1.0 : 0.6) * spatium;
    2969           32 :         return slurSeg->slur()->up() ? shoulderH : -shoulderH;
    2970              :     }
    2971              : 
    2972          937 :     double shoulderH = sqrt(slurLengthInSp / 4) * spatium;
    2973              : 
    2974              :     static constexpr double shoulderReduction = 0.75;
    2975          937 :     if (isOverBeams(slurSeg->slur())) {
    2976           15 :         shoulderH *= shoulderReduction;
    2977              :     }
    2978              : 
    2979          937 :     shoulderH -= shoulderOffset.y();
    2980          937 :     if (!slurSeg->slur()->up()) {
    2981          532 :         shoulderH = -shoulderH;
    2982              :     }
    2983              : 
    2984          937 :     return shoulderH;
    2985              : }
    2986              : 
    2987            0 : double SlurTieLayout::defaultStemLengthStart(TremoloTwoChord* tremolo)
    2988              : {
    2989            0 :     return TremoloLayout::extendedStemLenWithTwoNoteTremolo(tremolo,
    2990              :                                                             tremolo->chord1()->defaultStemLength(),
    2991            0 :                                                             tremolo->chord2()->defaultStemLength()).first;
    2992              : }
    2993              : 
    2994            0 : double SlurTieLayout::defaultStemLengthEnd(TremoloTwoChord* tremolo)
    2995              : {
    2996            0 :     return TremoloLayout::extendedStemLenWithTwoNoteTremolo(tremolo,
    2997              :                                                             tremolo->chord1()->defaultStemLength(),
    2998            0 :                                                             tremolo->chord2()->defaultStemLength()).second;
    2999              : }
    3000              : 
    3001         1283 : bool SlurTieLayout::isDirectionMixture(const Chord* c1, const Chord* c2, LayoutContext& ctx)
    3002              : {
    3003         1283 :     if (c1->track() != c2->track()) {
    3004           11 :         return false;
    3005              :     }
    3006         1272 :     const bool up = c1->up();
    3007         1272 :     if (c2->isGrace() && c2->up() != up) {
    3008            6 :         return true;
    3009              :     }
    3010         1266 :     if (c1->isGraceBefore() && c2->isGraceAfter() && c1->ownershipParent() == c2->ownershipParent()) {
    3011            2 :         const Chord* mainChord = toChord(c1->ownershipParent());
    3012            2 :         if (mainChord->stem() && mainChord->up() != up) {
    3013            0 :             return true;
    3014              :         }
    3015              :     }
    3016         1266 :     const track_idx_t track = c1->track();
    3017         4916 :     for (const Segment* seg = c1->segment(); seg && seg->tick() <= c2->tick(); seg = seg->next1(SegmentType::ChordRest)) {
    3018         3850 :         if ((c1->isGrace() || c2->isGraceBefore()) && seg->tick() == c2->tick()) {
    3019              :             // if slur ends at a grace-note-before, we don't need to look at the main note
    3020           45 :             return false;
    3021              :         }
    3022         3805 :         EngravingItem* e = seg->element(track);
    3023         3805 :         if (!e || !e->isChord()) {
    3024          192 :             continue;
    3025              :         }
    3026         3613 :         Chord* c = toChord(e);
    3027         3613 :         const Measure* m = c->measure();
    3028         3613 :         const System* c1Sys = c1->measure()->system();
    3029         3613 :         const System* cSys = m->system();
    3030         3613 :         if (!c->staff()->isDrumStaff(c->tick()) && c1Sys && cSys && c1Sys != cSys) {
    3031              :             // This chord is on a different system and may not have been laid out yet
    3032           16 :             for (Note* note : c->notes()) {
    3033            8 :                 note->updateLine();     // because chord direction is based on note lines
    3034              :             }
    3035            8 :             ChordLayout::computeUp(c, ctx);
    3036              :         }
    3037              : 
    3038         3613 :         if (c->up() != up) {
    3039          155 :             return true;
    3040              :         }
    3041              :     }
    3042         1066 :     return false;
    3043              : }
    3044              : 
    3045          945 : bool SlurTieLayout::shouldHideSlurSegment(SlurSegment* item)
    3046              : {
    3047          945 :     if (item->isHammerOnPullOffSegment()) {
    3048           62 :         return false;
    3049              :     }
    3050              : 
    3051          883 :     if (item->configuration()->specificSlursLayoutWorkaround()) {
    3052            0 :         Slur* slur = item->slur();
    3053            0 :         if (slur->connectedElement() == Slur::ConnectedElement::GLISSANDO) {
    3054            0 :             return false;
    3055              :         }
    3056              :     }
    3057              : 
    3058          883 :     const StaffType* stType = item->staffType();
    3059          883 :     if (stType && stType->isHiddenElementOnTab(Sid::slurShowTabCommon, Sid::slurShowTabSimple)) {
    3060            0 :         return true;
    3061              :     }
    3062              : 
    3063          883 :     return false;
    3064              : }
    3065              : 
    3066         5001 : void SlurTieLayout::addLineAttachPoints(TieSegment* segment)
    3067              : {
    3068              :     // Add tie attach point to start and end note of segment
    3069         5001 :     Tie* tie = segment->tie();
    3070         5001 :     Note* startNote = tie->startNote();
    3071         5001 :     Note* endNote = tie->endNote();
    3072              : 
    3073         5001 :     const bool singleOrBegin = segment->spannerSegmentType() == SpannerSegmentType::SINGLE
    3074         5001 :                                || segment->spannerSegmentType() == SpannerSegmentType::BEGIN;
    3075              : 
    3076         5001 :     const bool singleOrEnd = segment->spannerSegmentType() == SpannerSegmentType::SINGLE
    3077         5001 :                              || segment->spannerSegmentType() == SpannerSegmentType::END;
    3078              : 
    3079         5001 :     if (startNote && singleOrBegin) {
    3080         4406 :         startNote->addStartLineAttachPoint(segment->ups(Grip::START).pos(), tie);
    3081              :     }
    3082         5001 :     if (endNote && singleOrEnd) {
    3083         4427 :         endNote->addEndLineAttachPoint(segment->ups(Grip::END).pos(), tie);
    3084              :     }
    3085         5001 : }
    3086              : 
    3087          340 : void SlurTieLayout::addLineAttachPoints(PartialTieSegment* segment)
    3088              : {
    3089              :     // Add tie attach point to parent note
    3090          340 :     PartialTie* tie = segment->partialTie();
    3091          340 :     Note* note = tie ? tie->note() : nullptr;
    3092          340 :     if (!note) {
    3093            0 :         return;
    3094              :     }
    3095              : 
    3096          340 :     const bool isOutgoing = tie->isOutgoing();
    3097              : 
    3098          340 :     if (isOutgoing) {
    3099          110 :         note->addStartLineAttachPoint(segment->ups(Grip::START).pos(), tie);
    3100              :     } else {
    3101          230 :         note->addEndLineAttachPoint(segment->ups(Grip::END).pos(), tie);
    3102              :     }
    3103              : }
    3104              : 
    3105         4857 : void SlurTieLayout::calculateDirection(Tie* item)
    3106              : {
    3107         4857 :     if (!item->startNote() && !item->endNote()) {
    3108            0 :         return;
    3109              :     }
    3110         4857 :     const bool tieHasBothNotes = item->startNote() && item->endNote();
    3111              : 
    3112         4857 :     const Note* primaryNote = item->startNote() ? item->startNote() : item->endNote();
    3113         4857 :     const Chord* primaryChord = primaryNote->chord();
    3114         4857 :     const Measure* primaryMeasure = primaryChord->measure();
    3115              : 
    3116         4857 :     const Note* secondaryNote = tieHasBothNotes ? item->endNote() : nullptr;
    3117         4857 :     const Chord* secondaryChord = secondaryNote ? secondaryNote->chord() : nullptr;
    3118         4857 :     const Measure* secondaryMeasure = secondaryChord ? secondaryChord->measure() : nullptr;
    3119              : 
    3120         4857 :     if (item->slurDirection() == DirectionV::AUTO) {
    3121         4722 :         std::vector<Note*> notes = primaryChord->notes();
    3122         4722 :         size_t n = notes.size();
    3123         4722 :         StaffType* st = item->staff()->staffType(primaryNote ? primaryNote->tick() : Fraction(0, 1));
    3124         4722 :         bool simpleException = st && st->isSimpleTabStaff();
    3125              :         // if there are multiple voices, the tie direction goes on stem side
    3126         4722 :         if (item->staff()->isJianpuStaff(primaryNote ? primaryNote->tick() : Fraction(0, 1))) {
    3127            0 :             item->setUp(true);
    3128         4722 :         } else if (primaryMeasure->hasVoices(primaryChord->staffIdx(), primaryChord->tick(), primaryChord->actualTicks())) {
    3129          330 :             item->setUp(simpleException ? isUpVoice(primaryChord->voice()) : primaryChord->up());
    3130         4392 :         } else if (tieHasBothNotes && secondaryMeasure->hasVoices(secondaryChord->staffIdx(), secondaryChord->tick(),
    3131              :                                                                   secondaryChord->actualTicks())) {
    3132           15 :             item->setUp(simpleException ? isUpVoice(secondaryChord->voice()) : secondaryChord->up());
    3133         4377 :         } else if (n == 1) {
    3134              :             //
    3135              :             // single note
    3136              :             //
    3137         3738 :             if (tieHasBothNotes && primaryChord->up() != secondaryChord->up()) {
    3138              :                 // if stem direction is mixed, always up
    3139          167 :                 item->setUp(true);
    3140              :             } else {
    3141         3571 :                 item->setUp(!primaryChord->up());
    3142              :             }
    3143              :         } else {
    3144              :             //
    3145              :             // chords
    3146              :             //
    3147              :             // first, find pivot point in chord (below which all ties curve down and above which all ties curve up)
    3148          639 :             Note* pivotPoint = nullptr;
    3149          639 :             bool multiplePivots = false;
    3150         2396 :             for (size_t i = 0; i < n - 1; ++i) {
    3151         1757 :                 if (!notes[i]->tieFor()) {
    3152          174 :                     continue; // don't include notes that don't have ties
    3153              :                 }
    3154         5122 :                 for (size_t j = i + 1; j < n; ++j) {
    3155         3539 :                     if (!notes[j]->tieFor()) {
    3156          148 :                         continue;
    3157              :                     }
    3158         3391 :                     int noteDiff = compareNotesPos(notes[i], notes[j]);
    3159         3391 :                     if (!multiplePivots && std::abs(noteDiff) <= 1) {
    3160              :                         // TODO: Fix unison ties somehow--if noteDiff == 0 then we need to determine which of the unison is 'lower'
    3161          180 :                         if (pivotPoint) {
    3162           18 :                             multiplePivots = true;
    3163           18 :                             pivotPoint = nullptr;
    3164              :                         } else {
    3165          162 :                             pivotPoint = noteDiff < 0 ? notes[i] : notes[j];
    3166              :                         }
    3167              :                     }
    3168              :                 }
    3169              :             }
    3170          639 :             if (!pivotPoint) {
    3171              :                 // if the pivot point was not found (either there are no unisons/seconds or there are more than one),
    3172              :                 // determine if this note is in the lower or upper half of this chord
    3173          495 :                 int notesAbove = 0, tiesAbove = 0;
    3174          495 :                 int notesBelow = 0, tiesBelow = 0;
    3175          495 :                 int unisonTies = 0;
    3176         2103 :                 for (size_t i = 0; i < n; ++i) {
    3177         1608 :                     if (notes[i] == primaryNote) {
    3178              :                         // skip counting if this note is the current note or if this note doesn't have a tie
    3179          495 :                         continue;
    3180              :                     }
    3181         1113 :                     int noteDiff = compareNotesPos(primaryNote, notes[i]);
    3182         1113 :                     if (noteDiff == 0) {  // unison
    3183            0 :                         if (notes[i]->tieFor()) {
    3184            0 :                             unisonTies++;
    3185              :                         }
    3186              :                     }
    3187         1113 :                     if (noteDiff < 0) { // the note is above startNote
    3188          537 :                         notesAbove++;
    3189          537 :                         if (notes[i]->tieFor()) {
    3190          461 :                             tiesAbove++;
    3191              :                         }
    3192              :                     }
    3193         1113 :                     if (noteDiff > 0) { // the note is below startNote
    3194          576 :                         notesBelow++;
    3195          576 :                         if (notes[i]->tieFor()) {
    3196          446 :                             tiesBelow++;
    3197              :                         }
    3198              :                     }
    3199              :                 }
    3200              : 
    3201          495 :                 if (tiesAbove == 0 && tiesBelow == 0 && unisonTies == 0) {
    3202              :                     // this is the only tie in the chord.
    3203           64 :                     if (notesAbove == notesBelow) {
    3204            4 :                         item->setUp(!primaryChord->up());
    3205              :                     } else {
    3206           60 :                         item->setUp(notesAbove < notesBelow);
    3207              :                     }
    3208          431 :                 } else if (tiesAbove == tiesBelow) {
    3209              :                     // this note is dead center, so its tie should go counter to the stem direction
    3210           24 :                     item->setUp(!primaryChord->up());
    3211              :                 } else {
    3212          407 :                     item->setUp(tiesAbove < tiesBelow);
    3213              :                 }
    3214          144 :             } else if (pivotPoint == primaryNote) {
    3215              :                 // the current note is the lower of the only second or unison in the chord; tie goes down.
    3216           28 :                 item->setUp(false);
    3217              :             } else {
    3218              :                 // if lower than the pivot, tie goes down, otherwise up
    3219          116 :                 int noteDiff = compareNotesPos(primaryNote, pivotPoint);
    3220          116 :                 item->setUp(noteDiff >= 0);
    3221              :             }
    3222              :         }
    3223         4722 :     } else {
    3224          135 :         item->setUp(item->slurDirection() == DirectionV::UP ? true : false);
    3225              :     }
    3226              : }
    3227              : 
    3228         4820 : void SlurTieLayout::calculateIsInside(Tie* item)
    3229              : {
    3230         4820 :     if (item->tiePlacement() != TiePlacement::AUTO) {
    3231            0 :         item->setIsInside(item->tiePlacement() == TiePlacement::INSIDE);
    3232            0 :         return;
    3233              :     }
    3234              : 
    3235         4820 :     const Note* startN = item->startNote();
    3236         4820 :     const Chord* startChord = startN ? startN->chord() : nullptr;
    3237         4820 :     const Note* endN = item->endNote();
    3238         4820 :     const Chord* endChord = endN ? endN->chord() : nullptr;
    3239              : 
    3240         4820 :     if (!startChord && !endChord) {
    3241            0 :         item->setIsInside(false);
    3242            0 :         return;
    3243              :     }
    3244              : 
    3245         4820 :     const bool startIsSingleNote = startChord ? startChord->notes().size() <= 1 : false;
    3246         4820 :     const bool endIsSingleNote = endChord ? endChord->notes().size() <= 1 : false;
    3247              : 
    3248         4820 :     const bool shouldPlaceInside = startChord && endChord ? startIsSingleNote && endIsSingleNote : startIsSingleNote || endIsSingleNote;
    3249              : 
    3250         4820 :     if (shouldPlaceInside) {
    3251         4063 :         item->setIsInside(item->style().styleV(Sid::tiePlacementSingleNote).value<TiePlacement>() == TiePlacement::INSIDE);
    3252              :     } else {
    3253          757 :         item->setIsInside(item->style().styleV(Sid::tiePlacementChord).value<TiePlacement>() == TiePlacement::INSIDE);
    3254              :     }
    3255              : }
    3256              : 
    3257          945 : void SlurTieLayout::layoutSegment(SlurSegment* item, const PointF& p1, const PointF& p2)
    3258              : {
    3259          945 :     SlurSegment::LayoutData* ldata = item->mutldata();
    3260          945 :     if (shouldHideSlurSegment(item)) {
    3261            0 :         ldata->setIsSkipDraw(true);
    3262            0 :         return;
    3263              :     }
    3264              : 
    3265          945 :     ldata->setIsSkipDraw(false);
    3266              : 
    3267          945 :     ldata->setPos(PointF());
    3268          945 :     item->ups(Grip::START).p = p1;
    3269          945 :     item->ups(Grip::END).p   = p2;
    3270          945 :     item->setExtraHeight(0.0);
    3271              : 
    3272              :     //Adjust Y pos to staff type yOffset before other calculations
    3273          945 :     ldata->moveY(item->staffOffsetY());
    3274              : 
    3275          945 :     computeBezier(item);
    3276              : }
    3277              : 
    3278         6225 : void SlurTieLayout::computeMidThickness(SlurTieSegment* slurTieSeg, double slurTieLengthInSp)
    3279              : {
    3280         6225 :     Staff* staff = slurTieSeg->score() ? slurTieSeg->score()->staff(slurTieSeg->vStaffIdx()) : nullptr;
    3281         6225 :     const double mag = staff ? staff->staffMag(slurTieSeg->slurTie()->tick()) : 1.0;
    3282         6225 :     const double scalingFactor = slurTieSeg->slurTie()->scalingFactor();
    3283              : 
    3284         6225 :     if (slurTieSeg->slurTie()->styleType() != SlurStyleType::Solid) {
    3285           57 :         slurTieSeg->mutldata()->midThickness.set_value(0.5 * slurTieSeg->dottedWidth() * mag * scalingFactor);
    3286           57 :         return;
    3287              :     }
    3288              : 
    3289         6168 :     const double endWidth = slurTieSeg->endWidth();
    3290         6168 :     const double midWidth = slurTieSeg->midWidth();
    3291         6168 :     const double minTieLength = mag * slurTieSeg->style().styleS(Sid::minTieLength).val();
    3292         6168 :     const double shortTieLimit = mag * 4.0;
    3293         6168 :     const double minTieThickness = mag * (0.15 * slurTieSeg->spatium() - endWidth);
    3294         6168 :     const double normalThickness = mag * (midWidth - endWidth);
    3295              : 
    3296         6168 :     bool invalid = muse::RealIsEqualOrMore(minTieLength, shortTieLimit);
    3297              : 
    3298              :     double finalThickness;
    3299         6168 :     if (slurTieLengthInSp > shortTieLimit || invalid) {
    3300         3123 :         finalThickness = normalThickness;
    3301              :     } else {
    3302         3045 :         const double A = 1 / (shortTieLimit - minTieLength);
    3303         3045 :         const double B = normalThickness - minTieThickness;
    3304         3045 :         const double C = shortTieLimit * minTieThickness - minTieLength * normalThickness;
    3305         3045 :         finalThickness = A * (B * slurTieLengthInSp + C);
    3306              :     }
    3307              : 
    3308         6168 :     finalThickness = std::min(finalThickness, normalThickness * scalingFactor);
    3309              : 
    3310         6168 :     slurTieSeg->mutldata()->midThickness.set_value(finalThickness);
    3311              : }
    3312              : 
    3313         6225 : void SlurTieLayout::fillShape(SlurTieSegment* slurTieSeg, double slurTieLengthInSp)
    3314              : {
    3315         6225 :     Shape shape(Shape::Type::Composite);
    3316         6225 :     PointF startPoint = slurTieSeg->ups(Grip::START).pos();
    3317              : 
    3318         6225 :     double midThickness = 2 * slurTieSeg->ldata()->midThickness();
    3319         6225 :     int nbShapes = round(5.0 * slurTieLengthInSp);
    3320         6225 :     nbShapes = std::max(nbShapes, 20);
    3321         6225 :     nbShapes = std::min(nbShapes, 50);
    3322        12450 :     const CubicBezier b(startPoint, slurTieSeg->ups(Grip::BEZIER1).pos(), slurTieSeg->ups(Grip::BEZIER2).pos(),
    3323        18675 :                         slurTieSeg->ups(Grip::END).pos());
    3324       202962 :     for (int i = 1; i <= nbShapes; i++) {
    3325       196737 :         double percent = pow(sin(0.5 * M_PI * (double(i) / double(nbShapes))), 2);
    3326       196737 :         const PointF point = b.pointAtPercent(percent);
    3327       196737 :         RectF re = RectF(startPoint, point).normalized();
    3328       196737 :         double approxThicknessAtPercent = midThickness;
    3329       196737 :         if (slurTieSeg->slurTie()->styleType() == SlurStyleType::Solid) {
    3330       194280 :             approxThicknessAtPercent *= (1 - 2 * std::abs(0.5 - percent));
    3331              :         }
    3332       196737 :         if (re.height() < approxThicknessAtPercent) {
    3333        90543 :             double adjust = (approxThicknessAtPercent - re.height()) * .5;
    3334        90543 :             re.adjust(0.0, -adjust, 0.0, adjust);
    3335              :         }
    3336       196737 :         shape.add(re, slurTieSeg);
    3337       196737 :         startPoint = point;
    3338              :     }
    3339              : 
    3340         6225 :     slurTieSeg->mutldata()->setShape(shape);
    3341         6225 : }
        

Generated by: LCOV version 2.0-1