ChannelRackComponent.cpp 203 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296
  1. #include "core/SelectionRename.h"
  2. #include "core/FlSettings.h"
  3. #include <unordered_map>
  4. #include "ui/Motion.h"
  5. #include "core/RackLayout.h"
  6. #include "core/RackFilter.h"
  7. #include "ui/FlMods.h"
  8. #include "ui/EditorTools.h"
  9. #include "core/FruityDance.h"
  10. #include "core/VideoPlayer.h"
  11. #include "ui/ColourPicker.h"
  12. #include "ui/FileChoosers.h"
  13. #include "ui/TrackIcons.h"
  14. #include "core/TrackIcons.h"
  15. #include "ui/PatcherEditor.h"
  16. #include "ui/UiTrace.h"
  17. #include "ui/TextCache.h"
  18. #include "ui/ChannelRackComponent.h"
  19. #include "core/NoteRepeat.h"
  20. #include "ui/PaintAB.h"
  21. #include "ui/ImageCaches.h"
  22. #include "ui/PluginOffTag.h"
  23. #include "ui/SpeechDialog.h"
  24. #include "core/Patcherize.h"
  25. #include "ui/QuickPick.h"
  26. #include "core/ControlSurface.h"
  27. #include "core/VoltageController.h"
  28. #include "core/MixerOps.h"
  29. #include "core/PlaylistOps.h"
  30. #include "ui/AutomationUi.h"
  31. #include "core/NoteNames.h"
  32. #include "core/NoteTools.h"
  33. #include "core/NoteEdit.h"
  34. #include "core/FlSynths.h"
  35. #include "core/MidiControls.h"
  36. #include "ui/ToolWindow.h"
  37. #include "ui/DialogFrame.h"
  38. #include "ui/LoopStarterWindow.h"
  39. #include "core/Rack.h"
  40. #include "core/Slicer.h"
  41. #include "ui/ChannelSettings.h"
  42. #include "engine/Text.h"
  43. #include "engine/ProjectFile.h"
  44. #include "platform/Paths.h"
  45. #include "ui/Dialogs.h"
  46. #include "ui/HintBar.h"
  47. #include "ui/ExportDialog.h"
  48. #include "core/StandIns.h"
  49. #include "ui/I18n.h"
  50. #include "ui/SamplerImportUi.h"
  51. #include "ui/LiveRemoteUi.h"
  52. #include "ui/BrowserComponent.h"
  53. #include "ui/PluginWindow.h"
  54. #include "ui/Theme.h"
  55. #include "ui/AudioEditor.h"
  56. #include "ui/AutoSamplerDialog.h"
  57. #include "core/RackOps.h"
  58. #include "core/TransportEdit.h"
  59. #include "core/ChannelBurn.h"
  60. #include "core/ChannelLoops.h"
  61. #include "core/SoundFont.h"
  62. #include "core/Vfx.h"
  63. #include "ui/SoundFontEditor.h"
  64. namespace lynx
  65. {
  66. namespace
  67. {
  68. void sliceChannelToDrumRack (AudioEngine& engine, int channel); // (round 190ec, below)
  69. // English name (used for new channel names stored in the song)
  70. juce::String instrumentName (InstrumentKind k)
  71. {
  72. switch (k)
  73. {
  74. case InstrumentKind::kick: return "Kick";
  75. case InstrumentKind::snare: return "Snare";
  76. case InstrumentKind::hat: return "Hat";
  77. case InstrumentKind::clap: return "Clap";
  78. case InstrumentKind::synth: return "Synth";
  79. case InstrumentKind::sampler: return "Sampler";
  80. case InstrumentKind::audioClip: return "Audio clip";
  81. case InstrumentKind::plugin: return "Plugin";
  82. case InstrumentKind::controller: return "Controller";
  83. case InstrumentKind::sakura: return "Sakura";
  84. case InstrumentKind::drumpad: return "Drumpad";
  85. case InstrumentKind::boobass: return "BooBass";
  86. case InstrumentKind::drumsynth: return "DrumSynth Live";
  87. case InstrumentKind::harmless: return "Harmless";
  88. case InstrumentKind::sytrus: return "Sytrus";
  89. case InstrumentKind::harmor: return "Harmor";
  90. case InstrumentKind::gms: return "GMS";
  91. case InstrumentKind::morphine: return "Morphine";
  92. case InstrumentKind::ogun: return "Ogun";
  93. case InstrumentKind::minisynth: return "MiniSynth";
  94. case InstrumentKind::dx10: return "Fruity DX10";
  95. case InstrumentKind::kepler: return "Kepler";
  96. case InstrumentKind::keplerExo: return "Kepler Exo";
  97. case InstrumentKind::poizone: return "PoiZone";
  98. case InstrumentKind::fruitkick: return "Fruit Kick";
  99. case InstrumentKind::bassdrum: return "BassDrum";
  100. case InstrumentKind::toxic: return "Toxic Biohazard";
  101. case InstrumentKind::threeosc: return "3x Osc";
  102. case InstrumentKind::autogun: return "Autogun";
  103. case InstrumentKind::transistorbass: return "Transistor Bass";
  104. case InstrumentKind::simsynth: return "SimSynth";
  105. case InstrumentKind::wasp: return "Wasp";
  106. case InstrumentKind::plucked: return "Plucked!";
  107. case InstrumentKind::beepmap: return "BeepMap";
  108. case InstrumentKind::sawer: return "Sawer";
  109. case InstrumentKind::flkeys: return "FL Keys";
  110. case InstrumentKind::granulizer: return "Fruity Granulizer";
  111. case InstrumentKind::drumaxx: return "Drumaxx";
  112. case InstrumentKind::slayer: return "FL Slayer";
  113. case InstrumentKind::fruitydance: return "Fruity Dance";
  114. case InstrumentKind::directwave: return "DirectWave";
  115. case InstrumentKind::midiOut: return "MIDI Out";
  116. case InstrumentKind::patcher: return "Patcher";
  117. case InstrumentKind::soundfont: return "LYNX Soundfont";
  118. case InstrumentKind::layer: return "Layer";
  119. case InstrumentKind::dashboard: return "Dashboard";
  120. case InstrumentKind::voltage: return "Voltage Controller";
  121. case InstrumentKind::vfx: return "VFX";
  122. case InstrumentKind::videoplayer: return "Fruity Video Player";
  123. case InstrumentKind::wavetraveller: return "Wave Traveller";
  124. case InstrumentKind::fruityslicer: return "Fruity Slicer";
  125. case InstrumentKind::slicex: return "Slicex";
  126. case InstrumentKind::fpc: return "FPC";
  127. case InstrumentKind::pocketSuperSaw: return "Pocket SuperSaw";
  128. case InstrumentKind::tetra: return "Tetra";
  129. case InstrumentKind::helix: return "Helix";
  130. case InstrumentKind::braid: return "Braid";
  131. case InstrumentKind::lynxModel: return "LYNX Model";
  132. }
  133. return "?";
  134. }
  135. // name shown in menus (translated)
  136. juce::String instrumentLabel (InstrumentKind k)
  137. {
  138. switch (k)
  139. {
  140. case InstrumentKind::kick: return tr ("Kick");
  141. case InstrumentKind::snare: return tr ("Snare");
  142. case InstrumentKind::hat: return tr ("Hat");
  143. case InstrumentKind::clap: return tr ("Clap");
  144. case InstrumentKind::synth: return tr ("Synth");
  145. case InstrumentKind::sampler: return tr ("Sampler");
  146. case InstrumentKind::audioClip: return tr ("Audio clip");
  147. case InstrumentKind::controller: return tr ("Envelope Controller");
  148. case InstrumentKind::midiOut: return tr ("MIDI Out");
  149. case InstrumentKind::layer: return tr ("Layer");
  150. case InstrumentKind::dashboard: return "Dashboard";
  151. case InstrumentKind::voltage: return "Voltage Controller";
  152. default: return instrumentName (k);
  153. }
  154. }
  155. void setStep (Pattern& p, int channel, int step, bool on, bool muteRemoved = false)
  156. {
  157. if (p.hasStep (channel, step) != on)
  158. p.toggleStep (channel, step, muteRemoved);
  159. }
  160. juce::String channelName (const Song& song, int row)
  161. {
  162. return row >= 0 && row < (int) song.channels.size() ? juce::String::fromUTF8 (song.channels[(std::size_t) row].name.c_str()) : juce::String();
  163. }
  164. } // namespace
  165. bool ChannelRackComponent::keepEditorsOpen = false;
  166. bool ChannelRackComponent::selectFirstChannelWithNotes = false;
  167. bool ChannelRackComponent::autoSelectLinked = true;
  168. bool ChannelRackComponent::muteRemovedSteps = false;
  169. bool ChannelRackComponent::nameAlignLeft = false;
  170. ChannelRackComponent::ChannelRackComponent (AudioEngine& e)
  171. : engine (e)
  172. {
  173. setWantsKeyboardFocus (false);
  174. setMouseClickGrabsKeyboardFocus (false);
  175. // paints every pixel (paint() starts with an opaque fillAll): the panel behind it is no longer filled under it on every
  176. // frame (round 190ms, perf: the window frame's fill under the rack was ~2.5 M instructions a whole frame on JUCE's
  177. // software renderer). Linux only: on Direct2D the frame's clip then becomes a rectangle list (a geometry layer), and
  178. // the rack's frame got 2-9 % slower (round 190ms, Windows --paintbench); macOS was not measured.
  179. #if JUCE_LINUX || JUCE_BSD
  180. setOpaque (true);
  181. #endif
  182. engine.addChangeListener (this);
  183. engine.getLevelsBroadcaster().addChangeListener (this);
  184. previews.setSender ([this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on); });
  185. updateSize();
  186. showingTimer = std::make_unique<ui::TimerWhileShowing> (*this, static_cast<juce::Timer&> (*this), 30); // (stopped while hidden; round 174f)
  187. }
  188. ChannelRackComponent::~ChannelRackComponent()
  189. {
  190. previews.releaseAll();
  191. engine.getLevelsBroadcaster().removeChangeListener (this);
  192. engine.removeChangeListener (this);
  193. }
  194. void ChannelRackComponent::moved()
  195. {
  196. // the viewport scrolled the rack sideways: the controls column follows the visible left edge
  197. const auto x = juce::jmax (0, -getX());
  198. if (x != stickyX)
  199. {
  200. stickyX = x;
  201. repaint();
  202. }
  203. }
  204. void ChannelRackComponent::visibilityChanged()
  205. {
  206. if (! isShowing())
  207. previews.releaseAll(); // hidden mid-gesture: nothing keeps sounding
  208. }
  209. int ChannelRackComponent::numSteps() const
  210. {
  211. const auto& song = engine.getSong();
  212. if (song.patterns.empty())
  213. return 16;
  214. const auto& p = song.activePattern();
  215. const auto steps = (int) (p.effectiveLength (song.meter()) / ticksPerStep);
  216. return juce::jlimit (16, 512, steps);
  217. }
  218. PreviewSpan ChannelRackComponent::previewSpan() const
  219. {
  220. auto visible = 0;
  221. if (const auto* holder = getParentComponent())
  222. visible = holder->getWidth() - gridLeft() - 8 - (advancedLoopShown() ? loopColumnWidth : 0);
  223. // (at least 8 steps wide: a rack squeezed narrower than that scrolls its miniatures too)
  224. return notePreviewSpan (numSteps() * stepWidth, juce::jmax (visible, 8 * stepWidth), stickyX, completePreview.load (std::memory_order_relaxed));
  225. }
  226. int ChannelRackComponent::shownSteps() const
  227. {
  228. return juce::jmin (512, numSteps() + ghostSteps);
  229. }
  230. bool ChannelRackComponent::isShown (int row) const
  231. {
  232. return rackfilter::shows (engine.getSong(), row, filterGroup);
  233. }
  234. int ChannelRackComponent::visibleIndex (int row) const
  235. {
  236. if (filterGroup == rackfilter::all)
  237. return row;
  238. int index = 0;
  239. for (int r = 0; r < row && r < (int) engine.getSong().channels.size(); ++r)
  240. index += isShown (r) ? 1 : 0;
  241. return index + juce::jmax (0, row - (int) engine.getSong().channels.size());
  242. }
  243. int ChannelRackComponent::shownCount() const
  244. {
  245. return visibleIndex ((int) engine.getSong().channels.size());
  246. }
  247. // round 190ld (DE-37): FL's Page Up / Page Down step the filter groups in the menu's order (All, Unsorted, Audio clips,
  248. // then the project's groups), wrapping round
  249. void ChannelRackComponent::stepFilterGroup (int direction)
  250. {
  251. const auto& song = engine.getSong();
  252. std::vector<int> order { rackfilter::all, rackfilter::unsorted, rackfilter::audioClips };
  253. for (int g = 0; g < (int) song.channelGroups.size(); ++g)
  254. if (! rackfilter::isBuiltinName (song.channelGroups[(std::size_t) g]))
  255. order.push_back (g);
  256. const auto at = std::find (order.begin(), order.end(), filterGroup);
  257. const auto i = at == order.end() ? 0 : (int) (at - order.begin());
  258. const auto n = (int) order.size();
  259. setFilterGroup (order[(std::size_t) (((i + (direction < 0 ? -1 : 1)) % n + n) % n)]);
  260. }
  261. void ChannelRackComponent::setFilterGroup (int group)
  262. {
  263. group = rackfilter::clamp (engine.getSong(), group);
  264. if (group == filterGroup)
  265. return;
  266. filterGroup = group;
  267. updateSize();
  268. repaint();
  269. if (onFilterChanged)
  270. onFilterChanged();
  271. }
  272. juce::String ChannelRackComponent::filterName() const
  273. {
  274. const auto& groups = engine.getSong().channelGroups;
  275. if (filterGroup == rackfilter::audioClips)
  276. return tr ("Audio clips");
  277. if (filterGroup == rackfilter::unsorted)
  278. return tr ("Unsorted");
  279. return filterGroup >= 0 && filterGroup < (int) groups.size() ? juce::String::fromUTF8 (groups[(std::size_t) filterGroup].c_str()) : tr ("All");
  280. }
  281. void ChannelRackComponent::showFilterMenu (juce::Component* target)
  282. {
  283. const auto& song = engine.getSong();
  284. juce::PopupMenu menu;
  285. menu.addItem (tr ("All"), true, filterGroup == rackfilter::all, [this] { setFilterGroup (rackfilter::all); });
  286. // FL's built-in views (round 168t, REA_rodada168t.md §3): the audio clip channels, and the channels in no group
  287. menu.addItem (tr ("Unsorted"), true, filterGroup == rackfilter::unsorted, [this] { setFilterGroup (rackfilter::unsorted); });
  288. menu.addItem (tr ("Audio clips"), true, filterGroup == rackfilter::audioClips, [this] { setFilterGroup (rackfilter::audioClips); });
  289. bool separated = false;
  290. for (int g = 0; g < (int) song.channelGroups.size(); ++g)
  291. {
  292. if (rackfilter::isBuiltinName (song.channelGroups[(std::size_t) g]))
  293. continue; // FL's own "Audio clips" / "Unsorted" groups: the two views above
  294. if (! std::exchange (separated, true))
  295. menu.addSeparator();
  296. menu.addItem (juce::String::fromUTF8 (song.channelGroups[(std::size_t) g].c_str()), true, filterGroup == g, [this, g] { setFilterGroup (g); });
  297. }
  298. menu.addSeparator();
  299. menu.addItem (tr ("Group selected...") + "\tAlt+G", [this] { groupSelected(); });
  300. {
  301. juce::PopupMenu move;
  302. move.addItem (tr ("(no group)"), [this] { moveSelectedToGroup (-1); });
  303. for (int g = 0; g < (int) song.channelGroups.size(); ++g)
  304. move.addItem (juce::String::fromUTF8 (song.channelGroups[(std::size_t) g].c_str()), [this, g] { moveSelectedToGroup (g); });
  305. menu.addSubMenu (tr ("Move selected channels to"), move, ! engine.getSelectedChannels().empty());
  306. }
  307. menu.addItem (tr ("Rename this group..."), filterGroup >= 0, false, [this] {
  308. const auto group = filterGroup;
  309. auto* window = new juce::AlertWindow (tr ("Filter group name"), {}, juce::MessageBoxIconType::NoIcon);
  310. window->addTextEditor ("name", filterName());
  311. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  312. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  313. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, group, window] (int result) {
  314. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  315. if (result != 1 || name.empty())
  316. return;
  317. engine.editSong ([group, name] (Song& s) {
  318. if (group < (int) s.channelGroups.size())
  319. s.channelGroups[(std::size_t) group] = name;
  320. });
  321. if (onFilterChanged)
  322. onFilterChanged();
  323. }),
  324. true);
  325. });
  326. menu.addItem (tr ("Delete this group (keeps its channels)"), filterGroup >= 0, false, [this] {
  327. const auto group = filterGroup;
  328. setFilterGroup (-1);
  329. engine.editSong ([group] (Song& s) {
  330. if (group >= (int) s.channelGroups.size())
  331. return;
  332. s.channelGroups.erase (s.channelGroups.begin() + group);
  333. for (auto& c : s.channels)
  334. c.group = c.group == group ? -1 : c.group > group ? c.group - 1 : c.group;
  335. });
  336. });
  337. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (target));
  338. }
  339. void ChannelRackComponent::moveSelectedToGroup (int group)
  340. {
  341. engine.editSong ([group, rows = engine.getSelectedChannels()] (Song& s) {
  342. for (auto r : rows)
  343. if (r >= 0 && r < (int) s.channels.size())
  344. s.channels[(std::size_t) r].group = group >= 0 && group < (int) s.channelGroups.size() ? group : -1;
  345. });
  346. updateSize();
  347. repaint();
  348. }
  349. void ChannelRackComponent::groupSelected()
  350. {
  351. // FL: Alt+G asks for the "Filter group name"; the selected channels move into the new group, which is shown
  352. auto* window = new juce::AlertWindow (tr ("Filter group name"), {}, juce::MessageBoxIconType::NoIcon);
  353. window->addTextEditor ("name", tr ("Group {0}", { juce::String ((int) engine.getSong().channelGroups.size() + 1) }));
  354. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  355. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  356. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  357. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  358. if (result != 1 || name.empty())
  359. return;
  360. const auto group = (int) engine.getSong().channelGroups.size();
  361. engine.editSong ([name, rows = engine.getSelectedChannels()] (Song& s) {
  362. s.channelGroups.push_back (name);
  363. for (auto r : rows)
  364. if (r >= 0 && r < (int) s.channels.size())
  365. s.channels[(std::size_t) r].group = (int) s.channelGroups.size() - 1;
  366. });
  367. setFilterGroup (group);
  368. }),
  369. true);
  370. }
  371. void ChannelRackComponent::updateSize()
  372. {
  373. refreshZipLayout(); // (round 190mk: zipped channels' strips)
  374. refreshAutomationRows(); // (round 190oo, PAT-7: the automation clip rows, after the strips they keep whole)
  375. const auto rows = shownCount() + 1; // +1 = "add channel" row
  376. // FL's ghost steps: when the rack is wider than the pattern, the free width shows faint steps after its end;
  377. // clicking one adds a step there and makes the pattern longer (issue #11)
  378. ghostSteps = 0;
  379. const auto loopColumn = advancedLoopShown() ? loopColumnWidth : 0; // (FL's advanced looping controls, at the right)
  380. if (const auto* holder = getParentComponent())
  381. ghostSteps = juce::jmax (0, (holder->getWidth() - gridLeft() - 8 - loopColumn) / stepWidth - numSteps());
  382. setSize (gridLeft() + shownSteps() * stepWidth + 8 + loopColumn,
  383. (zipLayout.top.empty() ? rows * rowHeight : zipLayout.total) + (int) autoRows.size() * rowHeight + 8 + (graphRow() >= 0 ? laneHeight : 0));
  384. }
  385. // --- FL's Channel button width (round 190mk, DE-39) ---------------------------------------------------------------------
  386. void ChannelRackComponent::setButtonWidth (int percent)
  387. {
  388. buttonWidthPercent = percent <= 0 ? 0 : juce::jlimit (100, 400, percent);
  389. if (buttonWidthPercent > 0)
  390. nameWidth = widthForPercent (buttonWidthPercent);
  391. else // Size to fit: the longest name with the button's margins, between 100 % and 400 %
  392. {
  393. const auto font = theme::font (theme::type::body);
  394. float widest = 0.0f;
  395. for (const auto& c : engine.getSong().channels)
  396. widest = juce::jmax (widest, juce::GlyphArrangement::getStringWidth (font, juce::String::fromUTF8 (c.name.c_str())));
  397. nameWidth = juce::jlimit (widthForPercent (100), widthForPercent (400), (int) std::ceil (widest) + 34);
  398. }
  399. updateSize();
  400. repaint();
  401. }
  402. // --- FL's zipped channels (round 190mk, DE-38; capture 190mf A4, core/RackZip.h) ----------------------------------------
  403. void ChannelRackComponent::refreshZipLayout()
  404. {
  405. const auto& channels = engine.getSong().channels;
  406. if (std::none_of (channels.begin(), channels.end(), [] (const ChannelDef& c) { return c.zipped; }))
  407. {
  408. zipLayout = {}; // (no zipped channel: FL's fixed rows, the code paths as before)
  409. return;
  410. }
  411. std::vector<bool> zipped, shown;
  412. zipped.reserve (channels.size());
  413. shown.reserve (channels.size());
  414. for (int r = 0; r < (int) channels.size(); ++r)
  415. {
  416. zipped.push_back (channels[(std::size_t) r].zipped);
  417. shown.push_back (isShown (r));
  418. }
  419. zipLayout = rackzip::layout (zipped, shown, rowHeight);
  420. }
  421. juce::Rectangle<int> ChannelRackComponent::zipBar (int row) const
  422. {
  423. if (! isZipped (row))
  424. return {};
  425. const auto slot = zipLayout.slot[(std::size_t) row];
  426. const auto top = rowY (row), height = rowHeight / 2;
  427. return { stickyX + nameLeft() + slot * (nameWidth + rackzip::barGap), top + (height - rackzip::barHeight) / 2, nameWidth, rackzip::barHeight };
  428. }
  429. int ChannelRackComponent::zipBarAt (int row, int x) const
  430. {
  431. if (! isZipped (row))
  432. return -1;
  433. return rackzip::barAt (zipLayout, zipLayout.first[(std::size_t) row], x, stickyX + nameLeft(), nameWidth);
  434. }
  435. bool ChannelRackComponent::zipStripForSnapshot (int row, juce::Rectangle<int>& strip) const
  436. {
  437. if (! isZipped (row))
  438. return false;
  439. strip = { 0, rowY (row), getWidth(), rowHeight / 2 };
  440. return true;
  441. }
  442. void ChannelRackComponent::paintZipStrips (juce::Graphics& g)
  443. {
  444. const auto& song = engine.getSong();
  445. const auto clip = g.getClipBounds();
  446. for (int row = 0; row < (int) song.channels.size(); ++row)
  447. {
  448. if (! isZipped (row) || ! isShown (row))
  449. continue;
  450. const auto bar = zipBar (row);
  451. if (! bar.intersects (clip.expanded (0, 1)))
  452. continue;
  453. const auto& c = song.channels[(std::size_t) row];
  454. // FL: the bar in the channel's colour, darker at the bottom (its channel buttons' colour when none is set)
  455. const auto top = c.colour != 0 ? c.colour : (std::uint32_t) theme::colour::bg5.getARGB();
  456. const auto r = bar.toFloat();
  457. g.setGradientFill (juce::ColourGradient (juce::Colour (top), r.getX(), r.getY(), juce::Colour (rackzip::barBottom (top)), r.getX(), r.getBottom(), false));
  458. g.fillRect (r);
  459. if (hoverArea == Area::zipped && hoverRow == row)
  460. {
  461. g.setColour (theme::colour::textPrimary.withAlpha (0.6f));
  462. g.drawRect (r.expanded (1.0f), 1.0f);
  463. }
  464. }
  465. }
  466. void ChannelRackComponent::zipSelected()
  467. {
  468. const auto rows = engine.getSelectedChannels();
  469. if (rows.empty())
  470. return;
  471. engine.editSong ([rows] (Song& s) {
  472. for (const auto r : rows)
  473. if (r >= 0 && r < (int) s.channels.size())
  474. s.channels[(std::size_t) r].zipped = true;
  475. });
  476. updateSize();
  477. repaint();
  478. }
  479. void ChannelRackComponent::unzipAll()
  480. {
  481. const auto& channels = engine.getSong().channels;
  482. if (std::none_of (channels.begin(), channels.end(), [] (const ChannelDef& c) { return c.zipped; }))
  483. return;
  484. engine.editSong ([] (Song& s) {
  485. for (auto& c : s.channels)
  486. c.zipped = false;
  487. });
  488. updateSize();
  489. repaint();
  490. }
  491. void ChannelRackComponent::unzip (int row)
  492. {
  493. if (row < 0 || row >= (int) engine.getSong().channels.size() || ! engine.getSong().channels[(std::size_t) row].zipped)
  494. return;
  495. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].zipped = false; });
  496. updateSize();
  497. repaint();
  498. }
  499. int ChannelRackComponent::graphRow() const
  500. {
  501. const auto count = (int) engine.getSong().channels.size();
  502. const auto row = graphLanes && count > 0 ? juce::jlimit (0, count - 1, engine.getSelectedChannel()) : -1;
  503. return row >= 0 && isShown (row) && ! isZipped (row) ? row : -1;
  504. }
  505. int ChannelRackComponent::rowY (int row) const
  506. {
  507. const auto base = baseRowY (row);
  508. if (autoBefore.empty() || row < 0) // (round 190oo: no automation clip rows, the rows as before)
  509. return base;
  510. return base + autoBefore[(std::size_t) juce::jmin (row, (int) autoBefore.size() - 1)] * rowHeight;
  511. }
  512. int ChannelRackComponent::baseRowY (int row) const
  513. {
  514. const auto lane = graphRow();
  515. const auto offset = lane >= 0 && row > lane ? laneHeight : 0;
  516. if (const auto count = (int) zipLayout.top.size() - 1; count >= 0 && row >= 0) // (round 190mk: zipped strips)
  517. return (row <= count ? zipLayout.top[(std::size_t) row] : zipLayout.top[(std::size_t) count] + (row - count) * rowHeight) + offset;
  518. return 4 + visibleIndex (row) * rowHeight + offset;
  519. }
  520. int ChannelRackComponent::rowAtY (int y) const
  521. {
  522. if (y < 4)
  523. return -1;
  524. // round 190oo (PAT-7): the automation clip rows above y move it up a row each; on one, the channel row under it
  525. // answers (the drags and drops that look for a channel; areaAt finds the automation row itself first)
  526. if (! autoRows.empty())
  527. {
  528. int above = 0;
  529. for (int i = 0; i < (int) autoRows.size(); ++i)
  530. {
  531. const auto top = automationRowTop (i);
  532. if (y >= top + rowHeight)
  533. ++above;
  534. else
  535. {
  536. if (y >= top)
  537. return autoRows[(std::size_t) i].gap;
  538. break;
  539. }
  540. }
  541. y -= above * rowHeight;
  542. }
  543. if (const auto lane = graphRow(); lane >= 0)
  544. {
  545. const auto laneTop = baseRowY (lane) + rowHeight;
  546. if (y >= laneTop && y < laneTop + laneHeight)
  547. return lane;
  548. if (y >= laneTop + laneHeight)
  549. y -= laneHeight;
  550. }
  551. if (! zipLayout.top.empty()) // (round 190mk: zipped strips; a strip answers with its first row)
  552. return rackzip::rowAt (zipLayout, y, rowHeight);
  553. const auto index = (y - 4) / rowHeight;
  554. if (filterGroup == rackfilter::all)
  555. return index;
  556. // the index-th shown row (the "add channel" row after the last one)
  557. const auto count = (int) engine.getSong().channels.size();
  558. int seen = 0;
  559. for (int r = 0; r < count; ++r)
  560. if (isShown (r) && seen++ == index)
  561. return r;
  562. return count + (index - seen);
  563. }
  564. juce::Rectangle<int> ChannelRackComponent::laneBounds() const
  565. {
  566. const auto lane = graphRow();
  567. return lane < 0 ? juce::Rectangle<int>() : juce::Rectangle<int> (0, rowY (lane) + rowHeight, getWidth(), laneHeight);
  568. }
  569. juce::Rectangle<int> ChannelRackComponent::rowBounds (int row) const
  570. {
  571. return { 0, rowY (row), getWidth(), rowHeight };
  572. }
  573. juce::Rectangle<int> ChannelRackComponent::stepBounds (int row, int step) const
  574. {
  575. // FL's step keycaps (round 190io, FM-11): 15 x 20 at an 18 px pitch (FL: 13 x 20 at 16; a bit wider for the mouse)
  576. return { gridLeft() + step * stepWidth + 1, rowY (row) + 5, stepWidth - 3, rowHeight - 10 };
  577. }
  578. // --- channel looping (FL 20.5+, round 165f-rack) ------------------------------------------------------
  579. int ChannelRackComponent::loopStepsOf (int row) const
  580. {
  581. const auto& song = engine.getSong();
  582. if (song.patterns.empty() || row < 0 || row >= (int) song.channels.size())
  583. return 0;
  584. const auto& p = song.activePattern();
  585. if (! p.loopOn)
  586. return 0;
  587. const auto length = p.effectiveLength (song.meter());
  588. const auto loop = channelloops::loopLength (p, row, channelloops::effectiveSetting (p, row), length, song.meter());
  589. return loop > 0 && loop < length ? (int) (loop / ticksPerStep) : 0;
  590. }
  591. bool ChannelRackComponent::advancedLoopShown() const
  592. {
  593. const auto& song = engine.getSong();
  594. if (song.patterns.empty())
  595. return false;
  596. const auto& p = song.activePattern();
  597. return p.loopOn && p.loopMode == RackLoopMode::advanced;
  598. }
  599. juce::Rectangle<int> ChannelRackComponent::loopBoxBounds (int row) const
  600. {
  601. // the right edge of what the viewport shows (the column stays there while the steps scroll, like the controls)
  602. auto right = getWidth();
  603. if (const auto* holder = getParentComponent())
  604. right = juce::jmin (getWidth(), stickyX + holder->getWidth());
  605. return { right - loopColumnWidth + 3, rowY (row) + 5, loopColumnWidth - 8, rowHeight - 10 };
  606. }
  607. void ChannelRackComponent::paintLoopColumn (juce::Graphics& g)
  608. {
  609. using namespace theme::colour;
  610. const auto& song = engine.getSong();
  611. const auto& p = song.activePattern();
  612. const auto first = loopBoxBounds (0);
  613. g.setColour (bg2);
  614. g.fillRect (first.getX() - 3, 0, loopColumnWidth, getHeight());
  615. g.setColour (border);
  616. g.fillRect (first.getX() - 4, 0, 1, getHeight());
  617. g.setFont (theme::font (theme::type::caption, true));
  618. for (int row = 0; row < (int) song.channels.size(); ++row)
  619. {
  620. if (! isShown (row) || isZipped (row) || song.channels[(std::size_t) row].instrument == InstrumentKind::audioClip)
  621. continue;
  622. const auto box = loopBoxBounds (row);
  623. const auto setting = channelloops::effectiveSetting (p, row);
  624. const auto hovered = (hoverArea == Area::loop && hoverRow == row) || loopDragRow == row;
  625. theme::fillRoundRect (g, box.toFloat(), theme::radius::sm, hovered ? bg4 : bg0);
  626. if (setting != ChannelLoop::dontLoop)
  627. {
  628. g.setColour (accent.withAlpha (hovered ? 0.9f : 0.6f));
  629. g.drawRoundedRectangle (box.toFloat().reduced (0.5f), theme::radius::sm, 1.0f);
  630. }
  631. g.setColour (setting == ChannelLoop::dontLoop ? textDisabled : textPrimary);
  632. const auto text = setting > 0 ? juce::String (setting) : setting == ChannelLoop::dontLoop ? juce::String ("...")
  633. : tr (channelloops::settingText (setting).c_str());
  634. textcache::drawText (g, text, box, juce::Justification::centred, true);
  635. }
  636. g.setFont (theme::font (theme::type::body));
  637. }
  638. void ChannelRackComponent::setLoopPoint (int row, int setting)
  639. {
  640. if (row < 0 || row >= (int) engine.getSong().channels.size())
  641. return;
  642. engine.editSong ([row, setting] (Song& s) {
  643. auto& p = s.activePattern();
  644. auto value = setting;
  645. // FL's "Set to next beat / bar": a fixed loop point, the steps to the boundary after the channel's last note
  646. if (setting == 1000 + ChannelLoop::nextBeat || setting == 1000 + ChannelLoop::nextBar)
  647. value = channelloops::nextBoundarySteps (p, row, setting - 1000, s.meter());
  648. channelloops::setSetting (p, row, value);
  649. // (FL switches the looping on, advanced, when a loop point is set from a channel)
  650. if (! p.loopOn && value != ChannelLoop::dontLoop)
  651. {
  652. p.loopOn = true;
  653. p.loopMode = RackLoopMode::advanced;
  654. }
  655. });
  656. updateSize();
  657. repaint();
  658. }
  659. void ChannelRackComponent::showLoopPointMenu (int row)
  660. {
  661. const auto& song = engine.getSong();
  662. if (row < 0 || row >= (int) song.channels.size())
  663. return;
  664. const auto& p = song.activePattern();
  665. const auto setting = channelloops::effectiveSetting (p, row);
  666. juce::PopupMenu menu;
  667. ui::addItemHeader (menu, tr ("Loop point"), channelName (song, row), {});
  668. menu.addItem (tr ("Don't loop"), true, setting == ChannelLoop::dontLoop, [this, row] { setLoopPoint (row, ChannelLoop::dontLoop); });
  669. menu.addSeparator();
  670. menu.addItem (tr ("Step") + " - " + tr ("loop at the next step"), true, setting == ChannelLoop::nextStep, [this, row] { setLoopPoint (row, ChannelLoop::nextStep); });
  671. menu.addItem (tr ("Beat") + " - " + tr ("loop at the next beat"), true, setting == ChannelLoop::nextBeat, [this, row] { setLoopPoint (row, ChannelLoop::nextBeat); });
  672. menu.addItem (tr ("Bar") + " - " + tr ("loop at the next bar"), true, setting == ChannelLoop::nextBar, [this, row] { setLoopPoint (row, ChannelLoop::nextBar); });
  673. menu.addSeparator();
  674. menu.addItem (tr ("Set to next beat"), [this, row] { setLoopPoint (row, 1000 + ChannelLoop::nextBeat); });
  675. menu.addItem (tr ("Set to next bar"), [this, row] { setLoopPoint (row, 1000 + ChannelLoop::nextBar); });
  676. if (setting > 0)
  677. menu.addItem (tr ("Every {0} steps", { juce::String (setting) }), false, true, [] {});
  678. menu.addSectionHeader (tr ("Tools"));
  679. menu.addItem (tr ("Burn to pattern"), loopStepsOf (row) > 0, false, [this, row] {
  680. engine.editSong ([row] (Song& s) { channelloops::burnChannel (s.activePattern(), row, s.meter()); });
  681. repaint();
  682. });
  683. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withTargetScreenArea (localAreaToGlobal (loopBoxBounds (row))));
  684. }
  685. bool ChannelRackComponent::isLoopingOn() const
  686. {
  687. const auto& song = engine.getSong();
  688. return ! song.patterns.empty() && song.activePattern().loopOn;
  689. }
  690. void ChannelRackComponent::toggleLooping()
  691. {
  692. engine.editSong ([] (Song& s) {
  693. auto& p = s.activePattern();
  694. p.loopOn = ! p.loopOn;
  695. });
  696. updateSize();
  697. repaint();
  698. if (onFilterChanged)
  699. onFilterChanged(); // (the title bar's Loop button)
  700. }
  701. void ChannelRackComponent::burnLoops (bool selectedOnly)
  702. {
  703. const auto rows = engine.getSelectedChannels();
  704. engine.editSong ([rows, selectedOnly] (Song& s) {
  705. auto& p = s.activePattern();
  706. if (selectedOnly)
  707. {
  708. for (auto r : rows)
  709. channelloops::burnChannel (p, r, s.meter());
  710. }
  711. else
  712. channelloops::burnChannels (p, {}, s.meter());
  713. });
  714. repaint();
  715. }
  716. void ChannelRackComponent::showLoopMenu (juce::Component* target)
  717. {
  718. const auto& song = engine.getSong();
  719. if (song.patterns.empty())
  720. return;
  721. const auto& p = song.activePattern();
  722. juce::PopupMenu menu;
  723. menu.addItem (tr ("Looping on"), true, p.loopOn, [this] { toggleLooping(); });
  724. menu.addSectionHeader (tr ("Loop type"));
  725. const std::pair<RackLoopMode, const char*> types[] = { { RackLoopMode::steps, TR_NOOP ("Loop step channels") },
  726. { RackLoopMode::all, TR_NOOP ("Loop all channels") },
  727. { RackLoopMode::advanced, TR_NOOP ("Advanced looping") } };
  728. for (const auto& [mode, name] : types)
  729. menu.addItem (tr (name), true, p.loopMode == mode, [this, mode = mode] {
  730. engine.editSong ([mode] (Song& s) {
  731. auto& q = s.activePattern();
  732. q.loopMode = mode;
  733. q.loopOn = true; // (FL: picking a type switches the looping on)
  734. });
  735. updateSize();
  736. repaint();
  737. if (onFilterChanged)
  738. onFilterChanged();
  739. });
  740. menu.addSectionHeader (tr ("Burn to pattern"));
  741. const auto looping = ! channelloops::loopingChannels (p, song.meter()).empty();
  742. menu.addItem (tr ("Burn selected channels"), looping, false, [this] { burnLoops (true); });
  743. menu.addItem (tr ("Burn all looping channels"), looping, false, [this] { burnLoops (false); });
  744. auto options = juce::PopupMenu::Options();
  745. if (target != nullptr)
  746. options = options.withTargetComponent (target);
  747. menu.showMenuAsync (options);
  748. }
  749. void ChannelRackComponent::burnMidi (int channel, bool toNewPattern)
  750. {
  751. const auto& song = engine.getSong();
  752. if (song.patterns.empty() || channel < 0 || channel >= (int) song.channels.size())
  753. return;
  754. if (channelburn::playedNotes (song, song.currentPattern, channel).empty())
  755. {
  756. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Nothing to burn"),
  757. tr ("The selected channel doesn't contain any notes to burn."));
  758. return;
  759. }
  760. const auto baked = channelburn::whatBurns (song, song.currentPattern, channel);
  761. auto run = [this, channel, toNewPattern] (channelburn::Reset reset) {
  762. engine.editSong ([channel, toNewPattern, reset] (Song& s) { channelburn::burnMidi (s, channel, toNewPattern, reset); });
  763. updateSize();
  764. repaint();
  765. };
  766. if (! (baked.arpeggiator || baked.echo || baked.swing || baked.time))
  767. {
  768. run ({});
  769. return;
  770. }
  771. // FL's "Reset after burning to MIDI": what the burn wrote into the notes is switched off, or it would play twice
  772. struct ResetDialog final : juce::AlertWindow
  773. {
  774. explicit ResetDialog (const channelburn::Baked& baked)
  775. : juce::AlertWindow (tr ("Reset after burning to MIDI"), tr ("Select what you want to reset:"), juce::MessageBoxIconType::QuestionIcon)
  776. {
  777. const std::pair<const char*, bool> items[] = { { TR_NOOP ("Arpeggiator"), baked.arpeggiator }, { TR_NOOP ("Echo delay"), baked.echo },
  778. { TR_NOOP ("Swing mix"), baked.swing }, { TR_NOOP ("Time (shift and gate)"), baked.time } };
  779. for (std::size_t i = 0; i < toggles.size(); ++i)
  780. {
  781. toggles[i].setButtonText (tr (items[i].first));
  782. toggles[i].setToggleState (items[i].second, juce::dontSendNotification);
  783. toggles[i].setEnabled (items[i].second);
  784. toggles[i].setSize (300, 24);
  785. addCustomComponent (&toggles[i]);
  786. }
  787. addButton (tr ("Burn"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  788. addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  789. }
  790. channelburn::Reset reset() const
  791. {
  792. return { toggles[0].getToggleState(), toggles[1].getToggleState(), toggles[2].getToggleState(), toggles[3].getToggleState() };
  793. }
  794. std::array<juce::ToggleButton, 4> toggles;
  795. };
  796. auto* w = new ResetDialog (baked);
  797. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, run] (int result) {
  798. if (result == 1)
  799. run (w->reset());
  800. }), true);
  801. }
  802. ChannelRackComponent::Area ChannelRackComponent::areaAt (int x, int y, int& row) const
  803. {
  804. const auto channels = (int) engine.getSong().channels.size();
  805. const auto rackX = x;
  806. if (x < stickyX + gridLeft()) // the controls column (painted at the visible left edge)
  807. x -= stickyX;
  808. // round 190oo (PAT-7): an automation clip row (FL's automation clip channel): its button, or the rest of the row
  809. if (const auto automationRow = autoRows.empty() ? -1 : automationRowAt (y); automationRow >= 0)
  810. {
  811. row = autoRows[(std::size_t) automationRow].automation;
  812. return x >= nameLeft() && x < selectLeft() ? Area::autoName : Area::autoRow;
  813. }
  814. row = rowAtY (y);
  815. if (row < 0 || row > channels)
  816. return Area::none;
  817. if (isZipped (row)) // round 190mk (DE-38): a zipped strip; on a bar, that bar's channel
  818. {
  819. if (const auto bar = zipBarAt (row, rackX); bar >= 0)
  820. {
  821. row = bar;
  822. return Area::zipped;
  823. }
  824. return Area::none;
  825. }
  826. if (laneBounds().contains (x, y))
  827. return x < gridLeft() ? Area::laneLevels : Area::lane;
  828. if (row == channels) // only the "+ add channel" box opens the menu (issue #116: as FL's + button)
  829. return racklayout::addChannelBox (nameLeft(), nameWidth, rowY (row), rowHeight).contains (x, y) ? Area::addRow : Area::none;
  830. if (advancedLoopShown() && x >= loopBoxBounds (row).getX() - 3) // the column covers the steps under it
  831. return loopBoxBounds (row).expanded (2, 3).contains (x, y) ? Area::loop : Area::none;
  832. if (x < muteWidth)
  833. return Area::mute;
  834. if (x < muteWidth + knobWidth)
  835. return Area::pan;
  836. if (x < muteWidth + 2 * knobWidth)
  837. return Area::volume;
  838. if (x < nameLeft())
  839. return Area::route;
  840. if (x < selectLeft())
  841. return Area::name;
  842. if (x < gridLeft())
  843. return Area::select;
  844. return Area::grid;
  845. }
  846. bool ChannelRackComponent::cellHasNote (int channel, int step) const
  847. {
  848. const auto& song = engine.getSong();
  849. const auto& p = song.activePattern();
  850. const auto from = (std::int64_t) step * ticksPerStep;
  851. const auto to = from + ticksPerStep;
  852. for (const auto& n : p.notes) // (a muted note leaves its step looking off, as in FL: round 169f, FL session)
  853. if (n.channel == channel && n.start >= from && n.start < to && ! n.muted)
  854. return true;
  855. return false;
  856. }
  857. bool ChannelRackComponent::channelHitsNow (int row) const
  858. {
  859. if (playheadStep < 0 || playheadStep >= numSteps())
  860. return false;
  861. const auto& song = engine.getSong();
  862. const auto& p = song.activePattern();
  863. const auto loopSteps = loopStepsOf (row);
  864. const auto step = loopSteps > 0 && playheadStep >= loopSteps ? playheadStep % loopSteps : playheadStep;
  865. return p.hasStep (row, step) || cellHasNote (row, step);
  866. }
  867. // Eight idle step keycaps (two groups of four, `a` then `b`) on the row's own background `bg`, from one opaque cached
  868. // tile (round 190io): an opaque tile is copied, not blended, by the software renderer, so a row of idle steps costs about
  869. // what the old flat tiles did although twice as many rows show steps now (the audio clip channels, FM-12). Drawn straight
  870. // where the scale is not whole.
  871. static void drawIdleStepStrip (juce::Graphics& g, juce::Rectangle<int> firstCell, int pitch, juce::Colour a, juce::Colour b, juce::Colour bg)
  872. {
  873. const auto bounds = firstCell.withWidth (7 * pitch + firstCell.getWidth());
  874. if (! g.clipRegionIntersects (bounds))
  875. return;
  876. const auto paintInto = [&] (juce::Graphics& k, bool withBackground) {
  877. if (withBackground)
  878. {
  879. k.setColour (bg);
  880. k.fillRect (juce::Rectangle<int> (bounds.getWidth(), bounds.getHeight()));
  881. }
  882. for (int i = 0; i < 8; ++i)
  883. theme::drawKeycap (k, juce::Rectangle<int> (i * pitch, 0, firstCell.getWidth(), firstCell.getHeight()), i < 4 ? a : b, false);
  884. };
  885. const auto s = g.getInternalContext().getPhysicalPixelScaleFactor();
  886. const auto scale = (int) std::round (s);
  887. if (! ui::paintCache() || scale < 1 || scale > 3 || std::abs (s - (float) scale) > 1.0e-4f || ! bg.isOpaque())
  888. {
  889. juce::Graphics::ScopedSaveState state (g);
  890. g.setOrigin (bounds.getPosition());
  891. paintInto (g, false);
  892. return;
  893. }
  894. static std::unordered_map<std::uint64_t, juce::Image> cache;
  895. static const bool registered = ui::registerImageCache ([] { cache.clear(); }); (void) registered;
  896. std::uint64_t key = 0xcbf29ce484222325ull;
  897. for (const std::uint64_t v : { (std::uint64_t) a.getARGB(), (std::uint64_t) b.getARGB(), (std::uint64_t) bg.getARGB(), (std::uint64_t) pitch,
  898. (std::uint64_t) firstCell.getWidth(), (std::uint64_t) firstCell.getHeight(), (std::uint64_t) scale,
  899. (std::uint64_t) theme::colour::bg0.getARGB(), (std::uint64_t) theme::colour::borderStrong.getARGB() })
  900. key = (key ^ v) * 0x100000001b3ull;
  901. auto it = cache.find (key);
  902. if (it == cache.end())
  903. {
  904. if (cache.size() > 200)
  905. cache.clear();
  906. juce::Image image (juce::Image::RGB, bounds.getWidth() * scale, bounds.getHeight() * scale, false,
  907. #if JUCE_WINDOWS
  908. juce::NativeImageType()
  909. #else
  910. juce::SoftwareImageType()
  911. #endif
  912. );
  913. {
  914. juce::Graphics ig (image);
  915. ig.addTransform (juce::AffineTransform::scale ((float) scale));
  916. paintInto (ig, true);
  917. }
  918. it = cache.emplace (key, std::move (image)).first;
  919. }
  920. g.setColour (juce::Colours::black); // (an image is drawn with the current colour's alpha as its opacity)
  921. if (scale == 1)
  922. g.drawImageAt (it->second, bounds.getX(), bounds.getY());
  923. else
  924. g.drawImage (it->second, bounds.toFloat(), juce::RectanglePlacement::stretchToFit);
  925. }
  926. void ChannelRackComponent::paintStepHit (juce::Graphics& g, juce::Rectangle<float> r)
  927. {
  928. theme::fillRoundRect (g, r, keycapRadius, juce::Colours::white.withAlpha (0.55f));
  929. g.setColour (theme::colour::playhead);
  930. g.drawRoundedRectangle (r.reduced (0.75f), keycapRadius, 1.5f);
  931. }
  932. // FL's raised step keycap (round 190io, design190ia FM-11; FL: a light top edge, a dark bottom edge and the dark LED slot
  933. // a quarter down): the body in the step's colour, a 1 px highlight on top, a 1 px shade at the bottom and the 1 px slot
  934. // line, which turns light on a lit step. Plain rectangles, so a playhead frame costs what the flat tiles did.
  935. void ChannelRackComponent::paintKeycap (juce::Graphics& g, juce::Rectangle<int> r, juce::Colour fill, bool lit)
  936. {
  937. theme::drawKeycap (g, r, fill, lit);
  938. }
  939. void ChannelRackComponent::paint (juce::Graphics& g)
  940. {
  941. const uitrace::Scope trace ("ChannelRackComponent paint", true, g.getClipBounds());
  942. using namespace theme::colour;
  943. g.fillAll (bg2);
  944. const auto& song = engine.getSong();
  945. if (song.patterns.empty())
  946. return;
  947. const auto& pattern = song.activePattern();
  948. const auto steps = shownSteps(), realSteps = numSteps();
  949. const auto clip = g.getClipBounds();
  950. const auto primary = engine.getSelectedChannel();
  951. const auto& selection = engine.getSelectedChannels();
  952. const auto palette = theme::currentPalette();
  953. const auto column = playheadColumn.load (std::memory_order_relaxed) && playheadStep >= 0 && playheadStep < steps;
  954. g.setFont (theme::font (theme::type::body));
  955. // round 190gr: which (channel, step) cells hold a Piano Roll note, from one pass over the pattern's notes (cellHasNote
  956. // walks every note of the pattern for each cell: rows x steps x notes per frame)
  957. const auto channelCount = (int) song.channels.size();
  958. const auto noteCells = ui::paintCache();
  959. if (noteCells)
  960. {
  961. noteCellBits.assign ((std::size_t) channelCount * (std::size_t) juce::jmax (0, steps), 0);
  962. for (const auto& n : pattern.notes)
  963. if (! n.muted && n.channel >= 0 && n.channel < channelCount && n.start >= 0)
  964. if (const auto step = n.start / ticksPerStep; step < steps)
  965. noteCellBits[(std::size_t) n.channel * (std::size_t) steps + (std::size_t) step] = 1;
  966. }
  967. const auto hasNote = [&] (int channel, int step) {
  968. if (! noteCells)
  969. return cellHasNote (channel, step);
  970. return step >= 0 && step < steps && noteCellBits[(std::size_t) channel * (std::size_t) steps + (std::size_t) step] != 0;
  971. };
  972. for (int row = 0; row < (int) song.channels.size(); ++row)
  973. {
  974. if (isZipped (row)) // (round 190mk: drawn as a bar in its strip, paintZipStrips)
  975. continue;
  976. const auto y = rowY (row);
  977. if (! isShown (row) || y > clip.getBottom() || y + rowHeight < clip.getY())
  978. continue;
  979. const auto& channel = song.channels[(std::size_t) row];
  980. const auto selected = std::binary_search (selection.begin(), selection.end(), row);
  981. const auto litOn = stepsChannelColour.load (std::memory_order_relaxed) && channel.colour != 0
  982. ? juce::Colour (themes::litStepColour (channel.colour, palette))
  983. : theme::colour::stepOn;
  984. if (selected) // selected rows are subtly lifted
  985. {
  986. g.setColour (bg3);
  987. g.fillRect (0, y + 1, getWidth(), rowHeight - 2);
  988. }
  989. if (column) // LYNX: the playing column, soft, under the step buttons (their colours and groups stay readable)
  990. {
  991. g.setColour (playhead.withAlpha (0.2f));
  992. g.fillRect (gridLeft() + playheadStep * stepWidth - 1, y, stepWidth, rowHeight);
  993. }
  994. // (round 190io, FM-12: an audio clip channel shows its steps as every channel does; FL's manual: "If desired,
  995. // Audio Clips can be triggered from the Step Sequencer or the Piano roll")
  996. const auto loopSteps = loopStepsOf (row); // the row loops: the repeats after its loop point are ghost steps
  997. const auto stepOn = litOn; // (the channel's lit-step colour, or the theme's)
  998. if (showsNotePreview (pattern, row, pianoRollView)) // piano-roll notes: a miniature instead of the step buttons
  999. {
  1000. paintNotePreview (g, row, pattern, channel.colour);
  1001. const auto span = previewSpan();
  1002. const auto stepX = [&] (int step) { return gridLeft() + span.x + (int) ((std::int64_t) span.width * step / realSteps); };
  1003. if (loopSteps > 0)
  1004. {
  1005. g.setColour (accent.withAlpha (0.85f));
  1006. g.fillRect (stepX (loopSteps) - 2, y + 3, 2, rowHeight - 6);
  1007. }
  1008. if (span.fitted && playheadStep >= 0 && playheadStep < realSteps) // (the playing column is elsewhere: a line here)
  1009. {
  1010. g.setColour (playhead.withAlpha (0.8f));
  1011. g.fillRect (stepX (playheadStep), y + 4, juce::jmax (2, span.width / realSteps), rowHeight - 8);
  1012. }
  1013. continue;
  1014. }
  1015. // round 190io: the idle keycaps (and the faint steps past the pattern's end) come eight at a time from one tile;
  1016. // the steps that differ (lit, hovered, playing, loop repeats) are drawn over them one by one below
  1017. const auto idleLimit = loopSteps > 0 ? juce::jmin (loopSteps, realSteps) : realSteps;
  1018. const auto stripKind = [&] (int step) { // 1: a keycap strip covers it, 2: a ghost strip, 0: drawn alone
  1019. const auto start = step / 8 * 8;
  1020. return start + 8 <= idleLimit ? 1 : start >= realSteps && start + 8 <= steps ? 2 : 0;
  1021. };
  1022. // (the strip under the playing column is drawn cell by cell: the column's soft tint shows between its steps)
  1023. const auto columnStrip = column ? playheadStep / 8 * 8 : -1;
  1024. for (int start = 0; start + 8 <= steps; start += 8)
  1025. if (const auto kind = stripKind (start); kind != 0 && start != columnStrip)
  1026. {
  1027. const auto first = stepBounds (row, start);
  1028. if (first.getX() + 8 * stepWidth < clip.getX() || first.getX() > clip.getRight())
  1029. continue;
  1030. if (kind == 1)
  1031. drawIdleStepStrip (g, first, stepWidth, theme::stepOff (start), theme::stepOff (start + 4), selected ? bg3 : bg2);
  1032. else
  1033. theme::drawStepStripOver (g, first, stepWidth, theme::stepOff (start), theme::stepOff (start + 4), true, selected ? bg3 : bg2);
  1034. }
  1035. for (int step = 0; step < steps; ++step)
  1036. {
  1037. const auto r = stepBounds (row, step);
  1038. if (r.getRight() < clip.getX() || r.getX() > clip.getRight())
  1039. continue;
  1040. auto onGrid = pattern.hasStep (row, step);
  1041. auto any = onGrid || hasNote (row, step);
  1042. const auto hoverStepHere = hoverArea == Area::grid && hoverRow == row && hoverStep == step && paintMode == PaintMode::none;
  1043. if (! any && ! hoverStepHere && stripKind (step) != 0 && step / 8 * 8 != columnStrip) // (drawn by its strip)
  1044. continue;
  1045. if (loopSteps > 0 && step >= loopSteps && step < realSteps)
  1046. {
  1047. // FL's loop ghosts: what the loop repeats here, faint; a step of its own past the loop point doesn't play
  1048. const auto source = step % loopSteps;
  1049. const auto repeated = pattern.hasStep (row, source) || hasNote (row, source);
  1050. auto fill = repeated ? stepOn : theme::stepOff (step);
  1051. theme::fillRoundRect (g, r.toFloat(), keycapRadius, fill.withMultipliedAlpha (hoverStepHere ? 0.75f : repeated ? 0.45f : 0.3f));
  1052. if (repeated && step == playheadStep) // the repeat plays: lit as a hit (below)
  1053. paintStepHit (g, r.toFloat());
  1054. if (any)
  1055. {
  1056. g.setColour (textDisabled);
  1057. g.drawRoundedRectangle (r.toFloat().reduced (1.5f), keycapRadius, 1.0f);
  1058. }
  1059. if (hoverStepHere)
  1060. {
  1061. g.setColour (textSecondary.withAlpha (0.7f));
  1062. g.drawRoundedRectangle (r.toFloat().reduced (0.5f), keycapRadius, 1.0f);
  1063. }
  1064. continue;
  1065. }
  1066. const auto ghost = step >= realSteps && ! any; // after the pattern's end: faint until clicked
  1067. auto fill = any ? (onGrid ? stepOn : stepNote) : theme::stepOff (step);
  1068. if (ghost) // a faint outlined cell, filled while hovered
  1069. {
  1070. theme::fillRoundRect (g, r.toFloat(), keycapRadius, fill.withMultipliedAlpha (hoverStepHere ? 0.9f : 0.35f));
  1071. g.setColour (fill.brighter (0.25f).withMultipliedAlpha (0.55f));
  1072. g.drawRoundedRectangle (r.toFloat().reduced (0.5f), keycapRadius, 1.0f);
  1073. }
  1074. else
  1075. paintKeycap (g, r, hoverStepHere ? fill.brighter (any ? 0.15f : 0.35f) : fill, any);
  1076. // FL lights the step as the playhead hits it (its LED turns red, round 170a [SHOT]): a step that plays now glows
  1077. if (any && step == playheadStep && step < realSteps)
  1078. paintStepHit (g, r.toFloat());
  1079. if (hoverStepHere)
  1080. {
  1081. g.setColour (textSecondary.withAlpha (0.7f));
  1082. g.drawRoundedRectangle (r.toFloat().reduced (0.5f), keycapRadius, 1.0f);
  1083. }
  1084. }
  1085. if (loopSteps > 0) // the loop point
  1086. {
  1087. g.setColour (accent.withAlpha (0.85f));
  1088. g.fillRect (gridLeft() + loopSteps * stepWidth - 2, y + 3, 2, rowHeight - 6);
  1089. }
  1090. }
  1091. if (! autoRows.empty()) // round 190oo (PAT-7): the automation clip rows' steps
  1092. paintAutomationSteps (g, clip);
  1093. paintLane (g);
  1094. const auto addY = rowY ((int) song.channels.size());
  1095. g.setColour (theme::colour::textSecondary); // (round 190oo PAT-14: an informative hint, 7:1; was textDisabled 2.9:1)
  1096. g.setFont (theme::font (theme::type::small));
  1097. textcache::drawText (g, tr ("or drop an audio file here"), gridLeft() + 4, addY + positionStripHeight, 400, rowHeight - positionStripHeight,
  1098. juce::Justification::centredLeft);
  1099. const auto stepsPerBar = (int) std::max<std::int64_t> (1, song.barTicks() / ticksPerStep);
  1100. // FL's "Playing step" strip (PosLEDPanel, REA round 170a §2): a slim LED row under the steps, beat groups
  1101. // alternating, the playing step lit — in Pattern mode and whenever the shown pattern plays in Song mode
  1102. for (int step = 0; step < realSteps; ++step)
  1103. {
  1104. const auto cell = juce::Rectangle<float> ((float) (gridLeft() + step * stepWidth) + 1.0f, (float) addY + 2.0f, (float) stepWidth - 4.0f,
  1105. (float) positionStripHeight - 3.0f);
  1106. if (cell.getRight() < (float) clip.getX() || cell.getX() > (float) clip.getRight())
  1107. continue;
  1108. theme::fillRoundRect (g, cell, 1.5f, step == playheadStep ? playhead : theme::stepOff (step).brighter (0.12f));
  1109. // LYNX: each bar's first step marked (finding the bars on 32 / 64-step patterns)
  1110. if (playheadColumn.load (std::memory_order_relaxed) && step % stepsPerBar == 0 && step != playheadStep)
  1111. {
  1112. g.setColour (accent.withAlpha (0.7f));
  1113. g.fillRect (cell.withHeight (2.0f));
  1114. }
  1115. }
  1116. // the controls column stays put while the steps scroll sideways (FL's rack keeps the channel buttons in
  1117. // view): the viewport moves the whole rack, so the column is painted again at the visible left edge
  1118. {
  1119. juce::Graphics::ScopedSaveState state (g);
  1120. g.reduceClipRegion (stickyX, 0, gridLeft(), getHeight());
  1121. g.setOrigin (stickyX, 0);
  1122. g.setColour (bg2);
  1123. g.fillRect (0, 0, gridLeft(), getHeight());
  1124. const auto column = g.getClipBounds();
  1125. for (int row = 0; row < (int) song.channels.size(); ++row)
  1126. {
  1127. if (isZipped (row)) // (round 190mk)
  1128. continue;
  1129. const auto y = rowY (row);
  1130. if (! isShown (row) || y > column.getBottom() || y + rowHeight < column.getY())
  1131. continue;
  1132. const auto& channel = song.channels[(std::size_t) row];
  1133. const auto selected = std::binary_search (selection.begin(), selection.end(), row);
  1134. const auto nameArea = juce::Rectangle<float> ((float) nameLeft(), (float) y + 3, (float) nameWidth, (float) rowHeight - 6);
  1135. if (selected) // selected rows are subtly lifted
  1136. {
  1137. g.setColour (bg3);
  1138. g.fillRect (0, y + 1, getWidth(), rowHeight - 2);
  1139. }
  1140. const auto hovered = [this, row] (Area a) { return hoverRow == row && hoverArea == a; };
  1141. // round 190ge: a playhead step repaints the selector column only (the selectors flash with the hits): the mute
  1142. // LED, knobs, route box and name, all left of it, are drawn only when the repainted area reaches them
  1143. if (column.getX() < selectLeft() || ! ui::paintSavings())
  1144. {
  1145. const auto led = juce::Rectangle<float> (9.0f, (float) y + rowHeight / 2.0f - 4.5f, 9.0f, 9.0f);
  1146. g.setColour (theme::muteLed (channel.muted));
  1147. g.fillEllipse (led);
  1148. if (hovered (Area::mute)) // hover ring
  1149. {
  1150. g.setColour (textSecondary.withAlpha (0.8f));
  1151. g.drawEllipse (led.expanded (2.5f), 1.0f);
  1152. }
  1153. const auto touched = knobDrag != Area::none && knobRow == row;
  1154. // (while the song plays an automated knob shows its automation's value, issue #12)
  1155. const auto& automated = engine.getAutomationDisplay();
  1156. theme::drawKnob (g, controlBounds (Area::pan, row).toFloat().reduced (1.0f, 2.0f),
  1157. automated.shown ({ AutomationTargetKind::channelPan, row }, (channel.pan + 1.0f) / 2.0f), true,
  1158. touched && knobDrag == Area::pan ? accent : info, hovered (Area::pan) || (touched && knobDrag == Area::pan));
  1159. theme::drawKnob (g, controlBounds (Area::volume, row).toFloat().reduced (1.0f, 2.0f),
  1160. automated.shown ({ AutomationTargetKind::channelVolume, row }, channel.volume), false,
  1161. touched && knobDrag == Area::volume ? accent : knobArc, hovered (Area::volume) || (touched && knobDrag == Area::volume));
  1162. // small box with the mixer insert ("-" = straight to Master)
  1163. const auto routeArea = controlBounds (Area::route, row).toFloat();
  1164. g.setColour (theme::drawDigitDisplay (g, routeArea, hovered (Area::route) || (touched && knobDrag == Area::route),
  1165. channel.mixerTrack <= 0));
  1166. g.setFont (theme::font (theme::type::caption, true));
  1167. textcache::drawText (g, channel.mixerTrack > 0 ? juce::String (channel.mixerTrack) : juce::String ("-"), routeArea.toNearestInt(),
  1168. juce::Justification::centred);
  1169. g.setFont (theme::font (theme::type::body));
  1170. // name button: filled with the channel colour as FL's (round 190io, design190ia FM-10: FL's Synth Bass
  1171. // #11479C, Grv Kick #892019), its brightness held where white text reads (0.42-0.58), a slight top-down
  1172. // gradient (+6 % / -6 %); FL's grey #485156 for a channel without a colour; muted = greyed and darker
  1173. {
  1174. auto fill = theme::colourFill (channel.colour != 0 ? juce::Colour (channel.colour) : juce::Colour (0xff485156), 0.42f, 0.58f);
  1175. if (channel.muted)
  1176. fill = fill.withMultipliedSaturation (0.45f).withMultipliedBrightness (0.7f);
  1177. if (hovered (Area::name))
  1178. fill = fill.brighter (0.12f);
  1179. theme::fillPlate (g, nameArea, theme::radius::sm, fill.withMultipliedBrightness (1.06f), fill.withMultipliedBrightness (0.94f));
  1180. }
  1181. if (row == primary) // the focused channel: a light outline (the selector beside it shows the selection)
  1182. {
  1183. g.setColour (textPrimary);
  1184. g.drawRoundedRectangle (nameArea.reduced (0.75f), theme::radius::sm, 1.5f);
  1185. }
  1186. const auto locked = ! channel.receiveFrom.empty();
  1187. if (locked) // FL's lock icon: the channel receives the notes of one MIDI input ("Receive notes from")
  1188. {
  1189. const auto lockBox = juce::Rectangle<float> (nameArea.getRight() - 15.0f, nameArea.getCentreY() - 6.0f, 9.0f, 11.0f);
  1190. g.setColour (warning);
  1191. juce::Path shackle;
  1192. shackle.addCentredArc (lockBox.getCentreX(), lockBox.getY() + 4.0f, 2.8f, 3.2f, 0.0f, -juce::MathConstants<float>::halfPi,
  1193. juce::MathConstants<float>::halfPi, true);
  1194. g.strokePath (shackle, juce::PathStrokeType (1.4f));
  1195. g.fillRoundedRectangle (lockBox.withTrimmedTop (4.5f), 1.5f);
  1196. }
  1197. // Online Sessions (round 168a): the plugin is not installed here, its stand-in render plays (an amber tag)
  1198. auto badgeWidth = 0.0f;
  1199. if (engine.playsStandIn (row))
  1200. {
  1201. badgeWidth = 16.0f;
  1202. juce::Graphics::ScopedSaveState keepFont (g);
  1203. const auto tag = juce::Rectangle<float> (nameArea.getRight() - (locked ? 34.0f : 18.0f), nameArea.getCentreY() - 6.5f, 14.0f, 13.0f);
  1204. theme::fillRoundRect (g, tag, 3.0f, warning.withAlpha (0.85f));
  1205. g.setColour (bg1);
  1206. g.setFont (theme::font (10.0f, true));
  1207. g.drawText ("R", tag, juce::Justification::centred, false);
  1208. }
  1209. // round 190ap: opened without third-party plugins, this channel's plugin is still off (a grey power tag)
  1210. else if (engine.channelPluginOff (row))
  1211. {
  1212. badgeWidth = 16.0f;
  1213. juce::Graphics::ScopedSaveState keepFont (g);
  1214. ui::drawPluginOffTag (g, juce::Rectangle<float> (nameArea.getRight() - (locked ? 34.0f : 18.0f), nameArea.getCentreY() - 6.5f, 14.0f, 13.0f));
  1215. }
  1216. // Freeze (round 190ay): a frozen channel plays its rendered audio, its instrument is unloaded — a snowflake
  1217. // tag (amber when the audio is out of date or missing) and a dimmed name
  1218. const auto frozen = channel.freeze.on();
  1219. if (frozen)
  1220. {
  1221. const auto attention = engine.frozenAudioMissing (row) || engine.freezeOutOfDate (row);
  1222. const auto tag = juce::Rectangle<float> (nameArea.getRight() - (locked ? 34.0f : 18.0f) - badgeWidth, nameArea.getCentreY() - 6.5f, 14.0f, 13.0f);
  1223. badgeWidth += 16.0f;
  1224. theme::fillRoundRect (g, nameArea, theme::radius::md, bg1.withAlpha (0.35f)); // the plate, dimmed
  1225. theme::drawFrozenTag (g, tag, (attention ? warning : info).withAlpha (0.85f), bg1);
  1226. }
  1227. // the channel's icon (round 168h) at the button's right edge, where FL draws it (round 190io, FM-10: FL's
  1228. // audio clip glyph sits 6 px from the right), left of the lock / tags
  1229. const auto rightUsed = (locked ? 18.0f : 0.0f) + badgeWidth;
  1230. auto iconWidth = 0.0f;
  1231. if (const auto icon = trackicons::iconFor (channel.icon); icon != trackicons::Icon::none)
  1232. {
  1233. iconWidth = 18.0f;
  1234. ui::drawTrackIcon (g, icon, juce::Rectangle<float> (nameArea.getRight() - 6.0f - rightUsed - 14.0f, nameArea.getCentreY() - 7.0f, 14.0f, 14.0f),
  1235. onAccent.withAlpha (channel.muted ? 0.45f : 0.85f));
  1236. }
  1237. // white on the colour (FL), the name's middle dropped when it is too long ("Titey..m #2", FM-14), centred in
  1238. // the room left of the icon and tags as FL centres it (round 190jp: "Synth Bass" on the button's centre line,
  1239. // "Titey Tom" between the left edge and the icon)
  1240. g.setColour (onAccent.withAlpha (channel.muted ? 0.5f : frozen ? 0.7f : 0.92f));
  1241. g.setFont (theme::font (theme::type::body + 1.0f));
  1242. // FL's Channel rack menu › Options › Channel name alignment › Left (round 190kd): the name from the left edge,
  1243. // as LYNX drew it before 190jp
  1244. const auto left = nameAlignLeft;
  1245. const auto rightTrim = rightUsed + iconWidth > 0.0f ? rightUsed + iconWidth + 4.0f : left ? 5.0f : 6.0f;
  1246. const auto textArea = nameArea.withTrimmedLeft (left ? 7.0f : 6.0f).withTrimmedRight (rightTrim);
  1247. textcache::drawText (g, theme::fitMiddle (juce::String::fromUTF8 (channel.name.c_str()), g.getCurrentFont(), textArea.getWidth()), textArea,
  1248. left ? juce::Justification::centredLeft : juce::Justification::centred, false);
  1249. g.setFont (theme::font (theme::type::body));
  1250. }
  1251. // selector: FL's tall slot (round 190io, design190ia FM-13: 12 x 27 with a 2 px outline when selected), here
  1252. // 10 x 24 in the inset colour with a hairline, outlined 2 px in the accent while its channel is selected
  1253. const auto slot = juce::Rectangle<float> ((float) selectLeft() + 1.0f, (float) y + 3.0f, (float) selectWidth - 2.0f, (float) rowHeight - 6.0f);
  1254. // (two filled plates, the rim and the well, from the rounded-rectangle tiles: no stroked path per row)
  1255. theme::fillRoundRect (g, slot, 2.0f, selected ? (hovered (Area::select) ? accentHover : accent) : hovered (Area::select) ? textDisabled : border);
  1256. theme::fillRoundRect (g, slot.reduced (selected ? 2.0f : 1.0f), selected ? 1.0f : 1.5f, bg1);
  1257. const auto pill = slot.reduced (selected ? 3.0f : 2.0f);
  1258. // FL flashes the channel's selector as its note plays (round 170a [SHOT]): the "sound lighting up when it hits"
  1259. // round 190ih: and with every note the channel plays (typing keyboard, MIDI, Piano roll, off-grid notes), bright
  1260. // at note-on, dimmer while held, fading out after the release (FL capture, details190if); orange for a
  1261. // channel locked to a controller ("Receive notes from"; FL's manual: "Orange for locked Channels")
  1262. const auto lit = row < (int) activityLights.size() ? activityLights[(std::size_t) row].level : 0.0f;
  1263. const auto hit = ! channel.muted && channelHitsNow (row);
  1264. if (hit || (! channel.muted && lit > 0.0f))
  1265. {
  1266. const auto top = selected ? 0.75f : 0.9f;
  1267. const auto colour = ! channel.receiveFrom.empty() ? warning : juce::Colours::white;
  1268. theme::fillRoundRect (g, pill, 1.5f, colour.withAlpha (juce::jmax (hit ? top : 0.0f, lit * top)));
  1269. }
  1270. }
  1271. if (! autoRows.empty()) // round 190oo (PAT-7): the automation clip rows' controls and buttons
  1272. paintAutomationButtons (g, column);
  1273. paintLane (g);
  1274. {
  1275. const auto box = racklayout::addChannelBox (nameLeft(), nameWidth, addY, rowHeight);
  1276. const auto addArea = juce::Rectangle<float> ((float) box.x, (float) box.y, (float) box.width, (float) box.height);
  1277. if (g.clipRegionIntersects (addArea.getSmallestIntegerContainer().expanded (1)) || ! ui::paintSavings()) // (round 190ge: a playhead frame repaints the steps only)
  1278. {
  1279. const float dash[] = { 3.0f, 3.0f };
  1280. juce::Path outline, dashed;
  1281. outline.addRoundedRectangle (addArea.reduced (0.5f), theme::radius::md);
  1282. juce::PathStrokeType (1.0f).createDashedStroke (dashed, outline, dash, 2);
  1283. const auto addHovered = hoverArea == Area::addRow;
  1284. g.setColour (addHovered ? textSecondary : borderStrong);
  1285. g.fillPath (dashed);
  1286. g.setColour (addHovered ? textPrimary : textSecondary);
  1287. g.setFont (theme::font (theme::type::small));
  1288. textcache::drawText (g, tr ("+ add channel"), addArea.toNearestInt(), juce::Justification::centred);
  1289. }
  1290. }
  1291. if (stickyX > 0) // steps pass under the column: a hairline marks its edge
  1292. {
  1293. g.setColour (border);
  1294. g.fillRect (gridLeft() - 1, 0, 1, getHeight());
  1295. }
  1296. }
  1297. if (! zipLayout.top.empty())
  1298. paintZipStrips (g);
  1299. if (advancedLoopShown())
  1300. paintLoopColumn (g);
  1301. }
  1302. // --- FL's automation clip channels (round 190oo, design review 2 PAT-7; core/RackAutomation.h) ------------------------
  1303. // FL lists every automation clip as a channel of the rack (Thief: "Volume Duck", "GROSS..w Bass", "CRASH REVERB" between
  1304. // YELP and "Riser..Metal", design190ia shots/ref/fl-channelrack.png). Here they are rows of their own between the channel
  1305. // rows: the channel rows keep their indices, so the selection, the filter groups, the Piano roll's channel, the mixer
  1306. // routing and the steps never see them.
  1307. void ChannelRackComponent::refreshAutomationRows()
  1308. {
  1309. autoRows.clear();
  1310. autoBefore.clear();
  1311. const auto& song = engine.getSong();
  1312. if (song.automations.empty() || ! rackauto::shownUnder (song, filterGroup))
  1313. return;
  1314. autoRows = rackauto::rows (song);
  1315. if (autoRows.empty())
  1316. return;
  1317. // a row inside a zipped strip (round 190mk) goes right below the strip: the strip stays whole
  1318. if (! zipLayout.first.empty())
  1319. {
  1320. const auto count = (int) song.channels.size();
  1321. for (auto& r : autoRows)
  1322. while (r.gap < count && r.gap < (int) zipLayout.first.size() && zipLayout.first[(std::size_t) r.gap] != r.gap)
  1323. ++r.gap;
  1324. std::stable_sort (autoRows.begin(), autoRows.end(), [] (const rackauto::Row& a, const rackauto::Row& b) { return a.gap < b.gap; });
  1325. }
  1326. autoBefore = rackauto::rowsBefore (song, autoRows);
  1327. }
  1328. int ChannelRackComponent::automationRowTop (int i) const
  1329. {
  1330. // the channel rows above its gap (the graph lane and the zipped strips included) and the automation rows before it
  1331. return baseRowY (autoRows[(std::size_t) i].gap) + i * rowHeight;
  1332. }
  1333. int ChannelRackComponent::automationRowAt (int y) const
  1334. {
  1335. for (int i = 0; i < (int) autoRows.size(); ++i)
  1336. {
  1337. const auto top = automationRowTop (i);
  1338. if (y < top)
  1339. return -1; // (top to bottom: the others are lower)
  1340. if (y < top + rowHeight)
  1341. return i;
  1342. }
  1343. return -1;
  1344. }
  1345. juce::Rectangle<int> ChannelRackComponent::automationRowBounds (int automation) const
  1346. {
  1347. for (int i = 0; i < (int) autoRows.size(); ++i)
  1348. if (autoRows[(std::size_t) i].automation == automation)
  1349. return { 0, automationRowTop (i), getWidth(), rowHeight };
  1350. return {};
  1351. }
  1352. // FL draws an automation clip channel's steps as any channel's (idle: LYNX does not start a clip from steps, the triggered
  1353. // playback of details DE-123); the piano roll overview leaves the row empty (a clip has no notes)
  1354. void ChannelRackComponent::paintAutomationSteps (juce::Graphics& g, juce::Rectangle<int> clip)
  1355. {
  1356. if (pianoRollView)
  1357. return;
  1358. using namespace theme::colour;
  1359. const auto steps = shownSteps(), realSteps = numSteps();
  1360. for (int i = 0; i < (int) autoRows.size(); ++i)
  1361. {
  1362. const auto y = automationRowTop (i);
  1363. if (y > clip.getBottom() || y + rowHeight < clip.getY())
  1364. continue;
  1365. for (int start = 0; start < steps; start += 8)
  1366. {
  1367. const auto first = juce::Rectangle<int> (gridLeft() + start * stepWidth + 1, y + 5, stepWidth - 3, rowHeight - 10); // (stepBounds)
  1368. if (first.getX() + 8 * stepWidth < clip.getX() || first.getX() > clip.getRight())
  1369. continue;
  1370. if (start + 8 <= realSteps)
  1371. drawIdleStepStrip (g, first, stepWidth, theme::stepOff (start), theme::stepOff (start + 4), bg2);
  1372. else if (start >= realSteps && start + 8 <= steps)
  1373. theme::drawStepStripOver (g, first, stepWidth, theme::stepOff (start), theme::stepOff (start + 4), true, bg2);
  1374. else
  1375. for (int step = start; step < juce::jmin (start + 8, steps); ++step)
  1376. {
  1377. const auto r = first.withX (gridLeft() + step * stepWidth + 1);
  1378. const auto fill = theme::stepOff (step);
  1379. if (step < realSteps)
  1380. {
  1381. paintKeycap (g, r, fill, false);
  1382. continue;
  1383. }
  1384. theme::fillRoundRect (g, r.toFloat(), keycapRadius, fill.withMultipliedAlpha (0.35f)); // (a ghost step)
  1385. g.setColour (fill.brighter (0.25f).withMultipliedAlpha (0.55f));
  1386. g.drawRoundedRectangle (r.toFloat().reduced (0.5f), keycapRadius, 1.0f);
  1387. }
  1388. }
  1389. }
  1390. }
  1391. // FL's row (fl-channelrack.png rows y 834-894): the mute light on, the two knobs (FL's are the clip's range, minimum and
  1392. // maximum; a LYNX clip spans its target's whole range: 0 and 1), the curve glyph where the mixer track box is, the button
  1393. // in the clip's colour (FL's grey #485156 without one) with the name in white and no icon, the selector's empty slot
  1394. void ChannelRackComponent::paintAutomationButtons (juce::Graphics& g, juce::Rectangle<int> column)
  1395. {
  1396. using namespace theme::colour;
  1397. const auto& song = engine.getSong();
  1398. for (int i = 0; i < (int) autoRows.size(); ++i)
  1399. {
  1400. const auto a = autoRows[(std::size_t) i].automation;
  1401. const auto y = automationRowTop (i);
  1402. if (a < 0 || a >= (int) song.automations.size() || y > column.getBottom() || y + rowHeight < column.getY())
  1403. continue;
  1404. const auto& automation = song.automations[(std::size_t) a];
  1405. if (column.getX() < selectLeft() || ! ui::paintSavings()) // (as the channel rows: a playhead frame skips them)
  1406. {
  1407. g.setColour (theme::muteLed (false));
  1408. g.fillEllipse (juce::Rectangle<float> (9.0f, (float) y + rowHeight / 2.0f - 4.5f, 9.0f, 9.0f));
  1409. const auto knob = [y] (int left) { return juce::Rectangle<float> ((float) left, (float) y, (float) knobWidth, (float) rowHeight).reduced (1.0f, 2.0f); };
  1410. theme::drawKnob (g, knob (muteWidth), 0.0f, false, knobArc, false);
  1411. theme::drawKnob (g, knob (muteWidth + knobWidth), 1.0f, false, knobArc, false);
  1412. if (showMixerSelectors) // FL's curve glyph: two small rings joined by a rising line
  1413. {
  1414. const auto box = juce::Rectangle<float> ((float) (muteWidth + 2 * knobWidth + 1), (float) y + 7.0f, (float) routeWidth - 3.0f, (float) rowHeight - 14.0f);
  1415. const auto centre = box.getCentre();
  1416. const juce::Point<float> low (centre.x - 5.0f, centre.y + 3.5f), high (centre.x + 5.0f, centre.y - 3.5f);
  1417. const auto along = (high - low) / low.getDistanceFrom (high) * 2.0f;
  1418. g.setColour (textSecondary.withAlpha (0.75f));
  1419. g.drawEllipse (juce::Rectangle<float> (4.0f, 4.0f).withCentre (low), 1.0f);
  1420. g.drawEllipse (juce::Rectangle<float> (4.0f, 4.0f).withCentre (high), 1.0f);
  1421. g.drawLine (juce::Line<float> (low + along, high - along), 1.0f);
  1422. }
  1423. const auto nameArea = juce::Rectangle<float> ((float) nameLeft(), (float) y + 3, (float) nameWidth, (float) rowHeight - 6);
  1424. auto fill = theme::colourFill (automation.colour != 0 ? juce::Colour (automation.colour) : juce::Colour (0xff485156), 0.42f, 0.58f);
  1425. if (hoverArea == Area::autoName && hoverRow == a)
  1426. fill = fill.brighter (0.12f);
  1427. theme::fillPlate (g, nameArea, theme::radius::sm, fill.withMultipliedBrightness (1.06f), fill.withMultipliedBrightness (0.94f));
  1428. g.setColour (onAccent.withAlpha (0.92f));
  1429. g.setFont (theme::font (theme::type::body + 1.0f));
  1430. const auto textArea = nameArea.withTrimmedLeft (nameAlignLeft ? 7.0f : 6.0f).withTrimmedRight (nameAlignLeft ? 5.0f : 6.0f);
  1431. const auto name = automation.name.empty() ? tr ("Automation clip") : juce::String::fromUTF8 (automation.name.c_str());
  1432. textcache::drawText (g, theme::fitMiddle (name, g.getCurrentFont(), textArea.getWidth()), textArea,
  1433. nameAlignLeft ? juce::Justification::centredLeft : juce::Justification::centred, false);
  1434. g.setFont (theme::font (theme::type::body));
  1435. }
  1436. const auto slot = juce::Rectangle<float> ((float) selectLeft() + 1.0f, (float) y + 3.0f, (float) selectWidth - 2.0f, (float) rowHeight - 6.0f);
  1437. theme::fillRoundRect (g, slot, 2.0f, border);
  1438. theme::fillRoundRect (g, slot.reduced (1.0f), 1.5f, bg1);
  1439. }
  1440. }
  1441. // Right-click on an automation clip row: what LYNX already does with a clip (the Playlist's automation clip items)
  1442. void ChannelRackComponent::showAutomationMenu (int automation)
  1443. {
  1444. const auto& song = engine.getSong();
  1445. if (automation < 0 || automation >= (int) song.automations.size())
  1446. return;
  1447. const auto& a = song.automations[(std::size_t) automation];
  1448. const auto gap = rackauto::gapOf (song, a);
  1449. const auto count = (int) song.channels.size();
  1450. juce::PopupMenu menu;
  1451. menu.addSectionHeader (a.name.empty() ? tr ("Automation clip") : juce::String::fromUTF8 (a.name.c_str()));
  1452. menu.addItem (tr ("Edit points..."), [this, automation] { openAutomationEditor (engine, automation); });
  1453. menu.addItem (tr ("Rename and color..."), [this, automation] {
  1454. const auto& s = engine.getSong();
  1455. if (automation >= (int) s.automations.size())
  1456. return;
  1457. const auto& clip = s.automations[(std::size_t) automation];
  1458. showNameAndColourDialog (tr ("Rename automation clip"), juce::String::fromUTF8 (clip.name.c_str()), clip.colour,
  1459. [this, automation] (const juce::String& name, std::uint32_t colour) {
  1460. engine.editSong ([automation, text = name.toStdString(), colour] (Song& edited) {
  1461. if (automation < (int) edited.automations.size())
  1462. {
  1463. edited.automations[(std::size_t) automation].name = text;
  1464. edited.automations[(std::size_t) automation].colour = colour;
  1465. }
  1466. });
  1467. });
  1468. });
  1469. menu.addSeparator();
  1470. menu.addItem (tr ("Move up"), gap > 0, false, [this, automation] { engine.editSong ([automation] (Song& s) { rackauto::moveRow (s, automation, -1); }); });
  1471. menu.addItem (tr ("Move down"), gap < count, false, [this, automation] { engine.editSong ([automation] (Song& s) { rackauto::moveRow (s, automation, 1); }); });
  1472. menu.addSeparator();
  1473. menu.addItem (tr ("Delete automation (all of its clips)"), [this, automation] {
  1474. engine.editSong ([automation] (Song& s) { s.removeAutomation (automation); });
  1475. });
  1476. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1477. }
  1478. // The miniature of a channel's piano-roll notes across its step area (FL shows one once a channel has notes
  1479. // that steps can't show); the notes keep their time and length, pitch maps onto the row's height.
  1480. void ChannelRackComponent::paintNotePreview (juce::Graphics& g, int row, const Pattern& pattern, std::uint32_t channelColour)
  1481. {
  1482. using namespace theme::colour;
  1483. const auto steps = numSteps();
  1484. // (the whole pattern in the visible width when it is longer than the rack shows: FL's complete preview)
  1485. const auto place = previewSpan();
  1486. const auto area = juce::Rectangle<float> ((float) (gridLeft() + place.x) + 1.0f, (float) rowY (row) + 4.0f, (float) place.width - 3.0f,
  1487. (float) rowHeight - 8.0f);
  1488. const auto beatWidth = (float) place.width * 4.0f / (float) steps;
  1489. const auto hoveredHere = hoverArea == Area::grid && hoverRow == row;
  1490. theme::fillRoundRect (g, area, theme::radius::sm, hoveredHere ? bg4 : bg1);
  1491. for (int beat = 4; beat < steps; beat += 4) // beat lines, bars a little stronger (bars only once beats crowd)
  1492. {
  1493. if (beat % 16 != 0 && beatWidth < 8.0f)
  1494. continue;
  1495. g.setColour (beat % 16 == 0 ? border.brighter (0.2f) : border);
  1496. g.fillRect (area.getX() + beatWidth * (float) (beat / 4) - 1.5f, area.getY() + 2.0f, 1.0f, area.getHeight() - 4.0f);
  1497. }
  1498. const auto [low, high] = channelKeyRange (pattern, row);
  1499. const auto span = juce::jmax (high - low, 6); // a single key sits mid-row, not on an edge
  1500. const auto lowKey = low - (span - (high - low)) / 2;
  1501. const auto inner = area.reduced (1.0f, 3.0f);
  1502. const auto noteHeight = juce::jlimit (3.0f, 5.0f, inner.getHeight() / (float) (span + 1));
  1503. const auto ticks = (float) (steps * ticksPerStep);
  1504. const auto tint = channelColour != 0 ? theme::tame (juce::Colour (channelColour)).brighter (0.6f) : stepNote;
  1505. // a looping row (round 165f-rack): the notes before the loop point, then their repeats faint; a note of its own past
  1506. // the loop point doesn't play (dim)
  1507. const auto loopTicks = (std::int64_t) loopStepsOf (row) * ticksPerStep;
  1508. const auto patternTicks = (std::int64_t) steps * ticksPerStep;
  1509. for (const auto& n : pattern.notes)
  1510. {
  1511. if (n.channel != row)
  1512. continue;
  1513. const auto pastLoop = loopTicks > 0 && n.start >= loopTicks;
  1514. const auto repeats = loopTicks > 0 && ! pastLoop ? (int) ((patternTicks - n.start + loopTicks - 1) / loopTicks) : 1;
  1515. for (int k = 0; k < repeats; ++k)
  1516. {
  1517. const auto start = n.start + k * loopTicks;
  1518. const auto x = inner.getX() + inner.getWidth() * (float) start / ticks;
  1519. if (x > inner.getRight())
  1520. break;
  1521. const auto w = juce::jmax (2.0f, inner.getWidth() * (float) n.length / ticks - 1.0f);
  1522. const auto y = inner.getBottom() - noteHeight - (inner.getHeight() - noteHeight) * (float) (n.key - lowKey) / (float) span;
  1523. g.setColour (n.muted || pastLoop ? textDisabled.withAlpha (pastLoop ? 0.5f : 1.0f) : k > 0 ? tint.withAlpha (0.4f) : tint);
  1524. g.fillRect (juce::Rectangle<float> (x, y, juce::jmin (w, inner.getRight() - x), noteHeight));
  1525. }
  1526. }
  1527. // round 190mk (DE-33, capture 190mk A2.3; FL's option "Show a mute button on the piano roll preview", on): a round
  1528. // mute button in the preview's middle while it is hovered; a muted channel's preview dims and keeps the crossed icon
  1529. const auto muted = row >= 0 && row < (int) engine.getSong().channels.size() && engine.getSong().channels[(std::size_t) row].muted;
  1530. if (muted)
  1531. {
  1532. g.setColour (bg1.withAlpha (0.55f));
  1533. g.fillRect (area);
  1534. }
  1535. if (previewMuteButton && (hoveredHere || muted))
  1536. {
  1537. const auto b = previewMuteBounds (row).toFloat();
  1538. const auto hot = hoveredHere && b.contains (getMouseXYRelative().toFloat());
  1539. g.setColour (hot ? bg5 : bg3);
  1540. g.fillEllipse (b);
  1541. g.setColour (border);
  1542. g.drawEllipse (b.reduced (0.5f), 1.0f);
  1543. // a speaker: box and cone, then sound waves (on) or a cross (muted)
  1544. const auto c = b.getCentre();
  1545. const auto u = b.getWidth() / 18.0f;
  1546. juce::Path speaker;
  1547. speaker.startNewSubPath (c.x - 5.0f * u, c.y - 2.0f * u);
  1548. speaker.lineTo (c.x - 2.5f * u, c.y - 2.0f * u);
  1549. speaker.lineTo (c.x + 0.5f * u, c.y - 5.0f * u);
  1550. speaker.lineTo (c.x + 0.5f * u, c.y + 5.0f * u);
  1551. speaker.lineTo (c.x - 2.5f * u, c.y + 2.0f * u);
  1552. speaker.lineTo (c.x - 5.0f * u, c.y + 2.0f * u);
  1553. speaker.closeSubPath();
  1554. g.setColour (muted ? textSecondary : textPrimary);
  1555. g.fillPath (speaker);
  1556. if (muted)
  1557. {
  1558. g.drawLine (c.x + 2.0f * u, c.y - 2.5f * u, c.x + 5.5f * u, c.y + 2.5f * u, 1.2f * u);
  1559. g.drawLine (c.x + 2.0f * u, c.y + 2.5f * u, c.x + 5.5f * u, c.y - 2.5f * u, 1.2f * u);
  1560. }
  1561. else
  1562. {
  1563. juce::Path wave;
  1564. wave.addCentredArc (c.x + 0.5f * u, c.y, 3.5f * u, 3.5f * u, 0.0f, 0.6f, 2.55f, true);
  1565. g.strokePath (wave, juce::PathStrokeType (1.1f * u));
  1566. }
  1567. }
  1568. }
  1569. juce::Rectangle<int> ChannelRackComponent::previewMuteBounds (int row) const
  1570. {
  1571. const auto place = previewSpan();
  1572. const auto centre = juce::Point<int> (gridLeft() + place.x + place.width / 2, rowY (row) + rowHeight / 2);
  1573. return juce::Rectangle<int> (18, 18).withCentre (centre);
  1574. }
  1575. // --- the control contract for the knobs and the route box ----------------------------------------
  1576. ui::ValueSpec ChannelRackComponent::specFor (Area area, int row) const
  1577. {
  1578. const auto name = channelName (engine.getSong(), row);
  1579. if (area == Area::pan)
  1580. {
  1581. auto spec = ui::panSpec (name + " - " + tr ("Pan"));
  1582. spec.target = AutomationTarget { AutomationTargetKind::channelPan, row };
  1583. return spec;
  1584. }
  1585. if (area == Area::volume)
  1586. {
  1587. auto spec = ui::percentSpec (name + " - " + tr ("Volume"), 0.78);
  1588. spec.target = AutomationTarget { AutomationTargetKind::channelVolume, row };
  1589. return spec;
  1590. }
  1591. // route box: the mixer insert, as a number
  1592. ui::ValueSpec spec;
  1593. spec.name = name + " - " + tr ("Target mixer track");
  1594. spec.maximum = maxMixerTracks - 1; // every insert, like FL (round 162: the inserts past the mixer's last one are added)
  1595. spec.interval = 1.0;
  1596. spec.toText = [] (double v) { return v < 0.5 ? tr ("Master") : tr ("Insert {0}", { juce::String (juce::roundToInt (v)) }); };
  1597. spec.fromText = [] (const juce::String& t) -> std::optional<double> {
  1598. if (t.trim().startsWithIgnoreCase ("m"))
  1599. return 0.0;
  1600. const auto digits = t.retainCharacters ("0123456789");
  1601. return digits.isEmpty() ? std::nullopt : std::optional<double> (digits.getDoubleValue());
  1602. };
  1603. return ui::digitWheel (spec); // FL's channel rack mixer-track digiwheel (round 168s)
  1604. }
  1605. double ChannelRackComponent::valueOf (Area area, int row) const
  1606. {
  1607. const auto& c = engine.getSong().channels[(std::size_t) row];
  1608. return area == Area::pan ? c.pan : area == Area::volume ? c.volume : (double) c.mixerTrack;
  1609. }
  1610. void ChannelRackComponent::setValue (Area area, int row, double value)
  1611. {
  1612. if (row < 0 || row >= (int) engine.getSong().channels.size())
  1613. return;
  1614. if (area == Area::pan)
  1615. engine.editLevels ([row, v = (float) value] (Song& s) { s.channels[(std::size_t) row].pan = v; });
  1616. else if (area == Area::volume)
  1617. engine.editLevels ([row, v = (float) value] (Song& s) { s.channels[(std::size_t) row].volume = v; });
  1618. else if (area == Area::route)
  1619. {
  1620. const auto track = juce::roundToInt (value);
  1621. if (track != engine.getSong().channels[(std::size_t) row].mixerTrack)
  1622. engine.editSong ([row, track] (Song& s) { mixerops::routeChannel (s, row, track); });
  1623. }
  1624. }
  1625. juce::Rectangle<int> ChannelRackComponent::controlBounds (Area area, int row) const
  1626. {
  1627. const auto y = rowY (row);
  1628. switch (area)
  1629. {
  1630. case Area::pan: return { muteWidth, y, knobWidth, rowHeight };
  1631. case Area::volume: return { muteWidth + knobWidth, y, knobWidth, rowHeight };
  1632. case Area::route: return showMixerSelectors ? juce::Rectangle<int> { muteWidth + 2 * knobWidth + 1, y + 7, routeWidth - 3, rowHeight - 14 } : juce::Rectangle<int>();
  1633. case Area::lane:
  1634. {
  1635. const auto lane = laneBounds();
  1636. const auto step = juce::jmax (0, hoverStep);
  1637. return { gridLeft() + step * stepWidth, lane.getY() + 6, stepWidth, lane.getHeight() - 12 };
  1638. }
  1639. default: return {};
  1640. }
  1641. }
  1642. void ChannelRackComponent::showTip (Area area, int row, bool transient)
  1643. {
  1644. if (row < 0 || row >= (int) engine.getSong().channels.size())
  1645. return;
  1646. const auto spec = specFor (area, row);
  1647. const auto text = spec.text (valueOf (area, row));
  1648. ui::postHint (ui::valueHint (spec, valueOf (area, row), ui::valueGestures()));
  1649. const auto bounds = area == Area::lane ? controlBounds (area, row) : controlBounds (area, row).translated (stickyX, 0);
  1650. if (transient)
  1651. ui::flashValueTip (*this, bounds, text);
  1652. else
  1653. ui::showValueTip (*this, bounds, text);
  1654. }
  1655. void ChannelRackComponent::setHover (Area area, int row, int step)
  1656. {
  1657. if (area == hoverArea && row == hoverRow && step == hoverStep)
  1658. return;
  1659. auto dirty = [this] (Area a, int r) {
  1660. if (a == Area::lane || a == Area::laneLevels)
  1661. repaint (laneBounds());
  1662. else if (a == Area::addRow)
  1663. repaint (rowBounds ((int) engine.getSong().channels.size()));
  1664. else if (a == Area::autoName || a == Area::autoRow) // (round 190oo: `r` is an automation)
  1665. repaint (automationRowBounds (r));
  1666. else if (r >= 0)
  1667. repaint (rowBounds (r));
  1668. };
  1669. dirty (hoverArea, hoverRow);
  1670. hoverArea = area;
  1671. hoverRow = row;
  1672. hoverStep = step;
  1673. dirty (hoverArea, hoverRow);
  1674. }
  1675. void ChannelRackComponent::mouseMove (const juce::MouseEvent& e)
  1676. {
  1677. int row = 0;
  1678. const auto area = areaAt (e.x, e.y, row);
  1679. const auto step = area == Area::grid || area == Area::lane ? (e.x - gridLeft()) / stepWidth : -1;
  1680. setHover (area, row, step >= 0 && step < (area == Area::grid ? shownSteps() : numSteps()) ? step : -1);
  1681. }
  1682. void ChannelRackComponent::mouseExit (const juce::MouseEvent&)
  1683. {
  1684. setHover (Area::none, -1, -1);
  1685. }
  1686. void ChannelRackComponent::setSwingMixOfSelected (int channel)
  1687. {
  1688. const auto& song = engine.getSong();
  1689. if (channel < 0 || channel >= (int) song.channels.size())
  1690. return;
  1691. auto spec = ui::percentSpec (channelName (song, channel) + " - " + tr ("Swing mix"), 1.0);
  1692. const auto rows = engine.getSelectedChannels();
  1693. ui::typeValue (*this, spec, song.channels[(std::size_t) channel].swingMix, [this, rows, channel] (double v) {
  1694. engine.editSong ([rows, channel, v] (Song& s) {
  1695. auto targets = rows;
  1696. if (std::find (targets.begin(), targets.end(), channel) == targets.end())
  1697. targets = { channel };
  1698. for (auto r : targets)
  1699. if (r >= 0 && r < (int) s.channels.size())
  1700. s.channels[(std::size_t) r].swingMix = (float) v;
  1701. });
  1702. });
  1703. }
  1704. // --- selection -----------------------------------------------------------------------------------
  1705. void ChannelRackComponent::selectRows (std::vector<int> rows, int primary)
  1706. {
  1707. engine.setChannelSelection (std::move (rows), primary);
  1708. repaint();
  1709. }
  1710. void ChannelRackComponent::clickSelector (int row, const juce::ModifierKeys& mods)
  1711. {
  1712. ChannelSelection selection;
  1713. selection.rows = engine.getSelectedChannels();
  1714. selection.anchor = selectionAnchor;
  1715. if (mods.isShiftDown())
  1716. selection.extendTo (row);
  1717. else if (flmods::ctrl (mods) || flmods::popup (mods))
  1718. selection.toggle (row);
  1719. else
  1720. selection.selectOnly (row);
  1721. selectionAnchor = selection.anchor;
  1722. const auto primary = selection.contains (row) ? row : selection.rows.front();
  1723. selectRows (selection.rows, primary);
  1724. }
  1725. void ChannelRackComponent::selectRelative (int delta, bool extend)
  1726. {
  1727. const auto count = (int) engine.getSong().channels.size();
  1728. if (count == 0)
  1729. return;
  1730. const auto row = juce::jlimit (0, count - 1, engine.getSelectedChannel() + delta);
  1731. if (extend)
  1732. {
  1733. ChannelSelection selection;
  1734. selection.anchor = selectionAnchor;
  1735. selection.extendTo (row);
  1736. selectRows (selection.rows, row);
  1737. }
  1738. else
  1739. {
  1740. selectionAnchor = row;
  1741. selectRows ({ row }, row);
  1742. }
  1743. }
  1744. void ChannelRackComponent::selectAll()
  1745. {
  1746. ChannelSelection selection;
  1747. selection.selectAll ((int) engine.getSong().channels.size());
  1748. selectRows (selection.rows, engine.getSelectedChannel());
  1749. }
  1750. bool ChannelRackComponent::moveSelected (int delta)
  1751. {
  1752. auto rows = engine.getSelectedChannels();
  1753. const auto primary = engine.getSelectedChannel();
  1754. const auto primaryIndex = (int) (std::find (rows.begin(), rows.end(), primary) - rows.begin());
  1755. bool moved = false;
  1756. std::vector<int> after;
  1757. // round 190oo (PAT-7): FL moves channels past an automation clip channel as past any channel: an automation clip row
  1758. // right next to the selected block goes to its other side, the channels keep their rows (core/RackAutomation.h)
  1759. if (! autoRows.empty())
  1760. if (const auto pass = rackauto::passFor (engine.getSong(), rows, delta); pass.first >= 0)
  1761. {
  1762. engine.editSong ([pass] (Song& s) {
  1763. if (pass.first < (int) s.automations.size())
  1764. s.automations[(std::size_t) pass.first].rackSlot = pass.second;
  1765. });
  1766. updateSize();
  1767. repaint();
  1768. return true;
  1769. }
  1770. engine.editSongStructural ([&] (Song& s) {
  1771. after = rows;
  1772. moved = moveChannels (s, after, delta);
  1773. });
  1774. if (! moved)
  1775. return false;
  1776. const auto newPrimary = primaryIndex < (int) after.size() ? after[(std::size_t) primaryIndex] : after.front();
  1777. openEditorRow = -1;
  1778. selectionAnchor = juce::jlimit (0, (int) engine.getSong().channels.size() - 1, selectionAnchor + delta);
  1779. selectRows (after, newPrimary);
  1780. return true;
  1781. }
  1782. void ChannelRackComponent::cloneSelected()
  1783. {
  1784. auto rows = engine.getSelectedChannels();
  1785. std::vector<int> clones;
  1786. engine.editSong ([&] (Song& s) {
  1787. // from the bottom up, so earlier clones don't shift the rows still to clone
  1788. for (auto it = rows.rbegin(); it != rows.rend(); ++it)
  1789. cloneChannel (s, *it);
  1790. });
  1791. // each clone sits right below its original: original i (sorted) ends at rows[i] + i, its clone one below
  1792. for (std::size_t i = 0; i < rows.size(); ++i)
  1793. clones.push_back (rows[i] + (int) i + 1);
  1794. if (! clones.empty())
  1795. selectRows (clones, clones.front());
  1796. }
  1797. void ChannelRackComponent::deleteSelected()
  1798. {
  1799. const auto rows = engine.getSelectedChannels();
  1800. const auto count = (int) engine.getSong().channels.size();
  1801. if (rows.empty() || (int) rows.size() >= count) // at least one channel stays
  1802. return;
  1803. for (auto r : rows)
  1804. closeEditor (r);
  1805. engine.editSong ([rows] (Song& s) { removeChannels (s, rows); });
  1806. openEditorRow = -1;
  1807. const auto row = juce::jlimit (0, juce::jmax (0, (int) engine.getSong().channels.size() - 1), rows.front());
  1808. selectRows ({ row }, row);
  1809. }
  1810. void ChannelRackComponent::sendSelectedToInserts()
  1811. {
  1812. const auto rows = engine.getSelectedChannels();
  1813. engine.editSong ([rows] (Song& s) { sendChannelsToFreeInserts (s, rows); });
  1814. }
  1815. void ChannelRackComponent::toggleMute (int channel)
  1816. {
  1817. if (channel >= 0 && channel < (int) engine.getSong().channels.size())
  1818. engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].muted = ! s.channels[(std::size_t) channel].muted; });
  1819. }
  1820. void ChannelRackComponent::toggleSoloLock (int channel)
  1821. {
  1822. if (channel >= 0 && channel < (int) engine.getSong().channels.size())
  1823. engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].soloLock = ! s.channels[(std::size_t) channel].soloLock; });
  1824. }
  1825. void ChannelRackComponent::solo (int row)
  1826. {
  1827. if (row < 0 || row >= (int) engine.getSong().channels.size())
  1828. return;
  1829. // only this channel plays (the channels with "Lock active/mute state" keep theirs); repeating on the soloed channel
  1830. // unmutes them (FL's channel solo, REA_rodada167l §5)
  1831. // (round 190bx: FL's General › "Restore previous state after solo" — the un-solo then puts back the mute switches
  1832. // from before the solo; core/FlSettings.h)
  1833. engine.editSong ([row] (Song& s) {
  1834. noteedit::soloChannel (s, row, &flsettings::channelSoloMemory(), flsettings::options().restoreStateAfterSolo.load());
  1835. });
  1836. }
  1837. // --- channel editors ---------------------------------------------------------------------------
  1838. bool ChannelRackComponent::isEditorOpen (int channel)
  1839. {
  1840. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  1841. return false;
  1842. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::plugin)
  1843. {
  1844. if (auto* plugin = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get()))
  1845. return PluginWindows::isOpen (plugin->getInstance());
  1846. return false;
  1847. }
  1848. return isChannelSettingsOpen (channel);
  1849. }
  1850. void ChannelRackComponent::closeEditor (int channel)
  1851. {
  1852. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  1853. return;
  1854. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::plugin)
  1855. {
  1856. if (auto* plugin = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get()))
  1857. PluginWindows::close (plugin->getInstance());
  1858. }
  1859. else
  1860. closeChannelSettings (channel);
  1861. }
  1862. // --- Freeze (round 190ay) -----------------------------------------------------------------------------------------------
  1863. ui::Hint ChannelRackComponent::getChannelHintForSnapshot (int channel)
  1864. {
  1865. return hintAt ({ stickyX + nameLeft() + nameWidth / 2, rowY (channel) + rowHeight / 2 });
  1866. }
  1867. juce::String ChannelRackComponent::frozenHint (int channel)
  1868. {
  1869. if (engine.frozenAudioMissing (channel))
  1870. return tr ("Frozen, but its audio files are missing: the instrument plays instead. [RMB] Re-freeze or Unfreeze");
  1871. if (engine.freezeOutOfDate (channel))
  1872. return tr ("Frozen, out of date (changed since the freeze): the old audio plays. [RMB] Re-freeze"); // (round 190bj: shorter, the action fits the bar)
  1873. return tr ("Frozen: its rendered audio plays and its instrument is unloaded (no CPU, no RAM). [RMB] Unfreeze to edit");
  1874. }
  1875. bool ChannelRackComponent::refuseFrozenEdit (int channel)
  1876. {
  1877. const auto& song = engine.getSong();
  1878. if (channel < 0 || channel >= (int) song.channels.size() || ! song.channels[(std::size_t) channel].freeze.on())
  1879. return false;
  1880. ui::postNotice ({ tr ("{0} is frozen: Unfreeze to edit ([RMB] on the channel, Unfreeze)", { channelName (song, channel) }), {} }, 3000);
  1881. return true;
  1882. }
  1883. void ChannelRackComponent::freezeChannels (std::vector<std::uint64_t> uids)
  1884. {
  1885. // round 190bj (QA: "Freeze selected channels" stopped at the first channel that can't be frozen with "Can't freeze
  1886. // this channel", not saying which): with several, the ones that can't are named with their reason and the others
  1887. // are frozen, as the selection's Unfreeze treats each channel on its own
  1888. if (uids.size() > 1)
  1889. {
  1890. const auto& song = engine.getSong();
  1891. juce::StringArray refused;
  1892. std::vector<std::uint64_t> go;
  1893. for (const auto uid : uids)
  1894. {
  1895. const auto it = std::find_if (song.channels.begin(), song.channels.end(), [uid] (const ChannelDef& c) { return c.uid == uid && uid != 0; });
  1896. if (it == song.channels.end())
  1897. continue;
  1898. if (const auto why = freezeRefusal (engine, (int) (it - song.channels.begin())); why.isNotEmpty())
  1899. refused.add (juce::String::fromUTF8 (it->name.c_str()) + ": " + why);
  1900. else
  1901. go.push_back (uid);
  1902. }
  1903. if (! refused.isEmpty())
  1904. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Some selected channels can't be frozen"),
  1905. refused.joinIntoString ("\n\n")
  1906. + (go.empty() ? juce::String() : "\n\n" + tr ("The other selected channels are frozen.")));
  1907. uids = std::move (go);
  1908. }
  1909. while (! uids.empty())
  1910. {
  1911. const auto uid = uids.front();
  1912. uids.erase (uids.begin());
  1913. const auto& channels = engine.getSong().channels;
  1914. const auto it = std::find_if (channels.begin(), channels.end(), [uid] (const ChannelDef& c) { return c.uid == uid && uid != 0; });
  1915. if (it == channels.end())
  1916. continue;
  1917. const auto channel = (int) (it - channels.begin());
  1918. if (openEditorRow == channel) // (freezeChannel closes the channel's windows)
  1919. openEditorRow = -1;
  1920. freezeChannel (engine, channel, [safe = juce::Component::SafePointer<ChannelRackComponent> (this), uids] (bool ok) {
  1921. if (safe == nullptr)
  1922. return;
  1923. safe->repaint();
  1924. if (ok && ! uids.empty()) // (a refusal or Cancel stops the rest)
  1925. safe->freezeChannels (uids);
  1926. });
  1927. return;
  1928. }
  1929. }
  1930. void ChannelRackComponent::toggleEditor (int channel, bool keepOthers)
  1931. {
  1932. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  1933. return;
  1934. if (refuseFrozenEdit (channel)) // (its instrument is not loaded: there is nothing to show or change)
  1935. return;
  1936. const auto kind = engine.getSong().channels[(std::size_t) channel].instrument;
  1937. if (kind == InstrumentKind::patcher) // its node graph editor (REA_rodada141)
  1938. {
  1939. if (PatcherWindows::isChannelOpen (channel))
  1940. PatcherWindows::closeChannel (channel);
  1941. else
  1942. PatcherWindows::openChannel (engine, channel);
  1943. return;
  1944. }
  1945. // built-in drums and audio clips have no instrument page: as in FL, the click opens their channel window anyway
  1946. // (header + Misc tab — levels, polyphony, cut groups, arpeggiator), as the hint says; it only selected (round 165q)
  1947. if (isEditorOpen (channel))
  1948. {
  1949. closeEditor (channel);
  1950. if (openEditorRow == channel)
  1951. openEditorRow = -1;
  1952. return;
  1953. }
  1954. if (! keepOthers && ! keepEditorsOpen && openEditorRow != channel)
  1955. closeEditor (openEditorRow);
  1956. if (kind == InstrumentKind::plugin)
  1957. openPluginWindow (channel);
  1958. else
  1959. openChannelSettings (engine, channel);
  1960. openEditorRow = channel;
  1961. }
  1962. // --- step graph lanes (docs/WORKFLOW_FL.md P2, C4) --------------------------------------------------
  1963. juce::Rectangle<int> ChannelRackComponent::levelButtonBounds (int tab) const
  1964. {
  1965. const auto lane = laneBounds();
  1966. const auto width = (gridLeft() - 24) / 3;
  1967. return { 12 + (tab % 3) * width, lane.getY() + 6 + (tab / 3) * 22, width - 4, 19 };
  1968. }
  1969. void ChannelRackComponent::paintLane (juce::Graphics& g)
  1970. {
  1971. using namespace theme::colour;
  1972. const auto lane = laneBounds();
  1973. if (lane.isEmpty() || ! g.getClipBounds().intersects (lane))
  1974. return;
  1975. const auto& song = engine.getSong();
  1976. const auto& pattern = song.activePattern();
  1977. const auto channel = graphRow();
  1978. const auto level = (notetools::Level) graphLevel;
  1979. g.setColour (bg0);
  1980. g.fillRect (lane);
  1981. g.setColour (border);
  1982. g.drawHorizontalLine (lane.getY(), 0.0f, (float) getWidth());
  1983. g.drawHorizontalLine (lane.getBottom() - 1, 0.0f, (float) getWidth());
  1984. // FL's nine lanes in FL's order (issue #208); like FL, a narrow tab takes the shorter name
  1985. for (int tab = 0; tab < notetools::stepLevelCount; ++tab)
  1986. {
  1987. const auto l = (int) notetools::stepLevel (tab);
  1988. const auto r = levelButtonBounds (tab).toFloat();
  1989. theme::fillRoundRect (g, r, theme::radius::sm, l == graphLevel ? accent : bg4);
  1990. g.setColour (l == graphLevel ? onAccent : textSecondary);
  1991. const auto font = theme::font (theme::type::caption, l == graphLevel);
  1992. g.setFont (font);
  1993. auto name = tr (notetools::stepLevelName (tab, 2));
  1994. for (int size = 1; size >= 0 && juce::GlyphArrangement::getStringWidth (font, name) > r.getWidth() - 6.0f; --size)
  1995. name = tr (notetools::stepLevelName (tab, size));
  1996. textcache::drawFittedText (g, name, r.toNearestInt(), juce::Justification::centred, 1, 0.8f);
  1997. }
  1998. g.setColour (textDisabled);
  1999. g.setFont (theme::font (theme::type::caption));
  2000. textcache::drawFittedText (g, tr ("Drag: set · Ctrl+drag: scale all · Right-drag: ramp · Alt+click: reset"),
  2001. juce::Rectangle<int> (12, lane.getBottom() - 20, gridLeft() - 24, 16), juce::Justification::centredLeft, 1, 0.8f);
  2002. const auto top = (float) lane.getY() + 6.0f, bottom = (float) lane.getBottom() - 6.0f;
  2003. const auto bipolar = notetools::graphIsBipolar (graphLevel);
  2004. const auto base = bipolar ? (top + bottom) * 0.5f : bottom;
  2005. if (level == notetools::Level::notePitch) // FL's piano-roll rows: the black keys darker, the C rows named
  2006. {
  2007. const auto [lo, hi] = pitchLaneKeys();
  2008. const auto rowH = (bottom - top) / (float) (hi - lo + 1);
  2009. for (int key = lo; key <= hi; ++key)
  2010. {
  2011. const auto y = bottom - (float) (key - lo + 1) * rowH;
  2012. if (juce::MidiMessage::isMidiNoteBlack (key))
  2013. {
  2014. g.setColour (bg1);
  2015. g.fillRect (juce::Rectangle<float> ((float) gridLeft(), y, (float) (numSteps() * stepWidth), rowH));
  2016. }
  2017. if (key % 12 == 0 && rowH * 3.0f >= 9.0f)
  2018. {
  2019. g.setColour (textDisabled);
  2020. g.setFont (theme::font (theme::type::caption));
  2021. textcache::drawText (g, juce::String (notetools::levelText (level, (float) key / 127.0f)),
  2022. juce::Rectangle<int> (gridLeft() + 2, (int) (y + rowH - 10.0f), 28, 10), juce::Justification::bottomLeft);
  2023. }
  2024. }
  2025. }
  2026. for (int step = 0; step < numSteps(); ++step)
  2027. {
  2028. const auto x = (float) (gridLeft() + step * stepWidth + 1);
  2029. const auto w = (float) stepWidth - 3.0f;
  2030. if (step % 4 == 0 && step > 0)
  2031. {
  2032. g.setColour (step % 16 == 0 ? gridBar : gridBeat);
  2033. g.drawVerticalLine ((int) x - 2, top, bottom);
  2034. }
  2035. if (hoverArea == Area::lane && hoverStep == step)
  2036. {
  2037. g.setColour (bg3);
  2038. g.fillRect (juce::Rectangle<float> (x, top, w, bottom - top));
  2039. }
  2040. const auto notes = notesInStep (pattern, channel, step);
  2041. if (notes.empty())
  2042. {
  2043. g.setColour (theme::stepOff (step));
  2044. g.fillRect (x + w * 0.5f - 1.0f, base - 1.0f, 2.0f, 2.0f);
  2045. continue;
  2046. }
  2047. const auto& first = pattern.notes[(std::size_t) notes.front()];
  2048. if (level == notetools::Level::notePitch) // FL: a block at the step's key, named
  2049. {
  2050. const auto [lo, hi] = pitchLaneKeys();
  2051. const auto rowH = (bottom - top) / (float) (hi - lo + 1);
  2052. const auto block = juce::Rectangle<float> (x + 1.0f, bottom - (float) (first.key - lo + 1) * rowH, w - 2.0f, juce::jmax (3.0f, rowH));
  2053. g.setColour (info.withAlpha (0.85f));
  2054. g.fillRoundedRectangle (block, 1.5f);
  2055. if (block.getHeight() >= 9.0f && block.getWidth() >= 14.0f)
  2056. {
  2057. g.setColour (bg0);
  2058. g.setFont (theme::font (theme::type::caption));
  2059. textcache::drawFittedText (g, juce::String (notetools::levelText (level, (float) first.key / 127.0f)), block.toNearestInt(),
  2060. juce::Justification::centred, 1, 0.6f);
  2061. }
  2062. continue;
  2063. }
  2064. if (level == notetools::Level::repeat) // FL: a block at the rate's height, a line for each extra strike in a step
  2065. {
  2066. if (first.repeat <= 7)
  2067. continue; // (no second strike inside a step: FL draws nothing)
  2068. const auto rowH = (bottom - top) / 8.0f;
  2069. const auto block = juce::Rectangle<float> (x + 1.0f, bottom - (float) (first.repeat - 6) * rowH, w - 2.0f, rowH);
  2070. g.setColour (info.withAlpha (0.85f));
  2071. g.fillRoundedRectangle (block, 1.5f);
  2072. const auto strikes = noterepeat::strikeCount (first, ticksPerStep);
  2073. g.setColour (bg0.withAlpha (0.55f));
  2074. for (int k = 1; k < strikes; ++k)
  2075. g.fillRect (block.getX() + 3.0f, block.getY() + block.getHeight() * (float) k / (float) strikes - 0.5f, block.getWidth() - 6.0f, 1.0f);
  2076. continue;
  2077. }
  2078. const auto v = notetools::levelValue (first, level);
  2079. const auto y = bottom - v * (bottom - top);
  2080. g.setColour ((graphLevel == (int) notetools::Level::velocity ? accent : info).withAlpha (0.85f));
  2081. g.fillRect (juce::Rectangle<float> (x + 2.0f, juce::jmin (y, base), w - 4.0f, juce::jmax (2.0f, std::abs (base - y))));
  2082. g.setColour (textPrimary);
  2083. g.fillRect (x + 1.0f, y - 1.0f, w - 2.0f, 2.0f);
  2084. }
  2085. if (bipolar)
  2086. {
  2087. g.setColour (gridBar);
  2088. g.drawHorizontalLine ((int) base, (float) gridLeft(), (float) getWidth());
  2089. }
  2090. }
  2091. // FL's Note pitch lane is a small piano roll (issue #208, FL 2026 shot fl-note): the keys from a little below the
  2092. // channel's lowest step to a little above its highest (two octaves at least), each step a block at its key
  2093. std::pair<int, int> ChannelRackComponent::pitchLaneKeys() const
  2094. {
  2095. const auto& pattern = engine.getSong().activePattern();
  2096. const auto channel = graphRow();
  2097. int lo = 127, hi = 0;
  2098. for (const auto& n : pattern.notes)
  2099. if (n.channel == channel)
  2100. lo = juce::jmin (lo, n.key), hi = juce::jmax (hi, n.key);
  2101. if (lo > hi)
  2102. lo = hi = 60;
  2103. const auto middle = (lo + hi) / 2;
  2104. lo = juce::jmin (lo - 2, middle - 12);
  2105. hi = juce::jmax (hi + 2, middle + 12);
  2106. if (lo < 0)
  2107. hi -= lo, lo = 0;
  2108. if (hi > 127)
  2109. lo = juce::jmax (0, lo - (hi - 127)), hi = 127;
  2110. return { lo, hi };
  2111. }
  2112. float ChannelRackComponent::laneValueAt (int y) const
  2113. {
  2114. const auto lane = laneBounds();
  2115. const auto top = (float) lane.getY() + 6.0f, bottom = (float) lane.getBottom() - 6.0f;
  2116. const auto t = juce::jlimit (0.0f, 1.0f, (bottom - (float) y) / juce::jmax (1.0f, bottom - top));
  2117. const auto level = (notetools::Level) graphLevel;
  2118. if (level == notetools::Level::notePitch) // (the key row under the mouse)
  2119. {
  2120. const auto [lo, hi] = pitchLaneKeys();
  2121. return (float) juce::jlimit (0, 127, lo + (int) std::floor (t * (float) (hi - lo + 1))) / 127.0f;
  2122. }
  2123. if (level == notetools::Level::repeat) // FL's lane: 1/16 (one strike a step) at the bottom .. 1/64 triplet at the top
  2124. {
  2125. const auto index = juce::jlimit (7, noterepeat::rateCount, 7 + (int) std::floor (t * 8.0f));
  2126. return index <= 7 ? 0.0f : (float) index / (float) noterepeat::rateCount;
  2127. }
  2128. return t;
  2129. }
  2130. juce::Point<int> ChannelRackComponent::laneSpotForSnapshot (int step, float value) const
  2131. {
  2132. const auto lane = laneBounds();
  2133. const auto top = (float) lane.getY() + 6.0f, bottom = (float) lane.getBottom() - 6.0f;
  2134. return { gridLeft() + step * stepWidth + stepWidth / 2, juce::roundToInt (bottom - value * (bottom - top)) };
  2135. }
  2136. void ChannelRackComponent::setLaneValue (int step, float value)
  2137. {
  2138. const auto channel = graphRow();
  2139. const auto level = (notetools::Level) graphLevel;
  2140. engine.editSong ([channel, step, value, level] (Song& s) {
  2141. auto& p = s.activePattern();
  2142. for (auto i : notesInStep (p, channel, step))
  2143. notetools::setLevelValue (p.notes[(std::size_t) i], level, value);
  2144. if (level == notetools::Level::shift) // (Shift moves the notes inside their step)
  2145. p.sortNotes();
  2146. });
  2147. }
  2148. void ChannelRackComponent::applyLane (const juce::MouseEvent& e)
  2149. {
  2150. const auto steps = numSteps();
  2151. const auto step = juce::jlimit (0, steps - 1, (e.x - gridLeft()) / stepWidth);
  2152. const auto value = laneValueAt (e.y);
  2153. if (laneScaleBase >= 0.0f) // round 190lx (DE-31): Ctrl scales every column (bipolar lanes about their centre)
  2154. {
  2155. const auto level = graphLevel;
  2156. const auto centre = notetools::graphIsBipolar (level) ? 0.5f : 0.0f;
  2157. const auto from = laneScaleBase - centre, to = value - centre;
  2158. const auto k = std::abs (from) > 1.0e-4f ? to / from : 0.0f;
  2159. const auto offset = std::abs (from) > 1.0e-4f ? 0.0f : to - from; // (a column at the centre: they move with it)
  2160. engine.editSong ([=, items = laneScaleFrom] (Song& s) {
  2161. auto& p = s.activePattern();
  2162. for (const auto& [i, v0] : items)
  2163. if (i < p.notes.size())
  2164. notetools::setGraphValue (p.notes[i], level, centre + (v0 - centre) * k + offset, ticksPerStep);
  2165. });
  2166. return;
  2167. }
  2168. if (e.mods.isRightButtonDown()) // a straight ramp from the press to here
  2169. {
  2170. const auto from = juce::jmin (laneDownStep, step), to = juce::jmax (laneDownStep, step);
  2171. const auto channel = graphRow();
  2172. const auto level = (notetools::Level) graphLevel;
  2173. const auto v0 = laneDownStep <= step ? laneDownValue : value, v1 = laneDownStep <= step ? value : laneDownValue;
  2174. engine.editSong ([=] (Song& s) {
  2175. auto& p = s.activePattern();
  2176. for (int st = from; st <= to; ++st)
  2177. {
  2178. const auto t = to > from ? (float) (st - from) / (float) (to - from) : 0.0f;
  2179. for (auto i : notesInStep (p, channel, st))
  2180. notetools::setLevelValue (p.notes[(std::size_t) i], level, v0 + (v1 - v0) * t);
  2181. }
  2182. if (level == notetools::Level::shift)
  2183. p.sortNotes();
  2184. });
  2185. return;
  2186. }
  2187. setLaneValue (step, value);
  2188. }
  2189. void ChannelRackComponent::setPianoRollView (bool on)
  2190. {
  2191. if (pianoRollView == on)
  2192. return;
  2193. pianoRollView = on;
  2194. repaint();
  2195. if (onFilterChanged) // the title's switches follow
  2196. onFilterChanged();
  2197. }
  2198. void ChannelRackComponent::toggleGraphLanes()
  2199. {
  2200. graphLanes = ! graphLanes;
  2201. updateSize();
  2202. repaint();
  2203. if (onFilterChanged) // the title's graph switch follows
  2204. onFilterChanged();
  2205. }
  2206. // --- fills, rotation and organisation ------------------------------------------------------------
  2207. void ChannelRackComponent::rotateSelected (int steps)
  2208. {
  2209. const auto rows = engine.getSelectedChannels();
  2210. engine.editSong ([rows, steps] (Song& s) {
  2211. auto& p = s.activePattern();
  2212. const auto length = patternSteps (s, p);
  2213. for (auto r : rows)
  2214. rotateSteps (p, r, steps, length);
  2215. });
  2216. }
  2217. void ChannelRackComponent::copySelected()
  2218. {
  2219. const auto& song = engine.getSong();
  2220. stepClipboard = copyChannelSteps (song.activePattern(), engine.getSelectedChannels(), (int) song.channels.size());
  2221. }
  2222. void ChannelRackComponent::cutSelected()
  2223. {
  2224. copySelected();
  2225. const auto rows = engine.getSelectedChannels();
  2226. const auto& song = engine.getSong();
  2227. auto copy = song.activePattern();
  2228. if (clearChannelSteps (copy, rows)) // (nothing to cut: no undo step)
  2229. engine.editSong ([rows] (Song& s) { clearChannelSteps (s.activePattern(), rows); });
  2230. }
  2231. void ChannelRackComponent::pasteSelected()
  2232. {
  2233. if (stepClipboard.empty() || engine.getSelectedChannels().empty())
  2234. return;
  2235. engine.editSong ([rows = engine.getSelectedChannels(), clip = stepClipboard] (Song& s) {
  2236. pasteChannelSteps (s.activePattern(), clip, rows, (int) s.channels.size());
  2237. });
  2238. }
  2239. void ChannelRackComponent::fillSelected (int every)
  2240. {
  2241. const auto rows = engine.getSelectedChannels();
  2242. engine.editSong ([rows, every] (Song& s) {
  2243. auto& p = s.activePattern();
  2244. const auto length = patternSteps (s, p);
  2245. for (auto r : rows)
  2246. if (r < (int) s.channels.size()) // (audio clip channels too: they show their steps, round 190io)
  2247. fillEverySteps (p, r, every, length);
  2248. });
  2249. }
  2250. void ChannelRackComponent::sortChannels (ChannelSort by)
  2251. {
  2252. engine.editSong ([by] (Song& s) { permuteChannels (s, channelSortOrder (s, by)); });
  2253. openEditorRow = -1;
  2254. selectRows ({ 0 }, 0);
  2255. }
  2256. void ChannelRackComponent::selectUnused()
  2257. {
  2258. const auto unused = unusedChannels (engine.getSong());
  2259. if (unused.empty())
  2260. {
  2261. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Select unused channels"),
  2262. tr ("Every channel is used by a pattern or a Playlist clip."));
  2263. return;
  2264. }
  2265. selectRows (unused, unused.front());
  2266. }
  2267. int ChannelRackComponent::addChannel (ChannelDef c, bool openEditor, int insert)
  2268. {
  2269. int index = 0;
  2270. if (filterGroup >= 0 && c.group < 0) // a new channel joins the group shown (FL)
  2271. c.group = filterGroup;
  2272. engine.editSong ([&] (Song& s) { index = addChannelRouted (s, c, insert); });
  2273. selectionAnchor = index;
  2274. selectRows ({ index }, index);
  2275. if (openEditor && c.instrument == InstrumentKind::plugin)
  2276. {
  2277. openPluginWindow (index);
  2278. openEditorRow = index;
  2279. }
  2280. else if (openEditor && natives::instrumentEngine (c.instrument) != nullptr) // an FL engine: its editor (round 142)
  2281. openChannelSettings (engine, index);
  2282. return index;
  2283. }
  2284. bool ChannelRackComponent::loadSampleIntoSelected (const juce::File& file)
  2285. {
  2286. const auto row = engine.getSelectedChannel();
  2287. const auto& song = engine.getSong();
  2288. if (row < 0 || row >= (int) song.channels.size() || ! SampleLibrary::isSampleFile (file))
  2289. return false;
  2290. const auto kind = song.channels[(std::size_t) row].instrument;
  2291. // only channels that play a sample (or the built-in drums, which become samplers) take a file
  2292. if (kind != InstrumentKind::sampler && kind != InstrumentKind::kick && kind != InstrumentKind::snare && kind != InstrumentKind::hat
  2293. && kind != InstrumentKind::clap && kind != InstrumentKind::granulizer && kind != InstrumentKind::wavetraveller)
  2294. return false;
  2295. assignSample (row, file);
  2296. return true;
  2297. }
  2298. namespace
  2299. {
  2300. // Euclidean fill: pulses spread evenly over a length, rotated; previewed live on the pattern.
  2301. class EuclideanPanel final : public juce::Component
  2302. {
  2303. public:
  2304. EuclideanPanel (AudioEngine& e, int c) : engine (e), channel (c)
  2305. {
  2306. const auto& song = engine.getSong();
  2307. patternIndex = song.currentPattern;
  2308. originals = song.patterns[(std::size_t) patternIndex].notes;
  2309. steps = patternSteps (song, song.patterns[(std::size_t) patternIndex]);
  2310. auto setup = [this] (juce::Slider& s, juce::Label& l, const juce::String& name, double lo, double hi, double v) {
  2311. l.setText (name, juce::dontSendNotification);
  2312. addAndMakeVisible (l);
  2313. s.setSliderStyle (juce::Slider::LinearHorizontal);
  2314. s.setTextBoxStyle (juce::Slider::TextBoxRight, false, 50, 20);
  2315. s.setRange (lo, hi, 1.0);
  2316. s.setValue (v, juce::dontSendNotification);
  2317. s.onValueChange = [this] { preview(); };
  2318. addAndMakeVisible (s);
  2319. };
  2320. setup (pulses, pulsesLabel, tr ("Pulses"), 0, 32, 5);
  2321. setup (length, lengthLabel, tr ("Length (steps)"), 1, 32, 16);
  2322. setup (rotation, rotationLabel, tr ("Rotation"), -16, 16, 0);
  2323. title.setText (tr ("Euclidean fill: {0}", { juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str()) }), juce::dontSendNotification);
  2324. ui::dialog::styleTitle (title); // (round 190oo, WG-6: the one dialog title row, centred, 44 px)
  2325. addAndMakeVisible (title);
  2326. for (auto* b : { &accept, &cancel })
  2327. addAndMakeVisible (b);
  2328. ui::dialog::styleButton (accept, true); // (WG-6: Cancel | Accept, the one accent button at the far right)
  2329. accept.onClick = [this] {
  2330. restore();
  2331. const auto rhythm = current();
  2332. engine.editSong ([this, rhythm] (Song& s) { setStepRhythm (s.patterns[(std::size_t) patternIndex], channel, rhythm, steps); });
  2333. done = true;
  2334. closeToolWindowOf (*this);
  2335. };
  2336. cancel.onClick = [this] { closeToolWindowOf (*this); };
  2337. setSize (380, 330 + titleGrowth);
  2338. preview();
  2339. }
  2340. ~EuclideanPanel() override
  2341. {
  2342. if (! done)
  2343. restore();
  2344. }
  2345. void paint (juce::Graphics& g) override
  2346. {
  2347. ui::dialog::paintFrame (g, getLocalBounds().toFloat(), ui::dialog::Kind::window); // (round 190oo, WG-6)
  2348. // the rhythm as a ring of steps, the first step at the top
  2349. const auto rhythm = current();
  2350. const auto ring = juce::Rectangle<float> (0, (float) (150 + titleGrowth), (float) getWidth(), 120).withSizeKeepingCentre (110, 110);
  2351. const auto n = (int) rhythm.size();
  2352. for (int i = 0; i < n; ++i)
  2353. {
  2354. const auto angle = juce::MathConstants<float>::twoPi * (float) i / (float) n;
  2355. const auto centre = ring.getCentre() + juce::Point<float> (std::sin (angle), -std::cos (angle)) * 50.0f;
  2356. const auto dot = juce::Rectangle<float> (12, 12).withCentre (centre);
  2357. g.setColour (rhythm[(std::size_t) i] ? theme::colour::stepOn : theme::colour::stepOff);
  2358. g.fillEllipse (dot);
  2359. if (i == 0)
  2360. {
  2361. g.setColour (theme::colour::textPrimary);
  2362. g.drawEllipse (dot.expanded (2.0f), 1.0f);
  2363. }
  2364. }
  2365. }
  2366. void resized() override
  2367. {
  2368. title.setBounds (ui::dialog::titleRow (getLocalBounds()));
  2369. auto area = ui::dialog::bodyOf (getLocalBounds()).reduced (12, 10);
  2370. for (auto [s, l] : { std::pair { &pulses, &pulsesLabel }, std::pair { &length, &lengthLabel }, std::pair { &rotation, &rotationLabel } })
  2371. {
  2372. auto row = area.removeFromTop (30);
  2373. l->setBounds (row.removeFromLeft (120));
  2374. s->setBounds (row);
  2375. }
  2376. auto buttons = area.removeFromBottom (28);
  2377. accept.setBounds (buttons.removeFromRight (100));
  2378. buttons.removeFromRight (8);
  2379. cancel.setBounds (buttons.removeFromRight (90));
  2380. }
  2381. private:
  2382. std::vector<bool> current() const
  2383. {
  2384. return euclideanRhythm ((int) pulses.getValue(), (int) length.getValue(), (int) rotation.getValue());
  2385. }
  2386. void restore()
  2387. {
  2388. if (patternIndex < (int) engine.getSong().patterns.size())
  2389. engine.editSong ([this] (Song& s) { s.patterns[(std::size_t) patternIndex].notes = originals; }, false);
  2390. }
  2391. void preview()
  2392. {
  2393. const auto rhythm = current();
  2394. if (patternIndex < (int) engine.getSong().patterns.size())
  2395. engine.editSong ([this, rhythm] (Song& s) {
  2396. auto& p = s.patterns[(std::size_t) patternIndex];
  2397. p.notes = originals;
  2398. setStepRhythm (p, channel, rhythm, steps);
  2399. }, false);
  2400. repaint();
  2401. }
  2402. // the title row (WG-6): the rows start 15 px lower than under the old 24 px title line
  2403. static constexpr int titleGrowth = ui::dialog::titleRowHeight + 1 + 10 - 40;
  2404. AudioEngine& engine;
  2405. int channel, patternIndex = 0, steps = 16;
  2406. std::vector<Note> originals;
  2407. bool done = false;
  2408. juce::Label title, pulsesLabel, lengthLabel, rotationLabel;
  2409. juce::Slider pulses, length, rotation;
  2410. juce::TextButton accept { tr ("Accept") }, cancel { tr ("Cancel") };
  2411. };
  2412. } // namespace
  2413. std::unique_ptr<juce::Component> ChannelRackComponent::makeEuclideanPanel (int channel)
  2414. {
  2415. return std::make_unique<EuclideanPanel> (engine, juce::jlimit (0, juce::jmax (0, (int) engine.getSong().channels.size() - 1), channel));
  2416. }
  2417. void ChannelRackComponent::showEuclideanFill (int channel)
  2418. {
  2419. if (channel >= 0 && channel < (int) engine.getSong().channels.size())
  2420. openToolWindow (makeEuclideanPanel (channel), tr ("Euclidean fill"), "euclidean");
  2421. }
  2422. // --- mouse -------------------------------------------------------------------------------------
  2423. void ChannelRackComponent::mouseDown (const juce::MouseEvent& e)
  2424. {
  2425. const AudioEngine::UndoGesture undoGesture (engine, AudioEngine::UndoGesture::begin); // (round 190jv: one undo step per gesture)
  2426. int row = 0;
  2427. const auto area = areaAt (e.x, e.y, row);
  2428. const auto& song = engine.getSong();
  2429. switch (area)
  2430. {
  2431. case Area::none:
  2432. return;
  2433. case Area::autoName: // round 190oo (PAT-7): FL's automation clip channel; its button opens the clip
  2434. case Area::autoRow:
  2435. if (flmods::popup (e.mods))
  2436. showAutomationMenu (row);
  2437. else if (area == Area::autoName && e.mods.isLeftButtonDown())
  2438. openAutomationEditor (engine, row);
  2439. return;
  2440. case Area::zipped: // round 190mk (FL's manual: "Right-Click the button of a zipped Channel to unzip it")
  2441. if (flmods::popup (e.mods))
  2442. unzip (row);
  2443. else
  2444. {
  2445. selectionAnchor = row;
  2446. selectRows ({ row }, row);
  2447. }
  2448. return;
  2449. case Area::addRow:
  2450. showAddChannelMenu();
  2451. return;
  2452. case Area::loop: // the advanced looping control: drag sets the loop point in steps, right-click its menu
  2453. {
  2454. if (flmods::popup (e.mods))
  2455. {
  2456. showLoopPointMenu (row);
  2457. return;
  2458. }
  2459. const auto& p = song.activePattern();
  2460. const auto setting = channelloops::effectiveSetting (p, row);
  2461. const auto steps = loopStepsOf (row);
  2462. loopDragRow = row;
  2463. loopDragStart = setting > 0 ? setting : steps > 0 ? steps : numSteps();
  2464. loopDragY = e.position.y;
  2465. repaint();
  2466. return;
  2467. }
  2468. case Area::laneLevels:
  2469. for (int tab = 0; tab < notetools::stepLevelCount; ++tab)
  2470. if (levelButtonBounds (tab).contains (e.getPosition().translated (-stickyX, 0)))
  2471. {
  2472. graphLevel = (int) notetools::stepLevel (tab);
  2473. repaint();
  2474. }
  2475. return;
  2476. case Area::lane:
  2477. {
  2478. const auto step = juce::jlimit (0, numSteps() - 1, (e.x - gridLeft()) / stepWidth);
  2479. if (e.mods.isAltDown() || e.mods.isMiddleButtonDown())
  2480. {
  2481. setLaneValue (step, notetools::graphDefault (graphLevel));
  2482. return;
  2483. }
  2484. laneDownStep = step;
  2485. laneDownValue = laneValueAt (e.y);
  2486. laneScaleFrom.clear();
  2487. laneScaleBase = -1.0f;
  2488. if (e.mods.isCommandDown() && e.mods.isLeftButtonDown()) // round 190lx (DE-31)
  2489. {
  2490. const auto& p = engine.getSong().activePattern();
  2491. const auto level = graphLevel;
  2492. for (int st = 0; st < numSteps(); ++st)
  2493. for (auto i : notesInStep (p, graphRow(), st))
  2494. {
  2495. const auto v = notetools::graphValue (p.notes[(std::size_t) i], level, ticksPerStep);
  2496. if (st == step && laneScaleBase < 0.0f)
  2497. laneScaleBase = v;
  2498. laneScaleFrom.push_back ({ (std::size_t) i, v });
  2499. }
  2500. if (laneScaleBase < 0.0f) // (an empty column: nothing to scale from)
  2501. laneScaleFrom.clear();
  2502. else
  2503. return; // (the drag scales)
  2504. }
  2505. applyLane (e);
  2506. return;
  2507. }
  2508. case Area::mute:
  2509. if (flmods::popup (e.mods) || flmods::ctrl (e.mods))
  2510. solo (row);
  2511. else if (e.mods.isShiftDown()) // round 190ih (DE-11), FL's manual: "Lock state - (Shift+Click) a Mute icon"
  2512. toggleSoloLock (row);
  2513. else if (e.mods.isAltDown()) // round 190mv (DE-12): FL's Alt+click = the solo within the channel's filter group
  2514. engine.editSong ([row] (Song& s) { noteedit::soloChannelInGroup (s, row); });
  2515. else
  2516. toggleMute (row);
  2517. return;
  2518. case Area::pan:
  2519. case Area::volume:
  2520. case Area::route:
  2521. {
  2522. const auto spec = specFor (area, row);
  2523. if (flmods::popup (e.mods))
  2524. {
  2525. juce::PopupMenu menu;
  2526. menu.addSectionHeader (spec.name + ": " + spec.text (valueOf (area, row)));
  2527. ui::addValueItems (menu, *this, &engine, spec, valueOf (area, row), [this, area, row] (double v) { setValue (area, row, v); });
  2528. if (area == Area::route)
  2529. {
  2530. menu.addSeparator();
  2531. menu.addItem (tr ("Next free insert"), [this, row] {
  2532. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].mixerTrack = s.claimFreeInsert(); });
  2533. });
  2534. menu.addItem (tr ("Send the selected channels to free inserts") + "\tCtrl+L", [this] { sendSelectedToInserts(); });
  2535. if (onOpenMixerInsert)
  2536. menu.addItem (tr ("Show this insert in the Mixer"), [this, row] {
  2537. if (row < (int) engine.getSong().channels.size())
  2538. onOpenMixerInsert (engine.getSong().channels[(std::size_t) row].mixerTrack);
  2539. });
  2540. }
  2541. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  2542. return;
  2543. }
  2544. if (ui::isResetClick (e))
  2545. {
  2546. setValue (area, row, spec.defaultValue);
  2547. showTip (area, row, true);
  2548. return;
  2549. }
  2550. knobDrag = area;
  2551. knobRow = row;
  2552. drag.begin (e, valueOf (area, row));
  2553. showTip (area, row, false);
  2554. repaint();
  2555. return;
  2556. }
  2557. case Area::name:
  2558. if (flmods::popup (e.mods))
  2559. {
  2560. if (! std::binary_search (engine.getSelectedChannels().begin(), engine.getSelectedChannels().end(), row))
  2561. clickSelector (row, {});
  2562. else
  2563. selectRows (engine.getSelectedChannels(), row);
  2564. showChannelMenu (row);
  2565. return;
  2566. }
  2567. if (e.mods.isShiftDown())
  2568. {
  2569. clickSelector (row, e.mods);
  2570. return;
  2571. }
  2572. if (! std::binary_search (engine.getSelectedChannels().begin(), engine.getSelectedChannels().end(), row)
  2573. || engine.getSelectedChannels().size() > 1)
  2574. {
  2575. selectionAnchor = row;
  2576. selectRows ({ row }, row);
  2577. }
  2578. if (flmods::ctrl (e.mods)) // audition without opening anything
  2579. {
  2580. previews.press (row, 60, 0.8f); // stops on release
  2581. return;
  2582. }
  2583. // the editor opens on release, unless the button is dragged (that reorders the channels)
  2584. nameDownRow = row;
  2585. nameDragged = false;
  2586. nameDownAlt = e.mods.isAltDown();
  2587. nameDragY = e.position.y;
  2588. return;
  2589. case Area::select:
  2590. clickSelector (row, e.mods);
  2591. if (flmods::popup (e.mods)) // right-drag adds the rows it crosses
  2592. {
  2593. selectDownRow = row;
  2594. selectDragAdds = true;
  2595. selectDragBase = engine.getSelectedChannels();
  2596. }
  2597. else if (! e.mods.isShiftDown() && ! flmods::ctrl (e.mods)) // left-drag selects a range
  2598. {
  2599. selectDownRow = row;
  2600. selectDragAdds = false;
  2601. }
  2602. return;
  2603. case Area::grid:
  2604. {
  2605. auto step = (e.x - gridLeft()) / stepWidth;
  2606. if (const auto loop = loopStepsOf (row); loop > 0 && step >= loop && step < numSteps())
  2607. step %= loop; // a loop repeat edits the step it repeats
  2608. const auto& pattern = song.activePattern();
  2609. // Freeze (round 190ay): a frozen channel's steps cannot be edited; the miniature still opens the Piano Roll (read-only)
  2610. if (! showsNotePreview (pattern, row, pianoRollView) && refuseFrozenEdit (row))
  2611. return;
  2612. if (showsNotePreview (pattern, row, pianoRollView)) // the miniature opens the Piano Roll (steps would break the melody)
  2613. {
  2614. // round 190mk (DE-33, FL's manual "Channel Rack › Piano roll preview"): "Left-click the preview to show/hide
  2615. // the Piano roll window"; "Right-Click to open the Piano roll centered on the notes clicked"
  2616. if (previewMuteButton && ! flmods::popup (e.mods) && previewMuteBounds (row).contains (e.getPosition()))
  2617. {
  2618. toggleMute (row); // (FL: the preview's mute button; the preview stays)
  2619. repaint (rowBounds (row));
  2620. return;
  2621. }
  2622. const auto wasPrimary = engine.getSelectedChannel() == row;
  2623. selectionAnchor = row;
  2624. selectRows ({ row }, row);
  2625. if (flmods::popup (e.mods))
  2626. {
  2627. const auto span = previewSpan();
  2628. const auto at = juce::jlimit (0.0, 1.0, (double) (e.x - gridLeft() - span.x) / (double) juce::jmax (1, span.width));
  2629. if (onPreviewRightClick)
  2630. onPreviewRightClick (row, at * (double) numSteps() * (double) ticksPerStep);
  2631. }
  2632. else if (onPreviewClick)
  2633. onPreviewClick (wasPrimary ? row : -1); // (-1: another channel's preview: show its notes, never hide)
  2634. else if (onOpenPianoRoll)
  2635. onOpenPianoRoll();
  2636. return;
  2637. }
  2638. // FL's General › Input › "Use both mouse buttons in step sequencer" (round 190mr, DE-16 / owner E2; off as in FL,
  2639. // capture 190mr A1.1): on, the left button only switches steps on, the right one off; off, the left toggles
  2640. if (e.mods.isRightButtonDown())
  2641. paintMode = PaintMode::remove;
  2642. else
  2643. paintMode = pattern.hasStep (row, step) && ! flsettings::options().bothButtonsSteps.load() ? PaintMode::remove : PaintMode::add;
  2644. lastPaintedRow = lastPaintedStep = -1;
  2645. applyPaint (e);
  2646. return;
  2647. }
  2648. }
  2649. }
  2650. void ChannelRackComponent::mouseDrag (const juce::MouseEvent& e)
  2651. {
  2652. if (loopDragRow >= 0)
  2653. {
  2654. const auto steps = juce::jlimit (1, numSteps(), loopDragStart + juce::roundToInt ((loopDragY - e.position.y) / 6.0f));
  2655. const auto& p = engine.getSong().activePattern();
  2656. if (channelloops::storedSetting (p, loopDragRow) != steps)
  2657. setLoopPoint (loopDragRow, steps);
  2658. return;
  2659. }
  2660. if (knobDrag != Area::none && drag.isActive())
  2661. {
  2662. setValue (knobDrag, knobRow, drag.update (e, specFor (knobDrag, knobRow)));
  2663. showTip (knobDrag, knobRow, false);
  2664. return;
  2665. }
  2666. if (laneDownStep >= 0)
  2667. {
  2668. applyLane (e);
  2669. hoverStep = juce::jlimit (0, numSteps() - 1, (e.x - gridLeft()) / stepWidth);
  2670. hoverArea = Area::lane;
  2671. const auto v = laneValueAt (e.y);
  2672. const auto bipolar = notetools::graphIsBipolar (graphLevel);
  2673. const auto shown = juce::roundToInt ((bipolar ? v * 2.0f - 1.0f : v) * 100.0f);
  2674. // Note pitch, Shift and Repeat show FL's own values (a key, the part of a step, the repeat rate: issue #208)
  2675. const auto own = notetools::levelText ((notetools::Level) graphLevel, v);
  2676. auto ownText = tr (juce::String::fromUTF8 (own.c_str())); // ("No repeat"; FL's rate names keep their notation)
  2677. for (const char* word : { TR_NOOP ("dotted"), TR_NOOP ("triplet"), TR_NOOP ("Beat"), TR_NOOP ("Half step"), TR_NOOP ("Quarter step") })
  2678. ownText = ownText.replace (word, tr (word));
  2679. ownText = ownText.replace ("(Step)", "(" + tr ("Step") + ")");
  2680. const auto valueText = ! own.empty() ? ownText : (bipolar && shown > 0 ? "+" : "") + juce::String (shown) + "%";
  2681. const auto levelText = tr (notetools::levelName ((notetools::Level) graphLevel));
  2682. ui::showValueTip (*this, controlBounds (Area::lane, graphRow()), levelText + ": " + valueText);
  2683. ui::Hint live;
  2684. live.text = channelName (engine.getSong(), graphRow()) + " - " + levelText;
  2685. live.value = valueText;
  2686. ui::postHint (live);
  2687. repaint (laneBounds());
  2688. return;
  2689. }
  2690. if (nameDownRow >= 0)
  2691. {
  2692. if (! nameDragged && std::abs (e.position.y - nameDragY) < 4.0f)
  2693. return;
  2694. nameDragged = true;
  2695. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  2696. const auto count = (int) engine.getSong().channels.size();
  2697. const auto target = juce::jlimit (0, count - 1, rowAtY (e.y));
  2698. // move the selection one row at a time until the grabbed channel is under the mouse (round 190oo: passing an
  2699. // automation clip row is a step too)
  2700. for (int guard = 0; guard < count + (int) autoRows.size() && engine.getSelectedChannel() != target; ++guard)
  2701. if (! moveSelected (target < engine.getSelectedChannel() ? -1 : 1))
  2702. break;
  2703. return;
  2704. }
  2705. if (selectDownRow >= 0)
  2706. {
  2707. const auto count = (int) engine.getSong().channels.size();
  2708. const auto row = juce::jlimit (0, juce::jmax (0, count - 1), rowAtY (e.y));
  2709. std::vector<int> rows;
  2710. for (int r = juce::jmin (selectDownRow, row); r <= juce::jmax (selectDownRow, row); ++r)
  2711. rows.push_back (r);
  2712. if (selectDragAdds)
  2713. {
  2714. rows.insert (rows.end(), selectDragBase.begin(), selectDragBase.end());
  2715. std::sort (rows.begin(), rows.end());
  2716. rows.erase (std::unique (rows.begin(), rows.end()), rows.end());
  2717. }
  2718. else
  2719. selectionAnchor = selectDownRow;
  2720. if (rows != engine.getSelectedChannels())
  2721. selectRows (rows, row);
  2722. return;
  2723. }
  2724. if (paintMode != PaintMode::none)
  2725. applyPaint (e);
  2726. }
  2727. void ChannelRackComponent::mouseUp (const juce::MouseEvent& e)
  2728. {
  2729. const AudioEngine::UndoGesture undoGesture (engine, AudioEngine::UndoGesture::end); // (closes when mouseUp returns)
  2730. previews.releaseAll(); // the audition (Ctrl+click) and the steps' previews stop with the button
  2731. if (nameDownRow >= 0 && ! nameDragged && e.mouseWasClicked())
  2732. toggleEditor (nameDownRow, nameDownAlt);
  2733. if (nameDragged)
  2734. setMouseCursor (juce::MouseCursor::NormalCursor);
  2735. nameDownRow = -1;
  2736. nameDragged = false;
  2737. if (loopDragRow >= 0)
  2738. {
  2739. loopDragRow = -1;
  2740. repaint();
  2741. }
  2742. selectDownRow = -1;
  2743. selectDragBase.clear();
  2744. ui::hideValueTip();
  2745. ui::clearPostedHint();
  2746. paintMode = PaintMode::none;
  2747. laneDownStep = -1;
  2748. if (laneScaleBase >= 0.0f && graphLevel == notetools::graphShift) // (rollup step 11: a Ctrl-scaled Shift moved notes in their
  2749. engine.editSong ([] (Song& s) { s.activePattern().sortNotes(); }); // steps; sorted once the drag ends, as round 190ma's lane does)
  2750. laneScaleBase = -1.0f; // (round 190lx)
  2751. laneScaleFrom.clear();
  2752. if (knobDrag != Area::none)
  2753. repaint();
  2754. knobDrag = Area::none;
  2755. drag.end();
  2756. }
  2757. void ChannelRackComponent::mouseDoubleClick (const juce::MouseEvent& e)
  2758. {
  2759. int row = 0;
  2760. const auto area = areaAt (e.x, e.y, row);
  2761. if (area == Area::pan || area == Area::volume)
  2762. {
  2763. setValue (area, row, specFor (area, row).defaultValue);
  2764. showTip (area, row, true);
  2765. }
  2766. else if (area == Area::route)
  2767. {
  2768. if (onOpenMixerInsert)
  2769. onOpenMixerInsert (engine.getSong().channels[(std::size_t) row].mixerTrack);
  2770. else
  2771. engine.editSong ([row] (Song& s) { s.channels[(std::size_t) row].mixerTrack = s.claimFreeInsert(); });
  2772. }
  2773. else if (area == Area::loop && ! flmods::popup (e.mods))
  2774. setLoopPoint (row, ChannelLoop::nextBar);
  2775. else if (area == Area::select && ! flmods::popup (e.mods))
  2776. selectAll();
  2777. // a double-click on a channel's name is two clicks, as in FL: its window opens and closes again (FL 2026, checked
  2778. // round 165q F7). It no longer opens the Piano Roll — the hint promised that, but FL's channel button does not.
  2779. }
  2780. void ChannelRackComponent::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  2781. {
  2782. int row = 0;
  2783. const auto area = areaAt (e.x, e.y, row);
  2784. if (area == Area::pan || area == Area::volume || area == Area::route)
  2785. {
  2786. if (const auto v = ui::wheelValue (valueOf (area, row), e, wheel, specFor (area, row)))
  2787. {
  2788. setValue (area, row, *v);
  2789. showTip (area, row, true);
  2790. }
  2791. return;
  2792. }
  2793. if (area == Area::loop) // the loop point, a step at a time
  2794. {
  2795. const auto& song = engine.getSong();
  2796. const auto& p = song.activePattern();
  2797. const auto setting = channelloops::effectiveSetting (p, row);
  2798. const auto steps = setting > 0 ? setting : loopStepsOf (row) > 0 ? loopStepsOf (row) : numSteps();
  2799. const auto delta = (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? 1 : -1;
  2800. setLoopPoint (row, juce::jlimit (1, numSteps(), steps + delta));
  2801. return;
  2802. }
  2803. if ((area == Area::name || area == Area::select) && e.mods.isShiftDown()) // Shift+wheel moves the channel
  2804. {
  2805. const auto delta = (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? -1 : 1;
  2806. selectRows ({ row }, row);
  2807. moveSelected (delta);
  2808. return;
  2809. }
  2810. juce::Component::mouseWheelMove (e, wheel); // scroll the viewport
  2811. }
  2812. ui::Hint ChannelRackComponent::hintAt (juce::Point<int> p)
  2813. {
  2814. int row = 0;
  2815. const auto area = areaAt (p.x, p.y, row);
  2816. const auto& song = engine.getSong();
  2817. ui::Hint h;
  2818. if (area == Area::autoName || area == Area::autoRow) // round 190oo (PAT-7): FL's automation clip channel
  2819. {
  2820. if (row >= 0 && row < (int) song.automations.size())
  2821. {
  2822. const auto& a = song.automations[(std::size_t) row];
  2823. h.text = (a.name.empty() ? tr ("Automation clip") : juce::String::fromUTF8 (a.name.c_str())) + " - "
  2824. + tr ("Automation clip: [LMB] open it [RMB] menu");
  2825. h.value = tr ("Automation clip"); // (FL names the channel's type on the right)
  2826. h.hasMenu = true;
  2827. }
  2828. return h;
  2829. }
  2830. if (row >= 0 && row < (int) song.channels.size() && (area == Area::pan || area == Area::volume || area == Area::route))
  2831. {
  2832. const auto active = knobDrag != Area::none && drag.isActive();
  2833. const auto shownArea = active ? knobDrag : area;
  2834. const auto shownRow = active ? knobRow : row;
  2835. h = ui::valueHint (specFor (shownArea, shownRow), valueOf (shownArea, shownRow),
  2836. shownArea == Area::route ? tr ("[LMB] drag or [Wheel] routes [2xLMB] show in the Mixer [RMB] next free insert")
  2837. : ui::valueGestures());
  2838. return h;
  2839. }
  2840. const auto name = channelName (song, row);
  2841. switch (area)
  2842. {
  2843. case Area::mute:
  2844. h.text = name + " - " + tr ("Click: mute. Ctrl+click or right-click: solo. Alt+click: solo within its filter group. Shift+click: lock the mute state");
  2845. break;
  2846. case Area::name:
  2847. 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");
  2848. // sample channels: where the pitch is (round 163, "getting to the sample pitching")
  2849. if (row >= 0 && row < (int) song.channels.size()
  2850. && (song.channels[(std::size_t) row].instrument == InstrumentKind::sampler || song.channels[(std::size_t) row].instrument == InstrumentKind::audioClip))
  2851. h.text << " " << tr ("(pitch: [RMB] › Pitch...)");
  2852. if (row >= 0 && row < (int) song.channels.size() && ! song.channels[(std::size_t) row].receiveFrom.empty())
  2853. h.text << " " << tr ("(locked: receives the notes of {0})", { juce::String::fromUTF8 (song.channels[(std::size_t) row].receiveFrom.c_str()) });
  2854. if (engine.playsStandIn (row))
  2855. h.text = name + " - " + tr ("Stand-in: its plugin is not installed on this PC, a render of this part plays (the plugin's settings are kept)");
  2856. else if (engine.channelPluginOff (row)) // round 190ap
  2857. h.text = name + " - " + tr ("Plugin switched off: the project was opened without third-party plugins (its settings are kept; File › Switch plugins back on...)");
  2858. // Freeze (round 190ay): what a frozen channel is, and what to do when its audio needs attention
  2859. if (row >= 0 && row < (int) song.channels.size() && song.channels[(std::size_t) row].freeze.on())
  2860. h.text = name + " - " + frozenHint (row);
  2861. h.hasMenu = true;
  2862. // FL's hint bar names what the channel is ("Audio Clip", the plugin's name) on the right (REA round 143b)
  2863. if (row >= 0 && row < (int) song.channels.size())
  2864. {
  2865. const auto& c = song.channels[(std::size_t) row];
  2866. h.value = c.instrument == InstrumentKind::plugin && ! c.plugin.name.empty() ? juce::String::fromUTF8 (c.plugin.name.c_str())
  2867. : instrumentLabel (c.instrument);
  2868. }
  2869. break;
  2870. case Area::select:
  2871. 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");
  2872. break;
  2873. case Area::grid:
  2874. if (! song.patterns.empty() && showsNotePreview (song.activePattern(), row, pianoRollView))
  2875. h.text = name + " - " + (previewMuteButton && previewMuteBounds (row).contains (p) ? tr ("Mute / unmute the channel")
  2876. : tr ("Piano roll preview: [LMB] show / hide the Piano Roll [RMB] open it centred on the notes clicked"));
  2877. else
  2878. h.text = name + " - " + (hoverStep >= numSteps() ? tr ("After the pattern's end: [LMB] adds a step and makes the pattern longer")
  2879. : loopStepsOf (row) > 0 && hoverStep >= loopStepsOf (row)
  2880. ? tr ("Loop repeat (after the loop point): [LMB] edits the step it repeats")
  2881. : tr ("Steps: [LMB] drag draws (starting on a lit step erases) [RMB] drag erases"));
  2882. // and the step's position as bar:step:tick, like FL's hint bar
  2883. if (hoverStep >= 0)
  2884. h.value = juce::String (stepPositionText ((std::int64_t) hoverStep * ticksPerStep, song.meter()));
  2885. break;
  2886. case Area::addRow:
  2887. h.text = tr ("Add a channel (or drop audio files on the rack)");
  2888. break;
  2889. case Area::zipped: // round 190mk: FL's hint is the channel's name, its type on the right
  2890. h.text = name + " - " + tr ("Zipped channel: [RMB] unzip (Alt+U unzips all)");
  2891. if (row >= 0 && row < (int) song.channels.size())
  2892. {
  2893. const auto& c = song.channels[(std::size_t) row];
  2894. h.value = c.instrument == InstrumentKind::plugin && ! c.plugin.name.empty() ? juce::String::fromUTF8 (c.plugin.name.c_str())
  2895. : instrumentLabel (c.instrument);
  2896. }
  2897. break;
  2898. case Area::loop:
  2899. 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");
  2900. h.hasMenu = true;
  2901. if (row >= 0 && row < (int) song.channels.size() && ! song.patterns.empty())
  2902. {
  2903. const auto setting = channelloops::effectiveSetting (song.activePattern(), row);
  2904. h.value = setting == ChannelLoop::dontLoop ? tr ("Don't loop") : setting > 0 ? tr ("Every {0} steps", { juce::String (setting) })
  2905. : tr (channelloops::settingText (setting).c_str());
  2906. }
  2907. break;
  2908. case Area::laneLevels:
  2909. h.text = tr ("Graph lane: choose what the bars edit (Ctrl+K hides the lane)");
  2910. break;
  2911. case Area::lane:
  2912. h.text = name + " - " + tr ("Graph lane: drag sets the steps, Ctrl+drag scales them all, right-drag draws a ramp, Alt+click resets");
  2913. break;
  2914. default:
  2915. break;
  2916. }
  2917. return h;
  2918. }
  2919. void ChannelRackComponent::applyPaint (const juce::MouseEvent& e)
  2920. {
  2921. const auto& song = engine.getSong();
  2922. const auto row = rowAtY (e.y);
  2923. auto step = (e.x - gridLeft()) / stepWidth;
  2924. if (const auto loop = loopStepsOf (row); loop > 0 && step >= loop && step < numSteps())
  2925. step %= loop; // a loop repeat edits the step it repeats
  2926. if (laneBounds().contains (e.getPosition()) || (advancedLoopShown() && e.x >= loopBoxBounds (0).getX() - 3))
  2927. return;
  2928. if (! autoRows.empty() && automationRowAt (e.y) >= 0) // (round 190oo: an automation clip row has no steps to draw)
  2929. return;
  2930. if (row < 0 || row >= (int) song.channels.size() || step < 0 || step >= shownSteps() || e.x < stickyX + gridLeft()
  2931. || showsNotePreview (song.activePattern(), row, pianoRollView)) // drag-paint skips note rows
  2932. return;
  2933. if (row == lastPaintedRow && step == lastPaintedStep)
  2934. return;
  2935. lastPaintedRow = row;
  2936. lastPaintedStep = step;
  2937. const auto on = paintMode == PaintMode::add;
  2938. // FL: setting a step is silent, stopped or playing (issue #11; Ctrl+click on the channel button auditions it)
  2939. engine.editSong ([row, step, on, mute = muteRemovedSteps] (Song& s) {
  2940. auto& p = s.activePattern();
  2941. setStep (p, row, step, on, mute);
  2942. // a ghost step of a pattern with a set length: the length grows to the bar holding it (automatic lengths
  2943. // follow the notes by themselves)
  2944. if (on)
  2945. p.lengthTicks = lengthWithStep (p.lengthTicks, step, ticksPerStep, s.barTicks());
  2946. });
  2947. }
  2948. // --- menus -------------------------------------------------------------------------------------
  2949. // Round 190in (details190if R8): the channel's items of FL's wrapper ▸ menu in the channel and plugin windows, done the
  2950. // way this rack's own channel menu does them
  2951. void ChannelRackComponent::fillWindowMenu (int channel, wrappermenu::Spec& spec)
  2952. {
  2953. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  2954. return;
  2955. const juce::Component::SafePointer<ChannelRackComponent> safe (this);
  2956. spec.pianoRoll = [safe, channel] {
  2957. if (safe == nullptr || channel >= (int) safe->engine.getSong().channels.size())
  2958. return;
  2959. safe->selectionAnchor = channel;
  2960. safe->selectRows ({ channel }, channel);
  2961. if (safe->onOpenPianoRoll)
  2962. safe->onOpenPianoRoll();
  2963. };
  2964. spec.replace = [safe, channel] (juce::PopupMenu& m) {
  2965. if (safe != nullptr && channel < (int) safe->engine.getSong().channels.size())
  2966. m = safe->replaceMenu (channel);
  2967. };
  2968. if (engine.getSong().channels.size() > 1)
  2969. spec.remove = [safe, channel] {
  2970. if (safe == nullptr || channel >= (int) safe->engine.getSong().channels.size() || safe->engine.getSong().channels.size() < 2)
  2971. return;
  2972. safe->closeEditor (channel);
  2973. safe->engine.editSong ([channel] (Song& s) { s.removeChannel (channel); });
  2974. safe->openEditorRow = -1;
  2975. };
  2976. spec.rename = [safe, channel] {
  2977. if (safe != nullptr && channel < (int) safe->engine.getSong().channels.size())
  2978. safe->rename (channel);
  2979. };
  2980. // FL's Channel column (round 190ld, DF-118): "Save channel state as..." writes the channel as the project stores it
  2981. // (ProjectFile::channelStateBytes, LYNX's .lynxchannel); "Browse channel states" opens one into this channel (its
  2982. // mixer track stays). FL's own .fst states are read by the Browser.
  2983. spec.saveChannelState = [safe, channel] {
  2984. if (safe != nullptr && channel < (int) safe->engine.getSong().channels.size())
  2985. safe->saveChannelState (channel);
  2986. };
  2987. spec.browseChannelStates = [safe, channel] {
  2988. if (safe != nullptr && channel < (int) safe->engine.getSong().channels.size())
  2989. safe->openChannelState (channel);
  2990. };
  2991. spec.changeColour = [safe, channel] (juce::PopupMenu& m) {
  2992. if (safe == nullptr || channel >= (int) safe->engine.getSong().channels.size())
  2993. return;
  2994. m = ui::colourMenu (safe->engine.getSong().channels[(std::size_t) channel].colour, [safe, channel] (std::uint32_t colour) {
  2995. if (safe != nullptr && channel < (int) safe->engine.getSong().channels.size()) // (issue #201: every selected channel)
  2996. safe->engine.editSong ([targets = selrename::targets (channel, safe->engine.getSelectedChannels()), colour] (Song& s) {
  2997. selrename::colourChannels (s, targets, colour);
  2998. });
  2999. }, juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1));
  3000. };
  3001. spec.randomColour = [safe, channel] {
  3002. if (safe == nullptr || channel >= (int) safe->engine.getSong().channels.size())
  3003. return;
  3004. const auto& palette = lynxPalette();
  3005. const auto colour = palette[(std::size_t) juce::Random::getSystemRandom().nextInt ((int) palette.size())];
  3006. safe->engine.editSong ([targets = selrename::targets (channel, safe->engine.getSelectedChannels()), colour] (Song& s) {
  3007. selrename::colourChannels (s, targets, colour); // (issue #201)
  3008. });
  3009. };
  3010. spec.changeIcon = [safe, channel] {
  3011. if (safe == nullptr || channel >= (int) safe->engine.getSong().channels.size())
  3012. return;
  3013. ui::showTrackIconPicker (juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1),
  3014. safe->engine.getSong().channels[(std::size_t) channel].icon, [safe, channel] (int icon) {
  3015. if (safe != nullptr && channel < (int) safe->engine.getSong().channels.size())
  3016. safe->engine.editSong ([channel, icon] (Song& s) { s.channels[(std::size_t) channel].icon = icon; });
  3017. });
  3018. };
  3019. }
  3020. // Replace › lists exactly what Insert › and "+" list (issue #18: one source, quickpick::addGeneratorMenu); the channel
  3021. // keeps its place, notes, insert, levels and colour (FL; core replaceGenerator). (Round 190in: also the wrapper menu's.)
  3022. juce::PopupMenu ChannelRackComponent::replaceMenu (int channel)
  3023. {
  3024. const auto& c = engine.getSong().channels[(std::size_t) channel];
  3025. juce::PopupMenu instruments;
  3026. quickpick::addGeneratorMenu (instruments, engine, [this, channel] (ChannelDef generator) {
  3027. if (channel >= (int) engine.getSong().channels.size())
  3028. return;
  3029. closeEditor (channel);
  3030. const auto kind = generator.instrument;
  3031. engine.editSong ([channel, &generator] (Song& s) { replaceGenerator (s, channel, std::move (generator)); });
  3032. selectionAnchor = channel;
  3033. selectRows ({ channel }, channel);
  3034. openNewGenerator (channel, kind);
  3035. }, [this, channel] { chooseSample (channel); }, &c, this);
  3036. return instruments;
  3037. }
  3038. juce::PopupMenu ChannelRackComponent::buildChannelMenu (int channel)
  3039. {
  3040. const auto& c = engine.getSong().channels[(std::size_t) channel];
  3041. auto instruments = replaceMenu (channel);
  3042. // FL's layout (REA round 104): two columns, the channel on the left (editors, name and colour, sample,
  3043. // insert / replace / clone / delete) and its steps on the right (clipboard, fills, rotation); LYNX's own
  3044. // items (settings windows, arpeggiator, organisation) follow in their place
  3045. juce::PopupMenu menu;
  3046. ui::addItemHeader (menu, tr ("Channel"), juce::String::fromUTF8 (c.name.c_str()), c.colour != 0 ? juce::Colour (c.colour) : juce::Colour());
  3047. const auto selected = (int) engine.getSelectedChannels().size();
  3048. const auto count = (int) engine.getSong().channels.size();
  3049. menu.addItem (tr ("Piano Roll") + "\tF7", [this] {
  3050. if (onOpenPianoRoll)
  3051. onOpenPianoRoll();
  3052. });
  3053. menu.addItem (tr ("Graph editor") + "\tCtrl+K", true, graphLanes, [this] { toggleGraphLanes(); });
  3054. menu.addSeparator();
  3055. menu.addItem (theme::mnemonic (tr ("Rename, color and icon..."), 'R') + "\tF2", [this, channel] { rename (channel); }); // (FL's text, round 190ng)
  3056. menu.addSubMenu (tr ("Change color"), ui::colourMenu (c.colour, [this, channel] (std::uint32_t colour) {
  3057. if (channel < (int) engine.getSong().channels.size())
  3058. engine.editSong ([channel, colour] (Song& s) { s.channels[(std::size_t) channel].colour = colour; });
  3059. }, juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1)));
  3060. menu.addItem (tr ("Random color"), [this, channel] {
  3061. const auto& palette = lynxPalette();
  3062. const auto colour = palette[(std::size_t) juce::Random::getSystemRandom().nextInt ((int) palette.size())];
  3063. engine.editSong ([channel, colour] (Song& s) { s.channels[(std::size_t) channel].colour = colour; });
  3064. });
  3065. // FL's "Change icon" (SetPlugIconMenuClick, REA round 168h); LYNX's own icon set
  3066. menu.addItem (tr ("Change icon..."), [this, channel] {
  3067. if (channel >= (int) engine.getSong().channels.size())
  3068. return;
  3069. ui::showTrackIconPicker (juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1), engine.getSong().channels[(std::size_t) channel].icon, [this, channel] (int icon) {
  3070. if (channel < (int) engine.getSong().channels.size())
  3071. engine.editSong ([channel, icon] (Song& s) { s.channels[(std::size_t) channel].icon = icon; });
  3072. });
  3073. });
  3074. // FL's "Lock active/mute state" (the mute switch's menu, round 167l): soloing another channel leaves this one alone
  3075. menu.addItem (tr ("Lock active/mute state") + "\t" + tr ("Shift+click"), true, c.soloLock, [this, channel] { toggleSoloLock (channel); });
  3076. menu.addSeparator();
  3077. menu.addItem (theme::mnemonic (tr ("Load sample..."), 'L'), c.instrument != InstrumentKind::audioClip, false, [this, channel] { chooseSample (channel); });
  3078. {
  3079. // "Cut itself": a new note cuts the channel's own sounding note (its cut group and "cut by" are its own)
  3080. // (issue #68: the same state as the sample panel's checkbox and the Misc page's "Cut self")
  3081. const auto cutsItself = channelCutsItself (c);
  3082. menu.addItem (theme::mnemonic (tr ("Cut itself"), 't'), true, cutsItself, [this, channel, cutsItself] {
  3083. engine.editSong ([channel, cutsItself] (Song& s) {
  3084. if (channel < (int) s.channels.size())
  3085. setChannelCutsItself (s.channels[(std::size_t) channel], channel, ! cutsItself);
  3086. });
  3087. });
  3088. }
  3089. menu.addSeparator();
  3090. {
  3091. juce::PopupMenu insert;
  3092. addInstrumentItems (insert, channel);
  3093. menu.addSubMenu (theme::mnemonic (tr ("Insert"), 'I'), insert);
  3094. }
  3095. menu.addSubMenu (tr ("Replace"), instruments);
  3096. // FL's Patcherize (round 165m): the channel's instrument into a new Patcher, same sound
  3097. menu.addItem (tr ("Patcherize"), selected <= 1 && patcherize::canPatcherizeChannel (engine.getSong(), channel), false, [this, channel] {
  3098. engine.capturePluginStates(); // (the plugin's current settings go with it)
  3099. closeEditor (channel);
  3100. engine.editSong ([channel] (Song& s) { patcherize::patcherizeChannel (s, channel); });
  3101. });
  3102. // Freeze (round 190ay; LYNX's own, FL has none): the channel's sound rendered to audio that plays in its place while
  3103. // its instrument / plugin is unloaded; the clicked channel, or every selected one when it is among them
  3104. {
  3105. const auto& song = engine.getSong();
  3106. std::vector<std::uint64_t> targets;
  3107. const auto& rows = engine.getSelectedChannels();
  3108. if (selected > 1 && std::binary_search (rows.begin(), rows.end(), channel))
  3109. {
  3110. for (const auto r : rows)
  3111. if (r >= 0 && r < count && song.channels[(std::size_t) r].freeze.on() == c.freeze.on())
  3112. targets.push_back (song.channels[(std::size_t) r].uid);
  3113. }
  3114. else
  3115. targets.push_back (c.uid);
  3116. const auto several = targets.size() > 1;
  3117. if (! c.freeze.on())
  3118. menu.addItem (several ? tr ("Freeze selected channels") : trc ("@channel: Freeze"), [this, targets] { freezeChannels (targets); });
  3119. else
  3120. {
  3121. menu.addItem (several ? tr ("Unfreeze selected channels") : tr ("Unfreeze"), [this, targets] {
  3122. for (const auto uid : targets)
  3123. {
  3124. const auto& channels = engine.getSong().channels;
  3125. const auto it = std::find_if (channels.begin(), channels.end(), [uid] (const ChannelDef& d) { return d.uid == uid && uid != 0; });
  3126. if (it != channels.end())
  3127. unfreezeChannel (engine, (int) (it - channels.begin()));
  3128. }
  3129. repaint();
  3130. });
  3131. menu.addItem (several ? tr ("Re-freeze selected channels") : tr ("Re-freeze"), [this, targets] { freezeChannels (targets); });
  3132. }
  3133. }
  3134. // FL's Loop Starter channel menu (round 168b): Replace sample, Generate steps, Locked, One-shot category
  3135. loopstarterui::addChannelMenu (menu, engine, channel);
  3136. menu.addItem (selected > 1 ? theme::mnemonic (tr ("Clone {0} channels", { juce::String (selected) }), 'C') : theme::mnemonic (tr ("Clone"), 'C') + "\tAlt+C", [this] { cloneSelected(); });
  3137. if (selected > 1)
  3138. menu.addItem (theme::mnemonic (tr ("Delete {0} channels", { juce::String (selected) }), 'D') + "\tAlt+Del", selected < count, false, [this] { deleteSelected(); });
  3139. else
  3140. menu.addItem (theme::mnemonic (tr ("Delete..."), 'D') + "\tAlt+Del", count > 1, false, [this, channel] {
  3141. closeEditor (channel);
  3142. engine.editSong ([channel] (Song& s) { s.removeChannel (channel); });
  3143. openEditorRow = -1;
  3144. });
  3145. // FL's "Assign to new instrument track" after a line, the last item of the left column (LineAssignInstrTrackMenu,
  3146. // round 190dx; ChannelMenuPopup FUN_011f4450: "Unassign from instrument track" while the channel has one; enabled
  3147. // only for a generator that can have one)
  3148. menu.addSeparator();
  3149. if (const auto& song = engine.getSong(); trackmodes::instrumentTracksOf (song, channel).empty())
  3150. menu.addItem (theme::mnemonic (tr ("Assign to new instrument track"), 'A'), trackmodes::canBeInstrumentTrack (song, channel), false, [this, channel] {
  3151. int track = -1;
  3152. engine.editSong ([channel, &track] (Song& s) { track = trackmodes::assignToNewInstrumentTrack (s, channel); });
  3153. if (track < 0)
  3154. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Can't create new instrument track"),
  3155. tr ("There are no available mixer tracks."));
  3156. });
  3157. else
  3158. menu.addItem (theme::mnemonic (tr ("Unassign from instrument track"), 'U'), [this, channel] {
  3159. engine.editSong ([channel] (Song& s) { trackmodes::unassignFromInstrumentTracks (s, channel); });
  3160. });
  3161. // LYNX: the channel's settings windows and its arpeggiator
  3162. menu.addSeparator();
  3163. if (c.instrument == InstrumentKind::sampler)
  3164. {
  3165. menu.addItem (tr ("Sampler settings (pitch, envelope, reverse)..."),
  3166. [this, channel] { openChannelSettings (engine, channel); });
  3167. menu.addItem (tr ("Pitch... (semitones, cents, keep length)"), ! c.samplePath.empty() || ! c.zones.empty(), false,
  3168. [this, channel] { showSamplePitchDialog (engine, channel); });
  3169. menu.addItem (tr ("Edit the sample in the audio editor..."), ! c.samplePath.empty(), false, [this, channel] { openAudioEditorForChannel (engine, channel); });
  3170. if (c.sampler.slices.empty())
  3171. menu.addItem (tr ("Slice sample (slicer): one slice per key and a pattern with the loop"), [this, channel] { sliceChannel (channel); });
  3172. else
  3173. menu.addItem (tr ("Undo slices ({0})", { juce::String ((int) c.sampler.slices.size()) }), [this, channel] {
  3174. engine.editSong ([channel] (Song& s) { s.channels[(std::size_t) channel].sampler.slices.clear(); });
  3175. });
  3176. // Live's Simpler › Slice to Drum Rack (round 190ec): the channel becomes a Drum Rack, one pad per slice from C1
  3177. menu.addItem (tr ("Slice to Drum Rack"), ! c.samplePath.empty() && c.zones.empty(), false, [this, channel] { sliceChannelToDrumRack (engine, channel); });
  3178. }
  3179. else if (c.instrument == InstrumentKind::audioClip)
  3180. menu.addItem (tr ("Pitch... (semitones, cents, keep length)"), ! c.samplePath.empty(), false,
  3181. [this, channel] { showSamplePitchDialog (engine, channel); });
  3182. else if (c.instrument == InstrumentKind::synth)
  3183. menu.addItem (tr ("Synth settings (oscillators, envelope, filter)..."), [this, channel] { openChannelSettings (engine, channel); });
  3184. else if (hasChannelSettings (c.instrument))
  3185. menu.addItem (tr ("Channel settings..."), [this, channel] { openChannelSettings (engine, channel); });
  3186. // FL's wrench tab of the channel window, for every channel (REA round 143b)
  3187. menu.addItem (tr ("Miscellaneous functions (polyphony, cut groups, arpeggiator)..."), [this, channel] { openChannelMisc (engine, channel); });
  3188. if (c.instrument == InstrumentKind::patcher) // its published parameters (round 171b)
  3189. addPatcherParameterItems (menu, engine, c.patcher, { AutomationTargetKind::channelParam, channel, 0, 0 });
  3190. if (c.instrument == InstrumentKind::plugin)
  3191. {
  3192. menu.addItem (tr ("Open plugin editor"), [this, channel] { openPluginWindow (channel); });
  3193. // round 190ao: only while the plugin is down (it crashed, or its separate process died)
  3194. if (engine.hostedPluginDown ({ channel, -1, -1 }))
  3195. menu.addItem (tr ("Reload crashed plugin"), [this, channel] { PluginWindows::reload (engine, { { channel, -1, -1 } }); });
  3196. auto* live = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get());
  3197. menu.addSubMenu (tr ("Processing"), pluginProcessingMenu (engine, c.plugin, live != nullptr ? &live->getInstance() : nullptr,
  3198. [channel] (Song& song) -> PluginRef* {
  3199. if (channel >= (int) song.channels.size())
  3200. return nullptr;
  3201. return &song.channels[(std::size_t) channel].plugin;
  3202. }));
  3203. if (live != nullptr)
  3204. addPluginParameterItems (menu, engine, live->getInstance(), { AutomationTargetKind::channelParam, channel, 0, 0 });
  3205. }
  3206. {
  3207. // channel arpeggiator
  3208. const auto arp = c.arp;
  3209. auto set = [this, channel] (std::function<void (ArpSettings&)> change) {
  3210. engine.editSong ([channel, change] (Song& s) { change (s.channels[(std::size_t) channel].arp); });
  3211. };
  3212. juce::PopupMenu arpMenu;
  3213. const char* directions[] = { TR_NOOP ("Off"), TR_NOOP ("Up"), TR_NOOP ("Down"), TR_NOOP ("Up and down"), TR_NOOP ("Random") };
  3214. for (int d = 0; d < 5; ++d)
  3215. arpMenu.addItem (tr (directions[d]), true, arp.direction == d, [set, d] { set ([d] (ArpSettings& a) { a.direction = d; }); });
  3216. arpMenu.addSeparator();
  3217. juce::PopupMenu range, speed, gate, repeat;
  3218. for (int o = 1; o <= 4; ++o)
  3219. 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; }); });
  3220. const std::pair<const char*, float> speeds[] = { { "1/4", 1.0f }, { "1/8", 0.5f }, { TR_NOOP ("1/8 triplet"), 1.0f / 3.0f },
  3221. { "1/16", 0.25f }, { TR_NOOP ("1/16 triplet"), 1.0f / 6.0f }, { "1/32", 0.125f } };
  3222. for (const auto& [name, beats] : speeds)
  3223. speed.addItem (tr (name), true, std::abs (arp.stepBeats - beats) < 1e-4f, [set, b = beats] { set ([b] (ArpSettings& a) { a.stepBeats = b; }); });
  3224. for (int g : { 25, 50, 75, 100 })
  3225. 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; }); });
  3226. for (int n : { 1, 2, 3, 4 })
  3227. repeat.addItem (juce::String (n) + "x", true, arp.repeat == n, [set, n] { set ([n] (ArpSettings& a) { a.repeat = n; }); });
  3228. arpMenu.addSubMenu (tr ("Range"), range);
  3229. arpMenu.addSubMenu (tr ("Speed"), speed);
  3230. arpMenu.addSubMenu (tr ("Gate"), gate);
  3231. arpMenu.addSubMenu (tr ("Repeat"), repeat);
  3232. menu.addSubMenu (arp.enabled() ? tr ("Arpeggiator (on)") : tr ("Arpeggiator"), arpMenu);
  3233. }
  3234. // --- second column: the channel's steps in the current pattern ---
  3235. menu.addColumnBreak();
  3236. // FL's Cut / Copy / Paste (REA round 170a §1): the selected channels' steps and notes, as Ctrl+X / C / V
  3237. {
  3238. const auto& song = engine.getSong();
  3239. const auto& selection = engine.getSelectedChannels();
  3240. const auto& notes = song.activePattern().notes;
  3241. const auto hasNotes = std::any_of (notes.begin(), notes.end(), [&selection] (const Note& n) {
  3242. return std::binary_search (selection.begin(), selection.end(), n.channel);
  3243. });
  3244. menu.addItem (theme::mnemonic (tr ("Cut"), 't') + "\tCtrl+X", hasNotes, false, [this] { cutSelected(); });
  3245. menu.addItem (theme::mnemonic (tr ("Copy"), 'o') + "\tCtrl+C", hasNotes, false, [this] { copySelected(); });
  3246. menu.addItem (theme::mnemonic (tr ("Paste"), 'p') + "\tCtrl+V", ! stepClipboard.empty(), false, [this] { pasteSelected(); });
  3247. }
  3248. menu.addSeparator();
  3249. menu.addItem (theme::mnemonic (tr ("Fill each 2 steps"), '2'), [this] { fillSelected (2); });
  3250. menu.addItem (theme::mnemonic (tr ("Fill each 4 steps"), '4'), [this] { fillSelected (4); });
  3251. menu.addItem (theme::mnemonic (tr ("Fill each 8 steps"), '8'), [this] { fillSelected (8); });
  3252. menu.addItem (theme::mnemonic (tr ("Advanced fill..."), 'f'), [this, channel] { showEuclideanFill (channel); });
  3253. menu.addSeparator();
  3254. menu.addItem (tr ("Rotate left") + "\tShift+Ctrl+Left", [this] { rotateSelected (-1); });
  3255. menu.addItem (tr ("Rotate right") + "\tShift+Ctrl+Right", [this] { rotateSelected (1); });
  3256. menu.addSeparator();
  3257. {
  3258. // FL's "Receive notes from" (round 165f-rack): a MIDI input device (any or one MIDI channel) plays only this channel
  3259. juce::PopupMenu receive;
  3260. receive.addItem (theme::mnemonic (tr ("Unlock"), 'u'), ! c.receiveFrom.empty(), false, [this, channel] {
  3261. engine.editSong ([channel] (Song& s) {
  3262. s.channels[(std::size_t) channel].receiveFrom.clear();
  3263. s.channels[(std::size_t) channel].receiveMidiChannel = 0;
  3264. });
  3265. });
  3266. receive.addSeparator();
  3267. auto lockTo = [this, channel] (std::string device, int midiChannel) {
  3268. engine.editSong ([channel, device, midiChannel] (Song& s) {
  3269. // one device + MIDI channel plays one channel: another channel that had it lets go
  3270. for (auto& other : s.channels)
  3271. if (other.receiveFrom == device && other.receiveMidiChannel == midiChannel)
  3272. other.receiveFrom.clear();
  3273. s.channels[(std::size_t) channel].receiveFrom = device;
  3274. s.channels[(std::size_t) channel].receiveMidiChannel = midiChannel;
  3275. });
  3276. };
  3277. const auto devices = juce::MidiInput::getAvailableDevices();
  3278. for (const auto& d : devices)
  3279. {
  3280. const auto name = d.name.toStdString();
  3281. juce::PopupMenu channels;
  3282. channels.addItem (tr ("Any MIDI channel"), true, c.receiveFrom == name && c.receiveMidiChannel == 0, [lockTo, name] { lockTo (name, 0); });
  3283. for (int m = 1; m <= 16; ++m)
  3284. channels.addItem (tr ("MIDI channel {0}", { juce::String (m) }), true, c.receiveFrom == name && c.receiveMidiChannel == m,
  3285. [lockTo, name, m] { lockTo (name, m); });
  3286. receive.addSubMenu (d.name, channels, true, nullptr, c.receiveFrom == name);
  3287. }
  3288. // a device of the project that is not connected now stays listed
  3289. if (! c.receiveFrom.empty() && std::none_of (devices.begin(), devices.end(), [&c] (const juce::MidiDeviceInfo& d) { return d.name.toStdString() == c.receiveFrom; }))
  3290. receive.addItem (juce::String::fromUTF8 (c.receiveFrom.c_str()) + " (" + tr ("not connected") + ")", false, true, [] {});
  3291. if (devices.isEmpty() && c.receiveFrom.empty())
  3292. receive.addItem (tr ("No MIDI input device"), false, false, [] {});
  3293. menu.addSubMenu (theme::mnemonic (c.receiveFrom.empty() ? tr ("Receive notes from") : tr ("Receive notes from") + " (" + tr ("locked") + ")", 'n'), receive);
  3294. }
  3295. {
  3296. // FL's "Burn MIDI to" (round 165f-rack): what the channel plays (loops, swing, time, arpeggiator, echo) as notes
  3297. juce::PopupMenu burn;
  3298. burn.addItem (theme::mnemonic (tr ("Current pattern"), 'c'), [this, channel] { burnMidi (channel, false); });
  3299. burn.addItem (theme::mnemonic (tr ("New pattern"), 'n'), [this, channel] { burnMidi (channel, true); });
  3300. menu.addSubMenu (tr ("Burn MIDI to"), burn);
  3301. // its loop point in this pattern (FL's advanced looping control menu)
  3302. const auto& song = engine.getSong();
  3303. const auto& p = song.activePattern();
  3304. const auto setting = channelloops::effectiveSetting (p, channel);
  3305. juce::PopupMenu loop;
  3306. loop.addItem (tr ("Don't loop"), true, setting == ChannelLoop::dontLoop && p.loopOn, [this, channel] { setLoopPoint (channel, ChannelLoop::dontLoop); });
  3307. loop.addItem (tr ("Step"), true, p.loopOn && setting == ChannelLoop::nextStep, [this, channel] { setLoopPoint (channel, ChannelLoop::nextStep); });
  3308. loop.addItem (tr ("Beat"), true, p.loopOn && setting == ChannelLoop::nextBeat, [this, channel] { setLoopPoint (channel, ChannelLoop::nextBeat); });
  3309. loop.addItem (tr ("Bar"), true, p.loopOn && setting == ChannelLoop::nextBar, [this, channel] { setLoopPoint (channel, ChannelLoop::nextBar); });
  3310. loop.addSeparator();
  3311. loop.addItem (tr ("Set to next beat"), [this, channel] { setLoopPoint (channel, 1000 + ChannelLoop::nextBeat); });
  3312. loop.addItem (tr ("Set to next bar"), [this, channel] { setLoopPoint (channel, 1000 + ChannelLoop::nextBar); });
  3313. loop.addSeparator();
  3314. loop.addItem (tr ("Burn to pattern"), loopStepsOf (channel) > 0, false, [this, channel] {
  3315. engine.editSong ([channel] (Song& s) { channelloops::burnChannel (s.activePattern(), channel, s.meter()); });
  3316. repaint();
  3317. });
  3318. menu.addSubMenu (setting > 0 && p.loopOn ? tr ("Loop point ({0} steps)", { juce::String (setting) }) : tr ("Loop point"), loop);
  3319. }
  3320. // FL's "Create DirectWave instrument..." (round 165f-rack): the instrument sampled key by key into a Sampler channel
  3321. menu.addItem (tr ("Create sampled instrument..."), c.instrument != InstrumentKind::audioClip && c.instrument != InstrumentKind::controller,
  3322. false, [this, channel] { showAutoSamplerDialog (engine, channel); });
  3323. menu.addSeparator();
  3324. menu.addItem (tr ("Swing mix ({0})...", { juce::String (juce::roundToInt (c.swingMix * 100.0f)) + "%" }),
  3325. [this, channel] { setSwingMixOfSelected (channel); });
  3326. menu.addItem (tr ("Clear notes in this pattern"), [this, channel] {
  3327. engine.editSong ([channel] (Song& s) {
  3328. auto& notes = s.activePattern().notes;
  3329. notes.erase (std::remove_if (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }),
  3330. notes.end());
  3331. });
  3332. });
  3333. // organisation (acts on the selection; FL keeps these in the rack's options menu)
  3334. menu.addSeparator();
  3335. menu.addItem (tr ("Move up") + "\tAlt+Up", engine.getSelectedChannels().front() > 0, false, [this] { moveSelected (-1); });
  3336. menu.addItem (tr ("Move down") + "\tAlt+Down", engine.getSelectedChannels().back() < count - 1, false, [this] { moveSelected (1); });
  3337. menu.addItem (tr ("Send to free mixer inserts") + "\tCtrl+L", [this] { sendSelectedToInserts(); });
  3338. {
  3339. juce::PopupMenu sort;
  3340. sort.addItem (tr ("By name"), [this] { sortChannels (ChannelSort::name); });
  3341. sort.addItem (tr ("By color"), [this] { sortChannels (ChannelSort::colour); });
  3342. sort.addItem (tr ("By mixer insert"), [this] { sortChannels (ChannelSort::insert); });
  3343. sort.addItem (tr ("By type"), [this] { sortChannels (ChannelSort::type); });
  3344. menu.addSubMenu (tr ("Sort channels"), sort);
  3345. }
  3346. menu.addItem (tr ("Select unused channels"), [this] { selectUnused(); });
  3347. menu.addItem (theme::mnemonic (tr ("Group selected..."), 'G') + "\tAlt+G", [this] { groupSelected(); });
  3348. return menu;
  3349. }
  3350. void ChannelRackComponent::showChannelMenu (int channel)
  3351. {
  3352. buildChannelMenu (channel).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  3353. }
  3354. juce::String flEngineName (const natives::InstrumentEngine& e)
  3355. {
  3356. const auto name = juce::String::fromUTF8 (e.name);
  3357. if (! natives::available (e, flStudioAccess()))
  3358. return tr ("{0} (requires FL Studio)", { name });
  3359. return e.beta ? tr ("{0} (beta)", { name }) : name;
  3360. }
  3361. void ChannelRackComponent::openNewGenerator (int row, InstrumentKind kind)
  3362. {
  3363. switch (kind)
  3364. {
  3365. case InstrumentKind::kick: case InstrumentKind::snare: case InstrumentKind::hat: case InstrumentKind::clap:
  3366. case InstrumentKind::synth: case InstrumentKind::sampler: case InstrumentKind::audioClip:
  3367. return; // (LYNX's drums and synth: no window, as before)
  3368. case InstrumentKind::plugin:
  3369. openPluginWindow (row); // the plugin opens when added
  3370. openEditorRow = row;
  3371. return;
  3372. case InstrumentKind::patcher:
  3373. PatcherWindows::openChannel (engine, row);
  3374. return;
  3375. default:
  3376. openChannelSettings (engine, row);
  3377. return;
  3378. }
  3379. }
  3380. void ChannelRackComponent::addInstrumentItems (juce::PopupMenu& menu, int insertAt)
  3381. {
  3382. // a new channel at the end (insertAt < 0) or at a row; the list is the one Replace › shows (issue #18)
  3383. quickpick::addGeneratorMenu (menu, engine, [this, insertAt] (ChannelDef c) {
  3384. int index = 0;
  3385. if (filterGroup >= 0 && c.group < 0)
  3386. c.group = filterGroup;
  3387. const auto kind = c.instrument;
  3388. engine.editSong ([&] (Song& s) {
  3389. c.mixerTrack = s.claimFreeInsert();
  3390. index = insertAt < 0 ? (s.channels.push_back (c), (int) s.channels.size() - 1) : insertChannel (s, insertAt, c);
  3391. });
  3392. selectionAnchor = index;
  3393. selectRows ({ index }, index);
  3394. openNewGenerator (index, kind);
  3395. }, [this, insertAt] { chooseSample (-1, insertAt); }, nullptr, this);
  3396. }
  3397. void ChannelRackComponent::showAddChannelMenu (int insertAt)
  3398. {
  3399. juce::PopupMenu menu;
  3400. // FL's renamed plugins first (issue #11): "1_Synth" renamed in the Browser's Plugin database is added by typing 1
  3401. std::vector<quickpick::Pick> picks;
  3402. if (insertAt < 0)
  3403. picks = quickpick::renamedGenerators (engine, [safe = juce::Component::SafePointer<ChannelRackComponent> (this)] (ChannelDef c) {
  3404. if (safe != nullptr)
  3405. safe->addChannel (std::move (c), true);
  3406. });
  3407. quickpick::addPicks (menu, picks);
  3408. // the generators under FL's Plugin database categories and the user's folders (rounds 166f, 170b: addGeneratorMenu)
  3409. addInstrumentItems (menu, insertAt);
  3410. quickpick::addFolderViewItems (menu, engine); // FL: Categories / Simple / Tree at the bottom
  3411. quickpick::showMenu (menu, juce::PopupMenu::Options().withTargetComponent (this).withMousePosition(), std::move (picks));
  3412. }
  3413. juce::File ChannelRackComponent::channelStateFolder()
  3414. {
  3415. return platform::documentsFolder().getChildFile ("LYNX/Channel states");
  3416. }
  3417. void ChannelRackComponent::saveChannelState (int channel)
  3418. {
  3419. const auto& c = engine.getSong().channels[(std::size_t) channel];
  3420. const auto folder = channelStateFolder();
  3421. folder.createDirectory();
  3422. const auto name = juce::File::createLegalFileName (juce::String::fromUTF8 (c.name.c_str())).trim();
  3423. fileChooser = lynx::ui::makeFileChooser (tr ("Save channel state as..."), folder.getChildFile ((name.isEmpty() ? juce::String ("Channel") : name) + ".lynxchannel"),
  3424. "*.lynxchannel");
  3425. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles
  3426. | juce::FileBrowserComponent::warnAboutOverwriting,
  3427. [this, channel] (const juce::FileChooser& chooser) {
  3428. auto file = chooser.getResult();
  3429. if (file == juce::File() || channel >= (int) engine.getSong().channels.size())
  3430. return;
  3431. file = file.withFileExtension ("lynxchannel");
  3432. const auto bytes = ProjectFile::channelStateBytes (engine.getSong().channels[(std::size_t) channel]);
  3433. if (! file.replaceWithData (bytes.data(), bytes.size()))
  3434. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Save channel state as..."),
  3435. tr ("Could not write {0}", { file.getFullPathName() }));
  3436. });
  3437. }
  3438. void ChannelRackComponent::openChannelState (int channel)
  3439. {
  3440. fileChooser = lynx::ui::makeFileChooser (tr ("Browse channel states"), channelStateFolder(), "*.lynxchannel");
  3441. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  3442. [this, channel] (const juce::FileChooser& chooser) {
  3443. juce::MemoryBlock data;
  3444. if (! chooser.getResult().loadFileAsData (data) || channel >= (int) engine.getSong().channels.size())
  3445. return;
  3446. const auto* p = static_cast<const std::uint8_t*> (data.getData());
  3447. auto loaded = ProjectFile::channelFromStateBytes (std::vector<std::uint8_t> (p, p + data.getSize()));
  3448. if (! loaded)
  3449. {
  3450. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Browse channel states"),
  3451. tr ("This file is not a channel state LYNX SHARE can read."));
  3452. return;
  3453. }
  3454. closeEditor (channel);
  3455. engine.editSongStructural ([channel, def = *loaded] (Song& s) mutable {
  3456. if (channel >= (int) s.channels.size())
  3457. return;
  3458. auto& old = s.channels[(std::size_t) channel];
  3459. def.mixerTrack = old.mixerTrack; // (the channel keeps its place in the mix and its filter group)
  3460. def.group = old.group;
  3461. old = std::move (def);
  3462. });
  3463. });
  3464. }
  3465. void ChannelRackComponent::chooseSample (int channel, int insertAt)
  3466. {
  3467. fileChooser = lynx::ui::makeFileChooser (tr ("Choose sample"), juce::File(), engine.getSampleLibrary().wildcard());
  3468. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  3469. [this, channel, insertAt] (const juce::FileChooser& chooser) {
  3470. if (! chooser.getResult().existsAsFile())
  3471. return;
  3472. if (channel >= 0 || insertAt < 0)
  3473. {
  3474. assignSample (channel, chooser.getResult());
  3475. return;
  3476. }
  3477. // Insert › Sampler (choose file)...: a new sampler channel at the row
  3478. if (engine.getSampleLibrary().load (chooser.getResult().getFullPathName()) == nullptr)
  3479. return assignSample (channel, chooser.getResult()); // (its "could not read" message)
  3480. ChannelDef c;
  3481. c.instrument = InstrumentKind::sampler;
  3482. c.samplePath = chooser.getResult().getFullPathName().toStdString();
  3483. c.name = chooser.getResult().getFileNameWithoutExtension().toStdString();
  3484. if (filterGroup >= 0)
  3485. c.group = filterGroup;
  3486. int index = 0;
  3487. engine.editSong ([&] (Song& s) {
  3488. c.mixerTrack = s.claimFreeInsert();
  3489. index = insertChannel (s, std::min (insertAt, (int) s.channels.size()), c);
  3490. });
  3491. selectionAnchor = index;
  3492. selectRows ({ index }, index);
  3493. });
  3494. }
  3495. void ChannelRackComponent::assignSample (int channel, const juce::File& file)
  3496. {
  3497. // FL's .speech files open the Speech properties first, like FL's channel load does (round 168b); the file it
  3498. // returns (the edited copy, or this one) goes into the channel
  3499. if (file.hasFileExtension ("speech"))
  3500. {
  3501. speechui::editThenLoad (engine, file, [safe = juce::Component::SafePointer<ChannelRackComponent> (this), channel] (const juce::File& f) {
  3502. if (safe != nullptr)
  3503. safe->assignSampleNow (channel, f);
  3504. });
  3505. return;
  3506. }
  3507. assignSampleNow (channel, file);
  3508. }
  3509. void ChannelRackComponent::assignSampleNow (int channel, const juce::File& file)
  3510. {
  3511. if (engine.getSampleLibrary().load (file.getFullPathName()) == nullptr)
  3512. {
  3513. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Sample"),
  3514. tr ("Could not read {0}", { file.getFileName() }));
  3515. return;
  3516. }
  3517. const auto path = file.getFullPathName().toStdString();
  3518. const auto name = file.getFileNameWithoutExtension().toStdString();
  3519. engine.editSong ([channel, path, name] (Song& s) {
  3520. const auto isNew = channel < 0 || channel >= (int) s.channels.size();
  3521. const auto freeInsert = s.claimFreeInsert();
  3522. auto& c = isNew ? s.channels.emplace_back() : s.channels[(std::size_t) channel];
  3523. if (isNew)
  3524. c.mixerTrack = freeInsert;
  3525. // (an audio clip channel stays one: as a Sampler its Playlist clips went silent, round 190ax)
  3526. audioclips::loadSampleInto (c, path, name, flsettings::options().autoNameChannels.load());
  3527. });
  3528. if (channel < 0)
  3529. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  3530. }
  3531. void ChannelRackComponent::openPluginWindow (int channel)
  3532. {
  3533. // Online Sessions P5-A1: a plugin the session's host plays for this channel opens its parameter editor
  3534. if (channel >= 0 && channel < (int) engine.getSong().channels.size()
  3535. && liveui::showHostedEditor ({ { live::Kind::channel, engine.getSong().channels[(std::size_t) channel].uid, 0 }, -1 }))
  3536. return;
  3537. auto instrument = engine.getChannelInstrument (channel);
  3538. if (auto* plugin = dynamic_cast<PluginInstrument*> (instrument.get()))
  3539. {
  3540. // round 190ao: the same channel's window again, after a reload (the channel is found again by its instance tag:
  3541. // channels may have moved since)
  3542. auto reopen = [safe = juce::Component::SafePointer<ChannelRackComponent> (this), tag = engine.getSong().channels[(std::size_t) channel].instance.id] {
  3543. if (safe == nullptr)
  3544. return;
  3545. const auto& channels = safe->engine.getSong().channels;
  3546. for (std::size_t i = 0; i < channels.size(); ++i)
  3547. if (channels[i].instance.id == tag && channels[i].instrument == InstrumentKind::plugin)
  3548. {
  3549. if (safe->engine.hostedPluginDown ({ (int) i, -1, -1 }))
  3550. PluginWindows::reload (safe->engine, { { (int) i, -1, -1 } });
  3551. if (! safe->engine.hostedPluginDown ({ (int) i, -1, -1 }))
  3552. safe->openPluginWindow ((int) i);
  3553. return;
  3554. }
  3555. };
  3556. // crashed inside a call (not called again: its window would call into it), or its separate process died:
  3557. // "Reload" starts it again without reopening the project
  3558. if (engine.hostedPluginDown ({ channel, -1, -1 }))
  3559. {
  3560. PluginWindows::promptReload (engine, { channel, -1, -1 }, [safe = juce::Component::SafePointer<ChannelRackComponent> (this), channel] {
  3561. if (safe != nullptr)
  3562. safe->openPluginWindow (channel);
  3563. });
  3564. return;
  3565. }
  3566. PluginWindows::WrapperContext context { &engine, [channel] (Song& song) -> PluginRef* {
  3567. return channel < (int) song.channels.size() ? &song.channels[(std::size_t) channel].plugin : nullptr;
  3568. }, true, -1, -1, {}, {} };
  3569. context.reload = reopen;
  3570. context.down = [weak = std::weak_ptr<Instrument> (instrument)] {
  3571. const auto held = weak.lock();
  3572. auto* p = dynamic_cast<PluginInstrument*> (held.get());
  3573. return p != nullptr && p->hasCrashed();
  3574. };
  3575. PluginWindows::open (instrument, plugin->getInstance(),
  3576. juce::String::fromUTF8 (engine.getSong().channels[(std::size_t) channel].name.c_str()), std::move (context));
  3577. return;
  3578. }
  3579. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Plugin"),
  3580. tr ("This plugin could not be loaded (it is not installed or has not been scanned)."));
  3581. }
  3582. void ChannelRackComponent::rename (int channel)
  3583. {
  3584. const auto& c = engine.getSong().channels[(std::size_t) channel];
  3585. // issue #201 (round 190ll, core/SelectionRename.h): a new colour goes to every selected channel (the name to this one)
  3586. const auto targets = selrename::targets (channel, engine.getSelectedChannels());
  3587. // issue #220 (round 190ng): FL's "Rename, color and icon" sets the channel's icon in the same window
  3588. showNameColourIconDialog (tr ("Rename channel"), juce::String::fromUTF8 (c.name.c_str()), c.colour, c.icon,
  3589. [this, channel, targets, oldName = c.name, oldColour = c.colour, oldIcon = c.icon] (const juce::String& name, std::uint32_t colour, int icon) {
  3590. if (channel < (int) engine.getSong().channels.size())
  3591. engine.editSong ([channel, targets, icon, oldIcon, r = selrename::Result { oldName, name.toStdString(), oldColour, colour }] (Song& s) {
  3592. selrename::applyToChannels (s, channel, targets, r);
  3593. if (icon >= 0 && icon != oldIcon && channel < (int) s.channels.size())
  3594. s.channels[(std::size_t) channel].icon = icon;
  3595. });
  3596. });
  3597. }
  3598. namespace
  3599. {
  3600. // Live's "Slice to Drum Rack" (round 190ec): Simpler in Slicing mode → a Drum Rack on the same track, one pad per slice
  3601. // (Live's Default slicing facts: gated, choke group 1), no clip. LYNX: the Sampler channel's own slices if it has them,
  3602. // else its transients (a .speech sample: its words), inside its played region; the channel keeps its name, insert,
  3603. // levels and colour.
  3604. void sliceChannelToDrumRack (AudioEngine& engine, int channel)
  3605. {
  3606. const auto& song = engine.getSong();
  3607. if (channel < 0 || channel >= (int) song.channels.size())
  3608. return;
  3609. const auto& c = song.channels[(std::size_t) channel];
  3610. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str()));
  3611. if (sample == nullptr || sample->frames() == 0)
  3612. return;
  3613. std::vector<float> starts = c.sampler.slices;
  3614. if (starts.empty())
  3615. {
  3616. if (juce::File (juce::String::fromUTF8 (c.samplePath.c_str())).hasFileExtension ("speech") && ! sample->markerStarts.empty())
  3617. for (const auto start : sample->markerStarts)
  3618. starts.push_back ((float) ((double) start / (double) sample->frames()));
  3619. else
  3620. starts = detectSlices (*sample, 0.5f, rack::maxSlicePads);
  3621. }
  3622. const auto from = std::clamp (c.sampler.regionStart, 0.0f, 1.0f), to = std::clamp (c.sampler.regionEnd, from, 1.0f);
  3623. const auto slices = rack::slicesInRegion (starts, from, to);
  3624. const auto stem = juce::File (juce::String::fromUTF8 (c.samplePath.c_str())).getFileNameWithoutExtension().toStdString();
  3625. auto drum = rack::sliceToDrumRack (c.samplePath, slices, stem.empty() ? c.name : stem, rack::SliceTemplate::gated, to);
  3626. engine.editSong ([channel, patcher = std::move (drum.patcher)] (Song& s) {
  3627. if (channel >= (int) s.channels.size())
  3628. return;
  3629. auto& ch = s.channels[(std::size_t) channel];
  3630. ch.instrument = InstrumentKind::patcher;
  3631. ch.patcher = patcher;
  3632. ch.sampler.slices.clear();
  3633. });
  3634. }
  3635. } // namespace
  3636. void ChannelRackComponent::sliceChannel (int channel)
  3637. {
  3638. const auto& song = engine.getSong();
  3639. const auto& c = song.channels[(std::size_t) channel];
  3640. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str()));
  3641. if (sample == nullptr || sample->frames() == 0)
  3642. return;
  3643. // a spoken .speech sample is cut at its words (FL hands its words to the slicer as a Zero-X grid; round 168b)
  3644. std::vector<float> slices;
  3645. if (juce::File (juce::String::fromUTF8 (c.samplePath.c_str())).hasFileExtension ("speech") && ! sample->markerStarts.empty())
  3646. for (const auto start : sample->markerStarts)
  3647. slices.push_back ((float) ((double) start / (double) sample->frames()));
  3648. else
  3649. slices = detectSlices (*sample, 0.5f);
  3650. const auto seconds = (double) sample->frames() / sample->sampleRate;
  3651. const auto ticksPerSecond = song.bpm * ppq / 60.0;
  3652. const auto name = c.name + " (slices)";
  3653. engine.editSong ([&] (Song& s) {
  3654. s.channels[(std::size_t) channel].sampler.slices = slices;
  3655. // pattern that plays the slices in their original order and timing (at the project BPM)
  3656. auto& p = s.patterns.emplace_back();
  3657. p.name = name;
  3658. for (std::size_t i = 0; i < slices.size(); ++i)
  3659. {
  3660. const auto start = slices[i] * seconds;
  3661. const auto end = i + 1 < slices.size() ? slices[i + 1] * seconds : seconds;
  3662. Note n;
  3663. n.start = (std::int64_t) std::llround (start * ticksPerSecond);
  3664. n.length = std::max<std::int64_t> (1, (std::int64_t) std::llround ((end - start) * ticksPerSecond));
  3665. n.key = 60 + (int) i;
  3666. n.channel = channel;
  3667. p.notes.push_back (n);
  3668. }
  3669. p.sortNotes();
  3670. s.currentPattern = (int) s.patterns.size() - 1;
  3671. });
  3672. }
  3673. bool ChannelRackComponent::isInterestedInFileDrag (const juce::StringArray& files)
  3674. {
  3675. for (const auto& f : files)
  3676. if (SampleLibrary::isSampleFile (juce::File (f)) || juce::File (f).hasFileExtension ("sf2;sf3;sfz")
  3677. || isSamplerInstrumentFile (juce::File (f))) // (.dwp / .dwb / .gig / .nki: round 190ii)
  3678. return true;
  3679. return false;
  3680. }
  3681. void ChannelRackComponent::filesDropped (const juce::StringArray& files, int x, int y)
  3682. {
  3683. int row = 0;
  3684. const auto area = areaAt (x, y, row);
  3685. auto target = (area == Area::none || area == Area::addRow || area == Area::autoName || area == Area::autoRow) ? -1 : row; // (190oo: no channel)
  3686. for (const auto& f : files)
  3687. {
  3688. const juce::File file (f);
  3689. if (file.hasFileExtension ("sf2;sf3;sfz"))
  3690. {
  3691. // a SoundFont: into the LYNX Soundfont channel it was dropped on, else a new channel
  3692. openSoundFontFile (engine, file, target);
  3693. target = -1;
  3694. continue;
  3695. }
  3696. if (isSamplerInstrumentFile (file))
  3697. {
  3698. // another sampler's instrument (round 190ii, issue #149): into the DirectWave channel it was dropped on, else
  3699. // a new DirectWave channel
  3700. openSamplerInstrumentFile (engine, file, target);
  3701. target = -1;
  3702. continue;
  3703. }
  3704. if (! SampleLibrary::isSampleFile (file)) // (FL's WavPack pack samples too: round 165q)
  3705. continue;
  3706. assignSample (target, file);
  3707. target = -1; // the remaining files become new channels
  3708. }
  3709. }
  3710. void ChannelRackComponent::changeListenerCallback (juce::ChangeBroadcaster* source)
  3711. {
  3712. // a level drag (AudioEngine::editLevels, round 171c) changed only levels: repaint just the knobs that moved. Round
  3713. // 173f (discussion #10): every mouse move of a Mixer fader resized and repainted the whole rack, which moved nothing
  3714. const auto& channels = engine.getSong().channels;
  3715. if (source == &engine.getLevelsBroadcaster() && shownLevels.size() == channels.size())
  3716. {
  3717. for (std::size_t i = 0; i < channels.size(); ++i)
  3718. if (const std::array<float, 2> now { channels[i].volume, channels[i].pan }; now != shownLevels[i])
  3719. {
  3720. shownLevels[i] = now;
  3721. repaint (controlBounds (Area::pan, (int) i).getUnion (controlBounds (Area::volume, (int) i)).expanded (2));
  3722. }
  3723. return;
  3724. }
  3725. shownLevels.resize (channels.size());
  3726. for (std::size_t i = 0; i < channels.size(); ++i)
  3727. shownLevels[i] = { channels[i].volume, channels[i].pan };
  3728. updateSize();
  3729. repaint();
  3730. }
  3731. juce::Rectangle<int> ChannelRackComponent::selectorBounds (int row) const
  3732. {
  3733. // the whole selector slot (round 190io's tall slot, y + 3 … rowHeight - 6, whose lit pill reaches y + 5: rollup 0.1.30,
  3734. // round 190iy; 190ih's bounds were the slim pill's, so a fading light left its top and bottom rows lit), 1 px around
  3735. return { stickyX + selectLeft(), rowY (row) + 2, selectWidth, rowHeight - 4 };
  3736. }
  3737. // round 190ih (PLAN R4, DC-8 / DE-6): one step of every channel's activity light; only the selectors whose shade
  3738. // changed repaint, so a rack where nothing sounds costs one counter read per channel and no paint
  3739. void ChannelRackComponent::updateActivityLights()
  3740. {
  3741. const auto& song = engine.getSong();
  3742. const auto count = (int) song.channels.size();
  3743. if ((int) activityLights.size() != count)
  3744. activityLights.resize ((std::size_t) count);
  3745. const auto fade = ui::motion::enabled();
  3746. for (int row = 0; row < count; ++row)
  3747. {
  3748. auto& light = activityLights[(std::size_t) row];
  3749. const auto before = activity::shade (light.level);
  3750. const auto keys = engine.soundingKeys (row);
  3751. activity::step (light, engine.noteStrikes (row), (keys[0] | keys[1]) != 0, fade);
  3752. if (activity::shade (light.level) != before && isShown (row))
  3753. repaint (selectorBounds (row));
  3754. }
  3755. }
  3756. void ChannelRackComponent::timerCallback()
  3757. {
  3758. if (isShowing())
  3759. updateActivityLights();
  3760. // the channels' volume / pan knobs follow their automation (issue #12): only the automated knobs repaint
  3761. if (const auto& shown = engine.getAutomationDisplay(); shown.getGeneration() != shownAutomation)
  3762. {
  3763. shownAutomation = shown.getGeneration();
  3764. std::vector<int> rows;
  3765. for (const auto& t : shown.automatedTargets())
  3766. if (t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan)
  3767. rows.push_back (t.index);
  3768. if (isShowing())
  3769. for (const auto list : { &rows, &automatedRows })
  3770. for (const auto r : *list)
  3771. if (r >= 0 && r < (int) engine.getSong().channels.size())
  3772. repaint (controlBounds (Area::pan, r).getUnion (controlBounds (Area::volume, r)).expanded (2));
  3773. automatedRows = std::move (rows);
  3774. }
  3775. }
  3776. bool ChannelRackComponent::playheadFrame (double)
  3777. {
  3778. auto& transport = engine.getTransport();
  3779. auto step = -1;
  3780. const auto playing = transport.playing.load();
  3781. // the playhead shows whenever the shown pattern plays: Pattern mode, or a clip of it in Song mode (Busy Works
  3782. // Beats' video, round 170a: in Song mode the rack showed none), as the Piano Roll's (transportedit::patternPlayhead)
  3783. if (playing && isShowing())
  3784. {
  3785. const auto& song = engine.getSong();
  3786. // (between two audio blocks it moves on at the song's tempo, round 174e: the step lights when it is heard)
  3787. const auto tick = transportedit::patternPlayhead (song, song.currentPattern, transport.positionTicks.load() + engine.playheadAdvanceTicks());
  3788. if (tick >= 0.0)
  3789. step = (int) (tick / ticksPerStep);
  3790. }
  3791. if (step != playheadStep)
  3792. {
  3793. // (fitted miniatures draw their own playhead line, at the pattern's scale)
  3794. const auto span = previewSpan();
  3795. const auto total = numSteps();
  3796. auto dirty = [this, span, total] (int s) {
  3797. if (s < 0)
  3798. return;
  3799. repaint (gridLeft() + s * stepWidth - 1, 0, stepWidth + 1, getHeight());
  3800. if (span.fitted && s < total)
  3801. repaint (gridLeft() + span.x + (int) ((std::int64_t) span.width * s / total) - 1, 0, juce::jmax (2, span.width / total) + 3, getHeight());
  3802. };
  3803. dirty (playheadStep);
  3804. playheadStep = step;
  3805. dirty (playheadStep);
  3806. repaint (stickyX + selectLeft(), 0, selectWidth, getHeight()); // the selectors flash with the hits
  3807. followPlayhead();
  3808. return true;
  3809. }
  3810. return playing;
  3811. }
  3812. void ChannelRackComponent::followPlayhead()
  3813. {
  3814. // Follow (issue #12): a pattern longer than the view pages along with the playing step, as the Playlist does
  3815. if (playheadStep < 0 || ! EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack))
  3816. return;
  3817. auto* viewport = findParentComponentOfClass<juce::Viewport>();
  3818. if (viewport == nullptr)
  3819. return;
  3820. const auto view = viewport->getViewArea();
  3821. const auto stepsLeft = view.getX() + gridLeft(); // (the controls column stays on the left of the view)
  3822. const auto x = gridLeft() + playheadStep * stepWidth;
  3823. if (x >= stepsLeft && x + stepWidth <= view.getRight())
  3824. return;
  3825. const auto maxX = juce::jmax (0, getWidth() - view.getWidth());
  3826. viewport->setViewPosition (juce::jlimit (0, maxX, x - gridLeft()), view.getY());
  3827. }
  3828. bool ChannelRackComponent::isInterestedInDragSource (const SourceDetails& details)
  3829. {
  3830. std::string path;
  3831. int bank = 0, program = 0;
  3832. return BrowserComponent::isBrowserDrag (details) || BrowserComponent::isGeneratorDrag (details)
  3833. || parseSoundFontDrag (details.description.toString(), path, bank, program);
  3834. }
  3835. void ChannelRackComponent::itemDropped (const SourceDetails& details)
  3836. {
  3837. // a generator dragged from the Browser's Plugin database (round 162): below the channels a new channel with it, onto a
  3838. // channel it replaces that channel's instrument (FL, audit round 165z-a: insert, notes and levels stay); window open
  3839. if (BrowserComponent::isGeneratorDrag (details))
  3840. {
  3841. if (auto c = BrowserComponent::draggedGenerator (details))
  3842. {
  3843. int row = 0;
  3844. const auto area = areaAt (details.localPosition.x, details.localPosition.y, row);
  3845. if (area != Area::none && area != Area::addRow && area != Area::autoName && area != Area::autoRow && row >= 0
  3846. && row < (int) engine.getSong().channels.size())
  3847. {
  3848. closeEditor (row);
  3849. const auto kind = c->instrument;
  3850. engine.editSong ([row, &c] (Song& s) { replaceGenerator (s, row, std::move (*c)); });
  3851. selectionAnchor = row;
  3852. selectRows ({ row }, row);
  3853. if (kind == InstrumentKind::plugin)
  3854. {
  3855. openPluginWindow (row);
  3856. openEditorRow = row;
  3857. }
  3858. else if (natives::instrumentEngine (kind) != nullptr)
  3859. openChannelSettings (engine, row);
  3860. }
  3861. else
  3862. addChannel (std::move (*c), true);
  3863. }
  3864. return;
  3865. }
  3866. // a preset dragged from a LYNX Soundfont list: onto a LYNX Soundfont channel it loads there, else a new channel
  3867. std::string path;
  3868. int bank = 0, program = 0;
  3869. if (parseSoundFontDrag (details.description.toString(), path, bank, program))
  3870. {
  3871. int row = 0;
  3872. const auto area = areaAt (details.localPosition.x, details.localPosition.y, row);
  3873. const auto& song = engine.getSong();
  3874. if (area != Area::none && area != Area::addRow && area != Area::autoName && area != Area::autoRow && row >= 0
  3875. && row < (int) song.channels.size() && song.channels[(std::size_t) row].instrument == InstrumentKind::soundfont)
  3876. loadSoundFontInto (engine, row, path, bank, program);
  3877. else
  3878. addSoundFontChannel (engine, path, bank, program);
  3879. return;
  3880. }
  3881. if (const auto file = BrowserComponent::draggedFile (details); file.existsAsFile())
  3882. filesDropped ({ file.getFullPathName() }, details.localPosition.x, details.localPosition.y);
  3883. }
  3884. } // namespace lynx