SimpleDock.cpp 175 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820
  1. #include "ui/SimpleDock.h"
  2. #include "ui/TrackerComponent.h"
  3. #include "ui/DemoMode.h" // (round 190np: the Drum Machine is a demo::CellSource)
  4. #include <algorithm>
  5. #include <array>
  6. #include <cmath>
  7. #include <set>
  8. #include "core/ChainPresets.h"
  9. #include "core/DetailChain.h"
  10. #include "core/GoalKnobs.h"
  11. #include "core/KeyFollow.h"
  12. #include "core/MixerOps.h"
  13. #include "core/SimplePads.h"
  14. #include "core/SimpleSteps.h"
  15. #include "core/SmartControls.h"
  16. #include "core/SimpleTracks.h"
  17. #include "core/SoundLibrary.h"
  18. #include "engine/AudioEngine.h"
  19. #include "engine/PluginHost.h"
  20. #include "engine/ProjectFile.h"
  21. #include "platform/Paths.h"
  22. #include "ui/FileChoosers.h"
  23. #include "ui/BrowserComponent.h"
  24. #include "ui/I18n.h"
  25. #include "ui/MixerComponent.h"
  26. #include "ui/PianoRollComponent.h"
  27. #include "ui/QuickPick.h"
  28. #include "ui/SimpleLook.h"
  29. #include "ui/SoundFontEditor.h"
  30. #include "ui/TrackIcons.h"
  31. #include "ui/Icons.h"
  32. #include "ui/HintBar.h"
  33. #include "core/AudioCapture.h"
  34. #include "ui/Motion.h"
  35. #include "ui/Theme.h"
  36. #include "ui/TouchKeyboard.h"
  37. namespace lynx
  38. {
  39. using namespace theme;
  40. namespace
  41. {
  42. juce::String utf8 (const std::string& s) { return juce::String::fromUTF8 (s.c_str()); }
  43. juce::String glyph (const char* bytes) { return juce::String::fromUTF8 (bytes); }
  44. // geometry (px at 100 %)
  45. constexpr int sideWidth = 212, cardWidth = 148, cardGap = 8, addWidth = 52, titleHeight = 26, pad = 8;
  46. constexpr int rowHeight = 28, categoryWidth = 168; // (round 190jc, SG-9: sound rows 24 -> 28 px)
  47. // Words that mean something else elsewhere in the UI get their own translation here ("Keys" the instruments, not
  48. // the computer's keys; "Punch" the effect, not punch-in recording)
  49. juce::String goalText (int id) { return id == goals::punch ? trc ("@one-knob effect: Punch") : tr (goals::name (id)); }
  50. juce::String soundCategoryText (soundlib::Category c)
  51. {
  52. using C = soundlib::Category;
  53. return c == C::keys ? trc ("@sound category: Keys") : c == C::bass ? trc ("@instrument: Bass") : c == C::lead ? trc ("@sound category: Lead")
  54. : c == C::effects ? trc ("@sound category: Effects") : tr (soundlib::categoryName (c));
  55. }
  56. juce::String chainCategoryText (const char* name)
  57. {
  58. const juce::String n (name);
  59. return n == "Keys" ? trc ("@sound category: Keys") : n == "Bass" ? trc ("@instrument: Bass") : n == "Space" ? trc ("@preset category: Space") : tr (name);
  60. }
  61. juce::String percent (float v) { return juce::String (juce::roundToInt (v * 100.0f)) + " %"; }
  62. juce::String trackTitle (const Song& song, int track)
  63. {
  64. if (track >= 0 && track < (int) song.playlistTracks.size() && ! song.playlistTracks[(std::size_t) track].name.empty())
  65. return utf8 (song.playlistTracks[(std::size_t) track].name);
  66. return tr ("Track {0}", { juce::String (track + 1) });
  67. }
  68. // One rotary control of the dock: a value 0..1 with its text under the ring. Drag up / down (Shift: fine), the wheel,
  69. // the arrow keys; a double click goes back to `resetValue`. While it is dragged it keeps its own value, so the
  70. // song's change messages don't fight the hand.
  71. class DockKnob final : public juce::Component,
  72. public juce::SettableTooltipClient
  73. {
  74. public:
  75. std::function<void (float)> onChange;
  76. std::function<juce::String (float)> valueText;
  77. float resetValue = 0.5f;
  78. bool big = false;
  79. DockKnob()
  80. {
  81. setWantsKeyboardFocus (true);
  82. getProperties().set ("lynxClickKeepsKeys", true); // (round 190fc: clicked, the arrow keys turn it; Space still plays)
  83. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  84. }
  85. float value() const noexcept { return shown; }
  86. void setValue (float v)
  87. {
  88. v = juce::jlimit (0.0f, 1.0f, v);
  89. if (dragging || std::abs (v - shown) < 1.0e-6f)
  90. return;
  91. shown = v;
  92. repaint();
  93. }
  94. void setDimmed (bool d)
  95. {
  96. if (dimmed != d)
  97. {
  98. dimmed = d;
  99. repaint();
  100. }
  101. }
  102. // the user's move (tests call it as a drag does)
  103. void turnTo (float v)
  104. {
  105. shown = juce::jlimit (0.0f, 1.0f, v);
  106. repaint();
  107. if (onChange)
  108. onChange (shown);
  109. }
  110. void paint (juce::Graphics& g) override
  111. {
  112. auto r = getLocalBounds().toFloat();
  113. const auto textHeight = big ? 20.0f : 16.0f;
  114. const auto text = r.removeFromBottom (textHeight);
  115. const auto d = juce::jmin (r.getWidth(), r.getHeight());
  116. const auto ring = juce::Rectangle<float> (d, d).withCentre (r.getCentre()).reduced (big ? 3.0f : 2.0f);
  117. const bool hot = dragging || isMouseOver() || hasKeyboardFocus (false);
  118. if (big) // a face under the ring, so the one knob reads as the card's control
  119. {
  120. g.setColour (colour::bg0);
  121. g.fillEllipse (ring.reduced (ring.getWidth() * 0.16f));
  122. g.setColour (hot ? colour::borderStrong : colour::border);
  123. g.drawEllipse (ring.reduced (ring.getWidth() * 0.16f), 1.0f);
  124. }
  125. drawKnob (g, ring, shown, false, dimmed ? colour::textDisabled : dragging ? colour::accent : colour::knobArc, hot);
  126. g.setColour (dimmed ? colour::textDisabled : colour::textPrimary);
  127. g.setFont (font (big ? type::body : type::small, big));
  128. g.drawText (valueText ? valueText (shown) : percent (shown), text, juce::Justification::centred, false);
  129. }
  130. void mouseDown (const juce::MouseEvent& e) override
  131. {
  132. if (e.mods.isPopupMenu())
  133. return;
  134. dragging = true;
  135. start = shown;
  136. grabKeyboardFocus();
  137. repaint();
  138. }
  139. void mouseDrag (const juce::MouseEvent& e) override
  140. {
  141. if (! dragging)
  142. return;
  143. const auto span = e.mods.isShiftDown() ? 640.0f : 160.0f;
  144. turnTo (start - (float) e.getDistanceFromDragStartY() / span);
  145. }
  146. void mouseUp (const juce::MouseEvent&) override
  147. {
  148. dragging = false;
  149. repaint();
  150. }
  151. void mouseDoubleClick (const juce::MouseEvent&) override { turnTo (resetValue); }
  152. void mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel) override
  153. {
  154. if (std::abs (wheel.deltaY) > 0.0f)
  155. turnTo (shown + (wheel.deltaY > 0.0f ? 0.02f : -0.02f));
  156. }
  157. bool keyPressed (const juce::KeyPress& key) override
  158. {
  159. const auto step = key.getModifiers().isShiftDown() ? 0.01f : 0.05f;
  160. if (key.isKeyCode (juce::KeyPress::upKey) || key.isKeyCode (juce::KeyPress::rightKey))
  161. return turnTo (shown + step), true;
  162. if (key.isKeyCode (juce::KeyPress::downKey) || key.isKeyCode (juce::KeyPress::leftKey))
  163. return turnTo (shown - step), true;
  164. return false;
  165. }
  166. void mouseEnter (const juce::MouseEvent&) override { repaint(); }
  167. void mouseExit (const juce::MouseEvent&) override { repaint(); }
  168. void focusGained (FocusChangeType) override { repaint(); }
  169. void focusLost (FocusChangeType) override { repaint(); }
  170. private:
  171. float shown = 0.0f, start = 0.0f;
  172. bool dragging = false, dimmed = false;
  173. };
  174. // A small flat button of a card's title bar and of the sound picker (‹ › ×). Round 190jc (design190ia SG-9, SG-10): vector
  175. // glyphs (`size` px: chevrons 5 x 9 / 6 x 10, the X 8 x 8, stroke 1.5) instead of 2-5 px text glyphs; a round hover fill.
  176. class GlyphButton final : public juce::Button
  177. {
  178. public:
  179. GlyphButton (const juce::String& name, ui::simplelook::Glyph g, juce::Point<float> glyphSize, bool roundHover = true)
  180. : juce::Button (name), glyph (g), size (glyphSize), round (roundHover)
  181. {
  182. }
  183. void paintButton (juce::Graphics& g, bool over, bool down) override
  184. {
  185. const auto r = getLocalBounds().toFloat();
  186. if (isEnabled() && (over || down))
  187. {
  188. g.setColour (down ? colour::bg6 : colour::bg5);
  189. if (round)
  190. g.fillEllipse (r.withSizeKeepingCentre (juce::jmin (r.getWidth(), r.getHeight()), juce::jmin (r.getWidth(), r.getHeight())).reduced (0.5f));
  191. else
  192. g.fillRoundedRectangle (r.reduced (1.0f), radius::lg);
  193. }
  194. const auto scale = ui::simplelook::px (1.0f, 1.4f);
  195. ui::simplelook::drawGlyph (g, glyph, r.withSizeKeepingCentre (size.x * scale, size.y * scale),
  196. ! isEnabled() ? colour::textDisabled : over ? colour::textPrimary : colour::textSecondary, 1.5f);
  197. }
  198. private:
  199. ui::simplelook::Glyph glyph;
  200. juce::Point<float> size;
  201. bool round;
  202. };
  203. // The last "card" of the chain: a big + in a dashed frame
  204. class AddCardButton final : public juce::Button
  205. {
  206. public:
  207. AddCardButton() : juce::Button ("+") {}
  208. void paintButton (juce::Graphics& g, bool over, bool down) override
  209. {
  210. const auto r = getLocalBounds().toFloat().reduced (0.5f);
  211. fillRoundRect (g, r, radius::lg, down ? colour::bg4 : over ? colour::bg3 : colour::bg2);
  212. juce::Path frame;
  213. frame.addRoundedRectangle (r.reduced (0.5f), radius::lg);
  214. const float dashes[] { 4.0f, 4.0f };
  215. juce::Path dashed;
  216. juce::PathStrokeType (1.0f).createDashedStroke (dashed, frame, dashes, 2);
  217. g.setColour (! isEnabled() ? colour::border : over ? colour::textSecondary : colour::borderStrong);
  218. g.fillPath (dashed);
  219. const auto c = r.getCentre();
  220. g.setColour (! isEnabled() ? colour::textDisabled : over ? colour::textPrimary : colour::textSecondary);
  221. g.fillRect (juce::Rectangle<float> (18.0f, 2.0f).withCentre (c));
  222. g.fillRect (juce::Rectangle<float> (2.0f, 18.0f).withCentre (c));
  223. }
  224. };
  225. // BandLab's preset stepper chevrons and its chain bypass button (round 190kn, DS-26 / DS-28: bandlab190p
  226. // 11-sounds-free-loops.png "‹ Bass Boost ›" and the struck "Fx" disc beside Save). LYNX vectors.
  227. class ChevronButton final : public juce::Button
  228. {
  229. public:
  230. explicit ChevronButton (bool pointsRight) : juce::Button (pointsRight ? "next" : "previous"), right (pointsRight)
  231. {
  232. setMouseCursor (juce::MouseCursor::PointingHandCursor);
  233. }
  234. void paintButton (juce::Graphics& g, bool over, bool down) override
  235. {
  236. auto r = getLocalBounds().toFloat();
  237. if (over || down)
  238. {
  239. g.setColour (down ? colour::bg5 : colour::bg4);
  240. g.fillRoundedRectangle (r.reduced (1.0f), radius::sm);
  241. }
  242. const auto c = r.getCentre();
  243. const auto s = 3.5f, d = right ? 1.0f : -1.0f;
  244. juce::Path p;
  245. p.startNewSubPath (c.x - d * s * 0.5f, c.y - s);
  246. p.lineTo (c.x + d * s * 0.5f, c.y);
  247. p.lineTo (c.x - d * s * 0.5f, c.y + s);
  248. g.setColour (! isEnabled() ? colour::textDisabled : over ? colour::textPrimary : colour::textSecondary);
  249. g.strokePath (p, juce::PathStrokeType (1.5f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  250. }
  251. private:
  252. bool right;
  253. };
  254. // BandLab's ⓘ on an effect card (round 190kn, DS-25: bandlab190p 11-sounds-free-loops.png, the card's title bar)
  255. class InfoButton final : public juce::Button
  256. {
  257. public:
  258. InfoButton() : juce::Button ("about") { setMouseCursor (juce::MouseCursor::PointingHandCursor); }
  259. void paintButton (juce::Graphics& g, bool over, bool down) override
  260. {
  261. const auto r = getLocalBounds().toFloat().reduced (1.0f);
  262. const auto ink = down ? colour::textPrimary : over ? colour::textPrimary : colour::textSecondary;
  263. g.setColour (ink);
  264. g.drawEllipse (r.reduced (0.5f), 1.2f);
  265. const auto c = r.getCentre();
  266. const auto u = r.getWidth() / 12.0f;
  267. g.fillEllipse (c.x - 0.9f * u, c.y - 3.6f * u, 1.8f * u, 1.8f * u);
  268. g.fillRoundedRectangle (c.x - 0.8f * u, c.y - 1.0f * u, 1.6f * u, 4.6f * u, 0.6f * u);
  269. }
  270. };
  271. class ChainBypassButton final : public juce::Button
  272. {
  273. public:
  274. ChainBypassButton() : juce::Button ("bypass") { setMouseCursor (juce::MouseCursor::PointingHandCursor); }
  275. bool bypassed = false; // every effect of the chain off
  276. void paintButton (juce::Graphics& g, bool over, bool down) override
  277. {
  278. const auto r = getLocalBounds().toFloat().withSizeKeepingCentre (26.0f, 26.0f).reduced (0.5f);
  279. g.setColour (bypassed ? colour::accent : down ? colour::bg5 : over ? colour::bg4 : colour::bg3);
  280. g.fillEllipse (r);
  281. const auto ink = ! isEnabled() ? colour::textDisabled : bypassed ? colour::onAccent : over ? colour::textPrimary : colour::textSecondary;
  282. g.setColour (ink);
  283. g.setFont (font (type::caption, true).withStyle (juce::Font::bold | juce::Font::italic));
  284. g.drawText ("Fx", r.toNearestInt(), juce::Justification::centred, false);
  285. // the stroke through it (BandLab's bypass glyph)
  286. g.drawLine (r.getX() + 7.0f, r.getBottom() - 7.0f, r.getRight() - 7.0f, r.getY() + 7.0f, 1.4f);
  287. }
  288. };
  289. void styleCaption (juce::Label& label, const juce::String& text)
  290. {
  291. label.setText (text, juce::dontSendNotification);
  292. label.setFont (font (type::caption));
  293. label.setColour (juce::Label::textColourId, colour::textSecondary);
  294. label.setInterceptsMouseClicks (false, false);
  295. }
  296. } // namespace
  297. // =====================================================================================================================
  298. // Effects
  299. // =====================================================================================================================
  300. class SimpleDock::EffectsPage final : public juce::Component
  301. {
  302. public:
  303. explicit EffectsPage (AudioEngine& e) : engine (e), slotActions (e)
  304. {
  305. addChildComponent (slotActions); // (never shown: the Mixer slot's own menus, windows and edits on this insert)
  306. slotActions.setMenuTarget (this);
  307. styleCaption (presetCaption, tr ("Preset"));
  308. addAndMakeVisible (presetCaption);
  309. presetButton.setTooltip (tr ("A ready chain of effects for this track"));
  310. presetButton.onClick = [this] { presetMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&presetButton)); };
  311. addAndMakeVisible (presetButton);
  312. saveButton.setButtonText (tr ("Save"));
  313. saveButton.setTooltip (tr ("Keeps this chain as one of your presets"));
  314. saveButton.onClick = [this] { askSaveName(); };
  315. addAndMakeVisible (saveButton);
  316. // round 190kn: BandLab's ‹ › on the preset and its chain bypass
  317. previousPreset.setTooltip (tr ("Previous preset"));
  318. nextPreset.setTooltip (tr ("Next preset"));
  319. previousPreset.onClick = [this] { stepPreset (-1); };
  320. nextPreset.onClick = [this] { stepPreset (1); };
  321. addAndMakeVisible (previousPreset);
  322. addAndMakeVisible (nextPreset);
  323. bypassButton.setTooltip (tr ("Bypass all effects of this track (again: back on)"));
  324. bypassButton.onClick = [this] {
  325. const auto t = insert;
  326. if (t < 0 || ! hasEffects())
  327. return;
  328. const auto on = ! mixerops::anyEffectEnabled (engine.getSong(), t);
  329. engine.editSong ([t, on] (Song& s) { mixerops::setAllEffectsEnabled (s, t, on); });
  330. };
  331. addAndMakeVisible (bypassButton);
  332. styleCaption (blendCaption, tr ("Blend"));
  333. addAndMakeVisible (blendCaption);
  334. blend.resetValue = 1.0f;
  335. blend.setTooltip (tr ("How much of the effects you hear: 0 % is the track without them"));
  336. blend.setTitle (tr ("Blend"));
  337. blend.onChange = [this] (float v) {
  338. const auto t = insert;
  339. if (t >= 0)
  340. engine.editSong ([t, v] (Song& s) {
  341. if (t < (int) s.mixer.size())
  342. s.mixer[(std::size_t) t].chainBlend = v;
  343. });
  344. };
  345. addAndMakeVisible (blend);
  346. // round 190fo: the track's send into the shared "Reverb" insert (the original's per-track Reverb knob)
  347. styleCaption (reverbCaption, tr ("Reverb"));
  348. addAndMakeVisible (reverbCaption);
  349. reverb.resetValue = 0.0f;
  350. reverb.setTooltip (tr ("How much of the track goes to the shared reverb (one Reverb insert for every track)"));
  351. reverb.setTitle (tr ("Reverb"));
  352. reverb.onChange = [this] (float v) {
  353. const auto t = insert;
  354. if (t > 0)
  355. engine.editSong ([t, v] (Song& s) { simpletracks::setReverbSend (s, t, v < 0.005f ? 0.0f : v); });
  356. };
  357. addAndMakeVisible (reverb);
  358. // round 190ot (research190oe P5): the second shared send, an echo (GarageBand's Echo and Reverb sends)
  359. styleCaption (echoCaption, tr ("Echo"));
  360. addAndMakeVisible (echoCaption);
  361. echo.resetValue = 0.0f;
  362. echo.setTooltip (tr ("How much of the track goes to the shared echo (one Echo insert for every track, a dotted quarter note at the song's tempo)"));
  363. echo.setTitle (tr ("Echo"));
  364. echo.onChange = [this] (float v) {
  365. const auto t = insert;
  366. if (t > 0)
  367. engine.editSong ([t, v] (Song& s) { simpletracks::setEchoSend (s, t, v < 0.005f ? 0.0f : v); });
  368. };
  369. addAndMakeVisible (echo);
  370. // round 190ot: "Duck under..." — the track dips on every hit of the one picked (sidechain pumping in one pick)
  371. styleCaption (duckCaption, tr ("Duck under"));
  372. addAndMakeVisible (duckCaption);
  373. duckButton.setTooltip (tr ("Dips this track on every hit of another track, a kick say (sidechain pumping). The Duck card's knob sets how much"));
  374. duckButton.setComponentID ("simple.dock.duck");
  375. duckButton.onClick = [this] { duckMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&duckButton)); };
  376. addAndMakeVisible (duckButton);
  377. view.setViewedComponent (&strip, false);
  378. view.setScrollBarsShown (false, true);
  379. view.setScrollBarThickness (8);
  380. addAndMakeVisible (view);
  381. addCard.setTooltip (tr ("Add an effect"));
  382. addCard.setComponentID ("simple.dock.addEffect"); // (round 190dv: the tour's ring)
  383. addCard.onClick = [this] { addMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&addCard)); };
  384. strip.addAndMakeVisible (addCard);
  385. styleCaption (emptyHint, {});
  386. emptyHint.setFont (font (type::body));
  387. emptyHint.setJustificationType (juce::Justification::centredLeft);
  388. strip.addAndMakeVisible (emptyHint);
  389. }
  390. void show (int newInsert)
  391. {
  392. if (insert != newInsert)
  393. {
  394. insert = newInsert;
  395. cards.clear();
  396. view.setViewPosition (0, 0);
  397. }
  398. slotActions.setTrack (juce::jmax (0, insert));
  399. refresh();
  400. }
  401. void refresh()
  402. {
  403. const auto& song = engine.getSong();
  404. const bool has = insert >= 0 && insert < (int) song.mixer.size();
  405. presetButton.setEnabled (has);
  406. previousPreset.setEnabled (has);
  407. nextPreset.setEnabled (has);
  408. blend.setEnabled (has);
  409. reverb.setValue (has ? simpletracks::reverbSend (song, insert) : 0.0f);
  410. const auto bus = has && insert > 0 && insert != simpletracks::sharedReverb (song) && insert != simpletracks::sharedEcho (song);
  411. reverb.setEnabled (bus);
  412. echo.setEnabled (bus);
  413. echo.setValue (has ? simpletracks::echoSend (song, insert) : 0.0f);
  414. duckButton.setEnabled (bus);
  415. {
  416. const auto trigger = has ? simpletracks::duckTrigger (song, insert) : -1;
  417. duckButton.setButtonText ((trigger > 0 ? insertTitle (trigger) : tr ("None")) + glyph (" \xe2\x96\xbe"));
  418. }
  419. addCard.setEnabled (has);
  420. if (! has)
  421. {
  422. cards.clear();
  423. presetButton.setButtonText (tr ("None"));
  424. saveButton.setEnabled (false);
  425. bypassButton.setEnabled (false);
  426. bypassButton.bypassed = false;
  427. bypassButton.repaint();
  428. blend.setValue (1.0f);
  429. // (round 190oj CS-26: with no track the knobs looked live next to a greyed Save and preset)
  430. blend.setDimmed (true);
  431. reverb.setDimmed (true);
  432. emptyHint.setText (tr ("Select a track to see its effects."), juce::dontSendNotification);
  433. layoutStrip();
  434. return;
  435. }
  436. const auto& mixer = song.mixer[(std::size_t) insert];
  437. const auto& fx = mixer.effects;
  438. // the cards are kept while the chain has the same shape: a knob being dragged stays the same component
  439. bool same = cards.size() == fx.size();
  440. for (std::size_t i = 0; same && i < fx.size(); ++i)
  441. same = cards[i]->kind == fx[i].kind && cards[i]->goal == (goals::active (fx[i]) ? (int) fx[i].goal : 0);
  442. if (! same)
  443. {
  444. cards.clear();
  445. for (std::size_t i = 0; i < fx.size(); ++i)
  446. {
  447. cards.push_back (std::make_unique<Card> (*this, (int) i));
  448. strip.addAndMakeVisible (*cards.back());
  449. }
  450. }
  451. for (std::size_t i = 0; i < fx.size(); ++i)
  452. cards[i]->update (fx[i], (int) i, (int) fx.size());
  453. auto name = mixer.chainPreset.empty() ? tr ("None") : utf8 (mixer.chainPreset);
  454. if (! mixer.chainPreset.empty() && ! chains::unchanged (song, insert))
  455. name << " " << tr ("(edited)");
  456. presetButton.setButtonText (name + glyph (" \xe2\x96\xbe"));
  457. saveButton.setEnabled (! fx.empty());
  458. bypassButton.setEnabled (! fx.empty());
  459. if (const auto off = ! fx.empty() && ! mixerops::anyEffectEnabled (song, insert); off != bypassButton.bypassed)
  460. {
  461. bypassButton.bypassed = off;
  462. bypassButton.repaint();
  463. }
  464. blend.setValue (mixer.chainBlend);
  465. blend.setDimmed (fx.empty());
  466. reverb.setDimmed (! reverb.isEnabled());
  467. addCard.setEnabled ((int) fx.size() < maxEffectSlots);
  468. emptyHint.setText (fx.empty() ? tr ("No effects yet. Press + to add one, or pick a preset.") : juce::String(), juce::dontSendNotification);
  469. layoutStrip();
  470. }
  471. void resized() override
  472. {
  473. auto r = getLocalBounds().reduced (pad);
  474. auto side = r.removeFromLeft (sideWidth - pad);
  475. presetCaption.setBounds (side.removeFromTop (16));
  476. auto row = side.removeFromTop (26);
  477. presetButton.setBounds (row); // (BandLab: "‹ Bass Boost ›", the arrows inside the preset's capsule)
  478. previousPreset.setBounds (row.removeFromLeft (22).reduced (0, 2));
  479. nextPreset.setBounds (row.removeFromRight (22).reduced (0, 2));
  480. side.removeFromTop (6);
  481. auto second = side.removeFromTop (26); // BandLab: Save and the chain bypass under the preset
  482. saveButton.setBounds (second.removeFromLeft (theme::buttonWidth (saveButton, 58, 110))); // (round 190oj WG-12: de "Speiche...")
  483. second.removeFromLeft (8);
  484. bypassButton.setBounds (second.removeFromLeft (26));
  485. side.removeFromTop (8);
  486. // round 190ot: "Duck under [track ▾]" (a caption, then its picker), then Blend | Reverb | Echo
  487. auto duckRow = side.removeFromTop (24);
  488. duckCaption.setBounds (duckRow.removeFromLeft (76));
  489. duckButton.setBounds (duckRow);
  490. side.removeFromTop (8);
  491. auto captions = side.removeFromTop (16);
  492. auto knobs = side.removeFromTop (juce::jmin (84, side.getHeight()));
  493. const auto third = side.getWidth() / 3;
  494. blendCaption.setBounds (captions.removeFromLeft (third));
  495. blend.setBounds (knobs.removeFromLeft (third).withSizeKeepingCentre (juce::jmin (third - 4, 64), knobs.getHeight()).withX (blendCaption.getX()));
  496. reverbCaption.setBounds (captions.removeFromLeft (third));
  497. reverb.setBounds (knobs.removeFromLeft (third).withSizeKeepingCentre (juce::jmin (third - 4, 64), knobs.getHeight()).withX (reverbCaption.getX()));
  498. echoCaption.setBounds (captions);
  499. echo.setBounds (knobs.withSizeKeepingCentre (juce::jmin (third - 4, 64), knobs.getHeight()).withX (echoCaption.getX()));
  500. r.removeFromLeft (pad);
  501. view.setBounds (r);
  502. layoutStrip();
  503. }
  504. void paint (juce::Graphics& g) override
  505. {
  506. g.setColour (colour::border);
  507. g.fillRect (sideWidth, pad, 1, getHeight() - 2 * pad);
  508. }
  509. // --- menus ------------------------------------------------------------------------------------------------------
  510. juce::PopupMenu presetMenu()
  511. {
  512. juce::PopupMenu menu;
  513. const auto& song = engine.getSong();
  514. const auto current = insert >= 0 && insert < (int) song.mixer.size() ? song.mixer[(std::size_t) insert].chainPreset : std::string();
  515. auto files = userPresetFolder().findChildFiles (juce::File::findFiles, false, juce::String ("*") + ProjectFile::mixerTrackStateExtension);
  516. files.sort();
  517. // round 190dg: the favourites first, under their own heading (a factory preset or one of the user's)
  518. const auto favs = favouritePresets();
  519. if (! favs.isEmpty())
  520. {
  521. juce::PopupMenu starred;
  522. for (const auto& f : favs)
  523. {
  524. const auto name = f.toStdString();
  525. if (chains::find (name) != nullptr)
  526. starred.addItem (f, true, current == name, [this, name] { applyFactory (name); });
  527. else if (const auto file = userPresetFolder().getChildFile (f + ProjectFile::mixerTrackStateExtension); file.existsAsFile())
  528. starred.addItem (f, true, current == name, [this, file] { loadUserPreset (engine, insert, file); });
  529. }
  530. if (starred.getNumItems() > 0)
  531. {
  532. menu.addSubMenu (glyph ("\xe2\x98\x85 ") + tr ("Favourites"), starred, true, nullptr, favs.contains (utf8 (current)));
  533. menu.addSeparator();
  534. }
  535. }
  536. for (const auto* category : chains::categories())
  537. {
  538. juce::PopupMenu sub;
  539. bool ticked = false;
  540. for (const auto& p : chains::factory())
  541. if (std::string (p.category) == category)
  542. {
  543. const bool on = current == p.name;
  544. ticked = ticked || on;
  545. sub.addItem (utf8 (p.name) + glyph (" \xe2\x80\x94 ") + tr (p.description), true, on, [this, name = std::string (p.name)] { applyFactory (name); });
  546. }
  547. menu.addSubMenu (chainCategoryText (category), sub, true, nullptr, ticked);
  548. }
  549. menu.addSeparator();
  550. juce::PopupMenu mine;
  551. for (const auto& f : files)
  552. mine.addItem (f.getFileNameWithoutExtension(), true, current == f.getFileNameWithoutExtension().toStdString(),
  553. [this, f] { loadUserPreset (engine, insert, f); });
  554. if (files.isEmpty())
  555. mine.addItem (tr ("(none yet)"), false, false, nullptr);
  556. menu.addSubMenu (tr ("My presets"), mine);
  557. menu.addItem (tr ("Save as my preset..."), hasEffects(), false, [this] { askSaveName(); });
  558. if (! current.empty()) // the track's own preset as a favourite (or not any more)
  559. {
  560. const auto shown = utf8 (current);
  561. const bool starred = favs.contains (shown);
  562. menu.addItem (starred ? tr ("Remove \"{0}\" from favourites", { shown }) : tr ("Add \"{0}\" to favourites", { shown }),
  563. [shown, starred] { setFavouritePreset (shown, ! starred); });
  564. }
  565. if (! files.isEmpty()) // (to the system's bin: a preset removed by mistake can be taken back)
  566. {
  567. juce::PopupMenu bin;
  568. for (const auto& f : files)
  569. bin.addItem (f.getFileNameWithoutExtension(), [f] { f.moveToTrash(); });
  570. menu.addSubMenu (tr ("Delete one of my presets"), bin);
  571. }
  572. menu.addSeparator();
  573. menu.addItem (tr ("Remove all effects"), hasEffects(), false, [this] {
  574. const auto t = insert;
  575. engine.editSongStructural ([t] (Song& s) { chains::applyChain (s, t, {}, 1.0f, {}); });
  576. });
  577. return menu;
  578. }
  579. juce::PopupMenu addMenu()
  580. {
  581. juce::PopupMenu menu;
  582. menu.addSectionHeader (tr ("One-knob effects"));
  583. for (int id = 1; id <= goals::count; ++id)
  584. menu.addItem (goalText (id) + glyph (" \xe2\x80\x94 ") + tr (goals::description (id)), [this, id] { addOneKnob (id); });
  585. menu.addSeparator();
  586. menu.addItem (tr ("More effects..."), [this] { slotActions.showAddMenuFor (nextFreeRow()); });
  587. return menu;
  588. }
  589. // round 190ot: "Duck under..." — None, the other tracks of the song (a track this one feeds cannot be picked: the
  590. // sidechain would make a loop), then the three styles (the Duck card's knob at Subtle / Pumping / Hard)
  591. juce::PopupMenu duckMenu()
  592. {
  593. juce::PopupMenu menu;
  594. const auto& song = engine.getSong();
  595. const auto t = insert;
  596. if (t <= 0 || t >= (int) song.mixer.size())
  597. return menu;
  598. const auto trigger = simpletracks::duckTrigger (song, t);
  599. menu.addSectionHeader (tr ("Duck under"));
  600. menu.addItem (tr ("None"), trigger > 0 || simpletracks::duckSlot (song, t) >= 0, trigger <= 0, [this] { pickDuck (-1); });
  601. std::vector<int> seen;
  602. for (int track = 0; track < (int) song.playlistTracks.size(); ++track)
  603. {
  604. if (! simpletracks::kindOf (song, track))
  605. continue;
  606. const auto from = simpletracks::insertOf (song, track);
  607. if (from <= 0 || from == t || std::find (seen.begin(), seen.end(), from) != seen.end())
  608. continue;
  609. seen.push_back (from);
  610. const auto possible = song.routes (from, t) || song.canRoute (from, t);
  611. menu.addItem (trackTitle (song, track), possible, from == trigger, [this, from] { pickDuck (from); });
  612. }
  613. if (seen.empty())
  614. menu.addItem (tr ("(no other track yet)"), false, false, nullptr);
  615. menu.addSeparator();
  616. menu.addSectionHeader (tr ("Style"));
  617. const auto slot = simpletracks::duckSlot (song, t);
  618. const auto amount = slot >= 0 ? song.mixer[(std::size_t) t].effects[(std::size_t) slot].goalAmount : -1.0f;
  619. for (const auto style : { simpletracks::DuckStyle::subtle, simpletracks::DuckStyle::pumping, simpletracks::DuckStyle::hard })
  620. {
  621. const auto value = simpletracks::duckAmount (style);
  622. menu.addItem (duckStyleText (style), slot >= 0, slot >= 0 && std::abs (amount - value) < 0.005f, [this, value] {
  623. const auto at = insert;
  624. engine.editSong ([at, value] (Song& s) { simpletracks::setDuckAmount (s, at, value); });
  625. });
  626. }
  627. return menu;
  628. }
  629. void pickDuck (int from)
  630. {
  631. const auto t = insert;
  632. if (t <= 0)
  633. return;
  634. engine.editSongStructural ([t, from] (Song& s) { simpletracks::setDuck (s, t, from); });
  635. }
  636. static juce::String duckStyleText (simpletracks::DuckStyle style)
  637. {
  638. using S = simpletracks::DuckStyle;
  639. return style == S::subtle ? trc ("@duck style: Subtle") : style == S::pumping ? trc ("@duck style: Pumping") : trc ("@duck style: Hard");
  640. }
  641. // a mixer insert as the Simple layout names it: the track that plays through it, else the insert's own name
  642. juce::String insertTitle (int at) const
  643. {
  644. const auto& song = engine.getSong();
  645. for (int track = 0; track < (int) song.playlistTracks.size(); ++track)
  646. if (simpletracks::kindOf (song, track) && simpletracks::insertOf (song, track) == at)
  647. return trackTitle (song, track);
  648. return at > 0 && at < (int) song.mixer.size() ? utf8 (song.mixer[(std::size_t) at].name) : juce::String();
  649. }
  650. // --- edits (each through the Mixer's own paths) -------------------------------------------------------------------
  651. void addOneKnob (int goal)
  652. {
  653. const auto t = insert;
  654. if (t < 0)
  655. return;
  656. engine.editSongStructural ([t, goal] (Song& s) {
  657. if (t < (int) s.mixer.size())
  658. detailchain::insertEffectAt (s, t, goals::make (goal), (int) s.mixer[(std::size_t) t].effects.size());
  659. });
  660. }
  661. void turn (int index, bool oneKnob, float v)
  662. {
  663. const auto t = insert;
  664. if (oneKnob)
  665. engine.editSong ([t, index, v] (Song& s) {
  666. if (t >= 0 && t < (int) s.mixer.size() && index < (int) s.mixer[(std::size_t) t].effects.size())
  667. goals::setAmount (s.mixer[(std::size_t) t].effects[(std::size_t) index], v);
  668. });
  669. else
  670. slotActions.setSlotParam (-1, index, v); // the slot's Mix, as the Mixer sets it
  671. }
  672. void toggle (int index)
  673. {
  674. const auto t = insert;
  675. engine.editSong ([t, index] (Song& s) {
  676. if (t >= 0 && t < (int) s.mixer.size() && index < (int) s.mixer[(std::size_t) t].effects.size())
  677. s.mixer[(std::size_t) t].effects[(std::size_t) index].enabled = ! s.mixer[(std::size_t) t].effects[(std::size_t) index].enabled;
  678. });
  679. }
  680. void move (int index, int delta)
  681. {
  682. const auto t = insert;
  683. // (moveEffectBefore: `position` is the card it lands before, counted with the moved card still in place)
  684. const auto position = delta < 0 ? index - 1 : index + 2;
  685. if (position < 0 || position > (int) cards.size())
  686. return;
  687. engine.editSongStructural ([t, index, position] (Song& s) { detailchain::moveEffectBefore (s, t, index, position); });
  688. }
  689. void moveTo (int index, int position)
  690. {
  691. const auto t = insert;
  692. if (position == index || position == index + 1)
  693. return;
  694. engine.editSongStructural ([t, index, position] (Song& s) { detailchain::moveEffectBefore (s, t, index, position); });
  695. }
  696. void remove (int index) { slotActions.deleteSlot (index); }
  697. void openEditor (int index) { slotActions.toggleSlotEditor (index); }
  698. void stepPreset (int direction)
  699. {
  700. const auto& song = engine.getSong();
  701. if (insert < 0 || insert >= (int) song.mixer.size())
  702. return;
  703. if (const auto* p = chains::stepped (song.mixer[(std::size_t) insert].chainPreset, direction))
  704. applyFactory (p->name);
  705. }
  706. void applyFactory (const std::string& name)
  707. {
  708. const auto t = insert;
  709. if (const auto* preset = chains::find (name); preset != nullptr && t >= 0)
  710. engine.editSongStructural ([t, preset] (Song& s) { chains::apply (s, t, *preset); });
  711. }
  712. void askSaveName()
  713. {
  714. if (! hasEffects())
  715. return;
  716. const auto& mixer = engine.getSong().mixer[(std::size_t) insert];
  717. auto* window = new juce::AlertWindow (tr ("Save as my preset"), tr ("A name for this chain of effects. A preset of yours with the same name is replaced."),
  718. juce::MessageBoxIconType::NoIcon);
  719. const auto factory = chains::find (mixer.chainPreset) != nullptr;
  720. window->addTextEditor ("name", mixer.chainPreset.empty() ? tr ("My preset") : factory ? tr ("{0} (my version)", { utf8 (mixer.chainPreset) }) : utf8 (mixer.chainPreset));
  721. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  722. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  723. juce::Component::SafePointer<EffectsPage> safe (this);
  724. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, safe] (int result) {
  725. if (result == 1 && safe != nullptr)
  726. saveUserPreset (safe->engine, safe->insert, window->getTextEditorContents ("name"));
  727. }),
  728. true);
  729. }
  730. // --- dragging a card by its title --------------------------------------------------------------------------------
  731. void dragCard (int index, int stripX)
  732. {
  733. dragging = index;
  734. // the gap the card would land in: before the first card whose middle is right of the pointer
  735. int position = (int) cards.size();
  736. for (int i = 0; i < (int) cards.size(); ++i)
  737. if (stripX < cards[(std::size_t) i]->getBounds().getCentreX())
  738. {
  739. position = i;
  740. break;
  741. }
  742. if (dropAt != position)
  743. {
  744. dropAt = position;
  745. strip.repaint();
  746. }
  747. }
  748. void dropCard()
  749. {
  750. const auto from = dragging, to = dropAt;
  751. dragging = dropAt = -1;
  752. strip.repaint();
  753. if (from >= 0 && to >= 0)
  754. moveTo (from, to);
  755. }
  756. int cardCount() const noexcept { return (int) cards.size(); }
  757. int oneKnobCards() const noexcept
  758. {
  759. return (int) std::count_if (cards.begin(), cards.end(), [] (const auto& c) { return c->goal != 0; });
  760. }
  761. void turnForCheck (int card, float v)
  762. {
  763. if (card >= 0 && card < (int) cards.size())
  764. cards[(std::size_t) card]->knob.turnTo (v);
  765. }
  766. void blendForCheck (float v) { blend.turnTo (v); }
  767. void reverbForCheck (float v) { reverb.turnTo (v); }
  768. void echoForCheck (float v) { echo.turnTo (v); } // round 190ot
  769. void duckForCheck (int from) { pickDuck (from); }
  770. juce::PopupMenu duckMenuForCheck() { return duckMenu(); }
  771. juce::String duckButtonTextForCheck() const { return duckButton.getButtonText(); }
  772. void bypassForCheck() { bypassButton.onClick(); } // round 190kn
  773. bool bypassLitForCheck() const noexcept { return bypassButton.bypassed; }
  774. const juce::Component* cardForSnapshot (int card) const
  775. {
  776. return card >= 0 && card < (int) cards.size() ? cards[(std::size_t) card].get() : nullptr;
  777. }
  778. AudioEngine& engine;
  779. int insert = -1;
  780. private:
  781. // One slot of the insert. A one-knob effect shows its goal and one big knob; any other effect its name and its Mix.
  782. class Card final : public juce::Component
  783. {
  784. public:
  785. Card (EffectsPage& o, int i) : owner (o), index (i)
  786. {
  787. knob.big = true;
  788. knob.onChange = [this] (float v) { owner.turn (index, goal != 0, v); };
  789. addAndMakeVisible (knob);
  790. editor.setButtonText (tr ("Editor"));
  791. editor.setTooltip (tr ("Opens the effect's own window with every control"));
  792. editor.onClick = [this] { owner.openEditor (index); };
  793. addAndMakeVisible (editor);
  794. left.setTooltip (tr ("Move earlier in the chain"));
  795. left.onClick = [this] { owner.move (index, -1); };
  796. right.setTooltip (tr ("Move later in the chain"));
  797. right.onClick = [this] { owner.move (index, 1); };
  798. close.setTooltip (tr ("Remove this effect"));
  799. close.onClick = [this] { owner.remove (index); };
  800. for (auto* b : { &left, &right, &close })
  801. addAndMakeVisible (*b);
  802. // round 190kn (DS-25, BandLab's card: toggle, ⓘ, name, ×): what the effect does, in a bubble
  803. info.setTooltip (tr ("About this effect"));
  804. info.onClick = [this] { showAbout(); };
  805. addAndMakeVisible (info);
  806. }
  807. juce::String aboutText() const
  808. {
  809. if (goal != 0)
  810. return goalText (goal) + ": " + tr (goals::description (goal));
  811. return tr ("{0}: its knob sets how much of the effect is mixed in; Editor opens all of its controls.", { title });
  812. }
  813. void showAbout()
  814. {
  815. auto label = std::make_unique<juce::Label> (juce::String(), aboutText());
  816. label->setFont (font (type::body));
  817. label->setColour (juce::Label::textColourId, colour::textPrimary);
  818. label->setJustificationType (juce::Justification::topLeft);
  819. const auto width = 240;
  820. const auto lines = juce::jmax (1, (int) std::ceil (juce::GlyphArrangement::getStringWidth (label->getFont(), label->getText()) / (float) (width - 12)));
  821. label->setSize (width, 12 + lines * (int) std::ceil (label->getFont().getHeight() + 3.0f));
  822. juce::CallOutBox::launchAsynchronously (std::move (label), info.getScreenBounds(), nullptr);
  823. }
  824. void update (const EffectSlot& slot, int newIndex, int count)
  825. {
  826. index = newIndex;
  827. kind = slot.kind;
  828. goal = goals::active (slot) ? (int) slot.goal : 0;
  829. on = slot.enabled;
  830. const auto effectName = quickpick::slotName (owner.engine, slot);
  831. title = goal != 0 ? goalText (goal) : effectName;
  832. sub = goal != 0 ? effectName : tr ("Mix");
  833. if (goal == goals::duck) // round 190ot: the trigger it listens to
  834. sub = slot.sidechain > 0 ? tr ("under {0}", { owner.insertTitle (slot.sidechain) }) : tr ("under no track yet");
  835. knob.resetValue = goal != 0 ? goals::defaultAmount (goal) : 1.0f;
  836. knob.setValue (goal != 0 ? slot.goalAmount : slot.mix);
  837. knob.setDimmed (! on);
  838. knob.setTitle (title);
  839. knob.setTooltip (goal != 0 ? tr (goals::description (goal)) : tr ("How much of this effect is mixed in"));
  840. left.setEnabled (index > 0);
  841. right.setEnabled (index + 1 < count);
  842. repaint();
  843. }
  844. juce::Rectangle<int> ledBounds() const { return { 7, 6, 14, 14 }; } // (round 190jc, SG-10: 14 px, ringed when off)
  845. juce::String aboutForCheck() const { return aboutText(); }
  846. void resized() override
  847. {
  848. auto r = getLocalBounds();
  849. auto bar = r.removeFromTop (titleHeight);
  850. // round 190jc (SG-10): 20 x 20 hit boxes
  851. bar.removeFromRight (3);
  852. close.setBounds (bar.removeFromRight (20).withSizeKeepingCentre (20, 20));
  853. right.setBounds (bar.removeFromRight (20).withSizeKeepingCentre (20, 20));
  854. left.setBounds (bar.removeFromRight (20).withSizeKeepingCentre (20, 20));
  855. info.setBounds (ledBounds().getRight() + 3, ledBounds().getY(), 14, 14);
  856. r.reduce (pad, 6);
  857. editor.setBounds (r.removeFromBottom (24));
  858. r.removeFromBottom (4);
  859. r.removeFromBottom (16); // (the effect's own name, painted)
  860. knob.setBounds (r.withSizeKeepingCentre (juce::jmin (r.getWidth(), 96), juce::jmin (r.getHeight(), 104)));
  861. }
  862. void paint (juce::Graphics& g) override
  863. {
  864. const auto r = getLocalBounds().toFloat();
  865. fillRoundRect (g, r, radius::lg, colour::bg2);
  866. {
  867. juce::Graphics::ScopedSaveState save (g);
  868. g.reduceClipRegion (getLocalBounds().withHeight (titleHeight));
  869. fillRoundRect (g, r.withHeight ((float) titleHeight + radius::lg), radius::lg, colour::bg3);
  870. }
  871. g.setColour (owner.dragging == index ? colour::accent : colour::border);
  872. g.drawRoundedRectangle (r.reduced (0.5f), radius::lg, 1.0f);
  873. g.setColour (on ? colour::accent : colour::ledOff);
  874. g.fillEllipse (ledBounds().toFloat());
  875. if (! on)
  876. {
  877. g.setColour (colour::textDisabled);
  878. g.drawEllipse (ledBounds().toFloat().reduced (0.5f), 1.0f);
  879. }
  880. if (ledHover)
  881. {
  882. g.setColour (colour::textPrimary.withAlpha (0.6f));
  883. g.drawEllipse (ledBounds().toFloat().expanded (1.5f), 1.0f);
  884. }
  885. g.setColour (on ? colour::textPrimary : colour::textSecondary);
  886. g.setFont (font (type::body, true));
  887. g.drawText (title, juce::Rectangle<int> (info.getRight() + 5, 0, left.getX() - info.getRight() - 7, titleHeight), juce::Justification::centredLeft, true);
  888. g.setColour (colour::textSecondary);
  889. g.setFont (font (type::caption));
  890. g.drawText (sub, juce::Rectangle<int> (pad, editor.getY() - 20, getWidth() - 2 * pad, 16), juce::Justification::centred, true);
  891. }
  892. void mouseMove (const juce::MouseEvent& e) override
  893. {
  894. const bool over = ledBounds().expanded (3).contains (e.getPosition());
  895. if (over != ledHover)
  896. {
  897. ledHover = over;
  898. repaint();
  899. }
  900. setMouseCursor (! over && e.y < titleHeight ? juce::MouseCursor::DraggingHandCursor : juce::MouseCursor::NormalCursor);
  901. }
  902. void mouseExit (const juce::MouseEvent&) override
  903. {
  904. ledHover = false;
  905. repaint();
  906. }
  907. void mouseDown (const juce::MouseEvent& e) override
  908. {
  909. pressedLed = ledBounds().expanded (3).contains (e.getPosition());
  910. pressedTitle = ! pressedLed && e.y < titleHeight;
  911. }
  912. void mouseDrag (const juce::MouseEvent& e) override
  913. {
  914. if (pressedTitle && e.getDistanceFromDragStart() > 5)
  915. owner.dragCard (index, e.getEventRelativeTo (getParentComponent()).x);
  916. }
  917. void mouseUp (const juce::MouseEvent& e) override
  918. {
  919. if (owner.dragging == index)
  920. owner.dropCard();
  921. else if (pressedLed && ledBounds().expanded (3).contains (e.getPosition()))
  922. owner.toggle (index);
  923. pressedLed = pressedTitle = false;
  924. }
  925. void mouseDoubleClick (const juce::MouseEvent& e) override
  926. {
  927. if (e.y < titleHeight && ! ledBounds().expanded (3).contains (e.getPosition()))
  928. owner.openEditor (index);
  929. }
  930. EffectsPage& owner;
  931. int index = 0, goal = 0;
  932. EffectKind kind = EffectKind::eq;
  933. bool on = true, ledHover = false, pressedLed = false, pressedTitle = false;
  934. juce::String title, sub;
  935. DockKnob knob;
  936. juce::TextButton editor;
  937. InfoButton info; // (round 190kn: BandLab's ⓘ)
  938. GlyphButton left { glyph ("\xe2\x80\xb9"), ui::simplelook::Glyph::chevronLeft, { 5.0f, 9.0f } },
  939. right { glyph ("\xe2\x80\xba"), ui::simplelook::Glyph::chevronRight, { 5.0f, 9.0f } },
  940. close { glyph ("\xc3\x97"), ui::simplelook::Glyph::cross, { 8.0f, 8.0f } };
  941. };
  942. // The row of cards (inside the viewport): it paints the drop mark while a card is dragged
  943. class Strip final : public juce::Component
  944. {
  945. public:
  946. explicit Strip (EffectsPage& o) : owner (o) {}
  947. void paintOverChildren (juce::Graphics& g) override
  948. {
  949. if (owner.dragging < 0 || owner.dropAt < 0)
  950. return;
  951. const auto x = owner.dropAt < (int) owner.cards.size() ? owner.cards[(std::size_t) owner.dropAt]->getX() - cardGap / 2
  952. : owner.addCard.getX() - cardGap / 2;
  953. g.setColour (colour::accent);
  954. g.fillRect (x - 1, 0, 2, getHeight());
  955. }
  956. EffectsPage& owner;
  957. };
  958. void layoutStrip()
  959. {
  960. const auto h = juce::jmax (40, view.getHeight() - (view.isHorizontalScrollBarShown() ? view.getScrollBarThickness() : 0));
  961. int x = 0;
  962. for (auto& c : cards)
  963. {
  964. c->setBounds (x, 0, cardWidth, h);
  965. x += cardWidth + cardGap;
  966. }
  967. addCard.setBounds (x, 0, addWidth, h);
  968. x += addWidth;
  969. const auto hintWidth = emptyHint.getText().isEmpty() ? 0 : 360;
  970. emptyHint.setBounds (x + 12, 0, hintWidth, h);
  971. strip.setSize (juce::jmax (view.getWidth(), x + (hintWidth > 0 ? hintWidth + 12 : 0)), h);
  972. }
  973. bool hasEffects() const
  974. {
  975. const auto& song = engine.getSong();
  976. return insert >= 0 && insert < (int) song.mixer.size() && ! song.mixer[(std::size_t) insert].effects.empty();
  977. }
  978. int nextFreeRow() const
  979. {
  980. const auto& song = engine.getSong();
  981. if (insert < 0 || insert >= (int) song.mixer.size())
  982. return 0;
  983. const auto& fx = song.mixer[(std::size_t) insert].effects;
  984. const auto rows = mixerops::effectRows (fx);
  985. for (int r = rows.empty() ? 0 : rows.back() + 1; r < maxEffectSlots; ++r)
  986. if (mixerops::effectAtRow (fx, r) < 0)
  987. return r;
  988. for (int r = 0; r < maxEffectSlots; ++r)
  989. if (mixerops::effectAtRow (fx, r) < 0)
  990. return r;
  991. return 0;
  992. }
  993. EffectsPanel slotActions;
  994. juce::Label presetCaption, blendCaption, reverbCaption, echoCaption, duckCaption, emptyHint;
  995. juce::TextButton presetButton, saveButton, duckButton;
  996. ChevronButton previousPreset { false }, nextPreset { true };
  997. ChainBypassButton bypassButton;
  998. AddCardButton addCard;
  999. DockKnob blend, reverb, echo;
  1000. juce::Viewport view;
  1001. Strip strip { *this };
  1002. std::vector<std::unique_ptr<Card>> cards;
  1003. int dragging = -1, dropAt = -1;
  1004. };
  1005. // =====================================================================================================================
  1006. // Instrument
  1007. // =====================================================================================================================
  1008. class SimpleDock::InstrumentPage final : public juce::Component,
  1009. private juce::Timer
  1010. {
  1011. public:
  1012. InstrumentPage (AudioEngine& e, Hooks& h) : engine (e), hooks (h), categoryModel (*this), soundModel (*this)
  1013. {
  1014. styleCaption (soundCaption, tr ("Sound"));
  1015. addAndMakeVisible (soundCaption);
  1016. prev.setTooltip (tr ("Previous sound"));
  1017. prev.onClick = [this] { stepSound (-1); };
  1018. next.setTooltip (tr ("Next sound"));
  1019. next.onClick = [this] { stepSound (1); };
  1020. addAndMakeVisible (prev);
  1021. addAndMakeVisible (next);
  1022. name.setFont (font (type::title, true));
  1023. name.setColour (juce::Label::textColourId, colour::textPrimary);
  1024. name.setJustificationType (juce::Justification::centred);
  1025. name.setMinimumHorizontalScale (0.7f);
  1026. addAndMakeVisible (name);
  1027. styleCaption (detail, {});
  1028. detail.setJustificationType (juce::Justification::centred);
  1029. addAndMakeVisible (detail);
  1030. editorButton.setButtonText (tr ("Open full editor"));
  1031. editorButton.setTooltip (tr ("Opens the instrument's own window with every control"));
  1032. editorButton.onClick = [this] {
  1033. if (channel >= 0 && hooks.toggleChannelWindow)
  1034. hooks.toggleChannelWindow (channel);
  1035. };
  1036. addAndMakeVisible (editorButton);
  1037. keysButton.setButtonText (tr ("Keyboard"));
  1038. keysButton.setTooltip (tr ("Shows the on-screen keyboard to play this track"));
  1039. keysButton.onClick = [this] {
  1040. if (hooks.showKeys)
  1041. hooks.showKeys();
  1042. };
  1043. addAndMakeVisible (keysButton);
  1044. search.setTextToShowWhenEmpty (tr ("Search sounds"), colour::textDisabled);
  1045. search.onTextChange = [this] { refilter(); };
  1046. search.setTitle (tr ("Search sounds"));
  1047. addAndMakeVisible (search);
  1048. ownButton.setButtonText (tr ("LYNX sounds"));
  1049. fontsButton.setButtonText (tr ("My SoundFonts"));
  1050. fontsButton.setTooltip (tr ("The sounds of your own .sf2 and .sf3 files"));
  1051. pluginsButton.setButtonText (tr ("My plugins"));
  1052. pluginsButton.setTooltip (tr ("The instrument plugins installed on this computer"));
  1053. for (auto* b : { &ownButton, &fontsButton, &pluginsButton })
  1054. {
  1055. b->setClickingTogglesState (true);
  1056. b->setRadioGroupId (1902);
  1057. addAndMakeVisible (*b);
  1058. }
  1059. ownButton.setConnectedEdges (juce::Button::ConnectedOnRight);
  1060. fontsButton.setConnectedEdges (juce::Button::ConnectedOnLeft | juce::Button::ConnectedOnRight);
  1061. pluginsButton.setConnectedEdges (juce::Button::ConnectedOnLeft);
  1062. ownButton.setToggleState (true, juce::dontSendNotification);
  1063. ownButton.onClick = [this] {
  1064. if (ownButton.getToggleState())
  1065. setSource (From::own);
  1066. };
  1067. fontsButton.onClick = [this] {
  1068. if (fontsButton.getToggleState())
  1069. setSource (From::fonts);
  1070. };
  1071. pluginsButton.onClick = [this] {
  1072. if (pluginsButton.getToggleState())
  1073. setSource (From::plugins);
  1074. };
  1075. folderButton.setButtonText (tr ("Add folder..."));
  1076. folderButton.setTooltip (tr ("Adds a folder with your SoundFont files to the list"));
  1077. folderButton.onClick = [this] { addFolder(); };
  1078. addChildComponent (folderButton);
  1079. categories.setModel (&categoryModel);
  1080. categories.setRowHeight (rowHeight);
  1081. categories.setColour (juce::ListBox::backgroundColourId, colour::bg1);
  1082. categories.setTitle (tr ("Category"));
  1083. addAndMakeVisible (categories);
  1084. sounds.setModel (&soundModel);
  1085. sounds.setRowHeight (rowHeight);
  1086. sounds.setColour (juce::ListBox::backgroundColourId, colour::bg1);
  1087. sounds.setTitle (tr ("Sounds"));
  1088. addAndMakeVisible (sounds);
  1089. styleCaption (listHint, {});
  1090. listHint.setFont (font (type::body));
  1091. listHint.setJustificationType (juce::Justification::centred);
  1092. addChildComponent (listHint);
  1093. }
  1094. ~InstrumentPage() override { stopTimer(); }
  1095. void show (int newChannel)
  1096. {
  1097. channel = newChannel;
  1098. refresh();
  1099. }
  1100. void refresh()
  1101. {
  1102. if (! isVisible()) // (the Effects tab is in front: nothing of the list is worked out until it shows)
  1103. {
  1104. stale = true;
  1105. return;
  1106. }
  1107. stale = false;
  1108. const auto& song = engine.getSong();
  1109. const bool has = channel >= 0 && channel < (int) song.channels.size();
  1110. prev.setEnabled (has);
  1111. next.setEnabled (has);
  1112. editorButton.setEnabled (has);
  1113. if (! has)
  1114. {
  1115. name.setText ({}, juce::dontSendNotification);
  1116. detail.setText ({}, juce::dontSendNotification);
  1117. current = -1;
  1118. sounds.repaint();
  1119. return;
  1120. }
  1121. const auto& def = song.channels[(std::size_t) channel];
  1122. // which sound of the list the channel plays (looked up again only when its instrument changed)
  1123. if (! known || ! soundlib::sameSound (lastDef, def) || lastListSize != list().size())
  1124. {
  1125. current = soundlib::find (list(), def);
  1126. currentOwn = from != From::own ? soundlib::find (soundlib::builtIn(), def) : current;
  1127. lastDef = def;
  1128. lastListSize = list().size();
  1129. known = true;
  1130. }
  1131. const soundlib::Sound* sound = current >= 0 ? &list()[(std::size_t) current]
  1132. : currentOwn >= 0 ? &soundlib::builtIn()[(std::size_t) currentOwn] : nullptr;
  1133. if (sound != nullptr)
  1134. {
  1135. name.setText (utf8 (sound->name), juce::dontSendNotification);
  1136. detail.setText (soundCategoryText (sound->category) + glyph (" \xc2\xb7 ") + utf8 (sound->origin), juce::dontSendNotification);
  1137. }
  1138. else
  1139. {
  1140. name.setText (utf8 (def.name), juce::dontSendNotification);
  1141. detail.setText (tr ("Its own sound"), juce::dontSendNotification);
  1142. }
  1143. if (current >= 0 && ! categoryPicked)
  1144. category = (int) list()[(std::size_t) current].category;
  1145. else if (! categoryPicked && soundlib::filter (list(), (soundlib::Category) category).empty())
  1146. for (int c = 0; c < (int) soundlib::Category::count; ++c) // (the first category this list has sounds in)
  1147. if (! soundlib::filter (list(), (soundlib::Category) c).empty())
  1148. {
  1149. category = c;
  1150. break;
  1151. }
  1152. refilter();
  1153. }
  1154. void resized() override
  1155. {
  1156. auto r = getLocalBounds().reduced (pad);
  1157. auto side = r.removeFromLeft (sideWidth - pad);
  1158. soundCaption.setBounds (side.removeFromTop (16));
  1159. // round 190jc (SG-9, BandLab's "‹ Studio Grand ›" field): a 32 px field with the chevrons in 28 px ends
  1160. auto row = side.removeFromTop (32);
  1161. pickerField = row;
  1162. prev.setBounds (row.removeFromLeft (28));
  1163. next.setBounds (row.removeFromRight (28));
  1164. name.setBounds (row);
  1165. detail.setBounds (side.removeFromTop (18));
  1166. side.removeFromTop (8);
  1167. editorButton.setBounds (side.removeFromTop (26));
  1168. side.removeFromTop (6);
  1169. keysButton.setBounds (side.removeFromTop (26));
  1170. r.removeFromLeft (pad + 1 + pad);
  1171. auto top = r.removeFromTop (26);
  1172. ownButton.setBounds (top.removeFromLeft (juce::jmin (120, top.getWidth() / 5)));
  1173. fontsButton.setBounds (top.removeFromLeft (juce::jmin (130, top.getWidth() / 4)));
  1174. pluginsButton.setBounds (top.removeFromLeft (juce::jmin (110, top.getWidth() / 3)));
  1175. top.removeFromLeft (pad);
  1176. if (folderButton.isVisible())
  1177. {
  1178. folderButton.setBounds (top.removeFromRight (juce::jmin (130, top.getWidth() / 3)));
  1179. top.removeFromRight (pad);
  1180. }
  1181. search.setBounds (top.withWidth (juce::jmin (top.getWidth(), 280)));
  1182. r.removeFromTop (6);
  1183. categories.setBounds (r.removeFromLeft (juce::jmin (categoryWidth, r.getWidth() / 3)));
  1184. r.removeFromLeft (6);
  1185. sounds.setBounds (r);
  1186. listHint.setBounds (r.reduced (12));
  1187. }
  1188. void paint (juce::Graphics& g) override
  1189. {
  1190. g.setColour (colour::border);
  1191. g.fillRect (sideWidth, pad, 1, getHeight() - 2 * pad);
  1192. g.setColour (colour::bg4);
  1193. g.fillRoundedRectangle (pickerField.toFloat(), radius::lg);
  1194. }
  1195. juce::Rectangle<int> pickerField;
  1196. void visibilityChanged() override
  1197. {
  1198. if (isVisible() && stale)
  1199. refresh();
  1200. updateTimer();
  1201. }
  1202. void parentHierarchyChanged() override { updateTimer(); }
  1203. // --- the list ----------------------------------------------------------------------------------------------------
  1204. enum class From { own, fonts, plugins };
  1205. const std::vector<soundlib::Sound>& list() const
  1206. {
  1207. return from == From::fonts ? fontSounds : from == From::plugins ? pluginSounds : soundlib::builtIn();
  1208. }
  1209. void setSource (From source)
  1210. {
  1211. from = source;
  1212. fonts = from == From::fonts;
  1213. (from == From::fonts ? fontsButton : from == From::plugins ? pluginsButton : ownButton).setToggleState (true, juce::dontSendNotification);
  1214. folderButton.setVisible (fonts);
  1215. if (fonts && ! injected)
  1216. {
  1217. ensureSoundFontIndex();
  1218. takeFonts();
  1219. }
  1220. if (from == From::plugins && ! pluginsInjected)
  1221. takePlugins();
  1222. known = false;
  1223. categoryPicked = false;
  1224. resized();
  1225. refresh();
  1226. updateTimer();
  1227. }
  1228. void setFonts (std::vector<sf::IndexedFont> indexed, bool inject)
  1229. {
  1230. injected = inject;
  1231. fontSounds = soundlib::fromFonts (indexed);
  1232. known = false;
  1233. }
  1234. void pickCategory (int c)
  1235. {
  1236. category = juce::jlimit (0, (int) soundlib::Category::count - 1, c);
  1237. categoryPicked = true;
  1238. refilter();
  1239. }
  1240. void refilter()
  1241. {
  1242. rows = soundlib::filter (list(), (soundlib::Category) category, search.getText().toStdString());
  1243. counts.assign ((std::size_t) soundlib::Category::count, 0);
  1244. for (int c = 0; c < (int) soundlib::Category::count; ++c)
  1245. counts[(std::size_t) c] = (int) soundlib::filter (list(), (soundlib::Category) c, search.getText().toStdString()).size();
  1246. // the categories this source has sounds in (a search greys the ones without a match, it doesn't remove them)
  1247. shownCategories.clear();
  1248. for (int c = 0; c < (int) soundlib::Category::count; ++c)
  1249. if (! soundlib::filter (list(), (soundlib::Category) c).empty())
  1250. shownCategories.push_back (c);
  1251. categories.updateContent();
  1252. const auto shown = std::find (shownCategories.begin(), shownCategories.end(), category);
  1253. if (shown != shownCategories.end())
  1254. categories.selectRow ((int) (shown - shownCategories.begin()), true, true);
  1255. else
  1256. categories.deselectAllRows();
  1257. categories.repaint();
  1258. sounds.updateContent();
  1259. const auto it = std::find (rows.begin(), rows.end(), current);
  1260. if (it != rows.end())
  1261. sounds.selectRow ((int) (it - rows.begin()), true, true);
  1262. else
  1263. sounds.deselectAllRows();
  1264. sounds.repaint();
  1265. const bool noFonts = fonts && fontSounds.empty();
  1266. const bool noPlugins = from == From::plugins && pluginSounds.empty();
  1267. listHint.setVisible (noFonts || noPlugins || rows.empty());
  1268. listHint.setText (noFonts ? (sf::PresetIndex::shared().busy() && ! injected
  1269. ? tr ("Looking for your SoundFont files...")
  1270. : tr ("No SoundFont files found yet. Add a folder with your .sf2 or .sf3 files."))
  1271. : noPlugins ? tr ("No instrument plugins found yet. Scan for plugins in the Plugin manager.")
  1272. : rows.empty() ? tr ("No sounds here.") : juce::String(),
  1273. juce::dontSendNotification);
  1274. }
  1275. // --- picking and hearing -----------------------------------------------------------------------------------------
  1276. bool audition (const soundlib::Sound& s)
  1277. {
  1278. const auto def = soundlib::channelFor (s);
  1279. return def && engine.auditionSound (*def, soundlib::auditionKeys (s));
  1280. }
  1281. void pick (int listIndex, bool hear)
  1282. {
  1283. if (listIndex < 0 || listIndex >= (int) list().size() || channel < 0)
  1284. return;
  1285. const auto sound = list()[(std::size_t) listIndex];
  1286. const auto c = channel;
  1287. bool done = false;
  1288. engine.editSongStructural ([c, &sound, &done] (Song& s) {
  1289. if (c >= (int) s.channels.size())
  1290. return;
  1291. if (auto next = soundlib::withSound (s.channels[(std::size_t) c], sound))
  1292. {
  1293. s.channels[(std::size_t) c] = std::move (*next);
  1294. done = true;
  1295. }
  1296. });
  1297. if (done && hear)
  1298. {
  1299. if (sound.source == soundlib::Source::plugin) // (heard on the track itself, as it loaded)
  1300. engine.auditionChannelSound (c);
  1301. else
  1302. audition (sound);
  1303. }
  1304. }
  1305. void stepSound (int delta)
  1306. {
  1307. const auto fallback = (soundlib::Category) category;
  1308. const auto to = soundlib::step (list(), current, delta, fallback);
  1309. if (to >= 0)
  1310. {
  1311. categoryPicked = false;
  1312. pick (to, true);
  1313. }
  1314. }
  1315. void clickRow (int row, bool previewOnly)
  1316. {
  1317. if (row < 0 || row >= (int) rows.size())
  1318. return;
  1319. // (a plugin can only be heard once it runs on the track: its ▶ uses it too, and Ctrl+Z goes back)
  1320. if (previewOnly && list()[(std::size_t) rows[(std::size_t) row]].source != soundlib::Source::plugin)
  1321. audition (list()[(std::size_t) rows[(std::size_t) row]]);
  1322. else
  1323. pick (rows[(std::size_t) row], true);
  1324. }
  1325. int rowCount() const noexcept { return (int) rows.size(); }
  1326. void searchFor (const juce::String& text)
  1327. {
  1328. search.setText (text, false);
  1329. refilter(); // (what typing does, at once: the editor's own change message is posted)
  1330. }
  1331. juce::String shownName() const { return name.getText() + " [" + detail.getText() + "]"; }
  1332. AudioEngine& engine;
  1333. Hooks& hooks;
  1334. int channel = -1;
  1335. private:
  1336. struct CategoryModel final : juce::ListBoxModel
  1337. {
  1338. explicit CategoryModel (InstrumentPage& p) : page (p) {}
  1339. int getNumRows() override { return (int) page.shownCategories.size(); }
  1340. void paintListBoxItem (int index, juce::Graphics& g, int width, int height, bool selected) override
  1341. {
  1342. if (index < 0 || index >= (int) page.shownCategories.size())
  1343. return;
  1344. const auto row = page.shownCategories[(std::size_t) index];
  1345. const auto n = row < (int) page.counts.size() ? page.counts[(std::size_t) row] : 0;
  1346. if (selected)
  1347. fillRoundRect (g, juce::Rectangle<float> (0.0f, 1.0f, (float) width, (float) height - 2.0f), radius::sm, colour::accentMuted);
  1348. g.setColour (n == 0 ? colour::textDisabled : selected ? colour::textPrimary : colour::textSecondary);
  1349. g.setFont (font (type::body, selected));
  1350. g.drawText (soundCategoryText ((soundlib::Category) row), 10, 0, width - 50, height, juce::Justification::centredLeft, true);
  1351. // (round 190oo, CS-31: the counts were textDisabled, 2.95:1 on the list; #8f939b reads >= 4.5:1, the selected row's
  1352. // textSecondary on accentMuted too; an empty category's 0 stays disabled with its name)
  1353. g.setColour (n == 0 ? colour::textDisabled : selected ? colour::textSecondary : juce::Colour (0xff8f939b));
  1354. g.setFont (font (type::caption));
  1355. g.drawText (juce::String (n), width - 40, 0, 32, height, juce::Justification::centredRight, false);
  1356. }
  1357. void selectedRowsChanged (int index) override
  1358. {
  1359. if (index >= 0 && index < (int) page.shownCategories.size() && page.shownCategories[(std::size_t) index] != page.category)
  1360. page.pickCategory (page.shownCategories[(std::size_t) index]);
  1361. }
  1362. juce::String getNameForRow (int index) override
  1363. {
  1364. return index >= 0 && index < (int) page.shownCategories.size() ? soundCategoryText ((soundlib::Category) page.shownCategories[(std::size_t) index])
  1365. : juce::String();
  1366. }
  1367. InstrumentPage& page;
  1368. };
  1369. struct SoundModel final : juce::ListBoxModel
  1370. {
  1371. explicit SoundModel (InstrumentPage& p) : page (p) {}
  1372. int getNumRows() override { return (int) page.rows.size(); }
  1373. void paintListBoxItem (int row, juce::Graphics& g, int width, int height, bool) override
  1374. {
  1375. if (row < 0 || row >= (int) page.rows.size())
  1376. return;
  1377. const auto index = page.rows[(std::size_t) row];
  1378. const auto& s = page.list()[(std::size_t) index];
  1379. const bool isCurrent = index == page.current;
  1380. if (isCurrent)
  1381. fillRoundRect (g, juce::Rectangle<float> (0.0f, 1.0f, (float) width, (float) height - 2.0f), radius::sm, colour::accentMuted);
  1382. else if (row % 2 == 1)
  1383. g.fillAll (colour::bg2.withAlpha (0.5f));
  1384. // ▶: hear it without choosing it
  1385. juce::Path play;
  1386. const auto cx = 15.0f, cy = (float) height * 0.5f;
  1387. play.addTriangle (cx - 4.0f, cy - 5.5f, cx - 4.0f, cy + 5.5f, cx + 5.5f, cy);
  1388. g.setColour (isCurrent ? colour::accent : colour::textSecondary);
  1389. g.fillPath (play);
  1390. g.setColour (isCurrent ? colour::textPrimary : colour::textPrimary.withAlpha (0.9f));
  1391. g.setFont (font (type::body, isCurrent));
  1392. const auto originWidth = juce::jmin (180, width / 3);
  1393. g.drawText (utf8 (s.name), 32, 0, width - 40 - originWidth, height, juce::Justification::centredLeft, true);
  1394. g.setColour (colour::textSecondary);
  1395. g.setFont (font (type::small));
  1396. g.drawText (utf8 (s.origin), width - originWidth - 8, 0, originWidth, height, juce::Justification::centredRight, true);
  1397. }
  1398. void listBoxItemClicked (int row, const juce::MouseEvent& e) override { page.clickRow (row, e.x < 30); }
  1399. void returnKeyPressed (int row) override { page.clickRow (row, false); }
  1400. juce::String getNameForRow (int row) override
  1401. {
  1402. return row >= 0 && row < (int) page.rows.size() ? utf8 (page.list()[(std::size_t) page.rows[(std::size_t) row]].name) : juce::String();
  1403. }
  1404. juce::String getTooltipForRow (int) override
  1405. {
  1406. return page.from == From::plugins ? tr ("Click to load this plugin on the track and hear it (Ctrl+Z goes back)")
  1407. : tr ("Click to use this sound; the arrow plays it without choosing it");
  1408. }
  1409. InstrumentPage& page;
  1410. };
  1411. // the plugin host's scanned instruments (the list the plugin picker shows)
  1412. void takePlugins()
  1413. {
  1414. std::vector<soundlib::InstalledPlugin> installed;
  1415. for (const auto& t : engine.getPluginHost().getKnownPlugins().getTypes())
  1416. if (t.isInstrument)
  1417. installed.push_back ({ t.createIdentifierString().toStdString(), t.name.toStdString(), t.manufacturerName.toStdString(),
  1418. t.pluginFormatName.toStdString(), t.category.toStdString() });
  1419. pluginSounds = soundlib::fromPlugins (installed);
  1420. known = false;
  1421. }
  1422. public:
  1423. void setPlugins (std::vector<soundlib::InstalledPlugin> installed)
  1424. {
  1425. pluginsInjected = true;
  1426. pluginSounds = soundlib::fromPlugins (installed);
  1427. known = false;
  1428. }
  1429. private:
  1430. void takeFonts()
  1431. {
  1432. auto& index = sf::PresetIndex::shared();
  1433. generation = index.generation();
  1434. fontSounds = soundlib::fromFonts (index.fonts());
  1435. known = false;
  1436. }
  1437. // the SoundFont index fills in the background: follow it only while its list is on screen
  1438. void updateTimer()
  1439. {
  1440. if (fonts && ! injected && isShowing())
  1441. startTimer (500);
  1442. else
  1443. stopTimer();
  1444. }
  1445. void timerCallback() override
  1446. {
  1447. if (sf::PresetIndex::shared().generation() != generation)
  1448. {
  1449. takeFonts();
  1450. refresh();
  1451. }
  1452. }
  1453. void addFolder()
  1454. {
  1455. chooser = lynx::ui::makeFileChooser (tr ("Add a SoundFont folder"), juce::File::getSpecialLocation (juce::File::userDocumentsDirectory));
  1456. juce::Component::SafePointer<InstrumentPage> safe (this);
  1457. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories,
  1458. [safe] (const juce::FileChooser& fc) {
  1459. if (fc.getResult() == juce::File())
  1460. return;
  1461. // (the same list the LYNX Soundfont editor's "SoundFont folders" menu keeps)
  1462. auto lines = juce::StringArray::fromLines (soundFontFoldersFile().loadFileAsString());
  1463. lines.removeEmptyStrings();
  1464. lines.addIfNotAlreadyThere (fc.getResult().getFullPathName());
  1465. soundFontFoldersFile().getParentDirectory().createDirectory();
  1466. soundFontFoldersFile().replaceWithText (lines.joinIntoString ("\n") + "\n");
  1467. ensureSoundFontIndex (true);
  1468. if (safe != nullptr)
  1469. safe->refilter();
  1470. });
  1471. }
  1472. juce::Label soundCaption, name, detail, listHint;
  1473. GlyphButton prev { glyph ("\xe2\x80\xb9"), ui::simplelook::Glyph::chevronLeft, { 6.0f, 10.0f }, false },
  1474. next { glyph ("\xe2\x80\xba"), ui::simplelook::Glyph::chevronRight, { 6.0f, 10.0f }, false };
  1475. juce::TextButton editorButton, keysButton, ownButton, fontsButton, pluginsButton, folderButton;
  1476. juce::TextEditor search;
  1477. CategoryModel categoryModel;
  1478. SoundModel soundModel;
  1479. juce::ListBox categories, sounds;
  1480. std::unique_ptr<juce::FileChooser> chooser;
  1481. std::vector<soundlib::Sound> fontSounds, pluginSounds;
  1482. std::vector<int> rows, counts, shownCategories;
  1483. ChannelDef lastDef;
  1484. std::size_t lastListSize = 0;
  1485. int category = 0, current = -1, currentOwn = -1, generation = -1;
  1486. bool fonts = false, injected = false, pluginsInjected = false, known = false, categoryPicked = false, stale = true;
  1487. From from = From::own;
  1488. };
  1489. // =====================================================================================================================
  1490. // The dock
  1491. // =====================================================================================================================
  1492. // --- Editor: the Piano roll docked on the track's pattern (round 190ds) ---------------------------------------------
  1493. class SimpleDock::EditorPage final : public juce::Component
  1494. {
  1495. public:
  1496. EditorPage (AudioEngine& e, Hooks& h) : engine (e), hooks (h)
  1497. {
  1498. fold.setButtonText (tr ("Only notes in key"));
  1499. fold.setTooltip (tr ("Shows only the rows of the project key's notes"));
  1500. fold.onClick = [this] {
  1501. if (hooks.setFoldToKey)
  1502. hooks.setFoldToKey (fold.getToggleState());
  1503. };
  1504. open.setButtonText (tr ("Open in the Piano roll"));
  1505. open.setTooltip (tr ("The full Piano roll window, with every tool"));
  1506. open.onClick = [this] {
  1507. if (hooks.openPianoRollPanel)
  1508. hooks.openPianoRollPanel();
  1509. };
  1510. again.setButtonText (tr ("Show the editor here"));
  1511. again.onClick = [this] {
  1512. takenBack = false;
  1513. update();
  1514. };
  1515. makePattern.setButtonText (tr ("New pattern"));
  1516. makePattern.setTooltip (tr ("An empty 4-bar pattern on this track, to write notes into"));
  1517. makePattern.onClick = [this] { make(); };
  1518. // round 190mc (discussion #105): the Chord helper of the docked editor, in the Simple look
  1519. chordHelper.setButtonText (tr ("Chord helper"));
  1520. chordHelper.setTooltip (tr ("Select a chord: related keys and borrowed chords to insert after it"));
  1521. chordHelper.onClick = [this] {
  1522. if (auto* roll = dynamic_cast<PianoRollComponent*> (editor))
  1523. roll->openChordHelper();
  1524. };
  1525. addAndMakeVisible (chordHelper);
  1526. addAndMakeVisible (fold);
  1527. addAndMakeVisible (open);
  1528. addChildComponent (again);
  1529. addChildComponent (makePattern);
  1530. }
  1531. ~EditorPage() override { release(); }
  1532. void show (int newTrack, int newChannel)
  1533. {
  1534. if (newTrack != track)
  1535. takenBack = false;
  1536. track = newTrack;
  1537. channel = newChannel;
  1538. update();
  1539. }
  1540. // Docks the Piano roll on the track's pattern while this page shows. A track without a pattern gets one the first
  1541. // time (after this call returns: no song edit inside the dock's own refresh); after an undo removed it, a button.
  1542. void update()
  1543. {
  1544. const auto& song = engine.getSong();
  1545. const auto pattern = track >= 0 ? simpletracks::editorPattern (song, track) : -1;
  1546. const auto canHave = track >= 0 && (simpletracks::kindOf (song, track) == simpletracks::Kind::instrument
  1547. || simpletracks::kindOf (song, track) == simpletracks::Kind::sampler);
  1548. if (! shownInTree() || ! canHave)
  1549. {
  1550. release();
  1551. refreshControls (pattern);
  1552. return;
  1553. }
  1554. if (pattern < 0)
  1555. {
  1556. release();
  1557. if (made.count (song.playlistTracks[(std::size_t) track].channel) == 0 && ! pendingMake)
  1558. {
  1559. pendingMake = true;
  1560. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<EditorPage> (this)] {
  1561. if (safe != nullptr)
  1562. {
  1563. safe->pendingMake = false;
  1564. if (safe->shownInTree())
  1565. safe->make();
  1566. }
  1567. });
  1568. }
  1569. refreshControls (pattern);
  1570. return;
  1571. }
  1572. if (channel >= 0 && engine.getSelectedChannel() != channel)
  1573. engine.setSelectedChannel (channel); // (the Piano roll shows the selected channel's notes)
  1574. if (! takenBack && (editor == nullptr || dockedPattern != pattern || song.currentPattern != pattern) && hooks.dockPianoRoll)
  1575. {
  1576. if (auto* e = hooks.dockPianoRoll (pattern))
  1577. {
  1578. editor = e;
  1579. dockedPattern = pattern;
  1580. addAndMakeVisible (*editor);
  1581. resized();
  1582. }
  1583. }
  1584. refreshControls (pattern);
  1585. }
  1586. void release()
  1587. {
  1588. if (editor != nullptr && hooks.undockPianoRoll)
  1589. {
  1590. editor = nullptr;
  1591. hooks.undockPianoRoll();
  1592. }
  1593. editor = nullptr;
  1594. dockedPattern = -1;
  1595. }
  1596. void takenBackByPanel()
  1597. {
  1598. if (editor != nullptr)
  1599. {
  1600. editor = nullptr;
  1601. dockedPattern = -1;
  1602. takenBack = true;
  1603. }
  1604. refreshControls (dockedPattern);
  1605. }
  1606. bool docked() const noexcept { return editor != nullptr; }
  1607. void clickFold (bool on)
  1608. {
  1609. fold.setToggleState (on, juce::dontSendNotification);
  1610. if (fold.onClick)
  1611. fold.onClick();
  1612. }
  1613. void visibilityChanged() override { update(); }
  1614. void parentHierarchyChanged() override
  1615. {
  1616. if (! shownInTree())
  1617. release();
  1618. }
  1619. // visible with all its parents (isShowing() also asks for a window on the desktop, which --snapshot has not)
  1620. bool shownInTree() const
  1621. {
  1622. for (auto* c = static_cast<const juce::Component*> (this); c != nullptr; c = c->getParentComponent())
  1623. if (! c->isVisible())
  1624. return false;
  1625. return getParentComponent() != nullptr;
  1626. }
  1627. void resized() override
  1628. {
  1629. auto bar = getLocalBounds().removeFromTop (barHeight).reduced (10, 4);
  1630. open.setBounds (bar.removeFromRight (170));
  1631. bar.removeFromRight (8);
  1632. fold.setBounds (bar.removeFromRight (160));
  1633. bar.removeFromRight (8);
  1634. chordHelper.setBounds (bar.removeFromRight (120));
  1635. const auto body = getLocalBounds().withTrimmedTop (barHeight);
  1636. again.setBounds (body.withSizeKeepingCentre (220, 30));
  1637. makePattern.setBounds (body.withSizeKeepingCentre (160, 30));
  1638. if (editor != nullptr)
  1639. editor->setBounds (body);
  1640. }
  1641. void paint (juce::Graphics& g) override
  1642. {
  1643. g.fillAll (colour::bg1);
  1644. const auto& song = engine.getSong();
  1645. auto bar = getLocalBounds().removeFromTop (barHeight).reduced (12, 0);
  1646. const auto pattern = track >= 0 ? simpletracks::editorPattern (song, track) : -1;
  1647. g.setColour (colour::textSecondary);
  1648. g.setFont (font (type::small));
  1649. if (pattern >= 0)
  1650. g.drawText (tr ("Notes of {0}", { utf8 (song.patterns[(std::size_t) pattern].name) }), bar, juce::Justification::centredLeft, true);
  1651. if (editor == nullptr)
  1652. {
  1653. g.setFont (font (type::body));
  1654. const auto body = getLocalBounds().withTrimmedTop (barHeight).withTrimmedBottom (80);
  1655. g.drawText (takenBack ? tr ("The Piano roll is open in its own window") : pattern < 0 ? tr ("This track has no pattern yet") : juce::String(),
  1656. body, juce::Justification::centred, true);
  1657. }
  1658. }
  1659. static constexpr int barHeight = 30;
  1660. private:
  1661. void make()
  1662. {
  1663. if (track < 0)
  1664. return;
  1665. const auto t = track;
  1666. int ch = -1;
  1667. if (t < (int) engine.getSong().playlistTracks.size())
  1668. ch = engine.getSong().playlistTracks[(std::size_t) t].channel;
  1669. made.insert (ch);
  1670. engine.editSong ([t] (Song& s) { simpletracks::ensurePattern (s, t, 4); });
  1671. update();
  1672. }
  1673. void refreshControls (int pattern)
  1674. {
  1675. const auto& song = engine.getSong();
  1676. fold.setEnabled (projectkey::get (song).has_value() && editor != nullptr);
  1677. chordHelper.setEnabled (editor != nullptr);
  1678. fold.setToggleState (hooks.foldedToKey && hooks.foldedToKey(), juce::dontSendNotification);
  1679. again.setVisible (takenBack && editor == nullptr);
  1680. makePattern.setVisible (! takenBack && editor == nullptr && pattern < 0 && track >= 0 && ! pendingMake);
  1681. repaint();
  1682. }
  1683. AudioEngine& engine;
  1684. Hooks& hooks;
  1685. juce::ToggleButton fold;
  1686. juce::TextButton open, again, makePattern, chordHelper;
  1687. juce::Component* editor = nullptr; // the main window's Piano roll while docked here (not owned)
  1688. int track = -1, channel = -1, dockedPattern = -1;
  1689. bool takenBack = false, pendingMake = false;
  1690. std::set<int> made; // channels whose pattern this page made once (an undo then asks, it doesn't make it again)
  1691. };
  1692. // =====================================================================================================================
  1693. // Pads (round 190fo): the Sampler track's 16 pads (core/SimplePads.h)
  1694. // =====================================================================================================================
  1695. namespace
  1696. {
  1697. // LYNX's own pad colours (index 1…8; 0 = the track's colour)
  1698. juce::Colour padColour (int index, juce::Colour track)
  1699. {
  1700. static const juce::uint32 palette[simplepads::colourCount] { 0xffe5383b, 0xffe8833a, 0xffe2c044, 0xff5fbf6a,
  1701. 0xff3fb6b0, 0xff4f8ee0, 0xff9a6fe0, 0xffe06aa8 };
  1702. return index >= 1 && index <= simplepads::colourCount ? juce::Colour (palette[index - 1]) : track;
  1703. }
  1704. juce::String padColourName (int index)
  1705. {
  1706. switch (index)
  1707. {
  1708. case 1: return trc ("@colour: Red");
  1709. case 2: return trc ("@colour: Orange");
  1710. case 3: return trc ("@colour: Yellow");
  1711. case 4: return trc ("@colour: Green");
  1712. case 5: return trc ("@colour: Teal");
  1713. case 6: return trc ("@colour: Blue");
  1714. case 7: return trc ("@colour: Violet");
  1715. case 8: return trc ("@colour: Pink");
  1716. default: break;
  1717. }
  1718. return tr ("Track colour");
  1719. }
  1720. // the pad knobs' names
  1721. juce::String padKnobName (int k)
  1722. {
  1723. switch (k)
  1724. {
  1725. case 0: return tr ("Attack");
  1726. case 1: return tr ("Release");
  1727. case 2: return tr ("Tone");
  1728. case 3: return tr ("Pitch");
  1729. case 4: return trc ("@mixer: Pan");
  1730. default: break;
  1731. }
  1732. return trc ("@mixer: Volume");
  1733. }
  1734. juce::String modeText (simplepads::Mode m)
  1735. {
  1736. return m == simplepads::Mode::gate ? trc ("@pad mode: Gate") : m == simplepads::Mode::oneShot ? tr ("One-shot") : trc ("@pad mode: Loop");
  1737. }
  1738. juce::String toneLabel (float tone)
  1739. {
  1740. const auto t = simplepads::toneFilter (tone);
  1741. if (! t.on)
  1742. return tr ("Off");
  1743. const auto hz = t.cutoff >= 1000.0f ? juce::String (t.cutoff / 1000.0f, 1) + " kHz" : juce::String (juce::roundToInt (t.cutoff)) + " Hz";
  1744. return (t.filterType == 0 ? tr ("Low-pass") : tr ("High-pass")) + " " + hz;
  1745. }
  1746. // the knobs' laws: the dock's knob is 0…1
  1747. float attackFrom (float v) { return v * v * simplepads::maxAttack; }
  1748. float attackTo (float s) { return std::sqrt (juce::jlimit (0.0f, 1.0f, s / simplepads::maxAttack)); }
  1749. float releaseFrom (float v) { return v * v * simplepads::maxRelease; }
  1750. float releaseTo (float s) { return std::sqrt (juce::jlimit (0.0f, 1.0f, s / simplepads::maxRelease)); }
  1751. juce::String secondsText (float s) { return s < 1.0f ? juce::String (juce::roundToInt (s * 1000.0f)) + " ms" : juce::String (s, 2) + " s"; }
  1752. juce::String panText (float pan)
  1753. {
  1754. const auto p = juce::roundToInt (pan * 100.0f);
  1755. return p == 0 ? tr ("Centre") : p < 0 ? "L " + juce::String (-p) : "R " + juce::String (p);
  1756. }
  1757. juce::String pitchText (float semis)
  1758. {
  1759. const auto cents = juce::roundToInt (semis * 100.0f);
  1760. if (cents % 100 == 0)
  1761. return (cents > 0 ? "+" : "") + juce::String (cents / 100) + " st";
  1762. return (semis > 0.0f ? "+" : "") + juce::String (semis, 2) + " st";
  1763. }
  1764. } // namespace
  1765. class SimpleDock::PadsPage final : public juce::Component,
  1766. public juce::FileDragAndDropTarget,
  1767. public juce::DragAndDropTarget,
  1768. private juce::Timer
  1769. {
  1770. public:
  1771. explicit PadsPage (AudioEngine& e) : engine (e)
  1772. {
  1773. load.setButtonText (tr ("Import..."));
  1774. load.setTooltip (tr ("Put an audio file on the selected pad"));
  1775. load.onClick = [this] { chooseFile (selected); };
  1776. browse.setButtonText (tr ("Browse sounds"));
  1777. browse.setTooltip (tr ("The sample browser: drag a sound onto a pad"));
  1778. browse.onClick = [this] {
  1779. if (onBrowse)
  1780. onBrowse();
  1781. };
  1782. // round 190mr (DS-36, BandLab's empty sampler, bandlab190p 21-sampler-empty.png + capture 190mr C1): an empty pad's
  1783. // three calls to action — Record via an audio input, import a file, Browse Sounds — each a pill under its icon
  1784. ctaRecord.setButtonText (tr ("Record"));
  1785. ctaRecord.onClick = [this] { recording ? stopPadRecording() : startPadRecording(); };
  1786. ctaImport.setButtonText (tr ("Import"));
  1787. ctaImport.onClick = [this] { chooseFile (selected); };
  1788. ctaBrowse.setButtonText (tr ("Browse"));
  1789. ctaBrowse.onClick = [this] {
  1790. if (onBrowse)
  1791. onBrowse();
  1792. };
  1793. for (auto* b : { &ctaRecord, &ctaImport, &ctaBrowse })
  1794. addChildComponent (*b);
  1795. kit.setButtonText (tr ("Kit"));
  1796. kit.setTooltip (tr ("Save the pads as a kit, open one of your kits, or fill the pads from a folder"));
  1797. kit.onClick = [this] { showKitMenu(); };
  1798. reverse.setButtonText (tr ("Reverse"));
  1799. reverse.onClick = [this] { edit ([on = reverse.getToggleState()] (ChannelDef& c) { c.sampler.reverse = on; }); };
  1800. normalize.setButtonText (tr ("Normalize"));
  1801. normalize.setTooltip (tr ("Brings the pad's loudest point to full level"));
  1802. normalize.onClick = [this] { normalizePad(); };
  1803. group.setTooltip (tr ("Pads of the same group cut each other off (an open and a closed hi-hat)"));
  1804. group.onClick = [this] { showGroupMenu(); };
  1805. for (int m = 0; m < 3; ++m)
  1806. {
  1807. auto& b = modes[(std::size_t) m];
  1808. b.setButtonText (modeText ((simplepads::Mode) m));
  1809. b.setClickingTogglesState (true);
  1810. b.setRadioGroupId (1902);
  1811. b.onClick = [this, m, &b] {
  1812. if (b.getToggleState())
  1813. edit ([m] (ChannelDef& c) { c.simplePad.mode = (std::uint8_t) m; });
  1814. };
  1815. addAndMakeVisible (b);
  1816. }
  1817. modes[0].setTooltip (tr ("Plays while the key is held"));
  1818. modes[1].setTooltip (tr ("Plays to its end, however short the hit"));
  1819. modes[2].setTooltip (tr ("Repeats while the key is held"));
  1820. for (int k = 0; k < knobCount; ++k)
  1821. {
  1822. auto& knob = knobs[(std::size_t) k];
  1823. styleCaption (captions[(std::size_t) k], padKnobName (k));
  1824. captions[(std::size_t) k].setJustificationType (juce::Justification::centred);
  1825. addAndMakeVisible (captions[(std::size_t) k]);
  1826. knob.onChange = [this, k] (float v) { turn (k, v); };
  1827. addAndMakeVisible (knob);
  1828. }
  1829. knobs[0].resetValue = 0.0f;
  1830. knobs[0].valueText = [] (float v) { return secondsText (attackFrom (v)); };
  1831. knobs[1].resetValue = 0.0f;
  1832. knobs[1].valueText = [] (float v) { return secondsText (releaseFrom (v)); };
  1833. knobs[2].valueText = [] (float v) { return toneLabel (v * 2.0f - 1.0f); };
  1834. knobs[3].valueText = [] (float v) { return pitchText ((v * 2.0f - 1.0f) * simplepads::maxPitch); };
  1835. knobs[4].valueText = [] (float v) { return panText (v * 2.0f - 1.0f); };
  1836. knobs[5].resetValue = 0.78f;
  1837. knobs[2].setTooltip (tr ("Left: darker (low-pass). Right: thinner (high-pass). Middle: off"));
  1838. knobs[3].setTooltip (tr ("In semitones; Shift + drag for cents"));
  1839. for (auto* c : std::initializer_list<juce::Component*> { &load, &browse, &kit, &reverse, &normalize, &group })
  1840. addAndMakeVisible (c);
  1841. setWantsKeyboardFocus (false);
  1842. }
  1843. std::function<void()> onBrowse;
  1844. void show (int newTrack)
  1845. {
  1846. track = newTrack;
  1847. update();
  1848. }
  1849. void update()
  1850. {
  1851. const auto& song = engine.getSong();
  1852. channels = simplepads::padChannels (song, track);
  1853. const auto c = channelOf (selected);
  1854. const bool has = c != nullptr && ! c->samplePath.empty();
  1855. if (c != nullptr)
  1856. {
  1857. const auto mode = simplepads::modeOf (*c);
  1858. modes[(std::size_t) mode].setToggleState (true, juce::dontSendNotification);
  1859. knobs[0].setValue (attackTo (c->sampler.attack));
  1860. knobs[1].setValue (releaseTo (c->simplePad.release));
  1861. knobs[2].setValue ((c->simplePad.tone + 1.0f) * 0.5f);
  1862. knobs[3].setValue ((c->sampler.pitch / simplepads::maxPitch + 1.0f) * 0.5f);
  1863. knobs[4].setValue ((c->pan + 1.0f) * 0.5f);
  1864. knobs[5].setValue (c->volume);
  1865. reverse.setToggleState (c->sampler.reverse, juce::dontSendNotification);
  1866. group.setButtonText (tr ("Group: {0}", { c->simplePad.group > 0 ? juce::String (c->simplePad.group) : tr ("None") }));
  1867. knobs[1].setDimmed (mode == simplepads::Mode::oneShot);
  1868. }
  1869. for (auto* comp : std::initializer_list<juce::Component*> { &reverse, &normalize, &group, &modes[0], &modes[1], &modes[2] })
  1870. comp->setEnabled (has);
  1871. for (auto& k : knobs)
  1872. k.setEnabled (has);
  1873. for (auto* b : { &ctaRecord, &ctaImport, &ctaBrowse }) // round 190mr (DS-36): an empty pad's calls to action
  1874. b->setVisible (! has || recording);
  1875. styleRecordCta();
  1876. waveFor = {};
  1877. resized();
  1878. repaint();
  1879. }
  1880. int selectedPad() const noexcept { return selected; }
  1881. void select (int pad)
  1882. {
  1883. selected = juce::jlimit (0, simplepads::padCount - 1, pad);
  1884. update();
  1885. }
  1886. // a click on pad `pad`, as the mouse does (tests, --reabl190foshot)
  1887. void hit (int pad)
  1888. {
  1889. select (pad);
  1890. lightPad (selected);
  1891. if (const auto ch = channelIndex (selected); ch >= 0 && hasSound (selected))
  1892. {
  1893. engine.sendLiveNote (ch, simplepads::padKey, 0.8f, true, true);
  1894. engine.sendLiveNote (ch, simplepads::padKey, 0.0f, false, true);
  1895. }
  1896. repaint();
  1897. }
  1898. // tests / shots: the same edits the controls make
  1899. void loadFileForCheck (int pad, const juce::File& file) { loadFile (pad, file); }
  1900. void turnForCheck (int knob, float v) { knobs[(std::size_t) knob].turnTo (v); }
  1901. void setModeForCheck (int mode) // (the button's own edit, at once: triggerClick would post it)
  1902. {
  1903. modes[(std::size_t) mode].setToggleState (true, juce::dontSendNotification);
  1904. edit ([mode] (ChannelDef& c) { c.simplePad.mode = (std::uint8_t) mode; });
  1905. }
  1906. void dragPadForCheck (int from, int to, bool copy) { dropPad (from, to, copy); }
  1907. void setRegionForCheck (float start, float end)
  1908. {
  1909. edit ([start, end] (ChannelDef& c) {
  1910. c.sampler.regionStart = start;
  1911. c.sampler.regionEnd = end;
  1912. });
  1913. }
  1914. void normalizeForCheck() { normalizePad(); }
  1915. juce::PopupMenu kitMenuForSnapshot() { return kitMenu(); }
  1916. juce::PopupMenu padMenuForSnapshot (int pad) { return padMenu (pad); }
  1917. void paint (juce::Graphics& g) override
  1918. {
  1919. const auto& song = engine.getSong();
  1920. const auto trackColour = juce::Colour (track >= 0 && track < (int) song.playlistTracks.size() && song.playlistTracks[(std::size_t) track].colour != 0
  1921. ? song.playlistTracks[(std::size_t) track].colour
  1922. : simpletracks::defaultColour (simpletracks::Kind::pads));
  1923. for (int p = 0; p < simplepads::padCount; ++p)
  1924. {
  1925. const auto r = padBounds (p).toFloat();
  1926. const auto* c = channelOf (p);
  1927. const bool has = c != nullptr && ! c->samplePath.empty();
  1928. const auto tint = padColour (c != nullptr ? c->simplePad.colour : 0, trackColour);
  1929. // round 190jc (design190ia SG-11): the label is black or white, whichever reads better on the pad (>= 4.58:1 on any
  1930. // fill; white "Hat" on orange was 2.71:1). Round 190jj: a press darkens the plate (BandLab); the label keeps the
  1931. // ink of the pad at rest, as BandLab's glyph keeps its colour
  1932. const auto rest = has ? tint.withMultipliedBrightness (0.55f).withMultipliedSaturation (0.8f) : colour::bg2;
  1933. const auto press = pressShown[(std::size_t) p];
  1934. const auto fill = has && press > 0.0f ? rest.withMultipliedBrightness (1.0f - pressDepth * press) : rest;
  1935. const auto ink = ui::simplelook::inkOn (rest);
  1936. if (has)
  1937. {
  1938. fillRoundRect (g, r, radius::md, fill);
  1939. g.setColour (ink);
  1940. g.setFont (font (ui::simplelook::largeControls() ? type::body : type::small, true));
  1941. g.drawFittedText (utf8 (c->name), r.reduced (6.0f, 4.0f).withTrimmedTop (12.0f).toNearestInt(), juce::Justification::centredLeft, 2, 0.8f);
  1942. }
  1943. else
  1944. {
  1945. fillRoundRect (g, r, radius::md, p == dropTarget ? colour::bg4 : colour::bg2);
  1946. juce::Path frame, dashed;
  1947. frame.addRoundedRectangle (r.reduced (0.5f), radius::md);
  1948. const float dashes[] { 3.0f, 3.0f };
  1949. juce::PathStrokeType (1.0f).createDashedStroke (dashed, frame, dashes, 2);
  1950. g.setColour (colour::borderStrong);
  1951. g.fillPath (dashed);
  1952. g.setColour (colour::textDisabled);
  1953. g.fillRect (juce::Rectangle<float> (10.0f, 1.5f).withCentre (r.getCentre()));
  1954. g.fillRect (juce::Rectangle<float> (1.5f, 10.0f).withCentre (r.getCentre()));
  1955. }
  1956. // the typing key that plays it, top left
  1957. g.setColour (has ? ink : colour::textSecondary);
  1958. g.setFont (font (type::caption, true));
  1959. g.drawText (juce::String::charToString ((juce::juce_wchar) simplepads::typingKey (p)), r.reduced (6.0f, 3.0f).toNearestInt(),
  1960. juce::Justification::topLeft, false);
  1961. if (p == selected)
  1962. {
  1963. g.setColour (colour::accent);
  1964. g.drawRoundedRectangle (r.reduced (1.0f), radius::md, 2.0f);
  1965. }
  1966. if (p == selected && recording) // round 190mr (DS-36, capture 190mr C1): the pad being recorded is red with a dot
  1967. {
  1968. fillRoundRect (g, r.reduced (2.0f), radius::md, colour::accent.withAlpha (0.55f));
  1969. g.setColour (colour::accent);
  1970. g.fillEllipse (juce::Rectangle<float> (9.0f, 9.0f).withCentre (r.getCentre()));
  1971. }
  1972. if (p == dropTarget)
  1973. {
  1974. g.setColour (colour::textPrimary);
  1975. g.drawRoundedRectangle (r.reduced (2.5f), radius::md, 1.0f);
  1976. }
  1977. }
  1978. // the selected pad: its title and its waveform with the played region (not when only a pad repaints)
  1979. if (! g.clipRegionIntersects (titleArea.getUnion (waveArea)))
  1980. return;
  1981. const auto* c = channelOf (selected);
  1982. const bool has = c != nullptr && ! c->samplePath.empty();
  1983. g.setColour (colour::textPrimary);
  1984. g.setFont (font (type::body, true));
  1985. const auto title = tr ("Pad {0}", { juce::String (selected + 1) })
  1986. + (has ? juce::String::fromUTF8 (" \xc2\xb7 ") + utf8 (c->name) : juce::String())
  1987. + juce::String::fromUTF8 (" \xc2\xb7 ") + tr ("key {0}", { juce::String::charToString ((juce::juce_wchar) simplepads::typingKey (selected)) });
  1988. g.drawFittedText (title, titleArea, juce::Justification::centredLeft, 1, 0.8f);
  1989. const auto w = waveArea.toFloat();
  1990. fillRoundRect (g, w, radius::md, colour::bg0);
  1991. if (! has || recording)
  1992. {
  1993. // round 190mr (DS-36): BandLab's three columns — icon, caption, the pill under them (the pills are buttons)
  1994. static const char* const captions[] { TR_NOOP ("Record via an audio input"), TR_NOOP ("Drag and drop or import an audio file"),
  1995. TR_NOOP ("Browse Sounds") };
  1996. const Icon glyphs[] { Icon::mic, Icon::audioFile, Icon::listen };
  1997. for (int k = 0; k < 3; ++k)
  1998. {
  1999. const auto column = ctaColumn (k);
  2000. const auto icon = juce::Rectangle<float> (22.0f, 22.0f).withCentre ({ (float) column.getCentreX(), (float) column.getY() + 14.0f });
  2001. icons::draw (g, glyphs[k], icon, k == 0 && recording ? colour::accent : colour::textPrimary);
  2002. g.setColour (k == 0 && recording ? colour::accent : colour::textSecondary);
  2003. g.setFont (font (type::small));
  2004. g.drawFittedText (k == 0 && recording ? tr ("Recording...") : tr (captions[k]),
  2005. column.withTrimmedTop (32).withHeight (18), juce::Justification::centred, 1, 0.8f);
  2006. }
  2007. return;
  2008. }
  2009. drawWave (g, *c, w, padColour (c->simplePad.colour, trackColour));
  2010. }
  2011. void resized() override
  2012. {
  2013. auto r = getLocalBounds().reduced (pad, 6);
  2014. // round 190jc (SG-11): touch size at least (44 px; Large controls 48), up to 72
  2015. const auto side = juce::jlimit (ui::simplelook::px (44, 48), 72, (r.getHeight() - 3 * 4) / 4);
  2016. gridArea = r.removeFromLeft (side * 4 + 3 * 4).withHeight (side * 4 + 3 * 4);
  2017. r.removeFromLeft (14);
  2018. auto top = r.removeFromTop (26);
  2019. kit.setBounds (top.removeFromRight (64));
  2020. top.removeFromRight (6);
  2021. browse.setBounds (top.removeFromRight (124));
  2022. top.removeFromRight (6);
  2023. load.setBounds (top.removeFromRight (84));
  2024. titleArea = top;
  2025. r.removeFromTop (4);
  2026. auto controls = r.removeFromBottom (juce::jmin (84, r.getHeight() / 2 + 8));
  2027. waveArea = r.reduced (0, 2);
  2028. for (int k = 0; k < 3; ++k) // round 190mr (DS-36): each pill under its column's caption
  2029. {
  2030. auto* b = k == 0 ? &ctaRecord : k == 1 ? &ctaImport : &ctaBrowse;
  2031. const auto column = ctaColumn (k);
  2032. b->setBounds (juce::Rectangle<int> (juce::jmin (84, column.getWidth() - 8), 26).withCentre ({ column.getCentreX(), column.getY() + 70 }));
  2033. }
  2034. auto row = controls.removeFromTop (24);
  2035. for (auto& b : modes)
  2036. b.setBounds (row.removeFromLeft (84)), row.removeFromLeft (2);
  2037. row.removeFromLeft (10);
  2038. reverse.setBounds (row.removeFromLeft (84));
  2039. row.removeFromLeft (6);
  2040. normalize.setBounds (row.removeFromLeft (92));
  2041. row.removeFromLeft (6);
  2042. group.setBounds (row.removeFromLeft (110));
  2043. controls.removeFromTop (4);
  2044. const auto kw = juce::jmin (78, controls.getWidth() / knobCount);
  2045. for (int k = 0; k < knobCount; ++k)
  2046. {
  2047. auto cell = controls.removeFromLeft (kw);
  2048. captions[(std::size_t) k].setBounds (cell.removeFromTop (13));
  2049. knobs[(std::size_t) k].setBounds (cell);
  2050. }
  2051. }
  2052. void mouseDown (const juce::MouseEvent& e) override
  2053. {
  2054. dragFrom = -1;
  2055. regionDrag = 0;
  2056. if (const auto p = padAt (e.getPosition()); p >= 0)
  2057. {
  2058. if (e.mods.isPopupMenu())
  2059. {
  2060. select (p);
  2061. padMenu (p).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  2062. return;
  2063. }
  2064. dragFrom = p;
  2065. // a click plays the pad while the button is held (a Gate pad stops when it is let go)
  2066. select (p);
  2067. lightPad (p);
  2068. if (const auto ch = channelIndex (p); ch >= 0 && hasSound (p))
  2069. {
  2070. engine.sendLiveNote (ch, simplepads::padKey, 0.8f, true, true);
  2071. heldChannel = ch;
  2072. }
  2073. return;
  2074. }
  2075. if (waveArea.contains (e.getPosition()))
  2076. {
  2077. const auto* c = channelOf (selected);
  2078. if (c == nullptr || c->samplePath.empty())
  2079. return;
  2080. const auto x = (float) (e.x - waveArea.getX()) / (float) juce::jmax (1, waveArea.getWidth());
  2081. regionDrag = std::abs (x - c->sampler.regionStart) <= std::abs (x - c->sampler.regionEnd) ? 1 : 2;
  2082. mouseDrag (e);
  2083. }
  2084. }
  2085. void mouseDrag (const juce::MouseEvent& e) override
  2086. {
  2087. if (regionDrag != 0)
  2088. {
  2089. const auto x = juce::jlimit (0.0f, 1.0f, (float) (e.x - waveArea.getX()) / (float) juce::jmax (1, waveArea.getWidth()));
  2090. const bool start = regionDrag == 1;
  2091. edit ([x, start] (ChannelDef& c) {
  2092. if (start)
  2093. c.sampler.regionStart = juce::jmin (x, c.sampler.regionEnd - 0.01f);
  2094. else
  2095. c.sampler.regionEnd = juce::jmax (x, c.sampler.regionStart + 0.01f);
  2096. });
  2097. return;
  2098. }
  2099. if (dragFrom >= 0 && e.getDistanceFromDragStart() > 6)
  2100. {
  2101. const auto over = padAt (e.getPosition());
  2102. if (over != dropTarget)
  2103. {
  2104. dropTarget = over == dragFrom ? -1 : over;
  2105. repaint();
  2106. }
  2107. }
  2108. }
  2109. void mouseUp (const juce::MouseEvent& e) override
  2110. {
  2111. if (heldChannel >= 0)
  2112. {
  2113. engine.sendLiveNote (heldChannel, simplepads::padKey, 0.0f, false, true);
  2114. heldChannel = -1;
  2115. }
  2116. if (dragFrom >= 0 && dropTarget >= 0)
  2117. dropPad (dragFrom, dropTarget, e.mods.isAltDown());
  2118. dragFrom = dropTarget = -1;
  2119. regionDrag = 0;
  2120. repaint();
  2121. }
  2122. // files from the system and sounds from LYNX's browser land on the pad under the pointer
  2123. bool isInterestedInFileDrag (const juce::StringArray& files) override { return track >= 0 && ! files.isEmpty(); }
  2124. void fileDragMove (const juce::StringArray&, int x, int y) override { setDropTarget (padAt ({ x, y })); }
  2125. void fileDragExit (const juce::StringArray&) override { setDropTarget (-1); }
  2126. void filesDropped (const juce::StringArray& files, int x, int y) override
  2127. {
  2128. auto at = padAt ({ x, y });
  2129. setDropTarget (-1);
  2130. if (at < 0)
  2131. at = selected;
  2132. // several files fill the pads from there on
  2133. for (const auto& f : files)
  2134. if (SampleLibrary::isSampleFile (juce::File (f)) && at < simplepads::padCount)
  2135. loadFile (at++, juce::File (f));
  2136. }
  2137. bool isInterestedInDragSource (const SourceDetails& d) override
  2138. {
  2139. return track >= 0 && BrowserComponent::isBrowserDrag (d) && SampleLibrary::isSampleFile (BrowserComponent::draggedFile (d));
  2140. }
  2141. void itemDragMove (const SourceDetails& d) override { setDropTarget (padAt (d.localPosition)); }
  2142. void itemDragExit (const SourceDetails&) override { setDropTarget (-1); }
  2143. void itemDropped (const SourceDetails& d) override
  2144. {
  2145. const auto at = padAt (d.localPosition);
  2146. setDropTarget (-1);
  2147. loadFile (at >= 0 ? at : selected, BrowserComponent::draggedFile (d));
  2148. }
  2149. // Round 190jj (capture190ji §1a, shots/bl-a-pads-flash-z2.png, films/play-sampler-pads): BandLab's pad "press" — a
  2150. // pad that sounds darkens from its colour to ~55 % brightness in ~50 ms and back in ~90 ms (eased both ways), for a
  2151. // click, a key, and the notes the song plays. The timer runs only while a press runs (60 Hz with Animations on; with
  2152. // Animations off the pad darkens at once and comes back after the same 140 ms: two repaints). Only the pressed pad
  2153. // repaints. (Round 190ih, DS-34: the page is never repainted whole for a press.)
  2154. static constexpr double pressInMs = 50.0, pressOutMs = 90.0;
  2155. static constexpr float pressDepth = 0.45f; // (to 55 % of the colour)
  2156. float pressAmount (int p, double nowMs) const
  2157. {
  2158. const auto start = pressStart[(std::size_t) p];
  2159. if (start < 0.0)
  2160. return 0.0f;
  2161. const auto t = nowMs - start;
  2162. if (t >= pressInMs + pressOutMs || t < 0.0)
  2163. return 0.0f;
  2164. if (! ui::motion::enabled())
  2165. return 1.0f;
  2166. auto ease = [] (double x) { return (float) (x * x * (3.0 - 2.0 * x)); }; // (smoothstep: eased both ways)
  2167. return t < pressInMs ? ease (t / pressInMs) : 1.0f - ease ((t - pressInMs) / pressOutMs);
  2168. }
  2169. void timerCallback() override
  2170. {
  2171. const auto now = juce::Time::getMillisecondCounterHiRes();
  2172. bool any = false;
  2173. for (int p = 0; p < simplepads::padCount; ++p)
  2174. {
  2175. if (pressStart[(std::size_t) p] < 0.0)
  2176. continue;
  2177. const auto amount = pressAmount (p, now);
  2178. if (amount <= 0.0f && now - pressStart[(std::size_t) p] >= pressInMs + pressOutMs)
  2179. pressStart[(std::size_t) p] = -1.0;
  2180. if (amount != pressShown[(std::size_t) p])
  2181. {
  2182. pressShown[(std::size_t) p] = amount;
  2183. repaint (padBounds (p).expanded (2));
  2184. }
  2185. any = any || pressStart[(std::size_t) p] >= 0.0;
  2186. }
  2187. if (! any)
  2188. stopTimer();
  2189. }
  2190. void lightPad (int pad)
  2191. {
  2192. if (pad >= 0 && pad < simplepads::padCount)
  2193. {
  2194. pressStart[(std::size_t) pad] = juce::Time::getMillisecondCounterHiRes();
  2195. if (! isTimerRunning())
  2196. startTimerHz (ui::motion::enabled() ? 60 : 30);
  2197. timerCallback(); // (the first frame now)
  2198. }
  2199. }
  2200. // Round 190jj: the notes the song plays press their pads (BandLab). Called on the main window's 30 Hz timer; it reads
  2201. // the pads' channels' note-strike counters (the engine's activity counters: a new note-on, even one shorter than a
  2202. // frame) only while the song runs and the page shows; stopped it does nothing.
  2203. void watchPlayback()
  2204. {
  2205. const auto runs = engine.getTransport().playing.load (std::memory_order_relaxed) && isShowing() && track >= 0;
  2206. for (int p = 0; p < simplepads::padCount; ++p)
  2207. {
  2208. const auto ch = channelIndex (p);
  2209. const auto strikes = runs && ch >= 0 ? engine.noteStrikes (ch) : 0u;
  2210. if (runs && watching && ch == seenChannel[(std::size_t) p] && strikes != seenStrikes[(std::size_t) p] && hasSound (p))
  2211. lightPad (p);
  2212. seenStrikes[(std::size_t) p] = strikes;
  2213. seenChannel[(std::size_t) p] = ch;
  2214. }
  2215. watching = runs;
  2216. }
  2217. float pressShownForCheck (int pad) const { return pad >= 0 && pad < simplepads::padCount && pressStart[(std::size_t) pad] >= 0.0 ? 1.0f : pressShown[(std::size_t) pad]; }
  2218. float pressForSnapshot (int pad, float amount)
  2219. {
  2220. pressStart[(std::size_t) pad] = -1.0;
  2221. pressShown[(std::size_t) pad] = amount;
  2222. repaint();
  2223. return amount;
  2224. }
  2225. private:
  2226. static constexpr int knobCount = 6;
  2227. const ChannelDef* channelOf (int p) const
  2228. {
  2229. const auto& song = engine.getSong();
  2230. const auto i = p >= 0 && p < (int) channels.size() ? channels[(std::size_t) p] : -1;
  2231. return i >= 0 && i < (int) song.channels.size() ? &song.channels[(std::size_t) i] : nullptr;
  2232. }
  2233. int channelIndex (int p) const { return p >= 0 && p < (int) channels.size() ? channels[(std::size_t) p] : -1; }
  2234. bool hasSound (int p) const
  2235. {
  2236. const auto* c = channelOf (p);
  2237. return c != nullptr && ! c->samplePath.empty();
  2238. }
  2239. // the grid: pad 0 bottom left, pad 15 top right (the keys' shape)
  2240. juce::Rectangle<int> padBounds (int p) const
  2241. {
  2242. const auto side = (gridArea.getWidth() - 3 * 4) / 4;
  2243. const auto col = p % 4, row = 3 - p / 4;
  2244. return { gridArea.getX() + col * (side + 4), gridArea.getY() + row * (side + 4), side, side };
  2245. }
  2246. int padAt (juce::Point<int> pos) const
  2247. {
  2248. for (int p = 0; p < simplepads::padCount; ++p)
  2249. if (padBounds (p).contains (pos))
  2250. return p;
  2251. return -1;
  2252. }
  2253. void setDropTarget (int p)
  2254. {
  2255. if (p != dropTarget)
  2256. {
  2257. dropTarget = p;
  2258. repaint();
  2259. }
  2260. }
  2261. std::int64_t framesOf (const ChannelDef& c)
  2262. {
  2263. if (c.samplePath.empty())
  2264. return 0;
  2265. const auto data = engine.getSampleLibrary().load (utf8 (c.samplePath));
  2266. return data != nullptr ? (std::int64_t) data->frames() : 0;
  2267. }
  2268. // one undoable edit of the selected pad's channel; the pad's own settings are applied to the channel after it
  2269. void edit (const std::function<void (ChannelDef&)>& change, int pad = -1)
  2270. {
  2271. const auto p = pad >= 0 ? pad : selected;
  2272. const auto ch = channelIndex (p);
  2273. if (ch < 0)
  2274. return;
  2275. const auto frames = framesOf (engine.getSong().channels[(std::size_t) ch]);
  2276. engine.editSong ([ch, change, frames] (Song& s) {
  2277. if (ch < (int) s.channels.size())
  2278. {
  2279. change (s.channels[(std::size_t) ch]);
  2280. simplepads::apply (s.channels[(std::size_t) ch], frames);
  2281. }
  2282. });
  2283. update();
  2284. }
  2285. void turn (int k, float v)
  2286. {
  2287. switch (k)
  2288. {
  2289. case 0: edit ([s = attackFrom (v)] (ChannelDef& c) { c.sampler.attack = s; }); break;
  2290. case 1: edit ([s = releaseFrom (v)] (ChannelDef& c) { c.simplePad.release = s; }); break;
  2291. case 2: edit ([t = v * 2.0f - 1.0f] (ChannelDef& c) { c.simplePad.tone = std::abs (t) < 0.02f ? 0.0f : t; }); break;
  2292. case 3: edit ([p = (v * 2.0f - 1.0f) * simplepads::maxPitch] (ChannelDef& c) { c.sampler.pitch = p; }); break;
  2293. case 4: edit ([p = v * 2.0f - 1.0f] (ChannelDef& c) { c.pan = std::abs (p) < 0.01f ? 0.0f : p; }); break;
  2294. default: edit ([v] (ChannelDef& c) { c.volume = v; }); break;
  2295. }
  2296. }
  2297. // the same value on every pad (the knob's menu): what the original's "copy value to other pads" does
  2298. void copyKnobToAll (int k)
  2299. {
  2300. const auto* src = channelOf (selected);
  2301. if (src == nullptr)
  2302. return;
  2303. const auto from = *src;
  2304. const auto chans = channels;
  2305. std::vector<std::int64_t> frames;
  2306. for (auto ch : chans)
  2307. frames.push_back (ch >= 0 ? framesOf (engine.getSong().channels[(std::size_t) ch]) : 0);
  2308. engine.editSong ([k, from, chans, frames] (Song& s) {
  2309. for (std::size_t i = 0; i < chans.size(); ++i)
  2310. {
  2311. if (chans[i] < 0 || chans[i] >= (int) s.channels.size())
  2312. continue;
  2313. auto& c = s.channels[(std::size_t) chans[i]];
  2314. switch (k)
  2315. {
  2316. case 0: c.sampler.attack = from.sampler.attack; break;
  2317. case 1: c.simplePad.release = from.simplePad.release; break;
  2318. case 2: c.simplePad.tone = from.simplePad.tone; break;
  2319. case 3: c.sampler.pitch = from.sampler.pitch; break;
  2320. case 4: c.pan = from.pan; break;
  2321. default: c.volume = from.volume; break;
  2322. }
  2323. simplepads::apply (c, frames[i]);
  2324. }
  2325. });
  2326. update();
  2327. }
  2328. void loadFile (int p, const juce::File& file)
  2329. {
  2330. if (p < 0 || ! file.existsAsFile())
  2331. return;
  2332. const auto data = engine.getSampleLibrary().load (file.getFullPathName());
  2333. if (data == nullptr)
  2334. {
  2335. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"),
  2336. tr ("Could not read {0}", { file.getFileName() }));
  2337. return;
  2338. }
  2339. const auto t = track;
  2340. const auto path = file.getFullPathName().toStdString(), name = file.getFileNameWithoutExtension().toStdString();
  2341. const auto frames = (std::int64_t) data->frames();
  2342. const auto seconds = data->sampleRate > 0.0 ? (double) frames / data->sampleRate : 0.0;
  2343. engine.editSong ([t, p, path, name, frames, seconds] (Song& s) { simplepads::loadSample (s, t, p, path, name, frames, seconds); });
  2344. folder = file.getParentDirectory();
  2345. select (p);
  2346. }
  2347. void chooseFile (int p)
  2348. {
  2349. chooser = ui::makeFileChooser (tr ("Choose sample"), folder, engine.getSampleLibrary().wildcard());
  2350. ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  2351. [safe = juce::Component::SafePointer<PadsPage> (this), p] (const juce::FileChooser& fc) {
  2352. if (safe != nullptr)
  2353. safe->loadFile (p, fc.getResult());
  2354. });
  2355. }
  2356. void dropPad (int from, int to, bool copy)
  2357. {
  2358. if (from < 0 || to < 0 || from == to || ! hasSound (from))
  2359. return;
  2360. const auto t = track;
  2361. const auto ch = channelIndex (from);
  2362. const auto frames = ch >= 0 ? framesOf (engine.getSong().channels[(std::size_t) ch]) : 0;
  2363. // onto an empty pad it moves, onto a pad with a sound the two swap; with Alt it is copied
  2364. engine.editSong ([t, from, to, copy, frames] (Song& s) {
  2365. if (copy)
  2366. simplepads::copyPad (s, t, from, to, frames);
  2367. else
  2368. simplepads::swapPads (s, t, from, to);
  2369. });
  2370. select (to);
  2371. }
  2372. void normalizePad()
  2373. {
  2374. const auto* c = channelOf (selected);
  2375. if (c == nullptr || c->samplePath.empty())
  2376. return;
  2377. const auto data = engine.getSampleLibrary().load (utf8 (c->samplePath));
  2378. if (data == nullptr || data->frames() == 0)
  2379. return;
  2380. const auto n = (std::int64_t) data->frames();
  2381. const auto a = (std::int64_t) (c->sampler.regionStart * (float) n), b = juce::jmax (a + 1, (std::int64_t) (c->sampler.regionEnd * (float) n));
  2382. float peak = 0.0f;
  2383. for (auto i = a; i < b && i < n; ++i)
  2384. peak = juce::jmax (peak, std::abs (data->leftData()[i]), std::abs (data->rightData()[i]));
  2385. edit ([g = simplepads::normalizeGainDb (peak)] (ChannelDef& ch) { ch.sampler.gainDb = g; });
  2386. }
  2387. void showGroupMenu()
  2388. {
  2389. juce::PopupMenu m;
  2390. const auto* c = channelOf (selected);
  2391. const auto now = c != nullptr ? c->simplePad.group : 0;
  2392. m.addItem (tr ("None"), true, now == 0, [this] { edit ([] (ChannelDef& ch) { ch.simplePad.group = 0; }); });
  2393. for (int g = 1; g <= simplepads::groupCount; ++g)
  2394. m.addItem (tr ("Group {0}", { juce::String (g) }), true, now == g, [this, g] { edit ([g] (ChannelDef& ch) { ch.simplePad.group = g; }); });
  2395. m.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&group));
  2396. }
  2397. juce::PopupMenu padMenu (int p)
  2398. {
  2399. juce::PopupMenu m;
  2400. const bool has = hasSound (p);
  2401. m.addItem (tr ("Import..."), [this, p] { chooseFile (p); });
  2402. m.addSeparator();
  2403. m.addItem (tr ("Copy"), has, false, [this, p] { clipboard = p; });
  2404. m.addItem (tr ("Paste"), clipboard >= 0 && clipboard != p && hasSound (clipboard), false, [this, p] { dropPad (clipboard, p, true); });
  2405. m.addItem (tr ("Clear the pad"), has, false, [this, p] {
  2406. const auto t = track;
  2407. engine.editSong ([t, p] (Song& s) { simplepads::clearPad (s, t, p); });
  2408. update();
  2409. });
  2410. juce::PopupMenu colours;
  2411. const auto* c = channelOf (p);
  2412. const auto now = c != nullptr ? c->simplePad.colour : 0;
  2413. for (int i = 0; i <= simplepads::colourCount; ++i)
  2414. colours.addItem (padColourName (i), true, now == i, [this, p, i] { edit ([i] (ChannelDef& ch) { ch.simplePad.colour = i; }, p); });
  2415. m.addSubMenu (tr ("Colour"), colours);
  2416. juce::PopupMenu copyTo;
  2417. for (int k = 0; k < knobCount; ++k)
  2418. copyTo.addItem (padKnobName (k), has, false, [this, p, k] {
  2419. select (p);
  2420. copyKnobToAll (k);
  2421. });
  2422. m.addSubMenu (tr ("Copy a value to every pad"), copyTo, has);
  2423. return m;
  2424. }
  2425. // kits: the pads' sounds and settings in a file of the user's (Documents/LYNX/Sampler kits/<name>.lynxkit)
  2426. static juce::File kitFolder() { return platform::documentsFolder().getChildFile ("LYNX/Sampler kits"); }
  2427. juce::PopupMenu kitMenu()
  2428. {
  2429. juce::PopupMenu m;
  2430. m.addItem (tr ("Save the pads as a kit..."), track >= 0, false, [this] { askKitName(); });
  2431. juce::PopupMenu mine, rename, remove;
  2432. const auto files = kitFolder().findChildFiles (juce::File::findFiles, false, "*.lynxkit");
  2433. auto sorted = files;
  2434. std::sort (sorted.begin(), sorted.end(), [] (const juce::File& a, const juce::File& b) { return a.getFileName().compareNatural (b.getFileName()) < 0; });
  2435. for (const auto& f : sorted)
  2436. {
  2437. mine.addItem (f.getFileNameWithoutExtension(), [this, f] { openKit (f); });
  2438. rename.addItem (f.getFileNameWithoutExtension(), [this, f] { askRename (f); });
  2439. remove.addItem (f.getFileNameWithoutExtension(), [f] { f.moveToTrash(); });
  2440. }
  2441. m.addSubMenu (tr ("My kits"), mine, ! sorted.isEmpty());
  2442. m.addItem (tr ("Fill the pads from a folder..."), track >= 0, false, [this] { chooseKitFolder(); });
  2443. m.addSeparator();
  2444. m.addSubMenu (tr ("Rename a kit"), rename, ! sorted.isEmpty());
  2445. m.addSubMenu (tr ("Delete a kit"), remove, ! sorted.isEmpty());
  2446. return m;
  2447. }
  2448. void showKitMenu() { kitMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&kit)); }
  2449. void askKitName()
  2450. {
  2451. auto* w = new juce::AlertWindow (tr ("Save the pads as a kit"), tr ("Name of the kit:"), juce::MessageBoxIconType::NoIcon);
  2452. w->addTextEditor ("name", utf8 (track >= 0 && track < (int) engine.getSong().playlistTracks.size() ? engine.getSong().playlistTracks[(std::size_t) track].name : std::string()));
  2453. w->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  2454. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  2455. w->enterModalState (true, juce::ModalCallbackFunction::create ([this, w, safe = juce::Component::SafePointer<PadsPage> (this)] (int r) {
  2456. if (r == 1 && safe != nullptr)
  2457. saveKit (w->getTextEditorContents ("name").trim());
  2458. }),
  2459. true);
  2460. }
  2461. void askRename (const juce::File& kitFile)
  2462. {
  2463. auto* w = new juce::AlertWindow (tr ("Rename the kit"), tr ("New name of the kit:"), juce::MessageBoxIconType::NoIcon);
  2464. w->addTextEditor ("name", kitFile.getFileNameWithoutExtension());
  2465. w->addButton (tr ("Rename"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  2466. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  2467. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, kitFile] (int r) {
  2468. if (r == 1)
  2469. renameKit (kitFile, w->getTextEditorContents ("name"));
  2470. }),
  2471. true);
  2472. }
  2473. public:
  2474. // a kit file gets another name (2 to 50 characters, not taken); false when it can't
  2475. static bool renameKit (const juce::File& kitFile, const juce::String& rawName)
  2476. {
  2477. const auto name = juce::File::createLegalFileName (rawName).trim();
  2478. const auto target = kitFile.getSiblingFile (name + ".lynxkit");
  2479. if (name.length() < 2 || name.length() > 50 || target.exists() || ! kitFile.existsAsFile())
  2480. return false;
  2481. auto json = juce::JSON::parse (kitFile.loadFileAsString());
  2482. if (auto* o = json.getDynamicObject())
  2483. o->setProperty ("name", name);
  2484. return target.replaceWithText (juce::JSON::toString (json)) && kitFile.deleteFile();
  2485. }
  2486. bool saveKit (const juce::String& rawName)
  2487. {
  2488. const auto name = juce::File::createLegalFileName (rawName).trim();
  2489. if (name.length() < 2 || name.length() > 50) // (the original's rule for a kit's name)
  2490. return false;
  2491. auto pads = juce::Array<juce::var>();
  2492. for (int p = 0; p < simplepads::padCount; ++p)
  2493. {
  2494. const auto* c = channelOf (p);
  2495. if (c == nullptr || c->samplePath.empty())
  2496. continue;
  2497. auto o = std::make_unique<juce::DynamicObject>();
  2498. o->setProperty ("pad", p);
  2499. o->setProperty ("file", utf8 (c->samplePath));
  2500. o->setProperty ("name", utf8 (c->name));
  2501. o->setProperty ("mode", (int) c->simplePad.mode);
  2502. o->setProperty ("tone", c->simplePad.tone);
  2503. o->setProperty ("release", c->simplePad.release);
  2504. o->setProperty ("group", c->simplePad.group);
  2505. o->setProperty ("colour", c->simplePad.colour);
  2506. o->setProperty ("attack", c->sampler.attack);
  2507. o->setProperty ("pitch", c->sampler.pitch);
  2508. o->setProperty ("start", c->sampler.regionStart);
  2509. o->setProperty ("end", c->sampler.regionEnd);
  2510. o->setProperty ("reverse", c->sampler.reverse);
  2511. o->setProperty ("gainDb", c->sampler.gainDb);
  2512. o->setProperty ("volume", c->volume);
  2513. o->setProperty ("pan", c->pan);
  2514. pads.add (juce::var (o.release()));
  2515. }
  2516. auto root = std::make_unique<juce::DynamicObject>();
  2517. root->setProperty ("lynxSamplerKit", 1);
  2518. root->setProperty ("name", name);
  2519. root->setProperty ("pads", pads);
  2520. kitFolder().createDirectory();
  2521. return kitFolder().getChildFile (name + ".lynxkit").replaceWithText (juce::JSON::toString (juce::var (root.release())));
  2522. }
  2523. bool openKit (const juce::File& file)
  2524. {
  2525. const auto json = juce::JSON::parse (file.loadFileAsString());
  2526. if ((int) json.getProperty ("lynxSamplerKit", 0) != 1)
  2527. return false;
  2528. struct Loaded
  2529. {
  2530. int pad;
  2531. ChannelDef def;
  2532. std::int64_t frames;
  2533. };
  2534. std::vector<Loaded> loaded;
  2535. if (const auto* list = json.getProperty ("pads", {}).getArray())
  2536. for (const auto& v : *list)
  2537. {
  2538. const auto p = (int) v.getProperty ("pad", -1);
  2539. const juce::File f (v.getProperty ("file", "").toString());
  2540. const auto data = f.existsAsFile() ? engine.getSampleLibrary().load (f.getFullPathName()) : nullptr;
  2541. if (p < 0 || p >= simplepads::padCount || data == nullptr)
  2542. continue;
  2543. ChannelDef d;
  2544. d.samplePath = f.getFullPathName().toStdString();
  2545. d.name = v.getProperty ("name", f.getFileNameWithoutExtension()).toString().toStdString();
  2546. d.simplePad.mode = (std::uint8_t) juce::jlimit (0, 2, (int) v.getProperty ("mode", 0));
  2547. d.simplePad.tone = (float) v.getProperty ("tone", 0.0);
  2548. d.simplePad.release = (float) v.getProperty ("release", 0.0);
  2549. d.simplePad.group = (int) v.getProperty ("group", 0);
  2550. d.simplePad.colour = (int) v.getProperty ("colour", 0);
  2551. d.sampler.attack = (float) v.getProperty ("attack", 0.0);
  2552. d.sampler.pitch = (float) v.getProperty ("pitch", 0.0);
  2553. d.sampler.regionStart = (float) v.getProperty ("start", 0.0);
  2554. d.sampler.regionEnd = (float) v.getProperty ("end", 1.0);
  2555. d.sampler.reverse = (bool) v.getProperty ("reverse", false);
  2556. d.sampler.gainDb = (float) v.getProperty ("gainDb", 0.0);
  2557. d.volume = (float) v.getProperty ("volume", 0.78);
  2558. d.pan = (float) v.getProperty ("pan", 0.0);
  2559. loaded.push_back ({ p, std::move (d), (std::int64_t) data->frames() });
  2560. }
  2561. const auto t = track;
  2562. engine.editSong ([t, loaded] (Song& s) {
  2563. for (int p = 0; p < simplepads::padCount; ++p)
  2564. simplepads::clearPad (s, t, p);
  2565. for (const auto& l : loaded)
  2566. {
  2567. const auto ch = simplepads::padChannel (s, t, l.pad);
  2568. if (ch < 0)
  2569. continue;
  2570. auto& c = s.channels[(std::size_t) ch];
  2571. c.samplePath = l.def.samplePath;
  2572. c.name = l.def.name;
  2573. c.sampler.attack = l.def.sampler.attack;
  2574. c.sampler.pitch = l.def.sampler.pitch;
  2575. c.sampler.regionStart = l.def.sampler.regionStart;
  2576. c.sampler.regionEnd = l.def.sampler.regionEnd;
  2577. c.sampler.reverse = l.def.sampler.reverse;
  2578. c.sampler.gainDb = l.def.sampler.gainDb;
  2579. c.volume = l.def.volume;
  2580. c.pan = l.def.pan;
  2581. const auto index = c.simplePad.index;
  2582. c.simplePad = l.def.simplePad;
  2583. c.simplePad.index = index;
  2584. simplepads::apply (c, l.frames);
  2585. }
  2586. });
  2587. update();
  2588. return true;
  2589. }
  2590. // the first 16 sounds of a folder (by name), pad by pad
  2591. int fillFromFolder (const juce::File& dir)
  2592. {
  2593. auto files = dir.findChildFiles (juce::File::findFiles, false);
  2594. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFileName().compareNatural (b.getFileName()) < 0; });
  2595. int p = 0;
  2596. for (const auto& f : files)
  2597. if (p < simplepads::padCount && SampleLibrary::isSampleFile (f))
  2598. loadFile (p++, f);
  2599. select (0);
  2600. return p;
  2601. }
  2602. private:
  2603. void chooseKitFolder()
  2604. {
  2605. chooser = ui::makeFileChooser (tr ("Choose a folder of sounds"), folder, {});
  2606. ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories,
  2607. [safe = juce::Component::SafePointer<PadsPage> (this)] (const juce::FileChooser& fc) {
  2608. if (safe != nullptr && fc.getResult().isDirectory())
  2609. safe->fillFromFolder (fc.getResult());
  2610. });
  2611. }
  2612. // round 190jc (SG-11): the waveform in the pad's colour, one column per PHYSICAL pixel (at @2x it stepped every 2 px)
  2613. void drawWave (juce::Graphics& g, const ChannelDef& c, juce::Rectangle<float> w, juce::Colour hue)
  2614. {
  2615. const auto scale = juce::jlimit (1.0f, 4.0f, g.getInternalContext().getPhysicalPixelScaleFactor());
  2616. const auto width = juce::jmax (1, (int) std::round (w.getWidth() * scale));
  2617. if (waveFor != c.samplePath || (int) wave.size() != width)
  2618. {
  2619. wave.assign ((std::size_t) width, 0.0f);
  2620. if (const auto data = engine.getSampleLibrary().load (utf8 (c.samplePath)); data != nullptr && data->frames() > 0)
  2621. {
  2622. const auto n = (std::int64_t) data->frames();
  2623. for (int x = 0; x < width; ++x)
  2624. {
  2625. const auto a = n * x / width, b = juce::jmax (a + 1, n * (x + 1) / width);
  2626. float peak = 0.0f;
  2627. for (auto i = a; i < b; ++i) // (every sample: a stride aliases a low tone into a moiré; done once per sample)
  2628. peak = juce::jmax (peak, std::abs (data->leftData()[i]), std::abs (data->rightData()[i]));
  2629. wave[(std::size_t) x] = peak;
  2630. }
  2631. }
  2632. waveFor = c.samplePath;
  2633. }
  2634. const auto mid = w.getCentreY(), half = w.getHeight() * 0.45f;
  2635. const auto s = w.getX() + c.sampler.regionStart * w.getWidth(), e = w.getX() + c.sampler.regionEnd * w.getWidth();
  2636. const auto played = ui::simplelook::readableOn (hue, colour::bg0, 3.0f);
  2637. juce::RectangleList<float> inRegion, outside; // (two fills, not one per column)
  2638. for (int x = 0; x < width; ++x)
  2639. {
  2640. const auto px = w.getX() + (float) x / scale;
  2641. const auto idx = c.sampler.reverse ? width - 1 - x : x;
  2642. const auto h = juce::jmax (0.5f / scale, wave[(std::size_t) idx] * half);
  2643. (px >= s && px <= e ? inRegion : outside).addWithoutMerging ({ px, mid - h, 1.0f / scale, h * 2.0f });
  2644. }
  2645. g.setColour (played.withAlpha (0.95f));
  2646. g.fillRectList (inRegion);
  2647. g.setColour (colour::textDisabled.withAlpha (0.6f));
  2648. g.fillRectList (outside);
  2649. // the region's handles
  2650. g.setColour (colour::textPrimary);
  2651. for (auto x : { s, e })
  2652. {
  2653. g.fillRect (x - 1.0f, w.getY(), 2.0f, w.getHeight());
  2654. g.fillRect (x - 4.0f, w.getY(), 8.0f, 4.0f);
  2655. }
  2656. if (simplepads::modeOf (c) == simplepads::Mode::loop)
  2657. {
  2658. g.setFont (font (type::caption, true));
  2659. g.setColour (colour::textSecondary);
  2660. g.drawText (juce::String::fromUTF8 ("\xe2\x9f\xb3 ") + trc ("@pad mode: Loop"), w.reduced (6.0f, 3.0f).toNearestInt(), juce::Justification::topRight, false);
  2661. }
  2662. }
  2663. public:
  2664. ~PadsPage() override
  2665. {
  2666. if (recording) // (closed while recording: the tap and the input are let go, nothing is kept)
  2667. {
  2668. recorder.stopTimer();
  2669. engine.getMeters().capture.setSource (AudioCapture::off);
  2670. releaseInput();
  2671. }
  2672. }
  2673. bool recordingForCheck() const noexcept { return recording; }
  2674. void startRecordingForCheck() { startPadRecording(); }
  2675. void recordingLookForSnapshot (bool on) // (the look only: no input is opened)
  2676. {
  2677. recording = on;
  2678. recordingPad = on ? selected : -1;
  2679. update();
  2680. }
  2681. void stopRecordingForCheck() { stopPadRecording(); }
  2682. juce::Component* ctaForCheck (int k) { return k == 0 ? &ctaRecord : k == 1 ? (juce::Component*) &ctaImport : &ctaBrowse; }
  2683. private:
  2684. // --- round 190mr (DS-36): recording into the selected pad (BandLab: Record starts at once, no count-in; the dock says
  2685. // "Recording...", the button turns into a red Stop and the pad turns red; Stop puts the take on the pad) ---------
  2686. juce::Rectangle<int> ctaColumn (int k) const
  2687. {
  2688. const auto area = waveArea.reduced (8, 0);
  2689. const auto w = area.getWidth() / 3;
  2690. const auto top = area.getY() + juce::jmax (4, (area.getHeight() - 100) / 2);
  2691. return { area.getX() + k * w, top, w, 100 };
  2692. }
  2693. void styleRecordCta()
  2694. {
  2695. ctaRecord.setButtonText (recording ? tr ("Stop") : tr ("Record"));
  2696. ctaRecord.setColour (juce::TextButton::buttonColourId, recording ? colour::accent : colour::bg4);
  2697. ctaRecord.setColour (juce::TextButton::textColourOffId, colour::textPrimary);
  2698. }
  2699. struct PadRecorder final : juce::Timer
  2700. {
  2701. std::function<void()> tick;
  2702. void timerCallback() override { tick(); }
  2703. };
  2704. void startPadRecording()
  2705. {
  2706. if (recording || track < 0)
  2707. return;
  2708. if (! engine.hasAudioInput())
  2709. {
  2710. if (const auto result = engine.openAudioInput(); result.issue != AudioEngine::InputIssue::none)
  2711. {
  2712. ui::postNotice ({ result.detail.isNotEmpty() ? result.detail : tr ("No active audio input (Settings > Audio)"), {}, false, false });
  2713. return;
  2714. }
  2715. openedInput = true;
  2716. }
  2717. auto* device = engine.getDeviceManager().getCurrentAudioDevice();
  2718. if (device == nullptr || device->getActiveInputChannels().countNumberOfSetBits() == 0)
  2719. {
  2720. ui::postNotice ({ tr ("No active audio input (Settings > Audio)"), {}, false, false });
  2721. releaseInput();
  2722. return;
  2723. }
  2724. recRate = device->getCurrentSampleRate();
  2725. recStereo = device->getActiveInputChannels().countNumberOfSetBits() > 1;
  2726. recL.clear();
  2727. recR.clear();
  2728. recordingPad = selected;
  2729. engine.getMeters().capture.setSource (AudioCapture::input);
  2730. recording = true;
  2731. recorder.tick = [this] { pullRecording(); };
  2732. recorder.startTimerHz (20);
  2733. update();
  2734. }
  2735. void pullRecording()
  2736. {
  2737. std::vector<float> l, r;
  2738. engine.getMeters().capture.pull (l, r);
  2739. recL.insert (recL.end(), l.begin(), l.end());
  2740. recR.insert (recR.end(), r.begin(), r.end());
  2741. if ((double) recL.size() >= recRate * maxPadSeconds) // (a pad holds a sound, not a song: it stops by itself)
  2742. stopPadRecording();
  2743. }
  2744. void releaseInput()
  2745. {
  2746. if (std::exchange (openedInput, false))
  2747. engine.releaseAudioInputIfUnused();
  2748. }
  2749. void stopPadRecording()
  2750. {
  2751. if (! recording)
  2752. return;
  2753. pullRecording();
  2754. recorder.stopTimer();
  2755. engine.getMeters().capture.setSource (AudioCapture::off);
  2756. releaseInput();
  2757. recording = false;
  2758. const auto pad = std::exchange (recordingPad, -1);
  2759. if (recL.empty() || recRate <= 0.0)
  2760. {
  2761. ui::postHint ({ tr ("Nothing was recorded"), {}, false, false }, 3000);
  2762. update();
  2763. return;
  2764. }
  2765. const auto folder = engine.getRecordingFolder();
  2766. folder.createDirectory();
  2767. const auto file = folder.getNonexistentChildFile (tr ("Pad {0}", { juce::String (pad + 1) }) + " " + juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H%M%S"), ".wav", false);
  2768. juce::AudioBuffer<float> buffer (recStereo ? 2 : 1, (int) recL.size());
  2769. buffer.copyFrom (0, 0, recL.data(), (int) recL.size());
  2770. if (recStereo)
  2771. buffer.copyFrom (1, 0, recR.data(), (int) juce::jmin (recR.size(), recL.size()));
  2772. bool written = false;
  2773. if (auto out = std::unique_ptr<juce::FileOutputStream> (file.createOutputStream()))
  2774. {
  2775. juce::WavAudioFormat wav;
  2776. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (out.get(), recRate, (unsigned) buffer.getNumChannels(), 24, {}, 0)))
  2777. {
  2778. out.release();
  2779. written = writer->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  2780. }
  2781. }
  2782. recL.clear();
  2783. recR.clear();
  2784. if (written)
  2785. loadFile (pad, file);
  2786. else
  2787. ui::postNotice ({ tr ("Could not write {0}", { file.getFullPathName() }), {}, false, false });
  2788. update();
  2789. }
  2790. static constexpr double maxPadSeconds = 60.0;
  2791. PadRecorder recorder;
  2792. bool recording = false, recStereo = false, openedInput = false;
  2793. int recordingPad = -1;
  2794. double recRate = 0.0;
  2795. std::vector<float> recL, recR;
  2796. juce::TextButton ctaRecord, ctaImport, ctaBrowse;
  2797. AudioEngine& engine;
  2798. int track = -1, selected = 0, dragFrom = -1, dropTarget = -1, regionDrag = 0, clipboard = -1, heldChannel = -1;
  2799. std::vector<int> channels;
  2800. std::array<double, simplepads::padCount> pressStart = [] { std::array<double, simplepads::padCount> a; a.fill (-1.0); return a; }();
  2801. std::array<float, simplepads::padCount> pressShown {};
  2802. std::array<std::uint32_t, simplepads::padCount> seenStrikes {};
  2803. std::array<int, simplepads::padCount> seenChannel {};
  2804. bool watching = false;
  2805. juce::Rectangle<int> gridArea, titleArea, waveArea;
  2806. juce::TextButton load, browse, kit, normalize, group;
  2807. juce::ToggleButton reverse;
  2808. std::array<juce::TextButton, 3> modes;
  2809. std::array<DockKnob, knobCount> knobs;
  2810. std::array<juce::Label, knobCount> captions;
  2811. std::vector<float> wave;
  2812. std::string waveFor;
  2813. juce::File folder;
  2814. std::unique_ptr<juce::FileChooser> chooser;
  2815. };
  2816. #include "ui/SimpleControlsPage.inc" // round 190ke: the Controls tab
  2817. #include "ui/SimpleStepsPage.inc" // round 190lr: the Drum Machine tab
  2818. // Round 190nw: the Tracker tab, the track's pattern in the tracker editor (ui/TrackerComponent.h, compact: no pattern box
  2819. // or side panel), the track's channel only. A track without a pattern gets the "New pattern" button (as the Editor tab).
  2820. class SimpleDock::TrackerPage final : public juce::Component
  2821. {
  2822. public:
  2823. explicit TrackerPage (AudioEngine& e) : engine (e)
  2824. {
  2825. makePattern.setButtonText (tr ("New pattern"));
  2826. makePattern.setTooltip (tr ("An empty 4-bar pattern on this track, to write notes into"));
  2827. makePattern.onClick = [this] {
  2828. const auto t = track;
  2829. engine.editSong ([t] (Song& s) { simpletracks::ensurePattern (s, t); });
  2830. update();
  2831. };
  2832. addChildComponent (makePattern);
  2833. }
  2834. void show (int newTrack, int newChannel)
  2835. {
  2836. track = newTrack;
  2837. channel = newChannel;
  2838. update();
  2839. }
  2840. void update()
  2841. {
  2842. const auto& song = engine.getSong();
  2843. const auto pattern = track >= 0 && isVisible() ? simpletracks::patternOf (song, track) : -1;
  2844. if (pattern >= 0 && editor == nullptr)
  2845. {
  2846. editor = makeTracker (engine, true);
  2847. addAndMakeVisible (*editor);
  2848. resized();
  2849. }
  2850. if (editor != nullptr)
  2851. {
  2852. editor->setVisible (pattern >= 0);
  2853. if (pattern >= 0 && (editor->shownPattern() != pattern || shownChannel != channel))
  2854. {
  2855. shownChannel = channel;
  2856. editor->setOnlyChannels (channel >= 0 ? std::optional<std::vector<int>> (std::vector<int> { channel }) : std::nullopt);
  2857. editor->showPattern (pattern);
  2858. }
  2859. }
  2860. makePattern.setVisible (pattern < 0 && track >= 0 && isVisible());
  2861. }
  2862. void visibilityChanged() override { update(); }
  2863. void resized() override
  2864. {
  2865. if (editor != nullptr)
  2866. editor->setBounds (getLocalBounds());
  2867. makePattern.setBounds (getLocalBounds().withSizeKeepingCentre (180, 32));
  2868. }
  2869. juce::Component* trackerComponent() { return editor.get(); }
  2870. private:
  2871. AudioEngine& engine;
  2872. std::unique_ptr<TrackerComponent> editor;
  2873. juce::TextButton makePattern;
  2874. int track = -1, channel = -1, shownChannel = -2;
  2875. };
  2876. SimpleDock::SimpleDock (AudioEngine& e, Hooks h) : engine (e), hooks (std::move (h))
  2877. {
  2878. controlsPage = std::make_unique<ControlsPage> (e);
  2879. addChildComponent (*controlsPage);
  2880. stepsPage = std::make_unique<StepsPage> (e);
  2881. addChildComponent (*stepsPage);
  2882. // the Instrument tab's "Keyboard" button shows the dock's own Keyboard tab (round 190ds)
  2883. hooks.showKeys = [this] { showKeyboard(); };
  2884. effectsPage = std::make_unique<EffectsPage> (engine);
  2885. instrumentPage = std::make_unique<InstrumentPage> (engine, hooks);
  2886. editorPage = std::make_unique<EditorPage> (engine, hooks);
  2887. padsPage = std::make_unique<PadsPage> (engine);
  2888. padsPage->onBrowse = [this] {
  2889. if (onBrowseSounds)
  2890. onBrowseSounds();
  2891. };
  2892. addChildComponent (*padsPage);
  2893. addChildComponent (*effectsPage);
  2894. addChildComponent (*instrumentPage);
  2895. addChildComponent (*editorPage);
  2896. instrumentButton.setButtonText (tr ("Instrument"));
  2897. keyboardButton.setButtonText (tr ("Keyboard"));
  2898. keyboardButton.setTooltip (tr ("Play the track: piano, Scale keys or Chord pad"));
  2899. editorButton.setButtonText (tr ("Editor"));
  2900. editorButton.setTooltip (tr ("Write the track's notes"));
  2901. effectsButton.setButtonText (tr ("Effects"));
  2902. padsButton.setButtonText (tr ("Pads"));
  2903. padsButton.setTooltip (tr ("The Sampler track's 16 pads: their sounds and how they play"));
  2904. padsButton.setComponentID ("simple.dock.pads");
  2905. controlsButton.setButtonText (tr ("Controls"));
  2906. controlsButton.setTooltip (tr ("Eight big knobs for the track's main settings (its sound, its effects and its level)"));
  2907. controlsButton.setComponentID ("simple.dock.controls");
  2908. stepsButton.setButtonText (tr ("Drum Machine"));
  2909. stepsButton.setTooltip (tr ("The drum track's step grid: patterns A to H, length and swing"));
  2910. stepsButton.setComponentID ("simple.dock.steps");
  2911. trackerButton.setButtonText (tr ("Tracker"));
  2912. trackerButton.setTooltip (tr ("The track's notes as rows: typed from the keyboard, tracker style"));
  2913. trackerButton.setComponentID ("simple.dock.tracker");
  2914. trackerPage = std::make_unique<TrackerPage> (engine);
  2915. addChildComponent (*trackerPage);
  2916. // round 190dv: what the first-song tour's ring finds
  2917. setComponentID ("simple.dock"); // (round 190jp: the tour keeps its card off the dock)
  2918. keyboardButton.setComponentID ("simple.dock.keyboard");
  2919. editorButton.setComponentID ("simple.dock.editor");
  2920. effectsButton.setComponentID ("simple.dock.effects");
  2921. const std::pair<juce::TextButton*, Tab> tabs[] { { &instrumentButton, Tab::instrument }, { &keyboardButton, Tab::keyboard },
  2922. { &editorButton, Tab::editor }, { &trackerButton, Tab::tracker }, { &padsButton, Tab::pads }, { &stepsButton, Tab::steps }, { &controlsButton, Tab::controls },
  2923. { &effectsButton, Tab::effects } };
  2924. for (auto [b, t] : tabs)
  2925. {
  2926. b->setClickingTogglesState (true);
  2927. b->setRadioGroupId (1901);
  2928. addAndMakeVisible (*b);
  2929. b->onClick = [this, b = b, t = t] {
  2930. if (b->getToggleState())
  2931. {
  2932. tabChosen = true;
  2933. setTab (t);
  2934. }
  2935. };
  2936. }
  2937. followButton.setButtonText (tr ("Follow the project key"));
  2938. followButton.setTooltip (tr ("The loop is moved to the project key (its length stays); off: it plays in its own key"));
  2939. followButton.onClick = [this] { clickFollowForCheck(); };
  2940. addChildComponent (followButton);
  2941. // round 190jc (SG-8): each tab's icon; (SG-7) the hide button is the round close X at the strip's left
  2942. instrumentButton.glyph = (int) ui::simplelook::Glyph::piano;
  2943. keyboardButton.glyph = (int) ui::simplelook::Glyph::keyboard;
  2944. editorButton.glyph = (int) ui::simplelook::Glyph::notes;
  2945. effectsButton.glyph = (int) ui::simplelook::Glyph::fx;
  2946. padsButton.glyph = (int) ui::simplelook::Glyph::pads;
  2947. controlsButton.glyph = (int) ui::simplelook::Glyph::dials;
  2948. stepsButton.glyph = (int) ui::simplelook::Glyph::drumMachine;
  2949. trackerButton.glyph = (int) ui::simplelook::Glyph::tracker;
  2950. hideButton.setButtonText (tr ("Hide the track dock"));
  2951. hideButton.setTooltip (tr ("Hide the track dock"));
  2952. hideButton.onClick = [this] {
  2953. shownSetting = false;
  2954. if (hooks.layoutChanged)
  2955. hooks.layoutChanged();
  2956. };
  2957. addAndMakeVisible (hideButton);
  2958. showTrack (-1);
  2959. }
  2960. SimpleDock::~SimpleDock() = default;
  2961. void SimpleDock::showTrack (int newTrack)
  2962. {
  2963. if (newTrack != track)
  2964. tabChosen = false;
  2965. track = newTrack;
  2966. refresh();
  2967. }
  2968. void SimpleDock::refresh()
  2969. {
  2970. const auto& song = engine.getSong();
  2971. insert = channel = -1;
  2972. instrumentTab = false;
  2973. playTabs = false;
  2974. padsTab = track >= 0 && simpletracks::kindOf (song, track) == simpletracks::Kind::pads;
  2975. stepsTab = track >= 0 && simpletracks::kindOf (song, track) == simpletracks::Kind::drums; // round 190lr (DS-39)
  2976. if (track >= 0)
  2977. {
  2978. const auto chain = detailchain::forTrack (song, track);
  2979. insert = chain.insert;
  2980. channel = chain.channel;
  2981. // a sound can be picked for a track that plays one instrument (not a sample, an audio clip or a drum kit)
  2982. if (channel >= 0 && channel < (int) song.channels.size())
  2983. {
  2984. const auto kind = song.channels[(std::size_t) channel].instrument;
  2985. instrumentTab = kind != InstrumentKind::audioClip && kind != InstrumentKind::sampler
  2986. && simpletracks::kindOf (song, track).value_or (simpletracks::Kind::instrument) == simpletracks::Kind::instrument;
  2987. // the track plays notes: it can be played and written (round 190ds)
  2988. const auto trackKind = simpletracks::kindOf (song, track);
  2989. playTabs = trackKind == simpletracks::Kind::instrument || trackKind == simpletracks::Kind::sampler;
  2990. }
  2991. }
  2992. instrumentButton.setVisible (instrumentTab);
  2993. keyboardButton.setVisible (playTabs);
  2994. editorButton.setVisible (playTabs);
  2995. trackerButton.setVisible (playTabs);
  2996. padsButton.setVisible (padsTab);
  2997. stepsButton.setVisible (stepsTab);
  2998. controlsTab = track >= 0 && insert > 0 && insert < (int) song.mixer.size();
  2999. controlsButton.setVisible (controlsTab);
  3000. if ((tab == Tab::instrument && ! instrumentTab) || ((tab == Tab::keyboard || tab == Tab::editor || tab == Tab::tracker) && ! playTabs) || (tab == Tab::pads && ! padsTab)
  3001. || (tab == Tab::controls && ! controlsTab) || (tab == Tab::steps && ! stepsTab))
  3002. tab = Tab::effects;
  3003. if (! tabChosen && (instrumentTab || playTabs))
  3004. tab = instrumentTab ? Tab::instrument : Tab::keyboard; // (an instrument track opens on its sound; an audio track on its effects)
  3005. else if (! tabChosen && padsTab)
  3006. tab = Tab::pads; // (round 190fo: a Sampler track opens on its pads)
  3007. else if (! tabChosen && stepsTab)
  3008. tab = Tab::steps; // (round 190lr: a Drums track opens on its step grid, as BandLab's drum machine)
  3009. else if (! tabChosen)
  3010. tab = Tab::effects;
  3011. effectsPage->show (insert);
  3012. instrumentPage->show (instrumentTab ? channel : -1);
  3013. showPage();
  3014. editorPage->show (playTabs ? track : -1, channel);
  3015. trackerPage->show (playTabs ? track : -1, channel);
  3016. padsPage->show (padsTab ? track : -1);
  3017. stepsPage->show (stepsTab ? track : -1);
  3018. controlsPage->show (controlsTab ? track : -1, channel, controlsTab ? insert : -1);
  3019. updateFollow();
  3020. resized();
  3021. repaint();
  3022. }
  3023. void SimpleDock::setTab (Tab t)
  3024. {
  3025. tabChosen = true; // (a refresh keeps a tab that was asked for)
  3026. if ((t == Tab::instrument && ! instrumentTab) || ((t == Tab::keyboard || t == Tab::editor || t == Tab::tracker) && ! playTabs) || (t == Tab::pads && ! padsTab)
  3027. || (t == Tab::controls && ! controlsTab) || (t == Tab::steps && ! stepsTab))
  3028. t = Tab::effects;
  3029. const auto padsBefore = tab == Tab::pads;
  3030. tab = t;
  3031. showPage();
  3032. if (padsBefore != (tab == Tab::pads)) // (round 190jc: the Pads tab's least height: the holder lays the dock out again)
  3033. if (auto* holder = getParentComponent())
  3034. holder->resized();
  3035. }
  3036. void SimpleDock::cycleTab()
  3037. {
  3038. tabChosen = true;
  3039. std::vector<Tab> shown;
  3040. if (instrumentTab)
  3041. shown.push_back (Tab::instrument);
  3042. if (playTabs)
  3043. shown.push_back (Tab::keyboard), shown.push_back (Tab::editor), shown.push_back (Tab::tracker);
  3044. if (padsTab)
  3045. shown.push_back (Tab::pads);
  3046. if (stepsTab)
  3047. shown.push_back (Tab::steps);
  3048. if (controlsTab)
  3049. shown.push_back (Tab::controls);
  3050. shown.push_back (Tab::effects);
  3051. const auto at = std::find (shown.begin(), shown.end(), tab);
  3052. setTab (at == shown.end() || at + 1 == shown.end() ? shown.front() : *(at + 1));
  3053. }
  3054. void SimpleDock::showPage()
  3055. {
  3056. auto& button = tab == Tab::instrument ? instrumentButton : tab == Tab::keyboard ? keyboardButton : tab == Tab::editor ? editorButton
  3057. : tab == Tab::tracker ? trackerButton
  3058. : tab == Tab::pads ? padsButton
  3059. : tab == Tab::steps ? stepsButton
  3060. : tab == Tab::controls ? controlsButton
  3061. : effectsButton;
  3062. button.setToggleState (true, juce::dontSendNotification);
  3063. if (tab == Tab::keyboard && keyboardPage == nullptr)
  3064. {
  3065. keyboardPage = makeKeyboardPanel (engine, [this] { return channel; }, [this] { return trackColourNow(); });
  3066. addChildComponent (*keyboardPage);
  3067. resized();
  3068. }
  3069. if (tab == Tab::keyboard && channel >= 0 && engine.getSelectedChannel() != channel)
  3070. engine.setSelectedChannel (channel); // (the typing keys play the selected channel: this track)
  3071. instrumentPage->setVisible (tab == Tab::instrument);
  3072. effectsPage->setVisible (tab == Tab::effects);
  3073. editorPage->setVisible (tab == Tab::editor);
  3074. trackerPage->setVisible (tab == Tab::tracker);
  3075. padsPage->setVisible (tab == Tab::pads);
  3076. stepsPage->setVisible (tab == Tab::steps);
  3077. controlsPage->setVisible (tab == Tab::controls);
  3078. if (keyboardPage != nullptr)
  3079. keyboardPage->setVisible (tab == Tab::keyboard);
  3080. }
  3081. void SimpleDock::showKeyboard()
  3082. {
  3083. tabChosen = true;
  3084. setTab (Tab::keyboard);
  3085. }
  3086. void SimpleDock::editorTakenBack() { editorPage->takenBackByPanel(); }
  3087. juce::Component* SimpleDock::trackerForSnapshot() { return trackerPage != nullptr ? trackerPage->trackerComponent() : nullptr; }
  3088. void SimpleDock::padsLoadForCheck (int pad, const juce::File& file) { padsPage->loadFileForCheck (pad, file); }
  3089. void SimpleDock::padsSelectForCheck (int pad) { padsPage->select (pad); }
  3090. void SimpleDock::padsModeForCheck (int mode) { padsPage->setModeForCheck (mode); }
  3091. void SimpleDock::padsKnobForCheck (int knob, float v) { padsPage->turnForCheck (knob, v); }
  3092. void SimpleDock::padsRegionForCheck (float start, float end) { padsPage->setRegionForCheck (start, end); }
  3093. void SimpleDock::padsNormalizeForCheck() { padsPage->normalizeForCheck(); }
  3094. void SimpleDock::padsHitForCheck (int pad) { padsPage->hit (pad); }
  3095. juce::Component* SimpleDock::padsCtaForCheck (int k) { return padsPage->ctaForCheck (k); }
  3096. bool SimpleDock::padsRecordingForCheck() const { return padsPage->recordingForCheck(); }
  3097. void SimpleDock::padsRecordForCheck() { padsPage->startRecordingForCheck(); }
  3098. void SimpleDock::padsRecordingLookForSnapshot (bool on) { padsPage->recordingLookForSnapshot (on); }
  3099. void SimpleDock::controlsTurnForCheck (int knob, float value) { controlsPage->turnForCheck (knob, value); }
  3100. juce::String SimpleDock::controlsNameForCheck (int knob) const { return controlsPage->nameForCheck (knob); }
  3101. float SimpleDock::controlsValueForCheck (int knob) const { return controlsPage->valueForCheck (knob); }
  3102. void SimpleDock::controlsEditingForSnapshot (bool on) { controlsPage->setEditingForSnapshot (on); }
  3103. juce::PopupMenu SimpleDock::controlsMenuForSnapshot (int knob) { return controlsPage->remapMenu (knob); }
  3104. void SimpleDock::padsPressForSnapshot (int pad, float amount) { padsPage->pressForSnapshot (pad, amount); }
  3105. void SimpleDock::padsWatchForCheck() { padsPage->watchPlayback(); }
  3106. float SimpleDock::padsPressForCheck (int pad) const { return padsPage->pressShownForCheck (pad); }
  3107. void SimpleDock::padsDragForCheck (int from, int to, bool copy) { padsPage->dragPadForCheck (from, to, copy); }
  3108. void SimpleDock::padsUpdateForCheck() { padsPage->update(); }
  3109. juce::PopupMenu SimpleDock::padMenuForSnapshot (int pad) { return padsPage->padMenuForSnapshot (pad); }
  3110. juce::PopupMenu SimpleDock::kitMenuForSnapshot() { return padsPage->kitMenuForSnapshot(); }
  3111. bool SimpleDock::saveKitForCheck (const juce::String& name) { return padsPage->saveKit (name); }
  3112. bool SimpleDock::openKitForCheck (const juce::File& file) { return padsPage->openKit (file); }
  3113. bool SimpleDock::renameKitForCheck (const juce::File& file, const juce::String& name) { return PadsPage::renameKit (file, name); }
  3114. // Round 190ih (PLAN R14, DS-9): BandLab's dock shows "Input Level" with a slim bar on the right of its header
  3115. // (bandlab190p shots/22-sampler-kits.png). Here it shows while the track's insert is armed to record from an input
  3116. // (no input = no level), fed by the main window's 30 Hz timer only while the dock shows; only the bar repaints, and
  3117. // only when its drawn width changes.
  3118. bool SimpleDock::inputMeterShown() const
  3119. {
  3120. if (inputMeterForced)
  3121. return true;
  3122. const auto& song = engine.getSong();
  3123. if (track < 0 || insert <= 0 || insert >= (int) song.mixer.size() || ! engine.isInsertArmed (insert) || song.mixer[(std::size_t) insert].inputChannel < 0)
  3124. return false;
  3125. const auto kind = simpletracks::kindOf (song, track);
  3126. return kind && simpletracks::isAudioKind (*kind);
  3127. }
  3128. juce::Rectangle<int> SimpleDock::inputMeterArea() const
  3129. {
  3130. const auto right = followButton.isVisible() ? followButton.getX() - 10 : getWidth() - 10; // (round 190jj merge: 190jc moved the hide button to the left)
  3131. // the label ("Input Level") takes its text's width, at least 70 px: "Nível de entrada" (pt-BR) was cut to "Nível de en..." (190nx)
  3132. const auto label = juce::jmax (70, juce::GlyphArrangement::getStringWidthInt (font (type::small, true), tr ("Input Level")) + 6);
  3133. const auto width = 162 + label;
  3134. return { right - width, 0, width, stripHeight() };
  3135. }
  3136. juce::Rectangle<int> SimpleDock::inputMeterBar() const
  3137. {
  3138. const auto a = inputMeterArea();
  3139. return { a.getRight() - 42 - 110, a.getCentreY() - 2, 110, 4 };
  3140. }
  3141. // round 190ld (DS-9, BandLab B22: a round headphones switch right of the input bar): hear the input while recording
  3142. juce::Rectangle<int> SimpleDock::monitorButton() const
  3143. {
  3144. const auto a = inputMeterArea();
  3145. const auto d = juce::jmin (32, a.getHeight() - 4);
  3146. return { a.getRight() - d, a.getCentreY() - d / 2, d, d };
  3147. }
  3148. bool SimpleDock::monitoring() const
  3149. {
  3150. const auto& song = engine.getSong();
  3151. if (insert <= 0 || insert >= (int) song.mixer.size())
  3152. return false;
  3153. const auto mode = song.mixer[(std::size_t) insert].monitor;
  3154. return mode == InputMonitor::on || (mode != InputMonitor::off && engine.isInsertArmed (insert));
  3155. }
  3156. juce::Colour SimpleDock::trackColourNow() const
  3157. {
  3158. const auto& song = engine.getSong();
  3159. if (track < 0)
  3160. return theme::colour::accent;
  3161. const auto own = track < (int) song.playlistTracks.size() ? song.playlistTracks[(std::size_t) track].colour : 0u;
  3162. const auto kind = simpletracks::kindOf (song, track);
  3163. return own != 0 ? juce::Colour (own).withAlpha (1.0f) : kind ? juce::Colour (simpletracks::defaultColour (*kind)).withAlpha (1.0f) : theme::colour::accent;
  3164. }
  3165. void SimpleDock::tickInputMeter()
  3166. {
  3167. if (! isShowing())
  3168. return;
  3169. if (padsPage != nullptr && padsPage->isVisible()) // round 190jj: the song's notes press the pads (BandLab)
  3170. padsPage->watchPlayback();
  3171. if (stepsPage != nullptr && stepsPage->isVisible()) // round 190lr: the step the song plays (only its two columns repaint)
  3172. stepsPage->watchPlayback();
  3173. const auto shown = inputMeterShown();
  3174. auto level = 0.0f;
  3175. if (shown && insert > 0)
  3176. {
  3177. const auto peak = juce::jmax (engine.takeInputPeak (insert, 0), engine.takeInputPeak (insert, 1));
  3178. const auto db = juce::Decibels::gainToDecibels (peak, -60.0f);
  3179. level = juce::jmax ((db + 60.0f) / 60.0f, inputLevel * 0.86f); // (a quick fall, as the Mixer's)
  3180. if (level < 0.01f)
  3181. level = 0.0f;
  3182. }
  3183. const auto width = juce::roundToInt (level * (float) inputMeterBar().getWidth());
  3184. if (shown != inputMeterWasShown)
  3185. {
  3186. inputMeterWasShown = shown;
  3187. repaint (getLocalBounds().withHeight (stripHeight())); // (the record hint moves left of it)
  3188. }
  3189. else if (width != juce::roundToInt (inputLevel * (float) inputMeterBar().getWidth()))
  3190. repaint (inputMeterBar().expanded (1));
  3191. inputLevel = level;
  3192. }
  3193. bool SimpleDock::recordHintShown() const
  3194. {
  3195. const auto& song = engine.getSong();
  3196. if (track < 0 || insert <= 0 || insert >= (int) song.mixer.size() || ! engine.isInsertArmed (insert) || song.mixer[(std::size_t) insert].inputChannel < 0)
  3197. return false;
  3198. const auto kind = simpletracks::kindOf (song, track);
  3199. return kind && simpletracks::isAudioKind (*kind) && *kind != simpletracks::Kind::audio;
  3200. }
  3201. juce::Component* SimpleDock::stepsComponentForSnapshot() { return stepsPage.get(); }
  3202. int SimpleDock::stepsRowsForCheck() const { return stepsPage->rowCountForCheck(); }
  3203. int SimpleDock::stepsCountForCheck() const { return stepsPage->stepCountForCheck(); }
  3204. void SimpleDock::stepsClickForCheck (int row, int step) { stepsPage->clickStepForCheck (row, step); }
  3205. void SimpleDock::stepsLetterForCheck (int letter) { stepsPage->pickLetterForCheck (letter); }
  3206. void SimpleDock::stepsAddClipForCheck() { stepsPage->addClipForCheck(); }
  3207. int SimpleDock::stepsMessagesShownForCheck() const { return stepsPage->messagesShownForCheck(); }
  3208. void SimpleDock::stepsLengthForCheck (int bars) { stepsPage->setLengthForCheck (bars); }
  3209. void SimpleDock::stepsSwingForCheck (float v) { stepsPage->setSwingForCheck (v); }
  3210. void SimpleDock::stepsPreviewForCheck() { stepsPage->previewForCheck(); }
  3211. bool SimpleDock::stepsPreviewingForCheck() const { return stepsPage->previewingForCheck(); }
  3212. int SimpleDock::stepsPatternForCheck() const { return stepsPage->patternForCheck(); }
  3213. int SimpleDock::stepsPlayingStepForCheck() const { return stepsPage->playingStepForCheck(); }
  3214. void SimpleDock::stepsPlayingStepForSnapshot (int step) { stepsPage->playingStepForSnapshot (step); }
  3215. juce::PopupMenu SimpleDock::stepsLengthMenuForSnapshot() { return stepsPage->lengthMenuForSnapshot(); }
  3216. void SimpleDock::stepsWatchForCheck() { stepsPage->watchPlayback(); }
  3217. void SimpleDock::stepsVelocityForCheck (int row, int step, float v) { stepsPage->velocityForCheck (row, step, v); }
  3218. void SimpleDock::stepsVelocityToolForSnapshot (bool on) { stepsPage->velocityToolForSnapshot (on); }
  3219. int SimpleDock::stepsChannelForKey (int keyCode)
  3220. {
  3221. if (! stepsTab || tab != Tab::steps)
  3222. return -1;
  3223. const auto channel = stepsPage->channelForKey (keyCode);
  3224. if (channel >= 0)
  3225. stepsPage->lightRow (simplesteps::rowForKey (keyCode));
  3226. return channel;
  3227. }
  3228. void SimpleDock::lightPad (int pad)
  3229. {
  3230. if (padsTab && tab == Tab::pads)
  3231. padsPage->lightPad (pad);
  3232. }
  3233. void SimpleDock::releaseEditor() { editorPage->release(); }
  3234. bool SimpleDock::isEditorDocked() const noexcept { return editorPage->docked(); }
  3235. std::vector<int> SimpleDock::trackAudioClips() const
  3236. {
  3237. std::vector<int> out;
  3238. const auto& song = engine.getSong();
  3239. for (int i = 0; i < (int) song.playlist.size(); ++i)
  3240. if (const auto& c = song.playlist[(std::size_t) i]; c.kind == ClipKind::audio && c.track == track && track >= 0)
  3241. out.push_back (i);
  3242. return out;
  3243. }
  3244. // "Loop key: G minor · moved −5" and the switch, for an audio track whose loop has a known key (round 190ds)
  3245. void SimpleDock::updateFollow()
  3246. {
  3247. const auto& song = engine.getSong();
  3248. std::optional<keyfollow::LoopKey> key;
  3249. bool all = true;
  3250. int shift = 0;
  3251. for (const auto i : trackAudioClips())
  3252. {
  3253. const auto& c = song.playlist[(std::size_t) i];
  3254. if (const auto k = keyfollow::loopKeyOf (song, c.channel); k && ! key)
  3255. {
  3256. key = k;
  3257. shift = keyfollow::shiftOf (song, c);
  3258. }
  3259. all = all && c.followKey;
  3260. }
  3261. const auto show = key.has_value() && simpletracks::kindOf (song, track) == simpletracks::Kind::audio;
  3262. followButton.setVisible (show);
  3263. followText.clear();
  3264. if (show)
  3265. {
  3266. followButton.setToggleState (all, juce::dontSendNotification);
  3267. const auto name = utf8 (projectkey::rootName (key->root)) + " " + (key->minor ? tr ("minor") : tr ("major"));
  3268. followText = tr ("Loop key: {0}", { name }) + glyph (" \xc2\xb7 ")
  3269. + (! projectkey::get (song) ? tr ("no project key") : ! all ? tr ("plays in its own key")
  3270. : shift == 0 ? tr ("already in key") : tr ("moved {0} semitones", { (shift > 0 ? "+" : "") + juce::String (shift) }));
  3271. }
  3272. }
  3273. bool SimpleDock::followShownForCheck() const { return followButton.isVisible(); }
  3274. void SimpleDock::clickFollowForCheck()
  3275. {
  3276. const auto clips = trackAudioClips();
  3277. bool all = ! clips.empty();
  3278. for (const auto i : clips)
  3279. all = all && engine.getSong().playlist[(std::size_t) i].followKey;
  3280. engine.editSong ([clips, on = ! all] (Song& s) { keyfollow::setFollow (s, clips, on); });
  3281. updateFollow();
  3282. repaint();
  3283. }
  3284. void SimpleDock::clickFoldForCheck (bool on) { editorPage->clickFold (on); }
  3285. juce::Component* SimpleDock::keyboardPanelForSnapshot()
  3286. {
  3287. setTab (Tab::keyboard);
  3288. return keyboardPage.get();
  3289. }
  3290. int SimpleDock::heightFor (int available) const noexcept
  3291. {
  3292. // round 190jc (SG-11): the Pads tab needs its 4 x 44 px pads (Large controls: 48) under the strip
  3293. const auto least = tab == Tab::pads && padsTab ? stripHeight() + 4 * ui::simplelook::px (44, 48) + 12 + 12 + 8 : minHeight;
  3294. return juce::jlimit (std::min (least, available / 2), std::max (least, available * 6 / 10), juce::jmax (least, preferredHeight));
  3295. }
  3296. void SimpleDock::paint (juce::Graphics& g)
  3297. {
  3298. g.fillAll (colour::bg1);
  3299. auto strip = getLocalBounds().withHeight (stripHeight());
  3300. g.setColour (colour::bg3);
  3301. g.fillRect (strip);
  3302. g.setColour (colour::border);
  3303. g.fillRect (0, 0, getWidth(), 1);
  3304. g.fillRect (0, stripHeight() - 1, getWidth(), 1);
  3305. // the resize grip in the middle of the top edge
  3306. g.setColour (colour::borderStrong);
  3307. g.fillRoundedRectangle ((float) getWidth() * 0.5f - 16.0f, 2.0f, 32.0f, 2.0f, 1.0f);
  3308. const auto& song = engine.getSong();
  3309. // round 190dg: the track's chain preset, right of the tabs (the header's FX button is too small to name it)
  3310. auto rightEdge = followButton.isVisible() ? followButton.getX() - 10 : getWidth() - 10;
  3311. if (inputMeterShown()) // round 190ih: "Input Level" and its bar (BandLab's dock header)
  3312. {
  3313. const auto area = inputMeterArea(), bar = inputMeterBar();
  3314. g.setColour (colour::textPrimary);
  3315. g.setFont (font (type::small, true));
  3316. g.drawText (tr ("Input Level"), area.withRight (bar.getX() - 10), juce::Justification::centredRight, true);
  3317. fillRoundRect (g, bar.toFloat(), 2.0f, colour::bg1);
  3318. if (const auto w = juce::roundToInt (inputLevel * (float) bar.getWidth()); w > 0)
  3319. {
  3320. const auto db = inputLevel * 60.0f - 60.0f;
  3321. fillRoundRect (g, bar.withWidth (w).toFloat(), 2.0f, db >= -0.5f ? colour::meterClip : db >= -9.0f ? colour::meterMid : colour::meterLow);
  3322. }
  3323. // the monitor switch (round 190ld): lit while the input is heard
  3324. const auto button = monitorButton().toFloat();
  3325. const auto on = monitoring();
  3326. g.setColour (on ? colour::accent : colour::bg4);
  3327. g.fillEllipse (button);
  3328. ui::simplelook::drawGlyph (g, ui::simplelook::Glyph::headphones, button.reduced (button.getWidth() * 0.28f), on ? colour::onAccent : colour::textPrimary);
  3329. rightEdge = area.getX() - 10;
  3330. }
  3331. if (followButton.isVisible()) // round 190ds: the loop's key and what following does
  3332. {
  3333. g.setColour (colour::textSecondary);
  3334. g.setFont (font (type::small));
  3335. const auto area = strip.withLeft (effectsButton.getRight() + 16).withRight (rightEdge);
  3336. g.drawText (followText, area, juce::Justification::centredRight, true);
  3337. }
  3338. else if (recordHintShown())
  3339. {
  3340. // round 190fo: a track armed to record from an input (the original's mobile app warns the same way)
  3341. const auto area = strip.withLeft (effectsButton.getRight() + 16).withRight (rightEdge);
  3342. g.setColour (colour::warning);
  3343. g.setFont (font (type::small));
  3344. g.drawFittedText (tr ("Recording: wear headphones, so the microphone does not pick up the playback"), area, juce::Justification::centredRight, 1, 0.8f);
  3345. }
  3346. else if (insert > 0 && insert < (int) song.mixer.size() && ! song.mixer[(std::size_t) insert].chainPreset.empty())
  3347. {
  3348. auto name = utf8 (song.mixer[(std::size_t) insert].chainPreset);
  3349. if (! chains::unchanged (song, insert))
  3350. name << " " << tr ("(edited)");
  3351. const auto area = strip.withLeft (effectsButton.getRight() + 16).withRight (rightEdge);
  3352. g.setColour (colour::textSecondary);
  3353. g.setFont (font (type::small));
  3354. g.drawText (tr ("Preset") + glyph (": ") + name, area, juce::Justification::centredRight, true);
  3355. }
  3356. auto text = strip.withLeft (hideButton.getRight() + 10).withRight (instrumentButton.isVisible() ? instrumentButton.getX() - 12
  3357. : keyboardButton.isVisible() ? keyboardButton.getX() - 12
  3358. : padsButton.isVisible() ? padsButton.getX() - 12
  3359. : controlsButton.isVisible() ? controlsButton.getX() - 12
  3360. : effectsButton.getX() - 12);
  3361. if (track < 0)
  3362. {
  3363. g.setColour (colour::textSecondary);
  3364. g.setFont (font (type::body));
  3365. g.drawText (tr ("No track selected"), text, juce::Justification::centredLeft, true);
  3366. return;
  3367. }
  3368. const auto own = track < (int) song.playlistTracks.size() ? song.playlistTracks[(std::size_t) track].colour : 0u;
  3369. const auto kind = simpletracks::kindOf (song, track);
  3370. const auto hue = own != 0 ? juce::Colour (own) : kind ? juce::Colour (simpletracks::defaultColour (*kind)) : colour::textSecondary;
  3371. // round 190jc (SG-7): the track's type icon in its colour (BandLab's Track View header), else the colour bar
  3372. const auto ownIcon = track < (int) song.playlistTracks.size() ? trackicons::iconFor (song.playlistTracks[(std::size_t) track].icon) : trackicons::Icon::none;
  3373. const auto icon = ownIcon != trackicons::Icon::none ? ownIcon : kind ? simpletracks::iconOf (*kind) : trackicons::Icon::none;
  3374. if (icon != trackicons::Icon::none)
  3375. {
  3376. const auto size = (float) ui::simplelook::px (16, 20);
  3377. ui::drawTrackIcon (g, icon, juce::Rectangle<float> ((float) text.getX(), (float) strip.getCentreY() - size * 0.5f, size, size),
  3378. ui::simplelook::readableOn (hue, colour::bg3, 3.0f));
  3379. text.removeFromLeft ((int) size + 8);
  3380. }
  3381. else
  3382. {
  3383. g.setColour (hue);
  3384. g.fillRoundedRectangle ((float) text.getX(), (float) strip.getCentreY() - 7.0f, 4.0f, 14.0f, 2.0f);
  3385. text.removeFromLeft (12);
  3386. }
  3387. g.setColour (colour::textPrimary);
  3388. g.setFont (font (ui::simplelook::largeControls() ? type::title : type::body, true));
  3389. const auto title = trackTitle (song, track);
  3390. const auto titleWidth = juce::jmin (text.getWidth(), juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), title) + 4);
  3391. g.drawText (title, text.removeFromLeft (titleWidth), juce::Justification::centredLeft, true);
  3392. if (kind)
  3393. {
  3394. g.setColour (colour::textSecondary);
  3395. g.setFont (font (type::small));
  3396. g.drawText (glyph ("\xc2\xb7 ") + tr (simpletracks::defaultName (*kind)), text.withTrimmedLeft (6), juce::Justification::centredLeft, true);
  3397. }
  3398. }
  3399. int SimpleDock::stripHeight() { return ui::simplelook::px (36, 48); }
  3400. void SimpleDock::lookChanged()
  3401. {
  3402. refresh(); // (lays the strip and the pages out again)
  3403. padsPage->resized(); // (the pads' size floor; its bounds may stay the same)
  3404. if (keyboardPage != nullptr)
  3405. keyboardPage->resized();
  3406. if (auto* holder = getParentComponent())
  3407. holder->resized();
  3408. }
  3409. void SimpleDock::StripButton::paintButton (juce::Graphics& g, bool over, bool down)
  3410. {
  3411. using namespace theme;
  3412. const auto r = getLocalBounds().toFloat();
  3413. if (glyph < 0) // BandLab's round close X (the same action as the old caret: hides the dock)
  3414. {
  3415. const auto d = juce::jmin (r.getWidth(), r.getHeight());
  3416. const auto circle = juce::Rectangle<float> (d, d).withCentre (r.getCentre());
  3417. g.setColour (down ? colour::bg6 : over ? colour::bg5 : colour::bg4);
  3418. g.fillEllipse (circle);
  3419. ui::simplelook::drawGlyph (g, ui::simplelook::Glyph::cross, circle.withSizeKeepingCentre (d * 0.34f, d * 0.34f), colour::textPrimary, 1.5f);
  3420. return;
  3421. }
  3422. const auto on = getToggleState() && ! lone;
  3423. if (! lone)
  3424. {
  3425. // one pill per tab, joined into a segmented control: rounded only at the group's ends
  3426. const auto left = ! isConnectedOnLeft(), right = ! isConnectedOnRight();
  3427. const auto fill = on ? (down ? colour::accentPressed : over ? colour::accentHover : colour::accent) : down ? colour::bg6 : over ? colour::bg5 : colour::bg4;
  3428. juce::Path p;
  3429. p.addRoundedRectangle (r.getX(), r.getY(), r.getWidth() - (right ? 0.0f : 1.0f), r.getHeight(), radius::lg, radius::lg, left, right, left, right);
  3430. g.setColour (fill);
  3431. g.fillPath (p);
  3432. }
  3433. const auto f = font (ui::simplelook::largeControls() ? type::title : type::body, on || lone);
  3434. const auto text = getButtonText();
  3435. const auto iconSize = (float) ui::simplelook::px (14, 18), gap = 6.0f;
  3436. const auto textWidth = juce::GlyphArrangement::getStringWidth (f, text);
  3437. const auto total = juce::jmin (r.getWidth() - 12.0f, iconSize + gap + textWidth);
  3438. auto content = lone ? r.withTrimmedLeft (4.0f).withWidth (total) : r.withSizeKeepingCentre (total, r.getHeight());
  3439. const auto ink = on ? colour::onAccent : lone ? colour::textPrimary : over ? colour::textPrimary : colour::textSecondary;
  3440. ui::simplelook::drawGlyph (g, (ui::simplelook::Glyph) glyph, content.removeFromLeft (iconSize).withSizeKeepingCentre (iconSize, iconSize), ink, 1.4f);
  3441. content.removeFromLeft (gap);
  3442. g.setColour (ink);
  3443. g.setFont (f);
  3444. g.drawFittedText (text, content.toNearestInt(), juce::Justification::centredLeft, 1, 0.8f);
  3445. if (lone) // a section title: a short accent line under it
  3446. {
  3447. g.setColour (colour::accent);
  3448. g.fillRoundedRectangle (r.getX() + 4.0f, r.getBottom() - 2.0f, 24.0f, 2.0f, 1.0f);
  3449. }
  3450. }
  3451. void SimpleDock::resized()
  3452. {
  3453. // round 190jc (SG-7, SG-8): the round close X at the left (28 px; Large controls 40), tabs 28 px tall (40) with icons
  3454. const auto stripAll = getLocalBounds().withHeight (stripHeight());
  3455. const auto closeSize = ui::simplelook::px (28, 40);
  3456. hideButton.setBounds (juce::Rectangle<int> (8, (stripAll.getHeight() - closeSize) / 2, closeSize, closeSize));
  3457. const auto tabHeight = ui::simplelook::px (28, 40), tabWidth = ui::simplelook::px (112, 136);
  3458. auto strip = stripAll.withSizeKeepingCentre (stripAll.getWidth(), tabHeight);
  3459. followButton.setBounds (strip.removeFromRight (190).withTrimmedRight (10).withSizeKeepingCentre (180, juce::jmin (24, tabHeight)));
  3460. // the tabs sit after the track's name, left of the middle
  3461. const auto count = 1 + (instrumentTab ? 1 : 0) + (playTabs ? 3 : 0) + (padsTab ? 1 : 0) + (stepsTab ? 1 : 0) + (controlsTab ? 1 : 0);
  3462. auto tabs = strip.withLeft (juce::jmin (300, getWidth() / 3)).withWidth (tabWidth * count);
  3463. std::vector<juce::TextButton*> shown;
  3464. if (instrumentTab)
  3465. shown.push_back (&instrumentButton);
  3466. if (playTabs)
  3467. shown.push_back (&keyboardButton), shown.push_back (&editorButton), shown.push_back (&trackerButton);
  3468. if (padsTab)
  3469. shown.push_back (&padsButton);
  3470. if (stepsTab)
  3471. shown.push_back (&stepsButton);
  3472. if (controlsTab)
  3473. shown.push_back (&controlsButton);
  3474. shown.push_back (&effectsButton);
  3475. for (std::size_t i = 0; i < shown.size(); ++i)
  3476. {
  3477. shown[i]->setConnectedEdges ((i > 0 ? juce::Button::ConnectedOnLeft : 0) | (i + 1 < shown.size() ? juce::Button::ConnectedOnRight : 0));
  3478. static_cast<StripButton*> (shown[i])->lone = shown.size() == 1; // (round 190jc: an audio track's only tab is a title)
  3479. shown[i]->setBounds (tabs.removeFromLeft (tabWidth));
  3480. }
  3481. const auto body = getLocalBounds().withTrimmedTop (stripHeight());
  3482. effectsPage->setBounds (body);
  3483. instrumentPage->setBounds (body);
  3484. editorPage->setBounds (body);
  3485. trackerPage->setBounds (body);
  3486. padsPage->setBounds (body);
  3487. stepsPage->setBounds (body);
  3488. controlsPage->setBounds (body);
  3489. if (keyboardPage != nullptr)
  3490. keyboardPage->setBounds (body);
  3491. }
  3492. void SimpleDock::mouseMove (const juce::MouseEvent& e)
  3493. {
  3494. setMouseCursor (e.y < edgeHeight ? juce::MouseCursor::UpDownResizeCursor : juce::MouseCursor::NormalCursor);
  3495. }
  3496. void SimpleDock::mouseDown (const juce::MouseEvent& e)
  3497. {
  3498. if (inputMeterShown() && insert > 0 && monitorButton().contains (e.getPosition()) && ! e.mods.isPopupMenu())
  3499. {
  3500. // hear the input (Monitor On) / don't (Off); the Mixer's input menu has the other modes
  3501. engine.editSong ([i = insert, on = ! monitoring()] (Song& s) {
  3502. if (i < (int) s.mixer.size())
  3503. s.mixer[(std::size_t) i].monitor = on ? InputMonitor::on : InputMonitor::off;
  3504. });
  3505. repaint (monitorButton().expanded (2));
  3506. return;
  3507. }
  3508. resizing = e.y < edgeHeight;
  3509. dragStartHeight = getHeight();
  3510. }
  3511. void SimpleDock::mouseDrag (const juce::MouseEvent& e)
  3512. {
  3513. if (! resizing)
  3514. return;
  3515. const auto wanted = juce::jmax (minHeight, dragStartHeight - e.getDistanceFromDragStartY());
  3516. if (wanted != preferredHeight)
  3517. {
  3518. preferredHeight = wanted;
  3519. if (auto* parent = getParentComponent())
  3520. parent->resized();
  3521. }
  3522. }
  3523. void SimpleDock::mouseUp (const juce::MouseEvent&)
  3524. {
  3525. if (resizing && hooks.layoutChanged)
  3526. hooks.layoutChanged(); // (saves the height)
  3527. resizing = false;
  3528. }
  3529. // --- the user's own chain presets ------------------------------------------------------------------------------------
  3530. juce::File SimpleDock::userPresetFolder() { return platform::documentsFolder().getChildFile ("LYNX/Chain presets"); }
  3531. // round 190dg: the favourite chain presets, one name a line, in the order they were starred
  3532. juce::File SimpleDock::favouritesFile() { return userPresetFolder().getChildFile ("Favourites.txt"); }
  3533. juce::StringArray SimpleDock::favouritePresets()
  3534. {
  3535. auto lines = juce::StringArray::fromLines (favouritesFile().loadFileAsString());
  3536. lines.trim();
  3537. lines.removeEmptyStrings();
  3538. lines.removeDuplicates (false);
  3539. return lines;
  3540. }
  3541. bool SimpleDock::setFavouritePreset (const juce::String& name, bool on)
  3542. {
  3543. auto lines = favouritePresets();
  3544. if (on)
  3545. lines.addIfNotAlreadyThere (name.trim());
  3546. else
  3547. lines.removeString (name.trim());
  3548. favouritesFile().getParentDirectory().createDirectory();
  3549. return favouritesFile().replaceWithText (lines.joinIntoString ("\n") + (lines.isEmpty() ? "" : "\n"));
  3550. }
  3551. bool SimpleDock::saveUserPreset (AudioEngine& engine, int insert, const juce::String& rawName)
  3552. {
  3553. const auto name = juce::File::createLegalFileName (rawName.trim());
  3554. if (name.isEmpty() || insert < 0 || insert >= (int) engine.getSong().mixer.size())
  3555. return false;
  3556. engine.capturePluginStates(); // the plugins' current settings go into the preset
  3557. const auto file = userPresetFolder().getChildFile (name + ProjectFile::mixerTrackStateExtension);
  3558. file.getParentDirectory().createDirectory();
  3559. const auto state = chains::stateOf (engine.getSong().mixer[(std::size_t) insert], name.toStdString());
  3560. if (! file.replaceWithText (ProjectFile::mixerTrackStateToJson (state)))
  3561. return false;
  3562. engine.editSong ([insert, n = name.toStdString()] (Song& s) {
  3563. if (insert < (int) s.mixer.size())
  3564. s.mixer[(std::size_t) insert].chainPreset = n;
  3565. });
  3566. return true;
  3567. }
  3568. bool SimpleDock::loadUserPreset (AudioEngine& engine, int insert, const juce::File& file)
  3569. {
  3570. juce::String error;
  3571. auto state = ProjectFile::mixerTrackStateFromJson (file.loadFileAsString(), error);
  3572. if (! state || insert < 0 || insert >= (int) engine.getSong().mixer.size())
  3573. return false;
  3574. const auto name = file.getFileNameWithoutExtension().toStdString();
  3575. engine.editSongStructural ([insert, &state, &name] (Song& s) { chains::applyChain (s, insert, state->effects, state->chainBlend, name); });
  3576. return true;
  3577. }
  3578. // --- tests and --simplefxshot ----------------------------------------------------------------------------------------
  3579. int SimpleDock::cardCountForCheck() const { return effectsPage->cardCount(); }
  3580. int SimpleDock::oneKnobCardsForCheck() const { return effectsPage->oneKnobCards(); }
  3581. juce::PopupMenu SimpleDock::presetMenuForSnapshot() { return effectsPage->presetMenu(); }
  3582. void SimpleDock::stepPresetForCheck (int delta) { effectsPage->stepPreset (delta); }
  3583. void SimpleDock::bypassChainForCheck() { effectsPage->bypassForCheck(); }
  3584. bool SimpleDock::bypassLitForCheck() const { return effectsPage->bypassLitForCheck(); }
  3585. juce::PopupMenu SimpleDock::addMenuForSnapshot() { return effectsPage->addMenu(); }
  3586. void SimpleDock::setFontsForSnapshot (std::vector<sf::IndexedFont> fonts)
  3587. {
  3588. instrumentPage->setFonts (std::move (fonts), true);
  3589. instrumentPage->setSource (InstrumentPage::From::fonts);
  3590. }
  3591. void SimpleDock::setPluginsForSnapshot (std::vector<soundlib::InstalledPlugin> plugins)
  3592. {
  3593. instrumentPage->setPlugins (std::move (plugins));
  3594. instrumentPage->setSource (InstrumentPage::From::plugins);
  3595. }
  3596. void SimpleDock::showCategoryForSnapshot (int category) { instrumentPage->pickCategory (category); }
  3597. int SimpleDock::soundRowsForCheck() const { return instrumentPage->rowCount(); }
  3598. juce::String SimpleDock::soundNameForCheck() const { return instrumentPage->shownName(); }
  3599. void SimpleDock::clickSoundForCheck (int row) { instrumentPage->clickRow (row, false); }
  3600. void SimpleDock::stepSoundForCheck (int delta) { instrumentPage->stepSound (delta); }
  3601. void SimpleDock::turnKnobForCheck (int card, float value) { effectsPage->turnForCheck (card, value); }
  3602. void SimpleDock::moveCardForCheck (int card, int delta) { effectsPage->move (card, delta); }
  3603. void SimpleDock::removeCardForCheck (int card) { effectsPage->remove (card); }
  3604. void SimpleDock::addOneKnobForCheck (int goal) { effectsPage->addOneKnob (goal); }
  3605. void SimpleDock::setBlendForCheck (float value) { effectsPage->blendForCheck (value); }
  3606. void SimpleDock::setReverbForCheck (float value) { effectsPage->reverbForCheck (value); }
  3607. void SimpleDock::setEchoForCheck (float value) { effectsPage->echoForCheck (value); }
  3608. void SimpleDock::duckUnderForCheck (int triggerInsert) { effectsPage->duckForCheck (triggerInsert); }
  3609. juce::PopupMenu SimpleDock::duckMenuForCheck() { return effectsPage->duckMenuForCheck(); }
  3610. juce::String SimpleDock::duckButtonTextForCheck() const { return effectsPage->duckButtonTextForCheck(); }
  3611. juce::Rectangle<int> SimpleDock::cardBoundsForSnapshot (int card) const
  3612. {
  3613. const auto* c = effectsPage->cardForSnapshot (card);
  3614. return c != nullptr ? getLocalArea (c, c->getLocalBounds()) : juce::Rectangle<int>();
  3615. }
  3616. void SimpleDock::setSearchForSnapshot (const juce::String& text) { instrumentPage->searchFor (text); }
  3617. } // namespace lynx