ChannelRackComponent.cpp 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979
  1. #include "core/RackFilter.h"
  2. #include "ui/FlMods.h"
  3. #include "ui/EditorTools.h"
  4. #include "core/FruityDance.h"
  5. #include "core/VideoPlayer.h"
  6. #include "ui/ColourPicker.h"
  7. #include "ui/TrackIcons.h"
  8. #include "core/TrackIcons.h"
  9. #include "ui/PatcherEditor.h"
  10. #include "ui/UiTrace.h"
  11. #include "ui/TextCache.h"
  12. #include "ui/ChannelRackComponent.h"
  13. #include "ui/SpeechDialog.h"
  14. #include "core/Patcherize.h"
  15. #include "ui/QuickPick.h"
  16. #include "core/ControlSurface.h"
  17. #include "core/VoltageController.h"
  18. #include "core/MixerOps.h"
  19. #include "ui/AutomationUi.h"
  20. #include "core/NoteTools.h"
  21. #include "core/NoteEdit.h"
  22. #include "core/FlSynths.h"
  23. #include "core/MidiControls.h"
  24. #include "ui/ToolWindow.h"
  25. #include "ui/LoopStarterWindow.h"
  26. #include "core/Slicer.h"
  27. #include "ui/ChannelSettings.h"
  28. #include "engine/Text.h"
  29. #include "ui/Dialogs.h"
  30. #include "ui/HintBar.h"
  31. #include "ui/I18n.h"
  32. #include "ui/BrowserComponent.h"
  33. #include "ui/PluginWindow.h"
  34. #include "ui/Theme.h"
  35. #include "ui/AudioEditor.h"
  36. #include "ui/AutoSamplerDialog.h"
  37. #include "core/RackOps.h"
  38. #include "core/TransportEdit.h"
  39. #include "core/ChannelBurn.h"
  40. #include "core/ChannelLoops.h"
  41. #include "core/SoundFont.h"
  42. #include "core/Vfx.h"
  43. #include "ui/SoundFontEditor.h"
  44. namespace lynx
  45. {
  46. namespace
  47. {
  48. // English name (used for new channel names stored in the song)
  49. juce::String instrumentName (InstrumentKind k)
  50. {
  51. switch (k)
  52. {
  53. case InstrumentKind::kick: return "Kick";
  54. case InstrumentKind::snare: return "Snare";
  55. case InstrumentKind::hat: return "Hat";
  56. case InstrumentKind::clap: return "Clap";
  57. case InstrumentKind::synth: return "Synth";
  58. case InstrumentKind::sampler: return "Sampler";
  59. case InstrumentKind::audioClip: return "Audio clip";
  60. case InstrumentKind::plugin: return "Plugin";
  61. case InstrumentKind::controller: return "Controller";
  62. case InstrumentKind::sakura: return "Sakura";
  63. case InstrumentKind::drumpad: return "Drumpad";
  64. case InstrumentKind::boobass: return "BooBass";
  65. case InstrumentKind::drumsynth: return "DrumSynth Live";
  66. case InstrumentKind::harmless: return "Harmless";
  67. case InstrumentKind::sytrus: return "Sytrus";
  68. case InstrumentKind::harmor: return "Harmor";
  69. case InstrumentKind::gms: return "GMS";
  70. case InstrumentKind::morphine: return "Morphine";
  71. case InstrumentKind::ogun: return "Ogun";
  72. case InstrumentKind::minisynth: return "MiniSynth";
  73. case InstrumentKind::dx10: return "Fruity DX10";
  74. case InstrumentKind::kepler: return "Kepler";
  75. case InstrumentKind::keplerExo: return "Kepler Exo";
  76. case InstrumentKind::poizone: return "PoiZone";
  77. case InstrumentKind::fruitkick: return "Fruit Kick";
  78. case InstrumentKind::bassdrum: return "BassDrum";
  79. case InstrumentKind::toxic: return "Toxic Biohazard";
  80. case InstrumentKind::threeosc: return "3x Osc";
  81. case InstrumentKind::autogun: return "Autogun";
  82. case InstrumentKind::transistorbass: return "Transistor Bass";
  83. case InstrumentKind::simsynth: return "SimSynth";
  84. case InstrumentKind::wasp: return "Wasp";
  85. case InstrumentKind::plucked: return "Plucked!";
  86. case InstrumentKind::beepmap: return "BeepMap";
  87. case InstrumentKind::sawer: return "Sawer";
  88. case InstrumentKind::flkeys: return "FL Keys";
  89. case InstrumentKind::granulizer: return "Fruity Granulizer";
  90. case InstrumentKind::drumaxx: return "Drumaxx";
  91. case InstrumentKind::slayer: return "FL Slayer";
  92. case InstrumentKind::fruitydance: return "Fruity Dance";
  93. case InstrumentKind::directwave: return "DirectWave";
  94. case InstrumentKind::midiOut: return "MIDI Out";
  95. case InstrumentKind::patcher: return "Patcher";
  96. case InstrumentKind::soundfont: return "LYNX Soundfont";
  97. case InstrumentKind::layer: return "Layer";
  98. case InstrumentKind::dashboard: return "Dashboard";
  99. case InstrumentKind::voltage: return "Voltage Controller";
  100. case InstrumentKind::vfx: return "VFX";
  101. case InstrumentKind::videoplayer: return "Fruity Video Player";
  102. case InstrumentKind::wavetraveller: return "Wave Traveller";
  103. }
  104. return "?";
  105. }
  106. // name shown in menus (translated)
  107. juce::String instrumentLabel (InstrumentKind k)
  108. {
  109. switch (k)
  110. {
  111. case InstrumentKind::kick: return tr ("Kick");
  112. case InstrumentKind::snare: return tr ("Snare");
  113. case InstrumentKind::hat: return tr ("Hat");
  114. case InstrumentKind::clap: return tr ("Clap");
  115. case InstrumentKind::synth: return tr ("Synth");
  116. case InstrumentKind::sampler: return tr ("Sampler");
  117. case InstrumentKind::audioClip: return tr ("Audio clip");
  118. case InstrumentKind::controller: return tr ("Envelope Controller");
  119. case InstrumentKind::midiOut: return tr ("MIDI Out");
  120. case InstrumentKind::layer: return tr ("Layer");
  121. case InstrumentKind::dashboard: return "Dashboard";
  122. case InstrumentKind::voltage: return "Voltage Controller";
  123. default: return instrumentName (k);
  124. }
  125. }
  126. void setStep (Pattern& p, int channel, int step, bool on, bool muteRemoved = false)
  127. {
  128. if (p.hasStep (channel, step) != on)
  129. p.toggleStep (channel, step, muteRemoved);
  130. }
  131. juce::String channelName (const Song& song, int row)
  132. {
  133. return row >= 0 && row < (int) song.channels.size() ? juce::String::fromUTF8 (song.channels[(std::size_t) row].name.c_str()) : juce::String();
  134. }
  135. } // namespace
  136. bool ChannelRackComponent::keepEditorsOpen = false;
  137. bool ChannelRackComponent::selectFirstChannelWithNotes = false;
  138. bool ChannelRackComponent::muteRemovedSteps = false;
  139. ChannelRackComponent::ChannelRackComponent (AudioEngine& e)
  140. : engine (e)
  141. {
  142. setWantsKeyboardFocus (false);
  143. setMouseClickGrabsKeyboardFocus (false);
  144. engine.addChangeListener (this);
  145. engine.getLevelsBroadcaster().addChangeListener (this);
  146. previews.setSender ([this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on); });
  147. updateSize();
  148. startTimerHz (30);
  149. }
  150. ChannelRackComponent::~ChannelRackComponent()
  151. {
  152. previews.releaseAll();
  153. engine.getLevelsBroadcaster().removeChangeListener (this);
  154. engine.removeChangeListener (this);
  155. }
  156. void ChannelRackComponent::moved()
  157. {
  158. // the viewport scrolled the rack sideways: the controls column follows the visible left edge
  159. const auto x = juce::jmax (0, -getX());
  160. if (x != stickyX)
  161. {
  162. stickyX = x;
  163. repaint();
  164. }
  165. }
  166. void ChannelRackComponent::visibilityChanged()
  167. {
  168. if (! isShowing())
  169. previews.releaseAll(); // hidden mid-gesture: nothing keeps sounding
  170. }
  171. int ChannelRackComponent::numSteps() const
  172. {
  173. const auto& song = engine.getSong();
  174. if (song.patterns.empty())
  175. return 16;
  176. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  177. const auto steps = (int) (p.effectiveLength (song.beatsPerBar) / ticksPerStep);
  178. return juce::jlimit (16, 512, steps);
  179. }
  180. int ChannelRackComponent::shownSteps() const
  181. {
  182. return juce::jmin (512, numSteps() + ghostSteps);
  183. }
  184. bool ChannelRackComponent::isShown (int row) const
  185. {
  186. return rackfilter::shows (engine.getSong(), row, filterGroup);
  187. }
  188. int ChannelRackComponent::visibleIndex (int row) const
  189. {
  190. if (filterGroup == rackfilter::all)
  191. return row;
  192. int index = 0;
  193. for (int r = 0; r < row && r < (int) engine.getSong().channels.size(); ++r)
  194. index += isShown (r) ? 1 : 0;
  195. return index + juce::jmax (0, row - (int) engine.getSong().channels.size());
  196. }
  197. int ChannelRackComponent::shownCount() const
  198. {
  199. return visibleIndex ((int) engine.getSong().channels.size());
  200. }
  201. void ChannelRackComponent::setFilterGroup (int group)
  202. {
  203. group = rackfilter::clamp (engine.getSong(), group);
  204. if (group == filterGroup)
  205. return;
  206. filterGroup = group;
  207. updateSize();
  208. repaint();
  209. if (onFilterChanged)
  210. onFilterChanged();
  211. }
  212. juce::String ChannelRackComponent::filterName() const
  213. {
  214. const auto& groups = engine.getSong().channelGroups;
  215. if (filterGroup == rackfilter::audioClips)
  216. return tr ("Audio clips");
  217. if (filterGroup == rackfilter::unsorted)
  218. return tr ("Unsorted");
  219. return filterGroup >= 0 && filterGroup < (int) groups.size() ? juce::String::fromUTF8 (groups[(std::size_t) filterGroup].c_str()) : tr ("All");
  220. }
  221. void ChannelRackComponent::showFilterMenu (juce::Component* target)
  222. {
  223. const auto& song = engine.getSong();
  224. juce::PopupMenu menu;
  225. menu.addItem (tr ("All"), true, filterGroup == rackfilter::all, [this] { setFilterGroup (rackfilter::all); });
  226. // FL's built-in views (round 168t, REA_rodada168t.md §3): the audio clip channels, and the channels in no group
  227. menu.addItem (tr ("Unsorted"), true, filterGroup == rackfilter::unsorted, [this] { setFilterGroup (rackfilter::unsorted); });
  228. menu.addItem (tr ("Audio clips"), true, filterGroup == rackfilter::audioClips, [this] { setFilterGroup (rackfilter::audioClips); });
  229. bool separated = false;
  230. for (int g = 0; g < (int) song.channelGroups.size(); ++g)
  231. {
  232. if (rackfilter::isBuiltinName (song.channelGroups[(std::size_t) g]))
  233. continue; // FL's own "Audio clips" / "Unsorted" groups: the two views above
  234. if (! std::exchange (separated, true))
  235. menu.addSeparator();
  236. menu.addItem (juce::String::fromUTF8 (song.channelGroups[(std::size_t) g].c_str()), true, filterGroup == g, [this, g] { setFilterGroup (g); });
  237. }
  238. menu.addSeparator();
  239. menu.addItem (tr ("Group selected...") + "\tAlt+G", [this] { groupSelected(); });
  240. {
  241. juce::PopupMenu move;
  242. move.addItem (tr ("(no group)"), [this] { moveSelectedToGroup (-1); });
  243. for (int g = 0; g < (int) song.channelGroups.size(); ++g)
  244. move.addItem (juce::String::fromUTF8 (song.channelGroups[(std::size_t) g].c_str()), [this, g] { moveSelectedToGroup (g); });
  245. menu.addSubMenu (tr ("Move selected channels to"), move, ! engine.getSelectedChannels().empty());
  246. }
  247. menu.addItem (tr ("Rename this group..."), filterGroup >= 0, false, [this] {
  248. const auto group = filterGroup;
  249. auto* window = new juce::AlertWindow (tr ("Filter group name"), {}, juce::MessageBoxIconType::NoIcon);
  250. window->addTextEditor ("name", filterName());
  251. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  252. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  253. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, group, window] (int result) {
  254. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  255. if (result != 1 || name.empty())
  256. return;
  257. engine.editSong ([group, name] (Song& s) {
  258. if (group < (int) s.channelGroups.size())
  259. s.channelGroups[(std::size_t) group] = name;
  260. });
  261. if (onFilterChanged)
  262. onFilterChanged();
  263. }),
  264. true);
  265. });
  266. menu.addItem (tr ("Delete this group (keeps its channels)"), filterGroup >= 0, false, [this] {
  267. const auto group = filterGroup;
  268. setFilterGroup (-1);
  269. engine.editSong ([group] (Song& s) {
  270. if (group >= (int) s.channelGroups.size())
  271. return;
  272. s.channelGroups.erase (s.channelGroups.begin() + group);
  273. for (auto& c : s.channels)
  274. c.group = c.group == group ? -1 : c.group > group ? c.group - 1 : c.group;
  275. });
  276. });
  277. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (target));
  278. }
  279. void ChannelRackComponent::moveSelectedToGroup (int group)
  280. {
  281. engine.editSong ([group, rows = engine.getSelectedChannels()] (Song& s) {
  282. for (auto r : rows)
  283. if (r >= 0 && r < (int) s.channels.size())
  284. s.channels[(std::size_t) r].group = group >= 0 && group < (int) s.channelGroups.size() ? group : -1;
  285. });
  286. updateSize();
  287. repaint();
  288. }
  289. void ChannelRackComponent::groupSelected()
  290. {
  291. // FL: Alt+G asks for the "Filter group name"; the selected channels move into the new group, which is shown
  292. auto* window = new juce::AlertWindow (tr ("Filter group name"), {}, juce::MessageBoxIconType::NoIcon);
  293. window->addTextEditor ("name", tr ("Group {0}", { juce::String ((int) engine.getSong().channelGroups.size() + 1) }));
  294. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  295. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  296. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  297. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  298. if (result != 1 || name.empty())
  299. return;
  300. const auto group = (int) engine.getSong().channelGroups.size();
  301. engine.editSong ([name, rows = engine.getSelectedChannels()] (Song& s) {
  302. s.channelGroups.push_back (name);
  303. for (auto r : rows)
  304. if (r >= 0 && r < (int) s.channels.size())
  305. s.channels[(std::size_t) r].group = (int) s.channelGroups.size() - 1;
  306. });
  307. setFilterGroup (group);
  308. }),
  309. true);
  310. }
  311. void ChannelRackComponent::updateSize()
  312. {
  313. const auto rows = shownCount() + 1; // +1 = "add channel" row
  314. // FL's ghost steps: when the rack is wider than the pattern, the free width shows faint steps after its end;
  315. // clicking one adds a step there and makes the pattern longer (issue #11)
  316. ghostSteps = 0;
  317. const auto loopColumn = advancedLoopShown() ? loopColumnWidth : 0; // (FL's advanced looping controls, at the right)
  318. if (const auto* holder = getParentComponent())
  319. ghostSteps = juce::jmax (0, (holder->getWidth() - gridLeft() - 8 - loopColumn) / stepWidth - numSteps());
  320. setSize (gridLeft() + shownSteps() * stepWidth + 8 + loopColumn, rows * rowHeight + 8 + (graphRow() >= 0 ? laneHeight : 0));
  321. }
  322. int ChannelRackComponent::graphRow() const
  323. {
  324. const auto count = (int) engine.getSong().channels.size();
  325. const auto row = graphLanes && count > 0 ? juce::jlimit (0, count - 1, engine.getSelectedChannel()) : -1;
  326. return row >= 0 && isShown (row) ? row : -1;
  327. }
  328. int ChannelRackComponent::rowY (int row) const
  329. {
  330. const auto lane = graphRow();
  331. return 4 + visibleIndex (row) * rowHeight + (lane >= 0 && row > lane ? laneHeight : 0);
  332. }
  333. int ChannelRackComponent::rowAtY (int y) const
  334. {
  335. if (y < 4)
  336. return -1;
  337. if (const auto lane = graphRow(); lane >= 0)
  338. {
  339. const auto laneTop = rowY (lane) + rowHeight;
  340. if (y >= laneTop && y < laneTop + laneHeight)
  341. return lane;
  342. if (y >= laneTop + laneHeight)
  343. y -= laneHeight;
  344. }
  345. const auto index = (y - 4) / rowHeight;
  346. if (filterGroup == rackfilter::all)
  347. return index;
  348. // the index-th shown row (the "add channel" row after the last one)
  349. const auto count = (int) engine.getSong().channels.size();
  350. int seen = 0;
  351. for (int r = 0; r < count; ++r)
  352. if (isShown (r) && seen++ == index)
  353. return r;
  354. return count + (index - seen);
  355. }
  356. juce::Rectangle<int> ChannelRackComponent::laneBounds() const
  357. {
  358. const auto lane = graphRow();
  359. return lane < 0 ? juce::Rectangle<int>() : juce::Rectangle<int> (0, rowY (lane) + rowHeight, getWidth(), laneHeight);
  360. }
  361. juce::Rectangle<int> ChannelRackComponent::rowBounds (int row) const
  362. {
  363. return { 0, rowY (row), getWidth(), rowHeight };
  364. }
  365. juce::Rectangle<int> ChannelRackComponent::stepBounds (int row, int step) const
  366. {
  367. return { gridLeft() + step * stepWidth + 1, rowY (row) + 4, stepWidth - 3, rowHeight - 8 };
  368. }
  369. // --- channel looping (FL 20.5+, round 165f-rack) ------------------------------------------------------
  370. int ChannelRackComponent::loopStepsOf (int row) const
  371. {
  372. const auto& song = engine.getSong();
  373. if (song.patterns.empty() || row < 0 || row >= (int) song.channels.size())
  374. return 0;
  375. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  376. if (! p.loopOn)
  377. return 0;
  378. const auto length = p.effectiveLength (song.beatsPerBar);
  379. const auto loop = channelloops::loopLength (p, row, channelloops::effectiveSetting (p, row), length, song.beatsPerBar);
  380. return loop > 0 && loop < length ? (int) (loop / ticksPerStep) : 0;
  381. }
  382. bool ChannelRackComponent::advancedLoopShown() const
  383. {
  384. const auto& song = engine.getSong();
  385. if (song.patterns.empty())
  386. return false;
  387. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  388. return p.loopOn && p.loopMode == RackLoopMode::advanced;
  389. }
  390. juce::Rectangle<int> ChannelRackComponent::loopBoxBounds (int row) const
  391. {
  392. // the right edge of what the viewport shows (the column stays there while the steps scroll, like the controls)
  393. auto right = getWidth();
  394. if (const auto* holder = getParentComponent())
  395. right = juce::jmin (getWidth(), stickyX + holder->getWidth());
  396. return { right - loopColumnWidth + 3, rowY (row) + 5, loopColumnWidth - 8, rowHeight - 10 };
  397. }
  398. void ChannelRackComponent::paintLoopColumn (juce::Graphics& g)
  399. {
  400. using namespace theme::colour;
  401. const auto& song = engine.getSong();
  402. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  403. const auto first = loopBoxBounds (0);
  404. g.setColour (bg2);
  405. g.fillRect (first.getX() - 3, 0, loopColumnWidth, getHeight());
  406. g.setColour (border);
  407. g.fillRect (first.getX() - 4, 0, 1, getHeight());
  408. g.setFont (theme::font (theme::type::caption, true));
  409. for (int row = 0; row < (int) song.channels.size(); ++row)
  410. {
  411. if (! isShown (row) || song.channels[(std::size_t) row].instrument == InstrumentKind::audioClip)
  412. continue;
  413. const auto box = loopBoxBounds (row);
  414. const auto setting = channelloops::effectiveSetting (p, row);
  415. const auto hovered = (hoverArea == Area::loop && hoverRow == row) || loopDragRow == row;
  416. theme::fillRoundRect (g, box.toFloat(), theme::radius::sm, hovered ? bg4 : bg0);
  417. if (setting != ChannelLoop::dontLoop)
  418. {
  419. g.setColour (accent.withAlpha (hovered ? 0.9f : 0.6f));
  420. g.drawRoundedRectangle (box.toFloat().reduced (0.5f), theme::radius::sm, 1.0f);
  421. }
  422. g.setColour (setting == ChannelLoop::dontLoop ? textDisabled : textPrimary);
  423. const auto text = setting > 0 ? juce::String (setting) : setting == ChannelLoop::dontLoop ? juce::String ("...")
  424. : tr (channelloops::settingText (setting).c_str());
  425. textcache::drawText (g, text, box, juce::Justification::centred, true);
  426. }
  427. g.setFont (theme::font (theme::type::body));
  428. }
  429. void ChannelRackComponent::setLoopPoint (int row, int setting)
  430. {
  431. if (row < 0 || row >= (int) engine.getSong().channels.size())
  432. return;
  433. engine.editSong ([row, setting] (Song& s) {
  434. auto& p = s.patterns[(std::size_t) s.currentPattern];
  435. auto value = setting;
  436. // FL's "Set to next beat / bar": a fixed loop point, the steps to the boundary after the channel's last note
  437. if (setting == 1000 + ChannelLoop::nextBeat || setting == 1000 + ChannelLoop::nextBar)
  438. value = channelloops::nextBoundarySteps (p, row, setting - 1000, s.beatsPerBar);
  439. channelloops::setSetting (p, row, value);
  440. // (FL switches the looping on, advanced, when a loop point is set from a channel)
  441. if (! p.loopOn && value != ChannelLoop::dontLoop)
  442. {
  443. p.loopOn = true;
  444. p.loopMode = RackLoopMode::advanced;
  445. }
  446. });
  447. updateSize();
  448. repaint();
  449. }
  450. void ChannelRackComponent::showLoopPointMenu (int row)
  451. {
  452. const auto& song = engine.getSong();
  453. if (row < 0 || row >= (int) song.channels.size())
  454. return;
  455. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  456. const auto setting = channelloops::effectiveSetting (p, row);
  457. juce::PopupMenu menu;
  458. ui::addItemHeader (menu, tr ("Loop point"), channelName (song, row), {});
  459. menu.addItem (tr ("Don't loop"), true, setting == ChannelLoop::dontLoop, [this, row] { setLoopPoint (row, ChannelLoop::dontLoop); });
  460. menu.addSeparator();
  461. menu.addItem (tr ("Step") + " - " + tr ("loop at the next step"), true, setting == ChannelLoop::nextStep, [this, row] { setLoopPoint (row, ChannelLoop::nextStep); });
  462. menu.addItem (tr ("Beat") + " - " + tr ("loop at the next beat"), true, setting == ChannelLoop::nextBeat, [this, row] { setLoopPoint (row, ChannelLoop::nextBeat); });
  463. menu.addItem (tr ("Bar") + " - " + tr ("loop at the next bar"), true, setting == ChannelLoop::nextBar, [this, row] { setLoopPoint (row, ChannelLoop::nextBar); });
  464. menu.addSeparator();
  465. menu.addItem (tr ("Set to next beat"), [this, row] { setLoopPoint (row, 1000 + ChannelLoop::nextBeat); });
  466. menu.addItem (tr ("Set to next bar"), [this, row] { setLoopPoint (row, 1000 + ChannelLoop::nextBar); });
  467. if (setting > 0)
  468. menu.addItem (tr ("Every {0} steps", { juce::String (setting) }), false, true, [] {});
  469. menu.addSectionHeader (tr ("Tools"));
  470. menu.addItem (tr ("Burn to pattern"), loopStepsOf (row) > 0, false, [this, row] {
  471. engine.editSong ([row] (Song& s) { channelloops::burnChannel (s.patterns[(std::size_t) s.currentPattern], row, s.beatsPerBar); });
  472. repaint();
  473. });
  474. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withTargetScreenArea (localAreaToGlobal (loopBoxBounds (row))));
  475. }
  476. bool ChannelRackComponent::isLoopingOn() const
  477. {
  478. const auto& song = engine.getSong();
  479. return ! song.patterns.empty() && song.patterns[(std::size_t) song.currentPattern].loopOn;
  480. }
  481. void ChannelRackComponent::toggleLooping()
  482. {
  483. engine.editSong ([] (Song& s) {
  484. auto& p = s.patterns[(std::size_t) s.currentPattern];
  485. p.loopOn = ! p.loopOn;
  486. });
  487. updateSize();
  488. repaint();
  489. if (onFilterChanged)
  490. onFilterChanged(); // (the title bar's Loop button)
  491. }
  492. void ChannelRackComponent::burnLoops (bool selectedOnly)
  493. {
  494. const auto rows = engine.getSelectedChannels();
  495. engine.editSong ([rows, selectedOnly] (Song& s) {
  496. auto& p = s.patterns[(std::size_t) s.currentPattern];
  497. if (selectedOnly)
  498. {
  499. for (auto r : rows)
  500. channelloops::burnChannel (p, r, s.beatsPerBar);
  501. }
  502. else
  503. channelloops::burnChannels (p, {}, s.beatsPerBar);
  504. });
  505. repaint();
  506. }
  507. void ChannelRackComponent::showLoopMenu (juce::Component* target)
  508. {
  509. const auto& song = engine.getSong();
  510. if (song.patterns.empty())
  511. return;
  512. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  513. juce::PopupMenu menu;
  514. menu.addItem (tr ("Looping on"), true, p.loopOn, [this] { toggleLooping(); });
  515. menu.addSectionHeader (tr ("Loop type"));
  516. const std::pair<RackLoopMode, const char*> types[] = { { RackLoopMode::steps, TR_NOOP ("Loop step channels") },
  517. { RackLoopMode::all, TR_NOOP ("Loop all channels") },
  518. { RackLoopMode::advanced, TR_NOOP ("Advanced looping") } };
  519. for (const auto& [mode, name] : types)
  520. menu.addItem (tr (name), true, p.loopMode == mode, [this, mode = mode] {
  521. engine.editSong ([mode] (Song& s) {
  522. auto& q = s.patterns[(std::size_t) s.currentPattern];
  523. q.loopMode = mode;
  524. q.loopOn = true; // (FL: picking a type switches the looping on)
  525. });
  526. updateSize();
  527. repaint();
  528. if (onFilterChanged)
  529. onFilterChanged();
  530. });
  531. menu.addSectionHeader (tr ("Burn to pattern"));
  532. const auto looping = ! channelloops::loopingChannels (p, song.beatsPerBar).empty();
  533. menu.addItem (tr ("Burn selected channels"), looping, false, [this] { burnLoops (true); });
  534. menu.addItem (tr ("Burn all looping channels"), looping, false, [this] { burnLoops (false); });
  535. auto options = juce::PopupMenu::Options();
  536. if (target != nullptr)
  537. options = options.withTargetComponent (target);
  538. menu.showMenuAsync (options);
  539. }
  540. void ChannelRackComponent::burnMidi (int channel, bool toNewPattern)
  541. {
  542. const auto& song = engine.getSong();
  543. if (song.patterns.empty() || channel < 0 || channel >= (int) song.channels.size())
  544. return;
  545. if (channelburn::playedNotes (song, song.currentPattern, channel).empty())
  546. {
  547. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Nothing to burn"),
  548. tr ("The selected channel doesn't contain any notes to burn."));
  549. return;
  550. }
  551. const auto baked = channelburn::whatBurns (song, song.currentPattern, channel);
  552. auto run = [this, channel, toNewPattern] (channelburn::Reset reset) {
  553. engine.editSong ([channel, toNewPattern, reset] (Song& s) { channelburn::burnMidi (s, channel, toNewPattern, reset); });
  554. updateSize();
  555. repaint();
  556. };
  557. if (! (baked.arpeggiator || baked.echo || baked.swing || baked.time))
  558. {
  559. run ({});
  560. return;
  561. }
  562. // FL's "Reset after burning to MIDI": what the burn wrote into the notes is switched off, or it would play twice
  563. struct ResetDialog final : juce::AlertWindow
  564. {
  565. explicit ResetDialog (const channelburn::Baked& baked)
  566. : juce::AlertWindow (tr ("Reset after burning to MIDI"), tr ("Select what you want to reset:"), juce::MessageBoxIconType::QuestionIcon)
  567. {
  568. const std::pair<const char*, bool> items[] = { { TR_NOOP ("Arpeggiator"), baked.arpeggiator }, { TR_NOOP ("Echo delay"), baked.echo },
  569. { TR_NOOP ("Swing mix"), baked.swing }, { TR_NOOP ("Time (shift and gate)"), baked.time } };
  570. for (std::size_t i = 0; i < toggles.size(); ++i)
  571. {
  572. toggles[i].setButtonText (tr (items[i].first));
  573. toggles[i].setToggleState (items[i].second, juce::dontSendNotification);
  574. toggles[i].setEnabled (items[i].second);
  575. toggles[i].setSize (300, 24);
  576. addCustomComponent (&toggles[i]);
  577. }
  578. addButton (tr ("Burn"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  579. addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  580. }
  581. channelburn::Reset reset() const
  582. {
  583. return { toggles[0].getToggleState(), toggles[1].getToggleState(), toggles[2].getToggleState(), toggles[3].getToggleState() };
  584. }
  585. std::array<juce::ToggleButton, 4> toggles;
  586. };
  587. auto* w = new ResetDialog (baked);
  588. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, run] (int result) {
  589. if (result == 1)
  590. run (w->reset());
  591. }), true);
  592. }
  593. ChannelRackComponent::Area ChannelRackComponent::areaAt (int x, int y, int& row) const
  594. {
  595. const auto channels = (int) engine.getSong().channels.size();
  596. row = rowAtY (y);
  597. if (x < stickyX + gridLeft()) // the controls column (painted at the visible left edge)
  598. x -= stickyX;
  599. if (row < 0 || row > channels)
  600. return Area::none;
  601. if (laneBounds().contains (x, y))
  602. return x < gridLeft() ? Area::laneLevels : Area::lane;
  603. if (row == channels)
  604. return x < gridLeft() ? Area::addRow : Area::none;
  605. if (advancedLoopShown() && x >= loopBoxBounds (row).getX() - 3) // the column covers the steps under it
  606. return loopBoxBounds (row).expanded (2, 3).contains (x, y) ? Area::loop : Area::none;
  607. if (x < muteWidth)
  608. return Area::mute;
  609. if (x < muteWidth + knobWidth)
  610. return Area::pan;
  611. if (x < muteWidth + 2 * knobWidth)
  612. return Area::volume;
  613. if (x < nameLeft())
  614. return Area::route;
  615. if (x < selectLeft())
  616. return Area::name;
  617. if (x < gridLeft())
  618. return Area::select;
  619. return Area::grid;
  620. }
  621. bool ChannelRackComponent::cellHasNote (int channel, int step) const
  622. {
  623. const auto& song = engine.getSong();
  624. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  625. const auto from = (std::int64_t) step * ticksPerStep;
  626. const auto to = from + ticksPerStep;
  627. for (const auto& n : p.notes) // (a muted note leaves its step looking off, as in FL: round 169f, FL session)
  628. if (n.channel == channel && n.start >= from && n.start < to && ! n.muted)
  629. return true;
  630. return false;
  631. }
  632. bool ChannelRackComponent::channelHitsNow (int row) const
  633. {
  634. if (playheadStep < 0 || playheadStep >= numSteps())
  635. return false;
  636. const auto& song = engine.getSong();
  637. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  638. const auto loopSteps = loopStepsOf (row);
  639. const auto step = loopSteps > 0 && playheadStep >= loopSteps ? playheadStep % loopSteps : playheadStep;
  640. return p.hasStep (row, step) || cellHasNote (row, step);
  641. }
  642. void ChannelRackComponent::paintStepHit (juce::Graphics& g, juce::Rectangle<float> r)
  643. {
  644. theme::fillRoundRect (g, r, theme::radius::sm, juce::Colours::white.withAlpha (0.55f));
  645. g.setColour (theme::colour::playhead);
  646. g.drawRoundedRectangle (r.reduced (0.75f), theme::radius::sm, 1.5f);
  647. }
  648. void ChannelRackComponent::paint (juce::Graphics& g)
  649. {
  650. const uitrace::Scope trace ("ChannelRackComponent paint", true, g.getClipBounds());
  651. using namespace theme::colour;
  652. g.fillAll (bg2);
  653. const auto& song = engine.getSong();
  654. if (song.patterns.empty())
  655. return;
  656. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  657. const auto steps = shownSteps(), realSteps = numSteps();
  658. const auto clip = g.getClipBounds();
  659. const auto primary = engine.getSelectedChannel();
  660. const auto& selection = engine.getSelectedChannels();
  661. const auto column = playheadColumn.load (std::memory_order_relaxed) && playheadStep >= 0 && playheadStep < steps;
  662. g.setFont (theme::font (theme::type::body));
  663. for (int row = 0; row < (int) song.channels.size(); ++row)
  664. {
  665. const auto y = rowY (row);
  666. if (! isShown (row) || y > clip.getBottom() || y + rowHeight < clip.getY())
  667. continue;
  668. const auto& channel = song.channels[(std::size_t) row];
  669. const auto selected = std::binary_search (selection.begin(), selection.end(), row);
  670. if (selected) // selected rows are subtly lifted
  671. {
  672. g.setColour (bg3);
  673. g.fillRect (0, y + 1, getWidth(), rowHeight - 2);
  674. }
  675. if (column) // LYNX: the playing column, soft, under the step buttons (their colours and groups stay readable)
  676. {
  677. g.setColour (playhead.withAlpha (0.2f));
  678. g.fillRect (gridLeft() + playheadStep * stepWidth - 1, y, stepWidth, rowHeight);
  679. }
  680. if (channel.instrument == InstrumentKind::audioClip)
  681. {
  682. g.setColour (textDisabled);
  683. g.setFont (theme::font (theme::type::small));
  684. textcache::drawText (g, tr ("audio clip — plays from the Playlist"), gridLeft() + 4, y, 400, rowHeight, juce::Justification::centredLeft);
  685. g.setFont (theme::font (theme::type::body));
  686. continue;
  687. }
  688. const auto loopSteps = loopStepsOf (row); // the row loops: the repeats after its loop point are ghost steps
  689. if (showsNotePreview (pattern, row, pianoRollView)) // piano-roll notes: a miniature instead of the step buttons
  690. {
  691. paintNotePreview (g, row, pattern, channel.colour);
  692. if (loopSteps > 0)
  693. {
  694. g.setColour (accent.withAlpha (0.85f));
  695. g.fillRect (gridLeft() + loopSteps * stepWidth - 2, y + 3, 2, rowHeight - 6);
  696. }
  697. continue;
  698. }
  699. for (int step = 0; step < steps; ++step)
  700. {
  701. const auto r = stepBounds (row, step);
  702. if (r.getRight() < clip.getX() || r.getX() > clip.getRight())
  703. continue;
  704. auto onGrid = pattern.hasStep (row, step);
  705. auto any = onGrid || cellHasNote (row, step);
  706. const auto hoverStepHere = hoverArea == Area::grid && hoverRow == row && hoverStep == step && paintMode == PaintMode::none;
  707. if (loopSteps > 0 && step >= loopSteps && step < realSteps)
  708. {
  709. // FL's loop ghosts: what the loop repeats here, faint; a step of its own past the loop point doesn't play
  710. const auto source = step % loopSteps;
  711. const auto repeated = pattern.hasStep (row, source) || cellHasNote (row, source);
  712. auto fill = repeated ? stepOn : theme::stepOff (step);
  713. theme::fillRoundRect (g, r.toFloat(), theme::radius::sm, fill.withMultipliedAlpha (hoverStepHere ? 0.75f : repeated ? 0.45f : 0.3f));
  714. if (repeated && step == playheadStep) // the repeat plays: lit as a hit (below)
  715. paintStepHit (g, r.toFloat());
  716. if (any)
  717. {
  718. g.setColour (textDisabled);
  719. g.drawRoundedRectangle (r.toFloat().reduced (1.5f), theme::radius::sm, 1.0f);
  720. }
  721. if (hoverStepHere)
  722. {
  723. g.setColour (textSecondary.withAlpha (0.7f));
  724. g.drawRoundedRectangle (r.toFloat().reduced (0.5f), theme::radius::sm, 1.0f);
  725. }
  726. continue;
  727. }
  728. const auto ghost = step >= realSteps && ! any; // after the pattern's end: faint until clicked
  729. auto fill = any ? (onGrid ? stepOn : stepNote) : theme::stepOff (step);
  730. if (ghost) // a faint outlined cell, filled while hovered
  731. {
  732. theme::fillRoundRect (g, r.toFloat(), theme::radius::sm, fill.withMultipliedAlpha (hoverStepHere ? 0.9f : 0.35f));
  733. g.setColour (fill.brighter (0.25f).withMultipliedAlpha (0.55f));
  734. g.drawRoundedRectangle (r.toFloat().reduced (0.5f), theme::radius::sm, 1.0f);
  735. }
  736. else
  737. theme::fillRoundRect (g, r.toFloat(), theme::radius::sm, hoverStepHere ? fill.brighter (any ? 0.15f : 0.35f) : fill);
  738. // FL lights the step as the playhead hits it (its LED turns red, round 170a [SHOT]): a step that plays now glows
  739. if (any && step == playheadStep && step < realSteps)
  740. paintStepHit (g, r.toFloat());
  741. if (hoverStepHere)
  742. {
  743. g.setColour (textSecondary.withAlpha (0.7f));
  744. g.drawRoundedRectangle (r.toFloat().reduced (0.5f), theme::radius::sm, 1.0f);
  745. }
  746. }
  747. if (loopSteps > 0) // the loop point
  748. {
  749. g.setColour (accent.withAlpha (0.85f));
  750. g.fillRect (gridLeft() + loopSteps * stepWidth - 2, y + 3, 2, rowHeight - 6);
  751. }
  752. }
  753. paintLane (g);
  754. const auto addY = rowY ((int) song.channels.size());
  755. g.setColour (textDisabled);
  756. g.setFont (theme::font (theme::type::small));
  757. textcache::drawText (g, tr ("or drop an audio file here"), gridLeft() + 4, addY + positionStripHeight, 400, rowHeight - positionStripHeight,
  758. juce::Justification::centredLeft);
  759. const auto stepsPerBar = std::max (1, song.beatsPerBar) * (int) (ppq / ticksPerStep);
  760. // FL's "Playing step" strip (PosLEDPanel, REA round 170a §2): a slim LED row under the steps, beat groups
  761. // alternating, the playing step lit — in Pattern mode and whenever the shown pattern plays in Song mode
  762. for (int step = 0; step < realSteps; ++step)
  763. {
  764. const auto cell = juce::Rectangle<float> ((float) (gridLeft() + step * stepWidth) + 1.0f, (float) addY + 2.0f, (float) stepWidth - 4.0f,
  765. (float) positionStripHeight - 3.0f);
  766. if (cell.getRight() < (float) clip.getX() || cell.getX() > (float) clip.getRight())
  767. continue;
  768. theme::fillRoundRect (g, cell, 1.5f, step == playheadStep ? playhead : theme::stepOff (step).brighter (0.12f));
  769. // LYNX: each bar's first step marked (finding the bars on 32 / 64-step patterns)
  770. if (playheadColumn.load (std::memory_order_relaxed) && step % stepsPerBar == 0 && step != playheadStep)
  771. {
  772. g.setColour (accent.withAlpha (0.7f));
  773. g.fillRect (cell.withHeight (2.0f));
  774. }
  775. }
  776. // the controls column stays put while the steps scroll sideways (FL's rack keeps the channel buttons in
  777. // view): the viewport moves the whole rack, so the column is painted again at the visible left edge
  778. {
  779. juce::Graphics::ScopedSaveState state (g);
  780. g.reduceClipRegion (stickyX, 0, gridLeft(), getHeight());
  781. g.setOrigin (stickyX, 0);
  782. g.setColour (bg2);
  783. g.fillRect (0, 0, gridLeft(), getHeight());
  784. const auto column = g.getClipBounds();
  785. for (int row = 0; row < (int) song.channels.size(); ++row)
  786. {
  787. const auto y = rowY (row);
  788. if (! isShown (row) || y > column.getBottom() || y + rowHeight < column.getY())
  789. continue;
  790. const auto& channel = song.channels[(std::size_t) row];
  791. const auto selected = std::binary_search (selection.begin(), selection.end(), row);
  792. const auto nameArea = juce::Rectangle<float> ((float) nameLeft(), (float) y + 3, (float) nameWidth, (float) rowHeight - 6);
  793. if (selected) // selected rows are subtly lifted
  794. {
  795. g.setColour (bg3);
  796. g.fillRect (0, y + 1, getWidth(), rowHeight - 2);
  797. }
  798. const auto hovered = [this, row] (Area a) { return hoverRow == row && hoverArea == a; };
  799. const auto led = juce::Rectangle<float> (9.0f, (float) y + rowHeight / 2.0f - 4.5f, 9.0f, 9.0f);
  800. g.setColour (theme::muteLed (channel.muted));
  801. g.fillEllipse (led);
  802. if (hovered (Area::mute)) // hover ring
  803. {
  804. g.setColour (textSecondary.withAlpha (0.8f));
  805. g.drawEllipse (led.expanded (2.5f), 1.0f);
  806. }
  807. const auto touched = knobDrag != Area::none && knobRow == row;
  808. // (while the song plays an automated knob shows its automation's value, issue #12)
  809. const auto& automated = engine.getAutomationDisplay();
  810. theme::drawKnob (g, controlBounds (Area::pan, row).toFloat().reduced (1.0f, 2.0f),
  811. automated.shown ({ AutomationTargetKind::channelPan, row }, (channel.pan + 1.0f) / 2.0f), true,
  812. touched && knobDrag == Area::pan ? accent : info, hovered (Area::pan) || (touched && knobDrag == Area::pan));
  813. theme::drawKnob (g, controlBounds (Area::volume, row).toFloat().reduced (1.0f, 2.0f),
  814. automated.shown ({ AutomationTargetKind::channelVolume, row }, channel.volume), false,
  815. touched && knobDrag == Area::volume ? accent : knobArc, hovered (Area::volume) || (touched && knobDrag == Area::volume));
  816. // small box with the mixer insert ("-" = straight to Master)
  817. const auto routeArea = controlBounds (Area::route, row).toFloat();
  818. g.setColour (theme::drawDigitDisplay (g, routeArea, hovered (Area::route) || (touched && knobDrag == Area::route),
  819. channel.mixerTrack <= 0));
  820. g.setFont (theme::font (theme::type::caption, true));
  821. textcache::drawText (g, channel.mixerTrack > 0 ? juce::String (channel.mixerTrack) : juce::String ("-"), routeArea.toNearestInt(),
  822. juce::Justification::centred);
  823. g.setFont (theme::font (theme::type::body));
  824. // name button: tinted with the channel colour (from the .flp or user-picked), so channels are found by
  825. // colour as in FL; kept dark and toned down (LYNX look), with the colour strip at its left
  826. {
  827. auto plate = row == primary ? bg6 : hovered (Area::name) ? bg5 : bg4;
  828. if (channel.colour != 0)
  829. plate = plate.interpolatedWith (theme::tame (juce::Colour (channel.colour)), row == primary ? 0.42f : 0.32f);
  830. theme::fillRoundRect (g, nameArea, theme::radius::md, plate);
  831. }
  832. if (row == primary)
  833. {
  834. g.setColour (accent);
  835. g.drawRoundedRectangle (nameArea.reduced (0.5f), theme::radius::md, 1.0f);
  836. }
  837. theme::fillRoundRect (g, nameArea.withWidth (4.0f).reduced (0.0f, 3.0f).translated (3.0f, 0.0f), 1.5f, channel.colour != 0 ? theme::tame (juce::Colour (channel.colour)) : bg6.brighter (0.2f));
  838. const auto locked = ! channel.receiveFrom.empty();
  839. if (locked) // FL's lock icon: the channel receives the notes of one MIDI input ("Receive notes from")
  840. {
  841. const auto lockBox = juce::Rectangle<float> (nameArea.getRight() - 15.0f, nameArea.getCentreY() - 6.0f, 9.0f, 11.0f);
  842. g.setColour (warning);
  843. juce::Path shackle;
  844. shackle.addCentredArc (lockBox.getCentreX(), lockBox.getY() + 4.0f, 2.8f, 3.2f, 0.0f, -juce::MathConstants<float>::halfPi,
  845. juce::MathConstants<float>::halfPi, true);
  846. g.strokePath (shackle, juce::PathStrokeType (1.4f));
  847. g.fillRoundedRectangle (lockBox.withTrimmedTop (4.5f), 1.5f);
  848. }
  849. // Online Sessions (round 168a): the plugin is not installed here, its stand-in render plays (an amber tag)
  850. auto badgeWidth = 0.0f;
  851. if (engine.playsStandIn (row))
  852. {
  853. badgeWidth = 16.0f;
  854. juce::Graphics::ScopedSaveState keepFont (g);
  855. const auto tag = juce::Rectangle<float> (nameArea.getRight() - (locked ? 34.0f : 18.0f), nameArea.getCentreY() - 6.5f, 14.0f, 13.0f);
  856. theme::fillRoundRect (g, tag, 3.0f, warning.withAlpha (0.85f));
  857. g.setColour (bg1);
  858. g.setFont (theme::font (10.0f, true));
  859. g.drawText ("R", tag, juce::Justification::centred, false);
  860. }
  861. // the channel's icon before its name, as FL's channel button shows it (round 168h)
  862. auto iconWidth = 0;
  863. if (const auto icon = trackicons::iconFor (channel.icon); icon != trackicons::Icon::none)
  864. {
  865. iconWidth = 16;
  866. ui::drawTrackIcon (g, icon, juce::Rectangle<float> (nameArea.getX() + 12.0f, nameArea.getCentreY() - 7.0f, 14.0f, 14.0f),
  867. channel.muted ? textDisabled : textSecondary.brighter (0.3f));
  868. }
  869. g.setColour (channel.muted ? textDisabled : textPrimary);
  870. textcache::drawText (g, juce::String::fromUTF8 (channel.name.c_str()),
  871. nameArea.withTrimmedLeft ((float) (14 + iconWidth)).withTrimmedRight ((locked ? 18 : 6) + badgeWidth).toNearestInt(), juce::Justification::centredLeft, true);
  872. // selector: a slim pill, lit when the row is selected
  873. const auto pill = juce::Rectangle<float> ((float) selectLeft() + 3.0f, (float) y + 7.0f, (float) selectWidth - 6.0f, (float) rowHeight - 14.0f);
  874. theme::fillRoundRect (g, pill, 3.0f, selected ? (hovered (Area::select) ? accentHover : accent) : hovered (Area::select) ? textDisabled : ledOff);
  875. // FL flashes the channel's selector as its note plays (round 170a [SHOT]): the "sound lighting up when it hits"
  876. if (! channel.muted && channelHitsNow (row))
  877. theme::fillRoundRect (g, pill.expanded (1.0f, 0.0f), 3.0f, juce::Colours::white.withAlpha (selected ? 0.75f : 0.9f));
  878. }
  879. paintLane (g);
  880. {
  881. const auto addArea = juce::Rectangle<float> ((float) nameLeft(), (float) addY + 3, (float) nameWidth, (float) rowHeight - 6);
  882. const float dash[] = { 3.0f, 3.0f };
  883. juce::Path outline, dashed;
  884. outline.addRoundedRectangle (addArea.reduced (0.5f), theme::radius::md);
  885. juce::PathStrokeType (1.0f).createDashedStroke (dashed, outline, dash, 2);
  886. const auto addHovered = hoverArea == Area::addRow;
  887. g.setColour (addHovered ? textSecondary : borderStrong);
  888. g.fillPath (dashed);
  889. g.setColour (addHovered ? textPrimary : textSecondary);
  890. g.setFont (theme::font (theme::type::small));
  891. textcache::drawText (g, tr ("+ add channel"), addArea.toNearestInt(), juce::Justification::centred);
  892. }
  893. if (stickyX > 0) // steps pass under the column: a hairline marks its edge
  894. {
  895. g.setColour (border);
  896. g.fillRect (gridLeft() - 1, 0, 1, getHeight());
  897. }
  898. }
  899. if (advancedLoopShown())
  900. paintLoopColumn (g);
  901. }
  902. // The miniature of a channel's piano-roll notes across its step area (FL shows one once a channel has notes
  903. // that steps can't show); the notes keep their time and length, pitch maps onto the row's height.
  904. void ChannelRackComponent::paintNotePreview (juce::Graphics& g, int row, const Pattern& pattern, std::uint32_t channelColour)
  905. {
  906. using namespace theme::colour;
  907. const auto steps = numSteps();
  908. const auto area = juce::Rectangle<float> ((float) gridLeft() + 1.0f, (float) rowY (row) + 4.0f, (float) (steps * stepWidth) - 3.0f,
  909. (float) rowHeight - 8.0f);
  910. const auto hoveredHere = hoverArea == Area::grid && hoverRow == row;
  911. theme::fillRoundRect (g, area, theme::radius::sm, hoveredHere ? bg4 : bg1);
  912. for (int beat = 4; beat < steps; beat += 4) // beat lines, bars a little stronger
  913. {
  914. g.setColour (beat % 16 == 0 ? border.brighter (0.2f) : border);
  915. g.fillRect (area.getX() + (float) (beat * stepWidth) - 1.5f, area.getY() + 2.0f, 1.0f, area.getHeight() - 4.0f);
  916. }
  917. const auto [low, high] = channelKeyRange (pattern, row);
  918. const auto span = juce::jmax (high - low, 6); // a single key sits mid-row, not on an edge
  919. const auto lowKey = low - (span - (high - low)) / 2;
  920. const auto inner = area.reduced (1.0f, 3.0f);
  921. const auto noteHeight = juce::jlimit (3.0f, 5.0f, inner.getHeight() / (float) (span + 1));
  922. const auto ticks = (float) (steps * ticksPerStep);
  923. const auto tint = channelColour != 0 ? theme::tame (juce::Colour (channelColour)).brighter (0.6f) : stepNote;
  924. // a looping row (round 165f-rack): the notes before the loop point, then their repeats faint; a note of its own past
  925. // the loop point doesn't play (dim)
  926. const auto loopTicks = (std::int64_t) loopStepsOf (row) * ticksPerStep;
  927. const auto patternTicks = (std::int64_t) steps * ticksPerStep;
  928. for (const auto& n : pattern.notes)
  929. {
  930. if (n.channel != row)
  931. continue;
  932. const auto pastLoop = loopTicks > 0 && n.start >= loopTicks;
  933. const auto repeats = loopTicks > 0 && ! pastLoop ? (int) ((patternTicks - n.start + loopTicks - 1) / loopTicks) : 1;
  934. for (int k = 0; k < repeats; ++k)
  935. {
  936. const auto start = n.start + k * loopTicks;
  937. const auto x = inner.getX() + inner.getWidth() * (float) start / ticks;
  938. if (x > inner.getRight())
  939. break;
  940. const auto w = juce::jmax (2.0f, inner.getWidth() * (float) n.length / ticks - 1.0f);
  941. const auto y = inner.getBottom() - noteHeight - (inner.getHeight() - noteHeight) * (float) (n.key - lowKey) / (float) span;
  942. g.setColour (n.muted || pastLoop ? textDisabled.withAlpha (pastLoop ? 0.5f : 1.0f) : k > 0 ? tint.withAlpha (0.4f) : tint);
  943. g.fillRect (juce::Rectangle<float> (x, y, juce::jmin (w, inner.getRight() - x), noteHeight));
  944. }
  945. }
  946. }
  947. // --- the control contract for the knobs and the route box ----------------------------------------
  948. ui::ValueSpec ChannelRackComponent::specFor (Area area, int row) const
  949. {
  950. const auto name = channelName (engine.getSong(), row);
  951. if (area == Area::pan)
  952. {
  953. auto spec = ui::panSpec (name + " - " + tr ("Pan"));
  954. spec.target = AutomationTarget { AutomationTargetKind::channelPan, row };
  955. return spec;
  956. }
  957. if (area == Area::volume)
  958. {
  959. auto spec = ui::percentSpec (name + " - " + tr ("Volume"), 0.78);
  960. spec.target = AutomationTarget { AutomationTargetKind::channelVolume, row };
  961. return spec;
  962. }
  963. // route box: the mixer insert, as a number
  964. ui::ValueSpec spec;
  965. spec.name = name + " - " + tr ("Target mixer track");
  966. spec.maximum = maxMixerTracks - 1; // every insert, like FL (round 162: the inserts past the mixer's last one are added)
  967. spec.interval = 1.0;
  968. spec.toText = [] (double v) { return v < 0.5 ? tr ("Master") : tr ("Insert {0}", { juce::String (juce::roundToInt (v)) }); };
  969. spec.fromText = [] (const juce::String& t) -> std::optional<double> {
  970. if (t.trim().startsWithIgnoreCase ("m"))
  971. return 0.0;
  972. const auto digits = t.retainCharacters ("0123456789");
  973. return digits.isEmpty() ? std::nullopt : std::optional<double> (digits.getDoubleValue());
  974. };
  975. return ui::digitWheel (spec); // FL's channel rack mixer-track digiwheel (round 168s)
  976. }
  977. double ChannelRackComponent::valueOf (Area area, int row) const
  978. {
  979. const auto& c = engine.getSong().channels[(std::size_t) row];
  980. return area == Area::pan ? c.pan : area == Area::volume ? c.volume : (double) c.mixerTrack;
  981. }
  982. void ChannelRackComponent::setValue (Area area, int row, double value)
  983. {
  984. if (row < 0 || row >= (int) engine.getSong().channels.size())
  985. return;
  986. if (area == Area::pan)
  987. engine.editLevels ([row, v = (float) value] (Song& s) { s.channels[(std::size_t) row].pan = v; });
  988. else if (area == Area::volume)
  989. engine.editLevels ([row, v = (float) value] (Song& s) { s.channels[(std::size_t) row].volume = v; });
  990. else if (area == Area::route)
  991. {
  992. const auto track = juce::roundToInt (value);
  993. if (track != engine.getSong().channels[(std::size_t) row].mixerTrack)
  994. engine.editSong ([row, track] (Song& s) { mixerops::routeChannel (s, row, track); });
  995. }
  996. }
  997. juce::Rectangle<int> ChannelRackComponent::controlBounds (Area area, int row) const
  998. {
  999. const auto y = rowY (row);
  1000. switch (area)
  1001. {
  1002. case Area::pan: return { muteWidth, y, knobWidth, rowHeight };
  1003. case Area::volume: return { muteWidth + knobWidth, y, knobWidth, rowHeight };
  1004. case Area::route: return { muteWidth + 2 * knobWidth + 1, y + 7, routeWidth - 3, rowHeight - 14 };
  1005. case Area::lane:
  1006. {
  1007. const auto lane = laneBounds();
  1008. const auto step = juce::jmax (0, hoverStep);
  1009. return { gridLeft() + step * stepWidth, lane.getY() + 6, stepWidth, lane.getHeight() - 12 };
  1010. }
  1011. default: return {};
  1012. }
  1013. }
  1014. void ChannelRackComponent::showTip (Area area, int row, bool transient)
  1015. {
  1016. if (row < 0 || row >= (int) engine.getSong().channels.size())
  1017. return;
  1018. const auto spec = specFor (area, row);
  1019. const auto text = spec.text (valueOf (area, row));
  1020. ui::postHint (ui::valueHint (spec, valueOf (area, row), ui::valueGestures()));
  1021. const auto bounds = area == Area::lane ? controlBounds (area, row) : controlBounds (area, row).translated (stickyX, 0);
  1022. if (transient)
  1023. ui::flashValueTip (*this, bounds, text);
  1024. else
  1025. ui::showValueTip (*this, bounds, text);
  1026. }
  1027. void ChannelRackComponent::setHover (Area area, int row, int step)
  1028. {
  1029. if (area == hoverArea && row == hoverRow && step == hoverStep)
  1030. return;
  1031. auto dirty = [this] (Area a, int r) {
  1032. if (a == Area::lane || a == Area::laneLevels)
  1033. repaint (laneBounds());
  1034. else if (a == Area::addRow)
  1035. repaint (rowBounds ((int) engine.getSong().channels.size()));
  1036. else if (r >= 0)
  1037. repaint (rowBounds (r));
  1038. };
  1039. dirty (hoverArea, hoverRow);
  1040. hoverArea = area;
  1041. hoverRow = row;
  1042. hoverStep = step;
  1043. dirty (hoverArea, hoverRow);
  1044. }
  1045. void ChannelRackComponent::mouseMove (const juce::MouseEvent& e)
  1046. {
  1047. int row = 0;
  1048. const auto area = areaAt (e.x, e.y, row);
  1049. const auto step = area == Area::grid || area == Area::lane ? (e.x - gridLeft()) / stepWidth : -1;
  1050. setHover (area, row, step >= 0 && step < (area == Area::grid ? shownSteps() : numSteps()) ? step : -1);
  1051. }
  1052. void ChannelRackComponent::mouseExit (const juce::MouseEvent&)
  1053. {
  1054. setHover (Area::none, -1, -1);
  1055. }
  1056. void ChannelRackComponent::setSwingMixOfSelected (int channel)
  1057. {
  1058. const auto& song = engine.getSong();
  1059. if (channel < 0 || channel >= (int) song.channels.size())
  1060. return;
  1061. auto spec = ui::percentSpec (channelName (song, channel) + " - " + tr ("Swing mix"), 1.0);
  1062. const auto rows = engine.getSelectedChannels();
  1063. ui::typeValue (*this, spec, song.channels[(std::size_t) channel].swingMix, [this, rows, channel] (double v) {
  1064. engine.editSong ([rows, channel, v] (Song& s) {
  1065. auto targets = rows;
  1066. if (std::find (targets.begin(), targets.end(), channel) == targets.end())
  1067. targets = { channel };
  1068. for (auto r : targets)
  1069. if (r >= 0 && r < (int) s.channels.size())
  1070. s.channels[(std::size_t) r].swingMix = (float) v;
  1071. });
  1072. });
  1073. }
  1074. // --- selection -----------------------------------------------------------------------------------
  1075. void ChannelRackComponent::selectRows (std::vector<int> rows, int primary)
  1076. {
  1077. engine.setChannelSelection (std::move (rows), primary);
  1078. repaint();
  1079. }
  1080. void ChannelRackComponent::clickSelector (int row, const juce::ModifierKeys& mods)
  1081. {
  1082. ChannelSelection selection;
  1083. selection.rows = engine.getSelectedChannels();
  1084. selection.anchor = selectionAnchor;
  1085. if (mods.isShiftDown())
  1086. selection.extendTo (row);
  1087. else if (flmods::ctrl (mods) || flmods::popup (mods))
  1088. selection.toggle (row);
  1089. else
  1090. selection.selectOnly (row);
  1091. selectionAnchor = selection.anchor;
  1092. const auto primary = selection.contains (row) ? row : selection.rows.front();
  1093. selectRows (selection.rows, primary);
  1094. }
  1095. void ChannelRackComponent::selectRelative (int delta, bool extend)
  1096. {
  1097. const auto count = (int) engine.getSong().channels.size();
  1098. if (count == 0)
  1099. return;
  1100. const auto row = juce::jlimit (0, count - 1, engine.getSelectedChannel() + delta);
  1101. if (extend)
  1102. {
  1103. ChannelSelection selection;
  1104. selection.anchor = selectionAnchor;
  1105. selection.extendTo (row);
  1106. selectRows (selection.rows, row);
  1107. }
  1108. else
  1109. {
  1110. selectionAnchor = row;
  1111. selectRows ({ row }, row);
  1112. }
  1113. }
  1114. void ChannelRackComponent::selectAll()
  1115. {
  1116. ChannelSelection selection;
  1117. selection.selectAll ((int) engine.getSong().channels.size());
  1118. selectRows (selection.rows, engine.getSelectedChannel());
  1119. }
  1120. bool ChannelRackComponent::moveSelected (int delta)
  1121. {
  1122. auto rows = engine.getSelectedChannels();
  1123. const auto primary = engine.getSelectedChannel();
  1124. const auto primaryIndex = (int) (std::find (rows.begin(), rows.end(), primary) - rows.begin());
  1125. bool moved = false;
  1126. std::vector<int> after;
  1127. engine.editSongStructural ([&] (Song& s) {
  1128. after = rows;
  1129. moved = moveChannels (s, after, delta);
  1130. });
  1131. if (! moved)
  1132. return false;
  1133. const auto newPrimary = primaryIndex < (int) after.size() ? after[(std::size_t) primaryIndex] : after.front();
  1134. openEditorRow = -1;
  1135. selectionAnchor = juce::jlimit (0, (int) engine.getSong().channels.size() - 1, selectionAnchor + delta);
  1136. selectRows (after, newPrimary);
  1137. return true;
  1138. }
  1139. void ChannelRackComponent::cloneSelected()
  1140. {
  1141. auto rows = engine.getSelectedChannels();
  1142. std::vector<int> clones;
  1143. engine.editSong ([&] (Song& s) {
  1144. // from the bottom up, so earlier clones don't shift the rows still to clone
  1145. for (auto it = rows.rbegin(); it != rows.rend(); ++it)
  1146. cloneChannel (s, *it);
  1147. });
  1148. // each clone sits right below its original: original i (sorted) ends at rows[i] + i, its clone one below
  1149. for (std::size_t i = 0; i < rows.size(); ++i)
  1150. clones.push_back (rows[i] + (int) i + 1);
  1151. if (! clones.empty())
  1152. selectRows (clones, clones.front());
  1153. }
  1154. void ChannelRackComponent::deleteSelected()
  1155. {
  1156. const auto rows = engine.getSelectedChannels();
  1157. const auto count = (int) engine.getSong().channels.size();
  1158. if (rows.empty() || (int) rows.size() >= count) // at least one channel stays
  1159. return;
  1160. for (auto r : rows)
  1161. closeEditor (r);
  1162. engine.editSong ([rows] (Song& s) { removeChannels (s, rows); });
  1163. openEditorRow = -1;
  1164. const auto row = juce::jlimit (0, juce::jmax (0, (int) engine.getSong().channels.size() - 1), rows.front());
  1165. selectRows ({ row }, row);
  1166. }
  1167. void ChannelRackComponent::sendSelectedToInserts()
  1168. {
  1169. const auto rows = engine.getSelectedChannels();
  1170. engine.editSong ([rows] (Song& s) { sendChannelsToFreeInserts (s, rows); });
  1171. }
  1172. void ChannelRackComponent::toggleMute (int channel)
  1173. {
  1174. if (channel >= 0 && channel < (int) engine.getSong().channels.size())
  1175. engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].muted = ! s.channels[(std::size_t) channel].muted; });
  1176. }
  1177. void ChannelRackComponent::solo (int row)
  1178. {
  1179. if (row < 0 || row >= (int) engine.getSong().channels.size())
  1180. return;
  1181. // only this channel plays (the channels with "Lock active/mute state" keep theirs); repeating on the soloed channel
  1182. // unmutes them (FL's channel solo, REA_rodada167l §5)
  1183. engine.editSong ([row] (Song& s) { noteedit::soloChannel (s, row); });
  1184. }
  1185. // --- channel editors ---------------------------------------------------------------------------
  1186. bool ChannelRackComponent::isEditorOpen (int channel)
  1187. {
  1188. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  1189. return false;
  1190. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::plugin)
  1191. {
  1192. if (auto* plugin = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get()))
  1193. return PluginWindows::isOpen (plugin->getInstance());
  1194. return false;
  1195. }
  1196. return isChannelSettingsOpen (channel);
  1197. }
  1198. void ChannelRackComponent::closeEditor (int channel)
  1199. {
  1200. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  1201. return;
  1202. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::plugin)
  1203. {
  1204. if (auto* plugin = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get()))
  1205. PluginWindows::close (plugin->getInstance());
  1206. }
  1207. else
  1208. closeChannelSettings (channel);
  1209. }
  1210. void ChannelRackComponent::toggleEditor (int channel, bool keepOthers)
  1211. {
  1212. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  1213. return;
  1214. const auto kind = engine.getSong().channels[(std::size_t) channel].instrument;
  1215. if (kind == InstrumentKind::patcher) // its node graph editor (REA_rodada141)
  1216. {
  1217. if (PatcherWindows::isChannelOpen (channel))
  1218. PatcherWindows::closeChannel (channel);
  1219. else
  1220. PatcherWindows::openChannel (engine, channel);
  1221. return;
  1222. }
  1223. // built-in drums and audio clips have no instrument page: as in FL, the click opens their channel window anyway
  1224. // (header + Misc tab — levels, polyphony, cut groups, arpeggiator), as the hint says; it only selected (round 165q)
  1225. if (isEditorOpen (channel))
  1226. {
  1227. closeEditor (channel);
  1228. if (openEditorRow == channel)
  1229. openEditorRow = -1;
  1230. return;
  1231. }
  1232. if (! keepOthers && ! keepEditorsOpen && openEditorRow != channel)
  1233. closeEditor (openEditorRow);
  1234. if (kind == InstrumentKind::plugin)
  1235. openPluginWindow (channel);
  1236. else
  1237. openChannelSettings (engine, channel);
  1238. openEditorRow = channel;
  1239. }
  1240. // --- step graph lanes (docs/WORKFLOW_FL.md P2, C4) --------------------------------------------------
  1241. juce::Rectangle<int> ChannelRackComponent::levelButtonBounds (int level) const
  1242. {
  1243. const auto lane = laneBounds();
  1244. const auto width = (gridLeft() - 24) / 3;
  1245. return { 12 + (level % 3) * width, lane.getY() + 8 + (level / 3) * 24, width - 4, 20 };
  1246. }
  1247. void ChannelRackComponent::paintLane (juce::Graphics& g)
  1248. {
  1249. using namespace theme::colour;
  1250. const auto lane = laneBounds();
  1251. if (lane.isEmpty() || ! g.getClipBounds().intersects (lane))
  1252. return;
  1253. const auto& song = engine.getSong();
  1254. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  1255. const auto channel = graphRow();
  1256. const auto level = (notetools::Level) graphLevel;
  1257. g.setColour (bg0);
  1258. g.fillRect (lane);
  1259. g.setColour (border);
  1260. g.drawHorizontalLine (lane.getY(), 0.0f, (float) getWidth());
  1261. g.drawHorizontalLine (lane.getBottom() - 1, 0.0f, (float) getWidth());
  1262. for (int l = 0; l < notetools::levelCount; ++l)
  1263. {
  1264. const auto r = levelButtonBounds (l).toFloat();
  1265. theme::fillRoundRect (g, r, theme::radius::sm, l == graphLevel ? accent : bg4);
  1266. g.setColour (l == graphLevel ? onAccent : textSecondary);
  1267. g.setFont (theme::font (theme::type::caption, l == graphLevel));
  1268. textcache::drawFittedText (g, tr (notetools::levelName ((notetools::Level) l)), r.toNearestInt(), juce::Justification::centred, 1, 0.8f);
  1269. }
  1270. g.setColour (textDisabled);
  1271. g.setFont (theme::font (theme::type::caption));
  1272. textcache::drawFittedText (g, tr ("Drag: set · Right-drag: ramp · Alt+click: reset"),
  1273. juce::Rectangle<int> (12, lane.getBottom() - 20, gridLeft() - 24, 16), juce::Justification::centredLeft, 1, 0.8f);
  1274. const auto top = (float) lane.getY() + 6.0f, bottom = (float) lane.getBottom() - 6.0f;
  1275. const auto bipolar = notetools::levelIsBipolar (level);
  1276. const auto base = bipolar ? (top + bottom) * 0.5f : bottom;
  1277. for (int step = 0; step < numSteps(); ++step)
  1278. {
  1279. const auto x = (float) (gridLeft() + step * stepWidth + 1);
  1280. const auto w = (float) stepWidth - 3.0f;
  1281. if (step % 4 == 0 && step > 0)
  1282. {
  1283. g.setColour (step % 16 == 0 ? gridBar : gridBeat);
  1284. g.drawVerticalLine ((int) x - 2, top, bottom);
  1285. }
  1286. if (hoverArea == Area::lane && hoverStep == step)
  1287. {
  1288. g.setColour (bg3);
  1289. g.fillRect (juce::Rectangle<float> (x, top, w, bottom - top));
  1290. }
  1291. const auto notes = notesInStep (pattern, channel, step);
  1292. if (notes.empty())
  1293. {
  1294. g.setColour (theme::stepOff (step));
  1295. g.fillRect (x + w * 0.5f - 1.0f, base - 1.0f, 2.0f, 2.0f);
  1296. continue;
  1297. }
  1298. const auto v = notetools::levelValue (pattern.notes[(std::size_t) notes.front()], level);
  1299. const auto y = bottom - v * (bottom - top);
  1300. g.setColour ((level == notetools::Level::velocity ? accent : info).withAlpha (0.85f));
  1301. g.fillRect (juce::Rectangle<float> (x + 2.0f, juce::jmin (y, base), w - 4.0f, juce::jmax (2.0f, std::abs (base - y))));
  1302. g.setColour (textPrimary);
  1303. g.fillRect (x + 1.0f, y - 1.0f, w - 2.0f, 2.0f);
  1304. }
  1305. if (bipolar)
  1306. {
  1307. g.setColour (gridBar);
  1308. g.drawHorizontalLine ((int) base, (float) gridLeft(), (float) getWidth());
  1309. }
  1310. }
  1311. float ChannelRackComponent::laneValueAt (int y) const
  1312. {
  1313. const auto lane = laneBounds();
  1314. const auto top = (float) lane.getY() + 6.0f, bottom = (float) lane.getBottom() - 6.0f;
  1315. return juce::jlimit (0.0f, 1.0f, (bottom - (float) y) / juce::jmax (1.0f, bottom - top));
  1316. }
  1317. void ChannelRackComponent::setLaneValue (int step, float value)
  1318. {
  1319. const auto channel = graphRow();
  1320. const auto level = (notetools::Level) graphLevel;
  1321. engine.editSong ([channel, step, value, level] (Song& s) {
  1322. auto& p = s.patterns[(std::size_t) s.currentPattern];
  1323. for (auto i : notesInStep (p, channel, step))
  1324. notetools::setLevelValue (p.notes[(std::size_t) i], level, value);
  1325. });
  1326. }
  1327. void ChannelRackComponent::applyLane (const juce::MouseEvent& e)
  1328. {
  1329. const auto steps = numSteps();
  1330. const auto step = juce::jlimit (0, steps - 1, (e.x - gridLeft()) / stepWidth);
  1331. const auto value = laneValueAt (e.y);
  1332. if (e.mods.isRightButtonDown()) // a straight ramp from the press to here
  1333. {
  1334. const auto from = juce::jmin (laneDownStep, step), to = juce::jmax (laneDownStep, step);
  1335. const auto channel = graphRow();
  1336. const auto level = (notetools::Level) graphLevel;
  1337. const auto v0 = laneDownStep <= step ? laneDownValue : value, v1 = laneDownStep <= step ? value : laneDownValue;
  1338. engine.editSong ([=] (Song& s) {
  1339. auto& p = s.patterns[(std::size_t) s.currentPattern];
  1340. for (int st = from; st <= to; ++st)
  1341. {
  1342. const auto t = to > from ? (float) (st - from) / (float) (to - from) : 0.0f;
  1343. for (auto i : notesInStep (p, channel, st))
  1344. notetools::setLevelValue (p.notes[(std::size_t) i], level, v0 + (v1 - v0) * t);
  1345. }
  1346. });
  1347. return;
  1348. }
  1349. setLaneValue (step, value);
  1350. }
  1351. void ChannelRackComponent::setPianoRollView (bool on)
  1352. {
  1353. if (pianoRollView == on)
  1354. return;
  1355. pianoRollView = on;
  1356. repaint();
  1357. if (onFilterChanged) // the title's switches follow
  1358. onFilterChanged();
  1359. }
  1360. void ChannelRackComponent::toggleGraphLanes()
  1361. {
  1362. graphLanes = ! graphLanes;
  1363. updateSize();
  1364. repaint();
  1365. if (onFilterChanged) // the title's graph switch follows
  1366. onFilterChanged();
  1367. }
  1368. // --- fills, rotation and organisation ------------------------------------------------------------
  1369. void ChannelRackComponent::rotateSelected (int steps)
  1370. {
  1371. const auto rows = engine.getSelectedChannels();
  1372. engine.editSong ([rows, steps] (Song& s) {
  1373. auto& p = s.patterns[(std::size_t) s.currentPattern];
  1374. const auto length = patternSteps (s, p);
  1375. for (auto r : rows)
  1376. rotateSteps (p, r, steps, length);
  1377. });
  1378. }
  1379. void ChannelRackComponent::copySelected()
  1380. {
  1381. const auto& song = engine.getSong();
  1382. stepClipboard = copyChannelSteps (song.patterns[(std::size_t) song.currentPattern], engine.getSelectedChannels(), (int) song.channels.size());
  1383. }
  1384. void ChannelRackComponent::cutSelected()
  1385. {
  1386. copySelected();
  1387. const auto rows = engine.getSelectedChannels();
  1388. const auto& song = engine.getSong();
  1389. auto copy = song.patterns[(std::size_t) song.currentPattern];
  1390. if (clearChannelSteps (copy, rows)) // (nothing to cut: no undo step)
  1391. engine.editSong ([rows] (Song& s) { clearChannelSteps (s.patterns[(std::size_t) s.currentPattern], rows); });
  1392. }
  1393. void ChannelRackComponent::pasteSelected()
  1394. {
  1395. if (stepClipboard.empty() || engine.getSelectedChannels().empty())
  1396. return;
  1397. engine.editSong ([rows = engine.getSelectedChannels(), clip = stepClipboard] (Song& s) {
  1398. pasteChannelSteps (s.patterns[(std::size_t) s.currentPattern], clip, rows, (int) s.channels.size());
  1399. });
  1400. }
  1401. void ChannelRackComponent::fillSelected (int every)
  1402. {
  1403. const auto rows = engine.getSelectedChannels();
  1404. engine.editSong ([rows, every] (Song& s) {
  1405. auto& p = s.patterns[(std::size_t) s.currentPattern];
  1406. const auto length = patternSteps (s, p);
  1407. for (auto r : rows)
  1408. if (r < (int) s.channels.size() && s.channels[(std::size_t) r].instrument != InstrumentKind::audioClip)
  1409. fillEverySteps (p, r, every, length);
  1410. });
  1411. }
  1412. void ChannelRackComponent::sortChannels (ChannelSort by)
  1413. {
  1414. engine.editSong ([by] (Song& s) { permuteChannels (s, channelSortOrder (s, by)); });
  1415. openEditorRow = -1;
  1416. selectRows ({ 0 }, 0);
  1417. }
  1418. void ChannelRackComponent::selectUnused()
  1419. {
  1420. const auto unused = unusedChannels (engine.getSong());
  1421. if (unused.empty())
  1422. {
  1423. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Select unused channels"),
  1424. tr ("Every channel is used by a pattern or a Playlist clip."));
  1425. return;
  1426. }
  1427. selectRows (unused, unused.front());
  1428. }
  1429. int ChannelRackComponent::addChannel (ChannelDef c, bool openEditor, int insert)
  1430. {
  1431. int index = 0;
  1432. if (filterGroup >= 0 && c.group < 0) // a new channel joins the group shown (FL)
  1433. c.group = filterGroup;
  1434. engine.editSong ([&] (Song& s) { index = addChannelRouted (s, c, insert); });
  1435. selectionAnchor = index;
  1436. selectRows ({ index }, index);
  1437. if (openEditor && c.instrument == InstrumentKind::plugin)
  1438. {
  1439. openPluginWindow (index);
  1440. openEditorRow = index;
  1441. }
  1442. else if (openEditor && natives::instrumentEngine (c.instrument) != nullptr) // an FL engine: its editor (round 142)
  1443. openChannelSettings (engine, index);
  1444. return index;
  1445. }
  1446. bool ChannelRackComponent::loadSampleIntoSelected (const juce::File& file)
  1447. {
  1448. const auto row = engine.getSelectedChannel();
  1449. const auto& song = engine.getSong();
  1450. if (row < 0 || row >= (int) song.channels.size() || ! SampleLibrary::isSampleFile (file))
  1451. return false;
  1452. const auto kind = song.channels[(std::size_t) row].instrument;
  1453. // only channels that play a sample (or the built-in drums, which become samplers) take a file
  1454. if (kind != InstrumentKind::sampler && kind != InstrumentKind::kick && kind != InstrumentKind::snare && kind != InstrumentKind::hat
  1455. && kind != InstrumentKind::clap && kind != InstrumentKind::granulizer && kind != InstrumentKind::wavetraveller)
  1456. return false;
  1457. assignSample (row, file);
  1458. return true;
  1459. }
  1460. namespace
  1461. {
  1462. // Euclidean fill: pulses spread evenly over a length, rotated; previewed live on the pattern.
  1463. class EuclideanPanel final : public juce::Component
  1464. {
  1465. public:
  1466. EuclideanPanel (AudioEngine& e, int c) : engine (e), channel (c)
  1467. {
  1468. const auto& song = engine.getSong();
  1469. patternIndex = song.currentPattern;
  1470. originals = song.patterns[(std::size_t) patternIndex].notes;
  1471. steps = patternSteps (song, song.patterns[(std::size_t) patternIndex]);
  1472. auto setup = [this] (juce::Slider& s, juce::Label& l, const juce::String& name, double lo, double hi, double v) {
  1473. l.setText (name, juce::dontSendNotification);
  1474. addAndMakeVisible (l);
  1475. s.setSliderStyle (juce::Slider::LinearHorizontal);
  1476. s.setTextBoxStyle (juce::Slider::TextBoxRight, false, 50, 20);
  1477. s.setRange (lo, hi, 1.0);
  1478. s.setValue (v, juce::dontSendNotification);
  1479. s.onValueChange = [this] { preview(); };
  1480. addAndMakeVisible (s);
  1481. };
  1482. setup (pulses, pulsesLabel, tr ("Pulses"), 0, 32, 5);
  1483. setup (length, lengthLabel, tr ("Length (steps)"), 1, 32, 16);
  1484. setup (rotation, rotationLabel, tr ("Rotation"), -16, 16, 0);
  1485. title.setText (tr ("Euclidean fill: {0}", { juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str()) }), juce::dontSendNotification);
  1486. title.setFont (theme::font (theme::type::title, true));
  1487. addAndMakeVisible (title);
  1488. for (auto* b : { &accept, &cancel })
  1489. addAndMakeVisible (b);
  1490. accept.setColour (juce::TextButton::buttonColourId, theme::colour::accent);
  1491. accept.onClick = [this] {
  1492. restore();
  1493. const auto rhythm = current();
  1494. engine.editSong ([this, rhythm] (Song& s) { setStepRhythm (s.patterns[(std::size_t) patternIndex], channel, rhythm, steps); });
  1495. done = true;
  1496. closeToolWindowOf (*this);
  1497. };
  1498. cancel.onClick = [this] { closeToolWindowOf (*this); };
  1499. setSize (380, 330);
  1500. preview();
  1501. }
  1502. ~EuclideanPanel() override
  1503. {
  1504. if (! done)
  1505. restore();
  1506. }
  1507. void paint (juce::Graphics& g) override
  1508. {
  1509. g.fillAll (theme::colour::bg2);
  1510. // the rhythm as a ring of steps, the first step at the top
  1511. const auto rhythm = current();
  1512. const auto ring = juce::Rectangle<float> (0, 150, (float) getWidth(), 120).withSizeKeepingCentre (110, 110);
  1513. const auto n = (int) rhythm.size();
  1514. for (int i = 0; i < n; ++i)
  1515. {
  1516. const auto angle = juce::MathConstants<float>::twoPi * (float) i / (float) n;
  1517. const auto centre = ring.getCentre() + juce::Point<float> (std::sin (angle), -std::cos (angle)) * 50.0f;
  1518. const auto dot = juce::Rectangle<float> (12, 12).withCentre (centre);
  1519. g.setColour (rhythm[(std::size_t) i] ? theme::colour::stepOn : theme::colour::stepOff);
  1520. g.fillEllipse (dot);
  1521. if (i == 0)
  1522. {
  1523. g.setColour (theme::colour::textPrimary);
  1524. g.drawEllipse (dot.expanded (2.0f), 1.0f);
  1525. }
  1526. }
  1527. }
  1528. void resized() override
  1529. {
  1530. auto area = getLocalBounds().reduced (12, 10);
  1531. title.setBounds (area.removeFromTop (24));
  1532. area.removeFromTop (6);
  1533. for (auto [s, l] : { std::pair { &pulses, &pulsesLabel }, std::pair { &length, &lengthLabel }, std::pair { &rotation, &rotationLabel } })
  1534. {
  1535. auto row = area.removeFromTop (30);
  1536. l->setBounds (row.removeFromLeft (120));
  1537. s->setBounds (row);
  1538. }
  1539. auto buttons = area.removeFromBottom (28);
  1540. accept.setBounds (buttons.removeFromRight (100));
  1541. buttons.removeFromRight (8);
  1542. cancel.setBounds (buttons.removeFromRight (90));
  1543. }
  1544. private:
  1545. std::vector<bool> current() const
  1546. {
  1547. return euclideanRhythm ((int) pulses.getValue(), (int) length.getValue(), (int) rotation.getValue());
  1548. }
  1549. void restore()
  1550. {
  1551. if (patternIndex < (int) engine.getSong().patterns.size())
  1552. engine.editSong ([this] (Song& s) { s.patterns[(std::size_t) patternIndex].notes = originals; }, false);
  1553. }
  1554. void preview()
  1555. {
  1556. const auto rhythm = current();
  1557. if (patternIndex < (int) engine.getSong().patterns.size())
  1558. engine.editSong ([this, rhythm] (Song& s) {
  1559. auto& p = s.patterns[(std::size_t) patternIndex];
  1560. p.notes = originals;
  1561. setStepRhythm (p, channel, rhythm, steps);
  1562. }, false);
  1563. repaint();
  1564. }
  1565. AudioEngine& engine;
  1566. int channel, patternIndex = 0, steps = 16;
  1567. std::vector<Note> originals;
  1568. bool done = false;
  1569. juce::Label title, pulsesLabel, lengthLabel, rotationLabel;
  1570. juce::Slider pulses, length, rotation;
  1571. juce::TextButton accept { tr ("Accept") }, cancel { tr ("Cancel") };
  1572. };
  1573. } // namespace
  1574. std::unique_ptr<juce::Component> ChannelRackComponent::makeEuclideanPanel (int channel)
  1575. {
  1576. return std::make_unique<EuclideanPanel> (engine, juce::jlimit (0, juce::jmax (0, (int) engine.getSong().channels.size() - 1), channel));
  1577. }
  1578. void ChannelRackComponent::showEuclideanFill (int channel)
  1579. {
  1580. if (channel >= 0 && channel < (int) engine.getSong().channels.size())
  1581. openToolWindow (makeEuclideanPanel (channel), tr ("Euclidean fill"), "euclidean");
  1582. }
  1583. // --- mouse -------------------------------------------------------------------------------------
  1584. void ChannelRackComponent::mouseDown (const juce::MouseEvent& e)
  1585. {
  1586. int row = 0;
  1587. const auto area = areaAt (e.x, e.y, row);
  1588. const auto& song = engine.getSong();
  1589. switch (area)
  1590. {
  1591. case Area::none:
  1592. return;
  1593. case Area::addRow:
  1594. showAddChannelMenu();
  1595. return;
  1596. case Area::loop: // the advanced looping control: drag sets the loop point in steps, right-click its menu
  1597. {
  1598. if (flmods::popup (e.mods))
  1599. {
  1600. showLoopPointMenu (row);
  1601. return;
  1602. }
  1603. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  1604. const auto setting = channelloops::effectiveSetting (p, row);
  1605. const auto steps = loopStepsOf (row);
  1606. loopDragRow = row;
  1607. loopDragStart = setting > 0 ? setting : steps > 0 ? steps : numSteps();
  1608. loopDragY = e.position.y;
  1609. repaint();
  1610. return;
  1611. }
  1612. case Area::laneLevels:
  1613. for (int l = 0; l < notetools::levelCount; ++l)
  1614. if (levelButtonBounds (l).contains (e.getPosition().translated (-stickyX, 0)))
  1615. {
  1616. graphLevel = l;
  1617. repaint();
  1618. }
  1619. return;
  1620. case Area::lane:
  1621. {
  1622. const auto step = juce::jlimit (0, numSteps() - 1, (e.x - gridLeft()) / stepWidth);
  1623. if (e.mods.isAltDown() || e.mods.isMiddleButtonDown())
  1624. {
  1625. setLaneValue (step, notetools::levelDefault ((notetools::Level) graphLevel));
  1626. return;
  1627. }
  1628. laneDownStep = step;
  1629. laneDownValue = laneValueAt (e.y);
  1630. applyLane (e);
  1631. return;
  1632. }
  1633. case Area::mute:
  1634. if (flmods::popup (e.mods) || flmods::ctrl (e.mods))
  1635. solo (row);
  1636. else
  1637. toggleMute (row);
  1638. return;
  1639. case Area::pan:
  1640. case Area::volume:
  1641. case Area::route:
  1642. {
  1643. const auto spec = specFor (area, row);
  1644. if (flmods::popup (e.mods))
  1645. {
  1646. juce::PopupMenu menu;
  1647. menu.addSectionHeader (spec.name + ": " + spec.text (valueOf (area, row)));
  1648. ui::addValueItems (menu, *this, &engine, spec, valueOf (area, row), [this, area, row] (double v) { setValue (area, row, v); });
  1649. if (area == Area::route)
  1650. {
  1651. menu.addSeparator();
  1652. menu.addItem (tr ("Next free insert"), [this, row] {
  1653. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].mixerTrack = s.claimFreeInsert(); });
  1654. });
  1655. menu.addItem (tr ("Send the selected channels to free inserts") + "\tCtrl+L", [this] { sendSelectedToInserts(); });
  1656. if (onOpenMixerInsert)
  1657. menu.addItem (tr ("Show this insert in the Mixer"), [this, row] {
  1658. if (row < (int) engine.getSong().channels.size())
  1659. onOpenMixerInsert (engine.getSong().channels[(std::size_t) row].mixerTrack);
  1660. });
  1661. }
  1662. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1663. return;
  1664. }
  1665. if (ui::isResetClick (e))
  1666. {
  1667. setValue (area, row, spec.defaultValue);
  1668. showTip (area, row, true);
  1669. return;
  1670. }
  1671. knobDrag = area;
  1672. knobRow = row;
  1673. drag.begin (e, valueOf (area, row));
  1674. showTip (area, row, false);
  1675. repaint();
  1676. return;
  1677. }
  1678. case Area::name:
  1679. if (flmods::popup (e.mods))
  1680. {
  1681. if (! std::binary_search (engine.getSelectedChannels().begin(), engine.getSelectedChannels().end(), row))
  1682. clickSelector (row, {});
  1683. else
  1684. selectRows (engine.getSelectedChannels(), row);
  1685. showChannelMenu (row);
  1686. return;
  1687. }
  1688. if (e.mods.isShiftDown())
  1689. {
  1690. clickSelector (row, e.mods);
  1691. return;
  1692. }
  1693. if (! std::binary_search (engine.getSelectedChannels().begin(), engine.getSelectedChannels().end(), row)
  1694. || engine.getSelectedChannels().size() > 1)
  1695. {
  1696. selectionAnchor = row;
  1697. selectRows ({ row }, row);
  1698. }
  1699. if (flmods::ctrl (e.mods)) // audition without opening anything
  1700. {
  1701. previews.press (row, 60, 0.8f); // stops on release
  1702. return;
  1703. }
  1704. // the editor opens on release, unless the button is dragged (that reorders the channels)
  1705. nameDownRow = row;
  1706. nameDragged = false;
  1707. nameDownAlt = e.mods.isAltDown();
  1708. nameDragY = e.position.y;
  1709. return;
  1710. case Area::select:
  1711. clickSelector (row, e.mods);
  1712. if (flmods::popup (e.mods)) // right-drag adds the rows it crosses
  1713. {
  1714. selectDownRow = row;
  1715. selectDragAdds = true;
  1716. selectDragBase = engine.getSelectedChannels();
  1717. }
  1718. else if (! e.mods.isShiftDown() && ! flmods::ctrl (e.mods)) // left-drag selects a range
  1719. {
  1720. selectDownRow = row;
  1721. selectDragAdds = false;
  1722. }
  1723. return;
  1724. case Area::grid:
  1725. {
  1726. auto step = (e.x - gridLeft()) / stepWidth;
  1727. if (const auto loop = loopStepsOf (row); loop > 0 && step >= loop && step < numSteps())
  1728. step %= loop; // a loop repeat edits the step it repeats
  1729. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  1730. if (showsNotePreview (pattern, row, pianoRollView)) // the miniature opens the Piano Roll (steps would break the melody)
  1731. {
  1732. if (! flmods::popup (e.mods))
  1733. {
  1734. selectionAnchor = row;
  1735. selectRows ({ row }, row);
  1736. if (onOpenPianoRoll)
  1737. onOpenPianoRoll();
  1738. }
  1739. return;
  1740. }
  1741. if (e.mods.isRightButtonDown())
  1742. paintMode = PaintMode::remove;
  1743. else
  1744. paintMode = pattern.hasStep (row, step) ? PaintMode::remove : PaintMode::add;
  1745. lastPaintedRow = lastPaintedStep = -1;
  1746. applyPaint (e);
  1747. return;
  1748. }
  1749. }
  1750. }
  1751. void ChannelRackComponent::mouseDrag (const juce::MouseEvent& e)
  1752. {
  1753. if (loopDragRow >= 0)
  1754. {
  1755. const auto steps = juce::jlimit (1, numSteps(), loopDragStart + juce::roundToInt ((loopDragY - e.position.y) / 6.0f));
  1756. const auto& p = engine.getSong().patterns[(std::size_t) engine.getSong().currentPattern];
  1757. if (channelloops::storedSetting (p, loopDragRow) != steps)
  1758. setLoopPoint (loopDragRow, steps);
  1759. return;
  1760. }
  1761. if (knobDrag != Area::none && drag.isActive())
  1762. {
  1763. setValue (knobDrag, knobRow, drag.update (e, specFor (knobDrag, knobRow)));
  1764. showTip (knobDrag, knobRow, false);
  1765. return;
  1766. }
  1767. if (laneDownStep >= 0)
  1768. {
  1769. applyLane (e);
  1770. hoverStep = juce::jlimit (0, numSteps() - 1, (e.x - gridLeft()) / stepWidth);
  1771. hoverArea = Area::lane;
  1772. const auto v = laneValueAt (e.y);
  1773. const auto bipolar = notetools::levelIsBipolar ((notetools::Level) graphLevel);
  1774. const auto shown = juce::roundToInt ((bipolar ? v * 2.0f - 1.0f : v) * 100.0f);
  1775. const auto valueText = (bipolar && shown > 0 ? "+" : "") + juce::String (shown) + "%";
  1776. const auto levelText = tr (notetools::levelName ((notetools::Level) graphLevel));
  1777. ui::showValueTip (*this, controlBounds (Area::lane, graphRow()), levelText + ": " + valueText);
  1778. ui::Hint live;
  1779. live.text = channelName (engine.getSong(), graphRow()) + " - " + levelText;
  1780. live.value = valueText;
  1781. ui::postHint (live);
  1782. repaint (laneBounds());
  1783. return;
  1784. }
  1785. if (nameDownRow >= 0)
  1786. {
  1787. if (! nameDragged && std::abs (e.position.y - nameDragY) < 4.0f)
  1788. return;
  1789. nameDragged = true;
  1790. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  1791. const auto count = (int) engine.getSong().channels.size();
  1792. const auto target = juce::jlimit (0, count - 1, rowAtY (e.y));
  1793. // move the selection one row at a time until the grabbed channel is under the mouse
  1794. for (int guard = 0; guard < count && engine.getSelectedChannel() != target; ++guard)
  1795. if (! moveSelected (target < engine.getSelectedChannel() ? -1 : 1))
  1796. break;
  1797. return;
  1798. }
  1799. if (selectDownRow >= 0)
  1800. {
  1801. const auto count = (int) engine.getSong().channels.size();
  1802. const auto row = juce::jlimit (0, juce::jmax (0, count - 1), rowAtY (e.y));
  1803. std::vector<int> rows;
  1804. for (int r = juce::jmin (selectDownRow, row); r <= juce::jmax (selectDownRow, row); ++r)
  1805. rows.push_back (r);
  1806. if (selectDragAdds)
  1807. {
  1808. rows.insert (rows.end(), selectDragBase.begin(), selectDragBase.end());
  1809. std::sort (rows.begin(), rows.end());
  1810. rows.erase (std::unique (rows.begin(), rows.end()), rows.end());
  1811. }
  1812. else
  1813. selectionAnchor = selectDownRow;
  1814. if (rows != engine.getSelectedChannels())
  1815. selectRows (rows, row);
  1816. return;
  1817. }
  1818. if (paintMode != PaintMode::none)
  1819. applyPaint (e);
  1820. }
  1821. void ChannelRackComponent::mouseUp (const juce::MouseEvent& e)
  1822. {
  1823. previews.releaseAll(); // the audition (Ctrl+click) and the steps' previews stop with the button
  1824. if (nameDownRow >= 0 && ! nameDragged && e.mouseWasClicked())
  1825. toggleEditor (nameDownRow, nameDownAlt);
  1826. if (nameDragged)
  1827. setMouseCursor (juce::MouseCursor::NormalCursor);
  1828. nameDownRow = -1;
  1829. nameDragged = false;
  1830. if (loopDragRow >= 0)
  1831. {
  1832. loopDragRow = -1;
  1833. repaint();
  1834. }
  1835. selectDownRow = -1;
  1836. selectDragBase.clear();
  1837. ui::hideValueTip();
  1838. ui::clearPostedHint();
  1839. paintMode = PaintMode::none;
  1840. laneDownStep = -1;
  1841. if (knobDrag != Area::none)
  1842. repaint();
  1843. knobDrag = Area::none;
  1844. drag.end();
  1845. }
  1846. void ChannelRackComponent::mouseDoubleClick (const juce::MouseEvent& e)
  1847. {
  1848. int row = 0;
  1849. const auto area = areaAt (e.x, e.y, row);
  1850. if (area == Area::pan || area == Area::volume)
  1851. {
  1852. setValue (area, row, specFor (area, row).defaultValue);
  1853. showTip (area, row, true);
  1854. }
  1855. else if (area == Area::route)
  1856. {
  1857. if (onOpenMixerInsert)
  1858. onOpenMixerInsert (engine.getSong().channels[(std::size_t) row].mixerTrack);
  1859. else
  1860. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].mixerTrack = s.claimFreeInsert(); });
  1861. }
  1862. else if (area == Area::loop && ! flmods::popup (e.mods))
  1863. setLoopPoint (row, ChannelLoop::nextBar);
  1864. else if (area == Area::select && ! flmods::popup (e.mods))
  1865. selectAll();
  1866. // a double-click on a channel's name is two clicks, as in FL: its window opens and closes again (FL 2026, checked
  1867. // round 165q F7). It no longer opens the Piano Roll — the hint promised that, but FL's channel button does not.
  1868. }
  1869. void ChannelRackComponent::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  1870. {
  1871. int row = 0;
  1872. const auto area = areaAt (e.x, e.y, row);
  1873. if (area == Area::pan || area == Area::volume || area == Area::route)
  1874. {
  1875. if (const auto v = ui::wheelValue (valueOf (area, row), e, wheel, specFor (area, row)))
  1876. {
  1877. setValue (area, row, *v);
  1878. showTip (area, row, true);
  1879. }
  1880. return;
  1881. }
  1882. if (area == Area::loop) // the loop point, a step at a time
  1883. {
  1884. const auto& song = engine.getSong();
  1885. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  1886. const auto setting = channelloops::effectiveSetting (p, row);
  1887. const auto steps = setting > 0 ? setting : loopStepsOf (row) > 0 ? loopStepsOf (row) : numSteps();
  1888. const auto delta = (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? 1 : -1;
  1889. setLoopPoint (row, juce::jlimit (1, numSteps(), steps + delta));
  1890. return;
  1891. }
  1892. if ((area == Area::name || area == Area::select) && e.mods.isShiftDown()) // Shift+wheel moves the channel
  1893. {
  1894. const auto delta = (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? -1 : 1;
  1895. selectRows ({ row }, row);
  1896. moveSelected (delta);
  1897. return;
  1898. }
  1899. juce::Component::mouseWheelMove (e, wheel); // scroll the viewport
  1900. }
  1901. ui::Hint ChannelRackComponent::hintAt (juce::Point<int> p)
  1902. {
  1903. int row = 0;
  1904. const auto area = areaAt (p.x, p.y, row);
  1905. const auto& song = engine.getSong();
  1906. ui::Hint h;
  1907. if (row >= 0 && row < (int) song.channels.size() && (area == Area::pan || area == Area::volume || area == Area::route))
  1908. {
  1909. const auto active = knobDrag != Area::none && drag.isActive();
  1910. const auto shownArea = active ? knobDrag : area;
  1911. const auto shownRow = active ? knobRow : row;
  1912. h = ui::valueHint (specFor (shownArea, shownRow), valueOf (shownArea, shownRow),
  1913. shownArea == Area::route ? tr ("[LMB] drag or [Wheel] routes [2xLMB] show in the Mixer [RMB] next free insert")
  1914. : ui::valueGestures());
  1915. return h;
  1916. }
  1917. const auto name = channelName (song, row);
  1918. switch (area)
  1919. {
  1920. case Area::mute:
  1921. h.text = name + " - " + tr ("Click: mute. Ctrl+click or right-click: solo");
  1922. break;
  1923. case Area::name:
  1924. h.text = name + " - " + tr ("[LMB] open/close the editor [Alt]+[LMB] keep others open [Ctrl]+[LMB] audition [LMB] drag up/down reorders [RMB] channel menu");
  1925. // sample channels: where the pitch is (round 163, "getting to the sample pitching")
  1926. if (row >= 0 && row < (int) song.channels.size()
  1927. && (song.channels[(std::size_t) row].instrument == InstrumentKind::sampler || song.channels[(std::size_t) row].instrument == InstrumentKind::audioClip))
  1928. h.text << " " << tr ("(pitch: [RMB] › Pitch...)");
  1929. if (row >= 0 && row < (int) song.channels.size() && ! song.channels[(std::size_t) row].receiveFrom.empty())
  1930. h.text << " " << tr ("(locked: receives the notes of {0})", { juce::String::fromUTF8 (song.channels[(std::size_t) row].receiveFrom.c_str()) });
  1931. if (engine.playsStandIn (row))
  1932. h.text = name + " - " + tr ("Stand-in: its plugin is not installed on this PC, a render of this part plays (the plugin's settings are kept)");
  1933. h.hasMenu = true;
  1934. // FL's hint bar names what the channel is ("Audio Clip", the plugin's name) on the right (REA round 143b)
  1935. if (row >= 0 && row < (int) song.channels.size())
  1936. {
  1937. const auto& c = song.channels[(std::size_t) row];
  1938. h.value = c.instrument == InstrumentKind::plugin && ! c.plugin.name.empty() ? juce::String::fromUTF8 (c.plugin.name.c_str())
  1939. : instrumentLabel (c.instrument);
  1940. }
  1941. break;
  1942. case Area::select:
  1943. 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");
  1944. break;
  1945. case Area::grid:
  1946. if (! song.patterns.empty() && showsNotePreview (song.patterns[(std::size_t) song.currentPattern], row, pianoRollView))
  1947. h.text = name + " - " + tr ("Piano Roll notes: [LMB] opens them in the Piano Roll");
  1948. else
  1949. h.text = name + " - " + (hoverStep >= numSteps() ? tr ("After the pattern's end: [LMB] adds a step and makes the pattern longer")
  1950. : loopStepsOf (row) > 0 && hoverStep >= loopStepsOf (row)
  1951. ? tr ("Loop repeat (after the loop point): [LMB] edits the step it repeats")
  1952. : tr ("Steps: [LMB] drag draws (starting on a lit step erases) [RMB] drag erases"));
  1953. // and the step's position as bar:step:tick, like FL's hint bar
  1954. if (hoverStep >= 0)
  1955. h.value = juce::String (stepPositionText ((std::int64_t) hoverStep * ticksPerStep, song.beatsPerBar));
  1956. break;
  1957. case Area::addRow:
  1958. h.text = tr ("Add a channel (or drop audio files on the rack)");
  1959. break;
  1960. case Area::loop:
  1961. h.text = name + " - " + tr ("Loop point: [LMB] drag or [Wheel] sets it in steps [2xLMB] next bar [RMB] Don't loop / Step / Beat / Bar, Burn to pattern");
  1962. h.hasMenu = true;
  1963. if (row >= 0 && row < (int) song.channels.size() && ! song.patterns.empty())
  1964. {
  1965. const auto setting = channelloops::effectiveSetting (song.patterns[(std::size_t) song.currentPattern], row);
  1966. h.value = setting == ChannelLoop::dontLoop ? tr ("Don't loop") : setting > 0 ? tr ("Every {0} steps", { juce::String (setting) })
  1967. : tr (channelloops::settingText (setting).c_str());
  1968. }
  1969. break;
  1970. case Area::laneLevels:
  1971. h.text = tr ("Graph lane: choose what the bars edit (Ctrl+K hides the lane)");
  1972. break;
  1973. case Area::lane:
  1974. h.text = name + " - " + tr ("Graph lane: drag sets the steps, right-drag draws a ramp, Alt+click resets");
  1975. break;
  1976. default:
  1977. break;
  1978. }
  1979. return h;
  1980. }
  1981. void ChannelRackComponent::applyPaint (const juce::MouseEvent& e)
  1982. {
  1983. const auto& song = engine.getSong();
  1984. const auto row = rowAtY (e.y);
  1985. auto step = (e.x - gridLeft()) / stepWidth;
  1986. if (const auto loop = loopStepsOf (row); loop > 0 && step >= loop && step < numSteps())
  1987. step %= loop; // a loop repeat edits the step it repeats
  1988. if (laneBounds().contains (e.getPosition()) || (advancedLoopShown() && e.x >= loopBoxBounds (0).getX() - 3))
  1989. return;
  1990. if (row < 0 || row >= (int) song.channels.size() || step < 0 || step >= shownSteps() || e.x < stickyX + gridLeft()
  1991. || song.channels[(std::size_t) row].instrument == InstrumentKind::audioClip
  1992. || showsNotePreview (song.patterns[(std::size_t) song.currentPattern], row, pianoRollView)) // drag-paint skips note rows
  1993. return;
  1994. if (row == lastPaintedRow && step == lastPaintedStep)
  1995. return;
  1996. lastPaintedRow = row;
  1997. lastPaintedStep = step;
  1998. const auto on = paintMode == PaintMode::add;
  1999. // FL: setting a step is silent, stopped or playing (issue #11; Ctrl+click on the channel button auditions it)
  2000. engine.editSong ([row, step, on, mute = muteRemovedSteps] (Song& s) {
  2001. auto& p = s.patterns[(std::size_t) s.currentPattern];
  2002. setStep (p, row, step, on, mute);
  2003. // a ghost step of a pattern with a set length: the length grows to the bar holding it (automatic lengths
  2004. // follow the notes by themselves)
  2005. if (on)
  2006. p.lengthTicks = lengthWithStep (p.lengthTicks, step, ticksPerStep, (std::int64_t) ppq * std::max (1, s.beatsPerBar));
  2007. });
  2008. }
  2009. // --- menus -------------------------------------------------------------------------------------
  2010. juce::PopupMenu ChannelRackComponent::buildChannelMenu (int channel)
  2011. {
  2012. const auto& c = engine.getSong().channels[(std::size_t) channel];
  2013. // Replace › lists exactly what Insert › and "+" list (issue #18: one source, quickpick::addGeneratorMenu); the
  2014. // channel keeps its place, notes, insert, levels and colour (FL; core replaceGenerator)
  2015. juce::PopupMenu instruments;
  2016. quickpick::addGeneratorMenu (instruments, engine, [this, channel] (ChannelDef generator) {
  2017. if (channel >= (int) engine.getSong().channels.size())
  2018. return;
  2019. closeEditor (channel);
  2020. const auto kind = generator.instrument;
  2021. engine.editSong ([channel, &generator] (Song& s) { replaceGenerator (s, channel, std::move (generator)); });
  2022. selectionAnchor = channel;
  2023. selectRows ({ channel }, channel);
  2024. openNewGenerator (channel, kind);
  2025. }, [this, channel] { chooseSample (channel); }, &c, this);
  2026. // FL's layout (REA round 104): two columns, the channel on the left (editors, name and colour, sample,
  2027. // insert / replace / clone / delete) and its steps on the right (clipboard, fills, rotation); LYNX's own
  2028. // items (settings windows, arpeggiator, organisation) follow in their place
  2029. juce::PopupMenu menu;
  2030. ui::addItemHeader (menu, tr ("Channel"), juce::String::fromUTF8 (c.name.c_str()), c.colour != 0 ? juce::Colour (c.colour) : juce::Colour());
  2031. const auto selected = (int) engine.getSelectedChannels().size();
  2032. const auto count = (int) engine.getSong().channels.size();
  2033. menu.addItem (tr ("Piano Roll") + "\tF7", [this] {
  2034. if (onOpenPianoRoll)
  2035. onOpenPianoRoll();
  2036. });
  2037. menu.addItem (tr ("Graph editor") + "\tCtrl+K", true, graphLanes, [this] { toggleGraphLanes(); });
  2038. menu.addSeparator();
  2039. menu.addItem (theme::mnemonic (tr ("Rename and color..."), 'R') + "\tF2", [this, channel] { rename (channel); });
  2040. menu.addSubMenu (tr ("Change color"), ui::colourMenu (c.colour, [this, channel] (std::uint32_t colour) {
  2041. if (channel < (int) engine.getSong().channels.size())
  2042. engine.editSong ([channel, colour] (Song& s) { s.channels[(std::size_t) channel].colour = colour; });
  2043. }, juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1)));
  2044. menu.addItem (tr ("Random color"), [this, channel] {
  2045. const auto& palette = lynxPalette();
  2046. const auto colour = palette[(std::size_t) juce::Random::getSystemRandom().nextInt ((int) palette.size())];
  2047. engine.editSong ([channel, colour] (Song& s) { s.channels[(std::size_t) channel].colour = colour; });
  2048. });
  2049. // FL's "Change icon" (SetPlugIconMenuClick, REA round 168h); LYNX's own icon set
  2050. menu.addItem (tr ("Change icon..."), [this, channel] {
  2051. if (channel >= (int) engine.getSong().channels.size())
  2052. return;
  2053. ui::showTrackIconPicker (juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1), engine.getSong().channels[(std::size_t) channel].icon, [this, channel] (int icon) {
  2054. if (channel < (int) engine.getSong().channels.size())
  2055. engine.editSong ([channel, icon] (Song& s) { s.channels[(std::size_t) channel].icon = icon; });
  2056. });
  2057. });
  2058. // FL's "Lock active/mute state" (the mute switch's menu, round 167l): soloing another channel leaves this one alone
  2059. menu.addItem (tr ("Lock active/mute state"), true, c.soloLock, [this, channel] {
  2060. if (channel < (int) engine.getSong().channels.size())
  2061. engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].soloLock = ! s.channels[(std::size_t) channel].soloLock; });
  2062. });
  2063. menu.addSeparator();
  2064. menu.addItem (theme::mnemonic (tr ("Load sample..."), 'L'), c.instrument != InstrumentKind::audioClip, false, [this, channel] { chooseSample (channel); });
  2065. {
  2066. // "Cut itself": a new note cuts the channel's own sounding note (its cut group and "cut by" are its own)
  2067. const auto self = 1000 + channel;
  2068. const auto cutsItself = c.cutGroup != 0 && c.cutGroup == c.cutBy;
  2069. menu.addItem (theme::mnemonic (tr ("Cut itself"), 't'), true, cutsItself, [this, channel, self, cutsItself] {
  2070. engine.editSong ([channel, self, cutsItself] (Song& s) {
  2071. auto& ch = s.channels[(std::size_t) channel];
  2072. ch.cutGroup = ch.cutBy = cutsItself ? 0 : self;
  2073. });
  2074. });
  2075. }
  2076. menu.addSeparator();
  2077. {
  2078. juce::PopupMenu insert;
  2079. addInstrumentItems (insert, channel);
  2080. menu.addSubMenu (theme::mnemonic (tr ("Insert"), 'I'), insert);
  2081. }
  2082. menu.addSubMenu (tr ("Replace"), instruments);
  2083. // FL's Patcherize (round 165m): the channel's instrument into a new Patcher, same sound
  2084. menu.addItem (tr ("Patcherize"), selected <= 1 && patcherize::canPatcherizeChannel (engine.getSong(), channel), false, [this, channel] {
  2085. engine.capturePluginStates(); // (the plugin's current settings go with it)
  2086. closeEditor (channel);
  2087. engine.editSong ([channel] (Song& s) { patcherize::patcherizeChannel (s, channel); });
  2088. });
  2089. // FL's Loop Starter channel menu (round 168b): Replace sample, Generate steps, Locked, One-shot category
  2090. loopstarterui::addChannelMenu (menu, engine, channel);
  2091. menu.addItem (selected > 1 ? theme::mnemonic (tr ("Clone {0} channels", { juce::String (selected) }), 'C') : theme::mnemonic (tr ("Clone"), 'C') + "\tAlt+C", [this] { cloneSelected(); });
  2092. if (selected > 1)
  2093. menu.addItem (theme::mnemonic (tr ("Delete {0} channels", { juce::String (selected) }), 'D') + "\tAlt+Del", selected < count, false, [this] { deleteSelected(); });
  2094. else
  2095. menu.addItem (theme::mnemonic (tr ("Delete..."), 'D') + "\tAlt+Del", count > 1, false, [this, channel] {
  2096. closeEditor (channel);
  2097. engine.editSong ([channel] (Song& s) { s.removeChannel (channel); });
  2098. openEditorRow = -1;
  2099. });
  2100. // LYNX: the channel's settings windows and its arpeggiator
  2101. menu.addSeparator();
  2102. if (c.instrument == InstrumentKind::sampler)
  2103. {
  2104. menu.addItem (tr ("Sampler settings (pitch, envelope, reverse)..."),
  2105. [this, channel] { openChannelSettings (engine, channel); });
  2106. menu.addItem (tr ("Pitch... (semitones, cents, keep length)"), ! c.samplePath.empty() || ! c.zones.empty(), false,
  2107. [this, channel] { showSamplePitchDialog (engine, channel); });
  2108. menu.addItem (tr ("Edit the sample in the audio editor..."), ! c.samplePath.empty(), false, [this, channel] { openAudioEditorForChannel (engine, channel); });
  2109. if (c.sampler.slices.empty())
  2110. menu.addItem (tr ("Slice sample (slicer): one slice per key and a pattern with the loop"), [this, channel] { sliceChannel (channel); });
  2111. else
  2112. menu.addItem (tr ("Undo slices ({0})", { juce::String ((int) c.sampler.slices.size()) }), [this, channel] {
  2113. engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].sampler.slices.clear(); });
  2114. });
  2115. }
  2116. else if (c.instrument == InstrumentKind::audioClip)
  2117. menu.addItem (tr ("Pitch... (semitones, cents, keep length)"), ! c.samplePath.empty(), false,
  2118. [this, channel] { showSamplePitchDialog (engine, channel); });
  2119. else if (c.instrument == InstrumentKind::synth)
  2120. menu.addItem (tr ("Synth settings (oscillators, envelope, filter)..."), [this, channel] { openChannelSettings (engine, channel); });
  2121. else if (hasChannelSettings (c.instrument))
  2122. menu.addItem (tr ("Channel settings..."), [this, channel] { openChannelSettings (engine, channel); });
  2123. // FL's wrench tab of the channel window, for every channel (REA round 143b)
  2124. menu.addItem (tr ("Miscellaneous functions (polyphony, cut groups, arpeggiator)..."), [this, channel] { openChannelMisc (engine, channel); });
  2125. if (c.instrument == InstrumentKind::patcher) // its published parameters (round 171b)
  2126. addPatcherParameterItems (menu, engine, c.patcher, { AutomationTargetKind::channelParam, channel, 0, 0 });
  2127. if (c.instrument == InstrumentKind::plugin)
  2128. {
  2129. menu.addItem (tr ("Open plugin editor"), [this, channel] { openPluginWindow (channel); });
  2130. auto* live = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get());
  2131. menu.addSubMenu (tr ("Processing"), pluginProcessingMenu (engine, c.plugin, live != nullptr ? &live->getInstance() : nullptr,
  2132. [channel] (Song& song) -> PluginRef* {
  2133. if (channel >= (int) song.channels.size())
  2134. return nullptr;
  2135. return &song.channels[(std::size_t) channel].plugin;
  2136. }));
  2137. if (live != nullptr)
  2138. addPluginParameterItems (menu, engine, live->getInstance(), { AutomationTargetKind::channelParam, channel, 0, 0 });
  2139. }
  2140. {
  2141. // channel arpeggiator
  2142. const auto arp = c.arp;
  2143. auto set = [this, channel] (std::function<void (ArpSettings&)> change) {
  2144. engine.editSong ([channel, change] (Song& s) { change (s.channels[(std::size_t) channel].arp); });
  2145. };
  2146. juce::PopupMenu arpMenu;
  2147. const char* directions[] = { TR_NOOP ("Off"), TR_NOOP ("Up"), TR_NOOP ("Down"), TR_NOOP ("Up and down"), TR_NOOP ("Random") };
  2148. for (int d = 0; d < 5; ++d)
  2149. arpMenu.addItem (tr (directions[d]), true, arp.direction == d, [set, d] { set ([d] (ArpSettings& a) { a.direction = d; }); });
  2150. arpMenu.addSeparator();
  2151. juce::PopupMenu range, speed, gate, repeat;
  2152. for (int o = 1; o <= 4; ++o)
  2153. 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; }); });
  2154. const std::pair<const char*, float> speeds[] = { { "1/4", 1.0f }, { "1/8", 0.5f }, { TR_NOOP ("1/8 triplet"), 1.0f / 3.0f },
  2155. { "1/16", 0.25f }, { TR_NOOP ("1/16 triplet"), 1.0f / 6.0f }, { "1/32", 0.125f } };
  2156. for (const auto& [name, beats] : speeds)
  2157. speed.addItem (tr (name), true, std::abs (arp.stepBeats - beats) < 1e-4f, [set, b = beats] { set ([b] (ArpSettings& a) { a.stepBeats = b; }); });
  2158. for (int g : { 25, 50, 75, 100 })
  2159. 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; }); });
  2160. for (int n : { 1, 2, 3, 4 })
  2161. repeat.addItem (juce::String (n) + "x", true, arp.repeat == n, [set, n] { set ([n] (ArpSettings& a) { a.repeat = n; }); });
  2162. arpMenu.addSubMenu (tr ("Range"), range);
  2163. arpMenu.addSubMenu (tr ("Speed"), speed);
  2164. arpMenu.addSubMenu (tr ("Gate"), gate);
  2165. arpMenu.addSubMenu (tr ("Repeat"), repeat);
  2166. menu.addSubMenu (arp.enabled() ? tr ("Arpeggiator (on)") : tr ("Arpeggiator"), arpMenu);
  2167. }
  2168. // --- second column: the channel's steps in the current pattern ---
  2169. menu.addColumnBreak();
  2170. // FL's Cut / Copy / Paste (REA round 170a §1): the selected channels' steps and notes, as Ctrl+X / C / V
  2171. {
  2172. const auto& song = engine.getSong();
  2173. const auto& selection = engine.getSelectedChannels();
  2174. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  2175. const auto hasNotes = std::any_of (notes.begin(), notes.end(), [&selection] (const Note& n) {
  2176. return std::binary_search (selection.begin(), selection.end(), n.channel);
  2177. });
  2178. menu.addItem (theme::mnemonic (tr ("Cut"), 't') + "\tCtrl+X", hasNotes, false, [this] { cutSelected(); });
  2179. menu.addItem (theme::mnemonic (tr ("Copy"), 'o') + "\tCtrl+C", hasNotes, false, [this] { copySelected(); });
  2180. menu.addItem (theme::mnemonic (tr ("Paste"), 'p') + "\tCtrl+V", ! stepClipboard.empty(), false, [this] { pasteSelected(); });
  2181. }
  2182. menu.addSeparator();
  2183. menu.addItem (theme::mnemonic (tr ("Fill each 2 steps"), '2'), [this] { fillSelected (2); });
  2184. menu.addItem (theme::mnemonic (tr ("Fill each 4 steps"), '4'), [this] { fillSelected (4); });
  2185. menu.addItem (theme::mnemonic (tr ("Fill each 8 steps"), '8'), [this] { fillSelected (8); });
  2186. menu.addItem (theme::mnemonic (tr ("Advanced fill..."), 'f'), [this, channel] { showEuclideanFill (channel); });
  2187. menu.addSeparator();
  2188. menu.addItem (tr ("Rotate left") + "\tShift+Ctrl+Left", [this] { rotateSelected (-1); });
  2189. menu.addItem (tr ("Rotate right") + "\tShift+Ctrl+Right", [this] { rotateSelected (1); });
  2190. menu.addSeparator();
  2191. {
  2192. // FL's "Receive notes from" (round 165f-rack): a MIDI input device (any or one MIDI channel) plays only this channel
  2193. juce::PopupMenu receive;
  2194. receive.addItem (theme::mnemonic (tr ("Unlock"), 'u'), ! c.receiveFrom.empty(), false, [this, channel] {
  2195. engine.editSong ([channel] (Song& s) {
  2196. s.channels[(std::size_t) channel].receiveFrom.clear();
  2197. s.channels[(std::size_t) channel].receiveMidiChannel = 0;
  2198. });
  2199. });
  2200. receive.addSeparator();
  2201. auto lockTo = [this, channel] (std::string device, int midiChannel) {
  2202. engine.editSong ([channel, device, midiChannel] (Song& s) {
  2203. // one device + MIDI channel plays one channel: another channel that had it lets go
  2204. for (auto& other : s.channels)
  2205. if (other.receiveFrom == device && other.receiveMidiChannel == midiChannel)
  2206. other.receiveFrom.clear();
  2207. s.channels[(std::size_t) channel].receiveFrom = device;
  2208. s.channels[(std::size_t) channel].receiveMidiChannel = midiChannel;
  2209. });
  2210. };
  2211. const auto devices = juce::MidiInput::getAvailableDevices();
  2212. for (const auto& d : devices)
  2213. {
  2214. const auto name = d.name.toStdString();
  2215. juce::PopupMenu channels;
  2216. channels.addItem (tr ("Any MIDI channel"), true, c.receiveFrom == name && c.receiveMidiChannel == 0, [lockTo, name] { lockTo (name, 0); });
  2217. for (int m = 1; m <= 16; ++m)
  2218. channels.addItem (tr ("MIDI channel {0}", { juce::String (m) }), true, c.receiveFrom == name && c.receiveMidiChannel == m,
  2219. [lockTo, name, m] { lockTo (name, m); });
  2220. receive.addSubMenu (d.name, channels, true, nullptr, c.receiveFrom == name);
  2221. }
  2222. // a device of the project that is not connected now stays listed
  2223. if (! c.receiveFrom.empty() && std::none_of (devices.begin(), devices.end(), [&c] (const juce::MidiDeviceInfo& d) { return d.name.toStdString() == c.receiveFrom; }))
  2224. receive.addItem (juce::String::fromUTF8 (c.receiveFrom.c_str()) + " (" + tr ("not connected") + ")", false, true, [] {});
  2225. if (devices.isEmpty() && c.receiveFrom.empty())
  2226. receive.addItem (tr ("No MIDI input device"), false, false, [] {});
  2227. menu.addSubMenu (theme::mnemonic (c.receiveFrom.empty() ? tr ("Receive notes from") : tr ("Receive notes from") + " (" + tr ("locked") + ")", 'n'), receive);
  2228. }
  2229. {
  2230. // FL's "Burn MIDI to" (round 165f-rack): what the channel plays (loops, swing, time, arpeggiator, echo) as notes
  2231. juce::PopupMenu burn;
  2232. burn.addItem (theme::mnemonic (tr ("Current pattern"), 'c'), [this, channel] { burnMidi (channel, false); });
  2233. burn.addItem (theme::mnemonic (tr ("New pattern"), 'n'), [this, channel] { burnMidi (channel, true); });
  2234. menu.addSubMenu (tr ("Burn MIDI to"), burn);
  2235. // its loop point in this pattern (FL's advanced looping control menu)
  2236. const auto& song = engine.getSong();
  2237. const auto& p = song.patterns[(std::size_t) song.currentPattern];
  2238. const auto setting = channelloops::effectiveSetting (p, channel);
  2239. juce::PopupMenu loop;
  2240. loop.addItem (tr ("Don't loop"), true, setting == ChannelLoop::dontLoop && p.loopOn, [this, channel] { setLoopPoint (channel, ChannelLoop::dontLoop); });
  2241. loop.addItem (tr ("Step"), true, p.loopOn && setting == ChannelLoop::nextStep, [this, channel] { setLoopPoint (channel, ChannelLoop::nextStep); });
  2242. loop.addItem (tr ("Beat"), true, p.loopOn && setting == ChannelLoop::nextBeat, [this, channel] { setLoopPoint (channel, ChannelLoop::nextBeat); });
  2243. loop.addItem (tr ("Bar"), true, p.loopOn && setting == ChannelLoop::nextBar, [this, channel] { setLoopPoint (channel, ChannelLoop::nextBar); });
  2244. loop.addSeparator();
  2245. loop.addItem (tr ("Set to next beat"), [this, channel] { setLoopPoint (channel, 1000 + ChannelLoop::nextBeat); });
  2246. loop.addItem (tr ("Set to next bar"), [this, channel] { setLoopPoint (channel, 1000 + ChannelLoop::nextBar); });
  2247. loop.addSeparator();
  2248. loop.addItem (tr ("Burn to pattern"), loopStepsOf (channel) > 0, false, [this, channel] {
  2249. engine.editSong ([channel] (Song& s) { channelloops::burnChannel (s.patterns[(std::size_t) s.currentPattern], channel, s.beatsPerBar); });
  2250. repaint();
  2251. });
  2252. menu.addSubMenu (setting > 0 && p.loopOn ? tr ("Loop point ({0} steps)", { juce::String (setting) }) : tr ("Loop point"), loop);
  2253. }
  2254. // FL's "Create DirectWave instrument..." (round 165f-rack): the instrument sampled key by key into a Sampler channel
  2255. menu.addItem (tr ("Create sampled instrument..."), c.instrument != InstrumentKind::audioClip && c.instrument != InstrumentKind::controller,
  2256. false, [this, channel] { showAutoSamplerDialog (engine, channel); });
  2257. menu.addSeparator();
  2258. menu.addItem (tr ("Swing mix ({0})...", { juce::String (juce::roundToInt (c.swingMix * 100.0f)) + "%" }),
  2259. [this, channel] { setSwingMixOfSelected (channel); });
  2260. menu.addItem (tr ("Clear notes in this pattern"), [this, channel] {
  2261. engine.editSong ([channel] (Song& s) {
  2262. auto& notes = s.patterns[(std::size_t) s.currentPattern].notes;
  2263. notes.erase (std::remove_if (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }),
  2264. notes.end());
  2265. });
  2266. });
  2267. // organisation (acts on the selection; FL keeps these in the rack's options menu)
  2268. menu.addSeparator();
  2269. menu.addItem (tr ("Move up") + "\tAlt+Up", engine.getSelectedChannels().front() > 0, false, [this] { moveSelected (-1); });
  2270. menu.addItem (tr ("Move down") + "\tAlt+Down", engine.getSelectedChannels().back() < count - 1, false, [this] { moveSelected (1); });
  2271. menu.addItem (tr ("Send to free mixer inserts") + "\tCtrl+L", [this] { sendSelectedToInserts(); });
  2272. {
  2273. juce::PopupMenu sort;
  2274. sort.addItem (tr ("By name"), [this] { sortChannels (ChannelSort::name); });
  2275. sort.addItem (tr ("By color"), [this] { sortChannels (ChannelSort::colour); });
  2276. sort.addItem (tr ("By mixer insert"), [this] { sortChannels (ChannelSort::insert); });
  2277. sort.addItem (tr ("By type"), [this] { sortChannels (ChannelSort::type); });
  2278. menu.addSubMenu (tr ("Sort channels"), sort);
  2279. }
  2280. menu.addItem (tr ("Select unused channels"), [this] { selectUnused(); });
  2281. menu.addItem (theme::mnemonic (tr ("Group selected..."), 'G') + "\tAlt+G", [this] { groupSelected(); });
  2282. return menu;
  2283. }
  2284. void ChannelRackComponent::showChannelMenu (int channel)
  2285. {
  2286. buildChannelMenu (channel).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  2287. }
  2288. juce::String flEngineName (const natives::InstrumentEngine& e)
  2289. {
  2290. const auto name = juce::String::fromUTF8 (e.name);
  2291. if (! natives::available (e, flStudioAccess()))
  2292. return tr ("{0} (requires FL Studio)", { name });
  2293. return e.beta ? tr ("{0} (beta)", { name }) : name;
  2294. }
  2295. void ChannelRackComponent::openNewGenerator (int row, InstrumentKind kind)
  2296. {
  2297. switch (kind)
  2298. {
  2299. case InstrumentKind::kick: case InstrumentKind::snare: case InstrumentKind::hat: case InstrumentKind::clap:
  2300. case InstrumentKind::synth: case InstrumentKind::sampler: case InstrumentKind::audioClip:
  2301. return; // (LYNX's drums and synth: no window, as before)
  2302. case InstrumentKind::plugin:
  2303. openPluginWindow (row); // the plugin opens when added
  2304. openEditorRow = row;
  2305. return;
  2306. case InstrumentKind::patcher:
  2307. PatcherWindows::openChannel (engine, row);
  2308. return;
  2309. default:
  2310. openChannelSettings (engine, row);
  2311. return;
  2312. }
  2313. }
  2314. void ChannelRackComponent::addInstrumentItems (juce::PopupMenu& menu, int insertAt)
  2315. {
  2316. // a new channel at the end (insertAt < 0) or at a row; the list is the one Replace › shows (issue #18)
  2317. quickpick::addGeneratorMenu (menu, engine, [this, insertAt] (ChannelDef c) {
  2318. int index = 0;
  2319. if (filterGroup >= 0 && c.group < 0)
  2320. c.group = filterGroup;
  2321. const auto kind = c.instrument;
  2322. engine.editSong ([&] (Song& s) {
  2323. c.mixerTrack = s.claimFreeInsert();
  2324. index = insertAt < 0 ? (s.channels.push_back (c), (int) s.channels.size() - 1) : insertChannel (s, insertAt, c);
  2325. });
  2326. selectionAnchor = index;
  2327. selectRows ({ index }, index);
  2328. openNewGenerator (index, kind);
  2329. }, [this, insertAt] { chooseSample (-1, insertAt); }, nullptr, this);
  2330. }
  2331. void ChannelRackComponent::showAddChannelMenu (int insertAt)
  2332. {
  2333. juce::PopupMenu menu;
  2334. // FL's renamed plugins first (issue #11): "1_Synth" renamed in the Browser's Plugin database is added by typing 1
  2335. std::vector<quickpick::Pick> picks;
  2336. if (insertAt < 0)
  2337. picks = quickpick::renamedGenerators (engine, [safe = juce::Component::SafePointer<ChannelRackComponent> (this)] (ChannelDef c) {
  2338. if (safe != nullptr)
  2339. safe->addChannel (std::move (c), true);
  2340. });
  2341. quickpick::addPicks (menu, picks);
  2342. // the generators under FL's Plugin database categories and the user's folders (rounds 166f, 170b: addGeneratorMenu)
  2343. addInstrumentItems (menu, insertAt);
  2344. quickpick::addFolderViewItems (menu, engine); // FL: Categories / Simple / Tree at the bottom
  2345. quickpick::showMenu (menu, juce::PopupMenu::Options().withTargetComponent (this).withMousePosition(), std::move (picks));
  2346. }
  2347. void ChannelRackComponent::chooseSample (int channel, int insertAt)
  2348. {
  2349. fileChooser = std::make_unique<juce::FileChooser> (tr ("Choose sample"), juce::File(), engine.getSampleLibrary().wildcard());
  2350. fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  2351. [this, channel, insertAt] (const juce::FileChooser& chooser) {
  2352. if (! chooser.getResult().existsAsFile())
  2353. return;
  2354. if (channel >= 0 || insertAt < 0)
  2355. {
  2356. assignSample (channel, chooser.getResult());
  2357. return;
  2358. }
  2359. // Insert › Sampler (choose file)...: a new sampler channel at the row
  2360. if (engine.getSampleLibrary().load (chooser.getResult().getFullPathName()) == nullptr)
  2361. return assignSample (channel, chooser.getResult()); // (its "could not read" message)
  2362. ChannelDef c;
  2363. c.instrument = InstrumentKind::sampler;
  2364. c.samplePath = chooser.getResult().getFullPathName().toStdString();
  2365. c.name = chooser.getResult().getFileNameWithoutExtension().toStdString();
  2366. if (filterGroup >= 0)
  2367. c.group = filterGroup;
  2368. int index = 0;
  2369. engine.editSong ([&] (Song& s) {
  2370. c.mixerTrack = s.claimFreeInsert();
  2371. index = insertChannel (s, std::min (insertAt, (int) s.channels.size()), c);
  2372. });
  2373. selectionAnchor = index;
  2374. selectRows ({ index }, index);
  2375. });
  2376. }
  2377. void ChannelRackComponent::assignSample (int channel, const juce::File& file)
  2378. {
  2379. // FL's .speech files open the Speech properties first, like FL's channel load does (round 168b); the file it
  2380. // returns (the edited copy, or this one) goes into the channel
  2381. if (file.hasFileExtension ("speech"))
  2382. {
  2383. speechui::editThenLoad (engine, file, [safe = juce::Component::SafePointer<ChannelRackComponent> (this), channel] (const juce::File& f) {
  2384. if (safe != nullptr)
  2385. safe->assignSampleNow (channel, f);
  2386. });
  2387. return;
  2388. }
  2389. assignSampleNow (channel, file);
  2390. }
  2391. void ChannelRackComponent::assignSampleNow (int channel, const juce::File& file)
  2392. {
  2393. if (engine.getSampleLibrary().load (file.getFullPathName()) == nullptr)
  2394. {
  2395. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Sample"),
  2396. tr ("Could not read {0}", { file.getFileName() }));
  2397. return;
  2398. }
  2399. const auto path = file.getFullPathName().toStdString();
  2400. const auto name = file.getFileNameWithoutExtension().toStdString();
  2401. engine.editSong ([channel, path, name] (Song& s) {
  2402. const auto isNew = channel < 0 || channel >= (int) s.channels.size();
  2403. const auto freeInsert = s.claimFreeInsert();
  2404. auto& c = isNew ? s.channels.emplace_back() : s.channels[(std::size_t) channel];
  2405. if (isNew)
  2406. c.mixerTrack = freeInsert;
  2407. c.samplePath = path;
  2408. if (! isNew && (c.instrument == InstrumentKind::granulizer || c.instrument == InstrumentKind::wavetraveller)) // FL's Granulizer keeps its engine and plays the file (round 142); so does Wave Traveller
  2409. return;
  2410. c.instrument = InstrumentKind::sampler;
  2411. c.name = name;
  2412. });
  2413. if (channel < 0)
  2414. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  2415. }
  2416. void ChannelRackComponent::openPluginWindow (int channel)
  2417. {
  2418. auto instrument = engine.getChannelInstrument (channel);
  2419. if (auto* plugin = dynamic_cast<PluginInstrument*> (instrument.get()))
  2420. {
  2421. if (plugin->hasCrashed()) // (not called again: its window would call into it)
  2422. {
  2423. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Plugin"),
  2424. tr ("This plugin crashed and was switched off. Save the project and open it again to reload it."));
  2425. return;
  2426. }
  2427. PluginWindows::open (instrument, plugin->getInstance(),
  2428. juce::String::fromUTF8 (engine.getSong().channels[(std::size_t) channel].name.c_str()),
  2429. { &engine, [channel] (Song& song) -> PluginRef* {
  2430. return channel < (int) song.channels.size() ? &song.channels[(std::size_t) channel].plugin : nullptr;
  2431. }, true });
  2432. return;
  2433. }
  2434. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Plugin"),
  2435. tr ("This plugin could not be loaded (it is not installed or has not been scanned)."));
  2436. }
  2437. void ChannelRackComponent::rename (int channel)
  2438. {
  2439. const auto& c = engine.getSong().channels[(std::size_t) channel];
  2440. showNameAndColourDialog (tr ("Rename channel"), juce::String::fromUTF8 (c.name.c_str()), c.colour,
  2441. [this, channel] (const juce::String& name, std::uint32_t colour) {
  2442. if (channel < (int) engine.getSong().channels.size())
  2443. engine.editSong ([channel, n = name.toStdString(), colour] (Song& s) {
  2444. s.channels[(std::size_t) channel].name = n;
  2445. s.channels[(std::size_t) channel].colour = colour;
  2446. });
  2447. });
  2448. }
  2449. void ChannelRackComponent::sliceChannel (int channel)
  2450. {
  2451. const auto& song = engine.getSong();
  2452. const auto& c = song.channels[(std::size_t) channel];
  2453. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str()));
  2454. if (sample == nullptr || sample->frames() == 0)
  2455. return;
  2456. // a spoken .speech sample is cut at its words (FL hands its words to the slicer as a Zero-X grid; round 168b)
  2457. std::vector<float> slices;
  2458. if (juce::File (juce::String::fromUTF8 (c.samplePath.c_str())).hasFileExtension ("speech") && ! sample->markerStarts.empty())
  2459. for (const auto start : sample->markerStarts)
  2460. slices.push_back ((float) ((double) start / (double) sample->frames()));
  2461. else
  2462. slices = detectSlices (*sample, 0.5f);
  2463. const auto seconds = (double) sample->frames() / sample->sampleRate;
  2464. const auto ticksPerSecond = song.bpm * ppq / 60.0;
  2465. const auto name = c.name + " (slices)";
  2466. engine.editSong ([&] (Song& s) {
  2467. s.channels[(std::size_t) channel].sampler.slices = slices;
  2468. // pattern that plays the slices in their original order and timing (at the project BPM)
  2469. auto& p = s.patterns.emplace_back();
  2470. p.name = name;
  2471. for (std::size_t i = 0; i < slices.size(); ++i)
  2472. {
  2473. const auto start = slices[i] * seconds;
  2474. const auto end = i + 1 < slices.size() ? slices[i + 1] * seconds : seconds;
  2475. Note n;
  2476. n.start = (std::int64_t) std::llround (start * ticksPerSecond);
  2477. n.length = std::max<std::int64_t> (1, (std::int64_t) std::llround ((end - start) * ticksPerSecond));
  2478. n.key = 60 + (int) i;
  2479. n.channel = channel;
  2480. p.notes.push_back (n);
  2481. }
  2482. p.sortNotes();
  2483. s.currentPattern = (int) s.patterns.size() - 1;
  2484. });
  2485. }
  2486. bool ChannelRackComponent::isInterestedInFileDrag (const juce::StringArray& files)
  2487. {
  2488. for (const auto& f : files)
  2489. if (SampleLibrary::isSampleFile (juce::File (f)) || juce::File (f).hasFileExtension ("sf2;sf3;sfz"))
  2490. return true;
  2491. return false;
  2492. }
  2493. void ChannelRackComponent::filesDropped (const juce::StringArray& files, int x, int y)
  2494. {
  2495. int row = 0;
  2496. const auto area = areaAt (x, y, row);
  2497. auto target = (area == Area::none || area == Area::addRow) ? -1 : row;
  2498. for (const auto& f : files)
  2499. {
  2500. const juce::File file (f);
  2501. if (file.hasFileExtension ("sf2;sf3;sfz"))
  2502. {
  2503. // a SoundFont: into the LYNX Soundfont channel it was dropped on, else a new channel
  2504. openSoundFontFile (engine, file, target);
  2505. target = -1;
  2506. continue;
  2507. }
  2508. if (! SampleLibrary::isSampleFile (file)) // (FL's WavPack pack samples too: round 165q)
  2509. continue;
  2510. assignSample (target, file);
  2511. target = -1; // the remaining files become new channels
  2512. }
  2513. }
  2514. void ChannelRackComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  2515. {
  2516. updateSize();
  2517. repaint();
  2518. }
  2519. void ChannelRackComponent::timerCallback()
  2520. {
  2521. // the channels' volume / pan knobs follow their automation (issue #12): only the automated knobs repaint
  2522. if (const auto& shown = engine.getAutomationDisplay(); shown.getGeneration() != shownAutomation)
  2523. {
  2524. shownAutomation = shown.getGeneration();
  2525. std::vector<int> rows;
  2526. for (const auto& t : shown.automatedTargets())
  2527. if (t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan)
  2528. rows.push_back (t.index);
  2529. if (isShowing())
  2530. for (const auto list : { &rows, &automatedRows })
  2531. for (const auto r : *list)
  2532. if (r >= 0 && r < (int) engine.getSong().channels.size())
  2533. repaint (controlBounds (Area::pan, r).getUnion (controlBounds (Area::volume, r)).expanded (2));
  2534. automatedRows = std::move (rows);
  2535. }
  2536. auto& transport = engine.getTransport();
  2537. auto step = -1;
  2538. // the playhead shows whenever the shown pattern plays: Pattern mode, or a clip of it in Song mode (Busy Works
  2539. // Beats' video, round 170a: in Song mode the rack showed none), as the Piano Roll's (transportedit::patternPlayhead)
  2540. if (transport.playing.load() && isShowing())
  2541. {
  2542. const auto& song = engine.getSong();
  2543. const auto tick = transportedit::patternPlayhead (song, song.currentPattern, transport.positionTicks.load());
  2544. if (tick >= 0.0)
  2545. step = (int) (tick / ticksPerStep);
  2546. }
  2547. if (step != playheadStep)
  2548. {
  2549. auto dirty = [this] (int s) {
  2550. if (s >= 0)
  2551. repaint (gridLeft() + s * stepWidth - 1, 0, stepWidth + 1, getHeight());
  2552. };
  2553. dirty (playheadStep);
  2554. playheadStep = step;
  2555. dirty (playheadStep);
  2556. repaint (stickyX + selectLeft(), 0, selectWidth, getHeight()); // the selectors flash with the hits
  2557. followPlayhead();
  2558. }
  2559. }
  2560. void ChannelRackComponent::followPlayhead()
  2561. {
  2562. // Follow (issue #12): a pattern longer than the view pages along with the playing step, as the Playlist does
  2563. if (playheadStep < 0 || ! EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack))
  2564. return;
  2565. auto* viewport = findParentComponentOfClass<juce::Viewport>();
  2566. if (viewport == nullptr)
  2567. return;
  2568. const auto view = viewport->getViewArea();
  2569. const auto stepsLeft = view.getX() + gridLeft(); // (the controls column stays on the left of the view)
  2570. const auto x = gridLeft() + playheadStep * stepWidth;
  2571. if (x >= stepsLeft && x + stepWidth <= view.getRight())
  2572. return;
  2573. const auto maxX = juce::jmax (0, getWidth() - view.getWidth());
  2574. viewport->setViewPosition (juce::jlimit (0, maxX, x - gridLeft()), view.getY());
  2575. }
  2576. bool ChannelRackComponent::isInterestedInDragSource (const SourceDetails& details)
  2577. {
  2578. std::string path;
  2579. int bank = 0, program = 0;
  2580. return BrowserComponent::isBrowserDrag (details) || BrowserComponent::isGeneratorDrag (details)
  2581. || parseSoundFontDrag (details.description.toString(), path, bank, program);
  2582. }
  2583. void ChannelRackComponent::itemDropped (const SourceDetails& details)
  2584. {
  2585. // a generator dragged from the Browser's Plugin database (round 162): below the channels a new channel with it, onto a
  2586. // channel it replaces that channel's instrument (FL, audit round 165z-a: insert, notes and levels stay); window open
  2587. if (BrowserComponent::isGeneratorDrag (details))
  2588. {
  2589. if (auto c = BrowserComponent::draggedGenerator (details))
  2590. {
  2591. int row = 0;
  2592. const auto area = areaAt (details.localPosition.x, details.localPosition.y, row);
  2593. if (area != Area::none && area != Area::addRow && row >= 0 && row < (int) engine.getSong().channels.size())
  2594. {
  2595. closeEditor (row);
  2596. const auto kind = c->instrument;
  2597. engine.editSong ([row, &c] (Song& s) { replaceGenerator (s, row, std::move (*c)); });
  2598. selectionAnchor = row;
  2599. selectRows ({ row }, row);
  2600. if (kind == InstrumentKind::plugin)
  2601. {
  2602. openPluginWindow (row);
  2603. openEditorRow = row;
  2604. }
  2605. else if (natives::instrumentEngine (kind) != nullptr)
  2606. openChannelSettings (engine, row);
  2607. }
  2608. else
  2609. addChannel (std::move (*c), true);
  2610. }
  2611. return;
  2612. }
  2613. // a preset dragged from a LYNX Soundfont list: onto a LYNX Soundfont channel it loads there, else a new channel
  2614. std::string path;
  2615. int bank = 0, program = 0;
  2616. if (parseSoundFontDrag (details.description.toString(), path, bank, program))
  2617. {
  2618. int row = 0;
  2619. const auto area = areaAt (details.localPosition.x, details.localPosition.y, row);
  2620. const auto& song = engine.getSong();
  2621. if (area != Area::none && area != Area::addRow && row >= 0 && row < (int) song.channels.size()
  2622. && song.channels[(std::size_t) row].instrument == InstrumentKind::soundfont)
  2623. loadSoundFontInto (engine, row, path, bank, program);
  2624. else
  2625. addSoundFontChannel (engine, path, bank, program);
  2626. return;
  2627. }
  2628. if (const auto file = BrowserComponent::draggedFile (details); file.existsAsFile())
  2629. filesDropped ({ file.getFullPathName() }, details.localPosition.x, details.localPosition.y);
  2630. }
  2631. } // namespace lynx