From be20438e4dd680eaaf0a4decc9729a050f05a144 Mon Sep 17 00:00:00 2001 From: Joachim Schmitz Date: Thu, 25 Jan 2024 18:24:54 +0100 Subject: [PATCH 1/6] Add containers helpers Backport of #21205, part 0 (i.e. the prerequisites) --- global/containers.h | 453 +++++++++++++++++++ importexport/musicxml/importmxml.cpp | 4 +- importexport/musicxml/importmxmlpass1.cpp | 2 + importexport/musicxml/importmxmlpass1.h | 2 + importexport/musicxml/importxmlfirstpass.cpp | 2 + 5 files changed, 461 insertions(+), 2 deletions(-) create mode 100644 global/containers.h diff --git a/global/containers.h b/global/containers.h new file mode 100644 index 0000000000000..7f96fca82bcc7 --- /dev/null +++ b/global/containers.h @@ -0,0 +1,453 @@ +/* + * SPDX-License-Identifier: GPL-3.0-only + * MuseScore-CLA-applies + * + * MuseScore + * Music Composition & Notation + * + * Copyright (C) 2021 MuseScore BVBA and others + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#ifndef MU_GLOBAL_CONTAINERS_H +#define MU_GLOBAL_CONTAINERS_H + +#include +#include +#include +#include +#include +#include +#include + +//! NOTE useful functions for containers + +namespace mu { +static constexpr size_t nidx = static_cast(-1); + +// vector +template +inline bool contains(const std::vector& vec, const T& v) +{ + return std::find(vec.cbegin(), vec.cend(), v) != vec.cend(); +} + +template +inline T value(const std::vector& vec, size_t idx) +{ + if (idx < vec.size()) { + return vec.at(idx); + } + + if /*constexpr*/ (std::is_pointer::value) { + return nullptr; + } else { + return T(); + } +} + +template +inline bool remove(std::vector& vec, const T& v) +{ + size_t origSize = vec.size(); + vec.erase(std::remove(vec.begin(), vec.end(), v), vec.end()); + return origSize != vec.size(); +} + +template +inline bool remove_if(std::vector& vec, Predicate p) +{ + size_t origSize = vec.size(); + vec.erase(std::remove_if(vec.begin(), vec.end(), p), vec.end()); + return origSize != vec.size(); +} + +template +inline void removeFirst(std::vector& vec) +{ + vec.erase(vec.begin()); +} + +template +inline T takeAt(std::vector& vec, size_t idx) +{ + T v = value(vec, idx); + vec.erase(vec.begin() + idx); + return v; +} + +template +inline T takeFirst(std::vector& vec) +{ + return takeAt(vec, 0); +} + +template +inline T takeLast(std::vector& vec) +{ + return takeAt(vec, vec.size() - 1); +} + +template +inline void swapItemsAt(std::vector& vec, size_t idx1, size_t idx2) +{ + T v1 = vec[idx1]; + vec[idx1] = vec[idx2]; + vec[idx2] = v1; +} + +template +inline bool moveItem(std::vector& vec, size_t oldIdx, size_t newIdx) +{ + if (oldIdx == mu::nidx || oldIdx == newIdx) { + return false; + } + + newIdx = std::min(vec.size() - 1, newIdx); + + if (oldIdx > newIdx) { + std::rotate(vec.rend() - oldIdx - 1, vec.rend() - oldIdx, vec.rend() - newIdx); + } else { + std::rotate(vec.begin() + oldIdx, vec.begin() + oldIdx + 1, vec.begin() + newIdx + 1); + } + + return true; +} + +template +std::vector mid(const std::vector& c, size_t pos, int alength = -1) +{ + if (c.empty()) { + return std::vector(); + } + + size_t end = 0; + if (alength < 0) { + end = c.size(); + } else { + end = pos + static_cast(alength); + } + + if (end > (c.size())) { + end = c.size(); + } + + if (end == 0) { + return std::vector(); + } + + if (pos >= end) { + return std::vector(); + } + + std::vector sub(c.begin() + pos, c.begin() + end); + return sub; +} + +template +inline void join(std::vector& l1, const std::vector& l2) +{ + l1.insert(l1.end(), l2.begin(), l2.end()); +} + +// list +template +inline bool contains(const std::list& l, const T& v) +{ + return std::find(l.cbegin(), l.cend(), v) != l.cend(); +} + +template +inline void join(std::list& l1, const std::list& l2) +{ + l1.insert(l1.end(), l2.begin(), l2.end()); +} + +template +inline bool remove(std::list& l, const T& v) +{ + if (!contains(l, v)) { + return false; + } + l.remove(v); + return true; +} + +template +inline T takeFirst(std::list& l) +{ + T v = l.front(); + l.pop_front(); + return v; +} + +template +inline T takeLast(std::list& l) +{ + T v = l.back(); + l.pop_back(); + return v; +} + +template +inline std::pair take(std::list& l, const T& v) +{ + auto it = std::find(l.begin(), l.end(), v); + if (it == l.end()) { + return std::make_pair(false, T()); + } + std::pair ret = std::make_pair(true, *it); + l.erase(it); + return ret; +} + +// =========================== +// Set +// =========================== +template +inline bool contains(const std::set& s, const T& v) +{ + return s.find(v) != s.cend(); +} + +template +inline bool contains(const std::unordered_set& s, const T& v) +{ + return s.find(v) != s.cend(); +} + +// =========================== +// General +// =========================== + +template +inline size_t indexOf(const Container& c, const T& v) +{ + auto it = std::find(c.cbegin(), c.cend(), v); + if (it != c.cend()) { + return std::distance(c.cbegin(), it); + } + return mu::nidx; +} + +template +inline bool contains(const std::map& m, const K& k) +{ + return m.find(k) != m.cend(); +} + +template +inline bool contains(const std::multimap& m, const K& k) +{ + return m.find(k) != m.cend(); +} + +template +inline bool contains(const std::unordered_map& m, const K& k) +{ + return m.find(k) != m.cend(); +} + +template +inline auto keys(const Map& m) -> std::vector +{ + std::vector result; + for (auto&& p : m) { + result.push_back(p.first); + } + return result; +} + +template +inline auto values(const Map& m) -> std::vector +{ + std::vector result; + for (auto&& p : m) { + result.push_back(p.second); + } + return result; +} + +template +inline K key(const Map& m, const V& v, const K& def) +{ + for (const auto& p : m) { + if (p.second == v) { + return p.first; + } + } + return def; +} + +template +inline auto key(const Map& m, const V& v) -> typename Map::key_type +{ + for (const auto& p : m) { + if (p.second == v) { + return p.first; + } + } + typename Map::key_type def {}; + return def; +} + +template +inline auto value(const Map& m, const typename Map::key_type& k) -> typename Map::mapped_type +{ + auto it = m.find(k); + if (it != m.end()) { + return it->second; + } + typename Map::mapped_type def {}; + return def; +} + +template +inline auto value(const Map& m, const typename Map::key_type& k, const typename Map::mapped_type& def) -> typename Map::mapped_type +{ + auto it = m.find(k); + if (it != m.end()) { + return it->second; + } + return def; +} + +template +inline bool remove(Map& c, const T& k) +{ + auto it = c.find(k); + if (it != c.end()) { + c.erase(it); + return true; + } + return false; +} + +template +inline auto take(Map& m, const K& k) -> typename Map::mapped_type +{ + auto it = m.find(k); + if (it != m.end()) { + auto v = it->second; + m.erase(it); + return v; + } + typename Map::mapped_type def {}; + return def; +} + +template +inline std::set uniqueKeys(const std::multimap& mm) +{ + std::set keys; + for (auto it = mm.begin(); it != mm.end(); ++it) { + keys.insert(it->first); + } + return keys; +} + +template +inline auto values(const std::multimap& mm, const K& key) -> std::vector::mapped_type> +{ + std::vector::mapped_type> result; + const auto range = mm.equal_range(key); + for (auto it = range.first; it != range.second; ++it) { + result.push_back(it->second); + } + return result; +} + +template +inline typename C::const_iterator findLessOrEqual(const C& c, const typename C::key_type& k) +{ + if (c.empty()) { + return c.cend(); + } + + auto it = c.upper_bound(k); + if (it == c.cbegin()) { + return c.cend(); + } + + return std::prev(it); +} + +template +inline typename C::iterator findLessOrEqual(C& c, const typename C::key_type& k) +{ + if (c.empty()) { + return c.end(); + } + + auto it = c.upper_bound(k); + if (it == c.begin()) { + return c.end(); + } + + return std::prev(it); +} + +template +inline typename C::const_iterator findLess(const C& c, const typename C::key_type& k) +{ + if (c.empty()) { + return c.cend(); + } + + auto it = c.lower_bound(k); + if (it == c.cbegin()) { + return c.cend(); + } + + return std::prev(it); +} + +template +inline typename C::iterator findLess(C& c, const typename C::key_type& k) +{ + if (c.empty()) { + return c.end(); + } + + auto it = c.lower_bound(k); + if (it == c.begin()) { + return c.end(); + } + + return std::prev(it); +} + +template +inline void DeleteAll(ForwardIterator begin, ForwardIterator end) +{ + while (begin != end) { + delete *begin; + ++begin; + } +} + +template +inline void DeleteAll(const Container& c) +{ + DeleteAll(c.begin(), c.end()); +} +} + +template +inline std::set& operator<<(std::set& s, const T& v) +{ + s.insert(v); + return s; +} + +#endif // MU_GLOBAL_CONTAINERS_H diff --git a/importexport/musicxml/importmxml.cpp b/importexport/musicxml/importmxml.cpp index 2170f7a7b34c7..b272415be19e4 100644 --- a/importexport/musicxml/importmxml.cpp +++ b/importexport/musicxml/importmxml.cpp @@ -23,13 +23,13 @@ #include "libmscore/staff.h" #include "libmscore/style.h" +#include "mscore/preferences.h" + #include "importmxml.h" #include "importmxmllogger.h" #include "importmxmlpass1.h" #include "importmxmlpass2.h" -#include "mscore/preferences.h" - namespace Ms { Score::FileError removeInstrumentNames(Score* score, MxmlLogger* logger) diff --git a/importexport/musicxml/importmxmlpass1.cpp b/importexport/musicxml/importmxmlpass1.cpp index b0ad690510e3c..1157bc7366ae4 100644 --- a/importexport/musicxml/importmxmlpass1.cpp +++ b/importexport/musicxml/importmxmlpass1.cpp @@ -17,6 +17,8 @@ // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. //============================================================================= +#include "global/containers.h" + #include "libmscore/box.h" #include "libmscore/bracketItem.h" #include "libmscore/chordrest.h" diff --git a/importexport/musicxml/importmxmlpass1.h b/importexport/musicxml/importmxmlpass1.h index 77fe25d28ad41..81498f620f9e8 100644 --- a/importexport/musicxml/importmxmlpass1.h +++ b/importexport/musicxml/importmxmlpass1.h @@ -20,6 +20,8 @@ #ifndef __IMPORTMXMLPASS1_H__ #define __IMPORTMXMLPASS1_H__ +#include "global/containers.h" + #include "libmscore/score.h" #include "importxmlfirstpass.h" #include "musicxml.h" // for the creditwords and MusicXmlPartGroupList definitions diff --git a/importexport/musicxml/importxmlfirstpass.cpp b/importexport/musicxml/importxmlfirstpass.cpp index f73f1e60c2dd1..bd5883292d50a 100644 --- a/importexport/musicxml/importxmlfirstpass.cpp +++ b/importexport/musicxml/importxmlfirstpass.cpp @@ -10,6 +10,8 @@ // the file LICENCE.GPL //============================================================================= +#include "global/containers.h" + #include "importxmlfirstpass.h" namespace Ms { From 5fe9d338c0272456f939072cce5d3f9a8391f479 Mon Sep 17 00:00:00 2001 From: Igor Korsukov Date: Fri, 26 Jan 2024 17:11:26 +0100 Subject: [PATCH 2/6] [musicxml] Replaced QList and QVector to std::vector Backport of #21205, part 1 and #21236, part 2 --- importexport/musicxml/exportxml.cpp | 6 +- importexport/musicxml/importmxmlpass1.cpp | 58 +++++------ importexport/musicxml/importmxmlpass1.h | 12 +-- importexport/musicxml/importmxmlpass2.cpp | 99 +++++++++---------- importexport/musicxml/importmxmlpass2.h | 26 +++-- importexport/musicxml/importxmlfirstpass.cpp | 10 +- importexport/musicxml/importxmlfirstpass.h | 10 +- importexport/musicxml/musicxml.h | 4 +- importexport/musicxml/musicxmlfonthandler.cpp | 2 +- importexport/musicxml/musicxmlsupport.cpp | 17 ++-- importexport/musicxml/musicxmlsupport.h | 6 +- 11 files changed, 124 insertions(+), 126 deletions(-) diff --git a/importexport/musicxml/exportxml.cpp b/importexport/musicxml/exportxml.cpp index cf3a88c30535b..28926916dd7bd 100644 --- a/importexport/musicxml/exportxml.cpp +++ b/importexport/musicxml/exportxml.cpp @@ -2835,7 +2835,7 @@ static void tremoloSingleStartStop(Chord* chord, Notations& notations, Ornaments // fermatas //--------------------------------------------------------- -static void fermatas(const QVector& cra, XmlWriter& xml, Notations& notations) +static void fermatas(const std::vector& cra, XmlWriter& xml, Notations& notations) { for (const Element* e : cra) { if (!e->isFermata() || !ExportMusicXml::canWrite(e)) @@ -3218,7 +3218,7 @@ void ExportMusicXml::chordAttributes(Chord* chord, Notations& notations, Technic TrillHash& trillStart, TrillHash& trillStop) { if (!chord->isGrace()) { - QVector fl; + std::vector fl; for (Element* e : chord->segment()->annotations()) { if (e->track() == chord->track() && e->isFermata()) fl.push_back(e); @@ -4196,7 +4196,7 @@ void ExportMusicXml::rest(Rest* rest, int staff, const std::vector* ll) writeBeam(_xml, rest, rest->beam()); Notations notations; - QVector fl; + std::vector fl; for (Element* e : rest->segment()->annotations()) { if (e->isFermata() && e->track() == rest->track()) fl.push_back(e); diff --git a/importexport/musicxml/importmxmlpass1.cpp b/importexport/musicxml/importmxmlpass1.cpp index 1157bc7366ae4..f80245f74453e 100644 --- a/importexport/musicxml/importmxmlpass1.cpp +++ b/importexport/musicxml/importmxmlpass1.cpp @@ -210,7 +210,7 @@ void MusicXMLParserPass1::addError(const QString& error) Initialize members as required for reading the MusicXML part element. TODO: factor out part reading into a separate class TODO: preferably use automatically initialized variables - Note that Qt automatically initializes new elements in QVector (tuplets). + Note that Qt automatically initializes new elements in std::vector (tuplets). */ void MusicXMLParserPass1::initPartState(const QString& /* partId */) @@ -228,19 +228,19 @@ void MusicXMLParserPass1::initPartState(const QString& /* partId */) Return false on error. */ -bool MusicXMLParserPass1::determineMeasureLength(QVector& ml) const +bool MusicXMLParserPass1::determineMeasureLength(std::vector& ml) const { ml.clear(); // determine number of measures: max number of measures in any part - int nMeasures = 0; - foreach (const MusicXmlPart &part, _parts) { + size_t nMeasures = 0; + for (const MusicXmlPart &part : _parts) { if (part.nMeasures() > nMeasures) nMeasures = part.nMeasures(); } // determine max length of a specific measure in all parts - for (int i = 0; i < nMeasures; ++i) { + for (size_t i = 0; i < nMeasures; ++i) { Fraction maxMeasDur; foreach (const MusicXmlPart &part, _parts) { if (i < part.nMeasures()) { @@ -250,7 +250,7 @@ bool MusicXMLParserPass1::determineMeasureLength(QVector& ml) const } } //qDebug("determineMeasureLength() measure %d %s (%d)", i, qPrintable(maxMeasDur.print()), maxMeasDur.ticks()); - ml.append(maxMeasDur); + ml.push_back(maxMeasDur); } return true; } @@ -438,9 +438,9 @@ int MusicXMLParserPass1::trackForPart(const QString& id) const Return the measure start time for measure \a i. */ -Fraction MusicXMLParserPass1::getMeasureStart(const int i) const +Fraction MusicXMLParserPass1::getMeasureStart(const size_t i) const { - if (0 <= i && i < _measureStart.size()) + if (i < _measureStart.size()) return _measureStart.at(i); else return Fraction(0, 0); // invalid @@ -869,7 +869,7 @@ void MusicXMLParserPass1::createDefaultHeader(Score* const score) */ void MusicXMLParserPass1::createMeasuresAndVboxes(Score* const score, - const QVector& ml, const QVector& ms, + const std::vector& ml, const std::vector& ms, const std::set& systemStartMeasureNrs, const std::set& pageStartMeasureNrs, const CreditWordsList& crWords, @@ -879,12 +879,12 @@ void MusicXMLParserPass1::createMeasuresAndVboxes(Score* const score, createDefaultHeader(score); int pageNr = 0; - for (int i = 0; i < ml.size(); ++i) { + for (size_t i = 0; i < ml.size(); ++i) { VBox* vbox = nullptr; // add a header vbox if the this measure is the first in the score or the first on a new page - if (pageStartMeasureNrs.count(i) || i == 0) { + if (pageStartMeasureNrs.count(static_cast(i)) || i == 0) { ++pageNr; if (pageNr == 1) { vbox = addCreditWords(score, crWords, pageSize, true, _exporterString.contains("sibelius")); @@ -897,19 +897,19 @@ void MusicXMLParserPass1::createMeasuresAndVboxes(Score* const score, Measure* measure = new Measure(score); measure->setTick(ms.at(i)); measure->setTicks(ml.at(i)); - measure->setNo(i); + measure->setNo(static_cast(i)); score->measures()->add(measure); // add break to previous measure or vbox MeasureBase* mb = vbox; if (!mb) mb = measure; - if (pageStartMeasureNrs.count(i)) + if (pageStartMeasureNrs.count(static_cast(i))) addBreakToPreviousMeasureBase(score, mb, LayoutBreak::Type::PAGE); - else if (systemStartMeasureNrs.count(i)) + else if (systemStartMeasureNrs.count(static_cast(i))) addBreakToPreviousMeasureBase(score, mb, LayoutBreak::Type::LINE); // add a footer vbox if the next measure is on a new page or end of score has been reached - if ((pageStartMeasureNrs.count(i + 1) || i == (ml.size() - 1)) && pageNr == 1) + if ((pageStartMeasureNrs.count(static_cast(i) + 1) || i == (ml.size() - 1)) && pageNr == 1) addCreditWords(score, crWords, pageSize, false, _exporterString.contains("sibelius")); } } @@ -924,7 +924,7 @@ void MusicXMLParserPass1::createMeasuresAndVboxes(Score* const score, or start tick measure equals start tick previous measure plus length previous measure */ -static void determineMeasureStart(const QVector& ml, QVector& ms) +static void determineMeasureStart(const std::vector& ml, std::vector& ms) { ms.resize(ml.size()); if (!(ms.size() > 0)) @@ -933,7 +933,7 @@ static void determineMeasureStart(const QVector& ml, QVector // first measure starts at t = 0 ms[0] = Fraction(0, 1); // all others start at start time previous measure plus length previous measure - for (int i = 1; i < ml.size(); i++) + for (size_t i = 1; i < ml.size(); i++) ms[i] = ms.at(i - 1) + ml.at(i - 1); //for (int i = 0; i < ms.size(); i++) // qDebug("measurestart ms[%d] %s", i + 1, qPrintable(ms.at(i).print())); @@ -984,7 +984,7 @@ static void dumpCredits(const CreditWordsList& credits) Required by TimeSigMap::tickValues(), called (indirectly) by Segment::add(). */ -static void fixupSigmap(MxmlLogger* logger, Score* score, const QVector& measureLength) +static void fixupSigmap(MxmlLogger* logger, Score* score, const std::vector& measureLength) { auto it = score->sigmap()->find(0); @@ -994,7 +994,7 @@ static void fixupSigmap(MxmlLogger* logger, Score* score, const QVectorsigmap()->add(0, tsig); } } @@ -1195,7 +1195,7 @@ void MusicXMLParserPass1::scorePartwise() // handle the implicit brackets: // multi-staff parts w/o explicit brackets get a brace - for (Part const* const p : il) { + foreach (Part const* const p, il) { if (p->nstaves() > 1 && !partSet.contains(p)) { const int column = p->staff(0)->bracketLevels() + 1; p->staff(0)->setBracketType(column, BracketType::BRACE); @@ -1503,7 +1503,7 @@ void MusicXMLParserPass1::credit(CreditWordsList& credits) // use credit-type only if exactly one was found QString crtype = (crtypes.size() == 1) ? crtypes.at(0) : QString(); CreditWords* cw = new CreditWords(page, crtype, defaultx, defaulty, fontSize, justify, halign, valign, crwords); - credits.append(cw); + credits.push_back(cw); } } @@ -2915,8 +2915,8 @@ void MusicXMLParserPass1::direction(const QString& partId, const Fraction cTime) // note: file order is direction-type first, then staff // this means staff is still unknown when direction-type is handled - QList starts; - QList stops; + std::vector starts; + std::vector stops; int staff = 0; while (_e.readNextStartElement()) { @@ -2938,7 +2938,7 @@ void MusicXMLParserPass1::direction(const QString& partId, const Fraction cTime) } // handle the stops first - foreach (auto desc, stops) { + for (const MxmlOctaveShiftDesc& desc : stops) { if (_octaveShifts.contains(desc.num)) { MxmlOctaveShiftDesc prevDesc = _octaveShifts.value(desc.num); if (prevDesc.tp == MxmlOctaveShiftDesc::Type::UP @@ -2956,7 +2956,7 @@ void MusicXMLParserPass1::direction(const QString& partId, const Fraction cTime) } // then handle the starts - foreach (auto desc, starts) { + for (const MxmlOctaveShiftDesc& desc : starts) { if (_octaveShifts.contains(desc.num)) { MxmlOctaveShiftDesc prevDesc = _octaveShifts.value(desc.num); if (prevDesc.tp == MxmlOctaveShiftDesc::Type::STOP) { @@ -2982,8 +2982,8 @@ void MusicXMLParserPass1::direction(const QString& partId, const Fraction cTime) */ void MusicXMLParserPass1::directionType(const Fraction cTime, - QList& starts, - QList& stops) + std::vector& starts, + std::vector& stops) { while (_e.readNextStartElement()) { if (_e.name() == "octave-shift") { @@ -3006,9 +3006,9 @@ void MusicXMLParserPass1::directionType(const Fraction cTime, osDesc.num = n; if (osDesc.tp == MxmlOctaveShiftDesc::Type::UP || osDesc.tp == MxmlOctaveShiftDesc::Type::DOWN) - starts.append(osDesc); + starts.push_back(osDesc); else if (osDesc.tp == MxmlOctaveShiftDesc::Type::STOP) - stops.append(osDesc); + stops.push_back(osDesc); } else { _logger->logError(QString("invalid octave-shift number %1").arg(number), &_e); diff --git a/importexport/musicxml/importmxmlpass1.h b/importexport/musicxml/importmxmlpass1.h index 81498f620f9e8..9aa5482891830 100644 --- a/importexport/musicxml/importmxmlpass1.h +++ b/importexport/musicxml/importmxmlpass1.h @@ -144,7 +144,7 @@ class MusicXMLParserPass1 { void transpose(const QString& partId, const Fraction& tick); void divisions(); void direction(const QString& partId, const Fraction cTime); - void directionType(const Fraction cTime, QList& starts, QList& stops); + void directionType(const Fraction cTime, std::vector& starts, std::vector& stops); void handleOctaveShift(const Fraction cTime, const QString& type, short size, MxmlOctaveShiftDesc& desc); void notations(MxmlStartStop& tupletStartStop); void note(const QString& partId, const Fraction cTime, Fraction& missingPrev, Fraction& dura, Fraction& missingCurr, VoiceOverlapDetector& vod, MxmlTupletStates& tupletStates); @@ -159,7 +159,7 @@ class MusicXMLParserPass1 { void pitch(int& step, float& alter, int& oct); void rest(); void skipLogCurrElem(); - bool determineMeasureLength(QVector& ml) const; + bool determineMeasureLength(std::vector& ml) const; VoiceList getVoiceList(const QString id) const; bool determineStaffMoveVoice(const QString& id, const int mxStaff, const int& mxVoice, int& msMove, int& msTrack, int& msVoice) const; @@ -172,7 +172,7 @@ class MusicXMLParserPass1 { void setDrumsetDefault(const QString& id, const QString& instrId, const NoteHead::Group hg, const int line, const Direction sd); MusicXmlInstrList getInstrList(const QString id) const; MusicXmlIntervalList getIntervals(const QString id) const; - Fraction getMeasureStart(const int i) const; + Fraction getMeasureStart(const size_t i) const; int octaveShift(const QString& id, const int staff, const Fraction f) const; const CreditWordsList& credits() const { return _credits; } bool hasBeamingInfo() const { return _hasBeamingInfo; } @@ -184,7 +184,7 @@ class MusicXMLParserPass1 { void insertSeenDenominator(int val) { _seenDenominators.emplace(val); } void createDefaultHeader(Score* const score); void createMeasuresAndVboxes(Score* const score, - const QVector& ml, const QVector& ms, + const std::vector& ml, const std::vector& ms, const std::set& systemStartMeasureNrs, const std::set& pageStartMeasureNrs, const CreditWordsList& crWords, @@ -206,8 +206,8 @@ class MusicXMLParserPass1 { QMap _parts; ///< Parts data, mapped on part id std::set _systemStartMeasureNrs; ///< Measure numbers of measures starting a page std::set _pageStartMeasureNrs; ///< Measure numbers of measures starting a page - QVector _measureLength; ///< Length of each measure - QVector _measureStart; ///< Start time of each measure + std::vector _measureLength; ///< Length of each measure + std::vector _measureStart; ///< Start time of each measure CreditWordsList _credits; ///< All credits collected PartMap _partMap; ///< TODO merge into MusicXmlPart ?? QMap _instruments; ///< instruments for each part, mapped on part id diff --git a/importexport/musicxml/importmxmlpass2.cpp b/importexport/musicxml/importmxmlpass2.cpp index efe541b220a45..2e89683f55bbb 100644 --- a/importexport/musicxml/importmxmlpass2.cpp +++ b/importexport/musicxml/importmxmlpass2.cpp @@ -170,11 +170,11 @@ static Fraction lastChordTicks(const Segment* s, const Fraction& tick, const int void MusicXmlLyricsExtend::setExtend(const int no, const int track, const Fraction& tick, const Lyrics* prevAddedLyrics = nullptr) { - QList list; + std::vector list; for (Lyrics* l : _lyrics) { - Element* const el = l->parent(); + const Element* el = l->parent(); if (el->type() == ElementType::CHORD || el->type() == ElementType::REST) { - const ChordRest* par = static_cast(el); + const ChordRest* const par = static_cast(el); // no = -1: stop all extends on this track // otherwise, stop all extends in the stave with the same no and placement if ((no == -1 && par->track() == track) @@ -186,7 +186,7 @@ void MusicXmlLyricsExtend::setExtend(const int no, const int track, const Fracti // plus all notes covered by the melisma minus the last note length l->setTicks(tick - par->tick() - lct); } - list.append(l); + list.push_back(l); } } } @@ -1608,16 +1608,16 @@ static void cleanFretDiagrams(Measure* measure) // Case 2: All the fretboards attached to first beat Segment* firstBeat = measure->first(SegmentType::ChordRest); - QList beat1FretDiagrams; + std::vector beat1FretDiagrams; int fretDiagramsTrack = -1; for (Element* e : firstBeat->annotations()) { if (e->isFretDiagram() && (fretDiagramsTrack == e->track() || fretDiagramsTrack == -1)) { - beat1FretDiagrams.append(toFretDiagram(e)); + beat1FretDiagrams.push_back(toFretDiagram(e)); fretDiagramsTrack = e->track(); } } - if (beat1FretDiagrams.length() > 1 && fretDiagramsTrack != -1) { + if (beat1FretDiagrams.size() > 1 && fretDiagramsTrack != -1) { for (FretDiagram* fd : beat1FretDiagrams) { firstBeat->remove(fd); delete fd; @@ -2222,7 +2222,7 @@ void MusicXMLParserPass2::part() #endif // read the measures - int nr = 0; // current measure sequence number (always increments by one for each measure) + size_t nr = 0; // current measure sequence number (always increments by one for each measure) _measureNumber = 0; // written measure number (doesn't always increment by 1) while (_e.readNextStartElement()) { if (_e.name() == "measure") { @@ -2451,7 +2451,7 @@ static void markUserAccidentals(const int firstStaff, if (!e || e->type() != Ms::ElementType::CHORD) continue; Chord* chord = static_cast(e); - for (Note* nt : chord->notes()) { + foreach (Note* nt, chord->notes()) { if (alterMap.contains(nt)) { int alter = alterMap.value(nt); int ln = absStep(nt->tpc(), nt->pitch()); @@ -2519,15 +2519,14 @@ static void coerceGraceCue(Chord* mainChord, Chord* graceChord) to the chord \a c grace note after list */ -static void addGraceChordsAfter(Chord* c, GraceChordList& gcl, int& gac) +static void addGraceChordsAfter(Chord* c, GraceChordList& gcl, size_t& gac) { if (!c) return; while (gac > 0) { if (gcl.size() > 0) { - Chord* graceChord = gcl.first(); - gcl.removeFirst(); + Chord* graceChord = mu::takeFirst(gcl); graceChord->toGraceAfter(); c->add(graceChord); // TODO check if same voice ? coerceGraceCue(c, graceChord); @@ -2548,7 +2547,7 @@ static void addGraceChordsAfter(Chord* c, GraceChordList& gcl, int& gac) static void addGraceChordsBefore(Chord* c, GraceChordList& gcl) { - for (int i = gcl.size() - 1; i >= 0; i--) { + for (int i = static_cast(gcl.size()) - 1; i >= 0; i--) { Chord* gc = gcl.at(i); for (Element* e : gc->el()) { if (e->isFermata()) { @@ -2646,7 +2645,7 @@ void MusicXMLParserPass2::measure(const QString& partId, Chord* prevChord = 0; // previous chord Fraction mDura; // current total measure duration GraceChordList gcl; // grace chords collected sofar - int gac = 0; // grace after count in the grace chord list + size_t gac = 0; // grace after count in the grace chord list Beams beams; // Current beam for each voice in the current part QString cv = "1"; // current voice for chords, default is 1 FiguredBassList fbl; // List of figured bass elements under a single note @@ -2669,7 +2668,7 @@ void MusicXMLParserPass2::measure(const QString& partId, else if (_e.name() == "figured-bass") { FiguredBass* fb = figuredBass(); if (fb) - fbl.append(fb); + fbl.push_back(fb); } else if (_e.name() == "harmony") harmony(partId, measure, time + mTime, delayedHarmony); @@ -3191,8 +3190,8 @@ void MusicXMLParserDirection::direction(const QString& partId, bool delayOttava = _pass1.exporterString().contains("sibelius"); _systemDirection = _e.attributes().value("system").toString() == "only-top"; //qDebug("direction track %d", track); - QList starts; - QList stops; + std::vector starts; + std::vector stops; // note: file order is direction-type first, then staff // this means staff is still unknown when direction-type is handled @@ -3527,8 +3526,8 @@ void MusicXMLParserDirection::direction(const QString& partId, Parse the /score-partwise/part/measure/direction/direction-type node. */ -void MusicXMLParserDirection::directionType(QList& starts, - QList& stops) +void MusicXMLParserDirection::directionType(std::vector& starts, + std::vector& stops) { while (_e.readNextStartElement()) { // Prevent multi-word directions from overwriting y-values. @@ -4131,13 +4130,13 @@ double MusicXMLParserDirection::convertTextToNotes() static const QRegularExpression notesRegex("(?[yxeqhwW]\\.{0,2})((?:\\s|\u00A0)*=)"); QString notesSubstring = notesRegex.match(_wordsText).captured("note"); - QList> noteSyms{{"q", QString("metNoteQuarterUp")}, // note4_Sym - {"e", QString("metNote8thUp")}, // note8_Sym - {"h", QString("metNoteHalfUp")}, // note2_Sym - {"y", QString("metNote32ndUp")}, // note32_Sym - {"x", QString("metNote16thUp")}, // note16_Sym - {"w", QString("metNoteWhole")}, - {"W", QString("metNoteDoubleWhole")}}; + std::vector> noteSyms{{"q", QString("metNoteQuarterUp")}, // note4_Sym + {"e", QString("metNote8thUp")}, // note8_Sym + {"h", QString("metNoteHalfUp")}, // note2_Sym + {"y", QString("metNote32ndUp")}, // note32_Sym + {"x", QString("metNote16thUp")}, // note16_Sym + {"w", QString("metNoteWhole")}, + {"W", QString("metNoteDoubleWhole")}}; for (auto noteSym : noteSyms) { if (notesSubstring.contains(noteSym.first)) { notesSubstring.replace(noteSym.first, noteSym.second); @@ -4162,7 +4161,7 @@ double MusicXMLParserDirection::convertTextToNotes() bool MusicXMLParserDirection::attemptTempoTextCoercion(const Fraction& tick) { - QList tempoWords{"rit", "rall", "accel", "tempo", "allegr", "poco", "molto", "più", "meno", "mosso", "rubato"}; + std::vector tempoWords{"rit", "rall", "accel", "tempo", "allegr", "poco", "molto", "più", "meno", "mosso", "rubato"}; static const QRegularExpression re("[yxeqhwW.]+(?:\\s|\u00A0)*=(?:\\s|\u00A0)*\\d+"); if (_wordsText.contains(re)) { static const QRegularExpression tempoValRegex("=(?:\\s|\u00A0)*(?\\d+)"); @@ -4346,7 +4345,7 @@ void MusicXMLParserDirection::handleChordSym(const int track, const Fraction tic */ void MusicXMLParserDirection::bracket(const QString& type, const int number, - QList& starts, QList& stops) + std::vector& starts, std::vector& stops) { QStringRef lineEnd = _e.attributes().value("line-end"); QStringRef lineType = _e.attributes().value("line-type"); @@ -4397,7 +4396,7 @@ void MusicXMLParserDirection::bracket(const QString& type, const int number, textLine->setLineColor(color); } - starts.append(MusicXmlSpannerDesc(sline, elementType, number)); + starts.push_back(MusicXmlSpannerDesc(sline, elementType, number)); } else if (type == "stop") { SLine* sline = spdesc._isStarted ? spdesc._sp : 0; @@ -4416,7 +4415,7 @@ void MusicXMLParserDirection::bracket(const QString& type, const int number, textLine->setEndHookHeight(-1 * textLine->endHookHeight()); } - stops.append(MusicXmlSpannerDesc(sline, elementType, number)); + stops.push_back(MusicXmlSpannerDesc(sline, elementType, number)); } _e.skipCurrentElement(); } @@ -4430,7 +4429,7 @@ void MusicXMLParserDirection::bracket(const QString& type, const int number, */ void MusicXMLParserDirection::dashes(const QString& type, const int number, - QList& starts, QList& stops) + std::vector& starts, std::vector& stops) { const MusicXmlExtendedSpannerDesc& spdesc = _pass2.getSpanner({ ElementType::HAIRPIN, number }); if (type == "start") { @@ -4450,11 +4449,11 @@ void MusicXMLParserDirection::dashes(const QString& type, const int number, // TODO brackets and dashes now share the same storage // because they both use ElementType::TEXTLINE // use mxml specific type instead - starts.append(MusicXmlSpannerDesc(b, ElementType::TEXTLINE, number)); + starts.push_back(MusicXmlSpannerDesc(b, ElementType::TEXTLINE, number)); } else if (type == "stop") { TextLine* b = spdesc._isStarted ? toTextLine(spdesc._sp) : new TextLine(_score); - stops.append(MusicXmlSpannerDesc(b, ElementType::TEXTLINE, number)); + stops.push_back(MusicXmlSpannerDesc(b, ElementType::TEXTLINE, number)); } _e.skipCurrentElement(); } @@ -4468,7 +4467,7 @@ void MusicXMLParserDirection::dashes(const QString& type, const int number, */ void MusicXMLParserDirection::octaveShift(const QString& type, const int number, - QList& starts, QList& stops) + std::vector& starts, std::vector& stops) { const MusicXmlExtendedSpannerDesc& spdesc = _pass2.getSpanner({ ElementType::OTTAVA, number }); if (type == "up" || type == "down") { @@ -4490,12 +4489,12 @@ void MusicXMLParserDirection::octaveShift(const QString& type, const int number, if (color.isValid()) o->setLineColor(color); - starts.append(MusicXmlSpannerDesc(o, ElementType::OTTAVA, number)); + starts.push_back(MusicXmlSpannerDesc(o, ElementType::OTTAVA, number)); } } else if (type == "stop") { Ottava* o = spdesc._isStarted ? toOttava(spdesc._sp) : new Ottava(_score); - stops.append(MusicXmlSpannerDesc(o, ElementType::OTTAVA, number)); + stops.push_back(MusicXmlSpannerDesc(o, ElementType::OTTAVA, number)); } _e.skipCurrentElement(); } @@ -4509,8 +4508,8 @@ void MusicXMLParserDirection::octaveShift(const QString& type, const int number, */ void MusicXMLParserDirection::pedal(const QString& type, const int /* number */, - QList& starts, - QList& stops) + std::vector& starts, + std::vector& stops) { const int number { 0 }; QStringRef line = _e.attributes().value("line"); @@ -4585,7 +4584,7 @@ void MusicXMLParserDirection::pedal(const QString& type, const int /* number */, if (color.isValid()/* && preferences.getBool(PREF_IMPORT_MUSICXML_IMPORTLAYOUT)*/) p->setLineColor(color); - starts.append(MusicXmlSpannerDesc(p, ElementType::PEDAL, number)); + starts.push_back(MusicXmlSpannerDesc(p, ElementType::PEDAL, number)); } else if (type == "stop" || type == "discontinue") { Pedal* p = spdesc._isStarted ? toPedal(spdesc._sp) : new Pedal(_score); @@ -4597,7 +4596,7 @@ void MusicXMLParserDirection::pedal(const QString& type, const int /* number */, p->setEndText("keyboardPedalUp"); else p->setEndHookType(type == "discontinue" ? HookType::NONE : HookType::HOOK_90); - stops.append(MusicXmlSpannerDesc(p, ElementType::PEDAL, number)); + stops.push_back(MusicXmlSpannerDesc(p, ElementType::PEDAL, number)); } else if (type == "change") { // pedal change is implemented as two separate pedals @@ -4609,7 +4608,7 @@ void MusicXMLParserDirection::pedal(const QString& type, const int /* number */, p->setLineVisible(true); else if (line == "no") p->setLineVisible(false); - stops.append(MusicXmlSpannerDesc(p, ElementType::PEDAL, number)); + stops.push_back(MusicXmlSpannerDesc(p, ElementType::PEDAL, number)); } else _logger->logError(QString("\"change\" type pedal created without existing pedal"), &_e); @@ -4628,7 +4627,7 @@ void MusicXMLParserDirection::pedal(const QString& type, const int /* number */, p->setBeginText(""); p->setContinueText(""); } - starts.append(MusicXmlSpannerDesc(p, ElementType::PEDAL, number)); + starts.push_back(MusicXmlSpannerDesc(p, ElementType::PEDAL, number)); } else if (type == "continue") { // ignore @@ -4648,7 +4647,7 @@ void MusicXMLParserDirection::pedal(const QString& type, const int /* number */, */ void MusicXMLParserDirection::wedge(const QString& type, const int number, - QList& starts, QList& stops) + std::vector& starts, std::vector& stops) { QStringRef niente = _e.attributes().value("niente"); const MusicXmlExtendedSpannerDesc& spdesc = _pass2.getSpanner({ ElementType::HAIRPIN, number }); @@ -4663,13 +4662,13 @@ void MusicXMLParserDirection::wedge(const QString& type, const int number, if (color.isValid()/* && preferences.getBool(PREF_IMPORT_MUSICXML_IMPORTLAYOUT)*/) h->setLineColor(color); - starts.append(MusicXmlSpannerDesc(h, ElementType::HAIRPIN, number)); + starts.push_back(MusicXmlSpannerDesc(h, ElementType::HAIRPIN, number)); } else if (type == "stop") { Hairpin* h = spdesc._isStarted ? toHairpin(spdesc._sp) : new Hairpin(_score); if (niente == "yes") h->setHairpinCircledTip(true); - stops.append(MusicXmlSpannerDesc(h, ElementType::HAIRPIN, number)); + stops.push_back(MusicXmlSpannerDesc(h, ElementType::HAIRPIN, number)); } _e.skipCurrentElement(); } @@ -5838,7 +5837,7 @@ static Beam::Mode computeBeamMode(const QMap& beamTypes) static void addFiguredBassElemens(FiguredBassList& fbl, const Fraction noteStartTime, const int msTrack, const Fraction dura, Measure* measure) { - if (!fbl.isEmpty()) { + if (!fbl.empty()) { Fraction sTick = noteStartTime; // starting tick for (FiguredBass* fb : fbl) { fb->setTrack(msTrack); @@ -6009,7 +6008,7 @@ Note* MusicXMLParserPass2::note(const QString& partId, Fraction& missingCurr, QString& currentVoice, GraceChordList& gcl, - int& gac, + size_t& gac, Beams& currBeams, FiguredBassList& fbl, int& alt, @@ -6234,7 +6233,7 @@ Note* MusicXMLParserPass2::note(const QString& partId, // grace note // TODO: check if explicit stem direction should also be set for grace notes // (the DOM parser does that, but seems to have no effect on the autotester) - if (!chord || gcl.isEmpty()) { + if (!chord || gcl.empty()) { c = createGraceChord(_score, msTrack + msVoice, duration, graceSlash, isSmall || cue); // TODO FIX // the setStaffMove() below results in identical behaviour as 2.0: @@ -6245,10 +6244,10 @@ Note* MusicXMLParserPass2::note(const QString& partId, // the main note, e.g. DebuMandSample.xml first grace in part 2 // c->setStaffMove(msMove); // END TODO - gcl.append(c); + gcl.push_back(c); } else - c = gcl.last(); + c = gcl.back(); } note = new Note(_score); diff --git a/importexport/musicxml/importmxmlpass2.h b/importexport/musicxml/importmxmlpass2.h index d3550a91175bf..4c26541946c0d 100644 --- a/importexport/musicxml/importmxmlpass2.h +++ b/importexport/musicxml/importmxmlpass2.h @@ -34,10 +34,8 @@ namespace Ms { // support enums / structs / classes //--------------------------------------------------------- -using GraceChordList = QList; -using FiguredBassList = QVector; -// typedef QList GraceChordList; -// typedef QVector FiguredBassList; +using GraceChordList = std::vector; +using FiguredBassList = std::vector; using Tuplets = std::map; using Beams = QMap; @@ -193,7 +191,7 @@ class MxmlLogger; class MusicXMLDelayedDirectionElement; class MusicXMLInferredFingering; -using InferredFingeringsList = QList; +using InferredFingeringsList = std::vector; using SlurStack = std::array; using TrillStack = std::array; using BracketsStack = std::array; @@ -207,7 +205,7 @@ using SpannerSet = std::set; // DelayedDirectionsList //--------------------------------------------------------- -class DelayedDirectionsList : public QList { +class DelayedDirectionsList : public std::vector { public: void combineTempoText(); }; @@ -314,7 +312,7 @@ class MusicXMLParserPass2 { void divisions(); void transpose(const QString& partId, const Fraction& tick); Note* note(const QString& partId, Measure* measure, const Fraction sTime, const Fraction prevTime, Fraction& missingPrev, - Fraction& dura, Fraction& missingCurr, QString& currentVoice, GraceChordList& gcl, int& gac, Beams& currBeams, + Fraction& dura, Fraction& missingCurr, QString& currentVoice, GraceChordList& gcl, size_t& gac, Beams& currBeams, FiguredBassList& fbl, int& alt, MxmlTupletStates& tupletStates, Tuplets& tuplets); void notePrintSpacingNo(Fraction& dura); FiguredBassItem* figure(const int idx, const bool paren); @@ -428,15 +426,15 @@ class MusicXMLParserDirection { double _tpoSound; // tempo according to sound bool _systemDirection = false; bool _visible = true; - QList _elems; + std::vector _elems; Fraction _offset; - void directionType(QList& starts, QList& stops); - void bracket(const QString& type, const int number, QList& starts, QList& stops); - void octaveShift(const QString& type, const int number, QList& starts, QList& stops); - void pedal(const QString& type, const int number, QList& starts, QList& stops); - void dashes(const QString& type, const int number, QList& starts, QList& stops); - void wedge(const QString& type, const int number, QList& starts, QList& stops); + void directionType(std::vector& starts, std::vector& stops); + void bracket(const QString& type, const int number, std::vector& starts, std::vector& stops); + void octaveShift(const QString& type, const int number, std::vector& starts, std::vector& stops); + void pedal(const QString& type, const int number, std::vector& starts, std::vector& stops); + void dashes(const QString& type, const int number, std::vector& starts, std::vector& stops); + void wedge(const QString& type, const int number, std::vector& starts, std::vector& stops); QString metronome(double& r); void sound(); void dynamics(); diff --git a/importexport/musicxml/importxmlfirstpass.cpp b/importexport/musicxml/importxmlfirstpass.cpp index bd5883292d50a..d117078152f98 100644 --- a/importexport/musicxml/importxmlfirstpass.cpp +++ b/importexport/musicxml/importxmlfirstpass.cpp @@ -37,8 +37,8 @@ MusicXmlPart::MusicXmlPart(QString id, QString name) void MusicXmlPart::addMeasureNumberAndDuration(QString measureNumber, Fraction measureDuration) { - measureNumbers.append(measureNumber); - measureDurations.append(measureDuration); + measureNumbers.push_back(measureNumber); + measureDurations.push_back(measureDuration); } void MusicXmlPart::setMaxStaff(const int staff) @@ -47,9 +47,9 @@ void MusicXmlPart::setMaxStaff(const int staff) _maxStaff = staff; } -Fraction MusicXmlPart::measureDuration(int i) const +Fraction MusicXmlPart::measureDuration(size_t i) const { - if (i >= 0 && i < measureDurations.size()) + if (i < measureDurations.size()) return measureDurations.at(i); return Fraction(0, 0); // return invalid fraction } @@ -64,7 +64,7 @@ QString MusicXmlPart::toString() const .arg(QString(i.key() + 1), i.value().toString()); } - for (int i = 0; i < measureNumbers.size(); ++i) { + for (size_t i = 0; i < measureNumbers.size(); ++i) { if (i > 0) res += "\n"; res += QString("measure %1 duration %2 (%3)") diff --git a/importexport/musicxml/importxmlfirstpass.h b/importexport/musicxml/importxmlfirstpass.h index 2acc4a41d9676..f7f14da880d1f 100644 --- a/importexport/musicxml/importxmlfirstpass.h +++ b/importexport/musicxml/importxmlfirstpass.h @@ -61,8 +61,8 @@ class MusicXmlPart { QString getId() const { return id; } QString toString() const; VoiceList voicelist; // the voice map information TODO: make private - Fraction measureDuration(int i) const; - int nMeasures() const { return measureDurations.size(); } + Fraction measureDuration(size_t i) const; + size_t nMeasures() const { return measureDurations.size(); } MusicXmlInstrList _instrList; // TODO: make private MusicXmlIntervalList _intervals; ///< Transpositions Interval _inferredTranspose; @@ -96,9 +96,9 @@ class MusicXmlPart { QString abbr; bool _printAbbr = false; bool _hasTab = false; - QStringList measureNumbers; // MusicXML measure number attribute - QList measureDurations; // duration in fraction for every measure - QVector octaveShifts; // octave shift list for every staff + std::vector measureNumbers; // MusicXML measure number attribute + std::vector measureDurations; // duration in fraction for every measure + std::vector octaveShifts; // octave shift list for every staff LyricNumberHandler _lyricNumberHandler; int _maxStaff = -1; // maximum staff value found (0 based), -1 = none bool _hasLyrics = false; diff --git a/importexport/musicxml/musicxml.h b/importexport/musicxml/musicxml.h index df27b1df21795..768c26f8b0ef7 100644 --- a/importexport/musicxml/musicxml.h +++ b/importexport/musicxml/musicxml.h @@ -75,7 +75,7 @@ struct CreditWords { } }; -typedef QList CreditWordsList; +typedef std::vector CreditWordsList; typedef CreditWordsList::iterator iCreditWords; typedef CreditWordsList::const_iterator ciCreditWords; @@ -97,7 +97,7 @@ class JumpMarkerDesc { Measure* meas() const { return _meas; } }; -typedef QList JumpMarkerDescList; +typedef std::vector JumpMarkerDescList; //--------------------------------------------------------- // SlurDesc diff --git a/importexport/musicxml/musicxmlfonthandler.cpp b/importexport/musicxml/musicxmlfonthandler.cpp index 7e246de7fa760..4d88d3dcd60a8 100644 --- a/importexport/musicxml/musicxmlfonthandler.cpp +++ b/importexport/musicxml/musicxmlfonthandler.cpp @@ -98,7 +98,7 @@ QString MScoreTextToMXML::toPlainText(const QString& text) { QString res; bool inElem = false; - foreach(QChar ch, text) { + for (QChar ch : text) { if (ch == '<') inElem = true; else if (ch == '>') diff --git a/importexport/musicxml/musicxmlsupport.cpp b/importexport/musicxml/musicxmlsupport.cpp index e18501b1252e3..89d3e0442caf9 100644 --- a/importexport/musicxml/musicxmlsupport.cpp +++ b/importexport/musicxml/musicxmlsupport.cpp @@ -80,14 +80,15 @@ const static QMap smuflAccidentalTypes { NoteList::NoteList() { - for (int i = 0; i < MAX_VOICE_DESC_STAVES; ++i) - _staffNoteLists << StartStopList(); + _staffNoteLists.reserve(MAX_VOICE_DESC_STAVES); + for (size_t i = 0; i < MAX_VOICE_DESC_STAVES; ++i) + _staffNoteLists.push_back(StartStopList()); } -void NoteList::addNote(const int startTick, const int endTick, const int staff) +void NoteList::addNote(const int startTick, const int endTick, const size_t staff) { - if (staff >= 0 && staff < _staffNoteLists.size()) - _staffNoteLists[staff] << StartStop(startTick, endTick); + if (staff < _staffNoteLists.size()) + _staffNoteLists[staff].push_back(StartStop(startTick, endTick)); } void NoteList::dump(const int& voice) const @@ -95,7 +96,7 @@ void NoteList::dump(const int& voice) const // dump contents for (int i = 0; i < MAX_VOICE_DESC_STAVES; ++i) { printf("voice %d staff %d:", voice, i); - for (int j = 0; j < _staffNoteLists.at(i).size(); ++j) + for (size_t j = 0; j < _staffNoteLists.at(i).size(); ++j) printf(" %d-%d", _staffNoteLists.at(i).at(j).first, _staffNoteLists.at(i).at(j).second); printf("\n"); } @@ -125,8 +126,8 @@ static bool notesOverlap(const StartStop& n1, const StartStop& n2) bool NoteList::stavesOverlap(const int staff1, const int staff2) const { - for (int i = 0; i < _staffNoteLists.at(staff1).size(); ++i) - for (int j = 0; j < _staffNoteLists.at(staff2).size(); ++j) + for (size_t i = 0; i < _staffNoteLists.at(staff1).size(); ++i) + for (size_t j = 0; j < _staffNoteLists.at(staff2).size(); ++j) if (notesOverlap(_staffNoteLists.at(staff1).at(i), _staffNoteLists.at(staff2).at(j))) { //printf(" %d-%d", staff1, staff2); return true; diff --git a/importexport/musicxml/musicxmlsupport.h b/importexport/musicxml/musicxmlsupport.h index 7699ab7dd34fa..cd4d56aab9b61 100644 --- a/importexport/musicxml/musicxmlsupport.h +++ b/importexport/musicxml/musicxmlsupport.h @@ -38,7 +38,7 @@ namespace Ms { */ typedef QPair StartStop; -typedef QList StartStopList; +typedef std::vector StartStopList; //--------------------------------------------------------- // NoteList @@ -51,12 +51,12 @@ typedef QList StartStopList; class NoteList { public: NoteList(); - void addNote(const int startTick, const int endTick, const int staff); + void addNote(const int startTick, const int endTick, const size_t staff); void dump(const int& voice) const; bool stavesOverlap(const int staff1, const int staff2) const; bool anyStaffOverlaps() const; private: - QList _staffNoteLists; ///< The note start/stop times in all staves + std::vector _staffNoteLists; ///< The note start/stop times in all staves }; struct HarmonyDesc From 54accb010d3d9af721764f28c8790365a17b7bea Mon Sep 17 00:00:00 2001 From: Igor Korsukov Date: Thu, 25 Jan 2024 15:30:41 +0100 Subject: [PATCH 3/6] [musicxml] Replaced QMap to std::map Backport of #21205, part 2 --- importexport/musicxml/exportxml.cpp | 75 ++--- importexport/musicxml/importmxmlpass1.cpp | 162 +++++------ importexport/musicxml/importmxmlpass1.h | 22 +- importexport/musicxml/importmxmlpass2.cpp | 279 +++++++++---------- importexport/musicxml/importmxmlpass2.h | 8 +- importexport/musicxml/importxmlfirstpass.cpp | 11 +- importexport/musicxml/importxmlfirstpass.h | 8 +- importexport/musicxml/musicxml.h | 2 +- importexport/musicxml/musicxmlsupport.cpp | 245 ++++++++-------- importexport/musicxml/musicxmlsupport.h | 7 +- 10 files changed, 411 insertions(+), 408 deletions(-) diff --git a/importexport/musicxml/exportxml.cpp b/importexport/musicxml/exportxml.cpp index 28926916dd7bd..af51a198df490 100644 --- a/importexport/musicxml/exportxml.cpp +++ b/importexport/musicxml/exportxml.cpp @@ -38,6 +38,8 @@ #include "config.h" +#include "global/containers.h" + #include "libmscore/accidental.h" #include "libmscore/arpeggio.h" #include "libmscore/articulation.h" @@ -130,7 +132,7 @@ namespace Ms { // typedefs //--------------------------------------------------------- -typedef QMap FigBassMap; +typedef std::map FigBassMap; //--------------------------------------------------------- // attributes -- prints tag when necessary @@ -313,7 +315,7 @@ struct MeasurePrintContext final //--------------------------------------------------------- typedef QHash TrillHash; -typedef QMap MxmlInstrumentMap; +typedef std::map MxmlInstrumentMap; class ExportMusicXml { Score* _score; @@ -2306,12 +2308,12 @@ void ExportMusicXml::keysig(const KeySig* ks, ClefType ct, int staff, bool visib // are in insertion order -> sorting required // first put the KeySyms in a map - QMap map; + std::map map; for (const KeySym& ksym : keysyms) { - map.insert(ksym.spos.x(), ksym); + map.insert({ ksym.spos.x(), ksym}); } // then write them (automatically sorted on key) - for (const KeySym& ksym : map) { + for (const KeySym& ksym : mu::values(map)) { int line = static_cast(round(2 * ksym.spos.y())); int step = (po - line) % 7; _xml.tag("key-step", QString(QChar(table2[step]))); @@ -3891,7 +3893,7 @@ void ExportMusicXml::chord(Chord* chord, int staff, const std::vector* { Part* part = chord->score()->staff(chord->track() / VOICES)->part(); int partNr = _score->parts().indexOf(part); - int instNr = instrMap.value(part->instrument(_tick), -1); + int instNr = mu::value(instrMap, part->instrument(_tick), -1); /* qDebug("chord() %p parent %p isgrace %d #gracenotes %d graceidx %d", chord, chord->parent(), chord->isGrace(), chord->graceNotes().size(), chord->graceIndex()); @@ -5971,10 +5973,10 @@ static void figuredBass(XmlWriter& xml, int strack, int etrack, int track, const if (extend) { //qDebug("figuredbass() extend to %d + %d = %d", // cr->tick(), fb->ticks(), cr->tick() + fb->ticks()); - fbMap.insert(strack, fb); + fbMap.insert({ strack, fb }); } else - fbMap.remove(strack); + mu::remove(fbMap, strack); const Fraction crEndTick = cr->tick() + cr->actualTicks(); const Fraction fbEndTick = fb->segment()->tick() + fb->ticks(); const bool writeDuration = fb->ticks() < cr->actualTicks(); @@ -5995,8 +5997,8 @@ static void figuredBass(XmlWriter& xml, int strack, int etrack, int track, const } } // check for extend pending - if (fbMap.contains(strack)) { - const FiguredBass* fb = fbMap.value(strack); + if (mu::contains(fbMap, strack)) { + const FiguredBass* fb = fbMap.at(strack); Fraction crEndTick = cr->tick() + cr->actualTicks(); Fraction fbEndTick = fb->segment()->tick() + fb->ticks(); bool writeDuration = fb->ticks() < cr->actualTicks(); @@ -6006,7 +6008,7 @@ static void figuredBass(XmlWriter& xml, int strack, int etrack, int track, const } if (fbEndTick <= crEndTick) { //qDebug("figuredbass() at tick %d extend done", cr->tick() + cr->actualTicks()); - fbMap.remove(strack); + mu::remove(fbMap, strack); } } } @@ -6140,7 +6142,7 @@ void ExportMusicXml::keysigTimesig(const Measure* m, const Part* p) //qDebug("keysigTimesig m %p strack %d etrack %d", m, strack, etrack); // search all staves for non-generated key signatures - QMap keysigs; // map staff to key signature + std::map keysigs; // map staff to key signature for (Segment* seg = m->first(); seg; seg = seg->next()) { if (seg->tick() > m->tick()) break; @@ -6160,31 +6162,31 @@ void ExportMusicXml::keysigTimesig(const Measure* m, const Part* p) //ClefType ct = rest->staff()->clef(rest->tick()); // write the key signatues - if (!keysigs.isEmpty()) { + if (!keysigs.empty()) { // determine if all staves have a keysig and all keysigs are identical // in that case a single is written, without number=... attribute int nstaves = p->nstaves(); bool singleKey = true; // check if all staves have a keysig for (int i = 0; i < nstaves; i++) - if (!keysigs.contains(i)) + if (!mu::contains(keysigs, i)) singleKey = false; // check if all keysigs are identical if (singleKey) for (int i = 1; i < nstaves; i++) - if (!(keysigs.value(i)->key() == keysigs.value(0)->key())) + if (!(keysigs.at(i)->key() == keysigs.at(0)->key())) singleKey = false; // write the keysigs //qDebug(" singleKey %d", singleKey); if (singleKey) { // keysig applies to all staves - keysig(keysigs.value(0), p->staff(0)->clef(m->tick()), 0, keysigs.value(0)->visible()); + keysig(keysigs.at(0), p->staff(0)->clef(m->tick()), 0, keysigs.at(0)->visible()); } else { // staff-specific keysigs - for (int st : keysigs.keys()) - keysig(keysigs.value(st), p->staff(st)->clef(m->tick()), st + 1, keysigs.value(st)->visible()); + for (int st : mu::keys(keysigs)) + keysig(keysigs.at(st), p->staff(st)->clef(m->tick()), st + 1, keysigs.at(st)->visible()); } } else { @@ -6200,7 +6202,7 @@ void ExportMusicXml::keysigTimesig(const Measure* m, const Part* p) } // search all staves for non-generated time signatures - QMap timesigs; // map staff to time signature + std::map timesigs; // map staff to time signature for (Segment* seg = m->first(); seg; seg = seg->next()) { if (seg->tick() > m->tick()) break; @@ -6226,7 +6228,7 @@ void ExportMusicXml::keysigTimesig(const Measure* m, const Part* p) bool singleTime = true; // check if all staves have a keysig for (size_t i = 0; i < nstaves; i++) { - if (!timesigs.contains(static_cast(i))) + if (!mu::contains(timesigs, static_cast(i))) singleTime = false; } // check if all timesigs are identical @@ -6245,7 +6247,7 @@ void ExportMusicXml::keysigTimesig(const Measure* m, const Part* p) } else { // staff-specific timesig - for (int st : timesigs.keys()) + for (int st : mu::keys(timesigs)) timesig(timesigs[st], st + 1); } } @@ -6368,8 +6370,8 @@ static void initInstrMap(MxmlInstrumentMap& im, const InstrumentList* il, const im.clear(); for (auto i = il->begin(); i != il->end(); ++i) { const Instrument* pinstr = i->second; - if (!im.contains(pinstr)) - im.insert(pinstr, im.size()); + if (!mu::contains(im, pinstr)) + im.insert({ pinstr, static_cast(im.size()) }); } } @@ -6377,7 +6379,7 @@ static void initInstrMap(MxmlInstrumentMap& im, const InstrumentList* il, const // initReverseInstrMap //--------------------------------------------------------- -typedef QMap MxmlReverseInstrumentMap; +typedef std::map MxmlReverseInstrumentMap; /** Initialize the number t Instrument* map for a Part @@ -6387,9 +6389,9 @@ typedef QMap MxmlReverseInstrumentMap; static void initReverseInstrMap(MxmlReverseInstrumentMap& rim, const MxmlInstrumentMap& im) { rim.clear(); - for (const Instrument* i : im.keys()) { - int instNr = im.value(i); - rim.insert(instNr, i); + for (const Instrument* i : mu::keys(im)) { + int instNr = im.at(i); + rim.insert({ instNr, i }); } } @@ -6839,19 +6841,22 @@ static void partList(XmlWriter& xml, Score* score, MxmlInstrumentMap& instrMap) else { MxmlReverseInstrumentMap rim; initReverseInstrMap(rim, instrMap); - for (int instNr : rim.keys()) { - scoreInstrument(xml, idx + 1, instNr + 1, MScoreTextToMXML::toPlainText(rim.value(instNr)->trackName()), rim.value(instNr)); + for (int instNr : mu::keys(rim)) { + const Instrument* instr = rim.at(instNr); + scoreInstrument(xml, idx + 1, instNr + 1, + MScoreTextToMXML::toPlainText(instr->trackName()), + instr); } - for (auto ii = rim.constBegin(); ii != rim.constEnd(); ii++) { - int instNr = ii.key(); + for (auto ii = rim.cbegin(); ii != rim.cend(); ii++) { + int instNr = ii->first; int midiPort = part->midiPort() + 1; - if (ii.value()->channel().size() > 0) - midiPort = score->masterScore()->midiMapping(ii.value()->channel(0)->channel())->port() + 1; + if (ii->second->channel().size() > 0) + midiPort = score->masterScore()->midiMapping(ii->second->channel(0)->channel())->port() + 1; if (midiPort >= 1 && midiPort <= 16) xml.tag(QString("midi-device %1 port=\"%2\"").arg(instrId(idx+1, instNr + 1)).arg(midiPort), ""); else xml.tag(QString("midi-device %1").arg(instrId(idx+1, instNr + 1)), ""); - midiInstrument(xml, idx + 1, instNr + 1, rim.value(instNr), score); + midiInstrument(xml, idx + 1, instNr + 1, rim.at(instNr), score); } } @@ -7391,7 +7396,7 @@ void ExportMusicXml::writeMeasure(const Measure* const m, if (staves > 1) _xml.tag("staves", staves); if (instrMap.size() > 1) - _xml.tag("instruments", instrMap.size()); + _xml.tag("instruments", static_cast(instrMap.size())); } // make sure clefs at end of measure get exported at start of next measure diff --git a/importexport/musicxml/importmxmlpass1.cpp b/importexport/musicxml/importmxmlpass1.cpp index f80245f74453e..46d983b104956 100644 --- a/importexport/musicxml/importmxmlpass1.cpp +++ b/importexport/musicxml/importmxmlpass1.cpp @@ -71,18 +71,18 @@ static void allocateStaves(VoiceList& vcLst) // handle regular (non-overlapping) voices // note: outer loop executed vcLst.size() times, as each inner loop handles exactly one item - for (int i = 0; i < vcLst.size(); ++i) { + for (size_t i = 0; i < vcLst.size(); ++i) { // find the regular voice containing the highest number of chords and rests that has not been handled yet int max = 0; int key = -1; - for (VoiceList::const_iterator j = vcLst.constBegin(); j != vcLst.constEnd(); ++j) { - if (!j.value().overlaps() && j.value().numberChordRests() > max && j.value().staff() == -1) { - max = j.value().numberChordRests(); - key = j.key(); + for (VoiceList::const_iterator j = vcLst.cbegin(); j != vcLst.cend(); ++j) { + if (!j->second.overlaps() && j->second.numberChordRests() > max && j->second.staff() == -1) { + max = j->second.numberChordRests(); + key = j->first; } } if (key > 0) { - int prefSt = vcLst.value(key).preferredStaff(); + int prefSt = mu::value(vcLst, key).preferredStaff(); if (voicesAllocated[prefSt] < VOICES) { vcLst[key].setStaff(prefSt); voicesAllocated[prefSt]++; @@ -98,14 +98,14 @@ static void allocateStaves(VoiceList& vcLst) // the ones with the highest number of chords and rests get allocated first for (int h = 0; h < MAX_VOICE_DESC_STAVES; ++h) { // note: middle loop executed vcLst.size() times, as each inner loop handles exactly one item - for (int i = 0; i < vcLst.size(); ++i) { + for (size_t i = 0; i < vcLst.size(); ++i) { // find the overlapping voice containing the highest number of chords and rests that has not been handled yet int max = 0; int key = -1; - for (VoiceList::const_iterator j = vcLst.constBegin(); j != vcLst.constEnd(); ++j) { - if (j.value().overlaps() && j.value().numberChordRests(h) > max && j.value().staffAlloc(h) == -1) { - max = j.value().numberChordRests(h); - key = j.key(); + for (VoiceList::const_iterator j = vcLst.cbegin(); j != vcLst.cend(); ++j) { + if (j->second.overlaps() && j->second.numberChordRests(h) > max && j->second.staffAlloc(h) == -1) { + max = j->second.numberChordRests(h); + key = j->first;; } } if (key > 0) { @@ -139,9 +139,9 @@ static void allocateVoices(VoiceList& vcLst) nextVoice[i] = 0; // handle regular (non-overlapping) voices // a voice is allocated on one specific staff - for (VoiceList::const_iterator i = vcLst.constBegin(); i != vcLst.constEnd(); ++i) { - int staff = i.value().staff(); - int key = i.key(); + for (VoiceList::const_iterator i = vcLst.cbegin(); i != vcLst.cend(); ++i) { + int staff = i->second.staff(); + int key = i->first; if (staff >= 0) { vcLst[key].setVoice(nextVoice[staff]); nextVoice[staff]++; @@ -149,10 +149,10 @@ static void allocateVoices(VoiceList& vcLst) } // handle overlapping voices // each voice may be in every staff - for (VoiceList::const_iterator i = vcLst.constBegin(); i != vcLst.constEnd(); ++i) { + for (VoiceList::const_iterator i = vcLst.cbegin(); i != vcLst.cend(); ++i) { for (int j = 0; j < MAX_VOICE_DESC_STAVES; ++j) { - int staffAlloc = i.value().staffAlloc(j); - int key = i.key(); + int staffAlloc = i->second.staffAlloc(j); + int key = i->first; if (staffAlloc >= 0) { vcLst[key].setVoice(j, nextVoice[j]); nextVoice[j]++; @@ -172,8 +172,8 @@ static void allocateVoices(VoiceList& vcLst) static void copyOverlapData(VoiceOverlapDetector& vod, VoiceList& vcLst) { - for (VoiceList::const_iterator i = vcLst.constBegin(); i != vcLst.constEnd(); ++i) { - int key = i.key(); + for (VoiceList::const_iterator i = vcLst.cbegin(); i != vcLst.cend(); ++i) { + int key = i->first; if (vod.stavesOverlap(key)) vcLst[key].setOverlap(true); } @@ -234,7 +234,7 @@ bool MusicXMLParserPass1::determineMeasureLength(std::vector& ml) cons // determine number of measures: max number of measures in any part size_t nMeasures = 0; - for (const MusicXmlPart &part : _parts) { + for (const MusicXmlPart &part : mu::values(_parts)) { if (part.nMeasures() > nMeasures) nMeasures = part.nMeasures(); } @@ -242,7 +242,7 @@ bool MusicXMLParserPass1::determineMeasureLength(std::vector& ml) cons // determine max length of a specific measure in all parts for (size_t i = 0; i < nMeasures; ++i) { Fraction maxMeasDur; - foreach (const MusicXmlPart &part, _parts) { + for (const MusicXmlPart &part : mu::values(_parts)) { if (i < part.nMeasures()) { Fraction measDurPartJ = part.measureDuration(i); if (measDurPartJ > maxMeasDur) @@ -266,8 +266,8 @@ bool MusicXMLParserPass1::determineMeasureLength(std::vector& ml) cons VoiceList MusicXMLParserPass1::getVoiceList(const QString id) const { - if (_parts.contains(id)) - return _parts.value(id).voicelist; + if (mu::contains(_parts, id)) + return _parts.at(id).voicelist; return VoiceList(); } @@ -282,8 +282,8 @@ VoiceList MusicXMLParserPass1::getVoiceList(const QString id) const MusicXmlInstrList MusicXMLParserPass1::getInstrList(const QString id) const { - if (_parts.contains(id)) - return _parts.value(id)._instrList; + if (mu::contains(_parts, id)) + return _parts.at(id)._instrList; return MusicXmlInstrList(); } @@ -298,8 +298,8 @@ MusicXmlInstrList MusicXMLParserPass1::getInstrList(const QString id) const MusicXmlIntervalList MusicXMLParserPass1::getIntervals(const QString id) const { - if (_parts.contains(id)) - return _parts.value(id)._intervals; + if (mu::contains(_parts, id)) + return _parts.at(id)._intervals; return MusicXmlIntervalList(); } @@ -319,8 +319,8 @@ void MusicXMLParserPass1::setDrumsetDefault(const QString& id, const int line, const Direction sd) { - if (_instruments.contains(id) - && _instruments[id].contains(instrId)) { + if (mu::contains(_instruments, id) + && mu::contains(_instruments.at(id), instrId)) { _instruments[id][instrId].notehead = hg; _instruments[id][instrId].line = line; _instruments[id][instrId].stemDirection = sd; @@ -362,17 +362,17 @@ bool MusicXMLParserPass1::determineStaffMoveVoice(const QString& id, const int m //qDebug("voice mapper before: voice='%s' staff=%d", qPrintable(mxVoice), mxStaff); int s; // staff mapped by voice mapper int v; // voice mapped by voice mapper - if (voicelist.value(mxVoice).overlaps()) { + if (mu::value(voicelist, mxVoice).overlaps()) { // for overlapping voices, the staff does not change // and the voice is mapped and staff-dependent s = mxStaff; - v = voicelist.value(mxVoice).voice(s); + v = mu::value(voicelist, mxVoice).voice(s); } else { // for non-overlapping voices, both staff and voice are // set by the voice mapper - s = voicelist.value(mxVoice).staff(); - v = voicelist.value(mxVoice).voice(); + s = mu::value(voicelist, mxVoice).staff(); + v = mu::value(voicelist, mxVoice).voice(); } //qDebug("voice mapper mapped: s=%d v=%d", s, v); @@ -386,7 +386,7 @@ bool MusicXMLParserPass1::determineStaffMoveVoice(const QString& id, const int m msVoice = v; // make score-relative instead on part-relative - Part* part = _partMap.value(id); + Part* part = mu::value(_partMap, id); if (!part) return false; int scoreRelStaff = _score->staffIdx(part); // zero-based number of parts first staff in the score @@ -410,7 +410,7 @@ bool MusicXMLParserPass1::determineStaffMoveVoice(const QString& id, const int m bool MusicXMLParserPass1::hasPart(const QString& id) const { - return _parts.contains(id); + return mu::contains(_parts, id); } //--------------------------------------------------------- @@ -423,7 +423,7 @@ bool MusicXMLParserPass1::hasPart(const QString& id) const int MusicXMLParserPass1::trackForPart(const QString& id) const { - Part* part = _partMap.value(id); + Part* part = mu::value(_partMap, id); if (!part) return -1; int scoreRelStaff = _score->staffIdx(part); // zero-based number of parts first staff in the score @@ -456,8 +456,8 @@ Fraction MusicXMLParserPass1::getMeasureStart(const size_t i) const int MusicXMLParserPass1::octaveShift(const QString& id, const int staff, const Fraction f) const { - if (_parts.contains(id)) - return _parts.value(id).octaveShift(staff, f); + if (mu::contains(_parts, id)) + return _parts.at(id).octaveShift(staff, f); return 0; } @@ -1290,7 +1290,7 @@ static QString text2syms(const QString& t) // caching does not gain much ScoreFont* sf = ScoreFont::fallbackFont(); - QMap map; + std::map map; int maxStringSize = 0; // maximum string size found for (int i = int(SymId::noSym); i < int(SymId::lastSym); ++i) { @@ -1298,7 +1298,7 @@ static QString text2syms(const QString& t) QString string(sf->toString(id)); // insert all syms except space to prevent matching all regular spaces if (id != SymId::space) - map.insert(string, id); + map.insert({ string, id }); if (string.size() > maxStringSize) maxStringSize = string.size(); } @@ -1315,8 +1315,8 @@ static QString text2syms(const QString& t) QString sym; while (maxMatch > 0) { QString toBeMatched = in.left(maxMatch); - if (map.contains(toBeMatched)) { - sym = Sym::id2name(map.value(toBeMatched)); + if (mu::contains(map, toBeMatched)) { + sym = Sym::id2name(map.at(toBeMatched)); break; } maxMatch--; @@ -1943,7 +1943,7 @@ void MusicXMLParserPass1::partList(MusicXmlPartGroupList& partGroupList) static void createPart(Score* score, const QString& id, PartMap& pm) { Part* part = new Part(score); - pm.insert(id, part); + pm.insert({ id, part }); part->setId(id); score->appendPart(part); Staff* staff = new Staff(score); @@ -2129,14 +2129,14 @@ void MusicXMLParserPass1::scorePart() _logger->logDebugTrace("MusicXMLParserPass1::scorePart", &_e); QString id = _e.attributes().value("id").toString().trimmed(); - if (_parts.contains(id)) { + if (mu::contains(_parts, id)) { _logger->logError(QString("duplicate part id '%1'").arg(id), &_e); skipLogCurrElem(); return; } else { - _parts.insert(id, MusicXmlPart(id)); - _instruments.insert(id, MusicXMLInstruments()); + _parts.insert({ id, MusicXmlPart(id) }); + _instruments.insert({ id, MusicXMLInstruments() }); createPart(_score, id, _partMap); } @@ -2202,9 +2202,9 @@ void MusicXMLParserPass1::scorePart() // score-instrument elements in the score-part if (instrId.isEmpty()) { for (auto it = _instruments[id].cbegin(); it != _instruments[id].cend(); ++it) - _instruments[id][it.key()].midiPort = port.toInt() - 1; + _instruments[id][it->first].midiPort = port.toInt() - 1; } - else if (_instruments[id].contains(instrId)) + else if (mu::contains(_instruments.at(id), instrId)) _instruments[id][instrId].midiPort = port.toInt() - 1; _e.readElementText(); // empty string @@ -2241,32 +2241,32 @@ void MusicXMLParserPass1::scoreInstrument(const QString& partId) qPrintable(instrName) ); */ - _instruments[partId].insert(instrId, MusicXMLInstrument(instrName)); + _instruments[partId].insert({ instrId, MusicXMLInstrument(instrName) }); // Element instrument-name is typically not displayed in the score, // but used only internally - if (_instruments[partId].contains(instrId)) + if (mu::contains(_instruments.at(partId),instrId)) _instruments[partId][instrId].name = instrName; } else if (_e.name() == "instrument-abbreviation") { QString abbreviation = _e.readElementText(); - if (_instruments[partId].contains(instrId)) + if (mu::contains(_instruments.at(partId), instrId)) _instruments[partId][instrId].abbreviation = abbreviation; } else if (_e.name() == "instrument-sound") { QString instrSound = _e.readElementText(); - if (_instruments[partId].contains(instrId)) + if (mu::contains(_instruments.at(partId), instrId)) _instruments[partId][instrId].sound = instrSound; } else if (_e.name() == "virtual-instrument") { while (_e.readNextStartElement()) { if (_e.name() == "virtual-library") { QString virtualLibrary = _e.readElementText(); - if (_instruments[partId].contains(instrId)) + if (mu::contains(_instruments.at(partId), instrId)) _instruments[partId][instrId].virtLib = virtualLibrary; } else if (_e.name() == "virtual-name") { QString virtualName = _e.readElementText(); - if (_instruments[partId].contains(instrId)) + if (mu::contains(_instruments.at(partId), instrId)) _instruments[partId][instrId].virtName = virtualName; } else @@ -2304,7 +2304,7 @@ void MusicXMLParserPass1::midiInstrument(const QString& partId) _logger->logError(QString("incorrect midi-channel: %1").arg(channel), &_e); channel = 16; } - if (_instruments[partId].contains(instrId)) + if (mu::contains(_instruments.at(partId), instrId)) _instruments[partId][instrId].midiChannel = channel - 1; } else if (_e.name() == "midi-program") { @@ -2319,17 +2319,17 @@ void MusicXMLParserPass1::midiInstrument(const QString& partId) _logger->logError(QString("incorrect midi-program: %1").arg(program), &_e); program = 128; } - if (_instruments[partId].contains(instrId)) + if (mu::contains(_instruments.at(partId), instrId)) _instruments[partId][instrId].midiProgram = program - 1; } else if (_e.name() == "midi-unpitched") { - if (_instruments[partId].contains(instrId)) + if (mu::contains(_instruments.at(partId), instrId)) _instruments[partId][instrId].unpitched = _e.readElementText().toInt() - 1; } else if (_e.name() == "volume") { double vol = _e.readElementText().toDouble(); if (vol >= 0 && vol <= 100) { - if (_instruments[partId].contains(instrId)) + if (mu::contains(_instruments.at(partId), instrId)) _instruments[partId][instrId].midiVolume = static_cast((vol / 100) * 127); } else @@ -2338,7 +2338,7 @@ void MusicXMLParserPass1::midiInstrument(const QString& partId) else if (_e.name() == "pan") { double pan = _e.readElementText().toDouble(); if (pan >= -90 && pan <= 90) { - if (_instruments[partId].contains(instrId)) + if (mu::contains(_instruments.at(partId), instrId)) _instruments[partId][instrId].midiPan = static_cast(((pan + 90) / 180) * 127); } else @@ -2387,7 +2387,7 @@ void MusicXMLParserPass1::part() _logger->logDebugTrace("MusicXMLParserPass1::part", &_e); const QString id = _e.attributes().value("id").toString().trimmed(); - if (!_parts.contains(id)) { + if (!mu::contains(_parts, id)) { _logger->logError(QString("cannot find part '%1'").arg(id), &_e); skipLogCurrElem(); return; @@ -2411,7 +2411,7 @@ void MusicXMLParserPass1::part() } // Bug fix for Cubase 6.5.5..9.5.10 which generate 2 in a single staff part - setNumberOfStavesForPart(_partMap.value(id), _parts[id].maxStaff() + 1); + setNumberOfStavesForPart(mu::value(_partMap, id), _parts[id].maxStaff() + 1); // allocate MuseScore staff to MusicXML voices allocateStaves(_parts[id].voicelist); // allocate MuseScore voice to MusicXML voices @@ -2711,20 +2711,20 @@ void MusicXMLParserPass1::attributes(const QString& partId, const Fraction cTime _logger->logError("staves exceed MAX_VOICE_DESC_STAVES, but hidden staves can be discarded", &_e); // Some scores have parts with many staves (~10), but most are hidden // When this occurs, we can discard hidden staves - // and store a QMap between staffNumber and staffIndex. + // and store a std::map between staffNumber and staffIndex. int staffNumber = 1; - int staffIndex = 0; + size_t staffIndex = 0; for (; staffNumber <= staves; ++staffNumber) { if (hiddenStaves.find(staffNumber) != hiddenStaves.end()) { _logger->logError(QString("removing hidden staff %1").arg(staffNumber), &_e); continue; } - _parts[partId].insertStaffNumberToIndex(staffNumber, staffIndex); + _parts[partId].insertStaffNumberToIndex(staffNumber, static_cast(staffIndex)); ++staffIndex; } Q_ASSERT(staffIndex == _parts[partId].staffNumberToIndex().size()); - setNumberOfStavesForPart(_partMap.value(partId), staves - static_cast(hiddenStaves.size())); + setNumberOfStavesForPart(mu::value(_partMap, partId), staves - static_cast(hiddenStaves.size())); } else { // Otherwise, don't discard any staves @@ -2732,11 +2732,11 @@ void MusicXMLParserPass1::attributes(const QString& partId, const Fraction cTime // (MuseScore doesn't currently have a mechanism // for hiding non-empty staves, so this is an approximation // of the correct implementation) - setNumberOfStavesForPart(_partMap.value(partId), staves); + setNumberOfStavesForPart(mu::value(_partMap, partId), staves); for (int hiddenStaff : hiddenStaves) { - int hiddenStaffIndex = _parts.value(partId).staffNumberToIndex(hiddenStaff); + int hiddenStaffIndex = mu::value(_parts, partId).staffNumberToIndex(hiddenStaff); if (hiddenStaffIndex >= 0) - _partMap.value(partId)->staff(hiddenStaffIndex)->setHideWhenEmpty(Staff::HideMode::AUTO); + mu::value(_partMap, partId)->staff(hiddenStaffIndex)->setHideWhenEmpty(Staff::HideMode::AUTO); } } } @@ -2939,8 +2939,8 @@ void MusicXMLParserPass1::direction(const QString& partId, const Fraction cTime) // handle the stops first for (const MxmlOctaveShiftDesc& desc : stops) { - if (_octaveShifts.contains(desc.num)) { - MxmlOctaveShiftDesc prevDesc = _octaveShifts.value(desc.num); + if (mu::contains(_octaveShifts, static_cast(desc.num))) { + MxmlOctaveShiftDesc prevDesc = _octaveShifts.at(desc.num); if (prevDesc.tp == MxmlOctaveShiftDesc::Type::UP || prevDesc.tp == MxmlOctaveShiftDesc::Type::DOWN) { // a complete pair @@ -2949,16 +2949,16 @@ void MusicXMLParserPass1::direction(const QString& partId, const Fraction cTime) } else _logger->logError("double octave-shift stop", &_e); - _octaveShifts.remove(desc.num); + mu::remove(_octaveShifts, desc.num); } else - _octaveShifts.insert(desc.num, desc); + _octaveShifts.insert({ desc.num, desc }); } // then handle the starts for (const MxmlOctaveShiftDesc& desc : starts) { - if (_octaveShifts.contains(desc.num)) { - MxmlOctaveShiftDesc prevDesc = _octaveShifts.value(desc.num); + if (mu::contains(_octaveShifts, static_cast(desc.num))) { + MxmlOctaveShiftDesc prevDesc = _octaveShifts.at(desc.num); if (prevDesc.tp == MxmlOctaveShiftDesc::Type::STOP) { // a complete pair _parts[partId].addOctaveShift(staff, desc.size, desc.time); @@ -2966,10 +2966,10 @@ void MusicXMLParserPass1::direction(const QString& partId, const Fraction cTime) } else _logger->logError("double octave-shift start", &_e); - _octaveShifts.remove(desc.num); + mu::remove(_octaveShifts, desc.num); } else - _octaveShifts.insert(desc.num, desc); + _octaveShifts.insert({ desc.num, desc }); } } @@ -3539,7 +3539,7 @@ void MusicXMLParserPass1::note(const QString& partId, QString strStaff = _e.readElementText(); staff = _parts[partId].staffNumberToIndex(strStaff.toInt(&ok)); _parts[partId].setMaxStaff(staff); - Part* part = _partMap.value(partId); + Part* part = mu::value(_partMap, partId); if (!part) continue; if (!ok || staff < 0 || staff >= part->nstaves()) @@ -3601,9 +3601,9 @@ void MusicXMLParserPass1::note(const QString& partId, if (dura.isValid() && dura > Fraction(0, 1)) { // count the chords int voiceInt = voiceToInt(voice); - if (!_parts.value(partId).voicelist.contains(voiceInt)) { + if (!mu::contains(mu::value(_parts, partId).voicelist, voiceInt)) { VoiceDesc vs; - _parts[partId].voicelist.insert(voiceInt, vs); + _parts[partId].voicelist.insert({ voiceInt, vs }); } _parts[partId].voicelist[voiceInt].incrChordRests(staff); // determine note length for voiceInt overlap detection @@ -3669,8 +3669,8 @@ Fraction MusicXMLParserPass1::calcTicks(const int& intTicks, const int& _divisio // There are two strategies: // 1. Use a lookup table of previous adjustments // 2. Check if within maxDiff of a seenDenominator - if (_adjustedDurations.contains(dura)) { - dura = _adjustedDurations.value(dura); + if (mu::contains(_adjustedDurations, dura)) { + dura = _adjustedDurations.at(dura); } else if (dura.reduced().denominator() > 64) { for (int seenDenominator : _seenDenominators) { diff --git a/importexport/musicxml/importmxmlpass1.h b/importexport/musicxml/importmxmlpass1.h index 9aa5482891830..4c71b25365159 100644 --- a/importexport/musicxml/importmxmlpass1.h +++ b/importexport/musicxml/importmxmlpass1.h @@ -46,7 +46,7 @@ struct MxmlPageFormat { bool twosided { false }; }; -typedef QMap PartMap; +typedef std::map PartMap; typedef std::map MusicXmlPartGroupMap; //--------------------------------------------------------- @@ -166,9 +166,9 @@ class MusicXMLParserPass1 { int voiceToInt(const QString& voice); int trackForPart(const QString& id) const; bool hasPart(const QString& id) const; - Part* getPart(const QString& id) const { return _partMap.value(id); } - MusicXmlPart getMusicXmlPart(const QString& id) const { return _parts.value(id); } - MusicXMLInstruments getInstruments(const QString& id) const { return _instruments.value(id); } + Part* getPart(const QString& id) const { return mu::value(_partMap, id); } + MusicXmlPart getMusicXmlPart(const QString& id) const { return mu::value( _parts, id); } + MusicXMLInstruments getInstruments(const QString& id) const { return mu::value(_instruments, id); } void setDrumsetDefault(const QString& id, const QString& instrId, const NoteHead::Group hg, const int line, const Direction sd); MusicXmlInstrList getInstrList(const QString id) const; MusicXmlIntervalList getIntervals(const QString id) const; @@ -176,11 +176,11 @@ class MusicXMLParserPass1 { int octaveShift(const QString& id, const int staff, const Fraction f) const; const CreditWordsList& credits() const { return _credits; } bool hasBeamingInfo() const { return _hasBeamingInfo; } - bool isVocalStaff(const QString& id) const { return _parts[id].isVocalStaff(); } + bool isVocalStaff(const QString& id) const { return _parts.at(id).isVocalStaff(); } static VBox* createAndAddVBoxForCreditWords(Score* const score); int maxDiff() const { return _maxDiff; } - void insertAdjustedDuration(Fraction key, Fraction value) { _adjustedDurations.insert(key, value); } - QMap& adjustedDurations() { return _adjustedDurations; } + void insertAdjustedDuration(Fraction key, Fraction value) { _adjustedDurations.insert({ key, value }); } + std::map& adjustedDurations() { return _adjustedDurations; } void insertSeenDenominator(int val) { _seenDenominators.emplace(val); } void createDefaultHeader(Score* const score); void createMeasuresAndVboxes(Score* const score, @@ -203,14 +203,14 @@ class MusicXMLParserPass1 { QXmlStreamReader _e; QString _exporterString; ///< Name of the software which exported the file int _divs; ///< Current MusicXML divisions value - QMap _parts; ///< Parts data, mapped on part id + std::map _parts; ///< Parts data, mapped on part id std::set _systemStartMeasureNrs; ///< Measure numbers of measures starting a page std::set _pageStartMeasureNrs; ///< Measure numbers of measures starting a page std::vector _measureLength; ///< Length of each measure std::vector _measureStart; ///< Start time of each measure CreditWordsList _credits; ///< All credits collected PartMap _partMap; ///< TODO merge into MusicXmlPart ?? - QMap _instruments; ///< instruments for each part, mapped on part id + std::map _instruments; ///< instruments for each part, mapped on part id Score* _score; ///< MuseScore score MxmlLogger* _logger; ///< Error logger QString _errors; ///< Errors to present to the user @@ -220,11 +220,11 @@ class MusicXMLParserPass1 { // part specific data (TODO: move to part-specific class) Fraction _timeSigDura; ///< Measure duration according to last timesig read - QMap _octaveShifts; ///< Pending octave-shifts + std::map _octaveShifts; ///< Pending octave-shifts QSize _pageSize; ///< Page width read from defaults const int _maxDiff = 5; ///< Duration rounding tick threshold; - QMap _adjustedDurations; ///< Rounded durations + std::map _adjustedDurations; ///< Rounded durations std::set _seenDenominators; ///< Denominators seen. Used for rounding errors. }; diff --git a/importexport/musicxml/importmxmlpass2.cpp b/importexport/musicxml/importmxmlpass2.cpp index 2e89683f55bbb..20d7ddb56ccc5 100644 --- a/importexport/musicxml/importmxmlpass2.cpp +++ b/importexport/musicxml/importmxmlpass2.cpp @@ -371,13 +371,11 @@ static void fillGapsInFirstVoices(Measure* measure, Part* part) static bool hasDrumset(const MusicXMLInstruments& instruments) { bool res = false; - MusicXMLInstrumentsIterator ii(instruments); - while (ii.hasNext()) { - ii.next(); + for (const auto& p : instruments) { // debug: dump the instruments //qDebug("instrument: %s %s", qPrintable(ii.key()), qPrintable(ii.value().toString())); // find valid unpitched values - int unpitched = ii.value().unpitched; + int unpitched = p.second.unpitched; if (0 <= unpitched && unpitched <= 127) { res = true; } @@ -416,16 +414,15 @@ static bool hasDrumset(const MusicXMLInstruments& instruments) static void initDrumset(Drumset* drumset, const MusicXMLInstruments& instruments) { drumset->clear(); - MusicXMLInstrumentsIterator ii(instruments); - while (ii.hasNext()) { - ii.next(); + + for (const auto& ii : instruments) { // debug: also dump the drumset for this part //qDebug("initDrumset: instrument: %s %s", qPrintable(ii.key()), qPrintable(ii.value().toString())); - int unpitched = ii.value().unpitched; + int unpitched = ii.second.unpitched; if (0 <= unpitched && unpitched <= 127) { - drumset->drum(ii.value().unpitched) - = DrumInstrument(ii.value().name.toLatin1().constData(), - ii.value().notehead, ii.value().line, ii.value().stemDirection); + drumset->drum(ii.second.unpitched) + = DrumInstrument(ii.second.name.toLatin1().constData(), + ii.second.notehead, ii.second.line, ii.second.stemDirection); } } } @@ -584,7 +581,7 @@ static void setPartInstruments(MxmlLogger* logger, const QXmlStreamReader* const if (hasDrumset(instruments)) { // do not create multiple instruments for a drum part //qDebug("hasDrumset"); - MusicXMLInstrument mxmlInstr = instruments.first(); + MusicXMLInstrument mxmlInstr = instruments.begin()->second; updatePartWithInstrument(part, mxmlInstr, {}, true); return; } @@ -593,7 +590,7 @@ static void setPartInstruments(MxmlLogger* logger, const QXmlStreamReader* const // instrument details found, but no instrument ids found // -> only a single instrument is playing in the part //qDebug("single instrument"); - MusicXMLInstrument mxmlInstr = instruments.first(); + MusicXMLInstrument mxmlInstr = instruments.begin()->second; updatePartWithInstrument(part, mxmlInstr, intervList.interval({ 0, 1 })); return; } @@ -606,7 +603,7 @@ static void setPartInstruments(MxmlLogger* logger, const QXmlStreamReader* const Fraction tick = (*it).first; if (it == instrList.cbegin()) { prevInstrId = (*it).second; // first instrument id - MusicXMLInstrument mxmlInstr = instruments.value(prevInstrId); + MusicXMLInstrument mxmlInstr = mu::value(instruments, prevInstrId); updatePartWithInstrument(part, mxmlInstr, intervList.interval(tick)); } else { @@ -631,11 +628,11 @@ static void setPartInstruments(MxmlLogger* logger, const QXmlStreamReader* const if (!segment) logger->logError(QString("segment for instrument change at tick %1 not found") .arg(tick.ticks()), xmlreader); - else if (!instruments.contains(instrId)) + else if (!mu::contains(instruments, instrId)) logger->logError(QString("changed instrument '%1' at tick %2 not found in part '%3'") .arg(instrId).arg(tick.ticks()).arg(partId), xmlreader); else { - MusicXMLInstrument mxmlInstr = instruments.value(instrId); + MusicXMLInstrument mxmlInstr = mu::value(instruments, instrId); updatePartWithInstrumentChange(part, mxmlInstr, intervList.interval(tick), segment, track, tick); } } @@ -662,7 +659,7 @@ static QString text2syms(const QString& t) // caching does not gain much ScoreFont* sf = ScoreFont::fallbackFont(); - QMap map; + std::map map; int maxStringSize = 0; // maximum string size found for (int i = int(SymId::noSym); i < int(SymId::lastSym); ++i) { @@ -670,14 +667,14 @@ static QString text2syms(const QString& t) QString string(sf->toString(id)); // insert all syms except space to prevent matching all regular spaces if (id != SymId::space) - map.insert(string, id); + map.insert({ string, id }); if (string.size() > maxStringSize) maxStringSize = string.size(); } // Special case Dolet inference (TODO: put behind a setting or export type flag) - map.insert("$", SymId::segno); - map.insert("Ø", SymId::coda); + map.insert({ "$", SymId::segno }); + map.insert({ "Ø", SymId::coda }); //qDebug("text2syms map count %d maxsz %d filling time elapsed: %d ms", // map.size(), maxStringSize, time.elapsed()); @@ -692,8 +689,8 @@ static QString text2syms(const QString& t) QString sym; while (maxMatch > 0) { QString toBeMatched = in.left(maxMatch); - if (map.contains(toBeMatched)) { - sym = Sym::id2name(map.value(toBeMatched)); + if (mu::contains(map, toBeMatched)) { + sym = Sym::id2name(map.at(toBeMatched)); break; } maxMatch--; @@ -852,23 +849,23 @@ static void addLyric(MxmlLogger* logger, const QXmlStreamReader* const xmlreader static void addLyrics(MxmlLogger* logger, const QXmlStreamReader* const xmlreader, ChordRest* cr, - const QMap& numbrdLyrics, + const std::map& numbrdLyrics, const QSet& extLyrics, MusicXmlLyricsExtend& extendedLyrics) { - for (const auto lyricNo : numbrdLyrics.keys()) { - Lyrics* const lyric = numbrdLyrics.value(lyricNo); + for (const auto lyricNo : mu::keys(numbrdLyrics)) { + Lyrics* const lyric = numbrdLyrics.at(lyricNo); addLyric(logger, xmlreader, cr, lyric, lyricNo, extendedLyrics); if (extLyrics.contains(lyric)) extendedLyrics.addLyric(lyric); } } -static void addGraceNoteLyrics(const QMap& numberedLyrics, QSet extendedLyrics, +static void addGraceNoteLyrics(const std::map& numberedLyrics, QSet extendedLyrics, std::vector& gnLyrics) { - for (const auto lyricNo : numberedLyrics.keys()) { - Lyrics* const lyric = numberedLyrics[lyricNo]; + for (const auto lyricNo : mu::keys(numberedLyrics)) { + Lyrics* const lyric = numberedLyrics.at(lyricNo); if (lyric) { bool extend = extendedLyrics.contains(lyric); const GraceNoteLyrics gnl = GraceNoteLyrics(lyric, extend, lyricNo); @@ -1238,37 +1235,37 @@ static void addOtherOrnamentToChord(const Notation& notation, ChordRest* cr) static bool convertArticulationToSymId(const QString& mxmlName, SymId& id) { - QMap map; // map MusicXML articulation name to MuseScore symbol - map["accent"] = SymId::articAccentAbove; - map["staccatissimo"] = SymId::articStaccatissimoWedgeAbove; - map["staccato"] = SymId::articStaccatoAbove; - map["tenuto"] = SymId::articTenutoAbove; - map["strong-accent"] = SymId::articMarcatoAbove; - map["delayed-turn"] = SymId::ornamentTurn; - map["turn"] = SymId::ornamentTurn; - map["inverted-turn"] = SymId::ornamentTurnInverted; - map["stopped"] = SymId::brassMuteClosed; - map["up-bow"] = SymId::stringsUpBow; - map["down-bow"] = SymId::stringsDownBow; - map["detached-legato"] = SymId::articTenutoStaccatoAbove; - map["spiccato"] = SymId::articStaccatissimoAbove; - map["snap-pizzicato"] = SymId::pluckedSnapPizzicatoAbove; - map["schleifer"] = SymId::ornamentPrecompSlide; - map["open"] = SymId::brassMuteOpen; - map["open-string"] = SymId::brassMuteOpen; - map["thumb-position"] = SymId::stringsThumbPosition; - map["soft-accent"] = SymId::articSoftAccentAbove; - map["stress"] = SymId::articStressAbove; - map["unstress"] = SymId::articUnstressAbove; - - if (map.contains(mxmlName)) { - id = map.value(mxmlName); + static std::map map; // map MusicXML articulation name to MuseScore symbol + if (map.empty()) { + map["accent"] = SymId::articAccentAbove; + map["staccatissimo"] = SymId::articStaccatissimoWedgeAbove; + map["staccato"] = SymId::articStaccatoAbove; + map["tenuto"] = SymId::articTenutoAbove; + map["strong-accent"] = SymId::articMarcatoAbove; + map["delayed-turn"] = SymId::ornamentTurn; + map["turn"] = SymId::ornamentTurn; + map["inverted-turn"] = SymId::ornamentTurnInverted; + map["stopped"] = SymId::brassMuteClosed; + map["up-bow"] = SymId::stringsUpBow; + map["down-bow"] = SymId::stringsDownBow; + map["detached-legato"] = SymId::articTenutoStaccatoAbove; + map["spiccato"] = SymId::articStaccatissimoAbove; + map["snap-pizzicato"] = SymId::pluckedSnapPizzicatoAbove; + map["schleifer"] = SymId::ornamentPrecompSlide; + map["open"] = SymId::brassMuteOpen; + map["open-string"] = SymId::brassMuteOpen; + map["thumb-position"] = SymId::stringsThumbPosition; + map["soft-accent"] = SymId::articSoftAccentAbove; + map["stress"] = SymId::articStressAbove; + map["unstress"] = SymId::articUnstressAbove; + } + + if (mu::contains(map, mxmlName)) { + id = map.at(mxmlName); return true; } - else { - id = SymId::noSym; - return false; - } + id = SymId::noSym; + return false; } //--------------------------------------------------------- @@ -1281,18 +1278,20 @@ static bool convertArticulationToSymId(const QString& mxmlName, SymId& id) static SymId convertFermataToSymId(const QString& mxmlName) { - QMap map; // map MusicXML fermata name to MuseScore symbol - map["normal"] = SymId::fermataAbove; - map["angled"] = SymId::fermataShortAbove; - map["square"] = SymId::fermataLongAbove; - map["double-angled"] = SymId::fermataVeryShortAbove; - map["double-square"] = SymId::fermataVeryLongAbove; - map["double-dot"] = SymId::fermataLongHenzeAbove; - map["half-curve"] = SymId::fermataShortHenzeAbove; - map["curlew"] = SymId::curlewSign; - - if (map.contains(mxmlName)) - return map.value(mxmlName); + static std::map map; // map MusicXML fermata name to MuseScore symbol + if (map.empty()) { + map["normal"] = SymId::fermataAbove; + map["angled"] = SymId::fermataShortAbove; + map["square"] = SymId::fermataLongAbove; + map["double-angled"] = SymId::fermataVeryShortAbove; + map["double-square"] = SymId::fermataVeryLongAbove; + map["double-dot"] = SymId::fermataLongHenzeAbove; + map["half-curve"] = SymId::fermataShortHenzeAbove; + map["curlew"] = SymId::curlewSign; + } + + if (mu::contains(map, mxmlName)) + return map.at(mxmlName); return SymId::fermataAbove; } @@ -1306,30 +1305,32 @@ static SymId convertFermataToSymId(const QString& mxmlName) static NoteHead::Group convertNotehead(QString mxmlName) { - QMap map; // map MusicXML notehead name to a MuseScore headgroup - map["slash"] = int(NoteHead::Group::HEAD_SLASH); - map["triangle"] = int(NoteHead::Group::HEAD_TRIANGLE_UP); - map["diamond"] = int(NoteHead::Group::HEAD_DIAMOND); - map["cross"] = int(NoteHead::Group::HEAD_PLUS); - map["x"] = int(NoteHead::Group::HEAD_CROSS); - map["circled"] = int(NoteHead::Group::HEAD_CIRCLED); - map["circle-x"] = int(NoteHead::Group::HEAD_XCIRCLE); - map["inverted triangle"] = int(NoteHead::Group::HEAD_TRIANGLE_DOWN); - map["slashed"] = int(NoteHead::Group::HEAD_SLASHED1); - map["back slashed"] = int(NoteHead::Group::HEAD_SLASHED2); - map["normal"] = int(NoteHead::Group::HEAD_NORMAL); - map["rectangle"] = int(NoteHead::Group::HEAD_LA); - map["do"] = int(NoteHead::Group::HEAD_DO); - map["re"] = int(NoteHead::Group::HEAD_RE); - map["mi"] = int(NoteHead::Group::HEAD_MI); - map["fa"] = int(NoteHead::Group::HEAD_FA); - map["fa up"] = int(NoteHead::Group::HEAD_FA); - map["so"] = int(NoteHead::Group::HEAD_SOL); - map["la"] = int(NoteHead::Group::HEAD_LA); - map["ti"] = int(NoteHead::Group::HEAD_TI); - - if (map.contains(mxmlName)) - return NoteHead::Group(map.value(mxmlName)); + static std::map map; // map MusicXML notehead name to a MuseScore headgroup + if (map.empty()) { + map["slash"] = int(NoteHead::Group::HEAD_SLASH); + map["triangle"] = int(NoteHead::Group::HEAD_TRIANGLE_UP); + map["diamond"] = int(NoteHead::Group::HEAD_DIAMOND); + map["cross"] = int(NoteHead::Group::HEAD_PLUS); + map["x"] = int(NoteHead::Group::HEAD_CROSS); + map["circled"] = int(NoteHead::Group::HEAD_CIRCLED); + map["circle-x"] = int(NoteHead::Group::HEAD_XCIRCLE); + map["inverted triangle"] = int(NoteHead::Group::HEAD_TRIANGLE_DOWN); + map["slashed"] = int(NoteHead::Group::HEAD_SLASHED1); + map["back slashed"] = int(NoteHead::Group::HEAD_SLASHED2); + map["normal"] = int(NoteHead::Group::HEAD_NORMAL); + map["rectangle"] = int(NoteHead::Group::HEAD_LA); + map["do"] = int(NoteHead::Group::HEAD_DO); + map["re"] = int(NoteHead::Group::HEAD_RE); + map["mi"] = int(NoteHead::Group::HEAD_MI); + map["fa"] = int(NoteHead::Group::HEAD_FA); + map["fa up"] = int(NoteHead::Group::HEAD_FA); + map["so"] = int(NoteHead::Group::HEAD_SOL); + map["la"] = int(NoteHead::Group::HEAD_LA); + map["ti"] = int(NoteHead::Group::HEAD_TI); + } + + if (mu::contains(map, mxmlName)) + return NoteHead::Group(map.at(mxmlName)); else qDebug("unknown notehead %s", qPrintable(mxmlName)); // TODO // default: return 0 @@ -1435,7 +1436,7 @@ static void setSLinePlacement(SLine* sli, const QString placement) //--------------------------------------------------------- // note that in case of overlapping spanners, handleSpannerStart is called for every spanner -// as spanners QMap allows only one value per key, this does not hurt at all +// as spanners std::map allows only one value per key, this does not hurt at all static void handleSpannerStart(SLine* new_sp, int track, QString placement, const Fraction& tick, MusicXmlSpannerMap& spanners) { @@ -2208,14 +2209,14 @@ void MusicXMLParserPass2::part() // try to prevent an empty track name if (msPart->partName().isEmpty()) { QString instrId = _pass1.getInstrList(id).instrument(Fraction(0, 1)); - msPart->setPartName(instruments[instrId].name); + msPart->setPartName(mu::value(instruments, instrId).name); } #ifdef DEBUG_VOICE_MAPPER VoiceList voicelist = _pass1.getVoiceList(id); // debug: print voice mapper contents qDebug("voiceMapperStats: part '%s'", qPrintable(id)); - for (QMap::const_iterator i = voicelist.constBegin(); i != voicelist.constEnd(); ++i) { + for (std::map::const_iterator i = voicelist.cbBegin(); i != voicelist.cend(); ++i) { qDebug("voiceMapperStats: voice %s staff data %s", qPrintable(i.key()), qPrintable(i.value().toString())); } @@ -2260,11 +2261,11 @@ void MusicXMLParserPass2::part() const SpannerSet incompleteSpanners = findIncompleteSpannersAtPartEnd(); //qDebug("spanner list:"); - auto i = _spanners.constBegin(); - while (i != _spanners.constEnd()) { - SLine* const sp = i.key(); - Fraction tick1 = Fraction::fromTicks(i.value().first); - Fraction tick2 = Fraction::fromTicks(i.value().second); + auto i = _spanners.cbegin(); + while (i != _spanners.cend()) { + SLine* sp = i->first; + Fraction tick1 = Fraction::fromTicks(i->second.first); + Fraction tick2 = Fraction::fromTicks(i->second.second); if (sp->isPedal() && toPedal(sp)->endHookType() == HookType::HOOK_45) { // Handle pedal change end tick (slightly hacky) // Find CR on the end tick of @@ -2437,10 +2438,10 @@ static void markUserAccidentals(const int firstStaff, const int staves, const Key key, const Measure* measure, - const QMap& alterMap + const std::map& alterMap ) { - QMap accTmp; + std::map accTmp; AccidentalState currAcc; currAcc.init(key); @@ -2451,9 +2452,9 @@ static void markUserAccidentals(const int firstStaff, if (!e || e->type() != Ms::ElementType::CHORD) continue; Chord* chord = static_cast(e); - foreach (Note* nt, chord->notes()) { - if (alterMap.contains(nt)) { - int alter = alterMap.value(nt); + for (Note* nt : chord->notes()) { + if (mu::contains(alterMap, nt)) { + int alter = alterMap.at(nt); int ln = absStep(nt->tpc(), nt->pitch()); bool error = false; AccidentalVal currAccVal = currAcc.accidentalVal(ln, error); @@ -2462,25 +2463,25 @@ static void markUserAccidentals(const int firstStaff, if ((alter == -1 && currAccVal == AccidentalVal::FLAT && nt->accidental()->accidentalType() == AccidentalType::FLAT - && !accTmp.value(ln, false)) + && !mu::value(accTmp, ln, false)) || (alter == 0 && currAccVal == AccidentalVal::NATURAL && nt->accidental()->accidentalType() == AccidentalType::NATURAL - && !accTmp.value(ln, false)) + && !mu::value(accTmp, ln, false)) || (alter == 1 && currAccVal == AccidentalVal::SHARP && nt->accidental()->accidentalType() == AccidentalType::SHARP - && !accTmp.value(ln, false))) { + && !mu::value(accTmp, ln, false))) { nt->accidental()->setRole(AccidentalRole::USER); } else if (Accidental::isMicrotonal(nt->accidental()->accidentalType()) && nt->accidental()->accidentalType() < AccidentalType::END) { // microtonal accidental nt->accidental()->setRole(AccidentalRole::USER); - accTmp.insert(ln, false); + accTmp.insert({ ln, false }); } else { - accTmp.insert(ln, true); + accTmp.insert({ ln, true }); } } } @@ -2653,7 +2654,7 @@ void MusicXMLParserPass2::measure(const QString& partId, Tuplets tuplets; // Current tuplet for each voice in the current part // collect candidates for courtesy accidentals to work out at measure end - QMap alterMap; + std::map alterMap; DelayedDirectionsList delayedDirections; // Directions to be added to score *after* collecting all and sorting InferredFingeringsList inferredFingerings; // Directions to be reinterpreted as Fingerings HarmonyMap delayedHarmony; @@ -2689,7 +2690,7 @@ void MusicXMLParserPass2::measure(const QString& partId, if (n && !n->chord()->isGrace()) prevChord = n->chord(); // remember last non-grace chord if (n && n->accidental() && n->accidental()->accidentalType() != AccidentalType::NONE) - alterMap.insert(n, alt); + alterMap.insert({ n, alt }); if (missingPrev.isValid()) { mTime += missingPrev; } @@ -2787,7 +2788,7 @@ void MusicXMLParserPass2::measure(const QString& partId, fillGapsInFirstVoices(measure, part); // Prevent any beams from extending into the next measure - for (Beam* beam : beams.values()) + for (Beam* beam : mu::values(beams)) if (beam) removeBeam(beam); @@ -3665,7 +3666,7 @@ void MusicXMLParserDirection::otherDirection() else { // TODO: Multiple sets of maps for exporters other than Dolet 6/Sibelius // TODO: Add more symbols from Sibelius - QMap otherDirectionStrings; + std::map otherDirectionStrings; if (_pass1.exporterString().contains("dolet")) { otherDirectionStrings = { { QString("To Coda"), QString("To Coda") }, @@ -3673,7 +3674,7 @@ void MusicXMLParserDirection::otherDirection() { QString("CODA"), QString("coda") }, }; } - static const QMap otherDirectionSyms = { + static const std::map otherDirectionSyms = { { QString("Rhythm dot"), SymId::augmentationDot }, { QString("Whole rest"), SymId::restWhole }, { QString("l.v. down"), SymId::articLaissezVibrerBelow }, @@ -3684,11 +3685,11 @@ void MusicXMLParserDirection::otherDirection() { QString("Thick caesura"), SymId::caesuraThick } }; QString t = _e.readElementText(); - QString val = otherDirectionStrings.value(t); + QString val = mu::value(otherDirectionStrings, t); if (!val.isEmpty()) _wordsText += val; else { - SymId sym = otherDirectionSyms.value(t); + SymId sym = mu::value(otherDirectionSyms, t); Symbol* smuflSym = new Symbol(_score); smuflSym->setSym(sym); if (color.isValid()) @@ -4736,7 +4737,7 @@ void MusicXMLParserPass2::clearSpanner(const MusicXmlSpannerDesc& d) void MusicXMLParserPass2::deleteHandledSpanner(SLine* const& spanner) { - _spanners.remove(spanner); + mu::remove(_spanners, spanner); delete spanner; } @@ -5804,26 +5805,25 @@ static void setNoteHead(Note* note, const QColor noteheadColor, const bool noteh Calculate the beam mode based on the collected beamTypes. */ -static Beam::Mode computeBeamMode(const QMap& beamTypes) +static Beam::Mode computeBeamMode(const std::map& beamTypes) { // Start with uniquely-handled beam modes - if (beamTypes.value(1) == "continue" - && beamTypes.value(2) == "begin") + if (mu::value(beamTypes, 1) == "continue" + && mu::value(beamTypes, 2) == "begin") return Beam::Mode::BEGIN32; - else if (beamTypes.value(1) == "continue" - && beamTypes.value(2) == "continue" - && beamTypes.value(3) == "begin") + else if (mu::value(beamTypes, 1) == "continue" + && mu::value(beamTypes, 2) == "continue" + && mu::value(beamTypes, 3) == "begin") return Beam::Mode::BEGIN64; // Generic beam modes are naive to all except the first beam - else if (beamTypes.value(1) == "begin") + else if (mu::value(beamTypes, 1) == "begin") return Beam::Mode::BEGIN; - else if (beamTypes.value(1) == "continue") + else if (mu::value(beamTypes, 1) == "continue") return Beam::Mode::MID; - else if (beamTypes.value(1) == "end") + else if (mu::value(beamTypes, 1) == "end") return Beam::Mode::END; - else - // backward-hook, forward-hook, and other unknown combinations - return Beam::Mode::AUTO; + // backward-hook, forward-hook, and other unknown combinations + return Beam::Mode::AUTO; } //--------------------------------------------------------- @@ -5934,11 +5934,10 @@ static void setPitch(Note* note, MusicXMLParserPass1& pass1, const QString& part { const MusicXMLInstruments& instruments = pass1.getInstruments(partId); if (mnp.unpitched()) { - if (hasDrumset(instruments) - && instruments.contains(instrumentId)) { + if (hasDrumset(instruments) && mu::contains(instruments, instrumentId)) { // step and oct are display-step and ...-oct // get pitch from instrument definition in drumset instead - int unpitched = instruments[instrumentId].unpitched; + int unpitched = instruments.at(instrumentId).unpitched; note->setPitch(limit(unpitched, 0, 127)); // TODO - does this need to be key-aware? note->setTpc(pitch2tpc(unpitched, Key::C, Prefer::NEAREST)); // TODO: necessary ? @@ -6043,7 +6042,7 @@ Note* MusicXMLParserPass2::note(const QString& partId, bool graceSlash = false; bool printObject = _e.attributes().value("print-object") != "no"; Beam::Mode bm; - QMap beamTypes; + std::map beamTypes; QString instrumentId; QString tieType; MusicXMLParserLyric lyric { _pass1.getMusicXmlPart(partId).lyricNumberHandler(), _e, _score, _logger }; @@ -6143,8 +6142,8 @@ Note* MusicXMLParserPass2::note(const QString& partId, voice = "1"; // Define currBeam based on currentVoice to handle multi-voice beaming (and instantiate if not already) - if (!currBeams.contains(currentVoice)) - currBeams.insert(currentVoice, (Beam *)nullptr); + if (!mu::contains(currBeams, currentVoice)) + currBeams.insert({ currentVoice, (Beam *)nullptr }); Beam* &currBeam = currBeams[currentVoice]; bm = computeBeamMode(beamTypes); @@ -7035,12 +7034,12 @@ void MusicXMLParserPass2::harmony(const QString& partId, Measure* measure, const Collects beamTypes, used in computeBeamMode. */ -void MusicXMLParserPass2::beam(QMap& beamTypes) { +void MusicXMLParserPass2::beam(std::map& beamTypes) { bool hasBeamNo; int beamNo = _e.attributes().value("number").toInt(&hasBeamNo); QString s = _e.readElementText(); - beamTypes.insert(hasBeamNo ? beamNo : 1, s); + beamTypes.insert({ hasBeamNo ? beamNo : 1, s }); } //--------------------------------------------------------- @@ -7180,7 +7179,7 @@ void MusicXMLParserLyric::parse() _logger->logError(QString("too much lyrics (>%1)").arg(MAX_LYRICS), &_e); return; } - else if (_numberedLyrics.contains(lyricNo)) { + else if (mu::contains(_numberedLyrics, lyricNo)) { _logger->logError(QString("duplicate lyrics number (%1)").arg(lyricNumber), &_e); return; } diff --git a/importexport/musicxml/importmxmlpass2.h b/importexport/musicxml/importmxmlpass2.h index 4c26541946c0d..143b7c1066b29 100644 --- a/importexport/musicxml/importmxmlpass2.h +++ b/importexport/musicxml/importmxmlpass2.h @@ -37,7 +37,7 @@ namespace Ms { using GraceChordList = std::vector; using FiguredBassList = std::vector; using Tuplets = std::map; -using Beams = QMap; +using Beams = std::map; //--------------------------------------------------------- // MxmlStartStop @@ -132,7 +132,7 @@ class MusicXMLParserLyric { MusicXMLParserLyric(const LyricNumberHandler lyricNumberHandler, QXmlStreamReader& e, Score* score, MxmlLogger* logger); QSet extendedLyrics() const { return _extendedLyrics; } - QMap numberedLyrics() const { return _numberedLyrics; } + std::map numberedLyrics() const { return _numberedLyrics; } void parse(); private: void skipLogCurrElem(); @@ -141,7 +141,7 @@ class MusicXMLParserLyric { QXmlStreamReader& _e; Score* const _score = nullptr; // the score MxmlLogger* _logger = nullptr; ///< Error logger - QMap _numberedLyrics; // lyrics with valid number + std::map _numberedLyrics; // lyrics with valid number QSet _extendedLyrics; // lyrics with the extend flag set }; @@ -320,7 +320,7 @@ class MusicXMLParserPass2 { FretDiagram* frame(qreal& defaultY, qreal& relativeY); void harmony(const QString& partId, Measure* measure, const Fraction sTime, HarmonyMap& harmonyMap); Accidental* accidental(); - void beam(QMap& beamTypes); + void beam(std::map& beamTypes); void duration(Fraction& dura); void forward(Fraction& dura); void backup(Fraction& dura); diff --git a/importexport/musicxml/importxmlfirstpass.cpp b/importexport/musicxml/importxmlfirstpass.cpp index d117078152f98..3c70d905161aa 100644 --- a/importexport/musicxml/importxmlfirstpass.cpp +++ b/importexport/musicxml/importxmlfirstpass.cpp @@ -59,9 +59,9 @@ QString MusicXmlPart::toString() const QString res = QString("part id '%1' name '%2' print %3 abbr '%4' print %5 maxStaff %6\n") .arg(id, name).arg(_printName).arg(abbr).arg(_printAbbr, _maxStaff); - for (VoiceList::const_iterator i = voicelist.constBegin(); i != voicelist.constEnd(); ++i) { + for (VoiceList::const_iterator i = voicelist.cbegin(); i != voicelist.cend(); ++i) { res += QString("voice %1 map staff data %2\n") - .arg(QString(i.key() + 1), i.value().toString()); + .arg(QString(i->first + 1), i->second.toString()); } for (size_t i = 0; i < measureNumbers.size(); ++i) { @@ -223,10 +223,9 @@ int MusicXmlPart::staffNumberToIndex(const int staffNumber) const { if (_staffNumberToIndex.size() == 0) return staffNumber - 1; - else if (_staffNumberToIndex.contains(staffNumber)) - return _staffNumberToIndex[staffNumber]; - else - return -1; + else if (mu::contains(_staffNumberToIndex, staffNumber)) + return _staffNumberToIndex.at(staffNumber); + return -1; } //--------------------------------------------------------- diff --git a/importexport/musicxml/importxmlfirstpass.h b/importexport/musicxml/importxmlfirstpass.h index f7f14da880d1f..057385ff019e6 100644 --- a/importexport/musicxml/importxmlfirstpass.h +++ b/importexport/musicxml/importxmlfirstpass.h @@ -19,7 +19,7 @@ namespace Ms { -typedef QMap VoiceList; +typedef std::map VoiceList; //using Intervals = std::map; class MusicXmlIntervalList : public std::map { @@ -80,9 +80,9 @@ class MusicXmlPart { bool getPrintAbbr() const { return _printAbbr; } bool hasTab() const { return _hasTab; } void hasTab(const bool b) { _hasTab = b; } - QMap staffNumberToIndex() const { return _staffNumberToIndex; } + std::map staffNumberToIndex() const { return _staffNumberToIndex; } int staffNumberToIndex(const int staffNumber) const; - void insertStaffNumberToIndex(const int staffNumber, const int staffIndex) { _staffNumberToIndex.insert(staffNumber, staffIndex); } + void insertStaffNumberToIndex(const int staffNumber, const int staffIndex) { _staffNumberToIndex.insert({ staffNumber, staffIndex }); } LyricNumberHandler& lyricNumberHandler() { return _lyricNumberHandler; } const LyricNumberHandler& lyricNumberHandler() const { return _lyricNumberHandler; } void setMaxStaff(const int staff); @@ -102,7 +102,7 @@ class MusicXmlPart { LyricNumberHandler _lyricNumberHandler; int _maxStaff = -1; // maximum staff value found (0 based), -1 = none bool _hasLyrics = false; - QMap _staffNumberToIndex; // Mapping from staff number to index in staff list. + std::map _staffNumberToIndex; // Mapping from staff number to index in staff list. // Only for when staves are discarded in MusicXMLParserPass1::attributes. }; diff --git a/importexport/musicxml/musicxml.h b/importexport/musicxml/musicxml.h index 768c26f8b0ef7..e12cc1e89ac36 100644 --- a/importexport/musicxml/musicxml.h +++ b/importexport/musicxml/musicxml.h @@ -126,7 +126,7 @@ class SlurDesc { //--------------------------------------------------------- typedef std::vector MusicXmlPartGroupList; -typedef QMap > MusicXmlSpannerMap; +typedef std::map > MusicXmlSpannerMap; } // namespace Ms #endif diff --git a/importexport/musicxml/musicxmlsupport.cpp b/importexport/musicxml/musicxmlsupport.cpp index 89d3e0442caf9..e04556bdc3ab5 100644 --- a/importexport/musicxml/musicxmlsupport.cpp +++ b/importexport/musicxml/musicxmlsupport.cpp @@ -27,10 +27,11 @@ #include "musicxmlsupport.h" +#include "global/containers.h" namespace Ms { -const static QMap smuflAccidentalTypes { +const static std::map smuflAccidentalTypes { { "accidentalDoubleFlatOneArrowDown", AccidentalType::DOUBLE_FLAT_ONE_ARROW_DOWN }, { "accidentalFlatOneArrowDown", AccidentalType::FLAT_ONE_ARROW_DOWN }, { "accidentalNaturalOneArrowDown", AccidentalType::NATURAL_ONE_ARROW_DOWN }, @@ -156,19 +157,16 @@ VoiceOverlapDetector::VoiceOverlapDetector() void VoiceOverlapDetector::addNote(const int startTick, const int endTick, const int& voice, const int staff) { // if necessary, create the note list for voice - if (!_noteLists.contains(voice)) - _noteLists.insert(voice, NoteList()); + if (!mu::contains(_noteLists, voice)) + _noteLists.insert({ voice, NoteList()}); _noteLists[voice].addNote(startTick, endTick, staff); } void VoiceOverlapDetector::dump() const { // qDebug("VoiceOverlapDetector::dump()"); - QMapIterator i(_noteLists); - while (i.hasNext()) { - i.next(); - i.value().dump(i.key()); - } + for (auto p : _noteLists) + p.second.dump(p.first); } void VoiceOverlapDetector::newMeasure() @@ -179,10 +177,9 @@ void VoiceOverlapDetector::newMeasure() bool VoiceOverlapDetector::stavesOverlap(const int& voice) const { - if (_noteLists.contains(voice)) - return _noteLists.value(voice).anyStaffOverlaps(); - else - return false; + if (mu::contains(_noteLists, voice)) + return _noteLists.at(voice).anyStaffOverlaps(); + return false; } QString MusicXMLInstrument::toString() const @@ -520,58 +517,60 @@ QString accSymId2SmuflMxmlString(const SymId id) SymId mxmlString2accSymId(const QString mxmlName, const QString smufl) { - QMap map; // map MusicXML accidental name to MuseScore enum SymId - map["sharp"] = SymId::accidentalSharp; - map["natural"] = SymId::accidentalNatural; - map["flat"] = SymId::accidentalFlat; - map["double-sharp"] = SymId::accidentalDoubleSharp; - map["sharp-sharp"] = SymId::accidentalDoubleSharp; - //map["double-flat"] = SymId::accidentalDoubleFlat; // shouldn't harm, but doesn't exist in MusicXML - map["flat-flat"] = SymId::accidentalDoubleFlat; - map["natural-sharp"] = SymId::accidentalNaturalSharp; - map["natural-flat"] = SymId::accidentalNaturalFlat; - - map["quarter-flat"] = SymId::accidentalQuarterToneFlatStein; - map["quarter-sharp"] = SymId::accidentalQuarterToneSharpStein; - map["three-quarters-flat"] = SymId::accidentalThreeQuarterTonesFlatZimmermann; - map["three-quarters-sharp"] = SymId::accidentalThreeQuarterTonesSharpStein; - - map["sharp-down"] = SymId::accidentalQuarterToneSharpArrowDown; - map["sharp-up"] = SymId::accidentalThreeQuarterTonesSharpArrowUp; - map["natural-down"] = SymId::accidentalQuarterToneFlatNaturalArrowDown; - map["natural-up"] = SymId::accidentalQuarterToneSharpNaturalArrowUp; - map["flat-down"] = SymId::accidentalThreeQuarterTonesFlatArrowDown; - map["flat-up"] = SymId::accidentalQuarterToneFlatArrowUp; - map["double-sharp-down"] = SymId::accidentalThreeQuarterTonesSharpArrowDown; - map["double-sharp-up"] = SymId::accidentalFiveQuarterTonesSharpArrowUp; - map["flat-flat-down"] = SymId::accidentalFiveQuarterTonesFlatArrowDown; - map["flat-flat-up"] = SymId::accidentalThreeQuarterTonesFlatArrowUp; - - map["arrow-down"] = SymId::accidentalArrowDown; - map["arrow-up"] = SymId::accidentalArrowUp; - - map["triple-sharp"] = SymId::accidentalTripleSharp; - map["triple-flat"] = SymId::accidentalTripleFlat; - - map["slash-quarter-sharp"] = SymId::accidentalKucukMucennebSharp; - map["slash-sharp"] = SymId::accidentalBuyukMucennebSharp; - map["slash-flat"] = SymId::accidentalBakiyeFlat; - map["double-slash-flat"] = SymId::accidentalBuyukMucennebFlat; - - map["sharp-1"] = SymId::accidental1CommaSharp; - map["sharp-2"] = SymId::accidental2CommaSharp; - map["sharp-3"] = SymId::accidental3CommaSharp; - map["sharp-5"] = SymId::accidental5CommaSharp; - map["flat-1"] = SymId::accidental1CommaFlat; - map["flat-2"] = SymId::accidental2CommaFlat; - map["flat-3"] = SymId::accidental3CommaFlat; - map["flat-4"] = SymId::accidental4CommaFlat; - - map["sori"] = SymId::accidentalSori; - map["koron"] = SymId::accidentalKoron; - - if (map.contains(mxmlName)) - return map.value(mxmlName); + static std::map map; // map MusicXML accidental name to MuseScore enum SymId + if (map.empty()) { + map["sharp"] = SymId::accidentalSharp; + map["natural"] = SymId::accidentalNatural; + map["flat"] = SymId::accidentalFlat; + map["double-sharp"] = SymId::accidentalDoubleSharp; + map["sharp-sharp"] = SymId::accidentalDoubleSharp; + //map["double-flat"] = SymId::accidentalDoubleFlat; // shouldn't harm, but doesn't exist in MusicXML + map["flat-flat"] = SymId::accidentalDoubleFlat; + map["natural-sharp"] = SymId::accidentalNaturalSharp; + map["natural-flat"] = SymId::accidentalNaturalFlat; + + map["quarter-flat"] = SymId::accidentalQuarterToneFlatStein; + map["quarter-sharp"] = SymId::accidentalQuarterToneSharpStein; + map["three-quarters-flat"] = SymId::accidentalThreeQuarterTonesFlatZimmermann; + map["three-quarters-sharp"] = SymId::accidentalThreeQuarterTonesSharpStein; + + map["sharp-down"] = SymId::accidentalQuarterToneSharpArrowDown; + map["sharp-up"] = SymId::accidentalThreeQuarterTonesSharpArrowUp; + map["natural-down"] = SymId::accidentalQuarterToneFlatNaturalArrowDown; + map["natural-up"] = SymId::accidentalQuarterToneSharpNaturalArrowUp; + map["flat-down"] = SymId::accidentalThreeQuarterTonesFlatArrowDown; + map["flat-up"] = SymId::accidentalQuarterToneFlatArrowUp; + map["double-sharp-down"] = SymId::accidentalThreeQuarterTonesSharpArrowDown; + map["double-sharp-up"] = SymId::accidentalFiveQuarterTonesSharpArrowUp; + map["flat-flat-down"] = SymId::accidentalFiveQuarterTonesFlatArrowDown; + map["flat-flat-up"] = SymId::accidentalThreeQuarterTonesFlatArrowUp; + + map["arrow-down"] = SymId::accidentalArrowDown; + map["arrow-up"] = SymId::accidentalArrowUp; + + map["triple-sharp"] = SymId::accidentalTripleSharp; + map["triple-flat"] = SymId::accidentalTripleFlat; + + map["slash-quarter-sharp"] = SymId::accidentalKucukMucennebSharp; + map["slash-sharp"] = SymId::accidentalBuyukMucennebSharp; + map["slash-flat"] = SymId::accidentalBakiyeFlat; + map["double-slash-flat"] = SymId::accidentalBuyukMucennebFlat; + + map["sharp-1"] = SymId::accidental1CommaSharp; + map["sharp-2"] = SymId::accidental2CommaSharp; + map["sharp-3"] = SymId::accidental3CommaSharp; + map["sharp-5"] = SymId::accidental5CommaSharp; + map["flat-1"] = SymId::accidental1CommaFlat; + map["flat-2"] = SymId::accidental2CommaFlat; + map["flat-3"] = SymId::accidental3CommaFlat; + map["flat-4"] = SymId::accidental4CommaFlat; + + map["sori"] = SymId::accidentalSori; + map["koron"] = SymId::accidentalKoron; + } + + if (mu::contains(map, mxmlName)) + return map.at(mxmlName); else if (mxmlName == "other") return Sym::name2id(smufl); else @@ -650,7 +649,7 @@ QString accidentalType2MxmlString(const AccidentalType type) QString accidentalType2SmuflMxmlString(const AccidentalType type) { - return smuflAccidentalTypes.key(type); + return mu::key(smuflAccidentalTypes, type); } //--------------------------------------------------------- @@ -664,60 +663,61 @@ QString accidentalType2SmuflMxmlString(const AccidentalType type) AccidentalType mxmlString2accidentalType(const QString mxmlName, const QString smufl) { - QMap map; // map MusicXML accidental name to MuseScore enum AccidentalType - map["sharp"] = AccidentalType::SHARP; - map["natural"] = AccidentalType::NATURAL; - map["flat"] = AccidentalType::FLAT; - map["double-sharp"] = AccidentalType::SHARP2; - map["sharp-sharp"] = AccidentalType::SHARP2; - //map["double-flat"] = AccidentalType::FLAT2; // shouldn't harm, but doesn't exist in MusicXML - map["flat-flat"] = AccidentalType::FLAT2; - map["natural-sharp"] = AccidentalType::SHARP; - map["natural-flat"] = AccidentalType::FLAT; - - map["quarter-flat"] = AccidentalType::MIRRORED_FLAT; - map["quarter-sharp"] = AccidentalType::SHARP_SLASH; - map["three-quarters-flat"] = AccidentalType::MIRRORED_FLAT2; - map["three-quarters-sharp"] = AccidentalType::SHARP_SLASH4; - - map["sharp-up"] = AccidentalType::SHARP_ARROW_UP; - map["natural-down"] = AccidentalType::NATURAL_ARROW_DOWN; - map["natural-up"] = AccidentalType::NATURAL_ARROW_UP; - map["sharp-down"] = AccidentalType::SHARP_ARROW_DOWN; - map["flat-down"] = AccidentalType::FLAT_ARROW_DOWN; - map["flat-up"] = AccidentalType::FLAT_ARROW_UP; - map["double-sharp-down"] = AccidentalType::SHARP2_ARROW_DOWN; - map["double-sharp-up"] = AccidentalType::SHARP2_ARROW_UP; - map["flat-flat-down"] = AccidentalType::FLAT2_ARROW_DOWN; - map["flat-flat-up"] = AccidentalType::FLAT2_ARROW_UP; - - map["arrow-down"] = AccidentalType::ARROW_DOWN; - map["arrow-up"] = AccidentalType::ARROW_UP; - - map["triple-sharp"] = AccidentalType::SHARP3; - map["triple-flat"] = AccidentalType::FLAT3; - - map["slash-quarter-sharp"] = AccidentalType::SHARP_SLASH3; // MIRRORED_FLAT_SLASH; ? - map["slash-sharp"] = AccidentalType::SHARP_SLASH2; // SHARP_SLASH; ? - map["slash-flat"] = AccidentalType::FLAT_SLASH; - map["double-slash-flat"] = AccidentalType::FLAT_SLASH2; - - map["sharp-1"] = AccidentalType::ONE_COMMA_SHARP; - map["sharp-2"] = AccidentalType::TWO_COMMA_SHARP; - map["sharp-3"] = AccidentalType::THREE_COMMA_SHARP; - map["sharp-5"] = AccidentalType::FIVE_COMMA_SHARP; - map["flat-1"] = AccidentalType::ONE_COMMA_FLAT; - map["flat-2"] = AccidentalType::TWO_COMMA_FLAT; - map["flat-3"] = AccidentalType::THREE_COMMA_FLAT; - map["flat-4"] = AccidentalType::FOUR_COMMA_FLAT; - - map["sori"] = AccidentalType::SORI; - map["koron"] = AccidentalType::KORON; - - if (map.contains(mxmlName)) - return map.value(mxmlName); - else if (mxmlName == "other" && smuflAccidentalTypes.contains(smufl)) - return smuflAccidentalTypes.value(smufl); + static std::map map; // map MusicXML accidental name to MuseScore enum AccidentalType + if (map.empty()) { + map["sharp"] = AccidentalType::SHARP; + map["natural"] = AccidentalType::NATURAL; + map["flat"] = AccidentalType::FLAT; + map["double-sharp"] = AccidentalType::SHARP2; + map["sharp-sharp"] = AccidentalType::SHARP2; + //map["double-flat"] = AccidentalType::FLAT2; // shouldn't harm, but doesn't exist in MusicXML + map["flat-flat"] = AccidentalType::FLAT2; + map["natural-sharp"] = AccidentalType::SHARP; + map["natural-flat"] = AccidentalType::FLAT; + + map["quarter-flat"] = AccidentalType::MIRRORED_FLAT; + map["quarter-sharp"] = AccidentalType::SHARP_SLASH; + map["three-quarters-flat"] = AccidentalType::MIRRORED_FLAT2; + map["three-quarters-sharp"] = AccidentalType::SHARP_SLASH4; + + map["sharp-up"] = AccidentalType::SHARP_ARROW_UP; + map["natural-down"] = AccidentalType::NATURAL_ARROW_DOWN; + map["natural-up"] = AccidentalType::NATURAL_ARROW_UP; + map["sharp-down"] = AccidentalType::SHARP_ARROW_DOWN; + map["flat-down"] = AccidentalType::FLAT_ARROW_DOWN; + map["flat-up"] = AccidentalType::FLAT_ARROW_UP; + map["double-sharp-down"] = AccidentalType::SHARP2_ARROW_DOWN; + map["double-sharp-up"] = AccidentalType::SHARP2_ARROW_UP; + map["flat-flat-down"] = AccidentalType::FLAT2_ARROW_DOWN; + map["flat-flat-up"] = AccidentalType::FLAT2_ARROW_UP; + + map["arrow-down"] = AccidentalType::ARROW_DOWN; + map["arrow-up"] = AccidentalType::ARROW_UP; + + map["triple-sharp"] = AccidentalType::SHARP3; + map["triple-flat"] = AccidentalType::FLAT3; + + map["slash-quarter-sharp"] = AccidentalType::SHARP_SLASH3; // MIRRORED_FLAT_SLASH; ? + map["slash-sharp"] = AccidentalType::SHARP_SLASH2; // SHARP_SLASH; ? + map["slash-flat"] = AccidentalType::FLAT_SLASH; + map["double-slash-flat"] = AccidentalType::FLAT_SLASH2; + + map["sharp-1"] = AccidentalType::ONE_COMMA_SHARP; + map["sharp-2"] = AccidentalType::TWO_COMMA_SHARP; + map["sharp-3"] = AccidentalType::THREE_COMMA_SHARP; + map["sharp-5"] = AccidentalType::FIVE_COMMA_SHARP; + map["flat-1"] = AccidentalType::ONE_COMMA_FLAT; + map["flat-2"] = AccidentalType::TWO_COMMA_FLAT; + map["flat-3"] = AccidentalType::THREE_COMMA_FLAT; + map["flat-4"] = AccidentalType::FOUR_COMMA_FLAT; + + map["sori"] = AccidentalType::SORI; + map["koron"] = AccidentalType::KORON; + } + if (mu::contains(map, mxmlName)) + return map.at(mxmlName); + else if (mxmlName == "other" && mu::contains(smuflAccidentalTypes, smufl)) + return smuflAccidentalTypes.at(smufl); else qDebug("mxmlString2accidentalType: unknown accidental '%s'", qPrintable(mxmlName)); return AccidentalType::NONE; @@ -733,15 +733,16 @@ AccidentalType mxmlString2accidentalType(const QString mxmlName, const QString s QString mxmlAccidentalTextToChar(const QString mxmlName) { - static QMap map; // map MusicXML accidental name to MuseScore enum AccidentalType + static std::map map; // map MusicXML accidental name to MuseScore enum AccidentalType if (map.empty()) { map["sharp"] = "♯"; map["natural"] = "♮"; map["flat"] = "♭"; } - if (map.contains(mxmlName)) - return map.value(mxmlName); + auto it = map.find(mxmlName); + if (it != map.end()) + return it->second; else qDebug("mxmlAccidentalTextToChar: unsupported accidental '%s'", qPrintable(mxmlName)); return ""; diff --git a/importexport/musicxml/musicxmlsupport.h b/importexport/musicxml/musicxmlsupport.h index cd4d56aab9b61..9f26d9059dde9 100644 --- a/importexport/musicxml/musicxmlsupport.h +++ b/importexport/musicxml/musicxmlsupport.h @@ -135,7 +135,7 @@ class VoiceOverlapDetector { void newMeasure(); bool stavesOverlap(const int& voice) const; private: - QMap _noteLists; ///< The notelists for all the voices + std::map _noteLists; ///< The notelists for all the voices }; //--------------------------------------------------------- @@ -165,7 +165,7 @@ struct MusicXMLInstrument { QString toString() const; - MusicXMLInstrument() // required by QMap + MusicXMLInstrument() // required by std::map : unpitched(-1), name(), midiChannel(-1), midiPort(-1), midiProgram(-1), midiVolume(100), midiPan(63), notehead(NoteHead::Group::HEAD_INVALID), line(0), stemDirection(Direction::AUTO) {} MusicXMLInstrument(QString s) @@ -182,8 +182,7 @@ struct MusicXMLInstrument { A MusicXML drumset or set of instruments in a multi-instrument part. */ -typedef QMap MusicXMLInstruments; -typedef QMapIterator MusicXMLInstrumentsIterator; +typedef std::map MusicXMLInstruments; //--------------------------------------------------------- From 0925c77c51ab8e1ae20e2a368e06ab27898b6427 Mon Sep 17 00:00:00 2001 From: Igor Korsukov Date: Fri, 26 Jan 2024 17:11:38 +0100 Subject: [PATCH 4/6] [musicxml] Replaced QSet to std::set Backport of #21205, part 3 --- importexport/musicxml/exportxml.cpp | 53 +++++++++++++---------- importexport/musicxml/importmxmlpass1.cpp | 8 ++-- importexport/musicxml/importmxmlpass2.cpp | 10 ++--- importexport/musicxml/importmxmlpass2.h | 6 +-- 4 files changed, 43 insertions(+), 34 deletions(-) diff --git a/importexport/musicxml/exportxml.cpp b/importexport/musicxml/exportxml.cpp index af51a198df490..09a5359523043 100644 --- a/importexport/musicxml/exportxml.cpp +++ b/importexport/musicxml/exportxml.cpp @@ -363,8 +363,8 @@ class ExportMusicXml { void findAndExportClef(const Measure* const m, const int staves, const int strack, const int etrack); void exportDefaultClef(const Part* const part, const Measure* const m); void writeElement(Element* el, const Measure* m, int sstaff, bool useDrumset); - void writeMeasureTracks(const Measure* const m, const int partIndex, const int strack, const int staves, const bool useDrumset, FigBassMap& fbMap, QSet& spannersStopped); - void writeMeasure(const Measure* const m, const int idx, const int staffCount, MeasureNumberStateHandler& mnsh, FigBassMap& fbMap, const MeasurePrintContext& mpc, QSet& spannersStopped); + void writeMeasureTracks(const Measure* const m, const int partIndex, const int strack, const int staves, const bool useDrumset, FigBassMap& fbMap, std::set& spannersStopped); + void writeMeasure(const Measure* const m, const int idx, const int staffCount, MeasureNumberStateHandler& mnsh, FigBassMap& fbMap, const MeasurePrintContext& mpc, std::set& spannersStopped); void repeatAtMeasureStart(Attributes& attr, const Measure* const m, int strack, int etrack, int track); void repeatAtMeasureStop(const Measure* const m, int strack, int etrack, int track); void writeParts(); @@ -5241,15 +5241,24 @@ void ExportMusicXml::textLine(TextLineBase const* const tl, int staff, const Fra // supported by MusicXML need to be filtered out. Everything not recognized // as MusicXML dynamics is written as other-dynamics. +template +inline std::set& operator<<(std::set& s, const T& v) + { + s.insert(v); + return s; + } + void ExportMusicXml::dynamic(Dynamic const* const dyn, int staff) { - QSet set; // the valid MusicXML dynamics - set << "f" << "ff" << "fff" << "ffff" << "fffff" << "ffffff" - << "fp" << "fz" - << "mf" << "mp" - << "p" << "pp" << "ppp" << "pppp" << "ppppp" << "pppppp" - << "rf" << "rfz" - << "sf" << "sffz" << "sfp" << "sfpp" << "sfz"; + static std::set set; // the valid MusicXML dynamics + if (set.empty()) { + set << "f" << "ff" << "fff" << "ffff" << "fffff" << "ffffff" + << "fp" << "fz" + << "mf" << "mp" + << "p" << "pp" << "ppp" << "pppp" << "ppppp" << "pppppp" + << "rf" << "rfz" + << "sf" << "sffz" << "sfp" << "sfpp" << "sfz"; + } directionTag(_xml, _attr, dyn); @@ -5261,7 +5270,7 @@ void ExportMusicXml::dynamic(Dynamic const* const dyn, int staff) _xml.stag(tagName); const QString dynTypeName = dyn->dynamicTypeName(); - if (set.contains(dynTypeName)) { + if (mu::contains(set, dynTypeName)) { _xml.tagE(dynTypeName); } else if (!dynTypeName.isEmpty()) { @@ -5299,7 +5308,7 @@ void ExportMusicXml::dynamic(Dynamic const* const dyn, int staff) // found a non-dynamics character if (inDynamicsSym) { if (!text.isEmpty()) { - if (set.contains(text)) + if (mu::contains(set, text)) _xml.tagE(text); else _xml.tag("other-dynamics", text); @@ -5311,7 +5320,7 @@ void ExportMusicXml::dynamic(Dynamic const* const dyn, int staff) } } if (!text.isEmpty()) { - if (inDynamicsSym && set.contains(text)) + if (inDynamicsSym && mu::contains(set, text)) _xml.tagE(text); else _xml.tag("other-dynamics", text); @@ -6083,15 +6092,15 @@ static void spannerStart(ExportMusicXml* exp, int strack, int etrack, int track, // note that more than one voice may contains notes ending at tick2, // remember which spanners have already been stopped (the "stopped" set) -static void spannerStop(ExportMusicXml* exp, int strack, int etrack, const Fraction& tick2, int sstaff, QSet& stopped) +static void spannerStop(ExportMusicXml* exp, int strack, int etrack, const Fraction& tick2, int sstaff, std::set& stopped) { for (auto it : exp->score()->spanner()) { - Spanner* e = it.second; + const Spanner* e = it.second; if (e->tick2() != tick2 || e->track() < strack || e->track() >= etrack) continue; - if (!stopped.contains(e)) { + if (!mu::contains(stopped, e)) { stopped.insert(e); switch (e->type()) { case ElementType::HAIRPIN: @@ -6104,7 +6113,7 @@ static void spannerStop(ExportMusicXml* exp, int strack, int etrack, const Fract exp->pedal(toPedal(e), sstaff, Fraction(-1,1)); break; case ElementType::TEXTLINE: - exp->textLine(toTextLineBase(e), sstaff, Fraction(-1,1)); + exp->textLine(static_cast(e), sstaff, Fraction(-1,1)); break; case ElementType::LET_RING: exp->textLine(toLetRing(e), sstaff, Fraction(-1,1)); @@ -6683,7 +6692,7 @@ void ExportMusicXml::findAndExportClef(const Measure* const m, const int staves, Find the set of pitches actually used in a part. */ -typedef QSet pitchSet; // the set of pitches used +typedef std::set pitchSet; // the set of pitches used static void addChordPitchesToSet(const Chord* c, pitchSet& set) { @@ -6825,7 +6834,7 @@ static void partList(XmlWriter& xml, Score* score, MxmlInstrumentMap& instrMap) DrumInstrument di = drumset->drum(i); if (di.notehead != NoteHead::Group::HEAD_INVALID) scoreInstrument(xml, idx + 1, i + 1, di.name); - else if (pitches.contains(i)) + else if (mu::contains(pitches, i)) scoreInstrument(xml, idx + 1, i + 1, QString("Instrument %1").arg(i + 1)); } int midiPort = part->midiPort() + 1; @@ -6834,7 +6843,7 @@ static void partList(XmlWriter& xml, Score* score, MxmlInstrumentMap& instrMap) for (int i = 0; i < 128; ++i) { DrumInstrument di = drumset->drum(i); - if (di.notehead != NoteHead::Group::HEAD_INVALID || pitches.contains(i)) + if (di.notehead != NoteHead::Group::HEAD_INVALID || mu::contains(pitches, i)) midiInstrument(xml, idx + 1, i + 1, part->instrument(), score, i + 1); } } @@ -7254,7 +7263,7 @@ void ExportMusicXml::writeMeasureTracks(const Measure* const m, const int strack, const int staves, // TODO remove ?? const bool useDrumset, FigBassMap& fbMap, - QSet& spannersStopped) + std::set& spannersStopped) { bool tboxesAboveWritten = false; const auto tboxesAbove = findTextFramesToWriteAsWordsAbove(m); @@ -7355,7 +7364,7 @@ void ExportMusicXml::writeMeasure(const Measure* const m, MeasureNumberStateHandler& mnsh, FigBassMap& fbMap, const MeasurePrintContext& mpc, - QSet& spannersStopped) + std::set& spannersStopped) { const Part* part = _score->parts().at(partIndex); const int staves = part->nstaves(); @@ -7477,7 +7486,7 @@ void ExportMusicXml::writeParts() // set of spanners already stopped in this part // required to prevent multiple spanner stops for the same spanner - QSet spannersStopped; + std::set spannersStopped; const auto& pages = _score->pages(); MeasurePrintContext mpc; diff --git a/importexport/musicxml/importmxmlpass1.cpp b/importexport/musicxml/importmxmlpass1.cpp index 46d983b104956..9fa7f311783c4 100644 --- a/importexport/musicxml/importmxmlpass1.cpp +++ b/importexport/musicxml/importmxmlpass1.cpp @@ -1157,7 +1157,7 @@ void MusicXMLParserPass1::scorePartwise() // set of (typically multi-staff) parts containing one or more explicit brackets // spanning only that part: these won't get an implicit brace later // e.g. a two-staff piano part with an explicit brace - QSet partSet; + std::set partSet; // handle the explicit brackets const QList& il = _score->parts(); @@ -1189,14 +1189,14 @@ void MusicXMLParserPass1::scorePartwise() staff->setBracketSpan(pg->column, stavesSpan); // add part to set (skip implicit bracket later) if (pg->span == 1) - partSet << il.at(pg->start); + partSet.insert(il.at(pg->start)); } } // handle the implicit brackets: // multi-staff parts w/o explicit brackets get a brace - foreach (Part const* const p, il) { - if (p->nstaves() > 1 && !partSet.contains(p)) { + for (const Part* p : il) { + if (p->nstaves() > 1 && !mu::contains(partSet, p)) { const int column = p->staff(0)->bracketLevels() + 1; p->staff(0)->setBracketType(column, BracketType::BRACE); p->staff(0)->setBracketSpan(column, p->nstaves()); diff --git a/importexport/musicxml/importmxmlpass2.cpp b/importexport/musicxml/importmxmlpass2.cpp index 20d7ddb56ccc5..0d650482a6c69 100644 --- a/importexport/musicxml/importmxmlpass2.cpp +++ b/importexport/musicxml/importmxmlpass2.cpp @@ -192,7 +192,7 @@ void MusicXmlLyricsExtend::setExtend(const int no, const int track, const Fracti } // cleanup for (Lyrics* l: list) { - _lyrics.remove(l); + mu::remove(_lyrics, l); } } @@ -850,24 +850,24 @@ static void addLyric(MxmlLogger* logger, const QXmlStreamReader* const xmlreader static void addLyrics(MxmlLogger* logger, const QXmlStreamReader* const xmlreader, ChordRest* cr, const std::map& numbrdLyrics, - const QSet& extLyrics, + const std::set& extLyrics, MusicXmlLyricsExtend& extendedLyrics) { for (const auto lyricNo : mu::keys(numbrdLyrics)) { Lyrics* const lyric = numbrdLyrics.at(lyricNo); addLyric(logger, xmlreader, cr, lyric, lyricNo, extendedLyrics); - if (extLyrics.contains(lyric)) + if (mu::contains(extLyrics, lyric)) extendedLyrics.addLyric(lyric); } } -static void addGraceNoteLyrics(const std::map& numberedLyrics, QSet extendedLyrics, +static void addGraceNoteLyrics(const std::map& numberedLyrics, std::set extendedLyrics, std::vector& gnLyrics) { for (const auto lyricNo : mu::keys(numberedLyrics)) { Lyrics* const lyric = numberedLyrics.at(lyricNo); if (lyric) { - bool extend = extendedLyrics.contains(lyric); + bool extend = mu::contains(extendedLyrics, lyric); const GraceNoteLyrics gnl = GraceNoteLyrics(lyric, extend, lyricNo); gnLyrics.push_back(gnl); } diff --git a/importexport/musicxml/importmxmlpass2.h b/importexport/musicxml/importmxmlpass2.h index 143b7c1066b29..19ebfdf78a4fa 100644 --- a/importexport/musicxml/importmxmlpass2.h +++ b/importexport/musicxml/importmxmlpass2.h @@ -111,7 +111,7 @@ class MusicXmlLyricsExtend { void setExtend(const int no, const int track, const Fraction& tick, const Lyrics* prevAddedLyrics); private: - QSet _lyrics; + std::set _lyrics; }; struct GraceNoteLyrics { @@ -131,7 +131,7 @@ class MusicXMLParserLyric { public: MusicXMLParserLyric(const LyricNumberHandler lyricNumberHandler, QXmlStreamReader& e, Score* score, MxmlLogger* logger); - QSet extendedLyrics() const { return _extendedLyrics; } + std::set extendedLyrics() const { return _extendedLyrics; } std::map numberedLyrics() const { return _numberedLyrics; } void parse(); private: @@ -142,7 +142,7 @@ class MusicXMLParserLyric { Score* const _score = nullptr; // the score MxmlLogger* _logger = nullptr; ///< Error logger std::map _numberedLyrics; // lyrics with valid number - QSet _extendedLyrics; // lyrics with the extend flag set + std::set _extendedLyrics; // lyrics with the extend flag set }; //--------------------------------------------------------- From 52fc599bc5e00160624a93dd085a8bc9975cc5ec Mon Sep 17 00:00:00 2001 From: Igor Korsukov Date: Fri, 26 Jan 2024 18:46:36 +0100 Subject: [PATCH 5/6] [musicxml] Replaced QPair to std::pair Backport of #21236, part 3 --- importexport/musicxml/importmxmlpass2.cpp | 22 +++++++++++----------- importexport/musicxml/musicxml.h | 2 +- importexport/musicxml/musicxmlsupport.h | 2 +- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/importexport/musicxml/importmxmlpass2.cpp b/importexport/musicxml/importmxmlpass2.cpp index 0d650482a6c69..3eea9d204b76d 100644 --- a/importexport/musicxml/importmxmlpass2.cpp +++ b/importexport/musicxml/importmxmlpass2.cpp @@ -1443,7 +1443,7 @@ static void handleSpannerStart(SLine* new_sp, int track, QString placement, cons //qDebug("handleSpannerStart(sp %p, track %d, tick %s (%d))", new_sp, track, qPrintable(tick.print()), tick.ticks()); new_sp->setTrack(track); setSLinePlacement(new_sp, placement); - spanners[new_sp] = QPair(tick.ticks(), -1); + spanners[new_sp] = std::pair(tick.ticks(), -1); } //--------------------------------------------------------- @@ -4131,13 +4131,13 @@ double MusicXMLParserDirection::convertTextToNotes() static const QRegularExpression notesRegex("(?[yxeqhwW]\\.{0,2})((?:\\s|\u00A0)*=)"); QString notesSubstring = notesRegex.match(_wordsText).captured("note"); - std::vector> noteSyms{{"q", QString("metNoteQuarterUp")}, // note4_Sym - {"e", QString("metNote8thUp")}, // note8_Sym - {"h", QString("metNoteHalfUp")}, // note2_Sym - {"y", QString("metNote32ndUp")}, // note32_Sym - {"x", QString("metNote16thUp")}, // note16_Sym - {"w", QString("metNoteWhole")}, - {"W", QString("metNoteDoubleWhole")}}; + std::vector> noteSyms{{"q", QString("metNoteQuarterUp")}, // note4_Sym + {"e", QString("metNote8thUp")}, // note8_Sym + {"h", QString("metNoteHalfUp")}, // note2_Sym + {"y", QString("metNote32ndUp")}, // note32_Sym + {"x", QString("metNote16thUp")}, // note16_Sym + {"w", QString("metNoteWhole")}, + {"W", QString("metNoteDoubleWhole")}}; for (auto noteSym : noteSyms) { if (notesSubstring.contains(noteSym.first)) { notesSubstring.replace(noteSym.first, noteSym.second); @@ -7715,7 +7715,7 @@ static void addGlissandoSlide(const Notation& notation, Note* note, gliss->setLineColor(glissandoColor); gliss->setText(glissandoText); gliss->setGlissandoType(glissandoTag == 0 ? GlissandoType::STRAIGHT : GlissandoType::WAVY); - spanners[gliss] = QPair(tick.ticks(), -1); + spanners[gliss] = std::pair(tick.ticks(), -1); // qDebug("glissando/slide=%p inserted at first tick %d", gliss, tick); } } @@ -7871,11 +7871,11 @@ static void addWavyLine(ChordRest* cr, const Fraction& tick, trill = new Trill(cr->score()); trill->setTrack(trk); if (wavyLineType == "start") { - spanners[trill] = QPair(tick.ticks(), -1); + spanners[trill] = std::pair(tick.ticks(), -1); // qDebug("trill=%p inserted at first tick %d", trill, tick); } if (wavyLineType == "startstop") { - spanners[trill] = QPair(tick.ticks(), tick.ticks() + ticks.ticks()); + spanners[trill] = std::pair(tick.ticks(), tick.ticks() + ticks.ticks()); trill = nullptr; // qDebug("trill=%p inserted at first tick %d second tick %d", trill, tick, tick); } diff --git a/importexport/musicxml/musicxml.h b/importexport/musicxml/musicxml.h index e12cc1e89ac36..bf0b7cd3984dc 100644 --- a/importexport/musicxml/musicxml.h +++ b/importexport/musicxml/musicxml.h @@ -126,7 +126,7 @@ class SlurDesc { //--------------------------------------------------------- typedef std::vector MusicXmlPartGroupList; -typedef std::map > MusicXmlSpannerMap; +typedef std::map > MusicXmlSpannerMap; } // namespace Ms #endif diff --git a/importexport/musicxml/musicxmlsupport.h b/importexport/musicxml/musicxmlsupport.h index 9f26d9059dde9..214f464827912 100644 --- a/importexport/musicxml/musicxmlsupport.h +++ b/importexport/musicxml/musicxmlsupport.h @@ -37,7 +37,7 @@ namespace Ms { List of note start/stop times in a voice in a single staff. */ -typedef QPair StartStop; +typedef std::pair StartStop; typedef std::vector StartStopList; //--------------------------------------------------------- From a61b704b2270c9c5739dd2b0cb8c9cf589799e35 Mon Sep 17 00:00:00 2001 From: Igor Korsukov Date: Wed, 7 Feb 2024 18:00:42 +0100 Subject: [PATCH 6/6] [musicxml] Replaced QHash with std::unordered_map Backport of #21400, part 1, partly --- importexport/musicxml/exportxml.cpp | 30 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/importexport/musicxml/exportxml.cpp b/importexport/musicxml/exportxml.cpp index 09a5359523043..e36f22912e7b3 100644 --- a/importexport/musicxml/exportxml.cpp +++ b/importexport/musicxml/exportxml.cpp @@ -314,7 +314,7 @@ struct MeasurePrintContext final // ExportMusicXml //--------------------------------------------------------- -typedef QHash TrillHash; +typedef std::unordered_map TrillHash; typedef std::map MxmlInstrumentMap; class ExportMusicXml { @@ -355,10 +355,8 @@ class ExportMusicXml { void calcDivMoveToTick(const Fraction& t, const Fraction& stretch = {1, 1}); void calcDivisions(); void keysigTimesig(const Measure* m, const Part* p); - void chordAttributes(Chord* chord, Notations& notations, Technical& technical, - TrillHash& trillStart, TrillHash& trillStop); - void wavyLineStartStop(const ChordRest* const cr, Notations& notations, Ornaments& ornaments, - TrillHash& trillStart, TrillHash& trillStop); + void chordAttributes(Chord* chord, Notations& notations, Technical& technical, TrillHash& trillStart, TrillHash& trillStop); + void wavyLineStartStop(const ChordRest* cr, Notations& notations, Ornaments& ornaments, TrillHash& trillStart, TrillHash& trillStop); void print(const Measure* const m, const int partNr, const int firstStaffOfPart, const int nrStavesInPart, const MeasurePrintContext& mpc); void findAndExportClef(const Measure* const m, const int staves, const int strack, const int etrack); void exportDefaultClef(const Part* const part, const Measure* const m); @@ -1039,8 +1037,8 @@ static void findTrills(const Measure* const measure, int strack, int etrack, Tri Element* elem2 = tr->endElement(); if (elem1 && elem1->isChordRest() && elem2 && elem2->isChordRest()) { - trillStart.insert(toChordRest(elem1), tr); - trillStop.insert(toChordRest(elem2), tr); + trillStart.insert({ toChordRest(elem1), tr }); + trillStop.insert({ toChordRest(elem2), tr }); } } } @@ -2715,11 +2713,11 @@ static void wavyLineStop(const Trill* tr, const int number, Notations& notations // wavyLineStartStop //--------------------------------------------------------- -void ExportMusicXml::wavyLineStartStop(const ChordRest* const cr, Notations& notations, Ornaments& ornaments, +void ExportMusicXml::wavyLineStartStop(const ChordRest* cr, Notations& notations, Ornaments& ornaments, TrillHash& trillStart, TrillHash& trillStop) { - if (trillStart.contains(cr) && trillStop.contains(cr)) { - const Trill* tr = trillStart.value(cr); + if (mu::contains(trillStart, cr) && mu::contains(trillStop, cr)) { + const Trill* tr = trillStart.at(cr); int n = findTrill(0); if (n >= 0) { wavyLineStart(tr, n, notations, ornaments, _xml); @@ -2730,8 +2728,8 @@ void ExportMusicXml::wavyLineStartStop(const ChordRest* const cr, Notations& not cr, cr->staffIdx(), cr->tick().ticks()); } else { - if (trillStop.contains(cr)) { - const Trill* tr = trillStop.value(cr); + if (mu::contains(trillStop, cr)) { + const Trill* tr = trillStop.at(cr); int n = findTrill(tr); if (n >= 0) // trill stop after trill start @@ -2748,10 +2746,10 @@ void ExportMusicXml::wavyLineStartStop(const ChordRest* const cr, Notations& not if (n >= 0) { wavyLineStop(tr, n, notations, ornaments, _xml); } - trillStop.remove(cr); + mu::remove(trillStop, cr); } - if (trillStart.contains(cr)) { - const Trill* tr = trillStart.value(cr); + if (mu::contains(trillStart, cr)) { + const Trill* tr = trillStart.at(cr); int n = findTrill(tr); if (n >= 0) qDebug("wavyLineStartStop error"); @@ -2764,7 +2762,7 @@ void ExportMusicXml::wavyLineStartStop(const ChordRest* const cr, Notations& not else qDebug("too many overlapping trills (cr %p staff %d tick %d)", cr, cr->staffIdx(), cr->tick().ticks()); - trillStart.remove(cr); + mu::remove(trillStart, cr); } } }