BrowserComponent.cpp 339 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812
  1. #include "ui/TiltViewport.h"
  2. #include "ui/TypeAhead.h"
  3. #include "ui/DemoMode.h" // round 190pl
  4. #include "ui/PluginPresetMenu.h"
  5. #include "ui/ExternalDrag.h"
  6. #include "ui/GeneratorPresetMenu.h"
  7. #include "ui/FileChoosers.h"
  8. #include "ui/QuickPick.h"
  9. #include "ui/PluginThumbs.h"
  10. #include "engine/GeneratorCatalog.h"
  11. #include "engine/FlStudio.h"
  12. #include "ui/BrowserComponent.h"
  13. #include "core/UserFolders.h"
  14. #include "core/PluginDbFolder.h"
  15. #include "ui/AudioClipboard.h"
  16. #include "ui/SpeechDialog.h"
  17. #include "ui/UiTrace.h"
  18. #include "core/ControlSurface.h"
  19. #include "core/EffectPresets.h"
  20. #include "core/FlEffects.h"
  21. #include "core/PresetCycle.h"
  22. #include "ui/PluginHeader.h"
  23. #include "core/NativeEngines.h"
  24. #include "core/VoltageController.h"
  25. #include "core/FlpImport.h"
  26. #include "core/ProjectContents.h"
  27. #include "core/FactoryContent.h"
  28. #include "core/FactoryLoops.h" // (rollup 0.1.30 step 6: LYNX content in the Loop Browser)
  29. #include "core/LayoutStyle.h"
  30. #include "core/MidiDrop.h"
  31. #include "core/SoundLibrary.h"
  32. #include "core/SearchIndex.h"
  33. #include "core/SearchQuery.h"
  34. #include "core/SearchService.h"
  35. #include "core/SampleFiles.h"
  36. #include "core/SampleSimilarity.h"
  37. #include "engine/SampleLibrary.h"
  38. #include "core/ValueMath.h"
  39. #include "core/Vfx.h"
  40. #include "platform/Paths.h"
  41. #include "platform/CrashGuard.h"
  42. #include "core/FolderWatcher.h"
  43. #include <atomic>
  44. #include <chrono>
  45. #include <cstdio>
  46. #include <thread>
  47. #if JUCE_WINDOWS
  48. #ifndef NOMINMAX
  49. #define NOMINMAX
  50. #endif
  51. #ifndef WIN32_LEAN_AND_MEAN
  52. #define WIN32_LEAN_AND_MEAN
  53. #endif
  54. #include <windows.h>
  55. #else
  56. #include <sys/resource.h>
  57. #include <unistd.h>
  58. #if JUCE_LINUX
  59. #include <sys/syscall.h>
  60. #endif
  61. #endif
  62. #include <deque>
  63. #include <mutex>
  64. #include <unordered_map>
  65. #include "engine/PluginHost.h"
  66. #include "engine/Text.h"
  67. #include "ui/HintBar.h"
  68. #include "ui/PluginWindow.h" // round 190iz (the focused plugin window)
  69. #include "ui/I18n.h"
  70. #include "ui/Icons.h"
  71. #include "ui/PlaylistComponent.h"
  72. #include "ui/Theme.h"
  73. #include "ui/LabelFont.h"
  74. #include "ui/ValueControl.h"
  75. #include "ui/WaveformView.h"
  76. #include "ui/AudioEditor.h"
  77. #include "ui/AutomationUi.h"
  78. #include "ui/RemoteControl.h"
  79. #include "ui/ChannelRackComponent.h"
  80. #include "ui/MixerComponent.h"
  81. #include "ui/SoundFontEditor.h"
  82. #include "ui/SamplerImportUi.h"
  83. #include "ui/ToolWindow.h"
  84. #include "ui/WorkflowExtras.h" // round 190iu (issue #191.6)
  85. #include "ui/LoopInfo.h" // round 190kx
  86. #include "core/MidiPreview.h" // round 190qi
  87. #include "engine/MidiFileIo.h" // round 190qi
  88. namespace lynx
  89. {
  90. juce::ChangeBroadcaster& loopLengthsRead(); // (round 190mf, ui/LoopBrowserParts.inc: the Simple loop rows' lengths read)
  91. namespace
  92. {
  93. bool isAudio (const juce::File& f)
  94. {
  95. return SampleLibrary::isSampleFile (f);
  96. }
  97. bool isListed (const juce::File& f)
  98. {
  99. return f.hasFileExtension ("wav;flac;ogg;mp3;aif;aiff;wv;ncw;mid;midi;lynx;flp;als;flm;fst;sf2;sf3;sfz;dwp;dwb;gig;mod;xm;s3m;it");
  100. }
  101. constexpr int maxResults = 500;
  102. constexpr int maxLoops = 20000; // round gaps190kf: the files the Loop Browser describes at most
  103. constexpr int maxSimilar = 100; // "Find similar samples" lists the nearest 100
  104. juce::Array<juce::File> childrenOf (const juce::File& folder)
  105. {
  106. #if JUCE_MAC
  107. // JUCE's macOS iterator makes an NSURL of every entry to read its hidden flag, and a name NSString rejects
  108. // throws an Objective-C exception that ends the app (issue #42). readdir has no such step; names that are
  109. // not valid UTF-8 are skipped, the rest precomposed like JUCE does.
  110. // The listing itself is search::listFolderNames (JUCE-free, so the core tests run it on odd names).
  111. juce::Array<juce::File> children;
  112. for (const auto& name : search::listFolderNames (folder.getFullPathName().toStdString()))
  113. children.add (folder.getChildFile (juce::String::fromUTF8 (name.data(), (int) name.size()).convertToPrecomposedUnicode()));
  114. return children;
  115. #else
  116. return folder.findChildFiles (juce::File::findFilesAndDirectories, false, "*");
  117. #endif
  118. }
  119. search::FileSystem diskFileSystem()
  120. {
  121. search::FileSystem fs;
  122. fs.separator = juce::File::getSeparatorChar() == '\\' ? '\\' : '/';
  123. fs.folderTime = [] (const std::string& path) -> std::int64_t {
  124. const juce::File folder (juce::String::fromUTF8 (path.c_str()));
  125. return folder.isDirectory() ? folder.getLastModificationTime().toMilliseconds() : -1;
  126. };
  127. fs.list = [] (const std::string& path) {
  128. search::FolderListing listing;
  129. const juce::File folder (juce::String::fromUTF8 (path.c_str()));
  130. if (! folder.isDirectory())
  131. return listing;
  132. listing.exists = true;
  133. listing.time = folder.getLastModificationTime().toMilliseconds();
  134. auto children = childrenOf (folder);
  135. children.sort();
  136. for (const auto& c : children)
  137. {
  138. if (c.isDirectory())
  139. {
  140. // junctions and links (Windows' "My Music" inside Documents points back to itself) are not followed
  141. if (! c.isSymbolicLink())
  142. listing.subfolders.push_back (c.getFileName().toStdString());
  143. }
  144. else if (isListed (c))
  145. listing.files.push_back (c.getFileName().toStdString());
  146. }
  147. return listing;
  148. };
  149. return fs;
  150. }
  151. std::vector<std::string> toPaths (const juce::Array<juce::File>& folders)
  152. {
  153. std::vector<std::string> paths;
  154. for (const auto& f : folders)
  155. paths.push_back (f.getFullPathName().toStdString());
  156. return paths;
  157. }
  158. Icon iconFor (const juce::File& f, bool folder)
  159. {
  160. if (folder)
  161. return Icon::folder;
  162. if (isAudio (f))
  163. return Icon::audioFile;
  164. if (f.hasFileExtension ("mid;midi"))
  165. return Icon::pianoRoll;
  166. if (f.hasFileExtension ("lynx;flp;als;flm"))
  167. return Icon::project;
  168. if (f.hasFileExtension ("fst;sf2;sf3;sfz;lynxpreset;fxp;fxb;vstpreset;adv;adg;dwp;dwb;gig")) // (round 190hr: Live device / rack presets; round 190ii: sampler instruments)
  169. return Icon::preset;
  170. return Icon::file;
  171. }
  172. // The hint for a file or folder row: what the mouse can do with it.
  173. juce::String rowHint (const juce::File& f, bool folder, bool expanded)
  174. {
  175. if (folder)
  176. return (expanded ? tr ("Folder: [LMB] close") : tr ("Folder: [LMB] open")) + " " + tr ("[RMB] menu (collapse all, show in the file manager)");
  177. if (isAudio (f))
  178. return tr ("Sample: [LMB] preview [2xLMB] new channel drag to the Channel Rack or the Playlist [Enter] into the selected channel "
  179. "[Shift][Up] / [Shift][Down] swap through the files");
  180. if (f.hasFileExtension ("mid;midi"))
  181. // (issue #287, round 190rc: where else a MIDI file goes, as FL takes it, and the Playlist's LYNX extra)
  182. return mididrop::playlistTakes (layoutstyle::current() == layoutstyle::Style::clipLaunch)
  183. ? tr ("MIDI file: [2xLMB] open it as a project drag onto the Playlist (a clip), the Channel Rack or the Piano roll to import it")
  184. : tr ("MIDI file: [2xLMB] open it as a project drag onto the Channel Rack or the Piano roll to import it (onto the Playlist: "
  185. "Playlist menu › \"MIDI files dropped on the Playlist become pattern clips\")");
  186. if (f.hasFileExtension ("lynx;flp;als;flm"))
  187. return tr ("Project: [2xLMB] open it");
  188. if (f.hasFileExtension ("lynxtrack") || (f.hasFileExtension ("fst") && f.getFullPathName().containsIgnoreCase ("Mixer presets")))
  189. return tr ("Mixer preset: [2xLMB] load it onto the selected mixer tracks drag onto a mixer track (onto the empty mixer space: a new track)");
  190. if (f.hasFileExtension ("fst"))
  191. return tr ("Preset: [2xLMB] new channel with it (FL synth presets) drag onto a mixer insert: effect preset");
  192. if (f.hasFileExtension ("lynxpreset") && f.isAChildOf (genpresetui::root()))
  193. return tr ("Generator preset: [2xLMB] new channel with it");
  194. if (f.hasFileExtension ("lynxpreset;fxp;fxb;vstpreset"))
  195. return tr ("Plugin preset: [2xLMB] load it into its plugin (an open plugin window, or the selected channel's plugin)");
  196. if (f.hasFileExtension ("sfz"))
  197. return tr ("SFZ instrument: [LMB] preview [2xLMB] new LYNX Soundfont channel (or into the selected one) drag to the Channel Rack");
  198. if (f.hasFileExtension ("sf2;sf3;sfz"))
  199. return tr ("SoundFont: [LMB] preview its first preset [2xLMB] new LYNX Soundfont channel (or into the selected one) drag to the Channel Rack");
  200. if (isSamplerInstrumentFile (f))
  201. return tr ("Sampler instrument (DirectWave, GigaStudio): [2xLMB] new DirectWave channel [Enter] into the selected DirectWave channel "
  202. "drag to the Channel Rack");
  203. return {};
  204. }
  205. // A user / channel colour made readable as text and icons on the Browser's dark rows.
  206. juce::Colour readable (juce::Colour c)
  207. {
  208. return c.withMultipliedSaturation (0.8f).withBrightness (juce::jlimit (0.72f, 0.92f, c.getBrightness() + 0.15f));
  209. }
  210. // The Current project's sections, in FL's order (REA_rodada115).
  211. enum class Category
  212. {
  213. history,
  214. patterns,
  215. effects,
  216. generators,
  217. automation,
  218. initialized, // FL's "Initialized controls" (REA round 146)
  219. samples
  220. };
  221. constexpr Category categories[] = { Category::history, Category::patterns, Category::effects, Category::generators,
  222. Category::automation, Category::initialized, Category::samples };
  223. juce::String categoryName (Category c)
  224. {
  225. switch (c)
  226. {
  227. case Category::history: return tr ("History");
  228. case Category::patterns: return tr ("Patterns");
  229. case Category::effects: return tr ("Effects");
  230. case Category::generators: return tr ("Generators");
  231. case Category::automation: return tr ("Automation");
  232. case Category::initialized: return tr ("Initialized controls");
  233. case Category::samples: return tr ("Audio files");
  234. }
  235. return {};
  236. }
  237. juce::String categoryHint (Category c)
  238. {
  239. switch (c)
  240. {
  241. case Category::history: return tr ("Undo history of this project: [LMB] go back to that step");
  242. case Category::patterns: return tr ("Patterns of this project, in their colours");
  243. case Category::effects: return tr ("Effects in use, with the insert they sit on");
  244. case Category::generators: return tr ("Generators in use (the Channel Rack's channels), with the insert they play into");
  245. case Category::automation: return tr ("Automation clips of this project");
  246. case Category::initialized: return tr ("Initialized controls: to be reset when the song starts (a control's menu > Init song with this position)");
  247. case Category::samples: return tr ("Audio files used by this project (samples, audio clips), in the colour of the channel that plays them");
  248. }
  249. return {};
  250. }
  251. Icon categoryIcon (Category c)
  252. {
  253. switch (c)
  254. {
  255. case Category::history: return Icon::undo;
  256. case Category::patterns: return Icon::pattern;
  257. case Category::effects: return Icon::mixer;
  258. case Category::generators: return Icon::keyboard;
  259. case Category::automation: return Icon::automate;
  260. case Category::initialized: return Icon::automate;
  261. case Category::samples: return Icon::audioFile;
  262. }
  263. return Icon::folder;
  264. }
  265. // Each top-level folder has its own colour (FL colours its Browser's folders by kind; LYNX uses its own set).
  266. juce::Colour rootColour (int index)
  267. {
  268. static const juce::Colour colours[] = { juce::Colour (0xff6ea8fe), juce::Colour (0xff3ddc84), juce::Colour (0xffe58fd0),
  269. juce::Colour (0xffb39ddb), juce::Colour (0xffb39ddb), juce::Colour (0xfff5b942),
  270. juce::Colour (0xff4cc9c0), juce::Colour (0xfff2a65a), juce::Colour (0xff9fb7d0) };
  271. return index >= 0 && index < (int) std::size (colours) ? colours[index] : juce::Colour (0xff8fd18c);
  272. }
  273. } // namespace
  274. namespace
  275. {
  276. // A scanned JSFX script's key (its plugin list identifier, "JSFX-<name>-...": round 190pj)
  277. bool isJsfxKey (const std::string& key) { return key.rfind ("JSFX-", 0) == 0; }
  278. // The plugin being dragged from the Plugin database (one drag at a time; message thread).
  279. struct DraggedPlugin
  280. {
  281. std::function<std::optional<ChannelDef>()> generator;
  282. std::function<std::optional<EffectSlot>()> effect;
  283. };
  284. DraggedPlugin& draggedPlugin()
  285. {
  286. static DraggedPlugin d;
  287. return d;
  288. }
  289. } // namespace
  290. // --- search: the process's search worker ------------------------------------------------------------
  291. // Round 190hd: the indexer process (REA 190hc action 5, parts 2-3, after Live's Indexer: "StartIndex" runs the library
  292. // indexer as a separate process at a low priority and rescans on file-system events). The Browser's index of its
  293. // folders (core/SearchIndex.h) is kept up to date by `LYNX --browser-indexer <pid> <roots file>`: a child at the
  294. // lowest priority (Windows: idle class + background mode, so its disk reads are low priority too; elsewhere nice 19
  295. // and, on Linux, the idle I/O class) that walks the folders whose times changed, writes the index file, tells this
  296. // process, and then sleeps on the system's change notifications for those trees (core/FolderWatcher.h) until the
  297. // next change. It never shares a thread, a lock or a frame with the UI; it ends with its parent. This process then
  298. // saves nothing and only takes in what the child wrote (search::Service::setExternalIndexer / reload). A child that
  299. // cannot start or ends: the in-process pass as before.
  300. namespace
  301. {
  302. juce::File indexFile() { return platform::settingsFile ("browser-index.txt"); }
  303. juce::File indexRootsFile() { return platform::settingsFile ("browser-index-roots.txt"); }
  304. std::string loadIndexText()
  305. {
  306. const auto f = indexFile();
  307. juce::MemoryBlock data;
  308. if (! f.existsAsFile() || f.getSize() > 256 * 1024 * 1024 || ! f.loadFileAsData (data))
  309. return std::string();
  310. return std::string (static_cast<const char*> (data.getData()), data.getSize());
  311. }
  312. void saveIndexText (const std::string& text)
  313. {
  314. const auto f = indexFile();
  315. const auto temp = f.getSiblingFile (f.getFileName() + ".tmp");
  316. if (temp.replaceWithData (text.data(), text.size()))
  317. temp.moveFileTo (f);
  318. }
  319. #if JUCE_WINDOWS
  320. juce::String indexerSignalName (juce::int64 parentPid) { return "Local\\LYNX-browser-index-" + juce::String (parentPid); }
  321. #endif
  322. juce::int64 thisProcessId()
  323. {
  324. #if JUCE_WINDOWS
  325. return (juce::int64) GetCurrentProcessId();
  326. #else
  327. return (juce::int64) getpid();
  328. #endif
  329. }
  330. class IndexerProcess
  331. {
  332. public:
  333. explicit IndexerProcess (search::Service& s) : service (s) {}
  334. ~IndexerProcess() { stop(); }
  335. // starts the child for these folders (once; again when they change); false: it could not start
  336. bool start (const std::vector<std::string>& folders)
  337. {
  338. if (watcher.joinable() && folders == roots && child.isRunning())
  339. return true;
  340. stop();
  341. roots = folders;
  342. juce::StringArray lines;
  343. for (const auto& r : roots)
  344. lines.add (juce::String::fromUTF8 (r.c_str()));
  345. if (! indexRootsFile().replaceWithText (lines.joinIntoString ("\n") + "\n"))
  346. return false;
  347. #if JUCE_WINDOWS
  348. signal = CreateEventW (nullptr, FALSE, FALSE, indexerSignalName (thisProcessId()).toWideCharPointer());
  349. if (signal == nullptr)
  350. return false;
  351. #endif
  352. const juce::StringArray args { juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName(), "--browser-indexer",
  353. juce::String (thisProcessId()), indexRootsFile().getFullPathName() };
  354. #if JUCE_WINDOWS
  355. const auto started = child.start (args, 0);
  356. #else
  357. const auto started = child.start (args, juce::ChildProcess::wantStdOut);
  358. #endif
  359. if (! started)
  360. {
  361. closeSignal();
  362. return false;
  363. }
  364. service.setExternalIndexer (true);
  365. stopping = false;
  366. watcher = std::thread ([this] { watch(); });
  367. return true;
  368. }
  369. void stop()
  370. {
  371. stopping = true;
  372. if (child.isRunning())
  373. child.kill(); // (our own child; a write it was making is a temporary file, replaced by the next)
  374. #if JUCE_WINDOWS
  375. if (signal != nullptr)
  376. SetEvent (signal);
  377. #endif
  378. if (watcher.joinable())
  379. watcher.join();
  380. closeSignal();
  381. service.setExternalIndexer (false);
  382. }
  383. private:
  384. // (its own thread) the child's news: the index file was written
  385. void watch()
  386. {
  387. for (;;)
  388. {
  389. #if JUCE_WINDOWS
  390. const auto woken = WaitForSingleObject (signal, 2000) == WAIT_OBJECT_0;
  391. if (stopping)
  392. return;
  393. if (woken)
  394. service.reload();
  395. if (child.isRunning())
  396. continue;
  397. #else
  398. char c = 0;
  399. if (child.readProcessOutput (&c, 1) == 1) // (blocks; one byte at a time: a line is a write)
  400. {
  401. if (c == '\n')
  402. service.reload();
  403. continue;
  404. }
  405. if (stopping)
  406. return;
  407. #endif
  408. // the child ended on its own (a crash): this process indexes again, as before
  409. service.setExternalIndexer (false);
  410. service.refresh (roots);
  411. return;
  412. }
  413. }
  414. void closeSignal()
  415. {
  416. #if JUCE_WINDOWS
  417. if (signal != nullptr)
  418. CloseHandle (signal);
  419. signal = nullptr;
  420. #endif
  421. }
  422. search::Service& service;
  423. juce::ChildProcess child;
  424. std::vector<std::string> roots;
  425. std::atomic<bool> stopping { false };
  426. #if JUCE_WINDOWS
  427. HANDLE signal = nullptr;
  428. #endif
  429. std::thread watcher;
  430. };
  431. // (the child) the lowest priority for the CPU and the disk
  432. void lowerIndexerPriority()
  433. {
  434. #if JUCE_WINDOWS
  435. // background mode first (low disk and memory priority), then the idle class (the order: setting background mode
  436. // left the class at Normal, measured)
  437. SetPriorityClass (GetCurrentProcess(), PROCESS_MODE_BACKGROUND_BEGIN);
  438. SetPriorityClass (GetCurrentProcess(), IDLE_PRIORITY_CLASS);
  439. #else
  440. setpriority (PRIO_PROCESS, 0, 19);
  441. #if JUCE_LINUX
  442. syscall (SYS_ioprio_set, 1 /* IOPRIO_WHO_PROCESS */, 0, 3 << 13 /* IOPRIO_CLASS_IDLE */);
  443. #endif
  444. #endif
  445. }
  446. // (the child) returns when the parent process has ended
  447. void waitForParentEnd (juce::int64 parentPid)
  448. {
  449. #if JUCE_WINDOWS
  450. if (const auto parent = OpenProcess (SYNCHRONIZE, FALSE, (DWORD) parentPid))
  451. {
  452. WaitForSingleObject (parent, INFINITE);
  453. CloseHandle (parent);
  454. }
  455. #else
  456. while (getppid() == (pid_t) parentPid)
  457. std::this_thread::sleep_for (std::chrono::seconds (2));
  458. #endif
  459. }
  460. } // namespace
  461. int BrowserComponent::runIndexerProcess (const juce::StringArray& args)
  462. {
  463. const auto i = args.indexOf ("--browser-indexer");
  464. const auto parentPid = args[i + 1].getLargeIntValue();
  465. const juce::File rootsFile (args[i + 2].unquoted());
  466. lowerIndexerPriority();
  467. std::thread ([parentPid] {
  468. waitForParentEnd (parentPid);
  469. crashguard::exitNow (0);
  470. }).detach();
  471. std::vector<std::string> roots;
  472. juce::StringArray lines;
  473. lines.addLines (rootsFile.loadFileAsString());
  474. for (const auto& line : lines)
  475. if (line.isNotEmpty() && juce::File::isAbsolutePath (line) && juce::File (line).isDirectory())
  476. roots.push_back (line.toStdString());
  477. #if JUCE_WINDOWS
  478. const auto signal = OpenEventW (EVENT_MODIFY_STATE, FALSE, indexerSignalName (parentPid).toWideCharPointer());
  479. #endif
  480. search::Service::Callbacks cb;
  481. cb.load = loadIndexText;
  482. cb.save = saveIndexText;
  483. cb.indexChanged = [&] { // (the file is written by then)
  484. #if JUCE_WINDOWS
  485. if (signal != nullptr)
  486. SetEvent (signal);
  487. #else
  488. std::fputs ("changed\n", stdout);
  489. std::fflush (stdout);
  490. #endif
  491. };
  492. search::Service service (diskFileSystem(), std::move (cb));
  493. if (! roots.empty())
  494. service.refresh (roots);
  495. // then a pass after each change in those trees (a copy of a whole library: once it has been quiet for 2 s)
  496. folderwatch::Options options;
  497. options.quietMs = 2000;
  498. options.maxDelayMs = 10000;
  499. options.pollMs = 30000; // (where there are no notifications: a tree's folder times, every 30 s)
  500. folderwatch::Watcher watcher (roots, [&service, roots] { service.refresh (roots); }, options);
  501. for (;;)
  502. std::this_thread::sleep_for (std::chrono::hours (1)); // (ends with the parent: waitForParentEnd)
  503. }
  504. // The Browser's search index and its worker (core/SearchService.h, round 162): one per process while a Browser exists,
  505. // the index kept in the settings folder between sessions. Its news reach the Browsers through two broadcasters (they
  506. // are thread-safe and coalesce); the worker is joined (never killed) before they go.
  507. struct BrowserComponent::SearchShared
  508. {
  509. juce::ChangeBroadcaster statusChanged, indexChanged;
  510. std::unique_ptr<search::Service> service; // (last: goes first)
  511. std::unique_ptr<IndexerProcess> indexer; // (round 190hd; before the service)
  512. ~SearchShared()
  513. {
  514. indexer.reset();
  515. service.reset();
  516. }
  517. static juce::File file() { return indexFile(); }
  518. // the background pass over these folders: by the indexer process where it may run, else here (round 190hd)
  519. void refreshInBackground (std::vector<std::string> roots)
  520. {
  521. if (allowIndexerProcess && juce::SystemStats::getEnvironmentVariable ("LYNX_INDEXER_PROCESS", {}) != "0")
  522. {
  523. if (indexer == nullptr)
  524. indexer = std::make_unique<IndexerProcess> (*service);
  525. if (indexer->start (roots))
  526. return;
  527. }
  528. service->refresh (std::move (roots));
  529. }
  530. static std::shared_ptr<SearchShared> get()
  531. {
  532. static std::weak_ptr<SearchShared> current; // (message thread)
  533. if (auto s = current.lock())
  534. return s;
  535. auto s = std::make_shared<SearchShared>();
  536. search::Service::Callbacks cb;
  537. cb.load = loadIndexText;
  538. cb.save = saveIndexText;
  539. cb.statusChanged = [raw = s.get()] { raw->statusChanged.sendChangeMessage(); };
  540. cb.indexChanged = [raw = s.get()] { raw->indexChanged.sendChangeMessage(); };
  541. s->service = std::make_unique<search::Service> (diskFileSystem(), std::move (cb));
  542. current = s;
  543. return s;
  544. }
  545. };
  546. // "Find similar samples" (round 190as): the analysis of the Browser's samples and its worker (core/SampleSimilarity.h),
  547. // one per process while a Browser exists, the index kept in the settings folder between sessions. The worker has the
  548. // lowest priority, rests as long as it works and waits while LYNX plays, records or renders.
  549. struct BrowserComponent::SimilarShared
  550. {
  551. juce::ChangeBroadcaster statusChanged;
  552. SampleLibrary library; // its own readers: nothing goes into the engine's sample cache
  553. std::unique_ptr<similarity::Service> service; // (last: goes first)
  554. bool passAsked = false; // the background pass was started in this session (message thread)
  555. ~SimilarShared() { service.reset(); }
  556. static juce::File file() { return platform::settingsFile ("browser-similar.idx"); }
  557. static std::shared_ptr<SimilarShared> get (AudioEngine& engine)
  558. {
  559. static std::weak_ptr<SimilarShared> current; // (message thread)
  560. if (auto s = current.lock())
  561. return s;
  562. auto s = std::make_shared<SimilarShared>();
  563. similarity::Service::Callbacks cb;
  564. cb.fs = diskFileSystem();
  565. cb.stat = [] (const std::string& path, std::int64_t& size, std::int64_t& time) {
  566. const juce::File f (juce::String::fromUTF8 (path.c_str()));
  567. if (! f.existsAsFile())
  568. return false;
  569. size = f.getSize();
  570. time = f.getLastModificationTime().toMilliseconds();
  571. return true;
  572. };
  573. cb.decode = [raw = s.get()] (const std::string& path, double seconds, std::vector<float>& mono, double& rate) {
  574. return raw->library.readMono (juce::File (juce::String::fromUTF8 (path.c_str())), seconds, mono, rate);
  575. };
  576. cb.accepts = [] (const std::string& name) {
  577. const auto dot = name.find_last_of ('.');
  578. if (dot == std::string::npos)
  579. return false;
  580. const auto extension = name.substr (dot + 1);
  581. return isSampleExtension (extension) && extension.size() != 6; // (not .speech: it has no audio of its own)
  582. };
  583. cb.load = [] {
  584. const auto f = file();
  585. juce::MemoryBlock data;
  586. if (! f.existsAsFile() || f.getSize() > 64 * 1024 * 1024 || ! f.loadFileAsData (data))
  587. return std::string();
  588. return std::string (static_cast<const char*> (data.getData()), data.getSize());
  589. };
  590. cb.save = [] (const std::string& bytes) {
  591. const auto f = file();
  592. const auto temp = f.getSiblingFile (f.getFileName() + ".tmp");
  593. if (temp.replaceWithData (bytes.data(), bytes.size()))
  594. temp.moveFileTo (f);
  595. };
  596. cb.statusChanged = [raw = s.get()] { raw->statusChanged.sendChangeMessage(); };
  597. // (the engine outlives every Browser; these are atomics)
  598. cb.shouldPause = [&engine] { return engine.bounceStillPlaying() || engine.isRecording() || AudioEngine::offlineRendersRunning().load() > 0; };
  599. s->service = std::make_unique<similarity::Service> (std::move (cb));
  600. current = s;
  601. return s;
  602. }
  603. };
  604. // A click anywhere outside the search box (another panel, the toolbar, the Browser's own list) takes the keyboard
  605. // back from it, so Space plays / stops again (issue #9; FL ends typing in its search field the same way).
  606. class BrowserComponent::FocusWatcher final : public juce::MouseListener
  607. {
  608. public:
  609. explicit FocusWatcher (BrowserComponent& b) : browser (b) { juce::Desktop::getInstance().addGlobalMouseListener (this); }
  610. ~FocusWatcher() override { juce::Desktop::getInstance().removeGlobalMouseListener (this); }
  611. void mouseDown (const juce::MouseEvent& e) override
  612. {
  613. auto* clicked = e.eventComponent;
  614. if (! browser.isTypingInSearch() || clicked == nullptr)
  615. return;
  616. if (clicked == &browser.searchBox || browser.searchBox.isParentOf (clicked))
  617. return;
  618. // a menu (the box's own right-click menu: Paste...) keeps it
  619. if (clicked->getTopLevelComponent() != browser.getTopLevelComponent() && clicked->getTopLevelComponent()->isAlwaysOnTop()
  620. && dynamic_cast<juce::ResizableWindow*> (clicked->getTopLevelComponent()) == nullptr)
  621. return;
  622. browser.leaveSearchBox();
  623. }
  624. private:
  625. BrowserComponent& browser;
  626. };
  627. // --- the tree (and, flat, the search results) ---------------------------------------------------------
  628. // round 190iz: the tab icons, the row star, the TAGS button, the tags panel, the Live sidebar
  629. #include "ui/BrowserTagsLive.inc"
  630. #include "ui/BrowserQol190qi.inc" // round 190qi: MIDI preview, search completion, file types
  631. #include "ui/LoopBrowserPanel.inc" // round gaps190kf
  632. class BrowserComponent::FileTree final : public juce::Component,
  633. public ui::HintSource,
  634. public demo::CellSource,
  635. public juce::FileDragAndDropTarget
  636. {
  637. public:
  638. // round 190pl (--demo): a row is a cell (column = the list's row, the cell's row is ignored), so a script can click or
  639. // drag it; "name" finds the row by its label or file name
  640. juce::Rectangle<int> demoCellBounds (int, int row) const override
  641. {
  642. if (! juce::isPositiveAndBelow (row, (int) rows.size()))
  643. return {};
  644. return { 0, row * rowHeight, getWidth(), rowHeight };
  645. }
  646. // (the first row whose label, file name or file name without its extension is `name`)
  647. juce::Rectangle<int> demoCellNamed (int, const juce::String& name) const override
  648. {
  649. for (int i = 0; i < (int) rows.size(); ++i)
  650. if (const auto* n = rows[(std::size_t) i]; n->label == name || n->file.getFileName() == name || n->file.getFileNameWithoutExtension() == name)
  651. return demoCellBounds (0, i);
  652. return {};
  653. }
  654. // FL layout: 24 px rows (design slice FM-S7 / finding FM-9: FL's tree rows are 23 px with a larger face than LYNX's
  655. // 22 px ones); the Clip-launch layout's Live-style list: 19 px (Live's row pitch, CL-22). Round 190iz.
  656. static constexpr int flRowHeight = 24, liveRowHeight = 19;
  657. int rowHeight = flRowHeight;
  658. void setLiveRows (bool live)
  659. {
  660. const auto h = live ? liveRowHeight : flRowHeight;
  661. if (h == rowHeight)
  662. return;
  663. rowHeight = h;
  664. updateSize();
  665. repaint();
  666. }
  667. // the hover star's box on a row (FL: "the star that appears at the end of the content"); empty: none there
  668. juce::Rectangle<int> starBox (int row) const
  669. {
  670. if (! juce::isPositiveAndBelow (row, (int) rows.size()) || itemOf (*rows[(std::size_t) row]).empty())
  671. return {};
  672. return { getWidth() - 20, row * rowHeight, 16, rowHeight };
  673. }
  674. FileTree (BrowserComponent& b, bool isFlat) : browser (b), flat (isFlat)
  675. {
  676. setWantsKeyboardFocus (false);
  677. setMouseClickGrabsKeyboardFocus (false);
  678. }
  679. enum class Kind
  680. {
  681. fsFolder, // a folder on disk (top-level ones carry their own name and colour)
  682. file, // a file on disk
  683. project, // "Current project"
  684. category, // one of its sections
  685. item, // something of the project (pattern, sample, generator, effect, automation clip, undo step)
  686. plugins, // the Plugin database and its folders (round 142): built-in, FL engines, installed plugins
  687. plugin, // one of its plugins (double-click adds it)
  688. collection, // a collection's heading in the STARRED tab (round 190ce): its items are its children
  689. factory // round 190ke: "LYNX content" and its folders (the Simple layout): LYNX's own sounds, beats, chains
  690. };
  691. struct Node
  692. {
  693. Kind kind = Kind::file;
  694. juce::File file;
  695. juce::Array<juce::File> also; // fsFolder: more folders listed as this one (a merged root and its shared subfolders, round 178a)
  696. bool folder = false, expanded = false, loaded = false;
  697. int depth = 0;
  698. Node* parent = nullptr;
  699. std::vector<std::unique_ptr<Node>> children;
  700. juce::String label, detail; // display name (empty: the file's) and the dimmed detail after it
  701. juce::String loopText; // round 190kx: a loop's bars, tempo and key (the Simple layout's rows; empty: not known)
  702. bool loopKnown = false; // (the worker answered for this file)
  703. juce::Colour colour; // transparent: the default
  704. Icon icon = Icon::none; // none: by file type
  705. Category category = Category::samples;
  706. projectcontents::Item item; // kind == item (history: item.index = the step)
  707. bool history = false, missing = false, current = false;
  708. bool initial = false; // an initialized control (item.index = into Song::initialValues)
  709. std::function<void()> activate; // kind == plugin: adds it
  710. // kind == plugin: what it adds (one of them), also when it is dragged (round 162)
  711. std::function<std::optional<ChannelDef>()> generator;
  712. std::function<std::optional<EffectSlot>()> effect;
  713. std::string pluginKey; // kind == plugin: what a user name is stored under (ui/QuickPick.h, issue #11)
  714. juce::String original; // kind == plugin: the name before the user renamed it
  715. // round 166f (issue #16): kind == plugins — 0 the Effects folder or one of the user's effect folders, 1 the
  716. // Generators' (-1 the other database folders); userFolder = the user's folder path ("" = Effects / Generators)
  717. int folderKind = -1;
  718. std::string userFolder;
  719. // round 190bj (issue B4): LYNX's own groups under Effects / Generators — the format folder of their Installed
  720. // entries ("LYNX", "FL engines", "VFX"; "" = Installed itself), core/PluginDbFolder.h groupFolder()
  721. std::string group;
  722. bool isGroup = false;
  723. int collection = -1; // kind == collection: which one (0 = Starred)
  724. // round 190oa (DF-120, capture 190oa B4): FL's Current project › Effects / Generators entries open to their
  725. // plugin's parameters (what the wrapper menu's Browse parameters shows); a parameter row's target
  726. AutomationTarget parameter;
  727. // round 190oa (DF-109, capture 190oa B3): FL draws the plugin's editor picture (~106 × 52) on its own lines under
  728. // an effect / plugin generator entry of Current project; LYNX: the Plugin picker's picture, over `thumbRows`
  729. // pseudo rows (`thumbPart` 0, 1, 2 of the picture's lines; `thumbOwner` = the entry)
  730. juce::Image thumb;
  731. std::vector<std::unique_ptr<Node>> thumbRows;
  732. int thumbPart = -1;
  733. Node* thumbOwner = nullptr;
  734. };
  735. static constexpr int thumbRowCount = 3, thumbHeight = 52, thumbMaxWidth = 106;
  736. // The Plugin picker's picture of a mixer slot's effect or of a plugin channel's generator (null: none rendered)
  737. static juce::Image entryPicture (const Song& song, const projectcontents::Item& item, const std::vector<generators::Entry>* gens)
  738. {
  739. std::string key;
  740. bool native = true;
  741. if (item.kind == projectcontents::Kind::effect && item.index >= 0 && item.index < (int) song.mixer.size() && item.slot >= 0
  742. && item.slot < (int) song.mixer[(std::size_t) item.index].effects.size())
  743. {
  744. const auto& slot = song.mixer[(std::size_t) item.index].effects[(std::size_t) item.slot];
  745. if (slot.kind == EffectKind::plugin)
  746. key = slot.plugin.id, native = false;
  747. else
  748. key = std::string ("lynx:fx:") + effectInfo (slot.kind).name;
  749. }
  750. else if (item.kind == projectcontents::Kind::generator && item.index >= 0 && item.index < (int) song.channels.size() && gens != nullptr)
  751. {
  752. const auto& ch = song.channels[(std::size_t) item.index];
  753. for (const auto& e : *gens)
  754. if (ch.instrument == InstrumentKind::plugin ? (! ch.plugin.id.empty() && e.key == ch.plugin.id) : (e.kind == ch.instrument && e.folder != 3))
  755. {
  756. key = e.key, native = e.folder != 3;
  757. break;
  758. }
  759. }
  760. if (key.empty())
  761. return {};
  762. const auto file = pluginthumbs::fileFor (key, native);
  763. return file.existsAsFile() ? juce::ImageCache::getFromFile (file) : juce::Image();
  764. }
  765. static const std::vector<generators::Entry>& gens (AudioEngine& engine)
  766. {
  767. static std::vector<generators::Entry> cache;
  768. static juce::uint32 at = 0;
  769. if (const auto now = juce::Time::getMillisecondCounter(); cache.empty() || now - at > 5000)
  770. {
  771. cache = generators::entries (engine);
  772. at = now;
  773. }
  774. return cache;
  775. }
  776. static void addThumb (Node& node, juce::Image picture)
  777. {
  778. if (! picture.isValid())
  779. return;
  780. node.thumb = picture;
  781. for (int part = 0; part < thumbRowCount; ++part)
  782. {
  783. auto t = std::make_unique<Node>();
  784. t->kind = Kind::item;
  785. t->thumbPart = part;
  786. t->thumbOwner = &node;
  787. t->depth = node.depth;
  788. t->parent = node.parent;
  789. node.thumbRows.push_back (std::move (t));
  790. }
  791. }
  792. // The parameters an effect / generator entry lists (FL: every parameter of the plugin, a knob icon each): a native
  793. // effect's own, a hosted plugin's. Native generators list none here (their controls live in their windows).
  794. static std::vector<std::pair<AutomationTarget, juce::String>> parametersOf (AudioEngine& engine, const projectcontents::Item& item)
  795. {
  796. std::vector<std::pair<AutomationTarget, juce::String>> out;
  797. const auto& song = engine.getSong();
  798. if (item.kind == projectcontents::Kind::effect && item.index >= 0 && item.index < (int) song.mixer.size() && item.slot >= 0
  799. && item.slot < (int) song.mixer[(std::size_t) item.index].effects.size())
  800. {
  801. const auto& slot = song.mixer[(std::size_t) item.index].effects[(std::size_t) item.slot];
  802. if (slot.kind == EffectKind::plugin)
  803. {
  804. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (item.index, item.slot).get()))
  805. for (int i = 0; i < p->getInstance().getParameters().size(); ++i)
  806. out.push_back ({ { AutomationTargetKind::effectParam, item.index, item.slot, i }, p->getInstance().getParameters()[i]->getName (60) });
  807. }
  808. else
  809. {
  810. const auto& info = effectInfo (slot.kind);
  811. for (int i = 0; i < (int) info.params.size(); ++i)
  812. out.push_back ({ { AutomationTargetKind::effectParam, item.index, item.slot, i }, tr (info.params[(std::size_t) i].name) });
  813. }
  814. }
  815. else if (item.kind == projectcontents::Kind::generator && item.index >= 0 && item.index < (int) song.channels.size()
  816. && song.channels[(std::size_t) item.index].instrument == InstrumentKind::plugin)
  817. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (item.index).get()))
  818. for (int i = 0; i < p->getInstance().getParameters().size(); ++i)
  819. out.push_back ({ { AutomationTargetKind::channelParam, item.index, 0, i }, p->getInstance().getParameters()[i]->getName (60) });
  820. return out;
  821. }
  822. // What a row is to the collections (core/BrowserCollections.h): a file's or folder's path, a Plugin database
  823. // entry's key; empty = a row that can't be in one (the project's items, headings).
  824. static std::string itemOf (const Node& n)
  825. {
  826. if (n.kind == Kind::plugin)
  827. return n.pluginKey.empty() ? std::string() : collections::pluginItem (n.pluginKey);
  828. if ((n.kind == Kind::file || n.kind == Kind::fsFolder) && n.file != juce::File())
  829. return n.file.getFullPathName().toStdString();
  830. return {};
  831. }
  832. std::string selectedItem() const { return juce::isPositiveAndBelow (selected, (int) rows.size()) ? itemOf (*rows[(std::size_t) selected]) : std::string(); }
  833. const Node* selectedNode() const { return juce::isPositiveAndBelow (selected, (int) rows.size()) ? rows[(std::size_t) selected] : nullptr; }
  834. juce::String selectedLabel() const
  835. {
  836. const auto* n = selectedNode();
  837. return n == nullptr ? juce::String() : n->label.isNotEmpty() ? n->label : n->file.getFileName();
  838. }
  839. static std::unique_ptr<Node> makeCollection (int collection, int itemCount, bool open)
  840. {
  841. auto n = std::make_unique<Node>();
  842. n->kind = Kind::collection;
  843. n->collection = collection;
  844. n->folder = n->loaded = true;
  845. n->expanded = open;
  846. n->label = BrowserComponent::collectionName (collection);
  847. n->detail = juce::String (itemCount);
  848. n->colour = BrowserComponent::collectionColour (collection);
  849. return n;
  850. }
  851. // A Plugin database entry outside the database's tree (a collection's item): the same row, double-click and drag.
  852. static std::unique_ptr<Node> makePluginItem (BrowserComponent& browser, const std::string& key)
  853. {
  854. if (factorycontent::isKey (key)) // (round 190ke: LYNX's own content in a collection or a tag search)
  855. return makeFactoryItem (browser, key);
  856. auto safe = juce::Component::SafePointer<BrowserComponent> (&browser);
  857. for (int generators = 1; generators >= 0; --generators)
  858. {
  859. auto n = std::make_unique<Node>();
  860. n->kind = Kind::plugin;
  861. n->pluginKey = key;
  862. if (generators == 1)
  863. {
  864. for (auto& e : quickpick::generatorEntries (browser.engine))
  865. if (e.key == key)
  866. {
  867. n->label = quickpick::shownName (browser.engine, e.key, e.label);
  868. n->original = e.label;
  869. n->detail = e.detail;
  870. n->icon = e.folder == 3 ? Icon::plugin : Icon::keyboard;
  871. n->generator = e.make;
  872. n->activate = [safe, make = e.make] {
  873. if (auto c = make(); c && safe != nullptr && safe->onAddInstrument)
  874. safe->onAddInstrument (std::move (*c));
  875. };
  876. return n;
  877. }
  878. }
  879. else
  880. for (auto& e : quickpick::effectEntries (browser.engine))
  881. if (e.key == key)
  882. {
  883. n->label = quickpick::shownName (browser.engine, e.key, e.label);
  884. n->original = e.label;
  885. n->detail = e.detail;
  886. n->icon = e.folder == 3 ? Icon::plugin : Icon::mixer;
  887. n->effect = e.make;
  888. n->activate = [safe, make = e.make] {
  889. if (auto fx = make(); fx && safe != nullptr && safe->onAddEffect)
  890. safe->onAddEffect (std::move (*fx));
  891. };
  892. return n;
  893. }
  894. }
  895. return nullptr; // (the plugin is not installed any more: the collection leaves it out)
  896. }
  897. // Round 190ke (owner decision D2): one item of LYNX's own content, a plugin-like row (double-click / Enter: add it;
  898. // drag a sound onto the Channel Rack) whose key the collections and the tags store; nullptr for an unknown key
  899. static std::unique_ptr<Node> makeFactoryItem (BrowserComponent& browser, const std::string& key)
  900. {
  901. const auto* item = factorycontent::find (key);
  902. if (item == nullptr)
  903. return nullptr;
  904. auto safe = juce::Component::SafePointer<BrowserComponent> (&browser);
  905. auto n = std::make_unique<Node>();
  906. n->kind = Kind::plugin;
  907. n->pluginKey = key;
  908. n->label = n->original = juce::String::fromUTF8 (item->name.c_str());
  909. n->detail = juce::String::fromUTF8 (item->detail.c_str());
  910. if (item->kind == factorycontent::Kind::sound)
  911. {
  912. n->icon = Icon::keyboard;
  913. const auto index = item->index;
  914. n->generator = [index]() -> std::optional<ChannelDef> {
  915. const auto& sounds = soundlib::builtIn();
  916. return index >= 0 && index < (int) sounds.size() ? soundlib::channelFor (sounds[(std::size_t) index]) : std::nullopt;
  917. };
  918. n->activate = [safe, make = n->generator, key] {
  919. if (safe != nullptr && safe->onFactoryItem) // (the Simple layout: a new instrument track)
  920. safe->onFactoryItem (key);
  921. else if (auto c = make(); c && safe != nullptr && safe->onAddInstrument)
  922. safe->onAddInstrument (std::move (*c));
  923. };
  924. }
  925. else
  926. {
  927. n->icon = item->kind == factorycontent::Kind::beat ? Icon::note : Icon::mixer;
  928. n->activate = [safe, key] {
  929. if (safe != nullptr && safe->onFactoryItem)
  930. safe->onFactoryItem (key);
  931. };
  932. }
  933. return n;
  934. }
  935. // "LYNX content" with its three folders, each by category / genre (built open or closed as `open` remembers)
  936. static std::unique_ptr<Node> makeFactoryRoot (BrowserComponent& browser, const std::set<juce::String>& open)
  937. {
  938. auto folder = [&open] (Node* parent, const juce::String& label, const juce::String& path) {
  939. auto n = std::make_unique<Node>();
  940. n->kind = Kind::factory;
  941. n->folder = n->loaded = true;
  942. n->label = label;
  943. n->icon = Icon::folder;
  944. n->parent = parent;
  945. n->depth = parent != nullptr ? parent->depth + 1 : 0;
  946. n->userFolder = path.toStdString(); // (the key `open` remembers it by)
  947. n->expanded = open.count (path) > 0;
  948. return n;
  949. };
  950. auto root = folder (nullptr, tr ("LYNX content"), "lynx-content");
  951. root->colour = theme::colour::accent;
  952. const std::tuple<factorycontent::Kind, const char*, juce::String> kinds[] { { factorycontent::Kind::sound, "Sounds", tr ("Sounds") },
  953. { factorycontent::Kind::beat, "Beats", tr ("Beats") },
  954. { factorycontent::Kind::chain, "Effect chains", tr ("Effect chains") } };
  955. int total = 0;
  956. for (const auto& [kind, id, title] : kinds)
  957. {
  958. const auto kindPath = juce::String ("lynx-content/") + id;
  959. auto group = folder (root.get(), title, kindPath);
  960. std::map<std::string, std::unique_ptr<Node>> byFolder;
  961. std::vector<std::string> order;
  962. for (const auto& item : factorycontent::items())
  963. {
  964. if (item.kind != kind)
  965. continue;
  966. auto& sub = byFolder[item.folder];
  967. if (sub == nullptr)
  968. {
  969. const auto& f = item.folder; // (the words that mean something else elsewhere get their context, as the Simple dock's)
  970. const auto shown = f == "Keys" ? trc ("@sound category: Keys") : f == "Bass" ? trc ("@instrument: Bass") : f == "Lead" ? trc ("@sound category: Lead")
  971. : f == "Effects" ? trc ("@sound category: Effects") : tr (juce::String::fromUTF8 (f.c_str()));
  972. sub = folder (group.get(), shown, kindPath + "/" + juce::String::fromUTF8 (f.c_str()));
  973. order.push_back (item.folder);
  974. }
  975. if (auto leaf = makeFactoryItem (browser, item.key))
  976. {
  977. leaf->parent = sub.get();
  978. leaf->depth = sub->depth + 1;
  979. sub->children.push_back (std::move (leaf));
  980. }
  981. }
  982. int count = 0;
  983. for (const auto& f : order)
  984. {
  985. auto& sub = byFolder[f];
  986. sub->detail = juce::String ((int) sub->children.size());
  987. count += (int) sub->children.size();
  988. group->children.push_back (std::move (sub));
  989. }
  990. group->detail = juce::String (count);
  991. total += count;
  992. root->children.push_back (std::move (group));
  993. }
  994. root->detail = juce::String (total);
  995. return root;
  996. }
  997. // round 190iz: a collection's items (STARRED tab, Live's Collections) and Live's plugin categories as lists
  998. static std::vector<std::unique_ptr<Node>> collectionNodes (BrowserComponent& browser, int collection);
  999. static std::vector<std::unique_ptr<Node>> livePluginNodes (BrowserComponent& browser, browserplaces::Category category);
  1000. // tree mode: the given top-level nodes
  1001. void setTopLevel (std::vector<std::unique_ptr<Node>> nodes)
  1002. {
  1003. root = std::make_unique<Node>();
  1004. root->kind = Kind::fsFolder;
  1005. root->folder = root->expanded = root->loaded = true;
  1006. root->depth = -1;
  1007. for (auto& n : nodes)
  1008. {
  1009. n->parent = root.get();
  1010. n->depth = 0;
  1011. if (n->kind == Kind::collection) // (its items came with it)
  1012. for (auto& c : n->children)
  1013. {
  1014. c->parent = n.get();
  1015. c->depth = 1;
  1016. }
  1017. if (n->expanded)
  1018. load (*n);
  1019. root->children.push_back (std::move (n));
  1020. }
  1021. selected = hovered = -1;
  1022. marked.clear(); // (round 190qi)
  1023. rebuild();
  1024. }
  1025. static std::unique_ptr<Node> makeFolder (const juce::File& folder, const juce::String& label, juce::Colour colour)
  1026. {
  1027. auto n = std::make_unique<Node>();
  1028. n->kind = Kind::fsFolder;
  1029. n->file = folder;
  1030. n->folder = true;
  1031. n->label = label;
  1032. n->colour = colour;
  1033. return n;
  1034. }
  1035. // round 166f (issue #16): the user's folders of one kind (FL's Plugin database folders) as nodes under `kindNode`,
  1036. // parents before children; the map gives each path's node
  1037. template <typename MakeFolder>
  1038. static std::map<std::string, Node*> userFolderNodes (Node& kindNode, bool instruments, MakeFolder& folder, AudioEngine& engine)
  1039. {
  1040. std::map<std::string, Node*> out;
  1041. for (const auto& path : engine.getPluginHost().databaseFolders().kind (instruments)) // (a std::set: "A" before "A/B")
  1042. {
  1043. const auto parentPath = plugincatalog::parentFolder (path);
  1044. auto* parent = parentPath.empty() ? &kindNode : (out.count (parentPath) ? out[parentPath] : nullptr);
  1045. if (parent == nullptr) continue;
  1046. auto n = folder (parent, juce::String::fromUTF8 (plugincatalog::folderLeaf (path).c_str()), Icon::folder);
  1047. n->folderKind = instruments ? 1 : 0;
  1048. n->userFolder = path;
  1049. n->colour = theme::colour::info;
  1050. out[path] = n.get();
  1051. parent->children.push_back (std::move (n));
  1052. }
  1053. return out;
  1054. }
  1055. static Node* userFolderOf (const std::map<std::string, Node*>& nodes, AudioEngine& engine, bool instruments, const std::string& key)
  1056. {
  1057. const auto& folders = engine.getPluginHost().databaseFolders();
  1058. const auto it = folders.of.find (key);
  1059. if (it == folders.of.end() || ! folders.kind (instruments).count (it->second)) return nullptr;
  1060. const auto n = nodes.find (it->second);
  1061. return n != nodes.end() ? n->second : nullptr;
  1062. }
  1063. // subfolders first, then the plugins, each A-Z
  1064. static void sortFolder (Node& n)
  1065. {
  1066. std::stable_sort (n.children.begin(), n.children.end(), [] (const auto& a, const auto& b) {
  1067. if (a->folder != b->folder) return a->folder;
  1068. return a->label.compareNatural (b->label) < 0;
  1069. });
  1070. }
  1071. // FL's "Plugin database", interpreted (round 142, issue #5): Generators and Effects, each with LYNX's built-in ones,
  1072. // FL's engines (those the user's FL installation provides) and the installed VST3 / CLAP plugins
  1073. static std::unique_ptr<Node> makePluginDatabase (BrowserComponent& browser, const std::set<juce::String>& open)
  1074. {
  1075. auto folder = [&open] (Node* parent, const juce::String& label, Icon icon) {
  1076. auto n = std::make_unique<Node>();
  1077. n->kind = Kind::plugins;
  1078. n->folder = n->loaded = true;
  1079. n->label = label;
  1080. n->icon = icon;
  1081. n->parent = parent;
  1082. n->depth = parent != nullptr ? parent->depth + 1 : 0;
  1083. n->expanded = open.count ((parent != nullptr && parent->kind == Kind::plugins ? parent->label + "/" : juce::String()) + label) > 0;
  1084. return n;
  1085. };
  1086. auto node = [] (Node& parent, const juce::String& label, const juce::String& detail, Icon icon) -> Node& {
  1087. auto n = std::make_unique<Node>();
  1088. n->kind = Kind::plugin;
  1089. n->label = label;
  1090. n->detail = detail;
  1091. n->icon = icon;
  1092. n->parent = &parent;
  1093. n->depth = parent.depth + 1;
  1094. parent.children.push_back (std::move (n));
  1095. return *parent.children.back();
  1096. };
  1097. quickpick::refreshPluginDatabase (browser.engine); // (the folders as they are on disk now: issue #104)
  1098. auto root = folder (nullptr, tr ("Plugin database"), Icon::plugin);
  1099. root->colour = theme::colour::info;
  1100. auto safe = juce::Component::SafePointer<BrowserComponent> (&browser);
  1101. // a generator / an effect: double-click adds it (to the rack / the selected insert), or drag it there
  1102. auto generatorEntry = [&node, safe] (Node& parent, const juce::String& label, const juce::String& detail, Icon icon,
  1103. std::function<std::optional<ChannelDef>()> make) {
  1104. auto& n = node (parent, label, detail, icon);
  1105. n.generator = make;
  1106. n.activate = [safe, make] {
  1107. if (auto c = make(); c && safe != nullptr && safe->onAddInstrument)
  1108. safe->onAddInstrument (std::move (*c));
  1109. };
  1110. };
  1111. auto effectEntry = [&node, safe] (Node& parent, const juce::String& label, const juce::String& detail, Icon icon,
  1112. std::function<std::optional<EffectSlot>()> make) {
  1113. auto& n = node (parent, label, detail, icon);
  1114. n.effect = make;
  1115. n.activate = [safe, make] {
  1116. if (auto fx = make(); fx && safe != nullptr && safe->onAddEffect)
  1117. safe->onAddEffect (std::move (*fx));
  1118. };
  1119. };
  1120. // the entries (ui/QuickPick.h), each under the name the user gave it (issue #11: FL's renamed plugins, "1_EQ"),
  1121. // sorted by that name in each folder
  1122. auto& engine = browser.engine;
  1123. auto named = [&engine] (const std::string& key, const juce::String& label) { return quickpick::shownName (engine, key, label); };
  1124. auto byLabel = [] (Node& folderNode) {
  1125. std::stable_sort (folderNode.children.begin(), folderNode.children.end(),
  1126. [] (const auto& a, const auto& b) { return a->label.compareNatural (b->label) < 0; });
  1127. };
  1128. // Generators
  1129. {
  1130. auto gens = folder (root.get(), tr ("Generators"), Icon::keyboard);
  1131. auto lynxGens = folder (gens.get(), "LYNX SHARE", Icon::folder);
  1132. auto flGens = folder (gens.get(), tr ("FL engines"), Icon::folder);
  1133. // FL's VFX note processors (round 164b): channels with no sound, they play other channels / Patcher nodes
  1134. auto vfxGens = folder (gens.get(), tr ("VFX (note effects)"), Icon::folder);
  1135. auto installed = folder (gens.get(), tr ("Installed"), Icon::folder);
  1136. // round 190pj (issue #241): the JSFX scripts (the bundled pack and the JSFX folders) in a category of their own
  1137. auto jsfxGens = folder (gens.get(), "JSFX", Icon::folder);
  1138. Node* folders[] = { lynxGens.get(), flGens.get(), vfxGens.get(), installed.get() };
  1139. gens->folderKind = 1;
  1140. for (auto [node, group] : { std::pair { folders[0], "LYNX" }, std::pair { folders[1], "FL engines" }, std::pair { folders[2], "VFX" },
  1141. std::pair { folders[3], "" } })
  1142. {
  1143. node->group = group;
  1144. node->isGroup = true;
  1145. }
  1146. const auto mine = userFolderNodes (*gens, true, folder, engine); // round 166f: the user's folders first
  1147. for (auto& e : quickpick::generatorEntries (engine))
  1148. {
  1149. auto* target = userFolderOf (mine, engine, true, e.key);
  1150. if (target == nullptr) target = e.folder == 3 && isJsfxKey (e.key) ? jsfxGens.get() : folders[juce::jlimit (0, 3, e.folder)];
  1151. generatorEntry (*target, named (e.key, e.label), e.detail, e.folder == 3 ? Icon::plugin : Icon::keyboard, e.make);
  1152. target->children.back()->pluginKey = e.key;
  1153. target->children.back()->original = e.label;
  1154. }
  1155. for (auto& [path, n] : mine) sortFolder (*n);
  1156. for (auto* f : { &lynxGens, &flGens, &vfxGens, &jsfxGens, &installed })
  1157. if (! (*f)->children.empty())
  1158. {
  1159. byLabel (**f);
  1160. gens->children.push_back (std::move (*f));
  1161. }
  1162. root->children.push_back (std::move (gens));
  1163. }
  1164. // Effects
  1165. {
  1166. auto fxs = folder (root.get(), tr ("Effects"), Icon::mixer);
  1167. auto lynxFx = folder (fxs.get(), "LYNX SHARE", Icon::folder);
  1168. auto flFx = folder (fxs.get(), tr ("FL engines"), Icon::folder);
  1169. auto installed = folder (fxs.get(), tr ("Installed"), Icon::folder);
  1170. auto jsfxFx = folder (fxs.get(), "JSFX", Icon::folder); // (round 190pj)
  1171. Node* folders[] = { lynxFx.get(), flFx.get(), installed.get(), installed.get() };
  1172. fxs->folderKind = 0;
  1173. for (auto [node, group] : { std::pair { folders[0], "LYNX" }, std::pair { folders[1], "FL engines" }, std::pair { folders[2], "" } })
  1174. {
  1175. node->group = group;
  1176. node->isGroup = true;
  1177. }
  1178. const auto mine = userFolderNodes (*fxs, false, folder, engine); // round 166f: the user's folders first
  1179. for (auto& e : quickpick::effectEntries (engine))
  1180. {
  1181. auto* target = userFolderOf (mine, engine, false, e.key);
  1182. if (target == nullptr) target = e.folder == 3 && isJsfxKey (e.key) ? jsfxFx.get() : folders[juce::jlimit (0, 3, e.folder)];
  1183. effectEntry (*target, named (e.key, e.label), e.detail, e.folder == 3 ? Icon::plugin : Icon::mixer, e.make);
  1184. target->children.back()->pluginKey = e.key;
  1185. target->children.back()->original = e.label;
  1186. }
  1187. for (auto& [path, n] : mine) sortFolder (*n);
  1188. for (auto* f : { &lynxFx, &flFx, &jsfxFx, &installed })
  1189. if (! (*f)->children.empty())
  1190. {
  1191. byLabel (**f);
  1192. fxs->children.push_back (std::move (*f));
  1193. }
  1194. root->children.push_back (std::move (fxs));
  1195. }
  1196. // (the counts, dimmed after each folder)
  1197. std::function<int (Node&)> count = [&count] (Node& n) {
  1198. int total = 0;
  1199. for (auto& c : n.children)
  1200. total += c->kind == Kind::plugin ? 1 : count (*c);
  1201. if (n.kind == Kind::plugins)
  1202. n.detail = juce::String (total);
  1203. return total;
  1204. };
  1205. count (*root);
  1206. return root;
  1207. }
  1208. static std::unique_ptr<Node> makeProject (bool open)
  1209. {
  1210. auto n = std::make_unique<Node>();
  1211. n->kind = Kind::project;
  1212. n->folder = true;
  1213. n->expanded = open;
  1214. n->label = tr ("Current project");
  1215. n->icon = Icon::project;
  1216. n->colour = theme::colour::accent;
  1217. return n;
  1218. }
  1219. // flat mode: a list of files with their path relative to the folder searched that holds them
  1220. // (`details`: the dimmed text after each name, e.g. how similar the file is; round 190as)
  1221. void setFiles (const juce::Array<juce::File>& files, const juce::Array<juce::File>& newBases, const juce::String& newStatus,
  1222. const juce::StringArray& details = {})
  1223. {
  1224. bases = newBases;
  1225. status = newStatus;
  1226. flatNodes.clear();
  1227. for (const auto& f : files)
  1228. {
  1229. auto n = std::make_unique<Node>();
  1230. n->file = f;
  1231. n->detail = details[(int) flatNodes.size()];
  1232. flatNodes.push_back (std::move (n));
  1233. }
  1234. selected = hovered = -1;
  1235. marked.clear(); // (round 190qi)
  1236. rebuild();
  1237. }
  1238. // flat mode: project items (the PROJECT tab's search)
  1239. void setNodes (std::vector<std::unique_ptr<Node>> nodes, const juce::String& newStatus)
  1240. {
  1241. bases.clear();
  1242. status = newStatus;
  1243. flatNodes = std::move (nodes);
  1244. selected = hovered = -1;
  1245. marked.clear(); // (round 190qi)
  1246. rebuild();
  1247. }
  1248. // round 190mf: flat mode: changes some rows' dimmed detail in place (the Simple loop list's lengths as they are read)
  1249. void updateDetails (const std::function<bool (Node&)>& change)
  1250. {
  1251. bool any = false;
  1252. for (auto& n : flatNodes)
  1253. any = change (*n) || any;
  1254. if (any)
  1255. repaint();
  1256. }
  1257. void setStatus (const juce::String& text)
  1258. {
  1259. status = text;
  1260. repaint();
  1261. }
  1262. // Removes the folders on disk `drop` takes (round 164: the content filter found them empty), keeping what is open
  1263. // and selected. False when nothing went.
  1264. bool pruneFolders (const std::function<bool (const juce::File&)>& drop)
  1265. {
  1266. if (flat || root == nullptr)
  1267. return false;
  1268. auto* keep = juce::isPositiveAndBelow (selected, (int) rows.size()) ? rows[(std::size_t) selected] : nullptr;
  1269. bool removed = false, lostSelection = false;
  1270. std::function<void (Node&)> walk = [&] (Node& n) {
  1271. for (auto it = n.children.begin(); it != n.children.end();)
  1272. {
  1273. auto& c = **it;
  1274. if (c.kind == Kind::fsFolder && drop (c.file) && std::all_of (c.also.begin(), c.also.end(), drop))
  1275. {
  1276. for (auto* s = keep; s != nullptr; s = s->parent)
  1277. lostSelection = lostSelection || s == &c;
  1278. it = n.children.erase (it);
  1279. removed = true;
  1280. continue;
  1281. }
  1282. if (c.kind == Kind::fsFolder && c.loaded)
  1283. walk (c);
  1284. ++it;
  1285. }
  1286. };
  1287. walk (*root);
  1288. if (! removed)
  1289. return false;
  1290. rebuild();
  1291. selected = -1;
  1292. if (! lostSelection)
  1293. for (int i = 0; i < (int) rows.size(); ++i)
  1294. if (rows[(std::size_t) i] == keep)
  1295. selected = i;
  1296. hovered = -1;
  1297. return true;
  1298. }
  1299. juce::File selectedFile() const
  1300. {
  1301. return juce::isPositiveAndBelow (selected, (int) rows.size()) ? rows[(std::size_t) selected]->file : juce::File();
  1302. }
  1303. // the top-level folder on disk that holds the selection (none: the selection is not a file)
  1304. juce::File selectedRoot() const
  1305. {
  1306. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  1307. return {};
  1308. for (auto* n = rows[(std::size_t) selected]; n != nullptr; n = n->parent)
  1309. if (n->kind == Kind::fsFolder && n->depth == 0)
  1310. return n->file;
  1311. return {};
  1312. }
  1313. // the name a row shows (issue #182's type-to-jump matches it)
  1314. juce::String rowName (int row) const
  1315. {
  1316. if (! juce::isPositiveAndBelow (row, (int) rows.size()))
  1317. return {};
  1318. const auto& n = *rows[(std::size_t) row];
  1319. return n.label.isNotEmpty() ? n.label : n.folder || ! isAudio (n.file) ? n.file.getFileName() : n.file.getFileNameWithoutExtension();
  1320. }
  1321. bool selectedIsFolder() const { return juce::isPositiveAndBelow (selected, (int) rows.size()) && rows[(std::size_t) selected]->folder; }
  1322. int numRows() const { return (int) rows.size(); }
  1323. const Node* nodeAt (int row) const { return juce::isPositiveAndBelow (row, (int) rows.size()) ? rows[(std::size_t) row] : nullptr; } // (round 190kx)
  1324. // round 190ke (--simplegb190keshot): the rows' names as shown
  1325. juce::StringArray rowLabels() const
  1326. {
  1327. juce::StringArray out;
  1328. for (const auto* n : rows)
  1329. out.add (n->label.isNotEmpty() ? n->label : n->file.getFileName());
  1330. return out;
  1331. }
  1332. int getSelectedRow() const { return selected; }
  1333. void select (int row, bool preview)
  1334. {
  1335. row = rows.empty() ? -1 : juce::jlimit (0, (int) rows.size() - 1, row);
  1336. // (round 190oa, DF-109: a picture's line is never selected: stepping down passes it, up lands on its entry)
  1337. if (row >= 0 && rows[(std::size_t) row]->thumbPart >= 0)
  1338. {
  1339. const auto owner = row - rows[(std::size_t) row]->thumbPart - 1;
  1340. if (row > selected && selected >= owner)
  1341. row = juce::jmin ((int) rows.size() - 1, owner + thumbRowCount + 1);
  1342. else
  1343. row = juce::jmax (0, owner);
  1344. }
  1345. if (row != selected)
  1346. {
  1347. repaintRow (selected);
  1348. selected = row;
  1349. repaintRow (selected);
  1350. }
  1351. scrollToRow (row);
  1352. if (row >= 0)
  1353. browser.fileSelected (rows[(std::size_t) row]->file, preview && ! rows[(std::size_t) row]->folder);
  1354. }
  1355. // #218 follow-up (round 190nq): FL 2026's Enter on a selected folder opens or closes it ([SHOT] 190nq h04c -> h05c -> h06c)
  1356. bool toggleSelectedFolder()
  1357. {
  1358. if (! juce::isPositiveAndBelow (selected, (int) rows.size()) || ! rows[(std::size_t) selected]->folder)
  1359. return false;
  1360. toggle (*rows[(std::size_t) selected]);
  1361. return true;
  1362. }
  1363. // Left / Right: close the selected folder (or go to its parent) / open it
  1364. void openSelected (bool open)
  1365. {
  1366. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  1367. return;
  1368. auto* n = rows[(std::size_t) selected];
  1369. if (n->folder && n->expanded != open)
  1370. {
  1371. toggle (*n);
  1372. return;
  1373. }
  1374. if (! open && n->parent != nullptr && n->parent != root.get())
  1375. for (int i = 0; i < (int) rows.size(); ++i)
  1376. if (rows[(std::size_t) i] == n->parent)
  1377. {
  1378. select (i, false);
  1379. return;
  1380. }
  1381. }
  1382. void collapseAll()
  1383. {
  1384. if (root == nullptr)
  1385. return;
  1386. std::function<void (Node&)> close = [&close] (Node& n) {
  1387. for (auto& c : n.children)
  1388. {
  1389. c->expanded = false;
  1390. close (*c);
  1391. }
  1392. };
  1393. close (*root);
  1394. selected = hovered = -1;
  1395. marked.clear(); // (round 190qi)
  1396. rebuild();
  1397. }
  1398. void expandAll (Node& n)
  1399. {
  1400. n.expanded = true;
  1401. load (n);
  1402. if (n.kind == Kind::project || n.kind == Kind::category || n.kind == Kind::factory)
  1403. for (auto& c : n.children)
  1404. if (c->folder && c->kind != Kind::fsFolder)
  1405. expandAll (*c);
  1406. rebuild();
  1407. }
  1408. // FL's folder "Expand all": the folder and its sub-folders open (on disk: down to `depth` levels, so a big
  1409. // library is not scanned at once)
  1410. // --snapshot: opens the top-level folder `f` and its sub-folders (round 164)
  1411. void expandTop (const juce::File& f, int depth)
  1412. {
  1413. if (root != nullptr)
  1414. for (auto& c : root->children)
  1415. if (c->kind == Kind::fsFolder && c->file == f)
  1416. expandFolder (*c, depth);
  1417. }
  1418. // Opens the folders down to `file` (a file or folder under one of the top-level folders) and returns its row, or
  1419. // -1 when no folder shown here holds it (round 190ce: hot-swap shows the linked sample, "Show in its folder").
  1420. int revealFile (const juce::File& file)
  1421. {
  1422. if (root == nullptr || flat)
  1423. return -1;
  1424. for (auto& top : root->children)
  1425. {
  1426. if (top->kind != Kind::fsFolder)
  1427. continue;
  1428. juce::Array<juce::File> bases { top->file };
  1429. bases.addArray (top->also);
  1430. const auto holds = [&file] (const juce::File& folder) { return folder.isDirectory() && (file == folder || file.isAChildOf (folder)); };
  1431. if (std::none_of (bases.begin(), bases.end(), holds))
  1432. continue;
  1433. auto* node = top.get();
  1434. for (int guard = 0; guard < 64 && node != nullptr; ++guard)
  1435. {
  1436. node->expanded = true;
  1437. load (*node);
  1438. Node* next = nullptr;
  1439. for (auto& c : node->children)
  1440. if (c->file == file)
  1441. {
  1442. rebuild();
  1443. return rowOfFile (file);
  1444. }
  1445. else if (c->folder && file.isAChildOf (c->file))
  1446. next = c.get();
  1447. node = next;
  1448. }
  1449. rebuild();
  1450. }
  1451. return -1;
  1452. }
  1453. void expandFolder (Node& n, int depth)
  1454. {
  1455. n.expanded = true;
  1456. load (n);
  1457. if (depth > 1)
  1458. for (auto& c : n.children)
  1459. if (c->folder)
  1460. expandFolder (*c, depth - 1);
  1461. rebuild();
  1462. }
  1463. void rebuild()
  1464. {
  1465. rows.clear();
  1466. if (flat)
  1467. for (auto& n : flatNodes)
  1468. rows.push_back (n.get());
  1469. else if (root != nullptr)
  1470. addRows (*root);
  1471. if (! flat && browser.showsLoopRowInfo())
  1472. askLoopInfo();
  1473. updateSize();
  1474. repaint();
  1475. }
  1476. // round 190kx: the Simple layout's rows of audio files show their bars, tempo and key (BandLab's loop rows): the
  1477. // listed files are analysed once (ui/LoopInfo's worker, cached per file), answers fill the rows as they come
  1478. void askLoopInfo()
  1479. {
  1480. std::vector<std::string> wanted;
  1481. for (const auto* n : rows)
  1482. if (n->kind == Kind::file && ! n->folder && ! n->loopKnown && isAudio (n->file))
  1483. if (wanted.size() < 1000)
  1484. wanted.push_back (n->file.getFullPathName().toStdString());
  1485. if (wanted.empty())
  1486. return;
  1487. auto& shared = browser.loopInfoShared();
  1488. refreshLoopTexts();
  1489. shared.request (wanted);
  1490. }
  1491. void refreshLoopTexts()
  1492. {
  1493. if (browser.loopInfo == nullptr)
  1494. return;
  1495. const auto meter = browser.engine.getSong().meter();
  1496. bool changed = false;
  1497. for (auto* n : rows)
  1498. if (n->kind == Kind::file && ! n->folder && ! n->loopKnown)
  1499. if (const auto r = browser.loopInfo->known (n->file.getFullPathName().toStdString()))
  1500. {
  1501. n->loopKnown = true;
  1502. n->loopText = loopinfo::rowText (*r, meter);
  1503. changed = true;
  1504. }
  1505. if (changed)
  1506. repaint();
  1507. }
  1508. void updateSize()
  1509. {
  1510. if (auto* parent = getParentComponent())
  1511. {
  1512. auto width = parent->getWidth();
  1513. const auto viewHeight = parent->getParentComponent() != nullptr ? parent->getParentComponent()->getHeight() : parent->getHeight();
  1514. // round gaps190kf: the Loop Browser's list keeps its Tempo / Key column and stars clear of the scroll bar
  1515. if (auto* view = dynamic_cast<juce::Viewport*> (parent->getParentComponent());
  1516. view != nullptr && flat && browser.isLoopsShown() && (int) rows.size() * rowHeight > viewHeight)
  1517. width = view->getWidth() - view->getScrollBarThickness();
  1518. setSize (width, juce::jmax (viewHeight, (int) rows.size() * rowHeight));
  1519. }
  1520. }
  1521. // The project changed: the open sections are listed again (only those whose items changed), keeping what is
  1522. // open and selected.
  1523. void refreshProject()
  1524. {
  1525. if (root == nullptr)
  1526. return;
  1527. bool changed = false;
  1528. const auto key = selectionKey();
  1529. std::function<void (Node&)> visit = [&] (Node& n) {
  1530. if (n.kind == Kind::category)
  1531. {
  1532. Node fresh;
  1533. fresh.kind = Kind::category;
  1534. fresh.category = n.category;
  1535. fresh.depth = n.depth;
  1536. listCategory (fresh, browser.engine.getSong(), &browser.engine, ! n.loaded);
  1537. if (n.detail != fresh.detail)
  1538. {
  1539. n.detail = fresh.detail;
  1540. changed = true;
  1541. }
  1542. if (! n.loaded)
  1543. return;
  1544. if (signature (fresh) != signature (n))
  1545. {
  1546. n.children = std::move (fresh.children);
  1547. for (auto& c : n.children)
  1548. c->parent = &n;
  1549. changed = true;
  1550. }
  1551. else
  1552. for (std::size_t i = 0; i < n.children.size(); ++i) // the same items: only the "current" marks
  1553. n.children[i]->current = fresh.children[i]->current;
  1554. return;
  1555. }
  1556. for (auto& c : n.children)
  1557. if (c->kind == Kind::project || c->kind == Kind::category)
  1558. visit (*c);
  1559. };
  1560. visit (*root);
  1561. pendingKey = key;
  1562. if (changed)
  1563. {
  1564. rebuild();
  1565. restoreSelection (pendingKey);
  1566. }
  1567. else
  1568. repaint();
  1569. }
  1570. void paint (juce::Graphics& g) override
  1571. {
  1572. using namespace theme::colour;
  1573. g.fillAll (bg2);
  1574. const auto clip = g.getClipBounds();
  1575. const auto first = juce::jmax (0, clip.getY() / rowHeight), last = juce::jmin ((int) rows.size() - 1, clip.getBottom() / rowHeight);
  1576. const auto previewing = browser.isPreviewPlaying() ? browser.previewedFile : juce::File();
  1577. const auto live = rowHeight == liveRowHeight; // (round 190iz: the Clip-launch layout's Live-style list)
  1578. const auto loopRows = ! flat && browser.showsLoopRowInfo(); // (round 190kx: the Simple layout's loop rows)
  1579. juce::RectangleList<int> guides; // (round 190iz: FL's dotted tree guides, filled at once below)
  1580. for (int i = first; i <= last; ++i)
  1581. {
  1582. const auto& n = *rows[(std::size_t) i];
  1583. auto r = juce::Rectangle<int> (0, i * rowHeight, getWidth(), rowHeight);
  1584. if (! flat && ! live && n.depth > 0)
  1585. addGuides (guides, n, r);
  1586. if (n.thumbPart >= 0 && n.thumbOwner != nullptr) // (round 190oa, DF-109: a line of the entry's picture)
  1587. {
  1588. const auto& pic = n.thumbOwner->thumb;
  1589. const auto top = r.getY() - n.thumbPart * rowHeight + 2;
  1590. const auto h = (float) thumbHeight, w = juce::jmin ((float) thumbMaxWidth, h * (float) pic.getWidth() / (float) juce::jmax (1, pic.getHeight()));
  1591. const auto x = (float) (6 + n.thumbOwner->depth * 14 + 12 + 21);
  1592. const juce::Graphics::ScopedSaveState keep (g);
  1593. g.reduceClipRegion (r);
  1594. g.drawImage (pic, juce::Rectangle<float> (x, (float) top, w, h), juce::RectanglePlacement::centred);
  1595. continue;
  1596. }
  1597. // an open project section sits on a slightly raised band (FL draws its open folders on a band)
  1598. if ((n.kind == Kind::project || n.kind == Kind::category) && n.expanded)
  1599. {
  1600. g.setColour (bg3);
  1601. g.fillRect (r);
  1602. }
  1603. if (i == selected)
  1604. {
  1605. g.setColour (accentMuted);
  1606. g.fillRect (r);
  1607. g.setColour (accent);
  1608. g.fillRect (r.withWidth (2));
  1609. }
  1610. else if (isMarked (n)) // (round 190qi: the multi-selection)
  1611. {
  1612. g.setColour (accentMuted.withMultipliedAlpha (0.8f));
  1613. g.fillRect (r);
  1614. }
  1615. else if (i == hovered)
  1616. {
  1617. g.setColour (bg4);
  1618. g.fillRect (r);
  1619. }
  1620. const auto indent = flat ? 6 : 6 + n.depth * 14;
  1621. auto x = (float) indent;
  1622. if (n.folder) // a chevron: right when closed, down when open
  1623. {
  1624. juce::Path p;
  1625. const auto c = juce::Point<float> (x + 5.0f, (float) r.getCentreY());
  1626. if (n.expanded)
  1627. p.addTriangle (c.x - 3.5f, c.y - 2.0f, c.x + 3.5f, c.y - 2.0f, c.x, c.y + 2.5f);
  1628. else
  1629. p.addTriangle (c.x - 2.0f, c.y - 3.5f, c.x - 2.0f, c.y + 3.5f, c.x + 2.5f, c.y);
  1630. g.setColour (i == hovered || i == selected ? textPrimary : textSecondary);
  1631. g.fillPath (p);
  1632. }
  1633. if (! flat || n.kind != Kind::item)
  1634. x += 12.0f;
  1635. const auto playing = ! n.folder && n.file != juce::File() && n.file == previewing;
  1636. const auto hasColour = ! n.colour.isTransparent();
  1637. auto iconColour = playing ? accent : hasColour ? readable (n.colour) : n.folder ? warning.withAlpha (0.85f) : textSecondary;
  1638. if (n.missing)
  1639. iconColour = meterClip;
  1640. const auto icon = n.icon != Icon::none ? n.icon : iconFor (n.file, n.folder);
  1641. if (n.kind == Kind::collection) // a collection's heading: its colour as a square
  1642. {
  1643. g.setColour (n.colour);
  1644. g.fillRoundedRectangle (juce::Rectangle<float> (x + 3.0f, (float) r.getY() + 6.0f, 10.0f, 10.0f), 2.0f);
  1645. }
  1646. else
  1647. icons::draw (g, icon, juce::Rectangle<float> (x, (float) r.getY() + 3.0f, 16.0f, 16.0f), iconColour);
  1648. x += 21.0f;
  1649. auto text = r.withLeft ((int) x).withTrimmedRight (6);
  1650. // round 190iz (FL, REA_rodada115 #5): the favourite star at the row's end, on the hovered row and on the
  1651. // starred ones (filled); the Clip-launch layout keeps Live's colour squares only
  1652. const auto rowItem = itemOf (n);
  1653. const auto starred = ! rowItem.empty() && BrowserComponent::collectionStore().has (rowItem, 0);
  1654. if (! live && ! rowItem.empty() && (starred || i == hovered))
  1655. {
  1656. const auto box = starBox (i).toFloat().withSizeKeepingCentre (12.0f, 12.0f);
  1657. const auto overStar = i == hovered && starBox (i).contains (getMouseXYRelative());
  1658. browsertabicons::drawRowStar (g, box, starred, starred ? warning : overStar ? textPrimary : textSecondary);
  1659. text.setRight (starBox (i).getX() - 2);
  1660. }
  1661. // the collections the row is in: one small square per colour at the right edge (round 190ce; round 190iz:
  1662. // Starred is the star in the FL layout)
  1663. if (const auto item = rowItem; ! item.empty())
  1664. if (const auto bits = (std::uint8_t) (BrowserComponent::collectionStore().mask (item) & (live ? 0x7f : 0x7e)); bits != 0)
  1665. {
  1666. for (int c = collections::count - 1; c >= 0; --c)
  1667. if ((bits >> c & 1) != 0)
  1668. {
  1669. const auto chip = text.removeFromRight (9).withSizeKeepingCentre (7, 7);
  1670. g.setColour (BrowserComponent::collectionColour (c));
  1671. g.fillRoundedRectangle (chip.toFloat(), 1.5f);
  1672. }
  1673. text.removeFromRight (3);
  1674. }
  1675. const auto flatDetail = flat && n.kind == Kind::file && n.detail.isNotEmpty(); // "87%" of a similar sample
  1676. if (flat && n.kind == Kind::file) // the folder it lives in, on the right (similar samples: how similar)
  1677. {
  1678. const auto where = flatDetail ? n.detail : n.file.getParentDirectory().getRelativePathFrom (baseOf (n.file));
  1679. g.setFont (theme::font (theme::type::caption));
  1680. g.setColour (textDisabled);
  1681. const auto w = juce::jmin (text.getWidth() / 2, juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), where) + 4);
  1682. g.drawText (where, text.removeFromRight (w), juce::Justification::centredRight, true);
  1683. }
  1684. // round 190kx: a loop's bars, tempo and key on the right (the Simple layout, BandLab's loop rows)
  1685. if (n.loopText.isNotEmpty() && loopRows)
  1686. {
  1687. g.setFont (theme::font (theme::type::caption));
  1688. g.setColour (textDisabled);
  1689. const auto w = juce::jmin (text.getWidth() / 2, juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), n.loopText) + 6);
  1690. g.drawText (n.loopText, text.removeFromRight (w), juce::Justification::centredRight, true);
  1691. }
  1692. const auto name = n.label.isNotEmpty() ? n.label
  1693. : n.folder || ! isAudio (n.file) ? n.file.getFileName()
  1694. : n.file.getFileNameWithoutExtension();
  1695. const auto bold = (n.folder && n.expanded) || n.current || n.kind == Kind::project;
  1696. // round 190iz: FL's tree face one step larger (FM-9); Live's list a step smaller. Round 190je: the FL tree is
  1697. // condensed with FL-style labels on (theme::labelFont = theme::font while the option is off)
  1698. const juce::Font font (live ? theme::font (theme::type::small, bold) : theme::labelFont (theme::type::body + 1.0f, bold));
  1699. g.setFont (font);
  1700. auto nameColour = playing ? accentHover : n.folder || i == hovered || i == selected ? textPrimary : textPrimary.withAlpha (0.86f);
  1701. if (n.kind == Kind::item && hasColour && n.item.kind == projectcontents::Kind::pattern)
  1702. nameColour = readable (n.colour); // FL writes the patterns in their colours
  1703. if (n.missing)
  1704. nameColour = meterClip.withAlpha (0.9f);
  1705. if (n.kind == Kind::item && n.history && ! n.current && n.item.index > browser.engine.getHistoryPosition())
  1706. nameColour = textDisabled; // undone steps (redo)
  1707. g.setColour (nameColour);
  1708. const auto nameWidth = juce::GlyphArrangement::getStringWidthInt (font, name);
  1709. g.drawText (name, text, juce::Justification::centredLeft, true);
  1710. // the detail after the name, dimmed: "(insert)", "3x", "missing", a section's count
  1711. if (n.detail.isNotEmpty() && ! flatDetail && nameWidth + 12 < text.getWidth())
  1712. {
  1713. g.setFont (theme::font (theme::type::small));
  1714. g.setColour (n.missing ? meterClip.withAlpha (0.7f) : textDisabled);
  1715. const auto shown = n.kind == Kind::category || n.kind == Kind::project ? n.detail : "(" + n.detail + ")";
  1716. if (n.kind == Kind::category) // the count on the right
  1717. g.drawText (shown, text, juce::Justification::centredRight, true);
  1718. else
  1719. g.drawText (shown, text.withTrimmedLeft (nameWidth + 6), juce::Justification::centredLeft, true);
  1720. }
  1721. }
  1722. if (! guides.isEmpty())
  1723. {
  1724. g.setColour (border.brighter (0.25f));
  1725. g.fillRectList (guides);
  1726. }
  1727. if (juce::isPositiveAndBelow (dropRow, (int) rows.size())) // files from the system would go here
  1728. {
  1729. g.setColour (accent);
  1730. g.drawRect (juce::Rectangle<int> (0, dropRow * rowHeight, getWidth(), rowHeight), 2);
  1731. }
  1732. if (rows.empty() && status.isNotEmpty())
  1733. {
  1734. g.setColour (textDisabled);
  1735. g.setFont (theme::font (theme::type::small));
  1736. g.drawFittedText (status, getLocalBounds().reduced (10).withHeight (60), juce::Justification::centredTop, 3);
  1737. }
  1738. }
  1739. // FL's tree guides (round 190iz, FM-9: "a dotted tree connector"): 1 px dots every 2 px from each open parent down
  1740. // its children, and a short dotted tick into each child row
  1741. void addGuides (juce::RectangleList<int>& out, const Node& n, juce::Rectangle<int> r) const
  1742. {
  1743. const auto column = [] (int depth) { return 6 + depth * 14 + 5; }; // a parent's chevron centre
  1744. const auto mid = r.getCentreY();
  1745. auto vertical = [&out] (int x, int y0, int y1) {
  1746. for (int y = y0 + (y0 & 1); y < y1; y += 2)
  1747. out.addWithoutMerging ({ x, y, 1, 1 });
  1748. };
  1749. const auto* parent = n.parent;
  1750. if (parent == nullptr || parent->depth < 0)
  1751. return;
  1752. const auto isLast = [] (const Node& c) { return c.parent == nullptr || c.parent->children.empty() || c.parent->children.back().get() == &c; };
  1753. // the row's own branch: down to its middle (to the bottom when more siblings follow), then across
  1754. const auto x = column (n.depth - 1);
  1755. vertical (x, r.getY(), isLast (n) ? mid + 1 : r.getBottom());
  1756. for (int xx = x + 2; xx < x + 9; xx += 2)
  1757. out.addWithoutMerging ({ xx, mid, 1, 1 });
  1758. // the lines of the ancestors that still have children below this row
  1759. for (const auto* a = parent; a != nullptr && a->depth > 0; a = a->parent)
  1760. if (! isLast (*a))
  1761. vertical (column (a->depth - 1), r.getY(), r.getBottom());
  1762. }
  1763. int rowAt (int y) const
  1764. {
  1765. const auto row = y / rowHeight;
  1766. if (y < 0 || row >= (int) rows.size())
  1767. return -1;
  1768. if (const auto part = rows[(std::size_t) row]->thumbPart; part >= 0) // (round 190oa: a picture's line = its entry)
  1769. return juce::jmax (0, row - part - 1);
  1770. return row;
  1771. }
  1772. // --- files dragged in from the system (issue #12): copied into the folder under the mouse ----------------------
  1773. // The folder row a drop at y lands in: a folder on disk, or a file's own folder; -1 = nowhere to copy to.
  1774. int dropFolderRow (int y) const
  1775. {
  1776. auto row = rowAt (y);
  1777. if (row < 0)
  1778. return -1;
  1779. const Node* n = rows[(std::size_t) row];
  1780. if (n->kind == Kind::file)
  1781. n = n->parent;
  1782. if (n == nullptr || n->kind != Kind::fsFolder || ! n->file.isDirectory())
  1783. return -1;
  1784. const auto it = std::find (rows.begin(), rows.end(), n);
  1785. return it != rows.end() ? (int) (it - rows.begin()) : -1;
  1786. }
  1787. bool isInterestedInFileDrag (const juce::StringArray& files) override
  1788. {
  1789. // the files the Browser lists (samples, MIDI, projects, presets): an other file would not show in the folder
  1790. // (issue #200: folders alone go to the Browser itself, which adds them to its list)
  1791. return ! flat && std::any_of (files.begin(), files.end(), [] (const juce::String& f) {
  1792. const juce::File file (f);
  1793. return file.existsAsFile() && isListed (file);
  1794. });
  1795. }
  1796. void fileDragMove (const juce::StringArray&, int, int y) override
  1797. {
  1798. if (const auto row = dropFolderRow (y); row != dropRow)
  1799. {
  1800. dropRow = row;
  1801. repaint();
  1802. }
  1803. }
  1804. void fileDragExit (const juce::StringArray&) override
  1805. {
  1806. dropRow = -1;
  1807. repaint();
  1808. }
  1809. void filesDropped (const juce::StringArray& files, int, int y) override
  1810. {
  1811. dropRow = -1;
  1812. repaint();
  1813. // issue #200 (round 190ll): folders dropped with the files join the Browser's folder list (FL)
  1814. juce::StringArray folders;
  1815. for (const auto& path : files)
  1816. if (juce::File (path).isDirectory())
  1817. folders.add (path);
  1818. if (! folders.isEmpty() && browser.addUserFolders (folders) > 0)
  1819. return; // (the tree was built again: its rows are gone; the files stay where they are)
  1820. const auto row = dropFolderRow (y);
  1821. if (row < 0)
  1822. {
  1823. browser.showNote (tr ("Drop the files on a folder to copy them there"));
  1824. return;
  1825. }
  1826. auto* folderNode = rows[(std::size_t) row];
  1827. const auto folder = folderNode->file;
  1828. int copied = 0;
  1829. juce::File first;
  1830. for (const auto& path : files)
  1831. {
  1832. const juce::File source (path);
  1833. if (! source.existsAsFile() || ! isListed (source) || source.getParentDirectory() == folder)
  1834. continue;
  1835. // never over a file that is there: "Kick (2).wav"
  1836. auto target = folder.getChildFile (source.getFileName());
  1837. if (target.exists())
  1838. target = folder.getNonexistentChildFile (source.getFileNameWithoutExtension(), source.getFileExtension(), true);
  1839. if (source.copyFileTo (target))
  1840. {
  1841. ++copied;
  1842. if (first == juce::File())
  1843. first = target;
  1844. }
  1845. }
  1846. if (copied == 0)
  1847. {
  1848. browser.showNote (tr ("Nothing was copied to {0}", { folder.getFileName() }));
  1849. return;
  1850. }
  1851. // the folder lists again, open, with the first copy selected
  1852. folderNode->children.clear();
  1853. folderNode->loaded = false;
  1854. folderNode->expanded = true;
  1855. load (*folderNode);
  1856. rebuild();
  1857. for (int i = 0; i < (int) rows.size(); ++i)
  1858. if (rows[(std::size_t) i]->file == first)
  1859. {
  1860. select (i, false);
  1861. break;
  1862. }
  1863. browser.showNote (copied == 1 ? tr ("Copied 1 file to {0}", { folder.getFileName() })
  1864. : tr ("Copied {0} files to {1}", { juce::String (copied), folder.getFileName() }));
  1865. }
  1866. void mouseMove (const juce::MouseEvent& e) override
  1867. {
  1868. setHovered (rowAt (e.y));
  1869. // round 190iz: the hover star lights under the mouse (only its box repaints)
  1870. if (const auto over = starBox (hovered).contains (e.getPosition()); over != overStar)
  1871. {
  1872. overStar = over;
  1873. repaint (starBox (hovered));
  1874. }
  1875. }
  1876. void mouseExit (const juce::MouseEvent&) override
  1877. {
  1878. setHovered (-1);
  1879. overStar = false;
  1880. }
  1881. // FL's middle-click / "Send to selected channel or focused plugin" on a row (round 190iz)
  1882. void sendRow (const Node& n)
  1883. {
  1884. if (n.kind == Kind::plugin)
  1885. browser.sendPluginToSelected (n.generator, n.effect);
  1886. else if (! n.folder && n.file.existsAsFile() && ! n.missing)
  1887. browser.sendToSelected (n.file);
  1888. }
  1889. void mouseDown (const juce::MouseEvent& e) override
  1890. {
  1891. dragStarted = false;
  1892. const auto row = rowAt (e.y);
  1893. pressedRow = row;
  1894. if (row < 0)
  1895. return;
  1896. auto& n = *rows[(std::size_t) row];
  1897. // round 190iz (FL manual browser.htm): the star at the row's end = favourite; the middle button = send to the
  1898. // selected channel; Alt+Click = the whole sample (not FL's first 5 seconds)
  1899. if (e.mods.isMiddleButtonDown())
  1900. {
  1901. select (row, false);
  1902. sendRow (n);
  1903. return;
  1904. }
  1905. if (e.mods.isLeftButtonDown() && rowHeight != liveRowHeight && starBox (row).contains (e.getPosition()))
  1906. {
  1907. browser.toggleStarredItem (itemOf (n));
  1908. repaintRow (row);
  1909. return;
  1910. }
  1911. // round 190qi: Ctrl+click / Shift+click mark files for a batch (right-click › "Add tag..." tags them all)
  1912. if (e.mods.isLeftButtonDown() && ! e.mods.isPopupMenu() && (e.mods.isCommandDown() || e.mods.isShiftDown()) && markable (n))
  1913. {
  1914. if (e.mods.isShiftDown() && juce::isPositiveAndBelow (selected, (int) rows.size()))
  1915. {
  1916. marked.clear();
  1917. for (int i = juce::jmin (selected, row); i <= juce::jmax (selected, row); ++i)
  1918. if (markable (*rows[(std::size_t) i]))
  1919. marked.push_back (itemOf (*rows[(std::size_t) i]));
  1920. repaint();
  1921. return;
  1922. }
  1923. if (marked.empty() && juce::isPositiveAndBelow (selected, (int) rows.size()) && selected != row && markable (*rows[(std::size_t) selected]))
  1924. marked.push_back (itemOf (*rows[(std::size_t) selected]));
  1925. const auto item = itemOf (n);
  1926. if (const auto it = std::find (marked.begin(), marked.end(), item); it != marked.end())
  1927. marked.erase (it);
  1928. else
  1929. marked.push_back (item);
  1930. select (row, false);
  1931. repaint();
  1932. return;
  1933. }
  1934. if (! e.mods.isPopupMenu() || ! isMarked (n))
  1935. clearMarks();
  1936. if (e.mods.isAltDown() && ! n.folder)
  1937. browser.askPreview (0.0, true);
  1938. if (e.mods.isPopupMenu())
  1939. {
  1940. select (row, false);
  1941. showMenu (n);
  1942. return;
  1943. }
  1944. if (n.folder)
  1945. {
  1946. select (row, false);
  1947. if (e.getNumberOfClicks() == 1) // a click opens / closes it (the second click of a double click does not undo it)
  1948. toggle (n);
  1949. if (n.kind == Kind::item && e.getNumberOfClicks() == 1) // (round 190oa: a generator entry still selects its channel)
  1950. itemClicked (n);
  1951. return;
  1952. }
  1953. if (n.parameter.kind != AutomationTargetKind::none) // (round 190oa, DF-120: a parameter row)
  1954. {
  1955. select (row, false);
  1956. return;
  1957. }
  1958. if (n.kind == Kind::item)
  1959. {
  1960. select (row, n.item.kind == projectcontents::Kind::sample && ! n.missing);
  1961. itemClicked (n);
  1962. return;
  1963. }
  1964. if (n.kind == Kind::plugin)
  1965. {
  1966. select (row, false);
  1967. return;
  1968. }
  1969. // a click previews, even when the file is already selected (click again: hear it again)
  1970. select (row, true);
  1971. }
  1972. void mouseDrag (const juce::MouseEvent& e) override
  1973. {
  1974. if (dragStarted || e.getDistanceFromDragStart() < 5 || ! juce::isPositiveAndBelow (pressedRow, (int) rows.size()))
  1975. return;
  1976. const auto& n = *rows[(std::size_t) pressedRow];
  1977. auto* container = juce::DragAndDropContainer::findParentDragContainerFor (this);
  1978. if (n.folder || container == nullptr)
  1979. return;
  1980. if (n.kind == Kind::plugin && (n.generator || n.effect)) // a plugin onto the Channel Rack / the Mixer (round 162)
  1981. {
  1982. dragStarted = true;
  1983. draggedPlugin() = { n.generator, n.effect };
  1984. container->startDragging (juce::String (n.generator ? generatorDragDescription : effectDragDescription) + "|" + n.label, this,
  1985. juce::ScaledImage (dragImage (n)), true);
  1986. return;
  1987. }
  1988. if (n.kind == Kind::item && n.item.kind == projectcontents::Kind::pattern) // a pattern onto the Playlist
  1989. {
  1990. dragStarted = true;
  1991. container->startDragging (juce::String (patternDragDescription) + "|" + juce::String (n.item.index), this,
  1992. juce::ScaledImage (dragImage (n)), true);
  1993. return;
  1994. }
  1995. if (n.file.existsAsFile())
  1996. {
  1997. dragStarted = true;
  1998. container->startDragging (juce::String (dragDescription) + "|" + n.file.getFullPathName(), this, juce::ScaledImage (dragImage (n)),
  1999. true);
  2000. }
  2001. }
  2002. void mouseDoubleClick (const juce::MouseEvent& e) override
  2003. {
  2004. const auto row = rowAt (e.y);
  2005. if (row < 0 || rows[(std::size_t) row]->folder || ! e.mods.isLeftButtonDown())
  2006. return;
  2007. const auto& n = *rows[(std::size_t) row];
  2008. if (n.parameter.kind != AutomationTargetKind::none) // (round 190oa, DF-120: a parameter: its automation clip)
  2009. {
  2010. createAutomationClip (browser.engine, n.parameter);
  2011. return;
  2012. }
  2013. if (browser.isHotSwapping() && (n.kind == Kind::plugin || n.kind == Kind::file)) // round 190ce: it replaces the linked device
  2014. {
  2015. select (row, false);
  2016. browser.hotSwapLoadSelected();
  2017. return;
  2018. }
  2019. if (n.kind == Kind::plugin)
  2020. {
  2021. if (n.activate)
  2022. n.activate();
  2023. return;
  2024. }
  2025. if (n.kind != Kind::item)
  2026. {
  2027. browser.openFile (n.file);
  2028. return;
  2029. }
  2030. const auto& item = n.item;
  2031. switch (item.kind)
  2032. {
  2033. case projectcontents::Kind::pattern:
  2034. if (browser.onOpenPattern)
  2035. browser.onOpenPattern (item.index);
  2036. break;
  2037. case projectcontents::Kind::sample:
  2038. if (! n.missing)
  2039. browser.openFile (n.file);
  2040. break;
  2041. case projectcontents::Kind::generator:
  2042. if (browser.onOpenChannel)
  2043. browser.onOpenChannel (item.index);
  2044. break;
  2045. case projectcontents::Kind::effect:
  2046. if (browser.onOpenEffect)
  2047. browser.onOpenEffect (item.index, item.slot);
  2048. break;
  2049. case projectcontents::Kind::automation:
  2050. if (! n.history && ! n.initial && browser.onOpenAutomation)
  2051. browser.onOpenAutomation (item.index);
  2052. break;
  2053. }
  2054. }
  2055. ui::Hint hintAt (juce::Point<int> p) override
  2056. {
  2057. ui::Hint h;
  2058. const auto row = rowAt (p.y);
  2059. if (row < 0)
  2060. {
  2061. h.text = flat ? tr ("Search results: files in the current folder and below that match") : tr ("Browser: [LMB] open a folder or preview a sample");
  2062. return h;
  2063. }
  2064. const auto& n = *rows[(std::size_t) row];
  2065. h.hasMenu = true;
  2066. if (starBox (row).contains (p) && rowHeight != liveRowHeight) // round 190iz: FL's favourite star
  2067. {
  2068. h.text = BrowserComponent::collectionStore().has (itemOf (n), 0) ? tr ("Favorite: [LMB] take it out of the STARRED tab")
  2069. : tr ("Favorite: [LMB] add it to the STARRED tab");
  2070. return h;
  2071. }
  2072. switch (n.kind)
  2073. {
  2074. case Kind::project:
  2075. h.text = tr ("Current project: what this project uses (patterns, effects, generators, automation, audio files) [LMB] open [RMB] expand / collapse all");
  2076. return h;
  2077. case Kind::category:
  2078. h.text = categoryHint (n.category) + " " + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open"));
  2079. h.value = n.detail;
  2080. return h;
  2081. case Kind::fsFolder:
  2082. if (n.depth == 0 || (n.parent != nullptr && n.parent->kind == Kind::project))
  2083. {
  2084. h.text = n.label + ": " + n.file.getFullPathName() + " " + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open")) + " " + tr ("[RMB] menu");
  2085. return h;
  2086. }
  2087. break;
  2088. case Kind::item:
  2089. if (n.parameter.kind != AutomationTargetKind::none) // (round 190oa, DF-120)
  2090. {
  2091. h.text = describeAutomationTarget (browser.engine, n.parameter) + " " + tr ("[2xLMB] create an automation clip [RMB] menu");
  2092. h.automatable = true;
  2093. h.hasMenu = true;
  2094. return h;
  2095. }
  2096. return itemHint (n);
  2097. case Kind::plugins:
  2098. h.text = tr ("Plugin database: LYNX SHARE's built-in generators and effects, FL's engines and the installed plugins") + " "
  2099. + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open"));
  2100. h.value = n.detail;
  2101. return h;
  2102. case Kind::plugin:
  2103. if (factorycontent::isKey (n.pluginKey) && ! n.generator) // round 190ke: a beat or an effect chain
  2104. {
  2105. h.text = n.label + " (" + n.detail + ") " + tr ("[double-click] add it: a beat as a new Drums track at the playhead, a chain on the selected track");
  2106. h.hasMenu = true;
  2107. return h;
  2108. }
  2109. h.text = n.label + " (" + n.detail + ") "
  2110. + (n.generator ? tr ("[double-click] add it as a new channel, or drag it onto the Channel Rack")
  2111. : tr ("[double-click] add it to the selected insert, or drag it onto a mixer insert or an effect slot"));
  2112. h.hasMenu = true;
  2113. return h;
  2114. case Kind::factory:
  2115. h.text = tr ("LYNX content: LYNX's own sounds, beats and effect chains, with tags (the TAGS button filters them)") + " "
  2116. + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open"));
  2117. h.value = n.detail;
  2118. return h;
  2119. case Kind::collection:
  2120. h.text = tr ("Collection: the items you put in it (right-click an item > Collections, or the keys 1-7 on a selected row)") + " "
  2121. + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open")) + " " + tr ("[RMB] menu");
  2122. h.value = n.detail;
  2123. return h;
  2124. case Kind::file:
  2125. break;
  2126. }
  2127. h.text = rowHint (n.file, n.folder, n.expanded);
  2128. h.value = n.folder ? juce::String() : n.file.getFileExtension().substring (1).toUpperCase();
  2129. return h;
  2130. }
  2131. // for snapshots: the first audio file under the first folders on disk (opening them)
  2132. int firstAudioRow()
  2133. {
  2134. for (int pass = 0; pass < 3; ++pass)
  2135. {
  2136. for (int i = 0; i < (int) rows.size(); ++i)
  2137. if (rows[(std::size_t) i]->kind == Kind::file && isAudio (rows[(std::size_t) i]->file))
  2138. return i;
  2139. for (auto* n : rows)
  2140. if (n->kind == Kind::fsFolder && ! n->expanded)
  2141. {
  2142. toggle (*n);
  2143. break;
  2144. }
  2145. }
  2146. return -1;
  2147. }
  2148. // the first row labelled `label`, or -1
  2149. int rowOfFile (const juce::File& file) const
  2150. {
  2151. for (int i = 0; i < (int) rows.size(); ++i)
  2152. if (rows[(std::size_t) i]->file == file)
  2153. return i;
  2154. return -1;
  2155. }
  2156. int rowLabelled (const juce::String& label) const
  2157. {
  2158. for (int i = 0; i < (int) rows.size(); ++i)
  2159. if (rows[(std::size_t) i]->label == label)
  2160. return i;
  2161. return -1;
  2162. }
  2163. // for snapshots: opens these project sections; returns the first row of a sample item
  2164. void scrollRowIntoView (int row) { scrollToRow (row); }
  2165. bool categoryOpen (Category c) const
  2166. {
  2167. const auto row = categoryRow (c);
  2168. return row >= 0 && rows[(std::size_t) row]->expanded;
  2169. }
  2170. // round 190mr (DF-135): the row of a project section's header (−1: not listed)
  2171. int categoryRow (Category c) const
  2172. {
  2173. for (int i = 0; i < (int) rows.size(); ++i)
  2174. if (rows[(std::size_t) i]->kind == Kind::category && rows[(std::size_t) i]->category == c)
  2175. return i;
  2176. return -1;
  2177. }
  2178. int openProjectSections (std::initializer_list<Category> open)
  2179. {
  2180. for (auto* n : std::vector<Node*> (rows))
  2181. if (n->kind == Kind::category && std::find (open.begin(), open.end(), n->category) != open.end() && ! n->expanded)
  2182. {
  2183. n->expanded = true;
  2184. load (*n);
  2185. }
  2186. rebuild();
  2187. for (int i = 0; i < (int) rows.size(); ++i)
  2188. if (rows[(std::size_t) i]->kind == Kind::item && rows[(std::size_t) i]->item.kind == projectcontents::Kind::sample)
  2189. return i;
  2190. return -1;
  2191. }
  2192. // round 190my (FL's Project picker, right-click on a pattern tile): the pattern's row in Current project › Patterns,
  2193. // selected and in view; −1 when it isn't listed
  2194. int revealParameters (bool effect, int index, int slot)
  2195. {
  2196. openProjectSections ({ effect ? Category::effects : Category::generators });
  2197. for (int i = 0; i < (int) rows.size(); ++i)
  2198. {
  2199. auto& n = *rows[(std::size_t) i];
  2200. if (n.kind == Kind::item && n.parameter.kind == AutomationTargetKind::none
  2201. && n.item.kind == (effect ? projectcontents::Kind::effect : projectcontents::Kind::generator) && n.item.index == index
  2202. && (! effect || n.item.slot == slot))
  2203. {
  2204. if (n.folder && ! n.expanded)
  2205. toggle (n);
  2206. for (int j = 0; j < (int) rows.size(); ++j) // (the rows were made again)
  2207. if (rows[(std::size_t) j] == &n)
  2208. {
  2209. select (j, false);
  2210. scrollToRow (j);
  2211. return j;
  2212. }
  2213. return i;
  2214. }
  2215. }
  2216. return -1;
  2217. }
  2218. int revealPattern (int index)
  2219. {
  2220. openProjectSections ({ Category::patterns });
  2221. for (int i = 0; i < (int) rows.size(); ++i)
  2222. if (rows[(std::size_t) i]->kind == Kind::item && rows[(std::size_t) i]->item.kind == projectcontents::Kind::pattern
  2223. && rows[(std::size_t) i]->item.index == index)
  2224. {
  2225. select (i, false);
  2226. scrollToRow (i);
  2227. return i;
  2228. }
  2229. return -1;
  2230. }
  2231. // round 190iz (FL: "drag animations", details DF-100): the drag picture of a file, for the preview strip's drags too
  2232. juce::Image dragImageForFile (const juce::File& f) const
  2233. {
  2234. Node n;
  2235. n.file = f;
  2236. return dragImage (n);
  2237. }
  2238. // the name row `row` shows (round 190iz: --shots pick rows by it)
  2239. juce::String shownName (int row) const
  2240. {
  2241. if (! juce::isPositiveAndBelow (row, (int) rows.size()))
  2242. return {};
  2243. const auto& n = *rows[(std::size_t) row];
  2244. return n.label.isNotEmpty() ? n.label : n.folder || ! isAudio (n.file) ? n.file.getFileName() : n.file.getFileNameWithoutExtension();
  2245. }
  2246. void setHovered (int row)
  2247. {
  2248. if (row != hovered)
  2249. {
  2250. repaintRow (hovered);
  2251. hovered = row;
  2252. repaintRow (hovered);
  2253. }
  2254. }
  2255. // flat mode, PROJECT tab search: every project item whose name matches
  2256. static std::vector<std::unique_ptr<Node>> projectMatches (const Song& song, const juce::String& query)
  2257. {
  2258. const auto parsed = search::parse (query.toStdString());
  2259. std::vector<std::unique_ptr<Node>> found;
  2260. for (auto c : categories)
  2261. {
  2262. if (c == Category::history)
  2263. continue;
  2264. Node section;
  2265. section.kind = Kind::category;
  2266. section.category = c;
  2267. listCategory (section, song, {});
  2268. for (auto& child : section.children)
  2269. if (search::matches (parsed, child->label.toStdString()))
  2270. {
  2271. child->parent = nullptr;
  2272. found.push_back (std::move (child));
  2273. }
  2274. }
  2275. return found;
  2276. }
  2277. private:
  2278. juce::File baseOf (const juce::File& f) const
  2279. {
  2280. for (const auto& b : bases)
  2281. if (f.isAChildOf (b))
  2282. return b;
  2283. return f.getParentDirectory();
  2284. }
  2285. void load (Node& n)
  2286. {
  2287. if (n.loaded)
  2288. return;
  2289. n.loaded = true;
  2290. if (n.kind == Kind::item && (n.item.kind == projectcontents::Kind::effect || n.item.kind == projectcontents::Kind::generator)) // (round 190oa)
  2291. {
  2292. n.children.clear();
  2293. for (const auto& [target, name] : parametersOf (browser.engine, n.item))
  2294. {
  2295. auto c = std::make_unique<Node>();
  2296. c->kind = Kind::item;
  2297. c->label = name;
  2298. c->icon = Icon::tweak;
  2299. c->depth = n.depth + 1;
  2300. c->parent = &n;
  2301. c->parameter = target;
  2302. n.children.push_back (std::move (c));
  2303. }
  2304. return;
  2305. }
  2306. if (n.kind == Kind::project)
  2307. {
  2308. for (auto c : categories)
  2309. {
  2310. auto child = std::make_unique<Node>();
  2311. child->kind = Kind::category;
  2312. child->folder = true;
  2313. child->category = c;
  2314. child->label = categoryName (c);
  2315. child->icon = categoryIcon (c);
  2316. child->depth = n.depth + 1;
  2317. child->parent = &n;
  2318. listCategory (*child, browser.engine.getSong(), &browser.engine, true); // the counts show while closed
  2319. child->children.clear();
  2320. n.children.push_back (std::move (child));
  2321. if (c == Category::initialized && browser.projectFile.existsAsFile()) // then the project's folder (FL's "Project data")
  2322. {
  2323. auto folder = makeFolder (browser.projectFile.getParentDirectory(), tr ("Project folder"), juce::Colour());
  2324. folder->icon = Icon::folder;
  2325. folder->depth = n.depth + 1;
  2326. folder->parent = &n;
  2327. n.children.push_back (std::move (folder));
  2328. }
  2329. }
  2330. return;
  2331. }
  2332. if (n.kind == Kind::category)
  2333. {
  2334. loadCategory (n);
  2335. return;
  2336. }
  2337. auto list = [] (const juce::File& folder, juce::Array<juce::File>& folders, juce::Array<juce::File>& files) {
  2338. #if JUCE_MAC
  2339. // not JUCE's iterator on macOS: one name NSString rejects would end the app as the folder opens (issue #42)
  2340. for (const auto& c : childrenOf (folder))
  2341. (c.isDirectory() ? folders : files).add (c);
  2342. #else
  2343. folders = folder.findChildFiles (juce::File::findDirectories, false, "*", juce::File::FollowSymlinks::noCycles);
  2344. files = folder.findChildFiles (juce::File::findFiles, false, "*", juce::File::FollowSymlinks::noCycles);
  2345. #endif
  2346. };
  2347. juce::Array<juce::File> folders, files;
  2348. std::map<juce::String, juce::Array<juce::File>> alsoOf; // a merged subfolder's other copies (by its path)
  2349. if (n.also.isEmpty())
  2350. list (n.file, folders, files);
  2351. else
  2352. {
  2353. // a merged root (FL's Scores, Mixer presets): the union of its folders, the first one's entry on a clash
  2354. juce::Array<juce::File> sources { n.file };
  2355. sources.addArray (n.also);
  2356. std::vector<juce::Array<juce::File>> srcFolders (sources.size()), srcFiles (sources.size());
  2357. std::vector<browserview::Listing> listings (sources.size());
  2358. for (int i = 0; i < sources.size(); ++i)
  2359. {
  2360. list (sources[i], srcFolders[(std::size_t) i], srcFiles[(std::size_t) i]);
  2361. for (const auto& f : srcFolders[(std::size_t) i])
  2362. listings[(std::size_t) i].folders.push_back (f.getFileName().toStdString());
  2363. for (const auto& f : srcFiles[(std::size_t) i])
  2364. listings[(std::size_t) i].files.push_back (f.getFileName().toStdString());
  2365. }
  2366. auto find = [] (const juce::Array<juce::File>& in, const std::string& name) {
  2367. for (const auto& f : in)
  2368. if (f.getFileName().equalsIgnoreCase (juce::String (name)))
  2369. return f;
  2370. return juce::File();
  2371. };
  2372. const auto merged = browserview::mergeListings (listings);
  2373. for (const auto& e : merged.folders)
  2374. {
  2375. const auto f = find (srcFolders[(std::size_t) e.from], e.name);
  2376. folders.add (f);
  2377. for (const auto a : e.also)
  2378. alsoOf[f.getFullPathName()].add (find (srcFolders[(std::size_t) a], e.name));
  2379. }
  2380. for (const auto& e : merged.files)
  2381. files.add (find (srcFiles[(std::size_t) e.from], e.name));
  2382. }
  2383. auto byName = [] (const juce::File& a, const juce::File& b) { return a.getFileName().compareNatural (b.getFileName()) < 0; };
  2384. std::sort (folders.begin(), folders.end(), byName);
  2385. std::sort (files.begin(), files.end(), byName);
  2386. for (const auto& f : folders)
  2387. {
  2388. if (f.isHidden() || f.getFileName().startsWithChar ('.') || browser.hidesFolderNamed (f.getFileName())) // (round 190qi)
  2389. continue;
  2390. const auto also = alsoOf.count (f.getFullPathName()) ? alsoOf[f.getFullPathName()] : juce::Array<juce::File>();
  2391. if (browser.filterHides (f) && std::all_of (also.begin(), also.end(), [this] (const juce::File& a) { return browser.filterHides (a); }))
  2392. continue; // nothing in it is listed under the content filter (round 164)
  2393. auto c = std::make_unique<Node>();
  2394. c->kind = Kind::fsFolder;
  2395. c->file = f;
  2396. c->also = also;
  2397. c->folder = true;
  2398. c->depth = n.depth + 1;
  2399. c->parent = &n;
  2400. n.children.push_back (std::move (c));
  2401. }
  2402. for (const auto& f : files)
  2403. if (browser.lists (f))
  2404. {
  2405. auto c = std::make_unique<Node>();
  2406. c->file = f;
  2407. c->depth = n.depth + 1;
  2408. c->parent = &n;
  2409. n.children.push_back (std::move (c));
  2410. }
  2411. }
  2412. void loadCategory (Node& n)
  2413. {
  2414. n.loaded = true;
  2415. n.children.clear();
  2416. listCategory (n, browser.engine.getSong(), &browser.engine);
  2417. }
  2418. // The items of one project section (history needs the engine; the PROJECT search passes none).
  2419. static void listCategory (Node& n, const Song& song, AudioEngine* engine, bool countOnly = false)
  2420. {
  2421. auto add = [&n] (projectcontents::Item item, Icon icon, juce::Colour colour) -> Node& {
  2422. auto c = std::make_unique<Node>();
  2423. c->kind = Kind::item;
  2424. c->label = juce::String::fromUTF8 (item.name.c_str());
  2425. c->detail = juce::String::fromUTF8 (item.detail.c_str());
  2426. c->colour = colour;
  2427. c->icon = icon;
  2428. c->depth = n.depth + 1;
  2429. c->parent = &n;
  2430. c->item = std::move (item);
  2431. n.children.push_back (std::move (c));
  2432. return *n.children.back();
  2433. };
  2434. switch (n.category)
  2435. {
  2436. case Category::history:
  2437. if (engine != nullptr)
  2438. {
  2439. // each label compares two whole states: only listed while the section is open, the last 30
  2440. const auto size = engine->getHistorySize(), at = engine->getHistoryPosition();
  2441. for (int i = size - 1; ! countOnly && i >= juce::jmax (0, size - 30); --i) // newest first, as FL lists it
  2442. {
  2443. const auto l = engine->getHistoryLabel (i);
  2444. projectcontents::Item item;
  2445. item.kind = projectcontents::Kind::automation; // (unused for history rows)
  2446. item.index = i;
  2447. item.name = tr (l.text, { juce::String::fromUTF8 (l.arg.c_str()) }).toStdString();
  2448. auto& node = add (std::move (item), Icon::undo, juce::Colour());
  2449. node.history = true;
  2450. node.current = i == at;
  2451. }
  2452. n.detail = juce::String (size);
  2453. }
  2454. break;
  2455. case Category::patterns:
  2456. for (auto& item : projectcontents::patterns (song))
  2457. {
  2458. const auto colour = PlaylistComponent::patternColour (song, item.index);
  2459. const auto current = item.index == song.currentPattern;
  2460. if (item.uses == 0)
  2461. item.detail = tr ("not in the Playlist").toStdString();
  2462. add (std::move (item), Icon::pattern, colour).current = current;
  2463. }
  2464. break;
  2465. case Category::effects:
  2466. for (auto& item : projectcontents::effects (song))
  2467. {
  2468. auto picture = engine != nullptr && ! countOnly ? entryPicture (song, item, nullptr) : juce::Image();
  2469. auto& node = add (item, item.plugin ? Icon::plugin : Icon::mixer, item.colour != 0 ? juce::Colour (item.colour) : juce::Colour());
  2470. node.folder = engine != nullptr && ! countOnly; // (round 190oa, DF-120: opens to its parameters)
  2471. addThumb (node, picture); // (round 190oa, DF-109: its picture under it)
  2472. }
  2473. break;
  2474. case Category::generators:
  2475. for (auto& item : projectcontents::generators (song))
  2476. {
  2477. const auto& channel = song.channels[(std::size_t) item.index];
  2478. const auto icon = item.plugin ? Icon::plugin
  2479. : projectcontents::playsSampleFile (channel.instrument) ? Icon::audioFile
  2480. : Icon::keyboard;
  2481. const auto colour = channel.instrument == InstrumentKind::audioClip ? PlaylistComponent::audioClipColour (channel)
  2482. : item.colour != 0 ? juce::Colour (item.colour)
  2483. : juce::Colour();
  2484. const auto selected = engine != nullptr && engine->getSelectedChannel() == item.index;
  2485. const auto plugin = channel.instrument == InstrumentKind::plugin;
  2486. // (round 190oa, DF-109: FL draws generator plugins' pictures; sample / audio clip channels are text)
  2487. auto picture = engine != nullptr && ! countOnly && ! projectcontents::playsSampleFile (channel.instrument)
  2488. ? entryPicture (song, item, &gens (*engine))
  2489. : juce::Image();
  2490. auto& node = add (std::move (item), icon, colour);
  2491. node.current = selected;
  2492. node.folder = plugin && engine != nullptr && ! countOnly; // (round 190oa, DF-120: a plugin opens to its parameters)
  2493. addThumb (node, picture);
  2494. }
  2495. break;
  2496. case Category::automation:
  2497. for (auto& item : projectcontents::automations (song))
  2498. add (item, Icon::automate, item.colour != 0 ? juce::Colour (item.colour) : theme::colour::automation);
  2499. break;
  2500. case Category::initialized:
  2501. for (int i = 0; i < (int) song.initialValues.size(); ++i)
  2502. {
  2503. const auto& v = song.initialValues[(std::size_t) i];
  2504. projectcontents::Item item;
  2505. item.kind = projectcontents::Kind::automation;
  2506. item.index = i;
  2507. item.name = (engine != nullptr ? describeAutomationTarget (*engine, v.target) : juce::String ("?")).toStdString();
  2508. item.detail = std::to_string ((int) std::lround (v.value * 100.0f)) + "%";
  2509. add (std::move (item), Icon::automate, theme::colour::automation).initial = true;
  2510. }
  2511. break;
  2512. case Category::samples:
  2513. for (auto& item : projectcontents::samples (song))
  2514. {
  2515. const juce::String path = juce::String::fromUTF8 (item.path.c_str());
  2516. const juce::File file (juce::File::isAbsolutePath (path) ? path : juce::String());
  2517. auto colour = item.colour != 0 ? juce::Colour (item.colour) : theme::colour::audioClip;
  2518. if (item.index >= 0 && song.channels[(std::size_t) item.index].instrument == InstrumentKind::audioClip)
  2519. colour = PlaylistComponent::audioClipColour (song.channels[(std::size_t) item.index]);
  2520. auto& node = add (std::move (item), Icon::audioFile, colour);
  2521. node.file = file;
  2522. node.missing = ! countOnly && ! file.existsAsFile();
  2523. if (node.missing)
  2524. node.detail = tr ("missing");
  2525. }
  2526. break;
  2527. }
  2528. if (n.category != Category::history)
  2529. n.detail = juce::String ((int) n.children.size());
  2530. }
  2531. static juce::String signature (const Node& n)
  2532. {
  2533. juce::String s;
  2534. for (const auto& c : n.children)
  2535. s << c->label << '|' << c->detail << '|' << (int) c->colour.getARGB() << '|' << (int) c->missing << '|' << c->item.index << '|'
  2536. << c->item.slot << '\n';
  2537. return s;
  2538. }
  2539. juce::String selectionKey() const
  2540. {
  2541. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  2542. return {};
  2543. const auto& n = *rows[(std::size_t) selected];
  2544. if (n.kind != Kind::item)
  2545. return "f:" + n.file.getFullPathName() + n.label;
  2546. return "i:" + juce::String ((int) n.item.kind) + ":" + juce::String (n.item.index) + ":" + juce::String (n.item.slot) + ":"
  2547. + juce::String::fromUTF8 (n.item.path.c_str()) + (n.history ? "h" : "");
  2548. }
  2549. void restoreSelection (const juce::String& key)
  2550. {
  2551. if (key.isEmpty())
  2552. return;
  2553. const auto keep = selected;
  2554. selected = -1;
  2555. for (int i = 0; i < (int) rows.size(); ++i)
  2556. {
  2557. selected = i;
  2558. if (selectionKey() == key)
  2559. return;
  2560. }
  2561. selected = -1;
  2562. juce::ignoreUnused (keep);
  2563. }
  2564. void itemClicked (Node& n)
  2565. {
  2566. auto& engine = browser.engine;
  2567. const auto& item = n.item;
  2568. if (n.history)
  2569. {
  2570. engine.jumpToHistory (item.index);
  2571. return;
  2572. }
  2573. if (n.initial)
  2574. return;
  2575. switch (item.kind)
  2576. {
  2577. case projectcontents::Kind::pattern: // FL: clicking a pattern makes it the current one
  2578. if (item.index != engine.getSong().currentPattern && item.index < (int) engine.getSong().patterns.size())
  2579. engine.editSong ([index = item.index] (Song& s) { s.currentPattern = index; }, false);
  2580. break;
  2581. case projectcontents::Kind::generator:
  2582. if (item.index < (int) engine.getSong().channels.size())
  2583. engine.setSelectedChannel (item.index);
  2584. break;
  2585. case projectcontents::Kind::sample:
  2586. case projectcontents::Kind::effect:
  2587. case projectcontents::Kind::automation:
  2588. break;
  2589. }
  2590. }
  2591. ui::Hint itemHint (const Node& n) const
  2592. {
  2593. ui::Hint h;
  2594. h.hasMenu = true;
  2595. const auto& item = n.item;
  2596. if (n.initial)
  2597. {
  2598. h.text = n.label + ": " + tr ("reset to this value when the song starts [RMB] delete the initial value");
  2599. h.value = n.detail;
  2600. return h;
  2601. }
  2602. if (n.history)
  2603. {
  2604. h.text = tr ("Undo history: [LMB] go back to this step");
  2605. h.value = tr ("Level {0}/{1}", { juce::String (item.index + 1), juce::String (browser.engine.getHistorySize()) });
  2606. return h;
  2607. }
  2608. switch (item.kind)
  2609. {
  2610. case projectcontents::Kind::pattern:
  2611. h.text = n.label + ": " + tr ("[LMB] make it the current pattern [2xLMB] open in the Piano Roll drag into the Playlist [RMB] pattern menu");
  2612. h.value = item.uses == 0 ? tr ("not in the Playlist") : tr ("{0} clips", { juce::String (item.uses) });
  2613. break;
  2614. case projectcontents::Kind::sample:
  2615. h.text = juce::String::fromUTF8 (item.path.c_str()) + " "
  2616. + (n.missing ? tr ("(missing: File > Missing files... finds it)")
  2617. : tr ("[LMB] preview [2xLMB] new channel drag to the Playlist or the Channel Rack [RMB] menu"));
  2618. h.value = tr ("used {0}x", { juce::String (item.uses) });
  2619. break;
  2620. case projectcontents::Kind::generator:
  2621. h.text = n.label + (n.detail.isNotEmpty() ? " (" + n.detail + ")" : juce::String()) + ": "
  2622. + tr ("[LMB] select the channel [2xLMB] open its settings [RMB] menu");
  2623. break;
  2624. case projectcontents::Kind::effect:
  2625. h.text = n.label + " (" + n.detail + "): " + tr ("[2xLMB] open its editor [RMB] menu");
  2626. h.value = tr ("slot {0}", { juce::String (item.slot + 1) });
  2627. break;
  2628. case projectcontents::Kind::automation:
  2629. h.text = n.label + ": " + tr ("[2xLMB] open the automation editor");
  2630. h.value = item.uses == 0 ? tr ("not in the Playlist") : tr ("{0} clips", { juce::String (item.uses) });
  2631. break;
  2632. }
  2633. return h;
  2634. }
  2635. // --- round 166f (issue #16): the user's Plugin database folders (FL's folders, shown as headings in the slot menus)
  2636. void setPluginFolder (const std::string& key, bool instruments, const std::string& path)
  2637. {
  2638. auto& host = browser.engine.getPluginHost();
  2639. auto folders = host.databaseFolders();
  2640. plugincatalog::moveToFolder (folders, instruments, key, path);
  2641. host.setDatabaseFolders (folders);
  2642. browser.rebuildTree();
  2643. }
  2644. void askFolderName (const juce::String& title, const juce::String& initial, std::function<void (const std::string&)> done)
  2645. {
  2646. auto* window = new juce::AlertWindow (title, tr ("Folders hold plugins in the Plugin database; the mixer slot and the Channel Rack menus list each folder under its own heading. A / makes a subfolder (\"Stock/EQ\")."),
  2647. juce::MessageBoxIconType::NoIcon);
  2648. window->addTextEditor ("name", initial);
  2649. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  2650. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  2651. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, done] (int result) {
  2652. const auto name = plugincatalog::cleanFolder (window->getTextEditorContents ("name").toStdString());
  2653. if (result == 1 && ! name.empty() && done) done (name);
  2654. }),
  2655. true);
  2656. }
  2657. void addFolderItems (juce::PopupMenu& menu, Node& n)
  2658. {
  2659. auto safe = juce::Component::SafePointer<FileTree> (this);
  2660. const bool instruments = n.folderKind == 1;
  2661. const auto path = n.userFolder;
  2662. auto update = [safe, instruments] (std::function<void (plugincatalog::Folders&)> change) {
  2663. if (safe == nullptr) return;
  2664. auto& host = safe->browser.engine.getPluginHost();
  2665. auto folders = host.databaseFolders();
  2666. change (folders);
  2667. host.setDatabaseFolders (folders);
  2668. safe->browser.rebuildTree();
  2669. };
  2670. menu.addSeparator();
  2671. menu.addItem (path.empty() ? tr ("New folder...") : tr ("New subfolder..."), [safe, update, instruments, path] {
  2672. if (safe != nullptr)
  2673. safe->askFolderName (tr ("New folder"), {}, [update, instruments, path] (const std::string& name) {
  2674. update ([=] (plugincatalog::Folders& f) { plugincatalog::addFolder (f, instruments, path.empty() ? name : path + "/" + name); });
  2675. });
  2676. });
  2677. if (! path.empty())
  2678. {
  2679. menu.addItem (tr ("Rename folder..."), [safe, update, instruments, path] {
  2680. if (safe != nullptr)
  2681. safe->askFolderName (tr ("Rename folder"), juce::String::fromUTF8 (path.c_str()), [update, instruments, path] (const std::string& name) {
  2682. update ([=] (plugincatalog::Folders& f) { plugincatalog::renameFolder (f, instruments, path, name); });
  2683. });
  2684. });
  2685. menu.addItem (tr ("Delete folder (its plugins go back to their usual folder)"), [safe, update, instruments, path] {
  2686. if (safe == nullptr) return;
  2687. std::vector<std::string> keys;
  2688. if (instruments) for (const auto& e : quickpick::generatorEntries (safe->browser.engine)) keys.push_back (e.key);
  2689. else for (const auto& e : quickpick::effectEntries (safe->browser.engine)) keys.push_back (e.key);
  2690. update ([=] (plugincatalog::Folders& f) { plugincatalog::removeFolder (f, instruments, path, keys); });
  2691. });
  2692. }
  2693. else
  2694. {
  2695. // FL's own arrangement: the folders of FL Studio's Plugin database (Effects / Generators), when FL is here
  2696. const auto fl = findFlStudio();
  2697. const auto base = fl.userData.getChildFile ("Presets").getChildFile ("Plugin database").getChildFile (instruments ? "Generators" : "Effects");
  2698. menu.addItem (tr ("Folders from FL Studio's Plugin database"), base.isDirectory(), false, [safe, update, instruments, base] {
  2699. if (safe == nullptr) return;
  2700. std::vector<std::string> files;
  2701. for (const auto& entry : juce::RangedDirectoryIterator (base, true, "*.fst", juce::File::findFiles))
  2702. files.push_back (entry.getFile().getRelativePathFrom (base).replaceCharacter ('\\', '/').toStdString());
  2703. std::vector<std::pair<std::string, std::string>> names;
  2704. auto& engine = safe->browser.engine;
  2705. if (instruments) for (const auto& e : quickpick::generatorEntries (engine)) names.push_back ({ e.key, e.label.toStdString() });
  2706. else for (const auto& e : quickpick::effectEntries (engine)) names.push_back ({ e.key, e.label.toStdString() });
  2707. int placed = 0;
  2708. update ([&] (plugincatalog::Folders& f) { placed = plugincatalog::importFlFolders (f, instruments, files, names); });
  2709. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin database"),
  2710. tr ("{0} plugins placed in the folders of FL Studio's Plugin database.", { juce::String (placed) }));
  2711. });
  2712. }
  2713. }
  2714. // FL's "Delete file..." on a Plugin database entry (round 190bf): to the recycle bin after asking; the plugin leaves
  2715. // the menus' folders and the picker (it stays installed), as when the file is deleted in the file manager
  2716. void deleteDatabaseEntry (const juce::File& entry)
  2717. {
  2718. auto safe = juce::Component::SafePointer<FileTree> (this);
  2719. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::WarningIcon, tr ("Delete file"),
  2720. tr ("Move \"{0}\" to the recycle bin?", { entry.getFileName() }), tr ("Delete"), tr ("Cancel"), nullptr,
  2721. juce::ModalCallbackFunction::create ([safe, entry] (int result) {
  2722. if (result == 0 || safe == nullptr)
  2723. return;
  2724. if (! entry.moveToTrash())
  2725. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Delete file"),
  2726. tr ("The file could not be deleted."));
  2727. quickpick::refreshPluginDatabase (safe->browser.engine, true);
  2728. safe->browser.rebuildTree();
  2729. }));
  2730. }
  2731. public:
  2732. void renamePlugin (const std::string& key, const juce::String& original)
  2733. {
  2734. auto safe = juce::Component::SafePointer<FileTree> (this);
  2735. quickpick::rename (browser.engine, key, original, [safe] {
  2736. if (safe != nullptr)
  2737. safe->browser.rebuildTree();
  2738. });
  2739. }
  2740. bool renameSelectedPlugin()
  2741. {
  2742. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  2743. return false;
  2744. const auto& n = *rows[(std::size_t) selected];
  2745. if (n.kind != Kind::plugin || n.pluginKey.empty())
  2746. return false;
  2747. renamePlugin (n.pluginKey, n.original);
  2748. return true;
  2749. }
  2750. // --snapshot (round 190bf): the menu a right-click on that row shows (the Plugin database's), without showing it
  2751. juce::PopupMenu menuForSnapshot (int row)
  2752. {
  2753. juce::PopupMenu out;
  2754. if (! juce::isPositiveAndBelow (row, (int) rows.size()))
  2755. return out;
  2756. captured = &out;
  2757. showMenu (*rows[(std::size_t) row]);
  2758. captured = nullptr;
  2759. return out;
  2760. }
  2761. int firstRowOfKind (bool plugin) const
  2762. {
  2763. for (int i = 0; i < (int) rows.size(); ++i)
  2764. if (rows[(std::size_t) i]->kind == (plugin ? Kind::plugin : Kind::plugins) && (plugin || rows[(std::size_t) i]->folderKind >= 0))
  2765. return i;
  2766. return -1;
  2767. }
  2768. private:
  2769. juce::PopupMenu* captured = nullptr;
  2770. void present (juce::PopupMenu& menu)
  2771. {
  2772. if (captured != nullptr)
  2773. *captured = menu;
  2774. else
  2775. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  2776. }
  2777. void showMenu (Node& n)
  2778. {
  2779. auto& engine = browser.engine;
  2780. juce::PopupMenu menu;
  2781. if (n.parameter.kind != AutomationTargetKind::none) // (round 190oa, DF-120: a parameter row)
  2782. {
  2783. menu.addItem (tr ("Create automation clip"), [&engine, t = n.parameter] { createAutomationClip (engine, t); });
  2784. menu.addItem (tr ("Link to controller..."), [&engine, t = n.parameter] { openRemoteControlSettings (engine, { t }); });
  2785. present (menu);
  2786. return;
  2787. }
  2788. auto safe = juce::Component::SafePointer<FileTree> (this);
  2789. auto expandItems = [&menu, safe, &n] {
  2790. Node* target = &n;
  2791. while (target != nullptr && target->kind == Kind::item)
  2792. target = target->parent;
  2793. menu.addItem (tr ("Expand all"), [safe, target] {
  2794. if (safe != nullptr && target != nullptr)
  2795. safe->expandAll (*target);
  2796. });
  2797. menu.addItem (tr ("Collapse all"), [safe] {
  2798. if (safe != nullptr)
  2799. safe->collapseAll();
  2800. });
  2801. };
  2802. // (issue #104: the items below act on the Plugin database folder as it is on disk now)
  2803. if (n.kind == Kind::plugin || n.kind == Kind::plugins)
  2804. quickpick::refreshPluginDatabase (engine, true);
  2805. if (n.kind == Kind::plugin && factorycontent::isKey (n.pluginKey)) // round 190ke: LYNX's own content
  2806. {
  2807. menu.addSectionHeader (n.label);
  2808. menu.addItem (tr ("Add"), [act = n.activate] {
  2809. if (act)
  2810. act();
  2811. });
  2812. if (const auto item = itemOf (n); ! item.empty())
  2813. browser.addCollectionItems (menu, item);
  2814. present (menu);
  2815. return;
  2816. }
  2817. if (n.kind == Kind::plugin)
  2818. {
  2819. menu.addSectionHeader (n.label);
  2820. // round 190iz (REA round 143 B5: FL's first item on a plugin): a generator replaces the selected channel's
  2821. // (FL's Enter), an effect goes into the selected insert
  2822. menu.addItem (tr ("Send to selected channel or focused plugin"), [safe, generator = n.generator, effect = n.effect] {
  2823. if (safe != nullptr)
  2824. safe->browser.sendPluginToSelected (generator, effect);
  2825. });
  2826. menu.addItem (tr ("Add"), [act = n.activate] {
  2827. if (act)
  2828. act();
  2829. });
  2830. if (! n.pluginKey.empty()) // FL's renamed plugins (issue #11): "1_EQ" is then picked by typing 1 on an empty slot
  2831. {
  2832. menu.addSeparator();
  2833. menu.addItem (tr ("Rename...") + "\tF2", [safe, key = n.pluginKey, original = n.original] {
  2834. if (safe != nullptr)
  2835. safe->renamePlugin (key, original);
  2836. });
  2837. menu.addItem (tr ("Original name"), n.label != n.original, false, [safe, key = n.pluginKey] {
  2838. if (safe != nullptr)
  2839. {
  2840. safe->browser.engine.getPluginHost().setPluginName (key, {});
  2841. safe->browser.rebuildTree();
  2842. }
  2843. });
  2844. // round 166f (issue #16): FL's Plugin database folders — the slot menus list each folder under a heading
  2845. const bool instruments = (bool) n.generator;
  2846. const auto& folders = engine.getPluginHost().databaseFolders();
  2847. const auto it = folders.of.find (n.pluginKey);
  2848. const auto now = it != folders.of.end() && folders.kind (instruments).count (it->second) ? it->second : std::string();
  2849. juce::PopupMenu move;
  2850. for (const auto& path : folders.kind (instruments))
  2851. move.addItem (juce::String::fromUTF8 (plugincatalog::groupHeading (path).c_str()), true, path == now, [safe, key = n.pluginKey, instruments, path] {
  2852. if (safe != nullptr) safe->setPluginFolder (key, instruments, path);
  2853. });
  2854. if (! folders.kind (instruments).empty()) move.addSeparator();
  2855. move.addItem (tr ("New folder..."), [safe, key = n.pluginKey, instruments] {
  2856. if (safe != nullptr)
  2857. safe->askFolderName (tr ("New folder"), {}, [safe, key, instruments] (const std::string& name) {
  2858. if (safe != nullptr) safe->setPluginFolder (key, instruments, name);
  2859. });
  2860. });
  2861. move.addItem (tr ("No folder"), ! now.empty(), now.empty(), [safe, key = n.pluginKey, instruments] {
  2862. if (safe != nullptr) safe->setPluginFolder (key, instruments, {});
  2863. });
  2864. menu.addSubMenu (tr ("Move to folder"), move);
  2865. }
  2866. if (const auto item = itemOf (n); ! item.empty()) // round 190ce: the collections take Plugin database entries too
  2867. browser.addCollectionItems (menu, item);
  2868. // FL's "System" group on an entry (round 190bf, fl190be q1-entry-menu.png): its file in the Plugin database
  2869. // folder (the Installed one for a plugin in no folder). FL's "Windows shell menu" is left out: LYNX has no
  2870. // shell context menu of its own.
  2871. {
  2872. const auto entry = n.pluginKey.empty() ? juce::File() : quickpick::pluginDatabaseEntry (n.pluginKey, (bool) n.generator);
  2873. const auto ok = entry.existsAsFile();
  2874. menu.addSectionHeader (tr ("System"));
  2875. menu.addItem (tr ("Open parent folder"), ok, false, [entry] { entry.getParentDirectory().startAsProcess(); });
  2876. menu.addItem (tr ("Locate file"), ok, false, [entry] { entry.revealToUser(); });
  2877. menu.addItem (tr ("Delete file..."), ok, false, [safe, entry] {
  2878. if (safe != nullptr)
  2879. safe->deleteDatabaseEntry (entry);
  2880. });
  2881. }
  2882. present (menu);
  2883. return;
  2884. }
  2885. if (n.kind == Kind::collection)
  2886. {
  2887. auto safeBrowser = juce::Component::SafePointer<BrowserComponent> (&browser);
  2888. ui::addItemHeader (menu, tr ("Collection"), n.label, n.colour);
  2889. menu.addItem (tr ("Rename..."), [safeBrowser, c = n.collection] {
  2890. if (safeBrowser != nullptr)
  2891. safeBrowser->renameCollection (c);
  2892. });
  2893. menu.addItem (tr ("Hide this collection"), n.collection != 0 || BrowserComponent::collectionStore().shown().size() > 1, false, [safeBrowser, c = n.collection] {
  2894. if (safeBrowser != nullptr)
  2895. safeBrowser->setCollectionShown (c, false);
  2896. });
  2897. // the collections the STARRED tab lists (round 190cy: here, as Live's Collections › Edit, since the
  2898. // Clip-launch workflow's row menu has only the labels)
  2899. juce::PopupMenu show;
  2900. for (int c = 0; c < collections::count; ++c)
  2901. show.addItem (BrowserComponent::collectionName (c), true, BrowserComponent::collectionStore().isShown (c), [safeBrowser, c] {
  2902. if (safeBrowser != nullptr)
  2903. safeBrowser->setCollectionShown (c, ! BrowserComponent::collectionStore().isShown (c));
  2904. });
  2905. menu.addSubMenu (tr ("Show in the STARRED tab"), show);
  2906. present (menu);
  2907. return;
  2908. }
  2909. if (n.kind == Kind::project || n.kind == Kind::category || n.kind == Kind::plugins || n.kind == Kind::factory)
  2910. {
  2911. menu.addSectionHeader (n.label);
  2912. expandItems();
  2913. juce::File databaseDir; // (a Plugin database folder: its place on disk)
  2914. if (n.kind == Kind::plugins && n.folderKind >= 0) // round 166f (issue #16): the user's folders
  2915. addFolderItems (menu, n);
  2916. if (n.kind == Kind::plugins)
  2917. {
  2918. // round 190ba (issue #104): the Plugin database is a folder the user can arrange in the file manager, as
  2919. // FL's (its Browser opens the folder from this menu too). The database itself, Effects / Generators, one
  2920. // of the user's folders; LYNX's own groups (LYNX SHARE, FL engines, Installed) open the Installed entries
  2921. juce::File dir = quickpick::pluginDatabaseFolder();
  2922. if (n.folderKind >= 0)
  2923. dir = quickpick::pluginDatabaseFolder (n.folderKind == 1, n.userFolder);
  2924. else if (n.isGroup && n.parent != nullptr && n.parent->kind == Kind::plugins && n.parent->folderKind >= 0)
  2925. dir = juce::File (juce::String::fromUTF8 (plugindb::groupFolder (dir.getFullPathName().toStdString(), n.parent->folderKind == 1, n.group).c_str()));
  2926. databaseDir = dir;
  2927. }
  2928. if ((n.kind == Kind::project || n.kind == Kind::plugins) && n.parent == nullptr && browser.shownTab() == allTab) // round 163
  2929. {
  2930. menu.addSeparator();
  2931. browser.addHideItem (menu, n.kind == Kind::project ? browserview::projectRootId : browserview::pluginsRootId, n.label);
  2932. }
  2933. if (n.kind == Kind::plugins)
  2934. {
  2935. // FL's "System" group at the end of a folder's menu (round 190bf, fl190be q1-folder-menu.png): "Open"
  2936. // (FL's "Windows shell menu" is left out: LYNX has no shell context menu of its own)
  2937. menu.addSectionHeader (tr ("System"));
  2938. menu.addItem (tr ("Open"), databaseDir.isDirectory(), false, [dir = databaseDir] { dir.startAsProcess(); });
  2939. }
  2940. present (menu);
  2941. return;
  2942. }
  2943. if (n.kind != Kind::item)
  2944. {
  2945. if (n.folder)
  2946. browser.showFolderMenu (n.file, [safe, node = &n] {
  2947. if (safe != nullptr)
  2948. safe->expandFolder (*node, 3);
  2949. });
  2950. else
  2951. browser.showFileMenu (n.file);
  2952. return;
  2953. }
  2954. const auto item = n.item;
  2955. if (n.history)
  2956. return;
  2957. if (n.initial)
  2958. {
  2959. const auto& values = engine.getSong().initialValues;
  2960. if (! juce::isPositiveAndBelow (item.index, (int) values.size()))
  2961. return;
  2962. menu.addSectionHeader (n.label + ": " + n.detail);
  2963. menu.addItem (tr ("Delete initial value"), [&engine, target = values[(std::size_t) item.index].target] {
  2964. engine.editSong ([target] (Song& s) { s.removeInitialValue (target); });
  2965. });
  2966. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  2967. return;
  2968. }
  2969. switch (item.kind)
  2970. {
  2971. case projectcontents::Kind::pattern: // FL: the right-click makes it the current pattern, then its menu
  2972. itemClicked (n);
  2973. if (browser.onPatternMenu)
  2974. browser.onPatternMenu (item.index);
  2975. return;
  2976. case projectcontents::Kind::sample:
  2977. {
  2978. const auto file = n.file;
  2979. const auto ok = ! n.missing;
  2980. ui::addItemHeader (menu, tr ("Audio file"), n.label, n.colour);
  2981. menu.addItem (tr ("Send to the selected channel"), ok && browser.onLoadIntoChannel != nullptr, false, [safe, file] {
  2982. if (safe != nullptr && safe->browser.onLoadIntoChannel)
  2983. safe->browser.onLoadIntoChannel (file);
  2984. });
  2985. menu.addItem (tr ("Open in a new channel"), ok, false, [safe, file] {
  2986. if (safe != nullptr)
  2987. safe->browser.openFile (file);
  2988. });
  2989. menu.addItem (tr ("Send to the Playlist as an audio clip"), ok && browser.onSendToPlaylist != nullptr, false, [safe, file] {
  2990. if (safe != nullptr && safe->browser.onSendToPlaylist)
  2991. safe->browser.onSendToPlaylist (file);
  2992. });
  2993. menu.addSeparator();
  2994. menu.addItem (tr ("Edit in the audio editor..."), ok, false, [&engine, file] { openAudioEditor (engine, file); });
  2995. if (item.index >= 0)
  2996. menu.addItem (tr ("Show its channel"), [safe, channel = item.index] {
  2997. if (safe != nullptr && channel < (int) safe->browser.engine.getSong().channels.size())
  2998. safe->browser.engine.setSelectedChannel (channel);
  2999. });
  3000. menu.addSeparator();
  3001. menu.addItem (tr ("Show in the file manager"), ok, false, [file] { file.revealToUser(); });
  3002. workflowextras::addBrowserDeleteItem (menu, engine, false, item.index); // round 190iu (issue #191.6): a take
  3003. break;
  3004. }
  3005. case projectcontents::Kind::generator:
  3006. ui::addItemHeader (menu, tr ("Generator"), n.label, n.colour);
  3007. menu.addItem (tr ("Open settings"), [safe, channel = item.index] {
  3008. if (safe != nullptr && safe->browser.onOpenChannel)
  3009. safe->browser.onOpenChannel (channel);
  3010. });
  3011. if (engine.getSong().channels[(std::size_t) item.index].mixerTrack > 0)
  3012. menu.addItem (tr ("Show its mixer insert"), [safe, track = engine.getSong().channels[(std::size_t) item.index].mixerTrack] {
  3013. if (safe != nullptr && safe->browser.onShowInsert)
  3014. safe->browser.onShowInsert (track);
  3015. });
  3016. break;
  3017. case projectcontents::Kind::effect:
  3018. ui::addItemHeader (menu, tr ("Effect") + " - " + n.detail, n.label, n.colour);
  3019. menu.addItem (tr ("View editor"), [safe, track = item.index, slot = item.slot] {
  3020. if (safe != nullptr && safe->browser.onOpenEffect)
  3021. safe->browser.onOpenEffect (track, slot);
  3022. });
  3023. menu.addItem (tr ("Show its mixer insert"), [safe, track = item.index] {
  3024. if (safe != nullptr && safe->browser.onShowInsert)
  3025. safe->browser.onShowInsert (track);
  3026. });
  3027. break;
  3028. case projectcontents::Kind::automation:
  3029. ui::addItemHeader (menu, tr ("Automation clip"), n.label, n.colour);
  3030. menu.addItem (tr ("Open the automation editor"), [safe, index = item.index] {
  3031. if (safe != nullptr && safe->browser.onOpenAutomation)
  3032. safe->browser.onOpenAutomation (index);
  3033. });
  3034. workflowextras::addBrowserDeleteItem (menu, engine, true, item.index); // round 190iu (issue #191.6)
  3035. break;
  3036. }
  3037. menu.addSeparator();
  3038. expandItems();
  3039. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  3040. }
  3041. void addRows (Node& n)
  3042. {
  3043. for (auto& c : n.children)
  3044. {
  3045. rows.push_back (c.get());
  3046. for (auto& t : c->thumbRows) // (round 190oa, DF-109: the picture's lines, right under its entry)
  3047. rows.push_back (t.get());
  3048. if (c->folder && c->expanded)
  3049. addRows (*c);
  3050. }
  3051. }
  3052. void toggle (Node& n)
  3053. {
  3054. const auto keep = selectionKey();
  3055. n.expanded = ! n.expanded;
  3056. if (n.kind == Kind::plugins) // (remembered: the database is built again with the tree)
  3057. {
  3058. const auto key = (n.parent != nullptr && n.parent->kind == Kind::plugins ? n.parent->label + "/" : juce::String()) + n.label;
  3059. if (n.expanded)
  3060. browser.openPluginFolders.insert (key);
  3061. else
  3062. browser.openPluginFolders.erase (key);
  3063. }
  3064. if (n.kind == Kind::factory) // round 190ke (remembered: the folders are built again with the tree)
  3065. {
  3066. const auto key = juce::String::fromUTF8 (n.userFolder.c_str());
  3067. if (n.expanded)
  3068. browser.openFactoryFolders.insert (key);
  3069. else
  3070. browser.openFactoryFolders.erase (key);
  3071. }
  3072. if (n.kind == Kind::collection)
  3073. {
  3074. if (n.expanded)
  3075. browser.closedCollections.erase (n.collection);
  3076. else
  3077. browser.closedCollections.insert (n.collection);
  3078. }
  3079. if (n.expanded)
  3080. load (n);
  3081. if (n.expanded && n.file.isDirectory()) // round 190lr (DF-96): an opened folder is a place in the history
  3082. browser.noteLocation (n.file);
  3083. rebuild();
  3084. restoreSelection (keep);
  3085. if (n.expanded) // show what opened
  3086. for (int i = 0; i < (int) rows.size(); ++i)
  3087. if (rows[(std::size_t) i] == &n)
  3088. scrollToRow (juce::jmin ((int) rows.size() - 1, i + juce::jmin ((int) n.children.size(), 6)));
  3089. }
  3090. void scrollToRow (int row)
  3091. {
  3092. if (row < 0)
  3093. return;
  3094. if (auto* view = findParentComponentOfClass<juce::Viewport>())
  3095. {
  3096. const auto top = row * rowHeight, bottom = top + rowHeight;
  3097. const auto y = view->getViewPositionY(), h = view->getViewHeight();
  3098. if (top < y)
  3099. view->setViewPosition (0, top);
  3100. else if (bottom > y + h)
  3101. view->setViewPosition (0, bottom - h);
  3102. }
  3103. }
  3104. void repaintRow (int row)
  3105. {
  3106. if (row >= 0)
  3107. repaint (0, row * rowHeight, getWidth(), rowHeight);
  3108. }
  3109. juce::Image dragImage (const Node& n) const
  3110. {
  3111. const auto name = n.label.isNotEmpty() ? n.label : n.file.getFileNameWithoutExtension();
  3112. const auto font = juce::Font (theme::font (theme::type::body));
  3113. const auto width = juce::jlimit (80, 260, juce::GlyphArrangement::getStringWidthInt (font, name) + 36);
  3114. const auto colour = n.colour.isTransparent() ? theme::colour::accent : readable (n.colour);
  3115. juce::Image image (juce::Image::ARGB, width, 24, true);
  3116. juce::Graphics g (image);
  3117. g.setColour (theme::colour::bg4.withAlpha (0.92f));
  3118. g.fillRoundedRectangle (0.5f, 0.5f, (float) width - 1.0f, 23.0f, 5.0f);
  3119. g.setColour (colour);
  3120. g.drawRoundedRectangle (0.5f, 0.5f, (float) width - 1.0f, 23.0f, 5.0f, 1.0f);
  3121. icons::draw (g, n.icon != Icon::none ? n.icon : iconFor (n.file, false), { 6.0f, 4.0f, 16.0f, 16.0f }, colour);
  3122. g.setColour (theme::colour::textPrimary);
  3123. g.setFont (font);
  3124. g.drawText (name, 28, 0, width - 32, 24, juce::Justification::centredLeft, true);
  3125. return image;
  3126. }
  3127. BrowserComponent& browser;
  3128. const bool flat;
  3129. std::unique_ptr<Node> root;
  3130. std::vector<std::unique_ptr<Node>> flatNodes;
  3131. std::vector<Node*> rows;
  3132. juce::Array<juce::File> bases;
  3133. juce::String status, pendingKey;
  3134. int selected = -1, hovered = -1, pressedRow = -1;
  3135. public:
  3136. // Round 190qi: the multi-selection — Ctrl+click adds / removes a file (or Plugin database entry), Shift+click the
  3137. // files from the selected row to it; their items (itemOf), in the order picked. A plain click or a new list ends it.
  3138. // Right-click › "Add tag..." then tags them all.
  3139. std::vector<std::string> marked;
  3140. bool isMarked (const Node& n) const
  3141. {
  3142. if (marked.empty())
  3143. return false;
  3144. const auto item = itemOf (n);
  3145. return ! item.empty() && std::find (marked.begin(), marked.end(), item) != marked.end();
  3146. }
  3147. static bool markable (const Node& n) { return ! n.folder && n.thumbPart < 0 && ! itemOf (n).empty() && (n.kind == Kind::file || n.kind == Kind::plugin); }
  3148. void clearMarks()
  3149. {
  3150. if (marked.empty())
  3151. return;
  3152. marked.clear();
  3153. repaint();
  3154. }
  3155. // the names of the folders listed so far (the search box's completion)
  3156. void folderNames (std::vector<std::string>& out) const
  3157. {
  3158. std::function<void (const Node&)> walk = [&] (const Node& n) {
  3159. for (const auto& c : n.children)
  3160. if (c != nullptr && c->folder && c->kind == Kind::fsFolder)
  3161. {
  3162. out.push_back ((c->label.isNotEmpty() ? c->label : c->file.getFileName()).toStdString());
  3163. walk (*c);
  3164. }
  3165. };
  3166. if (root != nullptr)
  3167. walk (*root);
  3168. }
  3169. private:
  3170. int dropRow = -1; // the folder files dragged in from the system would be copied to
  3171. bool dragStarted = false;
  3172. bool overStar = false; // (round 190iz: the mouse is on the hovered row's star)
  3173. };
  3174. // --- the tabs: FL 2026's six icon tabs (round 190iz; before: ALL / PROJECT / STARRED as text) ----------------------
  3175. // FL (fl-playlist.png 0,104,205,140): six icons spread over the width, the selected one in an outlined box; design finding
  3176. // FM-8: 30x30 boxes, the selected one with a 1.5 px accent outline (radius 4), the others textSecondary, hover bg5. The
  3177. // names are in the hint bar and the tooltip, as FL's icon tabs.
  3178. class BrowserComponent::TabBar final : public juce::Component,
  3179. public ui::HintSource,
  3180. public juce::TooltipClient
  3181. {
  3182. public:
  3183. explicit TabBar (BrowserComponent& b) : browser (b) { setRepaintsOnMouseActivity (true); }
  3184. static constexpr int preferredHeight = 32;
  3185. // the slot (left to right) of a tab, and its box
  3186. juce::Rectangle<int> tabBounds (int t) const
  3187. {
  3188. const auto slot = browserplaces::slotOf ((browserplaces::Tab) t);
  3189. const auto w = getWidth() / tabCount;
  3190. const auto cell = juce::Rectangle<int> (slot * w, 0, slot == tabCount - 1 ? getWidth() - slot * w : w, getHeight());
  3191. const auto side = juce::jmin (30, cell.getWidth() - 2, getHeight() - 2);
  3192. return cell.withSizeKeepingCentre (side, side);
  3193. }
  3194. int tabAt (juce::Point<int> p) const
  3195. {
  3196. const auto slot = juce::jlimit (0, tabCount - 1, p.x * tabCount / juce::jmax (1, getWidth()));
  3197. return (int) browserplaces::tabOrder[(std::size_t) slot];
  3198. }
  3199. static juce::String name (int t)
  3200. {
  3201. switch ((browserplaces::Tab) t)
  3202. {
  3203. case browserplaces::Tab::all: return tr ("ALL");
  3204. case browserplaces::Tab::project: return tr ("PROJECT");
  3205. case browserplaces::Tab::plugins: return tr ("PLUGINS");
  3206. case browserplaces::Tab::presets: return tr ("PRESETS");
  3207. case browserplaces::Tab::sounds: return tr ("SOUNDS");
  3208. case browserplaces::Tab::starred: return tr ("STARRED");
  3209. }
  3210. return {};
  3211. }
  3212. void paint (juce::Graphics& g) override
  3213. {
  3214. using namespace theme;
  3215. const auto mouse = isMouseOver() ? getMouseXYRelative() : juce::Point<int> (-1, -1);
  3216. const auto hoverTab = mouse.x >= 0 ? tabAt (mouse) : -1;
  3217. for (int t = 0; t < tabCount; ++t)
  3218. {
  3219. const auto r = tabBounds (t).toFloat();
  3220. const auto on = browser.tab == t;
  3221. if (! on && t == hoverTab)
  3222. {
  3223. g.setColour (colour::bg5);
  3224. g.fillRoundedRectangle (r, 4.0f);
  3225. }
  3226. if (on)
  3227. {
  3228. g.setColour (colour::bg4);
  3229. g.fillRoundedRectangle (r, 4.0f);
  3230. g.setColour (colour::accent);
  3231. g.drawRoundedRectangle (r.reduced (0.75f), 4.0f, 1.5f);
  3232. }
  3233. const auto icon = r.withSizeKeepingCentre (18.0f, 18.0f);
  3234. browsertabicons::draw (g, (browserplaces::Tab) t, icon.toNearestInt().toFloat(), on ? colour::textPrimary : colour::textSecondary);
  3235. }
  3236. }
  3237. void mouseDown (const juce::MouseEvent& e) override { browser.setTab (tabAt (e.getPosition())); }
  3238. juce::String getTooltip() override { return isMouseOver() ? name (tabAt (getMouseXYRelative())) : juce::String(); }
  3239. ui::Hint hintAt (juce::Point<int> p) override
  3240. {
  3241. ui::Hint h;
  3242. switch ((browserplaces::Tab) tabAt (p))
  3243. {
  3244. case browserplaces::Tab::all: h.text = tr ("Browser: ALL - the current project and every sample folder"); break;
  3245. case browserplaces::Tab::project:
  3246. h.text = tr ("Browser: PROJECT - only what the current project uses (patterns, effects, generators, audio files...)");
  3247. break;
  3248. case browserplaces::Tab::plugins: h.text = tr ("Browser: PLUGINS - the Plugin database (generators and effects)"); break;
  3249. case browserplaces::Tab::presets: h.text = tr ("Browser: PRESETS - the preset folders (synth, channel, plugin and mixer presets)"); break;
  3250. case browserplaces::Tab::sounds: h.text = tr ("Browser: SOUNDS - the sample folders, audio files only"); break;
  3251. case browserplaces::Tab::starred: h.text = tr ("Browser: STARRED - the files and folders you starred (the star at a row's end)"); break;
  3252. }
  3253. return h;
  3254. }
  3255. private:
  3256. BrowserComponent& browser;
  3257. };
  3258. // --- the preview strip: waveform of the selected sample ----------------------------------------------
  3259. class BrowserComponent::PreviewStrip final : public juce::Component,
  3260. public ui::HintSource,
  3261. private juce::Timer,
  3262. private juce::ChangeListener
  3263. {
  3264. public:
  3265. explicit PreviewStrip (BrowserComponent& b) : browser (b) { ui::WaveformCache::getInstance()->addChangeListener (this); }
  3266. ~PreviewStrip() override
  3267. {
  3268. if (auto* cache = ui::WaveformCache::getInstanceWithoutCreating())
  3269. cache->removeChangeListener (this);
  3270. }
  3271. void changeListenerCallback (juce::ChangeBroadcaster*) override { repaint(); } // the spectral waveform is ready
  3272. // FL 2026's preview strip (audit round 165z-a): over the waveform, bottom left, a Play / Stop toggle and the preview
  3273. // volume slider; they show while the mouse is over the strip or a sample plays
  3274. void adoptControls()
  3275. {
  3276. addChildComponent (browser.stopButton);
  3277. addChildComponent (browser.previewVolume);
  3278. updateControls();
  3279. }
  3280. void updateControls()
  3281. {
  3282. const auto playing = isPlaying();
  3283. const auto show = (isAudio (file) || isMidiFile190qi (file)) && (playing || isMouseOver (true));
  3284. if (playing != shownPlaying) // (only on a change: this runs on every timer tick)
  3285. {
  3286. shownPlaying = playing;
  3287. browser.stopButton.setIcon (playing ? Icon::stop : Icon::play);
  3288. browser.stopButton.setPrimary (playing);
  3289. const auto midi = isMidiFile190qi (file);
  3290. const auto text = playing ? (midi ? tr ("Stop the MIDI preview") : tr ("Stop the sample preview"))
  3291. : (midi ? tr ("Play the MIDI file on the selected channel") : tr ("Play the sample preview"));
  3292. browser.stopButton.setTooltip (text);
  3293. ui::setHint (browser.stopButton, text, true);
  3294. }
  3295. if (browser.stopButton.isVisible() != show)
  3296. {
  3297. browser.stopButton.setVisible (show);
  3298. browser.previewVolume.setVisible (show);
  3299. }
  3300. if (show && ! isTimerRunning())
  3301. startTimerHz (30); // (hides them again when the mouse leaves)
  3302. }
  3303. void resized() override
  3304. {
  3305. auto row = getLocalBounds().reduced (8, 6).removeFromBottom (14);
  3306. browser.stopButton.setBounds (row.removeFromLeft (20));
  3307. row.removeFromLeft (6);
  3308. browser.previewVolume.setBounds (row.removeFromLeft (juce::jmin (90, juce::jmax (40, row.getWidth() / 2))));
  3309. }
  3310. void mouseEnter (const juce::MouseEvent&) override { updateControls(); }
  3311. void mouseExit (const juce::MouseEvent&) override { updateControls(); }
  3312. void togglePlay()
  3313. {
  3314. if (isPlaying())
  3315. browser.stopPreview();
  3316. else if (isMidiFile190qi (file)) // (round 190qi)
  3317. browser.fileSelected (file, true);
  3318. else if (isAudio (file))
  3319. {
  3320. browser.askPreview (0.0, true); // (FL's Preview Player: Play plays the whole sample)
  3321. browser.fileSelected (file, true);
  3322. }
  3323. }
  3324. // round 190iz: what the preview plays (FL's 5 s from the start or from a Shift+Click, or all of it)
  3325. void show (const juce::File& f, bool playing, double fromFraction, bool full)
  3326. {
  3327. startFraction = juce::jlimit (0.0, 1.0, fromFraction);
  3328. playFull = full;
  3329. show (f, playing);
  3330. }
  3331. void show (const juce::File& f, bool playing)
  3332. {
  3333. if (f != file)
  3334. {
  3335. file = f;
  3336. peaks.clear();
  3337. seconds = 0.0;
  3338. info.clear();
  3339. midiNotes.clear();
  3340. if (isMidiFile190qi (f)) // round 190qi: the notes, drawn as a small piano roll, at the project's tempo
  3341. {
  3342. juce::String error;
  3343. if (auto notes = MidiFileIo::loadNotes (f, 0, error); notes.has_value() && ! notes->empty())
  3344. {
  3345. midiNotes = std::move (*notes);
  3346. const auto events = midipreview::schedule (midiNotes, juce::jmax (10.0, browser.engine.getSong().bpm), 600.0);
  3347. seconds = midipreview::lengthMs (events) / 1000.0;
  3348. info = tr ("{0} notes", { juce::String ((int) midiNotes.size()) }) + " " + juce::String (seconds, seconds < 10.0 ? 2 : 1) + " s "
  3349. + tr ("{0} BPM", { juce::String (browser.engine.getSong().bpm, 0) });
  3350. }
  3351. else
  3352. info = tr ("No notes");
  3353. }
  3354. else if (isAudio (f))
  3355. if (const auto sample = browser.engine.getSampleLibrary().load (f.getFullPathName()); sample != nullptr && sample->frames() > 0)
  3356. {
  3357. // 256 peaks over the whole file
  3358. const auto frames = sample->frames();
  3359. constexpr std::size_t count = 256;
  3360. peaks.assign (count, 0.0f);
  3361. const auto* l = sample->leftData();
  3362. const auto* r = sample->rightData();
  3363. const auto stride = std::max<std::size_t> (1, frames / (count * 64)); // look at up to 64 points per peak
  3364. for (std::size_t i = 0; i < count; ++i)
  3365. {
  3366. const auto from = frames * i / count, to = juce::jmax (from + 1, frames * (i + 1) / count);
  3367. float m = 0.0f;
  3368. for (auto k = from; k < to && k < frames; k += stride)
  3369. m = juce::jmax (m, std::abs (l[k]), std::abs (r[k]));
  3370. peaks[i] = m;
  3371. }
  3372. const auto top = *std::max_element (peaks.begin(), peaks.end());
  3373. if (top > 1.0e-6f) // normalised: quiet files are still readable
  3374. for (auto& p : peaks)
  3375. p /= top;
  3376. seconds = (double) frames / juce::jmax (1.0, sample->sampleRate);
  3377. info = juce::String (seconds, seconds < 10.0 ? 2 : 1) + " s " + juce::String (juce::roundToInt (sample->sampleRate / 100.0) / 10.0, 1)
  3378. + " kHz " + (sample->isStereo() ? tr ("stereo") : tr ("mono"));
  3379. }
  3380. }
  3381. if (playing && seconds > 0.0)
  3382. {
  3383. startedAt = juce::Time::getMillisecondCounterHiRes();
  3384. startTimerHz (30);
  3385. }
  3386. updateControls();
  3387. repaint();
  3388. }
  3389. void paint (juce::Graphics& g) override
  3390. {
  3391. using namespace theme::colour;
  3392. g.fillAll (bg1);
  3393. g.setColour (border);
  3394. g.fillRect (0, 0, getWidth(), 1);
  3395. auto area = getLocalBounds().reduced (6, 4).withTrimmedTop (1);
  3396. if (isMidiFile190qi (file)) // round 190qi
  3397. {
  3398. paintMidi (g, area);
  3399. return;
  3400. }
  3401. if (file == juce::File() || ! isAudio (file))
  3402. {
  3403. g.setColour (textDisabled);
  3404. g.setFont (theme::font (theme::type::small));
  3405. g.drawFittedText (tr ("Click a sample to hear it; its waveform shows here"), area, juce::Justification::centred, 2);
  3406. return;
  3407. }
  3408. auto top = area.removeFromTop (14);
  3409. g.setFont (theme::font (theme::type::caption, true));
  3410. g.setColour (textPrimary);
  3411. g.drawText (file.getFileNameWithoutExtension(), top, juce::Justification::centredLeft, true);
  3412. g.setFont (theme::font (theme::type::caption));
  3413. g.setColour (textSecondary);
  3414. g.drawText (info + tempoText(), top, juce::Justification::centredRight, true);
  3415. area.removeFromTop (2);
  3416. g.setColour (bg0);
  3417. g.fillRoundedRectangle (area.toFloat(), theme::radius::sm);
  3418. if (peaks.empty())
  3419. return;
  3420. const auto wave = area.toFloat().reduced (2.0f, 2.0f);
  3421. const auto mid = wave.getCentreY();
  3422. const auto progress = position();
  3423. const auto playedX = wave.getX() + wave.getWidth() * (float) progress;
  3424. const auto fromX = wave.getX() + wave.getWidth() * (float) (progress > 0.0 ? startFraction : 0.0); // (round 190iz)
  3425. // the detailed, frequency-coloured waveform (ui/WaveformView) once analysed; the quick peaks until then
  3426. const auto path = file.getFullPathName();
  3427. if (const auto summary = ui::WaveformCache::getInstance()->find (path, [this, path] { return browser.engine.getSampleLibrary().load (path); }))
  3428. {
  3429. ui::paintWaveform (g, wave, *summary, 0.0, (double) summary->frames / juce::jmax (1.0f, wave.getWidth()),
  3430. ui::currentWaveStyle (textSecondary, ui::normalisingGain (*summary)));
  3431. if (progress > 0.0)
  3432. {
  3433. g.setColour (accent.withAlpha (0.22f)); // the part already heard
  3434. g.fillRect (juce::Rectangle<float>::leftTopRightBottom (fromX, wave.getY(), juce::jmax (fromX, playedX), wave.getBottom()));
  3435. g.setColour (textPrimary);
  3436. g.fillRect (playedX, wave.getY(), 1.0f, wave.getHeight());
  3437. }
  3438. return;
  3439. }
  3440. for (int x = 0; x < (int) wave.getWidth(); ++x)
  3441. {
  3442. const auto p = peaks[(std::size_t) (x * (int) peaks.size() / juce::jmax (1, (int) wave.getWidth()))];
  3443. const auto h = juce::jmax (0.5f, p * wave.getHeight() * 0.5f);
  3444. const auto px = wave.getX() + (float) x;
  3445. g.setColour (progress > 0.0 && px <= playedX && px >= fromX ? accent : textSecondary.withAlpha (0.75f));
  3446. g.fillRect (px, mid - h, 1.0f, h * 2.0f);
  3447. }
  3448. if (progress > 0.0)
  3449. {
  3450. g.setColour (textPrimary);
  3451. g.fillRect (playedX, wave.getY(), 1.0f, wave.getHeight());
  3452. }
  3453. }
  3454. // Round 190qi: a MIDI file's notes as a small piano roll (its lowest to highest key), what has played in the accent
  3455. void paintMidi (juce::Graphics& g, juce::Rectangle<int> area)
  3456. {
  3457. using namespace theme::colour;
  3458. auto top = area.removeFromTop (14);
  3459. g.setFont (theme::font (theme::type::caption, true));
  3460. g.setColour (textPrimary);
  3461. g.drawText (file.getFileNameWithoutExtension(), top, juce::Justification::centredLeft, true);
  3462. g.setFont (theme::font (theme::type::caption));
  3463. g.setColour (textSecondary);
  3464. g.drawText (info, top, juce::Justification::centredRight, true);
  3465. area.removeFromTop (2);
  3466. g.setColour (bg0);
  3467. g.fillRoundedRectangle (area.toFloat(), theme::radius::sm);
  3468. if (midiNotes.empty())
  3469. return;
  3470. const auto box = area.toFloat().reduced (3.0f, 3.0f);
  3471. std::int64_t first = midiNotes.front().start, last = first;
  3472. int low = 127, high = 0;
  3473. for (const auto& n : midiNotes)
  3474. {
  3475. first = std::min (first, n.start);
  3476. last = std::max (last, n.start + n.length);
  3477. low = juce::jmin (low, n.key);
  3478. high = juce::jmax (high, n.key);
  3479. }
  3480. const auto span = (double) juce::jmax<std::int64_t> (1, last - first);
  3481. const auto keys = (float) juce::jmax (12, high - low + 1);
  3482. const auto rowH = box.getHeight() / keys;
  3483. const auto progress = position();
  3484. const auto playedX = box.getX() + box.getWidth() * (float) progress;
  3485. for (const auto& n : midiNotes)
  3486. {
  3487. const auto x = box.getX() + box.getWidth() * (float) ((double) (n.start - first) / span);
  3488. const auto w = juce::jmax (1.0f, box.getWidth() * (float) ((double) n.length / span));
  3489. const auto y = box.getBottom() - rowH * (float) (n.key - low + 1) - (keys - (float) (high - low + 1)) * rowH * 0.5f;
  3490. g.setColour (progress > 0.0 && x <= playedX ? accent : textSecondary.withAlpha (0.75f));
  3491. g.fillRect (x, y, w, juce::jmax (1.0f, rowH - 0.5f));
  3492. }
  3493. if (progress > 0.0)
  3494. {
  3495. g.setColour (textPrimary);
  3496. g.fillRect (playedX, box.getY(), 1.0f, box.getHeight());
  3497. }
  3498. }
  3499. void mouseDown (const juce::MouseEvent& e) override
  3500. {
  3501. if (isMidiFile190qi (file) && e.mods.isLeftButtonDown()) // (round 190qi: a click plays it again from the start)
  3502. {
  3503. browser.fileSelected (file, true);
  3504. return;
  3505. }
  3506. if (! isAudio (file) || ! e.mods.isLeftButtonDown())
  3507. return;
  3508. // round 190iz: FL's Shift+Click (and a click in the Clip-launch layout, Live's scrub area) plays from the mouse
  3509. // position; Alt+Click plays to the end; a plain click hears it again from the start
  3510. const auto wave = getLocalBounds().reduced (6, 4).withTrimmedTop (17).toFloat().reduced (2.0f, 2.0f);
  3511. const auto at = wave.getWidth() > 1.0f ? juce::jlimit (0.0, 1.0, (double) ((float) e.x - wave.getX()) / (double) wave.getWidth()) : 0.0;
  3512. browser.askPreview (e.mods.isShiftDown() || browser.isLiveLayout() ? at : 0.0, e.mods.isAltDown());
  3513. browser.fileSelected (file, true);
  3514. }
  3515. void mouseDrag (const juce::MouseEvent& e) override
  3516. {
  3517. if (! dragging && isAudio (file) && e.getDistanceFromDragStart() > 5)
  3518. if (auto* container = juce::DragAndDropContainer::findParentDragContainerFor (this))
  3519. {
  3520. dragging = true;
  3521. container->startDragging (juce::String (dragDescription) + "|" + file.getFullPathName(), this,
  3522. juce::ScaledImage (browser.tree->dragImageForFile (file)), true); // (round 190iz: the drag ghost)
  3523. }
  3524. }
  3525. void mouseUp (const juce::MouseEvent&) override { dragging = false; }
  3526. ui::Hint hintAt (juce::Point<int>) override
  3527. {
  3528. ui::Hint h;
  3529. if (isMidiFile190qi (file)) // (round 190qi)
  3530. {
  3531. h.text = tr ("MIDI preview: the file's notes on the selected channel at the project's tempo [LMB] play again");
  3532. h.value = info;
  3533. return h;
  3534. }
  3535. h.text = isAudio (file) ? (browser.isLiveLayout() ? tr ("Sample preview: [LMB] play from there [Alt+LMB] to the end drag it like a file in the list")
  3536. : tr ("Sample preview: [LMB] hear it again [Shift+LMB] from there [Alt+LMB] to the end drag it like a file in the list"))
  3537. : tr ("Sample preview");
  3538. h.value = info;
  3539. return h;
  3540. }
  3541. bool isPlaying() const { return position() > 0.0 && position() < 1.0; }
  3542. // "Preview in time" (round 190aq): the tempo found in the file and the project's, after the file's details
  3543. juce::String tempoText() const
  3544. {
  3545. const auto& timing = browser.engine.getPreviewTiming();
  3546. if (! browser.engine.isPreviewInTime() || timing.path != file.getFullPathName() || ! (timing.fileBpm > 0.0))
  3547. return {};
  3548. auto bpm = [] (double v) { return juce::String (v, std::abs (v - std::round (v)) < 0.05 ? 0 : 1); };
  3549. // "120 BPM" at the project's tempo already, else "120 → 140 BPM" (what it is stretched to)
  3550. return " " + tr ("{0} BPM", { timing.ratio == 1.0 ? bpm (timing.fileBpm)
  3551. : bpm (timing.fileBpm) + juce::String::fromUTF8 (" \xe2\x86\x92 ") + bpm (timing.fileBpm / timing.ratio) });
  3552. }
  3553. void stop()
  3554. {
  3555. startedAt = 0.0;
  3556. if (! isMouseOver (true))
  3557. stopTimer();
  3558. updateControls();
  3559. repaint();
  3560. }
  3561. private:
  3562. double position() const
  3563. {
  3564. if (isMidiFile190qi (file)) // (round 190qi: the MIDI preview says where it is; 0 when it isn't playing this file)
  3565. return browser.midiPreview != nullptr && browser.midiPreview->isPlaying (file) ? browser.midiPreview->progress() : (startedAt > 0.0 ? 1.0 : 0.0);
  3566. if (startedAt <= 0.0 || seconds <= 0.0)
  3567. return 0.0;
  3568. // "Preview in time" (round 190aq): the stretched preview starts later (its stretch, then its beat) and lasts
  3569. // another time, so the engine says where it is
  3570. if (const auto& timing = browser.engine.getPreviewTiming(); timing.path == file.getFullPathName() && (timing.pending || timing.inTime))
  3571. {
  3572. const auto p = browser.engine.getPreviewInTimeProgress();
  3573. return p < 0.0 ? 1.0 : juce::jlimit (1.0e-6, 1.0 - 1.0e-6, p);
  3574. }
  3575. // round 190iz: from where it started, for FL's 5 seconds unless it plays to the end
  3576. const auto elapsed = (juce::Time::getMillisecondCounterHiRes() - startedAt) / 1000.0;
  3577. const auto limit = playFull || browser.engine.isFullSamplePreview() ? seconds : juce::jmin (seconds, (double) browserpreview::defaultSeconds + startFraction * seconds);
  3578. if (startFraction * seconds + elapsed >= limit)
  3579. return 1.0;
  3580. return juce::jlimit (0.0, 1.0, startFraction + elapsed / seconds);
  3581. }
  3582. void timerCallback() override
  3583. {
  3584. if (startedAt > 0.0 && position() >= 1.0)
  3585. {
  3586. stop();
  3587. browser.tree->repaint(); // the "playing" colour goes
  3588. browser.results->repaint();
  3589. }
  3590. updateControls();
  3591. if (startedAt <= 0.0 && ! browser.stopButton.isVisible())
  3592. stopTimer();
  3593. repaint();
  3594. }
  3595. BrowserComponent& browser;
  3596. juce::File file;
  3597. std::vector<float> peaks;
  3598. double seconds = 0.0, startedAt = 0.0;
  3599. double startFraction = 0.0; // round 190iz: where the preview started (0..1)
  3600. bool playFull = false; // ... and whether it plays to the end
  3601. juce::String info;
  3602. bool dragging = false;
  3603. std::optional<bool> shownPlaying; // the Play / Stop state the button shows
  3604. std::vector<Note> midiNotes; // round 190qi: a MIDI file's notes (its preview)
  3605. };
  3606. // --- the browser -------------------------------------------------------------------------------------
  3607. bool BrowserComponent::isPreviewPlaying() const
  3608. {
  3609. return strip != nullptr && strip->isPlaying();
  3610. }
  3611. // FL's Browser details box (REA round 134/139): what is selected — a column of labels (Date, Size, Version for a
  3612. // project FL saved, Path) and their values, the path wrapping over the last lines. Hidden while nothing is selected.
  3613. class BrowserComponent::DetailsBox final : public juce::Component,
  3614. public ui::HintSource
  3615. {
  3616. public:
  3617. static constexpr int preferredHeight = 70;
  3618. void show (const juce::File& f)
  3619. {
  3620. file = f;
  3621. rows.clear();
  3622. if (file != juce::File())
  3623. {
  3624. rows.push_back ({ tr ("Date"), file.getLastModificationTime().formatted ("%Y-%m-%d %H:%M:%S") });
  3625. if (file.existsAsFile())
  3626. {
  3627. rows.push_back ({ tr ("Size"), juce::File::descriptionOfSizeInBytes (file.getSize()) });
  3628. if (file.hasFileExtension (".flp"))
  3629. {
  3630. juce::MemoryBlock head;
  3631. if (juce::FileInputStream in (file); in.openedOk())
  3632. in.readIntoMemoryBlock (head, 4096);
  3633. const auto version = flp::readSavedVersion ({ (const std::uint8_t*) head.getData(), head.getSize() });
  3634. if (! version.empty())
  3635. rows.push_back ({ tr ("Version"), juce::String (version) });
  3636. }
  3637. }
  3638. rows.push_back ({ tr ("Path"), file.getFullPathName() });
  3639. }
  3640. repaint();
  3641. }
  3642. bool hasFile() const noexcept { return file != juce::File(); }
  3643. ui::Hint hintAt (juce::Point<int>) override
  3644. {
  3645. ui::Hint h;
  3646. if (file != juce::File())
  3647. h.text = tr ("Selected: {0}", { file.getFullPathName() });
  3648. return h;
  3649. }
  3650. void paint (juce::Graphics& g) override
  3651. {
  3652. using namespace theme::colour;
  3653. g.fillAll (bg1);
  3654. g.setColour (border);
  3655. g.fillRect (0, 0, getWidth(), 1);
  3656. auto area = getLocalBounds().reduced (6, 3).withTrimmedTop (1);
  3657. g.setFont (theme::font (theme::type::caption));
  3658. constexpr int line = 13, labelWidth = 48;
  3659. for (std::size_t i = 0; i < rows.size() && area.getHeight() >= line; ++i)
  3660. {
  3661. const auto last = i + 1 == rows.size();
  3662. // the path (last row) takes the lines left and wraps, as FL's box does
  3663. auto r = last ? area : area.removeFromTop (line);
  3664. g.setColour (textDisabled);
  3665. g.drawText (rows[i].first, r.removeFromLeft (labelWidth).withHeight (line), juce::Justification::centredLeft, false);
  3666. g.setColour (textSecondary);
  3667. if (last)
  3668. g.drawFittedText (rows[i].second, r, juce::Justification::topLeft, juce::jmax (1, r.getHeight() / line), 1.0f);
  3669. else
  3670. g.drawText (rows[i].second, r, juce::Justification::centredLeft, true);
  3671. }
  3672. }
  3673. private:
  3674. juce::File file;
  3675. std::vector<std::pair<juce::String, juce::String>> rows;
  3676. };
  3677. // --- Hot-swap (round 190ce): the bar -------------------------------------------------------------------
  3678. // The bar over the tabs while the Browser is linked to a device: what it is linked to, and an X that ends the link
  3679. // (the reference shows a coloured banner at the top of its browser with a close button).
  3680. class BrowserComponent::HotSwapBar final : public juce::Component, public ui::HintSource
  3681. {
  3682. public:
  3683. explicit HotSwapBar (BrowserComponent& b) : browser (b) { setRepaintsOnMouseActivity (true); }
  3684. static constexpr int height = 22;
  3685. void paint (juce::Graphics& g) override
  3686. {
  3687. using namespace theme;
  3688. g.setColour (colour::accent);
  3689. g.fillRoundedRectangle (getLocalBounds().toFloat(), radius::md);
  3690. auto r = getLocalBounds().reduced (6, 0);
  3691. const auto x = closeBounds();
  3692. r.setRight (x.getX() - 4);
  3693. g.setColour (juce::Colours::white);
  3694. g.setFont (font (type::caption, true));
  3695. g.drawText (tr ("Swapping {0}", { browser.hotSwapTargetName() }), r, juce::Justification::centredLeft, true); // (the reference: "Swapping Instrument")
  3696. const auto over = isMouseOver() && x.contains (getMouseXYRelative());
  3697. if (over)
  3698. {
  3699. g.setColour (juce::Colours::white.withAlpha (0.22f));
  3700. g.fillRoundedRectangle (x.toFloat(), 3.0f);
  3701. }
  3702. g.setColour (juce::Colours::white);
  3703. const auto c = x.toFloat().reduced (5.0f);
  3704. g.drawLine (c.getX(), c.getY(), c.getRight(), c.getBottom(), 1.6f);
  3705. g.drawLine (c.getX(), c.getBottom(), c.getRight(), c.getY(), 1.6f);
  3706. }
  3707. void mouseUp (const juce::MouseEvent& e) override
  3708. {
  3709. if (closeBounds().contains (e.getPosition()))
  3710. browser.endHotSwap();
  3711. }
  3712. ui::Hint hintAt (juce::Point<int> p) override
  3713. {
  3714. if (closeBounds().contains (p))
  3715. return { tr ("End hot-swap (Esc)"), {}, false, false };
  3716. return { tr ("Hot-swap: Enter or a double-click loads the selected plugin, preset or sample in place of this device"), browser.hotSwapTargetName(), false, false };
  3717. }
  3718. private:
  3719. juce::Rectangle<int> closeBounds() const { return getLocalBounds().removeFromRight (height).reduced (2); }
  3720. BrowserComponent& browser;
  3721. };
  3722. BrowserComponent::BrowserComponent (AudioEngine& e, Role r)
  3723. : engine (e), role (r)
  3724. {
  3725. tabs = std::make_unique<TabBar> (*this);
  3726. addAndMakeVisible (*tabs);
  3727. // round 190iz: FL's TAGS button and tags panel, Live's sidebar (the Clip-launch layout shows it)
  3728. tagsButton = std::make_unique<TagsButton> (*this);
  3729. addAndMakeVisible (*tagsButton);
  3730. tagsPanel = std::make_unique<TagsPanel> (*this);
  3731. addChildComponent (*tagsPanel);
  3732. // round gaps190kf: the Loop Browser (the Sample browser window's: LYNX's own window, so FL's Browser panel keeps FL's row)
  3733. loopsButton = std::make_unique<LoopsButton> (*this);
  3734. addChildComponent (*loopsButton);
  3735. loopsButton->setVisible (role == Role::samples);
  3736. loopPanel = std::make_unique<LoopPanel> (*this);
  3737. addChildComponent (*loopPanel);
  3738. sidebar = std::make_unique<LiveSidebar> (*this);
  3739. sidebarView = std::make_unique<ui::TiltViewport>();
  3740. sidebarView->setViewedComponent (sidebar.get(), false);
  3741. sidebarView->setScrollBarsShown (true, false);
  3742. sidebarView->setScrollBarThickness (8);
  3743. sidebarView->setWantsKeyboardFocus (false);
  3744. addChildComponent (*sidebarView);
  3745. loadTags();
  3746. loadPrefs();
  3747. swapBar = std::make_unique<HotSwapBar> (*this);
  3748. addChildComponent (*swapBar);
  3749. liveBrowsers().push_back (this);
  3750. // the search index (round 162): a background pass over every folder a few seconds after start (FL's automatic
  3751. // indexing: only the folders that changed since the last session are listed again)
  3752. searcher = SearchShared::get();
  3753. searcher->statusChanged.addChangeListener (this);
  3754. searcher->indexChanged.addChangeListener (this);
  3755. loopLengthsRead().addChangeListener (this); // (round 190mf: the Simple loop rows' lengths)
  3756. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<BrowserComponent> (this)] {
  3757. if (safe != nullptr && safe->role == Role::main && ! safe->allRoots.isEmpty())
  3758. safe->searcher->refreshInBackground (toPaths (safe->withMerged (safe->allRoots))); // (round 190hd: the indexer process)
  3759. });
  3760. // "Find similar samples" (round 190as): once it was used (its index file exists), the folders are checked for new
  3761. // samples in the background a while after start; before that nothing is analysed
  3762. similar = SimilarShared::get (engine);
  3763. similar->statusChanged.addChangeListener (this);
  3764. juce::Timer::callAfterDelay (20000, [safe = juce::Component::SafePointer<BrowserComponent> (this)] {
  3765. if (safe != nullptr && safe->role == Role::main && ! safe->allRoots.isEmpty() && SimilarShared::file().existsAsFile()
  3766. && ! std::exchange (safe->similar->passAsked, true))
  3767. safe->similar->service->refresh (toPaths (safe->withMerged (safe->allRoots)));
  3768. });
  3769. focusWatcher = std::make_unique<FocusWatcher> (*this);
  3770. // (round 190oo CS-22: Live's short placeholder; the syntax example is in the hint below, it was cut at every width)
  3771. searchBox.setTextToShowWhenEmpty (tr ("Search (Ctrl+F)"), theme::colour::textDisabled);
  3772. searchBox.setComponentID ("browser.search"); // (round 190pl: --demo)
  3773. searchBox.addListener (this);
  3774. searchBox.setEscapeAndReturnKeysConsumed (true);
  3775. // round 190qi: Tab completes the last word (a tag after '#', a folder name), the rest shown greyed after the text
  3776. searchGhost = std::make_unique<SearchGhost> (searchBox);
  3777. searchBox.addChildComponent (*searchGhost);
  3778. {
  3779. auto keys = std::make_unique<SearchTabKeys>();
  3780. keys->accept = [this] { return acceptSearchSuggestion(); };
  3781. searchKeys = std::move (keys);
  3782. searchBox.addKeyListener (searchKeys.get());
  3783. }
  3784. ui::setHint (searchBox, tr ("Search the selected folder (or every folder) and below; in PROJECT, the project's items: words must all match; "
  3785. "OR, -word (not), \"exact phrase\", * and ? wildcards [Enter] to the results [Esc] clear"));
  3786. addAndMakeVisible (searchBox);
  3787. // FL's Browser has a way to silence the preview too (issue #9): a Play / Stop toggle on the preview strip, beside
  3788. // the preview volume, as in FL 2026 (audit round 165z-a); the strip adopts both below
  3789. stopButton.setFlat (true);
  3790. stopButton.setWantsKeyboardFocus (false);
  3791. stopButton.setMouseClickGrabsKeyboardFocus (false);
  3792. stopButton.onClick = [this] {
  3793. if (strip != nullptr)
  3794. strip->togglePlay();
  3795. };
  3796. // what this Browser shows (round 163): content filter, folders shown, the Sample browser window
  3797. viewButton.setFlat (true);
  3798. viewButton.setWantsKeyboardFocus (false);
  3799. viewButton.setMouseClickGrabsKeyboardFocus (false);
  3800. viewButton.setClickingTogglesState (false);
  3801. viewButton.onClick = [this] { showViewMenu(); };
  3802. addAndMakeVisible (viewButton);
  3803. // the sample preview volume (FL's Browser has one too): a slider on the preview strip, as in FL 2026
  3804. previewVolume.setSliderStyle (juce::Slider::LinearHorizontal);
  3805. previewVolume.setRange (0.0, controls::maxUtilityVolume, 0.01);
  3806. previewVolume.setDoubleClickReturnValue (true, 1.0);
  3807. previewVolume.textFromValueFunction = [] (double v) { return ui::utilityVolumeText (v); };
  3808. previewVolume.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  3809. previewVolume.setValue (engine.getPreviewVolume(), juce::dontSendNotification);
  3810. previewVolume.setMouseClickGrabsKeyboardFocus (false);
  3811. previewVolume.setWantsKeyboardFocus (false);
  3812. previewVolume.onValueChange = [this] {
  3813. engine.setPreviewVolume (previewVolume.getValue());
  3814. refreshPreviewVolume();
  3815. if (onPreviewVolumeChanged != nullptr)
  3816. onPreviewVolumeChanged();
  3817. };
  3818. refreshPreviewVolume();
  3819. tree = std::make_unique<FileTree> (*this, false);
  3820. results = std::make_unique<FileTree> (*this, true);
  3821. tree->setComponentID ("browser.tree"); // (round 190pl: --demo, rows as cells)
  3822. results->setComponentID ("browser.results");
  3823. for (auto [view, list] : { std::pair { &treeView, tree.get() }, std::pair { &resultsView, results.get() } })
  3824. {
  3825. *view = std::make_unique<ui::TiltViewport>(); // (issue #254: the horizontal wheel scrolls the list as FL's Browser)
  3826. (*view)->setViewedComponent (list, false);
  3827. (*view)->setScrollBarsShown (true, false);
  3828. (*view)->setScrollBarThickness (10);
  3829. (*view)->setWantsKeyboardFocus (false);
  3830. }
  3831. addAndMakeVisible (*treeView);
  3832. addChildComponent (*resultsView);
  3833. strip = std::make_unique<PreviewStrip> (*this);
  3834. addAndMakeVisible (*strip);
  3835. strip->adoptControls();
  3836. details = std::make_unique<DetailsBox>();
  3837. addChildComponent (*details);
  3838. browserStartupMark (" browser: search index, widgets");
  3839. if (tagsPanelShown)
  3840. tagsPanel->setVisible (true);
  3841. rebuildRoots();
  3842. browserStartupMark (" browser: roots and tree");
  3843. engine.addChangeListener (this);
  3844. constructing = false;
  3845. }
  3846. void BrowserComponent::browserStartupMark (const char* step) const
  3847. {
  3848. if (constructing && role == Role::main && startupMark != nullptr)
  3849. startupMark (step);
  3850. }
  3851. juce::File BrowserComponent::userFoldersFile()
  3852. {
  3853. return PluginHost::settingsFolder().getChildFile ("browser-folders.txt");
  3854. }
  3855. juce::File BrowserComponent::starredFile()
  3856. {
  3857. return PluginHost::settingsFolder().getChildFile ("browser-starred.txt");
  3858. }
  3859. void BrowserComponent::setStarred (const juce::File& file, bool on)
  3860. {
  3861. setInCollection (file.getFullPathName().toStdString(), 0, on);
  3862. }
  3863. // --- Collections (round 190ce) ------------------------------------------------------------------------
  3864. juce::File BrowserComponent::collectionsFile()
  3865. {
  3866. return PluginHost::settingsFolder().getChildFile ("browser-collections.txt");
  3867. }
  3868. collections::Store& BrowserComponent::collectionStore()
  3869. {
  3870. static collections::Store store;
  3871. return store;
  3872. }
  3873. std::vector<BrowserComponent*>& BrowserComponent::liveBrowsers()
  3874. {
  3875. static std::vector<BrowserComponent*> all;
  3876. return all;
  3877. }
  3878. void BrowserComponent::loadCollections()
  3879. {
  3880. if (const auto file = collectionsFile(); file.existsAsFile())
  3881. {
  3882. collectionStore() = collections::Store::fromText (file.loadFileAsString().toStdString());
  3883. return;
  3884. }
  3885. // before round 190ce: one starred path per line
  3886. std::vector<std::string> paths;
  3887. for (const auto& line : juce::StringArray::fromLines (starredFile().loadFileAsString()))
  3888. if (line.trim().isNotEmpty() && juce::File::isAbsolutePath (line.trim()))
  3889. paths.push_back (line.trim().toStdString());
  3890. collectionStore() = collections::Store::fromStarred (paths);
  3891. }
  3892. void BrowserComponent::saveCollections()
  3893. {
  3894. const auto& store = collectionStore();
  3895. collectionsFile().getParentDirectory().createDirectory();
  3896. collectionsFile().replaceWithText (juce::String::fromUTF8 (store.toText().c_str()));
  3897. juce::String starredText; // (an older LYNX SHARE reads this one)
  3898. for (const auto& path : store.starredPaths())
  3899. starredText << juce::String::fromUTF8 (path.c_str()) << "\n";
  3900. starredFile().replaceWithText (starredText);
  3901. }
  3902. juce::String BrowserComponent::collectionName (int collection)
  3903. {
  3904. const auto& store = collectionStore();
  3905. if (store.hasOwnName (collection))
  3906. return juce::String::fromUTF8 (store.name (collection).c_str());
  3907. switch (collection)
  3908. {
  3909. case 0: return tr ("Starred");
  3910. case 1: return tr ("Orange");
  3911. case 2: return tr ("Yellow");
  3912. case 3: return tr ("Green");
  3913. case 4: return tr ("Blue");
  3914. case 5: return tr ("Purple");
  3915. case 6: return tr ("Gray");
  3916. default: return {};
  3917. }
  3918. }
  3919. juce::Colour BrowserComponent::collectionColour (int collection)
  3920. {
  3921. return juce::Colour (collections::colourArgb (collection));
  3922. }
  3923. void BrowserComponent::collectionsChanged()
  3924. {
  3925. for (auto* b : liveBrowsers())
  3926. {
  3927. if (b->liveLayout) // round 190iz: Live's sidebar lists the shown collections
  3928. b->sidebar->refresh();
  3929. if (b->liveLayout ? b->liveSelection.category == browserplaces::Category::collection : b->tab == starredTab)
  3930. {
  3931. const auto row = b->tree->getSelectedRow();
  3932. const auto scroll = b->treeView->getViewPosition();
  3933. b->rebuildTree();
  3934. if (row >= 0 && b->tree->numRows() > 0)
  3935. b->tree->select (juce::jmin (row, b->tree->numRows() - 1), false);
  3936. b->treeView->setViewPosition (scroll);
  3937. }
  3938. b->tree->repaint();
  3939. b->results->repaint();
  3940. if (b->loopsShown && b->loopFilterState.favouritesOnly) // (round gaps190kf: the Favorites button's list)
  3941. b->applyLoopFilter();
  3942. }
  3943. }
  3944. void BrowserComponent::setInCollection (const std::string& item, int collection, bool on)
  3945. {
  3946. if (! collectionStore().label (item, collection, on)) // (a hidden collection shows itself: round 190cy)
  3947. return;
  3948. saveCollections();
  3949. collectionsChanged();
  3950. }
  3951. void BrowserComponent::toggleCollectionOnSelection (int collection)
  3952. {
  3953. auto& list = activeList();
  3954. const auto item = list.selectedItem();
  3955. if (item.empty())
  3956. {
  3957. ui::postHint ({ tr ("Select a file, a folder or a plugin in the Browser first"), {} }, 2500);
  3958. return;
  3959. }
  3960. const auto label = list.selectedLabel();
  3961. const auto on = ! collectionStore().has (item, collection);
  3962. setInCollection (item, collection, on);
  3963. ui::postHint ({ on ? tr ("Added to the collection {0}", { collectionName (collection) }) : tr ("Removed from the collection {0}", { collectionName (collection) }), label }, 2500);
  3964. }
  3965. void BrowserComponent::clearCollectionsOnSelection()
  3966. {
  3967. auto& list = activeList();
  3968. const auto item = list.selectedItem();
  3969. if (item.empty())
  3970. return;
  3971. const auto label = list.selectedLabel();
  3972. if (! collectionStore().clear (item))
  3973. return;
  3974. saveCollections();
  3975. collectionsChanged();
  3976. ui::postHint ({ tr ("Removed from every collection"), label }, 2500);
  3977. }
  3978. void BrowserComponent::setCollectionShown (int collection, bool shown)
  3979. {
  3980. auto& store = collectionStore();
  3981. store.setShown (collection, shown);
  3982. if (store.shown().empty()) // (one stays: Starred)
  3983. store.setShown (0, true);
  3984. saveCollections();
  3985. collectionsChanged();
  3986. }
  3987. void BrowserComponent::renameCollection (int collection)
  3988. {
  3989. auto* window = new juce::AlertWindow (tr ("Rename collection"), tr ("Name of the collection (empty: its default name):"), juce::MessageBoxIconType::NoIcon, this);
  3990. window->addTextEditor ("name", juce::String::fromUTF8 (collectionStore().labels[(std::size_t) juce::jlimit (0, collections::count - 1, collection)].name.c_str()));
  3991. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3992. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3993. juce::Component::SafePointer<BrowserComponent> safe (this);
  3994. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, safe, collection] (int result) {
  3995. if (result != 1 || safe == nullptr)
  3996. return;
  3997. collectionStore().rename (collection, window->getTextEditorContents ("name").toStdString());
  3998. saveCollections();
  3999. safe->collectionsChanged();
  4000. }), true);
  4001. }
  4002. // The collections in a row's menu. Clip-launch workflow (round 190cy, Live 12.4.16 live check 190cw shot 05): a flat
  4003. // list in the menu itself, "Clear all colours" (0) then the seven with their keys (1-7), ticked when the item is in
  4004. // one; renaming and showing / hiding are on a collection's heading. Pattern workflow: as round 190ce built it, a
  4005. // "Collections" sub-menu with the seven, "Remove from all", which collections the STARRED tab lists and their names.
  4006. void BrowserComponent::addCollectionItems (juce::PopupMenu& menu, const std::string& item)
  4007. {
  4008. if (item.empty())
  4009. return;
  4010. juce::Component::SafePointer<BrowserComponent> safe (this);
  4011. const auto& store = collectionStore();
  4012. if (liveItemMenus)
  4013. {
  4014. menu.addSeparator();
  4015. menu.addItem (tr ("Clear all colours") + "\t0", store.mask (item) != 0, false, [safe, item] {
  4016. if (safe == nullptr || ! collectionStore().clear (item))
  4017. return;
  4018. saveCollections();
  4019. safe->collectionsChanged();
  4020. });
  4021. for (int c = 0; c < collections::count; ++c)
  4022. {
  4023. juce::PopupMenu::Item entry (collectionName (c) + "\t" + juce::String (c + 1));
  4024. entry.setTicked (store.has (item, c));
  4025. entry.setColour (collectionColour (c).brighter (0.25f));
  4026. entry.setAction ([safe, item, c] {
  4027. if (safe != nullptr)
  4028. safe->setInCollection (item, c, ! collectionStore().has (item, c));
  4029. });
  4030. menu.addItem (entry);
  4031. }
  4032. menu.addSeparator();
  4033. addTagItems (menu, item); // round 190iz
  4034. return;
  4035. }
  4036. juce::PopupMenu sub;
  4037. for (int c = 0; c < collections::count; ++c)
  4038. {
  4039. juce::PopupMenu::Item entry (collectionName (c) + "\t" + juce::String (c + 1));
  4040. entry.setTicked (store.has (item, c));
  4041. entry.setColour (collectionColour (c).brighter (0.25f));
  4042. entry.setAction ([safe, item, c] {
  4043. if (safe != nullptr)
  4044. safe->setInCollection (item, c, ! collectionStore().has (item, c));
  4045. });
  4046. sub.addItem (entry);
  4047. }
  4048. sub.addSeparator();
  4049. sub.addItem (tr ("Remove from all") + "\t0", store.mask (item) != 0, false, [safe, item] {
  4050. if (safe == nullptr || ! collectionStore().clear (item))
  4051. return;
  4052. saveCollections();
  4053. safe->collectionsChanged();
  4054. });
  4055. sub.addSeparator();
  4056. juce::PopupMenu show, rename;
  4057. for (int c = 0; c < collections::count; ++c)
  4058. {
  4059. show.addItem (collectionName (c), true, store.isShown (c), [safe, c] {
  4060. if (safe != nullptr)
  4061. safe->setCollectionShown (c, ! collectionStore().isShown (c));
  4062. });
  4063. rename.addItem (collectionName (c), [safe, c] {
  4064. if (safe != nullptr)
  4065. safe->renameCollection (c);
  4066. });
  4067. }
  4068. sub.addSubMenu (tr ("Show in the STARRED tab"), show);
  4069. sub.addSubMenu (tr ("Rename"), rename);
  4070. menu.addSubMenu (tr ("Collections"), sub);
  4071. addTagItems (menu, item); // round 190iz: FL's Tags section (Tags ▸, Add tag..., Edit tags...)
  4072. }
  4073. juce::PopupMenu BrowserComponent::collectionsMenuForSnapshot (const std::string& item)
  4074. {
  4075. juce::PopupMenu menu;
  4076. addCollectionItems (menu, item);
  4077. // (the shot shows the sub-menu's own items: a picture of a menu does not open its sub-menus)
  4078. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  4079. if (it.getItem().subMenu != nullptr)
  4080. return *it.getItem().subMenu;
  4081. return menu;
  4082. }
  4083. void BrowserComponent::selectRowForSnapshot (const juce::String& label)
  4084. {
  4085. auto& list = activeList();
  4086. for (int i = 0; i < list.numRows(); ++i)
  4087. {
  4088. list.select (i, false);
  4089. if (list.selectedLabel() == label)
  4090. return;
  4091. }
  4092. }
  4093. // --- Hot-swap (round 190ce) ---------------------------------------------------------------------------
  4094. juce::String BrowserComponent::hotSwapTargetName() const
  4095. {
  4096. const auto& song = engine.getSong();
  4097. const auto& t = swapSession.target;
  4098. if (t.kind == hotswap::Kind::effect)
  4099. {
  4100. if (const auto at = hotswap::findEffect (song, t.instance); at.found())
  4101. return quickpick::slotName (engine, song.mixer[(std::size_t) at.track].effects[(std::size_t) at.slot]);
  4102. }
  4103. else if (t.kind == hotswap::Kind::channel)
  4104. {
  4105. if (const auto c = hotswap::findChannel (song, t.instance); c >= 0)
  4106. return juce::String::fromUTF8 (song.channels[(std::size_t) c].name.c_str());
  4107. }
  4108. return {};
  4109. }
  4110. void BrowserComponent::beginHotSwap (const hotswap::Target& target)
  4111. {
  4112. const auto& song = engine.getSong();
  4113. if (! hotswap::exists (song, target))
  4114. return;
  4115. swapSession.begin (target, tab, searchBox.getText().toStdString());
  4116. if (searchBox.getText().isNotEmpty())
  4117. {
  4118. searchBox.setText ({}, false);
  4119. runSearch();
  4120. }
  4121. // the Browser goes to what can take the device's place: a sample channel's own sample in its folder, else the
  4122. // Plugin database's effects or generators
  4123. bool shown = false;
  4124. if (target.kind == hotswap::Kind::channel)
  4125. if (const auto c = hotswap::findChannel (song, target.instance); c >= 0 && hotswap::playsSample (song.channels[(std::size_t) c]))
  4126. {
  4127. const juce::File sample (juce::String::fromUTF8 (song.channels[(std::size_t) c].samplePath.c_str()));
  4128. setTab (allTab);
  4129. if (sample.existsAsFile())
  4130. if (const auto row = tree->revealFile (sample); row >= 0)
  4131. {
  4132. tree->select (row, false);
  4133. shown = true;
  4134. }
  4135. shown = shown || sample == juce::File() || ! sample.existsAsFile(); // (no sample yet: the folders as they are)
  4136. }
  4137. // an effect with a preset: that preset, as Live starts hot-swap on the device's current preset (round 190cy)
  4138. if (! shown && target.kind == hotswap::Kind::effect)
  4139. shown = revealCurrentPreset (target);
  4140. if (! shown)
  4141. showPluginDatabase ({}, target.kind == hotswap::Kind::channel ? 1 : 0);
  4142. swapBar->setVisible (true);
  4143. swapBar->repaint();
  4144. resized();
  4145. if (onHotSwapChanged != nullptr)
  4146. onHotSwapChanged();
  4147. }
  4148. bool BrowserComponent::revealCurrentPreset (const hotswap::Target& target)
  4149. {
  4150. const auto& song = engine.getSong();
  4151. const auto at = hotswap::findEffect (song, target.instance);
  4152. if (! at.found())
  4153. return false;
  4154. const auto& fx = song.mixer[(std::size_t) at.track].effects[(std::size_t) at.slot];
  4155. if (fx.presetName.empty())
  4156. return false;
  4157. // the files the effect's presets come from: FL's preset folders of the plugin it stands for (the editor's preset
  4158. // list, round 168r) and LYNX's own saved presets of the effect
  4159. juce::Array<juce::File> files, folders;
  4160. if (const auto roots = findFlStudioRoots(); ! roots.data.empty())
  4161. for (const auto& plugin : flPluginsForEffect (fx.kind))
  4162. {
  4163. const auto paths = presetcycle::pluginPresetFolders (roots, false, plugin);
  4164. for (const auto& folder : paths)
  4165. folders.addIfNotAlreadyThere (juce::File (juce::String::fromUTF8 (folder.c_str())));
  4166. for (const auto& p : presetcycle::listPresets (paths))
  4167. files.add (juce::File (juce::String::fromUTF8 (p.path.c_str())));
  4168. }
  4169. folders.add (pluginheader::userFolder (fx.kind));
  4170. files.addArray (pluginheader::userPresets (fx.kind));
  4171. const auto name = juce::String::fromUTF8 (fx.presetName.c_str());
  4172. const auto current = std::find_if (files.begin(), files.end(), [&name] (const juce::File& f) { return f.getFileNameWithoutExtension() == name; });
  4173. if (current == files.end())
  4174. return false;
  4175. const auto file = *current;
  4176. setTab (allTab);
  4177. if (const auto row = tree->revealFile (file); row >= 0)
  4178. {
  4179. tree->select (row, false);
  4180. return true;
  4181. }
  4182. resultsView->setVisible (true);
  4183. treeView->setVisible (false);
  4184. results->setFiles (files, folders, tr ("Presets of {0}", { hotSwapTargetName() }));
  4185. results->select (files.indexOf (file), false);
  4186. presetsListed = true;
  4187. return true;
  4188. }
  4189. void BrowserComponent::endHotSwap()
  4190. {
  4191. if (! swapSession.active())
  4192. return;
  4193. const auto back = swapSession.end();
  4194. swapBar->setVisible (false);
  4195. setTab (back.tab);
  4196. if (std::exchange (presetsListed, false) || searchBox.getText() != juce::String::fromUTF8 (back.search.c_str()))
  4197. {
  4198. searchBox.setText (juce::String::fromUTF8 (back.search.c_str()), false);
  4199. runSearch();
  4200. }
  4201. resized();
  4202. if (onHotSwapChanged != nullptr)
  4203. onHotSwapChanged();
  4204. }
  4205. void BrowserComponent::hotSwapRefused()
  4206. {
  4207. ui::postHint ({ tr ("Hot-swap: this can't take the place of {0}", { hotSwapTargetName() }), {} }, 3000);
  4208. }
  4209. bool BrowserComponent::hotSwapLoadSelected()
  4210. {
  4211. if (! swapSession.active())
  4212. return false;
  4213. const auto* n = activeList().selectedNode();
  4214. if (n == nullptr || n->folder)
  4215. return true; // (the mode keeps Enter: nothing is added to the project while it is on)
  4216. if (n->kind == FileTree::Kind::plugin)
  4217. {
  4218. if (! hotSwapLoadPlugin (n->generator, n->effect))
  4219. hotSwapRefused();
  4220. return true;
  4221. }
  4222. if (n->kind == FileTree::Kind::file && n->file.existsAsFile())
  4223. {
  4224. if (! hotSwapLoadFile (n->file))
  4225. hotSwapRefused();
  4226. return true;
  4227. }
  4228. hotSwapRefused();
  4229. return true;
  4230. }
  4231. bool BrowserComponent::hotSwapLoadPlugin (const std::function<std::optional<ChannelDef>()>& generator, const std::function<std::optional<EffectSlot>()>& effect)
  4232. {
  4233. const auto target = swapSession.target;
  4234. hotswap::Target now;
  4235. if (target.kind == hotswap::Kind::effect && effect)
  4236. {
  4237. auto fx = effect();
  4238. if (! fx)
  4239. return false;
  4240. engine.editSong ([&now, target, fx = std::move (*fx)] (Song& song) mutable { now = hotswap::swapEffect (song, target, std::move (fx)); });
  4241. }
  4242. else if (target.kind == hotswap::Kind::channel && generator)
  4243. {
  4244. auto c = generator();
  4245. if (! c)
  4246. return false;
  4247. if (const auto channel = hotswap::findChannel (engine.getSong(), target.instance); channel >= 0 && onHotSwapWillReplaceInstrument != nullptr)
  4248. onHotSwapWillReplaceInstrument (channel);
  4249. engine.editSong ([&now, target, c = std::move (*c)] (Song& song) mutable { now = hotswap::swapInstrument (song, target, std::move (c)); });
  4250. }
  4251. else
  4252. return false;
  4253. if (! now.active())
  4254. return false;
  4255. swapSession.retarget (now);
  4256. swapBar->repaint();
  4257. if (onHotSwapChanged != nullptr)
  4258. onHotSwapChanged();
  4259. return true;
  4260. }
  4261. bool BrowserComponent::hotSwapLoadFile (const juce::File& file)
  4262. {
  4263. const auto target = swapSession.target;
  4264. const auto& song = engine.getSong();
  4265. const auto loaded = [this] {
  4266. swapSession.loaded();
  4267. swapBar->repaint();
  4268. return true;
  4269. };
  4270. // a hosted plugin's own preset into the linked plugin (as its window's preset menu loads it)
  4271. if (pluginpresetui::isPresetFile (file) && (! file.hasFileExtension ("lynxpreset") || pluginpresetui::readLynxPreset (file).has_value()))
  4272. {
  4273. juce::AudioPluginInstance* plugin = nullptr;
  4274. if (target.kind == hotswap::Kind::effect)
  4275. {
  4276. if (const auto at = hotswap::findEffect (song, target.instance); at.found())
  4277. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (at.track, at.slot).get()))
  4278. plugin = &p->getInstance();
  4279. }
  4280. else if (const auto c = hotswap::findChannel (song, target.instance); c >= 0)
  4281. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (c).get()))
  4282. plugin = &p->getInstance();
  4283. juce::String error;
  4284. if (plugin == nullptr || ! pluginpresetui::load (*plugin, file, error))
  4285. return false;
  4286. engine.markModified();
  4287. // the device comes in on, as the preset loads it (round 190cy, Live 12.4.16)
  4288. if (const auto at = hotswap::findEffect (song, target.instance); at.found() && ! song.mixer[(std::size_t) at.track].effects[(std::size_t) at.slot].enabled)
  4289. engine.editSong ([target] (Song& s) { hotswap::presetLoadedInto (s, target); });
  4290. return loaded();
  4291. }
  4292. switch (hotswap::candidateFor (song, target, file.getFileName().toStdString()))
  4293. {
  4294. case hotswap::Candidate::effectPreset:
  4295. {
  4296. const auto at = hotswap::findEffect (song, target.instance);
  4297. if (file.hasFileExtension ("lynxpreset")) // one of LYNX's presets of this very effect: its settings only
  4298. {
  4299. const auto kind = song.mixer[(std::size_t) at.track].effects[(std::size_t) at.slot].kind;
  4300. const auto preset = presets::fromText (kind, file.loadFileAsString().toStdString());
  4301. if (! preset)
  4302. return false;
  4303. const auto name = preset->name.empty() ? file.getFileNameWithoutExtension().toStdString() : preset->name;
  4304. bool ok = false;
  4305. engine.editSong ([&ok, target, kind, &preset, &name] (Song& s) {
  4306. ok = hotswap::swapEffectPreset (s, target, kind, preset->params, preset->hasState ? &preset->state : nullptr, name);
  4307. });
  4308. return ok && loaded();
  4309. }
  4310. juce::MemoryBlock data;
  4311. if (! file.loadFileAsData (data))
  4312. return false;
  4313. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  4314. auto fx = effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), song.bpm, natives::flDataReader (flStudioAccess()));
  4315. if (! fx)
  4316. return false;
  4317. hotswap::Target now;
  4318. engine.editSong ([&now, target, fx = std::move (*fx)] (Song& s) mutable { now = hotswap::swapEffect (s, target, std::move (fx)); });
  4319. if (! now.active())
  4320. return false;
  4321. swapSession.retarget (now);
  4322. swapBar->repaint();
  4323. if (onHotSwapChanged != nullptr)
  4324. onHotSwapChanged();
  4325. return true;
  4326. }
  4327. case hotswap::Candidate::synthPreset:
  4328. {
  4329. juce::MemoryBlock data;
  4330. if (! file.loadFileAsData (data))
  4331. return false;
  4332. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  4333. const auto synth = synthFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()));
  4334. if (! synth)
  4335. return false;
  4336. ChannelDef c;
  4337. c.name = file.getFileNameWithoutExtension().toStdString();
  4338. c.instrument = InstrumentKind::synth;
  4339. c.synth = *synth;
  4340. return hotSwapLoadPlugin ([c] { return std::optional<ChannelDef> (c); }, {});
  4341. }
  4342. case hotswap::Candidate::sample:
  4343. {
  4344. const auto channel = hotswap::findChannel (song, target.instance);
  4345. if (channel < 0 || onHotSwapSample == nullptr)
  4346. return false;
  4347. onHotSwapSample (channel, file); // (the Channel Rack's own sample load: .speech files ask first)
  4348. return loaded();
  4349. }
  4350. default: break;
  4351. }
  4352. return false;
  4353. }
  4354. // --- what this Browser shows (round 163) ------------------------------------------------------------
  4355. juce::File BrowserComponent::viewFile (Role r)
  4356. {
  4357. return PluginHost::settingsFolder().getChildFile (r == Role::samples ? "sample-browser-view.txt" : "browser-view.txt");
  4358. }
  4359. bool BrowserComponent::sampleBrowserWasOpen()
  4360. {
  4361. return browserview::View::fromText (viewFile (Role::samples).loadFileAsString().toStdString()).open;
  4362. }
  4363. juce::Rectangle<int> BrowserComponent::sampleBrowserBounds()
  4364. {
  4365. const auto v = browserview::View::fromText (viewFile (Role::samples).loadFileAsString().toStdString());
  4366. return { v.x, v.y, v.width, v.height };
  4367. }
  4368. void BrowserComponent::loadView()
  4369. {
  4370. viewLoaded = true;
  4371. const auto file = viewFile (role);
  4372. viewFromFile = file.existsAsFile();
  4373. if (viewFromFile)
  4374. {
  4375. view = browserview::View::fromText (file.loadFileAsString().toStdString());
  4376. return;
  4377. }
  4378. view = {};
  4379. if (role == Role::samples)
  4380. {
  4381. // the Sample browser starts with only the places samples live, listing samples and SoundFonts
  4382. view.filter = browserview::ContentFilter::samples;
  4383. view.setShown (browserview::projectRootId, false);
  4384. view.setShown (browserview::pluginsRootId, false);
  4385. for (int i = 0; i < allRoots.size(); ++i)
  4386. if (! browserview::sampleBrowserShowsByDefault (allRootKinds[(std::size_t) i]))
  4387. view.setShown (allRoots[i].getFullPathName().toStdString(), false);
  4388. }
  4389. }
  4390. void BrowserComponent::saveView() const
  4391. {
  4392. if (! viewLoaded)
  4393. return;
  4394. const auto file = viewFile (role);
  4395. auto v = view;
  4396. if (role == Role::samples) // the window's open state and bounds are the window's to write
  4397. {
  4398. const auto old = browserview::View::fromText (file.loadFileAsString().toStdString());
  4399. v.open = old.open;
  4400. v.x = old.x, v.y = old.y, v.width = old.width, v.height = old.height;
  4401. }
  4402. file.getParentDirectory().createDirectory();
  4403. file.replaceWithText (juce::String::fromUTF8 (v.toText().c_str()));
  4404. }
  4405. bool BrowserComponent::lists (const juce::File& file) const
  4406. {
  4407. // (round 190iz: under the tab's / Live entry's own filter: PRESETS, SOUNDS, Samples...)
  4408. return (browserview::listed (file.getFileName().toStdString(), activeFilter()) && browserview::typeChosen (file.getFileName().toStdString(), view.types))
  4409. || file.isDirectory();
  4410. }
  4411. std::shared_ptr<const search::FolderMatches> BrowserComponent::filterMatches() const
  4412. {
  4413. const auto filter = activeFilter(); // (round 190iz)
  4414. if (filter == browserview::ContentFilter::all || searcher == nullptr)
  4415. return nullptr;
  4416. return searcher->service->folderMatches ((int) filter, [filter] (const std::string& name) { return browserview::listed (name, filter); });
  4417. }
  4418. bool BrowserComponent::filterHides (const juce::File& folder) const
  4419. {
  4420. // from the search index (cached; never waits for it): a folder it doesn't know yet stays listed
  4421. const auto matches = filterMatches();
  4422. return matches != nullptr && matches->of (folder.getFullPathName().toStdString()) == search::FolderMatches::Contents::none;
  4423. }
  4424. void BrowserComponent::applyFilterToTree()
  4425. {
  4426. const auto matches = filterMatches();
  4427. if (matches == nullptr || matches->generation == prunedGeneration)
  4428. return;
  4429. prunedGeneration = matches->generation;
  4430. if (tree->pruneFolders ([this] (const juce::File& f) { return filterHides (f); }))
  4431. treeView->setViewPosition (treeView->getViewPosition()); // (keeps the scroll inside the shorter list)
  4432. }
  4433. void BrowserComponent::setContentFilter (browserview::ContentFilter filter)
  4434. {
  4435. if (filter == view.filter)
  4436. return;
  4437. view.filter = filter;
  4438. saveView();
  4439. refreshViewButton();
  4440. prunedGeneration = 0;
  4441. rebuildTree();
  4442. refreshFoldersPanel();
  4443. if (searchBox.getText().trim().isNotEmpty())
  4444. runSearch();
  4445. }
  4446. void BrowserComponent::setRootShown (const juce::String& id, bool shown)
  4447. {
  4448. if (view.shows (id.toStdString()) == shown)
  4449. return;
  4450. view.setShown (id.toStdString(), shown);
  4451. saveView();
  4452. rebuildRoots();
  4453. if (searchBox.getText().trim().isNotEmpty())
  4454. runSearch();
  4455. }
  4456. void BrowserComponent::showAllRoots()
  4457. {
  4458. view.hidden.clear();
  4459. view.excluded.clear(); // (and every folder of the merged roots, round 178a)
  4460. saveView();
  4461. rebuildRoots();
  4462. }
  4463. juce::String BrowserComponent::rootId (const juce::File& folder) const
  4464. {
  4465. return allRoots.contains (folder) ? folder.getFullPathName() : juce::String();
  4466. }
  4467. void BrowserComponent::refreshViewButton()
  4468. {
  4469. const auto filtered = view.filter != browserview::ContentFilter::all;
  4470. int hidden = 0;
  4471. for (const auto& id : view.hidden)
  4472. hidden += id == browserview::projectRootId || id == browserview::pluginsRootId
  4473. || allRoots.contains (juce::File (juce::String::fromUTF8 (id.c_str())))
  4474. ? 1 : 0;
  4475. const auto ownTypes = ! view.types.empty() || ! view.hiddenFolderNames.empty(); // (round 190qi)
  4476. viewButton.setToggleState (filtered || hidden > 0 || ownTypes, juce::dontSendNotification);
  4477. juce::String text = tr ("Browser options: what to list, which folders to show");
  4478. if (filtered)
  4479. text << " (" << tr (browserview::contentFilterLabel (view.filter)) << ")";
  4480. if (hidden > 0)
  4481. text << " (" << (hidden == 1 ? tr ("1 folder hidden") : tr ("{0} folders hidden", { juce::String (hidden) })) << ")";
  4482. if (! view.types.empty())
  4483. text << " (" << tr ("some file types") << ")";
  4484. if (! view.hiddenFolderNames.empty())
  4485. text << " (" << tr ("folders hidden by name") << ")";
  4486. viewButton.setTooltip (text);
  4487. ui::setHint (viewButton, text, true);
  4488. }
  4489. void BrowserComponent::addHideItem (juce::PopupMenu& menu, const juce::String& id, const juce::String& label)
  4490. {
  4491. menu.addItem (tr ("Hide \"{0}\" from this Browser", { label }), [safe = juce::Component::SafePointer<BrowserComponent> (this), id] {
  4492. if (safe != nullptr)
  4493. safe->setRootShown (id, false);
  4494. });
  4495. }
  4496. void BrowserComponent::addViewItems (juce::PopupMenu& menu)
  4497. {
  4498. juce::Component::SafePointer<BrowserComponent> safe (this);
  4499. // what is listed (folders are always listed)
  4500. juce::PopupMenu filters;
  4501. for (int i = 0; i < browserview::contentFilterCount; ++i)
  4502. {
  4503. const auto f = (browserview::ContentFilter) i;
  4504. filters.addItem (tr (browserview::contentFilterLabel (f)), true, view.filter == f, [safe, f] {
  4505. if (safe != nullptr)
  4506. safe->setContentFilter (f);
  4507. });
  4508. }
  4509. menu.addSubMenu (tr ("Show") + ": " + tr (browserview::contentFilterLabel (view.filter)), filters);
  4510. // round 190qi (LYNX-own, FL users' request): the kinds of files listed, and folders left out by their names
  4511. {
  4512. std::size_t every = 0;
  4513. for (const auto& group : browserview::typeGroups())
  4514. every += group.extensions.size();
  4515. menu.addItem (view.types.empty() ? tr ("File types...")
  4516. : tr ("File types... ({0} of {1})", { juce::String ((int) view.types.size()), juce::String ((int) every) }),
  4517. [safe] {
  4518. if (safe != nullptr)
  4519. safe->showFileTypesDialog();
  4520. });
  4521. const auto names = juce::String::fromUTF8 (browserview::joinFolderNames (view.hiddenFolderNames).c_str());
  4522. menu.addItem (names.isEmpty() ? tr ("Hide folders named...") : tr ("Hide folders named... ({0})", { names.length() > 30 ? names.substring (0, 28) + "..." : names }),
  4523. [safe] {
  4524. if (safe != nullptr)
  4525. safe->askHiddenFolderNames();
  4526. });
  4527. }
  4528. // which top-level entries are shown and the user's own folders: a window (round 164; a checklist sub-menu before)
  4529. menu.addItem (tr ("Show folders..."), [safe] {
  4530. if (safe != nullptr)
  4531. safe->showFoldersDialog();
  4532. });
  4533. }
  4534. // --- the "Show folders" window (round 164) --------------------------------------------------------------
  4535. // Which top-level entries this Browser shows, as a checklist (ticks apply at once), the user's own folders with a
  4536. // Remove button, Add folder..., Show all. Each entry says where it is and, under a content filter, whether it holds
  4537. // anything to list (those folders are left out of the tree while the filter is on).
  4538. class BrowserComponent::FoldersPanel final : public juce::Component
  4539. {
  4540. public:
  4541. using Entry = FolderEntry;
  4542. explicit FoldersPanel (BrowserComponent* b) : browser (b)
  4543. {
  4544. title.setFont (theme::font (theme::type::body, true));
  4545. title.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  4546. addAndMakeVisible (title);
  4547. note.setFont (theme::font (theme::type::small));
  4548. note.setColour (juce::Label::textColourId, theme::colour::textSecondary);
  4549. note.setJustificationType (juce::Justification::topLeft);
  4550. addAndMakeVisible (note);
  4551. list.setViewedComponent (&rows, false);
  4552. list.setScrollBarsShown (true, false);
  4553. list.setScrollBarThickness (10);
  4554. addAndMakeVisible (list);
  4555. addFolder.setButtonText (tr ("Add folder..."));
  4556. addFolder.setTooltip (tr ("Add one of your own folders to the Browsers (samples, projects, SoundFonts...)"));
  4557. addFolder.onClick = [this] { if (browser != nullptr) browser->addUserFolder(); };
  4558. showAll.setButtonText (tr ("Show all"));
  4559. showAll.setTooltip (tr ("Tick every folder"));
  4560. showAll.onClick = [this] { if (browser != nullptr) browser->showAllRoots(); };
  4561. close.setButtonText (tr ("Close"));
  4562. close.setColour (juce::TextButton::buttonColourId, theme::colour::accent);
  4563. close.setColour (juce::TextButton::textColourOffId, theme::colour::onAccent);
  4564. close.onClick = [this] { closeToolWindowOf (*this); };
  4565. for (auto* button : { &addFolder, &showAll, &close })
  4566. addAndMakeVisible (button);
  4567. refresh();
  4568. setSize (520, 470);
  4569. }
  4570. // the browser's entries again (a tick, an added / removed folder, the filter changed)
  4571. void refresh()
  4572. {
  4573. if (browser == nullptr)
  4574. return;
  4575. setEntries (browser->folderEntries(), browser->role == Role::samples,
  4576. browser->view.filter == browserview::ContentFilter::all ? juce::String() : tr (browserview::contentFilterLabel (browser->view.filter)));
  4577. }
  4578. void setEntries (std::vector<Entry> newEntries, bool sampleBrowser, const juce::String& filterName)
  4579. {
  4580. entries = std::move (newEntries);
  4581. title.setText (sampleBrowser ? tr ("Folders shown in the Sample browser") : tr ("Folders shown in the Browser"), juce::dontSendNotification);
  4582. auto text = tr ("Untick what you don't use: it leaves this Browser and its searches. Nothing is deleted.");
  4583. if (filterName.isNotEmpty())
  4584. text << "\n" << tr ("Listing \"{0}\": folders with nothing of that kind are left out of the tree.", { filterName });
  4585. note.setText (text, juce::dontSendNotification);
  4586. int shown = 0;
  4587. for (const auto& e : entries)
  4588. shown += e.shown ? 1 : 0;
  4589. showAll.setEnabled (shown < (int) entries.size());
  4590. rows.deleteAllChildren();
  4591. for (int i = 0; i < (int) entries.size(); ++i)
  4592. rows.addAndMakeVisible (new Row (*this, i));
  4593. layoutRows();
  4594. }
  4595. void resized() override
  4596. {
  4597. auto area = getLocalBounds().reduced (14, 12);
  4598. title.setBounds (area.removeFromTop (22));
  4599. note.setBounds (area.removeFromTop (note.getText().containsChar ('\n') ? 36 : 20));
  4600. area.removeFromTop (6);
  4601. auto bottom = area.removeFromBottom (28);
  4602. close.setBounds (bottom.removeFromRight (90));
  4603. addFolder.setBounds (bottom.removeFromLeft (120));
  4604. bottom.removeFromLeft (8);
  4605. showAll.setBounds (bottom.removeFromLeft (90));
  4606. area.removeFromBottom (10);
  4607. list.setBounds (area);
  4608. layoutRows();
  4609. }
  4610. void paint (juce::Graphics& g) override
  4611. {
  4612. g.fillAll (theme::colour::bg2);
  4613. g.setColour (theme::colour::border);
  4614. g.drawRect (list.getBounds().expanded (1), 1);
  4615. }
  4616. static constexpr int rowHeight = 34;
  4617. private:
  4618. struct Row final : public juce::Component
  4619. {
  4620. Row (FoldersPanel& p, int i) : panel (p), index (i)
  4621. {
  4622. const auto& e = panel.entries[(std::size_t) i];
  4623. tick.setToggleState (e.shown, juce::dontSendNotification);
  4624. tick.setTooltip (e.shown ? tr ("Shown: untick to hide it from this Browser") : tr ("Hidden: tick to show it"));
  4625. tick.onClick = [this] { panel.toggle (index, tick.getToggleState()); };
  4626. addAndMakeVisible (tick);
  4627. if (e.user)
  4628. {
  4629. remove.setTooltip (tr ("Remove this folder from the Browsers (the folder itself stays on the disk)"));
  4630. remove.setFlat (true);
  4631. remove.onClick = [this] { panel.remove (index); };
  4632. addAndMakeVisible (remove);
  4633. }
  4634. }
  4635. void resized() override
  4636. {
  4637. auto area = getLocalBounds().reduced (6, 0);
  4638. tick.setBounds (area.removeFromLeft (26).withSizeKeepingCentre (24, 24));
  4639. if (remove.isVisible())
  4640. remove.setBounds (area.removeFromRight (26).withSizeKeepingCentre (22, 22));
  4641. }
  4642. void paint (juce::Graphics& g) override
  4643. {
  4644. const auto& e = panel.entries[(std::size_t) index];
  4645. if (index % 2 == 1)
  4646. g.fillAll (theme::colour::bg2.brighter (0.06f));
  4647. auto area = getLocalBounds().reduced (6, 2).withTrimmedLeft (32).withTrimmedRight (remove.isVisible() ? 30 : 0);
  4648. auto top = area.removeFromTop (area.getHeight() / 2 + 1);
  4649. g.setFont (theme::font (theme::type::body, e.shown));
  4650. g.setColour (e.shown ? theme::colour::textPrimary : theme::colour::textDisabled);
  4651. juce::String name = e.name;
  4652. if (e.user)
  4653. name << " " << tr ("(your folder)");
  4654. g.drawText (name, top, juce::Justification::bottomLeft, true);
  4655. g.setFont (theme::font (theme::type::small));
  4656. g.setColour (theme::colour::textDisabled);
  4657. auto detail = e.path;
  4658. if (e.empty)
  4659. detail = tr ("nothing to list under the filter") + " · " + detail;
  4660. g.drawFittedText (detail, area, juce::Justification::topLeft, 1, 0.9f);
  4661. }
  4662. void mouseUp (const juce::MouseEvent& e) override
  4663. {
  4664. if (e.mouseWasClicked() && ! e.mods.isPopupMenu())
  4665. tick.triggerClick(); // the whole row ticks
  4666. }
  4667. FoldersPanel& panel;
  4668. int index;
  4669. juce::ToggleButton tick;
  4670. IconButton remove { "remove folder", Icon::close };
  4671. };
  4672. void layoutRows()
  4673. {
  4674. const auto width = list.getWidth() - (entries.size() * (std::size_t) rowHeight > (std::size_t) list.getHeight() ? 10 : 0);
  4675. rows.setSize (juce::jmax (0, width), (int) entries.size() * rowHeight);
  4676. for (int i = 0; i < rows.getNumChildComponents(); ++i)
  4677. rows.getChildComponent (i)->setBounds (0, i * rowHeight, rows.getWidth(), rowHeight);
  4678. }
  4679. void toggle (int index, bool shown)
  4680. {
  4681. if (browser != nullptr && juce::isPositiveAndBelow (index, (int) entries.size()))
  4682. {
  4683. const auto id = entries[(std::size_t) index].id;
  4684. juce::MessageManager::callAsync ([safe = browser, id, shown] { // (rebuilds the rows: not inside a row's click)
  4685. if (safe != nullptr)
  4686. safe->setRootShown (id, shown);
  4687. });
  4688. }
  4689. }
  4690. void remove (int index)
  4691. {
  4692. if (browser != nullptr && juce::isPositiveAndBelow (index, (int) entries.size()))
  4693. {
  4694. const juce::File folder (entries[(std::size_t) index].path);
  4695. juce::MessageManager::callAsync ([safe = browser, folder] {
  4696. if (safe != nullptr)
  4697. safe->removeUserFolder (folder);
  4698. });
  4699. }
  4700. }
  4701. juce::Component::SafePointer<BrowserComponent> browser;
  4702. std::vector<Entry> entries;
  4703. juce::Label title, note;
  4704. juce::Viewport list;
  4705. juce::Component rows;
  4706. juce::TextButton addFolder, showAll, close;
  4707. };
  4708. std::vector<BrowserComponent::FolderEntry> BrowserComponent::folderEntries() const
  4709. {
  4710. std::vector<FolderEntry> out;
  4711. out.push_back ({ browserview::projectRootId, tr ("Current project"), tr ("the project's patterns, channels, samples and history"),
  4712. view.shows (browserview::projectRootId), false, false });
  4713. out.push_back ({ browserview::pluginsRootId, tr ("Plugin database"), tr ("LYNX SHARE's, FL's and your installed plugins"),
  4714. view.shows (browserview::pluginsRootId), false, false });
  4715. for (int i = 0; i < allRoots.size(); ++i)
  4716. {
  4717. FolderEntry e;
  4718. e.id = e.path = allRoots[i].getFullPathName();
  4719. e.name = allRootNames[i];
  4720. e.shown = view.shows (e.id.toStdString());
  4721. e.user = allRootKinds[(std::size_t) i] == browserview::RootKind::user;
  4722. const auto merged = withMerged ({ allRoots[i] });
  4723. e.empty = std::all_of (merged.begin(), merged.end(), [this] (const juce::File& f) { return filterHides (f); });
  4724. out.push_back (std::move (e));
  4725. }
  4726. return out;
  4727. }
  4728. void BrowserComponent::refreshFoldersPanel()
  4729. {
  4730. if (auto* panel = dynamic_cast<FoldersPanel*> (foldersPanel.getComponent()))
  4731. panel->refresh();
  4732. }
  4733. void BrowserComponent::showFoldersDialog()
  4734. {
  4735. auto panel = std::make_unique<FoldersPanel> (this);
  4736. foldersPanel = panel.get();
  4737. openToolWindow (std::move (panel), role == Role::samples ? tr ("Sample browser folders") : tr ("Browser folders"),
  4738. role == Role::samples ? "sample-browser-folders" : "browser-folders");
  4739. }
  4740. std::unique_ptr<juce::Component> BrowserComponent::makeFoldersPanelForSnapshot()
  4741. {
  4742. auto panel = std::make_unique<FoldersPanel> (this);
  4743. // a user folder (with its Remove button) and one hidden entry, whatever this machine has
  4744. auto entries = folderEntries();
  4745. entries.push_back ({ "D:\\Samples\\Drums", "Drums", "D:\\Samples\\Drums", true, true, false });
  4746. if (entries.size() > 3)
  4747. entries[2].shown = false;
  4748. panel->setEntries (std::move (entries), false, {});
  4749. return panel;
  4750. }
  4751. void BrowserComponent::showViewMenu()
  4752. {
  4753. buildViewMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&viewButton));
  4754. }
  4755. juce::PopupMenu BrowserComponent::buildViewMenu()
  4756. {
  4757. juce::PopupMenu menu;
  4758. addViewItems (menu);
  4759. juce::Component::SafePointer<BrowserComponent> safe (this);
  4760. menu.addSeparator();
  4761. // round 190ce (the reference's preview switch): off = a selected file is shown, not played; Play on the strip plays it
  4762. menu.addItem (tr ("Preview files when they are selected"), true, autoPreview, [safe] {
  4763. autoPreview = ! autoPreview;
  4764. if (! autoPreview && safe != nullptr)
  4765. safe->stopPreview();
  4766. if (safe != nullptr && safe->onPreviewVolumeChanged != nullptr)
  4767. safe->onPreviewVolumeChanged(); // (saved with the preview volume)
  4768. });
  4769. // FL's Browser menu › View "Auto-hide" (round 190mv, DF-107; capture 190mv A2: only a floating Browser hides)
  4770. if (role != Role::samples && onAutoHideChanged != nullptr)
  4771. menu.addItem (tr ("Auto-hide"), true, autoHide, [safe] {
  4772. autoHide = ! autoHide;
  4773. if (safe != nullptr && safe->onAutoHideChanged != nullptr)
  4774. safe->onAutoHideChanged();
  4775. });
  4776. // FL's Browser menu › View "Full sample preview" (round 190iz; off: a click plays the first 5 seconds, as FL)
  4777. menu.addItem (tr ("Full sample preview"), true, engine.isFullSamplePreview(), [safe] {
  4778. if (safe == nullptr)
  4779. return;
  4780. safe->engine.setFullSamplePreview (! safe->engine.isFullSamplePreview());
  4781. safe->savePrefs();
  4782. });
  4783. // LYNX's own (round 190aq, off by default): loops are auditioned at the project's tempo, starting on the beat
  4784. menu.addItem (tr ("Preview in time (loops play at the project's tempo, on the beat)"), true, engine.isPreviewInTime(), [safe] {
  4785. if (safe == nullptr)
  4786. return;
  4787. safe->engine.setPreviewInTime (! safe->engine.isPreviewInTime());
  4788. if (safe->onPreviewVolumeChanged != nullptr)
  4789. safe->onPreviewVolumeChanged(); // (saved with the preview volume)
  4790. });
  4791. // round 190kx (Simple layout, as BandLab): dropped loops take the tempo and key found in their audio
  4792. if (showsLoopRowInfo())
  4793. menu.addItem (tr ("Dropped loops take the tempo and key found in their audio"), true, loopanalysis::dropDetects().load(),
  4794. [] { workflowextras::setExtra ("simple.loopDetect", ! loopanalysis::dropDetects().load()); });
  4795. menu.addSeparator();
  4796. menu.addItem (tr ("Refresh"), [safe] { if (safe != nullptr) safe->rebuildRoots(); });
  4797. menu.addItem (tr ("Refresh search index"), [safe] { if (safe != nullptr) safe->refreshSearchIndex (false); });
  4798. if (onToggleSampleBrowser != nullptr)
  4799. {
  4800. menu.addSeparator();
  4801. menu.addItem (role == Role::samples ? tr ("Close the Sample browser") : tr ("Sample browser (separate window)"),
  4802. [safe] { if (safe != nullptr && safe->onToggleSampleBrowser != nullptr) safe->onToggleSampleBrowser(); });
  4803. }
  4804. return menu;
  4805. }
  4806. namespace
  4807. {
  4808. // The Sample browser window's content: a drag container (samples dragged out of this window reach the Channel Rack,
  4809. // the Playlist and the Mixer of the main window) holding the Browser; it keeps the window's bounds and whether the
  4810. // user closed it.
  4811. class SampleBrowserHost final : public juce::Component,
  4812. public juce::DragAndDropContainer
  4813. {
  4814. public:
  4815. SampleBrowserHost (AudioEngine& engine, const std::function<void (BrowserComponent&)>& wire)
  4816. : browser (engine, BrowserComponent::Role::samples)
  4817. {
  4818. if (wire != nullptr)
  4819. wire (browser);
  4820. addAndMakeVisible (browser);
  4821. setSize (340, 620);
  4822. if (std::exchange (BrowserComponent::openLoopsNext, false)) // (round gaps190kf: the Simple layout's Loops tile)
  4823. browser.setLoopsShown (true);
  4824. }
  4825. ~SampleBrowserHost() override
  4826. {
  4827. // a window the user closed is hidden first (ToolWindow::closeSoon); one deleted while visible goes with LYNX
  4828. // and opens again at the next start
  4829. auto* window = getTopLevelComponent();
  4830. auto v = browser.getView();
  4831. v.open = window != this && window->isVisible();
  4832. if (window != this)
  4833. {
  4834. const auto b = window->getBounds();
  4835. v.x = b.getX();
  4836. v.y = b.getY();
  4837. v.width = b.getWidth();
  4838. v.height = b.getHeight();
  4839. }
  4840. file().getParentDirectory().createDirectory();
  4841. file().replaceWithText (juce::String::fromUTF8 (v.toText().c_str()));
  4842. }
  4843. void resized() override { browser.setBounds (getLocalBounds()); }
  4844. // issue #174: a sample dragged from this window onto a plugin's own editor (or out of LYNX) goes on as a file drag
  4845. bool shouldDropFilesWhenDraggedExternally (const juce::DragAndDropTarget::SourceDetails& details, juce::StringArray& files,
  4846. bool& canMoveFiles) override
  4847. {
  4848. return externaldrag::shouldDropFiles (details, nullptr, files, canMoveFiles);
  4849. }
  4850. static juce::File file() { return PluginHost::settingsFolder().getChildFile ("sample-browser-view.txt"); }
  4851. BrowserComponent browser;
  4852. };
  4853. } // namespace
  4854. namespace
  4855. {
  4856. // Round 190lx (DS-42): the Simple layout's Loops dock (BrowserComponent::makeLoopsDock)
  4857. class LoopsDock final : public juce::Component
  4858. {
  4859. public:
  4860. LoopsDock (AudioEngine& engine, const std::function<void (BrowserComponent&)>& wire, std::function<void()> closed)
  4861. : browser (engine, BrowserComponent::Role::samples), onClose (std::move (closed))
  4862. {
  4863. if (wire != nullptr)
  4864. wire (browser);
  4865. title.setText (tr ("Loops"), juce::dontSendNotification);
  4866. title.setFont (theme::font (theme::type::title, true));
  4867. title.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  4868. title.setInterceptsMouseClicks (false, false);
  4869. closeButton.setButtonText (juce::String::fromUTF8 ("\xc3\x97"));
  4870. closeButton.setTooltip (tr ("Close"));
  4871. closeButton.onClick = [this] {
  4872. if (onClose != nullptr)
  4873. onClose();
  4874. };
  4875. addAndMakeVisible (title);
  4876. addAndMakeVisible (closeButton);
  4877. addAndMakeVisible (browser);
  4878. browser.setLoopsShown (true);
  4879. setTitle (tr ("Loops"));
  4880. }
  4881. void paint (juce::Graphics& g) override
  4882. {
  4883. g.fillAll (theme::colour::bg2);
  4884. g.setColour (theme::colour::border); // (BandLab: a 1 px edge on the left)
  4885. g.drawVerticalLine (0, 0.0f, (float) getHeight());
  4886. }
  4887. void resized() override
  4888. {
  4889. auto r = getLocalBounds().withTrimmedLeft (1);
  4890. auto head = r.removeFromTop (36).reduced (12, 4);
  4891. closeButton.setBounds (head.removeFromRight (28));
  4892. title.setBounds (head);
  4893. browser.setBounds (r);
  4894. }
  4895. BrowserComponent browser;
  4896. private:
  4897. juce::Label title;
  4898. juce::TextButton closeButton;
  4899. std::function<void()> onClose;
  4900. };
  4901. } // namespace
  4902. std::unique_ptr<juce::Component> BrowserComponent::makeLoopsDock (AudioEngine& engine, const std::function<void (BrowserComponent&)>& wire,
  4903. std::function<void()> onClose)
  4904. {
  4905. return std::make_unique<LoopsDock> (engine, wire, std::move (onClose));
  4906. }
  4907. BrowserComponent* BrowserComponent::browserOfLoopsDock (juce::Component* dock)
  4908. {
  4909. auto* d = dynamic_cast<LoopsDock*> (dock);
  4910. return d != nullptr ? &d->browser : nullptr;
  4911. }
  4912. std::unique_ptr<juce::Component> BrowserComponent::makeSampleBrowserContent (AudioEngine& engine, const std::function<void (BrowserComponent&)>& wire)
  4913. {
  4914. auto host = std::make_unique<SampleBrowserHost> (engine, wire);
  4915. auto v = host->browser.getView();
  4916. v.open = true; // (written at once: a crash keeps it open next time too)
  4917. SampleBrowserHost::file().getParentDirectory().createDirectory();
  4918. SampleBrowserHost::file().replaceWithText (juce::String::fromUTF8 (v.toText().c_str()));
  4919. return host;
  4920. }
  4921. juce::File BrowserComponent::firstSampleFolder() const
  4922. {
  4923. using browserview::RootKind;
  4924. for (auto wanted : { RootKind::flSamples, RootKind::user, RootKind::music })
  4925. for (int i = 0; i < allRoots.size() && i < (int) allRootKinds.size(); ++i)
  4926. if (allRootKinds[(std::size_t) i] == wanted && allRoots[i].isDirectory())
  4927. return allRoots[i];
  4928. return {};
  4929. }
  4930. void BrowserComponent::rebuildRoots()
  4931. {
  4932. roots.clear();
  4933. rootNames.clear();
  4934. allRoots.clear();
  4935. allRootNames.clear();
  4936. allRootKinds.clear();
  4937. rootAlso.clear();
  4938. using browserview::RootKind;
  4939. // FL folders (if installed) and user folders. Round 190bj (QA: the FL folders were listed with LYNX_NO_FL=1): the
  4940. // installation comes from findFlStudio, as everywhere else (FL's own install path, Program Files\Image-Line, Wine,
  4941. // LYNX_FL_INSTALL; none with LYNX_NO_FL)
  4942. const auto flInstall = findFlStudio();
  4943. const auto fl = flInstall.installDir;
  4944. auto add = [this] (const juce::String& name, const juce::File& folder, RootKind kind) {
  4945. if (folder.isDirectory() && ! allRoots.contains (folder))
  4946. {
  4947. allRoots.add (folder);
  4948. allRootNames.add (name);
  4949. allRootKinds.push_back (kind);
  4950. }
  4951. };
  4952. // one root for several folders, as FL's Browser shows its Scores and Mixer presets (the user's Presets folder and
  4953. // its own Data\\Patches one, round 178a): the first folder that exists is the root, the others are merged into it
  4954. auto addMerged = [this, &add] (const juce::String& name, juce::Array<juce::File> folders, RootKind kind) {
  4955. folders.removeIf ([] (const juce::File& f) { return ! f.isDirectory(); });
  4956. if (folders.isEmpty())
  4957. return;
  4958. const auto root = folders.removeAndReturn (0);
  4959. add (name, root, kind);
  4960. if (! folders.isEmpty() && allRoots.contains (root))
  4961. rootAlso[root.getFullPathName()] = folders;
  4962. };
  4963. const auto data = fl.getChildFile ("Data");
  4964. add (tr ("FL samples (Packs)"), data.getChildFile ("Patches").getChildFile ("Packs"), RootKind::flSamples);
  4965. add (tr ("FL demo projects"), data.getChildFile ("Demo projects"), RootKind::flDemos);
  4966. const auto userData = flInstall.userData;
  4967. auto userPresets = [&userData] (const char* folder) {
  4968. return userData.isDirectory() ? userData.getChildFile ("Presets").getChildFile (folder) : juce::File();
  4969. };
  4970. addMerged (tr ("Scores"), { userPresets ("Scores"), data.getChildFile ("Patches").getChildFile ("Scores") }, RootKind::flMidi);
  4971. add (tr ("3x Osc presets (FL)"), data.getChildFile ("Patches").getChildFile ("Channel presets").getChildFile ("3x Osc"), RootKind::flPresets);
  4972. add (tr ("Synth presets (FL)"), data.getChildFile ("Patches").getChildFile ("Plugin presets").getChildFile ("Generators"), RootKind::flPresets);
  4973. add (tr ("Speech (FL)"), data.getChildFile ("Patches").getChildFile ("Speech"), RootKind::speech);
  4974. speechui::userSpeechFolder().createDirectory(); // (the Speech properties save there; round 168b)
  4975. add (tr ("Speech"), speechui::userSpeechFolder(), RootKind::speech);
  4976. // FL's Browser folder "Mixer presets" (REA round 167q, FUN_009db5b0: the user's and the installation's, one root)
  4977. addMerged (tr ("Mixer presets"), { userPresets ("Mixer presets"), data.getChildFile ("Patches").getChildFile ("Mixer presets") },
  4978. RootKind::flPresets);
  4979. pluginpresetui::presetsRoot().createDirectory(); // (the plugin window saves presets there; round 162d)
  4980. add (tr ("Plugin presets"), pluginpresetui::presetsRoot(), RootKind::pluginPresets);
  4981. audioclipboard::folder().createDirectory(); // (Tools › Clipboard saves there; round 181b)
  4982. add (tr ("Clipboard files"), audioclipboard::folder(), RootKind::clipboardFiles);
  4983. add (tr ("Documents"), juce::File::getSpecialLocation (juce::File::userDocumentsDirectory), RootKind::documents);
  4984. add (tr ("Music"), juce::File::getSpecialLocation (juce::File::userMusicDirectory), RootKind::music);
  4985. add (tr ("Desktop"), juce::File::getSpecialLocation (juce::File::userDesktopDirectory), RootKind::desktop);
  4986. add (tr ("Downloads"), juce::File::getSpecialLocation (juce::File::userHomeDirectory).getChildFile ("Downloads"), RootKind::downloads);
  4987. for (const auto& line : juce::StringArray::fromLines (userFoldersFile().loadFileAsString()))
  4988. if (line.trim().isNotEmpty())
  4989. add (juce::File (line.trim()).getFileName(), juce::File (line.trim()), RootKind::user);
  4990. if (! viewLoaded)
  4991. loadView();
  4992. bool migrated = false; // (round 178a: the old "FL MIDI" / "Mixer presets (FL)" roots' hidden state)
  4993. for (const auto& [rootPath, folders] : rootAlso)
  4994. migrated = browserview::migrateMergedRoot (view, rootPath.toStdString(), toPaths (folders)) || migrated;
  4995. if (migrated && viewFromFile)
  4996. saveView();
  4997. for (int i = 0; i < allRoots.size(); ++i)
  4998. if (view.shows (allRoots[i].getFullPathName().toStdString()))
  4999. {
  5000. roots.add (allRoots[i]);
  5001. rootNames.add (allRootNames[i]);
  5002. }
  5003. refreshViewButton();
  5004. refreshFoldersPanel();
  5005. loadCollections();
  5006. if (liveLayout) // round 190iz: Live's Places follow the folders
  5007. sidebar->refresh();
  5008. rebuildTree();
  5009. }
  5010. // A collection's items for the STARRED tab and Live's Collections (round 190iz: from the STARRED tab's code of round 190ce):
  5011. // folders first (each opens like the ALL tab's), then files, then Plugin database entries, each by name; missing files
  5012. // and plugins that are gone are left out.
  5013. std::vector<std::unique_ptr<BrowserComponent::FileTree::Node>> BrowserComponent::FileTree::collectionNodes (BrowserComponent& browser, int collection)
  5014. {
  5015. const auto& store = collectionStore();
  5016. std::vector<std::unique_ptr<FileTree::Node>> out;
  5017. juce::Array<juce::File> folders, files;
  5018. std::vector<std::unique_ptr<FileTree::Node>> plugins;
  5019. for (const auto& item : store.itemsOf (collection))
  5020. {
  5021. if (collections::isPluginItem (item))
  5022. {
  5023. if (auto n = FileTree::makePluginItem (browser, collections::pluginKeyOf (item)))
  5024. plugins.push_back (std::move (n));
  5025. continue;
  5026. }
  5027. if (const juce::File f (juce::String::fromUTF8 (item.c_str())); f.isDirectory())
  5028. folders.add (f);
  5029. else if (f.existsAsFile())
  5030. files.add (f);
  5031. }
  5032. const auto byName = [] (const juce::File& a, const juce::File& b) { return a.getFileName().compareNatural (b.getFileName()) < 0; };
  5033. std::sort (folders.begin(), folders.end(), byName);
  5034. std::sort (files.begin(), files.end(), byName);
  5035. std::sort (plugins.begin(), plugins.end(), [] (const auto& a, const auto& b) { return a->label.compareNatural (b->label) < 0; });
  5036. for (const auto& f : folders)
  5037. out.push_back (FileTree::makeFolder (f, f.getFileName(), collectionColour (collection)));
  5038. for (const auto& f : files)
  5039. {
  5040. auto n = std::make_unique<FileTree::Node>();
  5041. n->file = f;
  5042. out.push_back (std::move (n));
  5043. }
  5044. for (auto& n : plugins)
  5045. out.push_back (std::move (n));
  5046. return out;
  5047. }
  5048. // Round 190iz: Live's Instruments / Audio Effects / MIDI Effects / Plug-Ins / Modulators: the Plugin database entries
  5049. // of that kind as one list, by name (the same rows, double-click and drag as in the database's tree)
  5050. std::vector<std::unique_ptr<BrowserComponent::FileTree::Node>> BrowserComponent::FileTree::livePluginNodes (BrowserComponent& browser, browserplaces::Category category)
  5051. {
  5052. std::vector<std::unique_ptr<FileTree::Node>> out;
  5053. auto safe = juce::Component::SafePointer<BrowserComponent> (&browser);
  5054. auto& engine = browser.engine;
  5055. const auto wanted = browserplaces::wantsPlugins (category);
  5056. if (wanted != 0)
  5057. for (auto& e : quickpick::generatorEntries (engine))
  5058. {
  5059. const char* groups[] = { "LYNX", "FL engines", "VFX", "" };
  5060. if (! browserplaces::keepsPlugin (category, true, groups[juce::jlimit (0, 3, e.folder)], e.label.toStdString()))
  5061. continue;
  5062. auto n = std::make_unique<FileTree::Node>();
  5063. n->kind = FileTree::Kind::plugin;
  5064. n->pluginKey = e.key;
  5065. n->label = quickpick::shownName (engine, e.key, e.label);
  5066. n->original = e.label;
  5067. n->detail = e.detail;
  5068. n->icon = e.folder == 3 ? Icon::plugin : Icon::keyboard;
  5069. n->generator = e.make;
  5070. n->activate = [safe, make = e.make] {
  5071. if (auto c = make(); c && safe != nullptr && safe->onAddInstrument)
  5072. safe->onAddInstrument (std::move (*c));
  5073. };
  5074. out.push_back (std::move (n));
  5075. }
  5076. if (wanted != 1)
  5077. for (auto& e : quickpick::effectEntries (engine))
  5078. {
  5079. const char* groups[] = { "LYNX", "FL engines", "", "" };
  5080. if (! browserplaces::keepsPlugin (category, false, groups[juce::jlimit (0, 3, e.folder)], e.label.toStdString()))
  5081. continue;
  5082. auto n = std::make_unique<FileTree::Node>();
  5083. n->kind = FileTree::Kind::plugin;
  5084. n->pluginKey = e.key;
  5085. n->label = quickpick::shownName (engine, e.key, e.label);
  5086. n->original = e.label;
  5087. n->detail = e.detail;
  5088. n->icon = e.folder == 3 ? Icon::plugin : Icon::mixer;
  5089. n->effect = e.make;
  5090. n->activate = [safe, make = e.make] {
  5091. if (auto fx = make(); fx && safe != nullptr && safe->onAddEffect)
  5092. safe->onAddEffect (std::move (*fx));
  5093. };
  5094. out.push_back (std::move (n));
  5095. }
  5096. std::stable_sort (out.begin(), out.end(), [] (const auto& a, const auto& b) { return a->label.compareNatural (b->label) < 0; });
  5097. return out;
  5098. }
  5099. bool BrowserComponent::showsRoot (int i) const
  5100. {
  5101. if (! juce::isPositiveAndBelow (i, allRoots.size()) || ! roots.contains (allRoots[i]))
  5102. return false; // hidden from this Browser (round 163)
  5103. const auto kind = allRootKinds[(std::size_t) i];
  5104. if (liveLayout)
  5105. {
  5106. if (liveSelection.category == browserplaces::Category::folder)
  5107. return allRoots[i].getFullPathName().toStdString() == liveSelection.path;
  5108. return browserplaces::categoryShowsRoot (liveSelection.category, kind);
  5109. }
  5110. return browserplaces::tabShowsRoot ((browserplaces::Tab) tab, kind);
  5111. }
  5112. browserview::ContentFilter BrowserComponent::activeFilter() const
  5113. {
  5114. if (liveLayout)
  5115. return browserplaces::categoryFilter (liveSelection.category, view.filter);
  5116. return browserplaces::tabFilter ((browserplaces::Tab) tab, view.filter);
  5117. }
  5118. void BrowserComponent::rebuildTree()
  5119. {
  5120. using browserplaces::Category;
  5121. std::vector<std::unique_ptr<FileTree::Node>> top;
  5122. const auto cat = liveSelection.category;
  5123. categoryQuery = {};
  5124. auto finish = [this, &top] {
  5125. tree->setTopLevel (std::move (top));
  5126. treeView->setViewPosition (0, 0);
  5127. };
  5128. if (liveLayout && cat == Category::collection) // round 190iz: Live's Collections
  5129. {
  5130. top = FileTree::collectionNodes (*this, liveSelection.collection);
  5131. finish();
  5132. return;
  5133. }
  5134. if (! liveLayout && tab == starredTab)
  5135. {
  5136. // Only Starred switched on (as it is at first): its items alone, the tab as it always was. More than one (or
  5137. // another one): each collection under its heading.
  5138. const auto shown = collectionStore().shown();
  5139. if (shown.size() == 1 && shown.front() == 0)
  5140. top = FileTree::collectionNodes (*this, 0);
  5141. else
  5142. for (const auto c : shown)
  5143. {
  5144. auto items = FileTree::collectionNodes (*this, c);
  5145. auto heading = FileTree::makeCollection (c, (int) items.size(), closedCollections.count (c) == 0);
  5146. heading->children = std::move (items);
  5147. top.push_back (std::move (heading));
  5148. }
  5149. finish();
  5150. return;
  5151. }
  5152. // round 190iz: FL's PLUGINS tab (the Plugin database, opened) and Live's plugin categories (one list each)
  5153. if (liveLayout ? (browserplaces::wantsPlugins (cat) >= 0 && cat != Category::all) : tab == pluginsTab)
  5154. {
  5155. if (liveLayout)
  5156. top = FileTree::livePluginNodes (*this, cat);
  5157. else
  5158. {
  5159. auto db = FileTree::makePluginDatabase (*this, openPluginFolders);
  5160. db->expanded = true;
  5161. top.push_back (std::move (db));
  5162. }
  5163. finish();
  5164. return;
  5165. }
  5166. const auto allLike = liveLayout ? cat == Category::all : tab == allTab;
  5167. if (liveLayout ? (cat == Category::currentProject || (allLike && view.shows (browserview::projectRootId)))
  5168. : (tab == projectTab || (allLike && view.shows (browserview::projectRootId))))
  5169. top.push_back (FileTree::makeProject (shownTab() == projectTab));
  5170. // FL's Plugin database, under the project (round 142); always while hot-swap is on (round 190ce: it is what the
  5171. // linked device is replaced from, also when the user's view leaves it out)
  5172. if (allLike && (view.shows (browserview::pluginsRootId) || swapSession.active()))
  5173. {
  5174. browserStartupMark (" browser: roots (FL folders, user folders, view, collections)");
  5175. top.push_back (FileTree::makePluginDatabase (*this, openPluginFolders));
  5176. browserStartupMark (" browser: the Plugin database tree");
  5177. }
  5178. // round 190ke (owner decision D2): LYNX's own content with its tags, in the Simple layout
  5179. if (! liveLayout && layoutstyle::current() == layoutstyle::Style::simple && (allLike || tab == presetsTab || tab == soundsTab))
  5180. top.push_back (FileTree::makeFactoryRoot (*this, openFactoryFolders));
  5181. if (liveLayout && cat == Category::templates) // round 190iz: Live's Templates: the user's project templates
  5182. {
  5183. if (const auto folder = userTemplatesFolder(); folder.isDirectory())
  5184. {
  5185. auto n = FileTree::makeFolder (folder, tr ("Templates"), rootColour (99));
  5186. n->expanded = true;
  5187. top.push_back (std::move (n));
  5188. }
  5189. }
  5190. else if (liveLayout || allLike || tab == presetsTab || tab == soundsTab)
  5191. for (int i = 0; i < allRoots.size(); ++i)
  5192. {
  5193. if (! showsRoot (i))
  5194. continue;
  5195. if (const auto merged = withMerged ({ allRoots[i] });
  5196. std::all_of (merged.begin(), merged.end(), [this] (const juce::File& f) { return filterHides (f); }))
  5197. continue; // nothing in it is listed under the content filter (round 164)
  5198. // the FL folders keep their colour by position; the user's own folders share one
  5199. auto colour = rootColour (i < 9 ? i : 99);
  5200. auto n = FileTree::makeFolder (allRoots[i], allRootNames[i], colour);
  5201. n->also = mergedInto (allRoots[i]);
  5202. if (allRootKinds[(std::size_t) i] == browserview::RootKind::flMidi)
  5203. n->icon = Icon::note; // (FL's Scores folder has a note)
  5204. if (liveLayout && cat == Category::folder) // (Live's place: its content at once)
  5205. n->expanded = true;
  5206. top.push_back (std::move (n));
  5207. }
  5208. finish();
  5209. // Live's Drums (round 190iz): the sample places searched for drum words, in the results list
  5210. if (liveLayout && cat == Category::drums)
  5211. {
  5212. categoryQuery = browserplaces::drumsQuery();
  5213. runSearch();
  5214. }
  5215. }
  5216. void BrowserComponent::setTab (int newTab)
  5217. {
  5218. newTab = juce::jlimit (0, tabCount - 1, newTab);
  5219. if (liveLayout) // round 190iz: no tabs in the Clip-launch layout: Live's All / Current Project / Favorites instead
  5220. {
  5221. browserplaces::Entry e;
  5222. if (newTab == projectTab)
  5223. e.category = browserplaces::Category::currentProject;
  5224. else if (newTab == starredTab)
  5225. {
  5226. e.group = browserplaces::Group::collections;
  5227. e.category = browserplaces::Category::collection;
  5228. e.collection = 0;
  5229. }
  5230. if (e.category != liveSelection.category || e.collection != liveSelection.collection || ! liveSelection.path.empty())
  5231. showLiveEntry (e);
  5232. return;
  5233. }
  5234. if (newTab == tab)
  5235. return;
  5236. tab = newTab;
  5237. rebuildTree();
  5238. tabs->repaint();
  5239. if (searchBox.getText().isNotEmpty() || tagFilterActive()) // (round 190iz: the tag filter too)
  5240. runSearch();
  5241. savePrefs(); // round 190iz: FL remembers the last tab (LastTabIndex)
  5242. }
  5243. void BrowserComponent::setProjectFile (const juce::File& file)
  5244. {
  5245. if (file == projectFile)
  5246. return;
  5247. projectFile = file;
  5248. rebuildTree(); // the "Project folder" entry follows the project
  5249. }
  5250. // round 190kx: the loop analysis' worker, made on first use
  5251. loopinfo::Shared& BrowserComponent::loopInfoShared()
  5252. {
  5253. if (loopInfo == nullptr)
  5254. {
  5255. loopInfo = loopinfo::Shared::get (engine);
  5256. loopInfo->addChangeListener (this);
  5257. }
  5258. return *loopInfo;
  5259. }
  5260. bool BrowserComponent::showsLoopRowInfo() const { return ! liveLayout && layoutstyle::current() == layoutstyle::Style::simple; }
  5261. void BrowserComponent::loopInfoChanged()
  5262. {
  5263. tree->refreshLoopTexts();
  5264. // the Loop Browser lists again with the new tempos and keys (at most twice a second: its rows are rebuilt)
  5265. if (loopsShown && ! std::exchange (loopFilterAgainAsked, true))
  5266. juce::Timer::callAfterDelay (500, [safe = juce::Component::SafePointer<BrowserComponent> (this)] {
  5267. if (safe == nullptr)
  5268. return;
  5269. safe->loopFilterAgainAsked = false;
  5270. if (safe->loopsShown)
  5271. safe->applyLoopFilter();
  5272. });
  5273. }
  5274. void BrowserComponent::changeListenerCallback (juce::ChangeBroadcaster* source)
  5275. {
  5276. if (loopInfo != nullptr && source == loopInfo.get())
  5277. {
  5278. loopInfoChanged();
  5279. return;
  5280. }
  5281. if (source == &loopLengthsRead())
  5282. {
  5283. loopLengthsArrived();
  5284. return;
  5285. }
  5286. if (source == &searcher->statusChanged)
  5287. {
  5288. indexStatusChanged();
  5289. return;
  5290. }
  5291. if (source == &similar->statusChanged)
  5292. {
  5293. similarStatusChanged();
  5294. return;
  5295. }
  5296. if (source == &searcher->indexChanged)
  5297. {
  5298. applyFilterToTree();
  5299. if (loopsShown) // (round gaps190kf: the loops are listed again, in place)
  5300. {
  5301. runLoopSearch();
  5302. return;
  5303. }
  5304. // the background check found changed folders: the results shown are searched again, in place
  5305. if (resultsView->isVisible() && shownTab() != projectTab && searchBox.getText().trim().isNotEmpty())
  5306. runSearch (true);
  5307. return;
  5308. }
  5309. // round 190ce: the device the Browser is linked to was deleted (or the project replaced): the link ends
  5310. if (swapSession.active())
  5311. {
  5312. if (! swapSession.stillValid (engine.getSong()))
  5313. endHotSwap();
  5314. else
  5315. swapBar->repaint();
  5316. }
  5317. // the project changed: its sections are listed again a moment later (not on every knob step)
  5318. projectDirty = true;
  5319. if (! isTimerRunning())
  5320. startTimer (300);
  5321. }
  5322. void BrowserComponent::addUserFolder()
  5323. {
  5324. chooser = lynx::ui::makeFileChooser (tr ("Add a folder to the Browser"), juce::File::getSpecialLocation (juce::File::userMusicDirectory));
  5325. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories, [this] (const juce::FileChooser& fc) {
  5326. const auto folder = fc.getResult();
  5327. if (! folder.isDirectory())
  5328. return;
  5329. auto lines = juce::StringArray::fromLines (userFoldersFile().loadFileAsString());
  5330. lines.removeEmptyStrings();
  5331. lines.addIfNotAlreadyThere (folder.getFullPathName());
  5332. userFoldersFile().replaceWithText (lines.joinIntoString ("\n"));
  5333. setTab (allTab);
  5334. rebuildRoots();
  5335. });
  5336. }
  5337. int BrowserComponent::addUserFolders (const juce::StringArray& paths)
  5338. {
  5339. std::vector<std::string> dropped;
  5340. juce::StringArray names;
  5341. for (const auto& path : paths)
  5342. if (const juce::File folder (path); folder.isDirectory())
  5343. dropped.push_back (folder.getFullPathName().toStdString());
  5344. if (dropped.empty())
  5345. return 0;
  5346. std::vector<std::string> list;
  5347. for (const auto& line : juce::StringArray::fromLines (userFoldersFile().loadFileAsString()))
  5348. list.push_back (line.toStdString());
  5349. const auto added = userfolders::add (list, dropped, ! juce::File::areFileNamesCaseSensitive());
  5350. if (added.empty())
  5351. {
  5352. showNote (dropped.size() == 1 ? tr ("{0} is in the Browser already", { juce::File (juce::String::fromUTF8 (dropped.front().c_str())).getFileName() })
  5353. : tr ("These folders are in the Browser already"));
  5354. return 0;
  5355. }
  5356. juce::StringArray lines;
  5357. for (const auto& l : list)
  5358. lines.add (juce::String::fromUTF8 (l.c_str()));
  5359. userFoldersFile().getParentDirectory().createDirectory();
  5360. userFoldersFile().replaceWithText (lines.joinIntoString ("\n"));
  5361. setTab (allTab);
  5362. rebuildRoots();
  5363. for (auto* other : liveBrowsers()) // (the other Browsers list the same folders)
  5364. if (other != this)
  5365. other->reloadUserFolders();
  5366. showNote (added.size() == 1 ? tr ("Added {0} to the Browser", { juce::File (juce::String::fromUTF8 (added.front().c_str())).getFileName() })
  5367. : tr ("Added {0} folders to the Browser", { juce::String ((int) added.size()) }));
  5368. return (int) added.size();
  5369. }
  5370. bool BrowserComponent::isInterestedInFileDrag (const juce::StringArray& files)
  5371. {
  5372. return std::any_of (files.begin(), files.end(), [] (const juce::String& f) { return juce::File (f).isDirectory(); });
  5373. }
  5374. void BrowserComponent::fileDragEnter (const juce::StringArray&, int, int)
  5375. {
  5376. folderDragOver = true;
  5377. repaint();
  5378. }
  5379. void BrowserComponent::fileDragExit (const juce::StringArray&)
  5380. {
  5381. folderDragOver = false;
  5382. repaint();
  5383. }
  5384. void BrowserComponent::filesDropped (const juce::StringArray& files, int, int)
  5385. {
  5386. folderDragOver = false;
  5387. repaint();
  5388. addUserFolders (files);
  5389. }
  5390. void BrowserComponent::paintOverChildren (juce::Graphics& g)
  5391. {
  5392. if (! folderDragOver)
  5393. return;
  5394. g.setColour (theme::colour::accent);
  5395. g.drawRect (getLocalBounds(), 2);
  5396. }
  5397. void BrowserComponent::removeUserFolder (const juce::File& folder)
  5398. {
  5399. auto lines = juce::StringArray::fromLines (userFoldersFile().loadFileAsString());
  5400. lines.removeEmptyStrings();
  5401. for (int i = lines.size(); --i >= 0;)
  5402. if (juce::File (lines[i].trim()) == folder)
  5403. lines.remove (i);
  5404. userFoldersFile().replaceWithText (lines.joinIntoString ("\n"));
  5405. if (view.hidden.erase (folder.getFullPathName().toStdString()) > 0) // (a hidden mark of a folder no longer listed)
  5406. saveView();
  5407. rebuildRoots();
  5408. }
  5409. BrowserComponent::~BrowserComponent()
  5410. {
  5411. std::erase (liveBrowsers(), this);
  5412. engine.removeChangeListener (this);
  5413. searcher->statusChanged.removeChangeListener (this);
  5414. searcher->indexChanged.removeChangeListener (this);
  5415. loopLengthsRead().removeChangeListener (this);
  5416. searcher->service->cancelSearch();
  5417. similar->statusChanged.removeChangeListener (this);
  5418. if (similarId != 0)
  5419. similar->service->cancel();
  5420. if (loopInfo != nullptr)
  5421. loopInfo->removeChangeListener (this);
  5422. focusWatcher.reset();
  5423. engine.previewFile ({});
  5424. midiPreview.reset(); // (round 190qi: its sounding notes end)
  5425. if (searchKeys != nullptr)
  5426. searchBox.removeKeyListener (searchKeys.get());
  5427. if (searchGhost != nullptr)
  5428. searchBox.removeChildComponent (searchGhost.get());
  5429. }
  5430. void BrowserComponent::waitForListing (int)
  5431. {
  5432. // the tree lists folders synchronously when they open
  5433. }
  5434. void BrowserComponent::resized()
  5435. {
  5436. auto area = getLocalBounds().reduced (4);
  5437. if (swapBar->isVisible()) // round 190ce: the hot-swap bar over the tabs
  5438. {
  5439. swapBar->setBounds (area.removeFromTop (HotSwapBar::height));
  5440. area.removeFromTop (3);
  5441. }
  5442. // round 190iz: FL's six icon tabs (Pattern / Simple layouts); the Clip-launch layout has Live's sidebar instead
  5443. tabs->setVisible (! liveLayout);
  5444. if (! liveLayout)
  5445. {
  5446. tabs->setBounds (area.removeFromTop (TabBar::preferredHeight));
  5447. area.removeFromTop (2);
  5448. }
  5449. {
  5450. auto row = area.removeFromTop (24);
  5451. viewButton.setBounds (row.removeFromRight (22));
  5452. row.removeFromRight (4);
  5453. tagsButton->setBounds (row.removeFromRight (TagsButton::width)); // (FL's TAGS button in the search row)
  5454. row.removeFromRight (4);
  5455. if (loopsButton->isVisible()) // (round gaps190kf: the Sample browser window's LOOPS)
  5456. {
  5457. loopsButton->setBounds (row.removeFromRight (LoopsButton::width));
  5458. row.removeFromRight (4);
  5459. }
  5460. searchBox.setBounds (row);
  5461. }
  5462. // indexing progress / what the search found (round 162)
  5463. statusArea = statusLine.isNotEmpty() ? area.removeFromTop (16).withTrimmedLeft (2) : juce::Rectangle<int>();
  5464. area.removeFromTop (4);
  5465. strip->setBounds (getLocalBounds().removeFromBottom (juce::jmin (64, getHeight() / 4)));
  5466. area.setBottom (strip->getY() - 2);
  5467. // FL's details box (date, size / version, folder) just above the preview strip, while something is selected
  5468. details->setVisible (details->hasFile() && area.getHeight() > 120);
  5469. if (details->isVisible())
  5470. details->setBounds (area.removeFromBottom (DetailsBox::preferredHeight).withX (0).withWidth (getWidth()));
  5471. // Live's two panes: the sidebar (about a third, 84-120 px) beside the content, whose top holds the tag chips and
  5472. // the "Name" column title
  5473. sidebarView->setVisible (liveLayout);
  5474. if (liveLayout)
  5475. {
  5476. // (round 190oj: at the default 258 px browser a third was 84 px and the English names were cut — "Instrume...",
  5477. // "Audio Eff...", "User Libr..."; Live's sidebar is ~100 px with a smaller face: 40 %, at least 100 px, and the
  5478. // names shrink a little before they are cut, in LiveSidebar::paint)
  5479. const auto sideWidth = juce::jlimit (juce::jmin (100, area.getWidth() / 2), 132, area.getWidth() * 2 / 5);
  5480. sidebarView->setBounds (area.removeFromLeft (sideWidth));
  5481. sidebar->setSize (sideWidth - (sidebar->getHeight() > sidebarView->getHeight() ? 8 : 0), sidebar->getHeight());
  5482. area.removeFromLeft (1);
  5483. }
  5484. tagsPanel->setVisible (tagsPanelShown);
  5485. if (tagsPanelShown)
  5486. tagsPanel->setBounds (area.removeFromTop (tagsPanel->heightFor (area.getWidth())));
  5487. loopPanel->setVisible (loopsShown);
  5488. if (loopsShown) // (round gaps190kf: the grid takes at most about half the height; its rows scroll past that)
  5489. loopPanel->setBounds (area.removeFromTop (loopPanel->heightFor (area.getWidth(), juce::jmax (140, area.getHeight() / 2 + 40))));
  5490. nameHeader = liveLayout ? area.removeFromTop (18) : juce::Rectangle<int>();
  5491. treeView->setBounds (area);
  5492. resultsView->setBounds (area);
  5493. for (auto* list : { tree.get(), results.get() })
  5494. {
  5495. list->setLiveRows (liveLayout);
  5496. list->setSize (area.getWidth() - 10, list->getHeight());
  5497. list->updateSize();
  5498. }
  5499. }
  5500. void BrowserComponent::refreshPreviewVolume()
  5501. {
  5502. previewVolume.setValue (engine.getPreviewVolume(), juce::dontSendNotification);
  5503. const auto text = tr ("Sample preview volume: {0}", { ui::utilityVolumeText (engine.getPreviewVolume()) });
  5504. previewVolume.setTooltip (text);
  5505. ui::setHint (previewVolume, text + " " + tr ("[LMB] drag [Wheel] step [2xLMB] 100% [RMB] type a value"), true);
  5506. }
  5507. void BrowserComponent::paint (juce::Graphics& g)
  5508. {
  5509. const uitrace::Scope trace ("BrowserComponent paint", true, g.getClipBounds());
  5510. g.fillAll (theme::colour::bg2);
  5511. if (auto header = nameHeader; ! header.isEmpty()) // round 190iz: Live's list title ("Name")
  5512. {
  5513. g.setColour (theme::colour::bg3);
  5514. g.fillRect (header);
  5515. g.setColour (theme::colour::border);
  5516. g.fillRect (header.removeFromBottom (1));
  5517. g.setFont (theme::font (theme::type::caption, true));
  5518. g.setColour (theme::colour::textSecondary);
  5519. g.drawText (tr ("Name"), header.withTrimmedLeft (8), juce::Justification::centredLeft, false);
  5520. }
  5521. if (! statusArea.isEmpty())
  5522. {
  5523. g.setFont (theme::font (theme::type::caption));
  5524. g.setColour (theme::colour::textSecondary); // (round 190oo PAT-13: textDisabled read too dim)
  5525. g.drawText (statusLine, statusArea, juce::Justification::centredLeft, true);
  5526. }
  5527. }
  5528. void BrowserComponent::showPreviewForSnapshot (const juce::File& file)
  5529. {
  5530. strip->show (file, false);
  5531. }
  5532. void BrowserComponent::fileSelected (const juce::File& file, bool preview)
  5533. {
  5534. // round 190iz: what was asked for this preview (Shift+Click / Alt+Click / Play), then plain again
  5535. const auto startFraction = std::exchange (previewStartAsked, 0.0);
  5536. const auto full = std::exchange (previewFullAsked, false);
  5537. preview = previewWanted (preview); // (round 190ce: the automatic preview can be switched off)
  5538. if (details != nullptr && file != juce::File())
  5539. {
  5540. const auto wasVisible = details->hasFile();
  5541. details->show (file);
  5542. if (! wasVisible)
  5543. resized();
  5544. }
  5545. // round 190qi: a MIDI file plays on the selected channel at the project's tempo (core/MidiPreview.h); any other
  5546. // preview ends it
  5547. if (preview || isMidiFile190qi (file))
  5548. stopMidiPreview();
  5549. if (isMidiFile190qi (file))
  5550. {
  5551. if (preview && file.existsAsFile())
  5552. {
  5553. engine.previewFile ({}); // (the sample preview stops, as one preview replaces another)
  5554. startMidiPreview (file);
  5555. }
  5556. strip->show (file, preview);
  5557. tree->repaint();
  5558. results->repaint();
  5559. return;
  5560. }
  5561. if (preview && file.hasFileExtension ("sf2;sf3;sfz") && file.existsAsFile())
  5562. {
  5563. int bank = 0, program = 0;
  5564. if (firstSoundFontPreset (file.getFullPathName().toStdString(), bank, program))
  5565. previewSoundFontPreset (engine, file.getFullPathName().toStdString(), bank, program);
  5566. return;
  5567. }
  5568. if (! isAudio (file))
  5569. return;
  5570. if (preview && file.existsAsFile())
  5571. {
  5572. engine.previewFile (file, startFraction, full); // (round 190iz: FL's 5 seconds unless full)
  5573. previewedFile = file;
  5574. }
  5575. strip->show (file, preview, startFraction, full);
  5576. tree->repaint();
  5577. results->repaint();
  5578. }
  5579. // FL's Browser menus (REA round 143b, [EXEC] FL 2026: right-click on a sample, a folder, a plugin): the file's actions
  5580. // first, then a "System" section (open the parent folder, locate the file, delete it) and a "Tags" section (Favorite);
  5581. // a folder: Expand all / Collapse all, then System (Open). LYNX keeps its own "Add folder..." and "Refresh".
  5582. // Round 163 (user feedback: "this sort of UI has a ton of wasted space"): no "System" / "Tags" titles any more; the
  5583. // rarely used system actions sit in one "File" sub-menu, Starred stays one click away.
  5584. void BrowserComponent::addSystemItems (juce::PopupMenu& menu, const juce::File& file)
  5585. {
  5586. menu.addSeparator();
  5587. menu.addItem (tr ("Starred"), true, isStarred (file), [this, file] { setStarred (file, ! isStarred (file)); });
  5588. addCollectionItems (menu, file.getFullPathName().toStdString());
  5589. if (resultsView->isVisible() && shownTab() != projectTab) // round 190ce: from a search result to its place in the folders
  5590. menu.addItem (tr ("Show in its folder"), [safe = juce::Component::SafePointer<BrowserComponent> (this), file] {
  5591. if (safe == nullptr)
  5592. return;
  5593. safe->searchBox.setText ({}, false);
  5594. safe->runSearch();
  5595. if (safe->liveLayout) // (round 190iz: Live's All shows every place)
  5596. safe->showLiveEntry ({});
  5597. else
  5598. safe->setTab (allTab);
  5599. if (const auto row = safe->tree->revealFile (file); row >= 0)
  5600. safe->tree->select (row, false);
  5601. else
  5602. safe->showNote (tr ("This file is not in a folder the Browser shows"));
  5603. });
  5604. juce::PopupMenu system;
  5605. system.addItem (tr ("Open parent folder"), [file] { file.getParentDirectory().startAsProcess(); });
  5606. system.addItem (tr ("Locate file"), [file] { file.revealToUser(); });
  5607. system.addItem (tr ("Copy the file path"), [file] { juce::SystemClipboard::copyTextToClipboard (file.getFullPathName()); });
  5608. system.addSeparator();
  5609. system.addItem (tr ("Delete file..."), file.existsAsFile(), false, [this, file] { confirmDeleteFile (file); });
  5610. menu.addSubMenu (tr ("File"), system);
  5611. }
  5612. void BrowserComponent::showNote (const juce::String& text)
  5613. {
  5614. const auto relayout = text.isEmpty() != statusLine.isEmpty();
  5615. statusLine = text;
  5616. if (relayout)
  5617. resized();
  5618. repaint();
  5619. // it goes away by itself (unless something else wrote there meanwhile)
  5620. juce::Timer::callAfterDelay (5000, [safe = juce::Component::SafePointer<BrowserComponent> (this), text] {
  5621. if (safe != nullptr && safe->statusLine == text)
  5622. safe->showNote ({});
  5623. });
  5624. }
  5625. void BrowserComponent::confirmDeleteFile (const juce::File& file)
  5626. {
  5627. juce::Component::SafePointer<BrowserComponent> safe (this);
  5628. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::WarningIcon, tr ("Delete file"),
  5629. tr ("Move \"{0}\" to the recycle bin?", { file.getFileName() }), tr ("Delete"), tr ("Cancel"), nullptr,
  5630. juce::ModalCallbackFunction::create ([safe, file] (int result) {
  5631. if (result == 0 || safe == nullptr)
  5632. return;
  5633. if (! file.moveToTrash())
  5634. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Delete file"),
  5635. tr ("The file could not be deleted."));
  5636. safe->rebuildRoots();
  5637. }));
  5638. }
  5639. void BrowserComponent::showFileMenu (const juce::File& file)
  5640. {
  5641. buildFileMenu (file).showMenuAsync (juce::PopupMenu::Options().withMousePosition()); // (round 190iz: built apart for --shots)
  5642. }
  5643. juce::PopupMenu BrowserComponent::buildFileMenu (const juce::File& file)
  5644. {
  5645. juce::PopupMenu menu;
  5646. menu.addSectionHeader (file.getFileName());
  5647. if (isAudio (file))
  5648. {
  5649. // FL's first item (REA round 143 B3; round 190iz: FL's own words and its focused-plugin rule, core/BrowserSend.h)
  5650. menu.addItem (tr ("Send to selected channel or focused plugin"), [this, file] { sendToSelected (file); });
  5651. menu.addItem (tr ("Open in a new channel"), [this, file] { openFile (file); });
  5652. menu.addSeparator();
  5653. menu.addItem (tr ("Send to the Playlist as an audio clip"), onSendToPlaylist != nullptr, false, [this, file] { onSendToPlaylist (file); });
  5654. menu.addSeparator();
  5655. menu.addItem (tr ("Edit in the audio editor..."), [this, file] { openAudioEditor (engine, file); });
  5656. // FL's Sounds tab menu: "Open/Edit in...", then "Find similar samples" (FL asks FL Cloud; LYNX looks through
  5657. // the Browser's own folders, round 190as)
  5658. if (! file.hasFileExtension ("speech"))
  5659. menu.addItem (tr ("Find similar samples"), [this, file] { findSimilar (file); });
  5660. }
  5661. else if (file.hasFileExtension ("lynx;flp;als;flm"))
  5662. menu.addItem (tr ("Open project"), onOpenProject != nullptr, false, [this, file] { onOpenProject (file); });
  5663. else if (file.hasFileExtension ("mid;midi"))
  5664. menu.addItem (tr ("Open MIDI file"), onOpenProject != nullptr, false, [this, file] { onOpenProject (file); });
  5665. else if (file.hasFileExtension ("fst;gmsynth") || genpresetui::isPresetFile (file))
  5666. {
  5667. if (pluginpresetui::isFlPresetOfPlugin (file)) // round 190iz: an FL preset of a hosted plugin
  5668. menu.addItem (tr ("Send to selected channel or focused plugin"), [this, file] { sendToSelected (file); });
  5669. menu.addItem (tr ("Open in a new channel"), [this, file] { openFile (file); });
  5670. }
  5671. else if (pluginpresetui::isPresetFile (file)) // round 190iz: a hosted plugin's preset (.lynxpreset, .fxp, .vstpreset)
  5672. menu.addItem (tr ("Send to selected channel or focused plugin"), [this, file] { sendToSelected (file); });
  5673. else if (file.hasFileExtension ("sf2;sf3;sfz"))
  5674. {
  5675. const auto selected = engine.getSelectedChannel();
  5676. const auto& song = engine.getSong();
  5677. const auto selectedIsFont = selected >= 0 && selected < (int) song.channels.size()
  5678. && song.channels[(std::size_t) selected].instrument == InstrumentKind::soundfont;
  5679. menu.addItem (tr ("Open in a new channel"), [this, file] { openSoundFontFile (engine, file); });
  5680. menu.addItem (tr ("Send to the selected channel"), selectedIsFont, false, [this, file, selected] { openSoundFontFile (engine, file, selected); });
  5681. }
  5682. else if (isSamplerInstrumentFile (file))
  5683. {
  5684. const auto selected = engine.getSelectedChannel();
  5685. const auto& song = engine.getSong();
  5686. const auto selectedIsDw = selected >= 0 && selected < (int) song.channels.size()
  5687. && song.channels[(std::size_t) selected].instrument == InstrumentKind::directwave;
  5688. menu.addItem (tr ("Open in a new channel"), [this, file] { openSamplerInstrumentFile (engine, file); });
  5689. menu.addItem (tr ("Send to the selected channel"), selectedIsDw, false, [this, file, selected] { openSamplerInstrumentFile (engine, file, selected); });
  5690. }
  5691. addSystemItems (menu, file);
  5692. menu.addItem (tr ("Collapse all folders"), [this] { tree->collapseAll(); });
  5693. juce::PopupMenu browserMenu;
  5694. addViewItems (browserMenu);
  5695. menu.addSubMenu (tr ("Browser"), browserMenu);
  5696. return menu;
  5697. }
  5698. void BrowserComponent::showFolderMenu (const juce::File& folder, std::function<void()> expandAll)
  5699. {
  5700. // compact (round 163): the folder's name as the only title, its actions, then the Browser's own options
  5701. juce::PopupMenu menu;
  5702. menu.addSectionHeader (folder.getFileName());
  5703. menu.addItem (tr ("Expand all"), expandAll != nullptr, false, [expandAll] { expandAll(); });
  5704. menu.addItem (tr ("Collapse all"), [this] { tree->collapseAll(); });
  5705. menu.addItem (tr ("Starred"), folder.isDirectory(), isStarred (folder), [this, folder] { setStarred (folder, ! isStarred (folder)); });
  5706. if (folder.isDirectory())
  5707. addCollectionItems (menu, folder.getFullPathName().toStdString());
  5708. menu.addItem (tr ("Open in the file manager"), [folder] { folder.startAsProcess(); });
  5709. menu.addItem (tr ("Copy the file path"), [folder] { juce::SystemClipboard::copyTextToClipboard (folder.getFullPathName()); });
  5710. menu.addSeparator();
  5711. if (const auto id = rootId (folder); id.isNotEmpty() && shownTab() == allTab)
  5712. {
  5713. addHideItem (menu, id, allRootNames[allRoots.indexOf (folder)]);
  5714. if (allRootKinds[(std::size_t) allRoots.indexOf (folder)] == browserview::RootKind::user)
  5715. menu.addItem (tr ("Remove this folder from the Browsers"), [safe = juce::Component::SafePointer<BrowserComponent> (this), folder] {
  5716. if (safe != nullptr)
  5717. safe->removeUserFolder (folder);
  5718. });
  5719. if (const auto merged = rootAlso.find (folder.getFullPathName()); merged != rootAlso.end())
  5720. {
  5721. // a LYNX extra (FL has no exclusion; round 178a): the folders this root merges, each one ticked in or out;
  5722. // the root's own folder stays (Hide... hides the root)
  5723. juce::PopupMenu folders;
  5724. folders.addItem (folder.getFullPathName(), false, true, nullptr);
  5725. for (const auto& f : merged->second)
  5726. {
  5727. const auto path = f.getFullPathName().toStdString();
  5728. folders.addItem (f.getFullPathName(), true, view.excluded.count (path) == 0,
  5729. [safe = juce::Component::SafePointer<BrowserComponent> (this), path] {
  5730. if (safe == nullptr)
  5731. return;
  5732. if (safe->view.excluded.erase (path) == 0)
  5733. safe->view.excluded.insert (path);
  5734. safe->saveView();
  5735. safe->rebuildRoots();
  5736. safe->searcher->service->refresh (toPaths (safe->withMerged (safe->allRoots)));
  5737. if (safe->searchBox.getText().trim().isNotEmpty())
  5738. safe->runSearch();
  5739. });
  5740. }
  5741. menu.addSubMenu (tr ("Folders"), folders);
  5742. }
  5743. }
  5744. juce::PopupMenu browserMenu;
  5745. addViewItems (browserMenu);
  5746. browserMenu.addSeparator();
  5747. browserMenu.addItem (tr ("Refresh"), [this] { rebuildRoots(); });
  5748. browserMenu.addItem (tr ("Refresh search index"), [this] { refreshSearchIndex (false); });
  5749. menu.addSubMenu (tr ("Browser"), browserMenu);
  5750. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  5751. }
  5752. BrowserComponent::FileTree& BrowserComponent::activeList() const
  5753. {
  5754. return resultsView->isVisible() ? *results : *tree;
  5755. }
  5756. // --- search ------------------------------------------------------------------------------------------
  5757. void BrowserComponent::focusSearch()
  5758. {
  5759. searchBox.grabKeyboardFocus();
  5760. searchBox.selectAll();
  5761. }
  5762. juce::Array<juce::File> BrowserComponent::searchRoots() const
  5763. {
  5764. // the top-level folder holding the selection; nothing selected there: every folder
  5765. if (const auto root = tree->selectedRoot(); root.isDirectory())
  5766. return withMerged ({ root });
  5767. if (liveLayout && liveSelection.category == browserplaces::Category::collection) // round 190iz: Live's collection
  5768. {
  5769. juce::Array<juce::File> folders;
  5770. for (const auto& item : collectionStore().itemsOf (liveSelection.collection))
  5771. if (const juce::File f (juce::String::fromUTF8 (item.c_str())); ! collections::isPluginItem (item) && f.isDirectory())
  5772. folders.addIfNotAlreadyThere (f);
  5773. return folders;
  5774. }
  5775. if (liveLayout || tab == presetsTab || tab == soundsTab) // round 190iz: the places the tab / Live entry lists
  5776. {
  5777. juce::Array<juce::File> shown;
  5778. for (int i = 0; i < allRoots.size(); ++i)
  5779. if (showsRoot (i))
  5780. shown.add (allRoots[i]);
  5781. if (liveLayout && liveSelection.category == browserplaces::Category::templates)
  5782. shown.add (userTemplatesFolder());
  5783. return withMerged (shown);
  5784. }
  5785. if (tab == starredTab) // the folders of the collections shown
  5786. {
  5787. juce::Array<juce::File> folders;
  5788. for (const auto c : collectionStore().shown())
  5789. for (const auto& item : collectionStore().itemsOf (c))
  5790. if (const juce::File f (juce::String::fromUTF8 (item.c_str())); ! collections::isPluginItem (item) && f.isDirectory())
  5791. folders.addIfNotAlreadyThere (f);
  5792. return folders;
  5793. }
  5794. return withMerged (roots);
  5795. }
  5796. juce::Array<juce::File> BrowserComponent::mergedInto (const juce::File& root) const
  5797. {
  5798. const auto it = rootAlso.find (root.getFullPathName());
  5799. if (it == rootAlso.end())
  5800. return {};
  5801. auto folders = it->second; // (less the folders this view leaves out: a hidden "FL MIDI" before round 178a)
  5802. folders.removeIf ([this] (const juce::File& f) { return view.excluded.count (f.getFullPathName().toStdString()) > 0; });
  5803. return folders;
  5804. }
  5805. juce::Array<juce::File> BrowserComponent::withMerged (const juce::Array<juce::File>& folders) const
  5806. {
  5807. auto out = folders;
  5808. for (const auto& f : folders)
  5809. out.addArray (mergedInto (f));
  5810. return out;
  5811. }
  5812. void BrowserComponent::setSearchForSnapshot (const juce::String& text)
  5813. {
  5814. // synchronous: the snapshot is drawn before any message is dispatched
  5815. searchBox.setText (text, juce::dontSendNotification);
  5816. searcher->service->cancelSearch();
  5817. resultsView->setVisible (text.isNotEmpty());
  5818. treeView->setVisible (text.isEmpty());
  5819. if (text.isEmpty() || roots.isEmpty())
  5820. return;
  5821. const juce::Array<juce::File> scope { roots[0] }; // the FL samples: the same results on every machine with FL
  5822. auto answer = std::make_shared<std::pair<std::mutex, search::SearchResult>>();
  5823. searcher->service->search (text.toStdString(), toPaths (scope), (std::size_t) maxResults, [answer] (const search::SearchResult& r) {
  5824. const std::lock_guard<std::mutex> guard (answer->first);
  5825. answer->second = r;
  5826. });
  5827. searcher->service->waitIdle (120000);
  5828. auto found = collectionMatches (text); // (round 190ce: as searchAnswered, the collections' names first)
  5829. {
  5830. const std::lock_guard<std::mutex> guard (answer->first);
  5831. for (const auto& path : answer->second.paths)
  5832. found.addIfNotAlreadyThere (juce::File (juce::String::fromUTF8 (path.c_str())));
  5833. }
  5834. results->setFiles (found, scope, found.isEmpty() ? tr ("Nothing found for \"{0}\".", { text }) : juce::String());
  5835. if (! found.isEmpty())
  5836. results->select (0, false);
  5837. }
  5838. void BrowserComponent::selectFirstSampleForSnapshot()
  5839. {
  5840. if (const auto row = tree->firstAudioRow(); row >= 0)
  5841. {
  5842. tree->select (row, false);
  5843. strip->show (tree->selectedFile(), false);
  5844. tree->setHovered (row + 1 < tree->numRows() ? row + 1 : -1);
  5845. }
  5846. }
  5847. void BrowserComponent::showFilterForSnapshot (const juce::File& folder, browserview::ContentFilter filter)
  5848. {
  5849. // a folder of the user's (not saved) listed under `filter` once the index knows it (nothing saved either)
  5850. if (! allRoots.contains (folder))
  5851. {
  5852. allRoots.add (folder);
  5853. allRootNames.add (folder.getFileName());
  5854. allRootKinds.push_back (browserview::RootKind::user);
  5855. }
  5856. roots.clear();
  5857. roots.add (folder);
  5858. view.filter = filter;
  5859. view.setShown (browserview::projectRootId, false);
  5860. view.setShown (browserview::pluginsRootId, false);
  5861. searcher->service->refresh (toPaths ({ folder }));
  5862. searcher->service->waitIdle (60000);
  5863. prunedGeneration = 0;
  5864. setTab (allTab);
  5865. rebuildTree();
  5866. tree->expandTop (folder, 3);
  5867. refreshViewButton();
  5868. }
  5869. void BrowserComponent::resetViewForSnapshot()
  5870. {
  5871. viewLoaded = false; // (read again: the snapshot's changes were never saved)
  5872. prunedGeneration = 0;
  5873. rebuildRoots();
  5874. }
  5875. std::vector<juce::PopupMenu> BrowserComponent::pluginDatabaseMenusForSnapshot()
  5876. {
  5877. // a folder of the user's (else Effects / Generators) and the first plugin entry shown, as a right-click opens them
  5878. showPluginDatabaseForSnapshot();
  5879. std::vector<juce::PopupMenu> out;
  5880. out.push_back (tree->menuForSnapshot (tree->firstRowOfKind (false)));
  5881. out.push_back (tree->menuForSnapshot (tree->firstRowOfKind (true)));
  5882. return out;
  5883. }
  5884. void BrowserComponent::showPluginDatabaseForSnapshot()
  5885. {
  5886. openPluginFolders = { tr ("Plugin database"), tr ("Plugin database") + "/" + tr ("Generators"), tr ("Generators") + "/" + tr ("FL engines"),
  5887. tr ("Plugin database") + "/" + tr ("Effects"), tr ("Effects") + "/" + tr ("FL engines") };
  5888. setTab (allTab);
  5889. rebuildTree();
  5890. }
  5891. void BrowserComponent::showJsfxForSnapshot()
  5892. {
  5893. openPluginFolders = { tr ("Plugin database"), tr ("Plugin database") + "/" + tr ("Generators"), tr ("Generators") + "/JSFX",
  5894. tr ("Plugin database") + "/" + tr ("Effects"), tr ("Effects") + "/JSFX" };
  5895. setTab (allTab);
  5896. rebuildTree();
  5897. }
  5898. void BrowserComponent::showPluginDatabase (const juce::String& folder, int generators)
  5899. {
  5900. const auto db = tr ("Plugin database");
  5901. openPluginFolders.insert (db);
  5902. openPluginFolders.insert (db + "/" + tr ("Generators"));
  5903. openPluginFolders.insert (db + "/" + tr ("Effects"));
  5904. // the Plugin picker's tab clicked (round 171c, FL opens its Browser on that category): that folder of the user's,
  5905. // else the Generators / Effects heading
  5906. const auto kind = generators > 0 ? tr ("Generators") : tr ("Effects");
  5907. if (generators >= 0 && folder.isNotEmpty())
  5908. openPluginFolders.insert (kind + "/" + folder);
  5909. setTab (allTab);
  5910. rebuildTree();
  5911. auto row = generators >= 0 && folder.isNotEmpty() ? tree->rowLabelled (folder) : -1;
  5912. if (row < 0)
  5913. row = tree->rowLabelled (generators >= 0 ? kind : db);
  5914. if (row >= 0)
  5915. {
  5916. tree->select (row, false);
  5917. tree->grabKeyboardFocus();
  5918. }
  5919. }
  5920. bool BrowserComponent::locateFile (const juce::File& file)
  5921. {
  5922. if (searchBox.getText().isNotEmpty())
  5923. {
  5924. searchBox.setText ({}, false);
  5925. runSearch();
  5926. }
  5927. if (liveLayout) // (round 190iz: Live's All shows every place)
  5928. showLiveEntry ({});
  5929. else
  5930. setTab (allTab);
  5931. if (const auto row = tree->revealFile (file); row >= 0)
  5932. {
  5933. tree->select (row, false);
  5934. tree->grabKeyboardFocus();
  5935. return true;
  5936. }
  5937. showNote (tr ("This file is not in a folder the Browser shows"));
  5938. return false;
  5939. }
  5940. juce::Rectangle<int> BrowserComponent::selectedRowScreenBounds() const
  5941. {
  5942. if (tree == nullptr || ! tree->isShowing() || tree->getSelectedRow() < 0)
  5943. return {};
  5944. const auto row = tree->getSelectedRow();
  5945. return tree->localAreaToGlobal (juce::Rectangle<int> (0, row * tree->rowHeight, tree->getWidth(), tree->rowHeight));
  5946. }
  5947. void BrowserComponent::showScores (const juce::String& subfolder)
  5948. {
  5949. // the Piano roll's File › Browse scores (round 168g; FL: FUN_0123a580 opens its browser at the Scores folder): the
  5950. // "Scores" root shown, opened and selected. With a subfolder (the Event editor's File › Browse automations: FL
  5951. // opens Scores\\Automation, the user's when there is one; REA round 178a) that folder's row is selected
  5952. for (int i = 0; i < allRoots.size(); ++i)
  5953. if (i < (int) allRootKinds.size() && allRootKinds[(std::size_t) i] == browserview::RootKind::flMidi)
  5954. {
  5955. const auto folder = allRoots[i];
  5956. if (const auto id = rootId (folder); id.isNotEmpty())
  5957. setRootShown (id, true);
  5958. setTab (allTab);
  5959. rebuildTree();
  5960. tree->expandTop (folder, 1);
  5961. int row = -1;
  5962. if (subfolder.isNotEmpty())
  5963. for (const auto& f : withMerged ({ folder })) // (the merged row is the first folder's that has it)
  5964. if (row < 0)
  5965. row = tree->rowOfFile (f.getChildFile (subfolder));
  5966. if (row < 0)
  5967. row = tree->rowLabelled (allRootNames[i]);
  5968. if (row >= 0)
  5969. {
  5970. tree->select (row, false);
  5971. tree->grabKeyboardFocus();
  5972. }
  5973. return;
  5974. }
  5975. showNote (tr ("FL Studio's scores were not found (FL Studio is not installed)"));
  5976. }
  5977. void BrowserComponent::showFactoryContentForSnapshot (const juce::StringArray& openFolders)
  5978. {
  5979. openFactoryFolders.clear();
  5980. for (const auto& f : openFolders)
  5981. openFactoryFolders.insert (f);
  5982. rebuildTree();
  5983. }
  5984. juce::StringArray BrowserComponent::rowLabelsForCheck() const { return tree->rowLabels(); }
  5985. // round 190kx (--loopinfo190kxshot): waits for the loop analysis of what is listed, then fills the rows / Loop Browser
  5986. bool BrowserComponent::waitLoopInfoForSnapshot (int timeoutMs)
  5987. {
  5988. if (loopInfo == nullptr)
  5989. return true;
  5990. const auto idle = loopInfo->service().waitIdle (timeoutMs);
  5991. tree->refreshLoopTexts();
  5992. if (loopsShown)
  5993. applyLoopFilter();
  5994. return idle;
  5995. }
  5996. std::size_t BrowserComponent::loopInfoQueuedForCheck() { return loopInfo != nullptr ? loopInfo->service().queued() : 0; }
  5997. juce::StringArray BrowserComponent::loopRowTextsForCheck() const
  5998. {
  5999. juce::StringArray out;
  6000. for (int i = 0; i < tree->numRows(); ++i)
  6001. if (const auto* n = tree->nodeAt (i); n != nullptr && n->loopText.isNotEmpty())
  6002. out.add (n->file.getFileNameWithoutExtension() + ": " + n->loopText);
  6003. return out;
  6004. }
  6005. juce::StringArray BrowserComponent::resultLabelsForCheck() const { return results->rowLabels(); }
  6006. // FL's General › Undo history › "Show undo history in the browser when undoing changes" (round 190mr, DF-135): the
  6007. // Browser's Current project › History opens, its header scrolled into view
  6008. void BrowserComponent::showHistory()
  6009. {
  6010. setTab (projectTab);
  6011. tree->openProjectSections ({ Category::history });
  6012. tree->scrollRowIntoView (tree->categoryRow (Category::history));
  6013. }
  6014. bool BrowserComponent::historyShownForCheck() const
  6015. {
  6016. return shownTab() == projectTab && tree->categoryOpen (Category::history);
  6017. }
  6018. bool BrowserComponent::revealProjectParameters (bool effect, int index, int slot)
  6019. {
  6020. setTab (projectTab);
  6021. return tree->revealParameters (effect, index, slot) >= 0;
  6022. }
  6023. bool BrowserComponent::revealProjectPattern (int pattern)
  6024. {
  6025. setTab (projectTab);
  6026. return tree->revealPattern (pattern) >= 0;
  6027. }
  6028. void BrowserComponent::showProjectForSnapshot()
  6029. {
  6030. setTab (projectTab);
  6031. if (const auto row = tree->openProjectSections ({ Category::patterns, Category::generators, Category::samples }); row >= 0)
  6032. {
  6033. tree->select (row, false);
  6034. strip->show (tree->selectedFile(), false);
  6035. tree->setHovered (row + 1 < tree->numRows() ? row + 1 : -1);
  6036. }
  6037. }
  6038. void BrowserComponent::textEditorTextChanged (juce::TextEditor&)
  6039. {
  6040. searchPending = true;
  6041. startTimer (250); // search once typing pauses
  6042. updateSearchSuggestion(); // (round 190qi)
  6043. }
  6044. void BrowserComponent::textEditorFocusLost (juce::TextEditor&)
  6045. {
  6046. searchSuggestion.clear(); // (round 190qi: the greyed completion shows only while typing)
  6047. if (searchGhost != nullptr)
  6048. searchGhost->setRest ({});
  6049. }
  6050. void BrowserComponent::textEditorEscapeKeyPressed (juce::TextEditor&)
  6051. {
  6052. // Esc: clears the search and gives the keyboard back (Space plays again)
  6053. searchPending = false;
  6054. searchBox.clear();
  6055. runSearch();
  6056. leaveSearchBox();
  6057. }
  6058. void BrowserComponent::textEditorReturnKeyPressed (juce::TextEditor&)
  6059. {
  6060. // Enter: searches now and leaves the box, so Up / Down step through the results (and Space plays)
  6061. searchPending = false;
  6062. runSearch();
  6063. leaveSearchBox();
  6064. }
  6065. bool BrowserComponent::isTypingInSearch() const
  6066. {
  6067. return searchBox.hasKeyboardFocus (true);
  6068. }
  6069. void BrowserComponent::leaveSearchBox()
  6070. {
  6071. if (! isTypingInSearch())
  6072. return;
  6073. // the window's first ancestor that takes keys (the main window's content: the shortcuts, the transport) gets them
  6074. for (auto* p = getParentComponent(); p != nullptr; p = p->getParentComponent())
  6075. if (p->getWantsKeyboardFocus() && p->isShowing())
  6076. {
  6077. p->grabKeyboardFocus();
  6078. if (! isTypingInSearch())
  6079. return;
  6080. }
  6081. searchBox.giveAwayKeyboardFocus();
  6082. }
  6083. void BrowserComponent::timerCallback()
  6084. {
  6085. stopTimer();
  6086. if (std::exchange (searchPending, false))
  6087. runSearch();
  6088. if (std::exchange (projectDirty, false))
  6089. {
  6090. tree->refreshProject();
  6091. if (shownTab() == projectTab && resultsView->isVisible())
  6092. runSearch();
  6093. }
  6094. }
  6095. void BrowserComponent::runSearch (bool quiet)
  6096. {
  6097. searcher->service->cancelSearch();
  6098. searchId = 0;
  6099. if (similarTo != juce::File())
  6100. {
  6101. // similar samples are listed while the box still says so; any other text is an ordinary search again
  6102. if (shownTab() != projectTab && searchBox.getText() == similarLabel())
  6103. {
  6104. runSimilar (quiet);
  6105. return;
  6106. }
  6107. similarTo = juce::File();
  6108. similarPartial = false;
  6109. if (std::exchange (similarId, 0) != 0)
  6110. similar->service->cancel();
  6111. }
  6112. if (loopsShown) // round gaps190kf: the Loop Browser's list (the box's text narrows it by name)
  6113. {
  6114. if (loopInfos.empty() && ! loopsAnswer)
  6115. runLoopSearch();
  6116. else
  6117. applyLoopFilter();
  6118. return;
  6119. }
  6120. if (tagFilterActive()) // round 190iz: tags picked in the tags panel, or "#tag" in the box
  6121. {
  6122. runTagFilter();
  6123. return;
  6124. }
  6125. const auto query = effectiveQuery(); // (round 190iz: Live's Drums searches when the box is empty)
  6126. resultsView->setVisible (query.isNotEmpty());
  6127. treeView->setVisible (query.isEmpty());
  6128. if (query.isEmpty())
  6129. {
  6130. searchPartial = false;
  6131. indexStatusChanged();
  6132. return;
  6133. }
  6134. if (shownTab() == projectTab) // the project's own items, at once
  6135. {
  6136. auto found = FileTree::projectMatches (engine.getSong(), query);
  6137. const auto none = found.empty();
  6138. results->setNodes (std::move (found), none ? tr ("Nothing found for \"{0}\".", { query }) : juce::String());
  6139. return;
  6140. }
  6141. const auto scope = searchRoots();
  6142. if (scope.isEmpty())
  6143. {
  6144. // round 190ce: no folder to search, but the collections are still searched by their names
  6145. const auto tagged = collectionMatches (query);
  6146. results->setFiles (tagged, {}, tagged.isEmpty() ? tr ("Nothing found for \"{0}\".", { query }) : juce::String());
  6147. return;
  6148. }
  6149. if (! quiet)
  6150. {
  6151. results->setFiles ({}, scope, tr ("Searching {0}...", { scope.size() == 1 ? scope[0].getFullPathName() : tr ("every folder") }));
  6152. resultsView->setViewPosition (0, 0);
  6153. }
  6154. // the worker answers on its thread: the answer comes to the message thread (and is dropped if this Browser went)
  6155. searchId = searcher->service->search (query.toStdString(), toPaths (scope), (std::size_t) maxResults,
  6156. [safe = juce::Component::SafePointer<BrowserComponent> (this), query, scope] (const search::SearchResult& r) {
  6157. juce::MessageManager::callAsync ([safe, query, scope, r] {
  6158. if (safe != nullptr)
  6159. safe->searchAnswered (r, query, scope);
  6160. });
  6161. });
  6162. }
  6163. juce::Array<juce::File> BrowserComponent::collectionMatches (const juce::String& query) const
  6164. {
  6165. std::array<std::string, collections::count> names;
  6166. for (int c = 0; c < collections::count; ++c)
  6167. names[(std::size_t) c] = collectionName (c).toStdString();
  6168. juce::Array<juce::File> out;
  6169. for (const auto& item : collectionStore().search (query.toStdString(), &names))
  6170. if (! collections::isPluginItem (item))
  6171. if (const juce::File f (juce::String::fromUTF8 (item.c_str())); f.existsAsFile() && (activeFilter() == browserview::ContentFilter::all || lists (f)) && ! userHides (f))
  6172. out.add (f);
  6173. return out;
  6174. }
  6175. void BrowserComponent::searchAnswered (const search::SearchResult& r, const juce::String& query, const juce::Array<juce::File>& scope)
  6176. {
  6177. if (r.id != searchId || effectiveQuery() != query)
  6178. return;
  6179. // round 190ce: first the files found through the name of a collection they are in ("starred kick"), then the
  6180. // files found by their own names
  6181. auto found = collectionMatches (query);
  6182. for (const auto& path : r.paths)
  6183. if (juce::File f (juce::String::fromUTF8 (path.c_str())); (activeFilter() == browserview::ContentFilter::all || lists (f)) && ! userHides (f))
  6184. found.addIfNotAlreadyThere (f);
  6185. // (partial answers and re-searches keep the selection and the scroll position)
  6186. const auto selected = results->selectedFile();
  6187. const auto scroll = resultsView->getViewPosition();
  6188. results->setFiles (found, scope,
  6189. found.isEmpty() ? (r.partial ? tr ("Indexing the folders... nothing found for \"{0}\" yet.", { query })
  6190. : tr ("Nothing found for \"{0}\".", { query }))
  6191. : juce::String());
  6192. if (selected != juce::File())
  6193. if (const auto row = found.indexOf (selected); row >= 0)
  6194. results->select (row, false);
  6195. resultsView->setViewPosition (scroll);
  6196. searchPartial = r.partial;
  6197. if (! r.partial && ! found.isEmpty())
  6198. // FL's hint bar after a search: "Found 51 files" (REA round 134)
  6199. ui::postHint ({ r.truncated ? tr ("Found more than {0} files", { juce::String (found.size()) })
  6200. : found.size() == 1 ? tr ("Found 1 file") : tr ("Found {0} files", { juce::String (found.size()) }),
  6201. {}, false, false },
  6202. 4000);
  6203. // the line under the search box
  6204. juce::String line;
  6205. if (r.partial)
  6206. line = tr ("Indexing... {0} found so far", { juce::String (found.size()) });
  6207. else if (r.truncated)
  6208. line = tr ("Showing the first {0} results.", { juce::String (maxResults) });
  6209. else
  6210. line = found.size() == 1 ? tr ("Found 1 file") : tr ("Found {0} files", { juce::String (found.size()) });
  6211. const auto st = searcher->service->status();
  6212. if (st.busy && ! r.partial)
  6213. line << " · " << tr ("checking the index...");
  6214. if (line != statusLine)
  6215. {
  6216. const auto relayout = line.isEmpty() != statusLine.isEmpty();
  6217. statusLine = line;
  6218. if (relayout)
  6219. resized();
  6220. repaint (statusArea);
  6221. }
  6222. }
  6223. void BrowserComponent::indexStatusChanged()
  6224. {
  6225. applyFilterToTree(); // the index changed: folders found empty under the content filter go (round 164)
  6226. if (similarTo != juce::File() && resultsView->isVisible())
  6227. return; // similar samples are listed: their own line stays
  6228. const auto st = searcher->service->status();
  6229. juce::String line;
  6230. if (resultsView->isVisible() && shownTab() != projectTab && searchBox.getText().trim().isNotEmpty())
  6231. {
  6232. // a search is shown: its line stays; while the folders are indexed, the progress is added
  6233. line = statusLine.upToFirstOccurrenceOf (" · ", false, false);
  6234. if (st.busy)
  6235. line << " · " << (searchPartial ? tr ("{0} folders indexed", { juce::String ((int) st.listed) }) : tr ("checking the index..."));
  6236. }
  6237. else if (st.busy && (st.rebuilding || st.listed > 0))
  6238. line = tr ("Indexing folders... {0}", { juce::String ((int) st.listed) }); // (round 190oo PAT-13: short, it was cut)
  6239. if (line != statusLine)
  6240. {
  6241. const auto relayout = line.isEmpty() != statusLine.isEmpty();
  6242. statusLine = line;
  6243. if (relayout)
  6244. resized();
  6245. repaint();
  6246. }
  6247. }
  6248. // --- "Find similar samples" (round 190as) ------------------------------------------------------------------------
  6249. juce::String BrowserComponent::similarLabel() const
  6250. {
  6251. return tr ("Similar to {0}", { similarTo.getFileNameWithoutExtension() });
  6252. }
  6253. juce::Array<juce::File> BrowserComponent::similarScope() const
  6254. {
  6255. return withMerged (roots); // every folder this Browser shows, wherever the sample itself is
  6256. }
  6257. void BrowserComponent::findSimilar (const juce::File& file)
  6258. {
  6259. if (! file.existsAsFile())
  6260. return;
  6261. if (shownTab() == projectTab)
  6262. setTab (allTab);
  6263. similarTo = file;
  6264. searchPending = false;
  6265. searchBox.setText (similarLabel(), juce::dontSendNotification);
  6266. // the first use starts the analysis of the Browser's folders (the clicked file is analysed first, at once)
  6267. if (! allRoots.isEmpty() && ! std::exchange (similar->passAsked, true))
  6268. similar->service->refresh (toPaths (withMerged (allRoots)));
  6269. runSearch();
  6270. }
  6271. void BrowserComponent::findSimilarSamples (const juce::File& file, std::function<void (juce::Array<juce::File>)> done)
  6272. {
  6273. BrowserComponent* main = nullptr;
  6274. for (auto* b : liveBrowsers())
  6275. if (b->role == Role::main)
  6276. main = b;
  6277. if (main == nullptr || main->similar == nullptr || ! file.existsAsFile())
  6278. {
  6279. if (done)
  6280. juce::MessageManager::callAsync ([done] { done ({}); });
  6281. return;
  6282. }
  6283. if (! main->allRoots.isEmpty() && ! std::exchange (main->similar->passAsked, true))
  6284. main->similar->service->refresh (toPaths (main->withMerged (main->allRoots)));
  6285. main->similar->service->findSimilar (file.getFullPathName().toStdString(), toPaths (main->similarScope()), (std::size_t) maxSimilar,
  6286. [done] (const similarity::Result& r) {
  6287. juce::Array<juce::File> found;
  6288. for (const auto& m : r.matches)
  6289. found.add (juce::File (juce::String::fromUTF8 (m.path.c_str())));
  6290. juce::MessageManager::callAsync ([done, found] {
  6291. if (done)
  6292. done (found);
  6293. });
  6294. });
  6295. }
  6296. void BrowserComponent::runSimilar (bool quiet)
  6297. {
  6298. resultsView->setVisible (true);
  6299. treeView->setVisible (false);
  6300. const auto scope = similarScope();
  6301. if (! quiet)
  6302. {
  6303. results->setFiles ({}, scope, tr ("Listening to \"{0}\"...", { similarTo.getFileName() }));
  6304. resultsView->setViewPosition (0, 0);
  6305. }
  6306. similarAskedAt = juce::Time::getMillisecondCounter();
  6307. // the worker answers on its thread: the answer comes to the message thread (and is dropped if this Browser went)
  6308. similarId = similar->service->findSimilar (similarTo.getFullPathName().toStdString(), toPaths (scope), (std::size_t) maxSimilar,
  6309. [safe = juce::Component::SafePointer<BrowserComponent> (this)] (const similarity::Result& r) {
  6310. juce::MessageManager::callAsync ([safe, r] {
  6311. if (safe != nullptr)
  6312. safe->similarAnswered (r);
  6313. });
  6314. });
  6315. }
  6316. void BrowserComponent::similarAnswered (const similarity::Result& r)
  6317. {
  6318. if (r.id != similarId || similarTo == juce::File() || r.query != similarTo.getFullPathName().toStdString())
  6319. return;
  6320. juce::Array<juce::File> found;
  6321. juce::StringArray details;
  6322. for (const auto& m : r.matches)
  6323. if (juce::File f (juce::String::fromUTF8 (m.path.c_str())); (activeFilter() == browserview::ContentFilter::all || lists (f)) && ! userHides (f))
  6324. {
  6325. found.add (f);
  6326. details.add (juce::String (similarity::percent (m.distance)) + "%");
  6327. }
  6328. const auto name = similarTo.getFileName();
  6329. // (partial answers keep the selection and the scroll position)
  6330. const auto selected = results->selectedFile();
  6331. const auto scroll = resultsView->getViewPosition();
  6332. results->setFiles (found, similarScope(),
  6333. r.failed ? tr ("\"{0}\" can't be compared: it is silent or can't be read.", { name })
  6334. : found.isEmpty() ? (r.partial ? tr ("Listening to the Browser's samples... nothing like \"{0}\" yet.", { name })
  6335. : tr ("No other samples to compare \"{0}\" with.", { name }))
  6336. : juce::String(),
  6337. details);
  6338. if (selected != juce::File())
  6339. if (const auto row = found.indexOf (selected); row >= 0)
  6340. results->select (row, false);
  6341. resultsView->setViewPosition (scroll);
  6342. similarPartial = r.partial && ! r.failed;
  6343. juce::String line;
  6344. if (! r.failed)
  6345. {
  6346. line = found.size() == 1 ? tr ("1 similar sample, most similar first") : tr ("{0} similar samples, most similar first", { juce::String (found.size()) });
  6347. if (r.partial)
  6348. line << " · " << tr ("{0} samples analysed so far", { juce::String ((int) r.searched) });
  6349. else if (! found.isEmpty())
  6350. ui::postHint ({ tr ("Compared with {0} samples", { juce::String ((int) r.searched) }), {}, false, false }, 4000);
  6351. }
  6352. if (line != statusLine)
  6353. {
  6354. const auto relayout = line.isEmpty() != statusLine.isEmpty();
  6355. statusLine = line;
  6356. if (relayout)
  6357. resized();
  6358. repaint (statusArea);
  6359. }
  6360. }
  6361. void BrowserComponent::similarStatusChanged()
  6362. {
  6363. // the background analysis moved on: a list still marked "so far" is asked again (not more than every 3 s; the
  6364. // last time when the pass ends)
  6365. if (similarTo == juce::File() || ! similarPartial || ! resultsView->isVisible())
  6366. return;
  6367. const auto busy = similar->service->status().busy;
  6368. if (! busy || juce::Time::getMillisecondCounter() - similarAskedAt > 3000)
  6369. runSimilar (true);
  6370. }
  6371. void BrowserComponent::findSimilarForSnapshot (const juce::File& file, const juce::File& folder)
  6372. {
  6373. similar->passAsked = true;
  6374. similar->service->refresh (toPaths ({ folder }));
  6375. similar->service->waitIdle (300000);
  6376. if (shownTab() == projectTab)
  6377. setTab (allTab);
  6378. similarTo = file;
  6379. searchBox.setText (similarLabel(), juce::dontSendNotification);
  6380. resultsView->setVisible (true);
  6381. treeView->setVisible (false);
  6382. auto answer = std::make_shared<std::pair<std::mutex, similarity::Result>>();
  6383. similarId = similar->service->findSimilar (file.getFullPathName().toStdString(), toPaths ({ folder }), (std::size_t) maxSimilar,
  6384. [answer] (const similarity::Result& r) {
  6385. const std::lock_guard<std::mutex> hold (answer->first);
  6386. answer->second = r;
  6387. });
  6388. similar->service->waitIdle (120000);
  6389. const std::lock_guard<std::mutex> hold (answer->first);
  6390. similarAnswered (answer->second);
  6391. }
  6392. void BrowserComponent::refreshSearchIndex (bool rebuild)
  6393. {
  6394. // the index is shared by every Browser: it covers every folder, hidden ones too
  6395. if (! allRoots.isEmpty())
  6396. searcher->service->refresh (toPaths (withMerged (allRoots)), rebuild);
  6397. ui::postHint ({ rebuild ? tr ("Rebuilding the Browser's search index in the background...")
  6398. : tr ("Checking the Browser's search index in the background (only changed folders are read again)..."),
  6399. {}, false, false },
  6400. 4000);
  6401. }
  6402. juce::String BrowserComponent::searchIndexStatus() const
  6403. {
  6404. const auto st = searcher->service->status();
  6405. if (! st.loaded)
  6406. return tr ("Search index: loading...");
  6407. auto text = tr ("Search index: {0} files in {1} folders", { juce::String ((juce::int64) st.files), juce::String ((juce::int64) st.folders) });
  6408. if (st.busy)
  6409. text << " (" << tr ("updating: {0} folders read", { juce::String ((int) st.listed) }) << ")";
  6410. else if (st.checkedAt > 0)
  6411. text << " (" << tr ("checked at {0}", { juce::Time (st.checkedAt).formatted ("%H:%M") }) << ")";
  6412. return text;
  6413. }
  6414. bool BrowserComponent::renameSelectedPlugin()
  6415. {
  6416. return activeList().renameSelectedPlugin();
  6417. }
  6418. void BrowserComponent::stopPreview()
  6419. {
  6420. engine.previewFile ({});
  6421. stopMidiPreview(); // (round 190qi)
  6422. if (strip != nullptr)
  6423. strip->stop();
  6424. tree->repaint();
  6425. results->repaint();
  6426. }
  6427. // --- keys --------------------------------------------------------------------------------------------
  6428. juce::File BrowserComponent::getSelectedFile() const
  6429. {
  6430. return activeList().selectedFile();
  6431. }
  6432. void BrowserComponent::step (int delta, bool load)
  6433. {
  6434. auto& list = activeList();
  6435. const auto count = list.numRows();
  6436. if (count == 0)
  6437. return;
  6438. // the next row in that direction, as in FL: Up / Down walk every row (folders too: Right opens one, Left closes
  6439. // it), previewing each sample; Shift+Up / Down (loading each file into the channel) skips the folders
  6440. auto row = list.getSelectedRow();
  6441. for (int guard = 0; guard < count; ++guard)
  6442. {
  6443. row = row < 0 ? (delta > 0 ? 0 : count - 1) : row + delta;
  6444. if (row < 0 || row >= count)
  6445. return;
  6446. list.select (row, false);
  6447. if (! load || ! list.selectedIsFolder())
  6448. break;
  6449. }
  6450. const auto file = list.selectedFile();
  6451. if (file.existsAsFile())
  6452. fileSelected (file, true);
  6453. if (load && file.existsAsFile() && onLoadIntoChannel)
  6454. onLoadIntoChannel (file);
  6455. }
  6456. // Round 190lr (DF-96, FL's Browser "Navigation history": Backspace / Shift+Backspace = previous / next location; DL-102,
  6457. // Live's Ctrl+[ / Ctrl+]): the folders opened, in order; going back or forward selects and reveals that folder again
  6458. void BrowserComponent::noteLocation (const juce::File& folder)
  6459. {
  6460. if (walkingHistory || folder == juce::File())
  6461. return;
  6462. if (historyAt >= 0 && historyAt < (int) locations.size() && locations[(std::size_t) historyAt] == folder)
  6463. return;
  6464. locations.resize ((std::size_t) juce::jmax (0, historyAt + 1)); // (a new place drops the forward part)
  6465. locations.push_back (folder);
  6466. if (locations.size() > 64)
  6467. locations.erase (locations.begin());
  6468. historyAt = (int) locations.size() - 1;
  6469. }
  6470. bool BrowserComponent::walkHistory (int delta)
  6471. {
  6472. const auto to = historyAt + delta;
  6473. if (to < 0 || to >= (int) locations.size())
  6474. return false;
  6475. historyAt = to;
  6476. const juce::ScopedValueSetter<bool> walking (walkingHistory, true);
  6477. return locateFile (locations[(std::size_t) to]);
  6478. }
  6479. // Round 190lr (DF-97, FL's Browser: "Use (F3) to skip to the next matching item"): with a search typed, the next (−1:
  6480. // previous) row of the results, round to the first after the last; a file is previewed as Up / Down do
  6481. void BrowserComponent::findMatch (int delta)
  6482. {
  6483. if (searchBox.getText().trim().isEmpty())
  6484. return;
  6485. auto& list = activeList();
  6486. const auto count = list.numRows();
  6487. if (count == 0)
  6488. return;
  6489. const auto at = list.getSelectedRow();
  6490. const auto row = at < 0 ? (delta > 0 ? 0 : count - 1) : ((at + delta) % count + count) % count;
  6491. list.select (row, false);
  6492. if (const auto file = list.selectedFile(); file.existsAsFile())
  6493. fileSelected (file, true);
  6494. }
  6495. bool BrowserComponent::typeToJump (const juce::KeyPress& key)
  6496. {
  6497. auto& list = activeList();
  6498. const auto row = ui::typeAheadRow (&list, key, list.getSelectedRow(), list.numRows(), [&list] (int r) { return list.rowName (r); });
  6499. if (row < 0)
  6500. return false;
  6501. list.select (row, false);
  6502. return true;
  6503. }
  6504. void BrowserComponent::openFolder (bool open)
  6505. {
  6506. if (! resultsView->isVisible())
  6507. tree->openSelected (open);
  6508. }
  6509. bool BrowserComponent::previewSelected()
  6510. {
  6511. const auto file = getSelectedFile();
  6512. if (! file.existsAsFile())
  6513. return false;
  6514. const juce::ScopedValueSetter<bool> force (forcePreview, true);
  6515. fileSelected (file, true);
  6516. return true;
  6517. }
  6518. int BrowserComponent::rowCountForSnapshot() const { return tree->numRows(); }
  6519. int BrowserComponent::selectedRowForSnapshot() const { return tree->getSelectedRow(); }
  6520. void BrowserComponent::selectRowIndexForSnapshot (int row) { tree->select (row, false); }
  6521. void BrowserComponent::loadSelected()
  6522. {
  6523. if (hotSwapLoadSelected()) // round 190ce: while linked, Enter replaces the linked device
  6524. return;
  6525. if (! resultsView->isVisible() && tree->toggleSelectedFolder()) // #218 follow-up (round 190nq): FL's Enter on a folder
  6526. return;
  6527. const auto file = getSelectedFile();
  6528. if (! file.existsAsFile())
  6529. return;
  6530. if (isSamplerInstrumentFile (file))
  6531. {
  6532. // Enter: into the selected DirectWave channel, else a new one (round 190ii)
  6533. openSamplerInstrumentFile (engine, file, engine.getSelectedChannel());
  6534. return;
  6535. }
  6536. if (file.hasFileExtension ("sf2;sf3;sfz"))
  6537. {
  6538. // Enter: into the selected LYNX Soundfont channel, else a new one
  6539. if (! openSoundFontFile (engine, file, engine.getSelectedChannel()))
  6540. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Load SoundFont"), tr ("This file is not a SoundFont LYNX SHARE can read."));
  6541. return;
  6542. }
  6543. if (! onLoadIntoChannel || ! onLoadIntoChannel (file))
  6544. openFile (file);
  6545. }
  6546. bool BrowserComponent::isAudioFile (const juce::File& file)
  6547. {
  6548. return isAudio (file);
  6549. }
  6550. bool BrowserComponent::isBrowserDrag (const juce::DragAndDropTarget::SourceDetails& details)
  6551. {
  6552. const auto text = details.description.toString();
  6553. return text == dragDescription || text.startsWith (juce::String (dragDescription) + "|");
  6554. }
  6555. juce::File BrowserComponent::draggedFile (const juce::DragAndDropTarget::SourceDetails& details)
  6556. {
  6557. const auto text = details.description.toString();
  6558. if (text.startsWith (juce::String (dragDescription) + "|"))
  6559. return juce::File (text.fromFirstOccurrenceOf ("|", false, false));
  6560. return {};
  6561. }
  6562. bool BrowserComponent::startPluginDrag (juce::Component& source, std::function<std::optional<ChannelDef>()> generator,
  6563. std::function<std::optional<EffectSlot>()> effect, const juce::String& label, const juce::Image& image,
  6564. juce::Component* containerOwner)
  6565. {
  6566. // (`containerOwner`: the Plugin picker is its own window, outside the main window's drag container)
  6567. // (findParentDragContainerFor looks from the parent up, so the owner itself is tried first)
  6568. auto* container = dynamic_cast<juce::DragAndDropContainer*> (containerOwner);
  6569. if (container == nullptr)
  6570. container = juce::DragAndDropContainer::findParentDragContainerFor (containerOwner != nullptr ? containerOwner : &source);
  6571. if (container == nullptr || (generator == nullptr && effect == nullptr))
  6572. return false;
  6573. const auto isGenerator = generator != nullptr;
  6574. draggedPlugin() = { std::move (generator), std::move (effect) };
  6575. container->startDragging (juce::String (isGenerator ? generatorDragDescription : effectDragDescription) + "|" + label, &source,
  6576. juce::ScaledImage (image), true);
  6577. return true;
  6578. }
  6579. bool BrowserComponent::isGeneratorDrag (const juce::DragAndDropTarget::SourceDetails& details)
  6580. {
  6581. return details.description.toString().startsWith (juce::String (generatorDragDescription) + "|") && draggedPlugin().generator != nullptr;
  6582. }
  6583. bool BrowserComponent::isEffectDrag (const juce::DragAndDropTarget::SourceDetails& details)
  6584. {
  6585. return details.description.toString().startsWith (juce::String (effectDragDescription) + "|") && draggedPlugin().effect != nullptr;
  6586. }
  6587. std::optional<ChannelDef> BrowserComponent::draggedGenerator (const juce::DragAndDropTarget::SourceDetails& details)
  6588. {
  6589. return isGeneratorDrag (details) ? draggedPlugin().generator() : std::nullopt;
  6590. }
  6591. std::optional<EffectSlot> BrowserComponent::draggedEffect (const juce::DragAndDropTarget::SourceDetails& details)
  6592. {
  6593. return isEffectDrag (details) ? draggedPlugin().effect() : std::nullopt;
  6594. }
  6595. int BrowserComponent::draggedPattern (const juce::DragAndDropTarget::SourceDetails& details)
  6596. {
  6597. const auto text = details.description.toString();
  6598. if (text.startsWith (juce::String (patternDragDescription) + "|"))
  6599. return text.fromFirstOccurrenceOf ("|", false, false).getIntValue();
  6600. return -1;
  6601. }
  6602. void BrowserComponent::newSampleChannel (const juce::File& file)
  6603. {
  6604. const auto path = file.getFullPathName().toStdString();
  6605. const auto name = file.getFileNameWithoutExtension().toStdString();
  6606. engine.editSong ([&] (Song& s) {
  6607. ChannelDef c;
  6608. c.name = name;
  6609. c.instrument = InstrumentKind::sampler;
  6610. c.samplePath = path;
  6611. c.mixerTrack = s.claimFreeInsert();
  6612. s.channels.push_back (c);
  6613. });
  6614. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  6615. }
  6616. void BrowserComponent::openFile (const juce::File& file)
  6617. {
  6618. // a user preset of one of LYNX's generators (round 190fs): a new channel with that generator and sound
  6619. if (genpresetui::isPresetFile (file))
  6620. {
  6621. juce::String error;
  6622. if (! genpresetui::addChannel (engine, file, error) && error.isNotEmpty())
  6623. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Preset"), error);
  6624. return;
  6625. }
  6626. // a hosted plugin's preset (round 162d, issue #8): into the plugin it belongs to
  6627. if (pluginpresetui::isPresetFile (file) && (! file.hasFileExtension ("lynxpreset") || pluginpresetui::readLynxPreset (file).has_value()))
  6628. {
  6629. juce::String message;
  6630. if (! pluginpresetui::applyFromBrowser (engine, file, message) && message.isNotEmpty())
  6631. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin preset"), message);
  6632. return;
  6633. }
  6634. if (file.hasFileExtension ("sf2;sf3;sfz"))
  6635. {
  6636. if (! openSoundFontFile (engine, file))
  6637. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Load SoundFont"), tr ("This file is not a SoundFont LYNX SHARE can read."));
  6638. return;
  6639. }
  6640. if (isSamplerInstrumentFile (file))
  6641. {
  6642. openSamplerInstrumentFile (engine, file); // (round 190ii, issue #149: a new DirectWave channel)
  6643. return;
  6644. }
  6645. if (isAudio (file) && file.hasFileExtension ("speech"))
  6646. {
  6647. // FL's .speech: the Speech properties first, then a new channel with the file it returns (round 168b)
  6648. speechui::editThenLoad (engine, file, [safe = juce::Component::SafePointer<BrowserComponent> (this)] (const juce::File& f) {
  6649. if (safe != nullptr && f.existsAsFile())
  6650. {
  6651. safe->newSampleChannel (f);
  6652. safe->rebuildTree(); // (an edited copy appears in the Speech folder)
  6653. }
  6654. });
  6655. return;
  6656. }
  6657. if (isAudio (file))
  6658. {
  6659. newSampleChannel (file);
  6660. return;
  6661. }
  6662. // FL's mixer preset (REA round 167q) or LYNX's mixer track state: onto the selected mixer tracks
  6663. if (file.hasFileExtension ("fst;lynxtrack") && onOpenMixerPreset && onOpenMixerPreset (file))
  6664. return;
  6665. // preset of an FL synth that LYNX converts (3x Osc, Sytrus, GMS...): new channel with the built-in synth
  6666. if (file.hasFileExtension ("fst;gmsynth"))
  6667. {
  6668. // FL's preset of a third-party plugin (round 190fs): into that plugin (an open window, or a new channel)
  6669. if (pluginpresetui::isFlPresetOfPlugin (file))
  6670. {
  6671. juce::String message;
  6672. if (! pluginpresetui::applyFlPresetFromBrowser (engine, file, message) && message.isNotEmpty())
  6673. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Preset"), message);
  6674. return;
  6675. }
  6676. // issue #288 (round 190rc): a preset of a generator LYNX plays natively (Sytrus, Harmor, 3x Osc, GMS...) opens that
  6677. // generator with the preset loaded, named after it, as FL's Browser does; it used to become LYNX's synth with an
  6678. // approximation of the sound ("it opens a 3x Osc")
  6679. if (auto native = natives::channelFromAnyPreset (file.getFullPathName().toStdString(), file.getFileNameWithoutExtension().toStdString(),
  6680. flStudioAccess()))
  6681. {
  6682. if (onAddInstrument != nullptr)
  6683. onAddInstrument (std::move (*native));
  6684. else
  6685. {
  6686. engine.editSong ([&native] (Song& s) {
  6687. native->mixerTrack = s.claimFreeInsert();
  6688. s.channels.push_back (std::move (*native));
  6689. });
  6690. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  6691. }
  6692. return;
  6693. }
  6694. juce::MemoryBlock data;
  6695. if (! file.loadFileAsData (data))
  6696. return;
  6697. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  6698. if (auto synth = synthFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize())))
  6699. {
  6700. const auto name = file.getFileNameWithoutExtension().toStdString();
  6701. engine.editSong ([&] (Song& s) {
  6702. ChannelDef c;
  6703. c.name = name;
  6704. c.instrument = InstrumentKind::synth;
  6705. c.synth = *synth;
  6706. c.mixerTrack = s.claimFreeInsert();
  6707. s.channels.push_back (c);
  6708. });
  6709. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  6710. }
  6711. else
  6712. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Preset"),
  6713. tr ("LYNX SHARE reads presets from 3x Osc, Sytrus, Harmor, GMS, Harmless, MiniSynth, DX10, Fruit Kick, Ogun and Sakura."));
  6714. return;
  6715. }
  6716. if (file.hasFileExtension ("lynx;flp;als;flm;mid;midi;mod;xm;s3m;it") && onOpenProject) // (round 190nw: tracker modules)
  6717. onOpenProject (file);
  6718. }
  6719. // --- Round 190iz: tags, Live's browser, send to selected, prefs ----------------------------------------------------------
  6720. browsertags::Store& BrowserComponent::tagStore()
  6721. {
  6722. static browsertags::Store store;
  6723. return store;
  6724. }
  6725. browsertags::Store BrowserComponent::shownTags()
  6726. {
  6727. if (layoutstyle::current() != layoutstyle::Style::simple)
  6728. return tagStore();
  6729. return factorycontent::merged (tagStore());
  6730. }
  6731. void BrowserComponent::layoutStyleChanged()
  6732. {
  6733. static bool wasSimple = false; // (only a move into or out of the Simple layout changes what is listed)
  6734. const auto simple = layoutstyle::current() == layoutstyle::Style::simple;
  6735. if (std::exchange (wasSimple, simple) == simple)
  6736. return;
  6737. for (auto* b : liveBrowsers())
  6738. {
  6739. b->rebuildTree();
  6740. if (b->tagsPanelShown)
  6741. {
  6742. b->tagsPanel->refresh();
  6743. b->resized();
  6744. }
  6745. if (b->tagFilterActive())
  6746. b->runSearch (true);
  6747. }
  6748. }
  6749. juce::File BrowserComponent::tagsFile()
  6750. {
  6751. // the user's tag store (FL: one tag database of the user; not in the project)
  6752. return PluginHost::settingsFolder().getChildFile ("browser-tags.txt");
  6753. }
  6754. void BrowserComponent::loadTags()
  6755. {
  6756. static bool loaded = false; // (once per process: every Browser shares the store)
  6757. if (std::exchange (loaded, true))
  6758. return;
  6759. if (const auto file = tagsFile(); file.existsAsFile())
  6760. tagStore() = browsertags::Store::fromText (file.loadFileAsString().toStdString());
  6761. }
  6762. void BrowserComponent::saveTags()
  6763. {
  6764. tagsFile().getParentDirectory().createDirectory();
  6765. tagsFile().replaceWithText (juce::String::fromUTF8 (tagStore().toText().c_str()));
  6766. }
  6767. void BrowserComponent::tagsChanged()
  6768. {
  6769. for (auto* b : liveBrowsers())
  6770. {
  6771. // picked tags that were deleted go
  6772. const auto shown = shownTags();
  6773. std::erase_if (b->picked, [&shown] (const std::string& t) { return ! shown.exists (t); });
  6774. if (b->tagsPanelShown)
  6775. {
  6776. b->tagsPanel->refresh();
  6777. b->resized(); // (the panel's height follows its chips)
  6778. }
  6779. b->tagsButton->repaint();
  6780. if (b->loopsShown) // (round gaps190kf: tags that name a keyword give it)
  6781. b->runLoopSearch();
  6782. else if (b->tagFilterActive() || b->resultsView->isVisible())
  6783. b->runSearch (true);
  6784. b->tree->repaint();
  6785. b->results->repaint();
  6786. }
  6787. }
  6788. void BrowserComponent::setTagged (const std::string& item, const juce::String& tag, bool on)
  6789. {
  6790. if (tagStore().set (item, tag.toStdString(), on))
  6791. {
  6792. saveTags();
  6793. tagsChanged();
  6794. }
  6795. }
  6796. void BrowserComponent::addTagItems (juce::PopupMenu& menu, const std::string& item)
  6797. {
  6798. if (item.empty())
  6799. return;
  6800. juce::Component::SafePointer<BrowserComponent> safe (this);
  6801. // round 190qi: a right-click on one of several marked rows acts on all of them
  6802. std::vector<std::string> items { item };
  6803. for (auto* list : { tree.get(), results.get() })
  6804. if (list != nullptr && list->marked.size() > 1 && std::find (list->marked.begin(), list->marked.end(), item) != list->marked.end())
  6805. items = list->marked;
  6806. // FL's Tags section: Favorite (LYNX's Starred / the collections, above), Tags ▸, Add tag, Edit tags
  6807. const auto shown = shownTags(); // (round 190ke: with LYNX content's tags in the Simple layout)
  6808. // round 190qi: "a/b" tags as submenus (a group's own tag first in it); ticked when every item has it, a click puts it
  6809. // on every item (or takes it off them all when they all have it)
  6810. std::function<void (juce::PopupMenu&, const std::vector<browsertags::TagNode>&)> addNodes = [&] (juce::PopupMenu& m, const std::vector<browsertags::TagNode>& nodes) {
  6811. for (const auto& node : nodes)
  6812. {
  6813. const auto path = node.path;
  6814. const auto all = std::all_of (items.begin(), items.end(), [&shown, &path] (const std::string& i) { return shown.has (i, path); });
  6815. const auto name = juce::String::fromUTF8 (node.name.c_str());
  6816. auto act = [safe, items, path, all] {
  6817. if (safe == nullptr)
  6818. return;
  6819. auto changed = false;
  6820. for (const auto& i : items)
  6821. changed = tagStore().set (i, path, ! all) || changed;
  6822. if (changed)
  6823. {
  6824. saveTags();
  6825. safe->tagsChanged();
  6826. }
  6827. };
  6828. if (node.children.empty())
  6829. {
  6830. m.addItem (name, true, all, act);
  6831. continue;
  6832. }
  6833. juce::PopupMenu sub;
  6834. if (node.exists)
  6835. {
  6836. sub.addItem (name, true, all, act);
  6837. sub.addSeparator();
  6838. }
  6839. addNodes (sub, node.children);
  6840. m.addSubMenu (name, sub, true, nullptr, all && node.exists);
  6841. }
  6842. };
  6843. juce::PopupMenu tags;
  6844. addNodes (tags, browsertags::tagTree (shown.all()));
  6845. if (tags.getNumItems() == 0)
  6846. tags.addItem (tr ("(no tags yet)"), false, false, nullptr);
  6847. menu.addSubMenu (tr ("Tags"), tags);
  6848. menu.addItem (items.size() > 1 ? tr ("Add tag to {0} items...", { juce::String ((int) items.size()) }) : tr ("Add tag..."), [safe, items] {
  6849. if (safe != nullptr)
  6850. safe->askAddTag (items);
  6851. });
  6852. menu.addItem (tr ("Edit tags..."), ! tagStore().names.empty(), false, [safe] {
  6853. if (safe != nullptr)
  6854. safe->showEditTags();
  6855. });
  6856. }
  6857. void BrowserComponent::askAddTag (const std::string& item)
  6858. {
  6859. auto* window = new juce::AlertWindow (tr ("Add tag"), tr ("Type a tag to add to the item. Separate several with commas: Kick,808,C# gives it three tags."),
  6860. juce::MessageBoxIconType::NoIcon);
  6861. window->addTextEditor ("tags", {});
  6862. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  6863. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6864. juce::Component::SafePointer<BrowserComponent> safe (this);
  6865. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, safe, item] (int result) {
  6866. const auto text = window->getTextEditorContents ("tags").toStdString();
  6867. if (result != 1 || safe == nullptr)
  6868. return;
  6869. if (tagStore().add ({ item }, text) > 0)
  6870. {
  6871. saveTags();
  6872. safe->tagsChanged();
  6873. }
  6874. }),
  6875. true);
  6876. }
  6877. void BrowserComponent::showEditTags()
  6878. {
  6879. // FL's "Edit tags": each tag with its count; pick one to rename or delete it everywhere
  6880. juce::PopupMenu menu;
  6881. menu.addSectionHeader (tr ("Edit tags"));
  6882. juce::Component::SafePointer<BrowserComponent> safe (this);
  6883. for (const auto& t : tagStore().all())
  6884. {
  6885. juce::PopupMenu one;
  6886. const auto tag = t.name;
  6887. one.addItem (tr ("Rename..."), [safe, tag] {
  6888. if (safe == nullptr)
  6889. return;
  6890. auto* window = new juce::AlertWindow (tr ("Rename tag"), tr ("The tag's new name, on every item that has it:"), juce::MessageBoxIconType::NoIcon);
  6891. window->addTextEditor ("name", juce::String::fromUTF8 (tag.c_str()));
  6892. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  6893. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6894. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, safe, tag] (int result) {
  6895. const auto name = window->getTextEditorContents ("name").toStdString();
  6896. if (result == 1 && safe != nullptr && tagStore().rename (tag, name))
  6897. {
  6898. for (auto& p : safe->picked)
  6899. if (browsertags::Store::key (p) == browsertags::Store::key (tag))
  6900. p = browsertags::cleanTag (name);
  6901. saveTags();
  6902. safe->tagsChanged();
  6903. }
  6904. }),
  6905. true);
  6906. });
  6907. one.addItem (tr ("Delete tag"), [safe, tag] {
  6908. if (safe == nullptr)
  6909. return;
  6910. tagStore().remove (tag);
  6911. saveTags();
  6912. safe->tagsChanged();
  6913. });
  6914. menu.addSubMenu (juce::String::fromUTF8 (tag.c_str()) + " (" + juce::String (t.items) + ")", one);
  6915. }
  6916. if (tagStore().names.empty())
  6917. menu.addItem (tr ("(no tags yet)"), false, false, nullptr);
  6918. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  6919. }
  6920. void BrowserComponent::setTagsPanelShown (bool shown)
  6921. {
  6922. if (shown == tagsPanelShown)
  6923. return;
  6924. tagsPanelShown = shown;
  6925. if (shown)
  6926. tagsPanel->refresh();
  6927. if (shown && loopsShown) // (round gaps190kf: one filter panel at a time)
  6928. {
  6929. setLoopsShown (false);
  6930. return;
  6931. }
  6932. resized();
  6933. tagsButton->repaint();
  6934. savePrefs();
  6935. }
  6936. void BrowserComponent::setPickedTags (std::vector<std::string> tags)
  6937. {
  6938. picked = std::move (tags);
  6939. if (layoutstyle::current() == layoutstyle::Style::simple && tagsPanelShown) // (round 190ke: the picked chips come first)
  6940. tagsPanel->refresh();
  6941. else
  6942. tagsPanel->repaint();
  6943. tagsButton->repaint();
  6944. runSearch();
  6945. savePrefs();
  6946. }
  6947. void BrowserComponent::setTagMatch (browsertags::Match match)
  6948. {
  6949. if (match == matchMode)
  6950. return;
  6951. matchMode = match;
  6952. tagsPanel->repaint();
  6953. if (tagFilterActive())
  6954. runSearch();
  6955. savePrefs();
  6956. }
  6957. bool BrowserComponent::tagFilterActive() const
  6958. {
  6959. return ! picked.empty() || ! browsertags::parseQuery (searchBox.getText().trim().toStdString()).tags.empty();
  6960. }
  6961. void BrowserComponent::runTagFilter()
  6962. {
  6963. // FL: the picked tags filter the content (Any / All); Live: "#tag" in the search; the rest of the text must be in
  6964. // the item's name
  6965. const auto query = browsertags::parseQuery (searchBox.getText().trim().toStdString());
  6966. const auto store = shownTags(); // (round 190ke: LYNX content's tags too, in the Simple layout)
  6967. std::vector<std::string> items;
  6968. if (! picked.empty())
  6969. items = store.filter (picked, matchMode);
  6970. if (! query.tags.empty())
  6971. {
  6972. const auto hashed = store.filter (query.tags, browsertags::Match::all);
  6973. if (picked.empty())
  6974. items = hashed;
  6975. else
  6976. std::erase_if (items, [&hashed] (const std::string& i) { return std::find (hashed.begin(), hashed.end(), i) == hashed.end(); });
  6977. }
  6978. std::vector<std::unique_ptr<FileTree::Node>> nodes;
  6979. for (const auto& item : items)
  6980. {
  6981. if (collections::isPluginItem (item))
  6982. {
  6983. if (auto n = FileTree::makePluginItem (*this, collections::pluginKeyOf (item)); n != nullptr && browsertags::nameHasWords (n->label.toStdString(), query.rest))
  6984. nodes.push_back (std::move (n));
  6985. continue;
  6986. }
  6987. const juce::File f (juce::String::fromUTF8 (item.c_str()));
  6988. if (! browsertags::nameHasWords (f.getFileName().toStdString(), query.rest))
  6989. continue;
  6990. if (f.isDirectory())
  6991. nodes.push_back (FileTree::makeFolder (f, f.getFileName(), juce::Colour()));
  6992. else if (f.existsAsFile() && lists (f))
  6993. {
  6994. auto n = std::make_unique<FileTree::Node>();
  6995. n->file = f;
  6996. n->detail = f.getParentDirectory().getFileName(); // (the folder it is in, on the right)
  6997. nodes.push_back (std::move (n));
  6998. }
  6999. }
  7000. std::stable_sort (nodes.begin(), nodes.end(), [] (const auto& a, const auto& b) {
  7001. const auto na = a->label.isNotEmpty() ? a->label : a->file.getFileName();
  7002. const auto nb = b->label.isNotEmpty() ? b->label : b->file.getFileName();
  7003. return na.compareNatural (nb) < 0;
  7004. });
  7005. const auto count = (int) nodes.size();
  7006. resultsView->setVisible (true);
  7007. treeView->setVisible (false);
  7008. results->setNodes (std::move (nodes), count == 0 ? tr ("No item has these tags.") : juce::String());
  7009. resultsView->setViewPosition (0, 0);
  7010. const auto line = count == 1 ? tr ("1 tagged item") : tr ("{0} tagged items", { juce::String (count) });
  7011. if (line != statusLine)
  7012. {
  7013. const auto relayout = statusLine.isEmpty();
  7014. statusLine = line;
  7015. if (relayout)
  7016. resized();
  7017. repaint();
  7018. }
  7019. }
  7020. void BrowserComponent::setLiveLayout (bool on)
  7021. {
  7022. if (on == liveLayout)
  7023. return;
  7024. liveLayout = on;
  7025. if (on)
  7026. sidebar->refresh();
  7027. resized();
  7028. rebuildTree();
  7029. if (searchBox.getText().isNotEmpty() || tagFilterActive())
  7030. runSearch();
  7031. }
  7032. void BrowserComponent::showLiveEntry (const browserplaces::Entry& entry)
  7033. {
  7034. if (! entry.available)
  7035. return;
  7036. if (entry.category == browserplaces::Category::addFolder) // Live's "Add Folder...": a place, not a view
  7037. {
  7038. addUserFolder();
  7039. return;
  7040. }
  7041. liveSelection = entry;
  7042. sidebar->repaint();
  7043. rebuildTree();
  7044. if (searchBox.getText().isNotEmpty() || tagFilterActive())
  7045. runSearch();
  7046. else if (categoryQuery.isEmpty())
  7047. {
  7048. resultsView->setVisible (false);
  7049. treeView->setVisible (true);
  7050. }
  7051. savePrefs();
  7052. }
  7053. browsersend::Channel BrowserComponent::selectedChannelKind() const
  7054. {
  7055. const auto row = engine.getSelectedChannel();
  7056. const auto& song = engine.getSong();
  7057. if (row < 0 || row >= (int) song.channels.size())
  7058. return browsersend::Channel::none;
  7059. const auto kind = song.channels[(std::size_t) row].instrument;
  7060. if (kind == InstrumentKind::sampler || kind == InstrumentKind::kick || kind == InstrumentKind::snare || kind == InstrumentKind::hat
  7061. || kind == InstrumentKind::clap || kind == InstrumentKind::granulizer || kind == InstrumentKind::wavetraveller)
  7062. return browsersend::Channel::playsSample;
  7063. if (kind == InstrumentKind::soundfont)
  7064. return browsersend::Channel::soundFont;
  7065. if (kind == InstrumentKind::plugin)
  7066. return browsersend::Channel::plugin;
  7067. return browsersend::Channel::other;
  7068. }
  7069. void BrowserComponent::sendToSelected (const juce::File& file)
  7070. {
  7071. using namespace browsersend;
  7072. const auto item = isAudio (file) ? Item::sample
  7073. : file.hasFileExtension ("sf2;sf3;sfz") ? Item::soundFont
  7074. : pluginpresetui::isFlPresetOfPlugin (file) || pluginpresetui::isPresetFile (file) ? Item::pluginPreset
  7075. : genpresetui::isPresetFile (file) || file.hasFileExtension ("fst;gmsynth") ? Item::generatorPreset
  7076. : Item::other;
  7077. const auto focused = ! PluginWindows::openPlugins().empty();
  7078. // issue #288 (round 190rc): a preset of the selected channel's own generator goes into that channel (FL's "Send to
  7079. // selected channel or focused plugin", and Shift+Up / Down through a preset folder); another generator's preset
  7080. // still opens a new channel
  7081. if (item == Item::generatorPreset)
  7082. {
  7083. const auto channel = engine.getSelectedChannel();
  7084. const auto& song = engine.getSong();
  7085. if (channel >= 0 && channel < (int) song.channels.size())
  7086. {
  7087. const auto& current = song.channels[(std::size_t) channel];
  7088. if (genpresetui::isPresetFile (file))
  7089. {
  7090. if (const auto own = genpresetui::read (file); own && own->kind == current.instrument)
  7091. {
  7092. juce::String error;
  7093. if (! genpresetui::loadInto (engine, channel, file, error) && error.isNotEmpty())
  7094. showNote (error);
  7095. return;
  7096. }
  7097. }
  7098. else if (const auto path = file.getFullPathName().toStdString(); natives::presetKind (path, flStudioAccess()) == current.instrument)
  7099. {
  7100. if (auto loaded = natives::withPreset (current, path, file.getFileNameWithoutExtension().toStdString(), flStudioAccess()))
  7101. {
  7102. const auto kind = current.instrument;
  7103. engine.editSong ([channel, kind, c = std::move (*loaded)] (Song& s) {
  7104. if (channel < (int) s.channels.size() && s.channels[(std::size_t) channel].instrument == kind)
  7105. s.channels[(std::size_t) channel] = c;
  7106. });
  7107. }
  7108. else
  7109. showNote (tr ("This preset could not be read: {0}", { file.getFileNameWithoutExtension() }));
  7110. return;
  7111. }
  7112. }
  7113. }
  7114. switch (decide (item, selectedChannelKind(), focused))
  7115. {
  7116. case Action::sampleIntoSelected:
  7117. if (onLoadIntoChannel == nullptr || ! onLoadIntoChannel (file))
  7118. openFile (file);
  7119. return;
  7120. case Action::fontIntoSelected:
  7121. openSoundFontFile (engine, file, engine.getSelectedChannel());
  7122. return;
  7123. case Action::presetToFocusedPlugin:
  7124. {
  7125. juce::String message;
  7126. const auto ok = pluginpresetui::isFlPresetOfPlugin (file) ? pluginpresetui::applyFlPresetFromBrowser (engine, file, message)
  7127. : pluginpresetui::applyFromBrowser (engine, file, message);
  7128. if (! ok && message.isNotEmpty())
  7129. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin preset"), message);
  7130. return;
  7131. }
  7132. case Action::sampleNewChannel:
  7133. case Action::fontNewChannel:
  7134. case Action::generatorPresetChannel:
  7135. case Action::none: // (a plugin preset with no plugin to take it: what a double-click does, which says what to open)
  7136. if (item != Item::other)
  7137. openFile (file);
  7138. else
  7139. showNote (tr ("Select a channel or open a plugin window that can take this file"));
  7140. return;
  7141. case Action::replaceSelected:
  7142. case Action::newChannel:
  7143. case Action::effectToInsert: return; // (Plugin database entries: sendPluginToSelected)
  7144. }
  7145. }
  7146. void BrowserComponent::sendPluginToSelected (const std::function<std::optional<ChannelDef>()>& generator,
  7147. const std::function<std::optional<EffectSlot>()>& effect)
  7148. {
  7149. using namespace browsersend;
  7150. const auto action = decide (generator ? Item::generator : Item::effect, selectedChannelKind(), ! PluginWindows::openPlugins().empty());
  7151. if (action == Action::replaceSelected && generator)
  7152. {
  7153. // FL's Enter on a generator: it replaces the selected channel's (as hot-swap does, one undo step)
  7154. auto c = generator();
  7155. if (! c)
  7156. return;
  7157. const auto channel = engine.getSelectedChannel();
  7158. const auto target = hotswap::targetOfChannel (engine.getSong(), channel);
  7159. if (! target.active())
  7160. return;
  7161. if (onHotSwapWillReplaceInstrument != nullptr)
  7162. onHotSwapWillReplaceInstrument (channel);
  7163. engine.editSong ([target, c = std::move (*c)] (Song& song) mutable { hotswap::swapInstrument (song, target, std::move (c)); });
  7164. return;
  7165. }
  7166. if (action == Action::newChannel && generator)
  7167. {
  7168. if (auto c = generator(); c && onAddInstrument)
  7169. onAddInstrument (std::move (*c));
  7170. return;
  7171. }
  7172. if (effect)
  7173. if (auto fx = effect(); fx && onAddEffect)
  7174. onAddEffect (std::move (*fx));
  7175. }
  7176. void BrowserComponent::hoverRowForSnapshot (const juce::String& label)
  7177. {
  7178. auto& list = activeList();
  7179. for (int i = 0; i < list.numRows(); ++i)
  7180. if (list.shownName (i) == label)
  7181. {
  7182. list.setHovered (i);
  7183. return;
  7184. }
  7185. }
  7186. void BrowserComponent::showPreviewPlayedForSnapshot (const juce::File& file, double fromFraction)
  7187. {
  7188. strip->show (file, true, fromFraction, false);
  7189. }
  7190. void BrowserComponent::toggleStarredItem (const std::string& item)
  7191. {
  7192. if (! item.empty())
  7193. setInCollection (item, 0, ! collectionStore().has (item, 0));
  7194. }
  7195. juce::File BrowserComponent::prefsFile() const
  7196. {
  7197. return PluginHost::settingsFolder().getChildFile (role == Role::main ? "browser-prefs.txt" : "browser-prefs-samples.txt");
  7198. }
  7199. void BrowserComponent::loadPrefs()
  7200. {
  7201. if (! readPrefs)
  7202. return;
  7203. for (const auto& line : juce::StringArray::fromLines (prefsFile().loadFileAsString()))
  7204. {
  7205. const auto key = line.upToFirstOccurrenceOf ("=", false, false).trim();
  7206. const auto value = line.fromFirstOccurrenceOf ("=", false, false).trim();
  7207. if (key == "tab")
  7208. tab = juce::jlimit (0, tabCount - 1, value.getIntValue());
  7209. else if (key == "fullSamplePreview" && role == Role::main)
  7210. engine.setFullSamplePreview (value == "1");
  7211. else if (key == "tagsPanel")
  7212. tagsPanelShown = value == "1";
  7213. else if (key == "tagMatch")
  7214. matchMode = value == "all" ? browsertags::Match::all : browsertags::Match::any;
  7215. else if (key == "tag" && value.isNotEmpty())
  7216. picked.push_back (value.toStdString());
  7217. else if (key == "liveCategory")
  7218. liveSelection.category = (browserplaces::Category) juce::jlimit (0, (int) browserplaces::Category::collection, value.getIntValue());
  7219. else if (key == "liveCollection")
  7220. liveSelection.collection = value.getIntValue();
  7221. else if (key == "livePath")
  7222. liveSelection.path = value.toStdString();
  7223. else if (key == "loopsPanel") // (round gaps190kf)
  7224. loopsShown = value == "1" && role == Role::samples;
  7225. else if (key == "loopCategories")
  7226. loopCategoryMask = juce::jlimit (1, 7, value.getIntValue());
  7227. else if (key == "loopLayout")
  7228. loopLayoutState = loopkeys::Layout::fromText (value.replaceCharacter ('|', '\n').toStdString());
  7229. }
  7230. {
  7231. const auto shown = shownTags();
  7232. std::erase_if (picked, [&shown] (const std::string& t) { return ! shown.exists (t); });
  7233. }
  7234. if (! browserplaces::libraryAvailable (liveSelection.category) || liveSelection.category == browserplaces::Category::addFolder)
  7235. liveSelection = {};
  7236. }
  7237. void BrowserComponent::savePrefs() const
  7238. {
  7239. if (! readPrefs) // (--shots leave the user's file alone)
  7240. return;
  7241. juce::String text;
  7242. text << "tab=" << tab << "\n"
  7243. << "fullSamplePreview=" << (engine.isFullSamplePreview() ? 1 : 0) << "\n"
  7244. << "tagsPanel=" << (tagsPanelShown ? 1 : 0) << "\n"
  7245. << "tagMatch=" << (matchMode == browsertags::Match::all ? "all" : "any") << "\n"
  7246. << "liveCategory=" << (int) liveSelection.category << "\n"
  7247. << "liveCollection=" << liveSelection.collection << "\n"
  7248. << "livePath=" << juce::String::fromUTF8 (liveSelection.path.c_str()) << "\n"
  7249. << "loopsPanel=" << (loopsShown ? 1 : 0) << "\n"
  7250. << "loopCategories=" << loopCategoryMask << "\n";
  7251. if (loopLayoutState != loopkeys::Layout::defaults())
  7252. text << "loopLayout=" << juce::String::fromUTF8 (loopLayoutState.toText().c_str()).trimEnd().replaceCharacter ('\n', '|') << "\n";
  7253. for (const auto& t : picked)
  7254. text << "tag=" << juce::String::fromUTF8 (t.c_str()) << "\n";
  7255. prefsFile().getParentDirectory().createDirectory();
  7256. prefsFile().replaceWithText (text);
  7257. }
  7258. #include "ui/BrowserQol190qiParts.inc" // round 190qi: the parts that need the tree
  7259. #include "ui/LoopBrowserParts.inc" // round gaps190kf
  7260. } // namespace lynx