LCOV - code coverage report
Current view: top level - src/engraving/dom - harmony.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 55.2 % 841 464
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) 2021 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 "harmony.h"
      24              : 
      25              : #include "containers.h"
      26              : #include "translation.h"
      27              : 
      28              : #include "draw/fontmetrics.h"
      29              : 
      30              : #include "iengravingconfiguration.h" // IWYU pragma: keep
      31              : 
      32              : #include "../editing/transpose.h"
      33              : #include "../editing/transaction/transaction.h"
      34              : #include "../editing/transaction/undostack.h"
      35              : #include "../rendering/iscorerenderer.h"
      36              : 
      37              : #include "chordlist.h"
      38              : #include "fret.h"
      39              : #include "linkedobjects.h"
      40              : #include "measure.h"
      41              : #include "mscore.h"
      42              : #include "part.h"
      43              : #include "parenthesis.h"
      44              : #include "pitchspelling.h"
      45              : #include "repeatlist.h"
      46              : #include "score.h"
      47              : #include "segment.h"
      48              : #include "staff.h"
      49              : #include "textbase.h"
      50              : #include "utils.h"
      51              : 
      52              : #include "log.h"
      53              : 
      54              : using namespace mu;
      55              : using namespace muse::draw;
      56              : using namespace mu::engraving;
      57              : 
      58              : namespace mu::engraving {
      59              : static const char* FALLBACK_SYMBOLTEXT_FONT = "Bravura Text";
      60              : 
      61              : //---------------------------------------------------------
      62              : //   descr
      63              : //    look up id in chord list
      64              : //    return chord description if found, or null
      65              : //---------------------------------------------------------
      66              : 
      67         6131 : const ChordDescription* HarmonyInfo::descr() const
      68              : {
      69         6131 :     if (!chordList()) {
      70            0 :         return nullptr;
      71              :     }
      72         6131 :     return chordList()->description(id());
      73              : }
      74              : 
      75              : //---------------------------------------------------------
      76              : //   descr
      77              : //    look up name in chord list
      78              : //    optionally look up by parsed chord as fallback
      79              : //    return chord description if found, or null
      80              : //---------------------------------------------------------
      81              : 
      82          854 : const ChordDescription* HarmonyInfo::descr(const String& name, const ParsedChord* pc) const
      83              : {
      84          854 :     const ChordDescription* match = nullptr;
      85          854 :     if (!chordList()) {
      86            0 :         return nullptr;
      87              :     }
      88         2829 :     for (const auto& p : *chordList()) {
      89         2592 :         const ChordDescription& cd = p.second;
      90         4567 :         for (const String& s : cd.names) {
      91         2592 :             if (s == name) {
      92          617 :                 return &cd;
      93              :             }
      94         1975 :             if (!pc) {
      95         1494 :                 continue;
      96              :             }
      97          481 :             for (const ParsedChord& sParsed : cd.parsedChords) {
      98            0 :                 if (sParsed == *pc) {
      99            0 :                     match = &cd;
     100              :                 }
     101              :             }
     102              :         }
     103              :     }
     104              :     // exact match failed, so fall back on parsed match if one was found
     105          237 :     return match;
     106              : }
     107              : 
     108              : //---------------------------------------------------------
     109              : //   getDescription
     110              : //    look up id in chord list
     111              : //    return chord description if found
     112              : //    if not found, and chord is parseable,
     113              : //    generate a new chord description
     114              : //    and add to chord list
     115              : //---------------------------------------------------------
     116              : 
     117         3614 : const ChordDescription* HarmonyInfo::getDescription()
     118              : {
     119         3614 :     const ChordDescription* cd = descr();
     120         3614 :     if (cd && !cd->names.empty()) {
     121         3605 :         m_textName = cd->names.front();
     122            9 :     } else if (!m_textName.empty()) {
     123            9 :         cd = generateDescription();
     124            9 :         m_id = cd->id;
     125              :     }
     126         3614 :     return cd;
     127              : }
     128              : 
     129              : //---------------------------------------------------------
     130              : //   getDescription
     131              : //    same but lookup by name and optionally parsed chord
     132              : //---------------------------------------------------------
     133              : 
     134          783 : const ChordDescription* HarmonyInfo::getDescription(const String& name, const ParsedChord* pc)
     135              : {
     136          783 :     const ChordDescription* cd = descr(name, pc);
     137          783 :     if (cd) {
     138          578 :         m_id = cd->id;
     139              :     } else {
     140          205 :         cd = generateDescription();
     141          205 :         m_id = cd->id;
     142              :     }
     143          783 :     return cd;
     144              : }
     145              : 
     146              : //---------------------------------------------------------
     147              : //   generateDescription
     148              : //    generate new chord description from _textName
     149              : //    add to chord list using private id
     150              : //---------------------------------------------------------
     151              : 
     152          263 : const ChordDescription* HarmonyInfo::generateDescription()
     153              : {
     154          263 :     ChordDescription cd(m_textName);
     155          263 :     cd.complete(getParsedChord(), chordList());
     156              :     // remove parsed chord from description
     157              :     // so we will only match it literally in the future
     158          263 :     cd.parsedChords.clear();
     159          263 :     chordList()->insert({ cd.id, cd });
     160          526 :     return &chordList()->at(cd.id);
     161          263 : }
     162              : 
     163          883 : ParsedChord* HarmonyInfo::getParsedChord()
     164              : {
     165          883 :     if (!m_parsedChord) {
     166          609 :         m_parsedChord = new ParsedChord();
     167          609 :         m_parsedChord->parse(m_textName, chordList(), false);
     168              :     }
     169          883 :     return m_parsedChord;
     170              : }
     171              : 
     172            0 : bool HarmonyInfo::hasModifiers() const
     173              : {
     174            0 :     return m_parsedChord ? m_parsedChord->modifiers().size() > 0 : false;
     175              : }
     176              : 
     177          212 : String Harmony::displayText() const
     178              : {
     179              :     // String representation of what the user sees on the score
     180              :     // Used in fretbox
     181          212 :     String name;
     182          386 :     for (const HarmonyRenderItem* segment : ldata()->renderItemList()) {
     183          174 :         if (const TextSegment* textSeg = dynamic_cast<const TextSegment*>(segment)) {
     184          174 :             String t = textSeg->text();
     185          174 :             t.replace(u"\uE87C", u"/");
     186          174 :             name += t;
     187          174 :         } else if (const ChordSymbolParen* parenSeg = dynamic_cast<const ChordSymbolParen*>(segment)) {
     188            0 :             name += parenSeg->parenItem->direction() == DirectionH::LEFT ? u"(" : u")";
     189              :         }
     190              :     }
     191              : 
     192          212 :     return name;
     193            0 : }
     194              : 
     195              : //---------------------------------------------------------
     196              : //   harmonyName
     197              : //---------------------------------------------------------
     198              : 
     199          989 : String Harmony::harmonyName() const
     200              : {
     201          989 :     String name;
     202              : 
     203          989 :     if (leftParen()) {
     204            1 :         name = u"(";
     205              :     }
     206              : 
     207         1954 :     for (size_t i = 0; i < m_chords.size(); i++) {
     208          965 :         const HarmonyInfo* info = m_chords.at(i);
     209          965 :         HChord hc = info->descr() ? info->descr()->chord : HChord();
     210          965 :         String s, r, e, b;
     211              : 
     212          965 :         if (i != 0) {
     213            4 :             name += u"|";
     214              :         }
     215              : 
     216          965 :         if (m_harmonyType == HarmonyType::STANDARD && tpcIsValid(info->rootTpc())) {
     217          916 :             NoteSpellingType spelling = style().styleV(Sid::chordSymbolSpelling).value<NoteSpellingType>();
     218          916 :             r = tpc2name(info->rootTpc(), spelling, m_rootCase);
     219           49 :         } else if (m_harmonyType == HarmonyType::NASHVILLE && tpcIsValid(info->rootTpc())) {
     220           24 :             const Staff* st = staff();
     221           24 :             Key key = st ? st->key(tick()) : Key::INVALID;
     222           24 :             r = tpc2Function(info->rootTpc(), key);
     223              :         }
     224              : 
     225          965 :         if (!info->textName().empty()) {
     226          594 :             e = info->textName();
     227          594 :             if (m_harmonyType != HarmonyType::ROMAN) {
     228          575 :                 e.remove(u'=');
     229              :             }
     230          371 :         } else if (!m_degreeList.empty()) {
     231            0 :             hc.add(m_degreeList);
     232              :             // try to find the chord in chordList
     233            0 :             const ChordDescription* newExtension = nullptr;
     234            0 :             const ChordList* cl = score()->chordList();
     235            0 :             for (const auto& p : *cl) {
     236            0 :                 const ChordDescription& cd = p.second;
     237            0 :                 if (cd.chord == hc && !cd.names.empty()) {
     238            0 :                     newExtension = &cd;
     239            0 :                     break;
     240              :                 }
     241              :             }
     242              :             // now determine the chord name
     243            0 :             if (newExtension) {
     244            0 :                 e = newExtension->names.front();
     245              :             } else {
     246              :                 // not in table, fallback to using HChord.name()
     247            0 :                 r = hc.name(info->rootTpc());
     248            0 :                 e = u"";
     249              :             }
     250              :         }
     251              : 
     252          965 :         if (tpcIsValid(info->bassTpc())) {
     253           13 :             NoteSpellingType spelling = style().styleV(Sid::chordSymbolSpelling).value<NoteSpellingType>();
     254           13 :             b = u"/" + tpc2name(info->bassTpc(), spelling, m_bassCase);
     255              :         }
     256              : 
     257          965 :         s += r + e + b;
     258              : 
     259          965 :         name += s;
     260          965 :     }
     261              : 
     262          989 :     if (rightParen()) {
     263            1 :         name += u")";
     264              :     }
     265              : 
     266          989 :     return name;
     267            0 : }
     268              : 
     269          492 : bool Harmony::isRealizable() const
     270              : {
     271          492 :     if (m_chords.empty()) {
     272            0 :         return false;
     273              :     }
     274          984 :     for (const HarmonyInfo* info : m_chords) {
     275          492 :         if (!tpcIsValid(info->rootTpc())) {
     276            0 :             return false;
     277              :         }
     278              :     }
     279          492 :     return true;
     280              : }
     281              : 
     282            7 : int Harmony::bassTpc() const
     283              : {
     284            7 :     if (m_chords.empty()) {
     285            0 :         return Tpc::TPC_INVALID;
     286              :     }
     287            7 :     return m_chords.front()->bassTpc();
     288              : }
     289              : 
     290          132 : int Harmony::rootTpc() const
     291              : {
     292          132 :     if (m_chords.empty()) {
     293            0 :         return Tpc::TPC_INVALID;
     294              :     }
     295          132 :     return m_chords.front()->rootTpc();
     296              : }
     297              : 
     298            0 : bool Harmony::isInFretBox() const
     299              : {
     300            0 :     EngravingObject* parent = ownershipParent();
     301            0 :     if (!parent) {
     302            0 :         return false;
     303              :     }
     304              : 
     305            0 :     if (parent->isFretDiagram()) {
     306            0 :         return toFretDiagram(parent)->isInFretBox();
     307              :     }
     308              : 
     309            0 :     return parent->isFBox();
     310              : }
     311              : 
     312              : //---------------------------------------------------------
     313              : //   chordSymbolStyle
     314              : //---------------------------------------------------------
     315              : 
     316              : const ElementStyle chordSymbolStyle {
     317              :     { Sid::harmonyPlacement, Pid::PLACEMENT },
     318              :     { Sid::minHarmonyDistance, Pid::MIN_DISTANCE },
     319              :     { Sid::chordBassNoteScale, Pid::HARMONY_BASS_SCALE },
     320              :     { Sid::harmonyVoiceLiteral, Pid::HARMONY_VOICE_LITERAL },
     321              :     { Sid::harmonyVoicing, Pid::HARMONY_VOICING },
     322              :     { Sid::harmonyDuration, Pid::HARMONY_DURATION },
     323              : };
     324              : 
     325              : //---------------------------------------------------------
     326              : //   Harmony
     327              : //---------------------------------------------------------
     328              : 
     329         1072 : Harmony::Harmony(DummyParentOr<Segment, FretDiagram> parent)
     330         1072 :     : TextBase(ElementType::HARMONY, parent, TextStyleType::HARMONY_A, ElementFlag::MOVABLE | ElementFlag::ON_STAFF)
     331              : {
     332         1072 :     m_rootCase   = NoteCaseType::CAPITAL;
     333         1072 :     m_bassCase   = NoteCaseType::CAPITAL;
     334         1072 :     m_harmonyType = HarmonyType::STANDARD;
     335         1072 :     m_play = true;
     336         1072 :     m_realizedHarmony = RealizedHarmony(this);
     337         1072 :     initElementStyle(&chordSymbolStyle);
     338         1072 : }
     339              : 
     340           66 : Harmony::Harmony(const Harmony& h)
     341           66 :     : TextBase(h)
     342              : {
     343           66 :     m_rootCase   = h.m_rootCase;
     344           66 :     m_bassCase   = h.m_bassCase;
     345           66 :     m_bassScale = h.m_bassScale;
     346           66 :     m_degreeList = h.m_degreeList;
     347           66 :     m_harmonyType = h.m_harmonyType;
     348           66 :     m_play       = h.m_play;
     349           66 :     m_realizedHarmony = h.m_realizedHarmony;
     350           66 :     m_realizedHarmony.setHarmony(this);
     351          132 :     for (const HarmonyInfo* hi : h.m_chords) {
     352           66 :         HarmonyInfo* newInfo = new HarmonyInfo(*hi);
     353           66 :         m_chords.push_back(newInfo);
     354              :     }
     355              : 
     356           66 :     m_fontFamily = h.m_fontFamily;
     357           66 :     m_fontStyle  = h.m_fontStyle;
     358           66 :     m_fontSize   = h.m_fontSize;
     359           66 : }
     360              : 
     361              : //---------------------------------------------------------
     362              : //   ~Harmony
     363              : //---------------------------------------------------------
     364              : 
     365         2178 : Harmony::~Harmony()
     366              : {
     367         4469 :     for (const HarmonyRenderItem* renderItem : mutldata()->renderItemList()) {
     368         3372 :         delete renderItem;
     369              :     }
     370         2201 :     for (const HarmonyInfo* info : m_chords) {
     371         1104 :         delete info;
     372              :     }
     373         2178 : }
     374              : 
     375            0 : int Harmony::id() const
     376              : {
     377            0 :     if (m_chords.empty()) {
     378            0 :         return -1;
     379              :     }
     380            0 :     return m_chords.front()->id();
     381              : }
     382              : 
     383              : //---------------------------------------------------------
     384              : //   getParentSeg
     385              : ///   gets the parent segment of this harmony
     386              : //---------------------------------------------------------
     387              : 
     388         1715 : Segment* Harmony::getParentSeg() const
     389              : {
     390         1715 :     Segment* seg = nullptr;
     391         1715 :     if (!ownershipParent()) {
     392            0 :         return nullptr;
     393              :     }
     394              : 
     395         1715 :     if (ownershipParent()->isFretDiagram()) {
     396              :         // When this harmony is the child of a fret diagram, we need to go up twice
     397              :         // to get to the parent seg.
     398           34 :         seg = toFretDiagram(ownershipParent())->segment();
     399              :     } else {
     400         1681 :         seg = toSegment(ownershipParent());
     401              :     }
     402         1715 :     return seg;
     403              : }
     404              : 
     405          219 : FretDiagram* Harmony::getParentFretDiagram() const
     406              : {
     407          219 :     if (ownershipParent() && ownershipParent()->isFretDiagram()) {
     408          215 :         return toFretDiagram(ownershipParent());
     409              :     }
     410              : 
     411            4 :     return nullptr;
     412              : }
     413              : 
     414          709 : void Harmony::afterRead()
     415              : {
     416              :     // TODO: now that we can render arbitrary chords,
     417              :     // we could try to construct a full representation from a degree list.
     418              :     // These will typically only exist for chords imported from MusicXML prior to MuseScore 2.0
     419              :     // or constructed in the Chord Symbol Properties dialog.
     420              : 
     421         1421 :     for (HarmonyInfo* info : m_chords) {
     422          712 :         if (tpcIsValid(info->rootTpc())) {
     423          704 :             if (info->id() > 0) {
     424              :                 // positive id will happen only for scores that were created with explicit chord lists
     425              :                 // lookup id in chord list and generate new description if necessary
     426            0 :                 info->getDescription();
     427              :             } else {
     428              :                 // default case: look up by name
     429              :                 // description will be found for any chord already read in this score
     430              :                 // and we will generate a new one if necessary
     431          704 :                 info->getDescription(info->textName());
     432              :             }
     433            8 :         } else if (info->textName().empty()) {
     434              :             // unrecognized chords prior to 2.0 were stored as text with markup
     435              :             // we need to strip away the markup
     436              :             // this removes any user-applied formatting,
     437              :             // but we no longer support user-applied formatting for chord symbols anyhow
     438              :             // with any luck, the resulting text will be parseable now, so give it a shot
     439            0 :             createBlocks();
     440            0 :             String s = plainText();
     441            0 :             if (!s.isEmpty()) {
     442            0 :                 setHarmony(s);
     443            0 :                 return;
     444              :             }
     445              :             // empty text could also indicate a root-less slash chord ("/E")
     446              :             // we'll fall through and render it normally
     447            0 :         }
     448              :     }
     449              : 
     450              :     // render chord from description (or _textName)
     451          709 :     setPlainText(harmonyName());
     452              : }
     453              : 
     454            0 : bool Harmony::hasModifiers() const
     455              : {
     456            0 :     for (const HarmonyInfo* info : m_chords) {
     457            0 :         if (info->hasModifiers()) {
     458            0 :             return true;
     459              :         }
     460              :     }
     461              : 
     462            0 :     return false;
     463              : }
     464              : 
     465              : //---------------------------------------------------------
     466              : //   parseHarmony
     467              : //    determine root and bass tpc & case
     468              : //    compare body of chordname against chord list
     469              : //    return true if chord is recognized
     470              : //---------------------------------------------------------
     471              : 
     472           87 : const std::vector<const ChordDescription*> Harmony::parseHarmony(const String& ss, bool syntaxOnly)
     473              : {
     474              :     // pre-process for parentheses
     475           87 :     String s = ss.simplified();
     476           87 :     if (s.startsWith('(')) {
     477            0 :         setParenthesesMode(rightParen() ? ParenthesesMode::BOTH : ParenthesesMode::LEFT, true, false);
     478            0 :         s.remove(0, 1);
     479              :     } else {
     480           87 :         setParenthesesMode(rightParen() ? ParenthesesMode::RIGHT : ParenthesesMode::NONE, true, false);
     481              :     }
     482              : 
     483           87 :     if (s.endsWith(')') && s.count('(') < s.count(')')) {
     484            0 :         setParenthesesMode(leftParen() ? ParenthesesMode::BOTH : ParenthesesMode::RIGHT, true, false);
     485            0 :         s.remove(s.size() - 1, 1);
     486              :     } else {
     487           87 :         setParenthesesMode(leftParen() ? ParenthesesMode::LEFT : ParenthesesMode::NONE, true, false);
     488              :     }
     489              : 
     490           87 :     if (parenthesesMode() == ParenthesesMode::BOTH) {
     491            0 :         s = s.simplified();         // in case of spaces inside parentheses
     492              :     }
     493              : 
     494           87 :     muse::DeleteAll(m_chords);
     495           87 :     m_chords.clear();
     496              : 
     497           87 :     std::vector<const ChordDescription*> descriptions;
     498           87 :     if (s.isEmpty()) {
     499            0 :         return descriptions;
     500              :     }
     501              : 
     502           87 :     StringList chords = s.split('|');
     503              : 
     504          175 :     for (const String& subChord : chords) {
     505           88 :         if (subChord.empty()) {
     506            0 :             continue;
     507              :         }
     508           88 :         HarmonyInfo* info = new HarmonyInfo(score());
     509           88 :         const ChordDescription* cd = parseSingleHarmony(subChord, info, syntaxOnly);
     510           88 :         descriptions.push_back(cd);
     511           88 :         m_chords.push_back(info);
     512              :     }
     513              : 
     514           87 :     return descriptions;
     515           87 : }
     516              : 
     517           88 : const ChordDescription* Harmony::parseSingleHarmony(const String& ss, HarmonyInfo* info, bool syntaxOnly)
     518              : {
     519           88 :     String s = ss.simplified();
     520              : 
     521           88 :     if (m_harmonyType == HarmonyType::ROMAN) {
     522           16 :         info->setTextName(s);
     523           16 :         info->setRootTpc(Tpc::TPC_INVALID);
     524           16 :         info->setBassTpc(Tpc::TPC_INVALID);
     525           16 :         return nullptr;
     526              :     }
     527              : 
     528           72 :     bool useLiteral = false;
     529           72 :     if (ss.endsWith(' ')) {
     530            0 :         useLiteral = true;
     531              :     }
     532              : 
     533              :     // pre-process for lower case minor chords
     534              :     bool preferMinor;
     535           72 :     if (style().styleB(Sid::lowerCaseMinorChords) && s.at(0).isLower()) {
     536            0 :         preferMinor = true;
     537              :     } else {
     538           72 :         preferMinor = false;
     539              :     }
     540              : 
     541           72 :     size_t idx = 0;
     542           72 :     const Staff* st = staff();
     543           72 :     Key key = st ? st->key(tick()) : Key::INVALID;
     544           72 :     NoteSpellingType spelling = style().styleV(Sid::chordSymbolSpelling).value<NoteSpellingType>();
     545              : 
     546           72 :     int r = Tpc::TPC_INVALID;
     547           72 :     if (m_harmonyType == HarmonyType::STANDARD) {
     548           72 :         r = convertNote(s, spelling, m_rootCase, idx);
     549            0 :     } else if (m_harmonyType == HarmonyType::NASHVILLE) {
     550            0 :         r = function2Tpc(s, key, idx);
     551              :     }
     552           72 :     if (!tpcIsValid(r)) {
     553            1 :         if (s.at(0) == '/') {
     554            0 :             idx = 0;
     555              :         } else {
     556            1 :             LOGD("failed <%s>", muPrintable(ss));
     557            1 :             info->setTextName(s);
     558            1 :             return 0;
     559              :         }
     560              :     }
     561           71 :     info->setRootTpc(r);
     562           71 :     info->setBassTpc(Tpc::TPC_INVALID);
     563           71 :     size_t slash = s.lastIndexOf(u'/');
     564           71 :     if (slash != muse::nidx) {
     565            8 :         String bs = s.mid(slash + 1).simplified();
     566            8 :         s = s.mid(idx, slash - idx).simplified();
     567            8 :         size_t idx2 = 0;
     568            8 :         if (m_harmonyType == HarmonyType::STANDARD) {
     569            8 :             info->setBassTpc(convertNote(bs, spelling, m_bassCase, idx2));
     570            0 :         } else if (m_harmonyType == HarmonyType::NASHVILLE) {
     571            0 :             info->setBassTpc(function2Tpc(bs, key, idx2));
     572              :         }
     573              : 
     574            8 :         if (idx2 != bs.size()) {
     575            0 :             info->setBassTpc(Tpc::TPC_INVALID);
     576              :         }
     577            8 :         if (!tpcIsValid(info->bassTpc())) {
     578              :             // if what follows after slash is not (just) a TPC
     579              :             // then reassemble chord and try to parse with the slash
     580            0 :             s = s + u"/" + bs;
     581              :         }
     582            8 :     } else {
     583           63 :         s = s.mid(idx);             // don't simplify; keep leading space before extension if present
     584              :     }
     585              : 
     586           71 :     const ChordList* cl = score()->chordList();
     587           71 :     const ChordDescription* cd = 0;
     588           71 :     if (useLiteral) {
     589            0 :         cd = info->descr(s);
     590              :     } else {
     591           71 :         ParsedChord* pc = new ParsedChord();
     592           71 :         pc->parse(s, cl, syntaxOnly, preferMinor);
     593              :         // parser prepends "=" to name of implied minor chords
     594              :         // use this here as well
     595           71 :         if (preferMinor) {
     596            0 :             s = pc->name();
     597              :         }
     598              :         // look up to see if we already have a descriptor (chord has been used before)
     599           71 :         cd = info->descr(s, pc);
     600           71 :         info->setParsedChord(pc);
     601              :     }
     602           71 :     if (cd) {
     603              :         // descriptor found; use its information
     604           39 :         info->setId(cd->id);
     605           39 :         if (!cd->names.empty()) {
     606           39 :             info->setTextName(cd->names.front());
     607              :         }
     608              :     } else {
     609              :         // no descriptor yet; just set textname
     610              :         // we will generate descriptor later if necessary (when we are done editing this chord)
     611           32 :         info->setTextName(s);
     612              :     }
     613           71 :     return cd;
     614           88 : }
     615              : 
     616         3614 : NoteCaseType Harmony::rootRenderCase(HarmonyInfo* info) const
     617              : {
     618              :     // case
     619              :     // always use case as typed if automatic capitalization is off
     620         3614 :     NoteCaseType noteCase = m_rootCase;
     621         3614 :     if (!style().styleB(Sid::automaticCapitalization)) {
     622            0 :         return noteCase;
     623              :     }
     624              : 
     625              :     // set default
     626         3614 :     if (style().styleB(Sid::allCapsNoteNames)) {
     627            0 :         noteCase = NoteCaseType::UPPER;
     628              :     } else {
     629         3614 :         noteCase = NoteCaseType::CAPITAL;
     630              :     }
     631              : 
     632              :     // override for minor chords
     633         3614 :     if (style().styleB(Sid::lowerCaseMinorChords)) {
     634            0 :         const ChordDescription* cd = info->descr();
     635            0 :         String quality;
     636            0 :         if (cd) {
     637              :             // use chord description if possible
     638              :             // this is the usual case
     639            0 :             quality = cd->quality();
     640            0 :         } else if (info->getParsedChord()) {
     641              :             // this happens on load of new chord list
     642              :             // for chord symbols that were added/edited since the score was loaded
     643              :             // or read aloud with screenreader
     644              :             // parsed form is usable even if out of date with respect to chord list
     645            0 :             quality = info->getParsedChord()->quality();
     646              :         } else {
     647              :             // this happens on load of new chord list
     648              :             // for chord symbols that have not been edited since the score was loaded
     649              :             // we need to parse this chord for now to determine quality
     650              :             // but don't keep the parsed form around as we're not ready for it yet
     651            0 :             quality = info->getParsedChord()->quality();
     652            0 :             delete info->parsedChord();
     653            0 :             info->setParsedChord(nullptr);
     654              :         }
     655            0 :         if (quality == "minor" || quality == "diminished" || quality == "half-diminished") {
     656            0 :             noteCase = NoteCaseType::LOWER;
     657              :         }
     658            0 :     }
     659              : 
     660         3614 :     return noteCase;
     661              : }
     662              : 
     663         3614 : NoteCaseType Harmony::bassRenderCase() const
     664              : {
     665              :     // case
     666              :     // always use case as typed if automatic capitalization is off
     667         3614 :     NoteCaseType noteCase = m_bassCase;
     668         3614 :     if (!style().styleB(Sid::automaticCapitalization)) {
     669            0 :         return noteCase;
     670              :     }
     671              : 
     672              :     // set default
     673         3614 :     if (style().styleB(Sid::allCapsNoteNames)) {
     674            0 :         noteCase = NoteCaseType::UPPER;
     675              :     } else {
     676         3614 :         noteCase = NoteCaseType::CAPITAL;
     677              :     }
     678              : 
     679              :     // override for bass note
     680         3614 :     if (style().styleB(Sid::lowerCaseBassNotes)) {
     681            0 :         noteCase = NoteCaseType::LOWER;
     682              :     }
     683              : 
     684         3614 :     return noteCase;
     685              : }
     686              : 
     687              : //---------------------------------------------------------
     688              : //   startEdit
     689              : //---------------------------------------------------------
     690              : 
     691            0 : void Harmony::startEdit(EditData& ed)
     692              : {
     693            0 :     if (!ldata()->renderItemList().empty()) {
     694              :         // convert chord symbol to plain text
     695            0 :         setPlainText(harmonyName());
     696              :         // clear rendering
     697            0 :         for (const HarmonyRenderItem* renderItem : mutldata()->renderItemList()) {
     698            0 :             delete renderItem;
     699              :         }
     700            0 :         mutldata()->renderItemList.mut_value().clear();
     701              :     }
     702              : 
     703            0 :     if (leftParen()) {
     704            0 :         leftParen()->mutldata()->reset();
     705              :     }
     706            0 :     if (rightParen()) {
     707            0 :         rightParen()->mutldata()->reset();
     708              :     }
     709              : 
     710              :     // layout as text, without position reset
     711            0 :     renderer()->layoutText1(this, true);
     712            0 :     triggerLayout();
     713              : 
     714            0 :     TextBase::startEdit(ed);
     715            0 : }
     716              : 
     717            0 : bool Harmony::isEditAllowed(EditData& ed) const
     718              : {
     719            0 :     if (isTextNavigationKey(ed.key, ed.modifiers)) {
     720            0 :         return false;
     721              :     }
     722              : 
     723            0 :     if (ed.key == Key_Semicolon || ed.key == Key_Colon) {
     724            0 :         return false;
     725              :     }
     726              : 
     727            0 :     if ((ed.key == Key_Left || ed.key == Key_Right) && (ed.modifiers & ControlModifier)) {
     728            0 :         return false;
     729              :     }
     730              : 
     731            0 :     if (ed.key == Key_Return || ed.key == Key_Enter) {
     732              :         // This "edit" is actually handled in NotationInteraction::editElement
     733            0 :         return true;
     734              :     }
     735              : 
     736            0 :     return TextBase::isEditAllowed(ed);
     737              : }
     738              : 
     739              : //---------------------------------------------------------
     740              : //   edit
     741              : //---------------------------------------------------------
     742              : 
     743            0 : bool Harmony::edit(EditData& ed)
     744              : {
     745            0 :     if (!isEditAllowed(ed)) {
     746            0 :         return false;
     747              :     }
     748              : 
     749            0 :     bool rv = TextBase::edit(ed);
     750              : 
     751              :     // layout as text, without position reset
     752            0 :     renderer()->layoutText1(this, true);
     753            0 :     triggerLayout();
     754              : 
     755              :     // check spelling
     756            0 :     String str = xmlText();
     757              : 
     758            0 :     std::vector<const ChordDescription*> descriptions = parseHarmony(str, true);
     759            0 :     bool descriptionsValid = true;
     760            0 :     for (const ChordDescription* cd : descriptions) {
     761            0 :         if (!cd) {
     762            0 :             descriptionsValid = false;
     763              :         }
     764              :     }
     765              : 
     766            0 :     bool tpcsValid = true;
     767            0 :     for (const HarmonyInfo* info : m_chords) {
     768            0 :         tpcsValid &= tpcIsValid(info->rootTpc());
     769              :     }
     770              : 
     771            0 :     m_isMisspelled = !str.isEmpty()
     772            0 :                      && !descriptionsValid
     773            0 :                      && !tpcsValid
     774            0 :                      && m_harmonyType == HarmonyType::STANDARD;
     775              : 
     776            0 :     if (m_isMisspelled) {
     777            0 :         LOGD("bad spell");
     778              :     }
     779              : 
     780            0 :     return rv;
     781            0 : }
     782              : 
     783              : //---------------------------------------------------------
     784              : //   endEdit
     785              : //---------------------------------------------------------
     786              : 
     787            0 : void Harmony::endEdit(EditData& ed)
     788              : {
     789              :     // get plain text
     790            0 :     String s = plainText();
     791              : 
     792              :     // if user explicitly added symbols to the text,
     793              :     // convert them back to their respective replacement texts
     794            0 :     if (harmonyType() != HarmonyType::ROMAN) {
     795            0 :         s.replace(u"\u1d12b", u"bb");     // double-flat
     796            0 :         s.replace(u"\u266d",  u"b");      // flat
     797            0 :         s.replace(u"\ue260",  u"b");      // flat
     798              :         // do not replace natural sign
     799              :         // (right now adding the symbol explicitly is the only way to force a natural sign to appear at all)
     800              :         //s.replace("\u266e",  "n");  // natural, if one day we support that too
     801              :         //s.replace("\ue261",  "n");  // natural, if one day we support that too
     802            0 :         s.replace(u"\u266f",  u"#");      // sharp
     803            0 :         s.replace(u"\ue262",  u"#");      // sharp
     804            0 :         s.replace(u"\u1d12a", u"x");      // double-sharp
     805            0 :         s.replace(u"\u0394",  u"^");      // &Delta;
     806            0 :         s.replace(u"\u00d0",  u"o");      // &deg;
     807            0 :         s.replace(u"\u00f8",  u"0");      // &oslash;
     808            0 :         s.replace(u"\u00d8",  u"0");      // &Oslash;
     809              :     } else {
     810            0 :         s.replace(u"\ue260",  u"\u266d");         // flat
     811            0 :         s.replace(u"\ue261",  u"\u266e");         // natural
     812            0 :         s.replace(u"\ue262",  u"\u266f");         // sharp
     813              :     }
     814              : 
     815              :     //play chord on edit and set dirty
     816            0 :     score()->setPlayChord(true);
     817              : 
     818            0 :     setHarmony(s);
     819            0 :     setPlainText(harmonyName());
     820              : 
     821              :     // disable spell check
     822            0 :     m_isMisspelled = false;
     823              : 
     824            0 :     const bool textEdited = textWasEdited(ed);
     825              : 
     826            0 :     TextBase::endEdit(ed);
     827              : 
     828            0 :     if (!links() || !textEdited) {
     829            0 :         return;
     830              :     }
     831              : 
     832            0 :     const bool thisConcertPitch = style().styleB(Sid::concertPitch);
     833            0 :     const Interval thisInterval = thisConcertPitch ? Interval(0, 0) : staff()->transpose(tick());
     834              : 
     835            0 :     for (EngravingObject* e : *links()) {
     836            0 :         if (e == this) {
     837            0 :             continue;
     838              :         }
     839            0 :         Harmony* h = toHarmony(e);
     840              :         // transpose if necessary
     841              :         // at this point chord will already have been rendered in same key as original
     842              :         // (as a result of TextBase::endEdit() calling setText() for linked elements)
     843              :         // we may now need to change the TPC's and the text, and re-render
     844            0 :         const bool linkedConcertPitch = h->style().styleB(Sid::concertPitch);
     845            0 :         if (thisConcertPitch == linkedConcertPitch) {
     846            0 :             continue;
     847              :         }
     848              : 
     849            0 :         Score* linkedScore = h->score();
     850            0 :         const Staff* linkedStaff = h->staff();
     851            0 :         const Interval linkedInterval = linkedConcertPitch ? Interval(0, 0) : linkedStaff->transpose(h->tick());
     852            0 :         const Interval transposeDiff(thisInterval.diatonic - linkedInterval.diatonic, thisInterval.chromatic - linkedInterval.chromatic);
     853            0 :         if (transposeDiff.isZero()) {
     854            0 :             continue;
     855              :         }
     856              : 
     857            0 :         UndoStack* undoStack = linkedScore->undoStack();
     858            0 :         const size_t undoIdx = undoStack->currentIndex();
     859              : 
     860            0 :         score()->transactionManager()->transaction(TranslatableString("undoableAction", "Transpose harmony"), [&](auto& tx) {
     861            0 :             Transpose::undoTransposeHarmony(tx, h, transposeDiff);
     862            0 :         });
     863              : 
     864              :         // Merge with end of text editing
     865            0 :         if (undoIdx != undoStack->currentIndex() && undoStack->currentIndex() >= 2) {
     866            0 :             const size_t penultimateCmdIdx = undoStack->currentIndex() - 2;
     867            0 :             undoStack->mergeTransactions(penultimateCmdIdx);
     868              :         }
     869              :     }
     870            0 : }
     871              : 
     872            0 : bool Harmony::isPlayable() const
     873              : {
     874            0 :     return !isInFretBox();
     875              : }
     876              : 
     877              : //---------------------------------------------------------
     878              : //   setHarmony
     879              : //---------------------------------------------------------
     880              : 
     881           87 : void Harmony::setHarmony(const String& s)
     882              : {
     883           87 :     m_realizedHarmony.setDirty(true);
     884              : 
     885           87 :     std::vector<const ChordDescription*> descriptions = parseHarmony(s);
     886          175 :     for (size_t i = 0; i < m_chords.size(); i++) {
     887           88 :         HarmonyInfo* info = m_chords.at(i);
     888           88 :         const ChordDescription* cd = i < descriptions.size() ? descriptions.at(i) : nullptr;
     889              : 
     890           88 :         if (!cd && info->getParsedChord()->parseable()) {
     891              :             // our first time encountering this chord
     892              :             // generate a descriptor and use it
     893           49 :             cd = info->generateDescription();
     894           49 :             info->setId(cd->id);
     895              :         }
     896           88 :         if (!cd) {
     897              :             // unparseable chord or roman numeral, render as plain text
     898            0 :             info->setRootTpc(Tpc::TPC_INVALID);
     899            0 :             info->setBassTpc(Tpc::TPC_INVALID);
     900            0 :             info->setId(-1);
     901              :         }
     902              :     }
     903           87 : }
     904              : 
     905              : //---------------------------------------------------------
     906              : //   baseLine
     907              : //---------------------------------------------------------
     908              : 
     909         3540 : double Harmony::baseLine() const
     910              : {
     911         3540 :     if (ldata()->renderItemList().empty() || !ldata()->baseline.has_value()) {
     912            0 :         return TextBase::baseLine();
     913              :     }
     914              : 
     915         3540 :     return ldata()->baseline.value();
     916              : }
     917              : 
     918              : //---------------------------------------------------------
     919              : //   text
     920              : //---------------------------------------------------------
     921              : 
     922           10 : String HDegree::text() const
     923              : {
     924           10 :     if (m_type == HDegreeType::UNDEF) {
     925            0 :         return String();
     926              :     }
     927           10 :     String degree;
     928           10 :     switch (m_type) {
     929            0 :     case HDegreeType::UNDEF: break;
     930            8 :     case HDegreeType::ADD:         degree = u"add";
     931            8 :         break;
     932            1 :     case HDegreeType::ALTER:       degree = u"alt";
     933            1 :         break;
     934            1 :     case HDegreeType::SUBTRACT:    degree = u"sub";
     935            1 :         break;
     936              :     }
     937              : 
     938           10 :     switch (m_alter) {
     939            1 :     case -1:          degree += u"b";
     940            1 :         break;
     941            1 :     case 1:           degree += u"#";
     942            1 :         break;
     943            8 :     default:          break;
     944              :     }
     945           20 :     String s = String::number(m_value);
     946           20 :     String ss = degree + s;
     947           10 :     return ss;
     948           10 : }
     949              : 
     950              : //---------------------------------------------------------
     951              : //   findInSeg
     952              : ///   find a Harmony in a given segment on the same track as this harmony.
     953              : ///
     954              : ///   returns 0 if there is none
     955              : //---------------------------------------------------------
     956              : 
     957         1173 : Harmony* Harmony::findInSeg(Segment* seg) const
     958              : {
     959              :     // Find harmony as parent of fret diagram on same track
     960         1173 :     EngravingItem* fde = seg->findAnnotation(ElementType::FRET_DIAGRAM, track(), track());
     961         1173 :     if (fde) {
     962            0 :         FretDiagram* fd = toFretDiagram(fde);
     963            0 :         if (fd->harmony()) {
     964            0 :             return toHarmony(fd->harmony());
     965              :         }
     966              :     }
     967              : 
     968              :     // Find harmony on same track
     969         1173 :     EngravingItem* e = seg->findAnnotation(ElementType::HARMONY, track(), track());
     970         1173 :     if (e) {
     971          481 :         return toHarmony(e);
     972              :     }
     973          692 :     return nullptr;
     974              : }
     975              : 
     976              : //---------------------------------------------------------
     977              : //   findNext
     978              : ///   find the next Harmony in the score
     979              : ///
     980              : ///   returns 0 if there is none
     981              : //---------------------------------------------------------
     982              : 
     983          492 : Harmony* Harmony::findNext() const
     984              : {
     985          492 :     const Segment* segment = getParentSeg();
     986          492 :     Segment* cur = segment ? segment->next1() : nullptr;
     987         1184 :     while (cur) {
     988         1173 :         Harmony* h = findInSeg(cur);
     989         1173 :         if (h) {
     990          481 :             return h;
     991              :         }
     992          692 :         cur = cur->next1();
     993              :     }
     994           11 :     return nullptr;
     995              : }
     996              : 
     997              : //---------------------------------------------------------
     998              : //   findPrev
     999              : ///   find the previous Harmony in the score
    1000              : ///
    1001              : ///   returns 0 if there is none
    1002              : //---------------------------------------------------------
    1003              : 
    1004            0 : Harmony* Harmony::findPrev() const
    1005              : {
    1006            0 :     const Segment* segment = getParentSeg();
    1007            0 :     Segment* cur = segment ? segment->prev1() : nullptr;
    1008            0 :     while (cur) {
    1009            0 :         Harmony* h = findInSeg(cur);
    1010            0 :         if (h) {
    1011            0 :             return h;
    1012              :         }
    1013            0 :         cur = cur->prev1();
    1014              :     }
    1015            0 :     return nullptr;
    1016              : }
    1017              : 
    1018              : //---------------------------------------------------------
    1019              : //   ticksTillNext
    1020              : ///   finds ticks until the next chord symbol or end of score
    1021              : ///
    1022              : ///   utick is our current playback position to start from
    1023              : ///
    1024              : ///   stopAtMeasureEnd being set to true will have the loop
    1025              : ///   stop at measure end.
    1026              : //---------------------------------------------------------
    1027          482 : Fraction Harmony::ticksTillNext(int utick, bool stopAtMeasureEnd) const
    1028              : {
    1029          482 :     const Segment* seg = getParentSeg();
    1030          482 :     if (!seg) {
    1031            0 :         return Fraction(-1, 1);
    1032              :     }
    1033              : 
    1034          482 :     Fraction duration = seg->ticks();
    1035              : 
    1036          482 :     const RepeatList& repeats = score()->repeatList();
    1037          482 :     auto rsIt = repeats.findRepeatSegmentFromUTick(utick);
    1038          482 :     if (rsIt == repeats.cend()) {
    1039            0 :         return duration;
    1040              :     }
    1041              : 
    1042          482 :     Segment* cur = seg->next();
    1043          482 :     Measure const* currentMeasure = seg->measure();
    1044          482 :     Measure const* endMeasure = (stopAtMeasureEnd) ? currentMeasure : (*rsIt)->lastMeasure();
    1045          482 :     Harmony const* nextHarmony = nullptr;
    1046              : 
    1047              :     do {
    1048              :         // Loop over segments of this measure
    1049         1597 :         while (cur) {
    1050              :             //find harmony on same track
    1051         1115 :             EngravingItem* e = cur->findAnnotation(ElementType::HARMONY, track(), track());
    1052         1115 :             if (e) {
    1053          471 :                 nextHarmony = toHarmony(e);
    1054              :             } else {
    1055              :                 // no harmony; look for fret diagram
    1056          644 :                 e = cur->findAnnotation(ElementType::FRET_DIAGRAM, track(), track());
    1057          644 :                 if (e) {
    1058            0 :                     nextHarmony = toFretDiagram(e)->harmony();
    1059              :                 }
    1060              :             }
    1061         1115 :             if (nextHarmony != nullptr) {
    1062              :                 //we have found the next chord symbol
    1063          471 :                 break;
    1064              :             }
    1065              :             //keep adding the duration of the current segment
    1066              :             //in case we are not able to find a next
    1067              :             //chord symbol
    1068          644 :             duration += cur->ticks();
    1069          644 :             cur = cur->next();
    1070              :         }
    1071              :         // Move segment reference to next measure
    1072          953 :         if (currentMeasure != endMeasure) {
    1073          932 :             currentMeasure = currentMeasure->nextMeasure();
    1074          932 :             if (currentMeasure && currentMeasure->mmRest()) {
    1075            0 :                 duration += currentMeasure->mmRest()->ticks();
    1076            0 :                 currentMeasure = currentMeasure->mmRest()->nextMeasure();
    1077              :             }
    1078          932 :             cur = (currentMeasure) ? currentMeasure->first() : nullptr;
    1079              :         } else {
    1080              :             // End of repeatSegment or search boundary reached
    1081           21 :             if (stopAtMeasureEnd) {
    1082            3 :                 break;
    1083           18 :             } else if (!nextHarmony) {
    1084              :                 // move to next RepeatSegment
    1085            9 :                 if (++rsIt != repeats.end()) {
    1086            0 :                     currentMeasure = (*rsIt)->firstMeasure();
    1087            0 :                     endMeasure     = (*rsIt)->lastMeasure();
    1088            0 :                     cur = currentMeasure->first();
    1089              :                 }
    1090              :             }
    1091              :         }
    1092          950 :     } while ((nextHarmony == nullptr) && (cur != nullptr));
    1093              : 
    1094          482 :     if (nextHarmony && rsIt != repeats.end()) {
    1095          471 :         int tickOffset = (*rsIt)->utick - (*rsIt)->tick;
    1096          471 :         int nextHarmonyUtick = nextHarmony->tick().ticks() + tickOffset;
    1097          471 :         duration = Fraction::fromTicks(nextHarmonyUtick - utick);
    1098              :     }
    1099              : 
    1100          482 :     return duration;
    1101              : }
    1102              : 
    1103              : //---------------------------------------------------------
    1104              : //   getRealizedHarmony
    1105              : //    get realized harmony or create one for the current symbol
    1106              : //    also updates the realized harmony and accounts for
    1107              : //    transposition. RealizedHarmony objects cannot be cached
    1108              : //    since the notes generated depends on context rather than
    1109              : //    just root, bass, chord symbol, and voicing.
    1110              : //---------------------------------------------------------
    1111              : 
    1112          492 : const RealizedHarmony& Harmony::getRealizedHarmony() const
    1113              : {
    1114          492 :     const Staff* st = staff();
    1115          492 :     IF_ASSERT_FAILED(st) {
    1116            0 :         return m_realizedHarmony;
    1117              :     }
    1118              : 
    1119          492 :     const Fraction tick = this->tick();
    1120          492 :     const CapoParams& capo = st->capo(tick);
    1121              : 
    1122          492 :     int offset = 0;
    1123          492 :     if (capo.active && CapoParams::TransposeMode::TAB_ONLY != capo.transposeMode) {
    1124            0 :         offset = capo.fretPosition;
    1125              :     }
    1126              : 
    1127          492 :     Interval interval = originPart()->instrument(tick)->transpose();
    1128          492 :     if (!style().styleB(Sid::concertPitch)) {
    1129          467 :         offset += interval.chromatic;
    1130              :     }
    1131              : 
    1132          492 :     HarmonyInfo* info = m_chords.empty() ? nullptr : m_chords.front();
    1133          492 :     int root = info ? info->rootTpc() : Tpc::TPC_INVALID;
    1134          492 :     int bass = info ? info->bassTpc() : Tpc::TPC_INVALID;
    1135              : 
    1136          492 :     m_realizedHarmony.update(root, bass, offset);
    1137              : 
    1138          492 :     return m_realizedHarmony;
    1139              : }
    1140              : 
    1141              : //---------------------------------------------------------
    1142              : //   realizedHarmony
    1143              : //    get realized harmony or create one for the current symbol
    1144              : //    without updating the realized harmony
    1145              : //---------------------------------------------------------
    1146              : 
    1147          108 : RealizedHarmony& Harmony::realizedHarmony()
    1148              : {
    1149          108 :     return m_realizedHarmony;
    1150              : }
    1151              : 
    1152          571 : const ParsedChord* Harmony::parsedForm()const
    1153              : {
    1154          571 :     if (m_chords.empty()) {
    1155            0 :         return nullptr;
    1156              :     }
    1157          571 :     return m_chords.front()->getParsedChord();
    1158              : }
    1159              : 
    1160            0 : Color Harmony::curColor(const rendering::PaintOptions& opt) const
    1161              : {
    1162            0 :     if (!opt.isPrinting && m_isMisspelled) {
    1163            0 :         return configuration()->criticalColor();
    1164              :     }
    1165              : 
    1166            0 :     return EngravingItem::curColor(opt);
    1167              : }
    1168              : 
    1169         1230 : void Harmony::setColor(const Color& color)
    1170              : {
    1171         1230 :     EngravingItem::setColor(color);
    1172              : 
    1173         1372 :     for (HarmonyRenderItem* item : ldata()->renderItemList()) {
    1174          142 :         if (ChordSymbolParen* paren = dynamic_cast<ChordSymbolParen*>(item)) {
    1175            8 :             paren->parenItem->setColor(color);
    1176              :         }
    1177              :     }
    1178         1230 : }
    1179              : 
    1180              : //---------------------------------------------------------
    1181              : //   width
    1182              : //---------------------------------------------------------
    1183              : 
    1184        10770 : double TextSegment::width() const
    1185              : {
    1186        10770 :     return FontMetrics::width(m_font, m_text);
    1187              : }
    1188              : 
    1189        14210 : double TextSegment::capHeight() const
    1190              : {
    1191        14210 :     return FontMetrics::capHeight(m_font);
    1192              : }
    1193              : 
    1194        53498 : RectF TextSegment::tightBoundingRect() const
    1195              : {
    1196        53498 :     return FontMetrics::tightBoundingRect(m_font, m_text);
    1197              : }
    1198              : 
    1199            0 : RectF TextSegment::boundingRect() const
    1200              : {
    1201            0 :     return FontMetrics::boundingRect(m_font, m_text);
    1202              : }
    1203              : 
    1204        10674 : void TextSegment::setFont(const muse::draw::Font& f)
    1205              : {
    1206        10674 :     m_font = f;
    1207        10674 :     if (f.type() != Font::Type::MusicSymbolText) {
    1208        10506 :         return;
    1209              :     }
    1210              : 
    1211              :     // Check all symbols in string are available in this font
    1212          168 :     FontMetrics fm(f);
    1213          168 :     bool fail = false;
    1214          336 :     for (size_t i = 0; i < m_text.size(); ++i) {
    1215          168 :         const Char& c = m_text.at(i);
    1216          168 :         if (c.isHighSurrogate()) {
    1217            0 :             if (i + 1 == m_text.size()) {
    1218            0 :                 ASSERT_X("bad string");
    1219              :             }
    1220            0 :             const Char& c2 = m_text.at(i + 1);
    1221            0 :             ++i;
    1222            0 :             char32_t v = Char::surrogateToUcs4(c, c2);
    1223            0 :             if (!fm.inFont(v)) {
    1224            0 :                 fail = true;
    1225            0 :                 break;
    1226              :             }
    1227              :         } else {
    1228          168 :             if (!fm.inFont(c.unicode())) {
    1229            0 :                 fail = true;
    1230            0 :                 break;
    1231              :             }
    1232              :         }
    1233              :     }
    1234              :     // Fallback to default musical text font
    1235          168 :     if (fail) {
    1236            0 :         m_font.setFamily(String::fromUtf8(FALLBACK_SYMBOLTEXT_FONT), Font::Type::MusicSymbolText);
    1237              :     }
    1238          168 : }
    1239              : 
    1240              : //---------------------------------------------------------
    1241              : //   spatiumChanged
    1242              : //---------------------------------------------------------
    1243              : 
    1244            5 : void Harmony::spatiumChanged(double oldValue, double newValue)
    1245              : {
    1246            5 :     TextBase::spatiumChanged(oldValue, newValue);
    1247            5 : }
    1248              : 
    1249              : //---------------------------------------------------------
    1250              : //   localSpatiumChanged
    1251              : //---------------------------------------------------------
    1252              : 
    1253            0 : void Harmony::localSpatiumChanged(double oldValue, double newValue)
    1254              : {
    1255            0 :     TextBase::localSpatiumChanged(oldValue, newValue);
    1256            0 : }
    1257              : 
    1258              : //---------------------------------------------------------
    1259              : //   addDegree
    1260              : //---------------------------------------------------------
    1261              : 
    1262            0 : void Harmony::addDegree(const HDegree& d)
    1263              : {
    1264            0 :     m_degreeList.push_back(d);
    1265            0 : }
    1266              : 
    1267              : //---------------------------------------------------------
    1268              : //   degreeList
    1269              : //---------------------------------------------------------
    1270              : 
    1271          750 : const std::vector<HDegree>& Harmony::degreeList() const
    1272              : {
    1273          750 :     return m_degreeList;
    1274              : }
    1275              : 
    1276              : //---------------------------------------------------------
    1277              : //   setHarmonyType
    1278              : //---------------------------------------------------------
    1279              : 
    1280           92 : void Harmony::setHarmonyType(HarmonyType val)
    1281              : {
    1282           92 :     m_harmonyType = val;
    1283           92 :     setPlacement(propertyDefault(Pid::PLACEMENT).value<PlacementV>());
    1284           92 :     switch (m_harmonyType) {
    1285           26 :     case HarmonyType::STANDARD:
    1286           26 :         initTextStyleType(TextStyleType::HARMONY_A);
    1287           26 :         break;
    1288           23 :     case HarmonyType::ROMAN:
    1289           23 :         initTextStyleType(TextStyleType::HARMONY_ROMAN);
    1290           23 :         break;
    1291           43 :     case HarmonyType::NASHVILLE:
    1292           43 :         initTextStyleType(TextStyleType::HARMONY_NASHVILLE);
    1293           43 :         break;
    1294              :     }
    1295              :     // TODO: convert text
    1296           92 : }
    1297              : 
    1298              : //---------------------------------------------------------
    1299              : //   typeUserName
    1300              : //---------------------------------------------------------
    1301              : 
    1302            0 : TranslatableString Harmony::typeUserName() const
    1303              : {
    1304            0 :     switch (m_harmonyType) {
    1305            0 :     case HarmonyType::ROMAN:
    1306            0 :         return TranslatableString("engraving", "Roman numeral");
    1307            0 :     case HarmonyType::NASHVILLE:
    1308            0 :         return TranslatableString("engraving", "Nashville number");
    1309            0 :     case HarmonyType::STANDARD:
    1310            0 :         break;
    1311              :     }
    1312            0 :     return EngravingItem::typeUserName();
    1313              : }
    1314              : 
    1315              : //---------------------------------------------------------
    1316              : //   accessibleInfo
    1317              : //---------------------------------------------------------
    1318              : 
    1319            0 : String Harmony::accessibleInfo() const
    1320              : {
    1321            0 :     return String(u"%1: %2").arg(translatedTypeUserName(), harmonyName());
    1322              : }
    1323              : 
    1324              : //---------------------------------------------------------
    1325              : //   screenReaderInfo
    1326              : //---------------------------------------------------------
    1327              : 
    1328            0 : String Harmony::screenReaderInfo() const
    1329              : {
    1330            0 :     return String(u"%1 %2").arg(translatedTypeUserName(), generateScreenReaderInfo());
    1331              : }
    1332              : 
    1333              : //---------------------------------------------------------
    1334              : //   generateScreenReaderInfo
    1335              : //---------------------------------------------------------
    1336              : 
    1337            0 : String Harmony::generateScreenReaderInfo() const
    1338              : {
    1339            0 :     String rez;
    1340            0 :     for (size_t i = 0; i < m_chords.size(); i++) {
    1341            0 :         HarmonyInfo* info = m_chords.at(i);
    1342            0 :         if (!tpcIsValid(info->rootTpc())) {
    1343            0 :             continue;
    1344              :         }
    1345            0 :         if (i != 0) {
    1346            0 :             rez += u" | ";
    1347              :         }
    1348              : 
    1349            0 :         switch (m_harmonyType) {
    1350            0 :         case HarmonyType::ROMAN: {
    1351            0 :             if (m_chords.empty()) {
    1352            0 :                 return u"";
    1353              :             }
    1354            0 :             String aux = info->textName();
    1355            0 :             bool hasUpper = aux.contains(u'I') || aux.contains(u'V');
    1356            0 :             bool hasLower = aux.contains(u'i') || aux.contains(u'v');
    1357            0 :             if (hasLower && !hasUpper) {
    1358            0 :                 rez = String(u"%1 %2").arg(rez, muse::mtrc("engraving", "lower case"));
    1359              :             }
    1360            0 :             aux = aux.toLower();
    1361              :             static const std::vector<std::pair<String, String> > rnaReplacements {
    1362              :                 { u"vii", u"7" },
    1363              :                 { u"vi", u"6" },
    1364              :                 { u"iv", u"4" },
    1365              :                 { u"v", u"5" },
    1366              :                 { u"iii", u"3" },
    1367              :                 { u"ii", u"2" },
    1368              :                 { u"i", u"1" },
    1369            0 :             };
    1370              :             static const std::vector<std::pair<String, String> > symbolReplacements {
    1371              :                 { u"bb", u"𝄫" },
    1372              :                 { u"##", u"𝄪" },
    1373              :                 { u"h", u"♮" },
    1374              :                 { u"\\♮", u"h" }, // \h should be h, so need to correct replacing in the previous step
    1375              :                 { u"#", u"♯" },
    1376              :                 { u"\\♯", u"#" }, // \# should be #, so need to correct replacing in the previous step
    1377              :                 { u"b", u"♭" },
    1378              :                 { u"\\♭", u"b" }, // \b should be b, so need to correct replacing in the previous step
    1379              :                 // TODO: use SMuFL glyphs and translate
    1380              :                 //{ "o", ""},
    1381              :                 //{ "0", ""},
    1382              :                 //{ "\+", ""},
    1383              :                 //{ "\^", ""},
    1384            0 :             };
    1385            0 :             for (auto const& r : rnaReplacements) {
    1386            0 :                 aux.replace(r.first, r.second);
    1387              :             }
    1388            0 :             for (auto const& r : symbolReplacements) {
    1389            0 :                 aux.replace(r.first, r.second);
    1390              :             }
    1391              :             // construct string one  character at a time
    1392            0 :             for (size_t j = 0; j < aux.size(); ++j) {
    1393            0 :                 rez = String(u"%1 %2").arg(rez).arg(aux.at(j));
    1394              :             }
    1395            0 :         }
    1396            0 :             return rez;
    1397            0 :         case HarmonyType::NASHVILLE: {
    1398            0 :             const Staff* st = staff();
    1399            0 :             Key key = st ? st->key(tick()) : Key::INVALID;
    1400            0 :             rez = String(u"%1 %2").arg(rez, tpc2Function(info->rootTpc(), key));
    1401            0 :             break;
    1402              :         }
    1403            0 :         case HarmonyType::STANDARD:
    1404              :         default:
    1405            0 :             rez = String(u"%1 %2").arg(rez, tpc2name(info->rootTpc(), NoteSpellingType::STANDARD, NoteCaseType::AUTO, true));
    1406              :         }
    1407              : 
    1408            0 :         if (!info->textName().isEmpty()) {
    1409            0 :             String aux = info->getParsedChord()->handle();
    1410            0 :             aux = aux.replace(u"#", u"♯").replace(u"<", u"");
    1411            0 :             String extension;
    1412              : 
    1413            0 :             for (String s : aux.split(u'>', muse::SkipEmptyParts)) {
    1414            0 :                 if (!s.contains(u"blues")) {
    1415            0 :                     s.replace(u"b", u"♭");
    1416              :                 }
    1417            0 :                 extension += s + u' ';
    1418            0 :             }
    1419            0 :             rez = String(u"%1 %2").arg(rez, extension);
    1420            0 :         } else {
    1421            0 :             rez = String(u"%1 %2").arg(rez, info->textName());
    1422              :         }
    1423              : 
    1424            0 :         if (tpcIsValid(info->bassTpc())) {
    1425            0 :             rez = String(u"%1 / %2").arg(rez, tpc2name(info->bassTpc(), NoteSpellingType::STANDARD, NoteCaseType::AUTO, true));
    1426              :         }
    1427              :     }
    1428              : 
    1429            0 :     return rez;
    1430            0 : }
    1431              : 
    1432              : //---------------------------------------------------------
    1433              : //   acceptDrop
    1434              : //---------------------------------------------------------
    1435              : 
    1436            0 : bool Harmony::acceptDrop(EditData& data) const
    1437              : {
    1438            0 :     EngravingItem* e = data.dropElement;
    1439            0 :     if (e->isFretDiagram()) {
    1440            0 :         EngravingObject* parent = ownershipParent();
    1441            0 :         return parent && parent->isSegment();
    1442            0 :     } else if (e->isSymbol() || e->isFSymbol()) {
    1443              :         // symbols can be added in edit mode
    1444            0 :         if (data.getData(this)) {
    1445            0 :             return true;
    1446              :         } else {
    1447            0 :             return false;
    1448              :         }
    1449              :     }
    1450            0 :     return false;
    1451              : }
    1452              : 
    1453              : //---------------------------------------------------------
    1454              : //   drop
    1455              : //---------------------------------------------------------
    1456              : 
    1457            0 : EngravingItem* Harmony::drop(Transaction& tx, EditData& data)
    1458              : {
    1459            0 :     EngravingItem* e = data.dropElement;
    1460            0 :     EngravingObject* parent = ownershipParent();
    1461            0 :     if (e->isFretDiagram() && parent && parent->isSegment()) {
    1462            0 :         FretDiagram* fd = toFretDiagram(e);
    1463            0 :         fd->setOwnershipParent(toSegment(parent));
    1464            0 :         fd->setTrack(track());
    1465            0 :         score()->undoAddElement(fd);
    1466            0 :     } else if (e->isSymbol() || e->isFSymbol()) {
    1467            0 :         TextBase::drop(tx, data);
    1468            0 :         renderer()->layoutText1(this);
    1469            0 :         e = 0;          // cannot select
    1470              :     } else {
    1471            0 :         LOGW("Harmony: cannot drop <%s>\n", e->typeName());
    1472            0 :         delete e;
    1473            0 :         e = 0;
    1474              :     }
    1475            0 :     return e;
    1476              : }
    1477              : 
    1478            0 : void Harmony::undoChangeProperty(Pid id, const PropertyValue& v, PropertyFlags ps)
    1479              : {
    1480            0 :     if (id == Pid::FONT_STYLE || id == Pid::FONT_FACE || id == Pid::FONT_SIZE) {
    1481            0 :         EngravingItem::undoChangeProperty(id, v, ps);
    1482            0 :     } else if (id == Pid::EXCLUDE_VERTICAL_ALIGN) {
    1483            0 :         TextBase::undoChangeProperty(id, v, ps);
    1484              : 
    1485            0 :         bool val = v.toBool();
    1486            0 :         FretDiagram* fd = getParentFretDiagram();
    1487            0 :         if (fd && fd->excludeVerticalAlign() != val) {
    1488            0 :             fd->undoChangeProperty(Pid::EXCLUDE_VERTICAL_ALIGN, val, ps);
    1489              :         }
    1490            0 :         Segment* parentSeg = getParentSeg();
    1491            0 :         if (!parentSeg) {
    1492            0 :             return;
    1493              :         }
    1494            0 :         for (EngravingItem* item : parentSeg->annotations()) {
    1495            0 :             if ((!item->isFretDiagram() && !item->isHarmony()) || item == this || track2staff(item->track()) != staffIdx()) {
    1496            0 :                 continue;
    1497              :             }
    1498              : 
    1499            0 :             if (item->excludeVerticalAlign() != val) {
    1500            0 :                 item->undoChangeProperty(Pid::EXCLUDE_VERTICAL_ALIGN, val, ps);
    1501              :             }
    1502              :         }
    1503            0 :         return;
    1504              :     }
    1505              : 
    1506            0 :     TextBase::undoChangeProperty(id, v, ps);
    1507              : }
    1508              : 
    1509              : //---------------------------------------------------------
    1510              : //   getProperty
    1511              : //---------------------------------------------------------
    1512              : 
    1513         9892 : PropertyValue Harmony::getProperty(Pid pid) const
    1514              : {
    1515         9892 :     switch (pid) {
    1516          750 :     case Pid::PLAY:
    1517          750 :         return PropertyValue(m_play);
    1518          750 :     case Pid::HARMONY_TYPE:
    1519          750 :         return PropertyValue(int(m_harmonyType));
    1520            0 :     case Pid::HARMONY_BASS_SCALE:
    1521            0 :         return m_bassScale;
    1522           25 :     case Pid::HARMONY_VOICE_LITERAL:
    1523           25 :         return m_realizedHarmony.literal();
    1524           25 :     case Pid::HARMONY_VOICING:
    1525           25 :         return int(m_realizedHarmony.voicing());
    1526            6 :     case Pid::HARMONY_DURATION:
    1527            6 :         return int(m_realizedHarmony.duration());
    1528          750 :     case Pid::HARMONY_DO_NOT_STACK_MODIFIERS:
    1529          750 :         return m_doNotStackModifiers;
    1530            0 :     case Pid::FONT_SIZE:
    1531            0 :         return m_fontSize;
    1532            0 :     case Pid::FONT_STYLE:
    1533            0 :         return static_cast<int>(m_fontStyle);
    1534            0 :     case Pid::FONT_FACE:
    1535            0 :         return m_fontFamily;
    1536         7586 :     default:
    1537         7586 :         return TextBase::getProperty(pid);
    1538              :     }
    1539              : }
    1540              : 
    1541              : //---------------------------------------------------------
    1542              : //   setProperty
    1543              : //---------------------------------------------------------
    1544              : 
    1545        27101 : bool Harmony::setProperty(Pid pid, const PropertyValue& v)
    1546              : {
    1547        27101 :     switch (pid) {
    1548            0 :     case Pid::PLAY:
    1549            0 :         m_play = v.toBool();
    1550            0 :         break;
    1551           29 :     case Pid::HARMONY_TYPE:
    1552           29 :         setHarmonyType(HarmonyType(v.toInt()));
    1553           29 :         break;
    1554         1135 :     case Pid::HARMONY_BASS_SCALE:
    1555         1135 :         setBassScale(v.toDouble());
    1556         1135 :         break;
    1557         1160 :     case Pid::HARMONY_VOICE_LITERAL:
    1558         1160 :         m_realizedHarmony.setLiteral(v.toBool());
    1559         1160 :         break;
    1560         1580 :     case Pid::HARMONY_VOICING:
    1561         1580 :         m_realizedHarmony.setVoicing(Voicing(v.toInt()));
    1562         1580 :         break;
    1563         1141 :     case Pid::HARMONY_DURATION:
    1564         1141 :         m_realizedHarmony.setDuration(HDuration(v.toInt()));
    1565         1141 :         break;
    1566            0 :     case Pid::EXCLUDE_VERTICAL_ALIGN: {
    1567            0 :         setExcludeVerticalAlign(v.toBool());
    1568            0 :         break;
    1569              :     }
    1570            0 :     case Pid::HARMONY_DO_NOT_STACK_MODIFIERS:
    1571            0 :         m_doNotStackModifiers = v.toBool();
    1572            0 :         break;
    1573            0 :     case Pid::TEXT:
    1574              :     {
    1575            0 :         String curText = xmlText();
    1576            0 :         TextBase::setProperty(pid, v);
    1577            0 :         setHarmony(v.value<String>());
    1578            0 :         String newText = xmlText();
    1579            0 :         if (newText != curText) {
    1580            0 :             FretDiagram* fretDiagram = ownershipParent()->isFretDiagram() ? toFretDiagram(ownershipParent()) : nullptr;
    1581            0 :             if (fretDiagram && !fretDiagram->isCustom(curText) && configuration()->autoUpdateFretboardDiagrams()) {
    1582            0 :                 fretDiagram->updateDiagram(plainText());
    1583              :             }
    1584            0 :             score()->rebuildFretBox();
    1585              :         }
    1586            0 :         break;
    1587            0 :     }
    1588        22056 :     default:
    1589        22056 :         return TextBase::setProperty(pid, v);
    1590              :     }
    1591         5045 :     triggerLayout();
    1592         5045 :     return true;
    1593              : }
    1594              : 
    1595              : //---------------------------------------------------------
    1596              : //   propertyDefault
    1597              : //---------------------------------------------------------
    1598              : 
    1599        10290 : PropertyValue Harmony::propertyDefault(Pid id) const
    1600              : {
    1601        10290 :     PropertyValue v;
    1602        10290 :     switch (id) {
    1603          750 :     case Pid::HARMONY_TYPE:
    1604          750 :         v = int(HarmonyType::STANDARD);
    1605          750 :         break;
    1606          750 :     case Pid::TEXT_STYLE: {
    1607          750 :         switch (m_harmonyType) {
    1608          735 :         case HarmonyType::STANDARD:
    1609          735 :             v = TextStyleType::HARMONY_A;
    1610          735 :             break;
    1611           15 :         case HarmonyType::ROMAN:
    1612           15 :             v = TextStyleType::HARMONY_ROMAN;
    1613           15 :             break;
    1614            0 :         case HarmonyType::NASHVILLE:
    1615            0 :             v = TextStyleType::HARMONY_NASHVILLE;
    1616            0 :             break;
    1617              :         }
    1618              :     }
    1619          750 :     break;
    1620            0 :     case Pid::HARMONY_BASS_SCALE:
    1621            0 :         v = style().styleV(Sid::chordBassNoteScale).toDouble();
    1622            0 :         break;
    1623          750 :     case Pid::HARMONY_DO_NOT_STACK_MODIFIERS:
    1624          750 :         return false;
    1625          750 :     case Pid::PLAY:
    1626          750 :         v = true;
    1627          750 :         break;
    1628              :     // fall-through
    1629         7290 :     default:
    1630         7290 :         v = TextBase::propertyDefault(id);
    1631         7290 :         break;
    1632              :     }
    1633         9540 :     return v;
    1634        10290 : }
    1635              : 
    1636           94 : bool Harmony::positionRelativeToNoteheadRest() const
    1637              : {
    1638           94 :     return !parent()->isFretDiagram();
    1639              : }
    1640              : 
    1641              : //---------------------------------------------------------
    1642              : //   getPropertyStyle
    1643              : //---------------------------------------------------------
    1644              : 
    1645         7926 : Sid Harmony::getPropertyStyle(Pid pid) const
    1646              : {
    1647         7926 :     if (pid == Pid::PLACEMENT) {
    1648          163 :         switch (m_harmonyType) {
    1649           97 :         case HarmonyType::STANDARD:
    1650           97 :             return Sid::harmonyPlacement;
    1651           23 :         case HarmonyType::ROMAN:
    1652           23 :             return Sid::romanNumeralPlacement;
    1653           43 :         case HarmonyType::NASHVILLE:
    1654           43 :             return Sid::nashvilleNumberPlacement;
    1655              :         }
    1656              :     }
    1657         7763 :     return TextBase::getPropertyStyle(pid);
    1658              : }
    1659              : 
    1660       134075 : double Harmony::mag() const
    1661              : {
    1662       134075 :     return EngravingItem::mag();
    1663              : }
    1664              : 
    1665           66 : HarmonyInfo::HarmonyInfo(const HarmonyInfo& h)
    1666              : {
    1667           66 :     m_id = h.m_id;
    1668           66 :     m_bassTpc = h.m_bassTpc;
    1669           66 :     m_rootTpc = h.m_rootTpc;
    1670           66 :     m_textName = h.m_textName;
    1671           66 :     m_score = h.m_score;
    1672           66 :     m_parsedChord = h.m_parsedChord ? new ParsedChord(*h.m_parsedChord) : 0;
    1673           66 : }
    1674              : 
    1675         1104 : HarmonyInfo::~HarmonyInfo()
    1676              : {
    1677         1104 :     if (m_parsedChord) {
    1678          775 :         delete m_parsedChord;
    1679              :     }
    1680         1104 : }
    1681              : }
        

Generated by: LCOV version 2.0-1