ChannelRackComponent.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009
  1. #include "ui/ChannelRackComponent.h"
  2. #include "ui/AutomationUi.h"
  3. #include "core/NoteTools.h"
  4. #include "ui/ToolWindow.h"
  5. #include "core/Slicer.h"
  6. #include "ui/ChannelSettings.h"
  7. #include "engine/Text.h"
  8. #include "ui/Dialogs.h"
  9. #include "ui/HintBar.h"
  10. #include "ui/I18n.h"
  11. #include "ui/BrowserComponent.h"
  12. #include "ui/PluginWindow.h"
  13. #include "ui/Theme.h"
  14. #include "ui/AudioEditor.h"
  15. namespace lynx
  16. {
  17. namespace
  18. {
  19. // English name (used for new channel names stored in the song)
  20. juce::String instrumentName (InstrumentKind k)
  21. {
  22. switch (k)
  23. {
  24. case InstrumentKind::kick: return "Kick";
  25. case InstrumentKind::snare: return "Snare";
  26. case InstrumentKind::hat: return "Hat";
  27. case InstrumentKind::clap: return "Clap";
  28. case InstrumentKind::synth: return "Synth";
  29. case InstrumentKind::sampler: return "Sampler";
  30. case InstrumentKind::audioClip: return "Audio clip";
  31. case InstrumentKind::plugin: return "Plugin";
  32. case InstrumentKind::controller: return "Controller";
  33. case InstrumentKind::sakura: return "Sakura";
  34. case InstrumentKind::drumpad: return "Drumpad";
  35. case InstrumentKind::boobass: return "BooBass";
  36. case InstrumentKind::drumsynth: return "DrumSynth Live";
  37. case InstrumentKind::harmless: return "Harmless";
  38. case InstrumentKind::sytrus: return "Sytrus";
  39. case InstrumentKind::harmor: return "Harmor";
  40. case InstrumentKind::gms: return "GMS";
  41. case InstrumentKind::morphine: return "Morphine";
  42. case InstrumentKind::ogun: return "Ogun";
  43. case InstrumentKind::minisynth: return "MiniSynth";
  44. case InstrumentKind::dx10: return "Fruity DX10";
  45. case InstrumentKind::kepler: return "Kepler";
  46. case InstrumentKind::poizone: return "PoiZone";
  47. case InstrumentKind::fruitkick: return "Fruit Kick";
  48. case InstrumentKind::bassdrum: return "BassDrum";
  49. case InstrumentKind::toxic: return "Toxic Biohazard";
  50. case InstrumentKind::threeosc: return "3x Osc";
  51. case InstrumentKind::autogun: return "Autogun";
  52. case InstrumentKind::transistorbass: return "Transistor Bass";
  53. case InstrumentKind::simsynth: return "SimSynth";
  54. case InstrumentKind::wasp: return "Wasp";
  55. case InstrumentKind::plucked: return "Plucked!";
  56. case InstrumentKind::beepmap: return "BeepMap";
  57. case InstrumentKind::sawer: return "Sawer";
  58. case InstrumentKind::flkeys: return "FL Keys";
  59. case InstrumentKind::granulizer: return "Fruity Granulizer";
  60. case InstrumentKind::drumaxx: return "Drumaxx";
  61. case InstrumentKind::slayer: return "FL Slayer";
  62. case InstrumentKind::fruitydance: return "Fruity Dance";
  63. case InstrumentKind::directwave: return "DirectWave";
  64. }
  65. return "?";
  66. }
  67. // name shown in menus (translated)
  68. juce::String instrumentLabel (InstrumentKind k)
  69. {
  70. switch (k)
  71. {
  72. case InstrumentKind::kick: return tr ("Kick");
  73. case InstrumentKind::snare: return tr ("Snare");
  74. case InstrumentKind::hat: return tr ("Hat");
  75. case InstrumentKind::clap: return tr ("Clap");
  76. case InstrumentKind::synth: return tr ("Synth");
  77. case InstrumentKind::sampler: return tr ("Sampler");
  78. case InstrumentKind::audioClip: return tr ("Audio clip");
  79. case InstrumentKind::controller: return tr ("Controller");
  80. default: return instrumentName (k);
  81. }
  82. }
  83. constexpr InstrumentKind builtInKinds[] = { InstrumentKind::kick, InstrumentKind::snare, InstrumentKind::hat,
  84. InstrumentKind::clap, InstrumentKind::synth };
  85. void setStep (Pattern& p, int channel, int step, bool on)
  86. {
  87. if (p.hasStep (channel, step) != on)
  88. p.toggleStep (channel, step);
  89. }
  90. juce::String channelName (const Song& song, int row)
  91. {
  92. return row >= 0 && row < (int) song.channels.size() ? juce::String::fromUTF8 (song.channels[(std::size_t) row].name.c_str()) : juce::String();
  93. }
  94. } // namespace
  95. bool ChannelRackComponent::keepEditorsOpen = false;
  96. ChannelRackComponent::ChannelRackComponent (AudioEngine& e)
  97. : engine (e)
  98. {
  99. setWantsKeyboardFocus (false);
  100. setMouseClickGrabsKeyboardFocus (false);
  101. engine.addChangeListener (this);
  102. previews.setSender ([this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on); });
  103. updateSize();
  104. startTimerHz (30);
  105. }
  106. ChannelRackComponent::~ChannelRackComponent()
  107. {
  108. previews.releaseAll();
  109. engine.removeChangeListener (this);
  110. }
  111. void ChannelRackComponent::moved()
  112. {
  113. // the viewport scrolled the rack sideways: the controls column follows the visible left edge
  114. const auto x = juce::jmax (0, -getX());
  115. if (x != stickyX)
  116. {
  117. stickyX = x;
  118. repaint();
  119. }
  120. }
  121. void ChannelRackComponent::visibilityChanged()
  122. {
  123. if (! isShowing())
  124. previews.releaseAll(); // hidden mid-gesture: nothing keeps sounding
  125. }
  126. int ChannelRackComponent::numSteps() const
  127. {
  128. const auto& song = engine.getSong();
  129. if (song.patterns.empty())
  130. return 16;
  131. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  132. const auto steps = (int) (p.effectiveLength (song.beatsPerBar) / ticksPerStep);
  133. return juce::jlimit (16, 512, steps);
  134. }
  135. void ChannelRackComponent::updateSize()
  136. {
  137. const auto rows = (int) engine.getSong().channels.size() + 1; // +1 = "add channel" row
  138. setSize (gridLeft() + numSteps() * stepWidth + 8, rows * rowHeight + 8 + (graphRow() >= 0 ? laneHeight : 0));
  139. }
  140. int ChannelRackComponent::graphRow() const
  141. {
  142. const auto count = (int) engine.getSong().channels.size();
  143. return graphLanes && count > 0 ? juce::jlimit (0, count - 1, engine.getSelectedChannel()) : -1;
  144. }
  145. int ChannelRackComponent::rowY (int row) const
  146. {
  147. const auto lane = graphRow();
  148. return 4 + row * rowHeight + (lane >= 0 && row > lane ? laneHeight : 0);
  149. }
  150. int ChannelRackComponent::rowAtY (int y) const
  151. {
  152. if (y < 4)
  153. return -1;
  154. if (const auto lane = graphRow(); lane >= 0)
  155. {
  156. const auto laneTop = rowY (lane) + rowHeight;
  157. if (y >= laneTop && y < laneTop + laneHeight)
  158. return lane;
  159. if (y >= laneTop + laneHeight)
  160. y -= laneHeight;
  161. }
  162. return (y - 4) / rowHeight;
  163. }
  164. juce::Rectangle<int> ChannelRackComponent::laneBounds() const
  165. {
  166. const auto lane = graphRow();
  167. return lane < 0 ? juce::Rectangle<int>() : juce::Rectangle<int> (0, rowY (lane) + rowHeight, getWidth(), laneHeight);
  168. }
  169. juce::Rectangle<int> ChannelRackComponent::rowBounds (int row) const
  170. {
  171. return { 0, rowY (row), getWidth(), rowHeight };
  172. }
  173. juce::Rectangle<int> ChannelRackComponent::stepBounds (int row, int step) const
  174. {
  175. return { gridLeft() + step * stepWidth + 1, rowY (row) + 4, stepWidth - 3, rowHeight - 8 };
  176. }
  177. ChannelRackComponent::Area ChannelRackComponent::areaAt (int x, int y, int& row) const
  178. {
  179. const auto channels = (int) engine.getSong().channels.size();
  180. row = rowAtY (y);
  181. if (x < stickyX + gridLeft()) // the controls column (painted at the visible left edge)
  182. x -= stickyX;
  183. if (row < 0 || row > channels)
  184. return Area::none;
  185. if (laneBounds().contains (x, y))
  186. return x < gridLeft() ? Area::laneLevels : Area::lane;
  187. if (row == channels)
  188. return x < gridLeft() ? Area::addRow : Area::none;
  189. if (x < muteWidth)
  190. return Area::mute;
  191. if (x < muteWidth + knobWidth)
  192. return Area::pan;
  193. if (x < muteWidth + 2 * knobWidth)
  194. return Area::volume;
  195. if (x < nameLeft())
  196. return Area::route;
  197. if (x < selectLeft())
  198. return Area::name;
  199. if (x < gridLeft())
  200. return Area::select;
  201. return Area::grid;
  202. }
  203. bool ChannelRackComponent::cellHasNote (int channel, int step) const
  204. {
  205. const auto& song = engine.getSong();
  206. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  207. const auto from = (std::int64_t) step * ticksPerStep;
  208. const auto to = from + ticksPerStep;
  209. for (const auto& n : p.notes)
  210. if (n.channel == channel && n.start >= from && n.start < to)
  211. return true;
  212. return false;
  213. }
  214. void ChannelRackComponent::paint (juce::Graphics& g)
  215. {
  216. using namespace theme::colour;
  217. g.fillAll (bg2);
  218. const auto& song = engine.getSong();
  219. if (song.patterns.empty())
  220. return;
  221. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  222. const auto steps = numSteps();
  223. const auto clip = g.getClipBounds();
  224. const auto primary = engine.getSelectedChannel();
  225. const auto& selection = engine.getSelectedChannels();
  226. g.setFont (theme::font (theme::type::body));
  227. for (int row = 0; row < (int) song.channels.size(); ++row)
  228. {
  229. const auto y = rowY (row);
  230. if (y > clip.getBottom() || y + rowHeight < clip.getY())
  231. continue;
  232. const auto& channel = song.channels[(std::size_t) row];
  233. const auto selected = std::binary_search (selection.begin(), selection.end(), row);
  234. if (selected) // selected rows are subtly lifted
  235. {
  236. g.setColour (bg3);
  237. g.fillRect (0, y + 1, getWidth(), rowHeight - 2);
  238. }
  239. if (channel.instrument == InstrumentKind::audioClip)
  240. {
  241. g.setColour (textDisabled);
  242. g.setFont (theme::font (theme::type::small));
  243. g.drawText (tr ("audio clip — plays from the Playlist"), gridLeft() + 4, y, 400, rowHeight, juce::Justification::centredLeft);
  244. g.setFont (theme::font (theme::type::body));
  245. continue;
  246. }
  247. if (showsNotePreview (pattern, row)) // piano-roll notes: a miniature instead of the step buttons
  248. {
  249. paintNotePreview (g, row, pattern, channel.colour);
  250. continue;
  251. }
  252. for (int step = 0; step < steps; ++step)
  253. {
  254. const auto r = stepBounds (row, step);
  255. if (r.getRight() < clip.getX() || r.getX() > clip.getRight())
  256. continue;
  257. const auto onGrid = pattern.hasStep (row, step);
  258. const auto any = onGrid || cellHasNote (row, step);
  259. const auto hoverStepHere = hoverArea == Area::grid && hoverRow == row && hoverStep == step && paintMode == PaintMode::none;
  260. const auto fill = any ? (onGrid ? stepOn : stepNote) : theme::stepOff (step);
  261. g.setColour (hoverStepHere ? fill.brighter (any ? 0.15f : 0.35f) : fill);
  262. g.fillRoundedRectangle (r.toFloat(), theme::radius::sm);
  263. if (hoverStepHere)
  264. {
  265. g.setColour (textSecondary.withAlpha (0.7f));
  266. g.drawRoundedRectangle (r.toFloat().reduced (0.5f), theme::radius::sm, 1.0f);
  267. }
  268. }
  269. }
  270. paintLane (g);
  271. const auto addY = rowY ((int) song.channels.size());
  272. g.setColour (textDisabled);
  273. g.setFont (theme::font (theme::type::small));
  274. g.drawText (tr ("or drop an audio file here"), gridLeft() + 4, addY, 400, rowHeight, juce::Justification::centredLeft);
  275. if (playheadStep >= 0 && playheadStep < steps)
  276. {
  277. g.setColour (playhead.withAlpha (0.28f));
  278. g.fillRoundedRectangle (juce::Rectangle<float> ((float) (gridLeft() + playheadStep * stepWidth), 2.0f, (float) stepWidth - 2.0f,
  279. (float) addY - 2.0f), theme::radius::sm);
  280. }
  281. // the controls column stays put while the steps scroll sideways (FL's rack keeps the channel buttons in
  282. // view): the viewport moves the whole rack, so the column is painted again at the visible left edge
  283. {
  284. juce::Graphics::ScopedSaveState state (g);
  285. g.reduceClipRegion (stickyX, 0, gridLeft(), getHeight());
  286. g.setOrigin (stickyX, 0);
  287. g.setColour (bg2);
  288. g.fillRect (0, 0, gridLeft(), getHeight());
  289. const auto column = g.getClipBounds();
  290. for (int row = 0; row < (int) song.channels.size(); ++row)
  291. {
  292. const auto y = rowY (row);
  293. if (y > column.getBottom() || y + rowHeight < column.getY())
  294. continue;
  295. const auto& channel = song.channels[(std::size_t) row];
  296. const auto selected = std::binary_search (selection.begin(), selection.end(), row);
  297. const auto nameArea = juce::Rectangle<float> ((float) nameLeft(), (float) y + 3, (float) nameWidth, (float) rowHeight - 6);
  298. if (selected) // selected rows are subtly lifted
  299. {
  300. g.setColour (bg3);
  301. g.fillRect (0, y + 1, getWidth(), rowHeight - 2);
  302. }
  303. const auto hovered = [this, row] (Area a) { return hoverRow == row && hoverArea == a; };
  304. const auto led = juce::Rectangle<float> (9.0f, (float) y + rowHeight / 2.0f - 4.5f, 9.0f, 9.0f);
  305. g.setColour (theme::muteLed (channel.muted));
  306. g.fillEllipse (led);
  307. if (hovered (Area::mute)) // hover ring
  308. {
  309. g.setColour (textSecondary.withAlpha (0.8f));
  310. g.drawEllipse (led.expanded (2.5f), 1.0f);
  311. }
  312. const auto touched = knobDrag != Area::none && knobRow == row;
  313. theme::drawKnob (g, controlBounds (Area::pan, row).toFloat().reduced (1.0f, 2.0f), (channel.pan + 1.0f) / 2.0f, true,
  314. touched && knobDrag == Area::pan ? accent : info, hovered (Area::pan) || (touched && knobDrag == Area::pan));
  315. theme::drawKnob (g, controlBounds (Area::volume, row).toFloat().reduced (1.0f, 2.0f), channel.volume, false,
  316. touched && knobDrag == Area::volume ? accent : knobArc, hovered (Area::volume) || (touched && knobDrag == Area::volume));
  317. // small box with the mixer insert ("-" = straight to Master)
  318. const auto routeArea = controlBounds (Area::route, row).toFloat();
  319. g.setColour (hovered (Area::route) || (touched && knobDrag == Area::route) ? bg4 : bg0);
  320. g.fillRoundedRectangle (routeArea, theme::radius::sm);
  321. if (hovered (Area::route))
  322. {
  323. g.setColour (borderStrong);
  324. g.drawRoundedRectangle (routeArea.reduced (0.5f), theme::radius::sm, 1.0f);
  325. }
  326. g.setColour (channel.mixerTrack > 0 ? textPrimary : textDisabled);
  327. g.setFont (theme::font (theme::type::caption, true));
  328. g.drawText (channel.mixerTrack > 0 ? juce::String (channel.mixerTrack) : juce::String ("-"), routeArea.toNearestInt(),
  329. juce::Justification::centred);
  330. g.setFont (theme::font (theme::type::body));
  331. // name button: tinted with the channel colour (from the .flp or user-picked), so channels are found by
  332. // colour as in FL; kept dark and toned down (LYNX look), with the colour strip at its left
  333. {
  334. auto plate = row == primary ? bg6 : hovered (Area::name) ? bg5 : bg4;
  335. if (channel.colour != 0)
  336. plate = plate.interpolatedWith (theme::tame (juce::Colour (channel.colour)), row == primary ? 0.42f : 0.32f);
  337. g.setColour (plate);
  338. g.fillRoundedRectangle (nameArea, theme::radius::md);
  339. }
  340. if (row == primary)
  341. {
  342. g.setColour (accent);
  343. g.drawRoundedRectangle (nameArea.reduced (0.5f), theme::radius::md, 1.0f);
  344. }
  345. g.setColour (channel.colour != 0 ? theme::tame (juce::Colour (channel.colour)) : bg6.brighter (0.2f));
  346. g.fillRoundedRectangle (nameArea.withWidth (4.0f).reduced (0.0f, 3.0f).translated (3.0f, 0.0f), 1.5f);
  347. g.setColour (channel.muted ? textDisabled : textPrimary);
  348. g.drawText (juce::String::fromUTF8 (channel.name.c_str()), nameArea.withTrimmedLeft (14).withTrimmedRight (6).toNearestInt(),
  349. juce::Justification::centredLeft, true);
  350. // selector: a slim pill, lit when the row is selected
  351. const auto pill = juce::Rectangle<float> ((float) selectLeft() + 3.0f, (float) y + 7.0f, (float) selectWidth - 6.0f, (float) rowHeight - 14.0f);
  352. g.setColour (selected ? (hovered (Area::select) ? accentHover : accent) : hovered (Area::select) ? textDisabled : ledOff);
  353. g.fillRoundedRectangle (pill, 3.0f);
  354. }
  355. paintLane (g);
  356. {
  357. const auto addArea = juce::Rectangle<float> ((float) nameLeft(), (float) addY + 3, (float) nameWidth, (float) rowHeight - 6);
  358. const float dash[] = { 3.0f, 3.0f };
  359. juce::Path outline, dashed;
  360. outline.addRoundedRectangle (addArea.reduced (0.5f), theme::radius::md);
  361. juce::PathStrokeType (1.0f).createDashedStroke (dashed, outline, dash, 2);
  362. const auto addHovered = hoverArea == Area::addRow;
  363. g.setColour (addHovered ? textSecondary : borderStrong);
  364. g.fillPath (dashed);
  365. g.setColour (addHovered ? textPrimary : textSecondary);
  366. g.setFont (theme::font (theme::type::small));
  367. g.drawText (tr ("+ add channel"), addArea.toNearestInt(), juce::Justification::centred);
  368. }
  369. if (stickyX > 0) // steps pass under the column: a hairline marks its edge
  370. {
  371. g.setColour (border);
  372. g.fillRect (gridLeft() - 1, 0, 1, getHeight());
  373. }
  374. }
  375. }
  376. // The miniature of a channel's piano-roll notes across its step area (FL shows one once a channel has notes
  377. // that steps can't show); the notes keep their time and length, pitch maps onto the row's height.
  378. void ChannelRackComponent::paintNotePreview (juce::Graphics& g, int row, const Pattern& pattern, std::uint32_t channelColour)
  379. {
  380. using namespace theme::colour;
  381. const auto steps = numSteps();
  382. const auto area = juce::Rectangle<float> ((float) gridLeft() + 1.0f, (float) rowY (row) + 4.0f, (float) (steps * stepWidth) - 3.0f,
  383. (float) rowHeight - 8.0f);
  384. const auto hoveredHere = hoverArea == Area::grid && hoverRow == row;
  385. g.setColour (hoveredHere ? bg4 : bg1);
  386. g.fillRoundedRectangle (area, theme::radius::sm);
  387. for (int beat = 4; beat < steps; beat += 4) // beat lines, bars a little stronger
  388. {
  389. g.setColour (beat % 16 == 0 ? border.brighter (0.2f) : border);
  390. g.fillRect (area.getX() + (float) (beat * stepWidth) - 1.5f, area.getY() + 2.0f, 1.0f, area.getHeight() - 4.0f);
  391. }
  392. const auto [low, high] = channelKeyRange (pattern, row);
  393. const auto span = juce::jmax (high - low, 6); // a single key sits mid-row, not on an edge
  394. const auto lowKey = low - (span - (high - low)) / 2;
  395. const auto inner = area.reduced (1.0f, 3.0f);
  396. const auto noteHeight = juce::jlimit (3.0f, 5.0f, inner.getHeight() / (float) (span + 1));
  397. const auto ticks = (float) (steps * ticksPerStep);
  398. const auto tint = channelColour != 0 ? theme::tame (juce::Colour (channelColour)).brighter (0.6f) : stepNote;
  399. for (const auto& n : pattern.notes)
  400. {
  401. if (n.channel != row)
  402. continue;
  403. const auto x = inner.getX() + inner.getWidth() * (float) n.start / ticks;
  404. if (x > inner.getRight())
  405. break;
  406. const auto w = juce::jmax (2.0f, inner.getWidth() * (float) n.length / ticks - 1.0f);
  407. const auto y = inner.getBottom() - noteHeight - (inner.getHeight() - noteHeight) * (float) (n.key - lowKey) / (float) span;
  408. g.setColour (n.muted ? textDisabled : tint);
  409. g.fillRect (juce::Rectangle<float> (x, y, juce::jmin (w, inner.getRight() - x), noteHeight));
  410. }
  411. }
  412. // --- the control contract for the knobs and the route box ----------------------------------------
  413. ui::ValueSpec ChannelRackComponent::specFor (Area area, int row) const
  414. {
  415. const auto name = channelName (engine.getSong(), row);
  416. if (area == Area::pan)
  417. {
  418. auto spec = ui::panSpec (name + " - " + tr ("Pan"));
  419. spec.target = AutomationTarget { AutomationTargetKind::channelPan, row };
  420. return spec;
  421. }
  422. if (area == Area::volume)
  423. {
  424. auto spec = ui::percentSpec (name + " - " + tr ("Volume"), 0.78);
  425. spec.target = AutomationTarget { AutomationTargetKind::channelVolume, row };
  426. return spec;
  427. }
  428. // route box: the mixer insert, as a number
  429. ui::ValueSpec spec;
  430. spec.name = name + " - " + tr ("Mixer insert");
  431. spec.maximum = juce::jmax (0, (int) engine.getSong().mixer.size() - 1);
  432. spec.interval = 1.0;
  433. spec.pixelsForRange = 6.0 * juce::jmax (1.0, spec.maximum);
  434. spec.toText = [] (double v) { return v < 0.5 ? tr ("Master") : tr ("Insert {0}", { juce::String (juce::roundToInt (v)) }); };
  435. spec.fromText = [] (const juce::String& t) -> std::optional<double> {
  436. if (t.trim().startsWithIgnoreCase ("m"))
  437. return 0.0;
  438. const auto digits = t.retainCharacters ("0123456789");
  439. return digits.isEmpty() ? std::nullopt : std::optional<double> (digits.getDoubleValue());
  440. };
  441. return spec;
  442. }
  443. double ChannelRackComponent::valueOf (Area area, int row) const
  444. {
  445. const auto& c = engine.getSong().channels[(std::size_t) row];
  446. return area == Area::pan ? c.pan : area == Area::volume ? c.volume : (double) c.mixerTrack;
  447. }
  448. void ChannelRackComponent::setValue (Area area, int row, double value)
  449. {
  450. if (row < 0 || row >= (int) engine.getSong().channels.size())
  451. return;
  452. if (area == Area::pan)
  453. engine.editSong ([row, v = (float) value] (Song& s) { s.channels[(std::size_t) row].pan = v; });
  454. else if (area == Area::volume)
  455. engine.editSong ([row, v = (float) value] (Song& s) { s.channels[(std::size_t) row].volume = v; });
  456. else if (area == Area::route)
  457. {
  458. const auto track = juce::roundToInt (value);
  459. if (track != engine.getSong().channels[(std::size_t) row].mixerTrack)
  460. engine.editSong ([row, track] (Song& s) { s.channels[(std::size_t) row].mixerTrack = track; });
  461. }
  462. }
  463. juce::Rectangle<int> ChannelRackComponent::controlBounds (Area area, int row) const
  464. {
  465. const auto y = rowY (row);
  466. switch (area)
  467. {
  468. case Area::pan: return { muteWidth, y, knobWidth, rowHeight };
  469. case Area::volume: return { muteWidth + knobWidth, y, knobWidth, rowHeight };
  470. case Area::route: return { muteWidth + 2 * knobWidth + 1, y + 7, routeWidth - 3, rowHeight - 14 };
  471. case Area::lane:
  472. {
  473. const auto lane = laneBounds();
  474. const auto step = juce::jmax (0, hoverStep);
  475. return { gridLeft() + step * stepWidth, lane.getY() + 6, stepWidth, lane.getHeight() - 12 };
  476. }
  477. default: return {};
  478. }
  479. }
  480. void ChannelRackComponent::showTip (Area area, int row, bool transient)
  481. {
  482. if (row < 0 || row >= (int) engine.getSong().channels.size())
  483. return;
  484. const auto spec = specFor (area, row);
  485. const auto text = spec.text (valueOf (area, row));
  486. ui::postHint (ui::valueHint (spec, valueOf (area, row), ui::valueGestures()));
  487. const auto bounds = area == Area::lane ? controlBounds (area, row) : controlBounds (area, row).translated (stickyX, 0);
  488. if (transient)
  489. ui::flashValueTip (*this, bounds, text);
  490. else
  491. ui::showValueTip (*this, bounds, text);
  492. }
  493. void ChannelRackComponent::setHover (Area area, int row, int step)
  494. {
  495. if (area == hoverArea && row == hoverRow && step == hoverStep)
  496. return;
  497. auto dirty = [this] (Area a, int r) {
  498. if (a == Area::lane || a == Area::laneLevels)
  499. repaint (laneBounds());
  500. else if (a == Area::addRow)
  501. repaint (rowBounds ((int) engine.getSong().channels.size()));
  502. else if (r >= 0)
  503. repaint (rowBounds (r));
  504. };
  505. dirty (hoverArea, hoverRow);
  506. hoverArea = area;
  507. hoverRow = row;
  508. hoverStep = step;
  509. dirty (hoverArea, hoverRow);
  510. }
  511. void ChannelRackComponent::mouseMove (const juce::MouseEvent& e)
  512. {
  513. int row = 0;
  514. const auto area = areaAt (e.x, e.y, row);
  515. const auto step = area == Area::grid || area == Area::lane ? (e.x - gridLeft()) / stepWidth : -1;
  516. setHover (area, row, step >= 0 && step < numSteps() ? step : -1);
  517. }
  518. void ChannelRackComponent::mouseExit (const juce::MouseEvent&)
  519. {
  520. setHover (Area::none, -1, -1);
  521. }
  522. void ChannelRackComponent::setSwingMixOfSelected (int channel)
  523. {
  524. const auto& song = engine.getSong();
  525. if (channel < 0 || channel >= (int) song.channels.size())
  526. return;
  527. auto spec = ui::percentSpec (channelName (song, channel) + " - " + tr ("Swing mix"), 1.0);
  528. const auto rows = engine.getSelectedChannels();
  529. ui::typeValue (*this, spec, song.channels[(std::size_t) channel].swingMix, [this, rows, channel] (double v) {
  530. engine.editSong ([rows, channel, v] (Song& s) {
  531. auto targets = rows;
  532. if (std::find (targets.begin(), targets.end(), channel) == targets.end())
  533. targets = { channel };
  534. for (auto r : targets)
  535. if (r >= 0 && r < (int) s.channels.size())
  536. s.channels[(std::size_t) r].swingMix = (float) v;
  537. });
  538. });
  539. }
  540. // --- selection -----------------------------------------------------------------------------------
  541. void ChannelRackComponent::selectRows (std::vector<int> rows, int primary)
  542. {
  543. engine.setChannelSelection (std::move (rows), primary);
  544. repaint();
  545. }
  546. void ChannelRackComponent::clickSelector (int row, const juce::ModifierKeys& mods)
  547. {
  548. ChannelSelection selection;
  549. selection.rows = engine.getSelectedChannels();
  550. selection.anchor = selectionAnchor;
  551. if (mods.isShiftDown())
  552. selection.extendTo (row);
  553. else if (mods.isCtrlDown() || mods.isPopupMenu())
  554. selection.toggle (row);
  555. else
  556. selection.selectOnly (row);
  557. selectionAnchor = selection.anchor;
  558. const auto primary = selection.contains (row) ? row : selection.rows.front();
  559. selectRows (selection.rows, primary);
  560. }
  561. void ChannelRackComponent::selectRelative (int delta, bool extend)
  562. {
  563. const auto count = (int) engine.getSong().channels.size();
  564. if (count == 0)
  565. return;
  566. const auto row = juce::jlimit (0, count - 1, engine.getSelectedChannel() + delta);
  567. if (extend)
  568. {
  569. ChannelSelection selection;
  570. selection.anchor = selectionAnchor;
  571. selection.extendTo (row);
  572. selectRows (selection.rows, row);
  573. }
  574. else
  575. {
  576. selectionAnchor = row;
  577. selectRows ({ row }, row);
  578. }
  579. }
  580. void ChannelRackComponent::selectAll()
  581. {
  582. ChannelSelection selection;
  583. selection.selectAll ((int) engine.getSong().channels.size());
  584. selectRows (selection.rows, engine.getSelectedChannel());
  585. }
  586. bool ChannelRackComponent::moveSelected (int delta)
  587. {
  588. auto rows = engine.getSelectedChannels();
  589. const auto primary = engine.getSelectedChannel();
  590. const auto primaryIndex = (int) (std::find (rows.begin(), rows.end(), primary) - rows.begin());
  591. bool moved = false;
  592. std::vector<int> after;
  593. engine.editSong ([&] (Song& s) {
  594. after = rows;
  595. moved = moveChannels (s, after, delta);
  596. });
  597. if (! moved)
  598. return false;
  599. const auto newPrimary = primaryIndex < (int) after.size() ? after[(std::size_t) primaryIndex] : after.front();
  600. openEditorRow = -1;
  601. selectionAnchor = juce::jlimit (0, (int) engine.getSong().channels.size() - 1, selectionAnchor + delta);
  602. selectRows (after, newPrimary);
  603. return true;
  604. }
  605. void ChannelRackComponent::cloneSelected()
  606. {
  607. auto rows = engine.getSelectedChannels();
  608. std::vector<int> clones;
  609. engine.editSong ([&] (Song& s) {
  610. // from the bottom up, so earlier clones don't shift the rows still to clone
  611. for (auto it = rows.rbegin(); it != rows.rend(); ++it)
  612. cloneChannel (s, *it);
  613. });
  614. // each clone sits right below its original: original i (sorted) ends at rows[i] + i, its clone one below
  615. for (std::size_t i = 0; i < rows.size(); ++i)
  616. clones.push_back (rows[i] + (int) i + 1);
  617. if (! clones.empty())
  618. selectRows (clones, clones.front());
  619. }
  620. void ChannelRackComponent::deleteSelected()
  621. {
  622. const auto rows = engine.getSelectedChannels();
  623. const auto count = (int) engine.getSong().channels.size();
  624. if (rows.empty() || (int) rows.size() >= count) // at least one channel stays
  625. return;
  626. for (auto r : rows)
  627. closeEditor (r);
  628. engine.editSong ([rows] (Song& s) { removeChannels (s, rows); });
  629. openEditorRow = -1;
  630. const auto row = juce::jlimit (0, juce::jmax (0, (int) engine.getSong().channels.size() - 1), rows.front());
  631. selectRows ({ row }, row);
  632. }
  633. void ChannelRackComponent::sendSelectedToInserts()
  634. {
  635. const auto rows = engine.getSelectedChannels();
  636. engine.editSong ([rows] (Song& s) { sendChannelsToFreeInserts (s, rows); });
  637. }
  638. void ChannelRackComponent::toggleMute (int channel)
  639. {
  640. if (channel >= 0 && channel < (int) engine.getSong().channels.size())
  641. engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].muted = ! s.channels[(std::size_t) channel].muted; });
  642. }
  643. void ChannelRackComponent::solo (int row)
  644. {
  645. if (row < 0 || row >= (int) engine.getSong().channels.size())
  646. return;
  647. // only this channel plays; repeating on the already-soloed channel unmutes all
  648. engine.editSong ([row] (Song& s) {
  649. const auto alone = ! s.channels[(std::size_t) row].muted
  650. && std::all_of (s.channels.begin(), s.channels.end(), [&] (const ChannelDef& c) {
  651. return &c == &s.channels[(std::size_t) row] || c.muted;
  652. });
  653. for (std::size_t i = 0; i < s.channels.size(); ++i)
  654. s.channels[i].muted = alone ? false : i != (std::size_t) row;
  655. });
  656. }
  657. // --- channel editors ---------------------------------------------------------------------------
  658. bool ChannelRackComponent::isEditorOpen (int channel)
  659. {
  660. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  661. return false;
  662. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::plugin)
  663. {
  664. if (auto* plugin = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get()))
  665. return PluginWindows::isOpen (plugin->getInstance());
  666. return false;
  667. }
  668. return isChannelSettingsOpen (channel);
  669. }
  670. void ChannelRackComponent::closeEditor (int channel)
  671. {
  672. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  673. return;
  674. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::plugin)
  675. {
  676. if (auto* plugin = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get()))
  677. PluginWindows::close (plugin->getInstance());
  678. }
  679. else
  680. closeChannelSettings (channel);
  681. }
  682. void ChannelRackComponent::toggleEditor (int channel, bool keepOthers)
  683. {
  684. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  685. return;
  686. const auto kind = engine.getSong().channels[(std::size_t) channel].instrument;
  687. if (kind != InstrumentKind::plugin && ! hasChannelSettings (kind))
  688. return; // built-in drums and audio clips have no editor window: the click only selects
  689. if (isEditorOpen (channel))
  690. {
  691. closeEditor (channel);
  692. if (openEditorRow == channel)
  693. openEditorRow = -1;
  694. return;
  695. }
  696. if (! keepOthers && ! keepEditorsOpen && openEditorRow != channel)
  697. closeEditor (openEditorRow);
  698. if (kind == InstrumentKind::plugin)
  699. openPluginWindow (channel);
  700. else
  701. openChannelSettings (engine, channel);
  702. openEditorRow = channel;
  703. }
  704. // --- step graph lanes (docs/WORKFLOW_FL.md P2, C4) --------------------------------------------------
  705. juce::Rectangle<int> ChannelRackComponent::levelButtonBounds (int level) const
  706. {
  707. const auto lane = laneBounds();
  708. const auto width = (gridLeft() - 24) / 3;
  709. return { 12 + (level % 3) * width, lane.getY() + 8 + (level / 3) * 24, width - 4, 20 };
  710. }
  711. void ChannelRackComponent::paintLane (juce::Graphics& g)
  712. {
  713. using namespace theme::colour;
  714. const auto lane = laneBounds();
  715. if (lane.isEmpty() || ! g.getClipBounds().intersects (lane))
  716. return;
  717. const auto& song = engine.getSong();
  718. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  719. const auto channel = graphRow();
  720. const auto level = (notetools::Level) graphLevel;
  721. g.setColour (bg0);
  722. g.fillRect (lane);
  723. g.setColour (border);
  724. g.drawHorizontalLine (lane.getY(), 0.0f, (float) getWidth());
  725. g.drawHorizontalLine (lane.getBottom() - 1, 0.0f, (float) getWidth());
  726. for (int l = 0; l < notetools::levelCount; ++l)
  727. {
  728. const auto r = levelButtonBounds (l).toFloat();
  729. g.setColour (l == graphLevel ? accent : bg4);
  730. g.fillRoundedRectangle (r, theme::radius::sm);
  731. g.setColour (l == graphLevel ? onAccent : textSecondary);
  732. g.setFont (theme::font (theme::type::caption, l == graphLevel));
  733. g.drawFittedText (tr (notetools::levelName ((notetools::Level) l)), r.toNearestInt(), juce::Justification::centred, 1, 0.8f);
  734. }
  735. g.setColour (textDisabled);
  736. g.setFont (theme::font (theme::type::caption));
  737. g.drawFittedText (tr ("Drag: set · Right-drag: ramp · Alt+click: reset"),
  738. juce::Rectangle<int> (12, lane.getBottom() - 20, gridLeft() - 24, 16), juce::Justification::centredLeft, 1, 0.8f);
  739. const auto top = (float) lane.getY() + 6.0f, bottom = (float) lane.getBottom() - 6.0f;
  740. const auto bipolar = notetools::levelIsBipolar (level);
  741. const auto base = bipolar ? (top + bottom) * 0.5f : bottom;
  742. for (int step = 0; step < numSteps(); ++step)
  743. {
  744. const auto x = (float) (gridLeft() + step * stepWidth + 1);
  745. const auto w = (float) stepWidth - 3.0f;
  746. if (step % 4 == 0 && step > 0)
  747. {
  748. g.setColour (step % 16 == 0 ? gridBar : gridBeat);
  749. g.drawVerticalLine ((int) x - 2, top, bottom);
  750. }
  751. if (hoverArea == Area::lane && hoverStep == step)
  752. {
  753. g.setColour (bg3);
  754. g.fillRect (juce::Rectangle<float> (x, top, w, bottom - top));
  755. }
  756. const auto notes = notesInStep (pattern, channel, step);
  757. if (notes.empty())
  758. {
  759. g.setColour (theme::stepOff (step));
  760. g.fillRect (x + w * 0.5f - 1.0f, base - 1.0f, 2.0f, 2.0f);
  761. continue;
  762. }
  763. const auto v = notetools::levelValue (pattern.notes[(std::size_t) notes.front()], level);
  764. const auto y = bottom - v * (bottom - top);
  765. g.setColour ((level == notetools::Level::velocity ? accent : info).withAlpha (0.85f));
  766. g.fillRect (juce::Rectangle<float> (x + 2.0f, juce::jmin (y, base), w - 4.0f, juce::jmax (2.0f, std::abs (base - y))));
  767. g.setColour (textPrimary);
  768. g.fillRect (x + 1.0f, y - 1.0f, w - 2.0f, 2.0f);
  769. }
  770. if (bipolar)
  771. {
  772. g.setColour (gridBar);
  773. g.drawHorizontalLine ((int) base, (float) gridLeft(), (float) getWidth());
  774. }
  775. }
  776. float ChannelRackComponent::laneValueAt (int y) const
  777. {
  778. const auto lane = laneBounds();
  779. const auto top = (float) lane.getY() + 6.0f, bottom = (float) lane.getBottom() - 6.0f;
  780. return juce::jlimit (0.0f, 1.0f, (bottom - (float) y) / juce::jmax (1.0f, bottom - top));
  781. }
  782. void ChannelRackComponent::setLaneValue (int step, float value)
  783. {
  784. const auto channel = graphRow();
  785. const auto level = (notetools::Level) graphLevel;
  786. engine.editSong ([channel, step, value, level] (Song& s) {
  787. auto& p = s.patterns[(std::size_t) s.currentPattern];
  788. for (auto i : notesInStep (p, channel, step))
  789. notetools::setLevelValue (p.notes[(std::size_t) i], level, value);
  790. });
  791. }
  792. void ChannelRackComponent::applyLane (const juce::MouseEvent& e)
  793. {
  794. const auto steps = numSteps();
  795. const auto step = juce::jlimit (0, steps - 1, (e.x - gridLeft()) / stepWidth);
  796. const auto value = laneValueAt (e.y);
  797. if (e.mods.isRightButtonDown()) // a straight ramp from the press to here
  798. {
  799. const auto from = juce::jmin (laneDownStep, step), to = juce::jmax (laneDownStep, step);
  800. const auto channel = graphRow();
  801. const auto level = (notetools::Level) graphLevel;
  802. const auto v0 = laneDownStep <= step ? laneDownValue : value, v1 = laneDownStep <= step ? value : laneDownValue;
  803. engine.editSong ([=] (Song& s) {
  804. auto& p = s.patterns[(std::size_t) s.currentPattern];
  805. for (int st = from; st <= to; ++st)
  806. {
  807. const auto t = to > from ? (float) (st - from) / (float) (to - from) : 0.0f;
  808. for (auto i : notesInStep (p, channel, st))
  809. notetools::setLevelValue (p.notes[(std::size_t) i], level, v0 + (v1 - v0) * t);
  810. }
  811. });
  812. return;
  813. }
  814. setLaneValue (step, value);
  815. }
  816. void ChannelRackComponent::toggleGraphLanes()
  817. {
  818. graphLanes = ! graphLanes;
  819. updateSize();
  820. repaint();
  821. }
  822. // --- fills, rotation and organisation ------------------------------------------------------------
  823. void ChannelRackComponent::rotateSelected (int steps)
  824. {
  825. const auto rows = engine.getSelectedChannels();
  826. engine.editSong ([rows, steps] (Song& s) {
  827. auto& p = s.patterns[(std::size_t) s.currentPattern];
  828. const auto length = patternSteps (s, p);
  829. for (auto r : rows)
  830. rotateSteps (p, r, steps, length);
  831. });
  832. }
  833. void ChannelRackComponent::fillSelected (int every)
  834. {
  835. const auto rows = engine.getSelectedChannels();
  836. engine.editSong ([rows, every] (Song& s) {
  837. auto& p = s.patterns[(std::size_t) s.currentPattern];
  838. const auto length = patternSteps (s, p);
  839. for (auto r : rows)
  840. if (r < (int) s.channels.size() && s.channels[(std::size_t) r].instrument != InstrumentKind::audioClip)
  841. fillEverySteps (p, r, every, length);
  842. });
  843. }
  844. void ChannelRackComponent::sortChannels (ChannelSort by)
  845. {
  846. engine.editSong ([by] (Song& s) { permuteChannels (s, channelSortOrder (s, by)); });
  847. openEditorRow = -1;
  848. selectRows ({ 0 }, 0);
  849. }
  850. void ChannelRackComponent::selectUnused()
  851. {
  852. const auto unused = unusedChannels (engine.getSong());
  853. if (unused.empty())
  854. {
  855. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Select unused channels"),
  856. tr ("Every channel is used by a pattern or a Playlist clip."));
  857. return;
  858. }
  859. selectRows (unused, unused.front());
  860. }
  861. int ChannelRackComponent::addChannel (ChannelDef c, bool openEditor)
  862. {
  863. int index = 0;
  864. engine.editSong ([&] (Song& s) {
  865. c.mixerTrack = s.nextFreeInsert();
  866. s.channels.push_back (c);
  867. index = (int) s.channels.size() - 1;
  868. });
  869. selectionAnchor = index;
  870. selectRows ({ index }, index);
  871. if (openEditor && c.instrument == InstrumentKind::plugin)
  872. {
  873. openPluginWindow (index);
  874. openEditorRow = index;
  875. }
  876. return index;
  877. }
  878. bool ChannelRackComponent::loadSampleIntoSelected (const juce::File& file)
  879. {
  880. const auto row = engine.getSelectedChannel();
  881. const auto& song = engine.getSong();
  882. if (row < 0 || row >= (int) song.channels.size() || ! file.hasFileExtension ("wav;aif;aiff;flac;ogg;mp3"))
  883. return false;
  884. const auto kind = song.channels[(std::size_t) row].instrument;
  885. // only channels that play a sample (or the built-in drums, which become samplers) take a file
  886. if (kind != InstrumentKind::sampler && kind != InstrumentKind::kick && kind != InstrumentKind::snare && kind != InstrumentKind::hat
  887. && kind != InstrumentKind::clap)
  888. return false;
  889. assignSample (row, file);
  890. return true;
  891. }
  892. namespace
  893. {
  894. // Euclidean fill: pulses spread evenly over a length, rotated; previewed live on the pattern.
  895. class EuclideanPanel final : public juce::Component
  896. {
  897. public:
  898. EuclideanPanel (AudioEngine& e, int c) : engine (e), channel (c)
  899. {
  900. const auto& song = engine.getSong();
  901. patternIndex = song.currentPattern;
  902. originals = song.patterns[(std::size_t) patternIndex].notes;
  903. steps = patternSteps (song, song.patterns[(std::size_t) patternIndex]);
  904. auto setup = [this] (juce::Slider& s, juce::Label& l, const juce::String& name, double lo, double hi, double v) {
  905. l.setText (name, juce::dontSendNotification);
  906. addAndMakeVisible (l);
  907. s.setSliderStyle (juce::Slider::LinearHorizontal);
  908. s.setTextBoxStyle (juce::Slider::TextBoxRight, false, 50, 20);
  909. s.setRange (lo, hi, 1.0);
  910. s.setValue (v, juce::dontSendNotification);
  911. s.onValueChange = [this] { preview(); };
  912. addAndMakeVisible (s);
  913. };
  914. setup (pulses, pulsesLabel, tr ("Pulses"), 0, 32, 5);
  915. setup (length, lengthLabel, tr ("Length (steps)"), 1, 32, 16);
  916. setup (rotation, rotationLabel, tr ("Rotation"), -16, 16, 0);
  917. title.setText (tr ("Euclidean fill: {0}", { juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str()) }), juce::dontSendNotification);
  918. title.setFont (theme::font (theme::type::title, true));
  919. addAndMakeVisible (title);
  920. for (auto* b : { &accept, &cancel })
  921. addAndMakeVisible (b);
  922. accept.setColour (juce::TextButton::buttonColourId, theme::colour::accent);
  923. accept.onClick = [this] {
  924. restore();
  925. const auto rhythm = current();
  926. engine.editSong ([this, rhythm] (Song& s) { setStepRhythm (s.patterns[(std::size_t) patternIndex], channel, rhythm, steps); });
  927. done = true;
  928. closeToolWindowOf (*this);
  929. };
  930. cancel.onClick = [this] { closeToolWindowOf (*this); };
  931. setSize (380, 330);
  932. preview();
  933. }
  934. ~EuclideanPanel() override
  935. {
  936. if (! done)
  937. restore();
  938. }
  939. void paint (juce::Graphics& g) override
  940. {
  941. g.fillAll (theme::colour::bg2);
  942. // the rhythm as a ring of steps, the first step at the top
  943. const auto rhythm = current();
  944. const auto ring = juce::Rectangle<float> (0, 150, (float) getWidth(), 120).withSizeKeepingCentre (110, 110);
  945. const auto n = (int) rhythm.size();
  946. for (int i = 0; i < n; ++i)
  947. {
  948. const auto angle = juce::MathConstants<float>::twoPi * (float) i / (float) n;
  949. const auto centre = ring.getCentre() + juce::Point<float> (std::sin (angle), -std::cos (angle)) * 50.0f;
  950. const auto dot = juce::Rectangle<float> (12, 12).withCentre (centre);
  951. g.setColour (rhythm[(std::size_t) i] ? theme::colour::stepOn : theme::colour::stepOff);
  952. g.fillEllipse (dot);
  953. if (i == 0)
  954. {
  955. g.setColour (theme::colour::textPrimary);
  956. g.drawEllipse (dot.expanded (2.0f), 1.0f);
  957. }
  958. }
  959. }
  960. void resized() override
  961. {
  962. auto area = getLocalBounds().reduced (12, 10);
  963. title.setBounds (area.removeFromTop (24));
  964. area.removeFromTop (6);
  965. for (auto [s, l] : { std::pair { &pulses, &pulsesLabel }, std::pair { &length, &lengthLabel }, std::pair { &rotation, &rotationLabel } })
  966. {
  967. auto row = area.removeFromTop (30);
  968. l->setBounds (row.removeFromLeft (120));
  969. s->setBounds (row);
  970. }
  971. auto buttons = area.removeFromBottom (28);
  972. accept.setBounds (buttons.removeFromRight (100));
  973. buttons.removeFromRight (8);
  974. cancel.setBounds (buttons.removeFromRight (90));
  975. }
  976. private:
  977. std::vector<bool> current() const
  978. {
  979. return euclideanRhythm ((int) pulses.getValue(), (int) length.getValue(), (int) rotation.getValue());
  980. }
  981. void restore()
  982. {
  983. if (patternIndex < (int) engine.getSong().patterns.size())
  984. engine.editSong ([this] (Song& s) { s.patterns[(std::size_t) patternIndex].notes = originals; }, false);
  985. }
  986. void preview()
  987. {
  988. const auto rhythm = current();
  989. if (patternIndex < (int) engine.getSong().patterns.size())
  990. engine.editSong ([this, rhythm] (Song& s) {
  991. auto& p = s.patterns[(std::size_t) patternIndex];
  992. p.notes = originals;
  993. setStepRhythm (p, channel, rhythm, steps);
  994. }, false);
  995. repaint();
  996. }
  997. AudioEngine& engine;
  998. int channel, patternIndex = 0, steps = 16;
  999. std::vector<Note> originals;
  1000. bool done = false;
  1001. juce::Label title, pulsesLabel, lengthLabel, rotationLabel;
  1002. juce::Slider pulses, length, rotation;
  1003. juce::TextButton accept { tr ("Accept") }, cancel { tr ("Cancel") };
  1004. };
  1005. } // namespace
  1006. std::unique_ptr<juce::Component> ChannelRackComponent::makeEuclideanPanel (int channel)
  1007. {
  1008. return std::make_unique<EuclideanPanel> (engine, juce::jlimit (0, juce::jmax (0, (int) engine.getSong().channels.size() - 1), channel));
  1009. }
  1010. void ChannelRackComponent::showEuclideanFill (int channel)
  1011. {
  1012. if (channel >= 0 && channel < (int) engine.getSong().channels.size())
  1013. openToolWindow (makeEuclideanPanel (channel), tr ("Euclidean fill"), "euclidean");
  1014. }
  1015. // --- mouse -------------------------------------------------------------------------------------
  1016. void ChannelRackComponent::mouseDown (const juce::MouseEvent& e)
  1017. {
  1018. int row = 0;
  1019. const auto area = areaAt (e.x, e.y, row);
  1020. const auto& song = engine.getSong();
  1021. switch (area)
  1022. {
  1023. case Area::none:
  1024. return;
  1025. case Area::addRow:
  1026. showAddChannelMenu();
  1027. return;
  1028. case Area::laneLevels:
  1029. for (int l = 0; l < notetools::levelCount; ++l)
  1030. if (levelButtonBounds (l).contains (e.getPosition().translated (-stickyX, 0)))
  1031. {
  1032. graphLevel = l;
  1033. repaint();
  1034. }
  1035. return;
  1036. case Area::lane:
  1037. {
  1038. const auto step = juce::jlimit (0, numSteps() - 1, (e.x - gridLeft()) / stepWidth);
  1039. if (e.mods.isAltDown() || e.mods.isMiddleButtonDown())
  1040. {
  1041. setLaneValue (step, notetools::levelDefault ((notetools::Level) graphLevel));
  1042. return;
  1043. }
  1044. laneDownStep = step;
  1045. laneDownValue = laneValueAt (e.y);
  1046. applyLane (e);
  1047. return;
  1048. }
  1049. case Area::mute:
  1050. if (e.mods.isPopupMenu() || e.mods.isCtrlDown())
  1051. solo (row);
  1052. else
  1053. toggleMute (row);
  1054. return;
  1055. case Area::pan:
  1056. case Area::volume:
  1057. case Area::route:
  1058. {
  1059. const auto spec = specFor (area, row);
  1060. if (e.mods.isPopupMenu())
  1061. {
  1062. juce::PopupMenu menu;
  1063. menu.addSectionHeader (spec.name + ": " + spec.text (valueOf (area, row)));
  1064. ui::addValueItems (menu, *this, &engine, spec, valueOf (area, row), [this, area, row] (double v) { setValue (area, row, v); });
  1065. if (area == Area::route)
  1066. {
  1067. menu.addSeparator();
  1068. menu.addItem (tr ("Next free insert"), [this, row] {
  1069. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].mixerTrack = s.nextFreeInsert(); });
  1070. });
  1071. menu.addItem (tr ("Send the selected channels to free inserts") + "\tCtrl+L", [this] { sendSelectedToInserts(); });
  1072. if (onOpenMixerInsert)
  1073. menu.addItem (tr ("Show this insert in the Mixer"), [this, row] {
  1074. if (row < (int) engine.getSong().channels.size())
  1075. onOpenMixerInsert (engine.getSong().channels[(std::size_t) row].mixerTrack);
  1076. });
  1077. }
  1078. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1079. return;
  1080. }
  1081. if (ui::isResetClick (e))
  1082. {
  1083. setValue (area, row, spec.defaultValue);
  1084. showTip (area, row, true);
  1085. return;
  1086. }
  1087. knobDrag = area;
  1088. knobRow = row;
  1089. drag.begin (e, valueOf (area, row));
  1090. showTip (area, row, false);
  1091. repaint();
  1092. return;
  1093. }
  1094. case Area::name:
  1095. if (e.mods.isPopupMenu())
  1096. {
  1097. if (! std::binary_search (engine.getSelectedChannels().begin(), engine.getSelectedChannels().end(), row))
  1098. clickSelector (row, {});
  1099. else
  1100. selectRows (engine.getSelectedChannels(), row);
  1101. showChannelMenu (row);
  1102. return;
  1103. }
  1104. if (e.mods.isShiftDown())
  1105. {
  1106. clickSelector (row, e.mods);
  1107. return;
  1108. }
  1109. if (! std::binary_search (engine.getSelectedChannels().begin(), engine.getSelectedChannels().end(), row)
  1110. || engine.getSelectedChannels().size() > 1)
  1111. {
  1112. selectionAnchor = row;
  1113. selectRows ({ row }, row);
  1114. }
  1115. if (e.mods.isCtrlDown()) // audition without opening anything
  1116. {
  1117. previews.press (row, 60, 0.8f); // stops on release
  1118. return;
  1119. }
  1120. // the editor opens on release, unless the button is dragged (that reorders the channels)
  1121. nameDownRow = row;
  1122. nameDragged = false;
  1123. nameDownAlt = e.mods.isAltDown();
  1124. nameDragY = e.position.y;
  1125. return;
  1126. case Area::select:
  1127. clickSelector (row, e.mods);
  1128. if (e.mods.isPopupMenu()) // right-drag adds the rows it crosses
  1129. {
  1130. selectDownRow = row;
  1131. selectDragAdds = true;
  1132. selectDragBase = engine.getSelectedChannels();
  1133. }
  1134. else if (! e.mods.isShiftDown() && ! e.mods.isCtrlDown()) // left-drag selects a range
  1135. {
  1136. selectDownRow = row;
  1137. selectDragAdds = false;
  1138. }
  1139. return;
  1140. case Area::grid:
  1141. {
  1142. const auto step = (e.x - gridLeft()) / stepWidth;
  1143. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  1144. if (showsNotePreview (pattern, row)) // the miniature opens the Piano Roll (steps would break the melody)
  1145. {
  1146. if (! e.mods.isPopupMenu())
  1147. {
  1148. selectionAnchor = row;
  1149. selectRows ({ row }, row);
  1150. if (onOpenPianoRoll)
  1151. onOpenPianoRoll();
  1152. }
  1153. return;
  1154. }
  1155. if (e.mods.isRightButtonDown())
  1156. paintMode = PaintMode::remove;
  1157. else
  1158. paintMode = pattern.hasStep (row, step) ? PaintMode::remove : PaintMode::add;
  1159. lastPaintedRow = lastPaintedStep = -1;
  1160. applyPaint (e);
  1161. return;
  1162. }
  1163. }
  1164. }
  1165. void ChannelRackComponent::mouseDrag (const juce::MouseEvent& e)
  1166. {
  1167. if (knobDrag != Area::none && drag.isActive())
  1168. {
  1169. setValue (knobDrag, knobRow, drag.update (e, specFor (knobDrag, knobRow)));
  1170. showTip (knobDrag, knobRow, false);
  1171. return;
  1172. }
  1173. if (laneDownStep >= 0)
  1174. {
  1175. applyLane (e);
  1176. hoverStep = juce::jlimit (0, numSteps() - 1, (e.x - gridLeft()) / stepWidth);
  1177. hoverArea = Area::lane;
  1178. const auto v = laneValueAt (e.y);
  1179. const auto bipolar = notetools::levelIsBipolar ((notetools::Level) graphLevel);
  1180. const auto shown = juce::roundToInt ((bipolar ? v * 2.0f - 1.0f : v) * 100.0f);
  1181. const auto valueText = (bipolar && shown > 0 ? "+" : "") + juce::String (shown) + "%";
  1182. const auto levelText = tr (notetools::levelName ((notetools::Level) graphLevel));
  1183. ui::showValueTip (*this, controlBounds (Area::lane, graphRow()), levelText + ": " + valueText);
  1184. ui::Hint live;
  1185. live.text = channelName (engine.getSong(), graphRow()) + " - " + levelText;
  1186. live.value = valueText;
  1187. ui::postHint (live);
  1188. repaint (laneBounds());
  1189. return;
  1190. }
  1191. if (nameDownRow >= 0)
  1192. {
  1193. if (! nameDragged && std::abs (e.position.y - nameDragY) < 4.0f)
  1194. return;
  1195. nameDragged = true;
  1196. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  1197. const auto count = (int) engine.getSong().channels.size();
  1198. const auto target = juce::jlimit (0, count - 1, rowAtY (e.y));
  1199. // move the selection one row at a time until the grabbed channel is under the mouse
  1200. for (int guard = 0; guard < count && engine.getSelectedChannel() != target; ++guard)
  1201. if (! moveSelected (target < engine.getSelectedChannel() ? -1 : 1))
  1202. break;
  1203. return;
  1204. }
  1205. if (selectDownRow >= 0)
  1206. {
  1207. const auto count = (int) engine.getSong().channels.size();
  1208. const auto row = juce::jlimit (0, juce::jmax (0, count - 1), rowAtY (e.y));
  1209. std::vector<int> rows;
  1210. for (int r = juce::jmin (selectDownRow, row); r <= juce::jmax (selectDownRow, row); ++r)
  1211. rows.push_back (r);
  1212. if (selectDragAdds)
  1213. {
  1214. rows.insert (rows.end(), selectDragBase.begin(), selectDragBase.end());
  1215. std::sort (rows.begin(), rows.end());
  1216. rows.erase (std::unique (rows.begin(), rows.end()), rows.end());
  1217. }
  1218. else
  1219. selectionAnchor = selectDownRow;
  1220. if (rows != engine.getSelectedChannels())
  1221. selectRows (rows, row);
  1222. return;
  1223. }
  1224. if (paintMode != PaintMode::none)
  1225. applyPaint (e);
  1226. }
  1227. void ChannelRackComponent::mouseUp (const juce::MouseEvent& e)
  1228. {
  1229. previews.releaseAll(); // the audition (Ctrl+click) and the steps' previews stop with the button
  1230. if (nameDownRow >= 0 && ! nameDragged && e.mouseWasClicked())
  1231. toggleEditor (nameDownRow, nameDownAlt);
  1232. if (nameDragged)
  1233. setMouseCursor (juce::MouseCursor::NormalCursor);
  1234. nameDownRow = -1;
  1235. nameDragged = false;
  1236. selectDownRow = -1;
  1237. selectDragBase.clear();
  1238. ui::hideValueTip();
  1239. ui::clearPostedHint();
  1240. paintMode = PaintMode::none;
  1241. laneDownStep = -1;
  1242. if (knobDrag != Area::none)
  1243. repaint();
  1244. knobDrag = Area::none;
  1245. drag.end();
  1246. }
  1247. void ChannelRackComponent::mouseDoubleClick (const juce::MouseEvent& e)
  1248. {
  1249. int row = 0;
  1250. const auto area = areaAt (e.x, e.y, row);
  1251. if (area == Area::pan || area == Area::volume)
  1252. {
  1253. setValue (area, row, specFor (area, row).defaultValue);
  1254. showTip (area, row, true);
  1255. }
  1256. else if (area == Area::route)
  1257. {
  1258. if (onOpenMixerInsert)
  1259. onOpenMixerInsert (engine.getSong().channels[(std::size_t) row].mixerTrack);
  1260. else
  1261. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].mixerTrack = s.nextFreeInsert(); });
  1262. }
  1263. else if (area == Area::select && ! e.mods.isPopupMenu())
  1264. selectAll();
  1265. else if (area == Area::name && ! e.mods.isAnyModifierKeyDown() && onOpenPianoRoll)
  1266. onOpenPianoRoll();
  1267. }
  1268. void ChannelRackComponent::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  1269. {
  1270. int row = 0;
  1271. const auto area = areaAt (e.x, e.y, row);
  1272. if (area == Area::pan || area == Area::volume || area == Area::route)
  1273. {
  1274. if (const auto v = ui::wheelValue (valueOf (area, row), e, wheel, specFor (area, row)))
  1275. {
  1276. setValue (area, row, *v);
  1277. showTip (area, row, true);
  1278. }
  1279. return;
  1280. }
  1281. if ((area == Area::name || area == Area::select) && e.mods.isShiftDown()) // Shift+wheel moves the channel
  1282. {
  1283. const auto delta = (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? -1 : 1;
  1284. selectRows ({ row }, row);
  1285. moveSelected (delta);
  1286. return;
  1287. }
  1288. juce::Component::mouseWheelMove (e, wheel); // scroll the viewport
  1289. }
  1290. ui::Hint ChannelRackComponent::hintAt (juce::Point<int> p)
  1291. {
  1292. int row = 0;
  1293. const auto area = areaAt (p.x, p.y, row);
  1294. const auto& song = engine.getSong();
  1295. ui::Hint h;
  1296. if (row >= 0 && row < (int) song.channels.size() && (area == Area::pan || area == Area::volume || area == Area::route))
  1297. {
  1298. const auto active = knobDrag != Area::none && drag.isActive();
  1299. const auto shownArea = active ? knobDrag : area;
  1300. const auto shownRow = active ? knobRow : row;
  1301. h = ui::valueHint (specFor (shownArea, shownRow), valueOf (shownArea, shownRow),
  1302. shownArea == Area::route ? tr ("[LMB] drag or [Wheel] routes [2xLMB] show in the Mixer [RMB] next free insert")
  1303. : ui::valueGestures());
  1304. return h;
  1305. }
  1306. const auto name = channelName (song, row);
  1307. switch (area)
  1308. {
  1309. case Area::mute:
  1310. h.text = name + " - " + tr ("Click: mute. Ctrl+click or right-click: solo");
  1311. break;
  1312. case Area::name:
  1313. h.text = name + " - " + tr ("[LMB] open/close the editor [Alt]+[LMB] keep others open [Ctrl]+[LMB] audition [2xLMB] Piano Roll [LMB] drag up/down reorders [RMB] channel menu");
  1314. h.hasMenu = true;
  1315. break;
  1316. case Area::select:
  1317. h.text = name + " - " + tr ("Select: [LMB] one [Ctrl]+[LMB] or [RMB] add/remove [Shift]+[LMB] range [LMB] drag range [RMB] drag adds [2xLMB] all [Alt]+[Up]/[Down] moves the selection");
  1318. break;
  1319. case Area::grid:
  1320. if (! song.patterns.empty() && showsNotePreview (song.patterns[(std::size_t) song.currentPattern], row))
  1321. h.text = name + " - " + tr ("Piano Roll notes: [LMB] opens them in the Piano Roll");
  1322. else
  1323. h.text = name + " - " + tr ("Steps: [LMB] drag draws (starting on a lit step erases) [RMB] drag erases");
  1324. break;
  1325. case Area::addRow:
  1326. h.text = tr ("Add a channel (or drop audio files on the rack)");
  1327. break;
  1328. case Area::laneLevels:
  1329. h.text = tr ("Graph lane: choose what the bars edit (Ctrl+K hides the lane)");
  1330. break;
  1331. case Area::lane:
  1332. h.text = name + " - " + tr ("Graph lane: drag sets the steps, right-drag draws a ramp, Alt+click resets");
  1333. break;
  1334. default:
  1335. break;
  1336. }
  1337. return h;
  1338. }
  1339. void ChannelRackComponent::applyPaint (const juce::MouseEvent& e)
  1340. {
  1341. const auto& song = engine.getSong();
  1342. const auto row = rowAtY (e.y);
  1343. const auto step = (e.x - gridLeft()) / stepWidth;
  1344. if (laneBounds().contains (e.getPosition()))
  1345. return;
  1346. if (row < 0 || row >= (int) song.channels.size() || step < 0 || step >= numSteps() || e.x < stickyX + gridLeft()
  1347. || song.channels[(std::size_t) row].instrument == InstrumentKind::audioClip
  1348. || showsNotePreview (song.patterns[(std::size_t) song.currentPattern], row)) // drag-paint skips note rows
  1349. return;
  1350. if (row == lastPaintedRow && step == lastPaintedStep)
  1351. return;
  1352. lastPaintedRow = row;
  1353. lastPaintedStep = step;
  1354. const auto on = paintMode == PaintMode::add;
  1355. engine.editSong ([row, step, on] (Song& s) { setStep (s.patterns[(std::size_t) s.currentPattern], row, step, on); });
  1356. if (on) // the new step sounds while the button is held (the previous one stops)
  1357. {
  1358. previews.releaseAll();
  1359. previews.press (row, 60, 0.78f);
  1360. }
  1361. }
  1362. // --- menus -------------------------------------------------------------------------------------
  1363. void ChannelRackComponent::showChannelMenu (int channel)
  1364. {
  1365. const auto& c = engine.getSong().channels[(std::size_t) channel];
  1366. juce::PopupMenu instruments;
  1367. for (auto kind : builtInKinds)
  1368. instruments.addItem (instrumentLabel (kind), true, c.instrument == kind, [this, channel, kind] {
  1369. engine.editSong ([channel, kind] (Song& s) { s.channels[(std::size_t) channel].instrument = kind; });
  1370. });
  1371. instruments.addSeparator();
  1372. instruments.addItem (tr ("Sampler (choose file)..."), [this, channel] { chooseSample (channel); });
  1373. juce::PopupMenu plugins;
  1374. addPluginItems (plugins, engine, true, [this, channel] (PluginRef ref) {
  1375. engine.editSong ([channel, ref] (Song& s) {
  1376. auto& c = s.channels[(std::size_t) channel];
  1377. c.instrument = InstrumentKind::plugin;
  1378. c.plugin = ref;
  1379. c.name = ref.name;
  1380. });
  1381. openPluginWindow (channel);
  1382. });
  1383. instruments.addSubMenu (tr ("Plugin (VST/VST3/CLAP)"), plugins);
  1384. juce::PopupMenu menu;
  1385. menu.addSectionHeader (juce::String::fromUTF8 (c.name.c_str()));
  1386. if (c.instrument == InstrumentKind::sampler)
  1387. {
  1388. menu.addItem (tr ("Sample: {0}", { juce::File (juce::String::fromUTF8 (c.samplePath.c_str())).getFileName() }),
  1389. false, false, [] {});
  1390. menu.addItem (tr ("Sampler settings (pitch, envelope, reverse)..."),
  1391. [this, channel] { openChannelSettings (engine, channel); });
  1392. menu.addItem (tr ("Edit the sample in the audio editor..."), ! c.samplePath.empty(), false, [this, channel] { openAudioEditorForChannel (engine, channel); });
  1393. if (c.sampler.slices.empty())
  1394. menu.addItem (tr ("Slice sample (slicer): one slice per key and a pattern with the loop"), [this, channel] { sliceChannel (channel); });
  1395. else
  1396. menu.addItem (tr ("Undo slices ({0})", { juce::String ((int) c.sampler.slices.size()) }), [this, channel] {
  1397. engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].sampler.slices.clear(); });
  1398. });
  1399. }
  1400. else if (c.instrument == InstrumentKind::synth)
  1401. menu.addItem (tr ("Synth settings (oscillators, envelope, filter)..."), [this, channel] { openChannelSettings (engine, channel); });
  1402. else if (hasChannelSettings (c.instrument))
  1403. menu.addItem (tr ("Channel settings..."), [this, channel] { openChannelSettings (engine, channel); });
  1404. if (c.instrument == InstrumentKind::plugin)
  1405. {
  1406. menu.addItem (tr ("Open plugin editor"), [this, channel] { openPluginWindow (channel); });
  1407. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get()))
  1408. addPluginParameterItems (menu, engine, p->getInstance(), { AutomationTargetKind::channelParam, channel, 0, 0 });
  1409. }
  1410. menu.addItem (tr ("Piano Roll"), [this] {
  1411. if (onOpenPianoRoll)
  1412. onOpenPianoRoll();
  1413. });
  1414. menu.addSubMenu (tr ("Instrument"), instruments);
  1415. {
  1416. // channel arpeggiator
  1417. const auto arp = c.arp;
  1418. auto set = [this, channel] (std::function<void (ArpSettings&)> change) {
  1419. engine.editSong ([channel, change] (Song& s) { change (s.channels[(std::size_t) channel].arp); });
  1420. };
  1421. juce::PopupMenu arpMenu;
  1422. const char* directions[] = { TR_NOOP ("Off"), TR_NOOP ("Up"), TR_NOOP ("Down"), TR_NOOP ("Up and down"), TR_NOOP ("Random") };
  1423. for (int d = 0; d < 5; ++d)
  1424. arpMenu.addItem (tr (directions[d]), true, arp.direction == d, [set, d] { set ([d] (ArpSettings& a) { a.direction = d; }); });
  1425. arpMenu.addSeparator();
  1426. juce::PopupMenu range, speed, gate, repeat;
  1427. for (int o = 1; o <= 4; ++o)
  1428. range.addItem (o == 1 ? tr ("1 octave") : tr ("{0} octaves", { juce::String (o) }), true, arp.range == o, [set, o] { set ([o] (ArpSettings& a) { a.range = o; }); });
  1429. const std::pair<const char*, float> speeds[] = { { "1/4", 1.0f }, { "1/8", 0.5f }, { TR_NOOP ("1/8 triplet"), 1.0f / 3.0f },
  1430. { "1/16", 0.25f }, { TR_NOOP ("1/16 triplet"), 1.0f / 6.0f }, { "1/32", 0.125f } };
  1431. for (const auto& [name, beats] : speeds)
  1432. speed.addItem (tr (name), true, std::abs (arp.stepBeats - beats) < 1e-4f, [set, b = beats] { set ([b] (ArpSettings& a) { a.stepBeats = b; }); });
  1433. for (int g : { 25, 50, 75, 100 })
  1434. 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; }); });
  1435. for (int n : { 1, 2, 3, 4 })
  1436. repeat.addItem (juce::String (n) + "x", true, arp.repeat == n, [set, n] { set ([n] (ArpSettings& a) { a.repeat = n; }); });
  1437. arpMenu.addSubMenu (tr ("Range"), range);
  1438. arpMenu.addSubMenu (tr ("Speed"), speed);
  1439. arpMenu.addSubMenu (tr ("Gate"), gate);
  1440. arpMenu.addSubMenu (tr ("Repeat"), repeat);
  1441. menu.addSubMenu (arp.enabled() ? tr ("Arpeggiator (on)") : tr ("Arpeggiator"), arpMenu);
  1442. }
  1443. menu.addItem (tr ("Rename and color...") + "\tF2", [this, channel] { rename (channel); });
  1444. {
  1445. juce::PopupMenu colours;
  1446. colours.addItem (tr ("Default"), [this, channel] { engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].colour = 0; }); });
  1447. for (auto colour : lynxPalette())
  1448. {
  1449. juce::Image swatch (juce::Image::ARGB, 16, 16, true);
  1450. juce::Graphics (swatch).fillAll (juce::Colour (colour));
  1451. juce::PopupMenu::Item item;
  1452. item.text = "#" + juce::String::toHexString ((juce::int64) (colour & 0xFFFFFF)).paddedLeft ('0', 6).toUpperCase();
  1453. item.image = std::make_unique<juce::DrawableImage> (swatch);
  1454. item.isTicked = c.colour == colour;
  1455. item.action = [this, channel, colour] { engine.editSong ([channel, colour] (Song& s) { s.channels[(std::size_t) channel].colour = colour; }); };
  1456. colours.addItem (std::move (item));
  1457. }
  1458. menu.addSubMenu (tr ("Color"), colours);
  1459. }
  1460. {
  1461. juce::PopupMenu steps;
  1462. steps.addItem (tr ("Fill every 2 steps"), [this] { fillSelected (2); });
  1463. steps.addItem (tr ("Fill every 4 steps"), [this] { fillSelected (4); });
  1464. steps.addItem (tr ("Fill every 8 steps"), [this] { fillSelected (8); });
  1465. steps.addItem (tr ("Euclidean fill..."), [this, channel] { showEuclideanFill (channel); });
  1466. steps.addSeparator();
  1467. steps.addItem (tr ("Rotate left") + "\tCtrl+Shift+Left", [this] { rotateSelected (-1); });
  1468. steps.addItem (tr ("Rotate right") + "\tCtrl+Shift+Right", [this] { rotateSelected (1); });
  1469. steps.addSeparator();
  1470. steps.addItem (tr ("Graph lanes (velocity, pan, pitch...)") + "\tCtrl+K", true, graphLanes, [this] { toggleGraphLanes(); });
  1471. steps.addSeparator();
  1472. steps.addItem (tr ("Swing mix ({0})...", { juce::String (juce::roundToInt (c.swingMix * 100.0f)) + "%" }),
  1473. [this, channel] { setSwingMixOfSelected (channel); });
  1474. menu.addSubMenu (tr ("Steps"), steps);
  1475. }
  1476. menu.addItem (tr ("Clear notes in this pattern"), [this, channel] {
  1477. engine.editSong ([channel] (Song& s) {
  1478. auto& notes = s.patterns[(std::size_t) s.currentPattern].notes;
  1479. notes.erase (std::remove_if (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }),
  1480. notes.end());
  1481. });
  1482. });
  1483. // organisation (acts on the selection)
  1484. const auto selected = (int) engine.getSelectedChannels().size();
  1485. const auto count = (int) engine.getSong().channels.size();
  1486. menu.addSeparator();
  1487. menu.addItem (selected > 1 ? tr ("Clone {0} channels", { juce::String (selected) }) : tr ("Clone channel"), [this] { cloneSelected(); });
  1488. {
  1489. juce::PopupMenu insert;
  1490. addInstrumentItems (insert, channel);
  1491. menu.addSubMenu (tr ("Insert channel here"), insert);
  1492. }
  1493. menu.addItem (tr ("Move up") + "\tAlt+Up", engine.getSelectedChannels().front() > 0, false, [this] { moveSelected (-1); });
  1494. menu.addItem (tr ("Move down") + "\tAlt+Down", engine.getSelectedChannels().back() < count - 1, false, [this] { moveSelected (1); });
  1495. menu.addItem (tr ("Send to free mixer inserts") + "\tCtrl+L", [this] { sendSelectedToInserts(); });
  1496. {
  1497. juce::PopupMenu sort;
  1498. sort.addItem (tr ("By name"), [this] { sortChannels (ChannelSort::name); });
  1499. sort.addItem (tr ("By color"), [this] { sortChannels (ChannelSort::colour); });
  1500. sort.addItem (tr ("By mixer insert"), [this] { sortChannels (ChannelSort::insert); });
  1501. sort.addItem (tr ("By type"), [this] { sortChannels (ChannelSort::type); });
  1502. menu.addSubMenu (tr ("Sort channels"), sort);
  1503. }
  1504. menu.addItem (tr ("Select unused channels"), [this] { selectUnused(); });
  1505. menu.addSeparator();
  1506. if (selected > 1)
  1507. menu.addItem (tr ("Delete {0} channels", { juce::String (selected) }) + "\tAlt+Del", selected < count, false, [this] { deleteSelected(); });
  1508. else
  1509. menu.addItem (tr ("Delete channel") + "\tAlt+Del", count > 1, false, [this, channel] {
  1510. closeEditor (channel);
  1511. engine.editSong ([channel] (Song& s) { s.removeChannel (channel); });
  1512. openEditorRow = -1;
  1513. });
  1514. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1515. }
  1516. void ChannelRackComponent::addInstrumentItems (juce::PopupMenu& menu, int insertAt)
  1517. {
  1518. // a new channel of `kind`, at the end (insertAt < 0) or at a row
  1519. auto add = [this, insertAt] (ChannelDef c) {
  1520. int index = 0;
  1521. engine.editSong ([&] (Song& s) {
  1522. c.mixerTrack = s.nextFreeInsert();
  1523. index = insertAt < 0 ? (s.channels.push_back (c), (int) s.channels.size() - 1) : insertChannel (s, insertAt, c);
  1524. });
  1525. selectionAnchor = index;
  1526. selectRows ({ index }, index);
  1527. return index;
  1528. };
  1529. for (auto kind : builtInKinds)
  1530. menu.addItem (instrumentLabel (kind), [add, kind] {
  1531. ChannelDef c;
  1532. c.name = instrumentName (kind).toStdString();
  1533. c.instrument = kind;
  1534. add (c);
  1535. });
  1536. menu.addSeparator();
  1537. if (insertAt < 0)
  1538. menu.addItem (tr ("Sampler (choose file)..."), [this] { chooseSample (-1); });
  1539. juce::PopupMenu plugins;
  1540. addPluginItems (plugins, engine, true, [this, add] (PluginRef ref) {
  1541. ChannelDef c;
  1542. c.name = ref.name;
  1543. c.instrument = InstrumentKind::plugin;
  1544. c.plugin = ref;
  1545. const auto added = add (c);
  1546. openPluginWindow (added); // the plugin opens when added
  1547. openEditorRow = added;
  1548. });
  1549. menu.addSubMenu (tr ("Plugin (VST/VST3/CLAP)"), plugins);
  1550. }
  1551. void ChannelRackComponent::showAddChannelMenu (int insertAt)
  1552. {
  1553. juce::PopupMenu menu;
  1554. addInstrumentItems (menu, insertAt);
  1555. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1556. }
  1557. void ChannelRackComponent::chooseSample (int channel)
  1558. {
  1559. fileChooser = std::make_unique<juce::FileChooser> (tr ("Choose sample"), juce::File(), engine.getSampleLibrary().wildcard());
  1560. fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  1561. [this, channel] (const juce::FileChooser& chooser) {
  1562. if (chooser.getResult().existsAsFile())
  1563. assignSample (channel, chooser.getResult());
  1564. });
  1565. }
  1566. void ChannelRackComponent::assignSample (int channel, const juce::File& file)
  1567. {
  1568. if (engine.getSampleLibrary().load (file.getFullPathName()) == nullptr)
  1569. {
  1570. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Sample"),
  1571. tr ("Could not read {0}", { file.getFileName() }));
  1572. return;
  1573. }
  1574. const auto path = file.getFullPathName().toStdString();
  1575. const auto name = file.getFileNameWithoutExtension().toStdString();
  1576. engine.editSong ([channel, path, name] (Song& s) {
  1577. const auto isNew = channel < 0 || channel >= (int) s.channels.size();
  1578. const auto freeInsert = s.nextFreeInsert();
  1579. auto& c = isNew ? s.channels.emplace_back() : s.channels[(std::size_t) channel];
  1580. if (isNew)
  1581. c.mixerTrack = freeInsert;
  1582. c.instrument = InstrumentKind::sampler;
  1583. c.samplePath = path;
  1584. c.name = name;
  1585. });
  1586. if (channel < 0)
  1587. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  1588. }
  1589. void ChannelRackComponent::openPluginWindow (int channel)
  1590. {
  1591. auto instrument = engine.getChannelInstrument (channel);
  1592. if (auto* plugin = dynamic_cast<PluginInstrument*> (instrument.get()))
  1593. {
  1594. PluginWindows::open (instrument, plugin->getInstance(),
  1595. juce::String::fromUTF8 (engine.getSong().channels[(std::size_t) channel].name.c_str()));
  1596. return;
  1597. }
  1598. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Plugin"),
  1599. tr ("This plugin could not be loaded (it is not installed or has not been scanned)."));
  1600. }
  1601. void ChannelRackComponent::rename (int channel)
  1602. {
  1603. const auto& c = engine.getSong().channels[(std::size_t) channel];
  1604. showNameAndColourDialog (tr ("Rename channel"), juce::String::fromUTF8 (c.name.c_str()), c.colour,
  1605. [this, channel] (const juce::String& name, std::uint32_t colour) {
  1606. if (channel < (int) engine.getSong().channels.size())
  1607. engine.editSong ([channel, n = name.toStdString(), colour] (Song& s) {
  1608. s.channels[(std::size_t) channel].name = n;
  1609. s.channels[(std::size_t) channel].colour = colour;
  1610. });
  1611. });
  1612. }
  1613. void ChannelRackComponent::sliceChannel (int channel)
  1614. {
  1615. const auto& song = engine.getSong();
  1616. const auto& c = song.channels[(std::size_t) channel];
  1617. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str()));
  1618. if (sample == nullptr || sample->frames() == 0)
  1619. return;
  1620. const auto slices = detectSlices (*sample, 0.5f);
  1621. const auto seconds = (double) sample->frames() / sample->sampleRate;
  1622. const auto ticksPerSecond = song.bpm * ppq / 60.0;
  1623. const auto name = c.name + " (slices)";
  1624. engine.editSong ([&] (Song& s) {
  1625. s.channels[(std::size_t) channel].sampler.slices = slices;
  1626. // pattern that plays the slices in their original order and timing (at the project BPM)
  1627. auto& p = s.patterns.emplace_back();
  1628. p.name = name;
  1629. for (std::size_t i = 0; i < slices.size(); ++i)
  1630. {
  1631. const auto start = slices[i] * seconds;
  1632. const auto end = i + 1 < slices.size() ? slices[i + 1] * seconds : seconds;
  1633. Note n;
  1634. n.start = (std::int64_t) std::llround (start * ticksPerSecond);
  1635. n.length = std::max<std::int64_t> (1, (std::int64_t) std::llround ((end - start) * ticksPerSecond));
  1636. n.key = 60 + (int) i;
  1637. n.channel = channel;
  1638. p.notes.push_back (n);
  1639. }
  1640. p.sortNotes();
  1641. s.currentPattern = (int) s.patterns.size() - 1;
  1642. });
  1643. }
  1644. bool ChannelRackComponent::isInterestedInFileDrag (const juce::StringArray& files)
  1645. {
  1646. for (const auto& f : files)
  1647. if (juce::File (f).hasFileExtension ("wav;aif;aiff;flac;ogg;mp3"))
  1648. return true;
  1649. return false;
  1650. }
  1651. void ChannelRackComponent::filesDropped (const juce::StringArray& files, int x, int y)
  1652. {
  1653. int row = 0;
  1654. const auto area = areaAt (x, y, row);
  1655. auto target = (area == Area::none || area == Area::addRow) ? -1 : row;
  1656. for (const auto& f : files)
  1657. {
  1658. const juce::File file (f);
  1659. if (! file.hasFileExtension ("wav;aif;aiff;flac;ogg;mp3"))
  1660. continue;
  1661. assignSample (target, file);
  1662. target = -1; // the remaining files become new channels
  1663. }
  1664. }
  1665. void ChannelRackComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  1666. {
  1667. updateSize();
  1668. repaint();
  1669. }
  1670. void ChannelRackComponent::timerCallback()
  1671. {
  1672. auto& transport = engine.getTransport();
  1673. auto step = -1;
  1674. if (transport.playing.load() && engine.getSong().mode == PlayMode::pattern)
  1675. {
  1676. const auto& song = engine.getSong();
  1677. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  1678. const auto length = (double) p.effectiveLength (song.beatsPerBar);
  1679. step = (int) (std::fmod (transport.positionTicks.load(), length) / ticksPerStep);
  1680. }
  1681. if (step != playheadStep)
  1682. {
  1683. auto dirty = [this] (int s) {
  1684. if (s >= 0)
  1685. repaint (gridLeft() + s * stepWidth, 0, stepWidth, getHeight());
  1686. };
  1687. dirty (playheadStep);
  1688. playheadStep = step;
  1689. dirty (playheadStep);
  1690. }
  1691. }
  1692. bool ChannelRackComponent::isInterestedInDragSource (const SourceDetails& details)
  1693. {
  1694. return BrowserComponent::isBrowserDrag (details);
  1695. }
  1696. void ChannelRackComponent::itemDropped (const SourceDetails& details)
  1697. {
  1698. if (const auto file = BrowserComponent::draggedFile (details); file.existsAsFile())
  1699. filesDropped ({ file.getFullPathName() }, details.localPosition.x, details.localPosition.y);
  1700. }
  1701. } // namespace lynx