LCOV - code coverage report
Current view: top level - src/engraving/rendering/score - restlayout.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 80.3 % 537 431
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              : 
      23              : #include "restlayout.h"
      24              : 
      25              : #include "beamlayout.h"
      26              : #include "chordlayout.h"
      27              : #include "tlayout.h"
      28              : 
      29              : #include "dom/beam.h"
      30              : #include "dom/jianpudurationline.h"
      31              : #include "dom/measure.h"
      32              : #include "dom/staff.h"
      33              : #include "dom/system.h"
      34              : #include "dom/utils.h"
      35              : 
      36              : using namespace muse;
      37              : using namespace mu::engraving;
      38              : 
      39              : namespace mu::engraving::rendering::score {
      40        75939 : void RestLayout::layoutRest(const Rest* item, Rest::LayoutData* ldata, const LayoutContext& ctx)
      41              : {
      42        75939 :     if (item->isGap()) {
      43          150 :         if (item->debugDrawGap()) {
      44            0 :             ldata->sym = item->getSymbol(item->durationType().type(), 16, 5);
      45            0 :             fillShape(item, ldata, ctx.conf());
      46            0 :             ldata->setPos(PointF(0.0, 10 * item->spatium()));
      47              :         } else {
      48          150 :             ldata->reset();
      49              :         }
      50          150 :         return;
      51              :     }
      52              : 
      53              :     //! NOTE The types are listed here explicitly to show what types there are (see Rest::add method)
      54              :     //! and accordingly show what depends on.
      55        75789 :     for (EngravingItem* e : item->el()) {
      56            0 :         switch (e->type()) {
      57            0 :         case ElementType::DEAD_SLAPPED: {
      58            0 :             DeadSlapped* ds = item_cast<DeadSlapped*>(e);
      59              :             LD_INDEPENDENT;
      60            0 :             TLayout::layoutDeadSlapped(ds, ds->mutldata());
      61            0 :         } break;
      62            0 :         case ElementType::SYMBOL: {
      63            0 :             Symbol* s = item_cast<Symbol*>(e);
      64              :             // LD_X not clear yet
      65            0 :             TLayout::layoutSymbol(s, s->mutldata(), ctx);
      66            0 :         } break;
      67            0 :         case ElementType::IMAGE: {
      68            0 :             Image* im = item_cast<Image*>(e);
      69              :             LD_INDEPENDENT;
      70            0 :             TLayout::layoutImage(im, im->mutldata());
      71            0 :         } break;
      72            0 :         default:
      73            0 :             UNREACHABLE;
      74              :         }
      75              :     }
      76              : 
      77        75789 :     if (item->deadSlapped()) {
      78            0 :         ldata->setIsSkipDraw(true);
      79            0 :         return;
      80              :     }
      81        75789 :     ldata->setIsSkipDraw(false);
      82              : 
      83        75789 :     double spatium = item->spatium();
      84              : 
      85        75789 :     ldata->setPosX(0.0);
      86        75789 :     const Staff* stf = item->staff();
      87        75789 :     const StaffType* stt = item->staffType();
      88        75789 :     if (stt && stt->isTabStaff()) {
      89              :         // if rests are shown and note values are shown as duration symbols
      90         1470 :         if (stt->showRests() && stt->genDurations()) {
      91            0 :             DurationType type = item->durationType().type();
      92            0 :             int dots = item->durationType().dots();
      93              :             // if rest is whole measure, convert into actual type and dot values
      94            0 :             if (type == DurationType::V_MEASURE && item->measure()) {
      95            0 :                 Fraction ticks = item->measure()->ticks();
      96            0 :                 TDuration dur  = TDuration(ticks).type();
      97            0 :                 type           = dur.type();
      98            0 :                 dots           = dur.dots();
      99              :             }
     100              :             // symbol needed; if not exist, create, if exists, update duration
     101            0 :             if (!item->tabDur()) {
     102            0 :                 const_cast<Rest*>(item)->setTabDur(new TabDurationSymbol(const_cast<Rest*>(item), stt, type, dots));
     103              :             } else {
     104            0 :                 item->tabDur()->setDuration(type, dots, stt);
     105              :             }
     106              : // needed?        _tabDur->setTrack(track());
     107            0 :             TLayout::layoutTabDurationSymbol(item->tabDur(), item->tabDur()->mutldata());
     108            0 :             ldata->setBbox(item->tabDur()->ldata()->bbox());
     109            0 :             ldata->setPos(0.0, 0.0);                   // no rest is drawn: reset any position might be set for it
     110            0 :             return;
     111              :         }
     112              :         // if no rests or no duration symbols, delete any dur. symbol and chain into standard staff mngmt
     113              :         // this is to ensure horiz space is reserved for rest, even if they are not displayed
     114              :         // Rest::draw() will skip their drawing, if not needed
     115         1470 :         if (item->tabDur()) {
     116            0 :             delete item->tabDur();
     117            0 :             const_cast<Rest*>(item)->setTabDur(nullptr);
     118              :         }
     119              :     }
     120              : 
     121        75789 :     if (stf->isJianpuStaff(item->tick())) {
     122          280 :         ldata->sym = SymId::noSym;
     123          280 :         layoutRestForJianpu(item, ldata, ctx);
     124          280 :         fillShape(item, ldata, ctx.conf());
     125          280 :         return;
     126              :     }
     127              : 
     128        75509 :     const_cast<Rest*>(item)->setDotLine(Rest::getDotline(item->durationType().type()));
     129              : 
     130        75509 :     double yOff = item->offset().y();
     131        75509 :     const StaffType* st = stf ? stf->staffTypeForElement(item) : 0;
     132        75509 :     double lineDist = st ? st->lineDistance().val() : 1.0;
     133        75509 :     int userLine   = RealIsNull(yOff) ? 0 : lrint(yOff / (lineDist * spatium));
     134        75509 :     int lines      = st ? st->lines() : 5;
     135              : 
     136        75509 :     int naturalLine = computeNaturalLine(lines); // Measured in 1sp steps
     137        75509 :     int voiceOffset = computeVoiceOffset(item, ldata); // Measured in 1sp steps
     138        75509 :     int wholeRestOffset = computeWholeOrBreveRestOffset(item, voiceOffset, lines);
     139        75509 :     int finalLine = naturalLine + voiceOffset + wholeRestOffset;
     140              : 
     141        75509 :     ldata->sym = item->getSymbol(item->durationType().type(), finalLine + userLine, lines);
     142              : 
     143        75509 :     ldata->setPosY(finalLine * lineDist * spatium);
     144        75509 :     if (!item->shouldNotBeDrawn()) {
     145        73829 :         fillShape(item, ldata, ctx.conf());
     146              :     }
     147              : 
     148        75509 :     const_cast<Rest*>(item)->checkDots();
     149        75509 :     double visibleX = item->symWidthNoLedgerLines(ldata) + ctx.conf().styleAbsolute(Sid::dotNoteDistance) * item->mag();
     150        75509 :     double visibleDX = ctx.conf().styleAbsolute(Sid::dotDotDistance) * item->mag();
     151        75509 :     double invisibleX = item->symWidthNoLedgerLines(ldata);
     152        75509 :     double y = item->dotLine() * item->spatium() * .5;
     153        75689 :     for (NoteDot* dot : item->dotList()) {
     154          180 :         NoteDot::LayoutData* dotldata = dot->mutldata();
     155          180 :         TLayout::layoutNoteDot(dot, dotldata);
     156          180 :         if (dot->visible()) {
     157          157 :             dotldata->setPos(visibleX, y);
     158          157 :             visibleX += visibleDX;
     159              :         } else {
     160           23 :             invisibleX +=  0.1 * item->spatium();
     161           23 :             dotldata->setPos(invisibleX, y);
     162           23 :             invisibleX += item->symWidth(SymId::augmentationDot) * dot->mag();
     163              :         }
     164              :     }
     165              : }
     166              : 
     167       337300 : void RestLayout::fillShape(const Rest* item, Rest::LayoutData* ldata, const LayoutConfiguration& conf)
     168              : {
     169       337300 :     switch (item->type()) {
     170       336613 :     case ElementType::REST:
     171       336613 :         fillShape(toRest(item), static_cast<Rest::LayoutData*>(ldata));
     172       336613 :         break;
     173          687 :     case ElementType::MMREST:
     174          687 :         fillShape(static_cast<const MMRest*>(item), static_cast<MMRest::LayoutData*>(ldata), conf);
     175          687 :         break;
     176            0 :     default:
     177            0 :         UNREACHABLE;
     178              :         return;
     179              :     }
     180       337300 : }
     181              : 
     182          280 : void RestLayout::layoutRestForJianpu(const Rest* item, Rest::LayoutData* ldata, const LayoutContext& ctx)
     183              : {
     184          280 :     const Measure* measure = item->measure();
     185          280 :     if (!measure) {
     186            0 :         return;
     187              :     }
     188          280 :     Fraction tick = measure->tick();
     189          280 :     const Staff* staff = item->staff();
     190          280 :     const StaffType* st = staff->staffTypeForElement(item);
     191              : 
     192              :     // Jianpu Y origin is at the center of the number.
     193              :     // It always starts half a spatium above, aligned with the middle of the measure line.
     194          280 :     const double hy = -item->spatium() * .5 * item->mag();
     195          280 :     const double hx = 0.0;
     196          280 :     ldata->setPos(hx, hy);
     197              : 
     198          280 :     staff_idx_t idx = item->staffIdx() + item->staffMove();
     199          280 :     track_idx_t track = staff2track(idx);
     200          280 :     bool staffVisible = !staff->isLinesInvisible(tick);
     201              : 
     202          280 :     muse::draw::Font font(item->staffType()->jianpuFont());
     203          280 :     font.setPointSizeF(font.pointSizeF() * item->mag());
     204              : 
     205          280 :     muse::draw::FontMetrics fm(font);
     206          280 :     const double width = fm.width(String(u"0")) / item->magS();
     207          280 :     const double height = st->jianpuBoxH() * item->magS();
     208              : 
     209          280 :     RectF noteBBox = RectF(0, -height * .5, width, height);
     210          280 :     ldata->setBbox(noteBBox);
     211          280 :     int lines = jianpuAugmentationLinesForDuration(item->durationType());
     212          280 :     if (lines == 0) {
     213          235 :         muse::DeleteAll(item->jianpuDurationLines());
     214          235 :         const_cast<Rest*>(item)->jianpuDurationLines().clear();
     215              :     } else {
     216           45 :         const_cast<Rest*>(item)->setJianpuDurationLineCount(lines);
     217           90 :         for (int i = 0; i < lines; ++i) {
     218           45 :             JianpuDurationLine* dl = item->jianpuDurationLines()[i];
     219           45 :             dl->setOwnershipParent(const_cast<Rest*>(item));
     220           45 :             dl->setTrack(track);
     221           45 :             dl->setVisible(staffVisible);
     222           45 :             dl->mutldata()->len = width;
     223           45 :             dl->setPos(hx + width * 1.2 * (i + 1), hy);
     224              :         }
     225              : 
     226           90 :         for (JianpuDurationLine* dl : item->jianpuDurationLines()) {
     227           45 :             TLayout::layoutJianpuDurationLine(dl, ctx);
     228              :         }
     229              :     }
     230          280 : }
     231              : 
     232        99685 : void RestLayout::resolveVerticalRestConflicts(LayoutContext& ctx, Segment* segment, staff_idx_t staffIdx)
     233              : {
     234        99685 :     const Staff* staffForIdx = ctx.dom().staff(staffIdx);
     235        99685 :     if (staffForIdx && staffForIdx->isJianpuStaff(segment->tick())) {
     236              :         // jianpu rests are stacked into per-voice bands (see ChordLayout::layoutVoiceOffsets)
     237              :         // instead of using standard notation's notehead/rest shape collision avoidance
     238        99078 :         return;
     239              :     }
     240              : 
     241        97740 :     std::vector<Rest*> rests;
     242        97740 :     std::vector<Chord*> chords;
     243              : 
     244        97740 :     collectChordsAndRest(segment, staffIdx, chords, rests);
     245              : 
     246        97740 :     if (rests.empty()) {
     247        87657 :         return;
     248              :     }
     249              : 
     250        10083 :     collectChordsOverlappingRests(segment, staffIdx, chords);
     251              : 
     252        20814 :     for (Rest* rest : rests) {
     253        10731 :         rest->verticalClearance().reset();
     254              :     }
     255              : 
     256        10083 :     const Staff* staff = ctx.dom().staff(staffIdx);
     257        10083 :     if (!chords.empty()) {
     258          649 :         resolveRestVSChord(rests, chords, staff, segment);
     259              :     }
     260              : 
     261        10083 :     if (rests.size() < 2) {
     262         9476 :         return;
     263              :     }
     264              : 
     265          607 :     resolveRestVSRest(rests, staff, segment, ctx);
     266       194873 : }
     267              : 
     268          658 : void RestLayout::resolveRestVSChord(std::vector<Rest*>& rests, std::vector<Chord*>& chords, const Staff* staff, Segment* segment)
     269              : {
     270          658 :     Fraction tick = segment->tick();
     271          658 :     int lines = staff->lines(tick);
     272          658 :     double spatium = staff->spatium(tick);
     273          658 :     double lineDistance = staff->lineDistance(tick) * spatium;
     274              : 
     275         1338 :     for (Rest* rest : rests) {
     276          680 :         if (!rest->visible() || !rest->autoplace()) {
     277          132 :             continue;
     278              :         }
     279          548 :         bool isWholeOrHalf = rest->isWholeRest() || rest->durationType() == DurationType::V_HALF;
     280          548 :         double minRestToChordClearance = isWholeOrHalf ? 0.55 * spatium : 0.35 * spatium;
     281          548 :         RestVerticalClearance& restVerticalClearance = rest->verticalClearance();
     282         1106 :         for (Chord* chord : chords) {
     283          558 :             if (!chord->visible() || !chord->autoplace()) {
     284          169 :                 continue;
     285              :             }
     286              : 
     287          558 :             bool restAbove = rest->voice() < chord->voice() || (chord->slash() && !(rest->voice() % 2));
     288          558 :             int upSign = restAbove ? -1 : 1;
     289          558 :             double restYOffset = rest->offset().y();
     290          558 :             bool ignoreYOffset = (restAbove && restYOffset > 0) || (!restAbove && restYOffset < 0);
     291          558 :             PointF offset = ignoreYOffset ? PointF(0, restYOffset) : PointF(0, 0);
     292              : 
     293          558 :             Shape chordShape = chord->shape().translate(chord->pos());
     294          558 :             chordShape.removeInvisibles();
     295         1116 :             chordShape.removeTypes({ ElementType::ARPEGGIO });
     296          558 :             if (chordShape.empty()) {
     297            0 :                 continue;
     298              :             }
     299              : 
     300          558 :             double clearance = 0.0;
     301          558 :             Shape restShape = rest->shape().translate(rest->pos() - offset);
     302          558 :             if (chord->segment() == rest->segment()) {
     303          474 :                 clearance = restAbove
     304          474 :                             ? restShape.verticalClearance(chordShape)
     305          331 :                             : chordShape.verticalClearance(restShape);
     306              :             } else {
     307           84 :                 Note* limitNote = restAbove ? chord->upNote() : chord->downNote();
     308           84 :                 RectF noteShape = limitNote->symBbox(limitNote->noteHead()).translated(limitNote->pos());
     309           84 :                 clearance = restAbove ? noteShape.top() - restShape.bottom() : restShape.top() - noteShape.bottom();
     310           84 :                 minRestToChordClearance = 0.0;
     311              :             }
     312              : 
     313          558 :             double margin = clearance - minRestToChordClearance;
     314          558 :             int marginInSteps = floor(margin / lineDistance);
     315          558 :             if (restAbove) {
     316          172 :                 restVerticalClearance.setBelow(marginInSteps);
     317              :             } else {
     318          386 :                 restVerticalClearance.setAbove(marginInSteps);
     319              :             }
     320          558 :             if (margin > 0) {
     321          169 :                 continue;
     322              :             }
     323              : 
     324          389 :             rest->verticalClearance().setLocked(true);
     325          389 :             bool outAboveStaff = restAbove && restShape.bottom() + margin < minRestToChordClearance;
     326          389 :             bool outBelowStaff = !restAbove && restShape.top() - margin > (lines - 1) * lineDistance - minRestToChordClearance;
     327          389 :             bool useHalfSpaceSteps = (outAboveStaff || outBelowStaff) && !isWholeOrHalf;
     328              :             double yMove;
     329          389 :             if (useHalfSpaceSteps) {
     330          186 :                 int steps = ceil(std::abs(margin) / (lineDistance / 2));
     331          186 :                 yMove = steps * lineDistance / 2 * upSign;
     332          186 :                 rest->mutldata()->moveY(yMove);
     333              :             } else {
     334          203 :                 int steps = ceil(std::abs(margin) / lineDistance);
     335          203 :                 yMove = steps * lineDistance * upSign;
     336          203 :                 rest->mutldata()->moveY(yMove);
     337              :             }
     338          389 :             for (Rest* mergedRest : rest->ldata()->mergedRests) {
     339            0 :                 mergedRest->mutldata()->moveY(yMove);
     340              :             }
     341          389 :             if (isWholeOrHalf) {
     342           85 :                 updateSymbol(rest, rest->mutldata()); // Because it may need to use the symbol with ledger line now
     343              :             }
     344          727 :         }
     345              :     }
     346          658 : }
     347              : 
     348          616 : void RestLayout::resolveRestVSRest(std::vector<Rest*>& rests, const Staff* staff,
     349              :                                    Segment* segment, LayoutContext& ctx,
     350              :                                    bool considerBeams)
     351              : {
     352          616 :     if (rests.empty()) {
     353            0 :         return;
     354              :     }
     355              : 
     356          616 :     Fraction tick = segment->tick();
     357          616 :     double spatium = staff->spatium(tick);
     358          616 :     double lineDistance = staff->lineDistance(tick) * spatium;
     359          616 :     int lines = staff->lines(tick);
     360          616 :     const double minRestToRestClearance = 0.55 * spatium;
     361              : 
     362         1264 :     for (size_t i = 0; i < rests.size() - 1; ++i) {
     363          648 :         Rest* rest1 = rests[i];
     364          648 :         if (!rest1->visible() || !rest1->autoplace()) {
     365          166 :             continue;
     366              :         }
     367              : 
     368          639 :         RestVerticalClearance& rest1Clearance = rest1->verticalClearance();
     369          639 :         Shape shape1 = rest1->shape().translate(rest1->pos() - rest1->offset());
     370              : 
     371          639 :         Rest* rest2 = rests[i + 1];
     372          639 :         if (!rest2->visible() || !rest2->autoplace()) {
     373           45 :             continue;
     374              :         }
     375              : 
     376          594 :         if (muse::contains(rest1->ldata()->mergedRests, rest2) || muse::contains(rest2->ldata()->mergedRests, rest1)) {
     377            0 :             continue;
     378              :         }
     379              : 
     380          594 :         Shape shape2 = rest2->shape().translate(rest2->pos() - rest2->offset());
     381          594 :         RestVerticalClearance& rest2Clearance = rest2->verticalClearance();
     382              : 
     383              :         double clearance;
     384          594 :         bool firstAbove = rest1->voice() < rest2->voice();
     385          594 :         if (firstAbove) {
     386          594 :             clearance = shape1.verticalClearance(shape2);
     387              :         } else {
     388            0 :             clearance = shape2.verticalClearance(shape1);
     389              :         }
     390          594 :         double margin = clearance - minRestToRestClearance;
     391          594 :         int marginInSteps = floor(margin / lineDistance);
     392          594 :         if (firstAbove) {
     393          594 :             rest1Clearance.setBelow(marginInSteps);
     394          594 :             rest2Clearance.setAbove(marginInSteps);
     395              :         } else {
     396            0 :             rest1Clearance.setAbove(marginInSteps);
     397            0 :             rest2Clearance.setBelow(marginInSteps);
     398              :         }
     399              : 
     400          594 :         if (margin > 0) {
     401          112 :             continue;
     402              :         }
     403              : 
     404          482 :         int steps = ceil(std::abs(margin) / lineDistance);
     405              :         // Move the two rests away from each other
     406          482 :         int step1 = floor(double(steps) / 2);
     407          482 :         int step2 = ceil(double(steps) / 2);
     408          482 :         int maxStep1 = firstAbove ? rest1Clearance.above() : rest1Clearance.below();
     409          482 :         int maxStep2 = firstAbove ? rest2Clearance.below() : rest2Clearance.above();
     410          482 :         maxStep1 = std::max(maxStep1, 0);
     411          482 :         maxStep2 = std::max(maxStep2, 0);
     412          482 :         if (step1 > maxStep1) {
     413           28 :             step2 += step1 - maxStep1; // First rest is locked, try move the second more
     414              :         }
     415          482 :         if (step2 > maxStep2) {
     416            5 :             step1 += step2 - maxStep2; // Second rest is locked, try move the first more
     417              :         }
     418          482 :         step1 = std::min(step1, maxStep1);
     419          482 :         step2 = std::min(step2, maxStep2);
     420          482 :         rest1->mutldata()->moveY(step1 * lineDistance * (firstAbove ? -1 : 1));
     421          482 :         rest2->mutldata()->moveY(step2 * lineDistance * (firstAbove ? 1 : -1));
     422              : 
     423          482 :         Beam* beam1 = rest1->beam();
     424          482 :         Beam* beam2 = rest2->beam();
     425          482 :         if (beam1 && beam2 && considerBeams) {
     426            0 :             shape1 = rest1->shape().translate(rest1->pos() - rest1->offset());
     427            0 :             shape2 = rest2->shape().translate(rest2->pos() - rest2->offset());
     428              : 
     429            0 :             ChordRest* beam1Start = beam1->elements().front();
     430            0 :             ChordRest* beam1End = beam1->elements().back();
     431            0 :             double y1Start = BeamLayout::chordBeamAnchorY(beam1, beam1Start) - beam1Start->pagePos().y();
     432            0 :             double y1End = BeamLayout::chordBeamAnchorY(beam1, beam1End) - beam1End->pagePos().y();
     433            0 :             double beam1Ymid = 0.5 * (y1Start + y1End);
     434              : 
     435            0 :             ChordRest* beam2Start = beam2->elements().front();
     436            0 :             ChordRest* beam2End = beam2->elements().back();
     437            0 :             double y2Start = BeamLayout::chordBeamAnchorY(beam2, beam2Start) - beam2Start->pagePos().y();
     438            0 :             double y2End = BeamLayout::chordBeamAnchorY(beam2, beam2End) - beam2End->pagePos().y();
     439            0 :             double beam2Ymid = 0.5 * (y2Start + y2End);
     440              : 
     441            0 :             double centerY = 0.5 * (beam1Ymid + beam2Ymid);
     442              : 
     443            0 :             double upperBound = shape1.bottom();
     444            0 :             double lowerBound = shape2.top();
     445            0 :             int steps2 = 0;
     446            0 :             if (centerY < upperBound) {
     447            0 :                 steps2 = floor((centerY - upperBound) / lineDistance);
     448            0 :             } else if (centerY > lowerBound) {
     449            0 :                 steps2 = ceil((centerY - lowerBound) / lineDistance);
     450              :             }
     451            0 :             double moveY = steps2 * lineDistance;
     452            0 :             rest1->mutldata()->moveY(moveY);
     453            0 :             rest2->mutldata()->moveY(moveY);
     454            0 :             shape1.translate(PointF(0.0, moveY));
     455            0 :             shape2.translate(PointF(0.0, moveY));
     456              : 
     457            0 :             double halfLineDistance = 0.5 * lineDistance;
     458            0 :             if (shape1.bottom() < -halfLineDistance) {
     459            0 :                 rest1->mutldata()->moveY(halfLineDistance);
     460            0 :             } else if (centerY >= (lines - 1) * lineDistance + halfLineDistance) {
     461            0 :                 rest2->mutldata()->moveY(-halfLineDistance);
     462              :             }
     463              : 
     464            0 :             rest1->verticalClearance().setLocked(true);
     465            0 :             rest2->verticalClearance().setLocked(true);
     466            0 :             TLayout::layoutBeam(beam1, ctx);
     467            0 :             TLayout::layoutBeam(beam2, ctx);
     468              :         }
     469              : 
     470          482 :         bool rest1IsWholeOrHalf = rest1->isWholeRest() || rest1->durationType() == DurationType::V_HALF;
     471          482 :         bool rest2IsWholeOrHalf = rest2->isWholeRest() || rest2->durationType() == DurationType::V_HALF;
     472              : 
     473          482 :         if (rest1IsWholeOrHalf) {
     474           35 :             updateSymbol(rest1, rest1->mutldata());
     475              :         }
     476          482 :         if (rest2IsWholeOrHalf) {
     477           37 :             updateSymbol(rest2, rest2->mutldata());
     478              :         }
     479          751 :     }
     480              : }
     481              : 
     482         8231 : void RestLayout::alignRests(const System* system, LayoutContext& ctx)
     483              : {
     484         8231 :     RestGroups restGroups = computeRestGroups(system, ctx);
     485              : 
     486        20788 :     for (RestGroup& group : restGroups) {
     487        12557 :         if (group.size() <= 1) {
     488        12279 :             continue;
     489              :         }
     490              : 
     491          278 :         Rest* firstRest = group.front();
     492          278 :         const bool alignUpwards = firstRest->voice() == 0;
     493          278 :         const double lineDist = firstRest->staff()->lineDistance(firstRest->tick()) * firstRest->spatium();
     494              : 
     495          278 :         double yOuterRest = alignUpwards ? DBL_MAX : -DBL_MAX;
     496         1080 :         for (Rest* rest : group) {
     497          802 :             double yRest = rest->ldata()->pos().y();
     498          802 :             yOuterRest = alignUpwards ? std::min(yOuterRest, yRest) : std::max(yOuterRest, yRest);
     499              :         }
     500         1080 :         for (Rest* rest : group) {
     501          802 :             double yCur = rest->ldata()->pos().y();
     502          802 :             double yResult = yOuterRest;
     503          802 :             double restVertClearance = lineDist * (alignUpwards ? rest->verticalClearance().above() : rest->verticalClearance().below());
     504          802 :             double vertPadding = lineDist;
     505          802 :             restVertClearance = std::max(0.0, restVertClearance - vertPadding);
     506          802 :             double requiredMove = yOuterRest - yCur;
     507          802 :             if (std::abs(requiredMove) > restVertClearance) {
     508            3 :                 yResult = alignUpwards ? yCur - restVertClearance : yCur + restVertClearance;
     509              :             }
     510          802 :             rest->mutldata()->setPosY(yResult);
     511          802 :             if (rest->isWholeRest() || rest->durationType() == DurationType::V_HALF) {
     512           70 :                 updateSymbol(rest, rest->mutldata());
     513              :             }
     514              :         }
     515              :     }
     516         8231 : }
     517              : 
     518         8231 : RestGroups RestLayout::computeRestGroups(const System* system, LayoutContext& ctx)
     519              : {
     520         8231 :     RestGroups restGroups;
     521              : 
     522        21227 :     for (staff_idx_t staffIdx = 0; staffIdx < ctx.dom().nstaves(); ++staffIdx) {
     523        66584 :         for (const MeasureBase* mb : system->measures()) {
     524        53588 :             if (!(mb->isMeasure() && toMeasure(mb)->hasVoices(staffIdx))) {
     525        52323 :                 continue;
     526              :             }
     527              : 
     528         1265 :             const Measure* measure = toMeasure(mb);
     529         1265 :             track_idx_t sTrack = staff2track(staffIdx);
     530              : 
     531         1265 :             InterruptionPoints interruptionPoints = computeInterruptionPoints(measure, staffIdx);
     532              : 
     533         6325 :             for (voice_idx_t voice = 0; voice < VOICES; ++voice) {
     534         5060 :                 restGroups.push_back(RestGroup());
     535              : 
     536         5060 :                 std::list<Fraction>& interruptionPointsOnThisVoice = interruptionPoints[voice];
     537         5060 :                 track_idx_t track = sTrack + voice;
     538              : 
     539        30160 :                 for (const Segment* segment = measure->first(SegmentType::ChordRest); segment;
     540        25100 :                      segment = segment->next(SegmentType::ChordRest)) {
     541        25100 :                     if (interruptionPointsOnThisVoice.size() > 0 && segment->rtick() >= interruptionPointsOnThisVoice.front()) {
     542         7497 :                         restGroups.push_back(RestGroup());
     543         7497 :                         interruptionPointsOnThisVoice.pop_front();
     544              :                     }
     545              : 
     546        25100 :                     EngravingItem* item = segment->element(track);
     547        25100 :                     if (!(item && item->isRest() && item->visible())) {
     548        23019 :                         continue;
     549              :                     }
     550         2081 :                     Rest* rest = toRest(item);
     551         2081 :                     if (rest->staffMove() == 0 && !rest->isGap() && rest->alignWithOtherRests()) {
     552         1937 :                         restGroups.back().push_back(rest);
     553              :                     }
     554              :                 }
     555              :             }
     556         1265 :         }
     557              :     }
     558              : 
     559         8231 :     return restGroups;
     560            0 : }
     561              : 
     562         1265 : InterruptionPoints RestLayout::computeInterruptionPoints(const Measure* measure, staff_idx_t staffIdx)
     563              : {
     564              :     // Start with sets to get automatic uniqueness and ordering
     565         1265 :     std::array<std::set<Fraction>, VOICES> interruptionPointSets;
     566              : 
     567         1265 :     track_idx_t sTrack = staffIdx * VOICES;
     568         1265 :     track_idx_t eTrack = sTrack + VOICES;
     569              : 
     570              :     // Compute all-voices interruptions
     571         7540 :     for (const Segment* segment = measure->first(SegmentType::ChordRest); segment; segment = segment->next(SegmentType::ChordRest)) {
     572        30210 :         for (track_idx_t track = sTrack; track < eTrack; ++track) {
     573        24307 :             EngravingItem* item = segment->element(track);
     574        24307 :             if (!item) {
     575        14400 :                 continue;
     576              :             }
     577         9907 :             const bool gapRest = item->isRest() && toRest(item)->isGap();
     578              :             // TODO: The fact that "merged" rests exists in both voices and are just graphically overlapped is a messy way of
     579              :             // doing it and way too fragile, because it means that any logic that may move one rest can break the "merging".
     580              :             // A more solid way of merging rests would be to *delete* the second voice rests, i.e. turn them into gap rests [M.S.].
     581         9907 :             const bool hasMergedRest = item->isRest() && !toRest(item)->ldata()->mergedRests.empty();
     582         9907 :             const bool invisible = item->isChord() ? toChord(item)->allElementsInvisible() : !item->visible();
     583         9907 :             if (gapRest || hasMergedRest || invisible) {
     584         1860 :                 for (voice_idx_t voice = 0; voice < VOICES; ++voice) {
     585         1488 :                     interruptionPointSets[voice].insert(segment->rtick());
     586         1488 :                     interruptionPointSets[voice].insert(segment->rtick() + toChordRest(item)->actualTicks());
     587              :                 }
     588          372 :                 break;
     589              :             }
     590              :         }
     591              :     }
     592              : 
     593         9355 :     auto interruptHere = [&](ChordRest* chordRest) {
     594         9355 :         Fraction crTicks = chordRest->ticks();
     595         9355 :         if (crTicks > Fraction(1, 8)) {
     596         5843 :             return true;
     597              :         }
     598              : 
     599         3512 :         BeamMode beamModeChordRest = Groups::baseBeamMode(chordRest);
     600         3512 :         switch (beamModeChordRest) {
     601          363 :         case BeamMode::BEGIN:
     602              :             // Beam certainly starts here
     603          363 :             return true;
     604          148 :         case BeamMode::BEGIN16:
     605              :         case BeamMode::BEGIN32:
     606              :         case BeamMode::MID:
     607              :         case BeamMode::END:
     608              :             // Beam certainly doesn not start here
     609          148 :             return false;
     610         3001 :         default:
     611         3001 :             break;
     612              :         }
     613              : 
     614              :         // If BeamMode is AUTO or NONE check measure beaming
     615         3001 :         const Groups& groups = chordRest->staff()->group(chordRest->tick());
     616         3001 :         BeamMode beamModeMeasure = groups.beamMode(chordRest->rtick().ticks(), chordRest->durationType().type());
     617         3001 :         return beamModeMeasure == BeamMode::BEGIN;
     618              :     };
     619              : 
     620              :     // Compute voice-spefic interruptions
     621         6325 :     for (voice_idx_t voice = 0; voice < VOICES; ++voice) {
     622         5060 :         track_idx_t track = sTrack + voice;
     623        30160 :         for (const Segment* segment = measure->first(SegmentType::ChordRest); segment; segment = segment->next(SegmentType::ChordRest)) {
     624        25100 :             if (ChordRest* thisCR = toChordRest(segment->element(track))) {
     625         9984 :                 if (thisCR->isRest()) {
     626         2286 :                     const Segment* prevSegment = segment->prevWithElementsOnTrack(track);
     627         2286 :                     bool hasAdjacentRest = prevSegment && prevSegment->element(track)->isRest();
     628         2286 :                     if (hasAdjacentRest) {
     629          629 :                         continue;
     630              :                     }
     631              :                 }
     632         9355 :                 if (interruptHere(thisCR)) {
     633         6220 :                     interruptionPointSets[voice].insert(segment->rtick());
     634              :                 }
     635              :             }
     636              :         }
     637              :     }
     638              : 
     639              :     // Convert sets to lists
     640         1265 :     InterruptionPoints interruptionPoints;
     641         6325 :     for (voice_idx_t voice = 0; voice < VOICES; ++voice) {
     642         5060 :         const std::set<Fraction>& set = interruptionPointSets[voice];
     643        10120 :         interruptionPoints[voice] = std::list(set.begin(), set.end());
     644              :     }
     645              : 
     646         1265 :     return interruptionPoints;
     647         1265 : }
     648              : 
     649         8231 : void RestLayout::checkFullMeasureRestCollisions(const System* system, LayoutContext& ctx)
     650              : {
     651        21227 :     for (staff_idx_t staffIdx = 0; staffIdx < ctx.dom().nstaves(); ++staffIdx) {
     652        66584 :         for (MeasureBase* mb : system->measures()) {
     653        53588 :             if (!(mb->isMeasure() && toMeasure(mb)->hasVoices(staffIdx))) {
     654        53398 :                 continue;
     655              :             }
     656              : 
     657         1265 :             Measure* measure = toMeasure(mb);
     658         1265 :             Rest* fullMeasureRest = nullptr;
     659              : 
     660         1265 :             Segment* firstCRSeg = measure->first(SegmentType::ChordRest);
     661         1265 :             IF_ASSERT_FAILED(firstCRSeg) {
     662            0 :                 continue;
     663              :             }
     664         1265 :             track_idx_t startTrack = staff2track(staffIdx);
     665         1265 :             track_idx_t endTrack = startTrack + VOICES;
     666         5558 :             for (track_idx_t track = startTrack; track < endTrack; ++track) {
     667         4485 :                 EngravingItem* item = firstCRSeg->element(track);
     668         4485 :                 if (item && item->isRest() && toRest(item)->isFullMeasureRest()) {
     669          192 :                     fullMeasureRest = toRest(item);
     670          192 :                     break;
     671              :                 }
     672              :             }
     673              : 
     674         1265 :             if (!fullMeasureRest) {
     675         1073 :                 continue;
     676              :             }
     677              : 
     678          192 :             double xRest = fullMeasureRest->pagePos().x() - system->pagePos().x();
     679          192 :             Shape restShape = fullMeasureRest->shape().translate(PointF(xRest, fullMeasureRest->ldata()->pos().y()));
     680              : 
     681          192 :             Shape measureShape;
     682         1449 :             for (const Segment& segment : measure->segments()) {
     683         1257 :                 if (!segment.isActive()) {
     684           61 :                     continue;
     685              :                 }
     686         1196 :                 double xSegment = segment.pagePos().x() - system->pagePos().x();
     687         1196 :                 measureShape.add(segment.staffShape(staffIdx).translated(PointF(xSegment, 0.0)));
     688              :             }
     689          192 :             measureShape.remove_if([] (const ShapeElement& shapeEl) {
     690         2197 :                 const EngravingItem* shapeItem = shapeEl.item();
     691         4386 :                 return shapeItem && ((shapeItem->isRest() && toRest(shapeItem)->isFullMeasureRest())
     692         4386 :                                      || shapeItem->isBarLine() || shapeItem->isAccidental() || shapeItem->isFermata());
     693              :             });
     694              : 
     695          192 :             if (measureShape.size() == 0) {
     696            2 :                 continue;
     697              :             }
     698              : 
     699          190 :             const double spatium = fullMeasureRest->spatium();
     700          190 :             const double lineDist = fullMeasureRest->staff()->lineDistance(fullMeasureRest->tick()) * spatium;
     701          190 :             const double minHorizontalDistance = 4 * spatium;
     702          190 :             const double minVertClearance = 0.75 * spatium;
     703              : 
     704          190 :             bool alignAbove = fullMeasureRest->voice() == 0;
     705          190 :             double verticalClearance = alignAbove ? restShape.verticalClearance(measureShape, minHorizontalDistance)
     706            1 :                                        : measureShape.verticalClearance(restShape, minHorizontalDistance);
     707              : 
     708          190 :             if (verticalClearance < minVertClearance) {
     709           94 :                 double diff = minVertClearance - verticalClearance;
     710           94 :                 int stepMoves = std::ceil(diff / lineDist);
     711           94 :                 double yMove = stepMoves * lineDist;
     712           94 :                 fullMeasureRest->mutldata()->moveY(alignAbove ? -yMove : yMove);
     713           94 :                 updateSymbol(fullMeasureRest, fullMeasureRest->mutldata());
     714              :             }
     715          194 :         }
     716              :     }
     717         8231 : }
     718              : 
     719       336613 : void RestLayout::fillShape(const Rest* item, Rest::LayoutData* ldata)
     720              : {
     721       336613 :     Shape shape(Shape::Type::Composite);
     722              : 
     723       336613 :     if ((!item->isGap() || item->debugDrawGap()) && !item->shouldNotBeDrawn()) {
     724       330557 :         shape.add(ChordLayout::chordRestShape(item));
     725              : 
     726       330557 :         if (ldata->sym == SymId::noSym) {
     727         1899 :             shape.add(ldata->bbox(), item);
     728              :         } else {
     729       328658 :             shape.add(item->symBbox(ldata->sym), item);
     730              :         }
     731              : 
     732       331390 :         for (const NoteDot* dot : item->dotList()) {
     733          833 :             if (dot->addToSkyline()) {
     734          822 :                 shape.add(item->symBbox(SymId::augmentationDot).translated(dot->pos()), dot);
     735              :             }
     736              :         }
     737              :     }
     738              : 
     739       336613 :     for (const EngravingItem* e : item->el()) {
     740            0 :         if (e->addToSkyline()) {
     741            0 :             shape.add(e->shape().translate(e->pos()));
     742              :         }
     743              :     }
     744              : 
     745       336613 :     ldata->setShape(shape);
     746       336613 : }
     747              : 
     748          687 : void RestLayout::fillShape(const MMRest* item, MMRest::LayoutData* ldata, const LayoutConfiguration& conf)
     749              : {
     750          687 :     Shape shape(Shape::Type::Composite);
     751              : 
     752          687 :     double vStrokeHeight = conf.styleAbsolute(Sid::mmRestHBarVStrokeHeight);
     753          687 :     shape.add(RectF(0.0, -(vStrokeHeight * .5), ldata->restWidth, vStrokeHeight), item);
     754          687 :     if (item->showNumber()) {
     755          645 :         shape.add(item->numberRect().translated(item->numberPos()), item);
     756              :     }
     757              : 
     758          687 :     ldata->setShape(shape);
     759          687 : }
     760              : 
     761        75509 : int RestLayout::computeNaturalLine(int lines)
     762              : {
     763        75509 :     int line = (lines % 2) ? floor(double(lines) / 2) : ceil(double(lines) / 2);
     764        75509 :     return line;
     765              : }
     766              : 
     767        75509 : int RestLayout::computeVoiceOffset(const Rest* item, Rest::LayoutData* ldata)
     768              : {
     769        75509 :     ldata->mergedRests.clear();
     770        75509 :     Segment* s = item->segment();
     771        75509 :     Measure* measure = item->measure();
     772        75509 :     bool offsetVoices = s && measure && (item->voice() > 0 || measure->hasVoices(item->staffIdx(), item->tick(), item->actualTicks()));
     773        75509 :     if (offsetVoices && item->voice() == 0) {
     774              :         // do not offset voice 1 rest if there exists a matching invisible rest in voice 2;
     775         1055 :         EngravingItem* e = s->element(item->track() + 1);
     776         1055 :         if (e && e->isRest() && !e->visible() && !toRest(e)->isGap()) {
     777            0 :             Rest* r = toRest(e);
     778            0 :             if (r->globalTicks() == item->globalTicks()) {
     779            0 :                 offsetVoices = false;
     780              :             }
     781              :         }
     782              :     }
     783              : 
     784        75509 :     if (offsetVoices && item->voice() < 2) {
     785              :         // in slash notation voices 1 and 2 are not offset outside the staff
     786              :         // if the staff contains slash notation then only offset rests in voices 3 and 4
     787         2118 :         track_idx_t baseTrack = item->staffIdx() * VOICES;
     788        10569 :         for (voice_idx_t v = 0; v < VOICES; ++v) {
     789         8461 :             EngravingItem* e = s->element(baseTrack + v);
     790         8461 :             if (e && e->isChord() && toChord(e)->slash()) {
     791           10 :                 offsetVoices = false;
     792           10 :                 break;
     793              :             }
     794              :         }
     795              :     }
     796              : 
     797        75509 :     if (offsetVoices && item->staff()->shouldMergeMatchingRests()) {
     798              :         // automatically merge matching rests if nothing in any other voice
     799              :         // this is not always the right thing to do do, but is useful in choral music
     800              :         // and can be enabled via a staff property
     801            0 :         bool matchFound = false;
     802            0 :         track_idx_t baseTrack = item->staffIdx() * VOICES;
     803            0 :         for (voice_idx_t v = 0; v < VOICES; ++v) {
     804            0 :             if (v == item->voice()) {
     805            0 :                 continue;
     806              :             }
     807            0 :             EngravingItem* e = s->element(baseTrack + v);
     808              :             // try to find match in any other voice
     809            0 :             if (e) {
     810            0 :                 if (e->isRest()) {
     811            0 :                     Rest* r = toRest(e);
     812            0 :                     if (r->globalTicks() == item->globalTicks() && r->durationType() == item->durationType()) {
     813            0 :                         matchFound = true;
     814            0 :                         ldata->mergedRests.push_back(r);
     815            0 :                         continue;
     816              :                     }
     817              :                 }
     818              :                 // no match found; no sense looking for anything else
     819            0 :                 matchFound = false;
     820            0 :                 break;
     821              :             }
     822              :         }
     823            0 :         if (matchFound) {
     824            0 :             offsetVoices = false;
     825              :         }
     826              :     }
     827              : 
     828        75509 :     if (!offsetVoices) {
     829        73296 :         return 0;
     830              :     }
     831              : 
     832         2213 :     bool up = item->voice() == 0 || item->voice() == 2;
     833         2213 :     int upSign = up ? -1 : 1;
     834         2213 :     int voiceLineOffset = item->style().styleB(Sid::multiVoiceRestTwoSpaceOffset) ? 2 : 1;
     835              : 
     836         2213 :     return voiceLineOffset * upSign;
     837              : }
     838              : 
     839        75509 : int RestLayout::computeWholeOrBreveRestOffset(const Rest* item, int voiceOffset, int lines)
     840              : {
     841        75509 :     int lineMove = 0;
     842        75509 :     if (item->isWholeRest()) {
     843        65074 :         bool moveToLineAbove = (lines > 5)
     844        65074 :                                || ((lines > 1 || voiceOffset == -1 || voiceOffset == 2) && !(voiceOffset == -2 || voiceOffset == 1));
     845        65074 :         if (moveToLineAbove) {
     846        64955 :             lineMove = -1;
     847              :         }
     848        10435 :     } else if (item->isBreveRest() && lines == 1) {
     849            0 :         lineMove = 1;
     850              :     }
     851              : 
     852        75509 :     return lineMove;
     853              : }
     854              : 
     855          321 : void RestLayout::updateSymbol(const Rest* item, Rest::LayoutData* ldata)
     856              : {
     857          321 :     Fraction t = item->tick();
     858          321 :     Staff* st = item->staff();
     859          321 :     if (st->isJianpuStaff(t)) {
     860            0 :         return;
     861              :     }
     862              : 
     863          321 :     double lineDistance = st->lineDistance(t) * item->spatium();
     864          321 :     int lines = st->lines(t);
     865              : 
     866          321 :     double y = item->pos().y();
     867          321 :     int line = floor(y / lineDistance);
     868              : 
     869          321 :     ldata->sym = item->getSymbol(item->durationType().type(), line, lines);
     870              : }
     871              : } // namespace mu::engraving::rendering::score
        

Generated by: LCOV version 2.0-1