AutomationUi.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. #include "ui/WindowOwner.h"
  2. #include "ui/AutomationUi.h"
  3. #include <map>
  4. #include "core/Effects.h"
  5. #include "core/MidiControls.h"
  6. #include "core/FlSynths.h"
  7. #include "engine/Text.h"
  8. #include "core/EditorGestures.h"
  9. #include "ui/EditorTools.h"
  10. #include "ui/EventEditor.h"
  11. #include "ui/I18n.h"
  12. #include "ui/Theme.h"
  13. #include "ui/ValueControl.h"
  14. namespace lynx
  15. {
  16. namespace
  17. {
  18. juce::String nameOf (const std::string& s)
  19. {
  20. return juce::String::fromUTF8 (s.c_str());
  21. }
  22. juce::AudioPluginInstance* pluginFor (AudioEngine& engine, const AutomationTarget& t)
  23. {
  24. if (t.kind == AutomationTargetKind::channelParam)
  25. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (t.index).get()))
  26. return &p->getInstance();
  27. if (t.kind == AutomationTargetKind::effectParam)
  28. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (t.index, t.slot).get()))
  29. return &p->getInstance();
  30. return nullptr;
  31. }
  32. // The CC / aftertouch / pitch bend value the plugin was last sent (or the controller's rest value).
  33. float midiControlValue (AudioEngine& engine, const AutomationTarget& t)
  34. {
  35. if (t.kind == AutomationTargetKind::channelParam)
  36. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (t.index).get()))
  37. return p->midiControlValue (t.param);
  38. if (t.kind == AutomationTargetKind::effectParam)
  39. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (t.index, t.slot).get()))
  40. return p->midiControlValue (t.param);
  41. return midictl::defaultValue (t.param);
  42. }
  43. // Point editor: time horizontal (bars), value vertical.
  44. // - click on empty space creates a point; drag moves; right-click deletes
  45. // - Alt+drag over a segment changes the curve (tension)
  46. // - Ctrl+wheel zooms at the mouse; wheel scrolls; middle-drag pans
  47. // - the cursor and the hint bar show what a click would do
  48. class AutomationEditor final : public juce::Component,
  49. public ui::HintSource,
  50. private juce::ChangeListener,
  51. private juce::Timer
  52. {
  53. public:
  54. AutomationEditor (AudioEngine& e, int index)
  55. : engine (e),
  56. automation (index)
  57. {
  58. engine.addChangeListener (this);
  59. setSize (760, 300);
  60. startTimerHz (30);
  61. }
  62. ~AutomationEditor() override { engine.removeChangeListener (this); }
  63. int getIndex() const noexcept { return automation; }
  64. void paint (juce::Graphics& g) override
  65. {
  66. using namespace theme;
  67. g.fillAll (colour::bg1);
  68. const auto* a = current();
  69. if (a == nullptr)
  70. return;
  71. const auto& song = engine.getSong();
  72. const auto area = plotArea();
  73. const auto bar = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar);
  74. g.setColour (colour::bg0);
  75. g.fillRect (area);
  76. // grid: beats and bars
  77. const auto beatPixels = ppq * pixelsPerTick;
  78. const auto lastTick = (std::int64_t) xToTick (area.getRight());
  79. for (auto tick = (std::int64_t) std::floor (scroll / ppq) * ppq; tick <= lastTick; tick += ppq)
  80. {
  81. const auto isBar = tick % bar == 0;
  82. if (! isBar && beatPixels < 8.0)
  83. continue;
  84. const auto x = (int) tickToX ((double) tick);
  85. g.setColour (isBar ? colour::gridBar : colour::gridBeat);
  86. g.drawVerticalLine (x, (float) area.getY(), (float) area.getBottom());
  87. if (isBar)
  88. {
  89. g.setColour (colour::textSecondary);
  90. g.setFont (font (type::caption));
  91. g.drawText (juce::String (tick / bar + 1), x + 3, 2, 40, 16, juce::Justification::centredLeft);
  92. }
  93. }
  94. for (auto v : { 0.25f, 0.5f, 0.75f })
  95. {
  96. g.setColour (colour::gridStep.brighter (0.15f));
  97. g.drawHorizontalLine ((int) valueToY (v), (float) area.getX(), (float) area.getRight());
  98. }
  99. // curve
  100. juce::Path curve;
  101. const auto& points = a->points;
  102. for (auto x = area.getX(); x <= area.getRight(); x += 2)
  103. {
  104. const auto y = valueToY (a->valueAt (xToTick (x)));
  105. if (x == area.getX())
  106. curve.startNewSubPath ((float) x, y);
  107. else
  108. curve.lineTo ((float) x, y);
  109. }
  110. // soft fill under the curve, then the line
  111. auto fill = curve;
  112. fill.lineTo ((float) area.getRight(), (float) area.getBottom());
  113. fill.lineTo ((float) area.getX(), (float) area.getBottom());
  114. fill.closeSubPath();
  115. g.setColour (colour::automation.withAlpha (0.10f));
  116. g.fillPath (fill);
  117. g.setColour (colour::automation);
  118. g.strokePath (curve, juce::PathStrokeType (2.0f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  119. for (std::size_t i = 0; i < points.size(); ++i)
  120. {
  121. const auto p = pointPosition (points[i]);
  122. const auto active = (int) i == hoverPoint || (int) i == dragPoint;
  123. g.setColour (colour::bg0);
  124. g.fillEllipse (p.x - 6.0f, p.y - 6.0f, 12.0f, 12.0f);
  125. g.setColour (active ? colour::textPrimary : colour::automation);
  126. g.fillEllipse (p.x - 4.5f, p.y - 4.5f, 9.0f, 9.0f);
  127. }
  128. // playback cursor (at the position of the clip currently playing)
  129. if (playhead >= 0.0)
  130. {
  131. g.setColour (colour::playhead);
  132. g.drawVerticalLine ((int) tickToX (playhead), (float) area.getY(), (float) area.getBottom());
  133. }
  134. if (hoverPoint >= 0 && hoverPoint < (int) points.size())
  135. {
  136. const auto p = pointPosition (points[(std::size_t) hoverPoint]);
  137. g.setColour (colour::textPrimary);
  138. g.setFont (font (type::small));
  139. const auto value = points[(std::size_t) hoverPoint].value;
  140. g.drawText (a->target.kind == AutomationTargetKind::tempo ? juce::String (tempoFromValue (value), 1) + " BPM"
  141. : juce::String (juce::roundToInt (value * 100.0f)) + "%",
  142. (int) p.x + 8, (int) p.y - 18, 60, 14, juce::Justification::centredLeft);
  143. }
  144. }
  145. void mouseMove (const juce::MouseEvent& e) override
  146. {
  147. const auto hit = pointAt (e.position);
  148. if (hit != hoverPoint)
  149. {
  150. hoverPoint = hit;
  151. repaint();
  152. }
  153. updateCursor (e.mods);
  154. }
  155. void modifierKeysChanged (const juce::ModifierKeys& mods) override
  156. {
  157. if (dragPoint < 0 && tensionPoint < 0 && ! panning)
  158. updateCursor (mods);
  159. }
  160. void updateCursor (juce::ModifierKeys mods)
  161. {
  162. using C = gesture::Cursor;
  163. const auto inPlot = plotArea().contains (getMouseXYRelative());
  164. if (inPlot && mods.isAltDown())
  165. setMouseCursor (juce::MouseCursor::UpDownResizeCursor); // drag up / down bends the segment
  166. else
  167. setMouseCursor (editorCursor (! inPlot ? C::normal : hoverPoint >= 0 ? C::move : C::draw));
  168. }
  169. ui::Hint hintAt (juce::Point<int> position) override
  170. {
  171. ui::Hint hint;
  172. if (! plotArea().contains (position))
  173. return hint;
  174. const auto* a = current();
  175. const auto point = pointAt (position.toFloat());
  176. hint.hasMenu = true;
  177. if (juce::ModifierKeys::currentModifiers.isAltDown())
  178. hint.text = tr ("[Alt][LMB] drag up / down bends this segment");
  179. else if (point >= 0)
  180. hint.text = tr ("Point: [LMB] drag moves, then [Shift] keeps time, [Ctrl] keeps value [RMB] menu");
  181. else
  182. hint.text = tr ("[LMB] new point [Shift][RMB] point on the curve [Alt][LMB] bend [Ctrl][Wheel] zoom [MMB] scroll");
  183. if (a != nullptr)
  184. hint.value = valueText (point >= 0 ? a->points[(std::size_t) point].value : yToValue (position.y));
  185. return hint;
  186. }
  187. void mouseDown (const juce::MouseEvent& e) override
  188. {
  189. const auto* a = current();
  190. if (a == nullptr || ! plotArea().contains (e.getPosition()))
  191. return;
  192. const auto hit = pointAt (e.position);
  193. downMods = e.mods;
  194. if (e.mods.isMiddleButtonDown()) // middle-drag scrolls
  195. {
  196. panning = true;
  197. panStart = scroll;
  198. setMouseCursor (editorCursor (gesture::Cursor::pan));
  199. return;
  200. }
  201. if (e.mods.isPopupMenu())
  202. {
  203. if (e.mods.isShiftDown() && hit < 0) // a point on the curve, keeping its level
  204. {
  205. AutomationPoint p;
  206. p.tick = snap (xToTick (e.x), true);
  207. p.value = a->valueAt ((double) p.tick);
  208. edit ([p] (Automation& x) {
  209. x.points.push_back (p);
  210. std::stable_sort (x.points.begin(), x.points.end(), [] (auto& l, auto& r) { return l.tick < r.tick; });
  211. });
  212. return;
  213. }
  214. if (hit >= 0)
  215. showPointMenu (hit);
  216. else
  217. showCurveMenu();
  218. return;
  219. }
  220. if (e.mods.isAltDown())
  221. {
  222. // segment under the mouse: the point on the left holds the tension
  223. tensionPoint = -1;
  224. const auto tick = xToTick (e.x);
  225. for (int i = 0; i + 1 < (int) a->points.size(); ++i)
  226. if (tick >= (double) a->points[(std::size_t) i].tick && tick < (double) a->points[(std::size_t) i + 1].tick)
  227. tensionPoint = i;
  228. if (tensionPoint >= 0)
  229. tensionStart = a->points[(std::size_t) tensionPoint].tension;
  230. return;
  231. }
  232. if (hit >= 0)
  233. {
  234. dragPoint = hit;
  235. return;
  236. }
  237. AutomationPoint p;
  238. p.tick = snap (xToTick (e.x), ! e.mods.isShiftDown());
  239. p.value = yToValue (e.y);
  240. edit ([p] (Automation& x) {
  241. x.points.push_back (p);
  242. std::stable_sort (x.points.begin(), x.points.end(), [] (auto& l, auto& r) { return l.tick < r.tick; });
  243. });
  244. for (int i = 0; i < (int) current()->points.size(); ++i)
  245. if (current()->points[(std::size_t) i].tick == p.tick && current()->points[(std::size_t) i].value == p.value)
  246. dragPoint = i;
  247. }
  248. void mouseDrag (const juce::MouseEvent& e) override
  249. {
  250. const auto* a = current();
  251. if (a == nullptr)
  252. return;
  253. if (panning)
  254. {
  255. scroll = juce::jmax (0.0, panStart - e.getDistanceFromDragStartX() / pixelsPerTick);
  256. repaint();
  257. return;
  258. }
  259. if (tensionPoint >= 0 && tensionPoint < (int) a->points.size())
  260. {
  261. const auto tension = juce::jlimit (-1.0f, 1.0f, tensionStart + (float) e.getDistanceFromDragStartY() / 100.0f);
  262. edit ([i = tensionPoint, tension] (Automation& x) { x.points[(std::size_t) i].tension = tension; });
  263. return;
  264. }
  265. if (dragPoint < 0 || dragPoint >= (int) a->points.size())
  266. return;
  267. // the point can't pass its neighbours (order doesn't change while dragging)
  268. const auto& points = a->points;
  269. auto tick = snap (xToTick (e.x), ! e.mods.isShiftDown());
  270. const auto lo = dragPoint > 0 ? points[(std::size_t) dragPoint - 1].tick : 0;
  271. const auto hi = dragPoint + 1 < (int) points.size() ? points[(std::size_t) dragPoint + 1].tick : std::numeric_limits<std::int64_t>::max();
  272. tick = juce::jlimit (lo, hi, tick);
  273. auto value = yToValue (e.y);
  274. // locks: Shift pressed after the click keeps the time, Ctrl keeps the value
  275. if (e.mods.isShiftDown() && ! downMods.isShiftDown())
  276. tick = points[(std::size_t) dragPoint].tick;
  277. if (e.mods.isCtrlDown() && ! downMods.isCtrlDown())
  278. value = points[(std::size_t) dragPoint].value;
  279. edit ([i = dragPoint, tick, value] (Automation& x) {
  280. x.points[(std::size_t) i].tick = tick;
  281. x.points[(std::size_t) i].value = value;
  282. });
  283. }
  284. void mouseUp (const juce::MouseEvent& e) override
  285. {
  286. dragPoint = tensionPoint = -1;
  287. panning = false;
  288. updateCursor (e.mods);
  289. repaint();
  290. }
  291. void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel) override
  292. {
  293. if (e.mods.isCtrlDown())
  294. {
  295. const auto anchor = xToTick (e.x);
  296. juce::ignoreUnused (anchor);
  297. const auto zoomed = juce::jlimit (4.0 / (4 * ppq), 600.0 / (4 * ppq), pixelsPerTick * gesture::wheelZoomFactor (wheel.deltaY, wheel.isSmooth));
  298. scroll = gesture::zoomAnchored (scroll, pixelsPerTick, zoomed, (double) juce::jmax (0, e.x - plotArea().getX()));
  299. pixelsPerTick = zoomed;
  300. }
  301. else
  302. scroll = juce::jmax (0.0, scroll - (wheel.deltaY + wheel.deltaX) * 300.0 / pixelsPerTick);
  303. repaint();
  304. }
  305. private:
  306. juce::ModifierKeys downMods;
  307. static inline float copiedValue = -1.0f;
  308. juce::String valueText (float v) const
  309. {
  310. const auto* a = current();
  311. return a != nullptr && a->target.kind == AutomationTargetKind::tempo ? juce::String (tempoFromValue (v), 2) + " BPM"
  312. : juce::String (v * 100.0f, 1) + "%";
  313. }
  314. void showPointMenu (int point)
  315. {
  316. const auto* a = current();
  317. const auto value = a->points[(std::size_t) point].value;
  318. juce::PopupMenu menu;
  319. menu.addSectionHeader (valueText (value));
  320. menu.addItem (tr ("Type value..."), [this, point] { typeValue (point); });
  321. menu.addItem (tr ("Copy value"), [value] { copiedValue = value; });
  322. menu.addItem (tr ("Paste value"), copiedValue >= 0.0f, false, [this, point] {
  323. edit ([point, v = copiedValue] (Automation& x) {
  324. if (point < (int) x.points.size())
  325. x.points[(std::size_t) point].value = v;
  326. });
  327. });
  328. menu.addItem (tr ("Straight segment (reset the curve)"), [this, point] {
  329. edit ([point] (Automation& x) {
  330. if (point < (int) x.points.size())
  331. x.points[(std::size_t) point].tension = 0.0f;
  332. });
  333. });
  334. menu.addSeparator();
  335. menu.addItem (tr ("Delete point"), a->points.size() > 1, false, [this, point] {
  336. edit ([point] (Automation& x) {
  337. if (point < (int) x.points.size() && x.points.size() > 1)
  338. x.points.erase (x.points.begin() + point);
  339. });
  340. });
  341. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  342. }
  343. void typeValue (int point)
  344. {
  345. const auto* a = current();
  346. const auto tempo = a->target.kind == AutomationTargetKind::tempo;
  347. const auto value = a->points[(std::size_t) point].value;
  348. auto* window = new juce::AlertWindow (tr ("Point value"), tempo ? tr ("BPM") : tr ("Percent (0 to 100)"), juce::MessageBoxIconType::NoIcon);
  349. window->addTextEditor ("value", tempo ? juce::String (tempoFromValue (value), 2) : juce::String (value * 100.0f, 1));
  350. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  351. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  352. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, point, tempo, window] (int result) {
  353. if (result != 1)
  354. return;
  355. const auto typed = window->getTextEditorContents ("value").retainCharacters ("0123456789.,-").replaceCharacter (',', '.').getDoubleValue();
  356. const auto v = juce::jlimit (0.0f, 1.0f, tempo ? valueFromTempo (typed) : (float) typed / 100.0f);
  357. edit ([point, v] (Automation& x) {
  358. if (point < (int) x.points.size())
  359. x.points[(std::size_t) point].value = v;
  360. });
  361. }),
  362. true);
  363. }
  364. void showCurveMenu()
  365. {
  366. juce::PopupMenu menu;
  367. menu.addItem (tr ("Scale the values into a range..."), [this] { rerange(); });
  368. menu.addItem (tr ("Flip the values upside down"), [this] {
  369. edit ([] (Automation& x) {
  370. for (auto& p : x.points)
  371. p.value = 1.0f - p.value;
  372. });
  373. });
  374. menu.addItem (tr ("All segments straight"), [this] {
  375. edit ([] (Automation& x) {
  376. for (auto& p : x.points)
  377. p.tension = 0.0f;
  378. });
  379. });
  380. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  381. }
  382. void rerange()
  383. {
  384. auto* window = new juce::AlertWindow (tr ("Scale the values into a range"), tr ("The lowest point goes to the minimum and the highest to the maximum (percent)."),
  385. juce::MessageBoxIconType::NoIcon);
  386. window->addTextEditor ("min", "0", tr ("Minimum"));
  387. window->addTextEditor ("max", "100", tr ("Maximum"));
  388. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  389. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  390. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  391. if (result != 1)
  392. return;
  393. const auto lo = juce::jlimit (0.0f, 1.0f, window->getTextEditorContents ("min").getFloatValue() / 100.0f);
  394. const auto hi = juce::jlimit (0.0f, 1.0f, window->getTextEditorContents ("max").getFloatValue() / 100.0f);
  395. edit ([lo, hi] (Automation& x) {
  396. if (x.points.empty())
  397. return;
  398. auto [mn, mx] = std::minmax_element (x.points.begin(), x.points.end(), [] (auto& a, auto& b) { return a.value < b.value; });
  399. const auto from = mn->value, span = mx->value - mn->value;
  400. for (auto& p : x.points)
  401. p.value = span > 1e-6f ? lo + (p.value - from) / span * (hi - lo) : lo;
  402. });
  403. }),
  404. true);
  405. }
  406. const Automation* current() const
  407. {
  408. const auto& song = engine.getSong();
  409. return automation >= 0 && automation < (int) song.automations.size() ? &song.automations[(std::size_t) automation] : nullptr;
  410. }
  411. void edit (const std::function<void (Automation&)>& fn)
  412. {
  413. engine.editSong ([this, &fn] (Song& s) {
  414. if (automation >= 0 && automation < (int) s.automations.size())
  415. fn (s.automations[(std::size_t) automation]);
  416. });
  417. }
  418. juce::Rectangle<int> plotArea() const { return getLocalBounds().withTrimmedTop (18).withTrimmedBottom (4).reduced (8, 4); }
  419. double tickToX (double tick) const { return plotArea().getX() + (tick - scroll) * pixelsPerTick; }
  420. double xToTick (int x) const { return juce::jmax (0.0, (x - plotArea().getX()) / pixelsPerTick + scroll); }
  421. float valueToY (float v) const { return (float) plotArea().getBottom() - v * (float) plotArea().getHeight(); }
  422. float yToValue (int y) const { return juce::jlimit (0.0f, 1.0f, (float) (plotArea().getBottom() - y) / (float) plotArea().getHeight()); }
  423. std::int64_t snap (double tick, bool on) const
  424. {
  425. const auto grid = on ? (double) ticksPerStep : 1.0;
  426. return (std::int64_t) std::round (tick / grid) * (std::int64_t) grid;
  427. }
  428. juce::Point<float> pointPosition (const AutomationPoint& p) const { return { (float) tickToX ((double) p.tick), valueToY (p.value) }; }
  429. int pointAt (juce::Point<float> pos) const
  430. {
  431. const auto* a = current();
  432. if (a == nullptr)
  433. return -1;
  434. for (int i = (int) a->points.size() - 1; i >= 0; --i)
  435. if (pointPosition (a->points[(std::size_t) i]).getDistanceFrom (pos) < 8.0f)
  436. return i;
  437. return -1;
  438. }
  439. void changeListenerCallback (juce::ChangeBroadcaster*) override
  440. {
  441. if (current() == nullptr) // automation removed: close
  442. {
  443. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<Component> (getParentComponent())] {
  444. if (auto* w = dynamic_cast<juce::DocumentWindow*> (safe.getComponent()))
  445. w->closeButtonPressed();
  446. });
  447. return;
  448. }
  449. if (auto* w = findParentComponentOfClass<juce::DocumentWindow>())
  450. w->setName (tr ("Automation - {0}", { juce::String::fromUTF8 (current()->name.c_str()) }));
  451. repaint();
  452. }
  453. void timerCallback() override
  454. {
  455. // position within the automation, if one of its clips is under the cursor
  456. auto tick = -1.0;
  457. const auto& song = engine.getSong();
  458. if (song.mode == PlayMode::song && engine.getTransport().playing.load())
  459. {
  460. const auto position = std::fmod (engine.getTransport().positionTicks.load(), (double) juce::jmax<std::int64_t> (1, song.songLength()));
  461. for (const auto& c : song.playlist)
  462. if (c.kind == ClipKind::automation && c.automation == automation && position >= (double) c.start && position < (double) c.end())
  463. tick = position - (double) c.start + (double) c.offset;
  464. }
  465. if (tick != playhead)
  466. {
  467. playhead = tick;
  468. repaint();
  469. }
  470. }
  471. AudioEngine& engine;
  472. int automation;
  473. double pixelsPerTick = 120.0 / (4 * ppq);
  474. double scroll = 0.0;
  475. int dragPoint = -1, hoverPoint = -1, tensionPoint = -1;
  476. bool panning = false;
  477. double panStart = 0.0;
  478. float tensionStart = 0.0f;
  479. double playhead = -1.0;
  480. };
  481. class AutomationWindow final : public juce::DocumentWindow
  482. {
  483. public:
  484. AutomationWindow (AudioEngine& engine, int index, const juce::String& title)
  485. : juce::DocumentWindow (title, theme::colour::bg1, DocumentWindow::closeButton)
  486. {
  487. setUsingNativeTitleBar (true);
  488. setContentOwned (new AutomationEditor (engine, index), true);
  489. setResizable (true, false);
  490. setResizeLimits (400, 200, 4000, 2000);
  491. centreWithSize (getWidth(), getHeight());
  492. setVisible (true);
  493. keepAboveMainWindow (*this);
  494. }
  495. int getIndex() const { return static_cast<AutomationEditor*> (getContentComponent())->getIndex(); }
  496. void closeButtonPressed() override;
  497. };
  498. std::vector<std::unique_ptr<AutomationWindow>>& windows()
  499. {
  500. static std::vector<std::unique_ptr<AutomationWindow>> open;
  501. return open;
  502. }
  503. void AutomationWindow::closeButtonPressed()
  504. {
  505. auto* self = this;
  506. juce::MessageManager::callAsync ([self] {
  507. auto& open = windows();
  508. open.erase (std::remove_if (open.begin(), open.end(), [self] (auto& w) { return w.get() == self; }), open.end());
  509. });
  510. }
  511. } // namespace
  512. juce::String describeAutomationTarget (AudioEngine& engine, const AutomationTarget& t)
  513. {
  514. const auto& song = engine.getSong();
  515. const auto channelName = t.index >= 0 && t.index < (int) song.channels.size() ? nameOf (song.channels[(std::size_t) t.index].name) : juce::String ("?");
  516. const auto trackName = t.index >= 0 && t.index < (int) song.mixer.size() ? nameOf (song.mixer[(std::size_t) t.index].name) : juce::String ("?");
  517. switch (t.kind)
  518. {
  519. case AutomationTargetKind::channelVolume: return channelName + " - " + tr ("Volume");
  520. case AutomationTargetKind::channelPan: return channelName + " - " + tr ("Pan");
  521. case AutomationTargetKind::mixerVolume: return trackName + " - " + tr ("Volume");
  522. case AutomationTargetKind::mixerPan: return trackName + " - " + tr ("Pan");
  523. case AutomationTargetKind::channelParam:
  524. case AutomationTargetKind::effectParam:
  525. {
  526. juce::String param = tr ("Param {0}", { juce::String (t.param + 1) });
  527. if (midictl::isMidiParam (t.param))
  528. param = midiParamLabel (t.param);
  529. else if (auto* plugin = pluginFor (engine, t))
  530. {
  531. if (t.param >= 0 && t.param < plugin->getParameters().size())
  532. param = plugin->getParameters()[t.param]->getName (40);
  533. }
  534. else if (t.kind == AutomationTargetKind::effectParam && t.index < (int) song.mixer.size()
  535. && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size())
  536. {
  537. const auto& info = effectInfo (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind);
  538. if (t.param >= 0 && t.param < (int) info.params.size())
  539. param = utf8 (info.params[(std::size_t) t.param].name);
  540. }
  541. return (t.kind == AutomationTargetKind::channelParam ? channelName : trackName) + " - " + param;
  542. }
  543. case AutomationTargetKind::tempo: return tr ("Tempo");
  544. case AutomationTargetKind::effectMix:
  545. {
  546. juce::String effect = "FX " + juce::String (t.slot + 1);
  547. if (t.index < (int) song.mixer.size() && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size())
  548. effect = utf8 (effectInfo (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind).name);
  549. return trackName + " - " + effect + " - " + tr ("Mix");
  550. }
  551. case AutomationTargetKind::none: break;
  552. }
  553. return tr ("(no target)");
  554. }
  555. void createAutomationClip (AudioEngine& engine, const AutomationTarget& target)
  556. {
  557. auto value = engine.getSong().targetValue (target);
  558. if (midictl::isMidiParam (target.param) && (target.kind == AutomationTargetKind::channelParam || target.kind == AutomationTargetKind::effectParam))
  559. value = midiControlValue (engine, target);
  560. else if (auto* plugin = pluginFor (engine, target); plugin != nullptr && target.param >= 0 && target.param < plugin->getParameters().size())
  561. value = plugin->getParameters()[target.param]->getValue();
  562. if (value < 0.0f)
  563. return;
  564. const auto name = describeAutomationTarget (engine, target).toStdString();
  565. engine.editSong ([&] (Song& s) {
  566. // the Playlist time selection gives the clip its place and length; otherwise the whole song
  567. const auto bar = (std::int64_t) ppq * std::max (1, s.beatsPerBar);
  568. const auto length = s.hasLoop() ? s.loopEnd - s.loopStart : s.playlist.empty() ? bar * 4 : s.songLength();
  569. Automation a;
  570. a.name = name;
  571. a.target = target;
  572. a.points = { { 0, value, 0.0f }, { length, value, 0.0f } };
  573. s.automations.push_back (std::move (a));
  574. int track = 0;
  575. for (const auto& c : s.playlist)
  576. track = std::max (track, c.track + 1);
  577. Clip clip;
  578. clip.kind = ClipKind::automation;
  579. clip.automation = (int) s.automations.size() - 1;
  580. clip.track = track;
  581. clip.start = s.hasLoop() ? s.loopStart : 0;
  582. clip.length = length;
  583. s.playlist.push_back (clip);
  584. });
  585. openAutomationEditor (engine, (int) engine.getSong().automations.size() - 1);
  586. }
  587. void openAutomationEditor (AudioEngine& engine, int index)
  588. {
  589. if (index < 0 || index >= (int) engine.getSong().automations.size())
  590. return;
  591. for (auto& w : windows())
  592. if (w->getIndex() == index)
  593. {
  594. w->toFront (true);
  595. return;
  596. }
  597. windows().push_back (std::make_unique<AutomationWindow> (
  598. engine, index, tr ("Automation - {0}", { nameOf (engine.getSong().automations[(std::size_t) index].name) })));
  599. }
  600. void closeAutomationEditors()
  601. {
  602. windows().clear();
  603. }
  604. std::unique_ptr<juce::Component> makeAutomationEditor (AudioEngine& engine, int automation)
  605. {
  606. return std::make_unique<AutomationEditor> (engine, automation);
  607. }
  608. std::vector<ControllerOutput> controllerOutputs (const Song& song)
  609. {
  610. std::vector<ControllerOutput> out;
  611. for (int c = 0; c < (int) song.channels.size(); ++c)
  612. {
  613. const auto& ch = song.channels[(std::size_t) c];
  614. if (ch.instrument != InstrumentKind::controller)
  615. continue;
  616. const auto name = nameOf (ch.name);
  617. if (parseKeyboardController (ch.controllerState))
  618. {
  619. out.push_back ({ -1, 0, 0, c, name + " - " + tr ("Key value") });
  620. continue;
  621. }
  622. for (int k = 0; k < 8; ++k)
  623. out.push_back ({ -1, 0, k, c, name + " - " + tr ("Output {0}", { juce::String (k + 1) }) });
  624. }
  625. for (int t = 0; t < (int) song.mixer.size(); ++t)
  626. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  627. {
  628. const auto kind = song.mixer[(std::size_t) t].effects[(std::size_t) s].kind;
  629. const auto track = t == 0 ? tr ("Master") : nameOf (song.mixer[(std::size_t) t].name);
  630. const auto where = (track.isNotEmpty() ? track : tr ("Insert {0}", { juce::String (t) })) + " (" + juce::String (s + 1) + ")";
  631. if (kind == EffectKind::formulaController)
  632. out.push_back ({ t, s, 0, -1, tr ("Formula Controller") + " " + where });
  633. else if (kind == EffectKind::peakController)
  634. {
  635. out.push_back ({ t, s, 1, -1, tr ("Peak Controller") + " " + where + " - " + tr ("Peak") });
  636. out.push_back ({ t, s, 2, -1, tr ("Peak Controller") + " " + where + " - " + tr ("LFO") });
  637. out.push_back ({ t, s, 0, -1, tr ("Peak Controller") + " " + where + " - " + tr ("Peak + LFO") });
  638. }
  639. }
  640. return out;
  641. }
  642. void linkToController (AudioEngine& engine, const AutomationTarget& target, const ControllerOutput& source)
  643. {
  644. const auto name = describeAutomationTarget (engine, target).toStdString() + " <- " + source.label.toStdString();
  645. engine.editSong ([&] (Song& s) {
  646. // one controller per target (FL's Link dialog replaces the old link)
  647. for (int i = (int) s.automations.size() - 1; i >= 0; --i)
  648. if (s.automations[(std::size_t) i].isLive() && s.automations[(std::size_t) i].target == target)
  649. s.removeAutomation (i);
  650. Automation a;
  651. a.name = name;
  652. a.target = target;
  653. a.source.track = source.track;
  654. a.source.slot = source.slot;
  655. a.source.output = source.output;
  656. a.source.channel = source.channel;
  657. s.automations.push_back (std::move (a));
  658. });
  659. }
  660. void addControllerLinkItems (juce::PopupMenu& menu, AudioEngine& engine, const AutomationTarget& target)
  661. {
  662. const auto& song = engine.getSong();
  663. const auto outputs = controllerOutputs (song);
  664. const auto current = std::find_if (song.automations.begin(), song.automations.end(),
  665. [&] (const Automation& a) { return a.isLive() && a.target == target; });
  666. juce::PopupMenu sub;
  667. for (const auto& o : outputs)
  668. {
  669. const auto ticked = current != song.automations.end() && current->source.track == o.track && current->source.slot == o.slot
  670. && current->source.output == o.output && current->source.channel == o.channel;
  671. sub.addItem (o.label, true, ticked, [&engine, target, o] { linkToController (engine, target, o); });
  672. }
  673. if (outputs.empty())
  674. sub.addItem (tr ("(add an Envelope, Formula or Peak Controller first)"), false, false, [] {});
  675. if (current != song.automations.end())
  676. {
  677. sub.addSeparator();
  678. sub.addItem (tr ("Remove controller link"), [&engine, target] {
  679. engine.editSong ([target] (Song& s) {
  680. for (int i = (int) s.automations.size() - 1; i >= 0; --i)
  681. if (s.automations[(std::size_t) i].isLive() && s.automations[(std::size_t) i].target == target)
  682. s.removeAutomation (i);
  683. });
  684. });
  685. }
  686. menu.addSubMenu (tr ("Link to internal controller"), sub);
  687. }
  688. std::function<void (const AutomationTarget&)> onEditEventsInPianoRoll;
  689. void addAutomationItem (juce::PopupMenu& menu, AudioEngine& engine, const AutomationTarget& target)
  690. {
  691. if (target.kind != AutomationTargetKind::tempo)
  692. {
  693. menu.addItem (tr ("Edit events in the pattern"), [&engine, target] { openEventEditor (engine, target); });
  694. if (onEditEventsInPianoRoll)
  695. menu.addItem (tr ("Edit events in piano roll"), [target] {
  696. if (onEditEventsInPianoRoll)
  697. onEditEventsInPianoRoll (target);
  698. });
  699. }
  700. // FL's initialized controls (REA round 146): the value the song resets this control to whenever it starts
  701. const auto initial = engine.getSong().findInitialValue (target);
  702. menu.addItem (tr ("Init song with this position"), engine.currentTargetValue (target) >= 0.0f, initial >= 0, [&engine, target] {
  703. const auto value = engine.currentTargetValue (target);
  704. if (value >= 0.0f)
  705. engine.editSong ([target, value] (Song& s) { s.setInitialValue (target, value); });
  706. });
  707. menu.addItem (tr ("Delete initial value"), initial >= 0, false, [&engine, target] {
  708. engine.editSong ([target] (Song& s) { s.removeInitialValue (target); });
  709. });
  710. menu.addItem (tr ("Create automation clip"), [&engine, target] { createAutomationClip (engine, target); });
  711. menu.addItem (tr ("Link to MIDI controller (move a knob on the controller)"), [&engine, target] {
  712. engine.learnMidiController (target);
  713. });
  714. // FL's "Override global link..." (form "Global link settings"): a link for every project, kept in the settings
  715. menu.addItem (tr ("Override global link... (for all projects: move a knob on the controller)"), [&engine, target] {
  716. engine.learnGlobalLink (target);
  717. });
  718. if (target.kind != AutomationTargetKind::tempo)
  719. addControllerLinkItems (menu, engine, target);
  720. const auto& links = engine.getSong().midiLinks;
  721. const auto linked = std::find_if (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == target; });
  722. if (linked != links.end())
  723. menu.addItem (tr ("Unlink controller (CC {0})", { juce::String (linked->cc) }), [&engine, target] {
  724. engine.editSong ([target] (Song& s) {
  725. s.midiLinks.erase (std::remove_if (s.midiLinks.begin(), s.midiLinks.end(), [&] (const MidiLink& l) { return l.target == target; }),
  726. s.midiLinks.end());
  727. });
  728. });
  729. if (const auto global = engine.globalLinkOf (target))
  730. menu.addItem (tr ("Remove global link (CC {0})", { juce::String (global->cc) }), [&engine, target] { engine.removeGlobalLink (target); });
  731. }
  732. juce::String midiParamLabel (int param)
  733. {
  734. if (midictl::isCc (param))
  735. {
  736. const auto cc = param - midictl::ccBase;
  737. const juce::String standard = midictl::ccName (cc);
  738. return tr ("MIDI CC #{0}", { juce::String (cc) }) + (standard.isEmpty() ? juce::String() : " (" + tr (standard) + ")");
  739. }
  740. if (midictl::isPressure (param))
  741. return tr ("MIDI Channel {0} Aftertouch", { juce::String (param - midictl::pressureBase + 1) });
  742. if (midictl::isPitchBend (param))
  743. return tr ("MIDI Channel {0} Pitch Bend", { juce::String (param - midictl::pitchBendBase + 1) });
  744. return {};
  745. }
  746. void addMidiParameterItems (juce::PopupMenu& menu, AudioEngine& engine, const AutomationTarget& base)
  747. {
  748. const auto item = [&] (juce::PopupMenu& into, int param) {
  749. auto target = base;
  750. target.param = param;
  751. juce::PopupMenu sub;
  752. addAutomationItem (sub, engine, target);
  753. into.addSubMenu (midiParamLabel (param), sub);
  754. };
  755. juce::PopupMenu midi;
  756. for (int group = 0; group < 4; ++group) // CC 0-31, 32-63, 64-95, 96-127
  757. {
  758. juce::PopupMenu ccs;
  759. for (int cc = group * 32; cc < group * 32 + 32; ++cc)
  760. item (ccs, midictl::ccBase + cc);
  761. midi.addSubMenu (tr ("MIDI CC {0}-{1}", { juce::String (group * 32), juce::String (group * 32 + 31) }), ccs);
  762. }
  763. // the ones people reach for first, without digging
  764. juce::PopupMenu common;
  765. for (int cc : { 1, 7, 10, 11, 64, 66, 67, 74 })
  766. item (common, midictl::ccBase + cc);
  767. midi.addSubMenu (tr ("Common controllers"), common);
  768. juce::PopupMenu pressure, bend;
  769. for (int c = 0; c < 16; ++c)
  770. {
  771. item (pressure, midictl::pressureBase + c);
  772. item (bend, midictl::pitchBendBase + c);
  773. }
  774. midi.addSubMenu (tr ("Channel aftertouch"), pressure);
  775. midi.addSubMenu (tr ("Pitch bend"), bend);
  776. menu.addSubMenu (tr ("Automate MIDI controller (CC, aftertouch, pitch bend)"), midi);
  777. }
  778. void addPluginParameterItems (juce::PopupMenu& menu, AudioEngine& engine, juce::AudioPluginInstance& plugin,
  779. const AutomationTarget& base)
  780. {
  781. juce::PopupMenu params;
  782. const auto& list = plugin.getParameters();
  783. const auto count = juce::jmin (list.size(), midictl::ccBase);
  784. // a long list (VSL's pianos expose ~950) goes into pages of 64, so the menu fits on the screen
  785. constexpr int page = 64;
  786. for (int first = 0; first < count; first += page)
  787. {
  788. juce::PopupMenu pageMenu;
  789. auto& into = count > page ? pageMenu : params;
  790. for (int i = first; i < juce::jmin (count, first + page); ++i)
  791. {
  792. auto target = base;
  793. target.param = i;
  794. juce::PopupMenu param;
  795. addAutomationItem (param, engine, target);
  796. into.addSubMenu (juce::String (i + 1) + ". " + list[i]->getName (60), param);
  797. }
  798. if (count > page)
  799. params.addSubMenu (tr ("Parameters {0}-{1}", { juce::String (first + 1), juce::String (juce::jmin (count, first + page)) }), pageMenu);
  800. }
  801. if (list.isEmpty())
  802. params.addItem (tr ("(the plugin exposes no parameters)"), false, false, [] {});
  803. menu.addSubMenu (tr ("Automate plugin parameter"), params);
  804. addMidiParameterItems (menu, engine, base);
  805. }
  806. } // namespace lynx