ChannelRackComponent.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. #include "ui/ChannelRackComponent.h"
  2. #include "ui/AutomationUi.h"
  3. #include "core/Slicer.h"
  4. #include "ui/ChannelSettings.h"
  5. #include "engine/Text.h"
  6. #include "ui/BrowserComponent.h"
  7. #include "ui/PluginWindow.h"
  8. #include "ui/Theme.h"
  9. namespace lynx
  10. {
  11. namespace
  12. {
  13. juce::String instrumentName (InstrumentKind k)
  14. {
  15. switch (k)
  16. {
  17. case InstrumentKind::kick: return "Kick";
  18. case InstrumentKind::snare: return "Snare";
  19. case InstrumentKind::hat: return "Hat";
  20. case InstrumentKind::clap: return "Clap";
  21. case InstrumentKind::synth: return "Synth";
  22. case InstrumentKind::sampler: return "Sampler";
  23. case InstrumentKind::audioClip: return utf8 ("Audio clip");
  24. case InstrumentKind::plugin: return "Plugin";
  25. case InstrumentKind::controller: return "Controller";
  26. case InstrumentKind::sakura: return "Sakura";
  27. case InstrumentKind::drumpad: return "Drumpad";
  28. }
  29. return "?";
  30. }
  31. constexpr InstrumentKind builtInKinds[] = { InstrumentKind::kick, InstrumentKind::snare, InstrumentKind::hat,
  32. InstrumentKind::clap, InstrumentKind::synth };
  33. void setStep (Pattern& p, int channel, int step, bool on)
  34. {
  35. if (p.hasStep (channel, step) != on)
  36. p.toggleStep (channel, step);
  37. }
  38. void drawKnob (juce::Graphics& g, juce::Rectangle<float> r, float value01, bool bipolar, juce::Colour colour)
  39. {
  40. const auto size = juce::jmin (r.getWidth(), r.getHeight()) - 6.0f;
  41. const auto area = r.withSizeKeepingCentre (size, size);
  42. const auto centre = area.getCentre();
  43. const auto radius = size / 2.0f;
  44. constexpr auto start = juce::MathConstants<float>::pi * 1.25f;
  45. constexpr auto range = juce::MathConstants<float>::pi * 1.5f;
  46. g.setColour (theme::knobBackground);
  47. g.fillEllipse (area);
  48. const auto from = bipolar ? start + range * 0.5f : start;
  49. const auto to = start + range * value01;
  50. juce::Path arc;
  51. arc.addCentredArc (centre.x, centre.y, radius - 1.5f, radius - 1.5f, 0.0f, juce::jmin (from, to), juce::jmax (from, to), true);
  52. g.setColour (colour);
  53. g.strokePath (arc, juce::PathStrokeType (2.5f));
  54. // JUCE angles: 0 = 12 o'clock, clockwise
  55. const auto length = radius - 3.0f;
  56. g.setColour (juce::Colours::white);
  57. g.drawLine (centre.x, centre.y, centre.x + std::sin (to) * length, centre.y - std::cos (to) * length, 1.5f);
  58. }
  59. } // namespace
  60. ChannelRackComponent::ChannelRackComponent (AudioEngine& e)
  61. : engine (e)
  62. {
  63. setWantsKeyboardFocus (false);
  64. setMouseClickGrabsKeyboardFocus (false);
  65. engine.addChangeListener (this);
  66. updateSize();
  67. startTimerHz (30);
  68. }
  69. ChannelRackComponent::~ChannelRackComponent()
  70. {
  71. engine.removeChangeListener (this);
  72. }
  73. int ChannelRackComponent::numSteps() const
  74. {
  75. const auto& song = engine.getSong();
  76. if (song.patterns.empty())
  77. return 16;
  78. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  79. const auto steps = (int) (p.effectiveLength (song.beatsPerBar) / ticksPerStep);
  80. return juce::jlimit (16, 512, steps);
  81. }
  82. void ChannelRackComponent::updateSize()
  83. {
  84. const auto rows = (int) engine.getSong().channels.size() + 1; // +1 = "add channel" row
  85. setSize (gridLeft() + numSteps() * stepWidth + 8, rows * rowHeight + 8);
  86. }
  87. juce::Rectangle<int> ChannelRackComponent::rowBounds (int row) const
  88. {
  89. return { 0, 4 + row * rowHeight, getWidth(), rowHeight };
  90. }
  91. juce::Rectangle<int> ChannelRackComponent::stepBounds (int row, int step) const
  92. {
  93. return { gridLeft() + step * stepWidth + 1, 4 + row * rowHeight + 4, stepWidth - 3, rowHeight - 8 };
  94. }
  95. ChannelRackComponent::Area ChannelRackComponent::areaAt (int x, int y, int& row) const
  96. {
  97. const auto channels = (int) engine.getSong().channels.size();
  98. row = (y - 4) / rowHeight;
  99. if (y < 4 || row > channels)
  100. return Area::none;
  101. if (row == channels)
  102. return x < gridLeft() ? Area::addRow : Area::none;
  103. if (x < muteWidth)
  104. return Area::mute;
  105. if (x < muteWidth + knobWidth)
  106. return Area::pan;
  107. if (x < muteWidth + 2 * knobWidth)
  108. return Area::volume;
  109. if (x < nameLeft())
  110. return Area::route;
  111. if (x < gridLeft())
  112. return Area::name;
  113. return Area::grid;
  114. }
  115. bool ChannelRackComponent::cellHasNote (int channel, int step) const
  116. {
  117. const auto& song = engine.getSong();
  118. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  119. const auto from = (std::int64_t) step * ticksPerStep;
  120. const auto to = from + ticksPerStep;
  121. for (const auto& n : p.notes)
  122. if (n.channel == channel && n.start >= from && n.start < to)
  123. return true;
  124. return false;
  125. }
  126. void ChannelRackComponent::paint (juce::Graphics& g)
  127. {
  128. g.fillAll (theme::panel);
  129. const auto& song = engine.getSong();
  130. if (song.patterns.empty())
  131. return;
  132. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  133. const auto steps = numSteps();
  134. const auto clip = g.getClipBounds();
  135. const auto selected = engine.getSelectedChannel();
  136. g.setFont (juce::FontOptions (14.0f));
  137. for (int row = 0; row < (int) song.channels.size(); ++row)
  138. {
  139. const auto y = 4 + row * rowHeight;
  140. if (y > clip.getBottom() || y + rowHeight < clip.getY())
  141. continue;
  142. const auto& channel = song.channels[(std::size_t) row];
  143. const auto nameArea = juce::Rectangle<float> ((float) nameLeft(), (float) y + 3, (float) nameWidth, (float) rowHeight - 6);
  144. g.setColour (theme::muteLed (channel.muted));
  145. g.fillEllipse ((float) 9, (float) y + rowHeight / 2.0f - 5, 10, 10);
  146. drawKnob (g, { (float) muteWidth, (float) y, (float) knobWidth, (float) rowHeight }, (channel.pan + 1.0f) / 2.0f,
  147. true, theme::accentBlue);
  148. drawKnob (g, { (float) muteWidth + knobWidth, (float) y, (float) knobWidth, (float) rowHeight }, channel.volume,
  149. false, theme::accentGreen);
  150. // small box with the mixer insert ("-" = straight to Master), as in FL
  151. const auto routeArea = juce::Rectangle<float> ((float) (muteWidth + 2 * knobWidth) + 1, (float) y + 7,
  152. (float) routeWidth - 3, (float) rowHeight - 14);
  153. g.setColour (theme::knobBackground);
  154. g.fillRoundedRectangle (routeArea, 3.0f);
  155. g.setColour (channel.mixerTrack > 0 ? theme::accentOrange : theme::text.withAlpha (0.5f));
  156. g.setFont (juce::FontOptions (12.0f));
  157. g.drawText (channel.mixerTrack > 0 ? juce::String (channel.mixerTrack) : juce::String ("-"), routeArea.toNearestInt(),
  158. juce::Justification::centred);
  159. g.setFont (juce::FontOptions (14.0f));
  160. // channel colour (from the .flp or user-picked) blended into the button, as in FL
  161. auto button = row == selected ? theme::channelButtonSelected : theme::channelButton;
  162. if (channel.colour != 0)
  163. button = button.interpolatedWith (juce::Colour (channel.colour), 0.55f);
  164. g.setColour (button);
  165. g.fillRoundedRectangle (nameArea, 4.0f);
  166. if (row == selected)
  167. {
  168. g.setColour (theme::accentOrange);
  169. g.fillRoundedRectangle (nameArea.withWidth (4.0f), 2.0f);
  170. }
  171. g.setColour (channel.muted ? juce::Colours::grey : juce::Colours::white);
  172. g.drawText (juce::String::fromUTF8 (channel.name.c_str()), nameArea.reduced (10, 0).toNearestInt(),
  173. juce::Justification::centredLeft, true);
  174. if (channel.instrument == InstrumentKind::audioClip)
  175. {
  176. g.setColour (theme::text.withAlpha (0.35f));
  177. g.drawText (utf8 ("audio clip — plays from the Playlist"), gridLeft() + 4, y, 400, rowHeight, juce::Justification::centredLeft);
  178. g.setFont (juce::FontOptions (14.0f));
  179. continue;
  180. }
  181. for (int step = 0; step < steps; ++step)
  182. {
  183. const auto r = stepBounds (row, step);
  184. if (r.getRight() < clip.getX() || r.getX() > clip.getRight())
  185. continue;
  186. const auto onGrid = pattern.hasStep (row, step);
  187. const auto any = onGrid || cellHasNote (row, step);
  188. g.setColour (any ? (onGrid ? theme::stepOn : theme::stepOnOffGrid) : theme::stepOff (step));
  189. g.fillRoundedRectangle (r.toFloat(), 3.0f);
  190. }
  191. }
  192. const auto addY = 4 + (int) song.channels.size() * rowHeight;
  193. g.setColour (juce::Colours::white.withAlpha (0.5f));
  194. g.drawText (utf8 ("+ add channel (or drop an audio file)"), nameLeft() + 2, addY,
  195. 400, rowHeight, juce::Justification::centredLeft);
  196. if (playheadStep >= 0 && playheadStep < steps)
  197. {
  198. g.setColour (theme::playhead.withAlpha (0.35f));
  199. g.fillRect (gridLeft() + playheadStep * stepWidth, 0, stepWidth - 2, addY);
  200. }
  201. }
  202. void ChannelRackComponent::mouseDown (const juce::MouseEvent& e)
  203. {
  204. int row = 0;
  205. const auto area = areaAt (e.x, e.y, row);
  206. const auto& song = engine.getSong();
  207. switch (area)
  208. {
  209. case Area::none:
  210. return;
  211. case Area::addRow:
  212. showAddChannelMenu();
  213. return;
  214. case Area::mute:
  215. if (e.mods.isPopupMenu() || e.mods.isCtrlDown())
  216. {
  217. // solo as in FL: only this channel plays; repeating on the already-soloed channel unmutes all
  218. engine.editSong ([row] (Song& s) {
  219. const auto alone = ! s.channels[(std::size_t) row].muted
  220. && std::all_of (s.channels.begin(), s.channels.end(), [&] (const ChannelDef& c) {
  221. return &c == &s.channels[(std::size_t) row] || c.muted;
  222. });
  223. for (std::size_t i = 0; i < s.channels.size(); ++i)
  224. s.channels[i].muted = alone ? false : i != (std::size_t) row;
  225. });
  226. }
  227. else
  228. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].muted = ! s.channels[(std::size_t) row].muted; });
  229. return;
  230. case Area::pan:
  231. case Area::volume:
  232. if (e.mods.isPopupMenu())
  233. {
  234. juce::PopupMenu menu;
  235. addAutomationItem (menu, engine, { area == Area::pan ? AutomationTargetKind::channelPan : AutomationTargetKind::channelVolume, row });
  236. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  237. return;
  238. }
  239. knobDrag = area;
  240. knobRow = row;
  241. knobStartValue = area == Area::pan ? song.channels[(std::size_t) row].pan : song.channels[(std::size_t) row].volume;
  242. return;
  243. case Area::route:
  244. knobDrag = area;
  245. knobRow = row;
  246. routeStartValue = song.channels[(std::size_t) row].mixerTrack;
  247. return;
  248. case Area::name:
  249. engine.setSelectedChannel (row);
  250. if (e.mods.isPopupMenu())
  251. showChannelMenu (row);
  252. else
  253. engine.sendLiveNote (row, 60, 0.8f, true);
  254. return;
  255. case Area::grid:
  256. {
  257. const auto step = (e.x - gridLeft()) / stepWidth;
  258. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  259. if (e.mods.isRightButtonDown())
  260. paintMode = PaintMode::remove;
  261. else
  262. paintMode = pattern.hasStep (row, step) ? PaintMode::remove : PaintMode::add;
  263. lastPaintedRow = lastPaintedStep = -1;
  264. applyPaint (e);
  265. return;
  266. }
  267. }
  268. }
  269. void ChannelRackComponent::mouseDrag (const juce::MouseEvent& e)
  270. {
  271. if (knobDrag != Area::none)
  272. {
  273. const auto delta = (float) -e.getDistanceFromDragStartY() / 150.0f;
  274. const auto row = knobRow;
  275. if (knobDrag == Area::route)
  276. {
  277. const auto tracks = juce::jmax (1, (int) engine.getSong().mixer.size());
  278. const auto value = juce::jlimit (0, tracks - 1, routeStartValue - e.getDistanceFromDragStartY() / 6);
  279. if (value != engine.getSong().channels[(std::size_t) row].mixerTrack)
  280. engine.editSong ([row, value] (Song& s) { s.channels[(std::size_t) row].mixerTrack = value; });
  281. }
  282. else if (knobDrag == Area::pan)
  283. {
  284. const auto value = juce::jlimit (-1.0f, 1.0f, knobStartValue + delta * 2.0f);
  285. engine.editSong ([row, value] (Song& s) { s.channels[(std::size_t) row].pan = value; });
  286. }
  287. else
  288. {
  289. const auto value = juce::jlimit (0.0f, 1.0f, knobStartValue + delta);
  290. engine.editSong ([row, value] (Song& s) { s.channels[(std::size_t) row].volume = value; });
  291. }
  292. return;
  293. }
  294. if (paintMode != PaintMode::none)
  295. applyPaint (e);
  296. }
  297. void ChannelRackComponent::mouseUp (const juce::MouseEvent& e)
  298. {
  299. int row = 0;
  300. if (areaAt (e.getMouseDownX(), e.getMouseDownY(), row) == Area::name && ! e.mods.isPopupMenu())
  301. engine.sendLiveNote (row, 60, 0.0f, false);
  302. paintMode = PaintMode::none;
  303. knobDrag = Area::none;
  304. }
  305. void ChannelRackComponent::mouseDoubleClick (const juce::MouseEvent& e)
  306. {
  307. int row = 0;
  308. const auto area = areaAt (e.x, e.y, row);
  309. if (area == Area::pan)
  310. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].pan = 0.0f; });
  311. else if (area == Area::volume)
  312. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].volume = 0.8f; });
  313. else if (area == Area::route)
  314. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].mixerTrack = s.nextFreeInsert(); });
  315. else if (area == Area::name && engine.getSong().channels[(std::size_t) row].instrument == InstrumentKind::plugin)
  316. openPluginWindow (row);
  317. else if (area == Area::name && onOpenPianoRoll)
  318. onOpenPianoRoll();
  319. }
  320. void ChannelRackComponent::applyPaint (const juce::MouseEvent& e)
  321. {
  322. const auto& song = engine.getSong();
  323. const auto row = (e.y - 4) / rowHeight;
  324. const auto step = (e.x - gridLeft()) / stepWidth;
  325. if (row < 0 || row >= (int) song.channels.size() || step < 0 || step >= numSteps() || e.x < gridLeft()
  326. || song.channels[(std::size_t) row].instrument == InstrumentKind::audioClip)
  327. return;
  328. if (row == lastPaintedRow && step == lastPaintedStep)
  329. return;
  330. lastPaintedRow = row;
  331. lastPaintedStep = step;
  332. const auto on = paintMode == PaintMode::add;
  333. engine.editSong ([row, step, on] (Song& s) { setStep (s.patterns[(std::size_t) s.currentPattern], row, step, on); });
  334. if (on)
  335. engine.sendLiveNote (row, 60, 0.78f, true);
  336. }
  337. void ChannelRackComponent::showChannelMenu (int channel)
  338. {
  339. const auto& c = engine.getSong().channels[(std::size_t) channel];
  340. juce::PopupMenu instruments;
  341. for (auto kind : builtInKinds)
  342. instruments.addItem (instrumentName (kind), true, c.instrument == kind, [this, channel, kind] {
  343. engine.editSong ([channel, kind] (Song& s) { s.channels[(std::size_t) channel].instrument = kind; });
  344. });
  345. instruments.addSeparator();
  346. instruments.addItem ("Sampler (choose file)...", [this, channel] { chooseSample (channel); });
  347. juce::PopupMenu plugins;
  348. addPluginItems (plugins, engine, true, [this, channel] (PluginRef ref) {
  349. engine.editSong ([channel, ref] (Song& s) {
  350. auto& c = s.channels[(std::size_t) channel];
  351. c.instrument = InstrumentKind::plugin;
  352. c.plugin = ref;
  353. c.name = ref.name;
  354. });
  355. openPluginWindow (channel);
  356. });
  357. instruments.addSubMenu ("Plugin (VST3/CLAP)", plugins);
  358. juce::PopupMenu menu;
  359. menu.addSectionHeader (juce::String::fromUTF8 (c.name.c_str()));
  360. if (c.instrument == InstrumentKind::sampler)
  361. {
  362. menu.addItem (juce::String ("Sample: ") + juce::File (juce::String::fromUTF8 (c.samplePath.c_str())).getFileName(),
  363. false, false, [] {});
  364. menu.addItem (utf8 ("Sampler settings (pitch, envelope, reverse)..."),
  365. [this, channel] { openChannelSettings (engine, channel); });
  366. if (c.sampler.slices.empty())
  367. menu.addItem (utf8 ("Slice sample (slicer): one slice per key and a pattern with the loop"), [this, channel] { sliceChannel (channel); });
  368. else
  369. menu.addItem (utf8 ("Undo slices (") + juce::String ((int) c.sampler.slices.size()) + ")", [this, channel] {
  370. engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].sampler.slices.clear(); });
  371. });
  372. }
  373. if (c.instrument == InstrumentKind::synth)
  374. menu.addItem (utf8 ("Synth settings (oscillators, envelope, filter)..."), [this, channel] { openChannelSettings (engine, channel); });
  375. if (c.instrument == InstrumentKind::plugin)
  376. {
  377. menu.addItem (utf8 ("Open plugin editor"), [this, channel] { openPluginWindow (channel); });
  378. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get()))
  379. addPluginParameterItems (menu, engine, p->getInstance(), { AutomationTargetKind::channelParam, channel, 0, 0 });
  380. }
  381. menu.addItem ("Piano Roll", [this] {
  382. if (onOpenPianoRoll)
  383. onOpenPianoRoll();
  384. });
  385. menu.addSubMenu ("Instrument", instruments);
  386. {
  387. // channel arpeggiator
  388. const auto arp = c.arp;
  389. auto set = [this, channel] (std::function<void (ArpSettings&)> change) {
  390. engine.editSong ([channel, change] (Song& s) { change (s.channels[(std::size_t) channel].arp); });
  391. };
  392. juce::PopupMenu arpMenu;
  393. const char* directions[] = { "Off", "Up", "Down", "Up and down", "Random" };
  394. for (int d = 0; d < 5; ++d)
  395. arpMenu.addItem (utf8 (directions[d]), true, arp.direction == d, [set, d] { set ([d] (ArpSettings& a) { a.direction = d; }); });
  396. arpMenu.addSeparator();
  397. juce::PopupMenu range, speed, gate, repeat;
  398. for (int o = 1; o <= 4; ++o)
  399. range.addItem (juce::String (o) + (o == 1 ? " octave" : " octaves"), true, arp.range == o, [set, o] { set ([o] (ArpSettings& a) { a.range = o; }); });
  400. const std::pair<const char*, float> speeds[] = { { "1/4", 1.0f }, { "1/8", 0.5f }, { "1/8 triplet", 1.0f / 3.0f },
  401. { "1/16", 0.25f }, { "1/16 triplet", 1.0f / 6.0f }, { "1/32", 0.125f } };
  402. for (const auto& [name, beats] : speeds)
  403. speed.addItem (name, true, std::abs (arp.stepBeats - beats) < 1e-4f, [set, b = beats] { set ([b] (ArpSettings& a) { a.stepBeats = b; }); });
  404. for (int g : { 25, 50, 75, 100 })
  405. gate.addItem (juce::String (g) + "%", true, std::abs (arp.gate - g / 100.0f) < 1e-4f, [set, g] { set ([g] (ArpSettings& a) { a.gate = g / 100.0f; }); });
  406. for (int n : { 1, 2, 3, 4 })
  407. repeat.addItem (juce::String (n) + "x", true, arp.repeat == n, [set, n] { set ([n] (ArpSettings& a) { a.repeat = n; }); });
  408. arpMenu.addSubMenu (utf8 ("Range"), range);
  409. arpMenu.addSubMenu ("Speed", speed);
  410. arpMenu.addSubMenu ("Gate", gate);
  411. arpMenu.addSubMenu (utf8 ("Repeat"), repeat);
  412. menu.addSubMenu (arp.enabled() ? utf8 ("Arpeggiator (on)") : utf8 ("Arpeggiator"), arpMenu);
  413. }
  414. menu.addItem ("Rename...", [this, channel] { rename (channel); });
  415. {
  416. juce::PopupMenu colours;
  417. colours.addItem (utf8 ("Default"), [this, channel] { engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].colour = 0; }); });
  418. for (auto c : { 0xff485156u, 0xffa14547u, 0xffa16f45u, 0xffa19d45u, 0xff6ca145u, 0xff45a175u, 0xff45a1a0u, 0xff457ca1u,
  419. 0xff4f45a1u, 0xff8a5096u, 0xffa1458au })
  420. {
  421. juce::Image swatch (juce::Image::ARGB, 16, 16, true);
  422. juce::Graphics (swatch).fillAll (juce::Colour (c));
  423. juce::PopupMenu::Item item;
  424. item.text = "#" + juce::String::toHexString ((juce::int64) (c & 0xFFFFFF)).paddedLeft ('0', 6).toUpperCase();
  425. item.image = std::make_unique<juce::DrawableImage> (swatch);
  426. item.action = [this, channel, c] { engine.editSong ([channel, c] (Song& s) { s.channels[(std::size_t) channel].colour = c; }); };
  427. colours.addItem (std::move (item));
  428. }
  429. menu.addSubMenu ("Colour", colours);
  430. }
  431. menu.addItem ("Clear notes in this pattern", [this, channel] {
  432. engine.editSong ([channel] (Song& s) {
  433. auto& notes = s.patterns[(std::size_t) s.currentPattern].notes;
  434. notes.erase (std::remove_if (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }),
  435. notes.end());
  436. });
  437. });
  438. menu.addSeparator();
  439. menu.addItem ("Delete channel", engine.getSong().channels.size() > 1, false, [this, channel] {
  440. engine.editSong ([channel] (Song& s) { s.removeChannel (channel); });
  441. });
  442. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  443. }
  444. void ChannelRackComponent::showAddChannelMenu()
  445. {
  446. juce::PopupMenu menu;
  447. for (auto kind : builtInKinds)
  448. menu.addItem (instrumentName (kind), [this, kind] {
  449. engine.editSong ([kind] (Song& s) {
  450. ChannelDef c;
  451. c.name = instrumentName (kind).toStdString();
  452. c.instrument = kind;
  453. c.mixerTrack = s.nextFreeInsert();
  454. s.channels.push_back (c);
  455. });
  456. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  457. });
  458. menu.addSeparator();
  459. menu.addItem ("Sampler (choose file)...", [this] { chooseSample (-1); });
  460. juce::PopupMenu plugins;
  461. addPluginItems (plugins, engine, true, [this] (PluginRef ref) {
  462. engine.editSong ([ref] (Song& s) {
  463. ChannelDef c;
  464. c.name = ref.name;
  465. c.instrument = InstrumentKind::plugin;
  466. c.plugin = ref;
  467. c.mixerTrack = s.nextFreeInsert();
  468. s.channels.push_back (c);
  469. });
  470. const auto added = (int) engine.getSong().channels.size() - 1;
  471. engine.setSelectedChannel (added);
  472. openPluginWindow (added); // as in FL: the plugin opens when added
  473. });
  474. menu.addSubMenu ("Plugin (VST3/CLAP)", plugins);
  475. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  476. }
  477. void ChannelRackComponent::chooseSample (int channel)
  478. {
  479. fileChooser = std::make_unique<juce::FileChooser> ("Choose sample", juce::File(), engine.getSampleLibrary().wildcard());
  480. fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  481. [this, channel] (const juce::FileChooser& chooser) {
  482. if (chooser.getResult().existsAsFile())
  483. assignSample (channel, chooser.getResult());
  484. });
  485. }
  486. void ChannelRackComponent::assignSample (int channel, const juce::File& file)
  487. {
  488. if (engine.getSampleLibrary().load (file.getFullPathName()) == nullptr)
  489. {
  490. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "Sample",
  491. utf8 ("Could not read ") + file.getFileName());
  492. return;
  493. }
  494. const auto path = file.getFullPathName().toStdString();
  495. const auto name = file.getFileNameWithoutExtension().toStdString();
  496. engine.editSong ([channel, path, name] (Song& s) {
  497. const auto isNew = channel < 0 || channel >= (int) s.channels.size();
  498. const auto freeInsert = s.nextFreeInsert();
  499. auto& c = isNew ? s.channels.emplace_back() : s.channels[(std::size_t) channel];
  500. if (isNew)
  501. c.mixerTrack = freeInsert;
  502. c.instrument = InstrumentKind::sampler;
  503. c.samplePath = path;
  504. c.name = name;
  505. });
  506. if (channel < 0)
  507. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  508. }
  509. void ChannelRackComponent::openPluginWindow (int channel)
  510. {
  511. auto instrument = engine.getChannelInstrument (channel);
  512. if (auto* plugin = dynamic_cast<PluginInstrument*> (instrument.get()))
  513. {
  514. PluginWindows::open (instrument, plugin->getInstance(),
  515. juce::String::fromUTF8 (engine.getSong().channels[(std::size_t) channel].name.c_str()));
  516. return;
  517. }
  518. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "Plugin",
  519. utf8 ("This plugin could not be loaded (it is not installed or has not been scanned)."));
  520. }
  521. void ChannelRackComponent::rename (int channel)
  522. {
  523. auto* window = new juce::AlertWindow ("Rename channel", {}, juce::MessageBoxIconType::NoIcon);
  524. window->addTextEditor ("name", juce::String::fromUTF8 (engine.getSong().channels[(std::size_t) channel].name.c_str()));
  525. window->addButton ("OK", 1, juce::KeyPress (juce::KeyPress::returnKey));
  526. window->addButton ("Cancel", 0, juce::KeyPress (juce::KeyPress::escapeKey));
  527. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, channel, window] (int result) {
  528. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  529. if (result == 1 && ! name.empty() && channel < (int) engine.getSong().channels.size())
  530. engine.editSong ([channel, name] (Song& s) { s.channels[(std::size_t) channel].name = name; });
  531. }),
  532. true);
  533. }
  534. void ChannelRackComponent::sliceChannel (int channel)
  535. {
  536. const auto& song = engine.getSong();
  537. const auto& c = song.channels[(std::size_t) channel];
  538. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str()));
  539. if (sample == nullptr || sample->frames() == 0)
  540. return;
  541. const auto slices = detectSlices (*sample, 0.5f);
  542. const auto seconds = (double) sample->frames() / sample->sampleRate;
  543. const auto ticksPerSecond = song.bpm * ppq / 60.0;
  544. const auto name = c.name + " (slices)";
  545. engine.editSong ([&] (Song& s) {
  546. s.channels[(std::size_t) channel].sampler.slices = slices;
  547. // pattern that plays the slices in their original order and timing (at the project BPM)
  548. auto& p = s.patterns.emplace_back();
  549. p.name = name;
  550. for (std::size_t i = 0; i < slices.size(); ++i)
  551. {
  552. const auto start = slices[i] * seconds;
  553. const auto end = i + 1 < slices.size() ? slices[i + 1] * seconds : seconds;
  554. Note n;
  555. n.start = (std::int64_t) std::llround (start * ticksPerSecond);
  556. n.length = std::max<std::int64_t> (1, (std::int64_t) std::llround ((end - start) * ticksPerSecond));
  557. n.key = 60 + (int) i;
  558. n.channel = channel;
  559. p.notes.push_back (n);
  560. }
  561. p.sortNotes();
  562. s.currentPattern = (int) s.patterns.size() - 1;
  563. });
  564. }
  565. bool ChannelRackComponent::isInterestedInFileDrag (const juce::StringArray& files)
  566. {
  567. for (const auto& f : files)
  568. if (juce::File (f).hasFileExtension ("wav;aif;aiff;flac;ogg;mp3"))
  569. return true;
  570. return false;
  571. }
  572. void ChannelRackComponent::filesDropped (const juce::StringArray& files, int x, int y)
  573. {
  574. int row = 0;
  575. const auto area = areaAt (x, y, row);
  576. auto target = (area == Area::none || area == Area::addRow) ? -1 : row;
  577. for (const auto& f : files)
  578. {
  579. const juce::File file (f);
  580. if (! file.hasFileExtension ("wav;aif;aiff;flac;ogg;mp3"))
  581. continue;
  582. assignSample (target, file);
  583. target = -1; // the remaining files become new channels
  584. }
  585. }
  586. void ChannelRackComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  587. {
  588. updateSize();
  589. repaint();
  590. }
  591. void ChannelRackComponent::timerCallback()
  592. {
  593. auto& transport = engine.getTransport();
  594. auto step = -1;
  595. if (transport.playing.load() && engine.getSong().mode == PlayMode::pattern)
  596. {
  597. const auto& song = engine.getSong();
  598. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  599. const auto length = (double) p.effectiveLength (song.beatsPerBar);
  600. step = (int) (std::fmod (transport.positionTicks.load(), length) / ticksPerStep);
  601. }
  602. if (step != playheadStep)
  603. {
  604. auto dirty = [this] (int s) {
  605. if (s >= 0)
  606. repaint (gridLeft() + s * stepWidth, 0, stepWidth, getHeight());
  607. };
  608. dirty (playheadStep);
  609. playheadStep = step;
  610. dirty (playheadStep);
  611. }
  612. }
  613. bool ChannelRackComponent::isInterestedInDragSource (const SourceDetails& details)
  614. {
  615. return details.description.toString() == BrowserComponent::dragDescription;
  616. }
  617. void ChannelRackComponent::itemDropped (const SourceDetails& details)
  618. {
  619. if (auto* tree = dynamic_cast<juce::FileTreeComponent*> (details.sourceComponent.get()))
  620. if (tree->getSelectedFile().existsAsFile())
  621. filesDropped ({ tree->getSelectedFile().getFullPathName() }, details.localPosition.x, details.localPosition.y);
  622. }
  623. } // namespace lynx