PlaylistComponent.cpp 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529
  1. #include "ui/ClipProperties.h"
  2. #include "ui/PlaylistComponent.h"
  3. #include "core/ClipOps.h"
  4. #include "core/EditorPolish.h"
  5. #include "core/RackOps.h"
  6. #include "core/NoteEdit.h"
  7. #include "engine/Text.h"
  8. #include "ui/BrowserComponent.h"
  9. #include "ui/AutomationUi.h"
  10. #include "ui/Dialogs.h"
  11. #include "ui/HintBar.h"
  12. #include "ui/I18n.h"
  13. #include "ui/Theme.h"
  14. #include "ui/WaveformView.h"
  15. namespace lynx
  16. {
  17. namespace
  18. {
  19. constexpr float clipTitleHeight = 13.0f;
  20. // --- clip look -------------------------------------------------------------------------------------
  21. // One recipe for every clip kind (studied from FL's Playlist, drawn with LYNX's own code and palette): a muted
  22. // header bar holding a small kind glyph and the name, a body in a deep tint of the clip colour, and the
  23. // content (waveform, notes, curve) in a light tint of it; a thin dark edge separates neighbours. Few elements,
  24. // one hue per clip, so a busy Playlist stays calm and every clip reads at a glance.
  25. enum class ClipGlyph { pattern, audio, automation };
  26. // Text colour readable on a clip's header bar.
  27. juce::Colour clipTitleText (juce::Colour band)
  28. {
  29. return band.getPerceivedBrightness() > 0.62f ? theme::colour::bg0 : juce::Colours::white.withAlpha (0.92f);
  30. }
  31. // the header keeps a hint of the clip colour, greyed so the names read and the bodies carry the colour
  32. juce::Colour clipHeaderColour (juce::Colour base) { return base.interpolatedWith (juce::Colour (0xff4b525a), 0.5f); }
  33. juce::Colour clipBodyColour (juce::Colour base) { return base.interpolatedWith (theme::colour::bg1, 0.72f); }
  34. juce::Colour clipContentColour (juce::Colour base) { return base.interpolatedWith (juce::Colours::white, 0.7f); }
  35. float clipHeaderHeight (juce::Rectangle<float> r) { return juce::jmin (clipTitleHeight, juce::jmax (0.0f, r.getHeight() - 8.0f)); }
  36. // The kind glyph at the header's left (the clip menu opens from it): LYNX's own small shapes.
  37. void paintClipGlyph (juce::Graphics& g, juce::Rectangle<float> box, ClipGlyph glyph, juce::Colour colour)
  38. {
  39. g.setColour (colour);
  40. const auto c = box.getCentre();
  41. switch (glyph)
  42. {
  43. case ClipGlyph::pattern: // three note bars, stepped
  44. for (int i = 0; i < 3; ++i)
  45. g.fillRect (juce::Rectangle<float> (c.x - 4.0f + (float) i * 2.0f, c.y - 3.5f + (float) i * 3.0f, 5.0f, 1.5f));
  46. break;
  47. case ClipGlyph::audio: // a small mirrored waveform
  48. {
  49. const float heights[] = { 2.0f, 6.0f, 9.0f, 5.0f, 3.0f };
  50. for (int i = 0; i < 5; ++i)
  51. g.fillRect (juce::Rectangle<float> (c.x - 4.5f + (float) i * 2.0f, c.y - heights[i] * 0.5f, 1.2f, heights[i]));
  52. break;
  53. }
  54. case ClipGlyph::automation: // a rising curve
  55. {
  56. juce::Path p;
  57. p.startNewSubPath (c.x - 4.5f, c.y + 3.5f);
  58. p.quadraticTo (c.x + 1.0f, c.y + 3.5f, c.x + 4.5f, c.y - 3.5f);
  59. g.strokePath (p, juce::PathStrokeType (1.3f));
  60. break;
  61. }
  62. }
  63. }
  64. // Clip body with the header bar, glyph and name; returns the body below the header.
  65. juce::Rectangle<float> paintClipFrame (juce::Graphics& g, juce::Rectangle<float> r, juce::Colour base, const juce::String& name,
  66. ClipGlyph glyph = ClipGlyph::pattern)
  67. {
  68. using namespace theme;
  69. g.setColour (clipBodyColour (base));
  70. g.fillRoundedRectangle (r, radius::sm);
  71. const auto title = r.withHeight (clipHeaderHeight (r));
  72. if (title.getHeight() >= 4.0f)
  73. {
  74. juce::Path band;
  75. band.addRoundedRectangle (title.getX(), title.getY(), title.getWidth(), title.getHeight(), radius::sm, radius::sm, true, true, false, false);
  76. const auto header = clipHeaderColour (base);
  77. g.setGradientFill (juce::ColourGradient (header.brighter (0.12f), 0.0f, title.getY(), header.darker (0.06f), 0.0f, title.getBottom(), false));
  78. g.fillPath (band);
  79. g.setColour (theme::colour::bg0.withAlpha (0.35f)); // the header's lower edge
  80. g.fillRect (title.getX(), title.getBottom() - 1.0f, title.getWidth(), 1.0f);
  81. if (r.getWidth() > 18.0f && title.getHeight() >= 9.0f)
  82. {
  83. auto text = title.withTrimmedLeft (3.0f).withTrimmedRight (2.0f);
  84. if (r.getWidth() >= 40.0f) // room for the glyph (where the clip menu opens)
  85. paintClipGlyph (g, text.removeFromLeft (13.0f), glyph, clipTitleText (header).withMultipliedAlpha (0.8f));
  86. g.setColour (clipTitleText (header));
  87. g.setFont (font (type::caption, true));
  88. g.drawText (name, text.withTrimmedLeft (2.0f).toNearestInt(), juce::Justification::centredLeft, true);
  89. }
  90. }
  91. return r.withTrimmedTop (title.getHeight());
  92. }
  93. void paintClipOutline (juce::Graphics& g, juce::Rectangle<float> r, juce::Colour base, bool selected, bool current)
  94. {
  95. using namespace theme;
  96. if (selected)
  97. {
  98. g.setColour (colour::selection);
  99. g.drawRoundedRectangle (r.reduced (0.5f), radius::sm, 2.0f);
  100. }
  101. else
  102. {
  103. g.setColour (current ? colour::textPrimary.withAlpha (0.55f) : colour::bg0.withAlpha (0.85f));
  104. g.drawRoundedRectangle (r.reduced (0.5f), radius::sm, current ? 1.2f : 1.0f);
  105. }
  106. }
  107. } // namespace
  108. PlaylistComponent::PlaylistComponent (AudioEngine& e)
  109. : engine (e)
  110. {
  111. setWantsKeyboardFocus (false);
  112. setMouseClickGrabsKeyboardFocus (false);
  113. for (auto* bar : { &hBar, &vBar })
  114. {
  115. bar->addListener (this);
  116. bar->setAutoHide (false);
  117. addAndMakeVisible (bar);
  118. }
  119. grid::fillEditorBox (snapBox);
  120. snapBox.setTooltip (tr ("Playlist grid: follows the global grid in the toolbar, or its own; hold Alt while dragging to ignore it"));
  121. snapBox.setWantsKeyboardFocus (false);
  122. snapBox.setMouseClickGrabsKeyboardFocus (false);
  123. snapBox.onChange = [this] { repaint(); };
  124. addAndMakeVisible (snapBox);
  125. tools.onChange = [this] (EditTool) { updateCursor (juce::ModifierKeys::currentModifiers); };
  126. setOpaque (true); // paints every pixel: nothing behind it is redrawn while scrolling
  127. addAndMakeVisible (tools);
  128. arrangementBox.setTooltip (tr ("Arrangement (as in FL, a project can have several)"));
  129. arrangementBox.setWantsKeyboardFocus (false);
  130. arrangementBox.setMouseClickGrabsKeyboardFocus (false);
  131. arrangementBox.onChange = [this] { arrangementChosen(); };
  132. addAndMakeVisible (arrangementBox);
  133. refreshArrangementBox();
  134. refreshTrackLayout();
  135. engine.addChangeListener (this);
  136. EditorGlobals::get().addChangeListener (this);
  137. ui::WaveformCache::getInstance()->addChangeListener (this); // a waveform became ready, or the settings changed
  138. startTimerHz (30);
  139. }
  140. namespace
  141. {
  142. enum ArrangementAction
  143. {
  144. newArrangement = 1001,
  145. cloneArrangement,
  146. renameArrangementAction,
  147. removeArrangementAction,
  148. manageArrangements
  149. };
  150. } // namespace
  151. void PlaylistComponent::refreshArrangementBox()
  152. {
  153. const auto& song = engine.getSong();
  154. juce::StringArray names;
  155. for (const auto& a : song.arrangements)
  156. names.add (juce::String::fromUTF8 (a.name.c_str()));
  157. // only rebuilds when something changed (rebuilding closes the open menu)
  158. bool same = arrangementBox.getNumItems() == names.size() + 4;
  159. for (int i = 0; same && i < names.size(); ++i)
  160. same = arrangementBox.getItemText (i) == names[i];
  161. if (! same)
  162. {
  163. arrangementBox.clear (juce::dontSendNotification);
  164. for (int i = 0; i < names.size(); ++i)
  165. arrangementBox.addItem (names[i], i + 1);
  166. arrangementBox.addSeparator();
  167. arrangementBox.addItem (tr ("New arrangement"), newArrangement);
  168. arrangementBox.addItem (tr ("Clone this one"), cloneArrangement);
  169. arrangementBox.addItem (tr ("Rename..."), renameArrangementAction);
  170. arrangementBox.addItem (tr ("Remove this one"), removeArrangementAction);
  171. arrangementBox.addSeparator();
  172. arrangementBox.addItem (tr ("Arrangements and merging..."), manageArrangements);
  173. arrangementBox.setItemEnabled (removeArrangementAction, names.size() > 1);
  174. }
  175. arrangementBox.setSelectedId (song.currentArrangement + 1, juce::dontSendNotification);
  176. }
  177. void PlaylistComponent::arrangementChosen()
  178. {
  179. const auto id = arrangementBox.getSelectedId();
  180. const auto& song = engine.getSong();
  181. setSelection ({});
  182. if (id >= 1 && id <= (int) song.arrangements.size())
  183. {
  184. if (id - 1 != song.currentArrangement)
  185. engine.editSong ([index = id - 1] (Song& s) { s.selectArrangement (index); }, false);
  186. return;
  187. }
  188. switch (id)
  189. {
  190. case newArrangement:
  191. engine.editSong ([] (Song& s) { s.addArrangement ("Arrangement " + std::to_string (s.arrangements.size() + 1)); });
  192. break;
  193. case cloneArrangement:
  194. engine.editSong ([] (Song& s) {
  195. s.addArrangement (s.arrangements[(std::size_t) s.currentArrangement].name + " (copy)", true);
  196. });
  197. break;
  198. case renameArrangementAction:
  199. renameArrangement();
  200. break;
  201. case manageArrangements:
  202. showArrangements (engine);
  203. break;
  204. case removeArrangementAction:
  205. engine.editSong ([] (Song& s) { s.removeArrangement (s.currentArrangement); });
  206. break;
  207. default:
  208. break;
  209. }
  210. refreshArrangementBox();
  211. }
  212. void PlaylistComponent::renameArrangement()
  213. {
  214. const auto index = engine.getSong().currentArrangement;
  215. auto* window = new juce::AlertWindow (tr ("Rename arrangement"), {}, juce::MessageBoxIconType::NoIcon);
  216. window->addTextEditor ("name", juce::String::fromUTF8 (engine.getSong().arrangements[(std::size_t) index].name.c_str()));
  217. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  218. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  219. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, index, window] (int result) {
  220. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  221. if (result == 1 && ! name.empty() && index < (int) engine.getSong().arrangements.size())
  222. engine.editSong ([index, name] (Song& s) { s.arrangements[(std::size_t) index].name = name; });
  223. }),
  224. true);
  225. }
  226. PlaylistComponent::~PlaylistComponent()
  227. {
  228. EditorGlobals::get().removeChangeListener (this);
  229. engine.removeChangeListener (this);
  230. if (auto* cache = ui::WaveformCache::getInstanceWithoutCreating())
  231. cache->removeChangeListener (this);
  232. }
  233. juce::Colour PlaylistComponent::patternColour (const Song& song, int pattern)
  234. {
  235. if (pattern >= 0 && pattern < (int) song.patterns.size() && song.patterns[(std::size_t) pattern].colour != 0)
  236. return juce::Colour (song.patterns[(std::size_t) pattern].colour);
  237. // hues spread by the golden ratio: neighboring patterns get clearly different colors
  238. const auto hue = std::fmod (0.08f + (float) pattern * 0.618034f, 1.0f);
  239. return juce::Colour::fromHSV (hue, 0.45f, 0.75f, 1.0f);
  240. }
  241. juce::Rectangle<int> PlaylistComponent::gridArea() const
  242. {
  243. return getLocalBounds().withTrimmedLeft (headerWidth).withTrimmedTop (headerHeight)
  244. .withTrimmedRight (scrollBarSize).withTrimmedBottom (scrollBarSize);
  245. }
  246. double PlaylistComponent::tickToX (double tick) const { return headerWidth + (tick - scrollTicks) * pixelsPerTick; }
  247. double PlaylistComponent::xToTick (int x) const { return (x - headerWidth) / pixelsPerTick + scrollTicks; }
  248. int PlaylistComponent::heightOf (int track) const
  249. {
  250. const auto& tracks = engine.getSong().playlistTracks;
  251. const auto h = track >= 0 && track < (int) tracks.size() ? tracks[(std::size_t) track].height : 0;
  252. return h > 0 ? polish::clampTrackHeight (h) : trackHeight;
  253. }
  254. void PlaylistComponent::refreshTrackLayout()
  255. {
  256. const auto count = numTracks();
  257. trackTops.assign ((std::size_t) count + 1, 0);
  258. for (int t = 0; t < count; ++t)
  259. trackTops[(std::size_t) t + 1] = trackTops[(std::size_t) t] + heightOf (t);
  260. }
  261. int PlaylistComponent::tracksHeight() const
  262. {
  263. return trackTops.empty() ? numTracks() * trackHeight : trackTops.back();
  264. }
  265. int PlaylistComponent::trackToY (int track) const
  266. {
  267. // past the cached rows (the list grew during a drag): default heights
  268. const auto last = (int) trackTops.size() - 1;
  269. const auto top = trackTops.empty() ? track * trackHeight
  270. : track <= last ? trackTops[(std::size_t) juce::jmax (0, track)]
  271. : trackTops.back() + (track - last) * trackHeight;
  272. return headerHeight + top - scrollY;
  273. }
  274. int PlaylistComponent::yToTrack (int y) const
  275. {
  276. const auto offset = y - headerHeight + scrollY;
  277. if (trackTops.size() < 2)
  278. return juce::jlimit (0, numTracks() - 1, offset / trackHeight);
  279. const auto it = std::upper_bound (trackTops.begin(), trackTops.end(), offset);
  280. const auto index = (int) (it - trackTops.begin()) - 1;
  281. return juce::jlimit (0, numTracks() - 1, index);
  282. }
  283. int PlaylistComponent::dividerAt (juce::Point<int> p) const
  284. {
  285. // the bottom edge of a track header (4 px band) resizes that track
  286. if (p.x >= headerWidth || p.y < headerHeight || p.y >= gridArea().getBottom())
  287. return -1;
  288. const auto track = yToTrack (p.y);
  289. for (auto t : { track - 1, track })
  290. if (t >= 0 && std::abs (p.y - (trackToY (t) + heightOf (t))) <= 3)
  291. return t;
  292. return -1;
  293. }
  294. void PlaylistComponent::setTrackHeights (std::vector<int> tracks, int height)
  295. {
  296. engine.editSong ([tracks, height] (Song& s) {
  297. for (auto t : tracks)
  298. {
  299. if (t < 0)
  300. continue;
  301. if ((int) s.playlistTracks.size() <= t)
  302. s.playlistTracks.resize ((std::size_t) t + 1);
  303. s.playlistTracks[(std::size_t) t].height = height == trackHeight ? 0 : polish::clampTrackHeight (height);
  304. }
  305. });
  306. refreshTrackLayout();
  307. updateScrollBars();
  308. repaint();
  309. }
  310. int PlaylistComponent::numTracks() const
  311. {
  312. int highest = 0;
  313. for (const auto& c : engine.getSong().playlist)
  314. highest = juce::jmax (highest, c.track);
  315. return juce::jlimit (16, 500, highest + 8); // always a few free tracks at the bottom
  316. }
  317. std::int64_t PlaylistComponent::gridTicks() const
  318. {
  319. const auto bar = (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  320. const auto& option = grid::resolve (snapBox);
  321. switch (option.kind)
  322. {
  323. case grid::Kind::none: return 1;
  324. case grid::Kind::ticks: return option.ticks;
  325. case grid::Kind::bar: return bar;
  326. case grid::Kind::screen:
  327. case grid::Kind::nearest: break;
  328. }
  329. return noteedit::screenStep (pixelsPerTick, bar);
  330. }
  331. std::vector<std::int64_t> PlaylistComponent::snapCandidates() const
  332. {
  333. // edges of the other clips ("Nearest note" in the Playlist snaps to clip edges)
  334. std::vector<std::int64_t> out;
  335. const auto& playlist = engine.getSong().playlist;
  336. for (int i = 0; i < (int) playlist.size(); ++i)
  337. if (std::find (dragIndices.begin(), dragIndices.end(), i) == dragIndices.end())
  338. {
  339. out.push_back (playlist[(std::size_t) i].start);
  340. out.push_back (playlist[(std::size_t) i].end());
  341. }
  342. return out;
  343. }
  344. std::int64_t PlaylistComponent::snap (double tick, bool enabled) const
  345. {
  346. if (! enabled)
  347. return (std::int64_t) std::floor (tick);
  348. const auto& option = grid::resolve (snapBox);
  349. const auto step = gridTicks();
  350. if (option.kind == grid::Kind::nearest)
  351. return noteedit::snapNearest (tick, snapCandidates(), 10.0 / pixelsPerTick, step);
  352. // whole bars respect time signature changes
  353. if (step == (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar))
  354. return engine.getSong().barAt ((std::int64_t) std::max (0.0, std::floor (tick))).tick;
  355. return noteedit::snapDown (tick, step);
  356. }
  357. void PlaylistComponent::updateScrollBars()
  358. {
  359. const auto& song = engine.getSong();
  360. const auto grid = gridArea();
  361. const auto bar = (double) ppq * song.beatsPerBar;
  362. const auto total = juce::jmax ((double) song.songLength() + 16 * bar, grid.getWidth() / pixelsPerTick);
  363. hBar.setRangeLimits (0.0, total, juce::dontSendNotification);
  364. hBar.setCurrentRange (scrollTicks, grid.getWidth() / pixelsPerTick, juce::dontSendNotification);
  365. vBar.setRangeLimits (0.0, (double) tracksHeight(), juce::dontSendNotification);
  366. vBar.setCurrentRange (scrollY, grid.getHeight(), juce::dontSendNotification);
  367. scrollTicks = hBar.getCurrentRangeStart();
  368. scrollY = (int) vBar.getCurrentRangeStart();
  369. }
  370. void PlaylistComponent::setTitleBarInsets (int left, int right)
  371. {
  372. if (left != titleInsetLeft || right != titleInsetRight)
  373. {
  374. titleInsetLeft = left;
  375. titleInsetRight = right;
  376. resized();
  377. }
  378. }
  379. void PlaylistComponent::resized()
  380. {
  381. const auto h = toolbarHeight - 6;
  382. arrangementBox.setBounds (4 + titleInsetLeft, 3, juce::jmin (150, getWidth() / 5), h);
  383. tools.setBounds (arrangementBox.getRight() + 8, 3, tools.getIdealWidth (h), h);
  384. snapBox.setBounds (tools.getRight() + 8, 3, 128, h);
  385. hBar.setBounds (headerWidth, getHeight() - scrollBarSize, getWidth() - headerWidth - scrollBarSize, scrollBarSize);
  386. vBar.setBounds (getWidth() - scrollBarSize, headerHeight, scrollBarSize, getHeight() - headerHeight - scrollBarSize);
  387. updateScrollBars();
  388. }
  389. void PlaylistComponent::paint (juce::Graphics& g)
  390. {
  391. if (trackTops.size() != (std::size_t) numTracks() + 1) // the track list grew or shrank since the last change message
  392. refreshTrackLayout();
  393. const auto& song = engine.getSong();
  394. const auto grid = gridArea();
  395. const auto bar = (std::int64_t) ppq * song.beatsPerBar;
  396. const auto tracks = numTracks();
  397. using namespace theme;
  398. g.fillAll (colour::bg1);
  399. // --- tracks and grid ---------------------------------------------------
  400. {
  401. juce::Graphics::ScopedSaveState state (g);
  402. g.reduceClipRegion (grid);
  403. for (int t = 0; t < tracks; ++t)
  404. {
  405. const auto y = trackToY (t);
  406. const auto trackHeight = heightOf (t);
  407. if (y > grid.getBottom() || y + trackHeight < grid.getY())
  408. continue;
  409. auto lane = t % 2 == 0 ? colour::bg2 : colour::bg2.interpolatedWith (colour::bg1, 0.5f);
  410. if (t == hover.track && drag == Drag::none)
  411. lane = lane.interpolatedWith (colour::textPrimary, 0.025f); // the track under the mouse
  412. g.setColour (lane);
  413. g.fillRect (grid.getX(), y, grid.getWidth(), trackHeight);
  414. g.setColour (colour::bg0);
  415. g.drawHorizontalLine (y + trackHeight - 1, (float) grid.getX(), (float) grid.getRight());
  416. }
  417. const auto beatPixels = ppq * pixelsPerTick;
  418. for (const auto& b : song.barsBetween ((std::int64_t) std::max (0.0, scrollTicks), (std::int64_t) xToTick (grid.getRight()) + 1))
  419. {
  420. g.setColour (colour::gridBar);
  421. g.drawVerticalLine ((int) tickToX ((double) b.tick), (float) grid.getY(), (float) grid.getBottom());
  422. if (beatPixels < 8.0)
  423. continue; // zoomed far out: bar lines only
  424. g.setColour (colour::gridBeat);
  425. for (auto tick = b.tick + ppq; tick < b.tick + b.length; tick += ppq)
  426. g.drawVerticalLine ((int) tickToX ((double) tick), (float) grid.getY(), (float) grid.getBottom());
  427. }
  428. // loop region
  429. if (song.hasLoop())
  430. {
  431. const auto lx0 = (float) tickToX ((double) song.loopStart), lx1 = (float) tickToX ((double) song.loopEnd);
  432. g.setColour (colour::accent.withAlpha (0.06f));
  433. g.fillRect (juce::Rectangle<float> (lx0, (float) grid.getY(), lx1 - lx0, (float) grid.getHeight()));
  434. g.setColour (colour::accent.withAlpha (0.45f));
  435. g.drawVerticalLine ((int) lx0, (float) grid.getY(), (float) grid.getBottom());
  436. g.drawVerticalLine ((int) lx1, (float) grid.getY(), (float) grid.getBottom());
  437. }
  438. // end of song
  439. if (! song.playlist.empty())
  440. {
  441. const auto endX = (float) tickToX ((double) song.songLength());
  442. g.setColour (colour::bg0.withAlpha (0.45f));
  443. g.fillRect (juce::Rectangle<float> (endX, (float) grid.getY(), (float) grid.getRight() - endX, (float) grid.getHeight()));
  444. }
  445. g.setFont (font (type::caption));
  446. // muted clips (the Mute tool) are veiled
  447. auto veilIfMuted = [&g] (const Clip& clip, juce::Rectangle<float> area) {
  448. if (clip.muted)
  449. {
  450. g.setColour (colour::bg1.withAlpha (0.62f));
  451. g.fillRoundedRectangle (area, radius::sm);
  452. g.setColour (colour::textDisabled);
  453. g.drawLine (area.getX() + 2.0f, area.getBottom() - 2.0f, area.getRight() - 2.0f, area.getY() + 2.0f, 1.0f);
  454. }
  455. };
  456. for (int i = 0; i < (int) song.playlist.size(); ++i)
  457. {
  458. const auto& c = song.playlist[(std::size_t) i];
  459. const auto x0 = (float) tickToX ((double) c.start);
  460. const auto x1 = (float) tickToX ((double) c.end());
  461. const auto y = (float) trackToY (c.track);
  462. const auto trackHeight = heightOf (c.track);
  463. if (x1 < grid.getX() || x0 > grid.getRight() || y > grid.getBottom() || y + trackHeight < grid.getY())
  464. continue;
  465. const auto r = juce::Rectangle<float> (x0, y + 1.0f, juce::jmax (3.0f, x1 - x0 - 1.0f), (float) trackHeight - 3.0f);
  466. if (! g.getClipBounds().toFloat().intersects (r.expanded (1.0f)))
  467. continue; // outside the area being repainted
  468. if (c.kind == ClipKind::automation)
  469. {
  470. paintAutomationClip (g, c, r);
  471. veilIfMuted (c, r);
  472. if (isSelected (i))
  473. paintClipOutline (g, r, colour::automation, true, false);
  474. continue;
  475. }
  476. if (c.kind == ClipKind::audio)
  477. {
  478. paintAudioClip (g, c, r);
  479. veilIfMuted (c, r);
  480. if (isSelected (i))
  481. paintClipOutline (g, r, colour::audioClip, true, false);
  482. continue;
  483. }
  484. const auto base = tame (patternColour (song, c.pattern));
  485. const auto current = c.pattern == song.currentPattern;
  486. const auto selected = isSelected (i);
  487. // body + name strip
  488. const auto clipBody = paintClipFrame (g, r, base, juce::String::fromUTF8 (song.patterns[(std::size_t) c.pattern].name.c_str()));
  489. // note thumbnail: the pattern's notes as small rounded bars in a light tint of the clip colour,
  490. // spread over the body's height by pitch (a few keys of padding so single notes don't hug the edges)
  491. const auto& notes = song.patterns[(std::size_t) c.pattern].notes;
  492. if (! notes.empty() && r.getWidth() > 6 && clipBody.getHeight() >= 4.0f)
  493. {
  494. int low = 127, high = 0;
  495. for (const auto& n : notes)
  496. {
  497. low = juce::jmin (low, n.key);
  498. high = juce::jmax (high, n.key);
  499. }
  500. const auto body = clipBody.reduced (1.0f, clipBody.getHeight() >= 12.0f ? 3.0f : 1.0f);
  501. const auto span = juce::jmax (6, high - low + 2); // a small pitch range stays centred
  502. const auto bottomKey = (low + high) / 2.0f - span / 2.0f;
  503. const auto rows = (float) span + 1.0f;
  504. const auto noteHeight = juce::jlimit (1.5f, 2.5f, body.getHeight() / rows);
  505. const auto patternLength = juce::jmax<std::int64_t> (1, song.patterns[(std::size_t) c.pattern].effectiveLength (song.beatsPerBar));
  506. g.setColour (clipContentColour (base));
  507. juce::Graphics::ScopedSaveState clip (g);
  508. g.reduceClipRegion (body.toNearestInt());
  509. // the pattern repeats along a clip longer than it (FL loops pattern clips that are stretched)
  510. for (auto loopStart = c.start - c.offset % patternLength; loopStart < c.end(); loopStart += patternLength)
  511. {
  512. for (const auto& n : notes)
  513. {
  514. const auto at = loopStart + n.start;
  515. if (at + n.length <= c.start || at >= c.end())
  516. continue;
  517. const auto nx = (float) tickToX ((double) at);
  518. const auto nw = juce::jmax (2.0f, (float) (n.length * pixelsPerTick) - 1.0f);
  519. const auto ny = body.getBottom() - ((float) n.key - bottomKey + 0.5f) / rows * body.getHeight() - noteHeight * 0.5f;
  520. g.fillRoundedRectangle (nx, ny, nw, noteHeight, juce::jmin (1.0f, noteHeight * 0.5f));
  521. }
  522. }
  523. }
  524. veilIfMuted (c, r);
  525. paintClipOutline (g, r, base, selected, current);
  526. }
  527. // the clip under the mouse: outline, the grip of the edge it is on, its menu button
  528. if (hover.clip >= 0 && hover.clip < (int) song.playlist.size() && drag == Drag::none)
  529. {
  530. const auto r = clipBounds (hover.clip).toFloat();
  531. g.setColour (colour::textPrimary.withAlpha (isSelected (hover.clip) ? 0.0f : 0.55f));
  532. g.drawRoundedRectangle (r.reduced (0.5f), radius::sm, 1.2f);
  533. if (hover.target == gesture::Target::leftEdge || hover.target == gesture::Target::rightEdge)
  534. {
  535. const auto x = hover.target == gesture::Target::rightEdge ? r.getRight() - 4.0f : r.getX() + 1.0f;
  536. g.setColour (colour::textPrimary);
  537. g.fillRoundedRectangle (x, r.getY() + clipTitleHeight + 3.0f, 3.0f, juce::jmax (4.0f, r.getHeight() - clipTitleHeight - 6.0f), 1.5f);
  538. }
  539. if (const auto button = clipMenuButton (hover.clip); ! button.isEmpty())
  540. {
  541. const auto b = button.toFloat();
  542. g.setColour (hover.target == gesture::Target::clipMenu ? colour::bg0.withAlpha (0.75f) : colour::bg0.withAlpha (0.45f));
  543. g.fillRoundedRectangle (b, 2.0f);
  544. icons::draw (g, Icon::chevronDown, b.reduced (1.0f), colour::textPrimary);
  545. }
  546. }
  547. if (! rubberBand.isEmpty())
  548. {
  549. g.setColour (colour::selectionFill);
  550. g.fillRect (rubberBand);
  551. g.setColour (colour::selection);
  552. g.drawRect (rubberBand);
  553. }
  554. if (drag == Drag::knife)
  555. {
  556. juce::Path cut;
  557. cut.startNewSubPath (knifeFrom.toFloat());
  558. cut.lineTo (knifeTo.toFloat());
  559. juce::Path dashed;
  560. const float dash[] = { 5.0f, 3.0f };
  561. juce::PathStrokeType (1.5f).createDashedStroke (dashed, cut, dash, 2);
  562. g.setColour (colour::textPrimary);
  563. g.fillPath (dashed);
  564. }
  565. if (playheadTick >= 0.0)
  566. {
  567. g.setColour (colour::playhead);
  568. g.fillRect (juce::Rectangle<float> ((float) tickToX (playheadTick) - 0.5f, (float) grid.getY(), 1.5f, (float) grid.getHeight()));
  569. }
  570. }
  571. // --- ruler (drawn in its own coordinates, below the toolbar) -----------------
  572. {
  573. juce::Graphics::ScopedSaveState state (g);
  574. g.setOrigin (0, toolbarHeight);
  575. const auto ruler = juce::Rectangle<int> (headerWidth, 0, grid.getWidth(), timelineHeight);
  576. g.setColour (colour::bg2);
  577. g.fillRect (ruler);
  578. g.setColour (colour::border);
  579. g.fillRect (ruler.withTop (ruler.getBottom() - 1));
  580. g.reduceClipRegion (ruler);
  581. g.setFont (font (type::small));
  582. if (song.hasLoop()) // the time selection
  583. {
  584. const auto lx0 = (float) tickToX ((double) song.loopStart), lx1 = (float) tickToX ((double) song.loopEnd);
  585. g.setColour (colour::accent.withAlpha (0.16f));
  586. g.fillRect (juce::Rectangle<float> (lx0, 0.0f, lx1 - lx0, (float) timelineHeight));
  587. g.setColour (colour::accent.withAlpha (0.75f));
  588. g.fillRect (juce::Rectangle<float> (lx0, 0.0f, lx1 - lx0, 4.0f));
  589. }
  590. const auto barPixels = bar * pixelsPerTick;
  591. const auto every = barPixels < 30.0 ? (barPixels < 10.0 ? 16 : 4) : 1; // numbers spaced further apart when zoomed out
  592. for (const auto& b : song.barsBetween ((std::int64_t) std::max (0.0, scrollTicks), (std::int64_t) xToTick (grid.getRight()) + 1))
  593. {
  594. if ((b.number - 1) % every != 0)
  595. continue;
  596. const auto x = (int) tickToX ((double) b.tick);
  597. g.setColour (colour::textDisabled);
  598. g.drawVerticalLine (x, 12.0f, (float) timelineHeight);
  599. g.setColour (colour::textSecondary);
  600. g.drawText (juce::String (b.number), x + 3, 2, 40, timelineHeight - 4, juce::Justification::centredLeft);
  601. }
  602. // markers: small flag with the name; time signature changes show the fraction
  603. g.setFont (font (type::caption, true));
  604. for (const auto& m : song.markers())
  605. {
  606. const auto x = (float) tickToX ((double) m.tick);
  607. if (x < (float) ruler.getX() - 200.0f || x > (float) ruler.getRight())
  608. continue;
  609. auto label = juce::String::fromUTF8 (m.name.c_str());
  610. if (const auto fraction = juce::String (m.numerator) + "/" + juce::String (m.denominator); m.isSignature() && label != fraction)
  611. label = fraction + (label.isEmpty() ? "" : " " + label);
  612. if (label.isEmpty())
  613. label = "*";
  614. const auto width = (float) juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), label) + 8.0f;
  615. const auto tag = juce::Rectangle<float> (x, (float) timelineHeight - 11.0f, width, 11.0f);
  616. g.setColour (m.isSignature() ? colour::info : colour::warning);
  617. g.fillRoundedRectangle (tag, 2.0f);
  618. g.drawVerticalLine ((int) x, 0.0f, (float) timelineHeight);
  619. g.setColour (colour::bg0);
  620. g.drawText (label, tag.reduced (3.0f, 0.0f), juce::Justification::centredLeft, false);
  621. }
  622. if (playheadTick >= 0.0)
  623. {
  624. const auto x = (float) tickToX (playheadTick);
  625. juce::Path tri;
  626. tri.addTriangle (x - 6, 0, x + 6, 0, x, 9);
  627. g.setColour (colour::playhead);
  628. g.fillPath (tri);
  629. }
  630. }
  631. // --- track headers -----------------------------------------------------
  632. {
  633. const auto headers = juce::Rectangle<int> (0, headerHeight, headerWidth, grid.getHeight());
  634. juce::Graphics::ScopedSaveState state (g);
  635. g.reduceClipRegion (headers);
  636. g.setColour (colour::bg2);
  637. g.fillRect (headers);
  638. g.setFont (font (type::small));
  639. for (int t = 0; t < tracks; ++t)
  640. {
  641. const auto y = trackToY (t);
  642. const auto trackHeight = heightOf (t);
  643. if (y > headers.getBottom() || y + trackHeight < headers.getY())
  644. continue;
  645. const auto muted = song.isTrackMuted (t);
  646. const auto custom = t < (int) song.playlistTracks.size() && ! song.playlistTracks[(std::size_t) t].name.empty();
  647. const auto hovered = hover.header && hover.track == t;
  648. auto plate = muted ? colour::bg2 : colour::bg3;
  649. if (hovered)
  650. plate = plate.interpolatedWith (colour::bg5, 0.6f);
  651. g.setColour (plate);
  652. g.fillRoundedRectangle (juce::Rectangle<float> (2.0f, (float) y + 1.0f, (float) headerWidth - 4.0f, (float) trackHeight - 3.0f), radius::sm);
  653. g.setColour (muteLed (muted));
  654. g.fillEllipse (7.0f, (float) y + trackHeight / 2.0f - 4.0f, 8.0f, 8.0f);
  655. if (hovered && hover.led) // the LED is a button: ring it
  656. {
  657. g.setColour (colour::textPrimary.withAlpha (0.7f));
  658. g.drawEllipse (5.0f, (float) y + trackHeight / 2.0f - 6.0f, 12.0f, 12.0f, 1.0f);
  659. }
  660. g.setColour (muted ? colour::textDisabled : (custom ? colour::textPrimary : colour::textSecondary));
  661. g.drawFittedText (custom ? juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str())
  662. : tr ("Track {0}", { juce::String (t + 1) }),
  663. 20, y, headerWidth - 24, trackHeight, juce::Justification::centredLeft, trackHeight >= 30 ? 2 : 1, 0.8f);
  664. // the divider under the header: lit while hovered or dragged (drag resizes the track)
  665. if (hover.divider == t || (drag == Drag::trackResize && (resizeTrack == t || resizeAll)))
  666. {
  667. g.setColour (colour::accent);
  668. g.fillRoundedRectangle (juce::Rectangle<float> (6.0f, (float) (y + trackHeight) - 2.0f, (float) headerWidth - 12.0f, 3.0f), 1.5f);
  669. }
  670. }
  671. }
  672. // toolbar band, and the corner left of the ruler
  673. g.setColour (colour::bg3);
  674. g.fillRect (0, 0, getWidth(), toolbarHeight);
  675. g.setColour (colour::bg2);
  676. g.fillRect (0, toolbarHeight, headerWidth, timelineHeight);
  677. g.setColour (colour::border);
  678. g.fillRect (0, toolbarHeight - 1, getWidth(), 1);
  679. g.fillRect (0, headerHeight - 1, headerWidth, 1);
  680. g.fillRect (headerWidth - 1, toolbarHeight, 1, getHeight() - toolbarHeight);
  681. }
  682. void PlaylistComponent::paintOverChildren (juce::Graphics& g)
  683. {
  684. if (! ripple)
  685. return;
  686. // ripple editing is on: a small tag in the grid's top-right corner
  687. const auto grid = gridArea();
  688. const auto tag = juce::Rectangle<float> ((float) grid.getRight() - 70.0f, (float) grid.getY() + 4.0f, 64.0f, 18.0f);
  689. g.setColour (theme::colour::accentMuted);
  690. g.fillRoundedRectangle (tag, theme::radius::sm);
  691. g.setColour (theme::colour::accent);
  692. g.drawRoundedRectangle (tag.reduced (0.5f), theme::radius::sm, 1.0f);
  693. g.setFont (theme::font (theme::type::caption, true));
  694. g.drawText (tr ("Ripple"), tag.toNearestInt(), juce::Justification::centred);
  695. }
  696. void PlaylistComponent::paintAudioClip (juce::Graphics& g, const Clip& c, juce::Rectangle<float> r)
  697. {
  698. const auto& song = engine.getSong();
  699. if (c.channel < 0 || c.channel >= (int) song.channels.size())
  700. return;
  701. const auto& channel = song.channels[(std::size_t) c.channel];
  702. const auto colour = audioClipColour (channel);
  703. const auto name = juce::String::fromUTF8 (channel.name.c_str());
  704. const auto body = paintClipFrame (g, r, colour, name, ClipGlyph::audio);
  705. // the waveform (ui/WaveformView, analysed in the background): the clean style fills the body with the
  706. // peak envelope mirrored around the centre, in a light tint of the clip colour
  707. const auto path = juce::String::fromUTF8 (channel.samplePath.c_str());
  708. const auto summary = ui::WaveformCache::getInstance()->find (path, [this, path] { return engine.getSampleLibrary().load (path); });
  709. if (summary != nullptr && body.getHeight() >= 3.0f)
  710. {
  711. const auto wave = body.reduced (0.0f, body.getHeight() >= 14.0f ? 2.0f : 1.0f);
  712. const auto total = (double) summary->frames;
  713. const auto perTick = clipops::framesPerTick (channel.sampler, total, summary->sampleRate, song.bpm);
  714. // r's left edge is the clip start, i.e. tick `offset` of the audio (counted from the file's end when
  715. // the channel is reversed)
  716. const auto startTick = (double) c.offset + (double) (wave.getX() - r.getX()) / pixelsPerTick;
  717. const auto forward = ! channel.sampler.reverse;
  718. const auto startFrame = forward ? startTick * perTick : total - startTick * perTick;
  719. auto style = ui::currentWaveStyle (clipContentColour (colour), juce::jmin (ui::normalisingGain (*summary), 4.0f) * c.gain);
  720. if (! style.spectral && c.gain > 1.0f) // louder clip gain: the shape may hit the top, which is honest
  721. style.gain = juce::jmin (style.gain, 8.0f);
  722. ui::paintWaveform (g, wave, *summary, startFrame, (forward ? perTick : -perTick) / pixelsPerTick, style);
  723. }
  724. paintClipOutline (g, r, colour, false, false);
  725. // fades: a shaded ramp over the body and a handle at the header's corner
  726. if (c.fadeIn > 0 || c.fadeOut > 0)
  727. {
  728. const auto inX = r.getX() + (float) (c.fadeIn * pixelsPerTick);
  729. const auto outX = r.getRight() - (float) (c.fadeOut * pixelsPerTick);
  730. const auto shade = theme::colour::bg0.withAlpha (0.45f);
  731. const auto line = clipContentColour (colour).withAlpha (0.9f);
  732. if (c.fadeIn > 0)
  733. {
  734. juce::Path p;
  735. p.startNewSubPath (body.getX(), body.getY());
  736. p.lineTo (inX, body.getY());
  737. p.lineTo (body.getX(), body.getBottom());
  738. p.closeSubPath();
  739. g.setColour (shade);
  740. g.fillPath (p);
  741. g.setColour (line);
  742. g.drawLine (body.getX(), body.getBottom(), inX, body.getY(), 1.2f);
  743. }
  744. if (c.fadeOut > 0)
  745. {
  746. juce::Path p;
  747. p.startNewSubPath (outX, body.getY());
  748. p.lineTo (body.getRight(), body.getY());
  749. p.lineTo (body.getRight(), body.getBottom());
  750. p.closeSubPath();
  751. g.setColour (shade);
  752. g.fillPath (p);
  753. g.setColour (line);
  754. g.drawLine (outX, body.getY(), body.getRight(), body.getBottom(), 1.2f);
  755. }
  756. }
  757. }
  758. juce::Colour PlaylistComponent::audioClipColour (const ChannelDef& channel)
  759. {
  760. return channel.colour != 0 ? theme::tame (juce::Colour (channel.colour)) : theme::colour::audioClip;
  761. }
  762. void PlaylistComponent::paintAutomationClip (juce::Graphics& g, const Clip& c, juce::Rectangle<float> r)
  763. {
  764. const auto& song = engine.getSong();
  765. if (c.automation < 0 || c.automation >= (int) song.automations.size())
  766. return;
  767. const auto& automation = song.automations[(std::size_t) c.automation];
  768. const auto colour = automation.target.kind == AutomationTargetKind::none ? theme::colour::textDisabled
  769. : theme::colour::automation.withMultipliedSaturation (0.75f).withMultipliedBrightness (0.8f);
  770. paintClipFrame (g, r, colour, juce::String::fromUTF8 (automation.name.c_str()), ClipGlyph::automation);
  771. paintClipOutline (g, r, colour, false, false);
  772. // automation curve over the clip's range
  773. const auto body = r.withTrimmedTop (14.0f).reduced (1.0f, 2.0f);
  774. const auto clip = g.getClipBounds().toFloat();
  775. juce::Path curve;
  776. bool started = false;
  777. for (auto x = std::max (body.getX(), clip.getX()); x <= std::min (body.getRight(), clip.getRight()); x += 2.0f)
  778. {
  779. const auto value = automation.valueAt ((double) c.offset + xToTick ((int) x) - (double) c.start);
  780. const auto y = body.getBottom() - value * body.getHeight();
  781. if (! started)
  782. curve.startNewSubPath (x, y);
  783. else
  784. curve.lineTo (x, y);
  785. started = true;
  786. }
  787. g.setColour (automation.target.kind == AutomationTargetKind::none ? theme::colour::textSecondary : theme::colour::automation.brighter (0.3f));
  788. g.strokePath (curve, juce::PathStrokeType (1.5f));
  789. // the points inside the clip, as handles (edited right here)
  790. if (r.getWidth() > 24.0f)
  791. for (const auto& p : automation.points)
  792. {
  793. const auto songTick = (double) (c.start + p.tick - c.offset);
  794. if (songTick < (double) c.start || songTick > (double) c.end())
  795. continue;
  796. const auto x = (float) tickToX (songTick);
  797. const auto y = body.getBottom() - p.value * body.getHeight();
  798. g.setColour (theme::colour::bg0);
  799. g.fillEllipse (x - 3.5f, y - 3.5f, 7.0f, 7.0f);
  800. g.setColour (theme::colour::automation.brighter (0.5f));
  801. g.fillEllipse (x - 2.5f, y - 2.5f, 5.0f, 5.0f);
  802. }
  803. }
  804. juce::Rectangle<float> PlaylistComponent::automationBody (const Clip& c) const
  805. {
  806. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  807. const auto y = (float) trackToY (c.track);
  808. const auto r = juce::Rectangle<float> (x0, y + 1.0f, juce::jmax (3.0f, x1 - x0 - 1.0f), (float) heightOf (c.track) - 3.0f);
  809. return r.withTrimmedTop (juce::jmin (14.0f, r.getHeight() * 0.4f)).reduced (1.0f, 2.0f);
  810. }
  811. int PlaylistComponent::automationPointAt (int clip, juce::Point<int> pos) const
  812. {
  813. const auto& song = engine.getSong();
  814. if (clip < 0 || clip >= (int) song.playlist.size() || song.playlist[(std::size_t) clip].kind != ClipKind::automation)
  815. return -1;
  816. const auto& c = song.playlist[(std::size_t) clip];
  817. if (c.automation < 0 || c.automation >= (int) song.automations.size())
  818. return -1;
  819. const auto body = automationBody (c);
  820. const auto& points = song.automations[(std::size_t) c.automation].points;
  821. for (int i = (int) points.size() - 1; i >= 0; --i)
  822. {
  823. const auto songTick = (double) (c.start + points[(std::size_t) i].tick - c.offset);
  824. if (songTick < (double) c.start || songTick > (double) c.end())
  825. continue;
  826. const juce::Point<float> at ((float) tickToX (songTick), body.getBottom() - points[(std::size_t) i].value * body.getHeight());
  827. if (at.getDistanceFrom (pos.toFloat()) <= 6.0f)
  828. return i;
  829. }
  830. return -1;
  831. }
  832. bool PlaylistComponent::isOnAutomationCurve (int clip, juce::Point<int> pos) const
  833. {
  834. const auto& song = engine.getSong();
  835. if (clip < 0 || clip >= (int) song.playlist.size() || song.playlist[(std::size_t) clip].kind != ClipKind::automation)
  836. return false;
  837. const auto& c = song.playlist[(std::size_t) clip];
  838. if (c.automation < 0 || c.automation >= (int) song.automations.size())
  839. return false;
  840. const auto body = automationBody (c);
  841. if (! body.expanded (0.0f, 4.0f).contains (pos.toFloat()))
  842. return false;
  843. const auto value = song.automations[(std::size_t) c.automation].valueAt ((double) c.offset + xToTick (pos.x) - (double) c.start);
  844. return std::abs (body.getBottom() - value * body.getHeight() - (float) pos.y) <= 5.0f;
  845. }
  846. int PlaylistComponent::fadeHandleAt (int index, juce::Point<int> p) const
  847. {
  848. const auto& c = engine.getSong().playlist[(std::size_t) index];
  849. if (c.kind != ClipKind::audio)
  850. return 0;
  851. const auto y = trackToY (c.track) + 1 + 15;
  852. const auto inX = tickToX ((double) c.start) + c.fadeIn * pixelsPerTick;
  853. const auto outX = tickToX ((double) c.end()) - c.fadeOut * pixelsPerTick;
  854. if (std::abs (p.y - y) > 6)
  855. return 0;
  856. if (std::abs (p.x - (inX + 2.0)) <= 6.0)
  857. return 1;
  858. if (std::abs (p.x - (outX - 2.0)) <= 6.0)
  859. return 2;
  860. return 0;
  861. }
  862. int PlaylistComponent::clipAt (int x, int y, bool& onRightEdge) const
  863. {
  864. bool left = false;
  865. return clipAt (x, y, onRightEdge, left);
  866. }
  867. int PlaylistComponent::clipAt (int x, int y, bool& onRightEdge, bool& onLeftEdge) const
  868. {
  869. const auto& playlist = engine.getSong().playlist;
  870. const auto track = yToTrack (y);
  871. onRightEdge = onLeftEdge = false;
  872. for (int i = (int) playlist.size() - 1; i >= 0; --i)
  873. {
  874. const auto& c = playlist[(std::size_t) i];
  875. if (c.track != track)
  876. continue;
  877. // the left edge only on clips wide enough to still be grabbed in the middle
  878. gesture::EdgeRules rules;
  879. rules.minimumForLeft = 24.0;
  880. if (const auto zone = gesture::zoneAt (x, tickToX ((double) c.start), tickToX ((double) c.end()), rules); zone != gesture::Zone::outside)
  881. {
  882. onRightEdge = zone == gesture::Zone::rightEdge;
  883. onLeftEdge = zone == gesture::Zone::leftEdge;
  884. return i;
  885. }
  886. }
  887. return -1;
  888. }
  889. void PlaylistComponent::seekTo (int x)
  890. {
  891. const auto tick = juce::jmax (0.0, (double) snap (xToTick (x), true));
  892. if (engine.getSong().mode != PlayMode::song)
  893. engine.editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  894. engine.seek (tick);
  895. playheadTick = tick;
  896. repaint();
  897. }
  898. bool PlaylistComponent::isSelected (int index) const
  899. {
  900. return std::binary_search (selection.begin(), selection.end(), index);
  901. }
  902. void PlaylistComponent::setSelection (std::vector<int> indices)
  903. {
  904. std::sort (indices.begin(), indices.end());
  905. indices.erase (std::unique (indices.begin(), indices.end()), indices.end());
  906. selection = std::move (indices);
  907. knownClipCount = engine.getSong().playlist.size();
  908. repaint();
  909. }
  910. void PlaylistComponent::sortClips()
  911. {
  912. auto tracked = selection;
  913. engine.editSong ([&tracked] (Song& s) { noteedit::sortByStartTracking (s.playlist, tracked); }, false);
  914. setSelection (tracked);
  915. }
  916. Clip PlaylistComponent::makeBrushClip (int track, std::int64_t start) const
  917. {
  918. // what is chosen in the Picker: the current pattern, an audio clip or an automation clip
  919. const auto& song = engine.getSong();
  920. Clip c;
  921. c.pattern = song.currentPattern;
  922. c.track = track;
  923. c.start = juce::jmax<std::int64_t> (0, start);
  924. c.length = song.patterns[(std::size_t) song.currentPattern].effectiveLength (song.beatsPerBar);
  925. if (brush.kind == ClipKind::audio && brush.index >= 0 && brush.index < (int) song.channels.size()
  926. && song.channels[(std::size_t) brush.index].instrument == InstrumentKind::audioClip)
  927. {
  928. c.kind = ClipKind::audio;
  929. c.channel = brush.index;
  930. c.pattern = 0;
  931. // audio length in ticks at the current BPM
  932. if (auto data = engine.getSampleLibrary().load (juce::String::fromUTF8 (song.channels[(std::size_t) brush.index].samplePath.c_str())))
  933. c.length = juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) ((double) data->frames() / data->sampleRate * song.bpm / 60.0 * ppq));
  934. }
  935. else if (brush.kind == ClipKind::automation && brush.index >= 0 && brush.index < (int) song.automations.size())
  936. {
  937. c.kind = ClipKind::automation;
  938. c.automation = brush.index;
  939. c.pattern = 0;
  940. c.length = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar) * 4; // 4 bars
  941. }
  942. return c;
  943. }
  944. void PlaylistComponent::setTimeSelection (std::int64_t from, std::int64_t to)
  945. {
  946. engine.editSong ([from, to] (Song& s) {
  947. s.loopStart = from;
  948. s.loopEnd = to;
  949. s.mode = PlayMode::song;
  950. }, false);
  951. setSelection (to > from ? noteedit::clipsInTime (engine.getSong().playlist, from, to) : std::vector<int> {});
  952. }
  953. void PlaylistComponent::setTimeSelectionForSnapshot (int fromBar, int toBar)
  954. {
  955. const auto bar = (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  956. setTimeSelection (fromBar * bar, toBar * bar);
  957. }
  958. void PlaylistComponent::setViewForSnapshot (double pixelsPerBar, int firstBar, int firstTrack)
  959. {
  960. const auto bar = (double) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  961. pixelsPerTick = pixelsPerBar / bar;
  962. scrollTicks = firstBar * bar;
  963. scrollY = juce::jmax (0, firstTrack) * trackHeight;
  964. updateScrollBars();
  965. repaint();
  966. }
  967. ui::Hint PlaylistComponent::hoverForSnapshot()
  968. {
  969. const auto& playlist = engine.getSong().playlist;
  970. const auto grid = gridArea();
  971. // the last clip fully in view (the floating Channel Rack tends to cover the first ones)
  972. for (int i = (int) playlist.size() - 1; i >= 0; --i)
  973. if (const auto r = clipBounds (i); grid.contains (r) && r.getWidth() >= 40 && playlist[(std::size_t) i].kind == ClipKind::pattern)
  974. {
  975. const auto at = juce::Point<int> (r.getRight() - 2, r.getCentreY() + 4);
  976. updateHover (at, {});
  977. return hintAt (at);
  978. }
  979. return {};
  980. }
  981. void PlaylistComponent::mouseDown (const juce::MouseEvent& e)
  982. {
  983. downMods = e.mods;
  984. startedOnEmpty = erasedSomething = holdExpired = false;
  985. hover = {};
  986. gliding = false;
  987. if (e.mods.isMiddleButtonDown() && e.x >= headerWidth) // middle-drag pans, in every tool
  988. {
  989. drag = Drag::pan;
  990. panStartTicks = scrollTicks;
  991. panStartY = scrollY;
  992. setMouseCursor (editorCursor (gesture::Cursor::pan));
  993. return;
  994. }
  995. // track header divider: drag resizes the track above it (Shift: every track)
  996. if (const auto divider = dividerAt (e.getPosition()); divider >= 0 && e.mods.isLeftButtonDown())
  997. {
  998. drag = Drag::trackResize;
  999. resizeTrack = divider;
  1000. resizeAll = e.mods.isShiftDown();
  1001. resizeStartHeight = heightOf (divider);
  1002. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  1003. return;
  1004. }
  1005. // track header: the LED mutes (Ctrl+click or right-click on it: solo); right-click elsewhere: track menu
  1006. if (e.x < headerWidth && e.y >= headerHeight && e.y < gridArea().getBottom())
  1007. {
  1008. const auto track = yToTrack (e.y);
  1009. const auto onLed = e.x < 20;
  1010. if (onLed && (e.mods.isPopupMenu() || e.mods.isCtrlDown()))
  1011. engine.editSong ([track, count = numTracks()] (Song& s) { noteedit::soloTrack (s, track, count); });
  1012. else if (e.mods.isPopupMenu())
  1013. showTrackMenu (track);
  1014. else if (onLed)
  1015. engine.editSong ([track] (Song& s) {
  1016. if ((int) s.playlistTracks.size() <= track)
  1017. s.playlistTracks.resize ((std::size_t) track + 1);
  1018. s.playlistTracks[(std::size_t) track].muted = ! s.playlistTracks[(std::size_t) track].muted;
  1019. });
  1020. return;
  1021. }
  1022. // ruler: click = position; Ctrl+drag = time selection (Ctrl+click or double click clears it)
  1023. if (e.y >= toolbarHeight && e.y < headerHeight && e.x >= headerWidth)
  1024. {
  1025. if (e.mods.isPopupMenu())
  1026. {
  1027. showRulerMenu (e.x);
  1028. return;
  1029. }
  1030. if (e.getNumberOfClicks() >= 2)
  1031. {
  1032. setTimeSelection (0, 0);
  1033. return;
  1034. }
  1035. loopAnchor = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), ! e.mods.isAltDown()));
  1036. // Shift+drag inside the time selection moves it with what it holds (Ctrl+Shift: a copy)
  1037. if (const auto& song = engine.getSong(); e.mods.isShiftDown() && song.hasLoop() && xToTick (e.x) >= (double) song.loopStart
  1038. && xToTick (e.x) < (double) song.loopEnd)
  1039. {
  1040. drag = Drag::timeMove;
  1041. timeMoveOriginals = song.playlist;
  1042. timeMoveFrom = song.loopStart;
  1043. timeMoveTo = song.loopEnd;
  1044. timeMoveAnchor = loopAnchor;
  1045. timeMoveCopy = e.mods.isCtrlDown();
  1046. return;
  1047. }
  1048. if (e.mods.isCtrlDown())
  1049. {
  1050. drag = Drag::loop;
  1051. return;
  1052. }
  1053. drag = Drag::seek;
  1054. seekTo (e.x);
  1055. EditorGlobals::get().seekMark = (std::int64_t) juce::jmax (0.0, (double) snap (xToTick (e.x), true));
  1056. return;
  1057. }
  1058. if (! gridArea().contains (e.getPosition()))
  1059. return;
  1060. bool rightEdge = false, leftEdge = false;
  1061. const auto hit = clipAt (e.x, e.y, rightEdge, leftEdge);
  1062. const auto tool = tools.getTool();
  1063. // Ctrl+right-click on empty space: zoom to show everything; again: back to the previous view
  1064. if (e.mods.isRightButtonDown() && e.mods.isCtrlDown() && hit < 0)
  1065. {
  1066. if (zoomBeforeAll > 0.0)
  1067. {
  1068. pixelsPerTick = zoomBeforeAll;
  1069. scrollTicks = scrollBeforeAll;
  1070. zoomBeforeAll = 0.0;
  1071. updateScrollBars();
  1072. repaint();
  1073. }
  1074. else
  1075. {
  1076. zoomBeforeAll = pixelsPerTick;
  1077. scrollBeforeAll = scrollTicks;
  1078. zoomAll();
  1079. }
  1080. return;
  1081. }
  1082. // the menu button in a clip's title strip
  1083. if (hit >= 0 && e.mods.isLeftButtonDown() && ! e.mods.isCtrlDown() && clipMenuButton (hit).contains (e.getPosition()))
  1084. {
  1085. showClipMenu (hit);
  1086. return;
  1087. }
  1088. // Alt+right-click on a clip: hear it while the button is held
  1089. if (e.mods.isRightButtonDown() && e.mods.isAltDown() && hit >= 0)
  1090. {
  1091. startPreview (hit, e.x);
  1092. return;
  1093. }
  1094. if (e.mods.isRightButtonDown())
  1095. {
  1096. // on an automation point: delete that point
  1097. if (const auto point = automationPointAt (hit, e.getPosition()); point >= 0)
  1098. {
  1099. const auto automation = engine.getSong().playlist[(std::size_t) hit].automation;
  1100. engine.editSong ([automation, point] (Song& s) {
  1101. auto& points = s.automations[(std::size_t) automation].points;
  1102. if (points.size() > 1 && point < (int) points.size())
  1103. points.erase (points.begin() + point);
  1104. });
  1105. return;
  1106. }
  1107. // on the name strip: clip menu; on the body: delete (press and hold on empty space: Knife)
  1108. if (hit >= 0 && e.y < trackToY (engine.getSong().playlist[(std::size_t) hit].track) + 15)
  1109. {
  1110. showClipMenu (hit);
  1111. return;
  1112. }
  1113. // double right-click on a clip: the first click deleted it; bring it back muted (or unmuted)
  1114. if (e.getNumberOfClicks() >= 2 && lastClipEraseTime != 0 && lastClipErasePos.getDistanceFrom (e.getPosition()) < 6
  1115. && juce::Time::getMillisecondCounter() - lastClipEraseTime < 1000)
  1116. {
  1117. lastClipEraseTime = 0;
  1118. engine.undo();
  1119. bool r = false, l = false;
  1120. if (const auto clip = clipAt (e.x, e.y, r, l); clip >= 0)
  1121. engine.editSong ([clip] (Song& s) { s.playlist[(std::size_t) clip].muted = ! s.playlist[(std::size_t) clip].muted; });
  1122. return;
  1123. }
  1124. drag = Drag::erase;
  1125. startedOnEmpty = hit < 0;
  1126. setSelection ({}); // indices change while deleting
  1127. lastClipEraseTime = 0;
  1128. if (hit >= 0)
  1129. {
  1130. erasedSomething = true;
  1131. lastClipEraseTime = juce::Time::getMillisecondCounter();
  1132. lastClipErasePos = e.getPosition();
  1133. engine.editSong ([hit] (Song& s) { s.playlist.erase (s.playlist.begin() + hit); });
  1134. }
  1135. return;
  1136. }
  1137. // every tool: Ctrl+click on a clip adds/removes it from the selection; Ctrl+drag selects (Shift adds)
  1138. if (hit >= 0 && e.mods.isCtrlDown())
  1139. {
  1140. auto s = selection;
  1141. if (isSelected (hit))
  1142. s.erase (std::find (s.begin(), s.end(), hit));
  1143. else
  1144. s.push_back (hit);
  1145. setSelection (s);
  1146. return;
  1147. }
  1148. if ((hit < 0 && e.mods.isCtrlDown()) || tool == EditTool::lasso
  1149. || (hit < 0 && e.mods.isShiftDown() && tool != EditTool::brush))
  1150. {
  1151. drag = Drag::select;
  1152. dragClip = hit; // a Lasso click without dragging selects this clip
  1153. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  1154. rubberBand = {};
  1155. setSelection (selectionBefore);
  1156. return;
  1157. }
  1158. const auto snapOn = ! e.mods.isAltDown();
  1159. auto grabClips = [&] (Drag kind) {
  1160. if (! isSelected (hit))
  1161. setSelection ({});
  1162. const auto& playlist = engine.getSong().playlist;
  1163. dragClip = hit;
  1164. dragIndices = selection.empty() ? std::vector<int> { hit } : selection;
  1165. dragOriginals.clear();
  1166. for (auto i : dragIndices)
  1167. dragOriginals.push_back (playlist[(std::size_t) i]);
  1168. drag = kind;
  1169. grabOffset = playlist[(std::size_t) hit].start - snap (xToTick (e.x), snapOn);
  1170. };
  1171. switch (tool)
  1172. {
  1173. case EditTool::eraser:
  1174. drag = Drag::erase;
  1175. setSelection ({});
  1176. if (hit >= 0)
  1177. engine.editSong ([hit] (Song& s) { s.playlist.erase (s.playlist.begin() + hit); });
  1178. return;
  1179. case EditTool::mute:
  1180. drag = Drag::muting;
  1181. touchedClips.clear();
  1182. muteTarget = true;
  1183. if (hit >= 0)
  1184. {
  1185. muteTarget = ! engine.getSong().playlist[(std::size_t) hit].muted;
  1186. touchedClips.push_back (hit);
  1187. engine.editSong ([hit, m = muteTarget] (Song& s) { s.playlist[(std::size_t) hit].muted = m; });
  1188. }
  1189. return;
  1190. case EditTool::knife:
  1191. drag = Drag::knife;
  1192. knifeFrom = knifeTo = e.getPosition();
  1193. repaint();
  1194. return;
  1195. case EditTool::zoom:
  1196. drag = Drag::zoomRange;
  1197. rubberBand = {};
  1198. return;
  1199. case EditTool::listen:
  1200. drag = Drag::listen;
  1201. seekTo (e.x);
  1202. engine.play();
  1203. return;
  1204. case EditTool::slip:
  1205. if (hit >= 0)
  1206. grabClips (Drag::slip);
  1207. return;
  1208. case EditTool::pencil:
  1209. case EditTool::brush:
  1210. case EditTool::drumPaint:
  1211. case EditTool::lasso:
  1212. break;
  1213. }
  1214. // automation clip: drag a point, or click on the curve to add one (Pencil and Brush)
  1215. if (hit >= 0 && ! e.mods.isShiftDown() && (tool == EditTool::pencil || tool == EditTool::brush))
  1216. {
  1217. auto point = automationPointAt (hit, e.getPosition());
  1218. if (point < 0 && isOnAutomationCurve (hit, e.getPosition()))
  1219. {
  1220. const auto& c = engine.getSong().playlist[(std::size_t) hit];
  1221. AutomationPoint p;
  1222. p.tick = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn) - c.start + c.offset);
  1223. const auto body = automationBody (c);
  1224. p.value = juce::jlimit (0.0f, 1.0f, (body.getBottom() - (float) e.y) / juce::jmax (1.0f, body.getHeight()));
  1225. engine.editSong ([a = c.automation, p] (Song& s) {
  1226. auto& points = s.automations[(std::size_t) a].points;
  1227. points.push_back (p);
  1228. std::stable_sort (points.begin(), points.end(), [] (auto& l, auto& r) { return l.tick < r.tick; });
  1229. });
  1230. point = automationPointAt (hit, e.getPosition());
  1231. }
  1232. if (point >= 0)
  1233. {
  1234. setSelection ({});
  1235. drag = Drag::autoPoint;
  1236. autoClip = hit;
  1237. autoPoint = point;
  1238. return;
  1239. }
  1240. }
  1241. // audio clip fade handles (drawn at the top corners of the body)
  1242. if (hit >= 0)
  1243. if (const auto fade = fadeHandleAt (hit, e.getPosition()); fade != 0)
  1244. {
  1245. setSelection ({});
  1246. dragClip = hit;
  1247. dragIndices = { hit };
  1248. drag = fade == 1 ? Drag::fadeIn : Drag::fadeOut;
  1249. return;
  1250. }
  1251. // Alt+Shift+drag inside a clip: slip its content
  1252. if (hit >= 0 && e.mods.isAltDown() && e.mods.isShiftDown() && ! rightEdge && ! leftEdge)
  1253. {
  1254. grabClips (Drag::slip);
  1255. return;
  1256. }
  1257. // Shift+drag on a clip body drags a copy (on an edge, Shift trims like a plain edge drag)
  1258. if (hit >= 0 && e.mods.isShiftDown() && ! rightEdge && ! leftEdge)
  1259. {
  1260. const auto sources = isSelected (hit) ? selection : std::vector<int> { hit };
  1261. const auto grabbedAt = (std::size_t) (std::find (sources.begin(), sources.end(), hit) - sources.begin());
  1262. std::vector<Clip> copies;
  1263. std::vector<int> added;
  1264. for (auto i : sources)
  1265. copies.push_back (engine.getSong().playlist[(std::size_t) i]);
  1266. // Shift+V held: the copies get their own pattern / automation (FL's "make unique" while cloning)
  1267. const auto unique = juce::KeyPress::isKeyCurrentlyDown ('V') || juce::KeyPress::isKeyCurrentlyDown ('v');
  1268. engine.editSong ([&] (Song& s) {
  1269. for (const auto& c : copies)
  1270. {
  1271. added.push_back ((int) s.playlist.size());
  1272. s.playlist.push_back (c);
  1273. }
  1274. if (unique)
  1275. polish::makeClipsUnique (s, added);
  1276. });
  1277. if (unique)
  1278. for (std::size_t j = 0; j < added.size(); ++j)
  1279. copies[j] = engine.getSong().playlist[(std::size_t) added[j]];
  1280. setSelection (added);
  1281. dragIndices = added;
  1282. dragOriginals = copies;
  1283. dragClip = added[grabbedAt];
  1284. drag = Drag::move;
  1285. grabOffset = copies[grabbedAt].start - snap (xToTick (e.x), snapOn);
  1286. return;
  1287. }
  1288. if (hit >= 0)
  1289. {
  1290. grabClips (rightEdge ? Drag::resize : leftEdge ? Drag::trimLeft : Drag::move);
  1291. if (drag == Drag::resize && ripple)
  1292. {
  1293. setSelection ({}); // a ripple resize works on the grabbed clip only
  1294. dragIndices = { hit };
  1295. dragOriginals = { engine.getSong().playlist[(std::size_t) hit] };
  1296. rippleOriginals = engine.getSong().playlist;
  1297. }
  1298. const auto& c = engine.getSong().playlist[(std::size_t) hit];
  1299. if (c.kind == ClipKind::pattern && c.pattern != engine.getSong().currentPattern)
  1300. engine.editSong ([p = c.pattern] (Song& s) { s.currentPattern = p; }, false);
  1301. return;
  1302. }
  1303. // paints what is chosen in the Picker (the current pattern, an audio clip or an automation clip)
  1304. setSelection ({});
  1305. const auto c = makeBrushClip (yToTrack (e.y), snap (xToTick (e.x), snapOn));
  1306. if (c.kind == ClipKind::pattern)
  1307. brush = {};
  1308. engine.editSong ([c] (Song& s) {
  1309. s.playlist.push_back (c);
  1310. s.mode = PlayMode::song; // someone arranging wants to hear the song
  1311. });
  1312. dragClip = (int) engine.getSong().playlist.size() - 1;
  1313. dragIndices = { dragClip };
  1314. dragOriginals = { c };
  1315. grabOffset = 0;
  1316. if (tool == EditTool::brush)
  1317. {
  1318. drag = Drag::paint;
  1319. paintClip = c;
  1320. nextPaintTick = c.end();
  1321. return;
  1322. }
  1323. drag = Drag::move;
  1324. }
  1325. void PlaylistComponent::mouseDrag (const juce::MouseEvent& e)
  1326. {
  1327. if (drag == Drag::trackResize)
  1328. {
  1329. const auto height = polish::clampTrackHeight (resizeStartHeight + e.getDistanceFromDragStartY());
  1330. std::vector<int> tracks;
  1331. if (resizeAll)
  1332. for (int t = 0; t < numTracks(); ++t)
  1333. tracks.push_back (t);
  1334. else
  1335. tracks.push_back (resizeTrack);
  1336. if (heightOf (resizeTrack) != height)
  1337. setTrackHeights (tracks, height);
  1338. ui::postHint ({ resizeAll ? tr ("Resizing every track") : tr ("Resizing the track"), juce::String (height) + " px", false, false });
  1339. return;
  1340. }
  1341. if (drag == Drag::preview)
  1342. return;
  1343. const auto snapOn = ! e.mods.isAltDown();
  1344. // after the step below, the hint bar says what the gesture is doing
  1345. const struct PostAfter
  1346. {
  1347. PlaylistComponent& list;
  1348. ~PostAfter() { list.postDragHint(); }
  1349. } postAfter { *this };
  1350. switch (drag)
  1351. {
  1352. case Drag::none:
  1353. case Drag::trackResize:
  1354. case Drag::preview:
  1355. return;
  1356. case Drag::pan:
  1357. scrollTicks = juce::jmax (0.0, panStartTicks - e.getDistanceFromDragStartX() / pixelsPerTick);
  1358. scrollY = juce::jmax (0, panStartY - e.getDistanceFromDragStartY());
  1359. updateScrollBars();
  1360. repaint();
  1361. return;
  1362. case Drag::autoPoint:
  1363. {
  1364. const auto& song = engine.getSong();
  1365. if (autoClip < 0 || autoClip >= (int) song.playlist.size())
  1366. return;
  1367. const auto& c = song.playlist[(std::size_t) autoClip];
  1368. if (c.automation < 0 || c.automation >= (int) song.automations.size())
  1369. return;
  1370. const auto& points = song.automations[(std::size_t) c.automation].points;
  1371. if (autoPoint < 0 || autoPoint >= (int) points.size())
  1372. return;
  1373. // the point stays between its neighbours; Shift pressed after the click keeps the time, Ctrl the value
  1374. auto tick = snap (xToTick (e.x), snapOn) - c.start + c.offset;
  1375. const auto lo = autoPoint > 0 ? points[(std::size_t) autoPoint - 1].tick : 0;
  1376. const auto hi = autoPoint + 1 < (int) points.size() ? points[(std::size_t) autoPoint + 1].tick : std::numeric_limits<std::int64_t>::max();
  1377. tick = juce::jlimit (lo, hi, tick);
  1378. const auto body = automationBody (c);
  1379. auto value = juce::jlimit (0.0f, 1.0f, (body.getBottom() - (float) e.y) / juce::jmax (1.0f, body.getHeight()));
  1380. if (e.mods.isShiftDown() && ! downMods.isShiftDown())
  1381. tick = points[(std::size_t) autoPoint].tick;
  1382. if (e.mods.isCtrlDown() && ! downMods.isCtrlDown())
  1383. value = points[(std::size_t) autoPoint].value;
  1384. engine.editSong ([a = c.automation, i = autoPoint, tick, value] (Song& s) {
  1385. auto& p = s.automations[(std::size_t) a].points[(std::size_t) i];
  1386. p.tick = tick;
  1387. p.value = value;
  1388. });
  1389. return;
  1390. }
  1391. case Drag::timeMove:
  1392. {
  1393. const auto here = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  1394. const auto delta = juce::jmax (-timeMoveFrom, here - timeMoveAnchor);
  1395. std::vector<int> moved;
  1396. engine.editSong ([&] (Song& s) {
  1397. s.playlist = timeMoveOriginals;
  1398. moved = noteedit::moveTimeRange (s.playlist, timeMoveFrom, timeMoveTo, delta, timeMoveCopy);
  1399. s.loopStart = timeMoveFrom + delta;
  1400. s.loopEnd = timeMoveTo + delta;
  1401. });
  1402. setSelection (moved);
  1403. return;
  1404. }
  1405. case Drag::seek:
  1406. case Drag::listen:
  1407. seekTo (e.x);
  1408. return;
  1409. case Drag::loop:
  1410. {
  1411. const auto here = juce::jmax<std::int64_t> (0, snap (xToTick (e.x) + (snapOn ? gridTicks() / 2.0 : 0.0), snapOn));
  1412. setTimeSelection (juce::jmin (loopAnchor, here), juce::jmax (loopAnchor, here));
  1413. return;
  1414. }
  1415. case Drag::fadeIn:
  1416. case Drag::fadeOut:
  1417. {
  1418. const auto& clip = engine.getSong().playlist[(std::size_t) dragClip];
  1419. const auto tick = snapOn ? snap (xToTick (e.x) + gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  1420. auto length = drag == Drag::fadeIn ? tick - clip.start : clip.end() - tick;
  1421. length = juce::jlimit<std::int64_t> (0, clip.length, length);
  1422. const auto in = drag == Drag::fadeIn;
  1423. if ((in ? clip.fadeIn : clip.fadeOut) == std::min (length, clip.length - (in ? clip.fadeOut : clip.fadeIn)))
  1424. return;
  1425. engine.editSong ([i = dragClip, length, in] (Song& s) {
  1426. auto& c = s.playlist[(std::size_t) i];
  1427. (in ? c.fadeIn : c.fadeOut) = std::min (length, c.length - (in ? c.fadeOut : c.fadeIn));
  1428. });
  1429. return;
  1430. }
  1431. case Drag::select:
  1432. case Drag::zoomRange:
  1433. {
  1434. if (e.getDistanceFromDragStart() < 3 && rubberBand.isEmpty())
  1435. return;
  1436. const auto area = gridArea();
  1437. rubberBand = juce::Rectangle<int> (e.getMouseDownPosition(), e.getPosition()).getIntersection (area);
  1438. if (drag == Drag::zoomRange)
  1439. {
  1440. rubberBand = rubberBand.withY (area.getY()).withHeight (area.getHeight());
  1441. repaint();
  1442. return;
  1443. }
  1444. const auto t0 = xToTick (rubberBand.getX()), t1 = xToTick (rubberBand.getRight());
  1445. const auto tr0 = yToTrack (rubberBand.getY()), tr1 = yToTrack (rubberBand.getBottom());
  1446. const auto& playlist = engine.getSong().playlist;
  1447. auto s = selectionBefore;
  1448. for (int i = 0; i < (int) playlist.size(); ++i)
  1449. {
  1450. const auto& c = playlist[(std::size_t) i];
  1451. if ((double) c.end() > t0 && (double) c.start < t1 && c.track >= tr0 && c.track <= tr1)
  1452. s.push_back (i);
  1453. }
  1454. setSelection (s);
  1455. return;
  1456. }
  1457. case Drag::erase:
  1458. {
  1459. // right press-and-hold on empty space, then drag: a temporary Knife
  1460. if (e.mods.isRightButtonDown() && startedOnEmpty && ! erasedSomething && ! holdExpired)
  1461. {
  1462. if (e.getLengthOfMousePress() >= 350)
  1463. {
  1464. drag = Drag::knife;
  1465. knifeFrom = e.getMouseDownPosition();
  1466. knifeTo = e.getPosition();
  1467. repaint();
  1468. return;
  1469. }
  1470. if (e.getDistanceFromDragStart() > 3)
  1471. holdExpired = true;
  1472. }
  1473. bool edge = false;
  1474. const auto hit = clipAt (e.x, e.y, edge);
  1475. if (hit >= 0)
  1476. {
  1477. erasedSomething = true;
  1478. engine.editSong ([hit] (Song& s) { s.playlist.erase (s.playlist.begin() + hit); });
  1479. }
  1480. return;
  1481. }
  1482. case Drag::muting:
  1483. {
  1484. bool edge = false;
  1485. const auto hit = clipAt (e.x, e.y, edge);
  1486. if (hit >= 0 && std::find (touchedClips.begin(), touchedClips.end(), hit) == touchedClips.end())
  1487. {
  1488. touchedClips.push_back (hit);
  1489. engine.editSong ([hit, m = muteTarget] (Song& s) { s.playlist[(std::size_t) hit].muted = m; });
  1490. }
  1491. return;
  1492. }
  1493. case Drag::knife:
  1494. knifeTo = e.getPosition();
  1495. repaint();
  1496. return;
  1497. case Drag::paint:
  1498. {
  1499. // copies of the painted clip, end to end, on the track under the mouse
  1500. const auto tick = snap (xToTick (e.x), snapOn);
  1501. const auto length = juce::jmax<std::int64_t> (1, paintClip.length);
  1502. for (int guard = 0; tick >= nextPaintTick && guard < 64; ++guard)
  1503. {
  1504. auto c = paintClip;
  1505. c.start = nextPaintTick;
  1506. c.track = yToTrack (e.y);
  1507. engine.editSong ([c] (Song& s) { s.playlist.push_back (c); });
  1508. nextPaintTick += length;
  1509. }
  1510. return;
  1511. }
  1512. case Drag::slip:
  1513. {
  1514. // the content moves by the (snapped) mouse movement; the clips stay put
  1515. const auto delta = snap (xToTick (e.x), snapOn) - snap (xToTick (e.getMouseDownX()), snapOn);
  1516. const auto grabbedAt = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragClip) - dragIndices.begin());
  1517. auto probe = dragOriginals[grabbedAt];
  1518. noteedit::slip (probe, delta);
  1519. if (engine.getSong().playlist[(std::size_t) dragClip].offset == probe.offset)
  1520. return;
  1521. engine.editSong ([this, delta] (Song& s) {
  1522. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  1523. {
  1524. auto c = dragOriginals[j];
  1525. noteedit::slip (c, delta);
  1526. s.playlist[(std::size_t) dragIndices[j]].offset = c.offset;
  1527. }
  1528. });
  1529. return;
  1530. }
  1531. case Drag::move:
  1532. {
  1533. const auto grabbedAt = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragClip) - dragIndices.begin());
  1534. const auto& grabbed = dragOriginals[grabbedAt];
  1535. auto deltaTicks = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn) + grabOffset) - grabbed.start;
  1536. auto deltaTracks = yToTrack (e.y) - grabbed.track;
  1537. // the group keeps its shape: clamp by the leftmost / topmost clip
  1538. for (const auto& c : dragOriginals)
  1539. {
  1540. deltaTicks = juce::jmax (deltaTicks, -c.start);
  1541. deltaTracks = juce::jlimit (-c.track, 499 - c.track, deltaTracks);
  1542. }
  1543. const auto& current = engine.getSong().playlist[(std::size_t) dragClip];
  1544. if (current.start == grabbed.start + deltaTicks && current.track == grabbed.track + deltaTracks)
  1545. return;
  1546. engine.editSong ([this, deltaTicks, deltaTracks] (Song& s) {
  1547. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  1548. {
  1549. auto& c = s.playlist[(std::size_t) dragIndices[j]];
  1550. c.start = dragOriginals[j].start + deltaTicks;
  1551. c.track = dragOriginals[j].track + deltaTracks;
  1552. }
  1553. });
  1554. return;
  1555. }
  1556. case Drag::resize:
  1557. {
  1558. const auto grabbedAt = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragClip) - dragIndices.begin());
  1559. const auto& grabbed = dragOriginals[grabbedAt];
  1560. const auto minimum = snapOn ? juce::jmax<std::int64_t> (10, gridTicks()) : (std::int64_t) 10;
  1561. const auto end = snapOn ? snap (xToTick (e.x) + gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  1562. const auto delta = juce::jmax (minimum, end - grabbed.start) - grabbed.length;
  1563. if (engine.getSong().playlist[(std::size_t) dragClip].length == grabbed.length + delta)
  1564. return;
  1565. if (ripple && ! rippleOriginals.empty()) // the later clips on the track follow the end
  1566. {
  1567. engine.editSong ([this, length = juce::jmax (minimum, grabbed.length + delta)] (Song& s) {
  1568. s.playlist = rippleOriginals;
  1569. noteedit::rippleResize (s.playlist, dragClip, length);
  1570. });
  1571. return;
  1572. }
  1573. engine.editSong ([this, delta, minimum] (Song& s) {
  1574. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  1575. {
  1576. auto& c = s.playlist[(std::size_t) dragIndices[j]];
  1577. c.length = juce::jmax (minimum, dragOriginals[j].length + delta);
  1578. c.fadeIn = juce::jmin (c.fadeIn, c.length);
  1579. c.fadeOut = juce::jmin (c.fadeOut, c.length - c.fadeIn);
  1580. }
  1581. });
  1582. return;
  1583. }
  1584. case Drag::trimLeft:
  1585. {
  1586. // the start moves, the content stays where it is (the offset follows)
  1587. const auto grabbedAt = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragClip) - dragIndices.begin());
  1588. const auto& grabbed = dragOriginals[grabbedAt];
  1589. const auto minimum = snapOn ? juce::jmax<std::int64_t> (10, gridTicks()) : (std::int64_t) 10;
  1590. const auto start = snapOn ? snap (xToTick (e.x) + gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  1591. const auto delta = start - grabbed.start;
  1592. auto probe = grabbed;
  1593. noteedit::trimStart (probe, grabbed.start + delta, minimum);
  1594. if (engine.getSong().playlist[(std::size_t) dragClip].start == probe.start)
  1595. return;
  1596. engine.editSong ([this, delta, minimum] (Song& s) {
  1597. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  1598. {
  1599. auto c = dragOriginals[j];
  1600. noteedit::trimStart (c, c.start + delta, minimum);
  1601. s.playlist[(std::size_t) dragIndices[j]] = c;
  1602. }
  1603. });
  1604. return;
  1605. }
  1606. }
  1607. }
  1608. void PlaylistComponent::postDragHint()
  1609. {
  1610. const auto& song = engine.getSong();
  1611. const auto count = juce::String ((int) juce::jmax<std::size_t> (1, dragIndices.size()));
  1612. auto position = [&song] (std::int64_t tick) {
  1613. const auto bar = song.barAt (juce::jmax<std::int64_t> (0, tick));
  1614. const auto beat = (tick - bar.tick) / ppq + 1;
  1615. return juce::String (bar.number) + ":" + juce::String (beat);
  1616. };
  1617. const auto clip = dragClip >= 0 && dragClip < (int) song.playlist.size() ? &song.playlist[(std::size_t) dragClip] : nullptr;
  1618. ui::Hint hint;
  1619. switch (drag)
  1620. {
  1621. case Drag::move:
  1622. if (clip == nullptr)
  1623. return;
  1624. hint.text = tr ("Moving {0} clip(s) [Alt] no snap", { count });
  1625. hint.value = position (clip->start) + " " + tr ("Track {0}", { juce::String (clip->track + 1) });
  1626. break;
  1627. case Drag::resize:
  1628. case Drag::trimLeft:
  1629. if (clip == nullptr)
  1630. return;
  1631. hint.text = tr ("Resizing {0} clip(s) [Alt] no snap", { count });
  1632. hint.value = position (drag == Drag::resize ? clip->end() : clip->start);
  1633. break;
  1634. case Drag::slip: hint.text = tr ("Sliding the content inside the clip [Alt] no snap"); break;
  1635. case Drag::fadeIn:
  1636. case Drag::fadeOut: hint.text = tr ("Setting the fade [Alt] no snap"); break;
  1637. case Drag::autoPoint: hint.text = tr ("Moving the point: then [Shift] keeps time [Ctrl] keeps value"); break;
  1638. case Drag::select:
  1639. hint.text = tr ("Selecting [Shift] adds to the selection");
  1640. hint.value = tr ("{0} selected", { juce::String ((int) selection.size()) });
  1641. break;
  1642. case Drag::loop:
  1643. hint.text = tr ("Time selection");
  1644. hint.value = position (song.loopStart) + " - " + position (song.loopEnd);
  1645. break;
  1646. case Drag::erase: hint.text = tr ("Deleting what the mouse crosses"); break;
  1647. case Drag::muting: hint.text = tr ("Muting / unmuting what the mouse crosses"); break;
  1648. case Drag::knife: hint.text = tr ("Cutting along the line [Alt] no snap"); break;
  1649. case Drag::paint: hint.text = tr ("Painting clips [Alt] no snap"); break;
  1650. case Drag::timeMove: hint.text = tr ("Moving the time selection with its clips"); break;
  1651. case Drag::seek:
  1652. case Drag::listen:
  1653. case Drag::pan:
  1654. case Drag::zoomRange:
  1655. case Drag::trackResize:
  1656. case Drag::preview:
  1657. case Drag::none: return;
  1658. }
  1659. ui::postHint (hint);
  1660. }
  1661. void PlaylistComponent::mouseUp (const juce::MouseEvent& e)
  1662. {
  1663. ui::clearPostedHint();
  1664. if (drag == Drag::knife)
  1665. cutWithKnife (knifeFrom, knifeTo, ! e.mods.isAltDown());
  1666. if (drag == Drag::zoomRange)
  1667. {
  1668. if (rubberBand.getWidth() > 4)
  1669. zoomToTicks (xToTick (rubberBand.getX()), xToTick (rubberBand.getRight()));
  1670. else
  1671. zoomOut (e.x);
  1672. }
  1673. if (drag == Drag::select && rubberBand.isEmpty() && dragClip >= 0)
  1674. {
  1675. auto s = selectionBefore;
  1676. if (auto it = std::find (s.begin(), s.end(), dragClip); it != s.end())
  1677. s.erase (it);
  1678. else
  1679. s.push_back (dragClip);
  1680. setSelection (s);
  1681. }
  1682. // Ctrl+click on the ruler without dragging clears the time selection
  1683. if (drag == Drag::loop && e.getDistanceFromDragStart() < 3)
  1684. setTimeSelection (0, 0);
  1685. if (drag == Drag::listen)
  1686. engine.stop();
  1687. if (drag == Drag::preview)
  1688. stopPreview();
  1689. resizeTrack = -1;
  1690. if (drag == Drag::move || drag == Drag::resize || drag == Drag::trimLeft || drag == Drag::paint || drag == Drag::timeMove)
  1691. sortClips();
  1692. rippleOriginals.clear();
  1693. timeMoveOriginals.clear();
  1694. autoClip = autoPoint = -1;
  1695. drag = Drag::none;
  1696. dragClip = -1;
  1697. dragIndices.clear();
  1698. dragOriginals.clear();
  1699. touchedClips.clear();
  1700. rubberBand = {};
  1701. knownClipCount = engine.getSong().playlist.size();
  1702. hover = {};
  1703. updateHover (e.getPosition(), e.mods); // the cursor of what is under the mouse now
  1704. repaint();
  1705. }
  1706. void PlaylistComponent::cutWithKnife (juce::Point<int> from, juce::Point<int> to, bool snapOn)
  1707. {
  1708. const auto& playlist = engine.getSong().playlist;
  1709. std::vector<std::pair<int, std::int64_t>> cuts;
  1710. const auto round = snapOn ? gridTicks() / 2.0 : 0.0;
  1711. if (from.getDistanceFrom (to) < 3)
  1712. {
  1713. bool edge = false;
  1714. if (const auto hit = clipAt (from.x, from.y, edge); hit >= 0)
  1715. cuts.push_back ({ hit, snap (xToTick (from.x) + round, snapOn) });
  1716. }
  1717. else
  1718. {
  1719. // every track the line crosses is cut where the line passes its middle
  1720. const auto top = juce::jmin (from.y, to.y), bottom = juce::jmax (from.y, to.y);
  1721. for (int i = 0; i < (int) playlist.size(); ++i)
  1722. {
  1723. const auto& c = playlist[(std::size_t) i];
  1724. const auto trackHeight = heightOf (c.track);
  1725. const auto rowY = trackToY (c.track) + trackHeight / 2;
  1726. if (rowY < top - trackHeight / 2 || rowY > bottom + trackHeight / 2)
  1727. continue;
  1728. const auto y = juce::jlimit (top, bottom, rowY);
  1729. const auto x = from.y == to.y ? (double) from.x : from.x + (double) (y - from.y) * (to.x - from.x) / (double) (to.y - from.y);
  1730. const auto tick = snap (xToTick ((int) std::round (x)) + round, snapOn);
  1731. if (tick > c.start && tick < c.end())
  1732. cuts.push_back ({ i, tick });
  1733. }
  1734. }
  1735. if (cuts.empty())
  1736. return;
  1737. setSelection ({});
  1738. engine.editSong ([&cuts] (Song& s) {
  1739. for (auto [index, tick] : cuts)
  1740. {
  1741. auto rest = splitClip (s.playlist[(std::size_t) index], tick);
  1742. s.playlist.push_back (rest);
  1743. }
  1744. });
  1745. sortClips();
  1746. }
  1747. void PlaylistComponent::zoomToTicks (double from, double to)
  1748. {
  1749. if (to - from < 1.0)
  1750. return;
  1751. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), 800.0 / (4 * ppq), gridArea().getWidth() / (to - from));
  1752. scrollTicks = juce::jmax (0.0, from);
  1753. updateScrollBars();
  1754. repaint();
  1755. }
  1756. void PlaylistComponent::zoomOut (int anchorX)
  1757. {
  1758. const auto anchor = xToTick (anchorX);
  1759. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), 800.0 / (4 * ppq), pixelsPerTick / 2.0);
  1760. scrollTicks = juce::jmax (0.0, anchor - (anchorX - headerWidth) / pixelsPerTick);
  1761. updateScrollBars();
  1762. repaint();
  1763. }
  1764. void PlaylistComponent::insertTimeSelection()
  1765. {
  1766. const auto& song = engine.getSong();
  1767. if (! song.hasLoop())
  1768. return;
  1769. setSelection ({});
  1770. engine.editSong ([from = song.loopStart, to = song.loopEnd] (Song& s) { noteedit::insertTime (s.playlist, s.markers(), from, to - from); });
  1771. sortClips();
  1772. }
  1773. void PlaylistComponent::deleteTimeSelection()
  1774. {
  1775. const auto& song = engine.getSong();
  1776. if (! song.hasLoop())
  1777. return;
  1778. setSelection ({});
  1779. engine.editSong ([from = song.loopStart, to = song.loopEnd] (Song& s) { noteedit::deleteTime (s.playlist, s.markers(), from, to); });
  1780. sortClips();
  1781. }
  1782. void PlaylistComponent::showTrackMenu (int track)
  1783. {
  1784. const auto& song = engine.getSong();
  1785. const auto muted = song.isTrackMuted (track);
  1786. const auto count = numTracks();
  1787. juce::PopupMenu menu;
  1788. menu.addSectionHeader (track < (int) song.playlistTracks.size() && ! song.playlistTracks[(std::size_t) track].name.empty()
  1789. ? juce::String::fromUTF8 (song.playlistTracks[(std::size_t) track].name.c_str())
  1790. : tr ("Track {0}", { juce::String (track + 1) }));
  1791. menu.addItem (tr ("Rename..."), [this, track] { renameTrack (track); });
  1792. menu.addItem (muted ? tr ("Unmute") : tr ("Mute"), [this, track] {
  1793. engine.editSong ([track] (Song& s) {
  1794. if ((int) s.playlistTracks.size() <= track)
  1795. s.playlistTracks.resize ((std::size_t) track + 1);
  1796. s.playlistTracks[(std::size_t) track].muted = ! s.playlistTracks[(std::size_t) track].muted;
  1797. });
  1798. });
  1799. menu.addItem (tr ("Solo (mute the other tracks)"), [this, track, count] { engine.editSong ([track, count] (Song& s) { noteedit::soloTrack (s, track, count); }); });
  1800. menu.addSeparator();
  1801. menu.addItem (tr ("Insert a track above"), [this, track] {
  1802. setSelection ({});
  1803. engine.editSong ([track] (Song& s) { noteedit::insertTrack (s, track); });
  1804. });
  1805. menu.addItem (tr ("Insert a track below"), [this, track] {
  1806. setSelection ({});
  1807. engine.editSong ([track] (Song& s) { noteedit::insertTrack (s, track + 1); });
  1808. });
  1809. menu.addItem (tr ("Move up"), track > 0, false, [this, track] { engine.editSong ([track] (Song& s) { noteedit::swapTracks (s, track, track - 1); }); });
  1810. menu.addItem (tr ("Move down"), [this, track] { engine.editSong ([track] (Song& s) { noteedit::swapTracks (s, track, track + 1); }); });
  1811. menu.addSeparator();
  1812. {
  1813. // row heights (P18); dragging the divider under a header does the same
  1814. struct Size
  1815. {
  1816. const char* name;
  1817. int height;
  1818. };
  1819. static const Size sizes[] = { { TR_NOOP ("Small"), 24 }, { TR_NOOP ("Normal"), trackHeight }, { TR_NOOP ("Large"), 60 }, { TR_NOOP ("Huge"), 100 } };
  1820. juce::PopupMenu one, all;
  1821. const auto current = heightOf (track);
  1822. for (const auto& size : sizes)
  1823. {
  1824. one.addItem (tr (size.name) + " (" + juce::String (size.height) + " px)", true, current == size.height,
  1825. [this, track, h = size.height] { setTrackHeights ({ track }, h); });
  1826. all.addItem (tr (size.name) + " (" + juce::String (size.height) + " px)", [this, count, h = size.height] {
  1827. std::vector<int> tracks;
  1828. for (int t = 0; t < count; ++t)
  1829. tracks.push_back (t);
  1830. setTrackHeights (tracks, h);
  1831. });
  1832. }
  1833. menu.addSubMenu (tr ("Track height"), one);
  1834. menu.addSubMenu (tr ("Height of every track"), all);
  1835. }
  1836. menu.addSeparator();
  1837. menu.addItem (tr ("Delete the track and its clips"), [this, track] {
  1838. setSelection ({});
  1839. engine.editSong ([track] (Song& s) { noteedit::removeTrack (s, track); });
  1840. });
  1841. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1842. }
  1843. void PlaylistComponent::renameTrack (int track)
  1844. {
  1845. const auto& tracks = engine.getSong().playlistTracks;
  1846. const auto current = track < (int) tracks.size() ? juce::String::fromUTF8 (tracks[(std::size_t) track].name.c_str()) : juce::String();
  1847. auto* window = new juce::AlertWindow (tr ("Rename track"), {}, juce::MessageBoxIconType::NoIcon);
  1848. window->addTextEditor ("name", current.isNotEmpty() ? current : tr ("Track {0}", { juce::String (track + 1) }));
  1849. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1850. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  1851. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, track, window] (int result) {
  1852. if (result != 1)
  1853. return;
  1854. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  1855. engine.editSong ([track, name] (Song& s) {
  1856. if ((int) s.playlistTracks.size() <= track)
  1857. s.playlistTracks.resize ((std::size_t) track + 1);
  1858. s.playlistTracks[(std::size_t) track].name = name;
  1859. });
  1860. }),
  1861. true);
  1862. }
  1863. void PlaylistComponent::showRulerMenu (int x)
  1864. {
  1865. const auto& song = engine.getSong();
  1866. const auto tick = juce::jmax<std::int64_t> (0, snap (xToTick (x), true));
  1867. // marker near the click (up to 6 px)
  1868. int near = -1;
  1869. for (int i = 0; i < (int) song.markers().size(); ++i)
  1870. if (std::abs (tickToX ((double) song.markers()[(std::size_t) i].tick) - x) <= 6.0)
  1871. near = i;
  1872. juce::PopupMenu menu;
  1873. menu.addItem (tr ("Add marker here..."), [this, tick] { editMarkerName (tick, -1); });
  1874. juce::PopupMenu signatures;
  1875. for (auto [n, d] : { std::pair { 2, 4 }, { 3, 4 }, { 4, 4 }, { 5, 4 }, { 6, 4 }, { 7, 4 }, { 6, 8 }, { 7, 8 }, { 9, 8 }, { 12, 8 } })
  1876. signatures.addItem (juce::String (n) + "/" + juce::String (d), [this, tick, n = n, d = d] {
  1877. engine.editSong ([tick, n, d] (Song& s) { s.addMarker ({ tick, {}, n, d }); });
  1878. });
  1879. menu.addSubMenu (tr ("Time signature change here"), signatures);
  1880. if (near >= 0)
  1881. {
  1882. menu.addSeparator();
  1883. menu.addItem (tr ("Rename marker..."), [this, near] { editMarkerName (0, near); });
  1884. menu.addItem (tr ("Remove marker"), [this, near] {
  1885. engine.editSong ([near] (Song& s) {
  1886. if (near < (int) s.markers().size())
  1887. s.markers().erase (s.markers().begin() + near);
  1888. });
  1889. });
  1890. }
  1891. if (song.hasLoop())
  1892. {
  1893. menu.addSeparator();
  1894. menu.addItem (tr ("Remove loop"), [this] { engine.editSong ([] (Song& s) { s.loopStart = s.loopEnd = 0; }, false); });
  1895. }
  1896. menu.addSeparator();
  1897. menu.addItem (tr ("Ripple editing (resizing and deleting move the later clips)") + "\tShift+S", true, ripple, [this] { setRipple (! ripple); });
  1898. {
  1899. juce::PopupMenu zoom;
  1900. zoom.addItem (tr ("Zoom in") + "\tPageUp", [this] { runAction ("playlist.zoomIn"); });
  1901. zoom.addItem (tr ("Zoom out") + "\tPageDown", [this] { runAction ("playlist.zoomOut"); });
  1902. zoom.addItem (tr ("Zoom: one bar") + "\tShift+1", [this] { runAction ("playlist.zoom1"); });
  1903. zoom.addItem (tr ("Zoom: four bars") + "\tShift+2", [this] { runAction ("playlist.zoom2"); });
  1904. zoom.addItem (tr ("Zoom: sixteen bars") + "\tShift+3", [this] { runAction ("playlist.zoom3"); });
  1905. zoom.addItem (tr ("Zoom to show everything") + "\tShift+4", [this] { runAction ("playlist.zoomAll"); });
  1906. zoom.addItem (tr ("Zoom to the selection") + "\tShift+5", [this] { runAction ("playlist.zoomSelection"); });
  1907. zoom.addItem (tr ("Centre the view on the playhead") + "\tShift+0", [this] { runAction ("playlist.centrePlayhead"); });
  1908. menu.addSubMenu (tr ("Zoom"), zoom);
  1909. }
  1910. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1911. }
  1912. void PlaylistComponent::editMarkerName (std::int64_t tick, int existing)
  1913. {
  1914. const auto& markers = engine.getSong().markers();
  1915. const auto current = existing >= 0 && existing < (int) markers.size() ? juce::String::fromUTF8 (markers[(std::size_t) existing].name.c_str())
  1916. : tr ("Marker");
  1917. auto* window = new juce::AlertWindow (existing >= 0 ? tr ("Rename marker") : tr ("New marker"), {}, juce::MessageBoxIconType::NoIcon);
  1918. window->addTextEditor ("name", current);
  1919. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1920. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  1921. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, tick, existing, window] (int result) {
  1922. if (result != 1)
  1923. return;
  1924. const auto name = window->getTextEditorContents ("name").trim().toStdString();
  1925. engine.editSong ([tick, existing, name] (Song& s) {
  1926. if (existing < 0)
  1927. s.addMarker ({ tick, name, 0, 4 });
  1928. else if (existing < (int) s.markers().size())
  1929. s.markers()[(std::size_t) existing].name = name;
  1930. });
  1931. }),
  1932. true);
  1933. }
  1934. void PlaylistComponent::showClipMenu (int index)
  1935. {
  1936. auto menu = buildClipMenu (index, getMouseXYRelative().x);
  1937. if (menu.getNumItems() > 0)
  1938. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1939. }
  1940. juce::PopupMenu PlaylistComponent::getClipMenuForSnapshot (int index)
  1941. {
  1942. if (index < 0 || index >= (int) engine.getSong().playlist.size())
  1943. return {};
  1944. const auto& c = engine.getSong().playlist[(std::size_t) index];
  1945. return buildClipMenu (index, (int) tickToX ((double) c.start + (double) c.length / 2.0));
  1946. }
  1947. juce::PopupMenu PlaylistComponent::buildClipMenu (int index, int mouseX)
  1948. {
  1949. const auto& song = engine.getSong();
  1950. juce::PopupMenu menu;
  1951. if (index < 0 || index >= (int) song.playlist.size())
  1952. return menu;
  1953. const auto clip = song.playlist[(std::size_t) index];
  1954. const auto targets = isSelected (index) ? selection : std::vector<int> { index };
  1955. const auto many = targets.size() > 1;
  1956. // --- the source: name, colour, uniqueness -------------------------------------------------------
  1957. juce::String sourceName;
  1958. if (clip.kind == ClipKind::pattern && clip.pattern >= 0 && clip.pattern < (int) song.patterns.size())
  1959. sourceName = juce::String::fromUTF8 (song.patterns[(std::size_t) clip.pattern].name.c_str());
  1960. else if (clip.kind == ClipKind::audio && clip.channel >= 0 && clip.channel < (int) song.channels.size())
  1961. sourceName = juce::String::fromUTF8 (song.channels[(std::size_t) clip.channel].name.c_str());
  1962. else if (clip.kind == ClipKind::automation && clip.automation >= 0 && clip.automation < (int) song.automations.size())
  1963. sourceName = juce::String::fromUTF8 (song.automations[(std::size_t) clip.automation].name.c_str());
  1964. menu.addSectionHeader (sourceName);
  1965. menu.addItem (tr ("Properties..."), [this, index, targets] {
  1966. showClipProperties (engine, index, targets, [safe = juce::Component::SafePointer<PlaylistComponent> (this)] {
  1967. if (safe != nullptr)
  1968. safe->sortClips();
  1969. });
  1970. });
  1971. if (clip.kind == ClipKind::pattern && onRenamePattern)
  1972. menu.addItem (tr ("Rename and color..."), [this, p = clip.pattern] { onRenamePattern (p); });
  1973. else if (clip.kind == ClipKind::audio)
  1974. menu.addItem (tr ("Rename and color..."), [this, ch = clip.channel] {
  1975. const auto& c = engine.getSong().channels[(std::size_t) ch];
  1976. showNameAndColourDialog (tr ("Rename audio clip"), juce::String::fromUTF8 (c.name.c_str()), c.colour,
  1977. [this, ch] (const juce::String& name, std::uint32_t colour) {
  1978. if (ch < (int) engine.getSong().channels.size())
  1979. engine.editSong ([ch, n = name.toStdString(), colour] (Song& s) {
  1980. s.channels[(std::size_t) ch].name = n;
  1981. s.channels[(std::size_t) ch].colour = colour;
  1982. });
  1983. });
  1984. });
  1985. if (clip.kind == ClipKind::pattern)
  1986. menu.addItem (tr ("Make unique") + "\tShift+V+drag", [this, targets] {
  1987. engine.editSong ([targets] (Song& s) { polish::makeClipsUnique (s, targets); });
  1988. });
  1989. else if (clip.kind == ClipKind::audio)
  1990. menu.addItem (tr ("Make unique"), [this, targets] {
  1991. engine.editSong ([targets] (Song& s) { clipops::makeAudioUnique (s, targets); });
  1992. });
  1993. else if (clip.kind == ClipKind::automation)
  1994. menu.addItem (tr ("Make unique"), [this, index] {
  1995. engine.editSong ([index] (Song& s) {
  1996. auto& c = s.playlist[(std::size_t) index];
  1997. auto copy = s.automations[(std::size_t) c.automation];
  1998. copy.name += " #2";
  1999. s.automations.push_back (std::move (copy));
  2000. c.automation = (int) s.automations.size() - 1;
  2001. });
  2002. });
  2003. menu.addItem (tr ("Select all clips of this source"), [this, index] { setSelection (clipops::sameSource (engine.getSong(), index)); });
  2004. menu.addSeparator();
  2005. // --- cutting and joining -------------------------------------------------------------------------
  2006. const auto splitAt = snap (xToTick (mouseX) + gridTicks() / 2.0, true);
  2007. menu.addItem (tr ("Split here"), splitAt > clip.start && splitAt < clip.end(), false, [this, index, splitAt] {
  2008. setSelection ({});
  2009. engine.editSong ([index, splitAt] (Song& s) {
  2010. if (index < (int) s.playlist.size() && splitAt > s.playlist[(std::size_t) index].start && splitAt < s.playlist[(std::size_t) index].end())
  2011. s.playlist.push_back (splitClip (s.playlist[(std::size_t) index], splitAt));
  2012. });
  2013. sortClips();
  2014. });
  2015. menu.addItem (tr ("Chop to grid"), [this, targets, grid = gridTicks()] {
  2016. setSelection ({});
  2017. engine.editSong ([targets, grid] (Song& s) {
  2018. auto sorted = targets; // chopping adds clips at the end: indices below stay valid
  2019. for (auto i : sorted)
  2020. noteedit::chopClip (s.playlist, i, grid);
  2021. });
  2022. sortClips();
  2023. });
  2024. menu.addItem (tr ("Merge clips"), clipops::canMerge (song, targets), false, [this, targets] {
  2025. setSelection ({});
  2026. engine.editSong ([targets] (Song& s) { clipops::mergeClips (s, targets); });
  2027. sortClips();
  2028. });
  2029. // --- audio ---------------------------------------------------------------------------------------
  2030. if (clip.kind == ClipKind::audio && clip.channel >= 0 && clip.channel < (int) song.channels.size())
  2031. {
  2032. menu.addSeparator();
  2033. const auto& channel = song.channels[(std::size_t) clip.channel];
  2034. const auto path = juce::String::fromUTF8 (channel.samplePath.c_str());
  2035. const auto sample = engine.getSampleLibrary().load (path);
  2036. const auto frames = sample != nullptr ? (double) sample->frames() : 0.0;
  2037. const auto rate = sample != nullptr ? sample->sampleRate : 44100.0;
  2038. menu.addItem (tr ("Reverse"), sample != nullptr, channel.sampler.reverse, [this, index, frames, rate] {
  2039. engine.editSong ([index, frames, rate] (Song& s) {
  2040. const auto ch = s.playlist[(std::size_t) index].channel;
  2041. clipops::reverseAudio (s, index, clipops::fileTicks (s.channels[(std::size_t) ch].sampler, frames, rate, s.bpm));
  2042. });
  2043. });
  2044. menu.addItem (tr ("Normalize"), [this, targets] { normalizeClips (targets); });
  2045. juce::PopupMenu gains;
  2046. for (auto db : { 6.0f, 3.0f, 0.0f, -3.0f, -6.0f, -12.0f })
  2047. {
  2048. const auto g = juce::Decibels::decibelsToGain (db);
  2049. gains.addItem ((db > 0 ? "+" : "") + juce::String (db, 0) + " dB", true, std::abs (clip.gain - g) < 0.01f, [this, targets, g] {
  2050. engine.editSong ([targets, g] (Song& s) {
  2051. for (auto i : targets)
  2052. if (i < (int) s.playlist.size() && s.playlist[(std::size_t) i].kind == ClipKind::audio)
  2053. s.playlist[(std::size_t) i].gain = g;
  2054. });
  2055. });
  2056. }
  2057. menu.addSubMenu (tr ("Clip volume"), gains);
  2058. // stretching the channel's file to a whole number of beats at the project tempo
  2059. juce::PopupMenu fit;
  2060. const auto seconds = frames / juce::jmax (1.0, rate);
  2061. const auto beats = clipops::fitBeats (seconds, song.bpm);
  2062. auto fitTo = [this, index, frames, rate] (float toBeats, bool keepPitch) {
  2063. engine.editSong ([index, frames, rate, toBeats, keepPitch] (Song& s) {
  2064. const auto ch = s.playlist[(std::size_t) index].channel;
  2065. auto& sampler = s.channels[(std::size_t) ch].sampler;
  2066. const auto before = clipops::fileTicks (sampler, frames, rate, s.bpm);
  2067. sampler.stretchBeats = toBeats;
  2068. sampler.keepPitch = keepPitch && toBeats > 0.0f;
  2069. const auto after = clipops::fileTicks (sampler, frames, rate, s.bpm);
  2070. if (before <= 0 || after <= 0)
  2071. return;
  2072. // every clip of the file keeps showing the same audio: offsets and lengths scale with it
  2073. const auto k = (double) after / (double) before;
  2074. for (auto& c : s.playlist)
  2075. if (c.kind == ClipKind::audio && c.channel == ch)
  2076. {
  2077. c.offset = (std::int64_t) std::llround ((double) c.offset * k);
  2078. c.length = juce::jmax<std::int64_t> (1, (std::int64_t) std::llround ((double) c.length * k));
  2079. c.fadeIn = (std::int64_t) std::llround ((double) c.fadeIn * k);
  2080. c.fadeOut = (std::int64_t) std::llround ((double) c.fadeOut * k);
  2081. }
  2082. });
  2083. sortClips();
  2084. };
  2085. if (beats > 0.0f)
  2086. {
  2087. const auto label = juce::String (beats, 0) + " " + (beats == 1.0f ? tr ("beat") : tr ("beats"));
  2088. fit.addItem (tr ("Fit to tempo, keep pitch ({0})", { label }), true, channel.sampler.stretchBeats == beats && channel.sampler.keepPitch,
  2089. [fitTo, beats] { fitTo (beats, true); });
  2090. fit.addItem (tr ("Fit to tempo, resample ({0})", { label }), true, channel.sampler.stretchBeats == beats && ! channel.sampler.keepPitch,
  2091. [fitTo, beats] { fitTo (beats, false); });
  2092. fit.addItem (tr ("Half as long"), channel.sampler.stretchBeats > 0.0f, false,
  2093. [fitTo, b = channel.sampler.stretchBeats, kp = channel.sampler.keepPitch] { fitTo (juce::jmax (0.25f, b * 0.5f), kp); });
  2094. fit.addItem (tr ("Twice as long"), channel.sampler.stretchBeats > 0.0f, false,
  2095. [fitTo, b = channel.sampler.stretchBeats, kp = channel.sampler.keepPitch] { fitTo (juce::jmin (1024.0f, b * 2.0f), kp); });
  2096. fit.addSeparator();
  2097. }
  2098. fit.addItem (tr ("Original speed (no stretch)"), true, channel.sampler.stretchBeats <= 0.0f, [fitTo] { fitTo (0.0f, false); });
  2099. menu.addSubMenu (tr ("Fit to tempo"), fit, sample != nullptr);
  2100. if (clip.fadeIn > 0 || clip.fadeOut > 0)
  2101. menu.addItem (tr ("Remove fades"), [this, targets] {
  2102. engine.editSong ([targets] (Song& s) {
  2103. for (auto i : targets)
  2104. if (i < (int) s.playlist.size())
  2105. s.playlist[(std::size_t) i].fadeIn = s.playlist[(std::size_t) i].fadeOut = 0;
  2106. });
  2107. });
  2108. menu.addItem (tr ("Open in a new Sampler channel"), sample != nullptr, false, [this, ch = clip.channel] {
  2109. if (onOpenInSampler)
  2110. onOpenInSampler (ch);
  2111. });
  2112. menu.addItem (tr ("Show the file in Explorer"), juce::File (path).existsAsFile(), false, [path] { juce::File (path).revealToUser(); });
  2113. }
  2114. // --- pattern -------------------------------------------------------------------------------------
  2115. if (clip.kind == ClipKind::pattern)
  2116. {
  2117. menu.addSeparator();
  2118. menu.addItem (tr ("Open in Channel Rack"), [this, p = clip.pattern] {
  2119. engine.editSong ([p] (Song& s) { if (p < (int) s.patterns.size()) s.currentPattern = p; }, false);
  2120. if (onOpenPattern)
  2121. onOpenPattern();
  2122. });
  2123. menu.addItem (tr ("Open in Piano Roll"), [this, p = clip.pattern] {
  2124. engine.editSong ([p] (Song& s) { if (p < (int) s.patterns.size()) s.currentPattern = p; }, false);
  2125. if (onOpenPianoRoll)
  2126. onOpenPianoRoll();
  2127. });
  2128. }
  2129. // --- automation ----------------------------------------------------------------------------------
  2130. if (clip.kind == ClipKind::automation && clip.automation >= 0 && clip.automation < (int) song.automations.size())
  2131. {
  2132. menu.addSeparator();
  2133. menu.addItem (tr ("Edit points..."), [this, a = clip.automation] { openAutomationEditor (engine, a); });
  2134. menu.addItem (tr ("Delete automation (all of its clips)"), [this, a = clip.automation] {
  2135. setSelection ({});
  2136. engine.editSong ([a] (Song& s) { s.removeAutomation (a); });
  2137. });
  2138. }
  2139. // --- mute and the clipboard ----------------------------------------------------------------------
  2140. menu.addSeparator();
  2141. menu.addItem (clip.muted ? tr ("Unmute") : tr ("Mute"), [this, targets, m = ! clip.muted] {
  2142. engine.editSong ([targets, m] (Song& s) {
  2143. for (auto i : targets)
  2144. if (i < (int) s.playlist.size())
  2145. s.playlist[(std::size_t) i].muted = m;
  2146. });
  2147. });
  2148. menu.addItem (tr ("Cut") + "\tCtrl+X", [this, targets] {
  2149. setSelection (targets);
  2150. copySelection();
  2151. deleteSelection();
  2152. });
  2153. menu.addItem (tr ("Copy") + "\tCtrl+C", [this, targets] {
  2154. setSelection (targets);
  2155. copySelection();
  2156. });
  2157. menu.addItem (tr ("Paste here") + "\tCtrl+V", ! clipboard.empty(), false, [this, at = snap (xToTick (mouseX), true)] { pasteClips (at); });
  2158. menu.addItem ((many ? tr ("Delete selected") : tr ("Delete")) + "\tDel", [this, targets] {
  2159. setSelection (targets);
  2160. deleteSelection();
  2161. });
  2162. return menu;
  2163. }
  2164. void PlaylistComponent::normalizeClips (const std::vector<int>& targets)
  2165. {
  2166. // clip gain so that the peak of the played segment reaches 0 dB (at most +24 dB)
  2167. const auto& song = engine.getSong();
  2168. std::vector<std::pair<int, float>> gainsFor;
  2169. for (auto i : targets)
  2170. {
  2171. if (i < 0 || i >= (int) song.playlist.size())
  2172. continue;
  2173. const auto& c = song.playlist[(std::size_t) i];
  2174. if (c.kind != ClipKind::audio || c.channel < 0 || c.channel >= (int) song.channels.size())
  2175. continue;
  2176. const auto& channel = song.channels[(std::size_t) c.channel];
  2177. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (channel.samplePath.c_str()));
  2178. if (sample == nullptr || sample->frames() == 0)
  2179. continue;
  2180. const auto total = (double) sample->frames();
  2181. const auto perTick = clipops::framesPerTick (channel.sampler, total, sample->sampleRate, song.bpm);
  2182. auto from = juce::jlimit (0.0, total, (double) c.offset * perTick);
  2183. auto to = juce::jlimit (from, total, (double) (c.offset + c.length) * perTick);
  2184. if (channel.sampler.reverse) // the clip's offset counts from the file's end
  2185. {
  2186. const auto f = total - to, t = total - from;
  2187. from = f;
  2188. to = t;
  2189. }
  2190. float peak = 0.0f;
  2191. for (auto* data : { sample->leftData(), sample->rightData() })
  2192. if (data != nullptr)
  2193. for (auto f = (std::size_t) from; f < (std::size_t) to; ++f)
  2194. peak = juce::jmax (peak, std::abs (data[f]));
  2195. if (peak > 1.0e-6f)
  2196. gainsFor.push_back ({ i, juce::jmin (1.0f / peak, juce::Decibels::decibelsToGain (24.0f)) });
  2197. }
  2198. if (! gainsFor.empty())
  2199. engine.editSong ([gainsFor] (Song& s) {
  2200. for (auto [i, g] : gainsFor)
  2201. if (i < (int) s.playlist.size())
  2202. s.playlist[(std::size_t) i].gain = g;
  2203. });
  2204. }
  2205. void PlaylistComponent::visibilityChanged()
  2206. {
  2207. // hidden while a clip preview or the Listen tool is sounding (no mouse up will come here): stop it
  2208. if (! isShowing() && (drag == Drag::preview || drag == Drag::listen))
  2209. {
  2210. if (drag == Drag::preview)
  2211. stopPreview();
  2212. else
  2213. engine.stop();
  2214. drag = Drag::none;
  2215. }
  2216. }
  2217. void PlaylistComponent::startPreview (int clip, int x)
  2218. {
  2219. const auto& song = engine.getSong();
  2220. if (clip < 0 || clip >= (int) song.playlist.size())
  2221. return;
  2222. const auto c = song.playlist[(std::size_t) clip];
  2223. previewPositionBefore = engine.getTransport().positionTicks.load();
  2224. previewPatternBefore = -1;
  2225. previewRestoreSong = false;
  2226. drag = Drag::preview;
  2227. const auto at = juce::jlimit ((double) c.start, (double) c.end(), xToTick (x));
  2228. if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) song.patterns.size())
  2229. {
  2230. // a pattern clip plays its pattern alone, from the clicked point
  2231. const auto length = (double) juce::jmax<std::int64_t> (1, song.patterns[(std::size_t) c.pattern].effectiveLength (song.beatsPerBar));
  2232. previewRestoreSong = song.mode == PlayMode::song;
  2233. previewPatternBefore = song.currentPattern;
  2234. engine.editSong ([p = c.pattern] (Song& s) {
  2235. s.mode = PlayMode::pattern;
  2236. s.currentPattern = p;
  2237. }, false);
  2238. engine.seek (std::fmod (at - (double) c.start + (double) c.offset, length));
  2239. }
  2240. else
  2241. {
  2242. if (song.mode != PlayMode::song)
  2243. engine.editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  2244. engine.seek (at);
  2245. }
  2246. engine.play();
  2247. setMouseCursor (editorCursor (gesture::Cursor::listen));
  2248. ui::postHint ({ tr ("Previewing the clip: release the mouse to stop"), {}, false, false }, 60000);
  2249. }
  2250. void PlaylistComponent::stopPreview()
  2251. {
  2252. engine.stop();
  2253. if (previewPatternBefore >= 0)
  2254. engine.editSong ([this] (Song& s) {
  2255. if (previewPatternBefore < (int) s.patterns.size())
  2256. s.currentPattern = previewPatternBefore;
  2257. if (previewRestoreSong)
  2258. s.mode = PlayMode::song;
  2259. }, false);
  2260. engine.seek (previewPositionBefore);
  2261. previewPatternBefore = -1;
  2262. ui::clearPostedHint();
  2263. }
  2264. void PlaylistComponent::setRipple (bool on)
  2265. {
  2266. ripple = on;
  2267. repaint();
  2268. }
  2269. void PlaylistComponent::rippleDeleteSelection()
  2270. {
  2271. if (selection.empty())
  2272. return;
  2273. auto doomed = selection;
  2274. setSelection ({});
  2275. engine.editSong ([&doomed] (Song& s) { noteedit::rippleDelete (s.playlist, doomed); });
  2276. }
  2277. void PlaylistComponent::zoomAroundCentre (double factor)
  2278. {
  2279. const auto grid = gridArea();
  2280. const auto centre = xToTick (grid.getCentreX());
  2281. pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), 800.0 / (4 * ppq), pixelsPerTick * factor);
  2282. scrollTicks = juce::jmax (0.0, centre - (grid.getCentreX() - headerWidth) / pixelsPerTick);
  2283. updateScrollBars();
  2284. repaint();
  2285. }
  2286. void PlaylistComponent::zoomToBars (int bars)
  2287. {
  2288. const auto bar = (double) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  2289. const auto from = std::floor (scrollTicks / bar) * bar;
  2290. zoomToTicks (from, from + bars * bar);
  2291. }
  2292. void PlaylistComponent::zoomAll()
  2293. {
  2294. zoomToTicks (0.0, (double) engine.getSong().songLength());
  2295. }
  2296. void PlaylistComponent::zoomToSelection()
  2297. {
  2298. const auto& song = engine.getSong();
  2299. if (song.hasLoop() && selection.empty())
  2300. return zoomToTicks ((double) song.loopStart, (double) song.loopEnd);
  2301. if (selection.empty())
  2302. return zoomAll();
  2303. std::int64_t from = INT64_MAX, to = 0;
  2304. int top = 1 << 20;
  2305. for (auto i : selection)
  2306. if (i >= 0 && i < (int) song.playlist.size())
  2307. {
  2308. from = juce::jmin (from, song.playlist[(std::size_t) i].start);
  2309. to = juce::jmax (to, song.playlist[(std::size_t) i].end());
  2310. top = juce::jmin (top, song.playlist[(std::size_t) i].track);
  2311. }
  2312. zoomToTicks ((double) from, (double) to);
  2313. scrollY = juce::jmax (0, trackToY (top) - headerHeight + scrollY);
  2314. updateScrollBars();
  2315. repaint();
  2316. }
  2317. void PlaylistComponent::centreOnPlayhead()
  2318. {
  2319. const auto& song = engine.getSong();
  2320. const auto tick = std::fmod (engine.getTransport().positionTicks.load(), (double) juce::jmax<std::int64_t> (1, song.songLength()));
  2321. scrollTicks = juce::jmax (0.0, tick - gridArea().getWidth() / pixelsPerTick / 2.0);
  2322. updateScrollBars();
  2323. repaint();
  2324. }
  2325. bool PlaylistComponent::runAction (const std::string& id)
  2326. {
  2327. auto is = [&id] (const char* name) { return id == name; };
  2328. if (is ("playlist.zoomIn")) zoomAroundCentre (1.25);
  2329. else if (is ("playlist.zoomOut")) zoomAroundCentre (1.0 / 1.25);
  2330. else if (is ("playlist.zoom1")) zoomToBars (1);
  2331. else if (is ("playlist.zoom2")) zoomToBars (4);
  2332. else if (is ("playlist.zoom3")) zoomToBars (16);
  2333. else if (is ("playlist.zoomAll")) zoomAll();
  2334. else if (is ("playlist.zoomSelection")) zoomToSelection();
  2335. else if (is ("playlist.centrePlayhead")) centreOnPlayhead();
  2336. else if (is ("playlist.rippleDelete")) rippleDeleteSelection();
  2337. else if (is ("playlist.ripple")) setRipple (! ripple);
  2338. else
  2339. return false;
  2340. return true;
  2341. }
  2342. void PlaylistComponent::deleteSelection()
  2343. {
  2344. if (selection.empty())
  2345. return;
  2346. auto doomed = selection;
  2347. setSelection ({});
  2348. engine.editSong ([&doomed] (Song& s) {
  2349. std::sort (doomed.rbegin(), doomed.rend());
  2350. for (auto i : doomed)
  2351. if (i >= 0 && i < (int) s.playlist.size())
  2352. s.playlist.erase (s.playlist.begin() + i);
  2353. });
  2354. }
  2355. void PlaylistComponent::copySelection()
  2356. {
  2357. clipboard.clear();
  2358. for (auto i : selection)
  2359. clipboard.push_back (engine.getSong().playlist[(std::size_t) i]);
  2360. }
  2361. void PlaylistComponent::pasteClips (std::int64_t at)
  2362. {
  2363. if (clipboard.empty())
  2364. return;
  2365. // pastes at `at` (the clip menu's click), else at the playback cursor (or where the first clip was),
  2366. // keeping tracks and spacing
  2367. std::int64_t first = clipboard.front().start;
  2368. for (const auto& c : clipboard)
  2369. first = juce::jmin (first, c.start);
  2370. const auto target = at >= 0 ? at : playheadTick >= 0.0 ? snap (playheadTick, true) : first;
  2371. std::vector<int> added;
  2372. engine.editSong ([&added, target, first] (Song& s) {
  2373. for (auto c : clipboard)
  2374. {
  2375. if (c.kind == ClipKind::pattern && c.pattern >= (int) s.patterns.size())
  2376. continue;
  2377. if (c.kind == ClipKind::audio && c.channel >= (int) s.channels.size())
  2378. continue;
  2379. if (c.kind == ClipKind::automation && c.automation >= (int) s.automations.size())
  2380. continue;
  2381. c.start = c.start - first + target;
  2382. added.push_back ((int) s.playlist.size());
  2383. s.playlist.push_back (c);
  2384. }
  2385. });
  2386. setSelection (added);
  2387. sortClips();
  2388. }
  2389. void PlaylistComponent::duplicateSelection()
  2390. {
  2391. const auto& song = engine.getSong();
  2392. // with a time selection: repeats it right after itself (the selected clips that start inside it, or
  2393. // all the clips that do), and the time selection moves on so the next Ctrl+B continues
  2394. if (song.hasLoop())
  2395. {
  2396. const auto from = song.loopStart, to = song.loopEnd;
  2397. std::vector<int> sources;
  2398. for (auto i : selection)
  2399. if (song.playlist[(std::size_t) i].start >= from && song.playlist[(std::size_t) i].start < to)
  2400. sources.push_back (i);
  2401. std::vector<int> added;
  2402. engine.editSong ([&] (Song& s) {
  2403. added = noteedit::repeatTime (s.playlist, from, to, sources);
  2404. s.loopStart = to;
  2405. s.loopEnd = to + (to - from);
  2406. });
  2407. setSelection (added);
  2408. sortClips();
  2409. return;
  2410. }
  2411. if (selection.empty())
  2412. return;
  2413. const auto bar = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar);
  2414. std::int64_t from = INT64_MAX, to = 0;
  2415. for (auto i : selection)
  2416. {
  2417. from = juce::jmin (from, song.playlist[(std::size_t) i].start);
  2418. to = juce::jmax (to, song.playlist[(std::size_t) i].end());
  2419. }
  2420. const auto offset = juce::jmax (bar, (to - from + bar - 1) / bar * bar); // like FL's Ctrl+B
  2421. const auto source = selection;
  2422. std::vector<int> added;
  2423. engine.editSong ([&added, &source, offset] (Song& s) {
  2424. for (auto i : source)
  2425. {
  2426. auto c = s.playlist[(std::size_t) i];
  2427. c.start += offset;
  2428. added.push_back ((int) s.playlist.size());
  2429. s.playlist.push_back (c);
  2430. }
  2431. });
  2432. setSelection (added);
  2433. sortClips();
  2434. }
  2435. bool PlaylistComponent::handleKey (const juce::KeyPress& key)
  2436. {
  2437. const auto mods = key.getModifiers();
  2438. const auto cmd = mods.isCommandDown();
  2439. const auto code = key.getKeyCode();
  2440. const auto letter = (int) juce::CharacterFunctions::toUpperCase ((juce::juce_wchar) code);
  2441. if (code == juce::KeyPress::backspaceKey)
  2442. {
  2443. EditorGlobals::get().toggleGrid();
  2444. return true;
  2445. }
  2446. // Ctrl+Ins / Ctrl+Del: insert / remove the time selection's length across all tracks
  2447. if (cmd && code == juce::KeyPress::insertKey)
  2448. {
  2449. insertTimeSelection();
  2450. return true;
  2451. }
  2452. if (cmd && code == juce::KeyPress::deleteKey)
  2453. {
  2454. deleteTimeSelection();
  2455. return true;
  2456. }
  2457. if (code == juce::KeyPress::deleteKey && ! mods.isShiftDown())
  2458. {
  2459. if (ripple)
  2460. rippleDeleteSelection();
  2461. else
  2462. deleteSelection();
  2463. return true;
  2464. }
  2465. if (code == juce::KeyPress::escapeKey)
  2466. {
  2467. setSelection ({});
  2468. return true;
  2469. }
  2470. if (cmd && letter == 'A')
  2471. {
  2472. std::vector<int> all ((std::size_t) engine.getSong().playlist.size());
  2473. for (std::size_t i = 0; i < all.size(); ++i)
  2474. all[i] = (int) i;
  2475. setSelection (all);
  2476. return true;
  2477. }
  2478. if (cmd && letter == 'C')
  2479. {
  2480. copySelection();
  2481. return true;
  2482. }
  2483. if (cmd && letter == 'X')
  2484. {
  2485. copySelection();
  2486. deleteSelection();
  2487. return true;
  2488. }
  2489. if (cmd && letter == 'V')
  2490. {
  2491. pasteClips();
  2492. return true;
  2493. }
  2494. if (cmd && letter == 'B')
  2495. {
  2496. duplicateSelection();
  2497. return true;
  2498. }
  2499. // single letters: only while the typing piano is off (otherwise they play notes)
  2500. if (! cmd && ! mods.isAltDown() && ! mods.isShiftDown() && ! EditorGlobals::get().typingPiano)
  2501. for (const auto& t : editTools())
  2502. if (letter == t.key && t.tool != EditTool::drumPaint)
  2503. {
  2504. tools.setTool (t.tool);
  2505. return true;
  2506. }
  2507. return false;
  2508. }
  2509. void PlaylistComponent::mouseMove (const juce::MouseEvent& e)
  2510. {
  2511. updateHover (e.getPosition(), e.mods);
  2512. }
  2513. void PlaylistComponent::mouseExit (const juce::MouseEvent&)
  2514. {
  2515. lastMouse = { -1, -1 };
  2516. if (! (hover == Hover {}))
  2517. {
  2518. hover = {};
  2519. repaint();
  2520. }
  2521. }
  2522. void PlaylistComponent::modifierKeysChanged (const juce::ModifierKeys& mods)
  2523. {
  2524. if (drag == Drag::none && lastMouse.x >= 0)
  2525. updateCursor (mods);
  2526. }
  2527. juce::Rectangle<int> PlaylistComponent::clipBounds (int index) const
  2528. {
  2529. const auto& c = engine.getSong().playlist[(std::size_t) index];
  2530. const auto x0 = (float) tickToX ((double) c.start), x1 = (float) tickToX ((double) c.end());
  2531. return juce::Rectangle<float> (x0, (float) trackToY (c.track) + 1.0f, juce::jmax (3.0f, x1 - x0 - 1.0f), (float) heightOf (c.track) - 3.0f)
  2532. .getSmallestIntegerContainer();
  2533. }
  2534. juce::Rectangle<int> PlaylistComponent::clipMenuButton (int index) const
  2535. {
  2536. const auto r = clipBounds (index);
  2537. if (r.getWidth() < 40)
  2538. return {};
  2539. return { r.getX() + 2, r.getY() + 1, 13, (int) clipTitleHeight - 2 };
  2540. }
  2541. PlaylistComponent::Hover PlaylistComponent::hoverAt (juce::Point<int> p) const
  2542. {
  2543. Hover h;
  2544. if (p.x < headerWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  2545. {
  2546. h.header = true;
  2547. h.track = yToTrack (p.y);
  2548. h.divider = dividerAt (p);
  2549. h.led = h.divider < 0 && p.x < 20;
  2550. return h;
  2551. }
  2552. if (! gridArea().contains (p))
  2553. return h;
  2554. h.track = yToTrack (p.y);
  2555. bool rightEdge = false, leftEdge = false;
  2556. h.clip = clipAt (p.x, p.y, rightEdge, leftEdge);
  2557. if (h.clip < 0)
  2558. return h;
  2559. const auto& c = engine.getSong().playlist[(std::size_t) h.clip];
  2560. h.target = rightEdge ? gesture::Target::rightEdge : leftEdge ? gesture::Target::leftEdge : gesture::Target::item;
  2561. if (clipMenuButton (h.clip).contains (p))
  2562. h.target = gesture::Target::clipMenu;
  2563. else if (fadeHandleAt (h.clip, p) != 0)
  2564. h.target = gesture::Target::fadeHandle;
  2565. else if (c.kind == ClipKind::automation && automationPointAt (h.clip, p) >= 0)
  2566. h.target = gesture::Target::autoPoint;
  2567. else if (c.kind == ClipKind::automation && isOnAutomationCurve (h.clip, p))
  2568. h.target = gesture::Target::autoCurve;
  2569. return h;
  2570. }
  2571. void PlaylistComponent::updateHover (juce::Point<int> p, juce::ModifierKeys mods)
  2572. {
  2573. lastMouse = p;
  2574. const auto h = hoverAt (p);
  2575. if (! (h == hover))
  2576. {
  2577. // repaint the old and new track rows (header and lane)
  2578. for (auto t : { hover.track, h.track })
  2579. if (t >= 0)
  2580. repaint (0, trackToY (t) - 4, getWidth(), heightOf (t) + 8);
  2581. hover = h;
  2582. }
  2583. if (drag == Drag::none)
  2584. updateCursor (mods);
  2585. }
  2586. void PlaylistComponent::updateCursor (juce::ModifierKeys mods)
  2587. {
  2588. const auto p = lastMouse;
  2589. auto cursor = gesture::Cursor::normal;
  2590. if (hover.header && hover.divider >= 0)
  2591. {
  2592. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  2593. return;
  2594. }
  2595. if (hover.header)
  2596. cursor = hover.led ? gesture::Cursor::point : gesture::Cursor::normal;
  2597. else if (gridArea().contains (p))
  2598. {
  2599. const gesture::Mods m { mods.isShiftDown(), mods.isCtrlDown(), mods.isAltDown() };
  2600. const auto tool = tools.getTool();
  2601. cursor = gesture::cursorFor (gesture::leftAction (tool, hover.target, m, true), tool);
  2602. }
  2603. else if (p.y >= toolbarHeight && p.y < headerHeight && p.x >= headerWidth)
  2604. cursor = mods.isCtrlDown() ? gesture::Cursor::select : gesture::Cursor::point;
  2605. setMouseCursor (editorCursor (cursor));
  2606. }
  2607. ui::Hint PlaylistComponent::hintAt (juce::Point<int> p)
  2608. {
  2609. ui::Hint hint;
  2610. const auto mods = juce::ModifierKeys::currentModifiers;
  2611. const auto& song = engine.getSong();
  2612. const auto h = hoverAt (p);
  2613. auto trackName = [&song] (int t) {
  2614. return t < (int) song.playlistTracks.size() && ! song.playlistTracks[(std::size_t) t].name.empty()
  2615. ? juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str())
  2616. : tr ("Track {0}", { juce::String (t + 1) });
  2617. };
  2618. if (h.header && h.divider >= 0)
  2619. {
  2620. hint.text = tr ("Track divider: [LMB] drag resizes this track [Shift][LMB] drag: all tracks [2xLMB] default height");
  2621. hint.value = juce::String (heightOf (h.divider)) + " px";
  2622. return hint;
  2623. }
  2624. if (h.header)
  2625. {
  2626. hint.text = h.led ? tr ("Track: [LMB] mute / unmute [Ctrl][LMB] or [RMB] solo")
  2627. : tr ("Track: [RMB] menu [2xLMB] rename [Shift][Wheel] move up / down");
  2628. hint.value = trackName (h.track);
  2629. hint.hasMenu = ! h.led;
  2630. return hint;
  2631. }
  2632. if (p.y >= toolbarHeight && p.y < headerHeight && p.x >= headerWidth)
  2633. {
  2634. hint.text = tr ("Ruler: [LMB] song position [Ctrl][LMB] drag: time selection (loop) [Shift][LMB] drag in it: move [2xLMB] clear [RMB] markers");
  2635. hint.hasMenu = true;
  2636. return hint;
  2637. }
  2638. if (! gridArea().contains (p))
  2639. return hint;
  2640. const gesture::Mods m { mods.isShiftDown(), mods.isCtrlDown(), mods.isAltDown() };
  2641. hint.text = actionHint (gesture::leftAction (tools.getTool(), h.target, m, true), true);
  2642. if (h.clip >= 0)
  2643. {
  2644. if (h.target == gesture::Target::item && ! m.ctrl)
  2645. hint.text << " " << tr ("[Shift][V] + drag: a unique copy [Alt][RMB] hold: hear it");
  2646. const auto& c = song.playlist[(std::size_t) h.clip];
  2647. hint.hasMenu = true;
  2648. if (c.kind == ClipKind::pattern && c.pattern >= 0 && c.pattern < (int) song.patterns.size())
  2649. hint.value = juce::String::fromUTF8 (song.patterns[(std::size_t) c.pattern].name.c_str());
  2650. else if (c.kind == ClipKind::audio && c.channel >= 0 && c.channel < (int) song.channels.size())
  2651. hint.value = juce::String::fromUTF8 (song.channels[(std::size_t) c.channel].name.c_str());
  2652. else if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < (int) song.automations.size())
  2653. hint.value = juce::String::fromUTF8 (song.automations[(std::size_t) c.automation].name.c_str());
  2654. }
  2655. else
  2656. hint.value = trackName (h.track);
  2657. return hint;
  2658. }
  2659. void PlaylistComponent::mouseDoubleClick (const juce::MouseEvent& e)
  2660. {
  2661. // double-click a track divider: back to the default height
  2662. if (const auto divider = dividerAt (e.getPosition()); divider >= 0)
  2663. {
  2664. setTrackHeights ({ divider }, trackHeight);
  2665. return;
  2666. }
  2667. // double-click a track name: rename it
  2668. if (e.x >= 20 && e.x < headerWidth && e.y >= headerHeight && e.y < gridArea().getBottom() && e.mods.isLeftButtonDown())
  2669. {
  2670. renameTrack (yToTrack (e.y));
  2671. return;
  2672. }
  2673. bool edge = false;
  2674. const auto hit = gridArea().contains (e.getPosition()) ? clipAt (e.x, e.y, edge) : -1;
  2675. if (hit < 0)
  2676. return;
  2677. const auto& clip = engine.getSong().playlist[(std::size_t) hit];
  2678. if (clip.kind == ClipKind::automation)
  2679. openAutomationEditor (engine, clip.automation);
  2680. else if (clip.kind == ClipKind::pattern)
  2681. {
  2682. auto pianoRoll = editPatternsIn == 2
  2683. || (editPatternsIn == 0 && clip.pattern < (int) engine.getSong().patterns.size()
  2684. && hasPianoRollNotes (engine.getSong().patterns[(std::size_t) clip.pattern]));
  2685. if (e.mods.isAltDown())
  2686. pianoRoll = ! pianoRoll;
  2687. if (pianoRoll && onOpenPianoRoll)
  2688. onOpenPianoRoll();
  2689. else if (! pianoRoll && onOpenPattern)
  2690. onOpenPattern();
  2691. }
  2692. }
  2693. bool PlaylistComponent::isInterestedInFileDrag (const juce::StringArray& files)
  2694. {
  2695. for (const auto& f : files)
  2696. if (juce::File (f).hasFileExtension ("wav;aif;aiff;flac;ogg;mp3"))
  2697. return true;
  2698. return false;
  2699. }
  2700. void PlaylistComponent::filesDropped (const juce::StringArray& files, int x, int y)
  2701. {
  2702. auto start = juce::jmax<std::int64_t> (0, snap (xToTick (x), true));
  2703. auto track = yToTrack (y);
  2704. for (const auto& f : files)
  2705. {
  2706. const juce::File file (f);
  2707. if (! file.hasFileExtension ("wav;aif;aiff;flac;ogg;mp3"))
  2708. continue;
  2709. const auto data = engine.getSampleLibrary().load (file.getFullPathName());
  2710. if (data == nullptr)
  2711. continue;
  2712. // audio length converted to ticks at the current BPM
  2713. const auto seconds = (double) data->frames() / data->sampleRate;
  2714. const auto length = juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) (seconds * engine.getSong().bpm / 60.0 * ppq));
  2715. const auto path = file.getFullPathName().toStdString();
  2716. const auto name = file.getFileNameWithoutExtension().toStdString();
  2717. engine.editSong ([=] (Song& s) {
  2718. ChannelDef c;
  2719. c.name = name;
  2720. c.instrument = InstrumentKind::audioClip;
  2721. c.samplePath = path;
  2722. c.mixerTrack = s.nextFreeInsert();
  2723. s.channels.push_back (c);
  2724. Clip clip;
  2725. clip.kind = ClipKind::audio;
  2726. clip.channel = (int) s.channels.size() - 1;
  2727. clip.track = track;
  2728. clip.start = start;
  2729. clip.length = length;
  2730. s.playlist.push_back (clip);
  2731. s.mode = PlayMode::song;
  2732. });
  2733. ++track; // multiple files: one below the other
  2734. }
  2735. }
  2736. void PlaylistComponent::glideBy (double ticks, double pixels)
  2737. {
  2738. if (! gliding)
  2739. {
  2740. glideX.jumpTo (scrollTicks);
  2741. glideY.jumpTo (scrollY);
  2742. gliding = true;
  2743. }
  2744. const auto grid = gridArea();
  2745. glideX.target = juce::jlimit (0.0, juce::jmax (0.0, hBar.getMaximumRangeLimit() - grid.getWidth() / pixelsPerTick), glideX.target + ticks);
  2746. glideY.target = juce::jlimit (0.0, juce::jmax (0.0, (double) tracksHeight() - grid.getHeight()), glideY.target + pixels);
  2747. glideFrame();
  2748. }
  2749. void PlaylistComponent::glideFrame()
  2750. {
  2751. if (! gliding)
  2752. return;
  2753. // someone else moved the view (scroll bar, zoom, pan, playback follow): the glide gives way
  2754. if (std::abs (scrollTicks - glideX.current) > 1e-6 || std::abs ((double) scrollY - std::round (glideY.current)) > 0.5)
  2755. {
  2756. gliding = false;
  2757. return;
  2758. }
  2759. scrollTicks = glideX.step (0.45, 0.5 / pixelsPerTick);
  2760. scrollY = (int) std::round (glideY.step (0.45, 1.0));
  2761. glideY.current = scrollY;
  2762. updateScrollBars();
  2763. glideX.current = scrollTicks;
  2764. gliding = glideX.isMoving() || glideY.isMoving();
  2765. repaint();
  2766. }
  2767. void PlaylistComponent::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  2768. {
  2769. const auto ctrl = e.mods.isCtrlDown(), alt = e.mods.isAltDown(), shift = e.mods.isShiftDown();
  2770. // Shift+wheel over a track header: moves the track up / down
  2771. if (shift && ! ctrl && e.x < headerWidth && e.y >= headerHeight && wheel.deltaY != 0.0f)
  2772. {
  2773. const auto track = yToTrack (e.y);
  2774. const auto other = track + (wheel.deltaY > 0 ? -1 : 1);
  2775. if (other >= 0 && other < numTracks())
  2776. {
  2777. setSelection ({});
  2778. engine.editSong ([track, other] (Song& s) { noteedit::swapTracks (s, track, other); });
  2779. // the mouse follows the track, so the next wheel step moves it further
  2780. refreshTrackLayout();
  2781. juce::Desktop::setMousePosition (localPointToGlobal (juce::Point<int> (e.x, trackToY (other) + heightOf (other) / 2)));
  2782. }
  2783. return;
  2784. }
  2785. if (shift && alt) // nudge the selected clips by the grid
  2786. {
  2787. if (wheel.deltaY != 0.0f && ! selection.empty())
  2788. {
  2789. const auto now = juce::Time::getMillisecondCounter();
  2790. const auto newBurst = now - lastWheelEdit > 700; // one undo step per burst
  2791. lastWheelEdit = now;
  2792. const auto ticks = (wheel.deltaY > 0 ? 1 : -1) * gridTicks();
  2793. engine.editSong ([this, ticks] (Song& s) {
  2794. auto delta = ticks;
  2795. for (auto i : selection)
  2796. delta = juce::jmax (delta, -s.playlist[(std::size_t) i].start);
  2797. for (auto i : selection)
  2798. s.playlist[(std::size_t) i].start += delta;
  2799. }, newBurst);
  2800. sortClips();
  2801. }
  2802. return;
  2803. }
  2804. if (ctrl)
  2805. {
  2806. gliding = false;
  2807. const auto anchorPixels = (double) juce::jmax (0, e.x - headerWidth);
  2808. const auto zoomed = juce::jlimit (4.0 / (4 * ppq), 800.0 / (4 * ppq), pixelsPerTick * gesture::wheelZoomFactor (wheel.deltaY, wheel.isSmooth));
  2809. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  2810. pixelsPerTick = zoomed;
  2811. zoomBeforeAll = 0.0;
  2812. updateScrollBars();
  2813. repaint();
  2814. return;
  2815. }
  2816. // plain wheel: up/down (Shift: left/right); a horizontal wheel or trackpad swipe scrolls sideways
  2817. if (shift)
  2818. glideBy (gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 120.0) / pixelsPerTick, 0.0);
  2819. else
  2820. glideBy (gesture::wheelScrollPixels (wheel.deltaX, wheel.isSmooth, 80.0) / pixelsPerTick,
  2821. gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 2.0 * trackHeight));
  2822. }
  2823. void PlaylistComponent::scrollBarMoved (juce::ScrollBar* bar, double start)
  2824. {
  2825. if (bar == &hBar)
  2826. scrollTicks = start;
  2827. else
  2828. scrollY = (int) start;
  2829. repaint();
  2830. }
  2831. void PlaylistComponent::changeListenerCallback (juce::ChangeBroadcaster* source)
  2832. {
  2833. if (source == ui::WaveformCache::getInstanceWithoutCreating())
  2834. {
  2835. repaint();
  2836. return;
  2837. }
  2838. // the clip list changed externally (undo, pattern removal...): the selection no longer applies
  2839. const auto count = engine.getSong().playlist.size();
  2840. if (count != knownClipCount && drag == Drag::none)
  2841. {
  2842. knownClipCount = count;
  2843. selection.clear();
  2844. }
  2845. // switching pattern (top bar, Channel Rack) sets the pencil back to the pattern
  2846. if (engine.getSong().currentPattern != knownCurrentPattern)
  2847. {
  2848. knownCurrentPattern = engine.getSong().currentPattern;
  2849. brush = {};
  2850. }
  2851. refreshArrangementBox();
  2852. refreshTrackLayout();
  2853. updateScrollBars();
  2854. repaint();
  2855. }
  2856. void PlaylistComponent::timerCallback()
  2857. {
  2858. auto& transport = engine.getTransport();
  2859. const auto& song = engine.getSong();
  2860. auto tick = -1.0;
  2861. if (song.mode == PlayMode::song && (transport.playing.load() || transport.positionTicks.load() > 0.0))
  2862. tick = std::fmod (transport.positionTicks.load(), (double) song.songLength());
  2863. if (tick != playheadTick && isShowing())
  2864. {
  2865. // only the cursor column (old and new) is repainted: large projects stay cheap
  2866. auto dirty = [this] (double t) {
  2867. if (t >= 0.0)
  2868. repaint ((int) tickToX (t) - 8, 0, 16, getHeight());
  2869. };
  2870. dirty (playheadTick);
  2871. playheadTick = tick;
  2872. // follows playback: if the cursor leaves the screen, scrolls one page
  2873. const auto grid = gridArea();
  2874. const auto x = tickToX (tick);
  2875. if (tick >= 0.0 && transport.playing.load() && (x > grid.getRight() - 20 || x < grid.getX()))
  2876. {
  2877. scrollTicks = juce::jmax (0.0, tick - 20.0 / pixelsPerTick);
  2878. updateScrollBars();
  2879. repaint();
  2880. }
  2881. else
  2882. dirty (tick);
  2883. }
  2884. }
  2885. bool PlaylistComponent::isInterestedInDragSource (const SourceDetails& details)
  2886. {
  2887. return BrowserComponent::isBrowserDrag (details);
  2888. }
  2889. void PlaylistComponent::itemDropped (const SourceDetails& details)
  2890. {
  2891. if (const auto file = BrowserComponent::draggedFile (details); file.existsAsFile())
  2892. filesDropped ({ file.getFullPathName() }, details.localPosition.x, details.localPosition.y);
  2893. }
  2894. // ---------------------------------------------------------------------------
  2895. PatternPicker::PatternPicker (AudioEngine& e, PlaylistComponent& p)
  2896. : engine (e),
  2897. playlist (p)
  2898. {
  2899. engine.addChangeListener (this);
  2900. }
  2901. PatternPicker::~PatternPicker()
  2902. {
  2903. engine.removeChangeListener (this);
  2904. }
  2905. void PatternPicker::changeListenerCallback (juce::ChangeBroadcaster*)
  2906. {
  2907. repaint();
  2908. }
  2909. std::vector<PatternPicker::Row> PatternPicker::rows() const
  2910. {
  2911. const auto& song = engine.getSong();
  2912. std::vector<Row> list;
  2913. list.push_back ({ ClipKind::pattern, -1, tr ("Patterns"), {} });
  2914. for (int i = 0; i < (int) song.patterns.size(); ++i)
  2915. list.push_back ({ ClipKind::pattern, i, juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str()),
  2916. PlaylistComponent::patternColour (song, i) });
  2917. bool audioHeader = false;
  2918. for (int c = 0; c < (int) song.channels.size(); ++c)
  2919. if (song.channels[(std::size_t) c].instrument == InstrumentKind::audioClip)
  2920. {
  2921. if (! audioHeader)
  2922. list.push_back ({ ClipKind::audio, -1, tr ("Audio"), {} });
  2923. audioHeader = true;
  2924. list.push_back ({ ClipKind::audio, c, juce::String::fromUTF8 (song.channels[(std::size_t) c].name.c_str()), theme::colour::audioClip });
  2925. }
  2926. if (! song.automations.empty())
  2927. list.push_back ({ ClipKind::automation, -1, tr ("Automation"), {} });
  2928. for (int a = 0; a < (int) song.automations.size(); ++a)
  2929. list.push_back ({ ClipKind::automation, a, juce::String::fromUTF8 (song.automations[(std::size_t) a].name.c_str()), theme::colour::automation });
  2930. return list;
  2931. }
  2932. int PatternPicker::rowAt (int y) const
  2933. {
  2934. if (y < headerHeight)
  2935. return -1;
  2936. const auto index = (y - headerHeight) / rowHeight + scroll;
  2937. return index < (int) rows().size() ? index : -1;
  2938. }
  2939. void PatternPicker::paint (juce::Graphics& g)
  2940. {
  2941. const auto& song = engine.getSong();
  2942. const auto list = rows();
  2943. using namespace theme;
  2944. g.fillAll (colour::bg2);
  2945. g.setColour (colour::bg3);
  2946. g.fillRect (0, 0, getWidth(), headerHeight);
  2947. g.setColour (colour::border);
  2948. g.fillRect (0, headerHeight - 1, getWidth(), 1);
  2949. g.setColour (colour::textSecondary);
  2950. g.setFont (font (type::small, true));
  2951. g.drawText (theme::caps (tr ("Picker")), 10, 0, getWidth() - 20, headerHeight, juce::Justification::centredLeft);
  2952. for (int i = scroll; i < (int) list.size(); ++i)
  2953. {
  2954. const auto y = headerHeight + (i - scroll) * rowHeight;
  2955. if (y > getHeight())
  2956. break;
  2957. const auto& row = list[(std::size_t) i];
  2958. if (row.index < 0) // section title
  2959. {
  2960. g.setColour (colour::textDisabled);
  2961. g.setFont (font (type::caption, true));
  2962. g.drawText (theme::caps (row.name), 10, y, getWidth() - 20, rowHeight - 3, juce::Justification::bottomLeft);
  2963. continue;
  2964. }
  2965. const auto r = juce::Rectangle<int> (4, y + 2, getWidth() - 8, rowHeight - 4);
  2966. const auto current = row.kind == ClipKind::pattern ? (playlist.brush.kind == ClipKind::pattern && row.index == song.currentPattern)
  2967. : (playlist.brush.kind == row.kind && playlist.brush.index == row.index);
  2968. const auto rowColour = tame (row.colour);
  2969. const auto box = r.toFloat();
  2970. g.setColour (current ? rowColour.interpolatedWith (colour::bg3, 0.35f) : colour::bg3);
  2971. g.fillRoundedRectangle (box, radius::sm);
  2972. // colour swatch on the left; the current row gets the accent strip instead
  2973. g.setColour (current ? colour::accent : rowColour);
  2974. g.fillRoundedRectangle (box.withWidth (3.0f), 1.5f);
  2975. g.setColour (current ? clipTitleText (rowColour.interpolatedWith (colour::bg3, 0.35f)) : colour::textPrimary.withAlpha (0.85f));
  2976. g.setFont (font (type::small, current));
  2977. g.drawText (row.name, r.withTrimmedLeft (10).withTrimmedRight (4), juce::Justification::centredLeft, true);
  2978. }
  2979. g.setColour (colour::border);
  2980. g.drawVerticalLine (getWidth() - 1, 0.0f, (float) getHeight());
  2981. }
  2982. void PatternPicker::mouseDown (const juce::MouseEvent& e)
  2983. {
  2984. const auto list = rows();
  2985. const auto i = rowAt (e.y);
  2986. if (i < 0 || list[(std::size_t) i].index < 0)
  2987. return;
  2988. const auto& row = list[(std::size_t) i];
  2989. playlist.brush = { row.kind, row.index };
  2990. if (row.kind == ClipKind::pattern && row.index != engine.getSong().currentPattern)
  2991. engine.editSong ([p = row.index] (Song& s) { s.currentPattern = p; }, false);
  2992. repaint();
  2993. }
  2994. void PatternPicker::mouseDoubleClick (const juce::MouseEvent& e)
  2995. {
  2996. const auto list = rows();
  2997. const auto i = rowAt (e.y);
  2998. if (i >= 0 && list[(std::size_t) i].kind == ClipKind::pattern && list[(std::size_t) i].index >= 0 && onOpenPattern)
  2999. onOpenPattern();
  3000. }
  3001. void PatternPicker::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  3002. {
  3003. const auto rows = (int) this->rows().size();
  3004. const auto visible = juce::jmax (1, (getHeight() - headerHeight) / rowHeight);
  3005. scroll = juce::jlimit (0, juce::jmax (0, rows - visible), scroll - (int) std::round (wheel.deltaY * 6.0f));
  3006. repaint();
  3007. }
  3008. } // namespace lynx