AutomationUi.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. #include "ui/AutomationUi.h"
  2. #include <map>
  3. #include "core/Effects.h"
  4. #include "engine/Text.h"
  5. #include "ui/Theme.h"
  6. namespace lynx
  7. {
  8. namespace
  9. {
  10. juce::String nameOf (const std::string& s)
  11. {
  12. return juce::String::fromUTF8 (s.c_str());
  13. }
  14. juce::AudioPluginInstance* pluginFor (AudioEngine& engine, const AutomationTarget& t)
  15. {
  16. if (t.kind == AutomationTargetKind::channelParam)
  17. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (t.index).get()))
  18. return &p->getInstance();
  19. if (t.kind == AutomationTargetKind::effectParam)
  20. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (t.index, t.slot).get()))
  21. return &p->getInstance();
  22. return nullptr;
  23. }
  24. // Editor dos pontos: tempo na horizontal (compassos), valor na vertical.
  25. // - clique no vazio cria um ponto; arrastar move; clique direito apaga
  26. // - arrastar com Alt sobre um trecho muda a curva (tensão)
  27. // - Ctrl+roda dá zoom; roda rola
  28. class AutomationEditor final : public juce::Component,
  29. private juce::ChangeListener,
  30. private juce::Timer
  31. {
  32. public:
  33. AutomationEditor (AudioEngine& e, int index)
  34. : engine (e),
  35. automation (index)
  36. {
  37. engine.addChangeListener (this);
  38. setSize (760, 300);
  39. startTimerHz (30);
  40. }
  41. ~AutomationEditor() override { engine.removeChangeListener (this); }
  42. int getIndex() const noexcept { return automation; }
  43. void paint (juce::Graphics& g) override
  44. {
  45. g.fillAll (theme::window);
  46. const auto* a = current();
  47. if (a == nullptr)
  48. return;
  49. const auto& song = engine.getSong();
  50. const auto area = plotArea();
  51. const auto bar = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar);
  52. g.setColour (juce::Colour (0xff262b30));
  53. g.fillRect (area);
  54. // grade: tempos e compassos
  55. const auto beatPixels = ppq * pixelsPerTick;
  56. const auto lastTick = (std::int64_t) xToTick (area.getRight());
  57. for (auto tick = (std::int64_t) std::floor (scroll / ppq) * ppq; tick <= lastTick; tick += ppq)
  58. {
  59. const auto isBar = tick % bar == 0;
  60. if (! isBar && beatPixels < 8.0)
  61. continue;
  62. const auto x = (int) tickToX ((double) tick);
  63. g.setColour (isBar ? juce::Colour (0xff15181b) : juce::Colour (0xff2c3238));
  64. g.drawVerticalLine (x, (float) area.getY(), (float) area.getBottom());
  65. if (isBar)
  66. {
  67. g.setColour (theme::text.withAlpha (0.6f));
  68. g.setFont (juce::FontOptions (11.0f));
  69. g.drawText (juce::String (tick / bar + 1), x + 3, 2, 40, 16, juce::Justification::centredLeft);
  70. }
  71. }
  72. for (auto v : { 0.25f, 0.5f, 0.75f })
  73. {
  74. g.setColour (juce::Colour (0xff2f353c));
  75. g.drawHorizontalLine ((int) valueToY (v), (float) area.getX(), (float) area.getRight());
  76. }
  77. // curva
  78. juce::Path curve;
  79. const auto& points = a->points;
  80. for (auto x = area.getX(); x <= area.getRight(); x += 2)
  81. {
  82. const auto y = valueToY (a->valueAt (xToTick (x)));
  83. if (x == area.getX())
  84. curve.startNewSubPath ((float) x, y);
  85. else
  86. curve.lineTo ((float) x, y);
  87. }
  88. g.setColour (theme::accentGreen);
  89. g.strokePath (curve, juce::PathStrokeType (2.0f));
  90. for (std::size_t i = 0; i < points.size(); ++i)
  91. {
  92. const auto p = pointPosition (points[i]);
  93. g.setColour ((int) i == hoverPoint || (int) i == dragPoint ? juce::Colours::white : theme::accentGreen);
  94. g.fillEllipse (p.x - 5.0f, p.y - 5.0f, 10.0f, 10.0f);
  95. g.setColour (juce::Colours::black.withAlpha (0.6f));
  96. g.drawEllipse (p.x - 5.0f, p.y - 5.0f, 10.0f, 10.0f, 1.0f);
  97. }
  98. // cursor de reprodução (na posição do clip que estiver tocando)
  99. if (playhead >= 0.0)
  100. {
  101. g.setColour (theme::playhead);
  102. g.drawVerticalLine ((int) tickToX (playhead), (float) area.getY(), (float) area.getBottom());
  103. }
  104. g.setColour (theme::text.withAlpha (0.45f));
  105. g.setFont (juce::FontOptions (11.0f));
  106. g.drawText (utf8 ("Clique: novo ponto · arrastar: mover · clique direito: apagar · Alt+arrastar: curva · Ctrl+roda: zoom"),
  107. area.getX(), getHeight() - 18, area.getWidth(), 16, juce::Justification::centredLeft);
  108. if (hoverPoint >= 0 && hoverPoint < (int) points.size())
  109. {
  110. const auto p = pointPosition (points[(std::size_t) hoverPoint]);
  111. g.setColour (theme::text);
  112. g.drawText (juce::String (juce::roundToInt (points[(std::size_t) hoverPoint].value * 100.0f)) + "%",
  113. (int) p.x + 8, (int) p.y - 18, 60, 14, juce::Justification::centredLeft);
  114. }
  115. }
  116. void mouseMove (const juce::MouseEvent& e) override
  117. {
  118. const auto hit = pointAt (e.position);
  119. if (hit != hoverPoint)
  120. {
  121. hoverPoint = hit;
  122. repaint();
  123. }
  124. }
  125. void mouseDown (const juce::MouseEvent& e) override
  126. {
  127. const auto* a = current();
  128. if (a == nullptr || ! plotArea().contains (e.getPosition()))
  129. return;
  130. const auto hit = pointAt (e.position);
  131. if (e.mods.isPopupMenu())
  132. {
  133. if (hit >= 0 && a->points.size() > 1)
  134. edit ([hit] (Automation& x) { x.points.erase (x.points.begin() + hit); });
  135. return;
  136. }
  137. if (e.mods.isAltDown())
  138. {
  139. // segmento sob o mouse: o ponto à esquerda guarda a tensão
  140. tensionPoint = -1;
  141. const auto tick = xToTick (e.x);
  142. for (int i = 0; i + 1 < (int) a->points.size(); ++i)
  143. if (tick >= (double) a->points[(std::size_t) i].tick && tick < (double) a->points[(std::size_t) i + 1].tick)
  144. tensionPoint = i;
  145. if (tensionPoint >= 0)
  146. tensionStart = a->points[(std::size_t) tensionPoint].tension;
  147. return;
  148. }
  149. if (hit >= 0)
  150. {
  151. dragPoint = hit;
  152. return;
  153. }
  154. AutomationPoint p;
  155. p.tick = snap (xToTick (e.x), ! e.mods.isShiftDown());
  156. p.value = yToValue (e.y);
  157. edit ([p] (Automation& x) {
  158. x.points.push_back (p);
  159. std::stable_sort (x.points.begin(), x.points.end(), [] (auto& l, auto& r) { return l.tick < r.tick; });
  160. });
  161. for (int i = 0; i < (int) current()->points.size(); ++i)
  162. if (current()->points[(std::size_t) i].tick == p.tick && current()->points[(std::size_t) i].value == p.value)
  163. dragPoint = i;
  164. }
  165. void mouseDrag (const juce::MouseEvent& e) override
  166. {
  167. const auto* a = current();
  168. if (a == nullptr)
  169. return;
  170. if (tensionPoint >= 0 && tensionPoint < (int) a->points.size())
  171. {
  172. const auto tension = juce::jlimit (-1.0f, 1.0f, tensionStart + (float) e.getDistanceFromDragStartY() / 100.0f);
  173. edit ([i = tensionPoint, tension] (Automation& x) { x.points[(std::size_t) i].tension = tension; });
  174. return;
  175. }
  176. if (dragPoint < 0 || dragPoint >= (int) a->points.size())
  177. return;
  178. // o ponto não passa dos vizinhos (a ordem não muda durante o arraste)
  179. const auto& points = a->points;
  180. auto tick = snap (xToTick (e.x), ! e.mods.isShiftDown());
  181. const auto lo = dragPoint > 0 ? points[(std::size_t) dragPoint - 1].tick : 0;
  182. const auto hi = dragPoint + 1 < (int) points.size() ? points[(std::size_t) dragPoint + 1].tick : std::numeric_limits<std::int64_t>::max();
  183. tick = juce::jlimit (lo, hi, tick);
  184. const auto value = yToValue (e.y);
  185. edit ([i = dragPoint, tick, value] (Automation& x) {
  186. x.points[(std::size_t) i].tick = tick;
  187. x.points[(std::size_t) i].value = value;
  188. });
  189. }
  190. void mouseUp (const juce::MouseEvent&) override
  191. {
  192. dragPoint = tensionPoint = -1;
  193. repaint();
  194. }
  195. void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel) override
  196. {
  197. if (e.mods.isCtrlDown())
  198. {
  199. const auto anchor = xToTick (e.x);
  200. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), 600.0 / (4 * ppq), pixelsPerTick * (wheel.deltaY > 0 ? 1.2 : 1.0 / 1.2));
  201. scroll = juce::jmax (0.0, anchor - (e.x - plotArea().getX()) / pixelsPerTick);
  202. }
  203. else
  204. scroll = juce::jmax (0.0, scroll - (wheel.deltaY + wheel.deltaX) * 300.0 / pixelsPerTick);
  205. repaint();
  206. }
  207. private:
  208. const Automation* current() const
  209. {
  210. const auto& song = engine.getSong();
  211. return automation >= 0 && automation < (int) song.automations.size() ? &song.automations[(std::size_t) automation] : nullptr;
  212. }
  213. void edit (const std::function<void (Automation&)>& fn)
  214. {
  215. engine.editSong ([this, &fn] (Song& s) {
  216. if (automation >= 0 && automation < (int) s.automations.size())
  217. fn (s.automations[(std::size_t) automation]);
  218. });
  219. }
  220. juce::Rectangle<int> plotArea() const { return getLocalBounds().withTrimmedTop (18).withTrimmedBottom (20).reduced (8, 4); }
  221. double tickToX (double tick) const { return plotArea().getX() + (tick - scroll) * pixelsPerTick; }
  222. double xToTick (int x) const { return juce::jmax (0.0, (x - plotArea().getX()) / pixelsPerTick + scroll); }
  223. float valueToY (float v) const { return (float) plotArea().getBottom() - v * (float) plotArea().getHeight(); }
  224. float yToValue (int y) const { return juce::jlimit (0.0f, 1.0f, (float) (plotArea().getBottom() - y) / (float) plotArea().getHeight()); }
  225. std::int64_t snap (double tick, bool on) const
  226. {
  227. const auto grid = on ? (double) ticksPerStep : 1.0;
  228. return (std::int64_t) std::round (tick / grid) * (std::int64_t) grid;
  229. }
  230. juce::Point<float> pointPosition (const AutomationPoint& p) const { return { (float) tickToX ((double) p.tick), valueToY (p.value) }; }
  231. int pointAt (juce::Point<float> pos) const
  232. {
  233. const auto* a = current();
  234. if (a == nullptr)
  235. return -1;
  236. for (int i = (int) a->points.size() - 1; i >= 0; --i)
  237. if (pointPosition (a->points[(std::size_t) i]).getDistanceFrom (pos) < 8.0f)
  238. return i;
  239. return -1;
  240. }
  241. void changeListenerCallback (juce::ChangeBroadcaster*) override
  242. {
  243. if (current() == nullptr) // automação removida: fecha
  244. {
  245. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<Component> (getParentComponent())] {
  246. if (auto* w = dynamic_cast<juce::DocumentWindow*> (safe.getComponent()))
  247. w->closeButtonPressed();
  248. });
  249. return;
  250. }
  251. if (auto* w = findParentComponentOfClass<juce::DocumentWindow>())
  252. w->setName (utf8 ("Automação - ") + juce::String::fromUTF8 (current()->name.c_str()));
  253. repaint();
  254. }
  255. void timerCallback() override
  256. {
  257. // posição dentro da automação, se algum clip dela estiver sob o cursor
  258. auto tick = -1.0;
  259. const auto& song = engine.getSong();
  260. if (song.mode == PlayMode::song && engine.getTransport().playing.load())
  261. {
  262. const auto position = std::fmod (engine.getTransport().positionTicks.load(), (double) juce::jmax<std::int64_t> (1, song.songLength()));
  263. for (const auto& c : song.playlist)
  264. if (c.kind == ClipKind::automation && c.automation == automation && position >= (double) c.start && position < (double) c.end())
  265. tick = position - (double) c.start + (double) c.offset;
  266. }
  267. if (tick != playhead)
  268. {
  269. playhead = tick;
  270. repaint();
  271. }
  272. }
  273. AudioEngine& engine;
  274. int automation;
  275. double pixelsPerTick = 120.0 / (4 * ppq);
  276. double scroll = 0.0;
  277. int dragPoint = -1, hoverPoint = -1, tensionPoint = -1;
  278. float tensionStart = 0.0f;
  279. double playhead = -1.0;
  280. };
  281. class AutomationWindow final : public juce::DocumentWindow
  282. {
  283. public:
  284. AutomationWindow (AudioEngine& engine, int index, const juce::String& title)
  285. : juce::DocumentWindow (title, theme::window, DocumentWindow::closeButton)
  286. {
  287. setUsingNativeTitleBar (true);
  288. setContentOwned (new AutomationEditor (engine, index), true);
  289. setResizable (true, false);
  290. setResizeLimits (400, 200, 4000, 2000);
  291. centreWithSize (getWidth(), getHeight());
  292. setVisible (true);
  293. }
  294. int getIndex() const { return static_cast<AutomationEditor*> (getContentComponent())->getIndex(); }
  295. void closeButtonPressed() override;
  296. };
  297. std::vector<std::unique_ptr<AutomationWindow>>& windows()
  298. {
  299. static std::vector<std::unique_ptr<AutomationWindow>> open;
  300. return open;
  301. }
  302. void AutomationWindow::closeButtonPressed()
  303. {
  304. auto* self = this;
  305. juce::MessageManager::callAsync ([self] {
  306. auto& open = windows();
  307. open.erase (std::remove_if (open.begin(), open.end(), [self] (auto& w) { return w.get() == self; }), open.end());
  308. });
  309. }
  310. } // namespace
  311. juce::String describeAutomationTarget (AudioEngine& engine, const AutomationTarget& t)
  312. {
  313. const auto& song = engine.getSong();
  314. const auto channelName = t.index >= 0 && t.index < (int) song.channels.size() ? nameOf (song.channels[(std::size_t) t.index].name) : juce::String ("?");
  315. const auto trackName = t.index >= 0 && t.index < (int) song.mixer.size() ? nameOf (song.mixer[(std::size_t) t.index].name) : juce::String ("?");
  316. switch (t.kind)
  317. {
  318. case AutomationTargetKind::channelVolume: return channelName + " - Volume";
  319. case AutomationTargetKind::channelPan: return channelName + " - Pan";
  320. case AutomationTargetKind::mixerVolume: return trackName + " - Volume";
  321. case AutomationTargetKind::mixerPan: return trackName + " - Pan";
  322. case AutomationTargetKind::channelParam:
  323. case AutomationTargetKind::effectParam:
  324. {
  325. juce::String param = juce::String ("Param ") + juce::String (t.param + 1);
  326. if (auto* plugin = pluginFor (engine, t))
  327. {
  328. if (t.param >= 0 && t.param < plugin->getParameters().size())
  329. param = plugin->getParameters()[t.param]->getName (40);
  330. }
  331. else if (t.kind == AutomationTargetKind::effectParam && t.index < (int) song.mixer.size()
  332. && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size())
  333. {
  334. const auto& info = effectInfo (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind);
  335. if (t.param >= 0 && t.param < (int) info.params.size())
  336. param = utf8 (info.params[(std::size_t) t.param].name);
  337. }
  338. return (t.kind == AutomationTargetKind::channelParam ? channelName : trackName) + " - " + param;
  339. }
  340. case AutomationTargetKind::none: break;
  341. }
  342. return utf8 ("(sem alvo)");
  343. }
  344. void createAutomationClip (AudioEngine& engine, const AutomationTarget& target)
  345. {
  346. auto value = engine.getSong().targetValue (target);
  347. if (auto* plugin = pluginFor (engine, target); plugin != nullptr && target.param < plugin->getParameters().size())
  348. value = plugin->getParameters()[target.param]->getValue();
  349. if (value < 0.0f)
  350. return;
  351. const auto name = describeAutomationTarget (engine, target).toStdString();
  352. engine.editSong ([&] (Song& s) {
  353. const auto bar = (std::int64_t) ppq * std::max (1, s.beatsPerBar);
  354. const auto length = s.playlist.empty() ? bar * 4 : s.songLength();
  355. Automation a;
  356. a.name = name;
  357. a.target = target;
  358. a.points = { { 0, value, 0.0f }, { length, value, 0.0f } };
  359. s.automations.push_back (std::move (a));
  360. int track = 0;
  361. for (const auto& c : s.playlist)
  362. track = std::max (track, c.track + 1);
  363. Clip clip;
  364. clip.kind = ClipKind::automation;
  365. clip.automation = (int) s.automations.size() - 1;
  366. clip.track = track;
  367. clip.length = length;
  368. s.playlist.push_back (clip);
  369. });
  370. openAutomationEditor (engine, (int) engine.getSong().automations.size() - 1);
  371. }
  372. void openAutomationEditor (AudioEngine& engine, int index)
  373. {
  374. if (index < 0 || index >= (int) engine.getSong().automations.size())
  375. return;
  376. for (auto& w : windows())
  377. if (w->getIndex() == index)
  378. {
  379. w->toFront (true);
  380. return;
  381. }
  382. windows().push_back (std::make_unique<AutomationWindow> (
  383. engine, index, utf8 ("Automação - ") + nameOf (engine.getSong().automations[(std::size_t) index].name)));
  384. }
  385. void closeAutomationEditors()
  386. {
  387. windows().clear();
  388. }
  389. void addAutomationItem (juce::PopupMenu& menu, AudioEngine& engine, const AutomationTarget& target)
  390. {
  391. menu.addItem (utf8 ("Criar clip de automação"), [&engine, target] { createAutomationClip (engine, target); });
  392. }
  393. void addPluginParameterItems (juce::PopupMenu& menu, AudioEngine& engine, juce::AudioPluginInstance& plugin,
  394. const AutomationTarget& base)
  395. {
  396. juce::PopupMenu params;
  397. const auto& list = plugin.getParameters();
  398. for (int i = 0; i < list.size() && i < 512; ++i)
  399. {
  400. auto target = base;
  401. target.param = i;
  402. params.addItem (list[i]->getName (60), [&engine, target] { createAutomationClip (engine, target); });
  403. }
  404. if (list.isEmpty())
  405. params.addItem (utf8 ("(o plugin não expõe parâmetros)"), false, false, [] {});
  406. menu.addSubMenu (utf8 ("Automatizar parâmetro do plugin"), params);
  407. }
  408. } // namespace lynx