ChannelSettings.cpp 389 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633
  1. #include <optional>
  2. #include "ui/WindowOwner.h"
  3. #include "core/NoteNames.h"
  4. #include "ui/ChannelSettings.h"
  5. #include "core/EditorScale.h"
  6. #include "core/FlControlMenus.h"
  7. #include "core/FlmDwSampler.h"
  8. #include "core/SamplerPage.h"
  9. #include "ui/NewtoneEditor.h"
  10. #include "ui/EditorTools.h"
  11. #include "ui/FileChoosers.h"
  12. #include "ui/Icons.h"
  13. #include "ui/WrapperMenu.h"
  14. #include "ui/LayerEditor.h"
  15. #include "ui/DanceView.h"
  16. #include "ui/Controllers164.h"
  17. #include "ui/VoltageEditor.h"
  18. #include "ui/AutomationUi.h"
  19. #include "ui/BrowserComponent.h"
  20. #include "core/MixerOps.h"
  21. #include "core/ClipOps.h"
  22. #include "core/TempoDetect.h"
  23. #include "ui/AudioClipboard.h"
  24. #include "ui/AudioEditor.h"
  25. #include "ui/TempoDetectionDialog.h"
  26. #include <cstring>
  27. #include <functional>
  28. #include "core/DrumSynthLive.h"
  29. #include "core/FlSynths.h"
  30. #include "core/FlKeys.h"
  31. #include "core/ChannelMiscFx.h"
  32. #include "core/FlpImport.h"
  33. #include "core/Harmor.h"
  34. #include "core/HarmorControls.h"
  35. #include "core/Gms.h"
  36. #include "core/MiniSynth.h"
  37. #include "core/SimSynth.h"
  38. #include "core/Drumaxx.h"
  39. #include "core/DrumControls.h"
  40. #include <map>
  41. #include "core/Granulizer.h"
  42. #include "core/Morphine.h"
  43. #include "core/Ogun.h"
  44. #include "core/Dx10.h"
  45. #include "core/Kepler.h"
  46. #include "core/PoiZone.h"
  47. #include "core/LynxBanks.h"
  48. #include "core/ModelParams.h"
  49. #include "core/SynthParams.h"
  50. #include "core/BassDrum.h"
  51. #include "core/FruitKick.h"
  52. #include "core/Toxic.h"
  53. #include "core/ThreeOsc.h"
  54. #include "core/BeepMap.h"
  55. #include "core/Sawer.h"
  56. #include "core/TransistorBass.h"
  57. #include "core/Slayer.h"
  58. #include "core/SytrusEngine.h"
  59. #include "core/SynthPresets.h"
  60. #include "core/PluginLayout.h"
  61. #include "engine/SampleLibrary.h"
  62. #include "engine/Text.h"
  63. #include "core/RackOps.h"
  64. #include "core/NativeEngines.h"
  65. #include "core/PresetCycle.h"
  66. #include "core/GeneratorPresets.h"
  67. #include "ui/GeneratorPresetMenu.h"
  68. #include "ui/ControllerEditors.h"
  69. #include "ui/HintBar.h"
  70. #include "ui/ValueControl.h"
  71. #include "ui/I18n.h"
  72. #include "ui/PluginSkin.h"
  73. #include "ui/Theme.h"
  74. #include "ui/WaveformView.h"
  75. #include "ui/SoundFontEditor.h"
  76. #include "ui/VfxEditors.h"
  77. #include "ui/VideoPlayerView.h"
  78. #include "ui/WaveTravellerEditor.h"
  79. #include "ui/DirectWaveEditor.h"
  80. #include "ui/FpcEditor.h"
  81. #include "ui/TetraEditor.h"
  82. #include "ui/HelixEditor.h"
  83. #include "ui/FruitySlicerEditor.h"
  84. #include "ui/FlVoicePanel.h"
  85. #include "core/FruitySlicer.h"
  86. #include "ui/SlicexEditor.h"
  87. #include "platform/FileTypes.h"
  88. #include "ui/BrowserComponent.h"
  89. #include "engine/SampleLibrary.h"
  90. #include "core/SampleFiles.h"
  91. #include "core/ProjectContents.h"
  92. namespace lynx
  93. {
  94. namespace
  95. {
  96. // Which channel a page edits (round 164f): a Channel Rack channel, or the generator of a Patcher node found through
  97. // `locate` (index −1) — the same pages edit both, so a node opens the editor its engine has on a channel.
  98. struct ChannelRef
  99. {
  100. std::function<ChannelDef* (Song&)> locate;
  101. int index = -1; // the Channel Rack index (automation targets, its windows); −1 = a Patcher node
  102. static ChannelRef rack (int c)
  103. {
  104. return { [c] (Song& s) -> ChannelDef* { return c >= 0 && c < (int) s.channels.size() ? &s.channels[(std::size_t) c] : nullptr; }, c };
  105. }
  106. const ChannelDef* get (const AudioEngine& engine) const { return locate ? locate (const_cast<Song&> (engine.getSong())) : nullptr; }
  107. void edit (AudioEngine& engine, std::function<void (ChannelDef&)> change, bool undoable = true) const
  108. {
  109. engine.editSong ([l = locate, change = std::move (change)] (Song& s) {
  110. if (auto* d = l ? l (s) : nullptr)
  111. change (*d);
  112. }, undoable);
  113. }
  114. };
  115. void showModulationFor (juce::Component& from, AudioEngine& engine, int channel);
  116. // Cutoff and pitch envelopes (FL's channel envelopes), used by the synth and the sampler.
  117. class ModEnvelopeEditor final : public juce::Component
  118. {
  119. public:
  120. std::function<void()> onChange;
  121. static constexpr int preferredHeight = 16 + 2 * 62;
  122. ModEnvelopeEditor()
  123. {
  124. const juce::String titles[] = { tr ("Cutoff env."), tr ("Pitch env.") };
  125. for (int e = 0; e < 2; ++e)
  126. {
  127. auto& row = rows[(std::size_t) e];
  128. row.title.setText (titles[e], juce::dontSendNotification);
  129. row.title.setFont (theme::font (theme::type::small));
  130. addAndMakeVisible (row.title);
  131. knob (row.amount, e == 0 ? -10.0 : -48.0, e == 0 ? 10.0 : 48.0, 0.01, e == 0 ? " oct" : " st");
  132. row.amount.setDoubleClickReturnValue (true, 0.0);
  133. row.amount.setTooltip (tr ("0 = off"));
  134. for (auto* s : { &row.attack, &row.hold, &row.decay, &row.release })
  135. {
  136. knob (*s, 0.0, 10.0, 0.001, " s");
  137. s->setSkewFactorFromMidPoint (0.5);
  138. }
  139. knob (row.sustain, 0.0, 1.0, 0.01, "");
  140. }
  141. const char* names[] = { TR_NOOP ("Amount"), TR_NOOP ("Attack"), TR_NOOP ("Hold"), TR_NOOP ("Decay"), TR_NOOP ("Sustain"), TR_NOOP ("Release") };
  142. for (int i = 0; i < 6; ++i)
  143. {
  144. labels[(std::size_t) i].setText (tr (names[i]), juce::dontSendNotification);
  145. labels[(std::size_t) i].setJustificationType (juce::Justification::centred);
  146. labels[(std::size_t) i].setFont (theme::font (theme::type::caption));
  147. addAndMakeVisible (labels[(std::size_t) i]);
  148. }
  149. }
  150. void resized() override
  151. {
  152. auto area = getLocalBounds();
  153. auto header = area.removeFromTop (16);
  154. header.removeFromLeft (80);
  155. const auto w = header.getWidth() / 6;
  156. for (auto& l : labels)
  157. l.setBounds (header.removeFromLeft (w));
  158. for (auto& row : rows)
  159. {
  160. auto line = area.removeFromTop (62);
  161. row.title.setBounds (line.removeFromLeft (80).withSizeKeepingCentre (80, 24));
  162. for (auto* s : { &row.amount, &row.attack, &row.hold, &row.decay, &row.sustain, &row.release })
  163. s->setBounds (line.removeFromLeft (w));
  164. }
  165. }
  166. void show (const ModEnvelope& filter, const ModEnvelope& pitch)
  167. {
  168. rows[0].show (filter);
  169. rows[1].show (pitch);
  170. }
  171. ModEnvelope filter() const { return rows[0].read(); }
  172. ModEnvelope pitch() const { return rows[1].read(); }
  173. private:
  174. struct Row
  175. {
  176. juce::Label title;
  177. juce::Slider amount, attack, hold, decay, sustain, release;
  178. void show (const ModEnvelope& e)
  179. {
  180. amount.setValue (e.amount, juce::dontSendNotification);
  181. attack.setValue (e.attack, juce::dontSendNotification);
  182. hold.setValue (e.hold, juce::dontSendNotification);
  183. decay.setValue (e.decay, juce::dontSendNotification);
  184. sustain.setValue (e.sustain, juce::dontSendNotification);
  185. release.setValue (e.release, juce::dontSendNotification);
  186. }
  187. ModEnvelope read() const
  188. {
  189. return { (float) amount.getValue(), (float) attack.getValue(), (float) hold.getValue(),
  190. (float) decay.getValue(), (float) sustain.getValue(), (float) release.getValue() };
  191. }
  192. };
  193. void knob (juce::Slider& s, double lo, double hi, double step, const char* suffix)
  194. {
  195. s.setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  196. s.setTextBoxStyle (juce::Slider::TextBoxBelow, false, 64, 16);
  197. // round 170j: the plugin kit's knobs in LYNX Synth's own art ("the LYNX lab"), or the forced plugin style
  198. s.getProperties().set (skin::sliderProperty, (juce::int64) skin::artAccent (skin::Art::lynxSynth).getARGB());
  199. s.getProperties().set (skin::styleProperty, skin::packStyle (skin::Style::themed, skin::Art::lynxSynth));
  200. s.setRange (lo, hi, step);
  201. s.setTextValueSuffix (suffix);
  202. s.onValueChange = [this] {
  203. if (onChange)
  204. onChange();
  205. };
  206. addAndMakeVisible (s);
  207. }
  208. std::array<Row, 2> rows;
  209. std::array<juce::Label, 6> labels;
  210. };
  211. // Channel LFOs (pan, volume, cutoff, pitch), like FL's.
  212. class LfoEditor final : public juce::Component
  213. {
  214. public:
  215. std::function<void()> onChange;
  216. static constexpr int preferredHeight = 18 + lfoTargets * 60;
  217. LfoEditor()
  218. {
  219. const juce::String titles[] = { tr ("Pan LFO"), tr ("Volume LFO"), tr ("Cutoff LFO"), tr ("Pitch LFO") };
  220. const double amountRange[] = { 1.0, 1.0, 8.0, 24.0 };
  221. const char* amountSuffix[] = { "", "", " oct", " st" };
  222. for (int i = 0; i < lfoTargets; ++i)
  223. {
  224. auto& row = rows[(std::size_t) i];
  225. row.title.setText (titles[i], juce::dontSendNotification);
  226. row.title.setFont (theme::font (theme::type::small));
  227. addAndMakeVisible (row.title);
  228. knob (row.amount, -amountRange[i], amountRange[i], 0.01, amountSuffix[i]);
  229. row.amount.setDoubleClickReturnValue (true, 0.0);
  230. row.amount.setTooltip (tr ("0 = off"));
  231. knob (row.period, 0.01, 16.0, 0.001, "");
  232. row.period.setSkewFactorFromMidPoint (0.5);
  233. knob (row.delay, 0.0, 8.0, 0.001, "");
  234. row.delay.setSkewFactorFromMidPoint (0.5);
  235. knob (row.attack, 0.0, 8.0, 0.001, "");
  236. row.attack.setSkewFactorFromMidPoint (0.5);
  237. row.shape.addItemList ({ tr ("Sine"), tr ("Triangle"), tr ("Pulse") }, 1);
  238. row.shape.onChange = [this] { changed(); };
  239. addAndMakeVisible (row.shape);
  240. row.sync.setButtonText (tr ("Beats"));
  241. row.sync.setTooltip (tr ("Period, delay and fade-in in beats (follows the BPM) instead of seconds"));
  242. row.sync.onClick = [this] { changed(); };
  243. addAndMakeVisible (row.sync);
  244. row.global.setButtonText (tr ("Global"));
  245. row.global.setTooltip (tr ("Phase follows the song position instead of restarting on each note"));
  246. row.global.onClick = [this] { changed(); };
  247. addAndMakeVisible (row.global);
  248. }
  249. const juce::String headers[] = { tr ("Amount"), tr ("Period"), tr ("Shape"), tr ("Delay"), tr ("Fade-in"), tr ("Unit") };
  250. for (int i = 0; i < 6; ++i)
  251. {
  252. labels[(std::size_t) i].setText (headers[i], juce::dontSendNotification);
  253. labels[(std::size_t) i].setJustificationType (juce::Justification::centred);
  254. labels[(std::size_t) i].setFont (theme::font (theme::type::caption));
  255. addAndMakeVisible (labels[(std::size_t) i]);
  256. }
  257. }
  258. void resized() override
  259. {
  260. auto area = getLocalBounds();
  261. auto header = area.removeFromTop (18);
  262. header.removeFromLeft (80);
  263. const auto w = header.getWidth() / 6;
  264. for (auto& l : labels)
  265. l.setBounds (header.removeFromLeft (w));
  266. for (auto& row : rows)
  267. {
  268. auto line = area.removeFromTop (60);
  269. row.title.setBounds (line.removeFromLeft (80).withSizeKeepingCentre (80, 24));
  270. row.amount.setBounds (line.removeFromLeft (w));
  271. row.period.setBounds (line.removeFromLeft (w));
  272. row.shape.setBounds (line.removeFromLeft (w).withSizeKeepingCentre (w - 6, 24));
  273. row.delay.setBounds (line.removeFromLeft (w));
  274. row.attack.setBounds (line.removeFromLeft (w));
  275. auto toggles = line.removeFromLeft (w).withSizeKeepingCentre (w - 6, 50);
  276. row.sync.setBounds (toggles.removeFromTop (24));
  277. row.global.setBounds (toggles.removeFromBottom (24));
  278. }
  279. }
  280. void show (const std::array<ChannelLfo, lfoTargets>& lfo)
  281. {
  282. for (std::size_t i = 0; i < lfoTargets; ++i)
  283. {
  284. auto& row = rows[i];
  285. const auto& l = lfo[i];
  286. row.amount.setValue (l.amount, juce::dontSendNotification);
  287. row.period.setValue (l.period, juce::dontSendNotification);
  288. row.delay.setValue (l.delay, juce::dontSendNotification);
  289. row.attack.setValue (l.attack, juce::dontSendNotification);
  290. row.shape.setSelectedId (l.shape + 1, juce::dontSendNotification);
  291. row.sync.setToggleState (l.sync, juce::dontSendNotification);
  292. row.global.setToggleState (l.global, juce::dontSendNotification);
  293. const auto unit = l.sync ? " t" : " s";
  294. for (auto* s : { &row.period, &row.delay, &row.attack })
  295. s->setTextValueSuffix (unit);
  296. }
  297. }
  298. std::array<ChannelLfo, lfoTargets> read() const
  299. {
  300. std::array<ChannelLfo, lfoTargets> lfo {};
  301. for (std::size_t i = 0; i < lfoTargets; ++i)
  302. {
  303. const auto& row = rows[i];
  304. lfo[i] = { (float) row.amount.getValue(), (float) row.period.getValue(), row.sync.getToggleState(),
  305. juce::jlimit (0, 2, row.shape.getSelectedId() - 1), (float) row.delay.getValue(), (float) row.attack.getValue(),
  306. row.global.getToggleState() };
  307. }
  308. return lfo;
  309. }
  310. private:
  311. struct Row
  312. {
  313. juce::Label title;
  314. juce::Slider amount, period, delay, attack;
  315. juce::ComboBox shape;
  316. juce::ToggleButton sync, global;
  317. };
  318. void knob (juce::Slider& s, double lo, double hi, double step, const char* suffix)
  319. {
  320. s.setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  321. s.setTextBoxStyle (juce::Slider::TextBoxBelow, false, 64, 16);
  322. // round 170j: the plugin kit's knobs in LYNX Synth's own art ("the LYNX lab"), or the forced plugin style
  323. s.getProperties().set (skin::sliderProperty, (juce::int64) skin::artAccent (skin::Art::lynxSynth).getARGB());
  324. s.getProperties().set (skin::styleProperty, skin::packStyle (skin::Style::themed, skin::Art::lynxSynth));
  325. s.setRange (lo, hi, step);
  326. s.setTextValueSuffix (suffix);
  327. s.onValueChange = [this] { changed(); };
  328. addAndMakeVisible (s);
  329. }
  330. void changed()
  331. {
  332. if (onChange)
  333. onChange();
  334. }
  335. std::array<Row, lfoTargets> rows;
  336. std::array<juce::Label, 6> labels;
  337. };
  338. // Channel modulation window: cutoff/pitch envelopes and LFOs of the synth or the sampler.
  339. class ModulationPanel final : public juce::Component,
  340. private juce::ChangeListener
  341. {
  342. public:
  343. ModulationPanel (AudioEngine& e, ChannelRef c)
  344. : engine (e),
  345. ref (std::move (c))
  346. {
  347. envelopes.onChange = [this] { apply(); };
  348. lfos.onChange = [this] { apply(); };
  349. addAndMakeVisible (envelopes);
  350. addAndMakeVisible (lfos);
  351. refresh();
  352. engine.addChangeListener (this);
  353. setSize (660, 20 + ModEnvelopeEditor::preferredHeight + 16 + LfoEditor::preferredHeight);
  354. }
  355. ~ModulationPanel() override { engine.removeChangeListener (this); }
  356. void resized() override
  357. {
  358. auto area = getLocalBounds().reduced (10);
  359. envelopes.setBounds (area.removeFromTop (ModEnvelopeEditor::preferredHeight));
  360. area.removeFromTop (16);
  361. lfos.setBounds (area.removeFromTop (LfoEditor::preferredHeight));
  362. }
  363. int getChannel() const noexcept { return ref.index; }
  364. private:
  365. const ChannelDef* current() const
  366. {
  367. return ref.get (engine);
  368. }
  369. bool isSynth() const { return current() != nullptr && current()->instrument == InstrumentKind::synth; }
  370. void refresh()
  371. {
  372. const auto* c = current();
  373. if (c == nullptr)
  374. return;
  375. if (isSynth())
  376. {
  377. envelopes.show (c->synth.filterEnv, c->synth.pitchEnv);
  378. lfos.show (c->synth.lfo);
  379. }
  380. else
  381. {
  382. envelopes.show (c->sampler.filterEnv, c->sampler.pitchEnv);
  383. lfos.show (c->sampler.lfo);
  384. }
  385. // only its own window: as a tab of the channel's window it left that window titled "Modulation - ..." while the
  386. // Sampler page showed (issue #12)
  387. // (round 190he: the window's content is the scaled holder around this page)
  388. if (auto* w = findParentComponentOfClass<juce::DocumentWindow>();
  389. w != nullptr && (w->getContentComponent() == this
  390. || (getParentComponent() == w->getContentComponent() && getParentComponent() != nullptr
  391. && (bool) getParentComponent()->getProperties().getWithDefault ("lynxScaledContent", false))))
  392. w->setName (tr ("Modulation - {0}", { juce::String::fromUTF8 (c->name.c_str()) }));
  393. }
  394. void apply()
  395. {
  396. if (current() == nullptr)
  397. return;
  398. const auto filter = envelopes.filter(), pitch = envelopes.pitch();
  399. const auto lfo = lfos.read();
  400. const auto synth = isSynth();
  401. ref.edit (engine, [synth, filter, pitch, lfo] (ChannelDef& channelDef) {
  402. auto& ch = channelDef;
  403. if (synth)
  404. {
  405. ch.synth.filterEnv = filter;
  406. ch.synth.pitchEnv = pitch;
  407. ch.synth.lfo = lfo;
  408. }
  409. else
  410. {
  411. ch.sampler.filterEnv = filter;
  412. ch.sampler.pitchEnv = pitch;
  413. ch.sampler.lfo = lfo;
  414. }
  415. });
  416. }
  417. void changeListenerCallback (juce::ChangeBroadcaster*) override { refresh(); }
  418. AudioEngine& engine;
  419. ChannelRef ref;
  420. ModEnvelopeEditor envelopes;
  421. LfoEditor lfos;
  422. };
  423. // A Sampler knob: right-click opens its automation menu instead of moving it (issue #12)
  424. class MenuSlider final : public juce::Slider
  425. {
  426. public:
  427. std::function<void()> onMenu;
  428. void mouseDown (const juce::MouseEvent& e) override
  429. {
  430. menuClick = e.mods.isPopupMenu() && onMenu != nullptr;
  431. if (menuClick)
  432. onMenu();
  433. else
  434. juce::Slider::mouseDown (e);
  435. }
  436. void mouseDrag (const juce::MouseEvent& e) override
  437. {
  438. if (! menuClick)
  439. juce::Slider::mouseDrag (e);
  440. }
  441. void mouseUp (const juce::MouseEvent& e) override
  442. {
  443. if (! menuClick)
  444. juce::Slider::mouseUp (e);
  445. menuClick = false;
  446. }
  447. private:
  448. bool menuClick = false;
  449. };
  450. // Physical-model channels (Sakura, Drumpad; REA_rodada28): knobs for the main raw FL parameters (0..1)
  451. class ModelPanel final : public juce::Component,
  452. public juce::TooltipClient,
  453. public juce::DragAndDropTarget,
  454. public juce::FileDragAndDropTarget,
  455. private juce::ChangeListener,
  456. private juce::Timer
  457. {
  458. public:
  459. ModelPanel (AudioEngine& e, ChannelRef c)
  460. : engine (e),
  461. ref (std::move (c))
  462. {
  463. static const ChannelDef none;
  464. const auto* found = ref.get (engine);
  465. const auto& def = found != nullptr ? *found : none;
  466. sakura = def.instrument == InstrumentKind::sakura;
  467. boobass = def.instrument == InstrumentKind::boobass;
  468. drumsynth = def.instrument == InstrumentKind::drumsynth;
  469. harmless = def.instrument == InstrumentKind::harmless;
  470. harmor = def.instrument == InstrumentKind::harmor;
  471. gms = def.instrument == InstrumentKind::gms;
  472. morphine = def.instrument == InstrumentKind::morphine;
  473. autogun = def.instrument == InstrumentKind::autogun;
  474. transistorBass = def.instrument == InstrumentKind::transistorbass;
  475. transistorBassMobile = transistorBass && transistorBassIsFlm (def);
  476. ogun = def.instrument == InstrumentKind::ogun || autogun; // Autogun: Ogun's parameter layout (REA_rodada57)
  477. miniSynth = def.instrument == InstrumentKind::minisynth;
  478. dx10 = def.instrument == InstrumentKind::dx10;
  479. kepler = def.instrument == InstrumentKind::kepler;
  480. keplerExo = def.instrument == InstrumentKind::keplerExo;
  481. poizone = def.instrument == InstrumentKind::poizone;
  482. fruitkick = def.instrument == InstrumentKind::fruitkick;
  483. bassdrum = def.instrument == InstrumentKind::bassdrum;
  484. toxic = def.instrument == InstrumentKind::toxic;
  485. threeOsc = def.instrument == InstrumentKind::threeosc;
  486. simSynth = def.instrument == InstrumentKind::simsynth;
  487. wasp = def.instrument == InstrumentKind::wasp;
  488. plucked = def.instrument == InstrumentKind::plucked;
  489. beepMap = def.instrument == InstrumentKind::beepmap;
  490. sawer = def.instrument == InstrumentKind::sawer;
  491. flKeys = def.instrument == InstrumentKind::flkeys;
  492. granulizer = def.instrument == InstrumentKind::granulizer;
  493. drumaxx = def.instrument == InstrumentKind::drumaxx;
  494. slayer = def.instrument == InstrumentKind::slayer;
  495. fruityDance = def.instrument == InstrumentKind::fruitydance;
  496. pocketSuperSaw = def.instrument == InstrumentKind::pocketSuperSaw; // round 190by
  497. // round 168q: the engines that run FL's own files say so when this computer lacks them
  498. engineFilesMissing = ((kepler || keplerExo) && ! keplerDllUsable (def.samplePath))
  499. || (transistorBass && ! transistorBassIsFlm (def) && ! transistorBassDllUsable (def.samplePath)) // (FLM's build needs no file)
  500. || (sawer && sawerReadTable (def.samplePath).empty());
  501. sytrus = def.instrument == InstrumentKind::sytrus;
  502. // DrumSynth Live: the patch on the key selected in FL's editor (raw FL values)
  503. if (drumsynth)
  504. {
  505. if (lynx::drumSynthEditorKeyIndex < (int) def.modelParams.size())
  506. editorKey = (int) def.modelParams[(std::size_t) lynx::drumSynthEditorKeyIndex];
  507. if (drumSynthKeyToSlot (editorKey) < 0)
  508. editorKey = 60;
  509. wavesFound = ! def.samplePath.empty();
  510. }
  511. const auto offset = drumsynth ? drumSynthPatchParams * drumSynthKeyToSlot (editorKey) : 0;
  512. static const std::pair<int, const char*> sakuraKnobs[] = {
  513. { 0, "Master" }, { 1, "Tune" }, { 2, "Attack" }, { 3, "Decay" }, { 4, "Sustain" }, { 5, "Release" },
  514. { 6, "Str1 decay" }, { 9, "Str1 damp" }, { 11, "Str2 decay" }, { 14, "Str2 damp" }, { 16, "Saturation" },
  515. { 17, "String mix" }, { 18, "Stereo sep" }, { 19, "Comb ratio" }, { 22, "Comb level" }, { 24, "Lo-cut" },
  516. { 29, "Hi-cut" }, { 30, "Hi-cut res" }, { 31, "Noise level" }, { 32, "Noise rate" } };
  517. static const std::pair<int, const char*> drumpadKnobs[] = {
  518. { 2, "Mallet amp" }, { 3, "Mallet decay" }, { 4, "Mallet noise" }, { 6, "Decay" }, { 7, "Cutoff" },
  519. { 8, "Tension" }, { 9, "Phase" }, { 10, "Material" }, { 11, "Size" }, { 12, "Shape" }, { 13, "Low freq" },
  520. { 18, "Mid freq" }, { 19, "Mid level" }, { 24, "High freq" }, { 25, "High level" }, { 27, "Lo-fi" },
  521. { 28, "Hold" }, { 29, "Pitch" } };
  522. auto add = [&] (int index, const char* name, double low = 0.0, double high = -1.0) {
  523. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  524. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  525. index += offset;
  526. if (high > low)
  527. knob->setRange (low, high, 1.0);
  528. else
  529. knob->setRange (0.0, boobass ? 65535.0 : 1.0, boobass ? 1.0 : 0.001);
  530. knob->setValue (index < (int) def.modelParams.size() ? def.modelParams[(std::size_t) index] : 0.0, juce::dontSendNotification);
  531. knob->setName (name);
  532. knob->onValueChange = [this, index, k = knob.get()] {
  533. ref.edit (engine, [index, v = (float) k->getValue()] (ChannelDef& channelDef) {
  534. auto& params = channelDef.modelParams;
  535. if (index < (int) params.size())
  536. params[(std::size_t) index] = v;
  537. });
  538. };
  539. addAndMakeVisible (*knob);
  540. knobs.push_back (std::move (knob));
  541. };
  542. static const std::pair<int, const char*> booBassKnobs[] = { { 0, "Bass" }, { 1, "Mid" }, { 2, "Treble" } };
  543. struct Ranged { int index; const char* name; double low, high; };
  544. static const Ranged drumSynthKnobs[] = {
  545. { 0, "Level", 0, 128 }, { 1, "Pan", -64, 64 }, { 2, "Tone", -50, 50 }, { 3, "Harmonics", -50, 50 },
  546. { 4, "Osc1 freq", 0, 1000 }, { 7, "Osc1 decay", 0, 127 }, { 8, "Osc1 level", 0, 127 }, { 10, "Osc2 freq", 0, 1000 },
  547. { 13, "Osc2 decay", 0, 127 }, { 14, "Osc2 level", 0, 127 }, { 17, "Wave mix", 0, 127 }, { 21, "Release", 0, 127 },
  548. { 23, "Click", 0, 100 }, { 33, "Ring mod", 0, 127 } };
  549. // Harmless: raw FL values (REA_rodada21/32 ranges)
  550. static const Ranged harmlessKnobs[] = {
  551. { 36, "Volume", 0, 2000 }, { 26, "Attack", 0, 1000 }, { 27, "Decay", 0, 1000 }, { 28, "Release", 0, 1000 },
  552. { 54, "Cutoff", 0, 8192 }, { 59, "Resonance", 0, 1000 }, { 52, "Filter env", -1000, 1000 },
  553. { 31, "Pluck", 0, 1000 }, { 23, "Mask mix", 0, 1000 }, { 65, "Unison", 1, 9 }, { 67, "Uni detune", 0, 256 },
  554. { 25, "Tremolo", 0, 1000 }, { 71, "Phaser mix", 0, 1000 }, { 79, "Harmonizer", 0, 1000 } };
  555. // Harmor: raw FL integers inside the saved state, both parts and the global strip (core/HarmorControls.h, round 172a)
  556. auto addHarmor = [&] (const harmorui::Control& k) {
  557. const auto at = harmorParamOffset (def.pluginState, k.part, k.index);
  558. if (at < 0)
  559. return;
  560. std::int32_t value = 0;
  561. std::memcpy (&value, def.pluginState.data() + at, 4);
  562. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  563. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  564. knob->setRange (k.low, k.high, 1.0);
  565. knob->setValue (k.invert ? k.low + k.high - value : value, juce::dontSendNotification);
  566. knob->setName (juce::String::fromUTF8 (k.name.c_str()));
  567. knob->onValueChange = [this, part = k.part, index = k.index, flip = k.invert ? k.low + k.high : 0, s = knob.get()] {
  568. const auto shown = (std::int32_t) s->getValue();
  569. ref.edit (engine, [part, index, v = flip != 0 ? flip - shown : shown] (ChannelDef& channelDef) {
  570. auto& st = channelDef.pluginState;
  571. if (const auto o = harmorParamOffset (st, part, index); o >= 0)
  572. std::memcpy (st.data() + o, &v, 4);
  573. });
  574. };
  575. addAndMakeVisible (*knob);
  576. knobs.push_back (std::move (knob));
  577. };
  578. // GMS / Morphine: the plugin's own 0…1 floats inside the saved state (GMS P[i], Morphine global A[i]; REA_rodada39)
  579. struct FloatKnob { int index; const char* name; };
  580. static const FloatKnob gmsKnobs[] = {
  581. { 0, "Master" }, { 1, "Pan" }, { 8, "Level" }, { 4, "Attack" }, { 5, "Decay" }, { 6, "Sustain" }, { 7, "Release" },
  582. { 12, "Cutoff" }, { 13, "Resonance" }, { 16, "Env1 amount" }, { 50, "Modulation" }, { 48, "Osc2 mix" }, { 49, "Osc3 mix" },
  583. { 45, "Noise" }, { 41, "Unison" }, { 42, "Uni detune" }, { 43, "Stereo" }, { 10, "Slide time" } };
  584. static const FloatKnob morphineKnobs[] = {
  585. { 0, "Master" }, { 9, "Attack" }, { 10, "Decay" }, { 11, "Sustain" }, { 12, "Release" }, { 1, "Glide" }, { 4, "Vel curve" },
  586. { 7, "Overdrive" }, { 14, "Chorus mix" }, { 21, "Delay mix" }, { 25, "Reverb mix" }, { 36, "Noise mix" } };
  587. // BassDrum: its 23 floats 0…1 inside the saved state (REA_rodada15 §12.3 / rodada43 §2.2)
  588. static const FloatKnob bassDrumKnobs[] = {
  589. { 0, "Output" }, { 6, "Base" }, { 7, "Peak" }, { 8, "Slide" }, { 2, "Duration" }, { 5, "Attack" }, { 4, "Drive" },
  590. { 3, "Butt" }, { 15, "Click level" }, { 14, "Click freq" }, { 13, "Click cut" }, { 21, "Noise mix" }, { 22, "Noise filter" },
  591. { 20, "Noise pitch" }, { 19, "Noise start" }, { 1, "Sampling" } };
  592. // MiniSynth: its 43 floats 0…1 inside the saved state (REA_rodada41 §1.2)
  593. static const FloatKnob miniSynthKnobs[] = {
  594. { 5, "Osc kind" }, { 6, "Osc mod" }, { 7, "Noise" }, { 1, "Transpose" }, { 8, "Cutoff" }, { 9, "Resonance" },
  595. { 16, "Filter env" }, { 21, "Attack" }, { 22, "Decay" }, { 23, "Sustain" }, { 24, "Release" }, { 20, "LFO amount" },
  596. { 19, "LFO rate" }, { 2, "Slide time" } };
  597. auto paramOffset = [this] (const std::vector<std::uint8_t>& st, int index) {
  598. return gms ? gmsParamOffset (st, index)
  599. : miniSynth ? miniSynthParamOffset (st, index)
  600. : poizone ? poizoneParamOffset (st, index)
  601. : bassdrum ? bassDrumParamOffset (st, index)
  602. : toxic ? toxicParamOffset (st, index) : morphineParamOffset (st, index);
  603. };
  604. auto addFloat = [&] (const FloatKnob& k) {
  605. const auto at = paramOffset (def.pluginState, k.index);
  606. if (at < 0)
  607. return;
  608. float value = 0.0f;
  609. std::memcpy (&value, def.pluginState.data() + at, 4);
  610. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  611. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  612. knob->setRange (0.0, 1.0, 0.001);
  613. knob->setValue (std::isfinite (value) ? std::clamp (value, 0.0f, 1.0f) : 0.0f, juce::dontSendNotification);
  614. knob->setName (k.name);
  615. knob->onValueChange = [this, k, paramOffset, s = knob.get()] {
  616. ref.edit (engine, [k, paramOffset, v = (float) s->getValue()] (ChannelDef& channelDef) {
  617. auto& st = channelDef.pluginState;
  618. if (const auto o = paramOffset (st, k.index); o >= 0)
  619. std::memcpy (st.data() + o, &v, 4);
  620. });
  621. };
  622. addAndMakeVisible (*knob);
  623. knobs.push_back (std::move (knob));
  624. };
  625. // SimSynth: its 45 doubles 0…1 at the start of the saved state (REA_rodada64 §1.1)
  626. static const FloatKnob simSynthKnobs[] = {
  627. { 3, "Osc 1 level" }, { 10, "Osc 2 level" }, { 17, "Osc 3 level" }, { 26, "Cutoff" }, { 27, "Resonance" },
  628. { 28, "Filter env" }, { 30, "Key track" }, { 35, "Attack" }, { 36, "Decay" }, { 37, "Sustain" }, { 38, "Release" },
  629. { 22, "LFO rate" }, { 29, "LFO cutoff" }, { 39, "Volume" } };
  630. auto addDouble = [&] (const FloatKnob& k) {
  631. const auto at = 8 * (std::size_t) k.index;
  632. if (! simSynthStateUsable (def.pluginState))
  633. return;
  634. double value = 0.0;
  635. std::memcpy (&value, def.pluginState.data() + at, 8);
  636. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  637. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  638. knob->setRange (0.0, 1.0, 0.001);
  639. knob->setValue (std::isfinite (value) ? std::clamp (value, 0.0, 1.0) : 0.0, juce::dontSendNotification);
  640. knob->setName (k.name);
  641. knob->onValueChange = [this, at, s = knob.get()] {
  642. ref.edit (engine, [at, v = s->getValue()] (ChannelDef& channelDef) {
  643. auto& st = channelDef.pluginState;
  644. if (simSynthStateUsable (st))
  645. std::memcpy (st.data() + at, &v, 8);
  646. });
  647. };
  648. addAndMakeVisible (*knob);
  649. knobs.push_back (std::move (knob));
  650. };
  651. // FL Slayer: the 28 parameter integers of the saved state (REA_rodada68 §6.1), ranges of the plugin's controls
  652. static const Ranged slayerKnobs[] = {
  653. { 0, "Strings", 0, 6 }, { 1, "Coils", 0, 2 }, { 2, "Pickup", 0, 65535 }, { 3, "Tone", 0, 65535 }, { 4, "Slap", 0, 65535 },
  654. { 5, "Fret", 0, 65535 }, { 6, "Harmonic", 0, 65535 }, { 7, "Damp", 0, 65535 }, { 8, "Vel volume", 0, 65535 },
  655. { 9, "Vel damp", 0, 65535 }, { 12, "Amp type", 0, 3 }, { 13, "Drive", 0, 65535 }, { 14, "Presence", 0, 65535 },
  656. { 15, "Feedback", 0, 65535 }, { 16, "EQ low", 0, 65535 }, { 17, "EQ mid", 0, 65535 }, { 18, "EQ high", 0, 65535 },
  657. { 19, "Cabinet", 0, 3 }, { 20, "Effect", 0, 15 }, { 21, "FX par 1", 0, 65535 }, { 22, "FX par 2", 0, 65535 },
  658. { 24, "Mode", 0, 5 }, { 25, "Timing", 0, 65535 }, { 26, "Latch", 0, 1 }, { 27, "Glissando", 0, 1 } };
  659. auto addSlayer = [&] (const Ranged& k) {
  660. const auto at = 4 + 4 * (std::size_t) k.index;
  661. if (! slayerStateUsable (def.pluginState) || at + 4 > def.pluginState.size())
  662. return;
  663. std::int32_t value = 0;
  664. std::memcpy (&value, def.pluginState.data() + at, 4);
  665. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  666. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  667. knob->setRange ((double) k.low, (double) k.high, 1.0);
  668. knob->setValue ((double) std::clamp ((int) value, (int) k.low, (int) k.high), juce::dontSendNotification);
  669. knob->setName (k.name);
  670. knob->onValueChange = [this, at, s = knob.get()] {
  671. ref.edit (engine, [at, v = (std::int32_t) s->getValue()] (ChannelDef& channelDef) {
  672. auto& st = channelDef.pluginState;
  673. if (slayerStateUsable (st) && at + 4 <= st.size())
  674. std::memcpy (st.data() + at, &v, 4);
  675. });
  676. };
  677. addAndMakeVisible (*knob);
  678. knobs.push_back (std::move (knob));
  679. };
  680. // Sytrus: its "Main settings" page, raw FL integers inside the saved (zlib) state (REA_rodada74 §3)
  681. auto addSytrus = [&] (int setting) {
  682. const auto value = sytrus::settingValue (def.pluginState, setting);
  683. if (! value)
  684. return;
  685. const auto& d = sytrus::settings()[(std::size_t) setting];
  686. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  687. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  688. knob->setRange (d.low, d.high, 1.0);
  689. knob->setValue (std::clamp (*value, d.low, d.high), juce::dontSendNotification);
  690. knob->setName (d.name);
  691. knob->onValueChange = [this, setting, s = knob.get()] {
  692. ref.edit (engine, [setting, v = (int) s->getValue()] (ChannelDef& channelDef) {
  693. sytrus::setSetting (channelDef.pluginState, setting, v);
  694. });
  695. };
  696. addAndMakeVisible (*knob);
  697. knobs.push_back (std::move (knob));
  698. };
  699. // Ogun: raw FL integers P0…P63 inside the saved (zlib) state (REA_rodada37 §1.3)
  700. static const Ranged ogunKnobs[] = {
  701. { 0, "Master vol", 0, 256 }, { 5, "Pre-decay", 0, 1000 }, { 6, "Decay", 0, 10000 }, { 7, "Release", 0, 10000 },
  702. { 8, "Fullness", -1000, 1000 }, { 9, "Morph", 0, 1000 }, { 10, "Seed 1", 0, 1000 }, { 11, "Seed 2", 0, 1000 },
  703. { 52, "Richness", 6, 16 }, { 12, "Unison", 1, 9 }, { 15, "Uni pitch", 0, 256 }, { 17, "Cutoff", 0, 256 },
  704. { 18, "Resonance", 0, 256 }, { 3, "Mod X", 0, 512 }, { 4, "Mod Y", 0, 512 }, { 54, "Quality", 0, 4 } };
  705. static const Ranged autogunKnobs[] = { { 63, "Magic dust", 0, 1000 } };
  706. auto addOgun = [&] (const Ranged& k) {
  707. const auto value = ogunParam (def.pluginState, k.index);
  708. if (! value)
  709. return;
  710. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  711. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  712. knob->setRange (k.low, k.high, 1.0);
  713. knob->setValue (*value, juce::dontSendNotification);
  714. knob->setName (k.name);
  715. knob->onValueChange = [this, index = k.index, s = knob.get()] {
  716. ref.edit (engine, [index, v = (int) s->getValue()] (ChannelDef& channelDef) {
  717. ogunSetParam (channelDef.pluginState, index, v);
  718. });
  719. };
  720. addAndMakeVisible (*knob);
  721. knobs.push_back (std::move (knob));
  722. };
  723. // Fruit Kick: its six integers (REA_rodada10 §4.2 ranges)
  724. static const Ranged fruitKickKnobs[] = {
  725. { 0, "Max freq", -2400, 3600 }, { 1, "Min freq", -1200, 1200 }, { 2, "Freq decay", 0, 256 }, { 3, "Amp decay", 0, 256 },
  726. { 4, "Click", 0, 64 }, { 5, "Distortion", 0, 128 } };
  727. auto addFruitKick = [&] (const Ranged& k) {
  728. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  729. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  730. knob->setRange (k.low, k.high, 1.0);
  731. knob->setValue (fruitKickParam (def.pluginState, k.index), juce::dontSendNotification);
  732. knob->setName (k.name);
  733. knob->onValueChange = [this, index = k.index, s = knob.get()] {
  734. ref.edit (engine, [index, v = (int) s->getValue()] (ChannelDef& channelDef) {
  735. fruitKickSetParam (channelDef.pluginState, index, v);
  736. });
  737. };
  738. addAndMakeVisible (*knob);
  739. knobs.push_back (std::move (knob));
  740. };
  741. // Fruity DX10: the 22 raw FL integers of the saved state (REA_rodada42 §1.2)
  742. static const Ranged dx10Knobs[] = {
  743. { 0, "Attack", 0, 65536 }, { 1, "Decay", 0, 65536 }, { 2, "Release", 0, 65536 }, { 21, "Coarse", -3, 3 },
  744. { 11, "Waveform", 0, 65536 }, { 10, "Vibrato", 0, 65536 }, { 13, "LFO rate", 0, 65536 },
  745. { 3, "Mod 1 coarse", 0, 65536 }, { 4, "Mod 1 fine", 0, 65536 }, { 5, "Mod 1 init", 0, 65536 }, { 6, "Mod 1 time", 0, 65536 },
  746. { 7, "Mod 1 sustain", 0, 65536 }, { 8, "Mod 1 release", 0, 65536 }, { 9, "Mod 1 velocity", 0, 65536 },
  747. { 14, "Mod 2 coarse", 0, 65536 }, { 15, "Mod 2 fine", 0, 65536 }, { 16, "Mod 2 init", 0, 65536 }, { 17, "Mod 2 time", 0, 65536 },
  748. { 18, "Mod 2 sustain", 0, 65536 }, { 19, "Mod 2 release", 0, 65536 }, { 20, "Mod 2 velocity", 0, 65536 }, { 12, "Mod thru", 0, 65536 } };
  749. auto addDx10 = [&] (const Ranged& k) {
  750. const auto value = dx10Param (def.pluginState, k.index);
  751. if (! value)
  752. return;
  753. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  754. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  755. knob->setRange (k.low, k.high, 1.0);
  756. knob->setValue (*value, juce::dontSendNotification);
  757. knob->setName (k.name);
  758. knob->onValueChange = [this, index = k.index, s = knob.get()] {
  759. ref.edit (engine, [index, v = (int) s->getValue()] (ChannelDef& channelDef) {
  760. dx10SetParam (channelDef.pluginState, index, v);
  761. });
  762. };
  763. addAndMakeVisible (*knob);
  764. knobs.push_back (std::move (knob));
  765. };
  766. // 3x Osc: the 21 parameters of the saved state, then invert ×3, AM and HQ (REA_rodada47 §1.1)
  767. static const char* const threeOscNames[] = {
  768. "Osc 1 pan", "Osc 1 shape", "Osc 1 coarse", "Osc 1 fine", "Osc 1 phase", "Osc 1 detune", "Osc 2 mix", "Osc 2 pan",
  769. "Osc 2 shape", "Osc 2 coarse", "Osc 2 fine", "Osc 2 phase", "Osc 2 detune", "Osc 3 mix", "Osc 3 pan", "Osc 3 shape",
  770. "Osc 3 coarse", "Osc 3 fine", "Osc 3 phase", "Osc 3 detune", "Phase rand", "Invert 1", "Invert 2", "Invert 3",
  771. "Osc 3 AM", "HQ" };
  772. auto addThreeOsc = [&] (int index) {
  773. const auto value = threeOscParam (def.pluginState, index);
  774. if (! value)
  775. return;
  776. const auto [low, high] = threeOscParamRange (index);
  777. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  778. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  779. knob->setRange (low, high, 1.0);
  780. knob->setValue (*value, juce::dontSendNotification);
  781. knob->setName (threeOscNames[index]);
  782. knob->onValueChange = [this, index, s = knob.get()] {
  783. ref.edit (engine, [index, v = (int) s->getValue()] (ChannelDef& channelDef) {
  784. threeOscSetParam (channelDef.pluginState, index, v);
  785. });
  786. };
  787. addAndMakeVisible (*knob);
  788. knobs.push_back (std::move (knob));
  789. };
  790. // Fruity Granulizer: the 12 parameters of the saved state (REA_rodada67 §1)
  791. static const char* const granulizerNames[] = {
  792. "Grain attack", "Grain hold", "Grain spacing", "Wave spacing", "Effect depth", "Effect speed", "Randomness",
  793. "Stereo", "Loop", "Freeze", "Sample start", "Transient hold" };
  794. auto addGranulizer = [&] (int index) {
  795. const auto value = granulizerParam (def.pluginState, index);
  796. if (! value)
  797. return;
  798. const auto [low, high] = granulizerParamRange (index);
  799. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  800. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  801. knob->setRange (low, high, 1.0);
  802. knob->setValue (*value, juce::dontSendNotification);
  803. knob->setName (granulizerNames[index]);
  804. knob->onValueChange = [this, index, s = knob.get()] {
  805. ref.edit (engine, [index, v = (int) s->getValue()] (ChannelDef& channelDef) {
  806. granulizerSetParam (channelDef.pluginState, index, v);
  807. });
  808. };
  809. addAndMakeVisible (*knob);
  810. knobs.push_back (std::move (knob));
  811. };
  812. // Drumaxx: the master level and the 16 pad volumes, 0…1 floats of the saved state (REA_rodada67 §6)
  813. auto addDrumaxx = [&] (int index, const juce::String& name) {
  814. const auto value = drumaxxParam (def.pluginState, index);
  815. if (! std::isfinite (value))
  816. return;
  817. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  818. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  819. knob->setRange (0.0, 1.0, 0.001);
  820. knob->setValue (std::clamp ((double) value, 0.0, 1.0), juce::dontSendNotification);
  821. knob->setName (name);
  822. knob->onValueChange = [this, index, s = knob.get()] {
  823. ref.edit (engine, [index, v = (float) s->getValue()] (ChannelDef& channelDef) {
  824. drumaxxSetParam (channelDef.pluginState, index, v);
  825. });
  826. };
  827. addAndMakeVisible (*knob);
  828. knobs.push_back (std::move (knob));
  829. };
  830. // Kepler: the panel's 0…1 floats inside the saved state ("Kepler-1" order, REA_rodada46 §1.1)
  831. static const FloatKnob keplerKnobs[] = {
  832. { 33, "Volume" }, { 19, "Cutoff" }, { 20, "Resonance" }, { 22, "Env amount" }, { 26, "Attack" }, { 27, "Decay" },
  833. { 28, "Sustain" }, { 29, "Release" }, { 11, "PW" }, { 16, "Sub level" }, { 17, "Noise" }, { 5, "LFO rate" },
  834. { 10, "Vibrato" }, { 18, "High-pass" }, { 30, "Chorus" } };
  835. // Kepler Exo: the same layout with the "Kepler-2" parameter list (REA_rodada167d §1)
  836. static const FloatKnob keplerExoKnobs[] = {
  837. { 0x48, "Volume" }, { 0x25, "Cutoff" }, { 0x26, "Resonance" }, { 0x2c, "Env amount" }, { 0x3d, "Attack" },
  838. { 0x3e, "Decay" }, { 0x3f, "Sustain" }, { 0x40, "Release" }, { 0x21, "DCO2 level" }, { 0x0e, "DCO2 detune" },
  839. { 0x30, "LFO1 rate" }, { 0x36, "LFO2 rate" }, { 0x50, "Portamento" }, { 0x24, "High-pass" }, { 0x87, "Saturation" },
  840. { 0x70, "Delay amount" }, { 0x73, "Delay feedback" }, { 0x80, "Reverb decay" }, { 0x85, "Reverb wet" },
  841. { 0x93, "Hyper chorus mix" } };
  842. auto addKepler = [&] (const FloatKnob& k) {
  843. const auto at = keplerPanelOffset (def.pluginState, k.index);
  844. if (at < 0)
  845. return;
  846. float value = 0.0f;
  847. std::memcpy (&value, def.pluginState.data() + at, 4);
  848. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  849. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  850. knob->setRange (0.0, 1.0, 0.001);
  851. knob->setValue (std::isfinite (value) ? std::clamp (value, 0.0f, 1.0f) : 0.0f, juce::dontSendNotification);
  852. knob->setName (k.name);
  853. knob->onValueChange = [this, k, s = knob.get()] {
  854. ref.edit (engine, [k, v = (float) s->getValue()] (ChannelDef& channelDef) {
  855. auto& st = channelDef.pluginState;
  856. if (const auto o = keplerPanelOffset (st, k.index); o >= 0)
  857. std::memcpy (st.data() + o, &v, 4);
  858. });
  859. };
  860. addAndMakeVisible (*knob);
  861. knobs.push_back (std::move (knob));
  862. };
  863. // Plucked!: the five int32 knobs of the saved state (REA_rodada65 §1.1)
  864. static const Ranged pluckedKnobs[] = { { 0, "Decay", 0, 256 }, { 1, "Color", 0, 128 }, { 2, "Normalize", 0, 1 },
  865. { 3, "Gate", 0, 1 }, { 4, "Widen", 0, 1 } };
  866. auto addPlucked = [&] (const Ranged& k) {
  867. if (def.pluginState.size() < 20)
  868. return;
  869. std::int32_t value = 0;
  870. std::memcpy (&value, def.pluginState.data() + 4 * k.index, 4);
  871. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  872. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  873. knob->setRange (k.low, k.high, 1.0);
  874. knob->setValue (std::clamp ((double) value, k.low, k.high), juce::dontSendNotification);
  875. knob->setName (k.name);
  876. knob->onValueChange = [this, k, s = knob.get()] {
  877. ref.edit (engine, [k, v = (std::int32_t) s->getValue()] (ChannelDef& channelDef) {
  878. auto& st = channelDef.pluginState;
  879. if (st.size() >= 20)
  880. std::memcpy (st.data() + 4 * k.index, &v, 4);
  881. });
  882. };
  883. addAndMakeVisible (*knob);
  884. knobs.push_back (std::move (knob));
  885. };
  886. // BeepMap: the int32 settings of the saved state (REA_rodada65 §2.1; Frequency's range not confirmed)
  887. static const Ranged beepMapKnobs[] = { { 0, "Frequency", 0, 9600 }, { 1, "Length", 0, 4096 }, { 2, "Scale", 0, 2 },
  888. { 3, "Use blue", 0, 1 }, { 4, "Grainy", 0, 1 }, { 5, "Loop", 0, 1 }, { 6, "Widen", 0, 1 } };
  889. auto addBeepMap = [&] (const Ranged& k) {
  890. const auto at = beepMapParamOffset (def.pluginState, k.index);
  891. if (at < 0)
  892. return;
  893. std::int32_t value = 0;
  894. std::memcpy (&value, def.pluginState.data() + at, 4);
  895. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  896. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  897. knob->setRange (k.low, k.high, 1.0);
  898. knob->setValue (std::clamp ((double) value, k.low, k.high), juce::dontSendNotification);
  899. knob->setName (k.name);
  900. knob->onValueChange = [this, k, s = knob.get()] {
  901. ref.edit (engine, [k, v = (std::int32_t) s->getValue()] (ChannelDef& channelDef) {
  902. auto& st = channelDef.pluginState;
  903. if (const auto o = beepMapParamOffset (st, k.index); o >= 0)
  904. std::memcpy (st.data() + o, &v, 4);
  905. });
  906. };
  907. addAndMakeVisible (*knob);
  908. knobs.push_back (std::move (knob));
  909. };
  910. // Sawer: 0…1 floats of the saved state (REA_rodada65 §3.3)
  911. static const FloatKnob sawerKnobs[] = {
  912. { 0, "Level" }, { 27, "Cutoff" }, { 28, "Resonance" }, { 36, "EGF amount" }, { 2, "Attack" }, { 3, "Decay" },
  913. { 4, "Sustain" }, { 5, "Release" }, { 19, "Sub level" }, { 18, "Sub harmonic" }, { 26, "Noise" }, { 14, "Unison" },
  914. { 15, "Uni detune" }, { 45, "LFO amount" } };
  915. auto addSawer = [&] (const FloatKnob& k) {
  916. const auto at = sawerParamOffset (def.pluginState, k.index);
  917. if (at < 0)
  918. return;
  919. float value = 0.0f;
  920. std::memcpy (&value, def.pluginState.data() + at, 4);
  921. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  922. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  923. knob->setRange (0.0, 1.0, 0.001);
  924. knob->setValue (std::isfinite (value) ? std::clamp (value, 0.0f, 1.0f) : 0.0f, juce::dontSendNotification);
  925. knob->setName (k.name);
  926. knob->onValueChange = [this, k, s = knob.get()] {
  927. ref.edit (engine, [k, v = (float) s->getValue()] (ChannelDef& channelDef) {
  928. auto& st = channelDef.pluginState;
  929. if (const auto o = sawerParamOffset (st, k.index); o >= 0)
  930. std::memcpy (st.data() + o, &v, 4);
  931. });
  932. };
  933. addAndMakeVisible (*knob);
  934. knobs.push_back (std::move (knob));
  935. };
  936. // FL Keys: the 15 int32 knobs of the saved state (REA_rodada69 §8.1)
  937. auto addFlKeys = [&] (int index) {
  938. const auto state = flkeys::parseState (def.pluginState);
  939. if (! state)
  940. return;
  941. const auto& r = flkeys::knobRange[index];
  942. auto knob = std::make_unique<juce::Slider> (juce::Slider::RotaryHorizontalVerticalDrag, juce::Slider::TextBoxBelow);
  943. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  944. knob->setRange (r.min, r.max, 1.0);
  945. knob->setValue (std::clamp ((double) state->knobs[(std::size_t) index], (double) r.min, (double) r.max), juce::dontSendNotification);
  946. knob->setName (r.name);
  947. knob->onValueChange = [this, index, s = knob.get()] {
  948. ref.edit (engine, [index, v = (int) s->getValue()] (ChannelDef& channelDef) {
  949. auto& st = channelDef.pluginState;
  950. if (auto parsed = flkeys::parseState (st))
  951. {
  952. parsed->knobs[(std::size_t) index] = v;
  953. st = flkeys::writeState (*parsed);
  954. }
  955. });
  956. };
  957. addAndMakeVisible (*knob);
  958. knobs.push_back (std::move (knob));
  959. };
  960. // an engine whose parameters are listed (core/ModelParams.h, round 168n): one knob per parameter, automatable
  961. // (right-click: FL's parameter menu; a move is a tweak)
  962. instrumentKind = def.instrument;
  963. modelTable = modelparams::tableOf (def.instrument);
  964. if (modelTable != nullptr && ! modelparams::rawValue (def, modelTable->params->front().index))
  965. modelTable = nullptr; // (a state the engine can't read: the plain page)
  966. if (modelTable != nullptr && (drumaxx || drumsynth))
  967. {
  968. // round 168p: Drumaxx's pad voice / DrumSynth Live's patch: one knob per control, editing the selected
  969. // pad's / key's parameter (the pad buttons / the key display pick the part); the rest as listed
  970. drumPart = drumsynth ? editorKey : drumaxxPadOf (ref.index);
  971. for (const auto& c : drumcontrols::controls (def.instrument))
  972. if (c.perPart)
  973. addPartParam (def, c);
  974. else if (const auto* p = modelparams::find (def.instrument, c.index))
  975. addModelParam (def, *p);
  976. }
  977. else if (modelTable != nullptr)
  978. {
  979. for (const auto& p : *modelTable->params)
  980. addModelParam (def, p);
  981. // Toxic Biohazard without the user's DLL: the drawn wave (0) and the sine (1) only — the built-in waves
  982. // 2…32 are FL's files
  983. if (toxic && ! toxicDllUsable (def.samplePath))
  984. for (auto& k : knobs)
  985. if (k->getName().endsWith (" wave"))
  986. k->setRange (0.0, 1.0, 1.0);
  987. }
  988. else if (flKeys)
  989. for (int i = 0; i < 15; ++i)
  990. addFlKeys (i);
  991. else if (plucked)
  992. for (const auto& k : pluckedKnobs)
  993. addPlucked (k);
  994. else if (beepMap)
  995. for (const auto& k : beepMapKnobs)
  996. addBeepMap (k);
  997. else if (sawer)
  998. for (const auto& k : sawerKnobs)
  999. addSawer (k);
  1000. else if (threeOsc)
  1001. for (int i = 0; i < threeOscParamCount(); ++i)
  1002. addThreeOsc (i);
  1003. else if (granulizer)
  1004. {
  1005. for (int i = 0; i < granulizerParamCount(); ++i)
  1006. addGranulizer (i);
  1007. setupGranulizerModes (def);
  1008. }
  1009. else if (drumaxx)
  1010. {
  1011. addDrumaxx (0x2c1, "Master");
  1012. for (int pad = 0; pad < 16; ++pad)
  1013. addDrumaxx (pad * 44, "Pad " + juce::String (pad + 1));
  1014. }
  1015. else if (dx10)
  1016. for (const auto& k : dx10Knobs)
  1017. addDx10 (k);
  1018. else if (kepler)
  1019. for (const auto& k : keplerKnobs)
  1020. addKepler (k);
  1021. else if (keplerExo)
  1022. for (const auto& k : keplerExoKnobs)
  1023. addKepler (k);
  1024. else if (gms)
  1025. for (const auto& k : gmsKnobs)
  1026. addFloat (k);
  1027. else if (bassdrum)
  1028. for (const auto& k : bassDrumKnobs)
  1029. addFloat (k);
  1030. else if (fruitkick)
  1031. for (const auto& k : fruitKickKnobs)
  1032. addFruitKick (k);
  1033. else if (morphine)
  1034. for (const auto& k : morphineKnobs)
  1035. addFloat (k);
  1036. else if (miniSynth)
  1037. for (const auto& k : miniSynthKnobs)
  1038. addFloat (k);
  1039. else if (simSynth)
  1040. for (const auto& k : simSynthKnobs)
  1041. addDouble (k);
  1042. else if (wasp || fruityDance)
  1043. ;
  1044. else if (slayer)
  1045. for (const auto& k : slayerKnobs)
  1046. addSlayer (k);
  1047. else if (sytrus)
  1048. for (int i = 0; i < (int) sytrus::settings().size(); ++i)
  1049. addSytrus (i);
  1050. else if (ogun)
  1051. {
  1052. for (const auto& k : ogunKnobs)
  1053. addOgun (k);
  1054. if (autogun)
  1055. for (const auto& k : autogunKnobs)
  1056. addOgun (k);
  1057. }
  1058. else if (harmor)
  1059. for (const auto& k : harmorui::controls())
  1060. addHarmor (k);
  1061. else if (harmless)
  1062. for (const auto& k : harmlessKnobs)
  1063. add (k.index, k.name, k.low, k.high);
  1064. else if (drumsynth)
  1065. for (const auto& k : drumSynthKnobs)
  1066. add (k.index, k.name, k.low, k.high);
  1067. else if (boobass)
  1068. for (const auto& [index, name] : booBassKnobs)
  1069. add (index, name);
  1070. else if (sakura)
  1071. for (const auto& [index, name] : sakuraKnobs)
  1072. add (index, name);
  1073. else
  1074. for (const auto& [index, name] : drumpadKnobs)
  1075. add (index, name);
  1076. const auto rows = ((int) knobs.size() + 6) / 7; // the grid of resized()
  1077. setSize (720, std::max (dx10 || threeOsc ? 500 : 384, 46 + rows * 110 + 8 + (granulizerModes ? 64 : 0)));
  1078. // a Granulizer node inside a Patcher (round 165c): no channel to drop a sample on, so its own Sample button
  1079. if (granulizer && ref.index < 0)
  1080. {
  1081. sampleButton.setButtonText (tr ("Sample..."));
  1082. const auto path = juce::String::fromUTF8 (def.samplePath.c_str());
  1083. ui::setHint (sampleButton, path.isEmpty() ? tr ("Choose the sample the Granulizer plays") : path);
  1084. sampleButton.onClick = [this] {
  1085. juce::StringArray patterns;
  1086. for (const auto e : sampleFileExtensions)
  1087. patterns.add ("*." + juce::String (std::string (e)));
  1088. chooser = lynx::ui::makeFileChooser (tr ("Sample"), juce::File(), patterns.joinIntoString (";"));
  1089. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  1090. [safe = juce::Component::SafePointer<ModelPanel> (this)] (const juce::FileChooser& fc) {
  1091. if (safe == nullptr || fc.getResult() == juce::File())
  1092. return;
  1093. safe->loadGranulizerSample (fc.getResult());
  1094. });
  1095. };
  1096. addAndMakeVisible (sampleButton);
  1097. resized(); // (setSize above laid the page out before the button existed)
  1098. }
  1099. // FL's arrangement of the plugin's page (core/PluginLayout.cpp): the knobs at FL's places, faders and
  1100. // switches drawn by the panel
  1101. // (a Transistor Bass from a .flm: FL Studio Mobile's build has no sequencer, delay or reverb)
  1102. layout = transistorBassMobile ? plugui::transistorBassFlmLayout() : plugui::instrumentLayout (def.instrument);
  1103. if (layout != nullptr && plugui::hostedElsewhere) // (round 180b: the plate prints the plugin's name)
  1104. {
  1105. hostedName = def.name;
  1106. hostedLayout = *layout;
  1107. for (auto& item : hostedLayout.items)
  1108. if ((item.style & plugui::enginePlate) != 0)
  1109. item.label = hostedName.c_str();
  1110. layout = &hostedLayout;
  1111. }
  1112. // a state the engine cannot read gives no knobs: keep the plain page then
  1113. if (layout != nullptr && ! wasp && std::none_of (knobs.begin(), knobs.end(), [this] (const auto& k) { return itemFor (k->getName()) != nullptr; }))
  1114. layout = nullptr;
  1115. if (layout != nullptr)
  1116. {
  1117. accent = flKeys ? skin::colour::azure : boobass || transistorBass ? skin::colour::ember : harmor || sytrus ? skin::colour::violet
  1118. : skin::colour::crimson;
  1119. // round 126: the page's own style (FL Keys hardware, BooBass vivid, the synths neon); round 170j: a plugin
  1120. // with its own art (Sakura, Toxic Biohazard, Sytrus, 3x Osc) is Themed
  1121. pageStyle = flKeys ? skin::Style::hardware : boobass || transistorBass ? skin::Style::vivid : skin::Style::neon;
  1122. pageArt = skin::artForInstrument (def.instrument);
  1123. if (pageArt != skin::Art::none)
  1124. {
  1125. pageStyle = skin::Style::themed;
  1126. artLayer = std::make_unique<skin::ArtLayer>();
  1127. addAndMakeVisible (*artLayer);
  1128. artLayer->setArt (pageArt, [this] { return themedNow(); });
  1129. }
  1130. for (auto& k : knobs)
  1131. {
  1132. k->getProperties().set (skin::sliderProperty, (juce::int64) accent.getARGB());
  1133. k->getProperties().set (skin::styleProperty, skin::packStyle (pageStyle, pageArt));
  1134. const auto* item = itemFor (k->getName());
  1135. if (item == nullptr || (item->type != plugui::Item::knob && item->type != plugui::Item::vslider && item->type != plugui::Item::hslider))
  1136. {
  1137. k->setVisible (false); // edited by a switch of the panel (or not shown by FL)
  1138. continue;
  1139. }
  1140. k->setTextBoxStyle (juce::Slider::NoTextBox, false, 0, 0);
  1141. if (item->type == plugui::Item::vslider)
  1142. k->setSliderStyle (juce::Slider::LinearVertical);
  1143. if ((item->style & plugui::springBack) != 0) // (a pitch bend wheel: back to the centre when let go)
  1144. k->onDragEnd = [s = k.get(), before = k->onDragEnd] {
  1145. s->setValue (0.5 * (s->getMinimum() + s->getMaximum()), juce::sendNotificationSync);
  1146. if (before)
  1147. before();
  1148. };
  1149. if (item->type == plugui::Item::hslider)
  1150. k->setSliderStyle (juce::Slider::LinearHorizontal);
  1151. k->setPopupDisplayEnabled (true, true, this);
  1152. k->setTooltip (k->getName());
  1153. }
  1154. updateConditional();
  1155. // FL's size × 1.25, at most about 1200 × 760 (big pages such as Harmor's fit a laptop screen)
  1156. const auto f = juce::jmin (layoutScale, 1200.0f / (float) layout->width, 720.0f / (float) layout->height);
  1157. setSize ((int) std::ceil (f * (float) layout->width) + 16, (int) std::ceil (f * (float) layout->height) + layoutTop() + 8);
  1158. }
  1159. // issue #152 (round 190he): the knobs follow the channel's state (a MIDI link, Init song values, undo) and play
  1160. // their automation, as FL's editors do; the timer also follows Transistor Bass's program (round 169g2)
  1161. rememberState();
  1162. engine.addChangeListener (this);
  1163. if (ref.index >= 0 && (! modelKnobs.empty() || ! partKnobs.empty() || transistorBass))
  1164. startTimerHz (30);
  1165. }
  1166. ~ModelPanel() override
  1167. {
  1168. stopTimer();
  1169. engine.removeChangeListener (this);
  1170. }
  1171. // issue #152: a change of the channel's state that this page did not make (a linked controller, an Init song value,
  1172. // undo / redo, a preset loaded elsewhere) moves the knobs; nothing is redrawn when the state is the same
  1173. void changeListenerCallback (juce::ChangeBroadcaster*) override
  1174. {
  1175. const auto* c = channelNow();
  1176. if (c == nullptr || (c->pluginState == seenState && c->modelParams == seenParams))
  1177. return;
  1178. rememberState();
  1179. auto moved = false;
  1180. for (const auto& [k, index] : modelKnobs)
  1181. if (! k->isMouseButtonDown() && ! isAutomatedShown (k))
  1182. if (const auto v = modelparams::rawValue (*c, index); v && std::abs (*v - (float) k->getValue()) > 1.0e-6f)
  1183. {
  1184. k->setValue (*v, juce::dontSendNotification);
  1185. moved = true;
  1186. }
  1187. for (const auto& [k, control] : partKnobs)
  1188. if (! k->isMouseButtonDown() && ! isAutomatedShown (k))
  1189. if (const auto v = drumcontrols::value (*c, *control, drumPart); v && std::abs (*v - (float) k->getValue()) > 1.0e-6f)
  1190. {
  1191. k->setValue (*v, juce::dontSendNotification);
  1192. moved = true;
  1193. }
  1194. if (moved && layout != nullptr)
  1195. updateConditional();
  1196. if (moved)
  1197. repaint();
  1198. }
  1199. void rememberState()
  1200. {
  1201. if (const auto* c = channelNow())
  1202. {
  1203. seenState = c->pluginState;
  1204. seenParams = c->modelParams;
  1205. }
  1206. }
  1207. bool isAutomatedShown (const juce::Slider* k) const
  1208. {
  1209. return std::find (automatedShown.begin(), automatedShown.end(), k) != automatedShown.end();
  1210. }
  1211. // issue #152: while the song plays, an automated knob shows its automation's value (AutomationDisplay, as the
  1212. // Sampler's and the effects' knobs); when the automation stops driving it, it shows the channel's value again
  1213. void showAutomation()
  1214. {
  1215. if (ref.index < 0 || (modelKnobs.empty() && partKnobs.empty()))
  1216. return;
  1217. const auto& shown = engine.getAutomationDisplay();
  1218. if (shown.getGeneration() == shownGeneration)
  1219. return;
  1220. shownGeneration = shown.getGeneration();
  1221. if (automatedShown.empty() && ! shown.any())
  1222. return;
  1223. const auto* c = channelNow();
  1224. if (c == nullptr)
  1225. return;
  1226. std::vector<const juce::Slider*> now;
  1227. auto moved = false;
  1228. const auto show = [&] (juce::Slider* k, int index, std::optional<float> songRaw) {
  1229. if (k->isMouseButtonDown())
  1230. return;
  1231. const auto* p = modelparams::find (instrumentKind, index);
  1232. const auto v = shown.valueOf ({ AutomationTargetKind::channelParam, ref.index, 0, index });
  1233. if (v && p != nullptr)
  1234. {
  1235. k->setValue (p->raw (*v), juce::dontSendNotification);
  1236. now.push_back (k);
  1237. moved = true;
  1238. }
  1239. else if (isAutomatedShown (k) && songRaw)
  1240. {
  1241. k->setValue (*songRaw, juce::dontSendNotification);
  1242. moved = true;
  1243. }
  1244. };
  1245. for (const auto& [k, index] : modelKnobs)
  1246. show (k, index, modelparams::rawValue (*c, index));
  1247. for (const auto& [k, control] : partKnobs)
  1248. show (k, drumcontrols::absoluteIndex (instrumentKind, *control, drumPart), drumcontrols::value (*c, *control, drumPart));
  1249. automatedShown = std::move (now);
  1250. if (moved && layout != nullptr)
  1251. updateConditional();
  1252. if (moved)
  1253. repaint();
  1254. }
  1255. void timerCallback() override
  1256. {
  1257. if (isShowing())
  1258. showAutomation();
  1259. if (transistorBass && ref.index >= 0 && ++programTicks >= 3) // (10 times a second, as before)
  1260. {
  1261. programTicks = 0;
  1262. followTransistorBassProgram();
  1263. }
  1264. }
  1265. // Transistor Bass with its sequencer on: a note selects program = key (REA_rodada57 §2.10) and FL's editor shows
  1266. // that program, so its knobs edit what plays. The channel's state takes the playing program (not an undo step)
  1267. // and every knob reads it again (round 169g2)
  1268. void followTransistorBassProgram()
  1269. {
  1270. const auto* c = channelNow();
  1271. const auto instrument = engine.getChannelInstrument (ref.index);
  1272. if (c == nullptr || instrument == nullptr)
  1273. return;
  1274. const auto selected = instrument->selectedProgram();
  1275. const auto prog = transistorBassProgram (c->pluginState);
  1276. if (selected < 0 || ! prog || prog->program == selected)
  1277. return;
  1278. auto next = c->pluginState;
  1279. if (! transistorBassSelectProgram (next, selected))
  1280. return;
  1281. ref.edit (engine, [next = std::move (next)] (ChannelDef& d) { d.pluginState = next; }, false);
  1282. syncKnobs (true);
  1283. repaint();
  1284. }
  1285. // a knob of a listed engine parameter (round 168n): raw range of the state, automation target channelParam
  1286. void addModelParam (const ChannelDef& def, const EngineParam& p)
  1287. {
  1288. auto knob = std::make_unique<MenuSlider>();
  1289. knob->setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  1290. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  1291. knob->setRange (p.low, p.high, p.stepped ? 1.0 : 0.0);
  1292. knob->setValue (modelparams::rawValue (def, p.index).value_or (p.low), juce::dontSendNotification);
  1293. knob->setDoubleClickReturnValue (false, 0.0);
  1294. knob->setName (juce::String::fromUTF8 (p.name.c_str()));
  1295. const auto index = p.index;
  1296. knob->onValueChange = [this, index, s = knob.get()] {
  1297. ref.edit (engine, [index, v = (float) s->getValue()] (ChannelDef& c) {
  1298. modelparams::setRawValue (c, index, v);
  1299. natives::followControl (c, index, flStudioAccess()); // (Harmless' compression type loads its preset)
  1300. });
  1301. if (instrumentKind == InstrumentKind::transistorbass && index >= tbseq::length) // (a step's note moves its octave)
  1302. syncKnobs();
  1303. if (layout != nullptr)
  1304. {
  1305. updateConditional();
  1306. repaint();
  1307. }
  1308. };
  1309. if (ref.index >= 0) // (a Patcher node: no automation target)
  1310. {
  1311. const auto target = [this, index] { return AutomationTarget { AutomationTargetKind::channelParam, ref.index, 0, index }; };
  1312. ui::setOwnMenu (*knob);
  1313. knob->onMenu = [this, k = knob.get(), target] { ui::showSliderMenu (*k, &engine, target()); };
  1314. knob->onDragStart = [this, target] { engine.noteTweaked (target(), true); };
  1315. knob->onDragEnd = [this, target] { engine.tweakReleased (target()); };
  1316. }
  1317. modelKnobs.push_back ({ knob.get(), index });
  1318. addAndMakeVisible (*knob);
  1319. knobs.push_back (std::move (knob));
  1320. }
  1321. // round 168p: a knob of Drumaxx's selected pad / DrumSynth Live's selected key (drumcontrols' per-part control):
  1322. // named as the control (the layout places it), editing and automating the part's engine parameter
  1323. void addPartParam (const ChannelDef& def, const drumcontrols::Control& c)
  1324. {
  1325. auto knob = std::make_unique<MenuSlider>();
  1326. knob->setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  1327. knob->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 16);
  1328. knob->setRange (c.low, c.high, c.integer ? 1.0 : 0.0);
  1329. knob->setValue (drumcontrols::value (def, c, drumPart).value_or (c.low), juce::dontSendNotification);
  1330. knob->setDoubleClickReturnValue (false, 0.0);
  1331. knob->setName (c.name);
  1332. const auto* control = &c;
  1333. knob->onValueChange = [this, control, s = knob.get()] {
  1334. ref.edit (engine, [control, part = drumPart, v = (float) s->getValue()] (ChannelDef& d) { drumcontrols::setValue (d, *control, v, part); });
  1335. if (layout != nullptr)
  1336. repaint();
  1337. };
  1338. if (ref.index >= 0)
  1339. {
  1340. const auto target = [this, control] {
  1341. return AutomationTarget { AutomationTargetKind::channelParam, ref.index, 0, drumcontrols::absoluteIndex (instrumentKind, *control, drumPart) };
  1342. };
  1343. ui::setOwnMenu (*knob);
  1344. knob->onMenu = [this, k = knob.get(), target] { ui::showSliderMenu (*k, &engine, target()); };
  1345. knob->onDragStart = [this, target] { engine.noteTweaked (target(), true); };
  1346. knob->onDragEnd = [this, target] { engine.tweakReleased (target()); };
  1347. }
  1348. partKnobs.push_back ({ knob.get(), control });
  1349. addAndMakeVisible (*knob);
  1350. knobs.push_back (std::move (knob));
  1351. }
  1352. // the pad remembered for each Drumaxx channel while LYNX runs (FL's editor keeps it, not the state)
  1353. static int& drumaxxPadOf (int channel)
  1354. {
  1355. static std::map<int, int> pads;
  1356. return pads[channel];
  1357. }
  1358. // another pad / key selected: the part's knobs show its values (no rebuild)
  1359. void selectPart (int part)
  1360. {
  1361. const auto* def = ref.get (engine);
  1362. if (def == nullptr || part == drumPart)
  1363. return;
  1364. drumPart = part;
  1365. if (drumaxx)
  1366. drumaxxPadOf (ref.index) = part;
  1367. if (drumsynth)
  1368. {
  1369. editorKey = part;
  1370. ref.edit (engine, [part] (ChannelDef& d) { // FL keeps the selected key in the state
  1371. if (lynx::drumSynthEditorKeyIndex < (int) d.modelParams.size())
  1372. d.modelParams[(std::size_t) lynx::drumSynthEditorKeyIndex] = (float) part;
  1373. });
  1374. }
  1375. for (const auto& [k, c] : partKnobs)
  1376. k->setValue (drumcontrols::value (*def, *c, drumPart).value_or (c->low), juce::dontSendNotification);
  1377. repaint();
  1378. }
  1379. // the listed parameters' knobs read the channel's state again (an edit that moved other values: Transistor Bass's
  1380. // note / octave, CLEAR, octave buttons; round 168q2)
  1381. void syncKnobs (bool all = false)
  1382. {
  1383. const auto* c = channelNow();
  1384. if (c == nullptr || modelTable == nullptr)
  1385. return;
  1386. for (auto& k : knobs)
  1387. if (const auto* p = modelparams::findByName (instrumentKind, k->getName().toStdString()); p != nullptr && (all || p->index >= tbseq::length))
  1388. if (const auto v = modelparams::rawValue (*c, p->index))
  1389. k->setValue (*v, juce::dontSendNotification);
  1390. }
  1391. // the items shown only while another control is within a range (LayoutItem::whenParam, e.g. an effect slot's
  1392. // fields for its type): their knobs follow
  1393. bool conditionHolds (const plugui::LayoutItem& item) const
  1394. {
  1395. auto holds = [this] (const char* param, float lo, float hi) {
  1396. if (param == nullptr)
  1397. return true;
  1398. const auto* k = knobFor (param);
  1399. if (k == nullptr)
  1400. return true;
  1401. const auto v = normalised (*k); // (0…1 over the knob's range, as the effect layouts' conditions)
  1402. return v >= lo && (v < hi || (hi >= 1.0f && v <= hi));
  1403. };
  1404. return (item.page < 0 || item.page == page) && holds (item.whenParam, item.whenMin, item.whenMax)
  1405. && holds (item.when2Param, item.when2Min, item.when2Max) && holds (item.when3Param, item.when3Min, item.when3Max);
  1406. }
  1407. int pageCount() const { return layout != nullptr ? (int) layout->pages.size() : 0; }
  1408. void showPage (int p)
  1409. {
  1410. page = p;
  1411. updateConditional();
  1412. repaint();
  1413. }
  1414. void updateConditional()
  1415. {
  1416. if (layout == nullptr)
  1417. return;
  1418. for (auto& k : knobs)
  1419. if (const auto* item = itemFor (k->getName()); item != nullptr && (item->type == plugui::Item::knob || item->type == plugui::Item::vslider || item->type == plugui::Item::hslider))
  1420. k->setVisible (conditionHolds (*item));
  1421. }
  1422. // --- FL's arrangement ------------------------------------------------------------------------------
  1423. static constexpr float layoutScale = 1.25f;
  1424. // round 190in (design190ia FW-6): a designed page no longer carries the "<Name> — FL's engine…" line over its art
  1425. // (FL draws nothing there; the line is the page's and its tab's tooltip): the art starts at the top unless the
  1426. // sample button or the missing-files band needs the strip
  1427. int layoutTop() const { return sampleButton.isVisible() || engineFilesMissing ? 34 : 8; }
  1428. const plugui::LayoutItem* itemFor (const juce::String& name) const
  1429. {
  1430. if (layout == nullptr)
  1431. return nullptr;
  1432. const plugui::LayoutItem* any = nullptr;
  1433. for (const auto& item : layout->items) // the knob / fader of the parameter first (a pad may share it)
  1434. if (item.param != nullptr && name == item.param)
  1435. {
  1436. if (item.type == plugui::Item::knob || item.type == plugui::Item::vslider)
  1437. return &item;
  1438. if (any == nullptr && item.type != plugui::Item::display)
  1439. any = &item;
  1440. }
  1441. return any;
  1442. }
  1443. juce::Slider* knobFor (const char* name) const
  1444. {
  1445. for (const auto& k : knobs)
  1446. if (name != nullptr && k->getName() == name)
  1447. return k.get();
  1448. return nullptr;
  1449. }
  1450. float layoutFactor() const
  1451. {
  1452. if (layout == nullptr)
  1453. return 1.0f;
  1454. return juce::jmax (0.4f, juce::jmin ((float) (getWidth() - 16) / (float) layout->width, (float) (getHeight() - layoutTop() - 8) / (float) layout->height));
  1455. }
  1456. juce::Rectangle<float> layoutRect (const plugui::LayoutItem& item) const
  1457. {
  1458. const auto f = layoutFactor();
  1459. return { 8.0f + item.x * f, (float) layoutTop() + item.y * f, item.w * f, item.h * f };
  1460. }
  1461. static float normalised (const juce::Slider& k)
  1462. {
  1463. const auto range = k.getMaximum() - k.getMinimum();
  1464. return range > 0.0 ? (float) ((k.getValue() - k.getMinimum()) / range) : 0.0f;
  1465. }
  1466. static void setNormalised (juce::Slider& k, float v)
  1467. {
  1468. k.setValue (k.getMinimum() + (double) v * (k.getMaximum() - k.getMinimum()), juce::sendNotificationSync);
  1469. }
  1470. // the radio's option cell (grids fill row by row)
  1471. juce::Rectangle<float> optionCell (const plugui::LayoutItem& item, int o, int count) const
  1472. {
  1473. const auto r = layoutRect (item);
  1474. const auto columns = juce::jmax (1, item.columns);
  1475. const auto rows = (count + columns - 1) / columns;
  1476. const auto w = r.getWidth() / (float) columns, h = r.getHeight() / (float) juce::jmax (1, rows);
  1477. return { r.getX() + w * (float) (o % columns), r.getY() + h * (float) (o / columns), w, h };
  1478. }
  1479. // a tabs item's segment o of `count` (left to right)
  1480. juce::Rectangle<float> tabCell (const plugui::LayoutItem& item, int o, int count) const
  1481. {
  1482. const auto r = layoutRect (item);
  1483. const auto w = r.getWidth() / (float) juce::jmax (1, count);
  1484. return { r.getX() + w * (float) o, r.getY(), w, r.getHeight() };
  1485. }
  1486. // a small drawing of an oscillator shape (3x Osc's shape buttons)
  1487. static void drawShape (juce::Graphics& g, juce::Rectangle<float> r, const juce::String& name)
  1488. {
  1489. juce::Path p;
  1490. const auto x0 = r.getX(), w = r.getWidth(), yc = r.getCentreY(), a = r.getHeight() * 0.5f;
  1491. const auto n = 48;
  1492. for (int i = 0; i <= n; ++i)
  1493. {
  1494. const auto t = (float) i / (float) n;
  1495. float y = 0.0f;
  1496. if (name == "Sine") y = std::sin (t * juce::MathConstants<float>::twoPi);
  1497. else if (name == "Square") y = t < 0.5f ? 1.0f : -1.0f;
  1498. else if (name == "Rounded") y = t < 0.46f ? 1.0f - 2.0f * std::pow (0.997f, t * 16384.0f) : (t < 0.83f ? 1.0f : -1.0f);
  1499. else if (name == "Triangle") y = t < 0.25f ? 4.0f * t : (t < 0.75f ? 2.0f - 4.0f * t : 4.0f * t - 4.0f);
  1500. else if (name == "Saw") y = 2.0f * t - 1.0f;
  1501. else if (name == "Noise") y = std::sin ((float) i * 12.9898f) * std::cos ((float) i * 4.1414f) * 1.6f;
  1502. else /* custom */ y = std::sin (t * juce::MathConstants<float>::twoPi * 3.0f) * std::exp (-std::abs (t - 0.5f) * 5.0f);
  1503. y = juce::jlimit (-1.0f, 1.0f, y);
  1504. const juce::Point<float> pt { x0 + w * t, yc - a * y };
  1505. if (i == 0)
  1506. p.startNewSubPath (pt);
  1507. else
  1508. p.lineTo (pt);
  1509. }
  1510. g.strokePath (p, juce::PathStrokeType (1.5f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  1511. }
  1512. // round 170j: the page draws its own art right now (Settings may force another style)
  1513. bool themedNow() const { return pageArt != skin::Art::none && skin::resolve (pageStyle, pageArt) == skin::Style::themed; }
  1514. juce::Colour pageAccent() const { return themedNow() ? skin::artAccent (pageArt) : accent; }
  1515. // where the art's moving part lives: next to the plugin's big name (Toxic's trefoil, Sytrus's figure, 3x Osc's
  1516. // scope); Sakura's petals fall in the band of the branch, above the first row of sections (a small area to repaint)
  1517. juce::Rectangle<float> artStage() const
  1518. {
  1519. if (layout == nullptr)
  1520. return {};
  1521. const auto f = layoutFactor();
  1522. if (pageArt == skin::Art::sakura)
  1523. {
  1524. auto top = (float) getHeight();
  1525. for (const auto& item : layout->items)
  1526. if (item.type == plugui::Item::section && layoutRect (item).getY() > (float) getHeight() * 0.18f)
  1527. top = juce::jmin (top, layoutRect (item).getY());
  1528. return { 0.0f, 30.0f, (float) getWidth(), juce::jmax (40.0f, top - 30.0f) };
  1529. }
  1530. for (const auto& item : layout->items)
  1531. if (item.type == plugui::Item::label && item.label != nullptr && (item.style & plugui::dim) != 0 && item.h * f > 30.0f * f
  1532. && juce::String (item.label).length() > 2)
  1533. {
  1534. const auto r = layoutRect (item);
  1535. const auto w = juce::GlyphArrangement::getStringWidth (theme::font (r.getHeight() * 0.6f, true), item.label);
  1536. const auto left = (item.style & plugui::alignLeft) != 0;
  1537. const auto x0 = left ? r.getX() : r.getRight() - juce::jmin (w, r.getWidth());
  1538. if (pageArt == skin::Art::toxic)
  1539. return { x0 - r.getHeight() * 1.5f, r.getY() - r.getHeight() * 0.15f, r.getHeight() * 1.3f, r.getHeight() * 1.3f };
  1540. return { left ? x0 + w + 12.0f : x0 - r.getHeight() * 2.6f - 12.0f, r.getY() - r.getHeight() * 0.1f, r.getHeight() * 2.6f, r.getHeight() * 1.2f };
  1541. }
  1542. return {};
  1543. }
  1544. void paintLayout (juce::Graphics& g)
  1545. {
  1546. using namespace theme;
  1547. const skin::StyleScope styleScope (skin::resolve (pageStyle, pageArt), pageArt);
  1548. const auto accent = pageAccent(); // (the art's own light when Themed)
  1549. const auto f = layoutFactor();
  1550. const auto* found = ref.get (engine);
  1551. if (found == nullptr)
  1552. return;
  1553. const auto& def = *found;
  1554. const auto caption = [&] (const char* text, juce::Rectangle<float> r, bool dimmed, juce::Justification j) {
  1555. if (text == nullptr || *text == 0)
  1556. return;
  1557. g.setColour (dimmed ? colour::textDisabled : colour::textSecondary);
  1558. g.setFont (font (juce::jmax (8.0f, 9.5f * f), true));
  1559. g.drawFittedText (caps (tr (text)), r.toNearestInt(), j, 1, 0.7f);
  1560. };
  1561. for (const auto& item : layout->items)
  1562. {
  1563. if (! conditionHolds (item))
  1564. continue;
  1565. const auto r = layoutRect (item);
  1566. // round 170j: a partial repaint (the art's petals) draws only the items it touches (captions may hang
  1567. // up to ~26 units past an item's sides)
  1568. if (! g.clipRegionIntersects (r.expanded (32.0f * f, 8.0f * f).getSmallestIntegerContainer()))
  1569. continue;
  1570. const auto dimmed = (item.style & plugui::dim) != 0;
  1571. auto* k = knobFor (item.param);
  1572. switch (item.type)
  1573. {
  1574. case plugui::Item::tabs: // a row of segmented buttons (round 168n); pageTabs: the layout's pages
  1575. if ((item.style & plugui::pageTabs) != 0)
  1576. {
  1577. const auto labels = plugui::optionLabels (item);
  1578. for (int o = 0; o < (int) labels.size(); ++o)
  1579. {
  1580. const auto cell = tabCell (item, o, (int) labels.size()).reduced (1.5f * f, 2.0f * f);
  1581. skin::button (g, cell, o == page, false, accent, radius::sm * f);
  1582. g.setColour (o == page ? colour::onAccent : colour::textSecondary);
  1583. g.setFont (font (juce::jmax (8.0f, juce::jmin (11.0f * f, cell.getHeight() * 0.62f)), true));
  1584. g.drawFittedText (tr (labels[(std::size_t) o]), cell.reduced (2.0f * f, 0.0f).toNearestInt(), juce::Justification::centred, 1, 0.6f);
  1585. }
  1586. }
  1587. else if (k != nullptr)
  1588. {
  1589. const auto labels = plugui::optionLabels (item);
  1590. const auto chosen = plugui::optionAt (item, normalised (*k));
  1591. for (int o = 0; o < (int) labels.size(); ++o)
  1592. {
  1593. const auto cell = tabCell (item, o, (int) labels.size()).reduced (1.5f * f, 2.0f * f);
  1594. skin::button (g, cell, o == chosen, false, accent, radius::sm * f);
  1595. g.setColour (o == chosen ? colour::onAccent : colour::textSecondary);
  1596. g.setFont (font (juce::jmax (8.0f, juce::jmin (11.0f * f, cell.getHeight() * 0.62f)), true));
  1597. g.drawFittedText (tr (labels[(std::size_t) o]), cell.reduced (2.0f * f, 0.0f).toNearestInt(), juce::Justification::centred, 1, 0.6f);
  1598. }
  1599. }
  1600. break;
  1601. case plugui::Item::menu: // a choice list: the current option and ▾ (round 168n)
  1602. if (k != nullptr)
  1603. {
  1604. const auto labels = plugui::optionLabels (item);
  1605. const auto chosen = plugui::optionAt (item, normalised (*k));
  1606. auto box = r;
  1607. if (item.label != nullptr && (item.style & plugui::noCaption) == 0)
  1608. caption (item.label, box.removeFromTop (12.0f * f), dimmed, juce::Justification::centredLeft);
  1609. skin::valuePlate (g, box, radius::sm * f);
  1610. g.setColour (colour::textPrimary);
  1611. g.setFont (font (juce::jmax (8.0f, juce::jmin (11.0f * f, box.getHeight() * 0.62f)), true));
  1612. const auto text = juce::isPositiveAndBelow (chosen, (int) labels.size()) ? tr (labels[(std::size_t) chosen]) : juce::String();
  1613. g.drawFittedText (text, box.reduced (4.0f * f, 0.0f).withTrimmedRight (10.0f * f).toNearestInt(), juce::Justification::centredLeft, 1, 0.6f);
  1614. g.setColour (colour::textSecondary);
  1615. g.drawText (juce::String::fromUTF8 ("\xe2\x96\xbe"), box.withTrimmedLeft (box.getWidth() - 12.0f * f), juce::Justification::centred, false);
  1616. }
  1617. break;
  1618. case plugui::Item::value: // the control's value as text (round 168n)
  1619. if (k != nullptr)
  1620. {
  1621. skin::valuePlate (g, r, radius::sm * f);
  1622. g.setColour (colour::textPrimary);
  1623. g.setFont (font (juce::jmax (8.0f, juce::jmin (11.0f * f, r.getHeight() * 0.7f)), true));
  1624. g.drawFittedText (k->getTextFromValue (k->getValue()), r.reduced (3.0f * f, 0.0f).toNearestInt(),
  1625. (item.style & plugui::alignLeft) != 0 ? juce::Justification::centredLeft : juce::Justification::centred, 1, 0.6f);
  1626. }
  1627. break;
  1628. case plugui::Item::section:
  1629. skin::section (g, r, radius::lg * f, (item.style & plugui::raised) != 0, accent);
  1630. if (item.label != nullptr && (item.style & plugui::boxed) == 0)
  1631. skin::sectionTitle (g, r.withHeight (16.0f * f).translated (0.0f, 1.0f * f), caps (tr (item.label)), accent, juce::jmax (8.0f, 10.0f * f));
  1632. break;
  1633. case plugui::Item::label:
  1634. if (item.label != nullptr && juce::String (item.label).length() <= 2 && dimmed) // big dim numbers (3x Osc rows)
  1635. {
  1636. g.setColour (colour::bg4);
  1637. g.setFont (font (r.getHeight() * 0.9f, true));
  1638. g.drawText (item.label, r, juce::Justification::centred, false);
  1639. }
  1640. else if (dimmed && r.getHeight() > 30.0f * f) // the plugin's name, big and readable (round 168q2)
  1641. {
  1642. g.setColour (themedNow() ? accent.interpolatedWith (juce::Colours::white, 0.55f) : colour::textSecondary);
  1643. g.setFont (font (r.getHeight() * 0.6f, true));
  1644. g.drawFittedText (item.label, r.toNearestInt(),
  1645. (item.style & plugui::alignLeft) != 0 ? juce::Justification::centredLeft : juce::Justification::centredRight, 1, 0.8f);
  1646. }
  1647. else
  1648. caption (item.label, r, dimmed, (item.style & plugui::alignLeft) != 0 ? juce::Justification::centredLeft : juce::Justification::centred);
  1649. break;
  1650. case plugui::Item::knob: // (a small knob's caption may use some room on both sides, as a fader's does)
  1651. if ((item.style & plugui::noCaption) == 0)
  1652. caption (item.label, r.withTop (r.getBottom() - 12.0f * f).expanded (juce::jmax (0.0f, 52.0f * f - r.getWidth()) * 0.5f, 0.0f), dimmed, juce::Justification::centred);
  1653. break;
  1654. case plugui::Item::vslider:
  1655. case plugui::Item::hslider:
  1656. if ((item.style & plugui::noCaption) == 0)
  1657. caption (item.label, r.withTop (r.getBottom() - 12.0f * f).expanded (16.0f * f, 0.0f), dimmed, juce::Justification::centred);
  1658. break;
  1659. case plugui::Item::radio:
  1660. if (k != nullptr)
  1661. {
  1662. const auto labels = plugui::optionLabels (item);
  1663. const auto chosen = plugui::optionAt (item, normalised (*k));
  1664. for (int o = 0; o < (int) labels.size(); ++o)
  1665. {
  1666. const auto cell = optionCell (item, o, (int) labels.size()).reduced (3.0f * f);
  1667. skin::button (g, cell, o == chosen, false, accent, radius::md * f);
  1668. g.setColour (o == chosen ? accent.brighter (0.5f) : colour::textSecondary);
  1669. if (item.columns > 0)
  1670. drawShape (g, cell.reduced (cell.getWidth() * 0.22f, cell.getHeight() * 0.3f), labels[(std::size_t) o]);
  1671. else
  1672. g.drawFittedText (tr (labels[(std::size_t) o]), cell.toNearestInt(), juce::Justification::centred, 1, 0.7f);
  1673. }
  1674. }
  1675. break;
  1676. case plugui::Item::toggle:
  1677. if (k != nullptr)
  1678. {
  1679. const auto on = normalised (*k) >= 0.5f;
  1680. if ((item.style & plugui::boxed) != 0)
  1681. {
  1682. const auto box = r.reduced (3.0f * f);
  1683. skin::button (g, box, on, false, accent, radius::md * f);
  1684. g.setColour (on ? colour::onAccent : colour::textSecondary);
  1685. g.setFont (font (juce::jmax (8.0f, 11.0f * f), true));
  1686. g.drawText (item.label != nullptr ? item.label : "", box, juce::Justification::centred, false);
  1687. }
  1688. else
  1689. {
  1690. const auto dot = juce::Rectangle<float> (10.0f * f, 10.0f * f).withCentre ({ r.getX() + 6.0f * f, r.getCentreY() });
  1691. if (on)
  1692. {
  1693. g.setColour (accent.withAlpha (0.3f));
  1694. g.fillEllipse (dot.expanded (3.0f * f));
  1695. }
  1696. g.setColour (on ? accent : juce::Colour (0xff0b0c0f));
  1697. g.fillEllipse (dot);
  1698. g.setColour (juce::Colours::white.withAlpha (on ? 0.4f : 0.08f));
  1699. g.drawEllipse (dot.reduced (0.5f), 1.0f);
  1700. caption (item.label, r.withTrimmedLeft (14.0f * f), false, juce::Justification::centredLeft);
  1701. }
  1702. }
  1703. break;
  1704. case plugui::Item::stepper:
  1705. if (k != nullptr)
  1706. {
  1707. auto box = r;
  1708. if (item.label != nullptr)
  1709. caption (item.label, box.removeFromTop (12.0f * f), false, juce::Justification::centred);
  1710. skin::valuePlate (g, box, radius::sm * f);
  1711. g.setColour (colour::textPrimary);
  1712. g.setFont (font (juce::jmax (9.0f, 12.0f * f), true));
  1713. // oversampling orders read as FL shows them (0 → 1x … 3 → 8x)
  1714. // a Transistor Bass step's note reads as a note name (60 = C5, FL's naming; round 168q2)
  1715. static const char* const noteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  1716. const auto whole = (int) std::lround (k->getValue());
  1717. const auto* units = unitParam (*k); // (round 169h: a 0…1 number box in whole units)
  1718. const auto text = units != nullptr ? juce::String (units->unitString (units->unitOf ((float) k->getValue())))
  1719. : juce::String (item.param).containsIgnoreCase ("oversampling") ? juce::String (1 << juce::jlimit (0, 8, (int) k->getValue())) + "x"
  1720. : juce::String (item.param).endsWith (" note") ? juce::String (noteNames[((whole % 12) + 12) % 12]) + juce::String (whole / 12)
  1721. : juce::String (whole);
  1722. g.drawFittedText (text, box.withTrimmedRight (8.0f * f).toNearestInt(), juce::Justification::centred, 1, 0.7f);
  1723. g.setColour (colour::textSecondary);
  1724. g.drawText (juce::String::fromUTF8 ("\xe2\x96\xb4"), box.withTrimmedLeft (box.getWidth() - 10.0f * f).withHeight (box.getHeight() * 0.5f), juce::Justification::centred, false);
  1725. g.drawText (juce::String::fromUTF8 ("\xe2\x96\xbe"), box.withTrimmedLeft (box.getWidth() - 10.0f * f).withTrimmedTop (box.getHeight() * 0.5f), juce::Justification::centred, false);
  1726. }
  1727. break;
  1728. case plugui::Item::display:
  1729. skin::well (g, r, radius::md * f);
  1730. // round 168q: BeepMap's bitmap, its file row, the Granulizer's sample and grains, Transistor Bass's
  1731. // program and sequence
  1732. if (juce::String (item.display) == "beepmapimage")
  1733. paintBeepMapImage (g, r.reduced (3.0f * f));
  1734. if (juce::String (item.display) == "beepmapfile")
  1735. paintBeepMapFile (g, r, f);
  1736. if (juce::String (item.display) == "granulizerwave")
  1737. paintGranulizerWave (g, r.reduced (4.0f * f), f);
  1738. if (juce::String (item.display) == "granulizergrains")
  1739. paintGranulizerGrains (g, r.reduced (5.0f * f), f);
  1740. if (juce::String (item.display) == "tbprogram")
  1741. paintTransistorBass (g, r, f);
  1742. if (juce::String (item.display) == "tbsteps")
  1743. paintTransistorBassSteps (g, r, f);
  1744. if (juce::String (item.display) == "tbseqtools")
  1745. paintTransistorBassTools (g, r, f);
  1746. if (juce::String (item.display) == "xy")
  1747. if (auto* kx = knobFor (item.param); kx != nullptr)
  1748. if (auto* ky = knobFor (item.param2); ky != nullptr)
  1749. {
  1750. // FL's Ogun pad (TQuickXYZ, round 169h shots fl-ogun-*.png): a 4 × 4 grid and a small ring
  1751. // whose centre is the value, drawn clipped to the pad — at X = 0 only its inner half shows
  1752. const juce::Graphics::ScopedSaveState clip (g);
  1753. g.reduceClipRegion (r.toNearestInt());
  1754. for (int k = 1; k < 4; ++k)
  1755. {
  1756. g.setColour (k == 2 ? colour::gridBar : colour::gridBeat);
  1757. g.drawVerticalLine ((int) (r.getX() + r.getWidth() * (float) k / 4.0f), r.getY(), r.getBottom());
  1758. g.drawHorizontalLine ((int) (r.getY() + r.getHeight() * (float) k / 4.0f), r.getX(), r.getRight());
  1759. }
  1760. const juce::Point<float> pt { r.getX() + r.getWidth() * normalised (*kx), r.getBottom() - r.getHeight() * normalised (*ky) };
  1761. g.setColour (accent);
  1762. g.drawEllipse (juce::Rectangle<float> (10.0f * f, 10.0f * f).withCentre (pt), juce::jmax (1.5f, 1.5f * f));
  1763. }
  1764. if (juce::String (item.display) == "toxicwave" && item.param != nullptr) // round 168n: the wave's cycle
  1765. {
  1766. const juce::String name (item.param);
  1767. const auto n = name.fromFirstOccurrenceOf (" ", false, false).getIntValue();
  1768. const auto slot = name.startsWith ("LFO") ? 5 + n : n - 1;
  1769. const auto inner = r.reduced (5.0f * f, 6.0f * f);
  1770. const auto shape = toxicWaveShape (def.pluginState, def.samplePath, slot, 96);
  1771. if (shape.empty())
  1772. {
  1773. g.setColour (colour::textSecondary);
  1774. g.setFont (font (juce::jmax (8.0f, 9.5f * f)));
  1775. g.drawFittedText (tr ("Needs FL Studio's files"), inner.toNearestInt(), juce::Justification::centred, 2, 0.7f);
  1776. }
  1777. else
  1778. {
  1779. g.setColour (colour::gridBeat);
  1780. g.drawHorizontalLine ((int) inner.getCentreY(), inner.getX(), inner.getRight());
  1781. juce::Path wave;
  1782. for (int i = 0; i < (int) shape.size(); ++i)
  1783. {
  1784. const juce::Point<float> pt { inner.getX() + inner.getWidth() * (float) i / (float) (shape.size() - 1),
  1785. inner.getCentreY() - inner.getHeight() * 0.5f * shape[(std::size_t) i] };
  1786. if (i == 0)
  1787. wave.startNewSubPath (pt);
  1788. else
  1789. wave.lineTo (pt);
  1790. }
  1791. g.setColour (accent.withAlpha (0.25f));
  1792. g.strokePath (wave, juce::PathStrokeType (3.0f * f));
  1793. g.setColour (accent.brighter (0.3f));
  1794. g.strokePath (wave, juce::PathStrokeType (1.3f * f));
  1795. }
  1796. }
  1797. paintDrumDisplay (g, item, r, def, f);
  1798. // round 168o: the envelopes of the synth group's pages, drawn from their knobs (attack, decay, sustain, release;
  1799. // a missing stage is skipped, a missing sustain is the level the decay falls to: none)
  1800. {
  1801. struct Env
  1802. {
  1803. const char* id;
  1804. const char* a;
  1805. const char* d;
  1806. const char* s;
  1807. const char* r;
  1808. const char* start; // a modulator's initial level (DX10)
  1809. };
  1810. static const Env envs[] = {
  1811. { "dx10amp", "Attack", "Decay", nullptr, "Release", nullptr },
  1812. { "dx10mod1", nullptr, "Mod 1 time", "Mod 1 sustain", "Mod 1 release", "Mod 1 init" },
  1813. { "dx10mod2", nullptr, "Mod 2 time", "Mod 2 sustain", "Mod 2 release", "Mod 2 init" },
  1814. { "simamp", "Attack", "Decay", "Sustain", "Release", nullptr },
  1815. { "simfilt", "Filter attack", "Filter decay", "Filter sustain", "Filter release", nullptr },
  1816. { "ministenv", "Attack", "Decay", "Sustain", "Release", nullptr },
  1817. };
  1818. for (const auto& e : envs)
  1819. if (juce::String (item.display) == e.id)
  1820. {
  1821. const auto value = [&] (const char* name, float otherwise) {
  1822. auto* kn = name != nullptr ? knobFor (name) : nullptr;
  1823. return kn != nullptr ? juce::jlimit (0.0f, 1.0f, normalised (*kn)) : otherwise;
  1824. };
  1825. const auto inner = r.reduced (5.0f * f, 5.0f * f);
  1826. const auto a = value (e.a, 0.0f), d = value (e.d, 0.5f), su = value (e.s, 0.0f), rl = value (e.r, 0.3f);
  1827. const auto peak = e.start != nullptr ? value (e.start, 1.0f) : 1.0f;
  1828. const auto unit = inner.getWidth() / 4.0f;
  1829. const auto y = [&] (float level) { return inner.getBottom() - inner.getHeight() * level; };
  1830. juce::Path env;
  1831. auto x = inner.getX();
  1832. env.startNewSubPath (x, y (e.start != nullptr ? peak : 0.0f));
  1833. x += unit * a;
  1834. env.lineTo (x, y (peak));
  1835. // DX10's amp decay ≥ 0.98 holds the note
  1836. const auto hold = e.s != nullptr ? su : (d >= 0.98f ? peak : 0.0f);
  1837. x += unit * (0.15f + 0.85f * d);
  1838. env.lineTo (x, y (hold));
  1839. env.lineTo (inner.getRight() - unit * (0.15f + 0.85f * rl), y (hold));
  1840. env.lineTo (inner.getRight(), y (0.0f));
  1841. g.setColour (colour::gridBeat);
  1842. g.drawHorizontalLine ((int) inner.getBottom(), inner.getX(), inner.getRight());
  1843. g.setColour (accent.withAlpha (0.25f));
  1844. g.strokePath (env, juce::PathStrokeType (3.0f * f));
  1845. g.setColour (accent.brighter (0.3f));
  1846. g.strokePath (env, juce::PathStrokeType (1.3f * f));
  1847. }
  1848. }
  1849. if (juce::String (item.display) == "gmswaves") // round 168o: GMS's waves are read from FL Studio's folder
  1850. {
  1851. g.setColour (colour::textSecondary);
  1852. g.setFont (font (juce::jmax (8.0f, 9.5f * f)));
  1853. const auto text = def.samplePath.empty() ? tr ("Needs FL Studio's files")
  1854. : juce::File (juce::String::fromUTF8 (def.samplePath.c_str())).getFileName();
  1855. g.drawFittedText (text, r.reduced (6.0f * f).toNearestInt(), juce::Justification::centred, 3, 0.7f);
  1856. }
  1857. if (juce::String (item.display) == "flkeysname")
  1858. if (const auto st = flkeys::parseState (def.pluginState))
  1859. {
  1860. g.setColour (colour::textPrimary);
  1861. g.setFont (font (juce::jmax (9.0f, 11.0f * f)));
  1862. g.drawFittedText (juce::String::fromUTF8 (st->wavetable.c_str()), r.reduced (6.0f * f, 0.0f).toNearestInt(),
  1863. juce::Justification::centredLeft, 1, 0.8f);
  1864. }
  1865. break;
  1866. default:
  1867. break;
  1868. }
  1869. }
  1870. }
  1871. // round 168p: the displays of the drum pages (Drumaxx's kit / pads, BassDrum's noise sample, DrumSynth Live's
  1872. // selected patch and its key display)
  1873. static juce::String keyName (int key) { return juce::String (notenames::keyName (key)); }
  1874. juce::Rectangle<float> dslKeyCell (juce::Rectangle<float> r, int key) const
  1875. {
  1876. // the 120 patch keys in 4 rows of 30 (C0 … B9, FL's octave numbers)
  1877. const auto w = r.getWidth() / 30.0f, h = r.getHeight() / 4.0f;
  1878. return { r.getX() + w * (float) (key % 30), r.getY() + h * (float) (key / 30), w, h };
  1879. }
  1880. void paintDrumDisplay (juce::Graphics& g, const plugui::LayoutItem& item, juce::Rectangle<float> r, const ChannelDef& def, float f)
  1881. {
  1882. using namespace theme;
  1883. const juce::String id (item.display);
  1884. auto text = [&] (const juce::String& t, juce::Colour c, juce::Justification j = juce::Justification::centred) {
  1885. g.setColour (c);
  1886. g.setFont (font (juce::jmax (8.0f, juce::jmin (12.0f * f, r.getHeight() * 0.62f))));
  1887. g.drawFittedText (t, r.reduced (4.0f * f, 1.0f).toNearestInt(), j, 1, 0.7f);
  1888. };
  1889. if (id == "drumaxxkit")
  1890. {
  1891. const auto name = juce::String::fromUTF8 (drumaxxKitName (def.pluginState).c_str());
  1892. text (name.isEmpty() ? tr ("(no kit name)") : name, colour::textPrimary, juce::Justification::centredLeft);
  1893. }
  1894. else if (id == "drumaxxpad")
  1895. {
  1896. const auto pad = item.steps;
  1897. const auto keyValue = drumaxxParam (def.pluginState, 44 * pad + 4);
  1898. const auto key = std::isfinite (keyValue) ? (int) keyValue : -1;
  1899. skin::button (g, r.reduced (2.0f * f), pad == drumPart, false, accent, radius::md * f);
  1900. g.setColour (pad == drumPart ? colour::onAccent : colour::textSecondary);
  1901. g.setFont (font (juce::jmax (8.0f, 10.0f * f), true));
  1902. g.drawFittedText (juce::String (pad + 1) + "\n" + (key >= 0 && key < 128 ? keyName (key) : juce::String()), r.toNearestInt(),
  1903. juce::Justification::centred, 2, 0.7f);
  1904. }
  1905. else if (id == "drumaxxpadname")
  1906. {
  1907. const auto name = juce::String::fromUTF8 (drumaxxPadName (def.pluginState, item.steps).c_str());
  1908. text (name.isEmpty() ? tr ("Pad {0}", { juce::String (item.steps + 1) }) : name, item.steps == drumPart ? accent.brighter (0.4f) : colour::textSecondary,
  1909. juce::Justification::centredLeft);
  1910. }
  1911. else if (id == "bassdrumnoise")
  1912. {
  1913. if (! bassDrumStateUsable (def.pluginState) || def.samplePath.empty())
  1914. text (tr ("Needs FL Studio's files"), colour::textSecondary);
  1915. else
  1916. {
  1917. const auto name = juce::String::fromUTF8 (bassDrumNoiseName (def.pluginState).c_str());
  1918. text (name.isEmpty() ? tr ("(no noise sample)") : name, colour::textPrimary, juce::Justification::centredLeft);
  1919. }
  1920. }
  1921. else if (id == "dslpatch")
  1922. text (keyName (drumPart) + " (" + juce::String (drumPart) + ")", colour::textPrimary);
  1923. else if (id == "dslsend" || id == "dslmorph")
  1924. {
  1925. const auto slot = drumSynthKeyToSlot (drumPart);
  1926. const auto at = drumSynthPatchParams * slot + (id == "dslsend" ? 34 : 36);
  1927. const auto v = slot >= 0 && at < (int) def.modelParams.size() ? (int) std::lround (def.modelParams[(std::size_t) at]) : -1;
  1928. text (id == "dslsend" ? (v < 0 ? juce::String ("-") : juce::String (v)) : (v < 0 || v > 119 ? tr ("(none)") : keyName (v)), colour::textPrimary);
  1929. }
  1930. else if (id == "dslkeys")
  1931. {
  1932. const auto inner = r.reduced (3.0f * f);
  1933. for (int key = 0; key < drumSynthPatches; ++key)
  1934. {
  1935. const auto cell = dslKeyCell (inner, key).reduced (0.5f * f);
  1936. const auto slot = drumSynthKeyToSlot (key);
  1937. const auto level = (std::size_t) (drumSynthPatchParams * slot) < def.modelParams.size() ? def.modelParams[(std::size_t) (drumSynthPatchParams * slot)] : 0.0f;
  1938. static constexpr bool blackKey[12] = { false, true, false, true, false, false, true, false, true, false, true, false };
  1939. const auto black = blackKey[key % 12];
  1940. g.setColour (key == drumPart ? accent : level > 0.0f ? accent.withAlpha (0.35f) : black ? colour::bg1 : colour::bg4);
  1941. g.fillRect (cell);
  1942. if (key % 12 == 0)
  1943. {
  1944. g.setColour (key == drumPart ? colour::onAccent : colour::textSecondary);
  1945. g.setFont (font (juce::jmax (6.5f, juce::jmin (8.0f * f, cell.getHeight() * 0.6f))));
  1946. g.drawText (juce::String (key / 12), cell, juce::Justification::centred, false);
  1947. }
  1948. }
  1949. }
  1950. }
  1951. // a click on a pad button / the key display selects the part the knobs edit; true when handled
  1952. bool clickDrumDisplay (const plugui::LayoutItem& item, juce::Point<float> at)
  1953. {
  1954. if (item.type != plugui::Item::display || item.display == nullptr || ! layoutRect (item).contains (at) || ! conditionHolds (item))
  1955. return false;
  1956. const juce::String id (item.display);
  1957. if (drumaxx && (id == "drumaxxpad" || id == "drumaxxpadname"))
  1958. {
  1959. selectPart (item.steps);
  1960. return true;
  1961. }
  1962. if (drumsynth && id == "dslkeys")
  1963. {
  1964. const auto inner = layoutRect (item).reduced (3.0f * layoutFactor());
  1965. for (int key = 0; key < drumSynthPatches; ++key)
  1966. if (dslKeyCell (inner, key).contains (at))
  1967. {
  1968. selectPart (key);
  1969. return true;
  1970. }
  1971. }
  1972. return false;
  1973. }
  1974. void resizeLayout()
  1975. {
  1976. for (auto& k : knobs)
  1977. {
  1978. const auto* item = itemFor (k->getName());
  1979. if (item == nullptr) // (hidden knobs too: another page's knobs keep their place for when the page shows)
  1980. continue;
  1981. auto r = layoutRect (*item);
  1982. if ((item->type == plugui::Item::vslider || item->type == plugui::Item::hslider) && (item->style & plugui::noCaption) == 0 && item->label != nullptr)
  1983. r.removeFromBottom (13.0f * layoutFactor());
  1984. if (item->type == plugui::Item::knob)
  1985. {
  1986. if ((item->style & plugui::noCaption) == 0)
  1987. r.removeFromBottom (14.0f * layoutFactor());
  1988. const auto d = juce::jmin (r.getWidth(), r.getHeight());
  1989. r = r.withSizeKeepingCentre (d, d).withY (r.getY());
  1990. }
  1991. k->setBounds (r.toNearestInt());
  1992. }
  1993. }
  1994. // a stepper's number moves one unit (the engine's own units for a 0…1 number box, round 169h)
  1995. const EngineParam* unitParam (const juce::Slider& k) const
  1996. {
  1997. const auto* p = modelparams::findByName (instrumentKind, k.getName().toStdString());
  1998. return p != nullptr && p->hasUnits() ? p : nullptr;
  1999. }
  2000. void stepBy (juce::Slider& k, int delta)
  2001. {
  2002. if (const auto* p = unitParam (k))
  2003. k.setValue (p->rawOfUnit (p->unitOf ((float) k.getValue()) + delta), juce::sendNotificationSync);
  2004. else
  2005. k.setValue (k.getValue() + delta, juce::sendNotificationSync);
  2006. }
  2007. void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel) override
  2008. {
  2009. if (layout != nullptr && wheel.deltaY != 0.0f)
  2010. for (const auto& item : layout->items)
  2011. if (item.type == plugui::Item::stepper && layoutRect (item).contains (e.position) && conditionHolds (item))
  2012. if (auto* k = knobFor (item.param))
  2013. {
  2014. stepBy (*k, wheel.deltaY > 0.0f ? 1 : -1);
  2015. repaint();
  2016. return;
  2017. }
  2018. juce::Component::mouseWheelMove (e, wheel);
  2019. }
  2020. void mouseDrag (const juce::MouseEvent& e) override
  2021. {
  2022. if (stepperDrag != nullptr)
  2023. {
  2024. if (auto* k = knobFor (stepperDrag->param))
  2025. {
  2026. const auto pixels = 6.0f * layoutFactor();
  2027. const auto units = (int) ((stepperDragY - e.position.y) / pixels);
  2028. if (units != stepperDragged)
  2029. {
  2030. stepBy (*k, units - stepperDragged);
  2031. stepperDragged = units;
  2032. repaint();
  2033. }
  2034. }
  2035. return;
  2036. }
  2037. if (xyItem == nullptr)
  2038. return;
  2039. const auto r = layoutRect (*xyItem);
  2040. if (auto* kx = knobFor (xyItem->param))
  2041. setNormalised (*kx, juce::jlimit (0.0f, 1.0f, (e.position.x - r.getX()) / r.getWidth()));
  2042. if (auto* ky = knobFor (xyItem->param2))
  2043. setNormalised (*ky, juce::jlimit (0.0f, 1.0f, (r.getBottom() - e.position.y) / r.getHeight()));
  2044. repaint();
  2045. }
  2046. void mouseUp (const juce::MouseEvent&) override
  2047. {
  2048. xyItem = nullptr;
  2049. stepperDrag = nullptr;
  2050. }
  2051. void mouseDown (const juce::MouseEvent& e) override
  2052. {
  2053. if (layout == nullptr)
  2054. return;
  2055. for (const auto& item : layout->items) // round 168p: Drumaxx's pads, DrumSynth Live's keys
  2056. if (clickDrumDisplay (item, e.position))
  2057. return;
  2058. for (const auto& item : layout->items) // the page switches first (they edit no parameter)
  2059. if (item.type == plugui::Item::tabs && (item.style & plugui::pageTabs) != 0 && layoutRect (item).contains (e.position) && conditionHolds (item))
  2060. {
  2061. const auto count = (int) plugui::optionLabels (item).size();
  2062. for (int o = 0; o < count; ++o)
  2063. if (tabCell (item, o, count).contains (e.position))
  2064. showPage (o);
  2065. return;
  2066. }
  2067. for (const auto& item : layout->items) // round 168q2: Transistor Bass's CLEAR / octave up / octave down
  2068. if (item.type == plugui::Item::display && juce::String (item.display) == "tbseqtools" && layoutRect (item).contains (e.position))
  2069. {
  2070. if (const auto button = transistorBassToolButton (item, e.position); button >= 0)
  2071. transistorBassToolAction (button);
  2072. return;
  2073. }
  2074. for (const auto& item : layout->items) // round 168q: BeepMap's Open / Paste
  2075. if (item.type == plugui::Item::display && juce::String (item.display) == "beepmapfile" && layoutRect (item).contains (e.position))
  2076. {
  2077. if (const auto button = beepMapFileButton (item, e.position); button >= 0)
  2078. beepMapAction (button);
  2079. return;
  2080. }
  2081. for (const auto& item : layout->items)
  2082. {
  2083. auto* k = knobFor (item.param);
  2084. if (k == nullptr || ! layoutRect (item).contains (e.position) || ! conditionHolds (item)
  2085. || item.type == plugui::Item::knob || item.type == plugui::Item::vslider || item.type == plugui::Item::hslider
  2086. || item.type == plugui::Item::section || item.type == plugui::Item::label)
  2087. continue;
  2088. if (e.mods.isPopupMenu() && ref.index >= 0 && modelTable != nullptr) // a switch / tabs: FL's parameter menu
  2089. {
  2090. if (const auto* p = modelparams::findByName (instrumentKind, k->getName().toStdString()))
  2091. ui::showSliderMenu (*k, &engine, AutomationTarget { AutomationTargetKind::channelParam, ref.index, 0, p->index });
  2092. return;
  2093. }
  2094. if (item.type == plugui::Item::menu)
  2095. {
  2096. const auto labels = plugui::optionLabels (item);
  2097. const auto chosen = plugui::optionAt (item, normalised (*k));
  2098. juce::PopupMenu menu;
  2099. for (int o = 0; o < (int) labels.size(); ++o)
  2100. menu.addItem (tr (labels[(std::size_t) o]), true, o == chosen,
  2101. [safe = juce::Component::SafePointer<ModelPanel> (this), name = k->getName(), value = plugui::optionValue (item, o)] {
  2102. if (safe == nullptr)
  2103. return;
  2104. if (auto* knob = safe->knobFor (name.toRawUTF8()))
  2105. setNormalised (*knob, value);
  2106. safe->repaint();
  2107. });
  2108. menu.showMenuAsync (juce::PopupMenu::Options().withTargetScreenArea (localAreaToGlobal (layoutRect (item).toNearestInt())));
  2109. return;
  2110. }
  2111. if (item.type == plugui::Item::tabs)
  2112. {
  2113. const auto count = (int) plugui::optionLabels (item).size();
  2114. for (int o = 0; o < count; ++o)
  2115. if (tabCell (item, o, count).contains (e.position))
  2116. setNormalised (*k, plugui::optionValue (item, o));
  2117. repaint();
  2118. return;
  2119. }
  2120. if (item.type == plugui::Item::display && juce::String (item.display) == "xy")
  2121. {
  2122. xyItem = &item;
  2123. mouseDrag (e);
  2124. return;
  2125. }
  2126. if (item.type == plugui::Item::stepper)
  2127. {
  2128. const auto r = layoutRect (item);
  2129. const auto up = e.position.y < r.getY() + (item.label != nullptr ? 12.0f * layoutFactor() : 0.0f) + (r.getHeight() - (item.label != nullptr ? 12.0f * layoutFactor() : 0.0f)) * 0.5f;
  2130. stepBy (*k, up ? 1 : -1);
  2131. stepperDrag = &item; // (round 169h) a vertical drag moves the number too
  2132. stepperDragY = e.position.y;
  2133. stepperDragged = 0;
  2134. }
  2135. else if (item.type == plugui::Item::toggle)
  2136. setNormalised (*k, normalised (*k) >= 0.5f ? 0.0f : 1.0f);
  2137. else if (item.type == plugui::Item::radio)
  2138. {
  2139. const auto count = (int) plugui::optionLabels (item).size();
  2140. for (int o = 0; o < count; ++o)
  2141. if (optionCell (item, o, count).contains (e.position))
  2142. setNormalised (*k, plugui::optionValue (item, o));
  2143. }
  2144. repaint();
  2145. return;
  2146. }
  2147. }
  2148. void paint (juce::Graphics& g) override
  2149. {
  2150. g.fillAll (theme::colour::bg2);
  2151. if (layout != nullptr) // a plugin page in FL's arrangement: the plugin skin's canvas (round 170j: the art's when Themed)
  2152. {
  2153. const skin::StyleScope styleScope (themedNow() ? skin::Style::themed : skin::style(), pageArt);
  2154. skin::canvas (g, getLocalBounds().toFloat(), pageAccent());
  2155. }
  2156. g.setColour (theme::colour::textPrimary);
  2157. g.setFont (theme::font (layout != nullptr ? theme::type::body : theme::type::title));
  2158. if (! engineFilesMissing && layout == nullptr) // (round 190in, FW-6: a designed page shows it as its tooltip)
  2159. g.drawFittedText (shownDescription(), descriptionArea(), juce::Justification::centredLeft, layout != nullptr ? 1 : 2, 0.8f);
  2160. if (engineFilesMissing) // round 168q: an engine that runs FL's own DLL / data file, which this computer lacks
  2161. {
  2162. const auto band = juce::Rectangle<float> (8.0f, 5.0f, (float) getWidth() - 16.0f, 22.0f);
  2163. g.setColour (accent.withAlpha (0.18f));
  2164. g.fillRoundedRectangle (band, 4.0f);
  2165. g.setColour (theme::colour::textPrimary);
  2166. g.setFont (theme::font (theme::type::small));
  2167. g.drawFittedText (tr ("Needs FL Studio's files: the engine file was not found, so the channel stays silent (its settings are kept)."),
  2168. band.reduced (6.0f, 0.0f).toNearestInt(), juce::Justification::centredLeft, 1, 0.7f);
  2169. }
  2170. if (layout != nullptr)
  2171. {
  2172. paintLayout (g);
  2173. return;
  2174. }
  2175. g.setFont (theme::font (theme::type::small));
  2176. for (const auto& k : knobs)
  2177. g.drawText (k->getName(), k->getBounds().withHeight (14).translated (0, -14), juce::Justification::centred);
  2178. }
  2179. // the engine's description (what it is and where its data comes from)
  2180. juce::String description() const
  2181. {
  2182. if (plugui::hostedElsewhere)
  2183. return juce::String::fromUTF8 (hostedName.c_str());
  2184. return drumsynth ? tr ("DrumSynth Live — FL's engine, patch on key {0}", { juce::String (editorKey) })
  2185. + (wavesFound ? tr (" (next hit; recorded waves from your FL installation)")
  2186. : tr (" (next hit; recorded waves not found: silent)"))
  2187. : harmless ? tr ("Harmless — FL's additive engine with its effects rack")
  2188. : harmor ? tr ("Harmor — FL's additive engine with its effects rack")
  2189. : gms ? tr ("GMS — FL's engine (waves read from your FL installation)")
  2190. : morphine ? tr ("Morphine — FL's additive engine (new settings restart the voices)")
  2191. : transistorBass && transistorBassMobile ? tr ("Transistor Bass — FL Studio Mobile's build of the engine")
  2192. : transistorBass ? tr ("Transistor Bass — FL's engine with its sequencer and effects (oscillator cycles read from your FL installation)")
  2193. : autogun ? tr ("Autogun — FL's engine with its effects and Magic Dust (SG.dat read from your FL installation)")
  2194. : ogun ? tr ("Ogun — FL's engine with its effects (Seed 2 Random is a fixed draw per channel)")
  2195. : poizone ? tr ("PoiZone — FL's engine with its gate, chorus, delay and arpeggiator (new settings restart the voices)")
  2196. : miniSynth ? tr ("MiniSynth — FL's engine with its effects (wave tables read from your FL installation)")
  2197. : dx10 ? tr ("Fruity DX10 — FL's FM engine")
  2198. : kepler ? tr ("Kepler — FL's engine (LFO shape and noise read from your FL installation)")
  2199. : keplerExo ? tr ("Kepler Exo — FL's engine with its effects (tables read from your FL installation)")
  2200. : fruitkick ? tr ("Fruit Kick — FL's engine (channel envelopes stepped per tick)")
  2201. : bassdrum ? tr ("BassDrum — FL's engine (table and noise samples read from your FL installation)")
  2202. : toxic ? tr ("Toxic Biohazard — FL's engine with its effects (waves read from your FL installation)")
  2203. : threeOsc ? tr ("3x Osc — FL's engine (custom wave from the channel's sample)")
  2204. : simSynth ? tr ("SimSynth — FL's engine (new settings restart the voices)")
  2205. : wasp ? tr ("Wasp — FL Studio 2026 has no 64-bit Wasp: the channel keeps its settings and stays silent, as in FL")
  2206. : flKeys ? tr ("FL Keys — FL's engine (wavetable read from your FL installation)")
  2207. : plucked ? tr ("Plucked! — FL's plucked-string engine")
  2208. : beepMap ? tr ("BeepMap — FL's engine (plays the bitmap saved with the channel)")
  2209. : sawer ? tr ("Sawer — FL's engine with its effects (oscillator cycle read from your FL installation)")
  2210. : granulizer ? tr ("Fruity Granulizer — FL's engine on the channel's sample")
  2211. : drumaxx ? tr ("Drumaxx — FL's physical drum engine (pads on their keys; patterns not played)")
  2212. : slayer ? tr ("FL Slayer — FL's engine with its effects, amp and cabinet (picks read from your FL installation; new settings restart the voices)")
  2213. : sytrus ? tr ("Sytrus — FL's engine, main settings (operators, filters and effects keep the saved patch)")
  2214. : pocketSuperSaw ? tr ("Pocket SuperSaw — LYNX's engine for FL Studio Mobile's SuperSaw")
  2215. : fruityDance ? tr ("Fruity Dance — a visual plugin: it makes no sound, the channel keeps its settings")
  2216. : boobass ? tr ("BooBass — FL's engine, its sound read from your FL installation (knobs: 3-band EQ)")
  2217. : sakura ? tr ("Sakura — physical strings (FL's engine; new parameters apply to the next note)")
  2218. : tr ("Drumpad — physical drum (FL's engine; new parameters apply to the next hit)");
  2219. }
  2220. // round 172a: a designed page shows only the plugin and what it is; the notes in brackets (data files, what restarts
  2221. // the voices...) are the header's tooltip instead of text on the page
  2222. juce::String shownDescription() const
  2223. {
  2224. const auto full = description();
  2225. if (layout == nullptr)
  2226. return full;
  2227. auto at = full.indexOfChar ('(');
  2228. if (const auto wide = full.indexOfChar ((juce::juce_wchar) 0xff08); wide > 0 && (at < 0 || wide < at)) // a full-width bracket
  2229. at = wide;
  2230. return at > 0 ? full.substring (0, at).trimEnd() : full;
  2231. }
  2232. juce::String getTooltip() override
  2233. {
  2234. const auto full = description();
  2235. if (layout != nullptr && ! engineFilesMissing) // round 190in (FW-6): the line left the page; the page says it
  2236. return full;
  2237. if (! engineFilesMissing && descriptionArea().contains (getMouseXYRelative()) && shownDescription() != full)
  2238. return full;
  2239. return {};
  2240. }
  2241. // the engine's one-line description at the top (round 169h: wrapped to a second line above the knob grid, or shrunk a
  2242. // little on a designed page, instead of cut with "…" in a narrow window); clear of the sample button
  2243. juce::Rectangle<int> descriptionArea() const
  2244. {
  2245. const auto right = sampleButton.isVisible() ? getWidth() - 136 : getWidth() - 10;
  2246. return { 10, layout != nullptr ? 6 : 2, juce::jmax (40, right - 10), layout != nullptr ? 20 : 30 }; // (the knob grid's captions start at y 32)
  2247. }
  2248. void resized() override
  2249. {
  2250. if (sampleButton.isVisible())
  2251. sampleButton.setBounds (getWidth() - 128, 4, 120, 24);
  2252. if (layout != nullptr)
  2253. {
  2254. resizeLayout();
  2255. if (artLayer != nullptr)
  2256. {
  2257. artLayer->setBounds (getLocalBounds());
  2258. artLayer->setStage (artStage());
  2259. artLayer->toFront (false);
  2260. }
  2261. return;
  2262. }
  2263. constexpr int columns = 7, w = 96, h = 92;
  2264. for (std::size_t i = 0; i < knobs.size(); ++i)
  2265. knobs[i]->setBounds (12 + (int) (i % columns) * (w + 4), 46 + (int) (i / columns) * (h + 18), w, h);
  2266. if (granulizerModes)
  2267. {
  2268. // FL's KEY TO, TRANSIENTS and TEMPO LOCKED controls, in a row under the knobs
  2269. const auto rows = ((int) knobs.size() + columns - 1) / columns;
  2270. const auto y = 46 + rows * (h + 18) + 4;
  2271. granKeyToLabel.setBounds (12, y, 150, 18);
  2272. granKeyTo.setBounds (12, y + 20, 150, 24);
  2273. granTransientsLabel.setBounds (174, y, 150, 18);
  2274. granTransients.setBounds (174, y + 20, 150, 24);
  2275. granTempoLocked.setBounds (336, y + 20, 140, 24);
  2276. granBeatsLabel.setBounds (488, y, 200, 18);
  2277. granBeats.setBounds (488, y + 20, 200, 24);
  2278. }
  2279. }
  2280. // FL's Granulizer takes a sample dropped on its window (from the Browser or the system) and plays it; before, the
  2281. // drop fell through to the Playlist under the window and made an audio clip (audit 165)
  2282. bool isInterestedInDragSource (const SourceDetails& details) override
  2283. {
  2284. return takesSample() && BrowserComponent::isBrowserDrag (details) && SampleLibrary::isSampleFile (BrowserComponent::draggedFile (details));
  2285. }
  2286. void itemDragEnter (const SourceDetails&) override { setDropHighlight (true); }
  2287. void itemDragExit (const SourceDetails&) override { setDropHighlight (false); }
  2288. void itemDropped (const SourceDetails& details) override
  2289. {
  2290. setDropHighlight (false);
  2291. loadGranulizerSample (BrowserComponent::draggedFile (details));
  2292. }
  2293. bool isInterestedInFileDrag (const juce::StringArray& files) override
  2294. {
  2295. return takesSample() && files.size() == 1 && SampleLibrary::isSampleFile (juce::File (files[0]));
  2296. }
  2297. void fileDragEnter (const juce::StringArray&, int, int) override { setDropHighlight (true); }
  2298. void fileDragExit (const juce::StringArray&) override { setDropHighlight (false); }
  2299. void filesDropped (const juce::StringArray& files, int, int) override
  2300. {
  2301. setDropHighlight (false);
  2302. loadGranulizerSample (juce::File (files[0]));
  2303. }
  2304. void paintOverChildren (juce::Graphics& g) override
  2305. {
  2306. if (dropHighlight)
  2307. {
  2308. g.setColour (theme::colour::accent);
  2309. g.drawRect (getLocalBounds(), 2);
  2310. }
  2311. }
  2312. private:
  2313. bool takesSample() const
  2314. {
  2315. const auto* c = ref.get (engine);
  2316. return c != nullptr && projectcontents::pluginWindowTakesSample (c->instrument);
  2317. }
  2318. void setDropHighlight (bool on)
  2319. {
  2320. if (dropHighlight != on)
  2321. {
  2322. dropHighlight = on;
  2323. repaint();
  2324. }
  2325. }
  2326. // the Granulizer plays the new sample with the same settings (FL keeps the knobs and the channel's name)
  2327. // --- round 168q: the displays of the group-D pages ---------------------------------------------------------
  2328. const ChannelDef* channelNow() const { return ref.get (engine); }
  2329. // BeepMap: the bitmap, stretched to the display (red = left, green = right, as the engine reads it)
  2330. void paintBeepMapImage (juce::Graphics& g, juce::Rectangle<float> r)
  2331. {
  2332. const auto* c = channelNow();
  2333. const auto pic = c != nullptr ? beepMapPicture (c->pluginState) : std::nullopt;
  2334. if (! pic || pic->width <= 0 || pic->height <= 0)
  2335. return;
  2336. if (beepMapCacheState != c->pluginState)
  2337. {
  2338. beepMapCacheState = c->pluginState;
  2339. beepMapCache = juce::Image (juce::Image::RGB, pic->width, pic->height, false);
  2340. for (int y = 0; y < pic->height; ++y)
  2341. for (int x = 0; x < pic->width; ++x)
  2342. {
  2343. const auto* px = pic->bgr.data() + 3 * ((std::size_t) y * (std::size_t) pic->width + (std::size_t) x);
  2344. beepMapCache.setPixelAt (x, y, juce::Colour (px[2], px[1], px[0]));
  2345. }
  2346. }
  2347. g.setImageResamplingQuality (juce::Graphics::lowResamplingQuality);
  2348. g.drawImage (beepMapCache, r, juce::RectanglePlacement::stretchToFit);
  2349. g.setImageResamplingQuality (juce::Graphics::mediumResamplingQuality);
  2350. }
  2351. void paintBeepMapFile (juce::Graphics& g, juce::Rectangle<float> r, float f)
  2352. {
  2353. using namespace theme;
  2354. const auto* c = channelNow();
  2355. const auto pic = c != nullptr ? beepMapPicture (c->pluginState) : std::nullopt;
  2356. auto row = r.reduced (4.0f * f);
  2357. const auto w = row.getWidth() / 3.2f;
  2358. const juce::String caps[] = { tr ("Open..."), tr ("Paste") };
  2359. for (int i = 0; i < 2; ++i)
  2360. {
  2361. const auto cell = row.removeFromLeft (w).reduced (2.0f * f, 0.0f);
  2362. skin::button (g, cell, false, false, accent, radius::sm * f);
  2363. g.setColour (colour::textPrimary);
  2364. g.setFont (font (juce::jmax (8.0f, juce::jmin (11.0f * f, cell.getHeight() * 0.5f)), true));
  2365. g.drawFittedText (caps[i], cell.toNearestInt(), juce::Justification::centred, 1, 0.6f);
  2366. }
  2367. g.setColour (colour::textSecondary);
  2368. g.setFont (font (juce::jmax (8.0f, 10.0f * f)));
  2369. const auto text = pic ? tr ("{0} × {1} pixels", { juce::String (pic->width), juce::String (pic->height) }) : tr ("No bitmap");
  2370. g.drawFittedText (text, row.reduced (4.0f * f, 0.0f).toNearestInt(), juce::Justification::centredLeft, 2, 0.7f);
  2371. }
  2372. // which button of the BeepMap file row is under `p` (0 open, 1 paste, −1 none)
  2373. int beepMapFileButton (const plugui::LayoutItem& item, juce::Point<float> p) const
  2374. {
  2375. auto row = layoutRect (item).reduced (4.0f * layoutFactor());
  2376. const auto w = row.getWidth() / 3.2f;
  2377. for (int i = 0; i < 2; ++i)
  2378. if (row.removeFromLeft (w).contains (p))
  2379. return i;
  2380. return -1;
  2381. }
  2382. void setBeepMapBitmap (const std::vector<std::uint8_t>& bmp)
  2383. {
  2384. const auto* c = channelNow();
  2385. if (c == nullptr)
  2386. return;
  2387. auto next = beepMapWithBitmap (c->pluginState, bmp);
  2388. if (next.empty())
  2389. {
  2390. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, juce::String ("BeepMap"),
  2391. tr ("BeepMap reads uncompressed 24- or 32-bit BMP pictures at least 3 pixels high."));
  2392. return;
  2393. }
  2394. ref.edit (engine, [next = std::move (next)] (ChannelDef& d) { d.pluginState = next; });
  2395. repaint();
  2396. }
  2397. void beepMapAction (int button)
  2398. {
  2399. if (button == 1) // a BMP file path or the file itself copied in the clipboard
  2400. {
  2401. const juce::File file (juce::SystemClipboard::getTextFromClipboard().trim().unquoted());
  2402. juce::MemoryBlock data;
  2403. if (file.existsAsFile() && file.loadFileAsData (data))
  2404. setBeepMapBitmap (std::vector<std::uint8_t> ((const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize()));
  2405. else
  2406. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, juce::String ("BeepMap"), tr ("Copy a .bmp file's path first, or use Open."));
  2407. return;
  2408. }
  2409. chooser = lynx::ui::makeFileChooser (tr ("Open a bitmap"), juce::File(), "*.bmp");
  2410. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  2411. [safe = juce::Component::SafePointer<ModelPanel> (this)] (const juce::FileChooser& fc) {
  2412. juce::MemoryBlock data;
  2413. if (safe == nullptr || ! fc.getResult().loadFileAsData (data))
  2414. return;
  2415. safe->setBeepMapBitmap (std::vector<std::uint8_t> ((const std::uint8_t*) data.getData(),
  2416. (const std::uint8_t*) data.getData() + data.getSize()));
  2417. });
  2418. }
  2419. // Granulizer: the channel's sample (or how to give it one) with the start point
  2420. void paintGranulizerWave (juce::Graphics& g, juce::Rectangle<float> r, float f)
  2421. {
  2422. using namespace theme;
  2423. const auto* c = channelNow();
  2424. const auto path = c != nullptr ? c->samplePath : std::string();
  2425. if (path.empty())
  2426. {
  2427. g.setColour (colour::textSecondary);
  2428. g.setFont (font (juce::jmax (9.0f, 11.0f * f)));
  2429. g.drawFittedText (tr ("Drop a sample here (or on the channel button)"), r.toNearestInt(), juce::Justification::centred, 2, 0.7f);
  2430. return;
  2431. }
  2432. if (path != granulizerPeaksPath)
  2433. {
  2434. granulizerPeaksPath = path;
  2435. granulizerPeaks.clear();
  2436. if (const auto s = engine.getSampleLibrary().load (juce::String::fromUTF8 (path.c_str())))
  2437. {
  2438. const auto n = (std::int64_t) s->left.size();
  2439. constexpr int columns = 400;
  2440. for (int i = 0; i < columns && n > 0; ++i)
  2441. {
  2442. float peak = 0.0f;
  2443. for (auto k = n * i / columns; k < n * (i + 1) / columns; ++k)
  2444. peak = std::max ({ peak, std::fabs (s->left[(std::size_t) k]), s->right.empty() ? 0.0f : std::fabs (s->right[(std::size_t) k]) });
  2445. granulizerPeaks.push_back (std::min (peak, 1.0f));
  2446. }
  2447. }
  2448. }
  2449. if (granulizerPeaks.empty())
  2450. return;
  2451. const auto mid = r.getCentreY();
  2452. juce::Path wave;
  2453. for (int i = 0; i < (int) granulizerPeaks.size(); ++i)
  2454. {
  2455. const auto x = r.getX() + r.getWidth() * (float) i / (float) (granulizerPeaks.size() - 1);
  2456. wave.addRectangle (x, mid - granulizerPeaks[(std::size_t) i] * r.getHeight() * 0.48f, juce::jmax (1.0f, r.getWidth() / (float) granulizerPeaks.size()),
  2457. juce::jmax (1.0f, granulizerPeaks[(std::size_t) i] * r.getHeight() * 0.96f));
  2458. }
  2459. g.setColour (accent.withAlpha (0.65f));
  2460. g.fillPath (wave);
  2461. if (const auto* k = knobFor ("Sample start"))
  2462. {
  2463. const auto x = r.getX() + r.getWidth() * normalised (*k);
  2464. g.setColour (colour::textPrimary);
  2465. g.drawVerticalLine ((int) x, r.getY(), r.getBottom());
  2466. }
  2467. g.setColour (colour::textSecondary);
  2468. g.setFont (font (juce::jmax (8.0f, 9.5f * f)));
  2469. g.drawFittedText (juce::File (juce::String::fromUTF8 (path.c_str())).getFileName(), r.removeFromTop (14.0f * f).toNearestInt(),
  2470. juce::Justification::topLeft, 1, 0.8f);
  2471. }
  2472. // Granulizer: one grain's envelope (attack, hold, release) and the next grain's start, from the knobs
  2473. void paintGranulizerGrains (juce::Graphics& g, juce::Rectangle<float> r, float)
  2474. {
  2475. using namespace theme;
  2476. const auto* att = knobFor ("Grain attack");
  2477. const auto* hold = knobFor ("Grain hold");
  2478. const auto* spacing = knobFor ("Grain spacing");
  2479. if (att == nullptr || hold == nullptr || spacing == nullptr)
  2480. return;
  2481. const auto a = (float) att->getValue(), h = (float) hold->getValue(), sp = (float) spacing->getValue();
  2482. const auto total = juce::jmax (1.0f, 2.0f * a + h + sp);
  2483. const auto xOf = [&] (float t) { return r.getX() + r.getWidth() * t / total; };
  2484. for (int grain = 0; grain < 2; ++grain)
  2485. {
  2486. const auto t0 = (float) grain * sp;
  2487. juce::Path p;
  2488. p.startNewSubPath (xOf (t0), r.getBottom());
  2489. p.lineTo (xOf (t0 + a), r.getY());
  2490. p.lineTo (xOf (t0 + a + h), r.getY());
  2491. p.lineTo (xOf (t0 + 2.0f * a + h), r.getBottom());
  2492. g.setColour ((grain == 0 ? accent : colour::textSecondary).withAlpha (0.8f));
  2493. g.strokePath (p, juce::PathStrokeType (1.5f));
  2494. }
  2495. }
  2496. // Transistor Bass: the current program and its sequence (16 steps: note, gate, accent, slide)
  2497. void paintTransistorBass (juce::Graphics& g, juce::Rectangle<float> r, float f)
  2498. {
  2499. using namespace theme;
  2500. const auto* c = channelNow();
  2501. const auto prog = c != nullptr ? transistorBassProgram (c->pluginState) : std::nullopt;
  2502. if (! prog)
  2503. return;
  2504. g.setColour (colour::textPrimary);
  2505. g.setFont (font (juce::jmax (9.0f, 11.0f * f), true));
  2506. const auto text = tr ("Program {0}", { juce::String (prog->program + 1) }) + " "
  2507. + (prog->sequencer ? tr ("sequencer on") : tr ("sequencer off"))
  2508. + (prog->transpose != 0 ? " " + tr ("transpose {0}", { juce::String (prog->transpose) }) : juce::String());
  2509. g.drawFittedText (text, r.reduced (6.0f * f, 0.0f).toNearestInt(), juce::Justification::centredLeft, 1, 0.7f);
  2510. }
  2511. // the step numbers under the sequence, lit up to its length (round 168q2)
  2512. void paintTransistorBassSteps (juce::Graphics& g, juce::Rectangle<float> r, float f)
  2513. {
  2514. using namespace theme;
  2515. const auto* c = channelNow();
  2516. const auto prog = c != nullptr ? transistorBassProgram (c->pluginState) : std::nullopt;
  2517. const auto length = prog ? juce::jlimit (1, 16, prog->length) : 16;
  2518. const auto w = r.getWidth() / 16.0f;
  2519. g.setFont (font (juce::jmax (8.0f, 10.0f * f), true));
  2520. for (int i = 0; i < 16; ++i)
  2521. {
  2522. const auto cell = juce::Rectangle<float> (r.getX() + w * (float) i, r.getY(), w, r.getHeight()).reduced (2.0f * f, 4.0f * f);
  2523. const auto in = i < length;
  2524. g.setColour (in ? accent.withAlpha (0.22f) : colour::bg3);
  2525. g.fillRoundedRectangle (cell, radius::sm * f);
  2526. g.setColour (in ? colour::textPrimary : colour::textDisabled);
  2527. g.drawText (juce::String (i + 1), cell, juce::Justification::centred, false);
  2528. }
  2529. }
  2530. static constexpr int transistorBassTools = 3;
  2531. juce::Rectangle<float> transistorBassToolCell (juce::Rectangle<float> r, int i) const
  2532. {
  2533. const auto h = r.getHeight() / (float) transistorBassTools;
  2534. return juce::Rectangle<float> (r.getX(), r.getY() + h * (float) i, r.getWidth(), h).reduced (2.0f * layoutFactor());
  2535. }
  2536. void paintTransistorBassTools (juce::Graphics& g, juce::Rectangle<float> r, float f)
  2537. {
  2538. using namespace theme;
  2539. const juce::String caps[] = { tr ("Clear"), juce::String::fromUTF8 ("Oct +"), juce::String::fromUTF8 ("Oct \xe2\x88\x92") };
  2540. for (int i = 0; i < transistorBassTools; ++i)
  2541. {
  2542. const auto cell = transistorBassToolCell (r, i);
  2543. skin::button (g, cell, false, false, accent, radius::sm * f);
  2544. g.setColour (colour::textPrimary);
  2545. g.setFont (font (juce::jmax (8.0f, juce::jmin (10.0f * f, cell.getHeight() * 0.45f)), true));
  2546. g.drawFittedText (caps[i], cell.toNearestInt(), juce::Justification::centred, 1, 0.6f);
  2547. }
  2548. }
  2549. int transistorBassToolButton (const plugui::LayoutItem& item, juce::Point<float> p) const
  2550. {
  2551. for (int i = 0; i < transistorBassTools; ++i)
  2552. if (transistorBassToolCell (layoutRect (item), i).contains (p))
  2553. return i;
  2554. return -1;
  2555. }
  2556. // FL's CLEAR (gates, slides and accents off, notes C5) and its octave up / down buttons on the whole sequence
  2557. void transistorBassToolAction (int button)
  2558. {
  2559. const auto* c = channelNow();
  2560. if (c == nullptr)
  2561. return;
  2562. auto next = c->pluginState;
  2563. if (! (button == 0 ? transistorBassClearSequence (next) : transistorBassShiftSequence (next, button == 1 ? 1 : -1)))
  2564. return;
  2565. ref.edit (engine, [next = std::move (next)] (ChannelDef& d) { d.pluginState = next; });
  2566. syncKnobs();
  2567. repaint();
  2568. }
  2569. juce::Image beepMapCache;
  2570. std::vector<std::uint8_t> beepMapCacheState;
  2571. std::string granulizerPeaksPath;
  2572. std::vector<float> granulizerPeaks;
  2573. void loadGranulizerSample (const juce::File& file)
  2574. {
  2575. if (! takesSample() || ! file.existsAsFile())
  2576. return;
  2577. if (engine.getSampleLibrary().load (file.getFullPathName()) == nullptr)
  2578. {
  2579. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Sample"), tr ("Could not read {0}", { file.getFileName() }));
  2580. return;
  2581. }
  2582. ref.edit (engine, [path = file.getFullPathName().toStdString()] (ChannelDef& d) { d.samplePath = path; });
  2583. if (sampleButton.isVisible())
  2584. ui::setHint (sampleButton, file.getFullPathName());
  2585. repaint();
  2586. }
  2587. bool dropHighlight = false;
  2588. // Fruity Granulizer: what the keys move (Key to), where the slices come from (Transients), tempo lock and the beat
  2589. // count it uses (REA_rodada165g-flgran165)
  2590. void setupGranulizerModes (const ChannelDef& def)
  2591. {
  2592. const auto keyMode = granulizerMode (def.pluginState, 1), sliceMode = granulizerMode (def.pluginState, 0),
  2593. sync = granulizerMode (def.pluginState, 2);
  2594. if (! keyMode || ! sliceMode || ! sync)
  2595. return;
  2596. granulizerModes = true;
  2597. auto label = [this] (juce::Label& l, const juce::String& text) {
  2598. l.setText (text, juce::dontSendNotification);
  2599. l.setFont (theme::font (theme::type::small));
  2600. addAndMakeVisible (l);
  2601. };
  2602. label (granKeyToLabel, tr ("Key to"));
  2603. granKeyTo.addItem (tr ("Pitch"), 1);
  2604. granKeyTo.addItem (tr ("Percent"), 2);
  2605. granKeyTo.addItem (tr ("Step"), 3);
  2606. granKeyTo.addItem (tr ("Transient"), 4);
  2607. granKeyTo.setSelectedId (std::clamp (*keyMode, 0, 3) + 1, juce::dontSendNotification);
  2608. granKeyTo.setTooltip (tr ("What the keys do: Pitch = transpose; Percent = start point (sample time, C5 to C7); "
  2609. "Step = start point in 16th notes (song time); Transient = start at the slice of the key"));
  2610. granKeyTo.onChange = [this] {
  2611. const auto v = granKeyTo.getSelectedId() - 1;
  2612. ref.edit (engine, [v] (ChannelDef& d) { granulizerSetMode (d.pluginState, 1, v); });
  2613. if (v == 3 && granTransients.getSelectedId() == 1) // as FL: transient keys switch slice detection on
  2614. granTransients.setSelectedId (3, juce::dontSendNotification);
  2615. };
  2616. addAndMakeVisible (granKeyTo);
  2617. label (granTransientsLabel, tr ("Transients"));
  2618. granTransients.addItem (tr ("Off"), 1);
  2619. granTransients.addItem (tr ("Use regions"), 2);
  2620. granTransients.addItem (tr ("Detect"), 3);
  2621. granTransients.setSelectedId (std::clamp (*sliceMode, 0, 2) + 1, juce::dontSendNotification);
  2622. granTransients.setTooltip (tr ("Transients source: the sample's cue points / regions, or FL's automatic slicing. "
  2623. "Grains then line up with the slices and the Transient hold knob sets how long each "
  2624. "slice's first grain holds"));
  2625. granTransients.onChange = [this] {
  2626. const auto v = granTransients.getSelectedId() - 1;
  2627. ref.edit (engine, [v] (ChannelDef& d) { granulizerSetMode (d.pluginState, 0, v); });
  2628. };
  2629. addAndMakeVisible (granTransients);
  2630. granTempoLocked.setButtonText (tr ("Tempo locked"));
  2631. granTempoLocked.setToggleState (*sync != 0, juce::dontSendNotification);
  2632. granTempoLocked.setTooltip (tr ("Match song tempo: the sample plays once per its length in beats (the WAV's ACID "
  2633. "beats, else Beats below). Loop is always on and Wave spacing has no effect while "
  2634. "locked"));
  2635. granTempoLocked.onClick = [this] {
  2636. const auto on = granTempoLocked.getToggleState();
  2637. ref.edit (engine, [on] (ChannelDef& d) { granulizerSetMode (d.pluginState, 2, on ? 1 : 0); });
  2638. };
  2639. addAndMakeVisible (granTempoLocked);
  2640. label (granBeatsLabel, tr ("Beats (0 = the sample's own)"));
  2641. granBeats.setSliderStyle (juce::Slider::LinearHorizontal);
  2642. granBeats.setTextBoxStyle (juce::Slider::TextBoxRight, false, 56, 20);
  2643. granBeats.setRange (0.0, 1024.0, 0.01);
  2644. granBeats.setValue (def.sampler.stretchBeats, juce::dontSendNotification);
  2645. granBeats.setTooltip (tr ("The sample's length in beats for Tempo locked and the Step keys, as FL's time-stretch "
  2646. "TIME; a WAV with ACID beats uses its own"));
  2647. granBeats.onValueChange = [this] {
  2648. const auto v = (float) granBeats.getValue();
  2649. ref.edit (engine, [v] (ChannelDef& d) { d.sampler.stretchBeats = v; });
  2650. };
  2651. addAndMakeVisible (granBeats);
  2652. }
  2653. bool granulizerModes = false;
  2654. juce::ComboBox granKeyTo, granTransients;
  2655. juce::ToggleButton granTempoLocked;
  2656. juce::Slider granBeats;
  2657. juce::Label granKeyToLabel, granTransientsLabel, granBeatsLabel;
  2658. AudioEngine& engine;
  2659. ChannelRef ref;
  2660. juce::Colour accent { skin::colour::crimson }; // the plugin page's accent (ui/PluginSkin.h)
  2661. skin::Style pageStyle = skin::Style::glow; // the plugin page's automatic style (round 126)
  2662. skin::Art pageArt = skin::Art::none; // its own art (round 170j: Themed)
  2663. std::unique_ptr<skin::ArtLayer> artLayer; // the art's moving part (petals, a glowing trefoil...)
  2664. bool sakura = true, boobass = false, drumsynth = false, harmless = false, harmor = false, gms = false, morphine = false, ogun = false, autogun = false, transistorBass = false, transistorBassMobile = false, miniSynth = false, dx10 = false, kepler = false, keplerExo = false, poizone = false,
  2665. fruitkick = false, bassdrum = false, toxic = false, threeOsc = false, simSynth = false, wasp = false, plucked = false, beepMap = false,
  2666. sawer = false, flKeys = false, granulizer = false, drumaxx = false, slayer = false, fruityDance = false, pocketSuperSaw = false, sytrus = false, wavesFound = false,
  2667. engineFilesMissing = false;
  2668. int editorKey = 60;
  2669. int drumPart = 0; // round 168p: the Drumaxx pad / DrumSynth Live key the per-part knobs edit
  2670. std::vector<std::pair<juce::Slider*, const drumcontrols::Control*>> partKnobs;
  2671. std::vector<std::pair<juce::Slider*, int>> modelKnobs; // a listed parameter's knob -> its index (issue #152)
  2672. std::vector<const juce::Slider*> automatedShown; // the knobs showing their automation now
  2673. std::uint32_t shownGeneration = 0;
  2674. std::vector<std::uint8_t> seenState; // the channel's state the knobs show (issue #152)
  2675. std::vector<float> seenParams;
  2676. int programTicks = 0;
  2677. std::vector<std::unique_ptr<juce::Slider>> knobs;
  2678. const plugui::Layout* layout = nullptr;
  2679. plugui::Layout hostedLayout;
  2680. std::string hostedName;
  2681. const modelparams::Table* modelTable = nullptr; // the engine's listed parameters (round 168n)
  2682. InstrumentKind instrumentKind = InstrumentKind::synth;
  2683. const plugui::LayoutItem* stepperDrag = nullptr; // (round 169h)
  2684. float stepperDragY = 0.0f;
  2685. int stepperDragged = 0;
  2686. int page = 0; // the layout's page shown (pageTabs items switch it; round 168n)
  2687. const plugui::LayoutItem* xyItem = nullptr; // the pad being dragged
  2688. juce::TextButton sampleButton; // (a Granulizer node: round 165c)
  2689. std::unique_ptr<juce::FileChooser> chooser;
  2690. };
  2691. // FL's Sampler › "Precomputed effects", the loop flags and the declicking mode (REA_rodada167h §1–§3): computed once on
  2692. // the sample when the channel changes (core/SamplePrecompute.h). Opened from the Sampler settings.
  2693. class PrecomputePanel final : public juce::Component
  2694. {
  2695. public:
  2696. PrecomputePanel (AudioEngine& e, ChannelRef c) : engine (e), ref (std::move (c))
  2697. {
  2698. const std::pair<juce::ToggleButton*, const char*> toggles[] = {
  2699. { &removeDc, TR_NOOP ("Remove DC offset") }, { &normalize, TR_NOOP ("Normalize") }, { &polarity, TR_NOOP ("Reverse polarity") },
  2700. { &fadeStereo, TR_NOOP ("Fade stereo") }, { &swapStereo, TR_NOOP ("Swap stereo") },
  2701. { &useLoops, TR_NOOP ("Use loop points") }, { &pingPong, TR_NOOP ("Ping pong loop") } };
  2702. for (auto [b, text] : toggles)
  2703. {
  2704. b->setButtonText (tr (text));
  2705. b->onClick = [this] { apply(); };
  2706. addAndMakeVisible (b);
  2707. }
  2708. normalize.setTooltip (tr ("Raises the sample so its loudest point reaches 0 dB"));
  2709. fadeStereo.setTooltip (tr ("The left channel fades out over the sample while the right one fades in"));
  2710. useLoops.setTooltip (tr ("Plays the loop stored in the sample file (WAV loop points)"));
  2711. pingPong.setTooltip (tr ("The loop plays forward, then backward"));
  2712. const std::tuple<juce::Slider*, juce::Label*, const char*, double> knobs[] = {
  2713. { &fadeIn, &fadeInLabel, TR_NOOP ("Fade in"), 1024.0 }, { &fadeOut, &fadeOutLabel, TR_NOOP ("Fade out"), 1024.0 },
  2714. { &crossfade, &crossfadeLabel, TR_NOOP ("Crossfade"), 2048.0 }, { &trim, &trimLabel, TR_NOOP ("Trim"), 32768.0 } };
  2715. for (auto [k, label, text, hi] : knobs)
  2716. {
  2717. k->setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  2718. k->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 70, 18);
  2719. k->setRange (0.0, hi, 1.0);
  2720. k->setDoubleClickReturnValue (true, 0.0);
  2721. k->onValueChange = [this] { apply(); };
  2722. addAndMakeVisible (k);
  2723. label->setText (tr (text), juce::dontSendNotification);
  2724. label->setJustificationType (juce::Justification::centred);
  2725. addAndMakeVisible (label);
  2726. }
  2727. auto percent = [] (double hi) { return [hi] (double v) { return juce::String (v / hi * 100.0, 1) + "%"; }; };
  2728. fadeIn.textFromValueFunction = percent (1024.0);
  2729. fadeOut.textFromValueFunction = percent (1024.0);
  2730. crossfade.textFromValueFunction = percent (2048.0);
  2731. trim.textFromValueFunction = [] (double v) {
  2732. return v <= 0.0 ? tr ("Off") : juce::String (20.0 * std::log10 (v / 32768.0), 1) + " dB";
  2733. };
  2734. fadeIn.setTooltip (tr ("Fades the sample in: 25% ramps over the whole sample, 100% over its last quarter"));
  2735. fadeOut.setTooltip (tr ("Fades the sample out: 25% over the whole sample, 100% within its first quarter"));
  2736. crossfade.setTooltip (tr ("Crossfades the loop's end into its start (a share of the loop), for a smooth loop"));
  2737. trim.setTooltip (tr ("Cuts the silence below this level at the sample's start and end"));
  2738. declickLabel.setText (tr ("Declicking mode"), juce::dontSendNotification);
  2739. addAndMakeVisible (declickLabel);
  2740. for (const auto* name : samplerpage::declickModeNames) // (FL's items, round 190dh)
  2741. declick.addItem (tr (name), declick.getNumItems() + 1);
  2742. declick.setTooltip (tr ("How fast a cut note fades out: 10 ms (out only, transient no bleeding), 20 ms (transient, generic), 100 ms (smooth), 200 ms (crossfade)"));
  2743. declick.onChange = [this] { apply(); };
  2744. addAndMakeVisible (declick);
  2745. // FL's legacy effects page (REA_rodada167l §1): FL's knob ranges, defaults and hints
  2746. legacyHeader.setText (tr ("Legacy effects"), juce::dontSendNotification);
  2747. legacyHeader.setFont (juce::FontOptions (13.0f, juce::Font::bold));
  2748. addAndMakeVisible (legacyHeader);
  2749. const std::tuple<juce::Slider*, juce::Label*, const char*, const char*, double, double, double> legacy[] = {
  2750. { &boost, &boostLabel, TR_NOOP ("Boost"), TR_NOOP ("Boosts the gain"), 0.0, 256.0, 0.0 },
  2751. { &eq, &eqLabel, TR_NOOP ("EQ"), TR_NOOP ("Shifts the frequency balance"), 0.0, 256.0, 128.0 },
  2752. { &ringMix, &ringMixLabel, TR_NOOP ("RM mix"), TR_NOOP ("Ring modulation mix"), 0.0, 256.0, 0.0 },
  2753. { &ringFreq, &ringFreqLabel, TR_NOOP ("RM freq"), TR_NOOP ("Ring modulation frequency"), 0.0, 256.0, 128.0 },
  2754. { &pogo, &pogoLabel, TR_NOOP ("Pogo"), TR_NOOP ("Pogo effect"), 0.0, 512.0, 256.0 },
  2755. { &cutoff, &cutoffLabel, TR_NOOP ("Cut"), TR_NOOP ("Filter cutoff"), 16.0, 1024.0, 1024.0 },
  2756. { &resonance, &resonanceLabel, TR_NOOP ("Res"), TR_NOOP ("Filter resonance"), 0.0, 640.0, 0.0 },
  2757. { &stereoDelay, &stereoDelayLabel, TR_NOOP ("Stereo delay"), TR_NOOP ("Stereo delay"), 0.0, 4096.0, 2048.0 },
  2758. { &reverbAmount, &reverbLabel, TR_NOOP ("Reverb"), TR_NOOP ("Reverb amount"), 0.0, 256.0, 0.0 } };
  2759. for (auto [k, label, text, hint, lo, hi, def] : legacy)
  2760. {
  2761. k->setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  2762. k->setTextBoxStyle (juce::Slider::TextBoxBelow, false, 56, 18);
  2763. k->setRange (lo, hi, 1.0);
  2764. k->setValue (def, juce::dontSendNotification);
  2765. k->setDoubleClickReturnValue (true, def);
  2766. k->setTooltip (tr (hint));
  2767. k->onValueChange = [this] { apply(); };
  2768. addAndMakeVisible (k);
  2769. label->setText (tr (text), juce::dontSendNotification);
  2770. label->setJustificationType (juce::Justification::centred);
  2771. addAndMakeVisible (label);
  2772. }
  2773. reverbType.addItemList ({ tr ("Type 1"), tr ("Type 2") }, 1);
  2774. reverbType.setTooltip (tr ("Reverb type"));
  2775. reverbType.onChange = [this] { apply(); };
  2776. addAndMakeVisible (reverbType);
  2777. clip.setButtonText (tr ("Clip"));
  2778. clip.setTooltip (tr ("Add clipping at 0dB"));
  2779. clip.onClick = [this] { apply(); };
  2780. addAndMakeVisible (clip);
  2781. load();
  2782. setSize (500, 560);
  2783. }
  2784. void resized() override
  2785. {
  2786. auto area = getLocalBounds().reduced (12);
  2787. auto rows = area.removeFromTop (4 * 26);
  2788. auto left = rows.removeFromLeft (rows.getWidth() / 2);
  2789. for (auto* b : { &removeDc, &normalize, &polarity, &fadeStereo })
  2790. b->setBounds (left.removeFromTop (26));
  2791. for (auto* b : { &swapStereo, &useLoops, &pingPong })
  2792. b->setBounds (rows.removeFromTop (26));
  2793. area.removeFromTop (10);
  2794. auto knobRow = area.removeFromTop (110);
  2795. const auto w = knobRow.getWidth() / 4;
  2796. for (auto [k, label] : { std::pair { &fadeIn, &fadeInLabel }, { &fadeOut, &fadeOutLabel }, { &crossfade, &crossfadeLabel }, { &trim, &trimLabel } })
  2797. {
  2798. auto column = knobRow.removeFromLeft (w);
  2799. label->setBounds (column.removeFromTop (18));
  2800. k->setBounds (column);
  2801. }
  2802. area.removeFromTop (12);
  2803. auto row = area.removeFromTop (26);
  2804. declickLabel.setBounds (row.removeFromLeft (140));
  2805. declick.setBounds (row.removeFromLeft (220));
  2806. area.removeFromTop (14);
  2807. legacyHeader.setBounds (area.removeFromTop (20));
  2808. auto layoutRow = [] (juce::Rectangle<int> r, std::initializer_list<std::pair<juce::Slider*, juce::Label*>> knobs) {
  2809. const auto w = r.getWidth() / 5;
  2810. for (auto [k, label] : knobs)
  2811. {
  2812. auto column = r.removeFromLeft (w);
  2813. label->setBounds (column.removeFromTop (18));
  2814. k->setBounds (column);
  2815. }
  2816. return r;
  2817. };
  2818. layoutRow (area.removeFromTop (96), { { &boost, &boostLabel }, { &eq, &eqLabel }, { &ringMix, &ringMixLabel }, { &ringFreq, &ringFreqLabel }, { &pogo, &pogoLabel } });
  2819. area.removeFromTop (6);
  2820. auto last = layoutRow (area.removeFromTop (96), { { &cutoff, &cutoffLabel }, { &resonance, &resonanceLabel }, { &stereoDelay, &stereoDelayLabel }, { &reverbAmount, &reverbLabel } });
  2821. last.removeFromTop (22);
  2822. reverbType.setBounds (last.removeFromTop (24).reduced (4, 0));
  2823. last.removeFromTop (8);
  2824. clip.setBounds (last.removeFromTop (24).reduced (4, 0));
  2825. }
  2826. private:
  2827. void load()
  2828. {
  2829. const auto* c = ref.get (engine);
  2830. if (c == nullptr)
  2831. return;
  2832. const juce::ScopedValueSetter<bool> guard (loading, true);
  2833. const auto& p = c->sampler.precompute;
  2834. removeDc.setToggleState (p.removeDc, juce::dontSendNotification);
  2835. normalize.setToggleState (p.normalize, juce::dontSendNotification);
  2836. polarity.setToggleState (p.reversePolarity, juce::dontSendNotification);
  2837. fadeStereo.setToggleState (p.fadeStereo, juce::dontSendNotification);
  2838. swapStereo.setToggleState (p.swapStereo, juce::dontSendNotification);
  2839. useLoops.setToggleState (c->sampler.useLoopPoints, juce::dontSendNotification);
  2840. pingPong.setToggleState (p.pingPong, juce::dontSendNotification);
  2841. fadeIn.setValue (p.fadeIn, juce::dontSendNotification);
  2842. fadeOut.setValue (p.fadeOut, juce::dontSendNotification);
  2843. crossfade.setValue (p.crossfade, juce::dontSendNotification);
  2844. trim.setValue (p.trim, juce::dontSendNotification);
  2845. boost.setValue (p.boost, juce::dontSendNotification);
  2846. eq.setValue (p.eq, juce::dontSendNotification);
  2847. ringMix.setValue (p.ringMix, juce::dontSendNotification);
  2848. ringFreq.setValue (p.ringFreq, juce::dontSendNotification);
  2849. pogo.setValue (p.pogo, juce::dontSendNotification);
  2850. cutoff.setValue (p.cutoff, juce::dontSendNotification);
  2851. resonance.setValue (p.resonance, juce::dontSendNotification);
  2852. stereoDelay.setValue (p.stereoDelay, juce::dontSendNotification);
  2853. reverbAmount.setValue (p.reverb, juce::dontSendNotification);
  2854. reverbType.setSelectedId (p.reverbType == 0 ? 1 : 2, juce::dontSendNotification);
  2855. clip.setToggleState (p.clip, juce::dontSendNotification);
  2856. declick.setSelectedId (juce::jlimit (0, 5, c->sampler.declickMode) + 1, juce::dontSendNotification);
  2857. }
  2858. void apply()
  2859. {
  2860. if (loading)
  2861. return;
  2862. SamplePrecompute p;
  2863. p.removeDc = removeDc.getToggleState();
  2864. p.normalize = normalize.getToggleState();
  2865. p.reversePolarity = polarity.getToggleState();
  2866. p.fadeStereo = fadeStereo.getToggleState();
  2867. p.swapStereo = swapStereo.getToggleState();
  2868. p.pingPong = pingPong.getToggleState();
  2869. p.fadeIn = (int) fadeIn.getValue();
  2870. p.fadeOut = (int) fadeOut.getValue();
  2871. p.crossfade = (int) crossfade.getValue();
  2872. p.trim = (int) trim.getValue();
  2873. p.boost = (int) boost.getValue();
  2874. p.eq = (int) eq.getValue();
  2875. p.ringMix = (int) ringMix.getValue();
  2876. p.ringFreq = (int) ringFreq.getValue();
  2877. p.pogo = (int) pogo.getValue();
  2878. p.cutoff = (int) cutoff.getValue();
  2879. p.resonance = (int) resonance.getValue();
  2880. p.stereoDelay = (int) stereoDelay.getValue();
  2881. p.reverb = (int) reverbAmount.getValue();
  2882. p.reverbType = reverbType.getSelectedId() == 1 ? 0 : 1;
  2883. p.clip = clip.getToggleState();
  2884. const auto loops = useLoops.getToggleState();
  2885. const auto mode = juce::jlimit (0, 5, declick.getSelectedId() - 1);
  2886. const auto* c = ref.get (engine);
  2887. if (c == nullptr || (c->sampler.precompute == p && c->sampler.useLoopPoints == loops && c->sampler.declickMode == mode))
  2888. return;
  2889. ref.edit (engine, [p, loops, mode] (ChannelDef& d) {
  2890. d.sampler.precompute = p;
  2891. d.sampler.useLoopPoints = loops;
  2892. d.sampler.declickMode = mode;
  2893. });
  2894. }
  2895. AudioEngine& engine;
  2896. ChannelRef ref;
  2897. bool loading = false;
  2898. juce::ToggleButton removeDc, normalize, polarity, fadeStereo, swapStereo, useLoops, pingPong;
  2899. juce::Slider fadeIn, fadeOut, crossfade, trim;
  2900. juce::Label fadeInLabel, fadeOutLabel, crossfadeLabel, trimLabel, declickLabel;
  2901. juce::ComboBox declick;
  2902. juce::Label legacyHeader;
  2903. juce::Slider boost, eq, ringMix, ringFreq, pogo, cutoff, resonance, stereoDelay, reverbAmount;
  2904. juce::Label boostLabel, eqLabel, ringMixLabel, ringFreqLabel, pogoLabel, cutoffLabel, resonanceLabel, stereoDelayLabel, reverbLabel;
  2905. juce::ComboBox reverbType;
  2906. juce::ToggleButton clip;
  2907. };
  2908. // FL's Load button of the sampler's File row (round 190df): an icon button that also takes the mouse wheel (FL steps
  2909. // through the sample history with it [OpenBtnMouseWheel 0xf68f50])
  2910. class WheelIconButton final : public IconButton
  2911. {
  2912. public:
  2913. using IconButton::IconButton;
  2914. std::function<void (int)> onWheel; // +1 up, -1 down
  2915. void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& w) override
  2916. {
  2917. if (onWheel != nullptr && w.deltaY != 0.0f)
  2918. onWheel (w.deltaY > 0.0f ? 1 : -1);
  2919. else
  2920. IconButton::mouseWheelMove (e, w);
  2921. }
  2922. };
  2923. // FL's "effects target" selector at the head of the Precomputed effects box (round 190dh; form TPluginForm
  2924. // FXPanel.EffectsTargetSelect, 46 x 19, two cells; EffectsTargetSelectChange 0xf616d0 shows FXLegacyPanel for cell 1):
  2925. // a wrench (the effects) and the legacy effects
  2926. class EffectsTargetSelect final : public juce::Component, public juce::SettableTooltipClient
  2927. {
  2928. public:
  2929. std::function<void (int)> onChange;
  2930. int getIndex() const noexcept { return index; }
  2931. void setIndex (int i)
  2932. {
  2933. if (i != index)
  2934. {
  2935. index = i;
  2936. repaint();
  2937. }
  2938. }
  2939. void paint (juce::Graphics& g) override
  2940. {
  2941. const auto b = getLocalBounds().toFloat();
  2942. for (int i = 0; i < 2; ++i)
  2943. {
  2944. auto cell = b.withWidth (b.getWidth() / 2.0f).translated ((float) i * b.getWidth() / 2.0f, 0.0f).reduced (1.0f);
  2945. g.setColour (i == index ? theme::colour::bg6 : theme::colour::bg3);
  2946. g.fillRoundedRectangle (cell, 2.0f);
  2947. const auto colour = i == index ? theme::colour::warning : theme::colour::textSecondary;
  2948. const auto icon = cell.withSizeKeepingCentre (cell.getHeight() - 3.0f, cell.getHeight() - 3.0f);
  2949. if (i == 1)
  2950. icons::draw (g, Icon::mic, icon, colour);
  2951. else
  2952. {
  2953. // a wrench: a handle and an open jaw
  2954. const auto u = icon.getWidth() / 24.0f;
  2955. juce::Path p;
  2956. p.startNewSubPath (icon.getX() + 5.0f * u, icon.getBottom() - 5.0f * u);
  2957. p.lineTo (icon.getX() + 14.0f * u, icon.getY() + 10.0f * u);
  2958. g.setColour (colour);
  2959. g.strokePath (p, juce::PathStrokeType (3.2f * u, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  2960. juce::Path jaw;
  2961. jaw.addCentredArc (icon.getX() + 16.5f * u, icon.getY() + 7.5f * u, 5.0f * u, 5.0f * u, 0.0f, 0.9f, 5.4f, true);
  2962. g.strokePath (jaw, juce::PathStrokeType (2.6f * u, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  2963. }
  2964. }
  2965. }
  2966. void mouseDown (const juce::MouseEvent& e) override
  2967. {
  2968. const auto i = e.x < getWidth() / 2 ? 0 : 1;
  2969. if (i != index)
  2970. {
  2971. index = i;
  2972. repaint();
  2973. if (onChange != nullptr)
  2974. onChange (index);
  2975. }
  2976. }
  2977. private:
  2978. int index = 0;
  2979. };
  2980. // The Sampler page (round 190dh: FL's Sampler page, form TPluginForm.SmpSheet, 561 x 399, and the FL 2026 shot
  2981. // dock188a): File row, Content, Playback | Time stretching, Precomputed effects; the waveform; then "LYNX extras", the
  2982. // sampler controls FL's page has no place for (Gain, the envelope, the filter, Cut itself, Porta, Modulation).
  2983. class SettingsPanel final : public juce::Component,
  2984. public juce::DragAndDropTarget,
  2985. public juce::FileDragAndDropTarget,
  2986. private juce::ChangeListener,
  2987. private juce::ScrollBar::Listener,
  2988. private juce::Timer
  2989. {
  2990. public:
  2991. // the page in FL's form units (FL's 561 x 399 sheet, then LYNX's extras below it)
  2992. static constexpr int designWidth = 558, designHeight = 524;
  2993. static constexpr int clipDesignHeight = 390; // an audio clip's page: FL's sheet without LYNX's extras under it
  2994. static constexpr float defaultScale = 1.25f;
  2995. SettingsPanel (AudioEngine& e, ChannelRef c)
  2996. : engine (e),
  2997. ref (std::move (c))
  2998. {
  2999. if (const auto* def = ref.get (engine))
  3000. clipChannel = def->instrument == InstrumentKind::audioClip;
  3001. // ---- File row (round 190df; form GrooveBox, shot dock188a fl-05) ----
  3002. fileLabel.setText (tr ("File"), juce::dontSendNotification);
  3003. fileLabel.setJustificationType (juce::Justification::centredRight);
  3004. addAndMakeVisible (fileLabel);
  3005. fileName.setMinimumHorizontalScale (1.0f);
  3006. addAndMakeVisible (fileName);
  3007. loadButton.setTooltip (tr ("Load sample file... / Sample history"));
  3008. loadButton.onClick = [this] { chooseSample(); };
  3009. loadButton.onRightClick = [this] { showSampleHistory(); };
  3010. loadButton.onWheel = [this] (int delta) {
  3011. if (const auto* c = current())
  3012. if (const auto next = samplehistory::step (c->samplePath, delta))
  3013. replaceSample (juce::File (juce::String::fromUTF8 (next->c_str())));
  3014. };
  3015. locateButton.setTooltip (tr ("Locate sample in browser"));
  3016. locateButton.onClick = [this] {
  3017. if (const auto* c = current(); c != nullptr && ! c->samplePath.empty() && locateInBrowserHandler())
  3018. locateInBrowserHandler() (juce::File (juce::String::fromUTF8 (c->samplePath.c_str())));
  3019. };
  3020. removeButton.setTooltip (tr ("Remove sample"));
  3021. removeButton.onClick = [this] { removeSample(); };
  3022. for (auto* b : { &loadButton, &locateButton, &removeButton })
  3023. {
  3024. b->setFlat (false);
  3025. addAndMakeVisible (b);
  3026. }
  3027. // ---- Content (form WavePanel) ----
  3028. toggle (keepOnDisk, TR_NOOP ("Keep on disk"), TR_NOOP ("Stream sample from hard disk when possible"));
  3029. keepOnDisk.setTooltip (tr ("Stream sample from hard disk when possible") + " - "
  3030. + tr ("FL's option, kept for FL projects: LYNX streams samples longer than 30 s from its disk cache by itself"));
  3031. toggle (resampleBox, TR_NOOP ("Resample"), TR_NOOP ("Upsample to mixing frequency"));
  3032. resampleBox.setTooltip (tr ("Upsample to mixing frequency") + " - " + tr ("FL's option, kept for FL projects: LYNX resamples in real time"));
  3033. toggle (loadRegionsBox, TR_NOOP ("Load regions"), nullptr);
  3034. loadRegionsBox.setTooltip (tr ("Load sample regions and REX / ZGR beat markers") + " - " + tr ("FL's option, kept for FL projects"));
  3035. toggle (loadMarkersBox, TR_NOOP ("Load slice markers"), nullptr);
  3036. loadMarkersBox.setTooltip (tr ("Load ACID and Apple Loops beat markers") + " - " + tr ("FL's option, kept for FL projects"));
  3037. declickLabel.setText (tr ("Declicking mode"), juce::dontSendNotification);
  3038. addAndMakeVisible (declickLabel);
  3039. for (const auto* name : samplerpage::declickModeNames)
  3040. declick.addItem (tr (name), declick.getNumItems() + 1);
  3041. declick.setTooltip (tr ("Declicking method") + " - "
  3042. + tr ("How fast a cut note fades out: 10 ms (out only, transient no bleeding), 20 ms (transient, generic), 100 ms (smooth), 200 ms (crossfade)"));
  3043. declick.onChange = [this] { apply (&declick); };
  3044. addAndMakeVisible (declick);
  3045. // ---- Playback (form LoopPanel) ----
  3046. knob (startOffsetKnob, startOffsetLabel, TR_NOOP ("Start offset"), TR_NOOP ("Sample start offset"), 0.0, 1.0, 1.0 / 16384.0, 0.0);
  3047. startOffsetKnob.textFromValueFunction = [] (double v) { return juce::String (v * 100.0, 1) + " %"; };
  3048. knob (loopStartKnob, loopStartLabel, TR_NOOP ("Start"), TR_NOOP ("Loop start position"), 0.0, 1.0, 1.0, 0.0);
  3049. knob (loopEndKnob, loopEndLabel, TR_NOOP ("End"), TR_NOOP ("Loop end position"), 0.0, 1.0, 1.0, 0.0);
  3050. for (auto* k : { &loopStartKnob, &loopEndKnob })
  3051. k->textFromValueFunction = [] (double v) { return juce::String ((juce::int64) std::llround (v)); }; // (frames)
  3052. toggle (useLoops, TR_NOOP ("Use loop points"), TR_NOOP ("Use sample loop points"));
  3053. toggle (pingPong, TR_NOOP ("Ping pong loop"), TR_NOOP ("Loop forward / backward"));
  3054. // ---- Time stretching (form StretchPanel) ----
  3055. knob (stretchPitchKnob, stretchPitchLabel, TR_NOOP ("Pitch"), TR_NOOP ("Pitch shift"), -1200.0, 1200.0, 1.0, 0.0);
  3056. stretchPitchKnob.textFromValueFunction = [] (double v) { return tr ("{0} cents", { (v > 0.5 ? "+" : "") + juce::String (juce::roundToInt (v)) }); };
  3057. knob (mulKnob, mulLabel, TR_NOOP ("Mul"), TR_NOOP ("Time stretch (multiplicator)"), -20000.0, 20000.0, 1.0, 0.0);
  3058. // (live check 190ew SMP-5: FL's hint reads "105.70%")
  3059. mulKnob.textFromValueFunction = [] (double v) { return juce::String (samplerpage::mulText ((int) v)); };
  3060. knob (stretch, stretchLabel, TR_NOOP ("Time"), TR_NOOP ("Time stretch (time)"), 0.0, 1024.0, 0.01, 0.0);
  3061. stretch.textFromValueFunction = [] (double v) { return v <= 0.0 ? tr ("(none)") : tr ("{0} beats", { juce::String (v, 2) }); };
  3062. // issue #32 #7: "Fit to tempo" sets exact lengths (16.45 beats for a loop with a tail, 128 for 32 bars)
  3063. stretch.setSkewFactorFromMidPoint (16.0);
  3064. stretch.addMouseListener (&stretchMenu, false);
  3065. modeLabel.setText (tr ("Mode"), juce::dontSendNotification);
  3066. addAndMakeVisible (modeLabel);
  3067. for (int i = 0; i < samplerpage::modeItemCount; ++i)
  3068. {
  3069. if (samplerpage::modeItems[i].header)
  3070. stretchMethod.addSectionHeading (tr (samplerpage::modeItems[i].name));
  3071. else
  3072. stretchMethod.addItem (tr (samplerpage::modeItems[i].name), i + 1);
  3073. }
  3074. stretchMethod.setTooltip (tr ("Stretching method") + " - " + tr ("Resample") + " / "
  3075. + tr ("How the stretch keeping pitch is computed: General for full mixes and chords, Drums for loops and percussive sounds (attacks kept sharp), Vocal for a single voice or instrument"));
  3076. stretchMethod.onChange = [this] { apply (&stretchMethod); };
  3077. addAndMakeVisible (stretchMethod);
  3078. // ---- Precomputed effects (form FXPanel) ----
  3079. toggle (removeDc, TR_NOOP ("Remove DC offset"), TR_NOOP ("Center vertically"));
  3080. toggle (normalize, TR_NOOP ("Normalize"), TR_NOOP ("Normalize to 0dB"));
  3081. toggle (reverse, TR_NOOP ("Reverse"), TR_NOOP ("Flip horizontally"));
  3082. toggle (polarity, TR_NOOP ("Reverse polarity"), TR_NOOP ("Flip vertically"));
  3083. toggle (fadeStereo, TR_NOOP ("Fade stereo"), TR_NOOP ("Fade from left channel to right channel"));
  3084. toggle (swapStereo, TR_NOOP ("Swap stereo"), TR_NOOP ("Swap left & right channels"));
  3085. knob (regionStart, regionStartLabel, TR_NOOP ("Smp start"), TR_NOOP ("Sample start offset"), 0.0, 1.0, 1.0 / 16384.0, 0.0);
  3086. knob (lengthKnob, lengthLabel, TR_NOOP ("Length"), TR_NOOP ("Sample end offset"), 0.0, 1.0, 1.0 / 16384.0, 1.0);
  3087. for (auto* k : { &regionStart, &lengthKnob })
  3088. k->textFromValueFunction = [] (double v) { return juce::String (v * 100.0, 1) + " %"; };
  3089. knob (fadeIn, fadeInLabel, TR_NOOP ("In"), TR_NOOP ("Quick fade in"), 0.0, 1024.0, 1.0, 0.0);
  3090. knob (fadeOut, fadeOutLabel, TR_NOOP ("Out"), TR_NOOP ("Quick fade out"), 0.0, 1024.0, 1.0, 0.0);
  3091. knob (crossfade, crossfadeLabel, TR_NOOP ("Crossfade"), TR_NOOP ("Crossfade loop"), 0.0, 1024.0, 1.0, 0.0);
  3092. knob (trim, trimLabel, TR_NOOP ("Trim"), TR_NOOP ("Silence trimming threshold"), 0.0, 256.0, 1.0, 0.0);
  3093. auto percent = [] (double hi) { return [hi] (double v) { return juce::String (v / hi * 100.0, 1) + " %"; }; };
  3094. fadeIn.textFromValueFunction = percent (1024.0);
  3095. fadeOut.textFromValueFunction = percent (1024.0);
  3096. crossfade.textFromValueFunction = percent (2048.0); // (of the loop: FL's knob reaches half of it)
  3097. trim.textFromValueFunction = [] (double v) { return v <= 0.0 ? tr ("Off") : juce::String (20.0 * std::log10 (v / 32768.0), 1) + " dB"; };
  3098. effectsTarget.setTooltip (tr ("effects target"));
  3099. effectsTarget.onChange = [this] (int) { showLegacy(); };
  3100. addAndMakeVisible (effectsTarget);
  3101. // the legacy effects (form FXLegacyPanel; REA round 167l §1: FL's ranges and defaults)
  3102. const std::tuple<MenuSlider*, juce::Label*, const char*, const char*, double, double, double> legacy[] = {
  3103. { &boost, &boostLabel, TR_NOOP ("Boost"), TR_NOOP ("Boosts the gain"), 0.0, 256.0, 0.0 },
  3104. { &eq, &eqLabel, TR_NOOP ("EQ"), TR_NOOP ("Shifts the frequency balance"), 0.0, 256.0, 128.0 },
  3105. { &ringMix, &ringMixLabel, TR_NOOP ("RM mix"), TR_NOOP ("Ring modulation mix"), 0.0, 256.0, 0.0 },
  3106. { &ringFreq, &ringFreqLabel, TR_NOOP ("RM freq"), TR_NOOP ("Ring modulation frequency"), 0.0, 256.0, 128.0 },
  3107. { &legacyCut, &legacyCutLabel, TR_NOOP ("Cut"), TR_NOOP ("Filter cutoff"), 16.0, 1024.0, 1024.0 },
  3108. { &legacyRes, &legacyResLabel, TR_NOOP ("Res"), TR_NOOP ("Filter resonance"), 0.0, 640.0, 0.0 },
  3109. { &reverbAmount, &reverbLabel, TR_NOOP ("Reverb"), TR_NOOP ("Reverb amount"), 0.0, 256.0, 0.0 },
  3110. { &stereoDelay, &stereoDelayLabel, TR_NOOP ("Stereo delay"), TR_NOOP ("Stereo delay"), 0.0, 4096.0, 2048.0 },
  3111. { &pogo, &pogoLabel, TR_NOOP ("Pogo"), TR_NOOP ("Pogo effect"), 0.0, 512.0, 256.0 } };
  3112. for (auto [k, label, text, hint, lo, hi, def] : legacy)
  3113. knob (*k, *label, text, hint, lo, hi, 1.0, def);
  3114. reverbType.addItemList ({ "A", "B" }, 1);
  3115. reverbType.setTooltip (tr ("Reverb type"));
  3116. reverbType.onChange = [this] { apply (&reverbType); };
  3117. addChildComponent (reverbType);
  3118. toggle (clip, TR_NOOP ("Clip"), TR_NOOP ("Add clipping at 0dB"));
  3119. // ---- the waveform ----
  3120. wave.setEmptyText (tr ("No sample loaded"));
  3121. wave.setTooltip (tr ("Waveform") + " - " + tr ("click: preview the sample; mouse wheel: zoom"));
  3122. wave.setWatermark (clipChannel ? tr ("Audio clip") : tr ("Sampler")); // (FL's audio clip page: "Audio Clip")
  3123. wave.setCaptionVisible (false);
  3124. wave.setZoomable (true);
  3125. wave.setFollowsSamplerViews (true); // (round 190gw: the waveform menu's Spectrum / Multichannel views)
  3126. wave.onViewChanged = [this] { waveScroll.setCurrentRange (wave.getViewStart(), wave.getViewEnd() - wave.getViewStart(), juce::dontSendNotification); };
  3127. // round 190w: FL 2026 previews the sample when its display is clicked (from the start offset, to its end) and shows
  3128. // the playback locator over it (What's New 21138; [SHOT] flgap190w burst n2 / o3)
  3129. wave.onClick = [this] { previewFromDisplay(); };
  3130. // round 190ey (live check 190ew SMP-7): FL's waveform menu on a right-click
  3131. wave.onRightClick = [this] {
  3132. auto menu = waveMenu();
  3133. if (menu.getNumItems() > 0)
  3134. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&wave).withMousePosition());
  3135. };
  3136. // round 190im (R11, DF-113): FL's handles dragged on the waveform — the "Start" marker turns the Start offset knob,
  3137. // the loop lines the loop Start / End knobs (Shift: the whole loop moves, as Shift on the knobs; FL)
  3138. wave.setHandlesEditable (true);
  3139. wave.onHandleDrag = [this] (ui::WaveformDisplay::Handle h, double v, bool shift) {
  3140. using H = ui::WaveformDisplay::Handle;
  3141. if (h == H::start)
  3142. {
  3143. startOffsetKnob.setValue (v, juce::sendNotificationSync);
  3144. return;
  3145. }
  3146. if (shownFrames <= 1 || ! loopStartKnob.isEnabled())
  3147. return;
  3148. const juce::ScopedValueSetter<bool> shiftNow (shiftHeld, shift);
  3149. auto& knob = h == H::loopStart ? loopStartKnob : loopEndKnob;
  3150. knob.setValue (std::round (v * (double) (shownFrames - 1)), juce::sendNotificationSync);
  3151. };
  3152. addAndMakeVisible (wave);
  3153. // round 190ih (PLAN R11 part, DF-115), FL's manual (Sampler › Drag and Drop): the sample is dragged out of the
  3154. // waveform onto the Playlist, a channel, the Browser's targets... (as a Browser file drag; an OS file drag from
  3155. // a window outside the main one)
  3156. waveDrag.path = [this] { return wavePath; };
  3157. wave.addMouseListener (&waveDrag, false);
  3158. waveScroll.setRangeLimits (0.0, 1.0, juce::dontSendNotification);
  3159. waveScroll.setCurrentRange (0.0, 1.0, juce::dontSendNotification);
  3160. waveScroll.setAutoHide (false);
  3161. waveScroll.addListener (this);
  3162. addAndMakeVisible (waveScroll);
  3163. // ---- LYNX extras ----
  3164. knob (gain, gainLabel, TR_NOOP ("Gain"), nullptr, -24.0, 24.0, 0.1, 0.0);
  3165. gain.textFromValueFunction = [] (double v) { return (v > 0.04 ? "+" : "") + juce::String (std::abs (v) < 0.05 ? 0.0 : v, 1) + " dB"; };
  3166. gain.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("+-0123456789.,").replaceCharacter (',', '.').getDoubleValue(); };
  3167. gain.setTooltip (tr ("Sample gain: boosts or cuts the sample's level before the channel volume (-24 to +24 dB, double-click = 0 dB)"));
  3168. knob (attack, attackLabel, TR_NOOP ("Attack"), nullptr, 0.0, 2.0, 0.001, 0.0);
  3169. knob (decay, decayLabel, TR_NOOP ("Decay"), nullptr, 0.0, 10.0, 0.001, 0.0);
  3170. knob (sustain, sustainLabel, TR_NOOP ("Sustain"), nullptr, 0.0, 1.0, 0.01, 1.0);
  3171. knob (release, releaseLabel, TR_NOOP ("Release"), nullptr, 0.0, 4.0, 0.001, 0.0);
  3172. for (auto* k : { &attack, &decay, &release })
  3173. k->textFromValueFunction = [] (double v) { return juce::String (v, 3) + " s"; };
  3174. knob (cutoff, cutoffLabel, TR_NOOP ("Cutoff"), nullptr, 20.0, 20000.0, 1.0, 20000.0);
  3175. cutoff.textFromValueFunction = [] (double v) { return juce::String (juce::roundToInt (v)) + " Hz"; };
  3176. knob (resonance, resonanceLabel, TR_NOOP ("Resonance"), nullptr, 0.0, 1.0, 0.01, 0.0);
  3177. cutoff.setSkewFactorFromMidPoint (1000.0);
  3178. cutoff.setTooltip (tr ("Channel filter cutoff (low-pass at maximum with no resonance = off)"));
  3179. decay.setSkewFactorFromMidPoint (0.5);
  3180. attack.setSkewFactorFromMidPoint (0.2);
  3181. release.setSkewFactorFromMidPoint (0.4);
  3182. release.setTooltip (tr ("0 = the whole sample plays (one-shot), like FL's steps"));
  3183. filterType.addItemList ({ tr ("Low-pass"), tr ("Band-pass"), tr ("High-pass"), tr ("Notch") }, 1);
  3184. filterType.onChange = [this] { apply (&filterType); };
  3185. addAndMakeVisible (filterType);
  3186. toggle (cut, TR_NOOP ("Cut itself"), nullptr);
  3187. cut.setTooltip (tr ("A new note cuts the previous one (good for hi-hats and 808s)"));
  3188. porta.setButtonText ("Porta");
  3189. porta.setTooltip (tr ("Portamento: the note starts from the previous note's pitch (with Cut itself, the 808 glide)"));
  3190. porta.onClick = [this] { apply (&porta); };
  3191. addAndMakeVisible (porta);
  3192. modulationButton.setButtonText (tr ("Modulation (envelopes and LFOs)..."));
  3193. modulationButton.onClick = [this] { showModulationFor (*this, engine, ref.index); };
  3194. addAndMakeVisible (modulationButton);
  3195. extrasLabel.setText (tr ("LYNX extras"), juce::dontSendNotification);
  3196. // the knobs an automation clip can drive (samplerparam, issue #12): right-click = FL's parameter menu; a move
  3197. // is a tweak (Last tweaked, automation recording)
  3198. for (auto [slider, param] : { std::pair { &attack, (int) samplerparam::attack }, { &decay, (int) samplerparam::decay },
  3199. { &sustain, (int) samplerparam::sustain }, { &release, (int) samplerparam::release },
  3200. { &cutoff, (int) samplerparam::cutoff }, { &resonance, (int) samplerparam::resonance },
  3201. { &regionStart, (int) samplerparam::start }, { &lengthKnob, (int) samplerparam::end } })
  3202. {
  3203. if (ref.index < 0) // (a Patcher node: no automation target)
  3204. break;
  3205. const auto target = [this, param] { return AutomationTarget { AutomationTargetKind::channelParam, ref.index, 0, param }; };
  3206. ui::setOwnMenu (*slider);
  3207. slider->onMenu = [this, slider, target] { ui::showSliderMenu (*slider, &engine, target()); };
  3208. slider->onDragStart = [this, target] { engine.noteTweaked (target(), true); };
  3209. slider->onDragEnd = [this, target] { engine.tweakReleased (target()); };
  3210. tweakTargets.push_back ({ slider, param });
  3211. }
  3212. // An audio clip's channel (live check 190ew, shot PL-x-audio-clip-channel-page-variants): FL's page has no
  3213. // Playback box (start offset, loop points) and nothing under the waveform. A Playlist clip plays its whole
  3214. // sample in LYNX too (SamplerInstrument clip mode skips the start offset, the loop knobs and the envelope /
  3215. // filter / portamento of LYNX's extras), so those controls are left out of it.
  3216. if (clipChannel)
  3217. for (auto* hidden : std::initializer_list<juce::Component*> { &startOffsetKnob, &startOffsetLabel, &loopStartKnob, &loopStartLabel,
  3218. &loopEndKnob, &loopEndLabel, &useLoops, &pingPong, &gain, &gainLabel,
  3219. &attack, &attackLabel, &decay, &decayLabel, &sustain, &sustainLabel,
  3220. &release, &releaseLabel, &cutoff, &cutoffLabel, &resonance,
  3221. &resonanceLabel, &filterType, &cut, &porta, &modulationButton })
  3222. hidden->setVisible (false);
  3223. refresh();
  3224. showLegacy();
  3225. engine.addChangeListener (this);
  3226. setSize (juce::roundToInt (designWidth * defaultScale), juce::roundToInt (pageHeight() * defaultScale));
  3227. if (ref.index >= 0)
  3228. startTimerHz (30); // the knobs follow their automation while the song plays (issue #12)
  3229. }
  3230. ~SettingsPanel() override
  3231. {
  3232. wave.removeMouseListener (&waveDrag);
  3233. stopPreview();
  3234. waveScroll.removeListener (this);
  3235. engine.removeChangeListener (this);
  3236. }
  3237. // FL's sample display click: the channel's root note, the sample from its start offset; a second click stops it
  3238. void previewFromDisplay()
  3239. {
  3240. const auto* c = current();
  3241. if (c == nullptr || ref.index < 0)
  3242. return;
  3243. if (previewKey >= 0)
  3244. {
  3245. stopPreview();
  3246. return;
  3247. }
  3248. previewKey = juce::jlimit (0, 127, c->misc.rootNote);
  3249. previewSeen = false;
  3250. previewFrames = 0;
  3251. engine.sendLiveNote (ref.index, previewKey, 100.0f / 128.0f, true); // (FL's default velocity)
  3252. }
  3253. void stopPreview()
  3254. {
  3255. if (previewKey >= 0 && ref.index >= 0)
  3256. engine.sendLiveNote (ref.index, previewKey, 0.0f, false);
  3257. previewKey = -1;
  3258. wave.setLocator (-1.0f);
  3259. }
  3260. // the locator follows the preview's voice; the preview ends with it (or ~2 s after a note that never sounded)
  3261. void followPreview()
  3262. {
  3263. if (previewKey < 0)
  3264. return;
  3265. const auto instrument = engine.getChannelInstrument (ref.index);
  3266. const auto at = instrument != nullptr ? instrument->playPosition() : -1.0f;
  3267. ++previewFrames;
  3268. if (at >= 0.0f)
  3269. previewSeen = true;
  3270. if ((previewSeen && at < 0.0f) || (! previewSeen && previewFrames > 60))
  3271. {
  3272. stopPreview();
  3273. return;
  3274. }
  3275. wave.setLocator (at);
  3276. }
  3277. void paint (juce::Graphics& g) override
  3278. {
  3279. g.fillAll (theme::colour::bg2);
  3280. // FL's boxes: a rounded panel with its caption on a tab at the top left (the File row has none)
  3281. for (const auto& [area, caption, captionLeft] : groups)
  3282. {
  3283. const auto r = area.toFloat();
  3284. g.setColour (theme::colour::bg3);
  3285. g.fillRoundedRectangle (r, 3.0f);
  3286. g.setColour (theme::colour::border);
  3287. g.drawRoundedRectangle (r.reduced (0.5f), 3.0f, 1.0f);
  3288. if (caption.isEmpty())
  3289. continue;
  3290. const auto h = scaled (19.0f);
  3291. g.setFont (theme::font (juce::jlimit (10.0f, 18.0f, scaled (12.5f)), true));
  3292. const auto w = (float) juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), caption) + scaled (16.0f);
  3293. juce::Path tab;
  3294. const auto x0 = r.getX() + scaled ((float) captionLeft);
  3295. tab.startNewSubPath (x0, r.getY());
  3296. tab.lineTo (x0 + w, r.getY());
  3297. tab.lineTo (x0 + w - h * 0.45f, r.getY() + h);
  3298. tab.lineTo (x0, r.getY() + h);
  3299. tab.closeSubPath();
  3300. g.setColour (theme::colour::bg4);
  3301. g.fillPath (tab);
  3302. g.setColour (theme::colour::textPrimary);
  3303. g.drawText (caption, juce::Rectangle<float> (x0 + scaled (6.0f), r.getY(), w, h), juce::Justification::centredLeft, false);
  3304. }
  3305. // FL 2026's loop glyph between the loop START and END captions
  3306. if (! loopGlyph.isEmpty())
  3307. icons::draw (g, Icon::loop, loopGlyph.toFloat(), theme::colour::textSecondary);
  3308. }
  3309. void resized() override
  3310. {
  3311. // FL's layout in its own units, scaled to the page (the whole page fits; at 1.25 it is FL's at 125 %)
  3312. scale = juce::jmax (0.55f, juce::jmin ((float) getWidth() / (float) designWidth, (float) getHeight() / (float) pageHeight()));
  3313. offsetX = juce::jmax (0, (getWidth() - juce::roundToInt ((float) designWidth * scale)) / 2);
  3314. groups.clear();
  3315. const auto captionFont = theme::font (juce::jlimit (8.0f, 13.0f, scaled (8.6f)), true);
  3316. const auto textFont = juce::jlimit (9.0f, 17.0f, scaled (12.0f));
  3317. auto place = [this, captionFont] (juce::Slider& k, juce::Label& label, int x, int y, int labelX, int labelW, int size = 34) {
  3318. k.setBounds (R (x, y, size, size));
  3319. label.setFont (captionFont);
  3320. label.setBounds (R (labelX, y + size - 1, labelW, 13));
  3321. };
  3322. // left column: File row, Content, Playback
  3323. groups.push_back ({ R (7, 7, 268, 35), juce::String(), 0 });
  3324. {
  3325. removeButton.setBounds (R (243, 13, 19, 23));
  3326. locateButton.setBounds (R (224, 13, 19, 23));
  3327. loadButton.setBounds (R (192, 13, 32, 23));
  3328. fileLabel.setFont (theme::font (textFont, true));
  3329. fileLabel.setBounds (R (11, 15, 24, 15));
  3330. fileName.setFont (theme::font (textFont));
  3331. fileName.setBounds (R (38, 13, 152, 21));
  3332. }
  3333. groups.push_back ({ R (7, 50, 268, 110), tr ("Content"), 0 });
  3334. keepOnDisk.setBounds (R (12, 75, 126, 21));
  3335. resampleBox.setBounds (R (12, 96, 126, 21));
  3336. loadRegionsBox.setBounds (R (140, 75, 128, 21));
  3337. loadMarkersBox.setBounds (R (140, 96, 128, 21));
  3338. declickLabel.setFont (theme::font (textFont));
  3339. declickLabel.setBounds (R (14, 126, 100, 23));
  3340. declick.setBounds (R (116, 126, 152, 23));
  3341. if (! clipChannel)
  3342. groups.push_back ({ R (7, 168, 268, 79), tr ("Playback"), 0 });
  3343. place (startOffsetKnob, startOffsetLabel, 26, 194, 9, 68);
  3344. place (loopStartKnob, loopStartLabel, 80, 194, 66, 40);
  3345. place (loopEndKnob, loopEndLabel, 118, 194, 112, 30);
  3346. loopGlyph = clipChannel ? juce::Rectangle<int>() : R (105, 229, 10, 10);
  3347. useLoops.setBounds (R (150, 191, 122, 21));
  3348. pingPong.setBounds (R (150, 213, 122, 21));
  3349. // right column: Time stretching, Precomputed effects
  3350. groups.push_back ({ R (283, 7, 268, 76), tr ("Time stretching"), 0 });
  3351. place (stretchPitchKnob, stretchPitchLabel, 291, 33, 285, 44, 32);
  3352. place (mulKnob, mulLabel, 333, 33, 327, 44, 32);
  3353. place (stretch, stretchLabel, 373, 33, 367, 44, 32);
  3354. modeLabel.setFont (theme::font (textFont, true));
  3355. modeLabel.setBounds (R (410, 31, 40, 23));
  3356. stretchMethod.setBounds (R (450, 31, 96, 23));
  3357. groups.push_back ({ R (283, 91, 268, 156), tr ("Precomputed effects"), 49 });
  3358. effectsTarget.setBounds (R (284, 92, 46, 18));
  3359. removeDc.setBounds (R (288, 116, 126, 23));
  3360. normalize.setBounds (R (288, 138, 126, 23));
  3361. reverse.setBounds (R (288, 160, 126, 23));
  3362. polarity.setBounds (R (416, 116, 130, 23));
  3363. fadeStereo.setBounds (R (416, 138, 130, 23));
  3364. swapStereo.setBounds (R (416, 160, 130, 23));
  3365. place (regionStart, regionStartLabel, 290, 195, 280, 54);
  3366. place (lengthKnob, lengthLabel, 332, 195, 326, 46);
  3367. place (fadeIn, fadeInLabel, 386, 195, 383, 40);
  3368. place (fadeOut, fadeOutLabel, 425, 195, 422, 40);
  3369. place (crossfade, crossfadeLabel, 472, 195, 459, 60);
  3370. place (trim, trimLabel, 511, 195, 508, 40);
  3371. // the legacy panel over the same box (FXLegacyPanel at 284, 113)
  3372. place (boost, boostLabel, 291, 118, 285, 46);
  3373. place (eq, eqLabel, 333, 118, 327, 46);
  3374. place (ringMix, ringMixLabel, 381, 118, 375, 46);
  3375. place (ringFreq, ringFreqLabel, 421, 118, 415, 46);
  3376. place (legacyCut, legacyCutLabel, 472, 117, 466, 46);
  3377. place (legacyRes, legacyResLabel, 511, 117, 505, 46);
  3378. clip.setBounds (R (287, 167, 52, 16));
  3379. reverbType.setBounds (R (288, 199, 44, 22));
  3380. place (reverbAmount, reverbLabel, 333, 195, 324, 52);
  3381. place (stereoDelay, stereoDelayLabel, 381, 195, 362, 72);
  3382. place (pogo, pogoLabel, 511, 195, 505, 46);
  3383. // the waveform under both columns, with its scroll bar
  3384. wave.setBounds (R (7, 255, 544, 112));
  3385. waveScroll.setBounds (R (7, 368, 544, 14));
  3386. // LYNX extras (FL's page has no place for them)
  3387. if (! clipChannel)
  3388. groups.push_back ({ R (7, 390, 544, 128), extrasLabel.getText(), 0 });
  3389. {
  3390. int x = 18;
  3391. for (auto [k, label] : { std::pair { &gain, &gainLabel }, { &attack, &attackLabel }, { &decay, &decayLabel },
  3392. { &sustain, &sustainLabel }, { &release, &releaseLabel }, { &cutoff, &cutoffLabel },
  3393. { &resonance, &resonanceLabel } })
  3394. {
  3395. place (*k, *label, x, 418, x - 12, 58, 36);
  3396. x += 58;
  3397. }
  3398. filterType.setBounds (R (432, 420, 110, 22));
  3399. cut.setBounds (R (432, 446, 110, 21));
  3400. porta.setBounds (R (432, 468, 110, 21));
  3401. modulationButton.setBounds (R (18, 488, 260, 22));
  3402. }
  3403. for (auto* b : { &keepOnDisk, &resampleBox, &loadRegionsBox, &loadMarkersBox, &useLoops, &pingPong, &removeDc, &normalize, &reverse,
  3404. &polarity, &fadeStereo, &swapStereo, &clip, &cut, &porta })
  3405. b->setSize (b->getWidth(), b->getHeight()); // (their text follows the LookAndFeel's toggle font, sized by height)
  3406. repaint();
  3407. }
  3408. int getChannel() const noexcept { return ref.index; }
  3409. // A sample dropped on the waveform (from the Browser or the system) replaces the channel's sample (issue #12)
  3410. bool isInterestedInDragSource (const SourceDetails& details) override
  3411. {
  3412. return BrowserComponent::isBrowserDrag (details) && SampleLibrary::isSampleFile (BrowserComponent::draggedFile (details));
  3413. }
  3414. void itemDragEnter (const SourceDetails&) override { setDropHighlight (true); }
  3415. void itemDragExit (const SourceDetails&) override { setDropHighlight (false); }
  3416. void itemDropped (const SourceDetails& details) override
  3417. {
  3418. setDropHighlight (false);
  3419. replaceSample (BrowserComponent::draggedFile (details));
  3420. }
  3421. bool isInterestedInFileDrag (const juce::StringArray& files) override
  3422. {
  3423. return files.size() == 1 && SampleLibrary::isSampleFile (juce::File (files[0]));
  3424. }
  3425. void fileDragEnter (const juce::StringArray&, int, int) override { setDropHighlight (true); }
  3426. void fileDragExit (const juce::StringArray&) override { setDropHighlight (false); }
  3427. void filesDropped (const juce::StringArray& files, int, int) override
  3428. {
  3429. setDropHighlight (false);
  3430. replaceSample (juce::File (files[0]));
  3431. }
  3432. void paintOverChildren (juce::Graphics& g) override
  3433. {
  3434. if (dropHighlight)
  3435. {
  3436. g.setColour (theme::colour::accent);
  3437. g.drawRect (wave.getBounds().expanded (2), 2);
  3438. }
  3439. }
  3440. // (the shot route, round 190dh: turn a control as a user would — `what`: a knob's name or a toggle's — and read the
  3441. // channel back; true when the control exists)
  3442. bool shotTurn (const juce::String& what, double value, bool shift = false)
  3443. {
  3444. refresh(); // (the engine's change message is asynchronous: the page shows the channel as a user would see it)
  3445. shiftHeld = shift;
  3446. const juce::ScopedValueSetter<bool> nofocus (shotDriven, true);
  3447. auto turn = [&] (juce::Slider& s) { s.setValue (value, juce::sendNotificationSync); return true; };
  3448. auto click = [&] (juce::Button& b) { b.setToggleState (value != 0.0, juce::dontSendNotification); b.onClick(); return true; };
  3449. bool done = false;
  3450. if (what == "pitch") done = turn (stretchPitchKnob);
  3451. else if (what == "mul") done = turn (mulKnob);
  3452. else if (what == "time") done = turn (stretch);
  3453. else if (what == "loopStart") done = turn (loopStartKnob);
  3454. else if (what == "loopEnd") done = turn (loopEndKnob);
  3455. else if (what == "crossfade") done = turn (crossfade);
  3456. else if (what == "smpStart") done = turn (regionStart);
  3457. else if (what == "length") done = turn (lengthKnob);
  3458. else if (what == "useLoops") done = click (useLoops);
  3459. else if (what == "pingPong") done = click (pingPong);
  3460. else if (what == "keepOnDisk") done = click (keepOnDisk);
  3461. else if (what == "mode") { stretchMethod.setSelectedId ((int) value + 1, juce::sendNotificationSync); done = true; }
  3462. else if (what == "declick") { declick.setSelectedId ((int) value + 1, juce::sendNotificationSync); done = true; }
  3463. else if (what == "legacy") { effectsTarget.setIndex ((int) value); showLegacy(); done = true; }
  3464. else if (what == "zoom") { wave.setView (0.25, 0.25 + value); done = true; }
  3465. // round 190im (R11): a handle dragged on the waveform to `value` (start: region fraction; loop: file fraction)
  3466. else if (what.startsWith ("drag") && wave.onHandleDrag != nullptr)
  3467. {
  3468. using H = ui::WaveformDisplay::Handle;
  3469. const auto h = what == "dragStart" ? H::start : what == "dragLoopStart" ? H::loopStart : H::loopEnd;
  3470. wave.onHandleDrag (h, value, shift);
  3471. done = true;
  3472. }
  3473. shiftHeld = false;
  3474. refresh();
  3475. return done;
  3476. }
  3477. bool shotLegacyShown() const { return boost.isVisible() && ! removeDc.isVisible(); }
  3478. juce::String handleProbeForShot (const juce::String& name) const
  3479. {
  3480. using H = ui::WaveformDisplay::Handle;
  3481. const auto h = name == "Start" ? H::start : name == "LoopStart" ? H::loopStart : H::loopEnd;
  3482. const auto x = wave.handleXForSnapshot (h);
  3483. if (x < 0.0f)
  3484. return "none";
  3485. const auto got = wave.handleAt ({ x + 1.0f, (float) wave.getHeight() * 0.25f });
  3486. return got == H::start ? "start" : got == H::loopStart ? "loopStart" : got == H::loopEnd ? "loopEnd" : "none";
  3487. }
  3488. bool shotEnabled (const juce::String& what) const
  3489. {
  3490. return what == "keepOnDisk" ? keepOnDisk.isEnabled()
  3491. : what == "loopStart" ? loopStartKnob.isEnabled()
  3492. : what == "resample" ? resampleBox.isEnabled()
  3493. : what == "loadRegions" ? loadRegionsBox.isEnabled()
  3494. : what == "loadMarkers" ? loadMarkersBox.isEnabled()
  3495. : false;
  3496. }
  3497. juce::String shotText (const juce::String& what)
  3498. {
  3499. if (what == "mulText")
  3500. return mulKnob.getTextFromValue (mulKnob.getValue());
  3501. if (what == "corner")
  3502. return wave.getCornerText();
  3503. if (what == "waveHint")
  3504. return wave.getTooltip();
  3505. return {};
  3506. }
  3507. double shotScrollStart() const { return waveScroll.getCurrentRangeStart(); }
  3508. juce::String shotModeText() const { return stretchMethod.getText(); }
  3509. private:
  3510. int pageHeight() const noexcept { return clipChannel ? clipDesignHeight : designHeight; }
  3511. juce::Rectangle<int> R (int x, int y, int w, int h) const
  3512. {
  3513. return { offsetX + juce::roundToInt ((float) x * scale), juce::roundToInt ((float) y * scale), juce::roundToInt ((float) w * scale),
  3514. juce::roundToInt ((float) h * scale) };
  3515. }
  3516. float scaled (float v) const noexcept { return v * scale; }
  3517. void toggle (juce::ToggleButton& b, const char* text, const char* hint)
  3518. {
  3519. b.setButtonText (tr (text));
  3520. if (hint != nullptr)
  3521. b.setTooltip (tr (hint));
  3522. b.onClick = [this, &b] { apply (&b); };
  3523. addAndMakeVisible (b);
  3524. }
  3525. void knob (juce::Slider& s, juce::Label& label, const char* name, const char* hint, double lo, double hi, double step, double def)
  3526. {
  3527. s.setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  3528. s.setTextBoxStyle (juce::Slider::NoTextBox, false, 0, 0);
  3529. s.setPopupDisplayEnabled (true, true, this);
  3530. s.setRange (lo, hi, step);
  3531. s.setValue (def, juce::dontSendNotification);
  3532. s.setDoubleClickReturnValue (true, def);
  3533. if (hint != nullptr)
  3534. s.setTooltip (tr (hint));
  3535. s.onValueChange = [this, &s] { apply (&s); };
  3536. label.setText (tr (name).toUpperCase(), juce::dontSendNotification);
  3537. label.setJustificationType (juce::Justification::centredTop);
  3538. label.setColour (juce::Label::textColourId, theme::colour::textSecondary);
  3539. label.setInterceptsMouseClicks (false, false);
  3540. label.setBorderSize ({});
  3541. addAndMakeVisible (s);
  3542. addAndMakeVisible (label);
  3543. }
  3544. // FL's EffectsTargetSelect: cell 1 shows the legacy panel over the effects (FUN_0060a270 on FXLegacyPanel)
  3545. void showLegacy()
  3546. {
  3547. const auto legacy = effectsTarget.getIndex() == 1;
  3548. for (juce::Component* c : std::initializer_list<juce::Component*> { &removeDc, &normalize, &reverse, &polarity, &fadeStereo, &swapStereo, &regionStart,
  3549. &regionStartLabel, &lengthKnob, &lengthLabel, &fadeIn, &fadeInLabel, &fadeOut,
  3550. &fadeOutLabel, &crossfade, &crossfadeLabel, &trim, &trimLabel })
  3551. c->setVisible (! legacy);
  3552. for (juce::Component* c : std::initializer_list<juce::Component*> { &boost, &boostLabel, &eq, &eqLabel, &ringMix, &ringMixLabel, &ringFreq, &ringFreqLabel,
  3553. &legacyCut, &legacyCutLabel, &legacyRes, &legacyResLabel, &reverbAmount, &reverbLabel,
  3554. &stereoDelay, &stereoDelayLabel, &pogo, &pogoLabel, &reverbType, &clip })
  3555. c->setVisible (legacy);
  3556. }
  3557. void scrollBarMoved (juce::ScrollBar*, double start) override
  3558. {
  3559. const auto width = wave.getViewEnd() - wave.getViewStart();
  3560. wave.setView (start, start + width);
  3561. }
  3562. void setDropHighlight (bool on)
  3563. {
  3564. if (dropHighlight != on)
  3565. {
  3566. dropHighlight = on;
  3567. repaint (wave.getBounds().expanded (4));
  3568. }
  3569. }
  3570. // the new sample plays with the same settings; slices of the old one no longer apply, the channel takes its name;
  3571. // loop points set on the old one go with it
  3572. void replaceSample (const juce::File& file)
  3573. {
  3574. if (current() == nullptr || ! file.existsAsFile())
  3575. return;
  3576. if (engine.getSampleLibrary().load (file.getFullPathName()) == nullptr)
  3577. {
  3578. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Sample"), tr ("Could not read {0}", { file.getFileName() }));
  3579. return;
  3580. }
  3581. ref.edit (engine, [path = file.getFullPathName().toStdString(), name = file.getFileNameWithoutExtension().toStdString()] (ChannelDef& d) {
  3582. d.samplePath = path;
  3583. d.zones.clear();
  3584. d.sampler.slices.clear();
  3585. d.sampler.loopStart = d.sampler.loopEnd = -1;
  3586. d.name = name;
  3587. });
  3588. samplehistory::add (file.getFullPathName().toStdString()); // (FL: every sample a sampler loads)
  3589. }
  3590. // FL's Load button [OpenBtnClick 0xf68f20]: the sample file dialog
  3591. void chooseSample()
  3592. {
  3593. const auto* c = current();
  3594. const juce::File now (c != nullptr ? juce::String::fromUTF8 (c->samplePath.c_str()) : juce::String());
  3595. sampleChooser = lynx::ui::makeFileChooser (tr ("Load sample file..."), now.existsAsFile() ? now : juce::File(),
  3596. "*.wav;*.aif;*.aiff;*.flac;*.ogg;*.mp3");
  3597. lynx::ui::launchChooser (sampleChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  3598. [safe = juce::Component::SafePointer<SettingsPanel> (this)] (const juce::FileChooser& fc) {
  3599. if (safe != nullptr && fc.getResult() != juce::File())
  3600. safe->replaceSample (fc.getResult());
  3601. });
  3602. }
  3603. // FL's right-click on Load [WAVFileNameListMenuPopup 0x121afb0]: caption "Sample history", then the samples loaded
  3604. // (newest first, by name); a click loads one into this channel
  3605. juce::PopupMenu sampleHistoryMenu()
  3606. {
  3607. juce::PopupMenu menu;
  3608. const auto& paths = samplehistory::list();
  3609. if (paths.empty())
  3610. return menu;
  3611. menu.addSectionHeader (tr ("Sample history"));
  3612. for (const auto& p : paths)
  3613. {
  3614. const juce::File file (juce::String::fromUTF8 (p.c_str()));
  3615. menu.addItem (file.getFileName(), [safe = juce::Component::SafePointer<SettingsPanel> (this), file] {
  3616. if (safe != nullptr)
  3617. if (const auto* c = safe->current(); c != nullptr && c->samplePath != file.getFullPathName().toStdString())
  3618. safe->replaceSample (file);
  3619. });
  3620. }
  3621. return menu;
  3622. }
  3623. void showSampleHistory()
  3624. {
  3625. auto menu = sampleHistoryMenu();
  3626. if (menu.getNumItems() > 0)
  3627. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&loadButton));
  3628. }
  3629. // FL's Remove sample [RemoveBtnClick 0xf667a0]: one undo step "remove channel sample", only with a sample
  3630. void removeSample()
  3631. {
  3632. const auto* c = current();
  3633. if (c == nullptr || (c->samplePath.empty() && c->zones.empty()))
  3634. return;
  3635. stopPreview();
  3636. // (live check 190ew CTL-4: FL also renames the channel "Sampler", without asking)
  3637. ref.edit (engine, [] (ChannelDef& d) { samplerpage::removeSample (d); });
  3638. }
  3639. // FL's waveform menu (live check 190ew SMP-7, samplerpage::waveMenu): the items LYNX performs, in FL's order and groups
  3640. juce::PopupMenu waveMenu()
  3641. {
  3642. juce::PopupMenu menu;
  3643. const auto* c = current();
  3644. if (c == nullptr)
  3645. return menu;
  3646. const auto sample = sampleOf (*c);
  3647. const juce::File file (juce::String::fromUTF8 (c->samplePath.c_str()));
  3648. const auto has = sample != nullptr && sample->frames() > 0;
  3649. auto pendingLine = false;
  3650. for (const auto& e : samplerpage::waveMenu())
  3651. {
  3652. if (e.text == nullptr)
  3653. {
  3654. pendingLine = menu.getNumItems() > 0;
  3655. continue;
  3656. }
  3657. if (! e.have)
  3658. continue;
  3659. if (pendingLine)
  3660. menu.addSeparator();
  3661. pendingLine = false;
  3662. const juce::String key (e.text);
  3663. const auto text = tr (e.text) + (juce::String (e.shortcut).isNotEmpty() ? "\t" + juce::String (e.shortcut) : juce::String());
  3664. auto safe = juce::Component::SafePointer<SettingsPanel> (this);
  3665. if (key == "Reload")
  3666. menu.addItem (text, file.existsAsFile(), false, [safe, file] {
  3667. if (safe == nullptr)
  3668. return;
  3669. // (the file may have changed on disk: the library reads it again)
  3670. safe->engine.getSampleLibrary().forget (file.getFullPathName());
  3671. safe->ref.edit (safe->engine, [path = file.getFullPathName().toStdString()] (ChannelDef& d) { d.samplePath = path; });
  3672. safe->refresh();
  3673. });
  3674. else if (key == "Save as...")
  3675. menu.addItem (text, has, false, [safe] { if (safe != nullptr) safe->saveSampleAs(); });
  3676. else if (key == "Locate file")
  3677. menu.addItem (text, file.existsAsFile(), false, [file] { file.revealToUser(); });
  3678. else if (key == "Copy audio to clipboard")
  3679. menu.addItem (text, has, false, [sample] {
  3680. audioedit::Audio a;
  3681. a.sampleRate = sample->sampleRate;
  3682. a.channels.emplace_back (sample->leftData(), sample->leftData() + sample->frames());
  3683. if (sample->isStereo())
  3684. a.channels.emplace_back (sample->rightData(), sample->rightData() + sample->frames());
  3685. audioclipboard::editor() = std::move (a);
  3686. });
  3687. else if (key == "Paste audio from clipboard")
  3688. menu.addItem (text, audioclipboard::hasAudio(), false, [safe] {
  3689. const auto wav = audioclipboard::wav();
  3690. if (safe == nullptr || wav.empty())
  3691. return;
  3692. // (FL loads the clipboard's audio as the channel's sample: LYNX writes it to the clipboard files first)
  3693. const auto saved = audioclipboard::save ("Audio clipboard", ".wav", wav.data(), wav.size());
  3694. if (saved.existsAsFile())
  3695. safe->replaceSample (saved);
  3696. });
  3697. else if (key == "Edit in audio editor")
  3698. menu.addItem (text, has && ref.index >= 0, false, [safe] {
  3699. if (safe != nullptr)
  3700. openAudioEditorForChannel (safe->engine, safe->ref.index);
  3701. });
  3702. else if (key == "Open in new sampler channel" || key == "Open in new Fruity Granulizer channel" || key == "Open in new Fruity Slicer channel"
  3703. || key == "Open in new Slicex channel")
  3704. {
  3705. const auto kind = key == "Open in new sampler channel" ? InstrumentKind::sampler
  3706. : key == "Open in new Fruity Granulizer channel" ? InstrumentKind::granulizer
  3707. : key == "Open in new Fruity Slicer channel" ? InstrumentKind::fruityslicer
  3708. : InstrumentKind::slicex;
  3709. menu.addItem (text, file.existsAsFile() && openInNewChannelHandler() != nullptr, false, [file, kind] {
  3710. if (openInNewChannelHandler())
  3711. openInNewChannelHandler() (file, kind);
  3712. });
  3713. }
  3714. else if (key == "Edit in pitch corrector" || key == "Edit in time warper") // (round 190gw)
  3715. menu.addItem (text, has && file.existsAsFile(), false, [safe, file, kind = key == "Edit in pitch corrector" ? EffectKind::newtone : EffectKind::newtime] {
  3716. if (safe != nullptr)
  3717. openSampleInMasterEditor (safe->engine, kind, file.getFullPathName().toStdString());
  3718. });
  3719. else if (key == "Spectrum view" || key == "Multichannel waveform view") // (round 190gw: FL's global view switches)
  3720. {
  3721. const auto spectrum = key == "Spectrum view";
  3722. auto& views = samplerpage::waveViews();
  3723. menu.addItem (text, true, spectrum ? views.spectrum : views.multichannel, [safe, spectrum] {
  3724. auto& v = samplerpage::waveViews();
  3725. (spectrum ? v.spectrum : v.multichannel) = ! (spectrum ? v.spectrum : v.multichannel);
  3726. if (safe != nullptr)
  3727. safe->wave.repaint();
  3728. if (EditorGlobals::get().onOptionsChanged) // (kept in the UI settings)
  3729. EditorGlobals::get().onOptionsChanged();
  3730. });
  3731. }
  3732. else if (key == "Get properties")
  3733. {
  3734. if (fileProperties) // (FL: Explorer's Properties of the sample's file; no such window on the other systems)
  3735. menu.addItem (text, file.existsAsFile(), false, [file] { showFileProperties (file); });
  3736. }
  3737. else if (key == "Detect tempo")
  3738. menu.addItem (text, has, false, [safe, sample] {
  3739. if (safe == nullptr)
  3740. return;
  3741. const auto* ch = safe->current();
  3742. ui::TempoDetectionRequest r;
  3743. r.name = ch != nullptr ? juce::String::fromUTF8 (ch->name.c_str()) : juce::String();
  3744. r.sample = sample;
  3745. r.projectBpm = safe->engine.getSong().bpm;
  3746. r.hasTempoInfo = sample->acidBeats > 0.0f;
  3747. // (the tempo picked: the sample lasts that many beats, TIME on the page; no tempo: TIME off)
  3748. r.apply = [safe] (double beats) {
  3749. if (safe != nullptr)
  3750. safe->ref.edit (safe->engine, [beats] (ChannelDef& d) { samplerpage::setStretchTime (d.sampler, (float) beats); });
  3751. };
  3752. ui::showTempoDetectionDialog (std::move (r));
  3753. });
  3754. }
  3755. return menu;
  3756. }
  3757. void saveSampleAs()
  3758. {
  3759. const auto* c = current();
  3760. const auto sample = c != nullptr ? sampleOf (*c) : nullptr;
  3761. if (sample == nullptr)
  3762. return;
  3763. const juce::File now (juce::String::fromUTF8 (c->samplePath.c_str()));
  3764. sampleChooser = lynx::ui::makeFileChooser (tr ("Save as..."), now.getParentDirectory().getChildFile (now.getFileNameWithoutExtension() + ".wav"), "*.wav");
  3765. lynx::ui::launchChooser (sampleChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles
  3766. | juce::FileBrowserComponent::warnAboutOverwriting,
  3767. [sample] (const juce::FileChooser& fc) {
  3768. auto target = fc.getResult();
  3769. if (target == juce::File())
  3770. return;
  3771. audioedit::Document doc;
  3772. doc.audio.sampleRate = sample->sampleRate;
  3773. doc.audio.channels.emplace_back (sample->leftData(), sample->leftData() + sample->frames());
  3774. if (sample->isStereo())
  3775. doc.audio.channels.emplace_back (sample->rightData(), sample->rightData() + sample->frames());
  3776. doc.loopStart = sample->loopStart;
  3777. doc.loopEnd = sample->loopEnd;
  3778. const auto format = sample->floatData || sample->bitsPerSample > 24 ? audioedit::WavFormat::float32
  3779. : sample->bitsPerSample > 16 ? audioedit::WavFormat::int24
  3780. : audioedit::WavFormat::int16;
  3781. const auto bytes = audioedit::encodeWav (doc, format);
  3782. target.withFileExtension ("wav").replaceWithData (bytes.data(), bytes.size());
  3783. });
  3784. }
  3785. public:
  3786. juce::PopupMenu waveMenuForShot() { return waveMenu(); }
  3787. // (the shot route: the history menu without showing it, and the row's buttons)
  3788. juce::PopupMenu sampleHistoryMenuForShot() { return sampleHistoryMenu(); }
  3789. void pressFileRow (int button)
  3790. {
  3791. if (button == 0 || button == 1)
  3792. loadButton.onWheel (button == 0 ? -1 : 1);
  3793. else if (button == 2)
  3794. locateButton.onClick();
  3795. else if (button == 3)
  3796. removeSample();
  3797. }
  3798. private:
  3799. const ChannelDef* current() const
  3800. {
  3801. return ref.get (engine);
  3802. }
  3803. // the channel's sample as the loop knobs see it (frames and the file's own loop); none for a multi-sample channel
  3804. std::shared_ptr<const SampleData> sampleOf (const ChannelDef& c) const
  3805. {
  3806. if (c.samplePath.empty() || ! c.zones.empty())
  3807. return nullptr;
  3808. return engine.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str()));
  3809. }
  3810. void refresh()
  3811. {
  3812. const auto* c = current();
  3813. if (c == nullptr)
  3814. return;
  3815. const auto& s = c->sampler;
  3816. const juce::ScopedValueSetter<bool> guard (updating, true);
  3817. const auto sample = sampleOf (*c);
  3818. const auto frames = sample != nullptr ? (std::int64_t) sample->frames() : 0;
  3819. // Content (live check 190ew SMP-1 / SMP-2: all greyed without a sample; Resample at the project's rate, Load
  3820. // regions / Load slice markers without regions / slice markers in the file)
  3821. const auto hasSample = sample != nullptr;
  3822. keepOnDisk.setToggleState (s.keepOnDisk, juce::dontSendNotification);
  3823. keepOnDisk.setEnabled (hasSample && samplerpage::keepOnDiskAvailable (s, sample->loopStart >= 0 && sample->loopEnd > sample->loopStart));
  3824. resampleBox.setEnabled (samplerpage::resampleAvailable (hasSample, hasSample ? sample->sampleRate : 0.0, engine.getTransport().sampleRate.load()));
  3825. loadRegionsBox.setEnabled (samplerpage::loadRegionsAvailable (hasSample, hasSample && ! sample->markerStarts.empty()));
  3826. loadMarkersBox.setEnabled (samplerpage::loadSliceMarkersAvailable (hasSample, hasSample && sample->sliceMarkers > 0));
  3827. resampleBox.setToggleState (s.resampleOnLoad, juce::dontSendNotification);
  3828. loadRegionsBox.setToggleState (s.loadRegions, juce::dontSendNotification);
  3829. loadMarkersBox.setToggleState (s.loadSliceMarkers, juce::dontSendNotification);
  3830. declick.setSelectedId (juce::jlimit (0, 5, s.declickMode) + 1, juce::dontSendNotification);
  3831. // Playback
  3832. startOffsetKnob.setValue (s.startOffset, juce::dontSendNotification);
  3833. useLoops.setToggleState (s.useLoopPoints, juce::dontSendNotification);
  3834. pingPong.setToggleState (s.precompute.pingPong, juce::dontSendNotification);
  3835. loopStartKnob.setEnabled (frames > 1);
  3836. loopEndKnob.setEnabled (frames > 1);
  3837. shownFileLoop = { sample != nullptr ? sample->loopStart : -1, sample != nullptr ? sample->loopEnd : -1 };
  3838. shownFrames = frames;
  3839. if (frames > 1)
  3840. {
  3841. loopStartKnob.setRange (0.0, (double) (frames - 1), 1.0);
  3842. loopEndKnob.setRange (0.0, (double) (frames - 1), 1.0);
  3843. const auto [a, b] = samplerpage::shownLoop (s, shownFileLoop.first, shownFileLoop.second);
  3844. loopStartKnob.setValue ((double) juce::jmax<std::int64_t> (0, a), juce::dontSendNotification);
  3845. loopEndKnob.setValue ((double) (b >= 0 ? b : frames - 1), juce::dontSendNotification);
  3846. loopStartKnob.setDoubleClickReturnValue (false, 0.0);
  3847. loopEndKnob.setDoubleClickReturnValue (false, 0.0);
  3848. wave.setLoop (a >= 0 && s.useLoopPoints ? (float) a / (float) (frames - 1) : -1.0f, b >= 0 && s.useLoopPoints ? (float) b / (float) (frames - 1) : -1.0f);
  3849. }
  3850. else
  3851. wave.setLoop (-1.0f, -1.0f);
  3852. // round 190ey (live check 190ew SMP-7 / SMP-7b): FL's bit-depth box, and its summary as the waveform's hint
  3853. if (hasSample)
  3854. {
  3855. const auto bits = samplerpage::bitDepthShown (sample->bitsPerSample, s.precompute.any());
  3856. wave.setCornerText (bits > 0 ? juce::String (bits) : juce::String());
  3857. wave.setTooltip (juce::String (samplerpage::sampleSummary (sample->sampleRate, sample->floatData && ! s.precompute.any() ? sample->bitsPerSample : bits,
  3858. sample->floatData || s.precompute.any(), sample->isStereo(),
  3859. (double) frames / juce::jmax (1.0, sample->sampleRate), sample->isMapped())));
  3860. }
  3861. else
  3862. {
  3863. wave.setCornerText ({});
  3864. wave.setTooltip (tr ("Waveform") + " - " + tr ("click: preview the sample; mouse wheel: zoom"));
  3865. }
  3866. // Time stretching
  3867. stretchPitchKnob.setValue (s.flStretchPitch, juce::dontSendNotification);
  3868. mulKnob.setValue (s.stretchMul, juce::dontSendNotification);
  3869. stretch.setValue (samplerpage::stretchTime (s), juce::dontSendNotification);
  3870. stretchMethod.setSelectedId (samplerpage::modeIndex (s) + 1, juce::dontSendNotification);
  3871. // Precomputed effects
  3872. const auto& p = s.precompute;
  3873. removeDc.setToggleState (p.removeDc, juce::dontSendNotification);
  3874. normalize.setToggleState (p.normalize, juce::dontSendNotification);
  3875. reverse.setToggleState (s.reverse, juce::dontSendNotification);
  3876. polarity.setToggleState (p.reversePolarity, juce::dontSendNotification);
  3877. fadeStereo.setToggleState (p.fadeStereo, juce::dontSendNotification);
  3878. swapStereo.setToggleState (p.swapStereo, juce::dontSendNotification);
  3879. regionStart.setValue (s.regionStart, juce::dontSendNotification);
  3880. lengthKnob.setValue (samplerpage::lengthOf (s), juce::dontSendNotification);
  3881. fadeIn.setValue (p.fadeIn, juce::dontSendNotification);
  3882. fadeOut.setValue (p.fadeOut, juce::dontSendNotification);
  3883. // (a value over FL's knob range from an old project shows at the end of a range that holds it)
  3884. crossfade.setRange (0.0, juce::jmax (1024.0, (double) p.crossfade), 1.0);
  3885. crossfade.setValue (p.crossfade, juce::dontSendNotification);
  3886. trim.setRange (0.0, juce::jmax (256.0, (double) p.trim), 1.0);
  3887. trim.setValue (p.trim, juce::dontSendNotification);
  3888. boost.setValue (p.boost, juce::dontSendNotification);
  3889. eq.setValue (p.eq, juce::dontSendNotification);
  3890. ringMix.setValue (p.ringMix, juce::dontSendNotification);
  3891. ringFreq.setValue (p.ringFreq, juce::dontSendNotification);
  3892. legacyCut.setValue (p.cutoff, juce::dontSendNotification);
  3893. legacyRes.setValue (p.resonance, juce::dontSendNotification);
  3894. reverbAmount.setValue (p.reverb, juce::dontSendNotification);
  3895. reverbType.setSelectedId (p.reverbType == 0 ? 1 : 2, juce::dontSendNotification);
  3896. stereoDelay.setValue (p.stereoDelay, juce::dontSendNotification);
  3897. pogo.setValue (p.pogo, juce::dontSendNotification);
  3898. clip.setToggleState (p.clip, juce::dontSendNotification);
  3899. // LYNX extras
  3900. gain.setValue (s.gainDb, juce::dontSendNotification);
  3901. attack.setValue (s.attack, juce::dontSendNotification);
  3902. decay.setValue (s.decay, juce::dontSendNotification);
  3903. sustain.setValue (s.sustain, juce::dontSendNotification);
  3904. release.setValue (s.release, juce::dontSendNotification);
  3905. cutoff.setValue (s.cutoff, juce::dontSendNotification);
  3906. resonance.setValue (s.resonance, juce::dontSendNotification);
  3907. filterType.setSelectedId (s.filterType + 1, juce::dontSendNotification);
  3908. cut.setToggleState (channelCutsItself (*c), juce::dontSendNotification); // (issue #68: the rack menu's state too)
  3909. porta.setToggleState (s.porta, juce::dontSendNotification);
  3910. showAutomation (true);
  3911. const auto path = juce::String::fromUTF8 ((c->samplePath.empty() && ! c->zones.empty() ? c->zones.front().path : c->samplePath).c_str());
  3912. fileName.setText (juce::File (path).getFileName(), juce::dontSendNotification); // (FL: the name, the path's end)
  3913. fileName.setTooltip (path);
  3914. locateButton.setEnabled (! c->samplePath.empty());
  3915. removeButton.setEnabled (! c->samplePath.empty() || ! c->zones.empty());
  3916. wave.setFile (path, [&e = engine, path] { return e.getSampleLibrary().load (path); });
  3917. wavePath = path;
  3918. wave.setRegion (s.regionStart, s.regionEnd);
  3919. wave.setReversed (s.reverse);
  3920. wave.setStartOffset (s.startOffset); // round 190w (FL dims the region before it)
  3921. if (auto* w = findParentComponentOfClass<juce::DocumentWindow>())
  3922. w->setName (tr ("Sampler settings - {0}", { juce::String::fromUTF8 (c->name.c_str()) })
  3923. + (c->zones.empty() ? juce::String() : tr (" (multi-sample: {0} zones)", { juce::String ((int) c->zones.size()) })));
  3924. }
  3925. // The knobs an automation drives show its value while the song plays, as in FL (issue #12); a knob held by the
  3926. // mouse shows the hand's value. `force`: after refresh() put the Song's values back.
  3927. void showAutomation (bool force)
  3928. {
  3929. const auto* c = current();
  3930. if (c == nullptr || ref.index < 0)
  3931. return;
  3932. const auto& shown = engine.getAutomationDisplay();
  3933. if (! force && shown.getGeneration() == shownGeneration)
  3934. return;
  3935. shownGeneration = shown.getGeneration();
  3936. if (! force && automatedShown.empty() && ! shown.any())
  3937. return;
  3938. std::vector<juce::Slider*> now;
  3939. const juce::ScopedValueSetter<bool> guard (updating, true);
  3940. auto shownSettings = c->sampler; // (the region as the automation has it: LENGTH is relative to SMP START)
  3941. for (const auto& [slider, param] : tweakTargets)
  3942. if (const auto v = shown.valueOf ({ AutomationTargetKind::channelParam, ref.index, 0, param }))
  3943. samplerparam::set (shownSettings, param, *v);
  3944. for (const auto& [slider, param] : tweakTargets)
  3945. {
  3946. if (slider->isMouseButtonDown())
  3947. continue;
  3948. const auto v = shown.valueOf ({ AutomationTargetKind::channelParam, ref.index, 0, param });
  3949. const auto was = std::find (automatedShown.begin(), automatedShown.end(), slider) != automatedShown.end();
  3950. const auto value = [&] (const SamplerSettings& s) {
  3951. return param == samplerparam::end ? (double) samplerpage::lengthOf (s) : (double) samplerparam::toNatural (param, samplerparam::get (s, param));
  3952. };
  3953. if (v)
  3954. {
  3955. slider->setValue (value (shownSettings), juce::dontSendNotification);
  3956. now.push_back (slider);
  3957. }
  3958. else if (was && ! force)
  3959. slider->setValue (value (c->sampler), juce::dontSendNotification);
  3960. }
  3961. automatedShown = std::move (now);
  3962. wave.setRegion (shownSettings.regionStart, shownSettings.regionEnd);
  3963. }
  3964. void timerCallback() override
  3965. {
  3966. if (isShowing())
  3967. showAutomation (false);
  3968. followPreview();
  3969. }
  3970. // One control changed (`changed`): its law applied to the channel's sampler settings (core/SamplerPage.h), one edit
  3971. void apply (juce::Component* changed)
  3972. {
  3973. const auto* c = current();
  3974. if (updating || c == nullptr)
  3975. return;
  3976. auto s = c->sampler;
  3977. const auto& old = c->sampler;
  3978. bool cutOn = channelCutsItself (*c), cutChanged = false;
  3979. auto value = [] (juce::Component* k) { return static_cast<juce::Slider*> (k)->getValue(); };
  3980. auto on = [] (juce::Component* b) { return static_cast<juce::Button*> (b)->getToggleState(); };
  3981. auto& p = s.precompute;
  3982. if (changed == &keepOnDisk) s.keepOnDisk = on (changed);
  3983. else if (changed == &resampleBox) s.resampleOnLoad = on (changed);
  3984. else if (changed == &loadRegionsBox) s.loadRegions = on (changed);
  3985. else if (changed == &loadMarkersBox) s.loadSliceMarkers = on (changed);
  3986. else if (changed == &declick) s.declickMode = juce::jlimit (0, 5, declick.getSelectedId() - 1);
  3987. else if (changed == &startOffsetKnob) s.startOffset = (float) value (changed);
  3988. else if (changed == &loopStartKnob || changed == &loopEndKnob)
  3989. {
  3990. const auto keep = shiftHeld || (! shotDriven && juce::ModifierKeys::currentModifiers.isShiftDown()); // (FL: Shift moves the loop)
  3991. if (changed == &loopStartKnob)
  3992. samplerpage::setLoopStart (s, (std::int64_t) std::llround (value (changed)), shownFrames, shownFileLoop.first, shownFileLoop.second, keep);
  3993. else
  3994. samplerpage::setLoopEnd (s, (std::int64_t) std::llround (value (changed)), shownFrames, shownFileLoop.first, shownFileLoop.second, keep);
  3995. }
  3996. else if (changed == &useLoops)
  3997. {
  3998. s.useLoopPoints = on (changed);
  3999. // FL's LoopBoxClick 0xf67f70: switching loop points on makes the channel cut itself (FUN_00feaaf0)
  4000. if (s.useLoopPoints && ! cutOn && ref.index >= 0)
  4001. cutOn = cutChanged = true;
  4002. }
  4003. else if (changed == &pingPong) p.pingPong = on (changed);
  4004. else if (changed == &stretchPitchKnob) samplerpage::turnStretchPitch (s, juce::roundToInt (value (changed)));
  4005. else if (changed == &mulKnob)
  4006. {
  4007. const auto sample = sampleOf (*c);
  4008. const auto beats = sample != nullptr && sample->sampleRate > 0.0
  4009. ? (double) sample->frames() / sample->sampleRate * engine.getSong().bpm / 60.0 : 0.0;
  4010. samplerpage::setStretchMul (s, juce::roundToInt (value (changed)), beats);
  4011. }
  4012. else if (changed == &stretch) samplerpage::setStretchTime (s, (float) value (changed));
  4013. else if (changed == &stretchMethod) samplerpage::selectMode (s, stretchMethod.getSelectedId() - 1);
  4014. else if (changed == &removeDc) p.removeDc = on (changed);
  4015. else if (changed == &normalize) p.normalize = on (changed);
  4016. else if (changed == &reverse) s.reverse = on (changed);
  4017. else if (changed == &polarity) p.reversePolarity = on (changed);
  4018. else if (changed == &fadeStereo) p.fadeStereo = on (changed);
  4019. else if (changed == &swapStereo) p.swapStereo = on (changed);
  4020. else if (changed == &regionStart) samplerpage::setSmpStart (s, (float) value (changed));
  4021. else if (changed == &lengthKnob) samplerpage::setLength (s, (float) value (changed));
  4022. else if (changed == &fadeIn) p.fadeIn = juce::roundToInt (value (changed));
  4023. else if (changed == &fadeOut) p.fadeOut = juce::roundToInt (value (changed));
  4024. else if (changed == &crossfade)
  4025. {
  4026. const auto loopsBefore = s.useLoopPoints;
  4027. // (live check 190ew SMP-4: on a loopless sample FL also sets END to the sample's end)
  4028. samplerpage::turnCrossfade (s, juce::roundToInt (value (changed)), shownFrames, shownFileLoop.first, shownFileLoop.second);
  4029. // (FL ticks "Use loop points" the way a click does, so the channel cuts itself as with the click)
  4030. if (s.useLoopPoints && ! loopsBefore && ! cutOn && ref.index >= 0)
  4031. cutOn = cutChanged = true;
  4032. }
  4033. else if (changed == &trim) p.trim = juce::roundToInt (value (changed));
  4034. else if (changed == &boost) p.boost = juce::roundToInt (value (changed));
  4035. else if (changed == &eq) p.eq = juce::roundToInt (value (changed));
  4036. else if (changed == &ringMix) p.ringMix = juce::roundToInt (value (changed));
  4037. else if (changed == &ringFreq) p.ringFreq = juce::roundToInt (value (changed));
  4038. else if (changed == &legacyCut) p.cutoff = juce::roundToInt (value (changed));
  4039. else if (changed == &legacyRes) p.resonance = juce::roundToInt (value (changed));
  4040. else if (changed == &reverbAmount) p.reverb = juce::roundToInt (value (changed));
  4041. else if (changed == &reverbType) p.reverbType = reverbType.getSelectedId() == 1 ? 0 : 1;
  4042. else if (changed == &stereoDelay) p.stereoDelay = juce::roundToInt (value (changed));
  4043. else if (changed == &pogo) p.pogo = juce::roundToInt (value (changed));
  4044. else if (changed == &clip) p.clip = on (changed);
  4045. else if (changed == &gain) s.gainDb = std::abs (value (changed)) < 0.05 ? 0.0f : (float) value (changed);
  4046. else if (changed == &attack) s.attack = (float) value (changed);
  4047. else if (changed == &decay) s.decay = (float) value (changed);
  4048. else if (changed == &sustain) s.sustain = (float) value (changed);
  4049. else if (changed == &release) s.release = (float) value (changed);
  4050. else if (changed == &cutoff) s.cutoff = (float) value (changed);
  4051. else if (changed == &resonance) s.resonance = (float) value (changed);
  4052. else if (changed == &filterType) s.filterType = juce::jlimit (0, 3, filterType.getSelectedId() - 1);
  4053. else if (changed == &cut)
  4054. {
  4055. cutOn = on (changed);
  4056. cutChanged = cutOn != channelCutsItself (*c); // (issue #68: the rack menu's cut-itself too)
  4057. }
  4058. else if (changed == &porta) s.porta = on (changed);
  4059. else
  4060. return;
  4061. // leaving Beats (or Resample): an imported clip's offline transposition moves to the Pitch knob, which the other
  4062. // modes apply in real time, so the sample stays at its pitch
  4063. s.moveBakedPitchToKnob();
  4064. bool dropFlmVoice = false;
  4065. {
  4066. // an ADSR edited by hand replaces FL's imported volume envelope (and FL Studio Mobile's pad envelope, round
  4067. // 190bs); so does an edited envelope or filter for FL's whole sampler voice (REA_rodada76)
  4068. auto moved = [] (float a, float b) { return std::abs (a - b) > 1.0e-4f; };
  4069. const auto adsr = moved (s.attack, old.attack) || moved (s.decay, old.decay) || moved (s.sustain, old.sustain) || moved (s.release, old.release);
  4070. if (adsr)
  4071. {
  4072. s.flVolumeEnvelope.clear();
  4073. s.flmPad.clear();
  4074. dropFlmVoice = flmdw::isChannel (*c); // and FL Studio Mobile's DW Sampler voice (round 190de)
  4075. }
  4076. if (adsr || moved (s.cutoff, old.cutoff) || moved (s.resonance, old.resonance) || s.filterType != old.filterType)
  4077. s.flChannel.clear();
  4078. }
  4079. if (cutChanged)
  4080. s.cut = cutOn;
  4081. if (s == old && ! cutChanged)
  4082. return;
  4083. const auto before = old;
  4084. ref.edit (engine, [s, cutChanged, cutOn, dropFlmVoice, index = ref.index] (ChannelDef& channelDef) {
  4085. channelDef.sampler = s;
  4086. if (dropFlmVoice) // (the Sampler's own voice from now on: the module's values go, its zones stay)
  4087. channelDef.modelParams.clear();
  4088. if (cutChanged)
  4089. setChannelCutsItself (channelDef, index, cutOn);
  4090. });
  4091. for (const auto& [slider, param] : tweakTargets)
  4092. if (std::abs (samplerparam::get (before, param) - samplerparam::get (s, param)) > 1.0e-6f)
  4093. engine.noteTweaked ({ AutomationTargetKind::channelParam, ref.index, 0, param });
  4094. }
  4095. void changeListenerCallback (juce::ChangeBroadcaster*) override
  4096. {
  4097. if (current() == nullptr) // channel removed
  4098. {
  4099. if (auto* w = findParentComponentOfClass<juce::DocumentWindow>())
  4100. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<juce::DocumentWindow> (w)] {
  4101. if (safe != nullptr)
  4102. safe->closeButtonPressed();
  4103. });
  4104. return;
  4105. }
  4106. refresh();
  4107. }
  4108. AudioEngine& engine;
  4109. ChannelRef ref;
  4110. bool updating = false, shiftHeld = false, shotDriven = false;
  4111. float scale = 1.0f;
  4112. int offsetX = 0;
  4113. struct Group
  4114. {
  4115. juce::Rectangle<int> area;
  4116. juce::String caption;
  4117. int captionLeft;
  4118. };
  4119. std::vector<Group> groups;
  4120. juce::Rectangle<int> loopGlyph;
  4121. bool clipChannel = false; // an audio clip's channel: FL's audio clip page (no Playback box, no LYNX extras)
  4122. // FL's TIME knob menu (r168s c_f20): (none), Autodetect, Project tempo, 1 beat, 2 beats, 1 bar, 2 bars, 3 bars, 4 bars
  4123. struct StretchMenu final : juce::MouseListener
  4124. {
  4125. explicit StretchMenu (SettingsPanel& p) : panel (p) {}
  4126. void mouseDown (const juce::MouseEvent& e) override
  4127. {
  4128. if (e.mods.isPopupMenu())
  4129. panel.showStretchMenu();
  4130. }
  4131. SettingsPanel& panel;
  4132. } stretchMenu { *this };
  4133. void showStretchMenu()
  4134. {
  4135. const auto* c = current();
  4136. if (c == nullptr)
  4137. return;
  4138. const auto& song = engine.getSong();
  4139. const auto sample = engine.getSampleLibrary().load (juce::String::fromUTF8 (c->samplePath.c_str()));
  4140. const auto now = samplerpage::stretchTime (c->sampler);
  4141. auto set = [this] (float beats) { ref.edit (engine, [beats] (ChannelDef& d) { samplerpage::setStretchTime (d.sampler, beats); }); };
  4142. juce::PopupMenu m;
  4143. m.addItem (tr ("(none)"), true, now <= 0.0f, [set] { set (0.0f); });
  4144. m.addItem (tr ("Autodetect"), sample != nullptr, false, [set, sample, bpm = song.bpm] { set (tempodetect::fitBeatsOf (sample.get(), bpm)); });
  4145. const auto atTempo = sample != nullptr && sample->sampleRate > 0.0 ? (float) ((double) sample->frames() / sample->sampleRate * song.bpm / 60.0) : 0.0f;
  4146. m.addItem (tr ("Project tempo"), atTempo > 0.0f, false, [set, atTempo] { set (atTempo); });
  4147. const auto barBeats = (float) song.barTicks() / (float) ppq; // (round 190fg: a bar in quarter notes)
  4148. for (const auto preset : clipops::timePresetBeats (song.meter()))
  4149. {
  4150. const auto bars = preset >= barBeats - 1.0e-4f ? preset / barBeats : 0.0f;
  4151. const auto label = bars > 0.0f ? (bars == 1.0f ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars, 0) }))
  4152. : (preset == 1.0f ? tr ("1 beat") : tr ("{0} beats", { juce::String (preset, 0) }));
  4153. m.addItem (label, true, now == preset, [set, preset] { set (preset); });
  4154. }
  4155. m.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&stretch));
  4156. }
  4157. // File row
  4158. static constexpr int fileRowHeight = 34; // FL's File row (round 190df)
  4159. juce::Label fileLabel, fileName;
  4160. WheelIconButton loadButton { "load", Icon::open }, locateButton { "locate", Icon::browser }, removeButton { "remove", Icon::close };
  4161. std::unique_ptr<juce::FileChooser> sampleChooser;
  4162. // Content
  4163. juce::ToggleButton keepOnDisk, resampleBox, loadRegionsBox, loadMarkersBox;
  4164. juce::Label declickLabel;
  4165. juce::ComboBox declick;
  4166. // Playback
  4167. MenuSlider startOffsetKnob, loopStartKnob, loopEndKnob;
  4168. juce::Label startOffsetLabel, loopStartLabel, loopEndLabel;
  4169. juce::ToggleButton useLoops, pingPong;
  4170. std::pair<std::int64_t, std::int64_t> shownFileLoop { -1, -1 };
  4171. std::int64_t shownFrames = 0;
  4172. // Time stretching
  4173. MenuSlider stretchPitchKnob, mulKnob, stretch;
  4174. juce::Label stretchPitchLabel, mulLabel, stretchLabel, modeLabel;
  4175. juce::ComboBox stretchMethod;
  4176. // Precomputed effects (and FL's legacy panel)
  4177. juce::ToggleButton removeDc, normalize, reverse, polarity, fadeStereo, swapStereo, clip;
  4178. MenuSlider regionStart, lengthKnob, fadeIn, fadeOut, crossfade, trim;
  4179. juce::Label regionStartLabel, lengthLabel, fadeInLabel, fadeOutLabel, crossfadeLabel, trimLabel;
  4180. EffectsTargetSelect effectsTarget;
  4181. MenuSlider boost, eq, ringMix, ringFreq, legacyCut, legacyRes, reverbAmount, stereoDelay, pogo;
  4182. juce::Label boostLabel, eqLabel, ringMixLabel, ringFreqLabel, legacyCutLabel, legacyResLabel, reverbLabel, stereoDelayLabel, pogoLabel;
  4183. juce::ComboBox reverbType;
  4184. // the waveform
  4185. ui::WaveformDisplay wave;
  4186. struct SampleDragOut final : juce::MouseListener // (round 190ih: drag the sample out)
  4187. {
  4188. std::function<juce::String()> path;
  4189. bool started = false;
  4190. void mouseDown (const juce::MouseEvent&) override { started = false; }
  4191. void mouseDrag (const juce::MouseEvent& e) override
  4192. {
  4193. if (started || e.mods.isPopupMenu() || e.getDistanceFromDragStart() < 8 || path == nullptr)
  4194. return;
  4195. const juce::File file (path());
  4196. if (! file.existsAsFile())
  4197. return;
  4198. started = true;
  4199. if (auto* container = juce::DragAndDropContainer::findParentDragContainerFor (e.eventComponent))
  4200. container->startDragging (juce::String (BrowserComponent::dragDescription) + "|" + file.getFullPathName(), e.eventComponent);
  4201. else
  4202. juce::DragAndDropContainer::performExternalDragDropOfFiles ({ file.getFullPathName() }, false, e.eventComponent);
  4203. }
  4204. };
  4205. SampleDragOut waveDrag;
  4206. juce::String wavePath;
  4207. juce::ScrollBar waveScroll { false };
  4208. // LYNX extras
  4209. MenuSlider gain, attack, decay, sustain, release, cutoff, resonance;
  4210. juce::Label gainLabel, attackLabel, decayLabel, sustainLabel, releaseLabel, cutoffLabel, resonanceLabel, extrasLabel;
  4211. juce::ComboBox filterType;
  4212. juce::ToggleButton cut, porta;
  4213. juce::TextButton modulationButton;
  4214. std::vector<std::pair<MenuSlider*, int>> tweakTargets; // knob -> samplerparam
  4215. std::vector<juce::Slider*> automatedShown; // knobs showing their automation's value now
  4216. std::uint32_t shownGeneration = 0;
  4217. bool dropHighlight = false;
  4218. int previewKey = -1, previewFrames = 0; // round 190w: the display's preview note (-1 = none)
  4219. bool previewSeen = false;
  4220. };
  4221. // Built-in synth page: 3 oscillators, envelope and filter.
  4222. class SynthPanel final : public juce::Component,
  4223. private juce::ChangeListener,
  4224. private juce::Timer
  4225. {
  4226. public:
  4227. SynthPanel (AudioEngine& e, ChannelRef c)
  4228. : engine (e),
  4229. ref (std::move (c))
  4230. {
  4231. for (int o = 0; o < 3; ++o)
  4232. {
  4233. auto& row = rows[(std::size_t) o];
  4234. row.title.setText (tr ("Osc {0}", { juce::String (o + 1) }), juce::dontSendNotification);
  4235. row.wave.addItemList ({ tr ("Sine"), tr ("Triangle"), tr ("Saw"), tr ("Square"), tr ("Noise"), tr ("Harmonics") }, 1);
  4236. row.wave.onChange = [this] { apply(); };
  4237. knob (row.octave, -3.0, 3.0, 1.0, " oct");
  4238. knob (row.semitones, -11.0, 11.0, 1.0, " st");
  4239. knob (row.detune, -100.0, 100.0, 1.0, " ct");
  4240. knob (row.pan, -1.0, 1.0, 0.01, "");
  4241. knob (row.level, 0.0, 4.0, 0.01, "");
  4242. row.level.setSkewFactorFromMidPoint (1.0); // above 1: gain (Harmor goes up to +12 dB)
  4243. addAndMakeVisible (row.title);
  4244. addAndMakeVisible (row.wave);
  4245. }
  4246. knob (attack, 0.0, 5.0, 0.001, " s");
  4247. knob (decay, 0.0, 5.0, 0.001, " s");
  4248. knob (sustain, 0.0, 1.0, 0.01, "");
  4249. knob (release, 0.0, 5.0, 0.001, " s");
  4250. knob (cutoff, 20.0, 20000.0, 1.0, " Hz");
  4251. knob (resonance, 0.0, 1.0, 0.01, "");
  4252. knob (fm, 0.0, 8.0, 0.01, "");
  4253. fm.setSkewFactorFromMidPoint (1.0);
  4254. fm.setTooltip (tr ("FM: osc 3 (which stops sounding) modulates the phase of osc 1 and 2; 0 = off"));
  4255. knob (fmDecay, 0.0, 5.0, 0.001, " s");
  4256. fmDecay.setSkewFactorFromMidPoint (0.5);
  4257. fmDecay.setTooltip (tr ("Time for the FM index to decay (0 = constant); the brightness fades like an electric piano"));
  4258. knob (keyTrack, -1.0, 2.0, 0.01, "");
  4259. keyTrack.setTooltip (tr ("Cutoff follows the note: cutoff octaves per note octave, relative to C3 (130.8 Hz)"));
  4260. knob (sweep, 0.0, 100.0, 0.01, "");
  4261. sweep.setSkewFactorFromMidPoint (2.0);
  4262. sweep.setTooltip (tr ("Kick pitch sweep: the note starts (1 + value) times higher and falls"));
  4263. knob (sweepTime, 0.001, 2.0, 0.001, " s");
  4264. sweepTime.setSkewFactorFromMidPoint (0.1);
  4265. sweepTime.setTooltip (tr ("Sweep time constant"));
  4266. for (auto* b : { &bandLow, &bandMid, &bandHigh })
  4267. {
  4268. knob (*b, 0.0, 2.0, 0.01, "");
  4269. b->setTooltip (tr ("3-band tone after the filter (low < 178 Hz < mid < 1.18 kHz < high); 1 = unchanged"));
  4270. }
  4271. ring.setButtonText (tr ("Ring"));
  4272. ring.setTooltip (tr ("With AM on: ring modulation, (osc 1 + 2) × (1 − level + osc 3), like Sytrus's RM"));
  4273. ring.onClick = [this] { apply(); };
  4274. addAndMakeVisible (ring);
  4275. modulationButton.setButtonText (tr ("Modulation (envelopes and LFOs)..."));
  4276. modulationButton.onClick = [this] { showModulationFor (*this, engine, ref.index); };
  4277. addAndMakeVisible (modulationButton);
  4278. for (auto* s : { &attack, &decay, &release })
  4279. s->setSkewFactorFromMidPoint (0.5);
  4280. cutoff.setSkewFactorFromMidPoint (1000.0);
  4281. const char* names[] = { TR_NOOP ("Octave"), TR_NOOP ("Semitone"), TR_NOOP ("Fine"), TR_NOOP ("Pan"), TR_NOOP ("Level"), TR_NOOP ("Attack"), TR_NOOP ("Decay"), TR_NOOP ("Sustain"), TR_NOOP ("Release"), TR_NOOP ("Cutoff"), TR_NOOP ("Resonance"), TR_NOOP ("Porta time"), TR_NOOP ("FM"), TR_NOOP ("FM decay"),
  4282. TR_NOOP ("Keytrack"), TR_NOOP ("Sweep"), TR_NOOP ("Sweep time"), TR_NOOP ("Low"), TR_NOOP ("Mid"), TR_NOOP ("High") };
  4283. for (int i = 0; i < (int) labels.size(); ++i)
  4284. {
  4285. labels[(std::size_t) i].setText (tr (names[i]), juce::dontSendNotification);
  4286. labels[(std::size_t) i].setJustificationType (juce::Justification::centred);
  4287. labels[(std::size_t) i].setFont (theme::font (theme::type::caption));
  4288. addAndMakeVisible (labels[(std::size_t) i]);
  4289. }
  4290. presetBox.setTextWhenNothingSelected (tr ("Presets..."));
  4291. fillPresetBox();
  4292. presetBox.beforePopup = [this] { fillPresetBox(); }; // (round 190fs: the user's presets as they are on disk now)
  4293. presetBox.onChange = [this] {
  4294. const auto presets = synthPresets();
  4295. const auto id = presetBox.getSelectedId();
  4296. const auto index = id - 1;
  4297. presetBox.setSelectedId (0, juce::dontSendNotification);
  4298. if (juce::isPositiveAndBelow (index, (int) presets.size()) && current() != nullptr)
  4299. ref.edit (engine, [s = presets[(std::size_t) index].second] (ChannelDef& channelDef) { channelDef.synth = s; });
  4300. else if (id >= userPresetId && id - userPresetId < userFiles.size())
  4301. loadUserPreset (userFiles[id - userPresetId]);
  4302. else if (id == savePresetId)
  4303. saveUserPreset();
  4304. else if (id == deletePresetId && lastUserPreset.existsAsFile())
  4305. {
  4306. lastUserPreset.deleteFile();
  4307. lastUserPreset = juce::File();
  4308. }
  4309. else if (id == showFolderId)
  4310. genpresetui::reveal (genpresetui::folderFor (InstrumentKind::synth));
  4311. };
  4312. addAndMakeVisible (presetBox);
  4313. flPresets.setButtonText (tr ("FL presets..."));
  4314. flPresets.setTooltip (tr ("The 3x Osc channel presets that ship with FL Studio (Patches\\Channel presets\\3x Osc)"));
  4315. flPresets.onClick = [this] { showFlPresets(); };
  4316. addAndMakeVisible (flPresets);
  4317. filterTypeBox.addItemList ({ tr ("Low-pass"), tr ("Band-pass"), tr ("High-pass"), tr ("Notch") }, 1);
  4318. filterTypeBox.setTooltip (tr ("Filter type"));
  4319. filterTypeBox.onChange = [this] { apply(); };
  4320. addAndMakeVisible (filterTypeBox);
  4321. am.setButtonText ("AM");
  4322. am.setTooltip (tr ("Osc 3 modulates the amplitude of osc 1 and 2 (like 3x Osc's AM); its level is the depth"));
  4323. am.onClick = [this] { apply(); };
  4324. addAndMakeVisible (am);
  4325. knob (porta, 0.0, 2.0, 0.005, " t");
  4326. porta.setSkewFactorFromMidPoint (0.25);
  4327. porta.setTooltip (tr ("Portamento time, in beats (applies to the Porta button and to notes marked porta)"));
  4328. portaOn.setButtonText ("Porta");
  4329. portaOn.setTooltip (tr ("Portamento: the new note glides from the previous one (notes marked porta invert this)"));
  4330. portaOn.onClick = [this] { apply(); };
  4331. addAndMakeVisible (portaOn);
  4332. mono.setButtonText ("Mono");
  4333. mono.setTooltip (tr ("Single voice: the new note takes over the one currently sounding (basses and leads)"));
  4334. mono.onClick = [this] { apply(); };
  4335. addAndMakeVisible (mono);
  4336. // issue #152 (round 190he): every knob is one of the synth's parameters (core/SynthParams.h), as FL's plugin
  4337. // parameters are: right-click = FL's parameter menu (Link to controller, automation clip, Init song value); a
  4338. // move is a tweak; the knobs follow MIDI links (refresh) and play their automation (timer)
  4339. if (ref.index >= 0) // (a Patcher node: no automation target)
  4340. {
  4341. for (int o = 0; o < 3; ++o)
  4342. {
  4343. auto& row = rows[(std::size_t) o];
  4344. wire (row.octave, synthparam::oscParam (o, synthparam::octave));
  4345. wire (row.semitones, synthparam::oscParam (o, synthparam::semitones));
  4346. wire (row.detune, synthparam::oscParam (o, synthparam::detune));
  4347. wire (row.pan, synthparam::oscParam (o, synthparam::pan));
  4348. wire (row.level, synthparam::oscParam (o, synthparam::level));
  4349. }
  4350. for (auto [slider, k] : { std::pair { &attack, (int) synthparam::attack }, { &decay, (int) synthparam::decay },
  4351. { &sustain, (int) synthparam::sustain }, { &release, (int) synthparam::release },
  4352. { &cutoff, (int) synthparam::cutoff }, { &resonance, (int) synthparam::resonance },
  4353. { &porta, (int) synthparam::porta }, { &fm, (int) synthparam::fm }, { &fmDecay, (int) synthparam::fmDecay },
  4354. { &keyTrack, (int) synthparam::keyTrack }, { &sweep, (int) synthparam::sweep },
  4355. { &sweepTime, (int) synthparam::sweepTime }, { &bandLow, (int) synthparam::bandLow },
  4356. { &bandMid, (int) synthparam::bandMid }, { &bandHigh, (int) synthparam::bandHigh } })
  4357. wire (*slider, k);
  4358. }
  4359. refresh();
  4360. engine.addChangeListener (this);
  4361. setSize (720, 510);
  4362. if (ref.index >= 0)
  4363. startTimerHz (30); // the knobs follow their automation while the song plays (cheap while nothing moves)
  4364. }
  4365. ~SynthPanel() override
  4366. {
  4367. stopTimer();
  4368. engine.removeChangeListener (this);
  4369. }
  4370. int getChannel() const noexcept { return ref.index; }
  4371. void paint (juce::Graphics& g) override // round 170j: the art's canvas behind the controls
  4372. {
  4373. const skin::StyleScope styleScope (skin::resolve (skin::Style::themed, skin::Art::lynxSynth), skin::Art::lynxSynth);
  4374. skin::canvas (g, getLocalBounds().toFloat(), skin::artAccent (skin::Art::lynxSynth));
  4375. }
  4376. void resized() override
  4377. {
  4378. auto area = getLocalBounds().reduced (10);
  4379. auto topRow = area.removeFromTop (24);
  4380. presetBox.setBounds (topRow.removeFromLeft (200));
  4381. mono.setBounds (topRow.removeFromLeft (90).withTrimmedLeft (16));
  4382. am.setBounds (topRow.removeFromLeft (52));
  4383. ring.setBounds (topRow.removeFromLeft (60));
  4384. flPresets.setBounds (topRow.removeFromLeft (130).reduced (4, 0));
  4385. portaOn.setBounds (topRow.removeFromLeft (70));
  4386. filterTypeBox.setBounds (topRow.removeFromRight (140));
  4387. area.removeFromTop (6);
  4388. auto header = area.removeFromTop (16);
  4389. header.removeFromLeft (150);
  4390. for (int i = 0; i < oscKnobs; ++i)
  4391. labels[(std::size_t) i].setBounds (header.removeFromLeft (88));
  4392. for (auto& row : rows)
  4393. {
  4394. auto line = area.removeFromTop (64);
  4395. row.title.setBounds (line.removeFromLeft (50).withSizeKeepingCentre (50, 24));
  4396. row.wave.setBounds (line.removeFromLeft (100).withSizeKeepingCentre (96, 24));
  4397. for (auto* s : { &row.octave, &row.semitones, &row.detune, &row.pan, &row.level })
  4398. s->setBounds (line.removeFromLeft (88));
  4399. }
  4400. area.removeFromTop (10);
  4401. auto names = area.removeFromTop (16);
  4402. const auto w = area.getWidth() / 9;
  4403. for (int i = oscKnobs; i < oscKnobs + 9; ++i)
  4404. labels[(std::size_t) i].setBounds (names.removeFromLeft (w));
  4405. auto knobsRow = area.removeFromTop (80);
  4406. for (auto* s : { &attack, &decay, &sustain, &release, &cutoff, &resonance, &porta, &fm, &fmDecay })
  4407. s->setBounds (knobsRow.removeFromLeft (w));
  4408. area.removeFromTop (6);
  4409. auto names2 = area.removeFromTop (16);
  4410. for (int i = oscKnobs + 9; i < (int) labels.size(); ++i)
  4411. labels[(std::size_t) i].setBounds (names2.removeFromLeft (w));
  4412. auto knobsRow2 = area.removeFromTop (80);
  4413. for (auto* s : { &keyTrack, &sweep, &sweepTime, &bandLow, &bandMid, &bandHigh })
  4414. s->setBounds (knobsRow2.removeFromLeft (w));
  4415. area.removeFromTop (12);
  4416. modulationButton.setBounds (area.removeFromTop (26).withSizeKeepingCentre (260, 26));
  4417. }
  4418. private:
  4419. struct Row
  4420. {
  4421. juce::Label title;
  4422. juce::ComboBox wave;
  4423. MenuSlider octave, semitones, detune, pan, level;
  4424. };
  4425. static constexpr int oscKnobs = 5; // oscillator knob labels come first
  4426. juce::TextButton modulationButton;
  4427. juce::ToggleButton mono, am, portaOn;
  4428. juce::TextButton flPresets;
  4429. // menu with the presets from the FL install for the synths LYNX converts: the 3x Osc channel .fst
  4430. // files (by letter) and, per generator, the "Plugin presets" folders (Sytrus, Harmor, GMS...)
  4431. void showFlPresets()
  4432. {
  4433. const auto roots = findFlStudioRoots();
  4434. const auto patches = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches");
  4435. auto sorted = [] (juce::Array<juce::File> files) {
  4436. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) {
  4437. return a.getFileName().compareNatural (b.getFileName()) < 0;
  4438. });
  4439. return files;
  4440. };
  4441. juce::PopupMenu menu;
  4442. // 3x Osc: ~170 presets grouped by first letter
  4443. {
  4444. juce::PopupMenu threeOsc, sub;
  4445. juce::juce_wchar letter = 0;
  4446. for (const auto& f : sorted (patches.getChildFile ("Channel presets/3x Osc").findChildFiles (juce::File::findFiles, false, "*.fst")))
  4447. {
  4448. const auto first = juce::CharacterFunctions::toUpperCase (f.getFileName()[0]);
  4449. if (first != letter && sub.getNumItems() > 0)
  4450. {
  4451. threeOsc.addSubMenu (juce::String::charToString (letter), sub);
  4452. sub = {};
  4453. }
  4454. letter = first;
  4455. sub.addItem (f.getFileNameWithoutExtension(), [this, f] { loadFlPreset (f); });
  4456. }
  4457. if (sub.getNumItems() > 0)
  4458. threeOsc.addSubMenu (juce::String::charToString (letter), sub);
  4459. if (threeOsc.getNumItems() > 0)
  4460. menu.addSubMenu ("3x Osc", threeOsc);
  4461. }
  4462. // a preset folder as a menu: subfolders become submenus
  4463. std::function<juce::PopupMenu (const juce::File&, int)> folderMenu = [&] (const juce::File& folder, int depth) {
  4464. juce::PopupMenu m;
  4465. if (depth < 3)
  4466. for (const auto& dir : sorted (folder.findChildFiles (juce::File::findDirectories, false)))
  4467. if (auto sub = folderMenu (dir, depth + 1); sub.getNumItems() > 0)
  4468. m.addSubMenu (dir.getFileName(), sub);
  4469. for (const auto& f : sorted (folder.findChildFiles (juce::File::findFiles, false, "*.fst;*.gmsynth")))
  4470. m.addItem (f.getFileNameWithoutExtension(), [this, f] { loadFlPreset (f); });
  4471. return m;
  4472. };
  4473. const auto generators = patches.getChildFile ("Plugin presets/Generators");
  4474. for (const auto* name : { "Sytrus", "Harmor", "GMS", "Harmless", "MiniSynth", "Fruity DX10", "Fruit Kick", "Ogun", "Sakura", "Kepler", "Kepler Exo",
  4475. "PoiZone", "Toxic Biohazard", "BassDrum" })
  4476. if (auto sub = folderMenu (generators.getChildFile (name), 0); sub.getNumItems() > 0)
  4477. menu.addSubMenu (name, sub);
  4478. if (menu.getNumItems() == 0)
  4479. {
  4480. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("FL presets"),
  4481. tr ("FL presets not found (install FL Studio or check the Data\\Patches folder)."));
  4482. return;
  4483. }
  4484. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&flPresets));
  4485. }
  4486. void loadFlPreset (const juce::File& file)
  4487. {
  4488. juce::MemoryBlock data;
  4489. if (! file.loadFileAsData (data) || current() == nullptr)
  4490. return;
  4491. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  4492. if (auto synth = synthFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize())))
  4493. ref.edit (engine, [s = *synth] (ChannelDef& channelDef) { channelDef.synth = s; });
  4494. else
  4495. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("FL presets"),
  4496. tr ("This preset is not for a synth LYNX SHARE converts, or it could not be read."));
  4497. }
  4498. MenuSlider porta;
  4499. juce::ComboBox filterTypeBox;
  4500. // a knob as the synth parameter k (issue #152)
  4501. AutomationTarget targetOf (int k) const { return { AutomationTargetKind::channelParam, ref.index, 0, synthparam::target (k) }; }
  4502. void wire (MenuSlider& slider, int k)
  4503. {
  4504. ui::setOwnMenu (slider);
  4505. slider.onMenu = [this, &slider, k] { ui::showSliderMenu (slider, &engine, targetOf (k)); };
  4506. slider.onDragStart = [this, k] { engine.noteTweaked (targetOf (k), true); };
  4507. slider.onDragEnd = [this, k] { engine.tweakReleased (targetOf (k)); };
  4508. wired.push_back ({ &slider, k });
  4509. }
  4510. // the knobs an automation drives show its value while the song plays; when it stops they show the Song's again
  4511. void timerCallback() override
  4512. {
  4513. if (isShowing())
  4514. showAutomation (false);
  4515. }
  4516. // `force`: after refresh() put the Song's values back (the automated ones go on the automation's value again)
  4517. void showAutomation (bool force)
  4518. {
  4519. if (wired.empty())
  4520. return;
  4521. const auto& shown = engine.getAutomationDisplay();
  4522. if (! force && shown.getGeneration() == shownGeneration)
  4523. return;
  4524. shownGeneration = shown.getGeneration();
  4525. if (automatedShown.empty() && ! shown.any())
  4526. return;
  4527. const auto* c = current();
  4528. if (c == nullptr)
  4529. return;
  4530. const juce::ScopedValueSetter<bool> guard (updating, true);
  4531. std::vector<juce::Slider*> now;
  4532. for (const auto& [slider, k] : wired)
  4533. {
  4534. if (slider->isMouseButtonDown())
  4535. continue;
  4536. const auto v = shown.valueOf (targetOf (k));
  4537. const auto was = std::find (automatedShown.begin(), automatedShown.end(), slider) != automatedShown.end();
  4538. if (v)
  4539. {
  4540. slider->setValue (synthparam::toNatural (k, *v), juce::dontSendNotification);
  4541. now.push_back (slider);
  4542. }
  4543. else if (was && ! force)
  4544. slider->setValue (synthparam::natural (c->synth, k), juce::dontSendNotification);
  4545. }
  4546. automatedShown = std::move (now);
  4547. }
  4548. std::vector<std::pair<MenuSlider*, int>> wired; // knob -> synth parameter
  4549. std::vector<juce::Slider*> automatedShown;
  4550. std::uint32_t shownGeneration = 0;
  4551. void knob (juce::Slider& s, double lo, double hi, double step, const char* suffix)
  4552. {
  4553. s.setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  4554. s.setTextBoxStyle (juce::Slider::TextBoxBelow, false, 64, 16);
  4555. // round 170j: the plugin kit's knobs in LYNX Synth's own art ("the LYNX lab"), or the forced plugin style
  4556. s.getProperties().set (skin::sliderProperty, (juce::int64) skin::artAccent (skin::Art::lynxSynth).getARGB());
  4557. s.getProperties().set (skin::styleProperty, skin::packStyle (skin::Style::themed, skin::Art::lynxSynth));
  4558. s.setRange (lo, hi, step);
  4559. s.setTextValueSuffix (suffix);
  4560. s.onValueChange = [this] { apply(); };
  4561. addAndMakeVisible (s);
  4562. }
  4563. const ChannelDef* current() const
  4564. {
  4565. return ref.get (engine);
  4566. }
  4567. void refresh()
  4568. {
  4569. const auto* c = current();
  4570. if (c == nullptr)
  4571. return;
  4572. updating = true;
  4573. const auto& s = c->synth;
  4574. for (std::size_t o = 0; o < 3; ++o)
  4575. {
  4576. rows[o].wave.setSelectedId ((int) s.osc[o].wave + 1, juce::dontSendNotification);
  4577. rows[o].octave.setValue (s.osc[o].octave, juce::dontSendNotification);
  4578. rows[o].detune.setValue (s.osc[o].detune, juce::dontSendNotification);
  4579. rows[o].semitones.setValue (s.osc[o].semitones, juce::dontSendNotification);
  4580. rows[o].pan.setValue (s.osc[o].pan, juce::dontSendNotification);
  4581. rows[o].level.setValue (s.osc[o].level, juce::dontSendNotification);
  4582. }
  4583. attack.setValue (s.attack, juce::dontSendNotification);
  4584. decay.setValue (s.decay, juce::dontSendNotification);
  4585. sustain.setValue (s.sustain, juce::dontSendNotification);
  4586. release.setValue (s.release, juce::dontSendNotification);
  4587. cutoff.setValue (s.cutoff, juce::dontSendNotification);
  4588. resonance.setValue (s.resonance, juce::dontSendNotification);
  4589. mono.setToggleState (s.mono, juce::dontSendNotification);
  4590. am.setToggleState (s.am, juce::dontSendNotification);
  4591. porta.setValue (s.portaBeats, juce::dontSendNotification);
  4592. portaOn.setToggleState (s.porta, juce::dontSendNotification);
  4593. filterTypeBox.setSelectedId (s.filterType + 1, juce::dontSendNotification);
  4594. fm.setValue (s.fm, juce::dontSendNotification);
  4595. fmDecay.setValue (s.fmDecay, juce::dontSendNotification);
  4596. keyTrack.setValue (s.keyTrack, juce::dontSendNotification);
  4597. sweep.setValue (s.sweep, juce::dontSendNotification);
  4598. sweepTime.setValue (s.sweepTime, juce::dontSendNotification);
  4599. bandLow.setValue (s.bandGain[0], juce::dontSendNotification);
  4600. bandMid.setValue (s.bandGain[1], juce::dontSendNotification);
  4601. bandHigh.setValue (s.bandGain[2], juce::dontSendNotification);
  4602. ring.setToggleState (s.ring, juce::dontSendNotification);
  4603. updating = false;
  4604. showAutomation (true); // (issue #152: an automated knob keeps showing its automation)
  4605. if (auto* w = findParentComponentOfClass<juce::DocumentWindow>())
  4606. w->setName (tr ("Synth settings - {0}", { juce::String::fromUTF8 (c->name.c_str()) }));
  4607. }
  4608. void apply()
  4609. {
  4610. if (updating || current() == nullptr)
  4611. return;
  4612. auto s = current()->synth; // keeps what this window does not show (envelopes and LFOs)
  4613. for (std::size_t o = 0; o < 3; ++o)
  4614. s.osc[o] = { (Waveform) juce::jlimit (0, 5, rows[o].wave.getSelectedId() - 1), (int) rows[o].octave.getValue(),
  4615. (float) rows[o].detune.getValue(), (float) rows[o].level.getValue(), (int) rows[o].semitones.getValue(),
  4616. (float) rows[o].pan.getValue() };
  4617. s.attack = (float) attack.getValue();
  4618. s.decay = (float) decay.getValue();
  4619. s.sustain = (float) sustain.getValue();
  4620. s.release = (float) release.getValue();
  4621. s.cutoff = (float) cutoff.getValue();
  4622. s.resonance = (float) resonance.getValue();
  4623. s.mono = mono.getToggleState();
  4624. s.am = am.getToggleState();
  4625. s.portaBeats = (float) porta.getValue();
  4626. s.porta = portaOn.getToggleState();
  4627. s.filterType = juce::jlimit (0, 3, filterTypeBox.getSelectedId() - 1);
  4628. s.fm = (float) fm.getValue();
  4629. s.fmDecay = (float) fmDecay.getValue();
  4630. if (s.fmDecay <= 0.0f)
  4631. s.fmSustain = 1.0f;
  4632. s.keyTrack = (float) keyTrack.getValue();
  4633. s.sweep = (float) sweep.getValue();
  4634. s.sweepTime = (float) sweepTime.getValue();
  4635. s.bandGain = { (float) bandLow.getValue(), (float) bandMid.getValue(), (float) bandHigh.getValue() };
  4636. s.ring = ring.getToggleState();
  4637. if (s == current()->synth)
  4638. return;
  4639. ref.edit (engine, [s] (ChannelDef& channelDef) { channelDef.synth = s; });
  4640. }
  4641. void changeListenerCallback (juce::ChangeBroadcaster*) override
  4642. {
  4643. if (current() == nullptr)
  4644. {
  4645. if (auto* w = findParentComponentOfClass<juce::DocumentWindow>())
  4646. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<juce::DocumentWindow> (w)] {
  4647. if (safe != nullptr)
  4648. safe->closeButtonPressed();
  4649. });
  4650. return;
  4651. }
  4652. refresh();
  4653. }
  4654. AudioEngine& engine;
  4655. ChannelRef ref;
  4656. bool updating = false;
  4657. std::array<Row, 3> rows;
  4658. MenuSlider attack, decay, sustain, release, cutoff, resonance, fm, fmDecay, keyTrack, sweep, sweepTime, bandLow, bandMid, bandHigh;
  4659. juce::ToggleButton ring;
  4660. std::array<juce::Label, 20> labels;
  4661. // round 190fs: the box lists LYNX's synth presets, then the user's own ("Your presets") and the preset items of
  4662. // LYNX's other preset menus (Save preset..., Delete preset, Show the presets folder)
  4663. struct PresetBox final : public juce::ComboBox
  4664. {
  4665. std::function<void()> beforePopup;
  4666. void showPopup() override
  4667. {
  4668. if (beforePopup)
  4669. beforePopup();
  4670. juce::ComboBox::showPopup();
  4671. }
  4672. };
  4673. static constexpr int userPresetId = 1001, savePresetId = 3001, deletePresetId = 3002, showFolderId = 3003;
  4674. PresetBox presetBox;
  4675. juce::Array<juce::File> userFiles;
  4676. juce::File lastUserPreset; // the user's preset loaded or saved last (Delete preset)
  4677. void fillPresetBox()
  4678. {
  4679. presetBox.clear (juce::dontSendNotification);
  4680. const auto presets = synthPresets();
  4681. for (int i = 0; i < (int) presets.size(); ++i)
  4682. presetBox.addItem (juce::String::fromUTF8 (presets[(std::size_t) i].first.c_str()), i + 1);
  4683. userFiles = genpresetui::userPresets (InstrumentKind::synth);
  4684. if (! userFiles.isEmpty())
  4685. {
  4686. presetBox.addSectionHeading (tr ("Your presets"));
  4687. for (int i = 0; i < userFiles.size(); ++i)
  4688. presetBox.addItem (userFiles[i].getFileNameWithoutExtension(), userPresetId + i);
  4689. }
  4690. presetBox.addSeparator();
  4691. presetBox.addItem (tr ("Save preset..."), savePresetId);
  4692. if (lastUserPreset.existsAsFile())
  4693. presetBox.addItem (tr ("Delete preset \"{0}\"", { lastUserPreset.getFileNameWithoutExtension() }), deletePresetId);
  4694. presetBox.addItem (tr ("Show the presets folder"), showFolderId);
  4695. }
  4696. void loadUserPreset (const juce::File& file)
  4697. {
  4698. const auto preset = genpresetui::read (file);
  4699. const auto* d = current();
  4700. if (! preset || d == nullptr)
  4701. return;
  4702. if (auto changed = genpresets::withPreset (*d, *preset))
  4703. {
  4704. ref.edit (engine, [c = std::move (*changed)] (ChannelDef& channelDef) {
  4705. if (channelDef.instrument == c.instrument)
  4706. channelDef = c;
  4707. });
  4708. lastUserPreset = file;
  4709. }
  4710. else
  4711. ui::postHint ({ tr ("This preset is for {0}.", { juce::String::fromUTF8 (genpresets::engineName (preset->kind).c_str()) }), {} }, 2500);
  4712. }
  4713. void saveUserPreset()
  4714. {
  4715. const auto* d = current();
  4716. if (d == nullptr)
  4717. return;
  4718. genpresetui::askName (*this, juce::String::fromUTF8 (d->name.c_str()), [safe = juce::Component::SafePointer<SynthPanel> (this)] (const juce::String& name) {
  4719. if (safe != nullptr)
  4720. safe->saveNamed (name);
  4721. });
  4722. }
  4723. public:
  4724. bool saveNamed (const juce::String& name)
  4725. {
  4726. const auto* now = current();
  4727. if (now == nullptr)
  4728. return false;
  4729. juce::File written;
  4730. juce::String error;
  4731. if (! genpresetui::save (*now, name, written, error))
  4732. {
  4733. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Save preset"), error);
  4734. return false;
  4735. }
  4736. lastUserPreset = written;
  4737. return true;
  4738. }
  4739. // the box's list as it opens (shots)
  4740. juce::PopupMenu presetBoxMenu()
  4741. {
  4742. fillPresetBox();
  4743. return *presetBox.getRootMenu();
  4744. }
  4745. private:
  4746. };
  4747. // --- FL's channel window frame (REA round 143b) --------------------------------------------------------------
  4748. // FL 2026 draws every channel's settings window the same way: a header strip with the channel's tabs on the left
  4749. // (the instrument / plugin page, the wrench "Miscellaneous functions" page) and ON, PAN, VOL and TRACK on the right
  4750. // [EXEC: FL 2026 build 5654, "Detailed settings" of a generator and of a sampler]. LYNX does the same around its own
  4751. // instrument pages, in its own style; the envelopes and LFOs of the synth and the sampler are the "Envelope /
  4752. // instrument" tab instead of a second window.
  4753. // A small rotary control with LYNX's control contract (drag, Ctrl = fine, wheel, Alt / middle-click / double-click
  4754. // reset, right-click menu with automation items when the spec has a target); the hint bar shows its name and value.
  4755. class FrameKnob final : public juce::Component,
  4756. public ui::HintSource,
  4757. private juce::Timer
  4758. {
  4759. public:
  4760. FrameKnob (AudioEngine& e, std::function<ui::ValueSpec()> makeSpec, std::function<double()> get, std::function<void (double)> set,
  4761. juce::String caption)
  4762. : engine (e), specOf (std::move (makeSpec)), getter (std::move (get)), setter (std::move (set)), label (std::move (caption))
  4763. {
  4764. setRepaintsOnMouseActivity (true);
  4765. if (specOf().target)
  4766. startTimerHz (30); // follows its automation while the song plays (issue #12)
  4767. }
  4768. // the value drawn: the automation's while the song plays (pan / volume: the targets these knobs have), else the Song's
  4769. double shownValue (const ui::ValueSpec& spec) const
  4770. {
  4771. if (spec.target && ! isMouseButtonDown())
  4772. if (const auto v = engine.getAutomationDisplay().valueOf (*spec.target))
  4773. return spec.target->kind == AutomationTargetKind::channelPan || spec.target->kind == AutomationTargetKind::mixerPan
  4774. ? (double) *v * 2.0 - 1.0
  4775. // the Levels adjustment (round 190dz): automation's 0..1 over the knob's own range
  4776. : spec.target->kind == AutomationTargetKind::channelAdjust ? spec.minimum + (double) *v * (spec.maximum - spec.minimum)
  4777. : (double) *v;
  4778. return getter();
  4779. }
  4780. void timerCallback() override
  4781. {
  4782. if (! isShowing())
  4783. return;
  4784. if (const auto generation = engine.getAutomationDisplay().getGeneration(); generation != shownGeneration)
  4785. {
  4786. shownGeneration = generation;
  4787. repaint();
  4788. }
  4789. }
  4790. std::uint32_t shownGeneration = 0;
  4791. ui::Hint hintAt (juce::Point<int>) override
  4792. {
  4793. return ui::valueHint (specOf(), getter(), doubleClicked ? tr ("[LMB] drag or [Wheel] changes [2xLMB] show in the Mixer [RMB] menu")
  4794. : ui::valueGestures());
  4795. }
  4796. // FL's number wheel (round 168s, issue #32): the value in a box over the caption instead of a knob; the whole
  4797. // control is the hit area, a notch / 7.5 px of drag = one step (ui::digitWheel). Double-click: `doubleClicked`.
  4798. bool digitBox = false;
  4799. std::function<void()> doubleClicked;
  4800. std::function<void (juce::PopupMenu&)> extraMenuItems;
  4801. // Round 190in (design190ia FW-3 / FW-4): FL's header look — a 30 px knob with no value line (the value shows in the
  4802. // hint bar and the drag tip), a bold caption under it; a number wheel as FL's red digit badge (`joinLeft`: RANGE,
  4803. // attached to the PITCH knob at its left). `restArc`: the arc's colour at rest (VOL: FL's green ring).
  4804. bool headerLook = false, joinLeft = false;
  4805. juce::Colour restArc;
  4806. static constexpr float headerKnob = 30.0f, headerCaptionTop = 34.0f;
  4807. juce::Rectangle<float> badgeArea() const
  4808. {
  4809. const auto b = getLocalBounds().toFloat();
  4810. const auto w = joinLeft ? 28.0f : 40.0f;
  4811. return { joinLeft ? 0.0f : b.getCentreX() - w * 0.5f, 5.0f, w, 26.0f };
  4812. }
  4813. void paintHeaderLook (juce::Graphics& g, const ui::ValueSpec& spec)
  4814. {
  4815. using namespace theme;
  4816. const auto b = getLocalBounds().toFloat();
  4817. const auto hot = isMouseOverOrDragging() || drag.isActive();
  4818. auto caption = juce::Rectangle<float> (b.getX(), headerCaptionTop, b.getWidth(), 10.0f);
  4819. if (digitBox)
  4820. {
  4821. const auto badge = badgeArea();
  4822. juce::Path p;
  4823. p.addRoundedRectangle (badge.getX(), badge.getY(), badge.getWidth(), badge.getHeight(), 4.0f, 4.0f, ! joinLeft, true, ! joinLeft, true);
  4824. g.setColour (hot ? juce::Colour (0xff6e252b) : colour::accentMuted);
  4825. g.fillPath (p);
  4826. g.setColour (drag.isActive() ? colour::accent : juce::Colour (0xff8a2d33));
  4827. g.strokePath (p, juce::PathStrokeType (1.0f));
  4828. // FL's ‹ › marks at the badge's right edge (the wheel)
  4829. g.setColour (colour::textSecondary.withAlpha (0.8f));
  4830. const auto mx = badge.getRight() - 5.0f, my = badge.getCentreY();
  4831. for (const auto dy : { -4.0f, 4.0f })
  4832. {
  4833. juce::Path m;
  4834. m.startNewSubPath (mx - 1.5f, my + dy - 2.0f);
  4835. m.lineTo (mx + 1.0f, my + dy);
  4836. m.lineTo (mx - 1.5f, my + dy + 2.0f);
  4837. g.strokePath (m, juce::PathStrokeType (1.0f));
  4838. }
  4839. g.setColour (colour::textPrimary);
  4840. g.setFont (font (18.0f, true));
  4841. g.drawFittedText (spec.text (getter()), badge.withTrimmedRight (9.0f).reduced (2.0f, 0.0f).toNearestInt(), juce::Justification::centredRight, 1, 0.6f);
  4842. if (joinLeft)
  4843. caption = caption.withX (badge.getX()).withWidth (badge.getWidth());
  4844. }
  4845. else
  4846. {
  4847. const auto shown = shownValue (spec);
  4848. const auto v = (float) juce::jlimit (0.0, 1.0, (shown - spec.minimum) / juce::jmax (1e-9, spec.maximum - spec.minimum));
  4849. const auto knob = juce::Rectangle<float> (headerKnob, headerKnob).withCentre ({ b.getCentreX(), 3.0f + headerKnob * 0.5f });
  4850. drawKnob (g, knob, v, spec.minimum < 0.0, hot ? colour::accent : restArc.isTransparent() ? colour::knobArc : restArc, isMouseOver());
  4851. }
  4852. // (FL's RANGE caption is the dim one of the strip)
  4853. g.setColour (hot ? colour::textPrimary : joinLeft ? colour::textDisabled : colour::textSecondary);
  4854. g.setFont (font (type::caption, true));
  4855. g.drawFittedText (caps (label), caption.toNearestInt(), juce::Justification::centred, 1, 0.6f);
  4856. }
  4857. void paint (juce::Graphics& g) override
  4858. {
  4859. const auto spec = specOf();
  4860. if (headerLook)
  4861. {
  4862. paintHeaderLook (g, spec);
  4863. return;
  4864. }
  4865. auto area = getLocalBounds().toFloat();
  4866. const auto caption = area.removeFromBottom (13.0f);
  4867. if (digitBox)
  4868. {
  4869. // FL's digiwheel (c_f14): a display about 22 px high, the value right-aligned before up / down marks; here dark,
  4870. // red only while touched
  4871. const auto box = area.withSizeKeepingCentre (juce::jmin (area.getWidth() - 2.0f, 48.0f), juce::jmin (22.0f, area.getHeight() - 4.0f));
  4872. g.setColour (theme::drawDigitDisplay (g, box, isMouseOverOrDragging() || drag.isActive(), false, true));
  4873. g.setFont (theme::font (13.0f, true));
  4874. g.drawFittedText (spec.text (getter()), box.withTrimmedRight (theme::digitMarksWidth).reduced (3.0f, 0.0f).toNearestInt(),
  4875. juce::Justification::centredRight, 1, 0.6f);
  4876. g.setColour (theme::colour::textSecondary);
  4877. g.setFont (theme::font (theme::type::caption));
  4878. g.drawFittedText (theme::caps (label), caption.toNearestInt(), juce::Justification::centred, 1, 0.65f);
  4879. return;
  4880. }
  4881. const auto valueArea = area.removeFromBottom (13.0f);
  4882. const auto size = juce::jmin (area.getWidth(), area.getHeight());
  4883. const auto shown = shownValue (spec);
  4884. const auto v = (float) juce::jlimit (0.0, 1.0, (shown - spec.minimum) / juce::jmax (1e-9, spec.maximum - spec.minimum));
  4885. theme::drawKnob (g, juce::Rectangle<float> (size, size).withCentre (area.getCentre()), v, spec.minimum < 0.0,
  4886. isMouseOverOrDragging() ? theme::colour::accent : theme::colour::knobArc, isMouseOver());
  4887. g.setFont (theme::font (theme::type::caption));
  4888. g.setColour (theme::colour::textPrimary);
  4889. // squeezed (down to 65 %) before an ellipsis: translated captions are often longer (round 165o)
  4890. g.drawFittedText (spec.text (shown), valueArea.toNearestInt(), juce::Justification::centred, 1, 0.65f);
  4891. g.setColour (theme::colour::textSecondary);
  4892. g.drawFittedText (theme::caps (label), caption.toNearestInt(), juce::Justification::centred, 1, 0.65f);
  4893. }
  4894. void mouseDown (const juce::MouseEvent& e) override
  4895. {
  4896. if (e.mods.isPopupMenu())
  4897. {
  4898. if (! extraMenuItems)
  4899. {
  4900. ui::showValueMenu (*this, &engine, specOf(), getter(), setter);
  4901. return;
  4902. }
  4903. const auto spec = specOf();
  4904. juce::PopupMenu menu;
  4905. menu.addSectionHeader (spec.name + ": " + spec.text (getter()));
  4906. ui::addValueItems (menu, *this, &engine, spec, getter(), setter);
  4907. menu.addSeparator();
  4908. extraMenuItems (menu);
  4909. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  4910. return;
  4911. }
  4912. if (ui::isResetClick (e))
  4913. {
  4914. setter (specOf().defaultValue);
  4915. repaint();
  4916. return;
  4917. }
  4918. drag.begin (e, getter());
  4919. }
  4920. void mouseDrag (const juce::MouseEvent& e) override
  4921. {
  4922. if (! drag.isActive())
  4923. return;
  4924. const auto spec = specOf();
  4925. setter (drag.update (e, spec));
  4926. ui::showValueTip (*this, getLocalBounds(), spec.text (getter()));
  4927. repaint();
  4928. }
  4929. void mouseUp (const juce::MouseEvent&) override
  4930. {
  4931. drag.end();
  4932. ui::hideValueTip();
  4933. }
  4934. void mouseDoubleClick (const juce::MouseEvent&) override
  4935. {
  4936. if (doubleClicked)
  4937. {
  4938. doubleClicked();
  4939. return;
  4940. }
  4941. setter (specOf().defaultValue);
  4942. repaint();
  4943. }
  4944. void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel) override
  4945. {
  4946. if (const auto v = ui::wheelValue (getter(), e, wheel, specOf()))
  4947. {
  4948. setter (*v);
  4949. ui::flashValueTip (*this, getLocalBounds(), specOf().text (getter()));
  4950. repaint();
  4951. }
  4952. }
  4953. private:
  4954. AudioEngine& engine;
  4955. std::function<ui::ValueSpec()> specOf;
  4956. std::function<double()> getter;
  4957. std::function<void (double)> setter;
  4958. juce::String label;
  4959. ui::ValueDrag drag;
  4960. };
  4961. juce::String channelNameOf (const Song& song, int channel)
  4962. {
  4963. if (channel < 0 || channel >= (int) song.channels.size())
  4964. return "?";
  4965. const auto& n = song.channels[(std::size_t) channel].name;
  4966. return n.empty() ? tr ("Channel {0}", { juce::String (channel + 1) }) : juce::String::fromUTF8 (n.c_str());
  4967. }
  4968. // An integer spec shown as a number, 0 as "--" (FL's empty number boxes).
  4969. ui::ValueSpec countSpec (const juce::String& name, int maximum, int defaultValue, std::function<juce::String (int)> text = {})
  4970. {
  4971. ui::ValueSpec spec;
  4972. spec.name = name;
  4973. spec.maximum = maximum;
  4974. spec.defaultValue = defaultValue;
  4975. spec.interval = 1.0;
  4976. spec.pixelsForRange = juce::jlimit (60.0, 400.0, 5.0 * maximum);
  4977. spec.toText = [text] (double v) {
  4978. const auto i = juce::roundToInt (v);
  4979. if (text)
  4980. return text (i);
  4981. return i == 0 ? juce::String ("--") : juce::String (i);
  4982. };
  4983. spec.fromText = [] (const juce::String& t) -> std::optional<double> {
  4984. const auto digits = t.retainCharacters ("0123456789");
  4985. return digits.isEmpty() ? std::optional<double> (0.0) : std::optional<double> (digits.getDoubleValue());
  4986. };
  4987. return spec;
  4988. }
  4989. // The wrench tab: FL's "Miscellaneous functions" with what LYNX's channels have (Levels, Polyphony, Time, Group,
  4990. // Arpeggiator).
  4991. // FL's Root note keyboard (Misc tab, REA round 149): every key 0…127 (C0…G10, C5 = 60), the channel's root marked;
  4992. // a click sets it. LYNX's own drawing.
  4993. class RootKeyboard final : public juce::Component, public juce::SettableTooltipClient
  4994. {
  4995. public:
  4996. std::function<void (int)> onPick;
  4997. // FL's key region ruler (round 164): a drag on the strip above the keys sets the notes the channel plays,
  4998. // a double-click there gives it the whole keyboard back
  4999. std::function<void (int, int)> onRegion;
  5000. void setRoot (int key)
  5001. {
  5002. root = key;
  5003. repaint();
  5004. }
  5005. void setRegion (int low, int high)
  5006. {
  5007. if (low != regionLow || high != regionHigh)
  5008. {
  5009. regionLow = low;
  5010. regionHigh = high;
  5011. repaint();
  5012. }
  5013. }
  5014. void paint (juce::Graphics& g) override
  5015. {
  5016. using namespace theme;
  5017. const auto w = whiteWidth();
  5018. const auto top = (float) rulerHeight();
  5019. const auto keysH = (float) getHeight() - top;
  5020. if (onRegion)
  5021. {
  5022. const auto ruler = juce::Rectangle<float> (0.0f, 0.0f, (float) getWidth(), top - 2.0f);
  5023. g.setColour (colour::bg0);
  5024. g.fillRect (ruler);
  5025. const auto full = regionLow <= 0 && regionHigh >= 127;
  5026. const auto x0 = keyLeft (regionLow), x1 = keyRight (regionHigh);
  5027. g.setColour (full ? colour::bg5 : colour::accent);
  5028. g.fillRect (juce::Rectangle<float> (x0, 1.0f, juce::jmax (2.0f, x1 - x0), ruler.getHeight() - 2.0f));
  5029. }
  5030. for (int k = 0, white = 0; k < 128; ++k)
  5031. if (! isBlack (k))
  5032. {
  5033. const auto r = juce::Rectangle<float> ((float) (white++) * w, top, w - 1.0f, keysH);
  5034. const auto outside = onRegion && (k < regionLow || k > regionHigh);
  5035. g.setColour (k == root ? colour::accent : k == hover ? juce::Colour (0xffc8ccd4) : outside ? juce::Colour (0xff9a9ea8) : juce::Colour (0xffe6e8ec));
  5036. g.fillRect (r);
  5037. if (k % 12 == 0 && w * 7.0f >= 14.0f) // the octave's C named (FL's C5 = 60)
  5038. {
  5039. g.setColour (k == root ? colour::onAccent : juce::Colour (0xff5a5f6a));
  5040. g.setFont (font (8.5f));
  5041. g.drawText ("C" + juce::String (k / 12), r.withTrimmedTop (r.getHeight() - 11.0f).expanded (6.0f, 0.0f).toNearestInt(),
  5042. juce::Justification::centred);
  5043. }
  5044. }
  5045. for (int k = 0; k < 128; ++k)
  5046. if (isBlack (k))
  5047. {
  5048. const auto x = (float) whitesBefore (k) * w - w * 0.32f;
  5049. g.setColour (k == root ? colour::accent : k == hover ? colour::bg5 : colour::bg0);
  5050. g.fillRect (juce::Rectangle<float> (x, top, w * 0.64f, keysH * 0.6f));
  5051. }
  5052. }
  5053. void mouseMove (const juce::MouseEvent& e) override
  5054. {
  5055. const auto onRuler = onRegion && e.position.y < (float) rulerHeight();
  5056. if (const auto k = keyAt (e.position); k != hover || onRuler != hoverRuler)
  5057. {
  5058. hover = k;
  5059. hoverRuler = onRuler;
  5060. if (onRuler)
  5061. setTooltip (tr ("Key region: {0} to {1} (drag to set, double-click for the whole keyboard)",
  5062. { keyName (regionLow), keyName (regionHigh) }));
  5063. else
  5064. setTooltip (k >= 0 ? tr ("Root note: {0}", { keyName (k) }) : juce::String());
  5065. repaint();
  5066. }
  5067. }
  5068. void mouseExit (const juce::MouseEvent&) override
  5069. {
  5070. hover = -1;
  5071. repaint();
  5072. }
  5073. void mouseDown (const juce::MouseEvent& e) override
  5074. {
  5075. dragFrom = -1;
  5076. if (onRegion && e.position.y < (float) rulerHeight())
  5077. {
  5078. dragFrom = keyAtX (e.position.x);
  5079. if (dragFrom >= 0)
  5080. onRegion (dragFrom, dragFrom);
  5081. return;
  5082. }
  5083. if (const auto k = keyAt (e.position); k >= 0 && onPick)
  5084. onPick (k);
  5085. }
  5086. void mouseDrag (const juce::MouseEvent& e) override
  5087. {
  5088. if (dragFrom < 0 || ! onRegion)
  5089. return;
  5090. const auto k = keyAtX (e.position.x);
  5091. if (k >= 0)
  5092. onRegion (juce::jmin (dragFrom, k), juce::jmax (dragFrom, k));
  5093. }
  5094. void mouseDoubleClick (const juce::MouseEvent& e) override
  5095. {
  5096. if (onRegion && e.position.y < (float) rulerHeight())
  5097. onRegion (0, 127);
  5098. }
  5099. static juce::String keyName (int key)
  5100. {
  5101. return juce::String (notenames::keyName (key)); // Settings › General › Note names (round 165f)
  5102. }
  5103. private:
  5104. static bool isBlack (int k) noexcept
  5105. {
  5106. const auto n = k % 12;
  5107. return n == 1 || n == 3 || n == 6 || n == 8 || n == 10;
  5108. }
  5109. static int whitesBefore (int k) noexcept
  5110. {
  5111. int count = 0;
  5112. for (int i = 0; i < k; ++i)
  5113. count += isBlack (i) ? 0 : 1;
  5114. return count;
  5115. }
  5116. int rulerHeight() const noexcept { return onRegion ? 9 : 0; }
  5117. float whiteWidth() const noexcept { return (float) getWidth() / 75.0f; } // 75 white keys in 0…127
  5118. float keyLeft (int k) const noexcept
  5119. {
  5120. const auto w = whiteWidth();
  5121. return isBlack (k) ? (float) whitesBefore (k) * w - w * 0.32f : (float) whitesBefore (k) * w;
  5122. }
  5123. float keyRight (int k) const noexcept
  5124. {
  5125. const auto w = whiteWidth();
  5126. return isBlack (k) ? keyLeft (k) + w * 0.64f : keyLeft (k) + w;
  5127. }
  5128. // the key under x on the ruler (each key owns its own horizontal span; black keys win where they overlap)
  5129. int keyAtX (float x) const noexcept
  5130. {
  5131. for (int k = 0; k < 128; ++k)
  5132. if (isBlack (k) && x >= keyLeft (k) && x < keyRight (k))
  5133. return k;
  5134. const auto white = (int) std::floor (x / whiteWidth());
  5135. for (int k = 0, n = 0; k < 128; ++k)
  5136. if (! isBlack (k) && n++ == white)
  5137. return k;
  5138. return x < 0.0f ? 0 : 127;
  5139. }
  5140. int keyAt (juce::Point<float> p) const noexcept
  5141. {
  5142. const auto w = whiteWidth();
  5143. const auto top = (float) rulerHeight();
  5144. if (p.y < top)
  5145. return keyAtX (p.x);
  5146. if (p.y < top + ((float) getHeight() - top) * 0.6f)
  5147. for (int k = 0; k < 128; ++k)
  5148. if (isBlack (k))
  5149. {
  5150. const auto x = (float) whitesBefore (k) * w - w * 0.32f;
  5151. if (p.x >= x && p.x < x + w * 0.64f)
  5152. return k;
  5153. }
  5154. const auto white = (int) std::floor (p.x / w);
  5155. for (int k = 0, n = 0; k < 128; ++k)
  5156. if (! isBlack (k) && n++ == white)
  5157. return k;
  5158. return -1;
  5159. }
  5160. int root = 60, hover = -1, dragFrom = -1;
  5161. int regionLow = 0, regionHigh = 127;
  5162. bool hoverRuler = false;
  5163. };
  5164. class MiscPanel final : public juce::Component,
  5165. private juce::ChangeListener
  5166. {
  5167. public:
  5168. static constexpr int preferredWidth = 800, preferredHeight = 360;
  5169. MiscPanel (AudioEngine& e, int c) : engine (e), channel (c)
  5170. {
  5171. const auto name = [this] { return channelNameOf (engine.getSong(), channel); };
  5172. auto knob = [this] (std::function<ui::ValueSpec()> spec, std::function<double (const ChannelDef&)> get,
  5173. std::function<void (ChannelDef&, double)> set, const char* caption) {
  5174. auto k = std::make_unique<FrameKnob> (
  5175. engine, std::move (spec), [this, get] { return current() != nullptr ? get (*current()) : 0.0; },
  5176. [this, set] (double v) {
  5177. if (current() == nullptr)
  5178. return;
  5179. engine.editSong ([ch = channel, set, v] (Song& s) {
  5180. if (ch < (int) s.channels.size())
  5181. set (s.channels[(std::size_t) ch], v);
  5182. });
  5183. },
  5184. tr (caption));
  5185. addAndMakeVisible (*k);
  5186. knobs.push_back (std::move (k));
  5187. return knobs.back().get();
  5188. };
  5189. // FL's "Levels adjustment" (round 190dz; TPluginForm OfsLevelsPanel, channel parameters 0x10 / 0x11): the offsets on
  5190. // top of the channel's own Pan / Volume (those stay on the header), which Automate on an audio clip moves
  5191. pan = knob ([this, name] {
  5192. auto s = ui::panSpec (name() + " - " + tr ("Panning offset"));
  5193. s.target = AutomationTarget { AutomationTargetKind::channelAdjust, channel, 0, leveladjust::pan };
  5194. return s;
  5195. },
  5196. [] (const ChannelDef& d) { return (double) d.misc.levels.pan; }, [] (ChannelDef& d, double v) { d.misc.levels.pan = (float) v; },
  5197. TR_NOOP ("Pan"));
  5198. volume = knob ([this, name] {
  5199. auto s = ui::percentSpec (name() + " - " + tr ("Volume multiplier"), 1.0);
  5200. s.maximum = 2.0; // FL: 0…25600, 12800 = 100 % (FL's volume curve, up to +21.6 dB)
  5201. s.toText = [] (double v) { return juce::String (levelVolumeText ((float) v)); }; // (live check 190ew PL-6)
  5202. s.target = AutomationTarget { AutomationTargetKind::channelAdjust, channel, 0, leveladjust::volume };
  5203. return s;
  5204. },
  5205. [] (const ChannelDef& d) { return (double) d.misc.levels.volume; },
  5206. [] (ChannelDef& d, double v) { d.misc.levels.volume = (float) v; }, TR_NOOP ("Vol"));
  5207. // Polyphony
  5208. maxPoly = knob ([name] { return countSpec (name() + " - " + tr ("Maximum polyphony (-- = no limit)"), 64, 0); },
  5209. [] (const ChannelDef& d) { return (double) d.maxPolyphony; },
  5210. [] (ChannelDef& d, double v) { d.maxPolyphony = juce::jlimit (0, 64, juce::roundToInt (v)); }, TR_NOOP ("Max"));
  5211. slide = knob (
  5212. [name] {
  5213. ui::ValueSpec s;
  5214. s.name = name() + " - " + tr ("Portamento time");
  5215. s.maximum = 2.0;
  5216. s.defaultValue = 0.125;
  5217. s.toText = [] (double v) { return tr ("{0} beats", { juce::String (v, 3) }); };
  5218. s.fromText = [] (const juce::String& t) -> std::optional<double> { return t.retainCharacters ("0123456789.,").replaceCharacter (',', '.').getDoubleValue(); };
  5219. return s;
  5220. },
  5221. [] (const ChannelDef& d) { return (double) channelPortamentoBeats (d); },
  5222. [] (ChannelDef& d, double v) { setChannelPortamento (d, channelPortamento (d), (float) v); }, TR_NOOP ("Slide"));
  5223. porta.setButtonText (tr ("Porta"));
  5224. porta.setTooltip (tr ("Portamento: each note glides from the previous one's pitch (the Slide knob sets the time)"));
  5225. porta.onClick = [this] { edit ([on = porta.getToggleState()] (ChannelDef& d) { setChannelPortamento (d, on, channelPortamentoBeats (d)); }); };
  5226. mono.setButtonText (tr ("Mono"));
  5227. mono.setTooltip (tr ("Mono: one voice; a note played over a held one glides to it (Slide time) without a new attack"));
  5228. mono.onClick = [this] { edit ([on = mono.getToggleState()] (ChannelDef& d) { setChannelMono (d, on); }); };
  5229. // Time
  5230. swing = knob ([name] { return ui::percentSpec (name() + " - " + tr ("Swing mix"), 1.0); },
  5231. [] (const ChannelDef& d) { return (double) d.swingMix; }, [] (ChannelDef& d, double v) { d.swingMix = (float) v; },
  5232. TR_NOOP ("Swing"));
  5233. // Levels adjustment: Mod X / Mod Y offsets (FL 0x13 / 0x14, ±256) on the channel filter's cutoff / resonance knobs'
  5234. // travel (sampler, synth); the knobs themselves are on the Sampler / Synth pages
  5235. auto offsetSpec = [name] (const char* what) {
  5236. ui::ValueSpec s;
  5237. s.name = name() + " - " + tr (what);
  5238. s.minimum = -1.0;
  5239. s.maximum = 1.0;
  5240. s.defaultValue = 0.0;
  5241. s.toText = [] (double v) { return juce::String (juce::roundToInt (v * 100.0)) + "%"; };
  5242. s.fromText = [] (const juce::String& t) -> std::optional<double> {
  5243. const auto digits = t.retainCharacters ("-0123456789.,").replaceCharacter (',', '.');
  5244. if (digits.isEmpty())
  5245. return std::nullopt;
  5246. return digits.getDoubleValue() / 100.0;
  5247. };
  5248. return s;
  5249. };
  5250. modX = knob ([offsetSpec] { return offsetSpec (TR_NOOP ("Modulation X offset")); },
  5251. [] (const ChannelDef& d) { return (double) d.misc.levels.modX; }, [] (ChannelDef& d, double v) { d.misc.levels.modX = (float) v; },
  5252. TR_NOOP ("Mod X"));
  5253. modY = knob ([offsetSpec] { return offsetSpec (TR_NOOP ("Modulation Y offset")); },
  5254. [] (const ChannelDef& d) { return (double) d.misc.levels.modY; }, [] (ChannelDef& d, double v) { d.misc.levels.modY = (float) v; },
  5255. TR_NOOP ("Mod Y"));
  5256. // Time: Gate and Shift on FL's time-knob scale (REA round 146b)
  5257. auto timeSpec = [name] (const char* what, int maximum, int defaultValue, bool offAtMax) {
  5258. ui::ValueSpec s;
  5259. s.name = name() + " - " + tr (what);
  5260. s.maximum = maximum;
  5261. s.defaultValue = defaultValue;
  5262. s.interval = 1.0;
  5263. s.pixelsForRange = 300.0;
  5264. s.toText = [maximum, offAtMax] (double v) {
  5265. const auto i = juce::roundToInt (v);
  5266. if (offAtMax && i >= maximum)
  5267. return tr ("Off");
  5268. // steps:ticks, as FL shows them (24 ticks per step)
  5269. const auto ticks = juce::roundToInt (channelmisc::flTimeKnobBeats (i) * 96.0);
  5270. return juce::String (ticks / 24) + ":" + juce::String (ticks % 24).paddedLeft ('0', 2);
  5271. };
  5272. return s;
  5273. };
  5274. timeGate = knob ([timeSpec] { return timeSpec (TR_NOOP ("Gate: long notes are cut to this length (Off = no limit)"), 1446, 1446, true); },
  5275. [] (const ChannelDef& d) { return d.misc.gateBeats > 0.0f ? (double) channelmisc::flTimeKnobValue (d.misc.gateBeats) : 1446.0; },
  5276. [] (ChannelDef& d, double v) {
  5277. const auto i = juce::roundToInt (v);
  5278. d.misc.gateBeats = i >= 1446 ? 0.0f : (float) std::max (1.0 / 96.0, channelmisc::flTimeKnobBeats (i));
  5279. },
  5280. TR_NOOP ("Gate"));
  5281. timeShift = knob ([timeSpec] { return timeSpec (TR_NOOP ("Fine time shift: delays the notes, up to one step"), 1024, 0, false); },
  5282. [] (const ChannelDef& d) { return (double) channelmisc::flTimeKnobValue (d.misc.shiftBeats); },
  5283. [] (ChannelDef& d, double v) { d.misc.shiftBeats = (float) channelmisc::flTimeKnobBeats (juce::roundToInt (v)); },
  5284. TR_NOOP ("Shift"));
  5285. fullPorta.setButtonText (tr ("Full porta"));
  5286. fullPorta.setTooltip (tr ("Full porta: portamento notes ignore the Gate and play their whole length"));
  5287. fullPorta.onClick = [this] { edit ([on = fullPorta.getToggleState()] (ChannelDef& d) { d.misc.fullPorta = on; }); };
  5288. // Vol / Key tracking
  5289. trackVol.setButtonText (tr ("Vol"));
  5290. trackKey.setButtonText (trc ("@key tracking: Key"));
  5291. for (auto* b : { &trackVol, &trackKey })
  5292. {
  5293. b->setClickingTogglesState (true);
  5294. b->setRadioGroupId (146);
  5295. b->onClick = [this] { repaint(); for (auto& k : knobs) k->repaint(); };
  5296. addAndMakeVisible (b);
  5297. }
  5298. trackVol.setTooltip (tr ("Velocity tracking: the note's velocity moves its pan"));
  5299. trackKey.setTooltip (tr ("Keyboard tracking: the note's key moves its pan"));
  5300. trackKey.setToggleState (true, juce::dontSendNotification);
  5301. auto tracking = [this] (ChannelDef& d) -> NoteTracking& { return trackKey.getToggleState() ? d.misc.key : d.misc.velocity; };
  5302. auto trackingOf = [this] (const ChannelDef& d) -> const NoteTracking& { return trackKey.getToggleState() ? d.misc.key : d.misc.velocity; };
  5303. trackPan = knob ([name] { return ui::panSpec (name() + " - " + tr ("Tracking: pan")); },
  5304. [trackingOf] (const ChannelDef& d) { return (double) trackingOf (d).pan; },
  5305. [tracking] (ChannelDef& d, double v) { tracking (d).pan = (float) v; }, TR_NOOP ("Pan"));
  5306. trackMid = knob ([this, name] {
  5307. const auto key = trackKey.getToggleState();
  5308. auto s = countSpec (name() + " - " + tr ("Tracking: the middle value (no offset)"), key ? 131 : 128, key ? 60 : 100,
  5309. [key] (int v) { return key ? juce::MidiMessage::getMidiNoteName (120 - v, true, true, 5) : juce::String (v); }); // FL: C5 = 60
  5310. return s;
  5311. },
  5312. [trackingOf] (const ChannelDef& d) { return (double) trackingOf (d).mid; },
  5313. [tracking] (ChannelDef& d, double v) { tracking (d).mid = juce::roundToInt (v); }, TR_NOOP ("Mid"));
  5314. // FL's tracking Mod X / Y (round 151): the notes' Mod X / Y follow the velocity / key like their pan
  5315. trackModX = knob ([name] { return ui::panSpec (name() + " - " + tr ("Tracking: Mod X (the note's filter cutoff / a plugin's MOD X)")); },
  5316. [trackingOf] (const ChannelDef& d) { return (double) trackingOf (d).modX; },
  5317. [tracking] (ChannelDef& d, double v) { tracking (d).modX = (float) v; }, TR_NOOP ("Mod X"));
  5318. trackModY = knob ([name] { return ui::panSpec (name() + " - " + tr ("Tracking: Mod Y (the note's filter resonance)")); },
  5319. [trackingOf] (const ChannelDef& d) { return (double) trackingOf (d).modY; },
  5320. [tracking] (ChannelDef& d, double v) { tracking (d).modY = (float) v; }, TR_NOOP ("Mod Y"));
  5321. // Echo delay / fat mode
  5322. echoFeed = knob ([name] { return ui::percentSpec (name() + " - " + tr ("Delay feedback (100% = the echoes as loud as the note)"), 0.0); },
  5323. [] (const ChannelDef& d) { return (double) d.misc.echo.feedback / 2.0; },
  5324. [] (ChannelDef& d, double v) { d.misc.echo.feedback = (float) (2.0 * v); }, TR_NOOP ("Feed"));
  5325. echoPan = knob ([name] { return ui::panSpec (name() + " - " + tr ("Delay pan: each echo moves this much")); },
  5326. [] (const ChannelDef& d) { return (double) d.misc.echo.pan; }, [] (ChannelDef& d, double v) { d.misc.echo.pan = (float) v; },
  5327. TR_NOOP ("Pan"));
  5328. echoModX = knob ([name] { return ui::panSpec (name() + " - " + tr ("Delay Mod X: each echo moves the note's Mod X this much")); },
  5329. [] (const ChannelDef& d) { return (double) d.misc.echo.modX; }, [] (ChannelDef& d, double v) { d.misc.echo.modX = (float) v; },
  5330. TR_NOOP ("Mod X"));
  5331. echoModY = knob ([name] { return ui::panSpec (name() + " - " + tr ("Delay Mod Y: each echo moves the note's Mod Y this much")); },
  5332. [] (const ChannelDef& d) { return (double) d.misc.echo.modY; }, [] (ChannelDef& d, double v) { d.misc.echo.modY = (float) v; },
  5333. TR_NOOP ("Mod Y"));
  5334. echoPitch = knob ([name] {
  5335. ui::ValueSpec s;
  5336. s.name = name() + " - " + tr ("Delay pitch: each echo moves this many cents");
  5337. s.minimum = -1200.0;
  5338. s.maximum = 1200.0;
  5339. s.interval = 1.0;
  5340. s.toText = [] (double v) { return tr ("{0} cents", { juce::String (juce::roundToInt (v)) }); };
  5341. return s;
  5342. },
  5343. [] (const ChannelDef& d) { return (double) d.misc.echo.pitch; }, [] (ChannelDef& d, double v) { d.misc.echo.pitch = (float) v; },
  5344. TR_NOOP ("Pitch"));
  5345. echoTime = knob ([name] {
  5346. ui::ValueSpec s;
  5347. s.name = name() + " - " + tr ("Delay time (steps:ticks)");
  5348. s.minimum = 1.0;
  5349. s.maximum = 192.0 * 4.0;
  5350. s.defaultValue = 144.0;
  5351. s.interval = 1.0;
  5352. s.pixelsForRange = 400.0;
  5353. s.toText = [] (double v) { const auto t = juce::roundToInt (v); return juce::String (t / 48) + ":" + juce::String ((t % 48) / 2).paddedLeft ('0', 2); };
  5354. return s;
  5355. },
  5356. [] (const ChannelDef& d) { return (double) d.misc.echo.timeBeats * 192.0; },
  5357. [] (ChannelDef& d, double v) { d.misc.echo.timeBeats = (float) (juce::roundToInt (v) / 192.0); }, TR_NOOP ("Time"));
  5358. echoCount = knob ([name] { return countSpec (name() + " - " + tr ("Delay number of echoes"), 10, 4); },
  5359. [] (const ChannelDef& d) { return (double) d.misc.echo.echoes; },
  5360. [] (ChannelDef& d, double v) { d.misc.echo.echoes = juce::jlimit (1, 10, juce::roundToInt (v)); }, TR_NOOP ("Echoes"));
  5361. pingPong.setButtonText (tr ("Ping pong"));
  5362. pingPong.setTooltip (tr ("Ping pong: the echoes' pan bounces off the left and right ends"));
  5363. pingPong.onClick = [this] { edit ([on = pingPong.getToggleState()] (ChannelDef& d) { d.misc.echo.pingPong = on; }); };
  5364. fatMode.setButtonText (tr ("Fat mode"));
  5365. fatMode.setTooltip (tr ("Fat mode: a second, mirrored series of echoes (opposite pan and pitch steps), all at the feedback level"));
  5366. fatMode.onClick = [this] { edit ([on = fatMode.getToggleState()] (ChannelDef& d) { d.misc.echo.fat = on; }); };
  5367. // Root note row: main pitch
  5368. mainPitch.setButtonText (tr ("Enable main pitch"));
  5369. mainPitch.setTooltip (tr ("The channel follows the main pitch (the toolbar's master pitch)"));
  5370. mainPitch.onClick = [this] { edit ([on = mainPitch.getToggleState()] (ChannelDef& d) { d.misc.mainPitch = on; }); };
  5371. // FL's Add to key and Root note keyboard (round 149): a sampler's root moves its pitch, other instruments are
  5372. // transposed by (C5 − root) with Add to key
  5373. addToKey.setButtonText (tr ("Add to key"));
  5374. addToKey.setTooltip (tr ("Add to key: the notes are played the root note's distance from C5 away (instruments that are not samplers)"));
  5375. addToKey.onClick = [this] { edit ([on = addToKey.getToggleState()] (ChannelDef& d) { d.misc.addToKey = on; }); };
  5376. // FL's Root note › Fine tune (round 151 [DATA: .flp event 0x8E, cents]): every note of the channel this many
  5377. // cents away
  5378. fineTune = knob ([name] {
  5379. ui::ValueSpec s;
  5380. s.name = name() + " - " + tr ("Fine tuning");
  5381. s.minimum = -100.0;
  5382. s.maximum = 100.0;
  5383. s.interval = 1.0;
  5384. s.toText = [] (double v) { return tr ("{0} cents", { (v > 0.0 ? "+" : "") + juce::String (juce::roundToInt (v)) }); };
  5385. return s;
  5386. },
  5387. [] (const ChannelDef& d) { return (double) d.misc.fineTune; }, [] (ChannelDef& d, double v) { d.misc.fineTune = (float) v; },
  5388. TR_NOOP ("Fine tune"));
  5389. rootReset.setButtonText (tr ("Reset"));
  5390. rootReset.setTooltip (tr ("Reset the root note to C5"));
  5391. rootReset.onClick = [this] { if (rootKeys.onPick) rootKeys.onPick (60); };
  5392. addAndMakeVisible (rootReset);
  5393. rootKeys.onPick = [this] (int key) {
  5394. edit ([key] (ChannelDef& d) {
  5395. if (d.instrument == InstrumentKind::sampler)
  5396. {
  5397. // the sample plays at its own pitch on the root: the pitch moves by the root's change (within ±24)
  5398. const auto pitch = std::clamp (d.sampler.pitch + (float) (d.misc.rootNote - key), -24.0f, 24.0f);
  5399. const auto moved = (int) std::lround (pitch - d.sampler.pitch);
  5400. d.sampler.pitch = pitch;
  5401. d.misc.rootNote = std::clamp (d.misc.rootNote - moved, 0, 127);
  5402. }
  5403. else
  5404. d.misc.rootNote = key;
  5405. });
  5406. };
  5407. rootKeys.onRegion = [this] (int low, int high) {
  5408. edit ([low, high] (ChannelDef& d) {
  5409. d.keyLow = juce::jlimit (0, 127, low);
  5410. d.keyHigh = juce::jlimit (d.keyLow, 127, high);
  5411. });
  5412. };
  5413. addAndMakeVisible (addToKey);
  5414. addAndMakeVisible (rootKeys);
  5415. // Arpeggiator: FL's Slide and Chord
  5416. arpSlide.setButtonText (tr ("Slide"));
  5417. arpSlide.setTooltip (tr ("Slide: the arpeggio glides from note to note (instruments that slide)"));
  5418. arpSlide.onClick = [this] { edit ([on = arpSlide.getToggleState()] (ChannelDef& d) { d.arp.slide = on; }); };
  5419. arpChord.addItem (tr ("Auto (sustain)"), 1);
  5420. arpChord.addItem (tr ("None (octaves)"), 2);
  5421. for (const auto& [chordName, intervals] : arpChords())
  5422. arpChord.addItem (tr (chordName), arpChord.getNumItems() + 1);
  5423. arpChord.setTooltip (tr ("Chord: Auto plays the held notes; a chord plays it on the lowest held note"));
  5424. arpChord.onChange = [this] {
  5425. const auto id = arpChord.getSelectedId();
  5426. if (id <= 0)
  5427. return;
  5428. edit ([id] (ChannelDef& d) {
  5429. if (id == 1)
  5430. d.arp.chord.clear();
  5431. else if (id == 2)
  5432. d.arp.chord = { 0 };
  5433. else if (id - 3 < (int) arpChords().size())
  5434. d.arp.chord = arpChords()[(std::size_t) (id - 3)].second;
  5435. });
  5436. };
  5437. for (auto* b : { &fullPorta, &pingPong, &fatMode, &mainPitch, &arpSlide })
  5438. addAndMakeVisible (b);
  5439. addAndMakeVisible (arpChord);
  5440. // Group
  5441. cut = knob ([this, name] { return countSpec (name() + " - " + tr ("Cut: notes of this channel stop the channels cut by this group"),
  5442. juce::jmax (99, current() != nullptr ? current()->cutGroup : 0), 0,
  5443. [this] (int g) { return juce::String (cutGroupText (g, channel)); }); },
  5444. [] (const ChannelDef& d) { return (double) d.cutGroup; }, [] (ChannelDef& d, double v) { d.cutGroup = juce::jmax (0, juce::roundToInt (v)); },
  5445. TR_NOOP ("Cut group"));
  5446. cutBy = knob ([this, name] { return countSpec (name() + " - " + tr ("By: this channel is cut by the channels of this group"),
  5447. juce::jmax (99, current() != nullptr ? current()->cutBy : 0), 0,
  5448. [this] (int g) { return juce::String (cutGroupText (g, channel)); }); },
  5449. [] (const ChannelDef& d) { return (double) d.cutBy; }, [] (ChannelDef& d, double v) { d.cutBy = juce::jmax (0, juce::roundToInt (v)); },
  5450. TR_NOOP ("Cut by"));
  5451. cutSelf.setButtonText (tr ("Cut self"));
  5452. cutSelf.setClickingTogglesState (true);
  5453. cutSelf.setTooltip (tr ("Cut self: a new note of this channel stops its own sounding note (hi-hats, 808s)"));
  5454. cutSelf.onClick = [this] { edit ([on = cutSelf.getToggleState(), ch = channel] (ChannelDef& d) { setChannelCutsItself (d, ch, on); }); };
  5455. // Arpeggiator
  5456. arpDirection.addItemList ({ tr ("Off"), tr ("Up"), tr ("Down"), tr ("Up and down"), tr ("Random"), tr ("Up and down (sticky)") }, 1);
  5457. arpDirection.setTooltip (tr ("Arpeggiator direction (Off = the notes play as written)"));
  5458. arpDirection.onChange = [this] { edit ([d = arpDirection.getSelectedId() - 1] (ChannelDef& c) { c.arp.direction = juce::jlimit (0, 5, d); }); };
  5459. for (const auto& [text, beats] : arpSpeeds())
  5460. arpTime.addItem (tr (text), arpTime.getNumItems() + 1);
  5461. arpTime.setTooltip (tr ("Arpeggiator time: the length of each step"));
  5462. arpTime.onChange = [this] {
  5463. const auto i = arpTime.getSelectedId() - 1;
  5464. if (i >= 0 && i < (int) arpSpeeds().size())
  5465. edit ([b = arpSpeeds()[(std::size_t) i].second] (ChannelDef& c) { c.arp.stepBeats = b; });
  5466. };
  5467. arpRange = knob ([name] { return countSpec (name() + " - " + tr ("Arpeggiator range (octaves)"), 4, 1); },
  5468. [] (const ChannelDef& d) { return (double) d.arp.range; },
  5469. [] (ChannelDef& d, double v) { d.arp.range = juce::jlimit (1, 4, juce::roundToInt (v)); }, TR_NOOP ("Range"));
  5470. arpGate = knob ([name] {
  5471. auto s = ui::percentSpec (name() + " - " + tr ("Arpeggio gate (past 100% the next note waits)"), 0.5);
  5472. s.minimum = 0.05;
  5473. s.maximum = 128.0 / 48.0;
  5474. return s;
  5475. },
  5476. [] (const ChannelDef& d) { return (double) d.arp.gate; },
  5477. [] (ChannelDef& d, double v) { d.arp.gate = juce::jlimit (0.05f, 128.0f / 48.0f, (float) v); }, TR_NOOP ("Gate"));
  5478. // FL's Repeat 0 plays the whole chord at once on each step (round 149)
  5479. arpRepeat = knob ([name] { return countSpec (name() + " - " + tr ("Arpeggiator repeat: times the arpeggio plays in an octave before the next one (0: the chord at once)"), 16, 1,
  5480. [] (int i) { return i == 0 ? tr ("Chord") : juce::String (i); }); },
  5481. [] (const ChannelDef& d) { return (double) d.arp.octaveRepeat; },
  5482. [] (ChannelDef& d, double v) { d.arp.octaveRepeat = juce::jlimit (0, 16, juce::roundToInt (v)); }, TR_NOOP ("Repeat"));
  5483. for (auto* b : { &porta, &mono })
  5484. addAndMakeVisible (b);
  5485. addAndMakeVisible (cutSelf);
  5486. addAndMakeVisible (arpDirection);
  5487. addAndMakeVisible (arpTime);
  5488. refresh();
  5489. engine.addChangeListener (this);
  5490. setSize (preferredWidth, preferredHeight);
  5491. }
  5492. ~MiscPanel() override { engine.removeChangeListener (this); }
  5493. void paint (juce::Graphics& g) override
  5494. {
  5495. g.fillAll (theme::colour::bg2);
  5496. for (const auto& [area, title] : sections)
  5497. {
  5498. g.setColour (theme::colour::bg3);
  5499. g.fillRoundedRectangle (area.toFloat(), 4.0f);
  5500. g.setColour (theme::colour::textSecondary);
  5501. g.setFont (theme::font (theme::type::caption, true));
  5502. auto text = theme::caps (title);
  5503. if (&title == &sections[(std::size_t) juce::jmax (0, rootSection)].second && rootSection >= 0 && current() != nullptr)
  5504. text << ": " << RootKeyboard::keyName (current()->misc.rootNote); // FL's "Root note: C5"
  5505. g.drawText (text, area.withHeight (20).reduced (8, 0), juce::Justification::centredLeft);
  5506. }
  5507. }
  5508. void resized() override
  5509. {
  5510. sections.clear();
  5511. auto area = getLocalBounds().reduced (8);
  5512. auto section = [this] (juce::Rectangle<int> r, const juce::String& title) {
  5513. sections.push_back ({ r, title });
  5514. return r.withTrimmedTop (20).reduced (6, 4);
  5515. };
  5516. constexpr int knobW = 50, knobH = 64;
  5517. auto row = [] (juce::Rectangle<int>& r, std::initializer_list<FrameKnob*> ks) {
  5518. auto line = r.removeFromTop (knobH);
  5519. for (auto* k : ks)
  5520. k->setBounds (line.removeFromLeft (knobW));
  5521. };
  5522. auto top = area.removeFromTop (118);
  5523. {
  5524. auto levels = section (top.removeFromLeft (4 * knobW + 12), tr ("Levels adjustment"));
  5525. row (levels, { pan, volume, modX, modY });
  5526. }
  5527. top.removeFromLeft (6);
  5528. {
  5529. auto poly = section (top.removeFromLeft (2 * knobW + 30), tr ("Polyphony"));
  5530. row (poly, { maxPoly, slide });
  5531. auto toggles = poly.removeFromTop (22);
  5532. porta.setBounds (toggles.removeFromLeft (64));
  5533. mono.setBounds (toggles);
  5534. }
  5535. top.removeFromLeft (6);
  5536. {
  5537. auto time = section (top.removeFromLeft (3 * knobW + 12), tr ("Time"));
  5538. row (time, { timeGate, timeShift, swing });
  5539. fullPorta.setBounds (time.removeFromTop (22));
  5540. }
  5541. top.removeFromLeft (6);
  5542. {
  5543. auto track = section (top, tr ("Tracking"));
  5544. auto tabs = track.removeFromTop (0);
  5545. juce::ignoreUnused (tabs);
  5546. const auto title = sections.back().first;
  5547. trackVol.setBounds (title.getRight() - 84, title.getY() + 2, 38, 16);
  5548. trackKey.setBounds (title.getRight() - 44, title.getY() + 2, 38, 16);
  5549. row (track, { trackPan, trackModX, trackModY, trackMid });
  5550. }
  5551. area.removeFromTop (6);
  5552. auto bottom = area.removeFromTop (130);
  5553. {
  5554. auto group = section (bottom.removeFromLeft (2 * knobW + 16), tr ("Group"));
  5555. row (group, { cut, cutBy });
  5556. cutSelf.setBounds (group.removeFromTop (24).reduced (4, 0));
  5557. }
  5558. bottom.removeFromLeft (6);
  5559. {
  5560. auto arp = section (bottom.removeFromLeft (330), tr ("Arpeggiator"));
  5561. auto boxes = arp.removeFromLeft (118);
  5562. arpDirection.setBounds (boxes.removeFromTop (22));
  5563. boxes.removeFromTop (4);
  5564. arpTime.setBounds (boxes.removeFromTop (22));
  5565. boxes.removeFromTop (4);
  5566. arpChord.setBounds (boxes.removeFromTop (22));
  5567. boxes.removeFromTop (4);
  5568. arpSlide.setBounds (boxes.removeFromTop (22));
  5569. arp.removeFromLeft (6);
  5570. row (arp, { arpRange, arpGate, arpRepeat });
  5571. }
  5572. bottom.removeFromLeft (6);
  5573. {
  5574. auto echo = section (bottom, tr ("Echo delay / fat mode"));
  5575. {
  5576. // seven knobs (round 151 added Mod X / Y): narrower when the window is
  5577. auto line = echo.removeFromTop (knobH);
  5578. const auto w = juce::jmin (knobW, line.getWidth() / 7);
  5579. for (auto* k : { echoFeed, echoPan, echoModX, echoModY, echoPitch, echoTime, echoCount })
  5580. k->setBounds (line.removeFromLeft (w));
  5581. }
  5582. auto toggles = echo.removeFromTop (22);
  5583. pingPong.setBounds (toggles.removeFromLeft (100));
  5584. fatMode.setBounds (toggles.removeFromLeft (100));
  5585. }
  5586. area.removeFromTop (6);
  5587. {
  5588. auto rootRow = section (area.removeFromTop (74), tr ("Root note"));
  5589. rootSection = (int) sections.size() - 1;
  5590. const auto resetWidth = theme::buttonWidth (rootReset, 50, 96); // long "Reset" translations
  5591. auto toggles = rootRow.removeFromLeft (100 + resetWidth);
  5592. mainPitch.setBounds (toggles.removeFromTop (22));
  5593. auto line = toggles.removeFromTop (22);
  5594. rootReset.setBounds (line.removeFromRight (resetWidth).reduced (0, 1));
  5595. addToKey.setBounds (line);
  5596. auto fine = rootRow.removeFromLeft (58);
  5597. row (fine, { fineTune });
  5598. rootKeys.setBounds (rootRow.reduced (4, 2));
  5599. }
  5600. }
  5601. private:
  5602. // LYNX's chord choices for the arpeggiator (the piano roll's chord stamps)
  5603. static const std::vector<std::pair<const char*, std::vector<int>>>& arpChords()
  5604. {
  5605. static const std::vector<std::pair<const char*, std::vector<int>>> chords {
  5606. { TR_NOOP ("Major"), { 0, 4, 7 } }, { TR_NOOP ("Minor"), { 0, 3, 7 } }, { "Dim", { 0, 3, 6 } }, { "Aug", { 0, 4, 8 } },
  5607. { "Sus2", { 0, 2, 7 } }, { "Sus4", { 0, 5, 7 } }, { "7", { 0, 4, 7, 10 } }, { "Maj7", { 0, 4, 7, 11 } },
  5608. { "m7", { 0, 3, 7, 10 } }, { "m9", { 0, 3, 7, 10, 14 } }, { TR_NOOP ("Octave"), { 0, 12 } },
  5609. };
  5610. return chords;
  5611. }
  5612. static const std::vector<std::pair<const char*, float>>& arpSpeeds()
  5613. {
  5614. static const std::vector<std::pair<const char*, float>> speeds { { "1/4", 1.0f }, { "1/8", 0.5f },
  5615. { TR_NOOP ("1/8 triplet"), 1.0f / 3.0f }, { "1/16", 0.25f },
  5616. { TR_NOOP ("1/16 triplet"), 1.0f / 6.0f }, { "1/32", 0.125f } };
  5617. return speeds;
  5618. }
  5619. const ChannelDef* current() const
  5620. {
  5621. const auto& channels = engine.getSong().channels;
  5622. return channel >= 0 && channel < (int) channels.size() ? &channels[(std::size_t) channel] : nullptr;
  5623. }
  5624. void edit (std::function<void (ChannelDef&)> change)
  5625. {
  5626. if (updating || current() == nullptr)
  5627. return;
  5628. engine.editSong ([ch = channel, change] (Song& s) {
  5629. if (ch < (int) s.channels.size())
  5630. change (s.channels[(std::size_t) ch]);
  5631. });
  5632. }
  5633. void refresh()
  5634. {
  5635. const auto* c = current();
  5636. if (c == nullptr)
  5637. return;
  5638. updating = true;
  5639. porta.setToggleState (channelPortamento (*c), juce::dontSendNotification);
  5640. porta.setEnabled (channelHasPortamento (*c));
  5641. slide->setEnabled (channelHasPortamento (*c));
  5642. mono.setToggleState (channelMono (*c), juce::dontSendNotification);
  5643. mono.setEnabled (channelHasMono (*c));
  5644. cutSelf.setToggleState (channelCutsItself (*c), juce::dontSendNotification);
  5645. arpDirection.setSelectedId (juce::jlimit (0, 5, c->arp.direction) + 1, juce::dontSendNotification);
  5646. fullPorta.setToggleState (c->misc.fullPorta, juce::dontSendNotification);
  5647. pingPong.setToggleState (c->misc.echo.pingPong, juce::dontSendNotification);
  5648. fatMode.setToggleState (c->misc.echo.fat, juce::dontSendNotification);
  5649. mainPitch.setToggleState (c->misc.mainPitch, juce::dontSendNotification);
  5650. addToKey.setToggleState (c->misc.addToKey, juce::dontSendNotification);
  5651. addToKey.setEnabled (c->instrument != InstrumentKind::sampler);
  5652. rootKeys.setRoot (c->misc.rootNote);
  5653. rootKeys.setRegion (c->keyLow, c->keyHigh);
  5654. arpSlide.setToggleState (c->arp.slide, juce::dontSendNotification);
  5655. const auto filter = c->instrument == InstrumentKind::synth || c->instrument == InstrumentKind::sampler;
  5656. modX->setEnabled (filter);
  5657. modY->setEnabled (filter);
  5658. {
  5659. auto chordId = c->arp.chord.empty() ? 1 : (c->arp.chord == std::vector<int> { 0 } ? 2 : 0);
  5660. for (int i = 0; chordId == 0 && i < (int) arpChords().size(); ++i)
  5661. if (arpChords()[(std::size_t) i].second == c->arp.chord)
  5662. chordId = i + 3;
  5663. arpChord.setSelectedId (chordId, juce::dontSendNotification);
  5664. if (chordId == 0)
  5665. arpChord.setText (tr ("Chord from FL"), juce::dontSendNotification);
  5666. }
  5667. int speed = 0;
  5668. for (int i = 0; i < (int) arpSpeeds().size(); ++i)
  5669. if (std::abs (arpSpeeds()[(std::size_t) i].second - c->arp.stepBeats) < 1e-4f)
  5670. speed = i + 1;
  5671. arpTime.setSelectedId (speed, juce::dontSendNotification);
  5672. if (speed == 0)
  5673. arpTime.setText (tr ("{0} beats", { juce::String (c->arp.stepBeats, 3) }), juce::dontSendNotification);
  5674. updating = false;
  5675. repaint();
  5676. }
  5677. void changeListenerCallback (juce::ChangeBroadcaster*) override { refresh(); }
  5678. AudioEngine& engine;
  5679. int channel;
  5680. bool updating = false;
  5681. std::vector<std::unique_ptr<FrameKnob>> knobs;
  5682. FrameKnob *pan = nullptr, *volume = nullptr, *maxPoly = nullptr, *slide = nullptr, *swing = nullptr, *cut = nullptr, *cutBy = nullptr,
  5683. *arpRange = nullptr, *arpGate = nullptr, *arpRepeat = nullptr, *modX = nullptr, *modY = nullptr, *timeGate = nullptr,
  5684. *timeShift = nullptr, *trackPan = nullptr, *trackMid = nullptr, *echoFeed = nullptr, *echoPan = nullptr, *echoPitch = nullptr,
  5685. *echoTime = nullptr, *echoCount = nullptr, *trackModX = nullptr, *trackModY = nullptr, *echoModX = nullptr, *echoModY = nullptr,
  5686. *fineTune = nullptr;
  5687. juce::ToggleButton porta, mono, fullPorta, pingPong, fatMode, mainPitch, arpSlide, addToKey;
  5688. RootKeyboard rootKeys;
  5689. juce::TextButton rootReset;
  5690. int rootSection = -1;
  5691. juce::TextButton trackVol, trackKey;
  5692. juce::ComboBox arpChord;
  5693. juce::TextButton cutSelf;
  5694. juce::ComboBox arpDirection, arpTime;
  5695. std::vector<std::pair<juce::Rectangle<int>, juce::String>> sections;
  5696. };
  5697. // FL's preset arrows of a generator's window (round 167o, issue #24; FL's TPluginForm NextPrevPreset, FLEngine
  5698. // 0x12b6c70): ◀ name ▶ over the .fst presets of the plugin's folder (FL's factory folder and the user's, subfolders
  5699. // too) in FL's order; no preset yet: ▶ the first, ◀ the last; both wrap. The step loads the preset into the channel
  5700. // (one undo step), names the channel after it and says "n / N" in the hint bar, as FL. A click on the name lists them.
  5701. class ChannelPresetBar final : public juce::Component
  5702. {
  5703. public:
  5704. // after a preset is loaded (the channel's old name, the preset's): the window refreshes its page and title
  5705. std::function<void (const juce::String&, const juce::String&)> onLoaded;
  5706. ChannelPresetBar (AudioEngine& e, int c) : engine (e), channel (c)
  5707. {
  5708. for (auto* b : { &prev, &next })
  5709. {
  5710. b->setTooltip (b == &prev ? tr ("Previous preset") : tr ("Next preset"));
  5711. b->setWantsKeyboardFocus (false);
  5712. addAndMakeVisible (*b);
  5713. }
  5714. prev.onClick = [this] { step (-1); };
  5715. next.onClick = [this] { step (1); };
  5716. ui::setHint (*this, tr ("Presets: [LMB] the list, the arrows load the previous / next one"));
  5717. }
  5718. // Whether this channel's instrument has an FL preset folder (the bar is shown only then)
  5719. static bool wanted (const AudioEngine& engine, int channel)
  5720. {
  5721. const auto& song = engine.getSong();
  5722. if (! juce::isPositiveAndBelow (channel, (int) song.channels.size()))
  5723. return false;
  5724. const auto kind = song.channels[(std::size_t) channel].instrument;
  5725. return ! natives::presetFolderOf (kind).empty() || banks::hasBank (kind);
  5726. }
  5727. // Round 190in (design190ia FW-5): in a window's title bar the bar is FL's — the preset's name, dim, then ◀ ▶ at the
  5728. // right, no box
  5729. void setTitleLook (bool shouldBe)
  5730. {
  5731. titleLook = shouldBe;
  5732. prev.setVisible (! titleLook);
  5733. next.setVisible (! titleLook);
  5734. setRepaintsOnMouseActivity (titleLook);
  5735. resized();
  5736. repaint();
  5737. }
  5738. void resized() override
  5739. {
  5740. auto r = getLocalBounds();
  5741. if (titleLook)
  5742. {
  5743. nextArea = r.removeFromRight (16);
  5744. prevArea = r.removeFromRight (16);
  5745. nameArea = r.withTrimmedRight (4);
  5746. return;
  5747. }
  5748. prev.setBounds (r.removeFromLeft (24));
  5749. next.setBounds (r.removeFromRight (24));
  5750. nameArea = r.reduced (4, 0);
  5751. }
  5752. void paint (juce::Graphics& g) override
  5753. {
  5754. if (titleLook)
  5755. {
  5756. using namespace theme;
  5757. const auto mouse = getMouseXYRelative();
  5758. const auto over = isMouseOver();
  5759. g.setColour (over && nameArea.contains (mouse) ? colour::textPrimary : colour::textSecondary);
  5760. g.setFont (font (type::small));
  5761. g.drawText (current >= 0 ? currentName : tr ("Presets"), nameArea, juce::Justification::centredRight, true);
  5762. for (const auto left : { true, false })
  5763. {
  5764. const auto r = (left ? prevArea : nextArea).toFloat();
  5765. juce::Path p;
  5766. p.addTriangle (left ? 3.0f : -3.0f, -4.5f, left ? 3.0f : -3.0f, 4.5f, left ? -3.0f : 3.0f, 0.0f);
  5767. p.applyTransform (juce::AffineTransform::translation (r.getCentreX(), r.getCentreY()));
  5768. g.setColour (over && r.contains (mouse.toFloat()) ? colour::accent : colour::textPrimary);
  5769. g.fillPath (p);
  5770. }
  5771. return;
  5772. }
  5773. g.setColour (theme::colour::bg2);
  5774. g.fillRoundedRectangle (nameArea.toFloat(), theme::radius::sm);
  5775. g.setColour (current >= 0 ? theme::colour::textPrimary : theme::colour::textSecondary);
  5776. g.setFont (theme::font (theme::type::body));
  5777. g.drawText (current >= 0 ? currentName : tr ("Presets"), nameArea.reduced (6, 0), juce::Justification::centredLeft, true);
  5778. }
  5779. void mouseMove (const juce::MouseEvent&) override
  5780. {
  5781. if (titleLook)
  5782. repaint(); // (the hovered part: the name, ◀ or ▶)
  5783. }
  5784. void mouseUp (const juce::MouseEvent& e) override
  5785. {
  5786. if (e.mouseWasDraggedSinceMouseDown())
  5787. return;
  5788. if (titleLook && prevArea.contains (e.getPosition()))
  5789. step (-1);
  5790. else if (titleLook && nextArea.contains (e.getPosition()))
  5791. step (1);
  5792. else if (nameArea.contains (e.getPosition()))
  5793. showMenu();
  5794. }
  5795. private:
  5796. const ChannelDef* def() const
  5797. {
  5798. const auto& song = engine.getSong();
  5799. return juce::isPositiveAndBelow (channel, (int) song.channels.size()) ? &song.channels[(std::size_t) channel] : nullptr;
  5800. }
  5801. const std::vector<presetcycle::Preset>& list()
  5802. {
  5803. const auto* d = def();
  5804. const auto kind = d != nullptr ? d->instrument : InstrumentKind::synth;
  5805. if (! loaded || kind != listedKind)
  5806. {
  5807. const auto folder = natives::presetFolderOf (kind);
  5808. presets = folder.empty() ? std::vector<presetcycle::Preset>()
  5809. : presetcycle::listPresets (presetcycle::pluginPresetFolders (flStudioAccess().roots, true, folder));
  5810. // LYNX's own bank after FL's presets (round 168n): the only presets without FL Studio
  5811. const auto& bank = banks::bankOf (kind);
  5812. for (int i = 0; i < (int) bank.size(); ++i)
  5813. presets.push_back ({ banks::pathOf (i), banks::relativeOf (bank[(std::size_t) i]), bank[(std::size_t) i].name });
  5814. // the user's own presets last (round 190fs): "Your presets" in the menu, the arrows go through them too
  5815. userFrom = (int) presets.size();
  5816. for (const auto& f : genpresetui::userPresets (kind))
  5817. presets.push_back ({ f.getFullPathName().toStdString(), {}, f.getFileNameWithoutExtension().toStdString() });
  5818. listedKind = kind;
  5819. loaded = true;
  5820. current = d != nullptr ? presetcycle::indexOfName (presets, d->name) : -1; // (a channel named after its preset)
  5821. currentName = current >= 0 ? juce::String::fromUTF8 (presets[(std::size_t) current].name.c_str()) : juce::String();
  5822. }
  5823. return presets;
  5824. }
  5825. void step (int delta)
  5826. {
  5827. const auto& all = list();
  5828. const auto count = (int) all.size();
  5829. // FL's next index; a preset LYNX can't read (an unknown or damaged state) is passed over in the same
  5830. // direction, so the arrows keep going
  5831. auto at = presetcycle::step (current, delta, count);
  5832. for (int tries = 0; at >= 0 && tries < count; ++tries)
  5833. {
  5834. if (load (at, tries == count - 1))
  5835. return;
  5836. at = presetcycle::step (at, delta, count);
  5837. }
  5838. }
  5839. bool load (int index, bool reportFailure = true)
  5840. {
  5841. const auto& all = list();
  5842. const auto* d = def();
  5843. if (d == nullptr || ! juce::isPositiveAndBelow (index, (int) all.size()))
  5844. return false;
  5845. const auto& preset = all[(std::size_t) index];
  5846. const auto bankIndex = banks::indexOfPath (preset.path);
  5847. std::optional<ChannelDef> changed;
  5848. if (index >= userFrom) // one of the user's own presets (round 190fs)
  5849. {
  5850. if (const auto own = genpresetui::read (juce::File (juce::String::fromUTF8 (preset.path.c_str()))))
  5851. changed = genpresets::withPreset (*d, *own);
  5852. }
  5853. else
  5854. changed = bankIndex >= 0 ? banks::withPreset (*d, bankIndex) : natives::withPreset (*d, preset.path, preset.name, flStudioAccess());
  5855. if (! changed)
  5856. {
  5857. if (reportFailure)
  5858. ui::postHint ({ tr ("This preset could not be read: {0}", { juce::String::fromUTF8 (preset.name.c_str()) }), {} }, 2500);
  5859. current = index; // (the next step goes on from it)
  5860. return false;
  5861. }
  5862. const auto kind = d->instrument;
  5863. const auto oldName = juce::String::fromUTF8 (d->name.c_str());
  5864. engine.editSong ([ch = channel, kind, c = std::move (*changed)] (Song& s) {
  5865. if (ch < (int) s.channels.size() && s.channels[(std::size_t) ch].instrument == kind)
  5866. s.channels[(std::size_t) ch] = c;
  5867. });
  5868. if (onLoaded != nullptr)
  5869. onLoaded (oldName, juce::String::fromUTF8 (preset.name.c_str()));
  5870. current = index;
  5871. currentName = juce::String::fromUTF8 (preset.name.c_str());
  5872. ui::postHint ({ currentName, juce::String (presetcycle::positionText (index, (int) all.size())) }, 2500);
  5873. repaint();
  5874. return true;
  5875. }
  5876. void showMenu()
  5877. {
  5878. buildMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this));
  5879. }
  5880. public:
  5881. juce::PopupMenu buildMenu()
  5882. {
  5883. refreshUserPresets(); // (another channel's window may have saved or deleted one)
  5884. const auto& all = list();
  5885. juce::PopupMenu menu;
  5886. std::map<std::string, juce::PopupMenu> folders;
  5887. std::vector<std::string> order;
  5888. for (int i = 0; i < juce::jmin (userFrom, (int) all.size()); ++i)
  5889. {
  5890. const auto& rel = all[(std::size_t) i].relative;
  5891. const auto slash = rel.find_last_of ('/');
  5892. const auto folder = slash == std::string::npos ? std::string() : rel.substr (0, slash);
  5893. if (folders.find (folder) == folders.end())
  5894. order.push_back (folder);
  5895. folders[folder].addItem (juce::String::fromUTF8 (all[(std::size_t) i].name.c_str()), true, i == current, [this, i] { load (i); });
  5896. }
  5897. for (const auto& folder : order)
  5898. if (folder.empty())
  5899. for (juce::PopupMenu::MenuItemIterator it (folders[folder]); it.next();)
  5900. menu.addItem (it.getItem());
  5901. else
  5902. menu.addSubMenu (juce::String::fromUTF8 (folder.c_str()), folders[folder]);
  5903. if (menu.getNumItems() == 0 && userFrom >= (int) all.size())
  5904. menu.addItem (tr ("No presets found (they come with FL Studio)"), false, false, [] {});
  5905. addUserItems (menu);
  5906. return menu;
  5907. }
  5908. // Round 190fs: the user's own presets of this generator, with the items the hosted plugins' and the mixer effects'
  5909. // preset menus have (Save preset..., Your presets, Delete preset, Show the presets folder). FL's wrapper saves a
  5910. // generator's settings with "Save preset as..." (PluginMenu SaveStateMenu); LYNX's channel window has no wrapper
  5911. // menu, so the item is in the preset box, as in the other LYNX preset menus.
  5912. void addUserItems (juce::PopupMenu& menu)
  5913. {
  5914. const auto& all = list();
  5915. const auto* d = def();
  5916. if (d == nullptr || ! genpresets::canSave (d->instrument))
  5917. return;
  5918. if (userFrom < (int) all.size())
  5919. {
  5920. menu.addSectionHeader (tr ("Your presets"));
  5921. for (int i = userFrom; i < (int) all.size(); ++i)
  5922. menu.addItem (juce::String::fromUTF8 (all[(std::size_t) i].name.c_str()), true, i == current, [this, i] { load (i); });
  5923. }
  5924. menu.addSeparator();
  5925. menu.addItem (tr ("Save preset..."), [safe = juce::Component::SafePointer<ChannelPresetBar> (this)] {
  5926. if (safe != nullptr)
  5927. safe->saveAs();
  5928. });
  5929. if (current >= userFrom && current < (int) all.size())
  5930. {
  5931. const juce::File file (juce::String::fromUTF8 (all[(std::size_t) current].path.c_str()));
  5932. menu.addItem (tr ("Delete preset \"{0}\"", { file.getFileNameWithoutExtension() }),
  5933. [safe = juce::Component::SafePointer<ChannelPresetBar> (this), file] {
  5934. file.deleteFile();
  5935. if (safe != nullptr)
  5936. safe->relist ({});
  5937. });
  5938. }
  5939. const auto kind = d->instrument;
  5940. menu.addItem (tr ("Show the presets folder"), [kind] { genpresetui::reveal (genpresetui::folderFor (kind)); });
  5941. }
  5942. // "Save preset...": the name box, then the file; the box shows the new preset (the channel keeps its name)
  5943. void saveAs()
  5944. {
  5945. const auto* d = def();
  5946. if (d == nullptr)
  5947. return;
  5948. genpresetui::askName (*this, current >= 0 ? currentName : juce::String::fromUTF8 (d->name.c_str()),
  5949. [safe = juce::Component::SafePointer<ChannelPresetBar> (this)] (const juce::String& name) {
  5950. if (safe != nullptr)
  5951. safe->saveNamed (name);
  5952. });
  5953. }
  5954. bool saveNamed (const juce::String& name)
  5955. {
  5956. const auto* d = def();
  5957. if (d == nullptr)
  5958. return false;
  5959. juce::File written;
  5960. juce::String error;
  5961. if (! genpresetui::save (*d, name, written, error))
  5962. {
  5963. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Save preset"), error);
  5964. return false;
  5965. }
  5966. relist (written.getFullPathName());
  5967. return true;
  5968. }
  5969. juce::String shownName() const { return current >= 0 ? currentName : juce::String(); }
  5970. int presetCount() { return (int) list().size(); }
  5971. int userPresetCount() { return (int) list().size() - userFrom; }
  5972. bool loadAt (int index) { return load (index, false); }
  5973. private:
  5974. // the user's presets as they are on disk now, the rest of the list kept; the current preset stays selected
  5975. void refreshUserPresets()
  5976. {
  5977. const auto* d = def();
  5978. if (! loaded || d == nullptr || d->instrument != listedKind)
  5979. return;
  5980. const auto was = current >= userFrom && current < (int) presets.size() ? presets[(std::size_t) current].path : std::string();
  5981. presets.resize ((std::size_t) userFrom);
  5982. for (const auto& f : genpresetui::userPresets (listedKind))
  5983. presets.push_back ({ f.getFullPathName().toStdString(), {}, f.getFileNameWithoutExtension().toStdString() });
  5984. if (! was.empty())
  5985. {
  5986. current = -1;
  5987. for (int i = userFrom; i < (int) presets.size(); ++i)
  5988. if (presets[(std::size_t) i].path == was)
  5989. current = i;
  5990. if (current < 0)
  5991. currentName = {};
  5992. }
  5993. }
  5994. // the list again (a preset was saved or deleted); `select` (a file path) becomes the current preset
  5995. void relist (const juce::String& select)
  5996. {
  5997. loaded = false;
  5998. const auto& all = list();
  5999. current = -1;
  6000. currentName = {};
  6001. for (int i = userFrom; i < (int) all.size() && select.isNotEmpty(); ++i)
  6002. if (juce::File (juce::String::fromUTF8 (all[(std::size_t) i].path.c_str())) == juce::File (select))
  6003. {
  6004. current = i;
  6005. currentName = juce::String::fromUTF8 (all[(std::size_t) i].name.c_str());
  6006. }
  6007. repaint();
  6008. }
  6009. AudioEngine& engine;
  6010. int channel;
  6011. juce::TextButton prev { juce::String::fromUTF8 ("\xe2\x97\x80") }, next { juce::String::fromUTF8 ("\xe2\x96\xb6") };
  6012. juce::Rectangle<int> nameArea, prevArea, nextArea;
  6013. bool titleLook = false;
  6014. std::vector<presetcycle::Preset> presets;
  6015. InstrumentKind listedKind = InstrumentKind::synth;
  6016. bool loaded = false;
  6017. int current = -1;
  6018. int userFrom = 0; // the first of the user's own presets in `presets`
  6019. juce::String currentName;
  6020. };
  6021. // FL's ON switch of a channel (round 190in, design190ia FW-2): a round green LED (15 px) with its caption under it, as
  6022. // FL's wrapper draws it; off = a dark LED. Clicking it mutes / unmutes the channel.
  6023. class OnLed final : public juce::Button
  6024. {
  6025. public:
  6026. OnLed() : juce::Button (tr ("On"))
  6027. {
  6028. setClickingTogglesState (true);
  6029. setWantsKeyboardFocus (false);
  6030. setMouseClickGrabsKeyboardFocus (false);
  6031. }
  6032. void paintButton (juce::Graphics& g, bool over, bool down) override
  6033. {
  6034. using namespace theme;
  6035. const auto b = getLocalBounds().toFloat();
  6036. const auto led = juce::Rectangle<float> (15.0f, 15.0f).withCentre ({ b.getCentreX(), 18.0f });
  6037. if (getToggleState())
  6038. {
  6039. g.setGradientFill (juce::ColourGradient (colour::ledOn.brighter (0.3f), led.getCentreX() - 2.0f, led.getCentreY() - 2.0f,
  6040. juce::Colour (0xff2a9d5e), led.getRight(), led.getBottom(), true));
  6041. g.fillEllipse (led);
  6042. g.setColour (over ? colour::textSecondary : juce::Colour (0xff1e5e3a));
  6043. }
  6044. else
  6045. {
  6046. g.setColour (juce::Colour (0xff2a2d34));
  6047. g.fillEllipse (led);
  6048. g.setColour (over ? colour::textSecondary : colour::borderStrong);
  6049. }
  6050. g.drawEllipse (led.reduced (0.5f), 1.0f);
  6051. g.setColour (over || down ? colour::textPrimary : colour::textSecondary);
  6052. g.setFont (font (type::caption, true));
  6053. g.drawFittedText (caps (getButtonText()), juce::Rectangle<int> (0, (int) FrameKnob::headerCaptionTop, getWidth(), 10), juce::Justification::centred, 1, 0.6f);
  6054. }
  6055. };
  6056. // FL's channel controls at the right of a channel's window header (ON, PAN, VOL, PITCH, RANGE, TRACK; REA round 143b,
  6057. // round 190in's FL look, design190ia FW-2..FW-4): the channel window's header and a hosted instrument's wrapper header
  6058. // (FW-7) show the same strip. Its width is `preferredWidth`; the controls keep FL's places from its right edge.
  6059. class ChannelHeaderControls final : public juce::Component,
  6060. private juce::ChangeListener
  6061. {
  6062. public:
  6063. static constexpr int preferredWidth = 232;
  6064. ChannelHeaderControls (AudioEngine& e, int c) : engine (e), channel (c)
  6065. {
  6066. on.setTooltip (tr ("Channel on / off (mute)"));
  6067. on.onClick = [this] {
  6068. const auto muted = ! on.getToggleState();
  6069. engine.editSong ([ch = channel, muted] (Song& s) {
  6070. if (ch < (int) s.channels.size())
  6071. s.channels[(std::size_t) ch].muted = muted;
  6072. });
  6073. };
  6074. addAndMakeVisible (on);
  6075. const auto name = [this] { return channelNameOf (engine.getSong(), channel); };
  6076. auto headerKnob = [this] (std::function<ui::ValueSpec()> spec, std::function<double (const ChannelDef&)> get, std::function<void (Song&, int, double)> set,
  6077. const char* caption) {
  6078. auto k = std::make_unique<FrameKnob> (
  6079. engine, std::move (spec),
  6080. [this, get] { return channel < (int) engine.getSong().channels.size() ? get (engine.getSong().channels[(std::size_t) channel]) : 0.0; },
  6081. [this, set] (double v) {
  6082. engine.editSong ([ch = channel, set, v] (Song& s) {
  6083. if (ch < (int) s.channels.size())
  6084. set (s, ch, v);
  6085. });
  6086. },
  6087. tr (caption));
  6088. addAndMakeVisible (*k);
  6089. header.push_back (std::move (k));
  6090. };
  6091. headerKnob ([this, name] {
  6092. auto s = ui::panSpec (name() + " - " + tr ("Pan"));
  6093. s.target = AutomationTarget { AutomationTargetKind::channelPan, channel };
  6094. return s;
  6095. },
  6096. [] (const ChannelDef& d) { return (double) d.pan; }, [] (Song& s, int ch, double v) { s.channels[(std::size_t) ch].pan = (float) v; },
  6097. TR_NOOP ("Pan"));
  6098. headerKnob ([this, name] {
  6099. auto s = ui::percentSpec (name() + " - " + tr ("Volume"), 0.78);
  6100. s.target = AutomationTarget { AutomationTargetKind::channelVolume, channel };
  6101. return s;
  6102. },
  6103. [] (const ChannelDef& d) { return (double) d.volume; },
  6104. [] (Song& s, int ch, double v) { s.channels[(std::size_t) ch].volume = (float) v; }, TR_NOOP ("Vol"));
  6105. // FL's PITCH knob and its RANGE (REA round 146b): the channel's pitch, within ± range semitones
  6106. headerKnob ([this, name] {
  6107. ui::ValueSpec s;
  6108. s.name = name() + " - " + tr ("Pitch (semitones, within the range)");
  6109. const auto range = channel < (int) engine.getSong().channels.size() ? engine.getSong().channels[(std::size_t) channel].misc.pitchRange : 2;
  6110. s.minimum = -juce::jmax (1, range);
  6111. s.maximum = juce::jmax (1, range);
  6112. s.toText = [] (double v) { return tr ("{0} cents", { juce::String (juce::roundToInt (v * 100.0)) }); };
  6113. return s;
  6114. },
  6115. [] (const ChannelDef& d) { return (double) d.sampler.pitch; },
  6116. [] (Song& s, int ch, double v) { s.channels[(std::size_t) ch].sampler.pitch = (float) juce::jlimit (-24.0, 24.0, v); }, TR_NOOP ("Pitch"));
  6117. headerKnob ([name] { return ui::digitWheel (countSpec (name() + " - " + tr ("Pitch knob range (semitones)"), 48, 2,
  6118. [] (int v) { return juce::String (v); })); },
  6119. [] (const ChannelDef& d) { return (double) d.misc.pitchRange; },
  6120. [] (Song& s, int ch, double v) { s.channels[(std::size_t) ch].misc.pitchRange = juce::jlimit (0, 48, juce::roundToInt (v)); },
  6121. TR_NOOP ("Range"));
  6122. header.back()->digitBox = true;
  6123. // FL's TRACK digiwheel (round 168s, issue #32 "very small and not accurate"): a wheel notch or 7.5 px of drag = the
  6124. // next insert, double-click shows the insert in the Mixer, the menu has "Assign to free mixer track"
  6125. headerKnob ([this, name] {
  6126. return ui::digitWheel (countSpec (name() + " - " + tr ("Target mixer track"), maxMixerTracks - 1, 0,
  6127. [] (int t) { return t == 0 ? tr ("Master") : juce::String (t); }));
  6128. },
  6129. [] (const ChannelDef& d) { return (double) d.mixerTrack; },
  6130. [] (Song& s, int ch, double v) {
  6131. mixerops::routeChannel (s, ch, juce::roundToInt (v)); // any insert (round 162): missing ones are added
  6132. },
  6133. TR_NOOP ("Track"));
  6134. {
  6135. auto& track = *header.back();
  6136. track.digitBox = true;
  6137. track.doubleClicked = [this] {
  6138. if (channel < (int) engine.getSong().channels.size() && openMixerInsertHandler())
  6139. openMixerInsertHandler() (engine.getSong().channels[(std::size_t) channel].mixerTrack);
  6140. };
  6141. track.extraMenuItems = [this] (juce::PopupMenu& menu) {
  6142. menu.addItem (tr ("Assign to free mixer track"), [this] {
  6143. engine.editSong ([ch = channel] (Song& s) {
  6144. if (ch < (int) s.channels.size())
  6145. s.channels[(std::size_t) ch].mixerTrack = s.claimFreeInsert();
  6146. });
  6147. });
  6148. };
  6149. }
  6150. for (auto& k : header)
  6151. k->headerLook = true;
  6152. header[1]->restArc = theme::colour::ledOn; // FL's green VOL ring
  6153. header[3]->joinLeft = true; // RANGE, attached to the PITCH knob
  6154. refresh();
  6155. engine.addChangeListener (this);
  6156. }
  6157. ~ChannelHeaderControls() override { engine.removeChangeListener (this); }
  6158. void resized() override
  6159. {
  6160. // FL's places from the right edge (ref/fl-plugin-wrapper-flex.png: ON 214, PAN 180, VOL 145, PITCH 111 px to the
  6161. // centre; RANGE right of PITCH; TRACK 7 px in)
  6162. const auto w = getWidth(), h = getHeight();
  6163. on.setBounds (w - 229, 0, 30, h);
  6164. const int xs[] = { w - 197, w - 162, w - 128, w - 96, w - 52 };
  6165. const int ws[] = { 34, 34, 34, 32, 46 };
  6166. for (std::size_t i = 0; i < header.size() && i < 5; ++i)
  6167. header[i]->setBounds (xs[i], 0, ws[i], h);
  6168. }
  6169. private:
  6170. void refresh()
  6171. {
  6172. if (channel < (int) engine.getSong().channels.size())
  6173. on.setToggleState (! engine.getSong().channels[(std::size_t) channel].muted, juce::dontSendNotification);
  6174. for (auto& k : header)
  6175. k->repaint();
  6176. }
  6177. void changeListenerCallback (juce::ChangeBroadcaster*) override { refresh(); }
  6178. AudioEngine& engine;
  6179. int channel;
  6180. OnLed on;
  6181. std::vector<std::unique_ptr<FrameKnob>> header;
  6182. };
  6183. // The frame: header strip (tabs on the left; ON, PAN, VOL, TRACK on the right) over the page of the selected tab.
  6184. // Round 190in (design190ia FW-1, FW-5): FL's 46 px strip — the tabs are FL's 44 px icon tabs flush at the left (the
  6185. // shown one raised, its icon green), the preset ◀ name ▶ and FL's ▸ menu go to the window's title bar when the window
  6186. // has LYNX's own (docked), else they sit in the strip (▸ at the far left, the presets after the tabs).
  6187. class ChannelFrame final : public juce::Component
  6188. {
  6189. public:
  6190. static constexpr int headerHeight = 46;
  6191. // c.index < 0 (a Patcher node, round 164f): the instrument's pages alone, without the channel's header and Misc tab
  6192. ChannelFrame (AudioEngine& e, ChannelRef c, std::unique_ptr<juce::Component> instrumentPage, std::unique_ptr<juce::Component> envelopePage)
  6193. : engine (e), channel (c.index), node (c.index < 0)
  6194. {
  6195. auto addPage = [this] (std::unique_ptr<juce::Component> page, const juce::String& title, const juce::String& tip, Icon icon) {
  6196. // FL's icon tab (FW-1): the caption is the tooltip and the hint
  6197. auto button = std::make_unique<IconButton> (title, icon);
  6198. button->setTooltip (title + ": " + tip);
  6199. button->setFlat (true);
  6200. button->setCorners (false, false);
  6201. button->setOnColour (theme::colour::bg5);
  6202. button->setIconColourWhenOn (theme::colour::ledOn);
  6203. button->setIconColour (theme::colour::textSecondary);
  6204. button->setIconSizing (0.5f, 22.0f);
  6205. button->setWantsKeyboardFocus (false);
  6206. button->setClickingTogglesState (true);
  6207. button->setRadioGroupId (1);
  6208. const auto index = (int) pages.size();
  6209. button->onClick = [this, index] { showTab (index); };
  6210. addAndMakeVisible (*button);
  6211. addChildComponent (*page);
  6212. sizes.push_back ({ juce::jmax (1, page->getWidth()), juce::jmax (1, page->getHeight()) });
  6213. tabs.push_back (std::move (button));
  6214. pages.push_back (std::move (page));
  6215. };
  6216. instrumentPageFirst = instrumentPage != nullptr;
  6217. if (instrumentPage != nullptr) // (none: a channel whose instrument has its own window, e.g. a hosted plugin)
  6218. {
  6219. // FL's channel window has one "Sample settings" sheet for the Sampler and for an audio clip's channel, and a
  6220. // "Plugin editor" sheet for every other generator (TPluginForm BtnHint "|Sample settings" / "|Plugin editor")
  6221. const auto kind = channel >= 0 && channel < (int) engine.getSong().channels.size()
  6222. ? engine.getSong().channels[(std::size_t) channel].instrument
  6223. : InstrumentKind::synth;
  6224. if (kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip)
  6225. addPage (std::move (instrumentPage), tr ("Sample"), tr ("Sample settings"), Icon::audioFile);
  6226. else
  6227. {
  6228. // round 190in (FW-6): the engine's description ("Harmless — FL's additive engine…") is the tab's tooltip
  6229. auto tip = tr ("The instrument's own settings");
  6230. if (auto* model = dynamic_cast<ModelPanel*> (instrumentPage.get()))
  6231. tip = model->description();
  6232. addPage (std::move (instrumentPage), tr ("Plugin"), tip, Icon::pluginPicker);
  6233. }
  6234. }
  6235. if (envelopePage != nullptr)
  6236. addPage (std::move (envelopePage), tr ("Envelope / instrument"), tr ("Envelope / instrument settings: the filter and pitch envelopes and the LFOs"),
  6237. Icon::envelope);
  6238. if (node)
  6239. {
  6240. int width = 1, height = 1;
  6241. for (auto& p : pages)
  6242. {
  6243. width = juce::jmax (width, p->getWidth());
  6244. height = juce::jmax (height, p->getHeight());
  6245. }
  6246. setSize (width, headerHeight + height);
  6247. showTab (0);
  6248. return;
  6249. }
  6250. addPage (std::make_unique<MiscPanel> (engine, channel), tr ("Misc"), tr ("Miscellaneous functions: levels, polyphony, time, tracking, cut groups, arpeggiator, echo delay"),
  6251. Icon::wrench);
  6252. controls = std::make_unique<ChannelHeaderControls> (engine, channel);
  6253. addAndMakeVisible (*controls);
  6254. // FL's ▸ wrapper menu (round 190in, R8): in the strip until the window takes it into its title bar
  6255. addAndMakeVisible (menuArrow);
  6256. menuArrow.onClick = [this] { showWrapperMenu (menuArrow); };
  6257. if (ChannelPresetBar::wanted (engine, channel))
  6258. {
  6259. presetBar = std::make_unique<ChannelPresetBar> (engine, channel);
  6260. presetBar->onLoaded = [this, hasPage = instrumentPageFirst] (const juce::String& oldName, const juce::String& newName) {
  6261. // the plugin page shows the new preset's settings, the window takes the channel's new name (as FL)
  6262. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<ChannelFrame> (this), hasPage, oldName, newName] {
  6263. if (safe != nullptr)
  6264. safe->presetLoaded (hasPage, oldName, newName);
  6265. });
  6266. };
  6267. addAndMakeVisible (*presetBar);
  6268. }
  6269. int width = MiscPanel::preferredWidth, height = MiscPanel::preferredHeight;
  6270. for (auto& p : pages)
  6271. {
  6272. width = juce::jmax (width, p->getWidth());
  6273. height = juce::jmax (height, p->getHeight());
  6274. }
  6275. setSize (width, headerHeight + height);
  6276. showTab (0);
  6277. }
  6278. void showTab (int index)
  6279. {
  6280. index = juce::jlimit (0, (int) pages.size() - 1, index);
  6281. current = index;
  6282. for (int i = 0; i < (int) pages.size(); ++i)
  6283. {
  6284. pages[(std::size_t) i]->setVisible (i == index);
  6285. tabs[(std::size_t) i]->setToggleState (i == index, juce::dontSendNotification);
  6286. }
  6287. }
  6288. void presetLoaded (bool hasPage, const juce::String& oldName, const juce::String& newName)
  6289. {
  6290. if (hasPage && ! pages.empty())
  6291. if (auto fresh = makeChannelSettingsPanel (engine, channel))
  6292. {
  6293. removeChildComponent (pages.front().get());
  6294. pages.front() = std::move (fresh);
  6295. addChildComponent (*pages.front());
  6296. resized();
  6297. showTab (current);
  6298. }
  6299. if (auto* window = findParentComponentOfClass<juce::DocumentWindow>())
  6300. if (const auto title = window->getName(); oldName.isNotEmpty() && title.startsWith (oldName))
  6301. window->setName (newName + title.substring (oldName.length()));
  6302. }
  6303. int getTab() const noexcept { return current; }
  6304. int tabCount() const noexcept { return (int) pages.size(); }
  6305. void paint (juce::Graphics& g) override
  6306. {
  6307. g.fillAll (theme::colour::bg2);
  6308. g.setColour (theme::colour::bg3);
  6309. g.fillRect (getLocalBounds().removeFromTop (headerHeight));
  6310. g.setColour (theme::colour::border);
  6311. g.drawHorizontalLine (headerHeight - 1, 0.0f, (float) getWidth());
  6312. for (auto& t : tabs) // FL's tabs sit side by side; a 1 px line closes each
  6313. g.fillRect (t->getRight(), 0, 1, headerHeight - 1);
  6314. }
  6315. // Round 190in: the window's title bar shows the ▸ menu and the presets (docked: LYNX's own title bar); the strip
  6316. // gives them up. The window calls this once it knows.
  6317. void movePresetsToTitleBar (juce::Component& titleBarOwner)
  6318. {
  6319. presetsInTitle = true;
  6320. menuArrow.setVisible (false);
  6321. if (presetBar != nullptr)
  6322. {
  6323. presetBar->setTitleLook (true);
  6324. titleBarOwner.addAndMakeVisible (*presetBar);
  6325. }
  6326. resized();
  6327. }
  6328. juce::Component* presetComponent() const noexcept { return presetBar.get(); }
  6329. int channelIndex() const noexcept { return channel; }
  6330. // FL's ▸ wrapper menu of this channel (round 190in, details190if R8). `scaling` / `detached`: the window's items.
  6331. std::function<void (wrappermenu::Spec&)> windowItems;
  6332. void showWrapperMenu (juce::Component& anchor);
  6333. juce::PopupMenu buildWrapperMenu();
  6334. void resized() override
  6335. {
  6336. auto strip = getLocalBounds().removeFromTop (headerHeight - 1);
  6337. if (menuArrow.isVisible())
  6338. menuArrow.setBounds (strip.removeFromLeft (20).withSizeKeepingCentre (20, 24));
  6339. for (auto& t : tabs) // FL's 44 px icon tabs, side by side, the strip's whole height
  6340. {
  6341. t->setBounds (strip.removeFromLeft (44));
  6342. strip.removeFromLeft (1);
  6343. }
  6344. if (controls != nullptr)
  6345. controls->setBounds (getWidth() - ChannelHeaderControls::preferredWidth, 0, ChannelHeaderControls::preferredWidth, headerHeight - 1);
  6346. if (presetBar != nullptr && ! presetsInTitle) // one row after the tabs (FW-5: where there is no title bar of LYNX's)
  6347. {
  6348. strip.removeFromLeft (8);
  6349. const auto room = (controls != nullptr ? controls->getX() : getWidth()) - 8 - strip.getX();
  6350. presetBar->setBounds (strip.withWidth (juce::jlimit (0, 280, room)).withSizeKeepingCentre (juce::jlimit (0, 280, room), 22));
  6351. }
  6352. // each page keeps its own size (some scale their drawing with it), centred under the header
  6353. const auto body = getLocalBounds().withTrimmedTop (headerHeight);
  6354. const juce::ScopedValueSetter<bool> placing (laying, true);
  6355. for (std::size_t i = 0; i < pages.size(); ++i)
  6356. {
  6357. const auto w = juce::jmin (body.getWidth(), sizes[i].x), h = juce::jmin (body.getHeight(), sizes[i].y);
  6358. pages[i]->setBounds (body.getX() + (body.getWidth() - w) / 2, body.getY(), w, h);
  6359. }
  6360. }
  6361. // A page that sizes itself (Slicex's display modes and keyboard button, round 190hg): the frame takes the new
  6362. // size and its window follows, as FL's plugin window does. Sizes set by resized() itself are not news.
  6363. void childBoundsChanged (juce::Component* child) override
  6364. {
  6365. if (laying)
  6366. return;
  6367. for (std::size_t i = 0; i < pages.size(); ++i)
  6368. if (pages[i].get() == child)
  6369. {
  6370. const juce::Point<int> now { juce::jmax (1, child->getWidth()), juce::jmax (1, child->getHeight()) };
  6371. if (now == sizes[i])
  6372. return;
  6373. sizes[i] = now;
  6374. int width = node ? 1 : MiscPanel::preferredWidth, height = node ? 1 : MiscPanel::preferredHeight;
  6375. for (const auto& size : sizes)
  6376. {
  6377. width = juce::jmax (width, size.x);
  6378. height = juce::jmax (height, size.y);
  6379. }
  6380. if (width != getWidth() || headerHeight + height != getHeight())
  6381. setSize (width, headerHeight + height);
  6382. else
  6383. resized();
  6384. return;
  6385. }
  6386. }
  6387. private:
  6388. AudioEngine& engine;
  6389. int channel;
  6390. bool node = false;
  6391. int current = 0;
  6392. std::vector<std::unique_ptr<IconButton>> tabs;
  6393. std::vector<std::unique_ptr<juce::Component>> pages;
  6394. std::vector<juce::Point<int>> sizes;
  6395. bool laying = false; // (resized() is placing the pages)
  6396. std::unique_ptr<ChannelHeaderControls> controls;
  6397. wrappermenu::MenuArrow menuArrow;
  6398. std::unique_ptr<ChannelPresetBar> presetBar;
  6399. bool instrumentPageFirst = false, presetsInTitle = false;
  6400. };
  6401. void ChannelFrame::showWrapperMenu (juce::Component& anchor)
  6402. {
  6403. buildWrapperMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&anchor));
  6404. }
  6405. juce::PopupMenu ChannelFrame::buildWrapperMenu()
  6406. {
  6407. // FL's channel ▸ menu (FL manual, Channel Settings › Menu commands; Plugin wrapper › Plugin Menu; capture
  6408. // live190gu/genpreset/fl-wrapper-menu-slicex.png). The Channel rack's own items come from the main window.
  6409. wrappermenu::Spec spec;
  6410. spec.channel = true;
  6411. if (channelWrapperItemsHandler())
  6412. channelWrapperItemsHandler() (channel, spec);
  6413. if (auto* bar = presetBar.get())
  6414. {
  6415. const juce::Component::SafePointer<ChannelPresetBar> safe (bar);
  6416. spec.presets = [safe] (juce::PopupMenu& m) {
  6417. if (safe != nullptr)
  6418. m = safe->buildMenu();
  6419. };
  6420. spec.savePresetAs = [safe] {
  6421. if (safe != nullptr)
  6422. safe->saveAs();
  6423. };
  6424. }
  6425. if (const auto* d = channel >= 0 && channel < (int) engine.getSong().channels.size() ? &engine.getSong().channels[(std::size_t) channel] : nullptr;
  6426. d != nullptr && genpresets::canSave (d->instrument) && locateInBrowserHandler())
  6427. spec.browsePresets = [folder = genpresetui::folderFor (d->instrument)] {
  6428. folder.createDirectory();
  6429. if (locateInBrowserHandler())
  6430. locateInBrowserHandler() (folder);
  6431. };
  6432. // FL's Route to free mixer track (Ctrl+L): the channel to the first free insert
  6433. spec.routeToFreeMixerTrack = [this] {
  6434. engine.editSong ([ch = channel] (Song& s) {
  6435. if (ch >= 0 && ch < (int) s.channels.size())
  6436. s.channels[(std::size_t) ch].mixerTrack = s.claimFreeInsert();
  6437. });
  6438. };
  6439. if (windowItems)
  6440. windowItems (spec);
  6441. return wrappermenu::build (spec);
  6442. }
  6443. bool hasEnvelopeTab (InstrumentKind kind) noexcept
  6444. {
  6445. return kind == InstrumentKind::synth || kind == InstrumentKind::sampler;
  6446. }
  6447. // The channel's Envelope / instrument settings page: LYNX's own for the synth and the sampler; FL's (the plugin voice
  6448. // processor's block in the generator's state) for Fruity Slicer (issue #129)
  6449. std::unique_ptr<juce::Component> makeEnvelopePage (AudioEngine& engine, const ChannelRef& ref, InstrumentKind kind)
  6450. {
  6451. // round 190df: a sampler that runs FL's voice (an FL project's sampler: SamplerSettings::flChannel) gets FL's own
  6452. // page, with the three tensions, the predelay and the envelope presets; its edits keep FL's voice (LYNX's page
  6453. // would replace it)
  6454. if (const auto* def = ref.get (engine); kind == InstrumentKind::sampler && def != nullptr && flsamplervoice::has (def->sampler))
  6455. return makeFlVoicePanel (
  6456. engine,
  6457. [&engine, ref] () -> std::optional<flvoice::Settings> {
  6458. const auto* d = ref.get (engine);
  6459. if (d == nullptr || d->instrument != InstrumentKind::sampler || ! flsamplervoice::has (d->sampler))
  6460. return std::nullopt;
  6461. return flsamplervoice::read (d->sampler);
  6462. },
  6463. [&engine, ref] (const flvoice::Settings& settings) {
  6464. ref.edit (engine, [settings] (ChannelDef& d) { flsamplervoice::write (d.sampler, settings); });
  6465. });
  6466. if (hasEnvelopeTab (kind))
  6467. return std::make_unique<ModulationPanel> (engine, ref);
  6468. if (kind != InstrumentKind::fruityslicer)
  6469. return nullptr;
  6470. return makeFlVoicePanel (
  6471. engine,
  6472. [&engine, ref] () -> std::optional<flvoice::Settings> {
  6473. const auto* def = ref.get (engine);
  6474. if (def == nullptr || def->instrument != InstrumentKind::fruityslicer)
  6475. return std::nullopt;
  6476. const auto state = fslicer::parse (def->pluginState);
  6477. return fslicer::voiceSettings (state ? *state : fslicer::State {});
  6478. },
  6479. [&engine, ref] (const flvoice::Settings& settings) {
  6480. ref.edit (engine, [settings] (ChannelDef& def) {
  6481. if (auto state = fslicer::parse (def.pluginState))
  6482. {
  6483. fslicer::setVoiceSettings (*state, settings);
  6484. def.pluginState = fslicer::write (*state);
  6485. }
  6486. });
  6487. });
  6488. }
  6489. void showModulationFor (juce::Component& from, AudioEngine& engine, int channel)
  6490. {
  6491. if (auto* frame = from.findParentComponentOfClass<ChannelFrame>(); frame != nullptr && frame->tabCount() >= 2)
  6492. frame->showTab (1);
  6493. else if (channel >= 0)
  6494. openChannelModulation (engine, channel);
  6495. }
  6496. bool isModelKind (InstrumentKind kind) noexcept
  6497. {
  6498. return kind == InstrumentKind::sakura || kind == InstrumentKind::drumpad || kind == InstrumentKind::boobass
  6499. || kind == InstrumentKind::drumsynth || kind == InstrumentKind::harmless || kind == InstrumentKind::harmor
  6500. || kind == InstrumentKind::gms || kind == InstrumentKind::morphine
  6501. || kind == InstrumentKind::ogun || kind == InstrumentKind::minisynth
  6502. || kind == InstrumentKind::dx10 || kind == InstrumentKind::kepler || kind == InstrumentKind::keplerExo || kind == InstrumentKind::poizone
  6503. || kind == InstrumentKind::fruitkick || kind == InstrumentKind::bassdrum || kind == InstrumentKind::toxic
  6504. || kind == InstrumentKind::threeosc
  6505. || kind == InstrumentKind::autogun || kind == InstrumentKind::transistorbass
  6506. || kind == InstrumentKind::simsynth || kind == InstrumentKind::wasp || kind == InstrumentKind::plucked
  6507. || kind == InstrumentKind::beepmap || kind == InstrumentKind::sawer || kind == InstrumentKind::flkeys
  6508. || kind == InstrumentKind::granulizer || kind == InstrumentKind::drumaxx
  6509. || kind == InstrumentKind::slayer || kind == InstrumentKind::fruitydance || kind == InstrumentKind::sytrus || kind == InstrumentKind::pocketSuperSaw;
  6510. }
  6511. // The instrument page of a channel or a Patcher node (null: none of its own)
  6512. std::unique_ptr<juce::Component> makeInstrumentPage (AudioEngine& engine, const ChannelRef& ref)
  6513. {
  6514. const auto* def = ref.get (engine);
  6515. if (def == nullptr)
  6516. return nullptr;
  6517. const auto kind = def->instrument;
  6518. if (kind == InstrumentKind::fruitydance && ref.index >= 0)
  6519. return makeDanceEditor (engine, ref.index); // round 165e
  6520. if (kind == InstrumentKind::videoplayer)
  6521. return makeVideoPlayerEditor (engine, ref.locate, ref.index); // round 165g
  6522. if (kind == InstrumentKind::wavetraveller)
  6523. return makeWaveTravellerEditor (engine, ref.locate, ref.index); // round 167f
  6524. if (kind == InstrumentKind::fruityslicer)
  6525. return makeFruitySlicerEditor (engine, ref.locate, ref.index); // round 180c
  6526. if (kind == InstrumentKind::slicex)
  6527. return makeSlicexEditor (engine, ref.locate, ref.index); // round 190r
  6528. if (kind == InstrumentKind::fpc)
  6529. return makeFpcEditor (engine, ref.locate, ref.index); // round 190q
  6530. if (kind == InstrumentKind::tetra)
  6531. return makeTetraEditor (engine, ref.locate, ref.index); // round 190hs
  6532. if (kind == InstrumentKind::directwave)
  6533. return makeDirectWaveEditor (engine, ref.locate, ref.index); // round 190hz
  6534. if (kind == InstrumentKind::helix)
  6535. return makeHelixEditor (engine, ref.locate, ref.index); // round 190ja
  6536. if (kind == InstrumentKind::synth)
  6537. return std::make_unique<SynthPanel> (engine, ref);
  6538. if (isModelKind (kind))
  6539. return std::make_unique<ModelPanel> (engine, ref);
  6540. if (kind == InstrumentKind::sampler)
  6541. return std::make_unique<SettingsPanel> (engine, ref);
  6542. return nullptr;
  6543. }
  6544. // Where "Align all channel editors" put every channel editor (FL stores it per channel, so editors opened later come
  6545. // up there too); empty = centred, as before.
  6546. std::optional<juce::Point<int>>& alignedChannelEditorPosition()
  6547. {
  6548. static std::optional<juce::Point<int>> at;
  6549. return at;
  6550. }
  6551. // Round 190he (issue #152: "the FL-engine plugins can't be made smaller"): a settings window's content at a scale of
  6552. // its own (FL's plugin menu › Scaling, core/EditorScale.h). The page keeps its own size and layout and is drawn through a
  6553. // transform; this holder is the page's size times the factor, and follows the page when it changes its size (a tab
  6554. // with another size). When the window is sized by its edge, the holder takes the new size and the factor follows.
  6555. class ScaledContent final : public juce::Component
  6556. {
  6557. public:
  6558. ScaledContent (std::unique_ptr<juce::Component> page, int storedScale)
  6559. : inner (std::move (page)),
  6560. stored (storedScale)
  6561. {
  6562. getProperties().set ("lynxScaledContent", true);
  6563. addAndMakeVisible (*inner);
  6564. fitToPage();
  6565. }
  6566. juce::Component& page() noexcept { return *inner; }
  6567. int storedScale() const noexcept { return stored; }
  6568. juce::Point<int> pageSize() const { return { juce::jmax (1, inner->getWidth()), juce::jmax (1, inner->getHeight()) }; }
  6569. void setStoredScale (int newStored)
  6570. {
  6571. stored = newStored <= 0 ? 0 : editorscale::storedFor (newStored);
  6572. fitToPage();
  6573. }
  6574. void resized() override
  6575. {
  6576. if (fitting)
  6577. return;
  6578. const auto size = pageSize();
  6579. const auto factor = juce::jmax (0.05, juce::jmin ((double) getWidth() / size.x, (double) getHeight() / size.y));
  6580. inner->setTransform (juce::AffineTransform::scale ((float) factor));
  6581. // (a pixel of rounding is not a new size: the window fitted to the page lands here too)
  6582. if (const auto percent = editorscale::percentForWidth (getWidth(), size.x); std::abs (percent - editorscale::percentOf (stored)) > 1)
  6583. stored = editorscale::storedFor (percent);
  6584. }
  6585. void childBoundsChanged (juce::Component* child) override
  6586. {
  6587. if (child == inner.get() && ! fitting)
  6588. fitToPage();
  6589. }
  6590. private:
  6591. void fitToPage()
  6592. {
  6593. const juce::ScopedValueSetter<bool> busy (fitting, true);
  6594. const auto factor = editorscale::factorOf (stored);
  6595. inner->setTopLeftPosition (0, 0);
  6596. inner->setTransform (juce::AffineTransform::scale ((float) factor));
  6597. const auto size = pageSize();
  6598. setSize (juce::roundToInt (size.x * factor), juce::roundToInt (size.y * factor));
  6599. }
  6600. std::unique_ptr<juce::Component> inner;
  6601. int stored = 0;
  6602. bool fitting = false;
  6603. };
  6604. // Sizing a settings window by its edge keeps the page's proportions (the content area is the page times one factor),
  6605. // between editorscale::minPercent and maxPercent.
  6606. class PageAspectConstrainer final : public juce::ComponentBoundsConstrainer
  6607. {
  6608. public:
  6609. explicit PageAspectConstrainer (juce::ResizableWindow& w) : window (w)
  6610. {
  6611. setMinimumOnscreenAmounts (0x10000, 16, 24, 16); // (as ResizableWindow's own constrainer: the title stays reachable)
  6612. }
  6613. std::function<juce::Point<int>()> pageSize;
  6614. std::function<void()> onResizeEnd; // (the size is remembered once, when the drag ends)
  6615. void resizeEnd() override
  6616. {
  6617. if (onResizeEnd != nullptr)
  6618. onResizeEnd();
  6619. }
  6620. void checkBounds (juce::Rectangle<int>& bounds, const juce::Rectangle<int>& previous, const juce::Rectangle<int>& limits, bool top,
  6621. bool left, bool bottom, bool right) override
  6622. {
  6623. const auto page = pageSize != nullptr ? pageSize() : juce::Point<int>();
  6624. // (only a drag of an edge keeps the proportions: a move, or the system placing the window, keeps its size)
  6625. if (page.x <= 0 || page.y <= 0 || ! (top || left || bottom || right))
  6626. {
  6627. juce::ComponentBoundsConstrainer::checkBounds (bounds, previous, limits, top, left, bottom, right);
  6628. return;
  6629. }
  6630. const auto border = window.getContentComponentBorder();
  6631. const auto w = (double) (bounds.getWidth() - border.getLeftAndRight()), h = (double) (bounds.getHeight() - border.getTopAndBottom());
  6632. const auto sideways = left || right, upDown = top || bottom;
  6633. auto factor = sideways && ! upDown ? w / page.x : upDown && ! sideways ? h / page.y : juce::jmax (w / page.x, h / page.y);
  6634. factor = juce::jlimit ((double) editorscale::minPercent / editorscale::defaultPercent,
  6635. (double) editorscale::maxPercent / editorscale::defaultPercent, factor);
  6636. const auto newW = juce::roundToInt (page.x * factor) + border.getLeftAndRight();
  6637. const auto newH = juce::roundToInt (page.y * factor) + border.getTopAndBottom();
  6638. if (left)
  6639. bounds.setLeft (bounds.getRight() - newW);
  6640. else
  6641. bounds.setWidth (newW);
  6642. if (top)
  6643. bounds.setTop (bounds.getBottom() - newH);
  6644. else
  6645. bounds.setHeight (newH);
  6646. juce::ComponentBoundsConstrainer::checkBounds (bounds, previous, limits, top, left, bottom, right); // (on screen)
  6647. }
  6648. private:
  6649. juce::ResizableWindow& window;
  6650. };
  6651. class SettingsWindow final : public juce::DocumentWindow
  6652. {
  6653. public:
  6654. // `shot` (round 190in): off the desktop, in the docked look (LYNX's title bar), for the snapshot routes
  6655. SettingsWindow (AudioEngine& engine, int c, bool modulationWindow, bool shot = false)
  6656. : juce::DocumentWindow (tr ("Channel settings"), theme::colour::bg2, DocumentWindow::closeButton, ! shot),
  6657. channel (c),
  6658. modulation (modulationWindow),
  6659. engineRef (engine),
  6660. aspect (*this)
  6661. {
  6662. setUsingNativeTitleBar (! shot);
  6663. // FL names the window after the channel and its mixer track (REA round 149 [EXEC]: "FL Studio VSTi (Master)",
  6664. // "Synth Bass (Synth Bass)")
  6665. if (const auto& song = engine.getSong(); channel >= 0 && channel < (int) song.channels.size())
  6666. {
  6667. const auto& def = song.channels[(std::size_t) channel];
  6668. const auto t = def.mixerTrack;
  6669. const auto track = t <= 0 || t >= (int) song.mixer.size() ? tr ("Master")
  6670. : song.mixer[(std::size_t) t].name.empty() ? tr ("Insert {0}", { juce::String (t) })
  6671. : juce::String::fromUTF8 (song.mixer[(std::size_t) t].name.c_str());
  6672. setName (juce::String::fromUTF8 (def.name.c_str()) + " (" + track + ")"
  6673. + (modulation ? " - " + tr ("Envelope / instrument") : juce::String()));
  6674. }
  6675. std::unique_ptr<juce::Component> page;
  6676. if (modulation)
  6677. page = std::make_unique<ModulationPanel> (engine, ChannelRef::rack (channel));
  6678. else if (! hasChannelSettings (engine.getSong().channels[(std::size_t) channel].instrument))
  6679. page = std::make_unique<ChannelFrame> (engine, ChannelRef::rack (channel), nullptr, nullptr); // the Misc tab alone
  6680. else
  6681. page = makeChannelFrame (engine, channel);
  6682. // FL's Scaling (round 190he): the channel's own size, remembered with the project (the modulation window too)
  6683. const auto& song = engine.getSong();
  6684. scaled = new ScaledContent (std::move (page), song.channels[(std::size_t) channel].editorScale);
  6685. setContentOwned (scaled, true);
  6686. aspect.pageSize = [this] { return scaled->pageSize(); };
  6687. aspect.onResizeEnd = [this] { remember (scaled->storedScale()); };
  6688. setConstrainer (&aspect);
  6689. setResizable (true, false);
  6690. auto docked = shot;
  6691. if (shot) // (as dockOrKeepAbove makes a docked window: LYNX's title bar, the close button alone)
  6692. {
  6693. setTitleBarButtonsRequired (juce::DocumentWindow::closeButton, false);
  6694. setTitleBarHeight (26);
  6695. setContentComponentSize (scaled->getWidth(), scaled->getHeight());
  6696. }
  6697. else
  6698. {
  6699. centreWithSize (getWidth(), getHeight());
  6700. if (! modulation)
  6701. if (const auto& at = alignedChannelEditorPosition(); at.has_value())
  6702. setTopLeftPosition (*at); // "Align all channel editors" set every channel's place (round 169k)
  6703. setVisible (true);
  6704. markLinkedWindow (*this, channel, -1); // FL's Auto select linked modules (round 187a)
  6705. docked = dockOrKeepAbove (*this); // FL's docked plugin window (round 190ev)
  6706. }
  6707. // Round 190in (design190ia FW-5, details190if R8): FL's title bar — ▸ menu at the left, "Name (target)" in two
  6708. // tones, the preset ◀ name ▶ at the right. Only LYNX's own title bar (docked) can hold them; a system title bar
  6709. // leaves them in the frame's strip.
  6710. if (auto* frame = dynamic_cast<ChannelFrame*> (&scaled->page()))
  6711. {
  6712. frame->windowItems = [safe = juce::Component::SafePointer<SettingsWindow> (this), docked] (wrappermenu::Spec& spec) {
  6713. if (safe == nullptr)
  6714. return;
  6715. spec.scaling = [safe] (juce::PopupMenu& m) {
  6716. if (safe != nullptr)
  6717. m = safe->scalingMenu();
  6718. };
  6719. spec.detached = ! docked; // (a window of the system's when docking is off: shown, not switched here)
  6720. };
  6721. if (docked)
  6722. {
  6723. setTitleBarTextCentred (false);
  6724. getProperties().set ("lynxTitleTwoTone", true);
  6725. getProperties().set ("lynxTitleLeft", 20);
  6726. titleMenu.onClick = [this, frame] { frame->showWrapperMenu (titleMenu); };
  6727. Component::addAndMakeVisible (titleMenu);
  6728. frame->movePresetsToTitleBar (*this);
  6729. titlePresets = frame->presetComponent();
  6730. getProperties().set ("lynxTitleRight", titlePresets != nullptr ? titlePresetsWidth + 6 : 0);
  6731. resized();
  6732. }
  6733. }
  6734. }
  6735. void resized() override
  6736. {
  6737. juce::DocumentWindow::resized();
  6738. const auto bar = getTitleBarArea();
  6739. if (titleMenu.isVisible())
  6740. titleMenu.setBounds (bar.getX() + 2, bar.getY(), 18, bar.getHeight());
  6741. if (titlePresets != nullptr && titlePresets->getParentComponent() == this)
  6742. {
  6743. auto right = bar.getRight();
  6744. if (auto* close = getCloseButton())
  6745. right = close->getX() - 6;
  6746. if (auto* min = getMinimiseButton(); min != nullptr && min->isVisible())
  6747. right = juce::jmin (right, min->getX() - 6);
  6748. titlePresets->setBounds (right - titlePresetsWidth, bar.getY() + 2, titlePresetsWidth, bar.getHeight() - 4);
  6749. }
  6750. }
  6751. int getChannel() const { return channel; }
  6752. bool isModulation() const { return modulation; }
  6753. juce::Component* page() const { return scaled != nullptr ? &scaled->page() : nullptr; }
  6754. void closeButtonPressed() override;
  6755. // FL's plugin menu › Scaling (PluginScalingMenu: 100 % … 400 % of the plugin's size): in the ▸ wrapper menu (round
  6756. // 190in, R8). A right-click on the title bar renames the channel, as in FL (DF-119: "the same can be done by
  6757. // Right-Clicking the title bar of the window"); without the Channel rack's rename (shots), it still shows Scaling.
  6758. void mouseDown (const juce::MouseEvent& e) override
  6759. {
  6760. if (e.mods.isPopupMenu() && e.eventComponent == this && ! isUsingNativeTitleBar() && e.y < getTitleBarHeight())
  6761. {
  6762. wrappermenu::Spec spec;
  6763. if (channelWrapperItemsHandler())
  6764. channelWrapperItemsHandler() (channel, spec);
  6765. if (spec.rename != nullptr)
  6766. spec.rename();
  6767. else
  6768. showScalingMenu();
  6769. return;
  6770. }
  6771. juce::DocumentWindow::mouseDown (e);
  6772. }
  6773. void showScalingMenu()
  6774. {
  6775. juce::PopupMenu menu;
  6776. menu.addSubMenu (tr ("Scaling"), scalingMenu());
  6777. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  6778. }
  6779. juce::PopupMenu scalingMenu()
  6780. {
  6781. juce::PopupMenu sizes;
  6782. const auto stored = scaled->storedScale();
  6783. const juce::Component::SafePointer<SettingsWindow> safe (this);
  6784. // FL's items (System is left out: LYNX's whole interface already follows the display's scale)
  6785. sizes.addItem (tr ("Host"), true, stored == 0, [safe] {
  6786. if (safe != nullptr)
  6787. safe->setStoredScale (0);
  6788. });
  6789. for (const auto percent : editorscale::menuPercents)
  6790. sizes.addItem (juce::String (percent) + "%", true, stored == percent, [safe, percent] {
  6791. if (safe != nullptr)
  6792. safe->setStoredScale (editorscale::storedFor (percent));
  6793. });
  6794. return sizes;
  6795. }
  6796. void setStoredScale (int stored)
  6797. {
  6798. scaled->setStoredScale (stored);
  6799. setContentComponentSize (scaled->getWidth(), scaled->getHeight());
  6800. remember (stored);
  6801. }
  6802. private:
  6803. void remember (int stored)
  6804. {
  6805. const auto& song = engineRef.getSong();
  6806. if (channel < 0 || channel >= (int) song.channels.size() || song.channels[(std::size_t) channel].editorScale == stored)
  6807. return;
  6808. engineRef.editSong ([ch = channel, stored] (Song& s) {
  6809. if (ch < (int) s.channels.size())
  6810. s.channels[(std::size_t) ch].editorScale = stored;
  6811. }, false);
  6812. engineRef.markModified();
  6813. }
  6814. int channel;
  6815. bool modulation;
  6816. AudioEngine& engineRef;
  6817. PageAspectConstrainer aspect;
  6818. ScaledContent* scaled = nullptr; // (owned by the window: its content)
  6819. wrappermenu::MenuArrow titleMenu; // FL's ▸ in LYNX's title bar (docked)
  6820. juce::Component* titlePresets = nullptr; // the frame's preset bar, moved into the title bar (owned by the frame)
  6821. static constexpr int titlePresetsWidth = 190;
  6822. };
  6823. std::vector<std::unique_ptr<SettingsWindow>>& windows()
  6824. {
  6825. static std::vector<std::unique_ptr<SettingsWindow>> open;
  6826. return open;
  6827. }
  6828. void SettingsWindow::closeButtonPressed()
  6829. {
  6830. auto* self = this;
  6831. juce::MessageManager::callAsync ([self] {
  6832. auto& open = windows();
  6833. open.erase (std::remove_if (open.begin(), open.end(), [self] (auto& w) { return w.get() == self; }), open.end());
  6834. });
  6835. }
  6836. } // namespace
  6837. namespace
  6838. {
  6839. void openWindow (AudioEngine& engine, int channel, bool modulation)
  6840. {
  6841. for (auto& w : windows())
  6842. if (w->getChannel() == channel && w->isModulation() == modulation)
  6843. {
  6844. w->toFront (true);
  6845. return;
  6846. }
  6847. windows().push_back (std::make_unique<SettingsWindow> (engine, channel, modulation));
  6848. }
  6849. } // namespace
  6850. void alignAllChannelEditors (int selectedChannel)
  6851. {
  6852. // FL's AlignAllChannelEditorsAction (FUN_012317c0, REA_rodada169k §2.4): the focused channel editor (else the
  6853. // selected channel's, else the first open one) gives the place; every channel editor goes there.
  6854. auto& open = windows();
  6855. SettingsWindow* reference = nullptr;
  6856. for (auto& w : open)
  6857. if (! w->isModulation() && w->isActiveWindow())
  6858. reference = w.get();
  6859. for (auto& w : open)
  6860. if (reference == nullptr && ! w->isModulation() && w->getChannel() == selectedChannel)
  6861. reference = w.get();
  6862. for (auto& w : open)
  6863. if (reference == nullptr && ! w->isModulation())
  6864. reference = w.get();
  6865. if (reference == nullptr)
  6866. return;
  6867. // (on the screen: a docked editor's own position is in the main window, round 190ev)
  6868. const auto at = reference->getScreenPosition();
  6869. alignedChannelEditorPosition() = at;
  6870. for (auto& w : open)
  6871. if (! w->isModulation())
  6872. setWindowScreenPosition (*w, at);
  6873. reference->toFront (true);
  6874. }
  6875. void openChannelSettings (AudioEngine& engine, int channel)
  6876. {
  6877. openWindow (engine, channel, false);
  6878. }
  6879. void openChannelMisc (AudioEngine& engine, int channel)
  6880. {
  6881. openWindow (engine, channel, false);
  6882. for (auto& w : windows())
  6883. if (w->getChannel() == channel && ! w->isModulation())
  6884. if (auto* frame = dynamic_cast<ChannelFrame*> (w->page()))
  6885. frame->showTab (frame->tabCount() - 1);
  6886. }
  6887. void openChannelModulation (AudioEngine& engine, int channel)
  6888. {
  6889. openWindow (engine, channel, true);
  6890. }
  6891. void closeChannelSettings()
  6892. {
  6893. windows().clear();
  6894. }
  6895. bool hasChannelSettings (InstrumentKind kind) noexcept
  6896. {
  6897. switch (kind)
  6898. {
  6899. case InstrumentKind::synth:
  6900. case InstrumentKind::sampler:
  6901. case InstrumentKind::audioClip:
  6902. case InstrumentKind::controller:
  6903. case InstrumentKind::midiOut:
  6904. case InstrumentKind::sakura:
  6905. case InstrumentKind::drumpad:
  6906. case InstrumentKind::boobass:
  6907. case InstrumentKind::drumsynth:
  6908. case InstrumentKind::harmless:
  6909. case InstrumentKind::harmor:
  6910. case InstrumentKind::gms:
  6911. case InstrumentKind::morphine:
  6912. case InstrumentKind::ogun:
  6913. case InstrumentKind::minisynth:
  6914. case InstrumentKind::dx10:
  6915. case InstrumentKind::kepler:
  6916. case InstrumentKind::keplerExo:
  6917. case InstrumentKind::poizone:
  6918. case InstrumentKind::fruitkick:
  6919. case InstrumentKind::bassdrum:
  6920. case InstrumentKind::toxic:
  6921. case InstrumentKind::threeosc:
  6922. case InstrumentKind::autogun:
  6923. case InstrumentKind::transistorbass:
  6924. case InstrumentKind::simsynth:
  6925. case InstrumentKind::wasp:
  6926. case InstrumentKind::plucked:
  6927. case InstrumentKind::beepmap:
  6928. case InstrumentKind::sawer:
  6929. case InstrumentKind::flkeys:
  6930. case InstrumentKind::granulizer:
  6931. case InstrumentKind::drumaxx:
  6932. case InstrumentKind::slayer:
  6933. case InstrumentKind::fruitydance:
  6934. case InstrumentKind::sytrus:
  6935. case InstrumentKind::soundfont:
  6936. case InstrumentKind::layer:
  6937. case InstrumentKind::dashboard:
  6938. case InstrumentKind::voltage:
  6939. case InstrumentKind::vfx:
  6940. case InstrumentKind::wavetraveller:
  6941. case InstrumentKind::fruityslicer:
  6942. case InstrumentKind::slicex:
  6943. case InstrumentKind::fpc:
  6944. case InstrumentKind::pocketSuperSaw:
  6945. case InstrumentKind::tetra:
  6946. case InstrumentKind::helix:
  6947. return true;
  6948. default:
  6949. return false;
  6950. }
  6951. }
  6952. bool isChannelSettingsOpen (int channel)
  6953. {
  6954. return std::any_of (windows().begin(), windows().end(), [channel] (auto& w) { return w->getChannel() == channel && ! w->isModulation(); });
  6955. }
  6956. void closeChannelSettings (int channel)
  6957. {
  6958. auto& open = windows();
  6959. open.erase (std::remove_if (open.begin(), open.end(), [channel] (auto& w) { return w->getChannel() == channel && ! w->isModulation(); }),
  6960. open.end());
  6961. }
  6962. std::unique_ptr<juce::Component> makeChannelModulationPanel (AudioEngine& engine, int channel)
  6963. {
  6964. return std::make_unique<ModulationPanel> (engine, ChannelRef::rack (channel));
  6965. }
  6966. std::unique_ptr<juce::Component> makeChannelPrecomputePanel (AudioEngine& engine, int channel)
  6967. {
  6968. return std::make_unique<PrecomputePanel> (engine, ChannelRef::rack (channel));
  6969. }
  6970. int showChannelLayoutPage (juce::Component& frame, int page)
  6971. {
  6972. if (auto* panel = dynamic_cast<ModelPanel*> (&frame); panel != nullptr && panel->pageCount() > 0)
  6973. {
  6974. const auto count = panel->pageCount();
  6975. if (page >= 0 && page < count)
  6976. panel->showPage (page);
  6977. return count;
  6978. }
  6979. for (auto* child : frame.getChildren())
  6980. if (const auto count = showChannelLayoutPage (*child, page); count > 0)
  6981. return count;
  6982. return 0;
  6983. }
  6984. int channelFrameHeaderHeight() noexcept
  6985. {
  6986. return ChannelFrame::headerHeight;
  6987. }
  6988. std::unique_ptr<juce::Component> makeChannelWindowForShot (AudioEngine& engine, int channel, int tab)
  6989. {
  6990. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  6991. return nullptr;
  6992. auto window = std::make_unique<SettingsWindow> (engine, channel, false, true);
  6993. if (auto* frame = dynamic_cast<ChannelFrame*> (window->page()))
  6994. frame->showTab (tab < 0 ? frame->tabCount() - 1 : tab);
  6995. return window;
  6996. }
  6997. std::optional<juce::PopupMenu> channelWrapperMenu (juce::Component& root)
  6998. {
  6999. if (auto* frame = dynamic_cast<ChannelFrame*> (&root))
  7000. return frame->buildWrapperMenu();
  7001. for (auto* child : root.getChildren())
  7002. if (auto menu = channelWrapperMenu (*child))
  7003. return menu;
  7004. return std::nullopt;
  7005. }
  7006. std::unique_ptr<juce::Component> makeChannelHeaderControls (AudioEngine& engine, int channel)
  7007. {
  7008. if (channel < 0 || channel >= (int) engine.getSong().channels.size())
  7009. return nullptr;
  7010. return std::make_unique<ChannelHeaderControls> (engine, channel);
  7011. }
  7012. int channelHeaderControlsWidth() noexcept
  7013. {
  7014. return ChannelHeaderControls::preferredWidth;
  7015. }
  7016. std::unique_ptr<juce::Component> makeChannelFrame (AudioEngine& engine, int channel, int tab)
  7017. {
  7018. const auto kind = engine.getSong().channels[(std::size_t) channel].instrument;
  7019. auto frame = std::make_unique<ChannelFrame> (engine, ChannelRef::rack (channel), makeChannelSettingsPanel (engine, channel),
  7020. makeEnvelopePage (engine, ChannelRef::rack (channel), kind));
  7021. frame->showTab (tab < 0 ? frame->tabCount() - 1 : tab);
  7022. return frame;
  7023. }
  7024. std::unique_ptr<juce::Component> makeChannelSettingsPanel (AudioEngine& engine, int channel)
  7025. {
  7026. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::synth)
  7027. return std::make_unique<SynthPanel> (engine, ChannelRef::rack (channel));
  7028. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::controller)
  7029. {
  7030. if (parseKeyboardController (engine.getSong().channels[(std::size_t) channel].controllerState))
  7031. return makeKeyboardControllerEditor (engine, channel); // round 165c (it showed the Envelope Controller's read-only page)
  7032. return makeEnvelopeControllerEditor (engine, channel);
  7033. }
  7034. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::midiOut)
  7035. return makeMidiOutEditor (engine, channel);
  7036. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::soundfont)
  7037. return makeSoundFontEditor (engine, channel);
  7038. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::layer)
  7039. return makeLayerEditor (engine, channel);
  7040. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::dashboard)
  7041. return makeDashboardEditor (engine, channel);
  7042. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::voltage)
  7043. return makeVoltageControllerEditor (engine, channel);
  7044. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::vfx)
  7045. return makeVfxEditor (engine, channel);
  7046. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::fruitydance)
  7047. return makeDanceEditor (engine, channel); // round 165e
  7048. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::videoplayer)
  7049. return makeVideoPlayerEditor (engine, channel); // round 165g
  7050. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::wavetraveller)
  7051. return makeWaveTravellerEditor (engine, channel); // round 167f
  7052. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::fruityslicer)
  7053. return makeFruitySlicerEditor (engine, [channel] (Song& s) -> ChannelDef* {
  7054. return channel >= 0 && channel < (int) s.channels.size() ? &s.channels[(std::size_t) channel] : nullptr;
  7055. }, channel); // round 180c
  7056. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::slicex)
  7057. return makeSlicexEditor (engine, [channel] (Song& s) -> ChannelDef* {
  7058. return channel >= 0 && channel < (int) s.channels.size() ? &s.channels[(std::size_t) channel] : nullptr;
  7059. }, channel); // round 190r
  7060. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::fpc)
  7061. return makeFpcEditor (engine, [channel] (Song& s) -> ChannelDef* {
  7062. return channel >= 0 && channel < (int) s.channels.size() ? &s.channels[(std::size_t) channel] : nullptr;
  7063. }, channel); // round 190q
  7064. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::tetra)
  7065. return makeTetraEditor (engine, [channel] (Song& s) -> ChannelDef* {
  7066. return channel >= 0 && channel < (int) s.channels.size() ? &s.channels[(std::size_t) channel] : nullptr;
  7067. }, channel); // round 190hs
  7068. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::directwave)
  7069. return makeDirectWaveEditor (engine, [channel] (Song& s) -> ChannelDef* {
  7070. return channel >= 0 && channel < (int) s.channels.size() ? &s.channels[(std::size_t) channel] : nullptr;
  7071. }, channel); // round 190hz
  7072. if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::helix)
  7073. return makeHelixEditor (engine, [channel] (Song& s) -> ChannelDef* {
  7074. return channel >= 0 && channel < (int) s.channels.size() ? &s.channels[(std::size_t) channel] : nullptr;
  7075. }, channel); // round 190ja
  7076. if (const auto kind = engine.getSong().channels[(std::size_t) channel].instrument;
  7077. kind == InstrumentKind::sakura || kind == InstrumentKind::drumpad || kind == InstrumentKind::boobass
  7078. || kind == InstrumentKind::drumsynth || kind == InstrumentKind::harmless || kind == InstrumentKind::harmor
  7079. || kind == InstrumentKind::gms || kind == InstrumentKind::morphine
  7080. || kind == InstrumentKind::ogun || kind == InstrumentKind::minisynth
  7081. || kind == InstrumentKind::dx10 || kind == InstrumentKind::kepler || kind == InstrumentKind::keplerExo || kind == InstrumentKind::poizone
  7082. || kind == InstrumentKind::fruitkick || kind == InstrumentKind::bassdrum || kind == InstrumentKind::toxic
  7083. || kind == InstrumentKind::threeosc
  7084. || kind == InstrumentKind::autogun || kind == InstrumentKind::transistorbass
  7085. || kind == InstrumentKind::simsynth || kind == InstrumentKind::wasp || kind == InstrumentKind::plucked
  7086. || kind == InstrumentKind::beepmap || kind == InstrumentKind::sawer || kind == InstrumentKind::flkeys
  7087. || kind == InstrumentKind::granulizer || kind == InstrumentKind::drumaxx
  7088. || kind == InstrumentKind::slayer || kind == InstrumentKind::fruitydance || kind == InstrumentKind::sytrus || kind == InstrumentKind::pocketSuperSaw)
  7089. return std::make_unique<ModelPanel> (engine, ChannelRef::rack (channel));
  7090. return std::make_unique<SettingsPanel> (engine, ChannelRef::rack (channel));
  7091. }
  7092. bool hasNodeEditor (const ChannelDef& channel) noexcept
  7093. {
  7094. return channel.instrument == InstrumentKind::synth || channel.instrument == InstrumentKind::sampler || isModelKind (channel.instrument)
  7095. || channel.instrument == InstrumentKind::tetra || channel.instrument == InstrumentKind::helix; // rounds 190hs, 190ja
  7096. }
  7097. std::unique_ptr<juce::Component> makeNodeChannelFrame (AudioEngine& engine, std::function<ChannelDef* (Song&)> locate)
  7098. {
  7099. ChannelRef ref { std::move (locate), -1 };
  7100. const auto* def = ref.get (engine);
  7101. if (def == nullptr)
  7102. return nullptr;
  7103. auto page = makeInstrumentPage (engine, ref);
  7104. if (page == nullptr)
  7105. return nullptr;
  7106. const auto kind = def->instrument;
  7107. return std::make_unique<ChannelFrame> (engine, ref, std::move (page), makeEnvelopePage (engine, ref, kind));
  7108. }
  7109. std::function<void (int channel, wrappermenu::Spec&)>& channelWrapperItemsHandler()
  7110. {
  7111. static std::function<void (int, wrappermenu::Spec&)> handler;
  7112. return handler;
  7113. }
  7114. std::function<void (int)>& openMixerInsertHandler()
  7115. {
  7116. static std::function<void (int)> handler;
  7117. return handler;
  7118. }
  7119. std::function<void (const juce::File&)>& locateInBrowserHandler()
  7120. {
  7121. static std::function<void (const juce::File&)> handler;
  7122. return handler;
  7123. }
  7124. std::function<void (const juce::File&, InstrumentKind)>& openInNewChannelHandler()
  7125. {
  7126. static std::function<void (const juce::File&, InstrumentKind)> handler;
  7127. return handler;
  7128. }
  7129. namespace
  7130. {
  7131. SettingsPanel* findSamplerPage (juce::Component& c)
  7132. {
  7133. if (auto* p = dynamic_cast<SettingsPanel*> (&c))
  7134. return p;
  7135. for (auto* child : c.getChildren())
  7136. if (auto* p = findSamplerPage (*child))
  7137. return p;
  7138. return nullptr;
  7139. }
  7140. } // namespace
  7141. std::optional<juce::PopupMenu> samplerHistoryMenu (juce::Component& root)
  7142. {
  7143. if (auto* p = findSamplerPage (root))
  7144. return p->sampleHistoryMenuForShot();
  7145. return std::nullopt;
  7146. }
  7147. bool samplerPageTurn (juce::Component& root, const juce::String& what, double value, bool shift)
  7148. {
  7149. auto* p = findSamplerPage (root);
  7150. return p != nullptr && p->shotTurn (what, value, shift);
  7151. }
  7152. juce::String samplerPageQuery (juce::Component& root, const juce::String& what)
  7153. {
  7154. auto* p = findSamplerPage (root);
  7155. if (p == nullptr)
  7156. return {};
  7157. if (what.startsWith ("handleAt")) // round 190im: the handle a press at a handle's drawn place takes ("start", "loopStart", "loopEnd")
  7158. return p->handleProbeForShot (what.fromFirstOccurrenceOf ("handleAt", false, false));
  7159. if (what == "legacy")
  7160. return p->shotLegacyShown() ? "1" : "0";
  7161. if (what == "mode")
  7162. return p->shotModeText();
  7163. if (what == "scroll")
  7164. return juce::String (p->shotScrollStart(), 3);
  7165. if (what == "mulText" || what == "corner" || what == "waveHint")
  7166. return p->shotText (what);
  7167. return p->shotEnabled (what) ? "1" : "0";
  7168. }
  7169. namespace
  7170. {
  7171. template <typename T>
  7172. T* findChild (juce::Component& c)
  7173. {
  7174. if (auto* p = dynamic_cast<T*> (&c))
  7175. return p;
  7176. for (auto* child : c.getChildren())
  7177. if (auto* p = findChild<T> (*child))
  7178. return p;
  7179. return nullptr;
  7180. }
  7181. } // namespace
  7182. std::optional<juce::PopupMenu> channelPresetMenu (juce::Component& root)
  7183. {
  7184. if (auto* bar = findChild<ChannelPresetBar> (root))
  7185. return bar->buildMenu();
  7186. if (auto* synth = findChild<SynthPanel> (root))
  7187. return synth->presetBoxMenu();
  7188. return std::nullopt;
  7189. }
  7190. bool channelPresetSave (juce::Component& root, const juce::String& name)
  7191. {
  7192. if (auto* bar = findChild<ChannelPresetBar> (root))
  7193. return bar->saveNamed (name);
  7194. if (auto* synth = findChild<SynthPanel> (root))
  7195. return synth->saveNamed (name);
  7196. return false;
  7197. }
  7198. juce::String channelPresetName (juce::Component& root)
  7199. {
  7200. if (auto* bar = findChild<ChannelPresetBar> (root))
  7201. return bar->shownName();
  7202. return {};
  7203. }
  7204. std::optional<juce::PopupMenu> samplerWaveMenu (juce::Component& root)
  7205. {
  7206. auto* p = findSamplerPage (root);
  7207. if (p == nullptr)
  7208. return std::nullopt;
  7209. return p->waveMenuForShot();
  7210. }
  7211. bool samplerFileRowPress (juce::Component& root, int button)
  7212. {
  7213. auto* p = findSamplerPage (root);
  7214. if (p == nullptr)
  7215. return false;
  7216. p->pressFileRow (button);
  7217. return true;
  7218. }
  7219. } // namespace lynx