ChannelRackComponent.cpp 123 KB

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