LCOV - code coverage report
Current view: top level - src/engraving/rendering/score - lyricslayout.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 93.7 % 508 476
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 "lyricslayout.h"
      23              : 
      24              : #include "dom/factory.h"
      25              : #include "dom/repeatlist.h"
      26              : #include "style/styledef.h"
      27              : 
      28              : #include "dom/chordrest.h"
      29              : #include "dom/lyrics.h"
      30              : #include "dom/measure.h"
      31              : #include "dom/score.h"
      32              : #include "dom/segment.h"
      33              : #include "dom/staff.h"
      34              : #include "dom/stafftype.h"
      35              : #include "dom/system.h"
      36              : 
      37              : #include "tlayout.h"
      38              : #include "textlayout.h"
      39              : 
      40              : using namespace mu;
      41              : using namespace mu::engraving;
      42              : using namespace mu::engraving::rendering::score;
      43              : 
      44         2374 : void LyricsLayout::layout(Lyrics* item, LayoutContext& ctx)
      45              : {
      46         2374 :     if (!item->ownershipParent()) {   // palette & clone trick
      47            0 :         item->setPos(PointF());
      48            0 :         TextLayout::layoutBaseTextBase1(item, ctx);
      49            0 :         return;
      50              :     }
      51              : 
      52         2374 :     Lyrics::LayoutData* ldata = item->mutldata();
      53              : 
      54              :     //
      55              :     // parse leading verse number and/or punctuation, so we can factor it into layout separately
      56              :     //
      57         2374 :     bool hasNumber = false;   // _verseNumber;
      58              : 
      59              :     // find:
      60              :     // 1) string of numbers and non-word characters at start of syllable
      61              :     // 2) at least one other character (indicating start of actual lyric)
      62              :     // 3) string of non-word characters at end of syllable
      63              :     //QRegularExpression leadingPattern("(^[\\d\\W]+)([^\\d\\W]+)");
      64              : 
      65         2374 :     const String text = item->plainText();
      66         2374 :     String leading;
      67         2374 :     String trailing;
      68              : 
      69         2374 :     if (ctx.conf().styleB(Sid::lyricsAlignVerseNumber)) {
      70         2374 :         size_t leadingIdx = 0;
      71         2532 :         for (size_t i = 0; i < text.size(); ++i) {
      72         2452 :             Char ch = text.at(i);
      73         2452 :             if (ch.isLetter()) {
      74         2294 :                 leadingIdx = i;
      75         2294 :                 break;
      76              :             }
      77              :         }
      78              : 
      79         2374 :         if (leadingIdx != 0) {
      80           30 :             leading = text.mid(0, leadingIdx);
      81              :         }
      82              : 
      83         2374 :         size_t trailingIdx = text.size() - 1;
      84         2760 :         for (int i = static_cast<int>(text.size() - 1); i >= 0; --i) {
      85         2680 :             Char ch = text.at(i);
      86         2680 :             if (ch.isLetter()) {
      87         2294 :                 trailingIdx = i;
      88         2294 :                 break;
      89              :             }
      90              :         }
      91              : 
      92         2374 :         if (trailingIdx != text.size() - 1) {
      93          288 :             trailing = text.mid(trailingIdx + 1);
      94              :         }
      95              : 
      96         2374 :         if (!leading.isEmpty() && leading.at(0).isDigit()) {
      97           24 :             hasNumber = true;
      98              :         }
      99              :     }
     100              : 
     101         2374 :     createOrRemoveLyricsLine(item, ctx);
     102              : 
     103         2374 :     if (item->isMelisma() || hasNumber) {
     104              :         // use the melisma style alignment setting
     105          190 :         if (item->isStyled(Pid::POSITION)) {
     106          190 :             if (ctx.conf().styleB(Sid::lyricsCenterDashedSyllables) && !(item->separator() && item->separator()->isEndMelisma())) {
     107            0 :                 item->setPosition(AlignH::HCENTER);
     108              :             } else {
     109          190 :                 item->setPosition(ctx.conf().styleV(Sid::lyricsMelismaAlign).value<Align>().horizontal);
     110              :             }
     111              :         }
     112              :     } else {
     113              :         // use the text style alignment setting
     114         2184 :         if (item->isStyled(Pid::POSITION)) {
     115         2159 :             item->setPosition(item->propertyDefault(Pid::POSITION).value<AlignH>());
     116              :         }
     117              :     }
     118              : 
     119              :     // Negate ChordRest offset
     120         2374 :     ChordRest* cr = item->chordRest();
     121         2374 :     double x = -cr->x();
     122              : 
     123              :     /* Preserve the vertical position: a lyric's Y is set in computeVerticalPositions(). Necessary
     124              :      * because layoutBaseTextBase1() ends with ldata->move(defaultPos), which accumulates a downward
     125              :      * shift of the lyric if the current function is called in a partially-relaid system without a
     126              :      * following computeVerticalPositions() call. */
     127         2374 :     const double posY = ldata->pos().y();
     128         2374 :     TextLayout::layoutBaseTextBase1(item, ctx);
     129         2374 :     TextLayout::computeTextHighResShape(item, ldata);
     130         2374 :     ldata->setPosY(posY);
     131              : 
     132         2374 :     double centerAdjust = 0.0;
     133         2374 :     double leftAdjust   = 0.0;
     134              : 
     135         2374 :     if (ctx.conf().styleB(Sid::lyricsAlignVerseNumber)) {
     136              :         // Calculate leading and trailing parts widths. Lyrics
     137              :         // should have text layout to be able to do it correctly.
     138         2374 :         DO_ASSERT(ldata->blocks.size() != 0);
     139         2374 :         if (!leading.isEmpty() || !trailing.isEmpty()) {
     140              : //                   LOGD("create leading, trailing <%s> -- <%s><%s>", muPrintable(text), muPrintable(leading), muPrintable(trailing));
     141          315 :             const TextBlock& tb = ldata->blocks.at(0);
     142              : 
     143          315 :             const double leadingWidth = tb.xpos(leading.size(), item) - tb.boundingRect().x();
     144          315 :             const size_t trailingPos = text.size() - trailing.size();
     145          315 :             const double trailingWidth = tb.boundingRect().right() - tb.xpos(trailingPos, item);
     146              : 
     147          315 :             leftAdjust = leadingWidth;
     148          315 :             centerAdjust = leadingWidth - trailingWidth;
     149              :         }
     150              :     }
     151              : 
     152         2374 :     if (item->position() == AlignH::HCENTER) {
     153              :         //
     154              :         // center under notehead, not origin
     155              :         // however, lyrics that are melismas or have verse numbers will be forced to left alignment
     156              :         //
     157              :         // center under note head
     158         2159 :         x += -centerAdjust * 0.5;
     159          215 :     } else if (item->position() == AlignH::LEFT) {
     160              :         // even for left aligned syllables, ignore leading verse numbers and/or punctuation
     161          215 :         x -= leftAdjust;
     162              :     }
     163              : 
     164         2374 :     ldata->setPosX(x);
     165              : 
     166         2374 :     if (item->ticks().isNotZero()) {
     167              :         // set melisma end
     168          107 :         ChordRest* ecr = ctx.mutDom().findCR(item->endTick(), item->track());
     169          107 :         if (ecr) {
     170          107 :             ecr->setMelismaEnd(true);
     171              :         }
     172              :     }
     173         2374 : }
     174              : 
     175          341 : void LyricsLayout::layout(LyricsLine* item)
     176              : {
     177          341 :     if (item->isDash()) {    // dash(es)
     178          234 :         item->setNextLyrics(searchNextLyrics(item->lyrics()->segment(),
     179              :                                              item->staffIdx(),
     180          234 :                                              item->lyrics()->verse(),
     181          234 :                                              item->lyrics()->placement()
     182              :                                              ));
     183          234 :         item->setTrack2(item->nextLyrics() ? item->nextLyrics()->track() : item->track());
     184              : 
     185          234 :         Fraction endTick = item->tick();
     186          234 :         const Measure* lyricsMeasure = item->lyrics()->segment()->measure();
     187          234 :         const Segment* endCRSeg = lyricsMeasure ? lyricsMeasure->last(SegmentType::ChordRest) : nullptr;
     188              : 
     189          234 :         const ChordRest* endCR = nullptr;
     190          234 :         if (endCRSeg && !endCRSeg->empty()) {
     191          532 :             for (EngravingItem* cr : endCRSeg->elist()) {
     192          532 :                 if (cr && cr->isChordRest()) {
     193          234 :                     endCR = toChordRest(cr);
     194          234 :                     break;
     195              :                 }
     196              :             }
     197              :         }
     198              : 
     199          234 :         if (item->nextLyrics()) {
     200          228 :             endTick = item->nextLyrics()->tick();
     201            6 :         } else if (endCR && endCR->hasFollowingJumpItem()) {
     202            1 :             endTick = endCR->tick();
     203              :         }
     204              : 
     205          234 :         item->setTick2(endTick);
     206              :     }
     207          341 : }
     208              : 
     209          364 : void LyricsLayout::layout(LyricsLineSegment* item, LayoutContext& ctx)
     210              : {
     211              :     UNUSED(ctx);
     212              : 
     213          364 :     assert(item->isPartialLyricsLineSegment() || item->lyrics());
     214              : 
     215          364 :     LyricsLineSegment::LayoutData* ldata = item->mutldata();
     216          364 :     ldata->clearDashes();
     217          364 :     ldata->clearReferenceLyrics();
     218              : 
     219          364 :     if (item->lyricsLine()->isEndMelisma()) {
     220          126 :         layoutMelismaLine(item);
     221              :     } else {
     222          238 :         layoutDashes(item);
     223              :     }
     224              : 
     225          364 :     double halfLineWidth = item->absoluteFromSpatium(item->lineWidth());
     226          364 :     RectF rect(PointF(), item->pos2());
     227          364 :     rect.adjust(0.0, -halfLineWidth, 0.0, halfLineWidth);
     228              : 
     229          364 :     ldata->setShape(Shape(rect, item));
     230          364 : }
     231              : 
     232          126 : void LyricsLayout::layoutMelismaLine(LyricsLineSegment* item)
     233              : {
     234          126 :     const bool isPartialLyricsLine = item->isPartialLyricsLineSegment();
     235          126 :     LyricsLine* lyricsLine = item->lyricsLine();
     236          126 :     Lyrics* startLyrics = lyricsLine->lyrics();
     237              : 
     238          126 :     System* system = item->system();
     239          126 :     if (!system) {
     240            0 :         return;
     241              :     }
     242          126 :     const MStyle& style = item->style();
     243              : 
     244          126 :     double startX = lyricsLineStartX(item);
     245          126 :     double endX = lyricsLineEndX(item);
     246              : 
     247          126 :     double tolerance = 0.05 * item->spatium();
     248          126 :     if (endX - startX < style.styleAbsolute(Sid::lyricsMelismaMinLength) - tolerance) {
     249            6 :         const Fraction ticks = isPartialLyricsLine ? lyricsLine->ticks() : startLyrics->ticks();
     250            6 :         if (style.styleB(Sid::lyricsMelismaForce) || ticks == Lyrics::TEMP_MELISMA_TICKS) {
     251            3 :             endX = startX + style.styleAbsolute(Sid::lyricsMelismaMinLength);
     252              :         } else {
     253            3 :             endX = startX;
     254              :         }
     255              :     }
     256              : 
     257          126 :     adjustLyricsLineYOffset(item);
     258              : 
     259          126 :     item->mutldata()->setPosX(startX);
     260          126 :     item->setPos2(PointF(endX - startX, 0.0));
     261              : 
     262          126 :     item->mutldata()->addDash(LineF(PointF(), item->pos2()));
     263              : }
     264              : 
     265          238 : void LyricsLayout::layoutDashes(LyricsLineSegment* item)
     266              : {
     267          238 :     const bool isPartialLyricsLine = item->isPartialLyricsLineSegment();
     268          238 :     LyricsLine* lyricsLine = item->lyricsLine();
     269              : 
     270          238 :     ChordRest* endCR = lyricsLine->endElement()
     271          238 :                        && lyricsLine->endElement()->isChordRest() ? toChordRest(lyricsLine->endElement()) : nullptr;
     272          238 :     Lyrics* endLyrics = nullptr;
     273          238 :     if (endCR) {
     274          322 :         for (Lyrics* lyr : endCR->lyrics()) {
     275          322 :             if (lyr->verse() == item->verse()) {
     276          238 :                 endLyrics = lyr;
     277          238 :                 break;
     278              :             }
     279              :         }
     280              :     }
     281              : 
     282              :     // When the end element is a timetick segment rather than a chordrest, the start element should be a chord with a following repeat
     283          238 :     ChordRest* startCR = lyricsLine->startElement()
     284          238 :                          && lyricsLine->startElement()->isChordRest() ? toChordRest(lyricsLine->startElement()) : nullptr;
     285          238 :     bool hasFollowingJump = endCR ? endCR->hasFollowingJumpItem() : (startCR ? startCR->hasFollowingJumpItem() : false);
     286              : 
     287          238 :     if (!endLyrics && !isPartialLyricsLine && !hasFollowingJump) {
     288            0 :         return;
     289              :     }
     290              : 
     291          238 :     System* system = item->system();
     292          238 :     if (!system) {
     293            0 :         return;
     294              :     }
     295          238 :     const MStyle& style = item->style();
     296              : 
     297          238 :     double startX = lyricsLineStartX(item);
     298          238 :     double endX = 0.0;
     299          238 :     if (endCR) {
     300          238 :         endX = lyricsLineEndX(item, endLyrics);
     301              :     } else {
     302            0 :         endX = startCR ? startCR->measure()->endingXForOpenEndedLines() : endX;
     303              :     }
     304              : 
     305          238 :     adjustLyricsLineYOffset(item, endLyrics);
     306              : 
     307          238 :     item->mutldata()->setPosX(startX);
     308          238 :     item->setPos2(PointF(endX - startX, 0.0));
     309              : 
     310          238 :     bool isDashOnFirstSyllable = lyricsLine->tick2() == system->firstMeasure()->tick();
     311          238 :     const double userStart = startX + item->offset().x();
     312          238 :     const double userEnd = endX + item->userOff2().x();
     313          238 :     double curLength = userEnd - userStart;
     314          238 :     double dashMinLength = style.styleAbsolute(Sid::lyricsDashMinLength);
     315          238 :     bool firstAndLastGapAreHalf = style.styleB(Sid::lyricsDashFirstAndLastGapAreHalf);
     316          238 :     bool forceDash = style.styleB(Sid::lyricsDashForce)
     317          238 :                      || (style.styleB(Sid::lyricsShowDashIfSyllableOnFirstNote) && isDashOnFirstSyllable);
     318          238 :     double maxDashDistance = style.styleAbsolute(Sid::lyricsDashMaxDistance);
     319          238 :     int dashCount = firstAndLastGapAreHalf && curLength > maxDashDistance ? std::ceil(curLength / maxDashDistance)
     320          224 :                     : std::floor(curLength / maxDashDistance);
     321              : 
     322          238 :     if (curLength > dashMinLength || forceDash) {
     323          238 :         dashCount = std::max(dashCount, 1);
     324              :     }
     325              : 
     326          238 :     if (style.styleB(Sid::lyricsLimitDashCount)) {
     327            0 :         dashCount = std::min(dashCount, style.styleI(Sid::lyricsMaxDashCount));
     328              :     }
     329              : 
     330          238 :     if (curLength < dashMinLength && dashCount > 0) {
     331           13 :         double diff = dashMinLength - curLength;
     332           13 :         if (isDashOnFirstSyllable) {
     333            0 :             startX -= diff;
     334              :         } else {
     335           13 :             startX -= 0.5 * diff;
     336           13 :             endX += 0.5 * diff;
     337              :         }
     338           13 :         item->mutldata()->setPosX(startX);
     339           13 :         item->setPos2(PointF(endX - startX, 0.0));
     340           13 :         curLength = endX - startX;
     341              :     }
     342              : 
     343          238 :     double dashWidth = std::min(curLength, style.styleAbsolute(Sid::lyricsDashMaxLength));
     344              : 
     345          238 :     LyricsDashSystemStart lyricsDashSystemStart = style.styleV(Sid::lyricsDashPosAtStartOfSystem).value<LyricsDashSystemStart>();
     346          238 :     bool dashesLeftAligned = lyricsDashSystemStart != LyricsDashSystemStart::STANDARD && !item->isSingleBeginType();
     347          238 :     double dashDist = curLength / (dashesLeftAligned || firstAndLastGapAreHalf ? dashCount : dashCount + 1);
     348          238 :     double xDash = 0.0;
     349          238 :     if (dashesLeftAligned) {
     350            0 :         for (int i = 0; i < dashCount; ++i) {
     351            0 :             item->mutldata()->addDash(LineF(PointF(xDash, 0.0), PointF(xDash + dashWidth, 0.0)));
     352            0 :             xDash += dashDist;
     353              :         }
     354              :     } else {
     355          493 :         for (int i = 0; i < dashCount; ++i) {
     356          255 :             if (firstAndLastGapAreHalf && i == 0) {
     357          238 :                 xDash += 0.5 * dashDist;
     358              :             } else {
     359           17 :                 xDash += dashDist;
     360              :             }
     361          255 :             item->mutldata()->addDash(LineF(PointF(xDash - 0.5 * dashWidth, 0.0), PointF(xDash + 0.5 * dashWidth, 0.0)));
     362              :         }
     363              :     }
     364              : }
     365              : 
     366           23 : Lyrics* LyricsLayout::findNextLyrics(const ChordRest* endChordRest, int verseNumber, std::optional<PlacementV> placement)
     367              : {
     368           23 :     if (!endChordRest) {
     369            0 :         return nullptr;
     370              :     }
     371           83 :     for (Segment* segment = endChordRest->segment()->next1(SegmentType::ChordRest); segment;
     372           60 :          segment = segment->next1(SegmentType::ChordRest)) {
     373           68 :         if (!segment->element(endChordRest->track())) {
     374           20 :             continue;
     375              :         }
     376           48 :         ChordRest* nextCR = toChordRest(segment->element(endChordRest->track()));
     377           48 :         for (Lyrics* lyr : nextCR->lyrics()) {
     378            8 :             if (lyr->verse() == verseNumber && (!placement || lyr->placement() == placement)) {
     379            8 :                 return lyr;
     380              :             }
     381              :         }
     382              :     }
     383              : 
     384           15 :     return nullptr;
     385              : }
     386              : 
     387         2374 : void LyricsLayout::createOrRemoveLyricsLine(Lyrics* item, LayoutContext& ctx)
     388              : {
     389         2374 :     if (item->needRemoveInvalidSegments()) {
     390           11 :         item->removeInvalidSegments();
     391              :     }
     392              : 
     393         4748 :     auto isEndMelisma = [item]() {
     394         4748 :         return item->ticks().isNotZero();
     395         2374 :     };
     396              : 
     397         2374 :     Fraction lyricsLineTicks = Lyrics::TEMP_MELISMA_TICKS;
     398              : 
     399              :     // Update the end tick
     400         2374 :     if (isEndMelisma()) {
     401          107 :         const track_idx_t track = item->track();
     402              : 
     403          107 :         const Segment* const startSegment = item->segment();
     404          107 :         const Fraction startTick = startSegment->tick();
     405              : 
     406              :         // if lyrics has a temporary one-chord melisma, interpret as 0 ticks (just its own chord)
     407          107 :         Fraction itemEndTick = item->ticks() == Lyrics::TEMP_MELISMA_TICKS ? startTick : item->endTick();
     408          107 :         Fraction endTick = itemEndTick;
     409              : 
     410          107 :         const Segment* endSegment = startSegment;
     411          366 :         while (endSegment && endSegment->tick() < endTick) {
     412          259 :             endSegment = endSegment->nextCR(track, true);
     413              :         }
     414          107 :         if (!endSegment) {
     415              :             // user probably deleted measures at end of score, leaving this melisma too long
     416              :             // set endSegment to last segment and reset lyricsEndTick to trigger FIXUP code below
     417            2 :             endSegment = ctx.dom().lastSegment();
     418            2 :             endTick = Fraction(-1, 1);
     419              :         }
     420              : 
     421          107 :         EngravingItem* endSegmentElement = endSegment->element(track);
     422          107 :         if (endSegment->tick() == endTick && endSegmentElement && endSegmentElement->isChord()) {
     423              :             // everything is OK if we have reached a chord at right tick on right track
     424              :             // advance to next CR after duration of note, or last segment if no next CR
     425          105 :             const Segment* endChordSeg = endSegment;
     426          105 :             const Chord* endChord = toChord(endSegmentElement);
     427              : 
     428          105 :             endSegment = endChordSeg->nextCR(track, false);
     429              : 
     430          105 :             if (!endSegment || endSegment->tick() > endChord->endTick()) {
     431            7 :                 endSegment = endChordSeg;
     432           26 :                 while (endSegment && endSegment->tick() < endChord->endTick()) {
     433           19 :                     endSegment = endSegment->nextCR(muse::nidx, true);
     434              :                 }
     435              :             }
     436              :         } else {
     437              :             // FIXUP - lyrics tick count not valid
     438              :             // this happens if edits to score have removed the original end segment
     439              :             // so let's fix it here
     440              :             // endSegment is already pointing to segment past endTick (or to last segment)
     441              :             // we should shorten the lyrics tick count to make this work
     442            2 :             const Segment* ns = endSegment;
     443            2 :             const Segment* ps = endSegment->prev1(SegmentType::ChordRest);
     444            5 :             while (ps && ps != startSegment) {
     445            5 :                 EngravingItem* pe = ps->element(track);
     446              :                 // we're looking for an actual chord on this track
     447            5 :                 if (pe && pe->isChord()) {
     448            2 :                     break;
     449              :                 }
     450            3 :                 endSegment = ps;
     451            3 :                 ps = ps->prev1(SegmentType::ChordRest);
     452              :             }
     453              : 
     454            2 :             if (!ps || ps == startSegment) {
     455              :                 // either there is no valid previous CR, or the previous CR is the one the lyric starts on
     456              :                 // we don't want to make the melisma longer arbitrarily, but there is a possibility that the next
     457              :                 // CR won't extend the melisma, so let's check it
     458            0 :                 ps = ns;
     459            0 :                 endSegment = ps->nextCR(track, false);
     460            0 :                 EngravingItem* e = endSegment ? endSegment->element(track) : nullptr;
     461              : 
     462              :                 // check to make sure we have a chord
     463            0 :                 if (!e || !e->isChord() || ps->tick() > itemEndTick) {
     464              :                     // nope, nothing to do but set ticks to 0
     465              :                     // this will result in no melisma
     466            0 :                     item->undoChangeProperty(Pid::LYRIC_TICKS, Fraction::fromTicks(0));
     467              :                 } else {
     468            0 :                     item->undoChangeProperty(Pid::LYRIC_TICKS, ps->tick() - startTick);
     469              :                 }
     470            0 :             } else {
     471            2 :                 item->undoChangeProperty(Pid::LYRIC_TICKS, ps->tick() - startTick);
     472              :             }
     473              :         }
     474              : 
     475          107 :         if (endSegment) {
     476              :             // Lyrics::_ticks points to the beginning of the last spanned segment,
     477              :             // but the line shall include it:
     478              :             // include the duration of this last segment in the melisma duration
     479          100 :             lyricsLineTicks = endSegment->tick() - startTick;
     480              :         } else {
     481            7 :             lyricsLineTicks = item->score()->endTick() - startTick;
     482              :         }
     483              :     }
     484              : 
     485         2374 :     ChordRest* cr = item->chordRest();
     486              : 
     487         2374 :     if (isEndMelisma() || item->syllabic() == LyricsSyllabic::BEGIN || item->syllabic() == LyricsSyllabic::MIDDLE) {
     488          341 :         if (!item->separator()) {
     489          253 :             LyricsLine* separator = Factory::createLyricsLine(ctx.mutDom().dummyParent());
     490          253 :             separator->setGenerated(true);
     491          253 :             separator->setTick(cr->tick());
     492          253 :             separator->setVisible(item->visible());
     493          253 :             item->setSeparator(separator);
     494          253 :             ctx.mutDom().addUnmanagedSpanner(item->separator());
     495              :         }
     496          341 :         item->separator()->setOwnershipParent(item);
     497          341 :         item->separator()->setTick(cr->tick());
     498          341 :         item->separator()->setTicks(lyricsLineTicks);
     499          341 :         item->separator()->setTrack(item->track());
     500          341 :         item->separator()->setTrack2(item->track());
     501          341 :         item->separator()->styleChanged();
     502              :     } else {
     503         2033 :         if (item->separator()) {
     504            2 :             item->separator()->removeUnmanaged();
     505            2 :             delete item->separator();
     506            2 :             item->setSeparator(nullptr);
     507              :         }
     508              :     }
     509         2374 : }
     510              : 
     511         8231 : void LyricsLayout::computeVerticalPositions(System* system, LayoutContext& ctx)
     512              : {
     513         8231 :     staff_idx_t nStaves = system->score()->nstaves();
     514              : 
     515         8231 :     std::vector<staff_idx_t> visibleStaves;
     516         8231 :     visibleStaves.reserve(system->staves().size());
     517              : 
     518        21227 :     for (staff_idx_t staffIdx = 0; staffIdx < nStaves; ++staffIdx) {
     519        12996 :         if (system->staff(staffIdx)->show()) {
     520        12216 :             computeVerticalPositions(staffIdx, system, ctx);
     521              :         }
     522              :     }
     523         8231 : }
     524              : 
     525        12216 : void LyricsLayout::computeVerticalPositions(staff_idx_t staffIdx, System* system, LayoutContext& ctx)
     526              : {
     527        12216 :     LyricsVersesMap lyricsVersesAbove;
     528        12216 :     LyricsVersesMap lyricsVersesBelow;
     529              : 
     530        12216 :     collectLyricsVerses(staffIdx, system, lyricsVersesAbove, lyricsVersesBelow);
     531              : 
     532        12216 :     setDefaultPositions(staffIdx, lyricsVersesAbove, lyricsVersesBelow, ctx);
     533              : 
     534        12216 :     checkCollisionsWithStaffElements(system, staffIdx, ctx, lyricsVersesAbove, lyricsVersesBelow);
     535              : 
     536        12216 :     addToSkyline(system, staffIdx, ctx, lyricsVersesAbove, lyricsVersesBelow);
     537        12216 : }
     538              : 
     539        12216 : void LyricsLayout::collectLyricsVerses(staff_idx_t staffIdx, System* system, LyricsVersesMap& lyricsVersesAbove,
     540              :                                        LyricsVersesMap& lyricsVersesBelow)
     541              : {
     542        12216 :     track_idx_t startTrack = staffIdx * VOICES;
     543        12216 :     track_idx_t endTrack = startTrack + VOICES;
     544              : 
     545        63956 :     for (MeasureBase* mb : system->measures()) {
     546        51740 :         if (!mb->isMeasure()) {
     547          184 :             continue;
     548              :         }
     549       245097 :         for (Segment& segment : toMeasure(mb)->segments()) {
     550       193541 :             if (!segment.isChordRestType()) {
     551        92529 :                 continue;
     552              :             }
     553       505060 :             for (track_idx_t track = startTrack; track < endTrack; ++track) {
     554       404048 :                 EngravingItem* element = segment.element(track);
     555       404048 :                 if (!element) {
     556       304920 :                     continue;
     557              :                 }
     558       101502 :                 for (Lyrics* lyrics : toChordRest(element)->lyrics()) {
     559         2374 :                     int verse = lyrics->verse();
     560         2374 :                     if (lyrics->placeAbove()) {
     561           16 :                         lyricsVersesAbove[verse].addLyrics(lyrics);
     562              :                     } else {
     563         2358 :                         lyricsVersesBelow[verse].addLyrics(lyrics);
     564              :                     }
     565              :                 }
     566              :             }
     567              :         }
     568              :     }
     569              : 
     570        22116 :     for (SpannerSegment* spannerSegment : system->spannerSegments()) {
     571         9900 :         if (spannerSegment->staffIdx() == staffIdx && spannerSegment->isLyricsLineSegment()) {
     572          364 :             if (muse::RealIsNull(spannerSegment->pos2().x())) {
     573            3 :                 continue;
     574              :             }
     575          361 :             LyricsLineSegment* lyricsLineSegment = toLyricsLineSegment(spannerSegment);
     576          361 :             int verse = lyricsLineSegment->verse();
     577          361 :             if (lyricsLineSegment->lyricsPlaceAbove()) {
     578            4 :                 lyricsVersesAbove[verse].addLine(lyricsLineSegment);
     579              :             } else {
     580          357 :                 lyricsVersesBelow[verse].addLine(lyricsLineSegment);
     581              :             }
     582              :         }
     583              :     }
     584        12216 : }
     585              : 
     586        12216 : void LyricsLayout::setDefaultPositions(staff_idx_t staffIdx, const LyricsVersesMap& lyricsVersesAbove,
     587              :                                        const LyricsVersesMap& lyricsVersesBelow,
     588              :                                        LayoutContext& ctx)
     589              : {
     590        12216 :     double staffHeight = ctx.dom().staff(staffIdx)->staffHeight();
     591        12216 :     double lyricsLineHeightFactor = ctx.conf().styleD(Sid::lyricsLineHeight);
     592              : 
     593        12216 :     int maxVerseAbove = !lyricsVersesAbove.empty() ? lyricsVersesAbove.crbegin()->first : 0;
     594        12224 :     for (auto& pair : lyricsVersesAbove) {
     595            8 :         int verse = pair.first;
     596            8 :         const LyricsVerse& lyricsVerse = pair.second;
     597           24 :         for (Lyrics* lyrics : lyricsVerse.lyrics()) {
     598           16 :             double y = -(maxVerseAbove - verse) * lyrics->lineSpacing() * lyricsLineHeightFactor;
     599           16 :             PointF defaultPos = lyrics->defaultPos();
     600           16 :             y += defaultPos.y();
     601           16 :             lyrics->setYRelativeToStaff(y);
     602              :         }
     603           12 :         for (LyricsLineSegment* lyricsLineSegment : lyricsVerse.lines()) {
     604            4 :             double y = -(maxVerseAbove - verse) * lyricsLineSegment->lineSpacing() * lyricsLineHeightFactor;
     605            4 :             lyricsLineSegment->move(PointF(0.0, y + lyricsLineSegment->baseLineShift()));
     606              :         }
     607              :     }
     608              : 
     609        12789 :     for (auto& pair : lyricsVersesBelow) {
     610          573 :         int verse = pair.first;
     611          573 :         const LyricsVerse& lyricsVerse = pair.second;
     612         2931 :         for (Lyrics* lyrics : lyricsVerse.lyrics()) {
     613         2358 :             double y = staffHeight + verse * lyrics->lineSpacing() * lyricsLineHeightFactor;
     614         2358 :             PointF defaultPos = lyrics->defaultPos();
     615         2358 :             y += defaultPos.y();
     616         2358 :             lyrics->setYRelativeToStaff(y);
     617              :         }
     618          930 :         for (LyricsLineSegment* lyricsLineSegment : lyricsVerse.lines()) {
     619          357 :             double y = staffHeight + verse * lyricsLineSegment->lineSpacing() * lyricsLineHeightFactor;
     620          357 :             lyricsLineSegment->move(PointF(0.0, y + lyricsLineSegment->baseLineShift()));
     621              :         }
     622              :     }
     623        12216 : }
     624              : 
     625        12216 : void LyricsLayout::checkCollisionsWithStaffElements(System* system, staff_idx_t staffIdx,  LayoutContext& ctx,
     626              :                                                     const LyricsVersesMap& lyricsVersesAbove,
     627              :                                                     const LyricsVersesMap& lyricsVersesBelow)
     628              : {
     629        12216 :     SysStaff* systemStaff = system->staff(staffIdx);
     630              : 
     631        12216 :     double lyricsMinDist = ctx.conf().styleAbsolute(Sid::lyricsMinTopDistance);
     632              : 
     633        12216 :     SkylineLine& staffSkylineNorth = systemStaff->skyline().north();
     634        12216 :     SkylineLine& staffSkylineSouth = systemStaff->skyline().south();
     635              : 
     636        12216 :     int maxVerseAbove = !lyricsVersesAbove.empty() ? lyricsVersesAbove.crbegin()->first : 0;
     637        12216 :     int maxVerseBelow = !lyricsVersesBelow.empty() ? lyricsVersesBelow.crbegin()->first : 0;
     638              : 
     639        24432 :     for (int verse = maxVerseAbove; verse >= 0; --verse) {
     640        12216 :         if (lyricsVersesAbove.count(verse) == 0) {
     641        12208 :             continue;
     642              :         }
     643            8 :         SkylineLine verseSkyline = createSkylineForVerse(verse, false, lyricsVersesAbove, system);
     644            8 :         double minDistance = -verseSkyline.minDistance(staffSkylineNorth);
     645            8 :         if (minDistance < lyricsMinDist) {
     646            6 :             double diff = lyricsMinDist - minDistance;
     647            6 :             moveThisVerseAndOuterOnes(verse, 0, true, -diff, lyricsVersesAbove);
     648              :         }
     649            8 :     }
     650              : 
     651        24497 :     for (int verse = 0; verse <= maxVerseBelow; ++verse) {
     652        12281 :         if (lyricsVersesBelow.count(verse) == 0) {
     653        11708 :             continue;
     654              :         }
     655          573 :         SkylineLine verseSkyline = createSkylineForVerse(verse, true, lyricsVersesBelow, system);
     656          573 :         double minDistance = -staffSkylineSouth.minDistance(verseSkyline);
     657          573 :         if (minDistance < lyricsMinDist) {
     658          386 :             double diff = lyricsMinDist - minDistance;
     659          386 :             moveThisVerseAndOuterOnes(verse, maxVerseBelow, false, diff, lyricsVersesBelow);
     660              :         }
     661          573 :     }
     662        12216 : }
     663              : 
     664          581 : SkylineLine LyricsLayout::createSkylineForVerse(int verse, bool north, const LyricsVersesMap& lyricsVerses, System* system)
     665              : {
     666          581 :     double systemX = system->pageX();
     667              : 
     668          581 :     SkylineLine lyricsSkyline(north);
     669              : 
     670          581 :     if (lyricsVerses.count(verse) > 0) {
     671          581 :         const LyricsVerse& lyricsVerse = lyricsVerses.at(verse);
     672         2955 :         for (Lyrics* lyrics : lyricsVerse.lyrics()) {
     673         2374 :             if (lyrics->addToSkyline()) {
     674         2359 :                 Shape lyricsShape = lyrics->highResShape().translated(PointF(lyrics->pageX() - systemX, lyrics->yRelativeToStaff()));
     675         2359 :                 lyricsSkyline.add(lyricsShape);
     676         2359 :             }
     677              :         }
     678          942 :         for (LyricsLineSegment* lyricsLineSeg : lyricsVerse.lines()) {
     679          361 :             if (lyricsLineSeg->lyricsAddToSkyline()) {
     680          361 :                 lyricsSkyline.add(lyricsLineSeg->shape().translate(lyricsLineSeg->pos()));
     681              :             }
     682              :         }
     683              :     }
     684              : 
     685          581 :     return lyricsSkyline;
     686            0 : }
     687              : 
     688          392 : void LyricsLayout::moveThisVerseAndOuterOnes(int verse, int lastVerse, bool above, double diff, const LyricsVersesMap& lyricsVerses)
     689              : {
     690          426 :     auto moveVerse = [&](int verse) {
     691          426 :         if (lyricsVerses.count(verse) > 0) {
     692          426 :             const LyricsVerse& lyricsVerse = lyricsVerses.at(verse);
     693         2345 :             for (Lyrics* lyrics : lyricsVerse.lyrics()) {
     694         1919 :                 lyrics->move(PointF(0.0, diff));
     695              :             }
     696          701 :             for (LyricsLineSegment* lyricsLineSeg : lyricsVerse.lines()) {
     697          275 :                 lyricsLineSeg->move(PointF(0.0, diff));
     698              :             }
     699              :         }
     700          426 :     };
     701              : 
     702          392 :     if (above) {
     703           12 :         for (int otherVerse = verse; otherVerse >= lastVerse; --otherVerse) {
     704            6 :             moveVerse(otherVerse);
     705              :         }
     706              :     } else {
     707          806 :         for (int otherVerse = verse; otherVerse <= lastVerse; ++otherVerse) {
     708          420 :             moveVerse(otherVerse);
     709              :         }
     710              :     }
     711          392 : }
     712              : 
     713        12216 : void LyricsLayout::addToSkyline(System* system, staff_idx_t staffIdx, LayoutContext& ctx, const LyricsVersesMap& lyricsVersesAbove,
     714              :                                 const LyricsVersesMap& lyricsVersesBelow)
     715              : {
     716        12216 :     double systemX = system->pageX();
     717              :     // HACK: subtract minVerticalDistance here because it's added later during staff distance calculations. Needs a better solution.
     718        12216 :     double lyricsVerticalPadding = ctx.conf().styleAbsolute(Sid::lyricsMinBottomDistance) - ctx.conf().styleAbsolute(
     719        12216 :         Sid::minVerticalDistance);
     720        12216 :     Skyline& skyline = system->staff(staffIdx)->skyline();
     721        12224 :     for (auto& pair : lyricsVersesAbove) {
     722            8 :         const LyricsVerse& lyricsVerse = pair.second;
     723           24 :         for (Lyrics* lyrics : lyricsVerse.lyrics()) {
     724           16 :             if (lyrics->addToSkyline()) {
     725              :                 Shape lyricsShape
     726           16 :                     = lyrics->highResShape().translated(PointF(lyrics->pageX() - systemX, lyrics->yRelativeToStaff()));
     727           16 :                 skyline.north().add(lyricsShape.adjust(0.0, -lyricsVerticalPadding, 0.0, 0.0));
     728           16 :             }
     729              :         }
     730           12 :         for (LyricsLineSegment* lyricsLineSeg : lyricsVerse.lines()) {
     731            4 :             if (lyricsLineSeg->lyricsAddToSkyline()) {
     732            4 :                 Shape lineShape = lyricsLineSeg->shape().translate(lyricsLineSeg->pos());
     733            4 :                 skyline.north().add(lineShape.adjust(0.0, -lyricsVerticalPadding, 0.0, 0.0));
     734            4 :             }
     735              :         }
     736              :     }
     737        12789 :     for (auto& pair : lyricsVersesBelow) {
     738          573 :         const LyricsVerse& lyricsVerse = pair.second;
     739         2931 :         for (Lyrics* lyrics : lyricsVerse.lyrics()) {
     740         2358 :             if (lyrics->addToSkyline()) {
     741              :                 Shape lyricsShape
     742         2343 :                     = lyrics->highResShape().translated(PointF(lyrics->pageX() - systemX, lyrics->yRelativeToStaff()));
     743         2343 :                 skyline.south().add(lyricsShape.adjust(0.0, 0.0, 0.0, lyricsVerticalPadding));
     744         2343 :             }
     745              :         }
     746          930 :         for (LyricsLineSegment* lyricsLineSeg : lyricsVerse.lines()) {
     747          357 :             if (lyricsLineSeg->lyricsAddToSkyline()) {
     748          357 :                 Shape lineShape = lyricsLineSeg->shape().translate(lyricsLineSeg->pos());
     749          357 :                 skyline.south().add(lineShape.adjust(0.0, 0.0, 0.0, lyricsVerticalPadding));
     750          357 :             }
     751              :         }
     752              :     }
     753        12216 : }
     754              : 
     755          364 : double LyricsLayout::lyricsLineStartX(LyricsLineSegment* item)
     756              : {
     757          364 :     const System* system = item->system();
     758          364 :     const LyricsLine* lyricsLine = item->lyricsLine();
     759          364 :     const Lyrics* startLyrics = lyricsLine->lyrics();
     760          364 :     const MStyle& style = item->style();
     761          364 :     const bool melisma = lyricsLine->isEndMelisma();
     762              : 
     763          364 :     const LyricsDashSystemStart lyricsDashSystemStart = style.styleV(Sid::lyricsDashPosAtStartOfSystem).value<LyricsDashSystemStart>();
     764          364 :     const bool leading = melisma || (lyricsDashSystemStart != LyricsDashSystemStart::UNDER_FIRST_NOTE);
     765              : 
     766              :     // Full melisma or dashes at beginning of system
     767          364 :     if (!item->isSingleBeginType()) {
     768           14 :         return system->firstNoteRestSegmentX(leading);
     769              :     }
     770              : 
     771              :     // Partial melisma or dashes
     772          350 :     if (lyricsLine->isPartialLyricsLine()) {
     773            9 :         const Measure* measure = lyricsLine->findStartMeasure();
     774            9 :         return measure->firstNoteRestSegmentX(leading);
     775              :     }
     776              : 
     777              :     // Full melisma or dashes in middle of system
     778          341 :     const double pad = melisma ? style.styleAbsolute(Sid::lyricsMelismaPad) : style.styleAbsolute(Sid::lyricsDashPad);
     779          341 :     const double lyricsRightEdge = startLyrics->pageX() - system->pageX() + startLyrics->shape().right();
     780          341 :     item->mutldata()->startXLyrics = startLyrics;
     781          341 :     return lyricsRightEdge + pad;
     782              : }
     783              : 
     784          364 : double LyricsLayout::lyricsLineEndX(LyricsLineSegment* item, const Lyrics* endLyrics)
     785              : {
     786          364 :     const System* system = item->system();
     787          364 :     const LyricsLine* lyricsLine = item->lyricsLine();
     788          364 :     const ChordRest* endChordRest = toChordRest(lyricsLine->endElement());
     789          364 :     if (!endChordRest) {
     790            0 :         return system->endingXForOpenEndedLines();
     791              :     }
     792          364 :     const double systemPageX = system->pageX();
     793          364 :     const MStyle& style = item->style();
     794          364 :     const bool melisma = lyricsLine->isEndMelisma();
     795          364 :     const bool hasFollowingJump = endChordRest->hasFollowingJumpItem();
     796          364 :     const bool hasPrecedingJump = endChordRest->hasPrecedingJumpItem();
     797              : 
     798          364 :     if (!melisma && !item->isPartialLyricsLineSegment() && !endLyrics && !hasFollowingJump) {
     799            0 :         return 0.0;
     800              :     }
     801              : 
     802          364 :     const bool dashesEndOfSystem = !melisma && lyricsLine->tick2() == system->endTick();
     803              : 
     804              :     // Full melisma or dashes at end of system
     805          364 :     if (!item->isSingleEndType() || dashesEndOfSystem || !lyricsLine->endElement()) {
     806           14 :         return system->endingXForOpenEndedLines();
     807              :     }
     808              : 
     809              :     // Partial dashes after a repeat
     810          350 :     if (!melisma && hasPrecedingJump && item->isPartialLyricsLineSegment()) {
     811            1 :         if (endLyrics) {
     812            1 :             const double lyricsLeftEdge = endLyrics->pageX() - systemPageX + endLyrics->ldata()->bbox().left();
     813            1 :             item->mutldata()->endXLyrics = endLyrics;
     814            1 :             return lyricsLeftEdge - style.styleAbsolute(Sid::lyricsDashPad);
     815            0 :         } else if (endChordRest->isChord()) {
     816            0 :             const Chord* endChord = toChord(endChordRest);
     817            0 :             const Note* note = endChord->up() ? endChord->downNote() : endChord->upNote();
     818            0 :             return note->pageX() - systemPageX + note->headWidth();
     819              :         }
     820              :     }
     821              : 
     822              :     // Full dashes or melisma before a repeat - possibly with a partial dash/repeat on the other side of the repeat
     823          349 :     if (endChordRest && hasFollowingJump && !lyricsLine->nextLyrics()) {
     824            5 :         Measure* endMeasure = lyricsLine->findEndMeasure();
     825              :         // check if there is a partial lyrics line in a following measure
     826            5 :         if (repeatHasPartialLyricLine(endMeasure) || endChordRest == lyricsLine->startElement()) {
     827            5 :             return endMeasure->endingXForOpenEndedLines();
     828              :         }
     829              :     }
     830              : 
     831              :     // Full or partial dashes in middle of system
     832          344 :     if (!melisma && endLyrics) {
     833          236 :         const double lyricsLeftEdge = endLyrics->pageX() - systemPageX + endLyrics->ldata()->bbox().left();
     834          236 :         item->mutldata()->endXLyrics = endLyrics;
     835          236 :         return lyricsLeftEdge - style.styleAbsolute(Sid::lyricsDashPad);
     836              :     }
     837              : 
     838              :     // Full or partial melisma in middle of system
     839          108 :     if (endChordRest->isChord()) {
     840          108 :         const Chord* endChord = toChord(endChordRest);
     841          108 :         const Note* note = endChord->up() ? endChord->downNote() : endChord->upNote();
     842          108 :         return note->pageX() - systemPageX + note->headWidth();
     843              :     }
     844              : 
     845            0 :     return endChordRest->pageX() - systemPageX + endChordRest->rightEdge();
     846              : }
     847              : 
     848          364 : void LyricsLayout::adjustLyricsLineYOffset(LyricsLineSegment* item, const Lyrics* endLyrics)
     849              : {
     850          364 :     const LyricsLine* lyricsLine = item->lyricsLine();
     851          364 :     ChordRest* endChordRest = lyricsLine->endElement()
     852          364 :                               && lyricsLine->endElement()->isChordRest() ? toChordRest(lyricsLine->endElement()) : nullptr;
     853          364 :     const Lyrics* startLyrics = lyricsLine->lyrics();
     854          364 :     const bool melisma = lyricsLine->isEndMelisma();
     855              : 
     856          364 :     LyricsLineSegment::LayoutData* ldata = item->mutldata();
     857              : 
     858              :     // Partial melisma or dashes
     859          364 :     if (lyricsLine->isPartialLyricsLine()) {
     860              :         // A partial lyrics line's placement is independent of the lyrics around it, so only
     861              :         // take the Y from a lyric which is on the same side of the staff:
     862            9 :         Lyrics* nextLyrics = findNextLyrics(endChordRest, item->verse(), lyricsLine->placement());
     863            9 :         if (nextLyrics) {
     864            6 :             PointF nextLyricsDefaultPos = nextLyrics->defaultPos();
     865            6 :             ldata->setPosY(nextLyrics->offset().y() + nextLyricsDefaultPos.y());
     866            6 :             ldata->yLyrics = nextLyrics;
     867              :         } else {
     868            6 :             PointF lyricsOffset = item->styleValue(Pid::OFFSET,
     869            6 :                                                    item->placeBelow() ? Sid::lyricsPosBelow : Sid::lyricsPosAbove).value<PointF>();
     870            3 :             ldata->setPosY(lyricsOffset.y());
     871              :         }
     872          364 :         return;
     873              :     }
     874              : 
     875          355 :     if (item->isSingleBeginType()) {
     876          341 :         PointF startLyricsDefaultPos = startLyrics->defaultPos();
     877          341 :         ldata->setPosY(startLyrics->offset().y() + startLyricsDefaultPos.y());
     878          341 :         ldata->yLyrics = startLyrics;
     879          341 :         return;
     880              :     }
     881              : 
     882           14 :     if (melisma || !endLyrics) {
     883           14 :         const Lyrics* nextLyrics = findNextLyrics(endChordRest, item->verse());
     884              : 
     885           14 :         const Lyrics* refLyrics = nextLyrics ? nextLyrics : startLyrics;
     886           14 :         PointF refLyricsDefaultPos = refLyrics->defaultPos();
     887              : 
     888           14 :         ldata->setPosY(refLyrics->offset().y() + refLyricsDefaultPos.y());
     889           14 :         ldata->yLyrics = refLyrics;
     890           14 :         return;
     891              :     }
     892              : 
     893            0 :     PointF endLyricsDefaultPos = endLyrics->defaultPos();
     894              : 
     895            0 :     ldata->setPosY(endLyrics->offset().y() + endLyricsDefaultPos.y());
     896            0 :     ldata->yLyrics = endLyrics;
     897              : }
        

Generated by: LCOV version 2.0-1