Line data Source code
1 : /*
2 : * SPDX-License-Identifier: GPL-3.0-only
3 : * MuseScore-Studio-CLA-applies
4 : *
5 : * MuseScore Studio
6 : * Music Composition & Notation
7 : *
8 : * Copyright (C) 2026 MuseScore Limited and others
9 : *
10 : * This program is free software: you can redistribute it and/or modify
11 : * it under the terms of the GNU General Public License version 3 as
12 : * published by the Free Software Foundation.
13 : *
14 : * This program is distributed in the hope that it will be useful,
15 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 : * GNU General Public License for more details.
18 : *
19 : * You should have received a copy of the GNU General Public License
20 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 : */
22 :
23 : #include "notationautomationcontroller.h"
24 :
25 : #include <algorithm>
26 : #include <cmath>
27 : #include <optional>
28 : #include <set>
29 :
30 : #include "uicomponents/qml/Muse/UiComponents/polylineplot.h"
31 :
32 : #include "engraving/iengravingconfiguration.h" // IWYU pragma: keep
33 : #include "engraving/automation/automationdata.h"
34 : #include "engraving/automation/dynamicvalues.h"
35 : #include "engraving/automation/tempovalues.h"
36 : #include "engraving/dom/masterscore.h"
37 : #include "engraving/dom/part.h"
38 : #include "engraving/dom/staff.h"
39 :
40 : #include "notation/imasternotation.h"
41 : #include "notation/inotation.h"
42 : #include "notation/inotationautomation.h"
43 : #include "notation/inotationelements.h" // IWYU pragma: keep
44 :
45 : #include "project/inotationproject.h" // IWYU pragma: keep
46 : #include "project/iprojectaudiosettings.h"
47 :
48 : #include "audio/common/audiotypes.h"
49 :
50 : #include "global/async/async.h"
51 : #include "global/containers.h"
52 : #include "global/realfn.h"
53 :
54 : using namespace mu::notation;
55 : using namespace mu::engraving;
56 : using namespace muse::uicomponents;
57 :
58 : using SetPoint = mu::engraving::AutomationPointEdit::SetPoint;
59 : using MovePoint = mu::engraving::AutomationPointEdit::MovePoint;
60 : using ErasePoint = mu::engraving::AutomationPointEdit::ErasePoint;
61 :
62 : constexpr static qreal POLYLINE_LINE_WIDTH = 1.5;
63 :
64 : constexpr static qreal POLYLINE_STANDARD_CENTER_RADIUS = 3.0;
65 : constexpr static qreal POLYLINE_HOVERED_CENTER_RADIUS = 3.5;
66 : constexpr static qreal POLYLINE_SELECTED_CENTER_RADIUS = 3.5;
67 :
68 : constexpr static qreal POLYLINE_SELECTED_MIDDLE_RING_WIDTH = 1.5;
69 :
70 : constexpr static int POLYLINE_SELECTED_HOVERED_ALPHA = 127;
71 : constexpr static int POLYLINE_GENERATED_AREA_ALPHA = 51;
72 : constexpr static int POLYLINE_EDITED_AREA_ALPHA = 102;
73 :
74 0 : static bool polylinePointIndexIsValid(const PolylinePlot* polyline, int pointIdx)
75 : {
76 0 : IF_ASSERT_FAILED(polyline) {
77 0 : return false;
78 : }
79 0 : return pointIdx > -1 && pointIdx < static_cast<int>(polyline->points().size());
80 : }
81 :
82 : namespace mu::notation {
83 : struct DynamicsDisplayRange {
84 : muse::real_t minSounding = 0.0;
85 : muse::real_t maxSounding = 0.0;
86 : double fadeOutHeight = 0.0;
87 : };
88 : }
89 :
90 : // Only the levels a sound source plays differently get their own height on the lane
91 : static const DynamicsDisplayRange MUSE_SAMPLER_DYNAMICS_RANGE {
92 : mu::engraving::ORDINARY_DYNAMIC_VALUES.at(mu::engraving::DynamicType::PPPPP),
93 : mu::engraving::ORDINARY_DYNAMIC_VALUES.at(mu::engraving::DynamicType::FFF),
94 : 0.01
95 : };
96 : static const DynamicsDisplayRange DEFAULT_DYNAMICS_RANGE {
97 : mu::engraving::ORDINARY_DYNAMIC_VALUES.at(mu::engraving::DynamicType::PPP),
98 : mu::engraving::ORDINARY_DYNAMIC_VALUES.at(mu::engraving::DynamicType::FFF)
99 : };
100 :
101 0 : static double dynamicsValueToDisplay(muse::real_t value, const DynamicsDisplayRange& range)
102 : {
103 0 : if (value <= range.minSounding) {
104 0 : if (muse::RealIsNull(range.fadeOutHeight)) {
105 0 : return 0.0;
106 : }
107 0 : return std::max(muse::real_t(0.0), value / range.minSounding * range.fadeOutHeight);
108 : }
109 :
110 0 : const double t = (value - range.minSounding) / (range.maxSounding - range.minSounding);
111 0 : return std::min(1.0, range.fadeOutHeight + t * (1.0 - range.fadeOutHeight));
112 : }
113 :
114 0 : static muse::real_t dynamicsValueFromDisplay(double displayValue, const DynamicsDisplayRange& range)
115 : {
116 0 : if (displayValue <= range.fadeOutHeight) {
117 0 : if (muse::RealIsNull(range.fadeOutHeight)) {
118 0 : return range.minSounding;
119 : }
120 0 : return muse::real_t(std::max(0.0, displayValue) / range.fadeOutHeight * range.minSounding);
121 : }
122 :
123 0 : const double t = (displayValue - range.fadeOutHeight) / (1.0 - range.fadeOutHeight);
124 0 : return muse::real_t(range.minSounding + t * (range.maxSounding - range.minSounding));
125 : }
126 :
127 : // Must match muse::audio::VOLUME_DB_MIN/MAX
128 : static constexpr double VOLUME_RANGE_MIN_DB = -60.0;
129 : static constexpr double VOLUME_RANGE_MAX_DB = 12.0;
130 :
131 : // Mirrors VolumeSlider.qml's fader curve, so dragging a point feels like moving the mixer fader -
132 : // a plain linear map would put 0dB at 83% up the lane instead of 75%
133 : static constexpr double VOLUME_LOCAL_CENTER_DB = -24.0;
134 : static constexpr double VOLUME_LOGICAL_CENTER_DB = -12.0;
135 : static constexpr double VOLUME_HIGH_ACCURACY_STEP = 1.5;
136 : static constexpr double VOLUME_LOW_ACCURACY_STEP = 0.75;
137 :
138 : // logical (actual) dB -> local (linear-in-display) dB
139 0 : static double volumeLogicalDbToLocalDb(double logicalDb)
140 : {
141 0 : if (logicalDb > VOLUME_LOGICAL_CENTER_DB) {
142 0 : const double diff = VOLUME_RANGE_MAX_DB - logicalDb;
143 0 : return VOLUME_RANGE_MAX_DB - diff * VOLUME_HIGH_ACCURACY_STEP;
144 : }
145 :
146 0 : const double diff = VOLUME_LOGICAL_CENTER_DB - logicalDb;
147 0 : return VOLUME_LOCAL_CENTER_DB - diff * VOLUME_LOW_ACCURACY_STEP;
148 : }
149 :
150 : // local (linear-in-display) dB -> logical (actual) dB
151 0 : static double volumeLocalDbToLogicalDb(double localDb)
152 : {
153 0 : if (localDb > VOLUME_LOCAL_CENTER_DB) {
154 0 : const double diff = VOLUME_RANGE_MAX_DB - localDb;
155 0 : return VOLUME_RANGE_MAX_DB - diff / VOLUME_HIGH_ACCURACY_STEP;
156 : }
157 :
158 0 : const double diff = VOLUME_LOCAL_CENTER_DB - localDb;
159 0 : return VOLUME_LOGICAL_CENTER_DB - diff / VOLUME_LOW_ACCURACY_STEP;
160 : }
161 :
162 0 : static double volumeValueToDisplay(muse::real_t value)
163 : {
164 0 : const double logicalDb = VOLUME_RANGE_MIN_DB + static_cast<double>(value) * (VOLUME_RANGE_MAX_DB - VOLUME_RANGE_MIN_DB);
165 0 : const double localDb = volumeLogicalDbToLocalDb(logicalDb);
166 0 : const double display = (localDb - VOLUME_RANGE_MIN_DB) / (VOLUME_RANGE_MAX_DB - VOLUME_RANGE_MIN_DB);
167 0 : return std::clamp(display, 0.0, 1.0);
168 : }
169 :
170 : // Mirrors the volume fader curve above, anchored on the default tempo instead of 0dB - a plain
171 : // linear map would put the default tempo (120bpm) at ~12% up the lane instead of the center
172 : // This is a UI-only display cap - the score model still allows tempos up to Constants::MAX_TEMPO
173 : static constexpr double TEMPO_RANGE_MAX_BPM = 300.0;
174 : static const double TEMPO_LOGICAL_CENTER_BPM = mu::engraving::Constants::DEFAULT_TEMPO.toBPM().val;
175 : static const double TEMPO_LOCAL_CENTER_BPM = TEMPO_RANGE_MAX_BPM / 2.0;
176 : static const double TEMPO_HIGH_ACCURACY_STEP = (TEMPO_RANGE_MAX_BPM - TEMPO_LOCAL_CENTER_BPM)
177 : / (TEMPO_RANGE_MAX_BPM - TEMPO_LOGICAL_CENTER_BPM);
178 : static const double TEMPO_LOW_ACCURACY_STEP = TEMPO_LOCAL_CENTER_BPM / TEMPO_LOGICAL_CENTER_BPM;
179 :
180 : // logical (actual) bpm -> local (linear-in-display) bpm
181 0 : static double tempoLogicalBpmToLocalBpm(double logicalBpm)
182 : {
183 0 : if (logicalBpm > TEMPO_LOGICAL_CENTER_BPM) {
184 0 : const double diff = TEMPO_RANGE_MAX_BPM - logicalBpm;
185 0 : return TEMPO_RANGE_MAX_BPM - diff * TEMPO_HIGH_ACCURACY_STEP;
186 : }
187 :
188 0 : const double diff = TEMPO_LOGICAL_CENTER_BPM - logicalBpm;
189 0 : return TEMPO_LOCAL_CENTER_BPM - diff * TEMPO_LOW_ACCURACY_STEP;
190 : }
191 :
192 : // local (linear-in-display) bpm -> logical (actual) bpm
193 0 : static double tempoLocalBpmToLogicalBpm(double localBpm)
194 : {
195 0 : if (localBpm > TEMPO_LOCAL_CENTER_BPM) {
196 0 : const double diff = TEMPO_RANGE_MAX_BPM - localBpm;
197 0 : return TEMPO_RANGE_MAX_BPM - diff / TEMPO_HIGH_ACCURACY_STEP;
198 : }
199 :
200 0 : const double diff = TEMPO_LOCAL_CENTER_BPM - localBpm;
201 0 : return TEMPO_LOGICAL_CENTER_BPM - diff / TEMPO_LOW_ACCURACY_STEP;
202 : }
203 :
204 0 : static muse::RectF regionCanvasRect(const System* system, staff_idx_t staffIdx, const Measure* startMeasure, const Measure* endMeasure)
205 : {
206 0 : const SysStaff* sysStaff = system ? system->staff(staffIdx) : nullptr;
207 0 : if (!sysStaff || !startMeasure || !endMeasure) {
208 0 : return muse::RectF();
209 : }
210 0 : const muse::RectF staffCanvasRect = sysStaff->bbox().translated(system->canvasPos());
211 0 : const double left = startMeasure->canvasX();
212 0 : const double right = endMeasure->canvasX() + endMeasure->width();
213 0 : return muse::RectF(left, staffCanvasRect.y(), right - left, staffCanvasRect.height());
214 : }
215 :
216 : // A point on a region's end tick is at the start of the next measure (so it belongs
217 : // to whatever follows the region) unless the region ends the score...
218 0 : static int regionLastTick(const Measure* endMeasure)
219 : {
220 0 : const int endTick = endMeasure->endTick().ticks();
221 0 : return endMeasure->nextMeasureMM() ? endTick - 1 : endTick;
222 : }
223 :
224 0 : static AutomationCurveKey curveKeyFor(AutomationLane lane, const Staff* staff)
225 : {
226 0 : const AutomationType type = automationTypeOf(lane);
227 :
228 0 : switch (lane) {
229 0 : case AutomationLane::Dynamics:
230 0 : return AutomationCurveKey::staff(type, staff->id());
231 0 : case AutomationLane::Tempo:
232 : case AutomationLane::MasterVolume:
233 : case AutomationLane::MasterPan:
234 0 : return AutomationCurveKey::global(type);
235 0 : case AutomationLane::Volume:
236 : case AutomationLane::Pan: {
237 0 : const Part* part = staff->part();
238 0 : const InstrumentTrackId trackId { part->id(), part->instrumentId() };
239 0 : return AutomationCurveKey::instrument(type, trackId);
240 0 : }
241 : }
242 :
243 0 : return AutomationCurveKey();
244 : }
245 :
246 0 : static int tickOfPointBefore(const AutomationCurve& curve, int tick)
247 : {
248 0 : auto it = curve.lower_bound(tick);
249 0 : if (it == curve.begin()) {
250 0 : return -1;
251 : }
252 0 : --it;
253 0 : return it->first;
254 : }
255 :
256 0 : static int tickOfPointAfter(const AutomationCurve& curve, int tick)
257 : {
258 0 : const auto it = curve.upper_bound(tick);
259 0 : if (it == curve.end()) {
260 0 : return -1;
261 : }
262 0 : return it->first;
263 : }
264 :
265 : // The curve's value at a tick lying between two of its points...
266 0 : static double curveValueBetween(const AutomationCurve& curve, int tickBefore, int tickAfter, int tick)
267 : {
268 0 : IF_ASSERT_FAILED(tickBefore >= 0 || tickAfter >= 0) {
269 0 : return 0.0;
270 : }
271 :
272 0 : if (tickAfter == -1) {
273 : // No point after - the curve stays flat at the last point's out value...
274 0 : const mu::engraving::AutomationPoint pointBefore = muse::value(curve, tickBefore, mu::engraving::AutomationPoint());
275 0 : return static_cast<double>(pointBefore.value.outValue);
276 : }
277 :
278 0 : const mu::engraving::AutomationPoint pointAfter = muse::value(curve, tickAfter, mu::engraving::AutomationPoint());
279 0 : if (tickBefore == -1) {
280 : // No point before - the curve is flat at the first point's in value...
281 0 : return static_cast<double>(muse::mpe::resolveInValue(pointAfter.value, std::nullopt));
282 : }
283 :
284 0 : const mu::engraving::AutomationPoint pointBefore = muse::value(curve, tickBefore, mu::engraving::AutomationPoint());
285 0 : const muse::real_t ratio = static_cast<muse::real_t>(tick - tickBefore) / static_cast<muse::real_t>(tickAfter - tickBefore);
286 0 : return static_cast<double>(muse::mpe::evaluateAt(pointAfter.value, pointBefore.value.outValue, ratio));
287 : }
288 :
289 0 : static staff_idx_t firstVisibleStaffIdx(const Score* score)
290 : {
291 0 : for (staff_idx_t i = 0; i < score->nstaves(); ++i) {
292 0 : if (score->staff(i)->show()) {
293 0 : return i;
294 : }
295 : }
296 :
297 0 : return muse::nidx;
298 : }
299 :
300 0 : static bool isStructuralChange(const mu::engraving::ScoreChanges& changes)
301 : {
302 0 : if (!changes.changedObjects.empty() && !changes.isValidBoundary()) {
303 0 : return true;
304 : }
305 :
306 : static const std::unordered_set<mu::engraving::ElementType> STRUCTURAL_TYPES {
307 : mu::engraving::ElementType::MEASURE,
308 : mu::engraving::ElementType::PART,
309 : mu::engraving::ElementType::HBOX,
310 0 : };
311 :
312 0 : for (const mu::engraving::ElementType type : changes.changedTypes) {
313 0 : if (muse::contains(STRUCTURAL_TYPES, type)) {
314 0 : return true;
315 : }
316 : }
317 :
318 0 : return false;
319 : }
320 :
321 0 : static qreal defaultValueFor(AutomationType type)
322 : {
323 0 : switch (type) {
324 0 : case AutomationType::Dynamics:
325 : case AutomationType::Tempo:
326 0 : return 0.0;
327 0 : case AutomationType::Volume: {
328 0 : const muse::real_t zeroDb((0.0 - VOLUME_RANGE_MIN_DB) / (VOLUME_RANGE_MAX_DB - VOLUME_RANGE_MIN_DB));
329 0 : return volumeValueToDisplay(zeroDb);
330 : }
331 0 : case AutomationType::Pan:
332 0 : return 0.5;
333 0 : case AutomationType::Unknown:
334 0 : break;
335 : }
336 :
337 0 : return 0.0;
338 : }
339 :
340 0 : NotationAutomationController::NotationAutomationController(QQuickItem* linesParent, const muse::modularity::ContextPtr& iocCtx)
341 0 : : muse::Contextable(iocCtx), m_linesParent(linesParent)
342 : {
343 0 : }
344 :
345 0 : void NotationAutomationController::init()
346 : {
347 0 : IF_ASSERT_FAILED(automation() && currentNotation()) {
348 0 : return;
349 : }
350 :
351 0 : onCurrentNotationChanged();
352 :
353 0 : automation()->automationModeEnabledChanged().onNotify(this, [this]() {
354 0 : if (automation()->isAutomationModeEnabled() && !m_pendingChanges.isEmpty()) {
355 0 : applyAutomationChanges(m_pendingChanges);
356 0 : m_pendingChanges.clear();
357 : } else {
358 0 : updatePolylinesGeometry();
359 : }
360 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
361 :
362 0 : automation()->resetEditStateRequested().onNotify(this, [this]() {
363 0 : if (m_currentlyEditedPolyline) {
364 0 : m_currentlyEditedPolyline->cancelEdit();
365 : // Rebuild all because changes to this polyline may have affected those on other systems...
366 : // TODO: As above - e.g. changes to the end of a polyline in one system should affect the polyline on
367 : // the next system (probably requires the implementation of "startY" in PolylinePlot)...
368 0 : rebuildAllPolylines();
369 : }
370 0 : m_currentlyEditedPolyline = nullptr;
371 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
372 :
373 0 : notationConfiguration()->currentAutomationLaneChanged().onNotify(this, [this]() {
374 0 : rebuildAllPolylines();
375 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
376 :
377 0 : projectSession()->currentNotationChanged().onNotify(this, [this]() {
378 0 : onCurrentNotationChanged();
379 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
380 :
381 0 : notationConfiguration()->scoreInversionChanged().onNotify(this, [this]() {
382 0 : updatePolylinesColors();
383 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
384 :
385 0 : notationConfiguration()->isOnlyInvertInDarkThemeChanged().onNotify(this, [this]() {
386 0 : updatePolylinesColors();
387 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
388 :
389 0 : uiConfiguration()->currentThemeChanged().onNotify(this, [this]() {
390 0 : updatePolylinesColors();
391 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
392 :
393 0 : engravingConfiguration()->selectionColorChanged().onReceive(this, [this](voice_idx_t idx, const muse::draw::Color&) {
394 : // voice 1 color is used for the centre of selected points, "all voices color" is used for the area under lines
395 0 : if (idx == 0 || idx == mu::engraving::VOICES) {
396 0 : updatePolylinesColors();
397 : }
398 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
399 : }
400 :
401 0 : void NotationAutomationController::buildAndAddPolylinesForSystem(const System* system)
402 : {
403 0 : IF_ASSERT_FAILED(system && m_linesParent && score()) {
404 0 : return;
405 : }
406 :
407 0 : staff_idx_t staffIdx = system->firstVisibleStaff();
408 0 : while (staffIdx != muse::nidx) {
409 0 : buildAndAddPolylinesForStaff(system, staffIdx);
410 0 : staffIdx = system->nextVisibleStaff(staffIdx);
411 : }
412 : }
413 :
414 0 : void NotationAutomationController::buildAndAddPolylinesForStaff(const System* system, staff_idx_t staffIdx)
415 : {
416 0 : IF_ASSERT_FAILED(score() && system && staffIdx != muse::nidx) {
417 0 : return;
418 : }
419 :
420 0 : const Staff* staff = score()->staff(staffIdx);
421 0 : IF_ASSERT_FAILED(staff) {
422 0 : return;
423 : }
424 0 : if (!staff->isPrimaryStaff()) {
425 0 : return;
426 : }
427 :
428 0 : const AutomationCurveKey curveKey = currentCurveKey(staff);
429 0 : if (curveKey.isGlobal() && staffIdx != firstVisibleStaffIdx(score())) {
430 : // Score-scoped automation is only drawn on the score's first staff
431 0 : return;
432 : }
433 :
434 0 : if (curveKey.trackId().has_value() && !staff->isTop()) {
435 : // Instrument-scoped automation is only drawn on the instrument's first staff
436 0 : return;
437 : }
438 :
439 0 : const Measure* startMeasure = nullptr;
440 0 : const Measure* endMeasure = nullptr;
441 0 : for (const MeasureBase* mb : system->measures()) {
442 0 : if (mb->isMeasure()) {
443 0 : if (!startMeasure) {
444 0 : startMeasure = toMeasure(mb);
445 : }
446 0 : endMeasure = toMeasure(mb);
447 0 : } else if (mb->isHBox() && startMeasure) {
448 : // Horizontal boxes end the current region - anything after them belongs to the next one...
449 0 : buildAndAddPolylineForStaffRegion(system, staff, startMeasure, endMeasure);
450 0 : startMeasure = nullptr;
451 0 : endMeasure = nullptr;
452 : }
453 : }
454 :
455 0 : if (startMeasure) {
456 0 : buildAndAddPolylineForStaffRegion(system, staff, startMeasure, endMeasure);
457 : }
458 0 : }
459 :
460 0 : void NotationAutomationController::buildAndAddPolylineForStaffRegion(const System* system, const Staff* staff,
461 : const Measure* startMeasure, const Measure* endMeasure)
462 : {
463 0 : IF_ASSERT_FAILED(score() && system && staff && startMeasure && endMeasure && m_linesParent) {
464 0 : return;
465 : }
466 :
467 0 : const staff_idx_t staffIdx = staff->idx();
468 0 : const muse::RectF regionRect = regionCanvasRect(system, staffIdx, startMeasure, endMeasure);
469 0 : IF_ASSERT_FAILED(regionRect.isValid()) {
470 0 : return;
471 : }
472 :
473 0 : const int startTick = startMeasure->tick().ticks();
474 0 : const int endTick = regionLastTick(endMeasure);
475 :
476 0 : PolylinePlot* polyline = new PolylinePlot(m_linesParent);
477 :
478 0 : const QVector<PointData> pointsData = pointsDataInStaffRegion(staff, regionRect, startTick, endTick);
479 :
480 0 : const PolylineKey key(system, staffIdx, startTick);
481 0 : const bool inserted = m_polylinesDataMap.emplace(key, PolylineData(polyline, pointsData, startMeasure, endMeasure)).second;
482 0 : IF_ASSERT_FAILED(inserted) {
483 0 : delete polyline;
484 0 : return;
485 : }
486 :
487 : //! NOTE: There can't be a 1-to-1 match between the number of points in the automation model and
488 : //! points on the polyline. A point with equal in/out values (i.e. a "BOTH" point) is represented
489 : //! as 1 polyline point, whereas a point with different in/out values will be represented with 2
490 : //! separate polyline points...
491 0 : QVector<QPointF> pointsForPolyline;
492 0 : pointsForPolyline.reserve(pointsData.size());
493 0 : for (const PointData& pointData : pointsData) {
494 0 : pointsForPolyline.emplace_back(pointData.qPointF);
495 : }
496 0 : polyline->setPoints(pointsForPolyline);
497 :
498 0 : applyPolylineStyle(polyline, key);
499 0 : applyPolylineEdgeValues(polyline, key);
500 0 : polyline->setVisible(false);
501 :
502 0 : QObject::connect(polyline, &muse::uicomponents::PolylinePlot::pointMoved,
503 0 : [this, key, polyline](int pointIdx, qreal x, qreal y, bool completed) {
504 0 : IF_ASSERT_FAILED(polylinePointIndexIsValid(polyline, pointIdx)) {
505 0 : return;
506 : }
507 :
508 0 : const PolylineData data = polylineData(key);
509 0 : IF_ASSERT_FAILED(data.polyline) {
510 0 : return;
511 : }
512 :
513 0 : const QVector<PointData>& pointsData = data.pointsData;
514 0 : IF_ASSERT_FAILED(pointIdx >= 0 && pointIdx < pointsData.size()) {
515 0 : return;
516 : }
517 :
518 : // Points can't be dragged past the region's first/last segments (TODO: we shouldn't need to enforce it like this,
519 : // the polyline should start end at the first/last segments)...
520 0 : const muse::RectF regionRect = regionCanvasRect(key.system, key.staffIdx, data.startMeasure, data.endMeasure);
521 0 : const Segment* firstSeg = data.startMeasure->first(SegmentType::Duration);
522 0 : const Segment* lastSeg = data.endMeasure->last(SegmentType::Duration);
523 0 : IF_ASSERT_FAILED(regionRect.isValid() && firstSeg && lastSeg) {
524 0 : return;
525 : }
526 :
527 0 : const qreal minX = (firstSeg->canvasX() - regionRect.x()) / regionRect.width();
528 0 : const qreal maxX = (lastSeg->canvasX() + lastSeg->width() - regionRect.x()) / regionRect.width();
529 :
530 0 : const PointData& oldPointData = pointsData[pointIdx];
531 0 : const mu::engraving::AutomationPoint* automationPoint = automationPointAt(key, oldPointData.tick);
532 0 : const bool editRestricted = !oldPointData.isPending
533 0 : && (!automationPoint || automationPoint->generated || automationPoint->itemId.has_value());
534 0 : const qreal clampedX = editRestricted ? oldPointData.qPointF.x() : std::clamp(x, minX, maxX);
535 :
536 0 : const auto setPreviewPoint = [this, polyline, pointIdx, key](const QPointF& point) {
537 0 : QVector<QPointF> points = polyline->points();
538 0 : points.replace(pointIdx, point);
539 0 : polyline->setPoints(points);
540 0 : applyPolylineColorsUnderLine(polyline, key);
541 0 : polyline->update(); // TODO: pass update rect?
542 0 : };
543 :
544 0 : if (completed) {
545 0 : m_currentlyEditedPolyline = nullptr;
546 :
547 0 : if (oldPointData.isPending) {
548 : // Not in the model yet - add it where it was dropped
549 0 : requestAddPoint(key, clampedX, y, /*useCurveValue*/ false);
550 0 : rebuildPolylinePoints(key);
551 0 : return;
552 : }
553 :
554 0 : if (!requestEditPoint(oldPointData, key, clampedX, y)) {
555 : // Edit was rejected - snap the point back to where it actually is instead of
556 : // leaving the live-drag preview stuck at the rejected position
557 0 : setPreviewPoint(oldPointData.qPointF);
558 : }
559 0 : return;
560 : }
561 :
562 0 : m_currentlyEditedPolyline = polyline;
563 :
564 : // Live drag preview
565 0 : setPreviewPoint({ clampedX, y });
566 0 : });
567 :
568 0 : QObject::connect(polyline, &muse::uicomponents::PolylinePlot::pointAdded,
569 0 : [this, key, polyline](qreal x, qreal y, bool completed) {
570 0 : if (completed) {
571 0 : m_currentlyEditedPolyline = nullptr;
572 0 : requestAddPoint(key, x, y, /*useCurveValue*/ true);
573 0 : rebuildPolylinePoints(key);
574 0 : return;
575 : }
576 :
577 0 : const PolylineData data = polylineData(key);
578 0 : IF_ASSERT_FAILED(data.polyline) {
579 0 : return;
580 : }
581 :
582 0 : const int tick = tickFromXInPolyline(key, data, x);
583 0 : if (tick == -1) {
584 0 : return;
585 : }
586 :
587 0 : m_currentlyEditedPolyline = polyline;
588 :
589 0 : QVector<PointData> pointsData = data.pointsData;
590 :
591 0 : int insertIdx = 0;
592 0 : while (insertIdx < pointsData.size() && pointsData.at(insertIdx).tick < tick) {
593 0 : ++insertIdx;
594 : }
595 0 : pointsData.insert(insertIdx, PointData(-1, tick, { x, y }, PointData::PointType::BOTH, /*isPending*/ true));
596 0 : setPolylinePointsData(key, pointsData);
597 :
598 0 : QVector<QPointF> points = polyline->points();
599 0 : points.insert(insertIdx, { x, y });
600 0 : polyline->setPoints(points);
601 0 : applyPolylineColorsUnderLine(polyline, key);
602 0 : });
603 :
604 0 : QObject::connect(polyline, &muse::uicomponents::PolylinePlot::pointRemoved,
605 0 : [this, key](int pointIdx, bool completed) {
606 0 : if (!completed) {
607 0 : return;
608 : }
609 0 : const PolylineData data = polylineData(key);
610 0 : IF_ASSERT_FAILED(data.polyline) {
611 0 : return;
612 : }
613 :
614 0 : const QVector<PointData>& pointsData = data.pointsData;
615 0 : IF_ASSERT_FAILED(pointIdx >= 0 && pointIdx < pointsData.size()) {
616 0 : return;
617 : }
618 0 : requestRemovePoint(pointsData.at(pointIdx), key);
619 0 : });
620 0 : }
621 :
622 0 : int NotationAutomationController::tickFromXInPolyline(const PolylineKey& key, const PolylineData& data, qreal x)
623 : {
624 0 : const Measure* startMeasure = data.startMeasure;
625 0 : const Measure* endMeasure = data.endMeasure;
626 0 : IF_ASSERT_FAILED(key.isValid() && startMeasure && endMeasure) {
627 0 : return -1;
628 : }
629 :
630 0 : const muse::RectF regionRect = regionCanvasRect(key.system, key.staffIdx, startMeasure, endMeasure);
631 0 : IF_ASSERT_FAILED(regionRect.isValid()) {
632 0 : return -1;
633 : }
634 :
635 0 : const double pointCanvasX = regionRect.x() + x * regionRect.width();
636 0 : const mu::engraving::SegmentType type = mu::engraving::SegmentType::Duration | mu::engraving::SegmentType::BarLineTypes;
637 :
638 0 : const Segment* lastSegInRegion = endMeasure->last(type);
639 0 : IF_ASSERT_FAILED(lastSegInRegion) {
640 0 : return -1;
641 : }
642 :
643 0 : const Segment* prevSeg = nullptr;
644 0 : const Segment* nextSeg = nullptr;
645 0 : for (const Segment* seg = startMeasure->first(type); seg; seg = seg->next1(type)) {
646 0 : if (seg->canvasX() <= pointCanvasX) {
647 0 : prevSeg = seg;
648 : } else {
649 0 : nextSeg = seg;
650 0 : break;
651 : }
652 0 : if (seg == lastSegInRegion) {
653 0 : break;
654 : }
655 : }
656 :
657 : // The end barline's tick (when there's a measure after it) is already in the next region...
658 0 : const int lastTick = regionLastTick(endMeasure);
659 :
660 0 : if (!prevSeg) {
661 : // The point is before the first segment, so snap to the next segment's tick (or none)...
662 0 : return nextSeg ? std::min(nextSeg->tick().ticks(), lastTick) : -1;
663 : }
664 :
665 : // No next segment - use prevSeg's own end as a virtual next point
666 0 : const double nextCanvasX = nextSeg ? nextSeg->canvasX() : prevSeg->canvasX() + prevSeg->width();
667 0 : const int nextTick = nextSeg ? nextSeg->tick().ticks() : prevSeg->tick().ticks() + prevSeg->ticks().ticks();
668 0 : const double canvasSpan = nextCanvasX - prevSeg->canvasX();
669 0 : const double ratio = canvasSpan > 0.0 ? (pointCanvasX - prevSeg->canvasX()) / canvasSpan : 0.0;
670 :
671 : // Interpolate between prevSeg's tick and the next tick (but don't go past the last tick that belongs to this region)...
672 0 : const int prevTick = prevSeg->tick().ticks();
673 0 : const int interpolatedTick = prevTick + static_cast<int>(ratio * (nextTick - prevTick));
674 0 : return std::min(interpolatedTick, lastTick);
675 : }
676 :
677 0 : QVector<NotationAutomationController::PointData> NotationAutomationController::pointsDataInStaffRegion(
678 : const mu::engraving::Staff* staff, const muse::RectF& regionRect, int startTick, int endTick) const
679 : {
680 0 : QVector<PointData> points;
681 0 : IF_ASSERT_FAILED(staff && score() && automationData() && regionRect.isValid()) {
682 0 : return points;
683 : }
684 :
685 0 : const AutomationType type = currentAutomationType();
686 :
687 0 : int currentPointIndex = 0;
688 0 : const mu::engraving::AutomationCurveKey key = currentCurveKey(staff);
689 0 : const mu::engraving::AutomationCurve& curve = automationData()->curve(key);
690 :
691 : // Start at the first point >= startTick rather than curve.begin() - resolvedInValue() only ever
692 : // looks backward via std::prev(it), which works on any valid iterator, not just one reached by
693 : // walking from the beginning
694 0 : for (auto it = curve.lower_bound(startTick); it != curve.end() && it->first <= endTick; ++it) {
695 0 : const int tick = it->first;
696 :
697 0 : const Fraction frac = Fraction::fromTicks(tick);
698 0 : const Segment* seg = score()->tick2leftSegmentMM(frac);
699 0 : if (!seg) { //! FIXME: fix automation curve on measure repeats
700 0 : continue;
701 : }
702 :
703 : // The point's tick may not exactly match that of a segment. For this reason we can only calculate the x position
704 : // of our points based on a "tickRatio". This ratio is based on the "tick difference" between the point tick and
705 : // the segment's tick, and the duration of the segment (in ticks)...
706 0 : const int tickDiff = tick - seg->tick().ticks();
707 0 : const double tickRatio = static_cast<double>(tickDiff) / seg->ticks().ticks();
708 0 : const double pointXInSeg = tickRatio * seg->width(); // The point's x relative to the segment
709 :
710 0 : const double segXInRegion = seg->canvasX() - regionRect.x(); // The segment's x relative to the region
711 0 : const double pointXInRegion = (segXInRegion + pointXInSeg) / regionRect.width();
712 :
713 : // Point in/out values are rescaled to the display range - higher value == lower Y...
714 0 : const mu::engraving::AutomationPoint& autoPoint = it->second;
715 0 : const mu::engraving::real_t resolvedIn = mu::engraving::resolveInValue(curve, it);
716 0 : if (resolvedIn == autoPoint.value.outValue) {
717 0 : const QPointF qpf(pointXInRegion, 1.0 - automationValueToDisplay(type, staff, tick, resolvedIn));
718 0 : points.emplace_back(PointData(currentPointIndex++, tick, qpf, PointData::PointType::BOTH));
719 : } else {
720 0 : const QPointF qpfIn(pointXInRegion, 1.0 - automationValueToDisplay(type, staff, tick, resolvedIn));
721 0 : points.emplace_back(PointData(currentPointIndex++, tick, qpfIn, PointData::PointType::IN));
722 :
723 0 : const QPointF qpfOut(pointXInRegion, 1.0 - automationValueToDisplay(type, staff, tick, autoPoint.value.outValue));
724 0 : points.emplace_back(PointData(currentPointIndex++, tick, qpfOut, PointData::PointType::OUT));
725 : }
726 : }
727 :
728 0 : return points;
729 0 : }
730 :
731 0 : void NotationAutomationController::applyPolylineStyle(PolylinePlot* polyline, const PolylineKey& key) const
732 : {
733 0 : IF_ASSERT_FAILED(polyline) {
734 0 : return;
735 : }
736 :
737 0 : polyline->setLineWidth(POLYLINE_LINE_WIDTH);
738 0 : polyline->setDrawBackground(false);
739 :
740 : //! NOTE: The polyline resets its baseline to its default value whenever it has no points. Higher value == lower Y...
741 0 : const qreal defaultValue = defaultValueFor(currentAutomationType());
742 0 : polyline->setDefaultValue(1.0 - defaultValue);
743 0 : polyline->setBaselineN(defaultValue);
744 :
745 0 : polyline->setGhostPointsEnabled(false);
746 0 : polyline->setSelectedPointsEnabled(true);
747 :
748 0 : PolylinePointStyle* standard = polyline->standardPointStyle();
749 0 : standard->setCenterRadius(POLYLINE_STANDARD_CENTER_RADIUS);
750 0 : standard->setOutlineWidth(POLYLINE_LINE_WIDTH);
751 :
752 0 : standard->setCenterRadiusHovered(POLYLINE_HOVERED_CENTER_RADIUS);
753 0 : standard->setOutlineWidthHovered(POLYLINE_LINE_WIDTH);
754 :
755 0 : PolylinePointStyle* selected = polyline->selectedPointStyle();
756 0 : selected->setCenterRadius(POLYLINE_SELECTED_CENTER_RADIUS);
757 0 : selected->setMiddleRingWidth(POLYLINE_SELECTED_MIDDLE_RING_WIDTH);
758 0 : selected->setOutlineWidth(POLYLINE_LINE_WIDTH);
759 :
760 0 : selected->setCenterRadiusHovered(POLYLINE_SELECTED_CENTER_RADIUS);
761 0 : selected->setMiddleRingWidthHovered(POLYLINE_SELECTED_MIDDLE_RING_WIDTH);
762 0 : selected->setOutlineWidthHovered(POLYLINE_LINE_WIDTH);
763 :
764 0 : applyPolylineColors(polyline, key);
765 : }
766 :
767 0 : void NotationAutomationController::applyPolylineColors(PolylinePlot* polyline, const PolylineKey& key) const
768 : {
769 0 : IF_ASSERT_FAILED(polyline) {
770 0 : return;
771 : }
772 :
773 0 : const QColor lineColor = inversionRelativeColor(muse::ui::FONT_PRIMARY_COLOR);
774 0 : polyline->setLineColor(lineColor);
775 :
776 0 : const QColor foregroundColor = notationConfiguration()->foregroundColor();
777 :
778 0 : PolylinePointStyle* standard = polyline->standardPointStyle();
779 0 : standard->setCenterColor(foregroundColor);
780 0 : standard->setOutlineColor(lineColor);
781 :
782 0 : standard->setCenterColorHovered(inversionRelativeColor(muse::ui::BUTTON_COLOR));
783 0 : standard->setOutlineColorHovered(lineColor);
784 :
785 0 : QColor selectionColor = engravingConfiguration()->selectionColor().toQColor();
786 :
787 0 : PolylinePointStyle* selected = polyline->selectedPointStyle();
788 0 : selected->setCenterColor(selectionColor);
789 0 : selected->setMiddleRingColor(foregroundColor);
790 0 : selected->setOutlineColor(lineColor);
791 :
792 0 : selectionColor.setAlpha(POLYLINE_SELECTED_HOVERED_ALPHA);
793 0 : selected->setCenterColorHovered(selectionColor);
794 0 : selected->setMiddleRingColorHovered(foregroundColor);
795 0 : selected->setOutlineColorHovered(lineColor);
796 :
797 0 : applyPolylineColorsUnderLine(polyline, key);
798 : }
799 :
800 0 : void NotationAutomationController::applyPolylineColorsUnderLine(PolylinePlot* polyline, const PolylineKey& key) const
801 : {
802 0 : const PolylineData data = polylineData(key);
803 0 : const Staff* staff = score() ? score()->staff(key.staffIdx) : nullptr;
804 0 : IF_ASSERT_FAILED(polyline && data.polyline && staff && automationData()) {
805 0 : return;
806 : }
807 :
808 : // TODO: Cache these colors?
809 0 : const QColor allVoicesColor = engravingConfiguration()->selectionColor(mu::engraving::VOICES).toQColor();
810 :
811 0 : QColor generatedColor = allVoicesColor;
812 0 : generatedColor.setAlpha(POLYLINE_GENERATED_AREA_ALPHA);
813 :
814 0 : QColor editedColor = allVoicesColor;
815 0 : editedColor.setAlpha(POLYLINE_EDITED_AREA_ALPHA);
816 :
817 0 : const QVector<PointData>& pointsData = data.pointsData;
818 :
819 : //! NOTE: The first and last segments run to/from the points just outside the region (if any), which can be in other polylines...
820 0 : const AutomationCurve& curve = automationData()->curve(currentCurveKey(staff));
821 0 : const int tickBeforeRegion = tickOfPointBefore(curve, data.startMeasure->tick().ticks());
822 0 : const int tickAfterRegion = tickOfPointAfter(curve, regionLastTick(data.endMeasure));
823 :
824 0 : QVector<QColor> colorsUnderLine;
825 0 : colorsUnderLine.reserve(pointsData.size() + 1); // +1 for the "trailing color" (see below)
826 :
827 0 : bool prevPointGenerated = tickBeforeRegion == -1 || curve.find(tickBeforeRegion)->second.generated;
828 0 : for (const PointData& pointData : pointsData) {
829 : //! NOTE: The following can be null for newly created (always non-generated) points because they're not in the model yet
830 0 : const mu::engraving::AutomationPoint* automationPoint = automationPointAt(key, pointData.tick);
831 0 : const bool currPointGenerated = automationPoint && automationPoint->generated;
832 :
833 : // Colors either side of an edited point should use the "edited color"...
834 0 : const bool useEditedColor = !prevPointGenerated || !currPointGenerated;
835 0 : colorsUnderLine.emplace_back(useEditedColor ? editedColor : generatedColor);
836 :
837 0 : prevPointGenerated = currPointGenerated;
838 : }
839 :
840 : // This is the trailing color (after the last point) - it follows the last point, as well as the point after the region...
841 0 : const bool nextPointGenerated = tickAfterRegion == -1 || curve.find(tickAfterRegion)->second.generated;
842 0 : colorsUnderLine.emplace_back(!prevPointGenerated || !nextPointGenerated ? editedColor : generatedColor);
843 :
844 0 : polyline->setColorsUnderLine(colorsUnderLine);
845 0 : }
846 :
847 0 : void NotationAutomationController::applyPolylineEdgeValues(PolylinePlot* polyline, const PolylineKey& key) const
848 : {
849 0 : const PolylineData data = polylineData(key);
850 0 : const Staff* staff = score() ? score()->staff(key.staffIdx) : nullptr;
851 0 : IF_ASSERT_FAILED(polyline && data.polyline && staff && automationData()) {
852 0 : return;
853 : }
854 :
855 0 : const AutomationType type = currentAutomationType();
856 0 : const AutomationCurve& curve = automationData()->curve(currentCurveKey(staff));
857 :
858 : //! NOTE: The curve carries on beyond the region, so the line at the region's edges is taken from the points either side
859 : //! of them (which may belong to other polylines) rather than from the points inside the region...
860 0 : const int startTick = data.startMeasure->tick().ticks();
861 0 : const int lastTick = regionLastTick(data.endMeasure);
862 0 : const int endTick = data.endMeasure->endTick().ticks();
863 :
864 0 : if (curve.empty()) {
865 0 : polyline->setLeftEdgeValue(polyline->defaultValue());
866 0 : polyline->setRightEdgeValue(polyline->defaultValue());
867 0 : return;
868 : }
869 :
870 : // Left edge - between the last point before the region and the first point in or after it...
871 0 : const int tickBeforeStart = tickOfPointBefore(curve, startTick);
872 0 : const int tickAtOrAfterStart = tickOfPointAfter(curve, startTick - 1);
873 0 : const double left = curveValueBetween(curve, tickBeforeStart, tickAtOrAfterStart, startTick);
874 :
875 : // Right edge - between the last point in or before the region and the first point after it...
876 0 : const int tickAtOrBeforeLast = tickOfPointBefore(curve, lastTick + 1);
877 0 : const int tickAfterLast = tickOfPointAfter(curve, lastTick);
878 0 : const double right = curveValueBetween(curve, tickAtOrBeforeLast, tickAfterLast, endTick);
879 :
880 : // Higher value == lower Y...
881 0 : polyline->setLeftEdgeValue(1.0 - automationValueToDisplay(type, staff, startTick, left));
882 0 : polyline->setRightEdgeValue(1.0 - automationValueToDisplay(type, staff, endTick, right));
883 0 : }
884 :
885 0 : QColor NotationAutomationController::inversionRelativeColor(const muse::ui::ThemeStyleKey& key) const
886 : {
887 : // This method is necessary because automation colors are relative to the score inversion as opposed to the current UI theme. In an
888 : // inverted score we use dark theme colors, and in a non-inverted score we use light theme colors...
889 :
890 : // TODO: High contrast colors should actually be fully customizable (issue #34154)
891 0 : const bool isHighContrast = uiConfiguration()->isHighContrast();
892 0 : const muse::ui::ThemeCode lightTheme = isHighContrast ? muse::ui::HIGH_CONTRAST_WHITE_THEME_CODE : muse::ui::LIGHT_THEME_CODE;
893 0 : const muse::ui::ThemeCode darkTheme = isHighContrast ? muse::ui::HIGH_CONTRAST_BLACK_THEME_CODE : muse::ui::DARK_THEME_CODE;
894 :
895 0 : const bool inverted = notationConfiguration()->shouldInvertScore();
896 :
897 0 : const muse::ui::ThemeList& themes = uiConfiguration()->themes();
898 0 : for (const muse::ui::ThemeInfo& theme : themes) {
899 : // Set line colors based on score inversion as opposed to current UI themes...
900 0 : const bool foundLightTheme = !inverted && theme.codeKey == lightTheme;
901 0 : const bool foundDarkTheme = inverted && theme.codeKey == darkTheme;
902 0 : if (foundLightTheme || foundDarkTheme) {
903 0 : return theme.values[key].toString();
904 : }
905 : }
906 :
907 0 : ASSERT_X("Error scanning themes");
908 :
909 : return QColor();
910 0 : }
911 :
912 0 : void NotationAutomationController::updatePolylinesGeometry()
913 : {
914 0 : const bool visible = automation() && automation()->isAutomationModeEnabled();
915 :
916 0 : for (const auto& [key, data] : m_polylinesDataMap) {
917 0 : PolylinePlot* polyline = data.polyline;
918 0 : IF_ASSERT_FAILED(key.isValid() && polyline) {
919 0 : continue;
920 : }
921 :
922 0 : const muse::RectF regionRect = regionCanvasRect(key.system, key.staffIdx, data.startMeasure, data.endMeasure);
923 0 : const bool shown = visible && regionRect.isValid();
924 0 : polyline->setVisible(shown);
925 0 : if (!shown) {
926 0 : if (visible) {
927 0 : ASSERT_X("Invalid region rect");
928 : }
929 0 : continue;
930 0 : }
931 :
932 : //! NOTE: Here we should only update properties of the polyline that change relative to the view matrix. Polyline points are
933 : //! placed relative to the polylines themselves, and thus do not need to be modified in here...
934 0 : const muse::RectF viewRect = m_viewMatrix.map(regionRect);
935 :
936 0 : polyline->setWidth(viewRect.width());
937 0 : polyline->setHeight(viewRect.height());
938 0 : polyline->setX(viewRect.x());
939 0 : polyline->setY(viewRect.y());
940 :
941 0 : applyPolylineColors(polyline, key);
942 : }
943 0 : }
944 :
945 0 : void NotationAutomationController::updatePolylinesColors()
946 : {
947 0 : for (const auto& [key, data] : m_polylinesDataMap) {
948 0 : PolylinePlot* polyline = data.polyline;
949 0 : IF_ASSERT_FAILED(key.isValid() && polyline) {
950 0 : continue;
951 : }
952 0 : applyPolylineColors(polyline, key);
953 : }
954 0 : }
955 :
956 0 : void NotationAutomationController::setViewMatrix(const muse::draw::Transform& viewMatrix)
957 : {
958 0 : if (viewMatrix == m_viewMatrix) {
959 0 : return;
960 : }
961 0 : m_viewMatrix = viewMatrix;
962 :
963 0 : if (automation() && automation()->isAutomationModeEnabled()) {
964 0 : updatePolylinesGeometry();
965 : }
966 : }
967 :
968 0 : void NotationAutomationController::onCurrentNotationChanged()
969 : {
970 0 : m_pendingChanges.clear();
971 0 : m_pendingScoreState = PendingScoreState();
972 0 : rebuildAllPolylines();
973 :
974 0 : if (automationData()) {
975 0 : automationData()->changed().onReceive(this, [this](const mu::engraving::AutomationChanges& changes) {
976 0 : mergePendingChanges(changes);
977 0 : scheduleUpdate();
978 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
979 : }
980 :
981 0 : if (score()) {
982 0 : score()->changesChannel().onReceive(this, [this](const mu::engraving::ScoreChanges& changes) {
983 0 : mergePendingScoreChanges(changes);
984 0 : scheduleUpdate();
985 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
986 : }
987 :
988 0 : if (currentNotation()) {
989 0 : currentNotation()->viewModeChanged().onNotify(this, [this]() {
990 0 : rebuildAllPolylines();
991 0 : }, Asyncable::Mode::SetReplace /* FIXME */);
992 : }
993 :
994 0 : const project::INotationProjectPtr notationProject = projectSession()->project();
995 0 : if (const project::IProjectAudioSettingsPtr settings = notationProject ? notationProject->audioSettings() : nullptr) {
996 : // The Dynamics display range depends on the track's sound
997 0 : settings->trackInputParamsChanged().onReceive(this, [this](const InstrumentTrackId&) {
998 0 : if (currentAutomationType() != AutomationType::Dynamics) {
999 0 : return;
1000 : }
1001 0 : m_pendingScoreState.hasChanges = true;
1002 0 : m_pendingScoreState.structural = true;
1003 0 : scheduleUpdate();
1004 : }, Asyncable::Mode::SetReplace /* FIXME */);
1005 0 : }
1006 0 : }
1007 :
1008 0 : void NotationAutomationController::mergePendingScoreChanges(const mu::engraving::ScoreChanges& changes)
1009 : {
1010 0 : const bool firstChange = !m_pendingScoreState.hasChanges;
1011 0 : m_pendingScoreState.hasChanges = true;
1012 0 : m_pendingScoreState.structural = m_pendingScoreState.structural || isStructuralChange(changes);
1013 :
1014 0 : if (!changes.isValidBoundary()) {
1015 0 : m_pendingScoreState.boundary = std::nullopt;
1016 0 : return;
1017 : }
1018 0 : if (!firstChange && !m_pendingScoreState.boundary) {
1019 0 : return;
1020 : }
1021 :
1022 0 : const TickStaffRange changeRange { changes.tickFrom, changes.tickTo, changes.staffIdxFrom, changes.staffIdxTo };
1023 0 : TickStaffRange range = m_pendingScoreState.boundary.value_or(changeRange);
1024 0 : range.tickFrom = std::min(range.tickFrom, changeRange.tickFrom);
1025 0 : range.tickTo = std::max(range.tickTo, changeRange.tickTo);
1026 0 : range.staffIdxFrom = std::min(range.staffIdxFrom, changeRange.staffIdxFrom);
1027 0 : range.staffIdxTo = std::max(range.staffIdxTo, changeRange.staffIdxTo);
1028 0 : m_pendingScoreState.boundary = range;
1029 : }
1030 :
1031 0 : void NotationAutomationController::scheduleUpdate()
1032 : {
1033 0 : if (m_updateScheduled) {
1034 0 : return;
1035 : }
1036 0 : m_updateScheduled = true;
1037 :
1038 0 : muse::async::Async::call(this, [this]() {
1039 0 : m_updateScheduled = false;
1040 0 : processPendingChanges();
1041 0 : });
1042 : }
1043 :
1044 0 : void NotationAutomationController::processPendingChanges()
1045 : {
1046 0 : if (!m_pendingScoreState.hasChanges && m_pendingChanges.isEmpty()) {
1047 0 : return;
1048 : }
1049 0 : const PendingScoreState scoreState = m_pendingScoreState;
1050 0 : m_pendingScoreState = PendingScoreState();
1051 :
1052 0 : const bool automationVisible = automation() && automation()->isAutomationModeEnabled();
1053 :
1054 0 : if (scoreState.structural) {
1055 0 : if (!automationVisible) {
1056 : // Nothing visible right now; defer the rebuild until automation mode is enabled again
1057 0 : m_pendingChanges.isFullReset = true;
1058 0 : return;
1059 : }
1060 0 : rebuildAllPolylines();
1061 0 : m_pendingChanges.clear();
1062 0 : return;
1063 : }
1064 :
1065 0 : if (!automationVisible) {
1066 : // Nothing visible right now; m_pendingChanges keeps accumulating for next time
1067 0 : return;
1068 : }
1069 :
1070 0 : if (!m_pendingChanges.isEmpty()) {
1071 0 : applyAutomationChanges(m_pendingChanges);
1072 0 : m_pendingChanges.clear();
1073 0 : return;
1074 : }
1075 :
1076 : // No automation-data change and nothing structural - just layout drift
1077 : // (e.g. measure widths shifted); refresh point positions using the batch's own range
1078 0 : for (const auto& [key, data] : m_polylinesDataMap) {
1079 0 : IF_ASSERT_FAILED(key.isValid()) {
1080 0 : continue;
1081 : }
1082 0 : const Staff* staff = score()->staff(key.staffIdx);
1083 0 : if (!staff) {
1084 0 : continue;
1085 : }
1086 :
1087 0 : const int regionStartTick = data.startMeasure->tick().ticks();
1088 0 : const int regionEndTick = data.endMeasure->endTick().ticks();
1089 0 : if (scoreState.boundary) {
1090 0 : const TickStaffRange& range = *scoreState.boundary;
1091 0 : if (staff->idx() < range.staffIdxFrom || staff->idx() > range.staffIdxTo) {
1092 0 : continue;
1093 : }
1094 0 : if (regionEndTick < range.tickFrom || regionStartTick > range.tickTo) {
1095 0 : continue;
1096 : }
1097 : }
1098 :
1099 0 : rebuildPolylinePoints(key);
1100 : }
1101 :
1102 0 : updatePolylinesGeometry();
1103 : }
1104 :
1105 0 : void NotationAutomationController::rebuildAllPolylines()
1106 : {
1107 0 : m_currentlyEditedPolyline = nullptr;
1108 :
1109 : // TODO: More efficient if we don't clear/recreate the polylines every time...
1110 0 : for (const auto& [key, data] : m_polylinesDataMap) {
1111 0 : delete data.polyline;
1112 : }
1113 0 : m_polylinesDataMap.clear();
1114 :
1115 0 : if (!score()) {
1116 : // Happens on close...
1117 0 : return;
1118 : }
1119 :
1120 0 : for (const System* system : score()->systems()) {
1121 0 : buildAndAddPolylinesForSystem(system);
1122 : }
1123 :
1124 0 : updatePolylinesGeometry();
1125 : }
1126 :
1127 0 : void NotationAutomationController::rebuildPolylinePoints(const PolylineKey& key)
1128 : {
1129 0 : const PolylineData data = polylineData(key);
1130 0 : PolylinePlot* polyline = data.polyline;
1131 0 : IF_ASSERT_FAILED(key.isValid() && polyline) {
1132 0 : return;
1133 : }
1134 :
1135 0 : const Staff* staff = score() ? score()->staff(key.staffIdx) : nullptr;
1136 0 : const muse::RectF regionRect = staff ? regionCanvasRect(key.system, key.staffIdx, data.startMeasure, data.endMeasure) : muse::RectF();
1137 0 : IF_ASSERT_FAILED(staff && regionRect.isValid()) {
1138 0 : return;
1139 : }
1140 :
1141 : //! NOTE: A polyline only holds the points inside its own region. Whatever lies outside it (which can still affect
1142 : //! the polyline) is covered by the edge values...
1143 0 : const QVector<PointData> pointsData = pointsDataInStaffRegion(staff, regionRect, data.startMeasure->tick().ticks(),
1144 0 : regionLastTick(data.endMeasure));
1145 0 : setPolylinePointsData(key, pointsData);
1146 :
1147 0 : QVector<QPointF> points;
1148 0 : points.reserve(pointsData.size());
1149 0 : for (const PointData& pointData : pointsData) {
1150 0 : points.push_back(pointData.qPointF);
1151 : }
1152 0 : polyline->setPoints(points);
1153 :
1154 0 : applyPolylineEdgeValues(polyline, key);
1155 0 : applyPolylineColorsUnderLine(polyline, key);
1156 0 : polyline->update();
1157 0 : }
1158 :
1159 0 : void NotationAutomationController::mergePendingChanges(const mu::engraving::AutomationChanges& changes)
1160 : {
1161 0 : if (changes.isFullReset) {
1162 0 : m_pendingChanges.isFullReset = true;
1163 0 : return;
1164 : }
1165 0 : for (const mu::engraving::AutomationCurveKey& key : changes.affectedKeys) {
1166 0 : m_pendingChanges.extend(key, changes.tickFrom, changes.tickTo);
1167 : }
1168 : }
1169 :
1170 0 : void NotationAutomationController::applyAutomationChanges(const mu::engraving::AutomationChanges& changes)
1171 : {
1172 0 : if (changes.isFullReset || !score()) {
1173 0 : rebuildAllPolylines();
1174 0 : return;
1175 : }
1176 :
1177 0 : IF_ASSERT_FAILED(automationData()) {
1178 0 : return;
1179 : }
1180 :
1181 0 : std::set<muse::ID> affectedStaffIds;
1182 0 : std::set<mu::engraving::InstrumentTrackId> affectedTrackIds;
1183 0 : bool globalAffected = false;
1184 0 : for (const mu::engraving::AutomationCurveKey& key : changes.affectedKeys) {
1185 0 : if (const std::optional<muse::ID> staffId = key.staffId()) {
1186 0 : affectedStaffIds.insert(*staffId);
1187 0 : } else if (const std::optional<mu::engraving::InstrumentTrackId> trackId = key.trackId()) {
1188 0 : affectedTrackIds.insert(*trackId);
1189 0 : } else if (key.isGlobal()) {
1190 0 : globalAffected = true;
1191 0 : }
1192 : }
1193 :
1194 : //! NOTE: A change can affect any polyline of an affected staff, even ones in other systems (the line between the
1195 : //! changed points and the points either side of them can span many regions), so they're all rebuilt...
1196 0 : for (const auto& [key, data] : m_polylinesDataMap) {
1197 0 : IF_ASSERT_FAILED(key.isValid()) {
1198 0 : continue;
1199 : }
1200 0 : const Staff* staff = score()->staff(key.staffIdx);
1201 0 : if (!staff) {
1202 0 : continue;
1203 : }
1204 0 : const bool staffAffected = affectedStaffIds.find(staff->id()) != affectedStaffIds.end();
1205 0 : const mu::engraving::InstrumentTrackId staffTrackId { staff->part()->id(), staff->part()->instrumentId() };
1206 0 : const bool trackAffected = affectedTrackIds.find(staffTrackId) != affectedTrackIds.end();
1207 0 : const bool globalCurveAffected = globalAffected && currentCurveKey(staff).isGlobal();
1208 0 : if (staffAffected || trackAffected || globalCurveAffected) {
1209 0 : rebuildPolylinePoints(key);
1210 : }
1211 0 : }
1212 :
1213 0 : updatePolylinesGeometry();
1214 0 : }
1215 :
1216 0 : bool NotationAutomationController::requestEditPoint(const PointData& oldPointData, const PolylineKey& key, qreal x, qreal y)
1217 : {
1218 : // STEP 1 - Check that all of our parameters are valid...
1219 0 : const PointData::PointType pointType = oldPointData.pointType;
1220 0 : IF_ASSERT_FAILED(key.isValid() && pointType != PointData::PointType::UNKNOWN) {
1221 0 : return false;
1222 : }
1223 0 : const Staff* staff = score() ? score()->staff(key.staffIdx) : nullptr;
1224 0 : IF_ASSERT_FAILED(staff) {
1225 0 : return false;
1226 : }
1227 :
1228 0 : const PolylineData data = polylineData(key);
1229 0 : IF_ASSERT_FAILED(data.polyline) {
1230 0 : return false;
1231 : }
1232 :
1233 : // STEP 2 - Determine the new tick value based on the x parameter...
1234 0 : const int resolvedTick = tickFromXInPolyline(key, data, x);
1235 0 : const int newTick = resolvedTick != -1 ? resolvedTick : oldPointData.tick;
1236 0 : const bool tickChanged = newTick != oldPointData.tick;
1237 :
1238 : // STEP 3 - Fetch the point being edited...
1239 0 : const mu::engraving::AutomationCurveKey curveKey = currentCurveKey(staff);
1240 :
1241 0 : const mu::engraving::AutomationCurve& curve = automationData()->curve(curveKey);
1242 0 : const auto existingIt = curve.find(oldPointData.tick);
1243 0 : IF_ASSERT_FAILED(existingIt != curve.end()) {
1244 0 : return false;
1245 : }
1246 0 : const mu::engraving::AutomationPoint& existingPoint = existingIt->second;
1247 0 : const mu::engraving::real_t existingInValue = mu::engraving::resolveInValue(curve, existingIt);
1248 :
1249 : //! NOTE: Point in/out values are rescaled to the display range - higher value == lower Y...
1250 0 : const mu::engraving::real_t referenceValue = pointType == PointData::PointType::IN ? existingInValue : existingPoint.value.outValue;
1251 0 : const mu::engraving::real_t newValue = automationValueFromDisplay(currentAutomationType(), staff, newTick, 1.0 - y, referenceValue);
1252 :
1253 : // STEP 4 - Update the point's value, and move it to the new tick if necessary...
1254 :
1255 : //! NOTE: Moving a BOTH point is the simplest case - we can update its value then simply change the tick.
1256 : //! Moving IN/OUT points is slightly more complex. In this case we need to set the in/out values to be
1257 : //! equal at oldTick (effectively converting the original point to a BOTH point) and create a new point
1258 : //! at newTick...
1259 :
1260 0 : if (!tickChanged || pointType == PointData::PointType::BOTH) {
1261 0 : mu::engraving::AutomationPoint editedPoint = existingPoint;
1262 : const mu::engraving::AutomationPoint::Ease preservedEase
1263 0 : = mu::engraving::ease(editedPoint).value_or(mu::engraving::AutomationPoint::Ease::none());
1264 0 : if (pointType == PointData::PointType::IN) {
1265 : // The user explicitly chose this arrival value; it no longer follows whatever precedes it
1266 0 : editedPoint.value.inValue = mu::engraving::AutomationPoint::ExplicitArrival { newValue, preservedEase };
1267 0 : } else if (pointType == PointData::PointType::BOTH) {
1268 0 : editedPoint.value.outValue = newValue;
1269 0 : editedPoint.value.inValue = mu::engraving::AutomationPoint::ExplicitArrival { editedPoint.value.outValue, preservedEase };
1270 : } else {
1271 0 : editedPoint.value.outValue = newValue;
1272 : }
1273 0 : editedPoint.generated = false;
1274 :
1275 : mu::engraving::AutomationPointEdits edits {
1276 0 : { newTick, MovePoint { editedPoint, oldPointData.tick } }
1277 0 : };
1278 :
1279 0 : editAutomationPoints(curveKey, edits);
1280 :
1281 0 : return true;
1282 0 : }
1283 :
1284 : // oldTick becomes a flat BOTH point, so its inValue is frozen to outValue at edit time (it no
1285 : // longer live-tracks outValue if it's edited again later)
1286 : const mu::engraving::AutomationPoint::Ease originalEase
1287 0 : = mu::engraving::ease(existingPoint).value_or(mu::engraving::AutomationPoint::Ease::none());
1288 :
1289 0 : mu::engraving::AutomationPoint updatedOldPoint = existingPoint;
1290 0 : if (pointType == PointData::PointType::OUT) {
1291 0 : updatedOldPoint.value.outValue = existingInValue;
1292 : }
1293 0 : updatedOldPoint.value.inValue = mu::engraving::AutomationPoint::ExplicitArrival { updatedOldPoint.value.outValue, originalEase };
1294 0 : updatedOldPoint.generated = false;
1295 :
1296 0 : mu::engraving::AutomationPoint newPoint;
1297 0 : newPoint.value.outValue = newValue;
1298 0 : newPoint.value.inValue = mu::engraving::AutomationPoint::ExplicitArrival { newPoint.value.outValue, originalEase };
1299 0 : newPoint.itemId = existingPoint.itemId;
1300 :
1301 : mu::engraving::AutomationPointEdits edits {
1302 0 : { oldPointData.tick, SetPoint { updatedOldPoint } },
1303 0 : { newTick, SetPoint { newPoint } }
1304 0 : };
1305 :
1306 0 : editAutomationPoints(curveKey, edits);
1307 :
1308 0 : return true;
1309 0 : }
1310 :
1311 0 : bool NotationAutomationController::requestAddPoint(const PolylineKey& key, qreal x, qreal y, bool useCurveValue)
1312 : {
1313 0 : IF_ASSERT_FAILED(key.isValid()) {
1314 0 : return false;
1315 : }
1316 :
1317 0 : const Staff* staff = score() ? score()->staff(key.staffIdx) : nullptr;
1318 0 : IF_ASSERT_FAILED(staff) {
1319 0 : return false;
1320 : }
1321 :
1322 0 : const PolylineData data = polylineData(key);
1323 0 : IF_ASSERT_FAILED(data.polyline) {
1324 0 : return false;
1325 : }
1326 :
1327 : //! NOTE: No need to clamp x here - tickFromXInPolyline can't resolve to a tick outside the region...
1328 0 : const int newTick = tickFromXInPolyline(key, data, x);
1329 0 : if (newTick == -1) {
1330 0 : return false;
1331 : }
1332 :
1333 0 : const mu::engraving::AutomationCurveKey curveKey = currentCurveKey(staff);
1334 0 : const mu::engraving::AutomationCurve& curve = automationData()->curve(curveKey);
1335 :
1336 : //! A click lands on the drawn line, which may be clamped, so keep the curve's own value. A dragged point
1337 : //! is placed wherever the user dropped it, so its y is used instead...
1338 0 : const std::optional<muse::real_t> curveValue = useCurveValue ? mu::engraving::evaluateCurveAt(curve, newTick) : std::nullopt;
1339 :
1340 0 : mu::engraving::AutomationPoint newPoint;
1341 0 : newPoint.value.outValue = curveValue ? *curveValue
1342 0 : : automationValueFromDisplay(currentAutomationType(), staff, newTick, 1.0 - y);
1343 0 : newPoint.value.inValue = mu::engraving::AutomationPoint::ExplicitArrival { newPoint.value.outValue,
1344 0 : mu::engraving::AutomationPoint::Ease::none() };
1345 0 : newPoint.generated = false;
1346 :
1347 : mu::engraving::AutomationPointEdits edits {
1348 0 : { newTick, SetPoint { newPoint } }
1349 0 : };
1350 :
1351 0 : editAutomationPoints(curveKey, edits);
1352 :
1353 0 : return true;
1354 0 : }
1355 :
1356 0 : bool NotationAutomationController::requestRemovePoint(const PointData& pointData, const PolylineKey& key)
1357 : {
1358 0 : IF_ASSERT_FAILED(key.isValid()) {
1359 0 : return false;
1360 : }
1361 :
1362 0 : const mu::engraving::AutomationPoint* automationPoint = automationPointAt(key, pointData.tick);
1363 0 : if (!automationPoint || automationPoint->generated || automationPoint->itemId.has_value()) {
1364 0 : return false;
1365 : }
1366 :
1367 0 : const Staff* staff = score() ? score()->staff(key.staffIdx) : nullptr;
1368 0 : IF_ASSERT_FAILED(staff) {
1369 0 : return false;
1370 : }
1371 :
1372 0 : const mu::engraving::AutomationCurveKey curveKey = currentCurveKey(staff);
1373 :
1374 : mu::engraving::AutomationPointEdits edits {
1375 0 : { pointData.tick, ErasePoint {} }
1376 0 : };
1377 :
1378 0 : editAutomationPoints(curveKey, edits);
1379 :
1380 0 : return true;
1381 0 : }
1382 :
1383 0 : void NotationAutomationController::editAutomationPoints(const mu::engraving::AutomationCurveKey& key,
1384 : mu::engraving::AutomationPointEdits& edits)
1385 : {
1386 0 : const INotationAutomationPtr notationAutomation = automation();
1387 0 : IF_ASSERT_FAILED(notationAutomation) {
1388 0 : return;
1389 : }
1390 :
1391 0 : notationAutomation->editPoints(key, edits);
1392 0 : }
1393 :
1394 0 : NotationAutomationController::PolylineData NotationAutomationController::polylineData(const PolylineKey& key) const
1395 : {
1396 0 : const auto it = m_polylinesDataMap.find(key);
1397 0 : IF_ASSERT_FAILED(it != m_polylinesDataMap.end()) {
1398 0 : return PolylineData();
1399 : }
1400 :
1401 0 : return it->second;
1402 : }
1403 :
1404 0 : void NotationAutomationController::setPolylinePointsData(const PolylineKey& key, const QVector<PointData>& pointsData)
1405 : {
1406 0 : const auto it = m_polylinesDataMap.find(key);
1407 0 : IF_ASSERT_FAILED(it != m_polylinesDataMap.end()) {
1408 0 : return;
1409 : }
1410 :
1411 0 : it->second.pointsData = pointsData;
1412 : }
1413 :
1414 0 : const mu::engraving::AutomationPoint* NotationAutomationController::automationPointAt(const PolylineKey& key, int tick) const
1415 : {
1416 0 : const Staff* staff = score() ? score()->staff(key.staffIdx) : nullptr;
1417 0 : IF_ASSERT_FAILED(staff && automationData()) {
1418 0 : return nullptr;
1419 : }
1420 :
1421 0 : const mu::engraving::AutomationCurveKey curveKey = currentCurveKey(staff);
1422 0 : const mu::engraving::AutomationCurve& curve = automationData()->curve(curveKey);
1423 0 : const auto it = curve.find(tick);
1424 0 : if (it == curve.end()) {
1425 0 : return nullptr;
1426 : }
1427 :
1428 0 : return &it->second;
1429 0 : }
1430 :
1431 0 : const DynamicsDisplayRange& NotationAutomationController::dynamicsDisplayRange(const Staff* staff, int tick) const
1432 : {
1433 0 : const project::INotationProjectPtr notationProject = projectSession()->project();
1434 0 : const project::IProjectAudioSettingsPtr settings = notationProject ? notationProject->audioSettings() : nullptr;
1435 0 : const Part* part = staff ? staff->part() : nullptr;
1436 0 : if (!settings || !part) {
1437 0 : return DEFAULT_DYNAMICS_RANGE;
1438 : }
1439 :
1440 0 : const InstrumentTrackId trackId { part->id(), part->instrumentId(Fraction::fromTicks(tick)) };
1441 0 : const bool isMuseSampler = muse::audio::isResourceType(settings->trackInputParams(trackId).resourceMeta,
1442 : muse::audio::AudioResourceType::MuseSamplerSoundPack);
1443 :
1444 0 : return isMuseSampler ? MUSE_SAMPLER_DYNAMICS_RANGE : DEFAULT_DYNAMICS_RANGE;
1445 0 : }
1446 :
1447 : // Values are stored normalized [0, 1]; Dynamics rescales that into its own sub-range for display,
1448 : // Volume and Tempo additionally apply a fader curve, other types map 1:1 onto the display range
1449 0 : double NotationAutomationController::automationValueToDisplay(AutomationType type, const Staff* staff, int tick,
1450 : muse::real_t value) const
1451 : {
1452 0 : if (type == AutomationType::Dynamics) {
1453 0 : return dynamicsValueToDisplay(value, dynamicsDisplayRange(staff, tick));
1454 : }
1455 :
1456 0 : if (type == AutomationType::Volume) {
1457 0 : return volumeValueToDisplay(value);
1458 : }
1459 :
1460 0 : if (type == AutomationType::Tempo) {
1461 0 : const double logicalBpm = mu::engraving::denormalizeTempo(value).toBPM().val;
1462 0 : const double localBpm = tempoLogicalBpmToLocalBpm(logicalBpm);
1463 0 : const double display = localBpm / TEMPO_RANGE_MAX_BPM;
1464 0 : return std::clamp(display, 0.0, 1.0);
1465 : }
1466 :
1467 0 : return std::clamp(static_cast<double>(value), 0.0, 1.0);
1468 : }
1469 :
1470 : // existingValue preserves values beyond the display range when the drag lands back at the same clamped edge
1471 0 : muse::real_t NotationAutomationController::automationValueFromDisplay(AutomationType type, const Staff* staff, int tick,
1472 : double displayValue,
1473 : std::optional<muse::real_t> existingValue) const
1474 : {
1475 0 : if (type == AutomationType::Dynamics) {
1476 0 : const DynamicsDisplayRange& dynamicsRange = dynamicsDisplayRange(staff, tick);
1477 0 : if (existingValue) {
1478 0 : const double existingDisplay = dynamicsValueToDisplay(*existingValue, dynamicsRange);
1479 0 : const bool atTop = muse::RealIsEqualOrMore(displayValue, 1.0) && muse::RealIsEqualOrMore(existingDisplay, 1.0);
1480 0 : const bool atBottom = muse::RealIsEqualOrLess(displayValue, 0.0) && muse::RealIsEqualOrLess(existingDisplay, 0.0);
1481 0 : if (atTop || atBottom) {
1482 0 : return *existingValue;
1483 : }
1484 : }
1485 :
1486 0 : return dynamicsValueFromDisplay(displayValue, dynamicsRange);
1487 : }
1488 :
1489 0 : if (type == AutomationType::Volume) {
1490 0 : const double localDb = VOLUME_RANGE_MIN_DB + displayValue * (VOLUME_RANGE_MAX_DB - VOLUME_RANGE_MIN_DB);
1491 0 : const double logicalDb = volumeLocalDbToLogicalDb(localDb);
1492 0 : const double normalized = (logicalDb - VOLUME_RANGE_MIN_DB) / (VOLUME_RANGE_MAX_DB - VOLUME_RANGE_MIN_DB);
1493 0 : return muse::real_t(normalized);
1494 : }
1495 :
1496 0 : if (type == AutomationType::Tempo) {
1497 0 : if (existingValue && muse::RealIsEqualOrMore(displayValue, 1.0)
1498 0 : && muse::RealIsEqualOrMore(automationValueToDisplay(type, staff, tick, *existingValue), 1.0)) {
1499 0 : return *existingValue;
1500 : }
1501 :
1502 0 : const double localBpm = displayValue * TEMPO_RANGE_MAX_BPM;
1503 0 : const double logicalBpm = tempoLocalBpmToLogicalBpm(localBpm);
1504 0 : const muse::real_t normalized = mu::engraving::normalizeTempo(mu::engraving::BeatsPerSecond::fromBPM(logicalBpm));
1505 0 : return std::clamp(normalized, mu::engraving::MIN_NORMALIZED_TEMPO, mu::engraving::MAX_NORMALIZED_TEMPO);
1506 : }
1507 :
1508 0 : return muse::real_t(displayValue);
1509 : }
1510 :
1511 0 : AutomationType NotationAutomationController::currentAutomationType() const
1512 : {
1513 0 : return automationTypeOf(notationConfiguration()->currentAutomationLane());
1514 : }
1515 :
1516 0 : AutomationCurveKey NotationAutomationController::currentCurveKey(const Staff* staff) const
1517 : {
1518 0 : return curveKeyFor(notationConfiguration()->currentAutomationLane(), staff);
1519 : }
1520 :
1521 0 : INotationAutomationPtr NotationAutomationController::automation() const
1522 : {
1523 0 : const IMasterNotationPtr masterNotation = projectSession()->masterNotation();
1524 0 : return masterNotation ? masterNotation->automation() : nullptr;
1525 0 : }
1526 :
1527 0 : INotationPtr NotationAutomationController::currentNotation() const
1528 : {
1529 0 : return projectSession()->currentNotation();
1530 : }
1531 :
1532 0 : mu::engraving::AutomationDataConstPtr NotationAutomationController::automationData() const
1533 : {
1534 0 : const INotationAutomationPtr notationAutomation = automation();
1535 0 : return notationAutomation ? notationAutomation->automationData() : nullptr;
1536 0 : }
1537 :
1538 0 : mu::engraving::Score* NotationAutomationController::score() const
1539 : {
1540 0 : return currentNotation() ? currentNotation()->elements()->msScore() : nullptr;
1541 : }
|