MixerComponent.cpp 253 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653
  1. #include "ui/FlMods.h"
  2. #include "platform/Paths.h"
  3. #include "ui/ColourPicker.h"
  4. #include "ui/FileChoosers.h"
  5. #include "ui/MixerComponent.h"
  6. #include "ui/SlotWatch.h"
  7. #include "core/ValueMath.h"
  8. #include "ui/UiTrace.h"
  9. #include "ui/TextCache.h"
  10. #include "core/Patcherize.h"
  11. #include "core/FlpImport.h"
  12. #include "engine/FlStudio.h"
  13. #include "core/FlEffects.h"
  14. #include "core/ProjectContents.h"
  15. #include "core/FruityVocoder.h"
  16. #include "core/LiveInput.h"
  17. #include "core/HardwareOutput.h"
  18. #include "core/MixerOps.h"
  19. #include "core/ProjectSafety.h"
  20. #include "core/Templates.h"
  21. #include "core/RackOps.h"
  22. #include "ui/AutomationUi.h"
  23. #include "ui/BrowserComponent.h"
  24. #include "ui/ExportDialog.h"
  25. #include <cmath>
  26. #include <complex>
  27. #include "core/Biquad.h"
  28. #include "core/Effects.h"
  29. #include "engine/Text.h"
  30. #include "engine/ProjectFile.h"
  31. #include <numeric>
  32. #include "ui/FacetEqEditor.h"
  33. #include "ui/ParametricEqEditor.h"
  34. #include "ui/PluginEditors.h"
  35. #include "ui/PluginWindow.h"
  36. #include "ui/HintBar.h"
  37. #include "ui/I18n.h"
  38. #include "core/LynxTune.h"
  39. #include "core/VocalPitch.h"
  40. #include "ui/Icons.h"
  41. #include "ui/ValueControl.h"
  42. #include "ui/Theme.h"
  43. #include "ui/AudioEditor.h"
  44. #include "ui/Dialogs.h"
  45. #include "ui/QuickPick.h"
  46. #include "ui/TrackIcons.h"
  47. #include "core/TrackIcons.h"
  48. namespace lynx
  49. {
  50. namespace
  51. {
  52. // strip layout, top to bottom: header (arm, number, icon, a horizontal name), the vertical name column (not in
  53. // Extra large; low in the strip in the alt layouts), knobs (pan, stereo), mute/solo, meters + fader, the dB read-out,
  54. // then the routing lane (send switch, send knob, wires). The rows follow FL's Mixer layout (MixerStrips::rows()).
  55. constexpr int switchHeight = 16;
  56. constexpr int sendKnobHeight = 26;
  57. constexpr int wiresHeight = 14;
  58. constexpr int laneHeight = switchHeight + sendKnobHeight + wiresHeight + 4;
  59. constexpr int masterScaleWidth = 17; // the dB numbers beside the master meter (round 162, issue #9)
  60. // Fader 0..1 -> dB, with 0.8 = 0 dB (as in FL).
  61. juce::String faderToDb (float volume)
  62. {
  63. if (volume <= 0.0001f)
  64. return juce::String::fromUTF8 ("-\xe2\x88\x9e");
  65. const auto db = juce::Decibels::gainToDecibels (faderGain (volume));
  66. return (db > 0 ? "+" : "") + juce::String (db, 1);
  67. }
  68. // Meter level 0..1 on a dB scale (-60..+6).
  69. float meterPosition (float gain)
  70. {
  71. const auto db = juce::Decibels::gainToDecibels (gain, -60.0f);
  72. return juce::jlimit (0.0f, 1.0f, (db + 60.0f) / 66.0f);
  73. }
  74. // Stereo separation: -1 = widest, 0 = normal, +1 = mono (MixerTrack::stereo).
  75. ui::ValueSpec stereoSpec (const juce::String& name)
  76. {
  77. ui::ValueSpec spec;
  78. spec.name = name;
  79. spec.minimum = -1.0;
  80. spec.maximum = 1.0;
  81. spec.defaultValue = 0.0;
  82. spec.toText = [] (double v) {
  83. const auto percent = juce::roundToInt (std::abs (v) * 100.0);
  84. if (percent == 0)
  85. return tr ("Normal width");
  86. if (v > 0.0 && percent >= 100)
  87. return tr ("Mono");
  88. return v < 0.0 ? tr ("{0}% wider", { juce::String (percent) }) : tr ("{0}% narrower", { juce::String (percent) });
  89. };
  90. spec.fromText = [] (const juce::String& t) -> std::optional<double> {
  91. const auto lower = t.toLowerCase().trim();
  92. if (lower.startsWith ("mono"))
  93. return 1.0;
  94. if (lower.startsWith ("n") && ! lower.containsAnyOf ("0123456789"))
  95. return 0.0;
  96. const auto digits = lower.initialSectionContainingOnly ("+-0123456789.,").replaceCharacter (',', '.');
  97. if (digits.isEmpty() || digits.containsOnly ("+-."))
  98. return std::nullopt;
  99. auto v = digits.getDoubleValue() / 100.0;
  100. if (lower.contains ("wid") || lower.contains ("larg")) // "50% wider" / "50% mais largo"
  101. v = -std::abs (v);
  102. return v;
  103. };
  104. return spec;
  105. }
  106. // Online Sessions (round 168a): the amber "R" of an insert whose stand-in render plays
  107. void drawStandInTag (juce::Graphics& g, juce::Rectangle<float> tag)
  108. {
  109. theme::fillRoundRect (g, tag, 3.0f, theme::colour::warning.withAlpha (0.85f));
  110. g.setColour (theme::colour::bg1);
  111. g.setFont (theme::font (9.0f, true));
  112. g.drawText ("R", tag, juce::Justification::centred, false);
  113. }
  114. ui::ValueSpec sendSpec (const juce::String& name)
  115. {
  116. // FL's send knob: the fader curve (0 dB at 80 %, +5.6 dB at the top); the value is the knob position
  117. auto spec = ui::faderSpec (name, unityFader);
  118. spec.pixelsForRange = 120.0;
  119. return spec;
  120. }
  121. } // namespace
  122. MixerStrips::MixerStrips (AudioEngine& e)
  123. : engine (e)
  124. {
  125. setWantsKeyboardFocus (false);
  126. setMouseClickGrabsKeyboardFocus (false);
  127. engine.addChangeListener (this);
  128. engine.getLevelsBroadcaster().addChangeListener (this);
  129. updateSize();
  130. // 60 Hz: faders that follow their automation move every frame (round 171c); the meters keep their 30 Hz ballistics
  131. startTimerHz (60);
  132. }
  133. MixerStrips::~MixerStrips()
  134. {
  135. engine.getLevelsBroadcaster().removeChangeListener (this);
  136. engine.removeChangeListener (this);
  137. }
  138. void MixerStrips::setVisibleHeight (int height)
  139. {
  140. visibleHeight = juce::jmax (300, height);
  141. updateSize();
  142. }
  143. void MixerStrips::updateSize()
  144. {
  145. const auto tracks = (int) engine.getSong().mixer.size();
  146. layoutStrips();
  147. setSize (contentWidth, visibleHeight);
  148. levels.resize ((std::size_t) juce::jmax (1, tracks) * 2);
  149. }
  150. void MixerStrips::layoutStrips()
  151. {
  152. const auto& song = engine.getSong();
  153. const auto tracks = (int) song.mixer.size();
  154. stripXs.assign ((std::size_t) tracks + 1, 0);
  155. // "Show only used inserts" (round 163): unused inserts take no room, except those brought back with "+" (so a new
  156. // insert shows; selecting another strip doesn't move the strips under the mouse)
  157. hidden.assign ((std::size_t) tracks + 1, false);
  158. if (showUsedOnly)
  159. for (int t = 1; t < tracks; ++t)
  160. hidden[(std::size_t) t] = revealed.count (t) == 0 && ! song.insertInUse (t);
  161. dockGaps.clear();
  162. separatorLines.clear();
  163. int x = 4;
  164. bool any = false, afterMaster = false;
  165. for (auto dock : { MixerDock::left, MixerDock::middle, MixerDock::right })
  166. {
  167. const auto d = (int) dock;
  168. blockStart[d] = x;
  169. bool first = true;
  170. for (int t = 0; t < tracks; ++t)
  171. {
  172. const auto& track = song.mixer[(std::size_t) t];
  173. if (track.dock != dock)
  174. continue;
  175. if (hidden[(std::size_t) t])
  176. {
  177. stripXs[(std::size_t) t] = hiddenX;
  178. continue;
  179. }
  180. if (any && first && dock == MixerDock::right)
  181. {
  182. // the gap between two blocks belongs to the pinned block: the right block's is before its strips,
  183. // the left block's after them (below)
  184. dockGaps.push_back ({ x + dockGap / 2 - 2, dock });
  185. x += dockGap;
  186. }
  187. else if (! first && track.separator && t > 0)
  188. {
  189. separatorLines.push_back ({ x + separatorGap / 2 - 3, dock });
  190. x += separatorGap;
  191. }
  192. else if (afterMaster)
  193. x += 8;
  194. stripXs[(std::size_t) t] = x;
  195. x += stripWidthOf (t);
  196. any = true;
  197. first = false;
  198. afterMaster = t == 0;
  199. }
  200. if (dock == MixerDock::middle) // the "+" button ends the middle block
  201. {
  202. if (afterMaster)
  203. x += 8;
  204. stripXs[(std::size_t) tracks] = x;
  205. x += spec().stripWidth;
  206. afterMaster = false;
  207. any = true;
  208. }
  209. blockEnd[d] = x;
  210. if (dock == MixerDock::left && ! first) // the left block carries its gap to the middle
  211. {
  212. dockGaps.push_back ({ x + dockGap / 2 - 2, dock });
  213. x += dockGap;
  214. blockEnd[d] = x;
  215. afterMaster = false;
  216. }
  217. }
  218. contentWidth = x + 8;
  219. }
  220. MixerDock MixerStrips::dockOf (int track) const noexcept
  221. {
  222. const auto& mixer = engine.getSong().mixer;
  223. return track >= 0 && track < (int) mixer.size() ? mixer[(std::size_t) track].dock : MixerDock::middle;
  224. }
  225. int MixerStrips::pinOffset (MixerDock dock) const noexcept
  226. {
  227. auto* parent = getParentComponent();
  228. if (parent == nullptr || dock == MixerDock::middle)
  229. return 0;
  230. const auto scroll = juce::jmax (0, -getX());
  231. const auto visible = parent->getWidth();
  232. if (dock == MixerDock::left)
  233. return blockEnd[0] > blockStart[0] ? juce::jmin (scroll, juce::jmax (0, contentWidth - blockEnd[0])) : 0;
  234. return blockEnd[2] > blockStart[2] ? juce::jmin (0, scroll + visible - contentWidth) : 0;
  235. }
  236. int MixerStrips::stripX (int track) const noexcept
  237. {
  238. if (track >= 0 && track < (int) stripXs.size())
  239. return stripXs[(std::size_t) track] + pinOffset (dockOf (track));
  240. return track == 0 ? 4 : 4 + spec().masterWidth + 8 + (track - 1) * spec().stripWidth;
  241. }
  242. bool MixerStrips::isInterestedInDragSource (const SourceDetails& details)
  243. {
  244. if (BrowserComponent::isEffectDrag (details) || BrowserComponent::isGeneratorDrag (details))
  245. return true;
  246. if (! BrowserComponent::isBrowserDrag (details))
  247. return false;
  248. // (asked on every mouse move of the drag: the answer for the dragged file is kept)
  249. static juce::File lastFile;
  250. static bool lastAnswer = false;
  251. if (const auto file = BrowserComponent::draggedFile (details); file != lastFile)
  252. {
  253. lastFile = file;
  254. lastAnswer = mixerpresets::isMixerPreset (file);
  255. }
  256. return lastAnswer;
  257. }
  258. void MixerStrips::itemDropped (const SourceDetails& details)
  259. {
  260. const auto t = trackAt (details.localPosition.x);
  261. const auto tracks = (int) engine.getSong().mixer.size();
  262. // FL's mixer preset dropped from the Browser (WhatsNew): onto a track it loads there, onto the empty mixer space
  263. // (or "+") it makes a new track
  264. if (BrowserComponent::isBrowserDrag (details))
  265. {
  266. const auto file = BrowserComponent::draggedFile (details);
  267. if (! mixerpresets::isMixerPreset (file))
  268. return;
  269. if (t >= 0 && t < tracks)
  270. mixerpresets::loadOnTracks (engine, { t }, file);
  271. else if (const auto added = mixerpresets::insertTrack (engine, tracks, file); added > 0)
  272. {
  273. revealed.insert (added);
  274. updateSize();
  275. selectTrack (added);
  276. }
  277. return;
  278. }
  279. if (t < 0 || t >= tracks)
  280. return;
  281. if (auto fx = BrowserComponent::draggedEffect (details); fx && onEffectDropped != nullptr)
  282. onEffectDropped (t, std::move (*fx));
  283. else if (auto c = BrowserComponent::draggedGenerator (details); c && onInstrumentDropped != nullptr)
  284. onInstrumentDropped (t, std::move (*c));
  285. }
  286. int MixerStrips::trackAt (int x) const noexcept
  287. {
  288. const auto tracks = (int) engine.getSong().mixer.size();
  289. // the pinned blocks lie over the scrolled middle: they are hit first
  290. for (auto dock : { MixerDock::left, MixerDock::right, MixerDock::middle })
  291. for (int t = 0; t <= tracks; ++t) // t == tracks = "+" button
  292. if (dockOf (t) == dock && x >= stripX (t) && x < stripX (t) + stripWidthOf (t))
  293. return t;
  294. return -1;
  295. }
  296. int MixerStrips::laneTop() const noexcept
  297. {
  298. return getHeight() - laneHeight;
  299. }
  300. const mixerlayout::Spec& MixerStrips::spec() noexcept
  301. {
  302. static mixerlayout::Layout cachedFor = (mixerlayout::Layout) -1;
  303. static mixerlayout::Spec cached;
  304. if (cachedFor != layout)
  305. {
  306. cached = mixerlayout::specOf (layout);
  307. cachedFor = layout;
  308. }
  309. return cached;
  310. }
  311. void MixerStrips::setLayout (mixerlayout::Layout newLayout)
  312. {
  313. if (newLayout == layout)
  314. return;
  315. layout = newLayout;
  316. updateSize();
  317. repaint();
  318. if (onLayoutChanged)
  319. onLayoutChanged();
  320. }
  321. MixerStrips::Rows MixerStrips::rows() const noexcept
  322. {
  323. const auto& sp = spec();
  324. const auto compact = mixerlayout::isCompact (layout);
  325. Rows r;
  326. r.header = sp.verticalName ? 38 : 54;
  327. // the vertical name column takes what the fader can spare (FL's runs the strip's upper part)
  328. r.nameHeight = sp.verticalName ? juce::jlimit (40, 110, (getHeight() - 300) / 2) : 0;
  329. r.knobsHeight = ! sp.stereoKnob ? sp.knobSize + 8 : sp.stackedKnobs ? sp.knobSize + (sp.knobSize - 6) + 10 : 32;
  330. r.buttonsHeight = compact ? 32 : 20; // compact: mute above solo
  331. r.readoutHeight = sp.dbReadout ? 16 : 0;
  332. auto y = r.header;
  333. if (sp.verticalName && ! sp.nameLow)
  334. {
  335. r.nameTop = y;
  336. y += r.nameHeight;
  337. }
  338. r.knobsTop = y;
  339. r.buttonsTop = r.knobsTop + r.knobsHeight;
  340. r.faderTop = r.buttonsTop + r.buttonsHeight + 6;
  341. auto bottom = laneTop() - r.readoutHeight - 4;
  342. if (compact)
  343. {
  344. r.armY = bottom - 14;
  345. bottom -= 16;
  346. }
  347. if (sp.verticalName && sp.nameLow)
  348. {
  349. // the alt layouts: the name runs up from the strip's bottom; the dB read-out stays under the fader, above the
  350. // name (rel 0.1.23: the read-out was drawn over the name's top)
  351. r.nameTop = bottom + r.readoutHeight - r.nameHeight;
  352. bottom = r.nameTop - 4 - r.readoutHeight;
  353. }
  354. r.faderBottom = juce::jmax (r.faderTop + 40, bottom);
  355. return r;
  356. }
  357. juce::Rectangle<int> MixerStrips::headerArea (int t) const
  358. {
  359. return { stripX (t), 0, stripWidthOf (t) - spec().gap, rows().header };
  360. }
  361. juce::Rectangle<int> MixerStrips::nameArea (int t) const
  362. {
  363. const auto r = rows();
  364. const auto w = stripWidthOf (t) - spec().gap;
  365. if (r.nameHeight <= 0) // Extra large: the name row of the header
  366. return { stripX (t) + 3, 38, w - 6, 14 };
  367. // the name runs up the strip's left part; the right part shows the meters (as FL's)
  368. const auto nameWidth = mixerlayout::isCompact (layout) ? w : juce::jmax (14, w - 2 * spec().meterWidth - 8);
  369. return { stripX (t), r.nameTop, nameWidth, r.nameHeight };
  370. }
  371. juce::Rectangle<int> MixerStrips::iconArea (int t) const
  372. {
  373. const auto w = stripWidthOf (t) - spec().gap;
  374. const auto size = juce::jmin (16, w - 2);
  375. return { stripX (t) + (w - size) / 2, rows().iconY, size, size };
  376. }
  377. juce::Rectangle<int> MixerStrips::armArea (int t) const
  378. {
  379. const auto r = rows();
  380. if (r.armY >= 0)
  381. {
  382. const auto w = stripWidthOf (t) - spec().gap;
  383. return { stripX (t) + (w - 13) / 2, r.armY, 13, 13 };
  384. }
  385. return { stripX (t) + 4, 4, 13, 13 };
  386. }
  387. juce::Rectangle<int> MixerStrips::inputArea (int t) const
  388. {
  389. // a thin level bar under the header (inserts with an input source)
  390. return { stripX (t) + 3, rows().header - 3, stripWidthOf (t) - spec().gap - 6, 3 };
  391. }
  392. juce::Rectangle<int> MixerStrips::panArea (int t) const
  393. {
  394. const auto r = rows();
  395. const auto& sp = spec();
  396. const auto w = stripWidthOf (t) - sp.gap;
  397. if (! sp.stereoKnob)
  398. return { stripX (t), r.knobsTop, w, r.knobsHeight };
  399. if (sp.stackedKnobs)
  400. return { stripX (t), r.knobsTop, w, sp.knobSize + 4 };
  401. return { stripX (t), r.knobsTop, w / 2, r.knobsHeight };
  402. }
  403. juce::Rectangle<int> MixerStrips::stereoArea (int t) const
  404. {
  405. const auto r = rows();
  406. const auto& sp = spec();
  407. const auto w = stripWidthOf (t) - sp.gap;
  408. if (! sp.stereoKnob)
  409. return {};
  410. if (sp.stackedKnobs)
  411. return { stripX (t), r.knobsTop + sp.knobSize + 4, w, r.knobsHeight - sp.knobSize - 4 };
  412. return { stripX (t) + w / 2, r.knobsTop, w - w / 2, r.knobsHeight };
  413. }
  414. juce::Rectangle<int> MixerStrips::muteArea (int t) const
  415. {
  416. const auto r = rows();
  417. const auto w = stripWidthOf (t) - spec().gap;
  418. if (mixerlayout::isCompact (layout))
  419. return { stripX (t), r.buttonsTop, w, 16 };
  420. if (t == 0)
  421. return { stripX (t) + 4, r.buttonsTop, 24, r.buttonsHeight };
  422. return { stripX (t) + 2, r.buttonsTop, w / 2 - 2, r.buttonsHeight };
  423. }
  424. juce::Rectangle<int> MixerStrips::soloArea (int t) const
  425. {
  426. const auto r = rows();
  427. const auto w = stripWidthOf (t) - spec().gap;
  428. if (mixerlayout::isCompact (layout))
  429. return { stripX (t) + (w - 16) / 2, r.buttonsTop + 16, 16, 16 };
  430. return { stripX (t) + w - juce::jmin (24, w / 2), r.buttonsTop, juce::jmin (24, w / 2), r.buttonsHeight };
  431. }
  432. juce::Rectangle<int> MixerStrips::faderArea (int t) const
  433. {
  434. const auto r = rows();
  435. const auto inset = mixerlayout::isCompact (layout) ? 1 : 5;
  436. return { stripX (t) + inset, r.faderTop, stripWidthOf (t) - spec().gap - 2 * inset, r.faderBottom - r.faderTop };
  437. }
  438. juce::Rectangle<int> MixerStrips::meterArea (int t) const
  439. {
  440. return faderArea (t).withWidth (spec().meterWidth * 2 + 2);
  441. }
  442. juce::Rectangle<int> MixerStrips::faderRail (int t) const
  443. {
  444. return faderArea (t).withTrimmedLeft (spec().meterWidth * 2 + (mixerlayout::isCompact (layout) ? 3 : 6) + (t == 0 ? masterScaleWidth : 0));
  445. }
  446. juce::Rectangle<int> MixerStrips::routeArea (int t) const
  447. {
  448. const auto inset = mixerlayout::isCompact (layout) ? 1 : 5;
  449. return { stripX (t) + inset, laneTop() + 2, stripWidthOf (t) - spec().gap - 2 * inset, switchHeight };
  450. }
  451. juce::Rectangle<int> MixerStrips::sendArea (int t) const
  452. {
  453. return { stripX (t), laneTop() + 2 + switchHeight, stripWidthOf (t) - spec().gap, sendKnobHeight };
  454. }
  455. MixerStrips::Part MixerStrips::partAt (int t, juce::Point<int> p) const
  456. {
  457. const auto& song = engine.getSong();
  458. if (t == (int) song.mixer.size())
  459. return Part::add;
  460. if (t < 0 || t > (int) song.mixer.size())
  461. return Part::none;
  462. const auto sending = selected > 0 && t != selected && selected < (int) song.mixer.size();
  463. if (t > 0 && armArea (t).expanded (1).contains (p))
  464. return Part::arm;
  465. if (t > 0 && t < (int) engine.getSong().mixer.size() && engine.getSong().mixer[(std::size_t) t].inputChannel >= 0
  466. && inputArea (t).expanded (0, 2).contains (p))
  467. return Part::input;
  468. if (headerArea (t).contains (p) || nameArea (t).contains (p))
  469. return Part::header;
  470. if (panArea (t).contains (p))
  471. return Part::pan;
  472. if (stereoArea (t).contains (p))
  473. return Part::stereo;
  474. if (muteArea (t).contains (p))
  475. return Part::mute;
  476. if (t > 0 && soloArea (t).contains (p))
  477. return Part::solo;
  478. if (sending && routeArea (t).contains (p) && (song.routes (selected, t) || song.canRoute (selected, t)))
  479. return Part::route;
  480. if (sending && sendArea (t).contains (p) && song.routes (selected, t))
  481. return Part::send;
  482. if (meterArea (t).contains (p))
  483. return Part::meter;
  484. if (faderRail (t).expanded (0, 6).contains (p))
  485. return Part::fader;
  486. return Part::body;
  487. }
  488. juce::Rectangle<int> MixerStrips::tipArea (Part part, int t) const
  489. {
  490. switch (part)
  491. {
  492. case Part::pan: return panArea (t);
  493. case Part::stereo: return stereoArea (t);
  494. case Part::send: return sendArea (t);
  495. case Part::route: return routeArea (t);
  496. case Part::fader:
  497. {
  498. const auto rail = faderRail (t);
  499. const auto& mixer = engine.getSong().mixer;
  500. const auto v = t >= 0 && t < (int) mixer.size() ? shownVolume (t) : 0.0f;
  501. const auto capY = rail.getBottom() - (int) (v * (float) rail.getHeight());
  502. return { rail.getX(), capY - 6, rail.getWidth(), 12 };
  503. }
  504. default: return {};
  505. }
  506. }
  507. void MixerStrips::showTip (Part part, int t, bool transient)
  508. {
  509. if (t < 0 || t >= (int) engine.getSong().mixer.size())
  510. return;
  511. const auto spec = specFor (part, t);
  512. const auto text = spec.text (valueOf (part, t));
  513. ui::postHint (ui::valueHint (spec, valueOf (part, t), ui::valueGestures()));
  514. if (transient)
  515. ui::flashValueTip (*this, tipArea (part, t), text);
  516. else
  517. ui::showValueTip (*this, tipArea (part, t), text);
  518. }
  519. void MixerStrips::setHover (Part part, int t)
  520. {
  521. if (part == hoverPart && t == hoverTrack)
  522. return;
  523. auto dirty = [this] (int track) {
  524. if (track >= 0)
  525. repaint (stripX (track) - 2, 0, stripWidthOf (track) + 4, getHeight());
  526. };
  527. dirty (hoverTrack);
  528. hoverPart = part;
  529. hoverTrack = t;
  530. dirty (hoverTrack);
  531. }
  532. void MixerStrips::mouseMove (const juce::MouseEvent& e)
  533. {
  534. const auto t = trackAt (e.x);
  535. setHover (t >= 0 ? partAt (t, e.getPosition()) : Part::none, t);
  536. }
  537. void MixerStrips::mouseExit (const juce::MouseEvent&)
  538. {
  539. setHover (Part::none, -1);
  540. }
  541. void MixerStrips::paint (juce::Graphics& g)
  542. {
  543. const uitrace::Scope trace ("MixerStrips paint", true, g.getClipBounds());
  544. using namespace theme;
  545. const auto& song = engine.getSong();
  546. const auto tracks = (int) song.mixer.size();
  547. const auto clip = g.getClipBounds();
  548. g.fillAll (colour::bg1);
  549. // the routing lane runs under all strips
  550. g.setColour (colour::bg0.withAlpha (0.55f));
  551. g.fillRect (0, laneTop() + switchHeight + sendKnobHeight + 2, getWidth(), wiresHeight + 2);
  552. // FL's separators (a line on the left of the track) and the gaps between the dock blocks (round 146a), drawn
  553. // per block so the pinned left / right blocks cover the scrolled middle (round 149)
  554. auto paintDividers = [&] (MixerDock dock) {
  555. const auto shift = pinOffset (dock);
  556. g.setColour (colour::borderStrong);
  557. for (auto [lx, d] : separatorLines)
  558. if (d == dock)
  559. theme::fillRoundRect (g, { (float) (lx + shift), 8.0f, 2.0f, (float) laneTop() - 14.0f }, 1.0f, colour::borderStrong);
  560. g.setColour (colour::bg0);
  561. for (auto [gx, d] : dockGaps)
  562. if (d == dock)
  563. g.fillRect (gx + shift - 3, 0, 6, getHeight());
  564. };
  565. for (auto pass : { MixerDock::middle, MixerDock::left, MixerDock::right })
  566. {
  567. if (pass == MixerDock::middle)
  568. {
  569. // "+" button
  570. if (tracks < maxMixerTracks)
  571. {
  572. const auto add = juce::Rectangle<int> (stripX (tracks), 2, spec().stripWidth - spec().gap, 60).toFloat();
  573. const auto addHovered = hoverPart == Part::add;
  574. theme::fillRoundRect (g, add, radius::md, addHovered ? colour::bg4 : colour::bg2);
  575. g.setColour (addHovered ? colour::borderStrong : colour::border);
  576. g.drawRoundedRectangle (add.reduced (0.5f), radius::md, 1.0f);
  577. icons::draw (g, Icon::plus, add.withSizeKeepingCentre (22.0f, 22.0f), addHovered ? colour::textPrimary : colour::textSecondary);
  578. }
  579. }
  580. else if (const auto shift = pinOffset (pass); shift != 0) // a pinned block hides what scrolls under it
  581. {
  582. const auto d = (int) pass;
  583. g.setColour (colour::bg1);
  584. g.fillRect (blockStart[d] + shift, 0, blockEnd[d] - blockStart[d], laneTop());
  585. g.setColour (colour::bg0.withAlpha (0.55f));
  586. g.fillRect (blockStart[d] + shift, laneTop(), blockEnd[d] - blockStart[d], getHeight() - laneTop());
  587. }
  588. for (int t = 0; t < tracks; ++t)
  589. {
  590. if (song.mixer[(std::size_t) t].dock != pass || isHidden (t))
  591. continue;
  592. const auto x = stripX (t);
  593. const auto w = stripWidthOf (t);
  594. if (x > clip.getRight() || x + w < clip.getX())
  595. continue;
  596. const auto& track = song.mixer[(std::size_t) t];
  597. const auto& sp = spec();
  598. const auto plateWidth = w - sp.gap;
  599. const auto compactLayout = mixerlayout::isCompact (layout);
  600. const auto strip = juce::Rectangle<int> (x, 2, plateWidth, laneTop() - 2);
  601. const auto isSelected = t == selected;
  602. const auto inSelection = std::binary_search (selection.begin(), selection.end(), t);
  603. const auto stripHovered = hoverTrack == t;
  604. const auto hovered = [this, t] (Part p) { return hoverTrack == t && hoverPart == p; };
  605. const auto dragging = [this, t] (Part p) { return dragTrack == t && dragPart == p; };
  606. // the strip is tinted with the insert's colour (FL tints whole strips, so groups read at a glance);
  607. // kept dark so meters, knobs and text keep their contrast
  608. auto plate = isSelected || inSelection ? colour::bg4 : (t == 0 ? colour::bg3 : stripHovered ? colour::bg3 : colour::bg2);
  609. if (track.colour != 0)
  610. plate = plate.interpolatedWith (tame (juce::Colour (track.colour)), isSelected ? 0.26f : 0.2f);
  611. theme::fillRoundRect (g, strip.toFloat(), radius::md, plate);
  612. if (track.colour != 0) // thin colour band at the top
  613. {
  614. theme::fillRoundRect (g, strip.toFloat().withHeight (3.0f).reduced (6.0f, 0.0f), 1.5f, tame (juce::Colour (track.colour)));
  615. }
  616. if (inSelection && ! isSelected)
  617. {
  618. g.setColour (colour::accent.withAlpha (0.3f));
  619. g.drawRoundedRectangle (strip.toFloat().reduced (0.5f), radius::md, 1.0f);
  620. }
  621. if (isSelected)
  622. {
  623. g.setColour (colour::accent.withAlpha (0.55f));
  624. g.drawRoundedRectangle (strip.toFloat().reduced (0.5f), radius::md, 1.0f);
  625. theme::fillRoundRect (g, strip.toFloat().withHeight (3.0f).reduced (6.0f, 0.0f), 1.5f, colour::accent);
  626. }
  627. if (headerDragged && headerDragTrack == t)
  628. {
  629. g.setColour (colour::accent);
  630. g.drawRoundedRectangle (strip.toFloat().reduced (0.5f), radius::md, 1.5f);
  631. }
  632. // record arm: the input recording goes through this insert
  633. if (t > 0)
  634. {
  635. const auto armed = engine.isInsertArmed (t);
  636. const auto r = armArea (t).toFloat().reduced (2.0f);
  637. g.setColour (armed ? colour::record : hovered (Part::arm) ? colour::bg5 : colour::bg0);
  638. g.fillEllipse (r);
  639. g.setColour (armed ? colour::record.brighter (0.3f) : hovered (Part::arm) ? colour::textSecondary : colour::borderStrong);
  640. g.drawEllipse (r, 1.0f);
  641. if (track.recordSafe) // record safe: a slash through the arm button
  642. {
  643. g.setColour (colour::textDisabled);
  644. g.drawLine (r.getX() + 1.0f, r.getBottom() - 1.0f, r.getRight() - 1.0f, r.getY() + 1.0f, 1.2f);
  645. }
  646. // the input level (inserts with an audio input source)
  647. if (track.inputChannel >= 0 && (std::size_t) t < inputLevels.size())
  648. {
  649. const auto bar = inputArea (t).toFloat();
  650. theme::fillRoundRect (g, bar, 1.0f, colour::bg0);
  651. const auto level = inputLevels[(std::size_t) t];
  652. const auto fill = juce::jlimit (0.0f, 1.0f, (juce::Decibels::gainToDecibels (level, -60.0f) + 60.0f) / 60.0f);
  653. theme::fillRoundRect (g, bar.withWidth (bar.getWidth() * fill), 1.0f, level >= 0.99f ? colour::record : colour::meterLow);
  654. }
  655. }
  656. // header: number and effect count on one line, the icon under them (FL's place), then the name: on the
  657. // header's last row (Extra large) or up a column of the strip (round 168h)
  658. g.setColour (isSelected ? colour::accent : colour::textSecondary);
  659. g.setFont (font (compactLayout ? 9.5f : type::caption, isSelected));
  660. textcache::drawFittedText (g, t == 0 ? juce::String ("M") : juce::String (t), juce::Rectangle<int> (x, 4, plateWidth, 13),
  661. juce::Justification::centred, 1, 0.6f);
  662. if (const auto icon = trackicons::iconFor (track.icon); icon != trackicons::Icon::none)
  663. ui::drawTrackIcon (g, icon, iconArea (t).toFloat(), track.muted ? colour::textDisabled : colour::textPrimary.withAlpha (0.88f));
  664. if (! track.effects.empty() && sp.fxBadge)
  665. {
  666. const auto on = mixerops::anyEffectEnabled (song, t);
  667. g.setColour (on ? colour::info : colour::textDisabled);
  668. g.setFont (font (9.0f, true));
  669. if (plateWidth >= 56)
  670. textcache::drawText (g, "FX" + juce::String ((int) track.effects.size()), x + plateWidth - 26, 4, 23, 13, juce::Justification::centredRight);
  671. else // narrow strips: a dot at the number's right
  672. g.fillEllipse ((float) (x + plateWidth) - 7.0f, 8.0f, 4.0f, 4.0f);
  673. }
  674. g.setColour (track.muted ? colour::textDisabled : (hovered (Part::header) ? colour::textPrimary : colour::textPrimary.withAlpha (0.9f)));
  675. g.setFont (font (compactLayout ? 10.0f : type::small, isSelected));
  676. // Online Sessions (round 168a): a plugin of this insert is not installed here, its stand-in render plays (an
  677. // amber R before the name)
  678. const auto standIn = engine.insertPlaysStandIn (t);
  679. const auto name = juce::String::fromUTF8 (track.name.c_str());
  680. if (const auto box = nameArea (t); ! sp.verticalName)
  681. {
  682. textcache::drawFittedText (g, name, box.withTrimmedLeft (standIn ? 16 : 0), juce::Justification::centred, 1, 0.7f);
  683. if (standIn)
  684. drawStandInTag (g, { (float) box.getX() + 1.0f, (float) box.getY() + 0.5f, 13.0f, 13.0f });
  685. }
  686. else
  687. {
  688. // the name reads bottom to top, as FL's narrow strips do
  689. auto column = box.reduced (2, 4);
  690. if (standIn)
  691. {
  692. drawStandInTag (g, juce::Rectangle<float> (13.0f, 13.0f).withCentre ({ (float) column.getCentreX(), (float) column.getBottom() - 6.5f }));
  693. column.removeFromBottom (16);
  694. }
  695. juce::Graphics::ScopedSaveState state (g);
  696. g.addTransform (juce::AffineTransform::rotation (-juce::MathConstants<float>::halfPi, (float) column.getCentreX(), (float) column.getCentreY()));
  697. const auto rotated = juce::Rectangle<int> (column.getHeight(), column.getWidth()).withCentre (column.getCentre());
  698. g.drawFittedText (name, rotated, juce::Justification::centredLeft, 1, 0.8f);
  699. }
  700. // FL's narrow strips show the level beside the name too: two thin bars (Wide layouts)
  701. if (sp.verticalName && ! sp.nameLow && ! compactLayout && t > 0)
  702. {
  703. const auto box = nameArea (t);
  704. const auto bars = juce::Rectangle<int> (box.getRight() + 2, box.getY() + 6, plateWidth - box.getWidth() - 6, box.getHeight() - 12);
  705. theme::fillRoundRect (g, bars.toFloat(), 2.0f, colour::bg0.withAlpha (0.8f));
  706. for (int ch = 0; ch < 2; ++ch)
  707. {
  708. const auto index = (std::size_t) t * 2 + (std::size_t) ch;
  709. const auto level = index < levels.size() ? levels[index].level : 0.0f;
  710. const auto bw = (bars.getWidth() - 3) / 2;
  711. const auto bar = juce::Rectangle<int> (bars.getX() + 1 + ch * (bw + 1), bars.getY() + 1, bw, bars.getHeight() - 2);
  712. const auto h = (int) (meterPosition (level) * (float) bar.getHeight());
  713. g.setColour (level >= 1.0f ? colour::meterClip : level >= 0.5f ? colour::meterMid : colour::meterLow);
  714. g.fillRect (bar.withTop (bar.getBottom() - h));
  715. }
  716. }
  717. // compensated latency (PDC) on the Master
  718. if (t == 0 && engine.getLatencySamples() > 0 && ! compactLayout)
  719. {
  720. const auto ms = 1000.0 * engine.getLatencySamples() / juce::jmax (1.0, engine.getTransport().sampleRate.load());
  721. g.setColour (colour::textSecondary);
  722. g.setFont (font (10.0f));
  723. textcache::drawFittedText (g, "PDC " + juce::String (ms, 1) + " ms", soloArea (t).withX (x + 30).withWidth (w - 36),
  724. juce::Justification::centredLeft, 1, 0.8f); // the Master has no solo: use its spot
  725. }
  726. // pan and stereo separation
  727. const auto knob = (float) sp.knobSize;
  728. const auto stereoKnob = sp.stackedKnobs ? knob - 6.0f : 22.0f;
  729. drawKnob (g, panArea (t).toFloat().withSizeKeepingCentre (knob, knob),
  730. engine.getAutomationDisplay().shown (AutomationTarget { AutomationTargetKind::mixerPan, t }, (track.pan + 1.0f) * 0.5f), true,
  731. dragging (Part::pan) ? colour::accent : colour::info, hovered (Part::pan) || dragging (Part::pan));
  732. if (sp.stereoKnob)
  733. drawKnob (g, stereoArea (t).toFloat().withSizeKeepingCentre (stereoKnob, stereoKnob), (track.stereo + 1.0f) * 0.5f, true,
  734. dragging (Part::stereo) ? colour::accent : colour::knobArc, hovered (Part::stereo) || dragging (Part::stereo));
  735. // mute and solo
  736. {
  737. const auto led = compactLayout ? 10.0f : 12.0f;
  738. const auto m = muteArea (t).toFloat().withSizeKeepingCentre (led, led);
  739. g.setColour (muteLed (track.muted));
  740. g.fillEllipse (m);
  741. if (! track.muted || hovered (Part::mute))
  742. {
  743. g.setColour (hovered (Part::mute) ? colour::textSecondary : colour::ledOn.withAlpha (0.25f));
  744. g.drawEllipse (m.expanded (2.0f), 1.0f);
  745. }
  746. if (t > 0)
  747. {
  748. const auto s = soloArea (t).toFloat().reduced (2.0f);
  749. theme::fillRoundRect (g, s, radius::sm, track.solo ? colour::accent : hovered (Part::solo) ? colour::bg5 : colour::bg0);
  750. g.setColour (track.solo ? colour::onAccent : hovered (Part::solo) ? colour::textPrimary : colour::textSecondary);
  751. g.setFont (font (type::caption, true));
  752. textcache::drawText (g, "S", s.toNearestInt(), juce::Justification::centred);
  753. }
  754. }
  755. // meters + fader
  756. {
  757. const auto area = faderArea (t);
  758. const auto meters = meterArea (t);
  759. const auto fader = faderRail (t);
  760. for (int ch = 0; ch < 2; ++ch)
  761. {
  762. const auto bar = juce::Rectangle<int> (meters.getX() + ch * (sp.meterWidth + 2), meters.getY(), sp.meterWidth, meters.getHeight());
  763. theme::fillRoundRect (g, bar.toFloat(), 1.5f, colour::bg0);
  764. const auto index = (std::size_t) t * 2 + (std::size_t) ch;
  765. const auto meter = index < levels.size() ? levels[index] : meters::PeakHold {};
  766. const auto h = (int) (meterPosition (meter.level) * (float) bar.getHeight());
  767. const auto lit = bar.withTop (bar.getBottom() - h);
  768. juce::ColourGradient gradient (colour::meterClip, (float) bar.getX(), (float) bar.getY(), colour::meterLow, (float) bar.getX(),
  769. (float) bar.getBottom(), false);
  770. gradient.addColour (1.0 - meterPosition (juce::Decibels::decibelsToGain (0.0f)), colour::meterClip); // above 0 dB: clip zone
  771. gradient.addColour (1.0 - meterPosition (juce::Decibels::decibelsToGain (-6.0f)), colour::meterMid);
  772. gradient.addColour (1.0 - meterPosition (juce::Decibels::decibelsToGain (-18.0f)), colour::meterLow);
  773. g.setGradientFill (gradient);
  774. g.fillRect (lit);
  775. if (meter.peak > 0.001f) // peak hold line
  776. {
  777. const auto peakY = bar.getBottom() - (int) (meterPosition (meter.peak) * (float) bar.getHeight());
  778. g.setColour (meter.peak >= 1.0f ? colour::meterClip : meter.peak >= 0.5f ? colour::meterMid : colour::textPrimary.withAlpha (0.85f));
  779. g.fillRect (bar.getX(), juce::jmax (bar.getY(), peakY - 1), bar.getWidth(), 2);
  780. }
  781. if (meter.clipped) // clip latch: stays until the meter is clicked
  782. {
  783. g.setColour (colour::meterClip);
  784. g.fillRect (bar.withHeight (4));
  785. }
  786. }
  787. if (hovered (Part::meter))
  788. {
  789. g.setColour (colour::textSecondary.withAlpha (0.5f));
  790. g.drawRect (meters.expanded (1), 1);
  791. }
  792. // the master's dB scale (FL prints it beside the master meter): as many values as fit without overlapping
  793. if (t == 0)
  794. {
  795. const auto scaleFont = font (9.0f);
  796. const auto textHeight = 10.0f;
  797. const auto left = (float) meters.getRight() + 1.0f;
  798. g.setFont (scaleFont);
  799. for (auto db : lynx::meters::scaleMarks ((float) meters.getHeight(), textHeight + 1.0f))
  800. {
  801. const auto y = (float) meters.getBottom() - lynx::meters::scalePosition ((float) db) * (float) meters.getHeight();
  802. g.setColour (db == 0 ? colour::textPrimary : colour::textSecondary);
  803. g.fillRect (juce::Rectangle<float> (left, y - 0.5f, 2.0f, 1.0f));
  804. const auto box = juce::Rectangle<float> (left + 2.0f, y - textHeight * 0.5f, (float) masterScaleWidth - 2.0f, textHeight)
  805. .withY (juce::jlimit ((float) meters.getY(), (float) meters.getBottom() - textHeight, y - textHeight * 0.5f));
  806. textcache::drawText (g, (db > 0 ? "+" : "") + juce::String (db), box, juce::Justification::centredRight, false);
  807. }
  808. }
  809. // fader track and 0 dB mark
  810. const auto railX = (float) fader.getCentreX();
  811. const auto volume = shownVolume (t); // (its automation's value while it plays: the fader moves, issue #12)
  812. const auto capY = (float) fader.getBottom() - volume * (float) fader.getHeight();
  813. theme::fillRoundRect (g, { railX - 2.0f, (float) fader.getY(), 4.0f, (float) fader.getHeight() }, 2.0f, colour::bg0);
  814. theme::fillRoundRect (g, { railX - 2.0f, capY, 4.0f, juce::jmax (0.0f, (float) fader.getBottom() - capY) }, 2.0f, colour::bg6.brighter (0.15f).withAlpha (track.muted ? 0.4f : 1.0f));
  815. const auto unityY = (float) fader.getBottom() - unityFader * (float) fader.getHeight();
  816. g.setColour (colour::textDisabled);
  817. g.drawHorizontalLine ((int) unityY, (float) fader.getX(), railX - 5.0f);
  818. g.drawHorizontalLine ((int) unityY, railX + 5.0f, (float) fader.getRight());
  819. const auto capActive = hovered (Part::fader) || dragging (Part::fader);
  820. const auto capWidth = juce::jmin ((float) fader.getWidth() + 2.0f, 26.0f);
  821. const auto cap = juce::Rectangle<float> (capWidth, 12.0f).withCentre ({ railX, capY });
  822. theme::fillRoundRect (g, cap.translated (0.0f, 1.5f), radius::sm, juce::Colours::black.withAlpha (0.35f));
  823. // same cap as the LookAndFeel's linear faders
  824. theme::fillRoundRect (g, cap, radius::sm, capActive ? juce::Colour (0xffffffff) : juce::Colour (0xffd4d7dd));
  825. g.setColour ((dragging (Part::fader) ? colour::accent : colour::bg0).withAlpha (0.8f));
  826. g.fillRect (cap.withSizeKeepingCentre (capWidth - 8.0f, 1.5f));
  827. g.setColour (colour::textSecondary);
  828. g.setFont (font (type::caption));
  829. if (sp.dbReadout)
  830. textcache::drawFittedText (g, faderToDb (volume) + " dB", juce::Rectangle<int> (x, area.getBottom() + 3, plateWidth, 14), juce::Justification::centred, 1, 0.7f);
  831. // a hardware output target (REA round 156, optional): a small badge at the fader's top right
  832. if (mixeroutput::isCustom (engine, t))
  833. {
  834. const auto text = mixeroutput::label (engine, t, true);
  835. const auto badgeLeft = (float) meterArea (t).getRight() + 3.0f + (t == 0 ? (float) masterScaleWidth : 0.0f);
  836. const auto badge = juce::Rectangle<float> (badgeLeft, (float) area.getY(), (float) (x + w - 6) - badgeLeft, 12.0f);
  837. theme::fillRoundRect (g, badge, 3.0f, colour::bg0.withAlpha (0.85f));
  838. g.setColour (text.endsWith ("?") ? colour::textDisabled : colour::info);
  839. g.setFont (font (9.0f, true));
  840. textcache::drawFittedText (g, text, badge.toNearestInt(), juce::Justification::centred, 1, 0.7f);
  841. }
  842. }
  843. // routing lane: send switch from the selected insert to this one, and its level knob
  844. if (selected > 0 && t != selected && selected < tracks)
  845. {
  846. const auto r = routeArea (t).toFloat();
  847. const auto on = song.routes (selected, t);
  848. const auto possible = on || song.canRoute (selected, t);
  849. const auto feedsSelected = t > 0 && song.routes (t, selected);
  850. if (possible)
  851. {
  852. theme::fillRoundRect (g, r, radius::sm, on ? colour::accent : hovered (Part::route) ? colour::bg5 : colour::bg0);
  853. if (hovered (Part::route))
  854. {
  855. g.setColour (on ? colour::accentHover : colour::textSecondary);
  856. g.drawRoundedRectangle (r.reduced (0.5f), radius::sm, 1.0f);
  857. }
  858. g.setColour (on ? colour::onAccent : colour::textSecondary);
  859. g.setFont (font (10.0f, on));
  860. textcache::drawText (g, (compactLayout ? juce::String() : juce::String::fromUTF8 ("\xe2\x86\x92 ")) + (t == 0 ? juce::String ("M") : juce::String (t)), r.toNearestInt(),
  861. juce::Justification::centred);
  862. // the route's level knob (FL's route knob), on the routes to inserts and to Master
  863. if (on)
  864. drawKnob (g, sendArea (t).toFloat().withSizeKeepingCentre (compactLayout ? 16.0f : 22.0f, compactLayout ? 16.0f : 22.0f),
  865. engine.getAutomationDisplay().shown (AutomationTarget { AutomationTargetKind::mixerSend, selected, t },
  866. faderPosition (song.routeLevel (selected, t))),
  867. false,
  868. dragging (Part::send) ? colour::accent : colour::accentHover, hovered (Part::send) || dragging (Part::send));
  869. }
  870. else if (feedsSelected) // this insert sends into the selected one
  871. {
  872. theme::fillRoundRect (g, r, radius::sm, colour::info.withAlpha (0.18f));
  873. g.setColour (colour::info);
  874. g.setFont (font (10.0f, true));
  875. textcache::drawText (g, (compactLayout ? juce::String() : juce::String::fromUTF8 ("\xe2\x86\x92 ")) + juce::String (selected), r.toNearestInt(), juce::Justification::centred);
  876. }
  877. }
  878. }
  879. paintDividers (pass);
  880. }
  881. paintRouting (g);
  882. }
  883. // Wires in the lane under the strips: from the selected insert to where it sends (accent), and from the
  884. // inserts that feed it (blue). The Master output is drawn dimmer.
  885. void MixerStrips::paintRouting (juce::Graphics& g)
  886. {
  887. using namespace theme;
  888. const auto& song = engine.getSong();
  889. const auto tracks = (int) song.mixer.size();
  890. if (selected <= 0 || selected >= tracks)
  891. return;
  892. const auto top = (float) (laneTop() + switchHeight + sendKnobHeight + 3);
  893. const auto bottom = top + (float) wiresHeight - 2.0f;
  894. const auto centre = [this] (int t) { return (float) stripX (t) + (float) (stripWidthOf (t) - 4) * 0.5f; };
  895. auto wire = [&] (int from, int to, juce::Colour c, float thickness) {
  896. const auto x0 = centre (from), x1 = centre (to);
  897. juce::Path p;
  898. p.startNewSubPath (x0, top);
  899. p.cubicTo (x0, bottom + 2.0f, x1, bottom + 2.0f, x1, top);
  900. g.setColour (c);
  901. g.strokePath (p, juce::PathStrokeType (thickness, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  902. g.fillEllipse (x1 - 2.5f, top - 2.5f, 5.0f, 5.0f);
  903. };
  904. const auto& from = song.mixer[(std::size_t) selected];
  905. for (int t = 1; t < tracks; ++t)
  906. if (t != selected && song.routes (t, selected))
  907. wire (t, selected, colour::info.withAlpha (0.85f), 1.5f);
  908. if (from.toMaster)
  909. wire (selected, 0, colour::accent.withAlpha (0.4f), 1.0f);
  910. for (const auto& send : from.sends)
  911. if (send.target > 0 && send.target < tracks)
  912. wire (selected, send.target, colour::accent.withAlpha (0.5f + 0.5f * juce::jlimit (0.0f, 1.0f, send.level)), 1.8f);
  913. g.setColour (colour::accent);
  914. g.fillEllipse (centre (selected) - 3.0f, top - 3.0f, 6.0f, 6.0f);
  915. }
  916. void MixerStrips::mouseDown (const juce::MouseEvent& e)
  917. {
  918. const auto t = trackAt (e.x);
  919. if (t < 0)
  920. return;
  921. const auto part = partAt (t, e.getPosition());
  922. headerDragTrack = -1;
  923. headerDragged = false;
  924. if (part == Part::add && flmods::popup (e.mods))
  925. {
  926. // FL's "+" menu (round 166d [SHOT]): Add one / Add multiple...
  927. juce::PopupMenu menu;
  928. const auto count = (int) engine.getSong().mixer.size();
  929. const auto room = mixerops::roomForInserts (engine.getSong()) > 0;
  930. menu.addItem (tr ("Add one"), room, false, [this, count] {
  931. engine.editSong ([count] (Song& s) { mixerops::insertTracks (s, juce::jmax (1, count), 1); });
  932. revealed.insert (juce::jmax (1, count));
  933. updateSize();
  934. selectTrack (juce::jmax (1, count));
  935. });
  936. menu.addItem (tr ("Add multiple..."), room, false, [this, count] { askInsertMultiple (juce::jmax (1, count)); });
  937. // FL's "Add from state" (REA round 167q: AddMixerTracksMenu, FUN_012a87d0 / FUN_012a83b0)
  938. juce::PopupMenu fromState;
  939. for (const auto& f : mixerpresets::all())
  940. fromState.addItem (f.getFileNameWithoutExtension(), room, false, [this, count, f] {
  941. if (const auto added = mixerpresets::insertTrack (engine, juce::jmax (1, count), f); added > 0)
  942. {
  943. revealed.insert (added);
  944. updateSize();
  945. selectTrack (added);
  946. }
  947. });
  948. menu.addSubMenu (tr ("Add from state"), fromState, room && fromState.getNumItems() > 0);
  949. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  950. return;
  951. }
  952. if (part == Part::add)
  953. {
  954. if (showUsedOnly) // the first unused insert (hidden) comes back before a new one is added
  955. if (const auto free = engine.getSong().nextFreeInsert(); free > 0 && isHidden (free))
  956. {
  957. revealed.insert (free);
  958. updateSize();
  959. selectTrack (free);
  960. return;
  961. }
  962. const auto added = (int) engine.getSong().mixer.size();
  963. engine.editSong ([] (Song& s) {
  964. if (s.mixer.empty())
  965. s.mixer = Song::defaultMixer (0);
  966. if ((int) s.mixer.size() >= maxMixerTracks)
  967. return;
  968. auto& track = s.mixer.emplace_back();
  969. track.name = "Insert " + std::to_string (s.mixer.size() - 1);
  970. });
  971. if (added < (int) engine.getSong().mixer.size())
  972. {
  973. revealed.insert (added); // shown even while unused
  974. updateSize();
  975. selectTrack (added);
  976. }
  977. return;
  978. }
  979. if (part == Part::arm)
  980. {
  981. if (flmods::popup (e.mods)) // FL: "Record <insert> to" (round 167a); the input box keeps the input menu
  982. mixerinput::chooseRecordTo (engine, t);
  983. else
  984. mixerinput::toggleArm (engine, t, this);
  985. repaint();
  986. return;
  987. }
  988. if (part == Part::input)
  989. {
  990. mixerinput::showMenu (engine, t, this);
  991. return;
  992. }
  993. if (part == Part::meter && ! flmods::popup (e.mods)) // clears the clip latch and the peak hold, and selects (as FL)
  994. {
  995. for (int ch = 0; ch < 2; ++ch)
  996. if (const auto i = (std::size_t) t * 2 + (std::size_t) ch; i < levels.size())
  997. levels[i].resetClip();
  998. repaint (meterArea (t).expanded (2));
  999. }
  1000. if (part == Part::route && flmods::popup (e.mods))
  1001. {
  1002. showSendMenu (t);
  1003. return;
  1004. }
  1005. if (part == Part::send)
  1006. {
  1007. const auto from = selected;
  1008. if (flmods::popup (e.mods))
  1009. {
  1010. juce::PopupMenu menu;
  1011. const auto spec = specFor (Part::send, t);
  1012. menu.addSectionHeader (spec.name + ": " + spec.text (valueOf (Part::send, t)));
  1013. ui::addValueItems (menu, *this, &engine, spec, valueOf (Part::send, t), [this, t] (double v) { setValue (Part::send, t, v); });
  1014. menu.addSeparator();
  1015. menu.addItem (t == 0 ? tr ("Remove the route to Master") : tr ("Remove this send"),
  1016. [this, from, t] { engine.editSong ([from, t] (Song& s) { s.setRoute (from, t, false); }); });
  1017. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1018. return;
  1019. }
  1020. if (ui::isResetClick (e))
  1021. {
  1022. setValue (Part::send, t, unityFader); // 0 dB
  1023. showTip (Part::send, t, true);
  1024. return;
  1025. }
  1026. dragPart = Part::send;
  1027. dragTrack = t;
  1028. drag.begin (e, valueOf (Part::send, t));
  1029. showTip (Part::send, t, false);
  1030. return;
  1031. }
  1032. if (part == Part::mute && (flmods::popup (e.mods) || flmods::ctrl (e.mods))) // solo on the same LED
  1033. {
  1034. soloExclusive (t);
  1035. return;
  1036. }
  1037. if (part == Part::route)
  1038. {
  1039. // the selection is the send source: don't change it. FL (round 170b, REA FUN_012aa110): the arrow acts on every
  1040. // selected track; Ctrl = route to this track only, Shift = sidechain, Ctrl+Shift = sidechain only.
  1041. const auto from = selected;
  1042. const auto sources = selection;
  1043. using K = mixerops::RouteKind;
  1044. if (flmods::ctrl (e.mods) || e.mods.isShiftDown())
  1045. {
  1046. routeSelection (t, flmods::ctrl (e.mods) ? (e.mods.isShiftDown() ? K::sidechainOnly : K::routeOnly) : K::sidechain);
  1047. return;
  1048. }
  1049. const auto on = engine.getSong().routes (from, t);
  1050. engine.editSong ([sources, t, on] (Song& s) { mixerops::switchSelectedRoute (s, sources, t, ! on); });
  1051. if (! on && engine.getSong().routes (from, t)) // just enabled (at 0 dB): dragging adjusts the level, like the route knob
  1052. {
  1053. dragPart = Part::send;
  1054. dragTrack = t;
  1055. drag.begin (e, unityFader);
  1056. }
  1057. return;
  1058. }
  1059. if ((part == Part::body || part == Part::header || part == Part::meter) && ! flmods::popup (e.mods) && flmods::ctrl (e.mods) && t > 0)
  1060. {
  1061. // FL (round 170b, REA FUN_012c5800 / FUN_012c5f60): Ctrl+click (and drag across the strips) selects the tracks
  1062. // from here to the mouse, alone; Ctrl+Shift adds them to the selection, or removes them when the click starts
  1063. // on a selected track
  1064. selectAnchor = t;
  1065. selectAdding = ! e.mods.isShiftDown() || ! std::binary_search (selection.begin(), selection.end(), t);
  1066. selectBase.clear();
  1067. if (e.mods.isShiftDown())
  1068. selectBase = selection;
  1069. dragSelectTo (t);
  1070. return;
  1071. }
  1072. if ((part == Part::body || part == Part::header || part == Part::meter) && ! flmods::popup (e.mods) && e.mods.isShiftDown() && t > 0)
  1073. {
  1074. auto s = selection;
  1075. {
  1076. s.clear();
  1077. for (int i = juce::jmin (selected, t); i <= juce::jmax (selected, t); ++i)
  1078. s.push_back (i);
  1079. }
  1080. setSelection (s, std::find (s.begin(), s.end(), t) != s.end() ? t : s.front());
  1081. return;
  1082. }
  1083. // a plain click on a track outside the selection selects only it; inside, the group stays
  1084. if (! std::binary_search (selection.begin(), selection.end(), t))
  1085. setSelection ({ t }, t);
  1086. else if (selected != t)
  1087. setSelection (selection, t);
  1088. if (part == Part::pan || part == Part::fader || part == Part::stereo)
  1089. {
  1090. if (flmods::popup (e.mods))
  1091. {
  1092. ui::showValueMenu (*this, part == Part::stereo ? nullptr : &engine, specFor (part, t), valueOf (part, t),
  1093. [this, part, t] (double v) { setValue (part, t, v); });
  1094. return;
  1095. }
  1096. if (ui::isResetClick (e))
  1097. {
  1098. setValue (part, t, specFor (part, t).defaultValue);
  1099. showTip (part, t, true);
  1100. return;
  1101. }
  1102. }
  1103. if (flmods::popup (e.mods))
  1104. {
  1105. showMenu (t);
  1106. return;
  1107. }
  1108. const auto& track = engine.getSong().mixer[(std::size_t) t];
  1109. switch (part)
  1110. {
  1111. case Part::mute:
  1112. engine.editSong ([t] (Song& s) { s.mixer[(std::size_t) t].muted = ! s.mixer[(std::size_t) t].muted; });
  1113. return;
  1114. case Part::solo:
  1115. engine.editSong ([t] (Song& s) { s.mixer[(std::size_t) t].solo = ! s.mixer[(std::size_t) t].solo; });
  1116. return;
  1117. case Part::header:
  1118. if (t > 0)
  1119. headerDragTrack = t; // dragging sideways reorders
  1120. return;
  1121. case Part::stereo:
  1122. dragPart = part;
  1123. dragTrack = t;
  1124. dragStartValue = track.stereo;
  1125. drag.begin (e, dragStartValue);
  1126. groupStart.clear();
  1127. showTip (part, t, false);
  1128. return;
  1129. case Part::pan:
  1130. case Part::fader:
  1131. dragPart = part;
  1132. dragTrack = t;
  1133. dragStartValue = part == Part::pan ? track.pan : track.volume;
  1134. if (part == Part::fader && ! flmods::ctrl (e.mods)) // clicking the track jumps the fader there
  1135. {
  1136. const auto area = faderRail (t);
  1137. const auto capY = area.getBottom() - track.volume * (float) area.getHeight();
  1138. if (std::abs ((float) e.y - capY) > 9.0f)
  1139. {
  1140. dragStartValue = juce::jlimit (0.0f, 1.0f, (float) (area.getBottom() - e.y) / (float) area.getHeight());
  1141. engine.editSong ([t, v = dragStartValue] (Song& s) { s.mixer[(std::size_t) t].volume = v; });
  1142. }
  1143. }
  1144. drag.begin (e, dragStartValue);
  1145. groupStart.clear();
  1146. groupGrab = dragStartValue;
  1147. if (selection.size() > 1) // the selected strips follow, keeping their offsets
  1148. for (auto s : selection)
  1149. if (s != t && s < (int) engine.getSong().mixer.size())
  1150. groupStart.push_back ({ s, part == Part::pan ? engine.getSong().mixer[(std::size_t) s].pan
  1151. : engine.getSong().mixer[(std::size_t) s].volume });
  1152. showTip (part, t, false);
  1153. return;
  1154. case Part::arm:
  1155. case Part::route:
  1156. case Part::send:
  1157. case Part::meter:
  1158. case Part::body:
  1159. case Part::none:
  1160. case Part::add:
  1161. return;
  1162. }
  1163. }
  1164. void MixerStrips::dragSelectTo (int t)
  1165. {
  1166. const auto count = (int) engine.getSong().mixer.size();
  1167. if (selectAnchor < 1 || count < 2)
  1168. return;
  1169. t = juce::jlimit (1, count - 1, t);
  1170. std::set<int> s (selectBase.begin(), selectBase.end());
  1171. for (int i = juce::jmin (selectAnchor, t); i <= juce::jmax (selectAnchor, t); ++i)
  1172. {
  1173. if (isHidden (i) && i != t && i != selectAnchor)
  1174. continue;
  1175. if (selectAdding)
  1176. s.insert (i);
  1177. else
  1178. s.erase (i);
  1179. }
  1180. if (s.empty())
  1181. s.insert (t);
  1182. // the track under the mouse becomes the current one (FL); when removing, a track that stays selected
  1183. auto primary = t;
  1184. if (! s.count (primary))
  1185. primary = s.count (selected) ? selected : *s.rbegin();
  1186. setSelection ({ s.begin(), s.end() }, primary);
  1187. }
  1188. void MixerStrips::mouseDrag (const juce::MouseEvent& e)
  1189. {
  1190. if (selectAnchor > 0)
  1191. {
  1192. if (const auto t = trackAt (juce::jlimit (0, getWidth() - 1, e.x)); t >= 0)
  1193. dragSelectTo (t);
  1194. return;
  1195. }
  1196. if (headerDragTrack > 0)
  1197. {
  1198. if (! headerDragged && std::abs (e.getDistanceFromDragStartX()) < 6)
  1199. return;
  1200. headerDragged = true;
  1201. setMouseCursor (juce::MouseCursor::LeftRightResizeCursor);
  1202. const auto count = (int) engine.getSong().mixer.size();
  1203. const auto target = trackAt (e.x);
  1204. if (target < 1 || target >= count)
  1205. return;
  1206. for (int guard = 0; guard < count && selected != target; ++guard)
  1207. if (! moveSelected (target < selected ? -1 : 1))
  1208. break;
  1209. headerDragTrack = selected;
  1210. repaint();
  1211. return;
  1212. }
  1213. if (dragPart == Part::none)
  1214. return;
  1215. const auto t = dragTrack;
  1216. setValue (dragPart, t, drag.update (e, specFor (dragPart, t)));
  1217. showTip (dragPart, t, false);
  1218. }
  1219. ui::ValueSpec MixerStrips::specFor (Part part, int t) const
  1220. {
  1221. const auto& song = engine.getSong();
  1222. const auto nameOf = [&song] (int track) {
  1223. return track >= 0 && track < (int) song.mixer.size() ? juce::String::fromUTF8 (song.mixer[(std::size_t) track].name.c_str()) : juce::String();
  1224. };
  1225. const auto name = nameOf (t);
  1226. if (part == Part::pan)
  1227. {
  1228. auto spec = ui::panSpec (name + " - " + tr ("Pan"));
  1229. spec.pixelsForRange = 150.0;
  1230. spec.target = AutomationTarget { AutomationTargetKind::mixerPan, t };
  1231. return spec;
  1232. }
  1233. if (part == Part::stereo)
  1234. return stereoSpec (name + " - " + tr ("Stereo separation"));
  1235. if (part == Part::send)
  1236. {
  1237. auto spec = sendSpec (nameOf (selected) + juce::String::fromUTF8 (" \xe2\x86\x92 ") + name + " - " + (t == 0 ? tr ("Level to Master") : tr ("Send level")));
  1238. spec.target = AutomationTarget { AutomationTargetKind::mixerSend, selected, t }; // automatable (issue #12)
  1239. return spec;
  1240. }
  1241. auto spec = ui::faderSpec (name + " - " + tr ("Volume"), unityFader);
  1242. spec.pixelsForRange = juce::jmax (60, faderRail (juce::jmax (0, t)).getHeight());
  1243. spec.target = AutomationTarget { AutomationTargetKind::mixerVolume, t };
  1244. return spec;
  1245. }
  1246. double MixerStrips::valueOf (Part part, int t) const
  1247. {
  1248. const auto& song = engine.getSong();
  1249. const auto& track = song.mixer[(std::size_t) t];
  1250. if (part == Part::send)
  1251. {
  1252. return faderPosition (song.routeLevel (selected, t));
  1253. }
  1254. return part == Part::pan ? track.pan : part == Part::stereo ? track.stereo : track.volume;
  1255. }
  1256. void MixerStrips::setValue (Part part, int t, double value)
  1257. {
  1258. if (t < 0 || t >= (int) engine.getSong().mixer.size())
  1259. return;
  1260. if (part == Part::send)
  1261. {
  1262. const auto from = selected;
  1263. engine.editSong ([from, t, v = faderGain ((float) value)] (Song& s) { s.setRouteLevel (from, t, v); });
  1264. return;
  1265. }
  1266. if (part == Part::stereo)
  1267. {
  1268. engine.editLevels ([t, v = (float) value] (Song& s) { s.mixer[(std::size_t) t].stereo = v; });
  1269. return;
  1270. }
  1271. // during a drag of a selected strip, the other selected strips move by the same amount
  1272. const auto delta = (float) value - groupGrab;
  1273. const auto group = dragTrack == t && dragPart == part ? groupStart : std::vector<std::pair<int, float>> {};
  1274. if (part == Part::pan)
  1275. engine.editLevels ([t, v = (float) value, group, delta] (Song& s) {
  1276. s.mixer[(std::size_t) t].pan = v;
  1277. for (auto [other, start] : group)
  1278. if (other < (int) s.mixer.size())
  1279. s.mixer[(std::size_t) other].pan = juce::jlimit (-1.0f, 1.0f, start + delta);
  1280. });
  1281. else if (part == Part::fader)
  1282. engine.editLevels ([t, v = (float) value, group, delta] (Song& s) {
  1283. s.mixer[(std::size_t) t].volume = v;
  1284. for (auto [other, start] : group)
  1285. if (other < (int) s.mixer.size())
  1286. s.mixer[(std::size_t) other].volume = juce::jlimit (0.0f, 1.0f, start + delta);
  1287. });
  1288. }
  1289. void MixerStrips::setSelection (std::vector<int> tracks, int primary)
  1290. {
  1291. const auto count = (int) engine.getSong().mixer.size();
  1292. tracks.erase (std::remove_if (tracks.begin(), tracks.end(), [count] (int t) { return t < 0 || t >= count; }), tracks.end());
  1293. primary = juce::jlimit (0, juce::jmax (0, count - 1), primary);
  1294. tracks.push_back (primary);
  1295. std::sort (tracks.begin(), tracks.end());
  1296. tracks.erase (std::unique (tracks.begin(), tracks.end()), tracks.end());
  1297. selection = tracks;
  1298. const auto changed = primary != selected;
  1299. selected = primary;
  1300. repaint();
  1301. if (changed && onSelectionChanged)
  1302. onSelectionChanged (selected);
  1303. }
  1304. bool MixerStrips::moveSelected (int delta)
  1305. {
  1306. auto moved = selection;
  1307. bool ok = false;
  1308. engine.editSongStructural ([&] (Song& s) { ok = mixerops::moveTracks (s, moved, delta); });
  1309. if (ok)
  1310. setSelection (moved, juce::jlimit (1, (int) engine.getSong().mixer.size() - 1, selected + (delta < 0 ? -1 : 1)));
  1311. return ok;
  1312. }
  1313. void MixerStrips::linkSelectedChannels (bool startingHere)
  1314. {
  1315. const auto channels = engine.getSelectedChannels();
  1316. engine.editSong ([channels, t = selected, startingHere] (Song& s) { mixerops::linkChannels (s, channels, t, startingHere); });
  1317. }
  1318. void MixerStrips::selectLinkedChannels()
  1319. {
  1320. const auto channels = mixerops::channelsOn (engine.getSong(), selected);
  1321. if (! channels.empty())
  1322. engine.setChannelSelection (channels, channels.front());
  1323. }
  1324. void MixerStrips::soloExclusive (int t)
  1325. {
  1326. if (t <= 0)
  1327. return;
  1328. // solo only this track; again on the only soloed track clears the solo
  1329. engine.editSong ([t] (Song& s) {
  1330. const auto alone = s.mixer[(std::size_t) t].solo
  1331. && std::none_of (s.mixer.begin() + 1, s.mixer.end(), [&] (const MixerTrack& m) { return &m != &s.mixer[(std::size_t) t] && m.solo; });
  1332. for (std::size_t i = 1; i < s.mixer.size(); ++i)
  1333. s.mixer[i].solo = ! alone && (int) i == t;
  1334. });
  1335. }
  1336. void MixerStrips::routeSelection (int t, mixerops::RouteKind kind)
  1337. {
  1338. using K = mixerops::RouteKind;
  1339. int linked = 0;
  1340. engine.editSong ([sources = selection, t, kind, &linked] (Song& s) {
  1341. mixerops::routeSelectedTo (s, sources, t, kind);
  1342. if (t >= 0 && t < (int) s.mixer.size())
  1343. for (const auto& fx : s.mixer[(std::size_t) t].effects)
  1344. linked += std::find (sources.begin(), sources.end(), fx.sidechain) != sources.end() ? 1 : 0;
  1345. });
  1346. if ((kind == K::sidechain || kind == K::sidechainOnly) && t > 0 && linked == 0)
  1347. // (round 170h: in the hint bar, not a box — FL says nothing here; adding the compressor links it)
  1348. ui::postHint ({ tr ("Sidechain") + ": " + tr ("The link was made; add a compressor to this insert to use it."), {} }, 6000);
  1349. }
  1350. void MixerStrips::showSendMenu (int t)
  1351. {
  1352. const auto& song = engine.getSong();
  1353. const auto from = selected;
  1354. if (from <= 0 || from == t)
  1355. return;
  1356. const auto fromName = juce::String::fromUTF8 (song.mixer[(std::size_t) from].name.c_str());
  1357. juce::PopupMenu menu;
  1358. const auto sources = (int) std::count_if (selection.begin(), selection.end(), [t] (int x) { return x > 0 && x != t; });
  1359. menu.addSectionHeader ((sources > 1 ? tr ("{0} selected tracks", { juce::String (sources) }) : fromName)
  1360. + juce::String::fromUTF8 (" \xe2\x86\x92 ") + juce::String::fromUTF8 (song.mixer[(std::size_t) t].name.c_str()));
  1361. // FL's route arrow menu (round 168s, issue #32 [SHOT] r168s c_f10): route / route only / sidechain / sidechain only
  1362. const auto on = song.routes (from, t);
  1363. const auto can = on || song.canRoute (from, t);
  1364. using K = mixerops::RouteKind;
  1365. // FL (round 170b, REA FUN_012aca70): every item acts on all the selected tracks, not only the current one
  1366. auto route = [this, t] (K kind) { routeSelection (t, kind); };
  1367. menu.addItem (tr ("Route to this track"), can && ! on, false, [route] { route (K::route); });
  1368. menu.addItem (tr ("Route to this track only"), can, false, [route] { route (K::routeOnly); });
  1369. menu.addSeparator();
  1370. menu.addItem (tr ("Sidechain to this track"), t > 0 && can, false, [route] { route (K::sidechain); });
  1371. menu.addItem (tr ("Sidechain to this track only"), t > 0 && can, false, [route] { route (K::sidechainOnly); });
  1372. if (on)
  1373. {
  1374. menu.addSeparator();
  1375. menu.addItem (t == 0 ? tr ("Remove the route to Master") : tr ("Remove this send"),
  1376. [this, from, t] { engine.editSong ([from, t] (Song& s) { s.setRoute (from, t, false); }); });
  1377. }
  1378. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1379. }
  1380. void MixerStrips::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  1381. {
  1382. const auto t = trackAt (e.x);
  1383. if (t > 0 && t < (int) engine.getSong().mixer.size() && e.mods.isShiftDown())
  1384. if (const auto part = partAt (t, e.getPosition()); part == Part::body || part == Part::header)
  1385. {
  1386. if (! std::binary_search (selection.begin(), selection.end(), t))
  1387. setSelection ({ t }, t);
  1388. moveSelected ((wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? -1 : 1);
  1389. return;
  1390. }
  1391. // (a spin that is scrolling the strips goes on scrolling over the faders and knobs, round 169c)
  1392. if (t >= 0 && t < (int) engine.getSong().mixer.size() && ! ui::wheelScrolling())
  1393. if (const auto part = partAt (t, e.getPosition()); part == Part::pan || part == Part::fader || part == Part::stereo || part == Part::send)
  1394. {
  1395. if (const auto v = ui::wheelValue (valueOf (part, t), e, wheel, specFor (part, t)))
  1396. {
  1397. setValue (part, t, *v);
  1398. showTip (part, t, true);
  1399. }
  1400. return;
  1401. }
  1402. ui::noteWheelScroll(); // the wheel scrolls the strips (the viewport)
  1403. juce::Component::mouseWheelMove (e, wheel);
  1404. }
  1405. ui::Hint MixerStrips::hintAt (juce::Point<int> p)
  1406. {
  1407. const auto active = dragPart == Part::pan || dragPart == Part::fader || dragPart == Part::stereo || dragPart == Part::send;
  1408. const auto t = active ? dragTrack : trackAt (p.x);
  1409. const auto& song = engine.getSong();
  1410. ui::Hint h;
  1411. if (t < 0 || t >= (int) song.mixer.size())
  1412. {
  1413. if (t == (int) song.mixer.size())
  1414. h.text = tr ("Add a mixer insert");
  1415. return h;
  1416. }
  1417. const auto part = active ? dragPart : partAt (t, p);
  1418. const auto name = juce::String::fromUTF8 (song.mixer[(std::size_t) t].name.c_str());
  1419. const auto gesture = ui::valueGestures();
  1420. // the channels that play into this insert (FL shows them by the insert; LYNX in the hint)
  1421. auto feeds = [&song, t, tracks = (int) song.mixer.size()] {
  1422. juce::StringArray names;
  1423. for (const auto& c : song.channels)
  1424. if (juce::jlimit (0, tracks - 1, c.mixerTrack) == t)
  1425. names.add (juce::String::fromUTF8 (c.name.c_str()));
  1426. if (names.isEmpty())
  1427. return juce::String();
  1428. const auto shown = names.size() > 6 ? names[0] + ", " + names[1] + ", " + names[2] + " +" + juce::String (names.size() - 3)
  1429. : names.joinIntoString (", ");
  1430. return " " + tr ("Channels: {0}", { shown });
  1431. };
  1432. // FL's "Track latency compensation" label (REA round 165f-mixer): the manual latency and the bypass, when set
  1433. auto latency = [&song, t] {
  1434. const auto& track = song.mixer[(std::size_t) t];
  1435. juce::String text;
  1436. if (track.latencyMs != 0.0f)
  1437. text << " " << tr ("Track latency: {0}", { (track.latencyMs > 0.0f ? "+" : "") + juce::String (track.latencyMs, 2) + " ms" });
  1438. if (track.latencyBypass == LatencyBypass::always)
  1439. text << " " << tr ("Bypass track latency compensation") << ": " << tr ("Always");
  1440. else if (track.latencyBypass == LatencyBypass::whenRecordingOrStopped)
  1441. text << " " << tr ("Bypass track latency compensation") << ": " << tr ("When recording or not playing");
  1442. return text;
  1443. };
  1444. switch (part)
  1445. {
  1446. case Part::pan:
  1447. case Part::fader:
  1448. case Part::stereo:
  1449. case Part::send:
  1450. return ui::valueHint (specFor (part, t), valueOf (part, t), gesture);
  1451. case Part::mute: h.text = name + " - " + tr ("Click: mute. Right-click or Ctrl+click: solo"); break;
  1452. case Part::arm: h.text = name + " - " + mixerinput::armHint (engine, t); h.hasMenu = true; break;
  1453. case Part::input: h.text = name + " - " + tr ("Input level of this insert's audio input [LMB] choose the input"); h.hasMenu = true; break;
  1454. case Part::solo: h.text = name + " - " + tr ("Solo"); break;
  1455. case Part::meter: h.text = name + " - " + tr ("Peak meter (left/right) with peak hold [LMB] selects the track and clears the clip light"); break;
  1456. case Part::route: h.text = name + " - " + tr ("Route the selected inserts to this one (drag after enabling: level). Ctrl+click: this track only, Shift: sidechain, Ctrl+Shift: sidechain only, right-click: menu"); h.hasMenu = true; break;
  1457. case Part::add: h.text = tr ("Add a mixer insert"); break;
  1458. case Part::header:
  1459. h.text = name + " - " + tr ("[LMB] selects [Ctrl]+[LMB] or drag across: range [Ctrl]+[Shift]+[LMB] adds or removes [LMB] drag sideways reorders [RMB] insert menu") + feeds() + latency();
  1460. h.hasMenu = true;
  1461. if (engine.insertPlaysStandIn (t))
  1462. h.text = name + " - " + tr ("Stand-in: a plugin of this insert is not installed on this PC, a render of its sound plays (the plugins' settings are kept)");
  1463. break;
  1464. case Part::body:
  1465. case Part::none:
  1466. h.text = name + " - " + tr ("Click selects the insert (Ctrl+click or drag across: range, Ctrl+Shift: add or remove), right-click opens its menu; Alt+Left/Right moves the selection") + feeds() + latency();
  1467. h.hasMenu = true;
  1468. break;
  1469. }
  1470. return h;
  1471. }
  1472. void MixerStrips::mouseUp (const juce::MouseEvent&)
  1473. {
  1474. if (headerDragged)
  1475. setMouseCursor (juce::MouseCursor::NormalCursor);
  1476. if (dragPart != Part::none || headerDragged)
  1477. repaint();
  1478. headerDragTrack = -1;
  1479. headerDragged = false;
  1480. selectAnchor = -1;
  1481. selectBase.clear();
  1482. dragPart = Part::none;
  1483. dragTrack = -1;
  1484. drag.end();
  1485. ui::hideValueTip();
  1486. ui::clearPostedHint();
  1487. }
  1488. void MixerStrips::mouseDoubleClick (const juce::MouseEvent& e)
  1489. {
  1490. const auto t = trackAt (e.x);
  1491. if (t < 0 || t >= (int) engine.getSong().mixer.size())
  1492. return;
  1493. const auto part = partAt (t, e.getPosition());
  1494. if (part == Part::fader || part == Part::pan || part == Part::stereo || part == Part::send)
  1495. {
  1496. setValue (part, t, specFor (part, t).defaultValue);
  1497. showTip (part, t, true);
  1498. }
  1499. }
  1500. void MixerStrips::selectTrack (int track)
  1501. {
  1502. selected = juce::jlimit (0, juce::jmax (0, (int) engine.getSong().mixer.size() - 1), track);
  1503. selection = { selected };
  1504. repaint();
  1505. if (onSelectionChanged)
  1506. onSelectionChanged (selected);
  1507. }
  1508. namespace
  1509. {
  1510. // The 3 knobs of each band of the track's built-in EQ (gain, frequency, width).
  1511. class TrackEqEditor final : public juce::Component
  1512. {
  1513. public:
  1514. TrackEqEditor (AudioEngine& e, int t)
  1515. : engine (e),
  1516. track (t)
  1517. {
  1518. const juce::String bands[] = { tr ("Low"), tr ("Mid"), tr ("High") };
  1519. const auto& eq = engine.getSong().mixer[(std::size_t) track].eq;
  1520. for (int b = 0; b < 3; ++b)
  1521. {
  1522. titles[(std::size_t) b].setText (bands[b], juce::dontSendNotification);
  1523. titles[(std::size_t) b].setJustificationType (juce::Justification::centred);
  1524. addAndMakeVisible (titles[(std::size_t) b]);
  1525. auto& gain = knobs[(std::size_t) b][0];
  1526. setup (gain, -18.0, 18.0, 0.1, " dB", eq.gainDb[(std::size_t) b]);
  1527. gain.setDoubleClickReturnValue (true, 0.0);
  1528. auto& hz = knobs[(std::size_t) b][1];
  1529. setup (hz, 10.0, 16000.0, 1.0, " Hz", eq.hz[(std::size_t) b]);
  1530. hz.setSkewFactorFromMidPoint (1000.0);
  1531. auto& width = knobs[(std::size_t) b][2];
  1532. setup (width, 0.0, 1.0, 0.01, "", eq.width[(std::size_t) b]);
  1533. width.setTooltip (b == 1 ? tr ("Peak width (Q)") : tr ("Shelf slope"));
  1534. }
  1535. setSize (3 * 90, 3 * 74 + 24);
  1536. }
  1537. void resized() override
  1538. {
  1539. auto area = getLocalBounds();
  1540. auto header = area.removeFromTop (20);
  1541. for (int b = 0; b < 3; ++b)
  1542. {
  1543. titles[(std::size_t) b].setBounds (header.removeFromLeft (90));
  1544. auto column = area.removeFromLeft (90);
  1545. for (auto& k : knobs[(std::size_t) b])
  1546. k.setBounds (column.removeFromTop (74));
  1547. }
  1548. }
  1549. private:
  1550. void setup (juce::Slider& s, double lo, double hi, double step, const char* suffix, float value)
  1551. {
  1552. s.setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  1553. s.setTextBoxStyle (juce::Slider::TextBoxBelow, false, 72, 16);
  1554. s.setRange (lo, hi, step);
  1555. s.setTextValueSuffix (suffix);
  1556. s.setValue (value, juce::dontSendNotification);
  1557. s.onValueChange = [this] { apply(); };
  1558. addAndMakeVisible (s);
  1559. }
  1560. void apply()
  1561. {
  1562. TrackEq eq;
  1563. for (std::size_t b = 0; b < 3; ++b)
  1564. {
  1565. eq.gainDb[b] = (float) knobs[b][0].getValue();
  1566. eq.hz[b] = (float) knobs[b][1].getValue();
  1567. eq.width[b] = (float) knobs[b][2].getValue();
  1568. }
  1569. engine.editSong ([t = track, eq] (Song& s) {
  1570. if (t < (int) s.mixer.size())
  1571. s.mixer[(std::size_t) t].eq = eq;
  1572. });
  1573. }
  1574. AudioEngine& engine;
  1575. int track;
  1576. std::array<juce::Label, 3> titles;
  1577. std::array<std::array<juce::Slider, 3>, 3> knobs; // [band][gain, frequency, width]
  1578. };
  1579. } // namespace
  1580. void MixerStrips::showTrackEq (int t)
  1581. {
  1582. auto editor = std::make_unique<TrackEqEditor> (engine, t);
  1583. juce::CallOutBox::launchAsynchronously (std::move (editor), getScreenBounds().withSize (10, 10).translated (getMouseXYRelative().x, getMouseXYRelative().y), nullptr);
  1584. }
  1585. namespace
  1586. {
  1587. juce::File mixerStatesFolder()
  1588. {
  1589. return lynx::platform::documentsFolder().getChildFile ("LYNX/Mixer states");
  1590. }
  1591. std::unique_ptr<juce::FileChooser>& mixerStateChooser()
  1592. {
  1593. static std::unique_ptr<juce::FileChooser> chooser;
  1594. return chooser;
  1595. }
  1596. // --- FL's track latency menu (REA round 165f-mixer: DelayMenu, FUN_012ae090 / FUN_012ad520 / FUN_012acd30) ---------
  1597. double sampleRateOf (const AudioEngine& engine)
  1598. {
  1599. return juce::jmax (1.0, engine.getTransport().sampleRate.load());
  1600. }
  1601. // The track's latency in the current PDC plan (its output: inputs + effects + manual), in ms
  1602. double trackLatencyMs (const AudioEngine& engine, int t)
  1603. {
  1604. const auto& plan = engine.getPdcPlan();
  1605. return t >= 0 && t < (int) plan.outLat.size() ? 1000.0 * plan.outLat[(std::size_t) t] / sampleRateOf (engine) : 0.0;
  1606. }
  1607. // FL's label: "(none)" or "<ms> ms / <samples> smp" of the manual latency
  1608. juce::String manualLatencyText (const AudioEngine& engine, const MixerTrack& track)
  1609. {
  1610. if (track.latencyMs == 0.0f)
  1611. return tr ("(none)");
  1612. const auto samples = manualLatencySamples (track, sampleRateOf (engine));
  1613. return (track.latencyMs > 0.0f ? "+" : "") + juce::String (track.latencyMs, 2) + " ms / " + (samples > 0 ? "+" : "") + juce::String (samples) + " smp";
  1614. }
  1615. void setTrackLatency (AudioEngine& engine, int t, double ms)
  1616. {
  1617. if (t < 0 || t >= (int) engine.getSong().mixer.size() || ! std::isfinite (ms))
  1618. return;
  1619. const auto v = (float) juce::jlimit ((double) -maxTrackLatencyMs, (double) maxTrackLatencyMs, ms);
  1620. engine.editSong ([t, v] (Song& s) { s.mixer[(std::size_t) t].latencyMs = v; });
  1621. }
  1622. // "Set in ms / samples / beats": FL's input box, the value in that unit (FUN_012ad520)
  1623. void askTrackLatency (AudioEngine& engine, int t, int unit)
  1624. {
  1625. const auto& track = engine.getSong().mixer[(std::size_t) t];
  1626. const auto rate = sampleRateOf (engine);
  1627. const auto bpm = juce::jmax (1.0, engine.getSong().bpm);
  1628. const juce::String units[] = { tr ("Latency (ms)"), tr ("Latency (samples)"), tr ("Latency (beats)") };
  1629. const auto value = unit == 0 ? juce::String (track.latencyMs, 2)
  1630. : unit == 1 ? juce::String (manualLatencySamples (track, rate))
  1631. : juce::String (track.latencyMs * bpm / 60000.0, 6);
  1632. auto* w = new juce::AlertWindow (tr ("Track latency"),
  1633. tr ("Positive: the other tracks wait for this one (it plays earlier). Negative: this track is delayed."),
  1634. juce::MessageBoxIconType::NoIcon);
  1635. w->addTextEditor ("v", value, units[juce::jlimit (0, 2, unit)]);
  1636. w->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1637. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  1638. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, &engine, t, unit, rate, bpm] (int result) {
  1639. if (result != 1)
  1640. return;
  1641. const auto text = w->getTextEditorContents ("v").trim().replaceCharacter (',', '.');
  1642. if (! text.containsAnyOf ("0123456789"))
  1643. return;
  1644. const auto v = text.getDoubleValue();
  1645. setTrackLatency (engine, t, unit == 0 ? v : unit == 1 ? v * 1000.0 / rate : v * 60000.0 / bpm);
  1646. }), true);
  1647. }
  1648. juce::PopupMenu trackLatencyMenu (AudioEngine& engine, int t)
  1649. {
  1650. const auto& song = engine.getSong();
  1651. const auto& track = song.mixer[(std::size_t) t];
  1652. juce::PopupMenu menu;
  1653. // FL's hint "^Track latency": "<x>ms (auto) <y>ms (manual)"
  1654. // auto = the plan's latency without the manual part, in samples (no ms rounding left over when no plugin has any)
  1655. const auto total = trackLatencyMs (engine, t);
  1656. const auto rate = sampleRateOf (engine);
  1657. const auto autoMs = total - 1000.0 * lynx::manualLatencySamples (track, rate) / rate;
  1658. menu.addSectionHeader (tr ("Latency {0} ms (auto {1} ms, manual {2} ms)",
  1659. { juce::String (total, 2), juce::String (std::abs (autoMs) < 0.005 ? 0.0 : autoMs, 2), juce::String (track.latencyMs, 2) }));
  1660. menu.addItem (tr ("Reset"), track.latencyMs != 0.0f, false, [&engine, t] { setTrackLatency (engine, t, 0.0); });
  1661. menu.addItem (tr ("Set in ms..."), [&engine, t] { askTrackLatency (engine, t, 0); });
  1662. menu.addItem (tr ("Set in samples..."), [&engine, t] { askTrackLatency (engine, t, 1); });
  1663. menu.addItem (tr ("Set in beats..."), [&engine, t] { askTrackLatency (engine, t, 2); });
  1664. {
  1665. // FL's "Set from": the tracks whose latency is not zero; this track's total becomes theirs (FUN_012acd30)
  1666. juce::PopupMenu from;
  1667. for (int o = 0; o < (int) song.mixer.size(); ++o)
  1668. {
  1669. const auto ms = trackLatencyMs (engine, o);
  1670. if (o == t || std::abs (ms) < 0.005)
  1671. continue;
  1672. const auto name = o == 0 ? tr ("Master") : juce::String (o) + " " + juce::String::fromUTF8 (song.mixer[(std::size_t) o].name.c_str());
  1673. from.addItem (name + " (" + juce::String (ms, 2) + " ms)", [&engine, t, o] {
  1674. const auto manual = (double) engine.getSong().mixer[(std::size_t) t].latencyMs + trackLatencyMs (engine, o) - trackLatencyMs (engine, t);
  1675. if (manual < 0.0)
  1676. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Track latency"),
  1677. tr ("The delay introduced by this mixer track is higher than the delay introduced by the source "
  1678. "mixer track. Set a make-up latency on the source track instead."));
  1679. else
  1680. setTrackLatency (engine, t, manual);
  1681. });
  1682. }
  1683. menu.addSubMenu (tr ("Set from"), from, from.getNumItems() > 0);
  1684. }
  1685. menu.addSeparator();
  1686. menu.addItem (tr ("Compensate for master latency"), track.outputChannel >= 0, track.compensateMasterLatency, [&engine, t] {
  1687. engine.editSong ([t] (Song& s) { s.mixer[(std::size_t) t].compensateMasterLatency = ! s.mixer[(std::size_t) t].compensateMasterLatency; });
  1688. });
  1689. if (t > 0)
  1690. {
  1691. menu.addSectionHeader (tr ("Bypass track latency compensation"));
  1692. const std::pair<const char*, LatencyBypass> modes[] = { { TR_NOOP ("Never"), LatencyBypass::never },
  1693. { TR_NOOP ("Always"), LatencyBypass::always },
  1694. { TR_NOOP ("When recording or not playing"), LatencyBypass::whenRecordingOrStopped } };
  1695. for (const auto& [label, mode] : modes)
  1696. menu.addItem (tr (label), true, track.latencyBypass == mode, [&engine, t, mode = mode] {
  1697. engine.editSong ([t, mode] (Song& s) { s.mixer[(std::size_t) t].latencyBypass = mode; });
  1698. });
  1699. }
  1700. return menu;
  1701. }
  1702. } // namespace
  1703. bool loadMixerTrackState (AudioEngine& engine, int track, const juce::File& file, bool asNewInsert)
  1704. {
  1705. if (track < 0 || track >= (int) engine.getSong().mixer.size())
  1706. return false;
  1707. if (asNewInsert)
  1708. return mixerpresets::insertTrack (engine, juce::jmax (1, track + 1), file) > 0;
  1709. return mixerpresets::loadOnTracks (engine, { track }, file);
  1710. }
  1711. namespace mixerpresets
  1712. {
  1713. juce::Array<juce::File> folders()
  1714. {
  1715. // FL's browser folder 0x3f8 (REA round 167q, FUN_009db5b0): "Presets\Mixer presets" of the user data folder and
  1716. // "Data\Patches\Mixer presets" of the installation
  1717. static const auto fl = findFlStudio();
  1718. juce::Array<juce::File> out;
  1719. if (fl.userData.isDirectory())
  1720. out.add (fl.userData.getChildFile ("Presets").getChildFile ("Mixer presets"));
  1721. if (fl.installDir.isDirectory())
  1722. out.add (fl.installDir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Mixer presets"));
  1723. out.add (mixerStatesFolder());
  1724. out.removeIf ([] (const juce::File& f) { return ! f.isDirectory(); });
  1725. return out;
  1726. }
  1727. juce::Array<juce::File> all()
  1728. {
  1729. juce::Array<juce::File> files;
  1730. for (const auto& folder : folders())
  1731. for (const auto& f : folder.findChildFiles (juce::File::findFiles, true, juce::String ("*.fst;*") + ProjectFile::mixerTrackStateExtension))
  1732. files.add (f);
  1733. std::stable_sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) {
  1734. return a.getFileNameWithoutExtension().compareNatural (b.getFileNameWithoutExtension()) < 0;
  1735. });
  1736. return files;
  1737. }
  1738. static std::vector<std::uint8_t> bytesOf (const juce::File& file)
  1739. {
  1740. juce::MemoryBlock data;
  1741. if (file.getSize() > 64 * 1024 * 1024 || ! file.loadFileAsData (data))
  1742. return {};
  1743. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  1744. return { bytes, bytes + data.getSize() };
  1745. }
  1746. bool isMixerPreset (const juce::File& file)
  1747. {
  1748. if (file.hasFileExtension (ProjectFile::mixerTrackStateExtension))
  1749. return true;
  1750. if (! file.hasFileExtension ("fst"))
  1751. return false;
  1752. for (auto p = file.getParentDirectory(); p != juce::File() && p.getParentDirectory() != p; p = p.getParentDirectory())
  1753. if (p.getFileName().equalsIgnoreCase ("Mixer presets"))
  1754. return true;
  1755. const auto bytes = bytesOf (file);
  1756. return flp::looksLikeMixerPreset (bytes);
  1757. }
  1758. std::optional<MixerTrack> read (const juce::File& file)
  1759. {
  1760. if (file.hasFileExtension ("fst"))
  1761. {
  1762. FlpImportOptions options;
  1763. options.roots = findFlStudioRoots();
  1764. options.fileExists = [] (const std::string& path) { return platform::localFile (path).existsAsFile(); };
  1765. options.readFile = [] (const std::string& path) { return bytesOf (platform::localFile (path)); };
  1766. return mixerTrackFromFlPreset (bytesOf (file), options);
  1767. }
  1768. juce::String error;
  1769. auto state = ProjectFile::mixerTrackStateFromJson (file.loadFileAsString(), error);
  1770. if (state && state->name.empty())
  1771. state->name = file.getFileNameWithoutExtension().toStdString();
  1772. return state;
  1773. }
  1774. bool loadOnTracks (AudioEngine& engine, const std::vector<int>& tracks, const juce::File& file)
  1775. {
  1776. const auto state = read (file);
  1777. if (! state)
  1778. return false;
  1779. // FL's mixer presets restore the track's name and colour (WhatsNew); LYNX's states keep the track's own
  1780. const auto takeName = file.hasFileExtension ("fst") && ! state->name.empty();
  1781. bool any = false;
  1782. engine.editSong ([&] (Song& s) {
  1783. for (const auto t : tracks)
  1784. if (t >= 0 && t < (int) s.mixer.size())
  1785. {
  1786. ProjectFile::applyMixerTrackState (s.mixer[(std::size_t) t], *state, takeName);
  1787. any = true;
  1788. }
  1789. });
  1790. return any;
  1791. }
  1792. int insertTrack (AudioEngine& engine, int at, const juce::File& file)
  1793. {
  1794. auto state = read (file);
  1795. if (! state)
  1796. return -1;
  1797. if (state->name.empty())
  1798. state->name = file.getFileNameWithoutExtension().toStdString();
  1799. at = juce::jlimit (1, (int) engine.getSong().mixer.size(), at);
  1800. bool ok = false;
  1801. engine.editSong ([&] (Song& s) {
  1802. ok = mixerops::insertTrack (s, at);
  1803. if (ok)
  1804. ProjectFile::applyMixerTrackState (s.mixer[(std::size_t) at], *state, true);
  1805. });
  1806. return ok ? at : -1;
  1807. }
  1808. } // namespace mixerpresets
  1809. bool saveMixerTrackState (AudioEngine& engine, int track, const juce::File& file)
  1810. {
  1811. if (track < 0 || track >= (int) engine.getSong().mixer.size())
  1812. return false;
  1813. engine.capturePluginStates(); // the plugins' current settings go into the state
  1814. file.getParentDirectory().createDirectory();
  1815. return file.replaceWithText (ProjectFile::mixerTrackStateToJson (engine.getSong().mixer[(std::size_t) track]));
  1816. }
  1817. // FL's "Auto-create audio clip" (round 167a [SHOT s28–s37]): the rendered files go on the Playlist, one undo step
  1818. static void placeRenderedFiles (AudioEngine& engine, const std::vector<juce::File>& files)
  1819. {
  1820. std::vector<mixerops::RenderedFile> list;
  1821. juce::AudioFormatManager formats;
  1822. formats.registerBasicFormats();
  1823. for (const auto& f : files)
  1824. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (f)); reader != nullptr)
  1825. list.push_back ({ f.getFullPathName().toStdString(), (double) reader->lengthInSamples, reader->sampleRate });
  1826. if (! list.empty())
  1827. engine.editSong ([list] (Song& s) { mixerops::placeRenderedFiles (s, list); });
  1828. }
  1829. void MixerStrips::askInsertMultiple (int at)
  1830. {
  1831. auto* window = new juce::AlertWindow (tr ("Insert multiple"), tr ("How many blank inserts?"), juce::MessageBoxIconType::NoIcon);
  1832. // FL 2026's box starts at 10, already selected; Ctrl+A selects it again (round 167a [SHOT s13–s15])
  1833. window->addTextEditor ("count", "10");
  1834. if (auto* field = window->getTextEditor ("count"))
  1835. field->setInputRestrictions (4, "0123456789");
  1836. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1837. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  1838. juce::Component::SafePointer<MixerStrips> safe (this);
  1839. window->enterModalState (true, juce::ModalCallbackFunction::create ([safe, at, window] (int result) {
  1840. if (safe == nullptr || result != 1)
  1841. return;
  1842. const auto n = window->getTextEditorContents ("count").getIntValue();
  1843. const auto room = mixerops::roomForInserts (safe->engine.getSong());
  1844. if (n > room) // FL 2026 shows "You can add a maximum of 375 tracks." (round 166d [SHOT]); nothing is added then
  1845. {
  1846. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Insert multiple"),
  1847. tr ("You can add a maximum of {0} inserts.", { juce::String (room) }));
  1848. return;
  1849. }
  1850. if (n > 0)
  1851. {
  1852. const auto first = juce::jlimit (1, (int) safe->engine.getSong().mixer.size(), at);
  1853. safe->engine.editSong ([first, n] (Song& s) { mixerops::insertTracks (s, first, n); });
  1854. for (int i = 0; i < n; ++i)
  1855. safe->revealed.insert (first + i); // shown even while unused
  1856. safe->updateSize();
  1857. safe->selectTrack (first);
  1858. }
  1859. }),
  1860. true);
  1861. if (auto* field = window->getTextEditor ("count"))
  1862. {
  1863. field->grabKeyboardFocus();
  1864. field->selectAll();
  1865. }
  1866. }
  1867. void MixerStrips::showMenu (int t)
  1868. {
  1869. buildMenu (t).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1870. }
  1871. bool MixerStrips::runMenuItem (const juce::String& caption)
  1872. {
  1873. auto menu = buildMenu (getSelectedTrack());
  1874. for (juce::PopupMenu::MenuItemIterator it (menu, true); it.next();)
  1875. {
  1876. const auto& item = it.getItem();
  1877. if (item.isEnabled && item.action != nullptr && item.subMenu == nullptr
  1878. && item.text.upToFirstOccurrenceOf ("\t", false, false).trim() == caption)
  1879. {
  1880. const auto action = item.action; // (the menu goes away first)
  1881. menu = {};
  1882. action();
  1883. return true;
  1884. }
  1885. }
  1886. return false;
  1887. }
  1888. juce::PopupMenu MixerStrips::buildMenu (int t)
  1889. {
  1890. const auto& song = engine.getSong();
  1891. const auto channel = engine.getSelectedChannel();
  1892. juce::PopupMenu menu;
  1893. if (t < 0 || t >= (int) song.mixer.size())
  1894. return menu;
  1895. // the tracks the "selected track(s)" items act on: the selection when the clicked track is in it
  1896. const auto targets = std::find (selection.begin(), selection.end(), t) != selection.end() ? selection : std::vector<int> { t };
  1897. const auto trackName = juce::String::fromUTF8 (song.mixer[(std::size_t) t].name.c_str());
  1898. auto rename = [this, t] {
  1899. if (t >= (int) engine.getSong().mixer.size())
  1900. return;
  1901. const auto& track = engine.getSong().mixer[(std::size_t) t];
  1902. showNameAndColourDialog (tr ("Rename track"), juce::String::fromUTF8 (track.name.c_str()), track.colour,
  1903. [this, t] (const juce::String& name, std::uint32_t colour) {
  1904. if (t < (int) engine.getSong().mixer.size())
  1905. engine.editSong ([t, n = name.trim().toStdString(), colour] (Song& s) {
  1906. if (! n.empty())
  1907. s.mixer[(std::size_t) t].name = n;
  1908. s.mixer[(std::size_t) t].colour = colour;
  1909. });
  1910. });
  1911. };
  1912. // the title band in the insert's colour (FL tints the whole menu); a double-click on it renames (issue #12)
  1913. ui::addItemHeader (menu, t == 0 ? tr ("Master") : tr ("Mixer track {0}", { juce::String (t) }), trackName,
  1914. song.mixer[(std::size_t) t].colour != 0 ? juce::Colour (song.mixer[(std::size_t) t].colour) : juce::Colour(), rename);
  1915. // FL's first section: name and colour (REA_rodada115)
  1916. menu.addItem (tr ("Rename and color...") + "\tF2", rename);
  1917. menu.addSubMenu (tr ("Change color"), ui::colourMenu (song.mixer[(std::size_t) t].colour, [this, t] (std::uint32_t colour) {
  1918. if (t < (int) engine.getSong().mixer.size())
  1919. engine.editSong ([t, colour] (Song& s) { s.mixer[(std::size_t) t].colour = colour; });
  1920. }, juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1)));
  1921. menu.addItem (tr ("Random color"), [this, t] {
  1922. const auto& palette = lynxPalette();
  1923. const auto colour = palette[(std::size_t) juce::Random::getSystemRandom().nextInt ((int) palette.size())];
  1924. engine.editSong ([t, colour] (Song& s) { s.mixer[(std::size_t) t].colour = colour; });
  1925. });
  1926. // FL's "Change icon..." (SetIconMenuClick, REA round 168h: every selected track gets it); LYNX's own icon set
  1927. menu.addItem (tr ("Change icon..."), [this, t, targets = std::find (selection.begin(), selection.end(), t) != selection.end() ? selection : std::vector<int> { t }] {
  1928. ui::showTrackIconPicker (juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1), engine.getSong().mixer[(std::size_t) t].icon, [this, targets] (int icon) {
  1929. engine.editSong ([targets, icon] (Song& s) {
  1930. for (auto track : targets)
  1931. if (track >= 0 && track < (int) s.mixer.size())
  1932. s.mixer[(std::size_t) track].icon = icon;
  1933. });
  1934. });
  1935. });
  1936. menu.addSeparator();
  1937. // FL's "File" submenu (REA round 167q, TFXForm's FileMenu): open/save a state, Browse states and the "States" list
  1938. // of FL's mixer presets (FL's own .fst and the user's) and LYNX's .lynxtrack states, loaded onto every selected
  1939. // track (FUN_012a7440)
  1940. {
  1941. const auto targets = std::find (selection.begin(), selection.end(), t) != selection.end() ? selection : std::vector<int> { t };
  1942. juce::PopupMenu file;
  1943. file.addItem (tr ("Open mixer track state..."), [this, targets] {
  1944. auto& chooser = mixerStateChooser();
  1945. const auto start = mixerpresets::folders().isEmpty() ? mixerStatesFolder() : mixerpresets::folders()[0];
  1946. chooser = lynx::ui::makeFileChooser (tr ("Open mixer track state"), start,
  1947. juce::String ("*.fst;*") + ProjectFile::mixerTrackStateExtension);
  1948. juce::Component::SafePointer<MixerStrips> safe (this);
  1949. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [safe, targets] (const juce::FileChooser& fc) {
  1950. if (safe != nullptr && fc.getResult().existsAsFile() && ! mixerpresets::loadOnTracks (safe->engine, targets, fc.getResult()))
  1951. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Open mixer track state"),
  1952. tr ("This file is not a mixer track state LYNX SHARE can read."));
  1953. });
  1954. });
  1955. file.addItem (tr ("Save mixer track state as...") + "\tCtrl+Shift+S", [this, t, trackName] {
  1956. auto& chooser = mixerStateChooser();
  1957. const auto name = juce::File::createLegalFileName (trackName.isNotEmpty() ? trackName : tr ("Mixer track {0}", { juce::String (t) }));
  1958. chooser = lynx::ui::makeFileChooser (tr ("Save mixer track state"), mixerStatesFolder().getChildFile (name + ProjectFile::mixerTrackStateExtension),
  1959. juce::String ("*") + ProjectFile::mixerTrackStateExtension);
  1960. juce::Component::SafePointer<MixerStrips> safe (this);
  1961. mixerStatesFolder().createDirectory();
  1962. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting, [safe, t] (const juce::FileChooser& fc) {
  1963. if (safe != nullptr && fc.getResult() != juce::File())
  1964. saveMixerTrackState (safe->engine, t, fc.getResult().withFileExtension (ProjectFile::mixerTrackStateExtension));
  1965. });
  1966. });
  1967. file.addItem (tr ("Browse states"), [] {
  1968. mixerStatesFolder().createDirectory();
  1969. mixerStatesFolder().startAsProcess();
  1970. });
  1971. const auto states = mixerpresets::all();
  1972. if (! states.isEmpty())
  1973. {
  1974. file.addSectionHeader (tr ("States"));
  1975. for (const auto& f : states)
  1976. file.addItem (f.getFileNameWithoutExtension(), [this, targets, f] { mixerpresets::loadOnTracks (engine, targets, f); });
  1977. }
  1978. menu.addSubMenu (tr ("File"), file);
  1979. }
  1980. if (t > 0)
  1981. {
  1982. const auto& mt = song.mixer[(std::size_t) t];
  1983. const auto current = mt.inputChannel >= 0
  1984. ? juce::String::fromUTF8 (inputSourceName (mt.inputChannel, mt.inputStereo, engine.getInputChannelNames()).c_str())
  1985. : tr ("none");
  1986. menu.addItem (tr ("Audio input: {0}...", { current }), [this, t] { mixerinput::showMenu (engine, t, this); });
  1987. }
  1988. menu.addItem (tr ("Open audio editor"), [this] { openAudioEditor (engine); });
  1989. menu.addItem (tr ("Reset selected track(s) to default"), [this, targets] { engine.editSong ([targets] (Song& s) { mixerops::resetToDefault (s, targets); }); });
  1990. // --- FL's "Routing" section -----------------------------------------------------------------------
  1991. menu.addSectionHeader (tr ("Routing"));
  1992. {
  1993. juce::PopupMenu channels;
  1994. channels.addItem (tr ("Route selected channels to this track") + "\tCtrl+L", [this, t] {
  1995. setSelection (selection, t);
  1996. linkSelectedChannels (false);
  1997. });
  1998. channels.addItem (tr ("Route selected channels starting from this track") + "\tCtrl+Shift+L", [this, t] {
  1999. setSelection (selection, t);
  2000. linkSelectedChannels (true);
  2001. });
  2002. if (channel < (int) song.channels.size())
  2003. channels.addItem (tr ("Route channel \"{0}\" here", { juce::String::fromUTF8 (song.channels[(std::size_t) channel].name.c_str()) }),
  2004. [this, channel, t] { engine.editSong ([channel, t] (Song& s) { s.channels[(std::size_t) channel].mixerTrack = t; }); });
  2005. menu.addSubMenu (tr ("Channel routing"), channels);
  2006. }
  2007. {
  2008. juce::PopupMenu select;
  2009. select.addItem (tr ("Channels routed to this track") + "\tAlt+L", ! mixerops::channelsOn (song, t).empty(), false, [this, t] {
  2010. setSelection (selection, t);
  2011. selectLinkedChannels();
  2012. });
  2013. select.addSeparator();
  2014. const auto destinations = mixerops::destinationsOf (song, t);
  2015. const auto sources = mixerops::sourcesOf (song, t);
  2016. select.addItem (tr ("Tracks this one is routed to"), ! destinations.empty(), false, [this, t, destinations] { setSelection (destinations, t); });
  2017. select.addItem (tr ("Tracks routed to this one"), ! sources.empty(), false, [this, t, sources] { setSelection (sources, t); });
  2018. select.addSeparator();
  2019. select.addItem (tr ("Group"), t > 0, false, [this, t] {
  2020. auto group = mixerops::groupOf (engine.getSong(), t);
  2021. std::sort (group.begin(), group.end());
  2022. setSelection (group, t);
  2023. });
  2024. select.addItem (tr ("All"), [this, t] {
  2025. std::vector<int> all ((std::size_t) engine.getSong().mixer.size());
  2026. std::iota (all.begin(), all.end(), 0);
  2027. setSelection (all, t);
  2028. });
  2029. menu.addSubMenu (tr ("Select"), select);
  2030. }
  2031. menu.addItem (tr ("Reset selected track(s) routing"), [this, targets] { engine.editSong ([targets] (Song& s) { mixerops::resetRouting (s, targets); }); });
  2032. menu.addItem (tr ("Unroute tracks routed to the selected track(s)"), [this, targets] { engine.editSong ([targets] (Song& s) { mixerops::unrouteInto (s, targets); }); });
  2033. {
  2034. // FL's Routing submenu (REA round 165f-mixer: FUN_012ac520 / FUN_012ac950): selected tracks ⇄ this track
  2035. std::vector<int> others;
  2036. for (auto x : selection)
  2037. if (x != t)
  2038. others.push_back (x);
  2039. const auto any = ! others.empty();
  2040. juce::PopupMenu routing;
  2041. routing.addSectionHeader (tr ("Selected tracks to this track"));
  2042. using K = mixerops::RouteKind;
  2043. auto selToThis = [this, others, t] (K kind) { engine.editSong ([others, t, kind] (Song& s) { mixerops::routeSelectedTo (s, others, t, kind); }); };
  2044. auto thisToSel = [this, others, t] (K kind) { engine.editSong ([others, t, kind] (Song& s) { mixerops::routeToSelected (s, t, others, kind); }); };
  2045. routing.addItem (tr ("Route selected to this track"), any, false, [selToThis] { selToThis (K::route); });
  2046. routing.addItem (tr ("Route selected to this track only"), any, false, [selToThis] { selToThis (K::routeOnly); });
  2047. routing.addItem (tr ("Sidechain selected to this track"), any && t > 0, false, [selToThis] { selToThis (K::sidechain); });
  2048. routing.addItem (tr ("Sidechain selected to this track only"), any && t > 0, false, [selToThis] { selToThis (K::sidechainOnly); });
  2049. routing.addSeparator();
  2050. routing.addItem (tr ("Create submix..."), any && t > 0, false, [this, others, t] {
  2051. const auto& track = engine.getSong().mixer[(std::size_t) t];
  2052. const auto name = mixerops::hasDefaultName (engine.getSong(), t) ? juce::String() : juce::String::fromUTF8 (track.name.c_str());
  2053. showNameAndColourDialog (tr ("Create submix"), name, track.colour, [this, others, t] (const juce::String& n, std::uint32_t colour) {
  2054. if (t < (int) engine.getSong().mixer.size())
  2055. engine.editSong ([others, t, n = n.trim().toStdString(), colour] (Song& s) {
  2056. s.mixer[(std::size_t) t].colour = colour;
  2057. mixerops::createSubmix (s, others, t, n);
  2058. });
  2059. });
  2060. });
  2061. const auto thisIsInsert = t > 0;
  2062. routing.addSectionHeader (tr ("This track to selected tracks"));
  2063. routing.addItem (tr ("Route this track to selected"), any && thisIsInsert, false, [thisToSel] { thisToSel (K::route); });
  2064. routing.addItem (tr ("Route this track to selected only"), any && thisIsInsert, false, [thisToSel] { thisToSel (K::routeOnly); });
  2065. routing.addItem (tr ("Sidechain this track to selected"), any && thisIsInsert, false, [thisToSel] { thisToSel (K::sidechain); });
  2066. routing.addItem (tr ("Sidechain this track to selected only"), any && thisIsInsert, false, [thisToSel] { thisToSel (K::sidechainOnly); });
  2067. menu.addSubMenu (tr ("Selected tracks ⇄ this track"), routing);
  2068. }
  2069. if (selected > 0 && selected != t && (t == 0 || song.canRoute (selected, t) || song.routes (selected, t)))
  2070. menu.addItem (tr ("Send \"{0}\" only to this track", { juce::String::fromUTF8 (song.mixer[(std::size_t) selected].name.c_str()) }),
  2071. [this, from = selected, t] {
  2072. engine.editSong ([from, t] (Song& s) {
  2073. s.mixer[(std::size_t) from].sends.clear();
  2074. s.mixer[(std::size_t) from].toMaster = false;
  2075. s.setRoute (from, t, true);
  2076. });
  2077. });
  2078. menu.addSeparator();
  2079. {
  2080. const auto inserts = [targets] {
  2081. std::vector<int> v;
  2082. for (auto x : targets)
  2083. if (x > 0)
  2084. v.push_back (x);
  2085. return v;
  2086. }();
  2087. // FL's two solo items (REA_rodada167l §4): the plain one mutes the tracks feeding the soloed ones, the alt one
  2088. // keeps them; the same item again clears the solo
  2089. menu.addItem (tr ("Solo selected track(s)") + "\tS", ! inserts.empty(), false, [this, inserts] {
  2090. engine.editSong ([inserts] (Song& s) { mixerops::soloSelected (s, inserts, false); });
  2091. });
  2092. menu.addItem (tr ("Alt solo selected track(s)") + "\tAlt+S", ! inserts.empty(), false, [this, inserts] {
  2093. engine.editSong ([inserts] (Song& s) { mixerops::soloSelected (s, inserts, true); });
  2094. });
  2095. menu.addItem (tr ("Arm selected track(s)"), ! inserts.empty(), false, [this, inserts] {
  2096. for (auto x : inserts)
  2097. if (! engine.isInsertArmed (x))
  2098. mixerinput::toggleArm (engine, x, this);
  2099. });
  2100. menu.addItem (tr ("Disarm selected track(s)"), ! inserts.empty(), false, [this, inserts] {
  2101. for (auto x : inserts)
  2102. if (engine.isInsertArmed (x))
  2103. engine.setInsertArmed (x, false);
  2104. });
  2105. }
  2106. // FL's track latency (the "Track latency compensation" label's menu, REA round 165f-mixer)
  2107. menu.addSubMenu (tr ("Track latency: {0}", { manualLatencyText (engine, song.mixer[(std::size_t) t]) }), trackLatencyMenu (engine, t));
  2108. // --- LYNX's sound items (FL has them on the strip itself) -------------------------------------------
  2109. menu.addSectionHeader (tr ("Sound"));
  2110. {
  2111. const auto& track = song.mixer[(std::size_t) t];
  2112. juce::PopupMenu stereo;
  2113. const std::pair<const char*, float> widths[] = { { TR_NOOP ("Mono"), 1.0f }, { TR_NOOP ("Narrower"), 0.5f }, { TR_NOOP ("Normal"), 0.0f },
  2114. { TR_NOOP ("Wider"), -0.5f }, { TR_NOOP ("Very wide"), -1.0f } };
  2115. for (const auto& [label, value] : widths)
  2116. stereo.addItem (tr (label), true, std::abs (track.stereo - value) < 0.01f,
  2117. [this, t, v = value] { engine.editSong ([t, v] (Song& s) { s.mixer[(std::size_t) t].stereo = v; }); });
  2118. menu.addSubMenu (tr ("Stereo separation"), stereo);
  2119. if (! song.cleanMixer)
  2120. menu.addItem (tr ("Track EQ..."), [this, t] { showTrackEq (t); });
  2121. menu.addItem (tr ("Invert phase"), true, track.invertPhase, [this, t] {
  2122. engine.editSong ([t] (Song& s) { s.mixer[(std::size_t) t].invertPhase = ! s.mixer[(std::size_t) t].invertPhase; });
  2123. });
  2124. menu.addItem (tr ("Swap left/right"), true, track.swapChannels, [this, t] {
  2125. engine.editSong ([t] (Song& s) { s.mixer[(std::size_t) t].swapChannels = ! s.mixer[(std::size_t) t].swapChannels; });
  2126. });
  2127. if (t > 0)
  2128. menu.addItem (tr ("Render to audio (freeze)..."), [this, t] { bounceInsertToAudio (engine, t); });
  2129. }
  2130. // --- FL's "Group" section (REA round 146a) -----------------------------------------------------------
  2131. if (t > 0)
  2132. {
  2133. menu.addSectionHeader (tr ("Group"));
  2134. const auto on = song.mixer[(std::size_t) t].separator;
  2135. menu.addItem (tr ("Separator"), true, on, [this, targets, on] {
  2136. engine.editSong ([targets, on] (Song& s) { mixerops::setSeparator (s, targets, ! on); });
  2137. });
  2138. menu.addItem (tr ("Create group"), [this, targets, t] { engine.editSong ([targets, t] (Song& s) { mixerops::createGroup (s, targets, t); }); });
  2139. menu.addItem (tr ("Auto color group"), song.mixer[(std::size_t) t].colour != 0, false,
  2140. [this, t] { engine.editSong ([t] (Song& s) { mixerops::autoColorGroup (s, t); }); });
  2141. }
  2142. // --- FL's "Layout" section --------------------------------------------------------------------------
  2143. {
  2144. menu.addSectionHeader (tr ("Layout"));
  2145. juce::PopupMenu dockMenu;
  2146. const auto dock = song.mixer[(std::size_t) t].dock;
  2147. const std::pair<const char*, MixerDock> docks[] = { { TR_NOOP ("Left"), MixerDock::left }, { TR_NOOP ("Middle"), MixerDock::middle },
  2148. { TR_NOOP ("Right"), MixerDock::right } };
  2149. for (const auto& [label, d] : docks)
  2150. dockMenu.addItem (tr (label), true, dock == d, [this, targets, d = d] {
  2151. engine.editSong ([targets, d] (Song& s) { mixerops::dockTracks (s, targets, d); });
  2152. });
  2153. menu.addSubMenu (tr ("Dock to"), dockMenu);
  2154. }
  2155. if (t > 0)
  2156. {
  2157. menu.addItem (tr ("Move left") + "\tAlt+Left", t > 1, false, [this, t] {
  2158. setSelection ({ t }, t);
  2159. moveSelected (-1);
  2160. });
  2161. menu.addItem (tr ("Move right") + "\tAlt+Right", t + 1 < (int) song.mixer.size(), false, [this, t] {
  2162. setSelection ({ t }, t);
  2163. moveSelected (1);
  2164. });
  2165. menu.addSeparator();
  2166. menu.addItem (tr ("Delete") + "\tDel", [this, t] {
  2167. engine.editSong ([t] (Song& s) { mixerops::deleteTrack (s, t); });
  2168. setSelection ({ t }, t);
  2169. });
  2170. const auto room = (int) song.mixer.size() < maxMixerTracks;
  2171. menu.addItem (tr ("Insert one"), room, false, [this, t] {
  2172. engine.editSong ([t] (Song& s) { mixerops::insertTrack (s, t); });
  2173. setSelection ({ t }, t);
  2174. });
  2175. menu.addItem (tr ("Insert multiple..."), room, false, [this, t] { askInsertMultiple (t); });
  2176. juce::PopupMenu fromState;
  2177. for (const auto& f : mixerpresets::all())
  2178. fromState.addItem (f.getFileNameWithoutExtension(), room, false, [this, t, f] {
  2179. if (const auto added = mixerpresets::insertTrack (engine, t, f); added > 0)
  2180. setSelection ({ added }, added);
  2181. });
  2182. menu.addSubMenu (tr ("Insert from state"), fromState, room && fromState.getNumItems() > 0);
  2183. // FL's last section, "CPU" (REA round 134)
  2184. menu.addSectionHeader (tr ("CPU"));
  2185. menu.addItem (tr ("Allow threaded processing"), true, song.mixer[(std::size_t) t].threaded, [this, t] {
  2186. engine.editSong ([t] (Song& s) { s.mixer[(std::size_t) t].threaded = ! s.mixer[(std::size_t) t].threaded; });
  2187. });
  2188. }
  2189. menu.addSectionHeader (tr ("Mixer"));
  2190. {
  2191. // FL's Mixer › Disk recording (REA round 165f-mixer: FUN_012a7a80 / FUN_012a7d80)
  2192. std::vector<int> armed;
  2193. for (int x = 1; x < (int) song.mixer.size(); ++x)
  2194. if (engine.isInsertArmed (x))
  2195. armed.push_back (x);
  2196. juce::PopupMenu disk;
  2197. auto& eng = engine;
  2198. disk.addItem (tr ("Render armed tracks to wave file(s)...") + "\tAlt+R", ! armed.empty(), false, [armed, &eng] {
  2199. if (mixeroptions::renderTracks)
  2200. mixeroptions::renderTracks (armed, [armed, &eng] (const std::vector<juce::File>& files) {
  2201. if (eng.getRecordOptions().unarmAfterRender) // FL's "Auto-unarm" (round 166e)
  2202. for (auto t : armed)
  2203. eng.setInsertArmed (t, false);
  2204. if (eng.getRecordOptions().autoCreateClip) // FL's "Auto-create audio clip" (round 167a)
  2205. placeRenderedFiles (eng, files);
  2206. });
  2207. });
  2208. disk.addItem (tr ("Render selected tracks to wave file(s)...") + "\tShift+Alt+R", ! targets.empty(), false, [targets] {
  2209. if (mixeroptions::renderTracks)
  2210. mixeroptions::renderTracks (targets, {});
  2211. });
  2212. // FL's Disk recording "Options" (round 166e) and LYNX's own disarm after a take (issue #16)
  2213. disk.addSectionHeader (tr ("Options"));
  2214. const auto& ro = engine.getRecordOptions();
  2215. auto setRecord = [&eng] (std::function<void (AudioEngine::RecordOptions&)> change) {
  2216. auto o = eng.getRecordOptions();
  2217. change (o);
  2218. eng.setRecordOptions (o);
  2219. if (mixeroptions::changed)
  2220. mixeroptions::changed();
  2221. };
  2222. disk.addItem (tr ("Auto-unarm (rendering the armed tracks disarms them)"), true, ro.unarmAfterRender,
  2223. [setRecord] { setRecord ([] (AudioEngine::RecordOptions& r) { r.unarmAfterRender = ! r.unarmAfterRender; }); });
  2224. disk.addItem (tr ("Auto-create audio clip (the rendered files go on the Playlist)"), true, ro.autoCreateClip,
  2225. [setRecord] { setRecord ([] (AudioEngine::RecordOptions& r) { r.autoCreateClip = ! r.autoCreateClip; }); });
  2226. disk.addItem (tr ("Disarm the inserts when recording stops"), true, ro.disarmOnStop,
  2227. [setRecord] { setRecord ([] (AudioEngine::RecordOptions& r) { r.disarmOnStop = ! r.disarmOnStop; }); });
  2228. menu.addSubMenu (tr ("Disk recording"), disk);
  2229. juce::PopupMenu pdc;
  2230. const auto manual = std::count_if (song.mixer.begin(), song.mixer.end(), [] (const MixerTrack& m) { return m.latencyMs != 0.0f; });
  2231. pdc.addItem (tr ("Reset manual latency on all tracks"), manual > 0, false, [this] {
  2232. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::WarningIcon, tr ("Warning"),
  2233. tr ("This will reset manual latency values on all mixer tracks."), tr ("OK"), tr ("Cancel"), nullptr,
  2234. juce::ModalCallbackFunction::create ([this] (int r) {
  2235. if (r == 1)
  2236. engine.editSong ([] (Song& s) { mixerops::resetManualLatency (s); });
  2237. }));
  2238. });
  2239. // FL's Automatic / Compensate automations (REA round 168j, .flp 0x1D / 0x27; FL's AutoPDCMenuClick toggles it)
  2240. pdc.addItem (tr ("Automatic (compensate the plugins' latencies)"), true, song.autoPdc,
  2241. [this] { engine.editSong ([] (Song& s) { s.autoPdc = ! s.autoPdc; }); });
  2242. pdc.addItem (tr ("Compensate automations (delay a plugin's automation with its audio)"), true, song.compensateAutomations,
  2243. [this] { engine.editSong ([] (Song& s) { s.compensateAutomations = ! s.compensateAutomations; }); });
  2244. menu.addSubMenu (tr ("Plugin delay compensation"), pdc);
  2245. }
  2246. menu.addSubMenu (tr ("Mixer layout"), MixerLayoutBox::menu (*this)); // as the title bar's drop-down (issue #52)
  2247. mixeroptions::addItems (menu, engine, false);
  2248. return menu;
  2249. }
  2250. void MixerStrips::changeListenerCallback (juce::ChangeBroadcaster*)
  2251. {
  2252. // only levels moved since the last call (a fader / knob drag, AudioEngine::editLevels; round 171c): repaint just
  2253. // the strips whose fader, pan or separation changed instead of the whole mixer at every mouse move
  2254. const auto& mixer = engine.getSong().mixer;
  2255. if (engine.getPublishCount() == seenPublish && shownLevels.size() == mixer.size())
  2256. {
  2257. for (std::size_t t = 0; t < mixer.size(); ++t)
  2258. {
  2259. const std::array<float, 3> now { mixer[t].volume, mixer[t].pan, mixer[t].stereo };
  2260. if (now != shownLevels[t])
  2261. {
  2262. shownLevels[t] = now;
  2263. repaint (stripX ((int) t), 0, stripWidthOf ((int) t), getHeight());
  2264. }
  2265. }
  2266. return;
  2267. }
  2268. seenPublish = engine.getPublishCount();
  2269. shownLevels.resize (mixer.size());
  2270. for (std::size_t t = 0; t < mixer.size(); ++t)
  2271. shownLevels[t] = { mixer[t].volume, mixer[t].pan, mixer[t].stereo };
  2272. selected = juce::jlimit (0, juce::jmax (0, (int) engine.getSong().mixer.size() - 1), selected);
  2273. const auto count = (int) engine.getSong().mixer.size();
  2274. selection.erase (std::remove_if (selection.begin(), selection.end(), [count] (int t) { return t >= count; }), selection.end());
  2275. if (! std::binary_search (selection.begin(), selection.end(), selected))
  2276. selection = { selected };
  2277. updateSize();
  2278. repaint();
  2279. }
  2280. float MixerStrips::shownVolume (int t) const
  2281. {
  2282. const auto& mixer = engine.getSong().mixer;
  2283. const auto base = t >= 0 && t < (int) mixer.size() ? mixer[(std::size_t) t].volume : 0.0f;
  2284. return engine.getAutomationDisplay().shown (AutomationTarget { AutomationTargetKind::mixerVolume, t }, base);
  2285. }
  2286. void MixerStrips::repaintAutomatedStrips()
  2287. {
  2288. // faders, pan and send knobs follow their automation while the song plays (issue #12): only the strips with an
  2289. // automated control repaint, and only when a shown value changed
  2290. const auto& shown = engine.getAutomationDisplay();
  2291. if (shown.getGeneration() == shownAutomation)
  2292. return;
  2293. shownAutomation = shown.getGeneration();
  2294. std::vector<int> strips;
  2295. for (const auto& t : shown.automatedTargets())
  2296. {
  2297. if (t.kind == AutomationTargetKind::mixerVolume || t.kind == AutomationTargetKind::mixerPan)
  2298. strips.push_back (t.index);
  2299. else if (t.kind == AutomationTargetKind::mixerSend && t.index == selected)
  2300. strips.push_back (t.slot); // (the route knob sits under the destination)
  2301. }
  2302. std::vector<int> all = strips;
  2303. all.insert (all.end(), automatedStrips.begin(), automatedStrips.end());
  2304. automatedStrips = std::move (strips);
  2305. if (! isShowing())
  2306. return;
  2307. std::sort (all.begin(), all.end());
  2308. all.erase (std::unique (all.begin(), all.end()), all.end());
  2309. const auto count = (int) engine.getSong().mixer.size();
  2310. for (const auto t : all)
  2311. if (t >= 0 && t < count)
  2312. repaint (stripX (t), 0, stripWidthOf (t), getHeight());
  2313. }
  2314. void MixerStrips::timerCallback()
  2315. {
  2316. auto& meters = engine.getMeters();
  2317. const auto showing = isShowing();
  2318. repaintAutomatedStrips();
  2319. if ((++timerTicks & 1) != 0) // (the meters and input bars: every other tick, 30 Hz)
  2320. return;
  2321. const auto& mixer = engine.getSong().mixer;
  2322. inputLevels.resize (mixer.size(), 0.0f);
  2323. for (std::size_t t = 1; t < mixer.size(); ++t)
  2324. {
  2325. const auto peak = mixer[t].inputChannel >= 0 ? juce::jmax (engine.takeInputPeak ((int) t, 0), engine.takeInputPeak ((int) t, 1)) : 0.0f;
  2326. auto level = juce::jmax (peak, inputLevels[t] * 0.8f);
  2327. level = level < 1e-4f ? 0.0f : level;
  2328. if (std::abs (level - inputLevels[t]) > 1e-4f)
  2329. {
  2330. inputLevels[t] = level;
  2331. if (showing)
  2332. repaint (inputArea ((int) t).expanded (1));
  2333. }
  2334. }
  2335. for (std::size_t i = 0; i < levels.size(); ++i)
  2336. {
  2337. auto& m = levels[i];
  2338. const auto before = m;
  2339. m.tick (meters.takePeak ((int) (i / 2), (int) (i % 2))); // ~20 dB/s falloff at 30 Hz, 1.5 s peak hold
  2340. // only the meter that changed is repainted
  2341. if (showing && (std::abs (m.level - before.level) > 1e-4f || std::abs (m.peak - before.peak) > 1e-4f || m.clipped != before.clipped))
  2342. repaint (meterArea ((int) (i / 2)).expanded (1));
  2343. }
  2344. }
  2345. // ---------------------------------------------------------------------------
  2346. namespace
  2347. {
  2348. constexpr int panelHeader = 30;
  2349. constexpr int inputRowHeight = 30; // the input row (arm, audio input source) above the slots
  2350. constexpr int slotsTop = panelHeader + inputRowHeight;
  2351. constexpr int slotHeight = 24;
  2352. const EffectKind allEffects[] = { EffectKind::eq, EffectKind::parametricEq, EffectKind::facetEq, EffectKind::compressor, EffectKind::limiter, EffectKind::apexLimiter,
  2353. EffectKind::delay, EffectKind::reverb, EffectKind::chorus, EffectKind::filter,
  2354. EffectKind::distortion, EffectKind::utility, EffectKind::volumeGate,
  2355. EffectKind::pitchShift, EffectKind::freqShift, EffectKind::lofi, EffectKind::effector, EffectKind::crossover, EffectKind::frequencySplitter, EffectKind::autoPan, EffectKind::vocoder, EffectKind::pitchCorrect,
  2356. EffectKind::ridgeStrip, EffectKind::glowLeveler, EffectKind::hushDeEsser, EffectKind::aether, EffectKind::ember, // LYNX's mixing suite
  2357. EffectKind::lynxTune, // LYNX's own pitch corrector
  2358. EffectKind::epochVerb, EffectKind::atrium, EffectKind::foilPlate, EffectKind::nebula, EffectKind::halo, EffectKind::horizon, // LYNX's reverbs
  2359. EffectKind::echoform, EffectKind::spiralEcho, EffectKind::orbit, EffectKind::latticeMod, // LYNX's delay / modulation suite
  2360. EffectKind::crestCompressor, EffectKind::prismMultiband, EffectKind::sentryGate, // LYNX's dynamics suite
  2361. EffectKind::quellDenoiser, EffectKind::geminiDoubler, EffectKind::voiceShift, // LYNX's voice tools
  2362. EffectKind::formulaController, EffectKind::peakController, EffectKind::xyController, EffectKind::xyzController,
  2363. EffectKind::controlSurface, // controllers (link their output to any knob)
  2364. EffectKind::patcher, // FL's Patcher: a graph of effects / instruments / plugins (REA_rodada141)
  2365. EffectKind::hardwareInsert, // outboard gear through device outputs / inputs, pinged round trip (round 164d)
  2366. EffectKind::fruityLimiter, EffectKind::fruityCompressor,
  2367. EffectKind::fruityWaveShaper, EffectKind::fruitySoftClipper,
  2368. EffectKind::reeverb2, EffectKind::reeverb1,
  2369. EffectKind::fruityDelay2, EffectKind::fruityDelay3,
  2370. EffectKind::stereoShaper, EffectKind::stereoEnhancer, EffectKind::transientProcessor,
  2371. EffectKind::spreader, EffectKind::fruityChorus, EffectKind::hyperChorus, EffectKind::vintageChorus,
  2372. EffectKind::fruityPanOMatic, EffectKind::fruityBalance, EffectKind::fruityBloodOverdrive, EffectKind::fruitySend,
  2373. EffectKind::fruityDelayBank, EffectKind::fruityMultiband,
  2374. EffectKind::fruityFastDist, EffectKind::fruityFlangus, EffectKind::fruityFlanger, EffectKind::fruityPhaser, EffectKind::luxeVerb,
  2375. EffectKind::fruityFastLP, EffectKind::fruityFreeFilter, EffectKind::fruityFilter,
  2376. EffectKind::hardcore,
  2377. EffectKind::multibandDelay, EffectKind::emphasizer, EffectKind::flEmphasis, EffectKind::flFrequencyShifter, EffectKind::flLowLifter,
  2378. EffectKind::flPhaseInverter, EffectKind::flCenter, EffectKind::flBassBoost, EffectKind::fl7BandEq, EffectKind::flDelay1, // round 165k
  2379. EffectKind::waveCandy, EffectKind::visualizer, // visual plugins (round 164c)
  2380. EffectKind::fruityMute2, EffectKind::bigClock, EffectKind::tuner, EffectKind::htmlNotebook, // round 165g
  2381. EffectKind::scratcher, // round 165g (flscratch165): FL's turntable
  2382. EffectKind::transmitter, // round 165g (fltrans165): FL's transient / sustain splitter
  2383. EffectKind::flTransporter, // round 167f: FL's transient looper, exact
  2384. // FL engines that need more than their parameters (round 142, issue #5): a new one starts from
  2385. // the plugin's Default preset of the user's FL installation (core/NativeEngines.h)
  2386. EffectKind::maximus, EffectKind::vocodex, EffectKind::equo, EffectKind::distructor, EffectKind::lovePhilter,
  2387. EffectKind::grossBeat, EffectKind::convolver, EffectKind::flPitchShifter, EffectKind::vintagePhaser,
  2388. EffectKind::squeeze, EffectKind::rhythmGain, EffectKind::newtone, EffectKind::newtime };
  2389. } // namespace
  2390. const std::vector<EffectKind>& addableEffects()
  2391. {
  2392. static const std::vector<EffectKind> list (std::begin (allEffects), std::end (allEffects));
  2393. return list;
  2394. }
  2395. bool isFlEffect (EffectKind kind)
  2396. {
  2397. // allEffects lists LYNX's own effects first and FL's from the Formula Controller on (the outboard gear insert is LYNX's)
  2398. const auto& list = addableEffects();
  2399. const auto first = std::find (list.begin(), list.end(), EffectKind::formulaController);
  2400. const auto at = std::find (list.begin(), list.end(), kind);
  2401. return at != list.end() && at >= first && kind != EffectKind::hardwareInsert;
  2402. }
  2403. bool addableEffectAvailable (EffectKind kind)
  2404. {
  2405. const auto* e = natives::effectEngine (kind);
  2406. return e == nullptr || natives::available (*e, flStudioAccess());
  2407. }
  2408. juce::String addableEffectName (EffectKind kind)
  2409. {
  2410. const auto name = juce::String::fromUTF8 (effectInfo (kind).name);
  2411. // LYNX's own pitch / frequency effects sit next to FL's look-alikes (Pitch Shifter, Frequency Shifter, Pitcher)
  2412. // in the lists: tell them apart (round 162, issue #7 review)
  2413. if (kind == EffectKind::pitchShift || kind == EffectKind::freqShift || kind == EffectKind::pitchCorrect)
  2414. return tr ("{0} (LYNX SHARE)", { name });
  2415. if (const auto* e = natives::effectEngine (kind))
  2416. {
  2417. if (! natives::available (*e, flStudioAccess()))
  2418. return tr ("{0} (requires FL Studio)", { name });
  2419. if (e->beta)
  2420. return tr ("{0} (beta)", { name });
  2421. }
  2422. return name;
  2423. }
  2424. std::optional<EffectSlot> newAddableEffect (EffectKind kind, double bpm)
  2425. {
  2426. return natives::newEffect (kind, flStudioAccess(), bpm);
  2427. }
  2428. EffectsPanel::EffectsPanel (AudioEngine& e)
  2429. : engine (e)
  2430. {
  2431. setWantsKeyboardFocus (false);
  2432. setMouseClickGrabsKeyboardFocus (false);
  2433. engine.addChangeListener (this);
  2434. startTimerHz (30);
  2435. }
  2436. EffectsPanel::~EffectsPanel()
  2437. {
  2438. engine.removeChangeListener (this);
  2439. }
  2440. juce::Rectangle<int> EffectsPanel::armBounds() const
  2441. {
  2442. return { 8, panelHeader + 2, 24, inputRowHeight - 8 };
  2443. }
  2444. juce::Rectangle<int> EffectsPanel::inputBoxBounds() const
  2445. {
  2446. return { 38, panelHeader + 2, getWidth() - 46, inputRowHeight - 8 };
  2447. }
  2448. void EffectsPanel::timerCallback()
  2449. {
  2450. // the input level of the shown insert (the strips read their own); decays like a meter
  2451. const auto& mixer = engine.getSong().mixer;
  2452. const auto hasInput = track >= 0 && track < (int) mixer.size() && mixer[(std::size_t) track].inputChannel >= 0;
  2453. auto changed = false;
  2454. for (int side = 0; side < 2; ++side)
  2455. {
  2456. const auto peak = hasInput ? engine.peekInputPeak (track, side) : 0.0f;
  2457. const auto level = juce::jmax (peak, inputLevel[(std::size_t) side] * 0.8f);
  2458. changed = changed || std::abs (level - inputLevel[(std::size_t) side]) > 1e-4f;
  2459. inputLevel[(std::size_t) side] = level < 1e-4f ? 0.0f : level;
  2460. }
  2461. if (changed && isShowing())
  2462. repaint (inputBoxBounds());
  2463. // another effect selected (its controls need another height): fold / unfold the EQ, scroll (round 164)
  2464. if (const auto* s = slots(); s != nullptr && isShowing())
  2465. {
  2466. const auto kind = selectedSlot >= 0 && selectedSlot < (int) s->size() ? (int) (*s)[(std::size_t) selectedSlot].kind : -1;
  2467. if (selectedSlot != fittedSlot || kind != fittedKind)
  2468. {
  2469. fittedSlot = selectedSlot;
  2470. fittedKind = kind;
  2471. refit();
  2472. }
  2473. }
  2474. }
  2475. void EffectsPanel::setTrack (int t)
  2476. {
  2477. track = t;
  2478. const auto* s = slots();
  2479. selectedSlot = s != nullptr && ! s->empty() ? 0 : -1;
  2480. refit();
  2481. repaint();
  2482. }
  2483. const std::vector<EffectSlot>* EffectsPanel::slots() const
  2484. {
  2485. const auto& mixer = engine.getSong().mixer;
  2486. return track >= 0 && track < (int) mixer.size() ? &mixer[(std::size_t) track].effects : nullptr;
  2487. }
  2488. int EffectsPanel::rowOf (int index) const
  2489. {
  2490. const auto* s = slots();
  2491. if (s == nullptr || index < 0 || index >= (int) s->size())
  2492. return -1;
  2493. return mixerops::effectRows (*s)[(std::size_t) index];
  2494. }
  2495. int EffectsPanel::effectIn (int row) const
  2496. {
  2497. const auto* s = slots();
  2498. return s == nullptr ? -1 : mixerops::effectAtRow (*s, row);
  2499. }
  2500. juce::Rectangle<int> EffectsPanel::mixBounds (int slot) const
  2501. {
  2502. return slotBounds (slot).withTrimmedRight (20).removeFromRight (24);
  2503. }
  2504. juce::Rectangle<int> EffectsPanel::ledBounds (int slot) const
  2505. {
  2506. return slotBounds (slot).removeFromRight (20);
  2507. }
  2508. juce::Rectangle<int> EffectsPanel::arrowBounds (int slot) const
  2509. {
  2510. return slotBounds (slot).removeFromLeft (18);
  2511. }
  2512. // --- the insert's built-in EQ and its output (FL's layout under the slots, REA round 104) ---------
  2513. namespace
  2514. {
  2515. constexpr int eqGraphHeight = 84, eqKnobsHeight = 46, outputRowHeight = 30;
  2516. constexpr float eqMinHz = 20.0f, eqMaxHz = 20000.0f, eqRangeDb = 18.0f;
  2517. const char* const eqBandNames[] = { TR_NOOP ("Low shelf"), TR_NOOP ("Peak"), TR_NOOP ("High shelf") };
  2518. juce::Colour eqBandColour (int band)
  2519. {
  2520. return band == 0 ? juce::Colour (0xFFE0A33Au) : band == 1 ? juce::Colour (0xFF5FC27Eu) : juce::Colour (0xFF5B9BE6u);
  2521. }
  2522. // stored 0..1 <-> the band's value
  2523. float eqToValue (const TrackEq& eq, int band, int what)
  2524. {
  2525. const auto b = (std::size_t) band;
  2526. if (what == 0)
  2527. return (eq.gainDb[b] + eqRangeDb) / (2.0f * eqRangeDb);
  2528. if (what == 1)
  2529. return std::log (eq.hz[b] / 10.0f) / std::log (1600.0f);
  2530. return eq.width[b];
  2531. }
  2532. void eqFromValue (TrackEq& eq, int band, int what, float v)
  2533. {
  2534. const auto b = (std::size_t) band;
  2535. v = juce::jlimit (0.0f, 1.0f, v);
  2536. if (what == 0)
  2537. eq.gainDb[b] = std::round ((v * 2.0f * eqRangeDb - eqRangeDb) * 10.0f) / 10.0f;
  2538. else if (what == 1)
  2539. eq.hz[b] = std::round (10.0f * std::pow (1600.0f, v));
  2540. else
  2541. eq.width[b] = v;
  2542. }
  2543. // the EQ's response at `hz` (dB), with the filters the mixer runs (RackRenderer::applyTrackEq)
  2544. float eqResponseDb (const TrackEq& eq, double hz, double sampleRate)
  2545. {
  2546. Biquad bands[3];
  2547. bands[0].shelf (sampleRate, std::min ((double) eq.hz[0], sampleRate * 0.45), eq.gainDb[0], false, TrackEq::shelfSlope (eq.width[0]));
  2548. bands[1].peaking (sampleRate, std::min ((double) eq.hz[1], sampleRate * 0.45), TrackEq::peakQ (eq.width[1]), eq.gainDb[1]);
  2549. bands[2].shelf (sampleRate, std::min ((double) eq.hz[2], sampleRate * 0.45), eq.gainDb[2], true, TrackEq::shelfSlope (eq.width[2]));
  2550. const auto w = juce::MathConstants<double>::twoPi * hz / sampleRate;
  2551. const std::complex<double> z1 = std::polar (1.0, -w), z2 = std::polar (1.0, -2.0 * w);
  2552. double db = 0.0;
  2553. for (int b = 0; b < 3; ++b)
  2554. {
  2555. if (eq.gainDb[(std::size_t) b] == 0.0f)
  2556. continue; // a band at 0 dB is not processed (like FL)
  2557. const auto& f = bands[b];
  2558. const auto h = (f.b0 + f.b1 * z1 + f.b2 * z2) / (1.0 + f.a1 * z1 + f.a2 * z2);
  2559. db += 20.0 * std::log10 (std::max (1e-9, std::abs (h)));
  2560. }
  2561. return (float) db;
  2562. }
  2563. } // namespace
  2564. constexpr int eqFoldBarHeight = 20;
  2565. bool EffectsPanel::eqShown() const
  2566. {
  2567. return ! engine.getSong().cleanMixer; // clean mixer (round 163): no built-in EQ to show
  2568. }
  2569. int EffectsPanel::belowHeight (bool folded) const
  2570. {
  2571. if (! eqShown()) // clean mixer: only the output row
  2572. return outputRowHeight + 8;
  2573. return outputRowHeight + eqFoldBarHeight + (folded ? 4 : eqGraphHeight + eqKnobsHeight + 14);
  2574. }
  2575. int EffectsPanel::bottomTop() const
  2576. {
  2577. return getHeight() - belowHeight (eqFolded);
  2578. }
  2579. juce::Rectangle<int> EffectsPanel::eqFoldBounds() const
  2580. {
  2581. if (! eqShown())
  2582. return {};
  2583. return { 8, bottomTop(), getWidth() - 16, eqFoldBarHeight };
  2584. }
  2585. int EffectsPanel::neededHeight (bool folded) const
  2586. {
  2587. // the slots and the selected effect's controls (round 164: its knobs and their names and values too, they were
  2588. // cut by the EQ at medium heights): when they don't fit with the EQ open, it folds; then the panel scrolls
  2589. return selectedEffectBottom() + 6 + belowHeight (folded);
  2590. }
  2591. void EffectsPanel::fitToView (int w, int h, int scrollBar)
  2592. {
  2593. viewWidth = w;
  2594. viewHeight = h;
  2595. scrollBarThickness = scrollBar;
  2596. refit();
  2597. }
  2598. void EffectsPanel::refit()
  2599. {
  2600. if (viewWidth <= 0 || viewHeight <= 0)
  2601. return;
  2602. const auto folded = eqFoldChoice == 2 || (eqFoldChoice == 0 && viewHeight < neededHeight (false));
  2603. const auto need = neededHeight (folded);
  2604. const auto scrolls = viewHeight < need;
  2605. const auto changed = folded != eqFolded;
  2606. eqFolded = folded;
  2607. const juce::Rectangle<int> size (viewWidth - (scrolls ? scrollBarThickness : 0), juce::jmax (viewHeight, need));
  2608. if (getWidth() != size.getWidth() || getHeight() != size.getHeight())
  2609. setSize (size.getWidth(), size.getHeight());
  2610. else if (changed)
  2611. repaint();
  2612. }
  2613. juce::Rectangle<int> EffectsPanel::eqGraphBounds() const
  2614. {
  2615. return { 8, bottomTop() + eqFoldBarHeight, getWidth() - 16 - 3 * 18 - 6, eqGraphHeight };
  2616. }
  2617. juce::Rectangle<int> EffectsPanel::eqFaderBounds (int band) const
  2618. {
  2619. const auto graph = eqGraphBounds();
  2620. return { graph.getRight() + 6 + band * 18, graph.getY(), 16, graph.getHeight() };
  2621. }
  2622. juce::Rectangle<int> EffectsPanel::eqKnobBounds (int band, int what) const
  2623. {
  2624. const auto fader = eqFaderBounds (band);
  2625. return { fader.getCentreX() - 11, eqGraphBounds().getBottom() + 2 + (what - 1) * 22, 22, 22 };
  2626. }
  2627. juce::Rectangle<int> EffectsPanel::outputBounds() const
  2628. {
  2629. return { 34, getHeight() - outputRowHeight - 2, getWidth() - 42, outputRowHeight - 8 };
  2630. }
  2631. juce::Point<float> EffectsPanel::eqHandle (int band) const
  2632. {
  2633. const auto graph = eqGraphBounds().toFloat().reduced (4.0f);
  2634. const auto& eq = engine.getSong().mixer[(std::size_t) track].eq;
  2635. const auto hz = juce::jlimit (eqMinHz, eqMaxHz, eq.hz[(std::size_t) band]);
  2636. const auto x = graph.getX() + graph.getWidth() * std::log (hz / eqMinHz) / std::log (eqMaxHz / eqMinHz);
  2637. const auto y = graph.getCentreY() - graph.getHeight() * 0.5f * eq.gainDb[(std::size_t) band] / eqRangeDb;
  2638. return { x, y };
  2639. }
  2640. int EffectsPanel::eqControlAt (juce::Point<int> p) const
  2641. {
  2642. if (slots() == nullptr || eqFolded || ! eqShown())
  2643. return 0;
  2644. for (int b = 0; b < 3; ++b)
  2645. {
  2646. if (eqFaderBounds (b).contains (p))
  2647. return eqParamBase - b * 3;
  2648. for (int what = 1; what <= 2; ++what)
  2649. if (eqKnobBounds (b, what).contains (p))
  2650. return eqParamBase - b * 3 - what;
  2651. }
  2652. if (eqGraphBounds().contains (p))
  2653. {
  2654. // the nearest handle (by distance in the graph): FL's "Tweak band N"
  2655. int best = 0;
  2656. float bestDistance = 1e9f;
  2657. for (int b = 0; b < 3; ++b)
  2658. if (const auto d = eqHandle (b).getDistanceFrom (p.toFloat()); d < bestDistance)
  2659. {
  2660. bestDistance = d;
  2661. best = b;
  2662. }
  2663. return eqPointBase - best;
  2664. }
  2665. return 0;
  2666. }
  2667. void EffectsPanel::setEqFromGraph (int band, juce::Point<int> p)
  2668. {
  2669. const auto graph = eqGraphBounds().toFloat().reduced (4.0f);
  2670. const auto fx = juce::jlimit (0.0f, 1.0f, (p.x - graph.getX()) / graph.getWidth());
  2671. const auto hz = juce::jlimit (10.0f, 16000.0f, std::round (eqMinHz * std::pow (eqMaxHz / eqMinHz, fx)));
  2672. const auto db = juce::jlimit (-eqRangeDb, eqRangeDb, std::round ((graph.getCentreY() - p.y) / (graph.getHeight() * 0.5f) * eqRangeDb * 10.0f) / 10.0f);
  2673. engine.editSong ([t = track, band, hz, db] (Song& s) {
  2674. if (t < (int) s.mixer.size())
  2675. {
  2676. s.mixer[(std::size_t) t].eq.hz[(std::size_t) band] = hz;
  2677. s.mixer[(std::size_t) t].eq.gainDb[(std::size_t) band] = db;
  2678. }
  2679. });
  2680. }
  2681. void EffectsPanel::paintEq (juce::Graphics& g)
  2682. {
  2683. using namespace theme;
  2684. const auto& song = engine.getSong();
  2685. if (track < 0 || track >= (int) song.mixer.size())
  2686. return;
  2687. const auto& eq = song.mixer[(std::size_t) track].eq;
  2688. const auto top = bottomTop();
  2689. g.setColour (colour::border);
  2690. g.fillRect (8, top, getWidth() - 16, 1);
  2691. // the title bar: click folds / unfolds the EQ (it folds by itself when the mixer is too short for it)
  2692. if (eqShown())
  2693. {
  2694. const auto bar = eqFoldBounds().toFloat();
  2695. const auto active = eq.gainDb[0] != 0.0f || eq.gainDb[1] != 0.0f || eq.gainDb[2] != 0.0f;
  2696. auto chevron = bar.withWidth (14.0f).withSizeKeepingCentre (12.0f, 12.0f);
  2697. {
  2698. juce::Graphics::ScopedSaveState state (g);
  2699. if (eqFolded)
  2700. g.addTransform (juce::AffineTransform::rotation (-juce::MathConstants<float>::halfPi, chevron.getCentreX(), chevron.getCentreY()));
  2701. icons::draw (g, Icon::chevronDown, chevron, colour::textSecondary);
  2702. }
  2703. g.setFont (font (type::small, true));
  2704. g.setColour (colour::textSecondary);
  2705. textcache::drawText (g, tr ("EQ"), bar.withTrimmedLeft (18.0f).toNearestInt(), juce::Justification::centredLeft);
  2706. if (eqFolded && active) // a folded EQ that still changes the sound says so
  2707. {
  2708. g.setColour (colour::accent);
  2709. g.setFont (font (type::caption));
  2710. textcache::drawText (g, tr ("active"), bar.withTrimmedLeft (44.0f).toNearestInt(), juce::Justification::centredLeft);
  2711. }
  2712. }
  2713. if (! eqFolded && eqShown())
  2714. {
  2715. // the response graph: frequency (log) across, ±18 dB up and down
  2716. const auto graph = eqGraphBounds().toFloat();
  2717. theme::fillRoundRect (g, graph, radius::sm, colour::bg1);
  2718. g.setColour (colour::border);
  2719. g.drawRoundedRectangle (graph.reduced (0.5f), radius::sm, 1.0f);
  2720. const auto inner = graph.reduced (4.0f);
  2721. g.setColour (colour::gridBeat);
  2722. for (float hz : { 100.0f, 1000.0f, 10000.0f })
  2723. {
  2724. const auto x = inner.getX() + inner.getWidth() * std::log (hz / eqMinHz) / std::log (eqMaxHz / eqMinHz);
  2725. g.drawVerticalLine ((int) x, inner.getY(), inner.getBottom());
  2726. }
  2727. g.drawHorizontalLine ((int) inner.getCentreY(), inner.getX(), inner.getRight());
  2728. juce::Path curve;
  2729. const auto sampleRate = juce::jmax (8000.0, engine.getTransport().sampleRate.load());
  2730. for (int i = 0; i <= (int) inner.getWidth(); i += 2)
  2731. {
  2732. const auto hz = eqMinHz * std::pow (eqMaxHz / eqMinHz, (float) i / inner.getWidth());
  2733. const auto db = juce::jlimit (-eqRangeDb, eqRangeDb, eqResponseDb (eq, hz, sampleRate));
  2734. const auto y = inner.getCentreY() - inner.getHeight() * 0.5f * db / eqRangeDb;
  2735. if (i == 0)
  2736. curve.startNewSubPath (inner.getX(), y);
  2737. else
  2738. curve.lineTo (inner.getX() + (float) i, y);
  2739. }
  2740. g.setColour (eq.active() ? colour::accent : colour::textSecondary.withAlpha (0.6f));
  2741. g.strokePath (curve, juce::PathStrokeType (1.5f));
  2742. for (int b = 0; b < 3; ++b)
  2743. {
  2744. const auto hot = hoverEq == eqPointBase - b || dragParam == eqPointBase - b;
  2745. const auto handle = eqHandle (b);
  2746. g.setColour (eqBandColour (b).withAlpha (hot ? 1.0f : 0.8f));
  2747. g.fillEllipse (juce::Rectangle<float> (hot ? 10.0f : 8.0f, hot ? 10.0f : 8.0f).withCentre (handle));
  2748. }
  2749. // the gain faders (one per band) and the frequency / width knobs under them
  2750. for (int b = 0; b < 3; ++b)
  2751. {
  2752. const auto fader = eqFaderBounds (b).toFloat();
  2753. const auto hot = hoverEq == eqParamBase - b * 3 || dragParam == eqParamBase - b * 3;
  2754. theme::fillRoundRect (g, fader.withSizeKeepingCentre (3.0f, fader.getHeight() - 6.0f), 1.5f, colour::bg0);
  2755. g.setColour (colour::border);
  2756. g.drawHorizontalLine ((int) fader.getCentreY(), fader.getX() + 2.0f, fader.getRight() - 2.0f);
  2757. const auto v = eqToValue (eq, b, 0);
  2758. const auto y = fader.getBottom() - 6.0f - v * (fader.getHeight() - 12.0f);
  2759. theme::fillRoundRect (g, juce::Rectangle<float> (fader.getWidth() - 2.0f, 7.0f).withCentre ({ fader.getCentreX(), y }), 2.0f, hot ? colour::textPrimary : colour::textSecondary);
  2760. g.setColour (eqBandColour (b));
  2761. g.fillRect (juce::Rectangle<float> (fader.getWidth() - 6.0f, 1.5f).withCentre ({ fader.getCentreX(), y }));
  2762. for (int what = 1; what <= 2; ++what)
  2763. {
  2764. const auto code = eqParamBase - b * 3 - what;
  2765. drawKnob (g, eqKnobBounds (b, what).toFloat().reduced (2.0f), eqToValue (eq, b, what), false, eqBandColour (b),
  2766. hoverEq == code || dragParam == code);
  2767. }
  2768. }
  2769. // the knob captions take the width their (translated) text needs, the title gives way (round 165o)
  2770. const juce::Font captionFont (font (type::caption));
  2771. const auto captionWidth = juce::jlimit (32, 70, (int) std::ceil (juce::jmax (juce::GlyphArrangement::getStringWidth (captionFont, tr ("Freq")),
  2772. juce::GlyphArrangement::getStringWidth (captionFont, tr ("Width")))) + 2);
  2773. g.setColour (colour::textSecondary);
  2774. g.setFont (font (type::title));
  2775. textcache::drawText (g, tr ("Equalizer"), 10, eqGraphBounds().getBottom() + 4, eqKnobBounds (0, 1).getX() - 8 - captionWidth, 20,
  2776. juce::Justification::centredLeft);
  2777. g.setFont (captionFont);
  2778. g.setColour (colour::textDisabled);
  2779. textcache::drawText (g, tr ("Freq"), eqKnobBounds (0, 1).getX() - 2 - captionWidth, eqKnobBounds (0, 1).getY(), captionWidth, 22,
  2780. juce::Justification::centredRight);
  2781. textcache::drawText (g, tr ("Width"), eqKnobBounds (0, 2).getX() - 2 - captionWidth, eqKnobBounds (0, 2).getY(), captionWidth, 22,
  2782. juce::Justification::centredRight);
  2783. }
  2784. // the audio output target
  2785. auto box = outputBounds().toFloat();
  2786. g.setColour (colour::border);
  2787. g.fillRect (8, (int) box.getY() - 5, getWidth() - 16, 1);
  2788. icons::draw (g, Icon::exportAudio, juce::Rectangle<float> (10.0f, box.getY(), 18.0f, box.getHeight()).withSizeKeepingCentre (16.0f, 16.0f),
  2789. colour::textSecondary);
  2790. theme::fillRoundRect (g, box, radius::sm, hoverOutput ? colour::bg4 : colour::bg3);
  2791. g.setColour (hoverOutput ? colour::borderStrong : colour::border);
  2792. g.drawRoundedRectangle (box.reduced (0.5f), radius::sm, 1.0f);
  2793. g.setColour (track == 0 ? colour::textPrimary : colour::textSecondary);
  2794. g.setFont (font (type::body));
  2795. textcache::drawText (g, outputName(), box.withTrimmedLeft (8.0f).withTrimmedRight (18.0f).toNearestInt(), juce::Justification::centredLeft, true);
  2796. icons::draw (g, Icon::chevronDown, box.removeFromRight (18.0f).reduced (4.0f).translated (-2.0f, 0.0f), colour::textSecondary);
  2797. }
  2798. juce::String EffectsPanel::outputName() const
  2799. {
  2800. if (track == 0 && const_cast<AudioEngine&> (engine).getDeviceManager().getCurrentAudioDevice() == nullptr)
  2801. return tr ("(no audio device)");
  2802. return mixeroutput::label (engine, track);
  2803. }
  2804. void EffectsPanel::showOutputMenu()
  2805. {
  2806. mixeroutput::showMenu (engine, track, this, localAreaToGlobal (outputBounds()));
  2807. }
  2808. namespace mixeroptions
  2809. {
  2810. std::function<void()> changed;
  2811. std::function<void (bool)> setShowUsedOnly;
  2812. std::function<void (std::vector<int>, std::function<void (const std::vector<juce::File>&)>)> renderTracks;
  2813. namespace
  2814. {
  2815. void notifyChanged()
  2816. {
  2817. if (changed)
  2818. changed();
  2819. }
  2820. void askNumber (const juce::String& title, const juce::String& text, int value, int lo, int hi, std::function<void (int)> done)
  2821. {
  2822. auto* w = new juce::AlertWindow (title, text, juce::MessageBoxIconType::NoIcon);
  2823. w->addTextEditor ("n", juce::String (value));
  2824. w->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  2825. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  2826. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, lo, hi, done = std::move (done)] (int result) {
  2827. if (result == 1)
  2828. done (juce::jlimit (lo, hi, w->getTextEditorContents ("n").trim().getIntValue()));
  2829. }), true);
  2830. }
  2831. } // namespace
  2832. void addItems (juce::PopupMenu& menu, AudioEngine& engine, bool newProjects)
  2833. {
  2834. const auto& song = engine.getSong();
  2835. menu.addItem (tr ("Clean mixer: no built-in EQ on the inserts (this project)"), true, song.cleanMixer, [&engine] {
  2836. const auto on = ! engine.getSong().cleanMixer;
  2837. engine.editSong ([on] (Song& s) { s.cleanMixer = on; });
  2838. const auto& mixer = engine.getSong().mixer;
  2839. const auto withEq = std::count_if (mixer.begin(), mixer.end(), [] (const MixerTrack& t) { return t.eq.active(); });
  2840. if (on && withEq > 0) // nothing is lost: switching it off brings the EQ back as it was
  2841. ui::postHint ({ tr ("Clean mixer: the EQ of {0} insert(s) is bypassed and hidden (kept in the project)", { juce::String ((int) withEq) }), {}, false, false }, 5000);
  2842. });
  2843. menu.addItem (tr ("Show only used inserts"), true, MixerStrips::showUsedOnly, [] {
  2844. const auto on = ! MixerStrips::showUsedOnly;
  2845. if (setShowUsedOnly)
  2846. setShowUsedOnly (on);
  2847. else
  2848. MixerStrips::showUsedOnly = on;
  2849. notifyChanged();
  2850. });
  2851. menu.addItem (tr ("Remove unused inserts at the end"), song.mixer.size() > 1 && ! song.insertInUse ((int) song.mixer.size() - 1), false, [&engine] {
  2852. int removed = 0;
  2853. engine.editSong ([&removed] (Song& s) { removed = mixerops::removeUnusedTrailingInserts (s); });
  2854. ui::postHint ({ tr ("Removed {0} unused insert(s)", { juce::String (removed) }), {}, false, false }, 3000);
  2855. });
  2856. if (! newProjects)
  2857. return;
  2858. auto& d = newProjectDefaults();
  2859. menu.addSectionHeader (tr ("New projects"));
  2860. {
  2861. juce::PopupMenu inserts;
  2862. bool listed = false;
  2863. for (int n : { 0, 1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 100, 125 })
  2864. {
  2865. listed = listed || n == d.inserts;
  2866. inserts.addItem (n == NewProjectDefaults::defaultInserts ? tr ("{0} (default)", { juce::String (n) }) : juce::String (n), true, n == d.inserts, [n] {
  2867. newProjectDefaults().inserts = n;
  2868. notifyChanged();
  2869. });
  2870. }
  2871. inserts.addItem (listed ? tr ("Other...") : tr ("Other ({0})...", { juce::String (d.inserts) }), true, ! listed, [] {
  2872. askNumber (tr ("Inserts in new projects"),
  2873. tr ("How many mixer inserts a new project starts with (0 to {0}). More are added when you need them.", { juce::String (maxMixerTracks - 1) }),
  2874. newProjectDefaults().inserts, 0, maxMixerTracks - 1, [] (int n) {
  2875. newProjectDefaults().inserts = n;
  2876. notifyChanged();
  2877. });
  2878. });
  2879. menu.addSubMenu (tr ("Inserts in new projects ({0})", { juce::String (d.inserts) }), inserts);
  2880. }
  2881. {
  2882. juce::PopupMenu chain;
  2883. const std::pair<const char*, MasterChain> chains[] = { { TR_NOOP ("Empty (nothing on the Master)"), MasterChain::empty },
  2884. { TR_NOOP ("Soft clipper only"), MasterChain::clipper },
  2885. { TR_NOOP ("LYNX SHARE default (limiter)"), MasterChain::lynxDefault } };
  2886. for (const auto& [label, c] : chains)
  2887. chain.addItem (tr (label), true, d.master == c, [c = c] {
  2888. newProjectDefaults().master = c;
  2889. notifyChanged();
  2890. });
  2891. menu.addSubMenu (tr ("Master chain in new projects"), chain);
  2892. }
  2893. menu.addItem (tr ("Clean mixer in new projects (no built-in EQ)"), true, d.cleanMixer, [] {
  2894. newProjectDefaults().cleanMixer = ! newProjectDefaults().cleanMixer;
  2895. notifyChanged();
  2896. });
  2897. {
  2898. juce::PopupMenu tracks;
  2899. for (int n : { 4, 8, 16, 24, 32, 64, 100 })
  2900. tracks.addItem (n == 16 ? tr ("{0} (default)", { juce::String (n) }) : juce::String (n), true, n == d.playlistTracks, [n] {
  2901. newProjectDefaults().playlistTracks = n;
  2902. notifyChanged();
  2903. });
  2904. menu.addSubMenu (tr ("Playlist tracks shown ({0})", { juce::String (d.playlistTracks) }), tracks);
  2905. }
  2906. }
  2907. } // namespace mixeroptions
  2908. namespace mixeroutput
  2909. {
  2910. namespace
  2911. {
  2912. juce::String modeSuffix (OutputMode mode)
  2913. {
  2914. switch (mode)
  2915. {
  2916. case OutputMode::stereo: return {};
  2917. case OutputMode::monoSum: return " " + tr ("(mono)");
  2918. case OutputMode::monoLeft: return " " + tr ("(mono, L)");
  2919. case OutputMode::monoRight: return " " + tr ("(mono, R)");
  2920. }
  2921. return {};
  2922. }
  2923. } // namespace
  2924. bool isCustom (const AudioEngine& engine, int track)
  2925. {
  2926. const auto& mixer = engine.getSong().mixer;
  2927. if (track < 0 || track >= (int) mixer.size())
  2928. return false;
  2929. const auto channel = mixer[(std::size_t) track].outputChannel;
  2930. return track == 0 ? channel != outputDefault : channel >= 0;
  2931. }
  2932. juce::String label (const AudioEngine& engine, int track, bool compact)
  2933. {
  2934. const auto& mixer = engine.getSong().mixer;
  2935. if (track < 0 || track >= (int) mixer.size())
  2936. return {};
  2937. const auto& mt = mixer[(std::size_t) track];
  2938. auto channel = mt.outputChannel;
  2939. auto mode = mt.outputMode;
  2940. if (track == 0 && channel == outputDefault)
  2941. channel = 0, mode = OutputMode::stereo;
  2942. if (channel < 0)
  2943. return tr ("(none)");
  2944. const auto names = engine.getOutputChannelNames();
  2945. const auto missing = ! outputAvailable (channel, mode, (int) names.size())
  2946. || ! engine.isOutputChannelOpen (channel) || (mode == OutputMode::stereo && ! engine.isOutputChannelOpen (channel + 1));
  2947. if (compact) // the strip badge: the channel numbers only
  2948. {
  2949. auto text = juce::String::fromUTF8 ("\xe2\x86\x92 ") + juce::String (channel + 1);
  2950. if (mode == OutputMode::stereo)
  2951. text << "-" << (channel + 2);
  2952. else
  2953. text << (mode == OutputMode::monoLeft ? " L" : mode == OutputMode::monoRight ? " R" : " m");
  2954. return missing ? text + " ?" : text;
  2955. }
  2956. auto nameOf = [&] (int c) {
  2957. return c < (int) names.size() ? juce::String::fromUTF8 (names[(std::size_t) c].c_str()) : tr ("Out {0}", { juce::String (c + 1) });
  2958. };
  2959. auto text = mode == OutputMode::stereo ? nameOf (channel) + " - " + nameOf (channel + 1) : nameOf (channel);
  2960. text += modeSuffix (mode);
  2961. if (missing)
  2962. text += " " + tr ("(missing)");
  2963. return text;
  2964. }
  2965. void showMenu (AudioEngine& engine, int track, juce::Component* target, juce::Rectangle<int> screenArea)
  2966. {
  2967. const auto& mixer = engine.getSong().mixer;
  2968. if (track < 0 || track >= (int) mixer.size())
  2969. return;
  2970. const auto& mt = mixer[(std::size_t) track];
  2971. const auto names = engine.getOutputChannelNames();
  2972. const auto custom = isCustom (engine, track);
  2973. juce::PopupMenu menu;
  2974. menu.addSectionHeader (tr ("Audio output target"));
  2975. auto set = [&engine, track] (int channel, OutputMode mode) {
  2976. return [&engine, track, channel, mode] { engine.setTrackOutput (track, channel, mode); };
  2977. };
  2978. if (track == 0)
  2979. {
  2980. const auto first = names.size() >= 2 ? juce::String::fromUTF8 (names[0].c_str()) + " - " + juce::String::fromUTF8 (names[1].c_str())
  2981. : tr ("first output pair");
  2982. menu.addItem (first + " " + tr ("(default)"), true, mt.outputChannel == outputDefault, set (outputDefault, OutputMode::stereo));
  2983. menu.addItem (tr ("(none)"), true, mt.outputChannel == outputNone, set (outputNone, OutputMode::stereo));
  2984. }
  2985. else
  2986. menu.addItem (tr ("(none) - through the Master only"), true, ! custom, set (outputDefault, OutputMode::stereo));
  2987. if (custom && (track > 0 || mt.outputChannel >= 0))
  2988. menu.addItem (label (engine, track), true, true, nullptr); // the current target (also when missing)
  2989. // the optional direct outputs: stereo pairs, then every channel alone
  2990. juce::PopupMenu direct;
  2991. direct.addItem (track == 0 ? tr ("Optional: send the Master to other outputs of your audio interface")
  2992. : tr ("Optional: also send this insert straight to an output of your audio interface, e.g. a mono output"),
  2993. false, false, nullptr);
  2994. if (names.empty())
  2995. direct.addItem (tr ("No audio device is open"), false, false, nullptr);
  2996. const auto targets = outputTargets (names);
  2997. auto pairsHeader = false, monoHeader = false;
  2998. for (const auto& t : targets)
  2999. {
  3000. const auto name = juce::String::fromUTF8 (t.name.c_str());
  3001. if (t.mode == OutputMode::stereo)
  3002. {
  3003. if (! std::exchange (pairsHeader, true))
  3004. direct.addSectionHeader (tr ("Stereo pair"));
  3005. direct.addItem (name, true, mt.outputChannel == t.channel && mt.outputMode == OutputMode::stereo, set (t.channel, OutputMode::stereo));
  3006. continue;
  3007. }
  3008. if (! std::exchange (monoHeader, true))
  3009. direct.addSectionHeader (tr ("Mono (one output)"));
  3010. const auto here = mt.outputChannel == t.channel && mt.outputMode != OutputMode::stereo;
  3011. juce::PopupMenu modes;
  3012. modes.addItem (tr ("Sum of L + R (mono)"), true, here && mt.outputMode == OutputMode::monoSum, set (t.channel, OutputMode::monoSum));
  3013. modes.addItem (tr ("Left side only"), true, here && mt.outputMode == OutputMode::monoLeft, set (t.channel, OutputMode::monoLeft));
  3014. modes.addItem (tr ("Right side only"), true, here && mt.outputMode == OutputMode::monoRight, set (t.channel, OutputMode::monoRight));
  3015. direct.addSubMenu (name, modes, true, nullptr, here);
  3016. }
  3017. if (! names.empty() && names.size() <= 2)
  3018. direct.addItem (tr ("This audio device has 2 outputs; an interface with more outputs lists all of them here"), false, false, nullptr);
  3019. menu.addSeparator();
  3020. menu.addSubMenu (track == 0 ? tr ("Hardware output") : tr ("Send to hardware output (optional)"), direct, true, nullptr, custom && mt.outputChannel >= 0);
  3021. if (custom)
  3022. menu.addItem (track == 0 ? tr ("Back to the default output") : tr ("Back to Master only"), set (outputDefault, OutputMode::stereo));
  3023. menu.addSeparator();
  3024. menu.addItem (tr ("Audio settings..."), [] {
  3025. if (mixerinput::openAudioSettings)
  3026. mixerinput::openAudioSettings();
  3027. });
  3028. auto options = juce::PopupMenu::Options();
  3029. if (target != nullptr)
  3030. options = options.withTargetComponent (target);
  3031. if (! screenArea.isEmpty())
  3032. options = options.withTargetScreenArea (screenArea);
  3033. else if (target != nullptr)
  3034. options = options.withMousePosition();
  3035. menu.showMenuAsync (options);
  3036. }
  3037. } // namespace mixeroutput
  3038. juce::Rectangle<int> EffectsPanel::slotBounds (int slot) const
  3039. {
  3040. return { 8, slotsTop + slot * slotHeight, getWidth() - 16, slotHeight - 3 };
  3041. }
  3042. namespace
  3043. {
  3044. // parameters shown as knobs: in the rhythmic envelope, only those of the points in use
  3045. int shownParams (const EffectSlot& slot)
  3046. {
  3047. const auto all = (int) effectInfo (slot.kind).params.size();
  3048. if (slot.kind == EffectKind::rhythmGain)
  3049. return std::min (all, 2 + 3 * (int) std::lround (slot.params[1] * 12.0f));
  3050. if (slot.kind == EffectKind::lynxTune) // the note switches are the keyboard strip above the knobs
  3051. return std::min (all, (int) lynxtune::noteC);
  3052. return all;
  3053. }
  3054. } // namespace
  3055. juce::Rectangle<int> EffectsPanel::knobBounds (int param) const
  3056. {
  3057. return knobBoundsIn (param, bottomTop());
  3058. }
  3059. juce::Rectangle<int> EffectsPanel::knobBoundsIn (int param, int areaBottom) const
  3060. {
  3061. auto top = slotsTop + maxEffectSlots * slotHeight + 40;
  3062. // many parameters (Effector: 12): 4 columns and shorter rows to fit the height
  3063. int count = 0;
  3064. if (const auto* s = slots(); ! gateSelected() && s != nullptr && selectedSlot >= 0 && selectedSlot < (int) s->size())
  3065. count = shownParams ((*s)[(std::size_t) selectedSlot]);
  3066. const auto columns = count > 9 ? 4 : 3;
  3067. const auto w = (getWidth() - 16) / columns;
  3068. const auto rows = juce::jmax (1, (count + columns - 1) / columns);
  3069. const auto rowHeight = count > 9 ? juce::jlimit (64, 86, (areaBottom - top - 4) / rows) : 86;
  3070. // volume gate: the 32 steps are bars (gateStepsBounds); the knobs are mix/attack/release
  3071. if (gateSelected())
  3072. {
  3073. if (param < 32)
  3074. return {};
  3075. param -= 32;
  3076. top = gateStepsBounds().getBottom() + 22;
  3077. }
  3078. if (vocoderSelected()) // the band levels above the knobs
  3079. top = bandLevelsBounds().getBottom() + 22;
  3080. if (tuneSelected()) // LYNX Tune's note keyboard above the knobs
  3081. top = tuneKeysBounds().getBottom() + 22;
  3082. return { 8 + (param % columns) * w, top + (param / columns) * rowHeight, w, rowHeight - 4 };
  3083. }
  3084. int EffectsPanel::selectedEffectBottom() const
  3085. {
  3086. const auto slotsBottom = slotsTop + maxEffectSlots * slotHeight;
  3087. auto bottom = slotsBottom + 64; // the effect's title row
  3088. const auto* s = slots();
  3089. if (s == nullptr || selectedSlot < 0 || selectedSlot >= (int) s->size())
  3090. return bottom;
  3091. const auto& slot = (*s)[(std::size_t) selectedSlot];
  3092. if (slot.kind == EffectKind::plugin || isSoundgoodizerApprox (slot))
  3093. return juce::jmax (bottom, pluginButtonBounds().getBottom() + 34 + 40);
  3094. if (slot.kind == EffectKind::parametricEq || slot.kind == EffectKind::facetEq)
  3095. return juce::jmax (bottom, pluginButtonBounds().getBottom() + 10 + 120);
  3096. if (slot.kind == EffectKind::parallel)
  3097. return juce::jmax (bottom, knobBoundsIn (0, 0).getY() - 28 + 20 + 22 * (int) slot.branches.size());
  3098. const auto count = gateSelected() ? 35 : shownParams (slot);
  3099. for (int p = 0; p < count; ++p)
  3100. if (const auto r = knobBoundsIn (p, 0); ! r.isEmpty()) // (tight grids at their shortest rows)
  3101. bottom = juce::jmax (bottom, r.getY() + juce::jlimit (30, 44, r.getHeight() - 30) + 32); // knob, name, value
  3102. return bottom;
  3103. }
  3104. bool EffectsPanel::gateSelected() const
  3105. {
  3106. const auto* s = slots();
  3107. return s != nullptr && selectedSlot >= 0 && selectedSlot < (int) s->size() && (*s)[(std::size_t) selectedSlot].kind == EffectKind::volumeGate;
  3108. }
  3109. juce::Rectangle<int> EffectsPanel::gateStepsBounds() const
  3110. {
  3111. return { 10, slotsTop + maxEffectSlots * slotHeight + 40, getWidth() - 20, 90 };
  3112. }
  3113. void EffectsPanel::setGateStep (juce::Point<int> p)
  3114. {
  3115. const auto area = gateStepsBounds();
  3116. const auto step = juce::jlimit (0, 31, (int) ((p.x - area.getX()) * 32 / juce::jmax (1, area.getWidth())));
  3117. const auto value = juce::jlimit (0.0f, 1.0f, (float) (area.getBottom() - p.y) / (float) area.getHeight());
  3118. engine.editSong ([t = track, slot = selectedSlot, step, value] (Song& song) {
  3119. song.mixer[(std::size_t) t].effects[(std::size_t) slot].params[(std::size_t) step] = value;
  3120. });
  3121. }
  3122. bool EffectsPanel::vocoderSelected() const
  3123. {
  3124. const auto* s = slots();
  3125. return s != nullptr && selectedSlot >= 0 && selectedSlot < (int) s->size() && (*s)[(std::size_t) selectedSlot].kind == EffectKind::vocoder;
  3126. }
  3127. bool EffectsPanel::tuneSelected() const
  3128. {
  3129. const auto* s = slots();
  3130. return s != nullptr && selectedSlot >= 0 && selectedSlot < (int) s->size() && (*s)[(std::size_t) selectedSlot].kind == EffectKind::lynxTune;
  3131. }
  3132. juce::Rectangle<int> EffectsPanel::tuneKeysBounds() const
  3133. {
  3134. return { 10, slotsTop + maxEffectSlots * slotHeight + 40, getWidth() - 20, 54 };
  3135. }
  3136. namespace
  3137. {
  3138. // LYNX Tune's keyboard strip: one octave, white keys in a row, black keys on top (C … B → key rectangles)
  3139. juce::Rectangle<float> tuneKeyRect (juce::Rectangle<float> area, int pc)
  3140. {
  3141. static constexpr int whiteIndex[12] { 0, -1, 1, -1, 2, 3, -1, 4, -1, 5, -1, 6 };
  3142. static constexpr float blackAt[12] { 0, 1.0f, 0, 2.0f, 0, 0, 4.0f, 0, 5.0f, 0, 6.0f, 0 };
  3143. const auto w = area.getWidth() / 7.0f;
  3144. if (whiteIndex[pc] >= 0)
  3145. return { area.getX() + whiteIndex[pc] * w, area.getY(), w, area.getHeight() };
  3146. return { area.getX() + blackAt[pc] * w - w * 0.3f, area.getY(), w * 0.6f, area.getHeight() * 0.58f };
  3147. }
  3148. int tuneKeyAt (juce::Rectangle<float> area, juce::Point<float> p)
  3149. {
  3150. for (int pc = 0; pc < 12; ++pc) // black keys first: they lie on top
  3151. if ((pc == 1 || pc == 3 || pc == 6 || pc == 8 || pc == 10) && tuneKeyRect (area, pc).contains (p))
  3152. return pc;
  3153. for (int pc = 0; pc < 12; ++pc)
  3154. if (tuneKeyRect (area, pc).contains (p))
  3155. return pc;
  3156. return -1;
  3157. }
  3158. } // namespace
  3159. void EffectsPanel::toggleTuneNote (juce::Point<int> p)
  3160. {
  3161. const auto pc = tuneKeyAt (tuneKeysBounds().toFloat(), p.toFloat());
  3162. if (pc < 0)
  3163. return;
  3164. engine.editSong ([t = track, slot = selectedSlot, pc] (Song& song) {
  3165. auto& v = song.mixer[(std::size_t) t].effects[(std::size_t) slot].params[(std::size_t) (lynxtune::noteC + pc)];
  3166. v = v >= 0.5f ? 0.0f : 1.0f;
  3167. });
  3168. }
  3169. juce::Rectangle<int> EffectsPanel::bandLevelsBounds() const
  3170. {
  3171. return { 10, slotsTop + maxEffectSlots * slotHeight + 40, getWidth() - 20, 70 };
  3172. }
  3173. namespace
  3174. {
  3175. // the Fruity Vocoder's state for the slot's current band count (levels kept while the count matches, as FL does)
  3176. fvocoder::State vocoderState (const EffectSlot& slot)
  3177. {
  3178. auto s = fvocoder::parse (slot.state).value_or (fvocoder::State());
  3179. const auto bands = 4 << std::clamp ((int) std::lround (slot.params[0] * 5.0f), 0, 5);
  3180. if (s.bands != bands)
  3181. {
  3182. s.bands = bands;
  3183. s.levels.fill (1.0f);
  3184. }
  3185. s.order = 1 + std::clamp ((int) std::lround (slot.params[1] * 2.0f), 0, 2);
  3186. s.listen = std::clamp ((int) std::lround (slot.params[2] * 2.0f), 0, 2);
  3187. s.swap = slot.params[3] > 0.5f;
  3188. for (int c = 0; c < fvocoder::controls; ++c)
  3189. s.c[(std::size_t) c] = fvocoder::rawFromKnob (slot.params[(std::size_t) (4 + c)], c, s.c[(std::size_t) c]);
  3190. return s;
  3191. }
  3192. constexpr float maxBandLevel = 2.0f; // the strip spans 0…2 (1 = unchanged)
  3193. } // namespace
  3194. void EffectsPanel::setBandLevel (juce::Point<int> p)
  3195. {
  3196. const auto* s = slots();
  3197. if (s == nullptr || ! vocoderSelected())
  3198. return;
  3199. const auto st = vocoderState ((*s)[(std::size_t) selectedSlot]);
  3200. const auto area = bandLevelsBounds();
  3201. const auto band = juce::jlimit (0, st.bands - 1, (int) ((p.x - area.getX()) * st.bands / juce::jmax (1, area.getWidth())));
  3202. auto level = juce::jlimit (0.0f, maxBandLevel, maxBandLevel * (float) (area.getBottom() - p.y) / (float) area.getHeight());
  3203. if (std::abs (level - 1.0f) < 0.04f)
  3204. level = 1.0f; // snaps to the unchanged level
  3205. engine.editSong ([t = track, slot = selectedSlot, band, level] (Song& song) {
  3206. auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) slot];
  3207. auto state = vocoderState (fx);
  3208. state.levels[(std::size_t) band] = level;
  3209. fx.state = fvocoder::serialise (state);
  3210. });
  3211. }
  3212. void EffectsPanel::showBandLevelMenu()
  3213. {
  3214. juce::PopupMenu menu;
  3215. auto apply = [this] (float (*level) (int, int)) {
  3216. engine.editSong ([t = track, slot = selectedSlot, level] (Song& song) {
  3217. auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) slot];
  3218. auto state = vocoderState (fx);
  3219. for (int k = 0; k < state.bands; ++k)
  3220. state.levels[(std::size_t) k] = level (k, state.bands);
  3221. fx.state = fvocoder::serialise (state);
  3222. });
  3223. };
  3224. menu.addItem (tr ("Reset band levels"), [apply] { apply ([] (int, int) { return 1.0f; }); });
  3225. menu.addItem (tr ("Brighter (tilt up)"), [apply] { apply ([] (int k, int n) { return 0.5f + (float) k / (float) std::max (1, n - 1); }); });
  3226. menu.addItem (tr ("Darker (tilt down)"), [apply] { apply ([] (int k, int n) { return 1.5f - (float) k / (float) std::max (1, n - 1); }); });
  3227. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  3228. }
  3229. void EffectsPanel::showGatePatterns()
  3230. {
  3231. // ready-made patterns (like Gross Beat's slots): value of step i of 32 (1/8 beat each)
  3232. struct Pattern
  3233. {
  3234. const char* name;
  3235. float (*level) (int);
  3236. };
  3237. static const Pattern patterns[] = {
  3238. { TR_NOOP ("All open"), [] (int) { return 1.0f; } },
  3239. { TR_NOOP ("1/2 beat gate"), [] (int i) { return (i % 4) < 2 ? 1.0f : 0.0f; } },
  3240. { TR_NOOP ("1 beat gate"), [] (int i) { return (i % 8) < 4 ? 1.0f : 0.0f; } },
  3241. { TR_NOOP ("Offbeat"), [] (int i) { return (i % 8) >= 4 ? 1.0f : 0.0f; } },
  3242. { TR_NOOP ("Sidechain (ramp per beat)"), [] (int i) { return std::min (1.0f, 0.15f + (float) (i % 8) / 5.0f); } },
  3243. { TR_NOOP ("Trance gate"), [] (int i) { return (i % 4) == 3 ? 0.0f : (i % 16) >= 12 ? 0.4f : 1.0f; } },
  3244. { TR_NOOP ("Fade-in over the bar"), [] (int i) { return (float) (i + 1) / 32.0f; } },
  3245. { TR_NOOP ("Fade-out over the bar"), [] (int i) { return 1.0f - (float) i / 32.0f; } },
  3246. };
  3247. juce::PopupMenu menu;
  3248. for (const auto& p : patterns)
  3249. menu.addItem (tr (p.name), [this, level = p.level] {
  3250. engine.editSong ([t = track, slot = selectedSlot, level] (Song& song) {
  3251. auto& params = song.mixer[(std::size_t) t].effects[(std::size_t) slot].params;
  3252. for (int i = 0; i < 32; ++i)
  3253. params[(std::size_t) i] = level (i);
  3254. });
  3255. });
  3256. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  3257. }
  3258. int EffectsPanel::knobAt (juce::Point<int> p) const
  3259. {
  3260. const auto* s = slots();
  3261. if (s == nullptr || selectedSlot < 0 || selectedSlot >= (int) s->size())
  3262. return -1;
  3263. if ((*s)[(std::size_t) selectedSlot].kind == EffectKind::parametricEq || (*s)[(std::size_t) selectedSlot].kind == EffectKind::facetEq)
  3264. return -1; // edited in its own window
  3265. const auto count = shownParams ((*s)[(std::size_t) selectedSlot]);
  3266. for (int i = gateSelected() ? 32 : 0; i < count; ++i)
  3267. if (knobBounds (i).contains (p))
  3268. return i;
  3269. return -1;
  3270. }
  3271. void EffectsPanel::paint (juce::Graphics& g)
  3272. {
  3273. const uitrace::Scope trace ("EffectsPanel paint", true, g.getClipBounds());
  3274. using namespace theme;
  3275. g.fillAll (colour::bg2);
  3276. g.setColour (colour::border);
  3277. g.drawVerticalLine (0, 0.0f, (float) getHeight());
  3278. const auto* s = slots();
  3279. if (s == nullptr)
  3280. return;
  3281. const auto& song = engine.getSong();
  3282. g.setColour (colour::textPrimary);
  3283. g.setFont (font (type::title, true));
  3284. textcache::drawText (g, tr ("Effects: {0}", { juce::String::fromUTF8 (song.mixer[(std::size_t) track].name.c_str()) }), 10, 4,
  3285. getWidth() - 70, panelHeader - 8, juce::Justification::centredLeft, true);
  3286. // input row: arm switch (inserts) and the audio input source with its level (the Master has one too, as in FL;
  3287. // REA round 143)
  3288. if (track >= 0 && track < (int) song.mixer.size())
  3289. {
  3290. const auto& mt = song.mixer[(std::size_t) track];
  3291. if (track > 0)
  3292. {
  3293. const auto armed = engine.isInsertArmed (track);
  3294. const auto a = armBounds().toFloat();
  3295. theme::fillRoundRect (g, a, radius::sm, armed ? colour::record.withAlpha (0.25f) : hoverInput == 1 ? colour::bg5 : colour::bg3);
  3296. const auto dot = a.withSizeKeepingCentre (11.0f, 11.0f);
  3297. g.setColour (armed ? colour::record : colour::bg0);
  3298. g.fillEllipse (dot);
  3299. g.setColour (armed ? colour::record.brighter (0.3f) : hoverInput == 1 ? colour::textSecondary : colour::borderStrong);
  3300. g.drawEllipse (dot, 1.0f);
  3301. if (mt.recordSafe)
  3302. {
  3303. g.setColour (colour::textDisabled);
  3304. g.drawLine (dot.getX() + 1.0f, dot.getBottom() - 1.0f, dot.getRight() - 1.0f, dot.getY() + 1.0f, 1.2f);
  3305. }
  3306. }
  3307. auto box = inputBoxBounds().toFloat();
  3308. theme::fillRoundRect (g, box, radius::sm, hoverInput == 2 ? colour::bg4 : colour::bg3);
  3309. g.setColour (hoverInput == 2 ? colour::borderStrong : colour::border);
  3310. g.drawRoundedRectangle (box.reduced (0.5f), radius::sm, 1.0f);
  3311. // the level, as a thin bar along the bottom of the box (left over right)
  3312. if (mt.inputChannel >= 0)
  3313. {
  3314. const auto bar = box.reduced (4.0f, 0.0f).withTop (box.getBottom() - 5.0f).withHeight (3.0f);
  3315. g.setColour (colour::bg0);
  3316. g.fillRect (bar);
  3317. for (int side = 0; side < 2; ++side)
  3318. {
  3319. const auto db = juce::Decibels::gainToDecibels (inputLevel[(std::size_t) side], -60.0f);
  3320. const auto fill = juce::jlimit (0.0f, 1.0f, (db + 60.0f) / 60.0f);
  3321. g.setColour (inputLevel[(std::size_t) side] >= 0.99f ? colour::record : colour::meterLow);
  3322. g.fillRect (bar.withHeight (1.5f).translated (0.0f, side * 1.5f).withWidth (bar.getWidth() * fill));
  3323. }
  3324. }
  3325. icons::draw (g, Icon::mic, box.withWidth (18.0f).reduced (2.0f).translated (3.0f, -1.0f), mt.inputChannel >= 0 ? colour::textPrimary : colour::textDisabled);
  3326. const auto names = engine.getInputChannelNames();
  3327. const auto label = mt.inputChannel >= 0 ? juce::String::fromUTF8 (inputSourceName (mt.inputChannel, mt.inputStereo, names).c_str())
  3328. : tr ("No audio input");
  3329. g.setColour (mt.inputChannel >= 0 ? colour::textPrimary : colour::textSecondary);
  3330. g.setFont (font (type::body));
  3331. textcache::drawText (g, label, box.withTrimmedLeft (24.0f).withTrimmedRight (18.0f).translated (0.0f, -1.0f).toNearestInt(), juce::Justification::centredLeft, true);
  3332. icons::draw (g, Icon::chevronDown, box.removeFromRight (18.0f).reduced (4.0f).translated (-2.0f, -1.0f), colour::textSecondary);
  3333. }
  3334. // the insert's effects switch
  3335. if (! s->empty())
  3336. {
  3337. const auto on = mixerops::anyEffectEnabled (song, track);
  3338. const auto r = fxSwitchBounds().toFloat();
  3339. theme::fillRoundRect (g, r, radius::sm, on ? colour::bg5 : colour::bg0);
  3340. g.setColour (muteLed (! on));
  3341. g.fillEllipse (r.withWidth (r.getHeight()).reduced (6.0f).translated (3.0f, 0.0f));
  3342. g.setColour (on ? colour::textPrimary : colour::textDisabled);
  3343. g.setFont (font (type::caption, true));
  3344. textcache::drawText (g, "FX", r.withTrimmedLeft (r.getHeight()).toNearestInt(), juce::Justification::centredLeft);
  3345. }
  3346. g.setFont (font (type::body));
  3347. // the 10 slots, as FL draws them: options arrow, name ("Slot N" when empty), mix knob, LED
  3348. // (rows: FL's slot places, an effect may sit below empty slots, round 170b)
  3349. for (int row = 0; row < maxEffectSlots; ++row)
  3350. {
  3351. const auto i = effectIn (row); // the effect shown here, -1 = empty
  3352. const auto r = slotBounds (row);
  3353. const auto filled = i >= 0;
  3354. const auto isSelected = i == selectedSlot && filled;
  3355. const auto slotHovered = row == hoverSlot && dragSlot < 0;
  3356. theme::fillRoundRect (g, r.toFloat(), radius::sm, isSelected ? colour::bg5 : filled ? (slotHovered ? colour::bg4 : colour::bg3) : (slotHovered ? colour::bg3 : colour::bg2.brighter (0.03f)));
  3357. g.setColour (slotHovered ? colour::borderStrong : colour::border);
  3358. g.drawRoundedRectangle (r.toFloat().reduced (0.5f), radius::sm, 1.0f);
  3359. if (isSelected)
  3360. {
  3361. theme::fillRoundRect (g, r.toFloat().withWidth (3.0f).reduced (0.0f, 3.0f), 1.5f, colour::accent);
  3362. }
  3363. {
  3364. const auto a = arrowBounds (row).toFloat().withSizeKeepingCentre (5.0f, 8.0f).translated (1.0f, 0.0f);
  3365. juce::Path tri;
  3366. tri.addTriangle (a.getX(), a.getY(), a.getRight(), a.getCentreY(), a.getX(), a.getBottom());
  3367. g.setColour (slotHovered && hoverArrow ? colour::textPrimary : colour::textSecondary.withAlpha (filled ? 1.0f : 0.6f));
  3368. g.fillPath (tri);
  3369. }
  3370. const auto ledArea = ledBounds (row).toFloat().withSizeKeepingCentre (8.0f, 8.0f);
  3371. const auto textArea = r.withTrimmedLeft (20).withTrimmedRight (46);
  3372. if (filled)
  3373. {
  3374. const auto& slot = (*s)[(std::size_t) i];
  3375. g.setColour (muteLed (! slot.enabled));
  3376. g.fillEllipse (ledArea);
  3377. if (slotHovered && hoverLed)
  3378. {
  3379. g.setColour (colour::textSecondary);
  3380. g.drawEllipse (ledArea.expanded (2.0f), 1.0f);
  3381. }
  3382. g.setColour (slot.enabled ? colour::textPrimary : colour::textDisabled);
  3383. // a LYNX substitute shows the plugin it stands in for, with a "LYNX" badge
  3384. const auto substitute = slot.isSubstitute();
  3385. auto name = quickpick::slotName (engine, slot); // (a plugin renamed in the Plugin database: its new name, round 165c)
  3386. if (slot.sidechain > 0 && slot.sidechain < (int) engine.getSong().mixer.size())
  3387. name << juce::String::fromUTF8 (" \xe2\x86\x90 ") << juce::String::fromUTF8 (engine.getSong().mixer[(std::size_t) slot.sidechain].name.c_str());
  3388. auto text = textArea;
  3389. if (substitute)
  3390. {
  3391. const auto badge = text.removeFromRight (34).withSizeKeepingCentre (32, 14).toFloat();
  3392. const auto playing = engine.getSong().slotActive (slot); // off while the project's substitutes are bypassed
  3393. theme::fillRoundRect (g, badge, 3.0f, colour::info.withAlpha (playing ? 0.25f : 0.12f));
  3394. g.setColour (playing ? colour::info : colour::textDisabled);
  3395. const auto keep = g.getCurrentFont();
  3396. g.setFont (font (type::caption, true));
  3397. textcache::drawText (g, "LYNX", badge, juce::Justification::centred);
  3398. g.setFont (keep);
  3399. g.setColour (slot.enabled ? colour::textPrimary : colour::textDisabled);
  3400. }
  3401. textcache::drawText (g, name, text, juce::Justification::centredLeft);
  3402. // slot's dry/wet knob
  3403. const auto mixActive = (hoverParam == mixParam && hoverSlot == row) || (dragParam == mixParam && selectedSlot == i);
  3404. drawKnob (g, mixBounds (row).toFloat().withSizeKeepingCentre (18.0f, 18.0f), slot.mix, false,
  3405. slot.enabled ? (dragParam == mixParam && selectedSlot == i ? colour::accent : colour::info) : colour::textDisabled, mixActive);
  3406. }
  3407. else
  3408. {
  3409. // an empty slot keeps its controls in place (dimmed), as FL shows them
  3410. g.setColour (muteLed (false).withAlpha (0.3f));
  3411. g.fillEllipse (ledArea);
  3412. drawKnob (g, mixBounds (row).toFloat().withSizeKeepingCentre (18.0f, 18.0f), 1.0f, false, colour::textDisabled.withAlpha (0.5f), false);
  3413. g.setColour (slotHovered ? colour::textSecondary : colour::textDisabled);
  3414. g.setFont (juce::Font (font (type::body)).italicised());
  3415. textcache::drawText (g, tr ("Slot {0}", { juce::String (row + 1) }), textArea, juce::Justification::centredLeft);
  3416. g.setFont (font (type::body));
  3417. }
  3418. }
  3419. paintEq (g);
  3420. g.reduceClipRegion (0, 0, getWidth(), bottomTop() - 6); // the selected effect's knobs stay above the EQ
  3421. if (dragSlot >= 0 && dropSlot >= 0 && dropSlot != rowOf (dragSlot)) // where the dragged slot lands (FL: swaps with
  3422. { // the effect there, or takes the empty slot)
  3423. g.setColour (colour::accent);
  3424. g.drawRoundedRectangle (slotBounds (dropSlot).toFloat().reduced (0.5f), radius::sm, 2.0f);
  3425. }
  3426. if (selectedSlot < 0 || selectedSlot >= (int) s->size())
  3427. return;
  3428. const auto& slot = (*s)[(std::size_t) selectedSlot];
  3429. auto drawButton = [&g] (juce::Rectangle<int> button, const juce::String& text, Icon icon) {
  3430. theme::fillRoundRect (g, button.toFloat(), radius::md, colour::bg4);
  3431. const auto f = juce::Font (font (type::body));
  3432. const auto textWidth = juce::GlyphArrangement::getStringWidth (f, text);
  3433. auto content = button.toFloat().withSizeKeepingCentre (juce::jmin ((float) button.getWidth() - 12.0f, textWidth + 22.0f), (float) button.getHeight());
  3434. icons::draw (g, icon, content.removeFromLeft (16.0f).withSizeKeepingCentre (16.0f, 16.0f), colour::textSecondary);
  3435. content.removeFromLeft (6.0f);
  3436. g.setColour (colour::textPrimary);
  3437. g.setFont (f);
  3438. textcache::drawFittedText (g, text, content.toNearestInt(), juce::Justification::centredLeft, 1, 0.85f);
  3439. };
  3440. if (slot.kind == EffectKind::plugin)
  3441. {
  3442. const auto button = pluginButtonBounds();
  3443. drawButton (button, tr ("Open plugin interface"), Icon::plugin);
  3444. g.setColour (colour::textSecondary);
  3445. g.setFont (font (type::caption));
  3446. textcache::drawText (g, quickpick::slotName (engine, slot), button.translated (0, 34), juce::Justification::centred);
  3447. return;
  3448. }
  3449. if (slot.kind == EffectKind::parametricEq)
  3450. {
  3451. const auto button = pluginButtonBounds();
  3452. drawButton (button, tr ("Open parametric EQ"), Icon::settings);
  3453. const auto curve = juce::Rectangle<int> (button.getX(), button.getBottom() + 10, button.getWidth(), 120).toFloat();
  3454. drawParametricEqCurve (g, curve, slot.params, juce::jmax (8000.0, engine.getTransport().sampleRate.load()), slot.enabled);
  3455. return;
  3456. }
  3457. if (isSoundgoodizerApprox (slot)) // approximated without FL's preset files: its page edits Preset and Amount
  3458. {
  3459. const auto button = pluginButtonBounds();
  3460. drawButton (button, tr ("Open Soundgoodizer"), Icon::settings);
  3461. g.setColour (colour::textSecondary);
  3462. g.setFont (font (type::caption));
  3463. textcache::drawFittedText (g, tr ("Approximation (FL Studio's Soundgoodizer presets were not found on this computer)"),
  3464. button.translated (0, 34).withHeight (40), juce::Justification::centredTop, 2);
  3465. return;
  3466. }
  3467. if (slot.kind == EffectKind::facetEq)
  3468. {
  3469. const auto button = pluginButtonBounds();
  3470. drawButton (button, tr ("Open Facet EQ"), Icon::settings);
  3471. const auto curve = juce::Rectangle<int> (button.getX(), button.getBottom() + 10, button.getWidth(), 120).toFloat();
  3472. drawFacetEqCurve (g, curve, slot.params, juce::jmax (8000.0, engine.getTransport().sampleRate.load()), slot.enabled);
  3473. return;
  3474. }
  3475. if (slot.kind == EffectKind::parallel) // container: list the branches
  3476. {
  3477. auto y = knobBounds (0).getY() - 28;
  3478. g.setColour (colour::textPrimary);
  3479. g.setFont (font (type::title, true));
  3480. textcache::drawText (g, juce::String::fromUTF8 (effectInfo (slot.kind).name), 10, y, getWidth() - 20, 20, juce::Justification::centredLeft);
  3481. g.setFont (font (type::small));
  3482. for (std::size_t b = 0; b < slot.branches.size(); ++b)
  3483. {
  3484. y += 22;
  3485. juce::String chain;
  3486. if (slot.branches[b].chain.empty())
  3487. chain = tr ("dry");
  3488. for (std::size_t c = 0; c < slot.branches[b].chain.size(); ++c)
  3489. chain += (c > 0 ? " -> " : "") + juce::String::fromUTF8 (effectInfo (slot.branches[b].chain[c].kind).name);
  3490. const auto line = tr ("Branch {0} (x{1}): {2}", { juce::String ((int) b + 1), juce::String (slot.branches[b].gain, 2), chain });
  3491. g.setColour (colour::textSecondary);
  3492. textcache::drawText (g, line, 14, y, getWidth() - 28, 20, juce::Justification::centredLeft, true);
  3493. }
  3494. return;
  3495. }
  3496. const auto& info = effectInfo (slot.kind);
  3497. const auto gate = slot.kind == EffectKind::volumeGate;
  3498. const auto vocoder = slot.kind == EffectKind::vocoder;
  3499. g.setColour (colour::textPrimary);
  3500. g.setFont (font (type::title, true));
  3501. const auto tune = slot.kind == EffectKind::lynxTune;
  3502. const auto editorButton = ! gate && ! vocoder && NativeEffectWindows::canOpen (slot.kind);
  3503. const auto titleY = (gate ? gateStepsBounds().getY() : vocoder ? bandLevelsBounds().getY() : tune ? tuneKeysBounds().getY() : knobBounds (0).getY()) - 28;
  3504. const auto titleRight = getWidth() - 10 - (editorButton ? editorButtonBounds().getWidth() + 6 : 0);
  3505. textcache::drawText (g, juce::String::fromUTF8 (info.name), 10, titleY, titleRight - 10, 20, juce::Justification::centredLeft, true);
  3506. if (slot.isSubstitute()) // which missing plugin this stands in for (the project keeps it)
  3507. {
  3508. const auto titleWidth = juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), juce::String::fromUTF8 (info.name));
  3509. g.setColour (colour::info);
  3510. g.setFont (font (type::caption));
  3511. const auto original = juce::String::fromUTF8 (substituteOriginalName (slot).c_str());
  3512. textcache::drawText (g, engine.getSong().substitutesBypassed ? tr ("LYNX SHARE substitute for {0} (bypassed)", { original }) : tr ("LYNX SHARE substitute for {0}", { original }),
  3513. 10 + titleWidth + 10, titleY,
  3514. juce::jmax (0, titleRight - 20 - titleWidth), 20, juce::Justification::centredLeft, true);
  3515. }
  3516. if (editorButton) // the effect's own window (FL's plugin window)
  3517. {
  3518. const auto b = editorButtonBounds().toFloat();
  3519. const auto hover = getMouseXYRelative().toFloat();
  3520. theme::fillRoundRect (g, b, radius::md, b.contains (hover) ? colour::bg5 : colour::bg4);
  3521. icons::draw (g, Icon::plugin, b.withWidth (22.0f).withSizeKeepingCentre (13.0f, 13.0f).translated (4.0f, 0.0f), colour::textSecondary);
  3522. g.setColour (colour::textPrimary);
  3523. g.setFont (font (type::small));
  3524. textcache::drawFittedText (g, tr ("Editor"), b.withTrimmedLeft (24.0f).toNearestInt(), juce::Justification::centredLeft, 1, 0.8f);
  3525. }
  3526. if (tune) // the scale's notes on one octave; a note switched off is never a target
  3527. {
  3528. const auto area = tuneKeysBounds().toFloat();
  3529. const auto scaleMask = vocal::scaleMask ((vocal::Scale) lynxtune::scaleIndex (slot.params[lynxtune::scale]), lynxtune::keyIndex (slot.params[lynxtune::key]), 0xfff);
  3530. const auto custom = lynxtune::scaleIndex (slot.params[lynxtune::scale]) == (int) vocal::Scale::custom;
  3531. for (const auto black : { false, true })
  3532. for (int pc = 0; pc < 12; ++pc)
  3533. {
  3534. const auto isBlack = pc == 1 || pc == 3 || pc == 6 || pc == 8 || pc == 10;
  3535. if (isBlack != black)
  3536. continue;
  3537. const auto r = tuneKeyRect (area, pc).reduced (1.0f);
  3538. const auto on = slot.params[(std::size_t) (lynxtune::noteC + pc)] >= 0.5f;
  3539. const auto inScale = custom || (scaleMask & (1u << pc)) != 0;
  3540. auto fill = isBlack ? colour::bg0 : colour::bg2;
  3541. if (inScale && on)
  3542. fill = (slot.enabled ? colour::accent : colour::textDisabled).withAlpha (isBlack ? 0.85f : 0.65f);
  3543. theme::fillRoundRect (g, r, 2.0f, fill);
  3544. g.setColour (colour::gridBar);
  3545. g.drawRoundedRectangle (r, 2.0f, 1.0f);
  3546. if (inScale && ! on) // in the scale but switched off
  3547. {
  3548. g.setColour (colour::textSecondary);
  3549. g.drawLine (r.getX() + 3.0f, r.getBottom() - 3.0f, r.getRight() - 3.0f, r.getBottom() - 14.0f, 1.2f);
  3550. }
  3551. if (! isBlack)
  3552. {
  3553. static const char* names[12] { "C", "", "D", "", "E", "F", "", "G", "", "A", "", "B" };
  3554. g.setColour (inScale && on ? colour::textPrimary : colour::textSecondary);
  3555. g.setFont (font (type::caption));
  3556. textcache::drawText (g, names[pc], r.withTrimmedTop (r.getHeight() - 16.0f), juce::Justification::centred);
  3557. }
  3558. }
  3559. g.setColour (colour::textSecondary);
  3560. g.setFont (font (type::caption));
  3561. textcache::drawFittedText (g, tr ("Target notes: click a key to switch it off or on"), tuneKeysBounds().withY (tuneKeysBounds().getBottom() + 2).withHeight (14),
  3562. juce::Justification::centredLeft, 1, 0.8f);
  3563. }
  3564. if (vocoder) // the analysis bands' levels, low to high (FL's band level strip)
  3565. {
  3566. const auto st = vocoderState (slot);
  3567. const auto area = bandLevelsBounds().toFloat();
  3568. theme::fillRoundRect (g, area, radius::sm, colour::bg0);
  3569. const auto w = area.getWidth() / (float) st.bands;
  3570. const auto unity = area.getBottom() - area.getHeight() / maxBandLevel;
  3571. for (int k = 0; k < st.bands; ++k)
  3572. {
  3573. const auto h = area.getHeight() * juce::jlimit (0.0f, 1.0f, st.levels[(std::size_t) k] / maxBandLevel);
  3574. g.setColour ((slot.enabled ? colour::accent : colour::textDisabled).withAlpha (k % 2 == 0 ? 1.0f : 0.8f));
  3575. g.fillRect (area.getX() + (float) k * w + (w > 4.0f ? 1.0f : 0.0f), area.getBottom() - h, juce::jmax (1.0f, w - (w > 4.0f ? 2.0f : 0.0f)), h);
  3576. }
  3577. g.setColour (colour::gridBar);
  3578. g.drawHorizontalLine ((int) unity, area.getX(), area.getRight());
  3579. g.setColour (colour::textSecondary);
  3580. g.setFont (font (type::caption));
  3581. textcache::drawFittedText (g, tr ("Band levels: draw them; right-click = presets"), area.withY (area.getBottom() + 2).withHeight (14).toNearestInt(),
  3582. juce::Justification::centredLeft, 1, 0.8f);
  3583. }
  3584. if (gate) // 32 steps = 1 bar of 4 beats
  3585. {
  3586. const auto area = gateStepsBounds().toFloat();
  3587. theme::fillRoundRect (g, area, radius::sm, colour::bg0);
  3588. const auto w = area.getWidth() / 32.0f;
  3589. for (int i = 0; i < 32; ++i)
  3590. {
  3591. const auto h = area.getHeight() * juce::jlimit (0.0f, 1.0f, slot.params[(std::size_t) i]);
  3592. g.setColour ((slot.enabled ? colour::accent : colour::textDisabled).withAlpha ((i / 8) % 2 == 0 ? 1.0f : 0.7f));
  3593. g.fillRect (area.getX() + i * w + 1.0f, area.getBottom() - h, w - 2.0f, h);
  3594. }
  3595. g.setColour (colour::gridBar);
  3596. for (int beat = 1; beat < 4; ++beat)
  3597. g.drawVerticalLine ((int) (area.getX() + beat * 8 * w), area.getY(), area.getBottom());
  3598. g.setColour (colour::textSecondary);
  3599. g.setFont (font (type::caption));
  3600. textcache::drawFittedText (g, tr ("1 bar: draw the steps; right-click = patterns"), area.withY (area.getBottom() + 2).withHeight (14).toNearestInt(),
  3601. juce::Justification::centredLeft, 1, 0.8f);
  3602. }
  3603. for (int p = gate ? 32 : 0; p < shownParams (slot); ++p)
  3604. {
  3605. const auto r = knobBounds (p);
  3606. const auto value = slot.params[(std::size_t) p];
  3607. // 38 px knob; in tight grids (Effector) it shrinks to fit name and value below
  3608. const auto knobHeight = juce::jlimit (30, 44, r.getHeight() - 30);
  3609. drawKnob (g, r.withHeight (knobHeight).toFloat(), value, false, slot.enabled ? colour::knobArc : colour::textDisabled,
  3610. dragParam == p || (hoverParam == p && hoverSlot < 0));
  3611. g.setColour (colour::textSecondary);
  3612. g.setFont (font (type::caption));
  3613. textcache::drawFittedText (g, juce::String::fromUTF8 (info.params[(std::size_t) p].name), r.getX(), r.getY() + knobHeight + 2, r.getWidth(), 14,
  3614. juce::Justification::centred, 1, 0.8f);
  3615. g.setColour (colour::textPrimary);
  3616. textcache::drawText (g, juce::String::fromUTF8 (formatEffectParam (slot.kind, p, value, song.bpm, slot.params).c_str()), r.getX(), r.getY() + knobHeight + 16,
  3617. r.getWidth(), 14, juce::Justification::centred);
  3618. }
  3619. }
  3620. void EffectsPanel::mouseDown (const juce::MouseEvent& e)
  3621. {
  3622. const auto* s = slots();
  3623. if (s == nullptr)
  3624. return;
  3625. if (eqFoldBounds().contains (e.getPosition()) && e.mods.isLeftButtonDown())
  3626. {
  3627. eqFoldChoice = eqFolded ? 1 : 2;
  3628. refit();
  3629. repaint();
  3630. return;
  3631. }
  3632. // the built-in EQ and the output target (bottom section)
  3633. if (outputBounds().contains (e.getPosition()))
  3634. {
  3635. showOutputMenu();
  3636. return;
  3637. }
  3638. if (const auto eqControl = eqControlAt (e.getPosition()); eqControl != 0)
  3639. {
  3640. if (isEqPoint (eqControl))
  3641. {
  3642. dragParam = eqControl;
  3643. setEqFromGraph (eqPointBase - eqControl, e.getPosition());
  3644. return;
  3645. }
  3646. if (flmods::popup (e.mods))
  3647. ui::showValueMenu (*this, &engine, specFor (eqControl, -1), valueOf (eqControl, -1), [this, eqControl] (double v) { setValue (eqControl, -1, v); });
  3648. else if (ui::isResetClick (e))
  3649. setValue (eqControl, -1, specFor (eqControl, -1).defaultValue);
  3650. else
  3651. {
  3652. dragParam = eqControl;
  3653. drag.begin (e, valueOf (eqControl, -1));
  3654. showTip (eqControl, -1, false);
  3655. }
  3656. return;
  3657. }
  3658. if (track > 0 && armBounds().contains (e.getPosition()))
  3659. {
  3660. if (flmods::popup (e.mods)) // FL: "Record <insert> to" (round 167a)
  3661. mixerinput::chooseRecordTo (engine, track);
  3662. else
  3663. mixerinput::toggleArm (engine, track, this);
  3664. repaint();
  3665. return;
  3666. }
  3667. if (track >= 0 && inputBoxBounds().contains (e.getPosition()))
  3668. {
  3669. mixerinput::showMenu (engine, track, this);
  3670. return;
  3671. }
  3672. if (! s->empty() && fxSwitchBounds().contains (e.getPosition()))
  3673. {
  3674. if (flmods::popup (e.mods))
  3675. toggleAllWindows();
  3676. else
  3677. {
  3678. const auto on = ! mixerops::anyEffectEnabled (engine.getSong(), track);
  3679. engine.editSong ([t = track, on] (Song& song) { mixerops::setAllEffectsEnabled (song, t, on); });
  3680. }
  3681. return;
  3682. }
  3683. for (int row = 0; row < maxEffectSlots; ++row)
  3684. {
  3685. const auto r = slotBounds (row);
  3686. if (! r.contains (e.getPosition()))
  3687. continue;
  3688. const auto i = effectIn (row);
  3689. if (i < 0)
  3690. {
  3691. showAddMenu (row); // (FL: the plugin lands in this slot)
  3692. return;
  3693. }
  3694. if (arrowBounds (row).contains (e.getPosition())) // FL's slot options arrow
  3695. {
  3696. selectedSlot = i;
  3697. repaint();
  3698. showSlotMenu (i);
  3699. return;
  3700. }
  3701. selectedSlot = i;
  3702. repaint();
  3703. if (mixBounds (row).contains (e.getPosition()))
  3704. {
  3705. if (flmods::popup (e.mods))
  3706. ui::showValueMenu (*this, &engine, specFor (mixParam, i), valueOf (mixParam, i), [this, i] (double v) { setValue (mixParam, i, v); });
  3707. else if (ui::isResetClick (e))
  3708. {
  3709. setValue (mixParam, i, 1.0);
  3710. showTip (mixParam, i, true);
  3711. }
  3712. else
  3713. {
  3714. dragParam = mixParam;
  3715. dragStart = (*s)[(std::size_t) i].mix;
  3716. drag.begin (e, dragStart);
  3717. showTip (mixParam, i, false);
  3718. }
  3719. return;
  3720. }
  3721. if (flmods::popup (e.mods) || (e.mods.isShiftDown() && ! ledBounds (row).contains (e.getPosition()))) // (FL: Shift+click = the menu)
  3722. showSlotMenu (i);
  3723. else if (ledBounds (row).contains (e.getPosition())) // LED: bypass
  3724. engine.editSong ([t = track, i] (Song& song) {
  3725. auto& slot = song.mixer[(std::size_t) t].effects[(std::size_t) i];
  3726. slot.enabled = ! slot.enabled;
  3727. });
  3728. else
  3729. dragSlot = i; // dragging the name moves the effect to another slot (a click shows its window)
  3730. return;
  3731. }
  3732. if (selectedSlot >= 0 && selectedSlot < (int) s->size() && (*s)[(std::size_t) selectedSlot].kind == EffectKind::plugin
  3733. && pluginButtonBounds().contains (e.getPosition()))
  3734. {
  3735. openPluginWindow (selectedSlot);
  3736. return;
  3737. }
  3738. if (selectedSlot >= 0 && selectedSlot < (int) s->size() && (*s)[(std::size_t) selectedSlot].kind == EffectKind::parametricEq
  3739. && pluginButtonBounds().withHeight (170).contains (e.getPosition()))
  3740. {
  3741. ParametricEqWindows::open (engine, track, selectedSlot);
  3742. return;
  3743. }
  3744. if (selectedSlot >= 0 && selectedSlot < (int) s->size() && isSoundgoodizerApprox ((*s)[(std::size_t) selectedSlot])
  3745. && pluginButtonBounds().contains (e.getPosition()))
  3746. {
  3747. NativeEffectWindows::open (engine, track, selectedSlot);
  3748. return;
  3749. }
  3750. if (selectedSlot >= 0 && selectedSlot < (int) s->size() && (*s)[(std::size_t) selectedSlot].kind == EffectKind::facetEq
  3751. && pluginButtonBounds().withHeight (170).contains (e.getPosition()))
  3752. {
  3753. FacetEqWindows::open (engine, track, selectedSlot);
  3754. return;
  3755. }
  3756. if (selectedSlot >= 0 && selectedSlot < (int) s->size() && (*s)[(std::size_t) selectedSlot].kind != EffectKind::volumeGate
  3757. && ! vocoderSelected() && NativeEffectWindows::canOpen ((*s)[(std::size_t) selectedSlot].kind)
  3758. && editorButtonBounds().contains (e.getPosition()))
  3759. {
  3760. openEditor (selectedSlot);
  3761. return;
  3762. }
  3763. if (vocoderSelected() && bandLevelsBounds().contains (e.getPosition()))
  3764. {
  3765. if (flmods::popup (e.mods))
  3766. showBandLevelMenu();
  3767. else
  3768. {
  3769. dragParam = bandLevelParam;
  3770. setBandLevel (e.getPosition());
  3771. }
  3772. return;
  3773. }
  3774. if (tuneSelected() && tuneKeysBounds().contains (e.getPosition()))
  3775. {
  3776. toggleTuneNote (e.getPosition());
  3777. return;
  3778. }
  3779. if (gateSelected() && gateStepsBounds().contains (e.getPosition()))
  3780. {
  3781. if (flmods::popup (e.mods))
  3782. showGatePatterns();
  3783. else
  3784. {
  3785. dragParam = gateStepParam;
  3786. setGateStep (e.getPosition());
  3787. }
  3788. return;
  3789. }
  3790. dragParam = knobAt (e.getPosition());
  3791. if (dragParam >= 0 && flmods::popup (e.mods))
  3792. {
  3793. const auto p = dragParam;
  3794. ui::showValueMenu (*this, &engine, specFor (p, selectedSlot), valueOf (p, selectedSlot),
  3795. [this, p, slot = selectedSlot] (double v) { setValue (p, slot, v); });
  3796. dragParam = -1;
  3797. return;
  3798. }
  3799. if (dragParam >= 0 && ui::isResetClick (e))
  3800. {
  3801. setValue (dragParam, selectedSlot, specFor (dragParam, selectedSlot).defaultValue);
  3802. showTip (dragParam, selectedSlot, true);
  3803. dragParam = -1;
  3804. return;
  3805. }
  3806. if (dragParam >= 0)
  3807. {
  3808. dragStart = (*s)[(std::size_t) selectedSlot].params[(std::size_t) dragParam];
  3809. drag.begin (e, dragStart);
  3810. showTip (dragParam, selectedSlot, false);
  3811. }
  3812. }
  3813. ui::ValueSpec EffectsPanel::specFor (int param, int slot) const
  3814. {
  3815. const auto& song = engine.getSong();
  3816. ui::ValueSpec spec;
  3817. spec.pixelsForRange = 150.0;
  3818. if (isEqParam (param)) // the built-in EQ (stored 0..1 here: gain ±18 dB, frequency 10 Hz..16 kHz log, width)
  3819. {
  3820. const auto band = (eqParamBase - param) / 3, what = (eqParamBase - param) % 3;
  3821. const juce::String whatName = what == 0 ? tr ("level") : what == 1 ? tr ("frequency") : tr ("width");
  3822. spec.name = juce::String::fromUTF8 (song.mixer[(std::size_t) track].name.c_str()) + " - " + tr ("EQ band {0} ({1})", { juce::String (band + 1), tr (eqBandNames[band]) })
  3823. + " " + whatName;
  3824. TrackEq defaults;
  3825. spec.defaultValue = eqToValue (defaults, band, what);
  3826. spec.toText = [band, what] (double v) {
  3827. TrackEq eq;
  3828. eqFromValue (eq, band, what, (float) v);
  3829. const auto b = (std::size_t) band;
  3830. return what == 0 ? juce::String (eq.gainDb[b], 1) + " dB"
  3831. : what == 1 ? (eq.hz[b] >= 1000.0f ? juce::String (eq.hz[b] / 1000.0f, 2) + " kHz" : juce::String ((int) eq.hz[b]) + " Hz")
  3832. : juce::String (eq.width[b], 2);
  3833. };
  3834. spec.fromText = ui::inverseOf (spec.toText, 0.0, 1.0);
  3835. return spec;
  3836. }
  3837. if (const auto* s = slots(); s == nullptr || slot < 0 || slot >= (int) s->size())
  3838. return spec;
  3839. const auto& fx = (*slots())[(std::size_t) slot];
  3840. const auto& info = effectInfo (fx.kind);
  3841. const auto trackName = juce::String::fromUTF8 (song.mixer[(std::size_t) track].name.c_str());
  3842. if (param == mixParam)
  3843. {
  3844. spec = ui::percentSpec (trackName + " - " + utf8 (info.name) + " - " + tr ("Mix"), 1.0);
  3845. spec.target = AutomationTarget { AutomationTargetKind::effectMix, track, slot };
  3846. return spec;
  3847. }
  3848. if (param < 0 || param >= (int) info.params.size())
  3849. return spec;
  3850. spec.name = trackName + " - " + utf8 (info.name) + " - " + utf8 (info.params[(std::size_t) param].name);
  3851. spec.defaultValue = info.params[(std::size_t) param].defaultValue;
  3852. spec.toText = [kind = fx.kind, param, bpm = song.bpm, context = fx.params] (double v) { return utf8 (formatEffectParam (kind, param, (float) v, bpm, context).c_str()); };
  3853. spec.fromText = ui::inverseOf (spec.toText, 0.0, 1.0);
  3854. spec.target = AutomationTarget { AutomationTargetKind::effectParam, track, slot, param };
  3855. return spec;
  3856. }
  3857. double EffectsPanel::valueOf (int param, int slot) const
  3858. {
  3859. if (isEqParam (param))
  3860. return track >= 0 && track < (int) engine.getSong().mixer.size()
  3861. ? eqToValue (engine.getSong().mixer[(std::size_t) track].eq, (eqParamBase - param) / 3, (eqParamBase - param) % 3)
  3862. : 0.0;
  3863. const auto* s = slots();
  3864. if (s == nullptr || slot < 0 || slot >= (int) s->size())
  3865. return 0.0;
  3866. const auto& fx = (*s)[(std::size_t) slot];
  3867. return param == mixParam ? fx.mix : (param >= 0 && param < (int) fx.params.size() ? fx.params[(std::size_t) param] : 0.0f);
  3868. }
  3869. void EffectsPanel::setValue (int param, int slot, double value)
  3870. {
  3871. if (isEqParam (param))
  3872. {
  3873. engine.editSong ([t = track, band = (eqParamBase - param) / 3, what = (eqParamBase - param) % 3, v = (float) value] (Song& song) {
  3874. if (t < (int) song.mixer.size())
  3875. eqFromValue (song.mixer[(std::size_t) t].eq, band, what, v);
  3876. });
  3877. return;
  3878. }
  3879. const auto* s = slots();
  3880. if (s == nullptr || slot < 0 || slot >= (int) s->size())
  3881. return;
  3882. if (param == mixParam)
  3883. engine.editSong ([t = track, slot, v = (float) value] (Song& song) { song.mixer[(std::size_t) t].effects[(std::size_t) slot].mix = v; });
  3884. else if (param >= 0)
  3885. engine.editSong ([t = track, slot, param, v = (float) value] (Song& song) {
  3886. song.mixer[(std::size_t) t].effects[(std::size_t) slot].params[(std::size_t) param] = v;
  3887. });
  3888. }
  3889. int EffectsPanel::mixKnobAt (juce::Point<int> p) const
  3890. {
  3891. for (int i = 0; slots() != nullptr && i < (int) slots()->size(); ++i)
  3892. if (mixBounds (rowOf (i)).contains (p))
  3893. return i;
  3894. return -1;
  3895. }
  3896. void EffectsPanel::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  3897. {
  3898. // a spin that is scrolling the mixer goes on scrolling over the EQ, the knobs and the slot names (round 169c)
  3899. if (ui::wheelScrolling())
  3900. {
  3901. ui::noteWheelScroll();
  3902. juce::Component::mouseWheelMove (e, wheel);
  3903. return;
  3904. }
  3905. if (auto eqControl = eqControlAt (e.getPosition()); eqControl != 0)
  3906. {
  3907. if (isEqPoint (eqControl)) // the wheel over a handle changes the band's width
  3908. eqControl = eqParamBase - (eqPointBase - eqControl) * 3 - 2;
  3909. if (const auto v = ui::wheelValue (valueOf (eqControl, -1), e, wheel, specFor (eqControl, -1)))
  3910. {
  3911. setValue (eqControl, -1, *v);
  3912. showTip (eqControl, -1, true);
  3913. }
  3914. return;
  3915. }
  3916. if (const auto slot = mixKnobAt (e.getPosition()); slot >= 0)
  3917. {
  3918. if (const auto v = ui::wheelValue (valueOf (mixParam, slot), e, wheel, specFor (mixParam, slot)))
  3919. {
  3920. setValue (mixParam, slot, *v);
  3921. showTip (mixParam, slot, true);
  3922. }
  3923. return;
  3924. }
  3925. if (const auto p = knobAt (e.getPosition()); p >= 0)
  3926. {
  3927. if (const auto v = ui::wheelValue (valueOf (p, selectedSlot), e, wheel, specFor (p, selectedSlot)))
  3928. {
  3929. setValue (p, selectedSlot, *v);
  3930. showTip (p, selectedSlot, true);
  3931. }
  3932. return;
  3933. }
  3934. // FL (REA FUN_012ab750): the wheel over a slot moves its effect one slot up or down (into an empty slot too,
  3935. // wrapping around the 10 slots) and the mouse pointer follows it. A trackpad's small steps add up to one move.
  3936. if (const auto slot = slotAt (e.getPosition()); slot >= 0)
  3937. {
  3938. const auto delta = (wheel.isReversed ? -1.0 : 1.0) * (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX);
  3939. if (wheelSlot != slot || juce::Time::getMillisecondCounter() - wheelTime > 400)
  3940. wheelAccumulator = 0.0;
  3941. wheelSlot = slot;
  3942. wheelTime = juce::Time::getMillisecondCounter();
  3943. const auto steps = controls::slotWheelSteps (wheelAccumulator, delta, wheel.isSmooth, wheel.isInertial);
  3944. if (steps == 0)
  3945. return;
  3946. int now = -1;
  3947. engine.editSongStructural ([t = track, slot, steps, &now] (Song& song) { now = mixerops::moveEffectBy (song, t, slot, steps > 0 ? -1 : 1); });
  3948. if (now >= 0)
  3949. {
  3950. selectedSlot = wheelSlot = now;
  3951. const auto target = slotBounds (rowOf (now));
  3952. juce::Desktop::getInstance().getMainMouseSource().setScreenPosition (localPointToGlobal (juce::Point<int> (e.x, target.getCentreY())).toFloat());
  3953. }
  3954. repaint();
  3955. return;
  3956. }
  3957. ui::noteWheelScroll();
  3958. juce::Component::mouseWheelMove (e, wheel);
  3959. }
  3960. ui::Hint EffectsPanel::hintAt (juce::Point<int> p)
  3961. {
  3962. const auto gesture = ui::valueGestures();
  3963. if (isEqParam (dragParam))
  3964. return ui::valueHint (specFor (dragParam, -1), valueOf (dragParam, -1), gesture);
  3965. if (const auto eqControl = eqControlAt (p); eqControl != 0)
  3966. {
  3967. if (isEqParam (eqControl))
  3968. return ui::valueHint (specFor (eqControl, -1), valueOf (eqControl, -1), gesture);
  3969. ui::Hint h;
  3970. const auto band = eqPointBase - eqControl;
  3971. h.text = tr ("EQ: [LMB] drag the band's frequency and level [Wheel] width [2xLMB] back to 0 dB");
  3972. h.value = tr ("Band {0}", { juce::String (band + 1) }) + " - " + tr (eqBandNames[band]);
  3973. return h;
  3974. }
  3975. if (slots() != nullptr && eqFoldBounds().contains (p))
  3976. {
  3977. ui::Hint h;
  3978. h.text = eqFolded ? tr ("Insert EQ (folded): [LMB] unfold it") : tr ("Insert EQ: [LMB] fold it (it folds by itself when the mixer is short)");
  3979. return h;
  3980. }
  3981. if (outputBounds().contains (p))
  3982. {
  3983. ui::Hint h;
  3984. h.text = track == 0 ? tr ("Audio output target: the outputs of your audio device the Master plays on [LMB] choose")
  3985. : tr ("Audio output target: through the Master by default; optional: also straight to an output of your audio interface (a mono output too) [LMB] choose");
  3986. h.value = outputName();
  3987. h.hasMenu = true;
  3988. return h;
  3989. }
  3990. if (dragParam == mixParam || (dragParam >= 0 && drag.isActive()))
  3991. return ui::valueHint (specFor (dragParam, dragParam == mixParam ? juce::jmax (0, selectedSlot) : selectedSlot),
  3992. valueOf (dragParam, dragParam == mixParam ? juce::jmax (0, selectedSlot) : selectedSlot), gesture);
  3993. if (const auto slot = mixKnobAt (p); slot >= 0)
  3994. return ui::valueHint (specFor (mixParam, slot), valueOf (mixParam, slot), gesture);
  3995. if (const auto param = knobAt (p); param >= 0)
  3996. return ui::valueHint (specFor (param, selectedSlot), valueOf (param, selectedSlot), gesture);
  3997. ui::Hint h;
  3998. if (const auto* s = slots(); s != nullptr && selectedSlot >= 0 && selectedSlot < (int) s->size()
  3999. && NativeEffectWindows::canOpen ((*s)[(std::size_t) selectedSlot].kind) && editorButtonBounds().contains (p))
  4000. {
  4001. h.text = tr ("Open the effect's window (its full controls, as in FL); clicking the slot's name does the same");
  4002. return h;
  4003. }
  4004. if (track > 0 && armBounds().contains (p))
  4005. {
  4006. h.text = mixerinput::armHint (engine, track);
  4007. h.hasMenu = true;
  4008. return h;
  4009. }
  4010. if (track >= 0 && inputBoxBounds().contains (p))
  4011. {
  4012. h.text = track == 0 ? tr ("Audio input source: the microphone or interface input the Master plays (through its effects) [LMB] choose")
  4013. : tr ("Audio input source: the microphone or interface input this insert plays and records [LMB] choose");
  4014. h.hasMenu = true;
  4015. const auto& mt = engine.getSong().mixer[(std::size_t) track];
  4016. if (mt.inputChannel >= 0)
  4017. h.value = juce::String::fromUTF8 (inputSourceName (mt.inputChannel, mt.inputStereo, engine.getInputChannelNames()).c_str());
  4018. return h;
  4019. }
  4020. if (fxSwitchBounds().contains (p) && slots() != nullptr && ! slots()->empty())
  4021. {
  4022. h.text = tr ("All effects of this insert on/off; right-click opens or closes their plugin windows");
  4023. h.hasMenu = true;
  4024. return h;
  4025. }
  4026. for (int i = 0; i < maxEffectSlots; ++i)
  4027. if (slotBounds (i).contains (p))
  4028. {
  4029. const auto used = effectIn (i) >= 0;
  4030. h.text = used ? (arrowBounds (i).contains (p) ? tr ("Effect slot options: replace, move, delete...")
  4031. : tr ("Effect slot: click shows or hides its window (and its knobs below), the LED bypasses, the wheel or a drag moves it up or down, right-click: options"))
  4032. : tr ("Empty slot: click to add an effect");
  4033. h.hasMenu = used;
  4034. }
  4035. return h;
  4036. }
  4037. void EffectsPanel::mouseDrag (const juce::MouseEvent& e)
  4038. {
  4039. if (dragSlot >= 0)
  4040. {
  4041. if (e.getDistanceFromDragStart() > 4)
  4042. {
  4043. const auto target = juce::jlimit (0, maxEffectSlots - 1, (e.y - slotsTop) / slotHeight); // (empty slots too, as FL)
  4044. if (target != dropSlot)
  4045. {
  4046. dropSlot = target;
  4047. setMouseCursor (juce::MouseCursor::DraggingHandCursor);
  4048. repaint();
  4049. }
  4050. }
  4051. return;
  4052. }
  4053. if (isEqPoint (dragParam))
  4054. {
  4055. setEqFromGraph (eqPointBase - dragParam, e.getPosition());
  4056. return;
  4057. }
  4058. if (isEqParam (dragParam))
  4059. {
  4060. setValue (dragParam, -1, drag.update (e, specFor (dragParam, -1)));
  4061. showTip (dragParam, -1, false);
  4062. return;
  4063. }
  4064. if (dragParam == gateStepParam)
  4065. {
  4066. setGateStep (e.getPosition());
  4067. return;
  4068. }
  4069. if (dragParam == bandLevelParam)
  4070. {
  4071. setBandLevel (e.getPosition());
  4072. return;
  4073. }
  4074. if (dragParam == mixParam)
  4075. {
  4076. setValue (mixParam, selectedSlot, drag.update (e, specFor (mixParam, selectedSlot)));
  4077. showTip (mixParam, selectedSlot, false);
  4078. return;
  4079. }
  4080. if (dragParam < 0)
  4081. return;
  4082. setValue (dragParam, selectedSlot, drag.update (e, specFor (dragParam, selectedSlot)));
  4083. showTip (dragParam, selectedSlot, false);
  4084. }
  4085. void EffectsPanel::showTip (int param, int slot, bool transient)
  4086. {
  4087. if (isEqParam (param))
  4088. {
  4089. const auto band = (eqParamBase - param) / 3, what = (eqParamBase - param) % 3;
  4090. const auto area = what == 0 ? eqFaderBounds (band) : eqKnobBounds (band, what);
  4091. const auto spec = specFor (param, -1);
  4092. ui::postHint (ui::valueHint (spec, valueOf (param, -1), ui::valueGestures()));
  4093. if (transient)
  4094. ui::flashValueTip (*this, area, spec.text (valueOf (param, -1)));
  4095. else
  4096. ui::showValueTip (*this, area, spec.text (valueOf (param, -1)));
  4097. return;
  4098. }
  4099. const auto* s = slots();
  4100. if (s == nullptr || slot < 0 || slot >= (int) s->size())
  4101. return;
  4102. const auto area = param == mixParam ? mixBounds (rowOf (slot)) : knobBounds (param).withHeight (juce::jlimit (30, 44, knobBounds (param).getHeight() - 30));
  4103. const auto text = specFor (param, slot).text (valueOf (param, slot));
  4104. ui::postHint (ui::valueHint (specFor (param, slot), valueOf (param, slot), ui::valueGestures()));
  4105. if (transient)
  4106. ui::flashValueTip (*this, area, text);
  4107. else
  4108. ui::showValueTip (*this, area, text);
  4109. }
  4110. void EffectsPanel::mouseMove (const juce::MouseEvent& e)
  4111. {
  4112. const auto p = e.getPosition();
  4113. auto slot = -1; // (a row)
  4114. auto param = -1;
  4115. auto led = false;
  4116. for (int i = 0; i < maxEffectSlots; ++i)
  4117. if (slotBounds (i).contains (p))
  4118. slot = i;
  4119. if (const auto m = mixKnobAt (p); m >= 0)
  4120. {
  4121. slot = rowOf (m);
  4122. param = mixParam;
  4123. }
  4124. else if (slot < 0)
  4125. param = knobAt (p);
  4126. else
  4127. led = p.x < slotBounds (slot).getX() + 22;
  4128. const auto input = track > 0 && armBounds().contains (p) ? 1 : track >= 0 && inputBoxBounds().contains (p) ? 2 : 0;
  4129. const auto eq = eqControlAt (p);
  4130. const auto output = outputBounds().contains (p);
  4131. auto arrow = false;
  4132. for (int i = 0; i < maxEffectSlots; ++i)
  4133. if (arrowBounds (i).contains (p))
  4134. {
  4135. slot = i;
  4136. arrow = true;
  4137. }
  4138. if (slot >= 0)
  4139. led = ledBounds (slot).contains (p);
  4140. if (slot != hoverSlot || param != hoverParam || led != hoverLed || input != hoverInput || eq != hoverEq || output != hoverOutput || arrow != hoverArrow)
  4141. {
  4142. hoverEq = eq;
  4143. hoverOutput = output;
  4144. hoverArrow = arrow;
  4145. hoverInput = input;
  4146. hoverSlot = slot;
  4147. hoverParam = param;
  4148. hoverLed = led;
  4149. repaint();
  4150. }
  4151. }
  4152. void EffectsPanel::mouseExit (const juce::MouseEvent&)
  4153. {
  4154. if (hoverSlot >= 0 || hoverParam != -1 || hoverInput != 0 || hoverEq != 0 || hoverOutput || hoverArrow)
  4155. {
  4156. hoverEq = 0;
  4157. hoverOutput = hoverArrow = false;
  4158. hoverInput = 0;
  4159. hoverSlot = hoverParam = -1;
  4160. hoverLed = false;
  4161. repaint();
  4162. }
  4163. }
  4164. void EffectsPanel::mouseUp (const juce::MouseEvent& e)
  4165. {
  4166. // a click on the slot's name (not a drag, not the second click of a double-click) shows or hides its window (FL)
  4167. if (dragSlot >= 0 && dropSlot < 0 && ! e.mouseWasDraggedSinceMouseDown() && e.getNumberOfClicks() == 1)
  4168. {
  4169. const auto slot = dragSlot;
  4170. dragSlot = -1;
  4171. toggleEditor (slot);
  4172. }
  4173. if (dragSlot >= 0 && dropSlot >= 0 && dropSlot != rowOf (dragSlot))
  4174. {
  4175. bool moved = false;
  4176. engine.editSongStructural ([t = track, from = dragSlot, to = dropSlot, &moved] (Song& song) { moved = mixerops::moveEffectToRow (song, t, from, to); });
  4177. if (moved)
  4178. selectedSlot = effectIn (dropSlot);
  4179. }
  4180. if (dragSlot >= 0)
  4181. setMouseCursor (juce::MouseCursor::NormalCursor);
  4182. dragSlot = dropSlot = -1;
  4183. repaint();
  4184. dragParam = -1;
  4185. drag.end();
  4186. ui::hideValueTip();
  4187. ui::clearPostedHint();
  4188. }
  4189. void EffectsPanel::mouseDoubleClick (const juce::MouseEvent& e)
  4190. {
  4191. if (const auto eqControl = eqControlAt (e.getPosition()); eqControl != 0)
  4192. {
  4193. if (isEqPoint (eqControl)) // the band back to 0 dB
  4194. setValue (eqParamBase - (eqPointBase - eqControl) * 3, -1, specFor (eqParamBase, -1).defaultValue);
  4195. else
  4196. setValue (eqControl, -1, specFor (eqControl, -1).defaultValue);
  4197. return;
  4198. }
  4199. for (int i = 0; slots() != nullptr && i < (int) slots()->size(); ++i)
  4200. if (mixBounds (rowOf (i)).contains (e.getPosition()))
  4201. {
  4202. engine.editSong ([t = track, i] (Song& song) { song.mixer[(std::size_t) t].effects[(std::size_t) i].mix = 1.0f; });
  4203. return;
  4204. }
  4205. else if (slotBounds (rowOf (i)).contains (e.getPosition()) && ! arrowBounds (rowOf (i)).contains (e.getPosition()) && ! ledBounds (rowOf (i)).contains (e.getPosition()))
  4206. {
  4207. openEditor (i); // (the first click opened it, round 170b): it stays open and comes to the front
  4208. return;
  4209. }
  4210. const auto p = knobAt (e.getPosition());
  4211. if (p < 0)
  4212. return;
  4213. const auto kind = (*slots())[(std::size_t) selectedSlot].kind;
  4214. const auto value = effectInfo (kind).params[(std::size_t) p].defaultValue;
  4215. engine.editSong ([t = track, slot = selectedSlot, p, value] (Song& song) {
  4216. song.mixer[(std::size_t) t].effects[(std::size_t) slot].params[(std::size_t) p] = value;
  4217. });
  4218. }
  4219. bool EffectsPanel::isInterestedInDragSource (const SourceDetails& details)
  4220. {
  4221. return (BrowserComponent::isBrowserDrag (details) && BrowserComponent::draggedFile (details).hasFileExtension ("fst"))
  4222. || BrowserComponent::isEffectDrag (details) || BrowserComponent::isGeneratorDrag (details);
  4223. }
  4224. void EffectsPanel::itemDropped (const SourceDetails& details)
  4225. {
  4226. if (BrowserComponent::isGeneratorDrag (details))
  4227. {
  4228. if (auto c = BrowserComponent::draggedGenerator (details); c && onInstrumentDropped != nullptr
  4229. && track >= 0 && track < (int) engine.getSong().mixer.size())
  4230. onInstrumentDropped (track, std::move (*c));
  4231. return;
  4232. }
  4233. if (BrowserComponent::isEffectDrag (details))
  4234. {
  4235. if (auto fx = BrowserComponent::draggedEffect (details))
  4236. dropEffect (std::move (*fx), details.localPosition);
  4237. return;
  4238. }
  4239. dropPreset (BrowserComponent::draggedFile (details), details.localPosition);
  4240. }
  4241. bool EffectsPanel::isInterestedInFileDrag (const juce::StringArray& files)
  4242. {
  4243. return files.size() == 1 && juce::File (files[0]).hasFileExtension ("fst");
  4244. }
  4245. void EffectsPanel::filesDropped (const juce::StringArray& files, int x, int y)
  4246. {
  4247. if (! files.isEmpty())
  4248. dropPreset (juce::File (files[0]), { x, y });
  4249. }
  4250. bool EffectsPanel::dropPreset (const juce::File& file, juce::Point<int> position)
  4251. {
  4252. juce::MemoryBlock data;
  4253. if (slots() == nullptr || ! file.loadFileAsData (data))
  4254. return false;
  4255. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  4256. const auto fx = effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), engine.getSong().bpm);
  4257. if (! fx)
  4258. {
  4259. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Preset"),
  4260. tr ("LYNX SHARE can't build an effect from this preset."));
  4261. return false;
  4262. }
  4263. return dropEffect (*fx, position);
  4264. }
  4265. bool EffectsPanel::dropEffect (EffectSlot fx, juce::Point<int> position)
  4266. {
  4267. if (slots() == nullptr)
  4268. return false;
  4269. auto target = -1, emptyRow = -1;
  4270. for (int row = 0; row < maxEffectSlots; ++row)
  4271. if (slotBounds (row).contains (position))
  4272. {
  4273. target = effectIn (row);
  4274. emptyRow = target < 0 ? row : -1;
  4275. }
  4276. if (target < 0 && (int) slots()->size() >= maxEffectSlots)
  4277. return false;
  4278. int added = -1;
  4279. engine.editSong ([t = track, target, emptyRow, &added, fx = std::move (fx)] (Song& song) {
  4280. auto& effects = song.mixer[(std::size_t) t].effects;
  4281. if (target >= 0 && target < (int) effects.size())
  4282. effects[(std::size_t) target] = fx;
  4283. else if (emptyRow >= 0) // dropped on an empty slot: it lands there (FL)
  4284. added = mixerops::insertEffectAtRow (song, t, fx, emptyRow);
  4285. else
  4286. effects.push_back (fx);
  4287. });
  4288. selectedSlot = target >= 0 ? target : added >= 0 ? added : (int) slots()->size() - 1;
  4289. repaint();
  4290. return true;
  4291. }
  4292. juce::Rectangle<int> EffectsPanel::fxSwitchBounds() const
  4293. {
  4294. return { getWidth() - 58, 6, 48, panelHeader - 12 };
  4295. }
  4296. int EffectsPanel::slotAt (juce::Point<int> p) const
  4297. {
  4298. const auto* s = slots();
  4299. for (int i = 0; s != nullptr && i < (int) s->size(); ++i)
  4300. if (const auto row = rowOf (i); slotBounds (row).contains (p) && ! mixBounds (row).contains (p) && ! ledBounds (row).contains (p) && ! arrowBounds (row).contains (p))
  4301. return i;
  4302. return -1;
  4303. }
  4304. void EffectsPanel::toggleAllWindows()
  4305. {
  4306. // opens every plugin effect window of the insert, or closes them all when one is open
  4307. const auto* s = slots();
  4308. if (s == nullptr)
  4309. return;
  4310. bool anyOpen = false;
  4311. for (int i = 0; i < (int) s->size(); ++i)
  4312. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (track, i).get()))
  4313. anyOpen = anyOpen || PluginWindows::isOpen (p->getInstance());
  4314. for (int i = 0; i < (int) s->size(); ++i)
  4315. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (track, i).get()))
  4316. {
  4317. if (anyOpen)
  4318. PluginWindows::close (p->getInstance());
  4319. else
  4320. openPluginWindow (i);
  4321. }
  4322. }
  4323. juce::Rectangle<int> EffectsPanel::pluginButtonBounds() const
  4324. {
  4325. return { 20, slotsTop + maxEffectSlots * slotHeight + 30, getWidth() - 40, 30 };
  4326. }
  4327. void EffectsPanel::openEditor (int slot)
  4328. {
  4329. const auto* s = slots();
  4330. if (s == nullptr || slot < 0 || slot >= (int) s->size())
  4331. return;
  4332. const auto kind = (*s)[(std::size_t) slot].kind;
  4333. if (kind == EffectKind::plugin)
  4334. openPluginWindow (slot);
  4335. else if (kind == EffectKind::parametricEq)
  4336. ParametricEqWindows::open (engine, track, slot);
  4337. else if (NativeEffectWindows::canOpen ((*s)[(std::size_t) slot]))
  4338. NativeEffectWindows::open (engine, track, slot);
  4339. }
  4340. void EffectsPanel::toggleEditor (int slot)
  4341. {
  4342. const auto* s = slots();
  4343. if (s == nullptr || slot < 0 || slot >= (int) s->size())
  4344. return;
  4345. // FL (REA FUN_012bde10, the slot name button's click): the plugin's editor is shown, or hidden when it shows
  4346. if ((*s)[(std::size_t) slot].kind == EffectKind::plugin)
  4347. {
  4348. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (track, slot).get()); p != nullptr && PluginWindows::isOpen (p->getInstance()))
  4349. {
  4350. PluginWindows::close (p->getInstance());
  4351. return;
  4352. }
  4353. openPluginWindow (slot);
  4354. return;
  4355. }
  4356. if (! ui::SlotGoneWatcher::closeWindow (engine, track, slot))
  4357. openEditor (slot);
  4358. }
  4359. juce::Rectangle<int> EffectsPanel::editorButtonBounds() const
  4360. {
  4361. // on the title row of the selected effect's knobs
  4362. return { getWidth() - 96, (tuneSelected() ? tuneKeysBounds().getY() : knobBounds (0).getY()) - 29, 86, 20 };
  4363. }
  4364. void EffectsPanel::openPluginWindow (int slot)
  4365. {
  4366. auto effect = engine.getEffect (track, slot);
  4367. if (auto* plugin = dynamic_cast<PluginEffect*> (effect.get()))
  4368. {
  4369. if (plugin->hasCrashed()) // (not called again: its window would call into it)
  4370. {
  4371. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Plugin"),
  4372. tr ("This plugin crashed and was switched off. Save the project and open it again to reload it."));
  4373. return;
  4374. }
  4375. const auto& s = engine.getSong().mixer[(std::size_t) track].effects[(std::size_t) slot];
  4376. PluginWindows::open (effect, plugin->getInstance(), quickpick::slotName (engine, s), // (its Plugin database name, round 165c)
  4377. { &engine, [t = track, slot] (Song& song) -> PluginRef* {
  4378. if (t >= (int) song.mixer.size() || slot >= (int) song.mixer[(std::size_t) t].effects.size())
  4379. return nullptr;
  4380. return &song.mixer[(std::size_t) t].effects[(std::size_t) slot].plugin;
  4381. } });
  4382. return;
  4383. }
  4384. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Plugin"),
  4385. tr ("This plugin could not be loaded (it is not installed or has not been scanned)."));
  4386. }
  4387. void EffectsPanel::showAddMenu (int row)
  4388. {
  4389. juce::PopupMenu menu;
  4390. // the effect lands in the clicked empty slot (FL's slot places, round 170b); returns its index, -1 = not added
  4391. auto place = [this, row] (EffectSlot fx) {
  4392. int at = -1;
  4393. engine.editSong ([t = track, row, &fx, &at] (Song& song) {
  4394. if (t < 0 || t >= (int) song.mixer.size() || (int) song.mixer[(std::size_t) t].effects.size() >= maxEffectSlots)
  4395. return;
  4396. at = mixerops::insertEffectAtRow (song, t, fx, row);
  4397. if (at < 0)
  4398. {
  4399. song.mixer[(std::size_t) t].effects.push_back (std::move (fx));
  4400. at = (int) song.mixer[(std::size_t) t].effects.size() - 1;
  4401. }
  4402. mixerops::linkAddedSidechain (song, t, at); // round 170h: the sole sidechain sender feeds a new compressor
  4403. });
  4404. if (at < 0)
  4405. return at;
  4406. selectedSlot = at;
  4407. if ((*slots())[(std::size_t) at].kind != EffectKind::plugin) // (plugins: their own window, below)
  4408. openEditor (at); // FL opens the effect's window when it is loaded (round 170h, fl-09)
  4409. repaint();
  4410. return at;
  4411. };
  4412. // FL's renamed plugins first (issue #11): "1_EQ" renamed in the Browser's Plugin database is added by typing 1
  4413. auto addFx = [this, place] (EffectSlot fx) {
  4414. const auto at = place (std::move (fx));
  4415. if (at >= 0 && (*slots())[(std::size_t) at].kind == EffectKind::plugin)
  4416. openPluginWindow (at);
  4417. };
  4418. auto picks = quickpick::renamedEffects (engine, addFx);
  4419. quickpick::addPicks (menu, picks);
  4420. // rounds 166f / 170b (Busy Works: "random order"): every effect under its category heading, A-Z, as FL's slot menu
  4421. // (LYNX SHARE first, then FL's Plugin database categories, the user's own folders among them)
  4422. quickpick::addFolderGroups (menu, engine, std::function<void (EffectSlot)> (addFx));
  4423. // LYNX equivalents of well-known third-party effects, with the same default preset a substitute gets
  4424. juce::PopupMenu equivalents;
  4425. for (const auto& entry : pluginSubstitutes())
  4426. if (! entry.instrument)
  4427. equivalents.addItem (juce::String::fromUTF8 (entry.product.c_str()) + juce::String::fromUTF8 (" \xe2\x86\x92 ") + juce::String::fromUTF8 (effectInfo (entry.effect).name),
  4428. [place, entry] { place (makeSubstituteSlot (entry)); });
  4429. if (equivalents.getNumItems() > 0)
  4430. menu.addSubMenu (tr ("LYNX SHARE equivalents"), equivalents);
  4431. juce::PopupMenu plugins;
  4432. addPluginItems (plugins, engine, false, [this, place] (PluginRef ref) {
  4433. EffectSlot slot;
  4434. slot.kind = EffectKind::plugin;
  4435. slot.plugin = ref;
  4436. if (const auto at = place (std::move (slot)); at >= 0)
  4437. openPluginWindow (at);
  4438. }, this);
  4439. menu.addSeparator();
  4440. menu.addSubMenu (tr ("Plugin (VST/VST3/CLAP)"), plugins);
  4441. menu.addSeparator();
  4442. menu.addItem (tr ("Audio editor (record this insert)..."), [this] { openAudioEditorForInsert (engine, track); });
  4443. quickpick::addFolderViewItems (menu, engine); // FL: Categories / Simple / Tree at the bottom
  4444. quickpick::showMenu (menu, juce::PopupMenu::Options().withTargetComponent (this).withMousePosition(), std::move (picks));
  4445. }
  4446. void EffectsPanel::showSlotMenu (int slot)
  4447. {
  4448. // the same categories as the empty slot's menu (rounds 166f / 170b)
  4449. juce::PopupMenu replace;
  4450. quickpick::addFolderGroups (replace, engine, std::function<void (EffectSlot)> ([this, slot] (EffectSlot fx) {
  4451. engine.editSong ([t = track, slot, fx] (Song& song) {
  4452. if (t < (int) song.mixer.size() && slot < (int) song.mixer[(std::size_t) t].effects.size())
  4453. song.mixer[(std::size_t) t].effects[(std::size_t) slot] = fx;
  4454. });
  4455. if (slot < (int) slots()->size() && (*slots())[(std::size_t) slot].kind == EffectKind::plugin)
  4456. openPluginWindow (slot);
  4457. }));
  4458. quickpick::addFolderViewItems (replace, engine);
  4459. juce::PopupMenu menu;
  4460. menu.addSubMenu (tr ("Replace with"), replace);
  4461. menu.addItem (tr ("Audio editor (record this insert)..."), [this] { openAudioEditorForInsert (engine, track); });
  4462. // FL presets (Plugin presets\Effects\<plugin>) that map to this effect
  4463. {
  4464. juce::PopupMenu presets;
  4465. const auto roots = findFlStudioRoots();
  4466. const auto base = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  4467. for (const auto& plugin : flPluginsForEffect ((*slots())[(std::size_t) slot].kind))
  4468. {
  4469. juce::PopupMenu sub;
  4470. auto files = base.getChildFile (juce::String::fromUTF8 (plugin.c_str())).findChildFiles (juce::File::findFiles, true, "*.fst");
  4471. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFileName().compareNatural (b.getFileName()) < 0; });
  4472. for (const auto& f : files)
  4473. sub.addItem (f.getFileNameWithoutExtension(), [this, slot, f] {
  4474. juce::MemoryBlock data;
  4475. if (! f.loadFileAsData (data))
  4476. return;
  4477. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  4478. if (auto fx = effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), engine.getSong().bpm))
  4479. engine.editSong ([t = track, slot, fx = *fx] (Song& song) {
  4480. auto& target = song.mixer[(std::size_t) t].effects[(std::size_t) slot];
  4481. const auto enabled = target.enabled;
  4482. const auto mix = target.mix;
  4483. target = fx;
  4484. target.enabled = enabled;
  4485. target.mix = mix;
  4486. });
  4487. });
  4488. if (sub.getNumItems() > 0)
  4489. presets.addSubMenu (juce::String::fromUTF8 (plugin.c_str()), sub);
  4490. }
  4491. if (presets.getNumItems() > 0)
  4492. menu.addSubMenu (tr ("FL presets"), presets);
  4493. }
  4494. // side inputs: another track's output feeds the compressor's detector, or the vocoder's modulator/carrier
  4495. const auto kind = (*slots())[(std::size_t) slot].kind;
  4496. auto sideMenu = [&] (const juce::String& title, bool second) {
  4497. juce::PopupMenu side;
  4498. const auto& fx = (*slots())[(std::size_t) slot];
  4499. const auto current = second ? fx.sidechain2 : fx.sidechain;
  4500. auto assign = [this, slot, second] (int source) {
  4501. engine.editSong ([tk = track, slot, second, source] (Song& s) {
  4502. auto& target = s.mixer[(std::size_t) tk].effects[(std::size_t) slot];
  4503. (second ? target.sidechain2 : target.sidechain) = source;
  4504. if (target.kind == EffectKind::vocoder && source >= 0)
  4505. target.params[16] = 1.0f; // separate inputs (otherwise L = modulator, R = carrier)
  4506. });
  4507. };
  4508. side.addItem (tr ("None"), true, current < 0, [assign] { assign (-1); });
  4509. const auto& song = engine.getSong();
  4510. for (int t = 1; t < (int) song.mixer.size(); ++t)
  4511. if (t != track)
  4512. side.addItem (juce::String (t) + " " + juce::String::fromUTF8 (song.mixer[(std::size_t) t].name.c_str()), true, current == t,
  4513. [assign, t] { assign (t); });
  4514. menu.addSubMenu (title, side);
  4515. };
  4516. if (kind == EffectKind::compressor || kind == EffectKind::fruityLimiter || kind == EffectKind::fruityCompressor || kind == EffectKind::facetEq)
  4517. sideMenu (tr ("Sidechain from"), false);
  4518. if (kind == EffectKind::vocoder || kind == EffectKind::vocodex)
  4519. {
  4520. sideMenu (tr ("Modulator from"), false);
  4521. sideMenu (tr ("Carrier from"), true);
  4522. }
  4523. if (kind == EffectKind::newtone || kind == EffectKind::newtime)
  4524. {
  4525. // the sample the plugin plays in slave mode (REA_rodada73): FL's edits are kept in the state but not reproduced
  4526. const auto& fx = (*slots())[(std::size_t) slot];
  4527. const auto current = juce::File (juce::String::fromUTF8 (fx.samplePath.c_str()));
  4528. juce::PopupMenu source;
  4529. source.addItem (fx.samplePath.empty() ? tr ("No sample") : current.getFileName(), false, false, [] {});
  4530. source.addItem (tr ("Choose a sample..."), [this, slot, current] {
  4531. sampleChooser = lynx::ui::makeFileChooser (tr ("Source sample"), current.existsAsFile() ? current : juce::File(),
  4532. "*.wav;*.aif;*.aiff;*.flac;*.ogg;*.mp3");
  4533. lynx::ui::launchChooser (sampleChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  4534. [this, slot] (const juce::FileChooser& fc) {
  4535. const auto file = fc.getResult();
  4536. if (file == juce::File())
  4537. return;
  4538. engine.editSong ([t = track, slot, path = file.getFullPathName().toStdString()] (Song& s) {
  4539. if (t < (int) s.mixer.size() && slot < (int) s.mixer[(std::size_t) t].effects.size())
  4540. s.mixer[(std::size_t) t].effects[(std::size_t) slot].samplePath = path;
  4541. });
  4542. });
  4543. });
  4544. source.addItem (tr ("Remove the sample"), ! fx.samplePath.empty(), false, [this, slot] {
  4545. engine.editSong ([t = track, slot] (Song& s) {
  4546. if (t < (int) s.mixer.size() && slot < (int) s.mixer[(std::size_t) t].effects.size())
  4547. s.mixer[(std::size_t) t].effects[(std::size_t) slot].samplePath.clear();
  4548. });
  4549. });
  4550. menu.addSubMenu (tr ("Source sample"), source);
  4551. }
  4552. {
  4553. // A/B compare: keep a copy of the settings, then swap between it and the current ones
  4554. const auto key = std::make_pair (track, slot);
  4555. const auto hasSpare = spare.count (key) > 0 && spare[key].kind == (*slots())[(std::size_t) slot].kind;
  4556. juce::PopupMenu ab;
  4557. ab.addItem (tr ("Store the current settings as B"), [this, key, slot] {
  4558. spare[key] = (*slots())[(std::size_t) slot];
  4559. });
  4560. ab.addItem (tr ("Swap with B"), hasSpare, false, [this, key, slot] {
  4561. const auto stored = spare[key];
  4562. spare[key] = (*slots())[(std::size_t) slot];
  4563. engine.editSong ([t = track, slot, stored] (Song& song) {
  4564. auto& target = song.mixer[(std::size_t) t].effects[(std::size_t) slot];
  4565. const auto enabled = target.enabled;
  4566. target = stored;
  4567. target.enabled = enabled;
  4568. });
  4569. });
  4570. ab.addItem (tr ("Forget B"), hasSpare, false, [this, key] { spare.erase (key); });
  4571. menu.addSubMenu (hasSpare ? tr ("A/B compare (B stored)") : tr ("A/B compare"), ab);
  4572. }
  4573. if ((*slots())[(std::size_t) slot].isSubstitute()) // A/B of every substitute of the project at once (round 113)
  4574. menu.addItem (tr ("Bypass all LYNX SHARE substitutes of this project"), true, engine.getSong().substitutesBypassed, [this] {
  4575. engine.editSong ([] (Song& song) { song.substitutesBypassed = ! song.substitutesBypassed; });
  4576. repaint();
  4577. });
  4578. // FL's slot menu "CPU" section (REA round 139): Allow threaded processing (plugins), Smart disable
  4579. menu.addSectionHeader (tr ("CPU"));
  4580. if ((*slots())[(std::size_t) slot].kind == EffectKind::plugin)
  4581. menu.addItem (tr ("Allow threaded processing"), true, (*slots())[(std::size_t) slot].plugin.threaded, [this, slot] {
  4582. engine.editSong ([t = track, slot] (Song& song) {
  4583. if (t < (int) song.mixer.size() && slot < (int) song.mixer[(std::size_t) t].effects.size())
  4584. song.mixer[(std::size_t) t].effects[(std::size_t) slot].plugin.threaded = ! song.mixer[(std::size_t) t].effects[(std::size_t) slot].plugin.threaded;
  4585. });
  4586. });
  4587. // FL's per-plugin "Smart disable": skipped while its input and output are silent
  4588. menu.addItem (tr ("Smart disable"), true, (*slots())[(std::size_t) slot].smartDisable, [this, slot] {
  4589. engine.editSong ([t = track, slot] (Song& song) {
  4590. if (t < (int) song.mixer.size() && slot < (int) song.mixer[(std::size_t) t].effects.size())
  4591. song.mixer[(std::size_t) t].effects[(std::size_t) slot].smartDisable = ! song.mixer[(std::size_t) t].effects[(std::size_t) slot].smartDisable;
  4592. });
  4593. });
  4594. menu.addSeparator();
  4595. // FL's Move up / Move down (REA FUN_01233de0 / FUN_01235190): one slot, into an empty one too, wrapping around
  4596. auto move = [this, slot] (int delta) {
  4597. int now = -1;
  4598. engine.editSongStructural ([t = track, slot, delta, &now] (Song& song) { now = mixerops::moveEffectBy (song, t, slot, delta); });
  4599. if (now >= 0)
  4600. selectedSlot = now;
  4601. repaint();
  4602. };
  4603. menu.addItem (tr ("Move up"), [move] { move (-1); });
  4604. menu.addItem (tr ("Move down"), [move] { move (1); });
  4605. if ((*slots())[(std::size_t) slot].kind == EffectKind::plugin)
  4606. {
  4607. auto* live = dynamic_cast<PluginEffect*> (engine.getEffect (track, slot).get());
  4608. menu.addSubMenu (tr ("Processing"), pluginProcessingMenu (engine, (*slots())[(std::size_t) slot].plugin, live != nullptr ? &live->getInstance() : nullptr,
  4609. [t = track, slot] (Song& song) -> PluginRef* {
  4610. if (t >= (int) song.mixer.size() || slot >= (int) song.mixer[(std::size_t) t].effects.size())
  4611. return nullptr;
  4612. return &song.mixer[(std::size_t) t].effects[(std::size_t) slot].plugin;
  4613. }));
  4614. }
  4615. if ((*slots())[(std::size_t) slot].kind == EffectKind::plugin)
  4616. {
  4617. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (track, slot).get()))
  4618. addPluginParameterItems (menu, engine, p->getInstance(), { AutomationTargetKind::effectParam, track, slot, 0 });
  4619. }
  4620. if ((*slots())[(std::size_t) slot].kind == EffectKind::patcher) // its published parameters (round 171b)
  4621. addPatcherParameterItems (menu, engine, (*slots())[(std::size_t) slot].patcher, { AutomationTargetKind::effectParam, track, slot, 0 });
  4622. // FL's Patcherize / Patcherize all (round 165m): the effect (or the whole chain) into a new Patcher, same sound
  4623. menu.addSeparator();
  4624. menu.addItem (tr ("Patcherize"), patcherize::canPatcherizeSlot (engine.getSong(), track, slot), false, [this, slot] {
  4625. engine.capturePluginStates(); // (the plugins' current settings go with them)
  4626. int placed = -1;
  4627. engine.editSong ([t = track, slot, &placed] (Song& song) { placed = patcherize::patcherizeSlots (song, t, slot, false); });
  4628. if (placed >= 0)
  4629. selectedSlot = placed;
  4630. repaint();
  4631. });
  4632. menu.addItem (tr ("Patcherize all"), patcherize::slotsForAll (engine.getSong(), track).size() > 1, false, [this, slot] {
  4633. engine.capturePluginStates();
  4634. int placed = -1;
  4635. engine.editSong ([t = track, slot, &placed] (Song& song) { placed = patcherize::patcherizeSlots (song, t, slot, true); });
  4636. if (placed >= 0)
  4637. selectedSlot = placed;
  4638. repaint();
  4639. });
  4640. menu.addSeparator();
  4641. menu.addItem (tr ("Delete") + "\tDel", [this, slot] { deleteSlot (slot); });
  4642. // FL: with the slot's menu open, Delete removes the plugin (issue #11)
  4643. quickpick::showMenu (menu, juce::PopupMenu::Options().withTargetComponent (this).withMousePosition(), {},
  4644. [safe = juce::Component::SafePointer<EffectsPanel> (this), slot] (const juce::KeyPress& key) {
  4645. if (! key.isKeyCode (juce::KeyPress::deleteKey) || safe == nullptr)
  4646. return false;
  4647. juce::MessageManager::callAsync ([safe, slot] {
  4648. if (safe != nullptr)
  4649. safe->deleteSlot (slot);
  4650. });
  4651. return true;
  4652. });
  4653. }
  4654. void EffectsPanel::deleteSlot (int slot)
  4655. {
  4656. const auto* s = slots();
  4657. if (s == nullptr || slot < 0 || slot >= (int) s->size())
  4658. return;
  4659. engine.editSongStructural ([t = track, slot] (Song& song) { mixerops::removeEffectKeepRows (song, t, slot); }); // (FL: the slot stays empty)
  4660. selectedSlot = juce::jmin (slot, (int) slots()->size() - 1);
  4661. repaint();
  4662. }
  4663. void EffectsPanel::changeListenerCallback (juce::ChangeBroadcaster*)
  4664. {
  4665. const auto* s = slots();
  4666. if (s == nullptr)
  4667. track = 0;
  4668. else if (selectedSlot >= (int) s->size())
  4669. selectedSlot = (int) s->size() - 1;
  4670. refit(); // the clean mixer (round 163) changes the height the panel needs
  4671. repaint();
  4672. }
  4673. // ---------------------------------------------------------------------------
  4674. namespace mixerinput
  4675. {
  4676. std::function<void()> openAudioSettings;
  4677. namespace
  4678. {
  4679. juce::String issueText (const AudioEngine::RecordingNotice& notice)
  4680. {
  4681. using I = AudioEngine::InputIssue;
  4682. switch (notice.issue)
  4683. {
  4684. case I::noDevice: return tr ("No audio device is open. Choose one in Settings > Audio.");
  4685. case I::noInputDevice:
  4686. return tr ("No audio input device was found. Connect a microphone or an audio interface, then choose it as the input device in Settings > Audio.");
  4687. case I::noInputOpen: return tr ("No audio input is open, so nothing can be recorded. Choose an input device in Settings > Audio.");
  4688. case I::armedWithoutInput:
  4689. return tr ("Please select an audio input first: the armed insert has none. Click the input box above the insert's effect slots in the Mixer.");
  4690. case I::insertWithoutInput: return tr ("Insert {0} is armed but has no audio input, so it records nothing.", { juce::String (notice.track) });
  4691. case I::failed: return tr ("The audio input could not be used: {0}", { notice.detail });
  4692. case I::lowDisk:
  4693. return tr ("The recordings drive is almost full: about {0} minute(s) of recording left. Free some space or choose another project folder.",
  4694. { notice.detail });
  4695. case I::recordSafe:
  4696. return tr ("Insert {0} is record safe, so it can't be armed. Click its input box and turn \"Record safe\" off first.",
  4697. { juce::String (notice.track) });
  4698. case I::framesLost:
  4699. return tr ("The disk could not keep up while recording: {0} sample(s) became silence (the timing of the take was kept). "
  4700. "Record to a faster drive or close other programs that use the disk.", { notice.detail });
  4701. case I::none: break;
  4702. }
  4703. return {};
  4704. }
  4705. bool aboutTheDevice (AudioEngine::InputIssue issue)
  4706. {
  4707. using I = AudioEngine::InputIssue;
  4708. return issue == I::noDevice || issue == I::noInputDevice || issue == I::noInputOpen || issue == I::failed;
  4709. }
  4710. } // namespace
  4711. void explain (const AudioEngine::RecordingNotice& notice)
  4712. {
  4713. if (notice.issue == AudioEngine::InputIssue::none)
  4714. return;
  4715. using I = AudioEngine::InputIssue;
  4716. const auto aboutRecording = notice.issue == I::lowDisk || notice.issue == I::recordSafe || notice.issue == I::framesLost;
  4717. auto options = juce::MessageBoxOptions()
  4718. .withIconType (juce::MessageBoxIconType::WarningIcon)
  4719. .withTitle (aboutRecording ? tr ("Recording") : tr ("Audio input needed"))
  4720. .withMessage (issueText (notice));
  4721. if (aboutTheDevice (notice.issue) && openAudioSettings)
  4722. {
  4723. options = options.withButton (tr ("Audio settings...")).withButton (tr ("Close"));
  4724. juce::AlertWindow::showAsync (options, [] (int result) {
  4725. if (result == 1 && openAudioSettings)
  4726. openAudioSettings();
  4727. });
  4728. }
  4729. else
  4730. juce::AlertWindow::showAsync (options.withButton (tr ("OK")), nullptr);
  4731. }
  4732. // Round 157 ([DATA] the 0.1.15 projects of a singer who found that "the effects do nothing" on her voice): her
  4733. // microphone was the input of both Insert 1 (with the effects) and the Master. The Master plays its input straight
  4734. // away, without any insert's effects, so the dry voice covered the processed one. When an input is chosen and the
  4735. // Master plays the same device channel as an insert, LYNX says so and offers to take it off the Master.
  4736. void warnDoubleMonitoring (AudioEngine& engine, int track)
  4737. {
  4738. const auto& mixer = engine.getSong().mixer;
  4739. if (mixer.empty() || track < 0 || track >= (int) mixer.size())
  4740. return;
  4741. auto channels = [] (const MixerTrack& t) {
  4742. std::pair<int, int> r { t.inputChannel, t.inputChannel + (t.inputStereo ? 1 : 0) };
  4743. return r;
  4744. };
  4745. auto overlaps = [&] (const MixerTrack& a, const MixerTrack& b) {
  4746. if (a.inputChannel < 0 || b.inputChannel < 0)
  4747. return false;
  4748. const auto [a0, a1] = channels (a);
  4749. const auto [b0, b1] = channels (b);
  4750. return a0 <= b1 && b0 <= a1;
  4751. };
  4752. const auto& master = mixer[0];
  4753. if (master.inputChannel < 0 || master.monitor == InputMonitor::off)
  4754. return;
  4755. int insert = -1;
  4756. for (int t = 1; t < (int) mixer.size() && insert < 0; ++t)
  4757. if ((track == 0 || t == track) && overlaps (master, mixer[(std::size_t) t]))
  4758. insert = t;
  4759. if (insert < 0)
  4760. return;
  4761. const auto name = juce::String::fromUTF8 (mixer[(std::size_t) insert].name.c_str());
  4762. auto options = juce::MessageBoxOptions()
  4763. .withIconType (juce::MessageBoxIconType::WarningIcon)
  4764. .withTitle (tr ("The same input plays twice"))
  4765. .withMessage (tr ("This audio input is the input of the Master and of {0}. The Master plays it straight away, without "
  4766. "{0}'s effects, so you hear the dry sound on top of the processed one (the effects seem to do nothing).\n\n"
  4767. "To hear it through {0}'s effects, take it off the Master.", { name.isNotEmpty() ? name : tr ("Insert {0}", { juce::String (insert) }) }))
  4768. .withButton (tr ("Take it off the Master"))
  4769. .withButton (tr ("Keep both"));
  4770. juce::AlertWindow::showAsync (options, [&engine] (int result) {
  4771. if (result == 1)
  4772. engine.setInsertInput (0, -1, true);
  4773. });
  4774. }
  4775. void showMenu (AudioEngine& engine, int track, juce::Component* target, std::function<void()> chosen)
  4776. {
  4777. if (track < 0 || track >= (int) engine.getSong().mixer.size())
  4778. return;
  4779. // the device input opens on demand (only then does Windows show the microphone as in use)
  4780. if (! engine.hasAudioInput())
  4781. if (const auto result = engine.openAudioInput(); result.issue != AudioEngine::InputIssue::none)
  4782. {
  4783. explain (result);
  4784. return;
  4785. }
  4786. const auto& mt = engine.getSong().mixer[(std::size_t) track];
  4787. const auto names = engine.getInputChannelNames();
  4788. juce::PopupMenu menu;
  4789. menu.addSectionHeader (tr ("Audio input source"));
  4790. menu.addItem (tr ("(none)"), true, mt.inputChannel < 0, [&engine, track] { engine.setInsertInput (track, -1, true); });
  4791. const auto sources = inputSources (names);
  4792. if (sources.empty())
  4793. menu.addItem (tr ("The audio device has no open input channels"), false, false, nullptr);
  4794. for (const auto& source : sources)
  4795. {
  4796. if (! source.stereo && source.channel == 0 && names.size() > 1)
  4797. menu.addSeparator(); // pairs, then single channels
  4798. const auto ticked = mt.inputChannel == source.channel && mt.inputStereo == source.stereo;
  4799. menu.addItem (juce::String::fromUTF8 (source.name.c_str()) + (source.stereo ? "" : " " + tr ("(mono)")), true, ticked,
  4800. [&engine, track, source, chosen] {
  4801. engine.setInsertInput (track, source.channel, source.stereo);
  4802. warnDoubleMonitoring (engine, track);
  4803. if (chosen)
  4804. chosen();
  4805. });
  4806. }
  4807. if (track > 0) // FL's "Record" positions (round 168x, issue #41; FL's AudioRecorderRoutingMenu, in its order)
  4808. {
  4809. menu.addSectionHeader (tr ("Record"));
  4810. const std::pair<RecordSource, const char*> points[] = { { RecordSource::externalInput, TR_NOOP ("External input only") },
  4811. { RecordSource::externalAndMixer, TR_NOOP ("External and mixer input") },
  4812. { RecordSource::postEffects, TR_NOOP ("Post effects") },
  4813. { RecordSource::postEq, TR_NOOP ("Post EQ") },
  4814. { RecordSource::postLevel, TR_NOOP ("Post level and panning") },
  4815. { RecordSource::postTrack, TR_NOOP ("Post track") } };
  4816. for (const auto& [point, label] : points)
  4817. menu.addItem (tr (label), true, mt.recordSource == point, [&engine, track, point = point] { engine.setInsertRecordSource (track, point); });
  4818. // LYNX extra: the dry device input as a second take beside a processed one (DI + amp, for re-amping)
  4819. menu.addItem (tr ("Also record the dry input as a second take (LYNX)"), mt.recordSource != RecordSource::externalInput,
  4820. mt.recordDryToo && mt.recordSource != RecordSource::externalInput,
  4821. [&engine, track, on = mt.recordDryToo] { engine.setInsertRecordDryToo (track, ! on); });
  4822. }
  4823. menu.addSectionHeader (tr ("Monitor external input"));
  4824. const std::pair<InputMonitor, const char*> modes[] = { { InputMonitor::off, TR_NOOP ("Off") },
  4825. { InputMonitor::whenArmed, TR_NOOP ("When armed") },
  4826. { InputMonitor::automatic, TR_NOOP ("Auto (when armed, not while playing back)") },
  4827. { InputMonitor::on, TR_NOOP ("On") } };
  4828. for (const auto& [mode, label] : modes)
  4829. {
  4830. // the Master has no record arm: its input plays unless monitoring is off
  4831. if (track == 0 && (mode == InputMonitor::whenArmed || mode == InputMonitor::automatic))
  4832. continue;
  4833. const auto ticked = track == 0 ? (mode == InputMonitor::off) == (mt.monitor == InputMonitor::off) : mt.monitor == mode;
  4834. menu.addItem (tr (label), true, ticked, [&engine, track, mode = mode] { engine.setInsertMonitor (track, mode); });
  4835. }
  4836. if (track > 0) // record safe (round 163): the insert can't be armed by accident
  4837. {
  4838. menu.addSeparator();
  4839. menu.addItem (tr ("Record safe (can't be armed)"), true, mt.recordSafe,
  4840. [&engine, track, safe = mt.recordSafe] { engine.setInsertRecordSafe (track, ! safe); });
  4841. }
  4842. menu.addSeparator();
  4843. menu.addItem (tr ("Audio settings (input device)..."), openAudioSettings != nullptr, false, [] {
  4844. if (openAudioSettings)
  4845. openAudioSettings();
  4846. });
  4847. auto options = juce::PopupMenu::Options();
  4848. if (target != nullptr)
  4849. options = options.withTargetComponent (target).withMousePosition();
  4850. menu.showMenuAsync (options);
  4851. }
  4852. juce::String armHint (const AudioEngine& engine, int track)
  4853. {
  4854. auto text = tr ("Record arm: Rec + Play records this insert into a Playlist clip [RMB] record to a file");
  4855. if (track <= 0 || track >= (int) engine.getSong().mixer.size())
  4856. return text;
  4857. // FL's hint names the position: "Recording: Post EQ" (round 168x; changed in the input box's menu)
  4858. static const char* const points[] { TR_NOOP ("External input only"), TR_NOOP ("External and mixer input"), TR_NOOP ("Post effects"),
  4859. TR_NOOP ("Post EQ"), TR_NOOP ("Post level and panning"), TR_NOOP ("Post track") };
  4860. const auto& mt = engine.getSong().mixer[(std::size_t) track];
  4861. text = tr ("Recording: {0}", { tr (points[juce::jlimit (0, 5, (int) mt.recordSource)]) })
  4862. + (mt.recordDryToo && mt.recordSource != RecordSource::externalInput ? " + " + tr ("dry input") : juce::String()) + " " + text;
  4863. if (mt.recordTo.empty())
  4864. return text;
  4865. const auto file = juce::File (juce::String::fromUTF8 (engine.getSong().mixer[(std::size_t) track].recordTo.c_str()));
  4866. return tr ("Record to: {0}", { file.getFileName() }) + " " + text;
  4867. }
  4868. void chooseRecordTo (AudioEngine& engine, int track)
  4869. {
  4870. if (track <= 0 || track >= (int) engine.getSong().mixer.size())
  4871. return;
  4872. if (engine.getSong().mixer[(std::size_t) track].recordSafe)
  4873. {
  4874. AudioEngine::RecordingNotice notice;
  4875. notice.issue = AudioEngine::InputIssue::recordSafe;
  4876. notice.track = track;
  4877. explain (notice);
  4878. return;
  4879. }
  4880. const auto insert = juce::String::fromUTF8 (mixerops::insertDisplayName (engine.getSong(), track).c_str());
  4881. const auto& current = engine.getSong().mixer[(std::size_t) track].recordTo;
  4882. juce::File initial;
  4883. if (! current.empty() && juce::File::isAbsolutePath (juce::String::fromUTF8 (current.c_str())))
  4884. initial = juce::File (juce::String::fromUTF8 (current.c_str()));
  4885. else
  4886. {
  4887. // FL's default: Audio\Recorded, "<project title>_YYYY-MM-DD HH-MM-SS_<insert name>"
  4888. auto folder = engine.getRecordingFolder();
  4889. folder.createDirectory();
  4890. const auto now = juce::Time::getCurrentTime();
  4891. const auto name = juce::File::createLegalFileName (juce::String::fromUTF8 (
  4892. safety::recordingName (engine.getRecordingStem().toStdString(), now.getYear(), now.getMonth() + 1, now.getDayOfMonth(), now.getHours(),
  4893. now.getMinutes(), now.getSeconds(), insert.toStdString()).c_str()));
  4894. initial = folder.getChildFile (name + ".wav");
  4895. }
  4896. static std::unique_ptr<juce::FileChooser> chooser;
  4897. chooser = lynx::ui::makeFileChooser (tr ("Record {0} to", { insert }), initial, "*.wav");
  4898. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  4899. [&engine, track] (const juce::FileChooser& fc) {
  4900. auto file = fc.getResult();
  4901. if (file == juce::File() || track >= (int) engine.getSong().mixer.size())
  4902. return;
  4903. if (! file.hasFileExtension (".wav"))
  4904. file = file.withFileExtension (".wav");
  4905. engine.editSong ([track, path = file.getFullPathName().toStdString()] (Song& s) {
  4906. if (track < (int) s.mixer.size())
  4907. s.mixer[(std::size_t) track].recordTo = path;
  4908. });
  4909. if (! engine.isInsertArmed (track)) // FL arms it (and the insert gets selected)
  4910. toggleArm (engine, track, nullptr);
  4911. });
  4912. }
  4913. void toggleArm (AudioEngine& engine, int track, juce::Component* /*target*/)
  4914. {
  4915. if (track < 0 || track >= (int) engine.getSong().mixer.size())
  4916. return;
  4917. // FL 2026: arms at once, also without an input source (the recording start reports a missing input)
  4918. switch (armClick (track, engine.isInsertArmed (track)))
  4919. {
  4920. case ArmClick::none: return;
  4921. case ArmClick::disarm: engine.setInsertArmed (track, false); return;
  4922. case ArmClick::arm:
  4923. engine.setInsertArmed (track, true);
  4924. if (const auto notice = engine.takeRecordingNotice(); notice.issue != AudioEngine::InputIssue::none)
  4925. explain (notice);
  4926. return;
  4927. }
  4928. }
  4929. } // namespace mixerinput
  4930. // ---------------------------------------------------------------------------
  4931. MixerLayoutBox::MixerLayoutBox (MixerStrips& s)
  4932. : strips (s)
  4933. {
  4934. setTooltip (tr ("Mixer layout"));
  4935. setMouseCursor (juce::MouseCursor::PointingHandCursor);
  4936. }
  4937. juce::PopupMenu MixerLayoutBox::menu (MixerStrips& strips)
  4938. {
  4939. juce::PopupMenu m;
  4940. for (int i = 0; i < mixerlayout::layoutCount; ++i)
  4941. {
  4942. const auto l = (mixerlayout::Layout) i;
  4943. m.addItem (tr (juce::String (std::string (mixerlayout::nameOf (l)))), true, MixerStrips::layout == l,
  4944. [&strips, l] { strips.setLayout (l); });
  4945. if (mixerlayout::separatorAfter (l))
  4946. m.addSeparator();
  4947. }
  4948. return m;
  4949. }
  4950. void MixerLayoutBox::paint (juce::Graphics& g)
  4951. {
  4952. using namespace theme;
  4953. const auto hot = isMouseOverOrDragging();
  4954. auto box = getLocalBounds().toFloat().reduced (1.0f, 2.0f);
  4955. theme::fillRoundRect (g, box, radius::sm, hot ? colour::bg4 : colour::bg2);
  4956. g.setColour (hot ? colour::borderStrong : colour::border);
  4957. g.drawRoundedRectangle (box.reduced (0.5f), radius::sm, 1.0f);
  4958. // round 170e: the strips icon names what the box is (it showed only "Wide")
  4959. icons::draw (g, Icon::mixer, box.withWidth (24.0f).withSizeKeepingCentre (14.0f, 14.0f), hot ? colour::textPrimary : colour::textSecondary);
  4960. g.setColour (colour::accent);
  4961. g.setFont (font (type::small, true));
  4962. g.drawFittedText (tr (juce::String (std::string (mixerlayout::nameOf (MixerStrips::layout)))), getLocalBounds().reduced (8, 0).withTrimmedLeft (18).withTrimmedRight (14),
  4963. juce::Justification::centredLeft, 1, 0.8f);
  4964. icons::draw (g, Icon::chevronDown, box.removeFromRight (18.0f).withSizeKeepingCentre (12.0f, 12.0f), hot ? colour::textPrimary : colour::textSecondary);
  4965. }
  4966. void MixerLayoutBox::mouseDown (const juce::MouseEvent&)
  4967. {
  4968. menu (strips).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this));
  4969. }
  4970. MixerComponent::MixerComponent (AudioEngine& e)
  4971. : engine (e),
  4972. strips (e),
  4973. effects (e)
  4974. {
  4975. viewport.setViewedComponent (&strips, false);
  4976. viewport.setScrollBarsShown (false, true);
  4977. addAndMakeVisible (viewport);
  4978. effectsView.setViewedComponent (&effects, false);
  4979. effectsView.setScrollBarsShown (true, false);
  4980. effectsView.setScrollBarThickness (10);
  4981. addAndMakeVisible (effectsView);
  4982. strips.onSelectionChanged = [this] (int track) { effects.setTrack (track); };
  4983. strips.onEffectDropped = [this] (int track, EffectSlot fx) {
  4984. strips.selectTrack (track);
  4985. effects.setTrack (track);
  4986. if (! addEffectToSelected (std::move (fx)))
  4987. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin database"),
  4988. tr ("The selected insert has no free effect slot."));
  4989. else // FL opens the dropped effect's window (round 171c: the Plugin picker's drag is FL's Browser drag)
  4990. openSlotEditor (track, (int) engine.getSong().mixer[(std::size_t) track].effects.size() - 1);
  4991. };
  4992. strips.onInstrumentDropped = [this] (int track, ChannelDef c) {
  4993. selectTrack (track);
  4994. if (onInstrumentDropped != nullptr)
  4995. onInstrumentDropped (track, std::move (c));
  4996. };
  4997. effects.onInstrumentDropped = strips.onInstrumentDropped;
  4998. }
  4999. bool MixerComponent::runAction (const std::string& id)
  5000. {
  5001. if (id == "mixer.moveLeft")
  5002. strips.moveSelected (-1);
  5003. else if (id == "mixer.moveRight")
  5004. strips.moveSelected (1);
  5005. else if (id == "mixer.linkChannels")
  5006. strips.linkSelectedChannels (false);
  5007. else if (id == "mixer.linkChannelsFrom")
  5008. strips.linkSelectedChannels (true);
  5009. else if (id == "mixer.selectLinkedChannels")
  5010. strips.selectLinkedChannels();
  5011. else if (id == "mixer.rename") // FL's mixer menu keys (round 167k): the menu's own items
  5012. return strips.runMenuItem (tr ("Rename and color..."));
  5013. else if (id == "mixer.soloSelected")
  5014. return strips.runMenuItem (tr ("Solo selected track(s)"));
  5015. else if (id == "mixer.altSoloSelected")
  5016. return strips.runMenuItem (tr ("Alt solo selected track(s)"));
  5017. else if (id == "mixer.renderArmed")
  5018. return strips.runMenuItem (tr ("Render armed tracks to wave file(s)..."));
  5019. else if (id == "mixer.renderSelected")
  5020. return strips.runMenuItem (tr ("Render selected tracks to wave file(s)..."));
  5021. else if (id == "mixer.deleteEffect") // FL: Delete on the selected effect slot (issue #11)
  5022. effects.deleteSlot (effects.getSelectedSlot());
  5023. else
  5024. return false;
  5025. return true;
  5026. }
  5027. bool MixerComponent::loadPresetOnSelection (const juce::File& file)
  5028. {
  5029. return mixerpresets::loadOnTracks (engine, strips.getSelection(), file);
  5030. }
  5031. bool MixerComponent::addEffectToSelected (EffectSlot slot)
  5032. {
  5033. const auto t = strips.getSelectedTrack();
  5034. bool added = false;
  5035. engine.editSong ([t, &slot, &added] (Song& s) {
  5036. if (s.mixer.empty())
  5037. s.mixer = Song::defaultMixer (0);
  5038. if (t < (int) s.mixer.size() && (int) s.mixer[(std::size_t) t].effects.size() < maxEffectSlots)
  5039. {
  5040. s.mixer[(std::size_t) t].effects.push_back (std::move (slot));
  5041. added = true;
  5042. }
  5043. });
  5044. if (added)
  5045. {
  5046. effects.setTrack (t);
  5047. effects.selectSlot ((int) engine.getSong().mixer[(std::size_t) t].effects.size() - 1);
  5048. }
  5049. return added;
  5050. }
  5051. void MixerComponent::selectFirstTrackWithEffects()
  5052. {
  5053. const auto& mixer = engine.getSong().mixer;
  5054. for (int t = 0; t < (int) mixer.size(); ++t)
  5055. if (! mixer[(std::size_t) t].effects.empty())
  5056. {
  5057. strips.selectTrack (t);
  5058. return;
  5059. }
  5060. }
  5061. void MixerComponent::selectTrack (int track)
  5062. {
  5063. strips.selectTrack (track);
  5064. // scroll the strip into view
  5065. const auto t = strips.getSelectedTrack();
  5066. const auto x = strips.stripLeft (t);
  5067. const auto w = strips.widthOf (t);
  5068. const auto view = viewport.getViewArea();
  5069. if (x < view.getX() || x + w > view.getRight())
  5070. viewport.setViewPosition (juce::jmax (0, x - view.getWidth() / 2), 0);
  5071. }
  5072. void MixerComponent::resized()
  5073. {
  5074. auto area = getLocalBounds();
  5075. effectsView.setBounds (area.removeFromRight (effectsWidth));
  5076. effects.fitToView (effectsView.getWidth(), effectsView.getHeight(), effectsView.getScrollBarThickness());
  5077. viewport.setBounds (area);
  5078. strips.setVisibleHeight (area.getHeight() - viewport.getScrollBarThickness());
  5079. }
  5080. } // namespace lynx