MixerComponent.cpp 231 KB

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