BrowserComponent.cpp 227 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341
  1. #include "ui/PluginPresetMenu.h"
  2. #include "ui/FileChoosers.h"
  3. #include "ui/QuickPick.h"
  4. #include "engine/FlStudio.h"
  5. #include "ui/BrowserComponent.h"
  6. #include "core/PluginDbFolder.h"
  7. #include "ui/AudioClipboard.h"
  8. #include "ui/SpeechDialog.h"
  9. #include "ui/UiTrace.h"
  10. #include "core/ControlSurface.h"
  11. #include "core/EffectPresets.h"
  12. #include "core/FlEffects.h"
  13. #include "core/PresetCycle.h"
  14. #include "ui/PluginHeader.h"
  15. #include "core/NativeEngines.h"
  16. #include "core/VoltageController.h"
  17. #include "core/FlpImport.h"
  18. #include "core/ProjectContents.h"
  19. #include "core/SearchIndex.h"
  20. #include "core/SearchQuery.h"
  21. #include "core/SearchService.h"
  22. #include "core/SampleFiles.h"
  23. #include "core/SampleSimilarity.h"
  24. #include "engine/SampleLibrary.h"
  25. #include "core/ValueMath.h"
  26. #include "core/Vfx.h"
  27. #include "platform/Paths.h"
  28. #include <mutex>
  29. #include "engine/PluginHost.h"
  30. #include "engine/Text.h"
  31. #include "ui/HintBar.h"
  32. #include "ui/I18n.h"
  33. #include "ui/Icons.h"
  34. #include "ui/PlaylistComponent.h"
  35. #include "ui/Theme.h"
  36. #include "ui/ValueControl.h"
  37. #include "ui/WaveformView.h"
  38. #include "ui/AudioEditor.h"
  39. #include "ui/AutomationUi.h"
  40. #include "ui/ChannelRackComponent.h"
  41. #include "ui/MixerComponent.h"
  42. #include "ui/SoundFontEditor.h"
  43. #include "ui/ToolWindow.h"
  44. namespace lynx
  45. {
  46. namespace
  47. {
  48. bool isAudio (const juce::File& f)
  49. {
  50. return SampleLibrary::isSampleFile (f);
  51. }
  52. bool isListed (const juce::File& f)
  53. {
  54. return f.hasFileExtension ("wav;flac;ogg;mp3;aif;aiff;wv;mid;midi;lynx;flp;als;flm;fst;sf2;sf3;sfz");
  55. }
  56. constexpr int maxResults = 500;
  57. constexpr int maxSimilar = 100; // "Find similar samples" lists the nearest 100
  58. juce::Array<juce::File> childrenOf (const juce::File& folder)
  59. {
  60. #if JUCE_MAC
  61. // JUCE's macOS iterator makes an NSURL of every entry to read its hidden flag, and a name NSString rejects
  62. // throws an Objective-C exception that ends the app (issue #42). readdir has no such step; names that are
  63. // not valid UTF-8 are skipped, the rest precomposed like JUCE does.
  64. // The listing itself is search::listFolderNames (JUCE-free, so the core tests run it on odd names).
  65. juce::Array<juce::File> children;
  66. for (const auto& name : search::listFolderNames (folder.getFullPathName().toStdString()))
  67. children.add (folder.getChildFile (juce::String::fromUTF8 (name.data(), (int) name.size()).convertToPrecomposedUnicode()));
  68. return children;
  69. #else
  70. return folder.findChildFiles (juce::File::findFilesAndDirectories, false, "*");
  71. #endif
  72. }
  73. search::FileSystem diskFileSystem()
  74. {
  75. search::FileSystem fs;
  76. fs.separator = juce::File::getSeparatorChar() == '\\' ? '\\' : '/';
  77. fs.folderTime = [] (const std::string& path) -> std::int64_t {
  78. const juce::File folder (juce::String::fromUTF8 (path.c_str()));
  79. return folder.isDirectory() ? folder.getLastModificationTime().toMilliseconds() : -1;
  80. };
  81. fs.list = [] (const std::string& path) {
  82. search::FolderListing listing;
  83. const juce::File folder (juce::String::fromUTF8 (path.c_str()));
  84. if (! folder.isDirectory())
  85. return listing;
  86. listing.exists = true;
  87. listing.time = folder.getLastModificationTime().toMilliseconds();
  88. auto children = childrenOf (folder);
  89. children.sort();
  90. for (const auto& c : children)
  91. {
  92. if (c.isDirectory())
  93. {
  94. // junctions and links (Windows' "My Music" inside Documents points back to itself) are not followed
  95. if (! c.isSymbolicLink())
  96. listing.subfolders.push_back (c.getFileName().toStdString());
  97. }
  98. else if (isListed (c))
  99. listing.files.push_back (c.getFileName().toStdString());
  100. }
  101. return listing;
  102. };
  103. return fs;
  104. }
  105. std::vector<std::string> toPaths (const juce::Array<juce::File>& folders)
  106. {
  107. std::vector<std::string> paths;
  108. for (const auto& f : folders)
  109. paths.push_back (f.getFullPathName().toStdString());
  110. return paths;
  111. }
  112. Icon iconFor (const juce::File& f, bool folder)
  113. {
  114. if (folder)
  115. return Icon::folder;
  116. if (isAudio (f))
  117. return Icon::audioFile;
  118. if (f.hasFileExtension ("mid;midi"))
  119. return Icon::pianoRoll;
  120. if (f.hasFileExtension ("lynx;flp;als;flm"))
  121. return Icon::project;
  122. if (f.hasFileExtension ("fst;sf2;sf3;sfz;lynxpreset;fxp;fxb;vstpreset"))
  123. return Icon::preset;
  124. return Icon::file;
  125. }
  126. // The hint for a file or folder row: what the mouse can do with it.
  127. juce::String rowHint (const juce::File& f, bool folder, bool expanded)
  128. {
  129. if (folder)
  130. return (expanded ? tr ("Folder: [LMB] close") : tr ("Folder: [LMB] open")) + " " + tr ("[RMB] menu (collapse all, show in the file manager)");
  131. if (isAudio (f))
  132. return tr ("Sample: [LMB] preview [2xLMB] new channel drag to the Channel Rack or the Playlist [Enter] into the selected channel "
  133. "[Shift][Up] / [Shift][Down] swap through the files");
  134. if (f.hasFileExtension ("mid;midi"))
  135. return tr ("MIDI file: [2xLMB] open it as a project");
  136. if (f.hasFileExtension ("lynx;flp;als;flm"))
  137. return tr ("Project: [2xLMB] open it");
  138. if (f.hasFileExtension ("lynxtrack") || (f.hasFileExtension ("fst") && f.getFullPathName().containsIgnoreCase ("Mixer presets")))
  139. 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)");
  140. if (f.hasFileExtension ("fst"))
  141. return tr ("Preset: [2xLMB] new channel with it (FL synth presets) drag onto a mixer insert: effect preset");
  142. if (f.hasFileExtension ("lynxpreset;fxp;fxb;vstpreset"))
  143. return tr ("Plugin preset: [2xLMB] load it into its plugin (an open plugin window, or the selected channel's plugin)");
  144. if (f.hasFileExtension ("sfz"))
  145. return tr ("SFZ instrument: [LMB] preview [2xLMB] new LYNX Soundfont channel (or into the selected one) drag to the Channel Rack");
  146. if (f.hasFileExtension ("sf2;sf3;sfz"))
  147. return tr ("SoundFont: [LMB] preview its first preset [2xLMB] new LYNX Soundfont channel (or into the selected one) drag to the Channel Rack");
  148. return {};
  149. }
  150. // A user / channel colour made readable as text and icons on the Browser's dark rows.
  151. juce::Colour readable (juce::Colour c)
  152. {
  153. return c.withMultipliedSaturation (0.8f).withBrightness (juce::jlimit (0.72f, 0.92f, c.getBrightness() + 0.15f));
  154. }
  155. // The Current project's sections, in FL's order (REA_rodada115).
  156. enum class Category
  157. {
  158. history,
  159. patterns,
  160. effects,
  161. generators,
  162. automation,
  163. initialized, // FL's "Initialized controls" (REA round 146)
  164. samples
  165. };
  166. constexpr Category categories[] = { Category::history, Category::patterns, Category::effects, Category::generators,
  167. Category::automation, Category::initialized, Category::samples };
  168. juce::String categoryName (Category c)
  169. {
  170. switch (c)
  171. {
  172. case Category::history: return tr ("History");
  173. case Category::patterns: return tr ("Patterns");
  174. case Category::effects: return tr ("Effects");
  175. case Category::generators: return tr ("Generators");
  176. case Category::automation: return tr ("Automation");
  177. case Category::initialized: return tr ("Initialized controls");
  178. case Category::samples: return tr ("Audio files");
  179. }
  180. return {};
  181. }
  182. juce::String categoryHint (Category c)
  183. {
  184. switch (c)
  185. {
  186. case Category::history: return tr ("Undo history of this project: [LMB] go back to that step");
  187. case Category::patterns: return tr ("Patterns of this project, in their colours");
  188. case Category::effects: return tr ("Effects in use, with the insert they sit on");
  189. case Category::generators: return tr ("Generators in use (the Channel Rack's channels), with the insert they play into");
  190. case Category::automation: return tr ("Automation clips of this project");
  191. case Category::initialized: return tr ("Initialized controls: to be reset when the song starts (a control's menu > Init song with this position)");
  192. case Category::samples: return tr ("Audio files used by this project (samples, audio clips), in the colour of the channel that plays them");
  193. }
  194. return {};
  195. }
  196. Icon categoryIcon (Category c)
  197. {
  198. switch (c)
  199. {
  200. case Category::history: return Icon::undo;
  201. case Category::patterns: return Icon::pattern;
  202. case Category::effects: return Icon::mixer;
  203. case Category::generators: return Icon::keyboard;
  204. case Category::automation: return Icon::automate;
  205. case Category::initialized: return Icon::automate;
  206. case Category::samples: return Icon::audioFile;
  207. }
  208. return Icon::folder;
  209. }
  210. // Each top-level folder has its own colour (FL colours its Browser's folders by kind; LYNX uses its own set).
  211. juce::Colour rootColour (int index)
  212. {
  213. static const juce::Colour colours[] = { juce::Colour (0xff6ea8fe), juce::Colour (0xff3ddc84), juce::Colour (0xffe58fd0),
  214. juce::Colour (0xffb39ddb), juce::Colour (0xffb39ddb), juce::Colour (0xfff5b942),
  215. juce::Colour (0xff4cc9c0), juce::Colour (0xfff2a65a), juce::Colour (0xff9fb7d0) };
  216. return index >= 0 && index < (int) std::size (colours) ? colours[index] : juce::Colour (0xff8fd18c);
  217. }
  218. } // namespace
  219. namespace
  220. {
  221. // The plugin being dragged from the Plugin database (one drag at a time; message thread).
  222. struct DraggedPlugin
  223. {
  224. std::function<std::optional<ChannelDef>()> generator;
  225. std::function<std::optional<EffectSlot>()> effect;
  226. };
  227. DraggedPlugin& draggedPlugin()
  228. {
  229. static DraggedPlugin d;
  230. return d;
  231. }
  232. } // namespace
  233. // --- search: the process's search worker ------------------------------------------------------------
  234. // The Browser's search index and its worker (core/SearchService.h, round 162): one per process while a Browser exists,
  235. // the index kept in the settings folder between sessions. Its news reach the Browsers through two broadcasters (they
  236. // are thread-safe and coalesce); the worker is joined (never killed) before they go.
  237. struct BrowserComponent::SearchShared
  238. {
  239. juce::ChangeBroadcaster statusChanged, indexChanged;
  240. std::unique_ptr<search::Service> service; // (last: goes first)
  241. ~SearchShared() { service.reset(); }
  242. static juce::File file() { return platform::settingsFile ("browser-index.txt"); }
  243. static std::shared_ptr<SearchShared> get()
  244. {
  245. static std::weak_ptr<SearchShared> current; // (message thread)
  246. if (auto s = current.lock())
  247. return s;
  248. auto s = std::make_shared<SearchShared>();
  249. search::Service::Callbacks cb;
  250. cb.load = [] {
  251. const auto f = file();
  252. juce::MemoryBlock data;
  253. if (! f.existsAsFile() || f.getSize() > 256 * 1024 * 1024 || ! f.loadFileAsData (data))
  254. return std::string();
  255. return std::string (static_cast<const char*> (data.getData()), data.getSize());
  256. };
  257. cb.save = [] (const std::string& text) {
  258. const auto f = file();
  259. const auto temp = f.getSiblingFile (f.getFileName() + ".tmp");
  260. if (temp.replaceWithData (text.data(), text.size()))
  261. temp.moveFileTo (f);
  262. };
  263. cb.statusChanged = [raw = s.get()] { raw->statusChanged.sendChangeMessage(); };
  264. cb.indexChanged = [raw = s.get()] { raw->indexChanged.sendChangeMessage(); };
  265. s->service = std::make_unique<search::Service> (diskFileSystem(), std::move (cb));
  266. current = s;
  267. return s;
  268. }
  269. };
  270. // "Find similar samples" (round 190as): the analysis of the Browser's samples and its worker (core/SampleSimilarity.h),
  271. // one per process while a Browser exists, the index kept in the settings folder between sessions. The worker has the
  272. // lowest priority, rests as long as it works and waits while LYNX plays, records or renders.
  273. struct BrowserComponent::SimilarShared
  274. {
  275. juce::ChangeBroadcaster statusChanged;
  276. SampleLibrary library; // its own readers: nothing goes into the engine's sample cache
  277. std::unique_ptr<similarity::Service> service; // (last: goes first)
  278. bool passAsked = false; // the background pass was started in this session (message thread)
  279. ~SimilarShared() { service.reset(); }
  280. static juce::File file() { return platform::settingsFile ("browser-similar.idx"); }
  281. static std::shared_ptr<SimilarShared> get (AudioEngine& engine)
  282. {
  283. static std::weak_ptr<SimilarShared> current; // (message thread)
  284. if (auto s = current.lock())
  285. return s;
  286. auto s = std::make_shared<SimilarShared>();
  287. similarity::Service::Callbacks cb;
  288. cb.fs = diskFileSystem();
  289. cb.stat = [] (const std::string& path, std::int64_t& size, std::int64_t& time) {
  290. const juce::File f (juce::String::fromUTF8 (path.c_str()));
  291. if (! f.existsAsFile())
  292. return false;
  293. size = f.getSize();
  294. time = f.getLastModificationTime().toMilliseconds();
  295. return true;
  296. };
  297. cb.decode = [raw = s.get()] (const std::string& path, double seconds, std::vector<float>& mono, double& rate) {
  298. return raw->library.readMono (juce::File (juce::String::fromUTF8 (path.c_str())), seconds, mono, rate);
  299. };
  300. cb.accepts = [] (const std::string& name) {
  301. const auto dot = name.find_last_of ('.');
  302. if (dot == std::string::npos)
  303. return false;
  304. const auto extension = name.substr (dot + 1);
  305. return isSampleExtension (extension) && extension.size() != 6; // (not .speech: it has no audio of its own)
  306. };
  307. cb.load = [] {
  308. const auto f = file();
  309. juce::MemoryBlock data;
  310. if (! f.existsAsFile() || f.getSize() > 64 * 1024 * 1024 || ! f.loadFileAsData (data))
  311. return std::string();
  312. return std::string (static_cast<const char*> (data.getData()), data.getSize());
  313. };
  314. cb.save = [] (const std::string& bytes) {
  315. const auto f = file();
  316. const auto temp = f.getSiblingFile (f.getFileName() + ".tmp");
  317. if (temp.replaceWithData (bytes.data(), bytes.size()))
  318. temp.moveFileTo (f);
  319. };
  320. cb.statusChanged = [raw = s.get()] { raw->statusChanged.sendChangeMessage(); };
  321. // (the engine outlives every Browser; these are atomics)
  322. cb.shouldPause = [&engine] { return engine.bounceStillPlaying() || engine.isRecording() || AudioEngine::offlineRendersRunning().load() > 0; };
  323. s->service = std::make_unique<similarity::Service> (std::move (cb));
  324. current = s;
  325. return s;
  326. }
  327. };
  328. // A click anywhere outside the search box (another panel, the toolbar, the Browser's own list) takes the keyboard
  329. // back from it, so Space plays / stops again (issue #9; FL ends typing in its search field the same way).
  330. class BrowserComponent::FocusWatcher final : public juce::MouseListener
  331. {
  332. public:
  333. explicit FocusWatcher (BrowserComponent& b) : browser (b) { juce::Desktop::getInstance().addGlobalMouseListener (this); }
  334. ~FocusWatcher() override { juce::Desktop::getInstance().removeGlobalMouseListener (this); }
  335. void mouseDown (const juce::MouseEvent& e) override
  336. {
  337. auto* clicked = e.eventComponent;
  338. if (! browser.isTypingInSearch() || clicked == nullptr)
  339. return;
  340. if (clicked == &browser.searchBox || browser.searchBox.isParentOf (clicked))
  341. return;
  342. // a menu (the box's own right-click menu: Paste...) keeps it
  343. if (clicked->getTopLevelComponent() != browser.getTopLevelComponent() && clicked->getTopLevelComponent()->isAlwaysOnTop()
  344. && dynamic_cast<juce::ResizableWindow*> (clicked->getTopLevelComponent()) == nullptr)
  345. return;
  346. browser.leaveSearchBox();
  347. }
  348. private:
  349. BrowserComponent& browser;
  350. };
  351. // --- the tree (and, flat, the search results) ---------------------------------------------------------
  352. class BrowserComponent::FileTree final : public juce::Component,
  353. public ui::HintSource,
  354. public juce::FileDragAndDropTarget
  355. {
  356. public:
  357. static constexpr int rowHeight = 22;
  358. FileTree (BrowserComponent& b, bool isFlat) : browser (b), flat (isFlat)
  359. {
  360. setWantsKeyboardFocus (false);
  361. setMouseClickGrabsKeyboardFocus (false);
  362. }
  363. enum class Kind
  364. {
  365. fsFolder, // a folder on disk (top-level ones carry their own name and colour)
  366. file, // a file on disk
  367. project, // "Current project"
  368. category, // one of its sections
  369. item, // something of the project (pattern, sample, generator, effect, automation clip, undo step)
  370. plugins, // the Plugin database and its folders (round 142): built-in, FL engines, installed plugins
  371. plugin, // one of its plugins (double-click adds it)
  372. collection // a collection's heading in the STARRED tab (round 190ce): its items are its children
  373. };
  374. struct Node
  375. {
  376. Kind kind = Kind::file;
  377. juce::File file;
  378. juce::Array<juce::File> also; // fsFolder: more folders listed as this one (a merged root and its shared subfolders, round 178a)
  379. bool folder = false, expanded = false, loaded = false;
  380. int depth = 0;
  381. Node* parent = nullptr;
  382. std::vector<std::unique_ptr<Node>> children;
  383. juce::String label, detail; // display name (empty: the file's) and the dimmed detail after it
  384. juce::Colour colour; // transparent: the default
  385. Icon icon = Icon::none; // none: by file type
  386. Category category = Category::samples;
  387. projectcontents::Item item; // kind == item (history: item.index = the step)
  388. bool history = false, missing = false, current = false;
  389. bool initial = false; // an initialized control (item.index = into Song::initialValues)
  390. std::function<void()> activate; // kind == plugin: adds it
  391. // kind == plugin: what it adds (one of them), also when it is dragged (round 162)
  392. std::function<std::optional<ChannelDef>()> generator;
  393. std::function<std::optional<EffectSlot>()> effect;
  394. std::string pluginKey; // kind == plugin: what a user name is stored under (ui/QuickPick.h, issue #11)
  395. juce::String original; // kind == plugin: the name before the user renamed it
  396. // round 166f (issue #16): kind == plugins — 0 the Effects folder or one of the user's effect folders, 1 the
  397. // Generators' (-1 the other database folders); userFolder = the user's folder path ("" = Effects / Generators)
  398. int folderKind = -1;
  399. std::string userFolder;
  400. // round 190bj (issue B4): LYNX's own groups under Effects / Generators — the format folder of their Installed
  401. // entries ("LYNX", "FL engines", "VFX"; "" = Installed itself), core/PluginDbFolder.h groupFolder()
  402. std::string group;
  403. bool isGroup = false;
  404. int collection = -1; // kind == collection: which one (0 = Starred)
  405. };
  406. // What a row is to the collections (core/BrowserCollections.h): a file's or folder's path, a Plugin database
  407. // entry's key; empty = a row that can't be in one (the project's items, headings).
  408. static std::string itemOf (const Node& n)
  409. {
  410. if (n.kind == Kind::plugin)
  411. return n.pluginKey.empty() ? std::string() : collections::pluginItem (n.pluginKey);
  412. if ((n.kind == Kind::file || n.kind == Kind::fsFolder) && n.file != juce::File())
  413. return n.file.getFullPathName().toStdString();
  414. return {};
  415. }
  416. std::string selectedItem() const { return juce::isPositiveAndBelow (selected, (int) rows.size()) ? itemOf (*rows[(std::size_t) selected]) : std::string(); }
  417. const Node* selectedNode() const { return juce::isPositiveAndBelow (selected, (int) rows.size()) ? rows[(std::size_t) selected] : nullptr; }
  418. juce::String selectedLabel() const
  419. {
  420. const auto* n = selectedNode();
  421. return n == nullptr ? juce::String() : n->label.isNotEmpty() ? n->label : n->file.getFileName();
  422. }
  423. static std::unique_ptr<Node> makeCollection (int collection, int itemCount, bool open)
  424. {
  425. auto n = std::make_unique<Node>();
  426. n->kind = Kind::collection;
  427. n->collection = collection;
  428. n->folder = n->loaded = true;
  429. n->expanded = open;
  430. n->label = BrowserComponent::collectionName (collection);
  431. n->detail = juce::String (itemCount);
  432. n->colour = BrowserComponent::collectionColour (collection);
  433. return n;
  434. }
  435. // A Plugin database entry outside the database's tree (a collection's item): the same row, double-click and drag.
  436. static std::unique_ptr<Node> makePluginItem (BrowserComponent& browser, const std::string& key)
  437. {
  438. auto safe = juce::Component::SafePointer<BrowserComponent> (&browser);
  439. for (int generators = 1; generators >= 0; --generators)
  440. {
  441. auto n = std::make_unique<Node>();
  442. n->kind = Kind::plugin;
  443. n->pluginKey = key;
  444. if (generators == 1)
  445. {
  446. for (auto& e : quickpick::generatorEntries (browser.engine))
  447. if (e.key == key)
  448. {
  449. n->label = quickpick::shownName (browser.engine, e.key, e.label);
  450. n->original = e.label;
  451. n->detail = e.detail;
  452. n->icon = e.folder == 3 ? Icon::plugin : Icon::keyboard;
  453. n->generator = e.make;
  454. n->activate = [safe, make = e.make] {
  455. if (auto c = make(); c && safe != nullptr && safe->onAddInstrument)
  456. safe->onAddInstrument (std::move (*c));
  457. };
  458. return n;
  459. }
  460. }
  461. else
  462. for (auto& e : quickpick::effectEntries (browser.engine))
  463. if (e.key == key)
  464. {
  465. n->label = quickpick::shownName (browser.engine, e.key, e.label);
  466. n->original = e.label;
  467. n->detail = e.detail;
  468. n->icon = e.folder == 3 ? Icon::plugin : Icon::mixer;
  469. n->effect = e.make;
  470. n->activate = [safe, make = e.make] {
  471. if (auto fx = make(); fx && safe != nullptr && safe->onAddEffect)
  472. safe->onAddEffect (std::move (*fx));
  473. };
  474. return n;
  475. }
  476. }
  477. return nullptr; // (the plugin is not installed any more: the collection leaves it out)
  478. }
  479. // tree mode: the given top-level nodes
  480. void setTopLevel (std::vector<std::unique_ptr<Node>> nodes)
  481. {
  482. root = std::make_unique<Node>();
  483. root->kind = Kind::fsFolder;
  484. root->folder = root->expanded = root->loaded = true;
  485. root->depth = -1;
  486. for (auto& n : nodes)
  487. {
  488. n->parent = root.get();
  489. n->depth = 0;
  490. if (n->kind == Kind::collection) // (its items came with it)
  491. for (auto& c : n->children)
  492. {
  493. c->parent = n.get();
  494. c->depth = 1;
  495. }
  496. if (n->expanded)
  497. load (*n);
  498. root->children.push_back (std::move (n));
  499. }
  500. selected = hovered = -1;
  501. rebuild();
  502. }
  503. static std::unique_ptr<Node> makeFolder (const juce::File& folder, const juce::String& label, juce::Colour colour)
  504. {
  505. auto n = std::make_unique<Node>();
  506. n->kind = Kind::fsFolder;
  507. n->file = folder;
  508. n->folder = true;
  509. n->label = label;
  510. n->colour = colour;
  511. return n;
  512. }
  513. // round 166f (issue #16): the user's folders of one kind (FL's Plugin database folders) as nodes under `kindNode`,
  514. // parents before children; the map gives each path's node
  515. template <typename MakeFolder>
  516. static std::map<std::string, Node*> userFolderNodes (Node& kindNode, bool instruments, MakeFolder& folder, AudioEngine& engine)
  517. {
  518. std::map<std::string, Node*> out;
  519. for (const auto& path : engine.getPluginHost().databaseFolders().kind (instruments)) // (a std::set: "A" before "A/B")
  520. {
  521. const auto parentPath = plugincatalog::parentFolder (path);
  522. auto* parent = parentPath.empty() ? &kindNode : (out.count (parentPath) ? out[parentPath] : nullptr);
  523. if (parent == nullptr) continue;
  524. auto n = folder (parent, juce::String::fromUTF8 (plugincatalog::folderLeaf (path).c_str()), Icon::folder);
  525. n->folderKind = instruments ? 1 : 0;
  526. n->userFolder = path;
  527. n->colour = theme::colour::info;
  528. out[path] = n.get();
  529. parent->children.push_back (std::move (n));
  530. }
  531. return out;
  532. }
  533. static Node* userFolderOf (const std::map<std::string, Node*>& nodes, AudioEngine& engine, bool instruments, const std::string& key)
  534. {
  535. const auto& folders = engine.getPluginHost().databaseFolders();
  536. const auto it = folders.of.find (key);
  537. if (it == folders.of.end() || ! folders.kind (instruments).count (it->second)) return nullptr;
  538. const auto n = nodes.find (it->second);
  539. return n != nodes.end() ? n->second : nullptr;
  540. }
  541. // subfolders first, then the plugins, each A-Z
  542. static void sortFolder (Node& n)
  543. {
  544. std::stable_sort (n.children.begin(), n.children.end(), [] (const auto& a, const auto& b) {
  545. if (a->folder != b->folder) return a->folder;
  546. return a->label.compareNatural (b->label) < 0;
  547. });
  548. }
  549. // FL's "Plugin database", interpreted (round 142, issue #5): Generators and Effects, each with LYNX's built-in ones,
  550. // FL's engines (those the user's FL installation provides) and the installed VST3 / CLAP plugins
  551. static std::unique_ptr<Node> makePluginDatabase (BrowserComponent& browser, const std::set<juce::String>& open)
  552. {
  553. auto folder = [&open] (Node* parent, const juce::String& label, Icon icon) {
  554. auto n = std::make_unique<Node>();
  555. n->kind = Kind::plugins;
  556. n->folder = n->loaded = true;
  557. n->label = label;
  558. n->icon = icon;
  559. n->parent = parent;
  560. n->depth = parent != nullptr ? parent->depth + 1 : 0;
  561. n->expanded = open.count ((parent != nullptr && parent->kind == Kind::plugins ? parent->label + "/" : juce::String()) + label) > 0;
  562. return n;
  563. };
  564. auto node = [] (Node& parent, const juce::String& label, const juce::String& detail, Icon icon) -> Node& {
  565. auto n = std::make_unique<Node>();
  566. n->kind = Kind::plugin;
  567. n->label = label;
  568. n->detail = detail;
  569. n->icon = icon;
  570. n->parent = &parent;
  571. n->depth = parent.depth + 1;
  572. parent.children.push_back (std::move (n));
  573. return *parent.children.back();
  574. };
  575. quickpick::refreshPluginDatabase (browser.engine); // (the folders as they are on disk now: issue #104)
  576. auto root = folder (nullptr, tr ("Plugin database"), Icon::plugin);
  577. root->colour = theme::colour::info;
  578. auto safe = juce::Component::SafePointer<BrowserComponent> (&browser);
  579. // a generator / an effect: double-click adds it (to the rack / the selected insert), or drag it there
  580. auto generatorEntry = [&node, safe] (Node& parent, const juce::String& label, const juce::String& detail, Icon icon,
  581. std::function<std::optional<ChannelDef>()> make) {
  582. auto& n = node (parent, label, detail, icon);
  583. n.generator = make;
  584. n.activate = [safe, make] {
  585. if (auto c = make(); c && safe != nullptr && safe->onAddInstrument)
  586. safe->onAddInstrument (std::move (*c));
  587. };
  588. };
  589. auto effectEntry = [&node, safe] (Node& parent, const juce::String& label, const juce::String& detail, Icon icon,
  590. std::function<std::optional<EffectSlot>()> make) {
  591. auto& n = node (parent, label, detail, icon);
  592. n.effect = make;
  593. n.activate = [safe, make] {
  594. if (auto fx = make(); fx && safe != nullptr && safe->onAddEffect)
  595. safe->onAddEffect (std::move (*fx));
  596. };
  597. };
  598. // the entries (ui/QuickPick.h), each under the name the user gave it (issue #11: FL's renamed plugins, "1_EQ"),
  599. // sorted by that name in each folder
  600. auto& engine = browser.engine;
  601. auto named = [&engine] (const std::string& key, const juce::String& label) { return quickpick::shownName (engine, key, label); };
  602. auto byLabel = [] (Node& folderNode) {
  603. std::stable_sort (folderNode.children.begin(), folderNode.children.end(),
  604. [] (const auto& a, const auto& b) { return a->label.compareNatural (b->label) < 0; });
  605. };
  606. // Generators
  607. {
  608. auto gens = folder (root.get(), tr ("Generators"), Icon::keyboard);
  609. auto lynxGens = folder (gens.get(), "LYNX SHARE", Icon::folder);
  610. auto flGens = folder (gens.get(), tr ("FL engines"), Icon::folder);
  611. // FL's VFX note processors (round 164b): channels with no sound, they play other channels / Patcher nodes
  612. auto vfxGens = folder (gens.get(), tr ("VFX (note effects)"), Icon::folder);
  613. auto installed = folder (gens.get(), tr ("Installed"), Icon::folder);
  614. Node* folders[] = { lynxGens.get(), flGens.get(), vfxGens.get(), installed.get() };
  615. gens->folderKind = 1;
  616. for (auto [node, group] : { std::pair { folders[0], "LYNX" }, std::pair { folders[1], "FL engines" }, std::pair { folders[2], "VFX" },
  617. std::pair { folders[3], "" } })
  618. {
  619. node->group = group;
  620. node->isGroup = true;
  621. }
  622. const auto mine = userFolderNodes (*gens, true, folder, engine); // round 166f: the user's folders first
  623. for (auto& e : quickpick::generatorEntries (engine))
  624. {
  625. auto* target = userFolderOf (mine, engine, true, e.key);
  626. if (target == nullptr) target = folders[juce::jlimit (0, 3, e.folder)];
  627. generatorEntry (*target, named (e.key, e.label), e.detail, e.folder == 3 ? Icon::plugin : Icon::keyboard, e.make);
  628. target->children.back()->pluginKey = e.key;
  629. target->children.back()->original = e.label;
  630. }
  631. for (auto& [path, n] : mine) sortFolder (*n);
  632. for (auto* f : { &lynxGens, &flGens, &vfxGens, &installed })
  633. if (! (*f)->children.empty())
  634. {
  635. byLabel (**f);
  636. gens->children.push_back (std::move (*f));
  637. }
  638. root->children.push_back (std::move (gens));
  639. }
  640. // Effects
  641. {
  642. auto fxs = folder (root.get(), tr ("Effects"), Icon::mixer);
  643. auto lynxFx = folder (fxs.get(), "LYNX SHARE", Icon::folder);
  644. auto flFx = folder (fxs.get(), tr ("FL engines"), Icon::folder);
  645. auto installed = folder (fxs.get(), tr ("Installed"), Icon::folder);
  646. Node* folders[] = { lynxFx.get(), flFx.get(), installed.get(), installed.get() };
  647. fxs->folderKind = 0;
  648. for (auto [node, group] : { std::pair { folders[0], "LYNX" }, std::pair { folders[1], "FL engines" }, std::pair { folders[2], "" } })
  649. {
  650. node->group = group;
  651. node->isGroup = true;
  652. }
  653. const auto mine = userFolderNodes (*fxs, false, folder, engine); // round 166f: the user's folders first
  654. for (auto& e : quickpick::effectEntries (engine))
  655. {
  656. auto* target = userFolderOf (mine, engine, false, e.key);
  657. if (target == nullptr) target = folders[juce::jlimit (0, 3, e.folder)];
  658. effectEntry (*target, named (e.key, e.label), e.detail, e.folder == 3 ? Icon::plugin : Icon::mixer, e.make);
  659. target->children.back()->pluginKey = e.key;
  660. target->children.back()->original = e.label;
  661. }
  662. for (auto& [path, n] : mine) sortFolder (*n);
  663. for (auto* f : { &lynxFx, &flFx, &installed })
  664. if (! (*f)->children.empty())
  665. {
  666. byLabel (**f);
  667. fxs->children.push_back (std::move (*f));
  668. }
  669. root->children.push_back (std::move (fxs));
  670. }
  671. // (the counts, dimmed after each folder)
  672. std::function<int (Node&)> count = [&count] (Node& n) {
  673. int total = 0;
  674. for (auto& c : n.children)
  675. total += c->kind == Kind::plugin ? 1 : count (*c);
  676. if (n.kind == Kind::plugins)
  677. n.detail = juce::String (total);
  678. return total;
  679. };
  680. count (*root);
  681. return root;
  682. }
  683. static std::unique_ptr<Node> makeProject (bool open)
  684. {
  685. auto n = std::make_unique<Node>();
  686. n->kind = Kind::project;
  687. n->folder = true;
  688. n->expanded = open;
  689. n->label = tr ("Current project");
  690. n->icon = Icon::project;
  691. n->colour = theme::colour::accent;
  692. return n;
  693. }
  694. // flat mode: a list of files with their path relative to the folder searched that holds them
  695. // (`details`: the dimmed text after each name, e.g. how similar the file is; round 190as)
  696. void setFiles (const juce::Array<juce::File>& files, const juce::Array<juce::File>& newBases, const juce::String& newStatus,
  697. const juce::StringArray& details = {})
  698. {
  699. bases = newBases;
  700. status = newStatus;
  701. flatNodes.clear();
  702. for (const auto& f : files)
  703. {
  704. auto n = std::make_unique<Node>();
  705. n->file = f;
  706. n->detail = details[(int) flatNodes.size()];
  707. flatNodes.push_back (std::move (n));
  708. }
  709. selected = hovered = -1;
  710. rebuild();
  711. }
  712. // flat mode: project items (the PROJECT tab's search)
  713. void setNodes (std::vector<std::unique_ptr<Node>> nodes, const juce::String& newStatus)
  714. {
  715. bases.clear();
  716. status = newStatus;
  717. flatNodes = std::move (nodes);
  718. selected = hovered = -1;
  719. rebuild();
  720. }
  721. void setStatus (const juce::String& text)
  722. {
  723. status = text;
  724. repaint();
  725. }
  726. // Removes the folders on disk `drop` takes (round 164: the content filter found them empty), keeping what is open
  727. // and selected. False when nothing went.
  728. bool pruneFolders (const std::function<bool (const juce::File&)>& drop)
  729. {
  730. if (flat || root == nullptr)
  731. return false;
  732. auto* keep = juce::isPositiveAndBelow (selected, (int) rows.size()) ? rows[(std::size_t) selected] : nullptr;
  733. bool removed = false, lostSelection = false;
  734. std::function<void (Node&)> walk = [&] (Node& n) {
  735. for (auto it = n.children.begin(); it != n.children.end();)
  736. {
  737. auto& c = **it;
  738. if (c.kind == Kind::fsFolder && drop (c.file) && std::all_of (c.also.begin(), c.also.end(), drop))
  739. {
  740. for (auto* s = keep; s != nullptr; s = s->parent)
  741. lostSelection = lostSelection || s == &c;
  742. it = n.children.erase (it);
  743. removed = true;
  744. continue;
  745. }
  746. if (c.kind == Kind::fsFolder && c.loaded)
  747. walk (c);
  748. ++it;
  749. }
  750. };
  751. walk (*root);
  752. if (! removed)
  753. return false;
  754. rebuild();
  755. selected = -1;
  756. if (! lostSelection)
  757. for (int i = 0; i < (int) rows.size(); ++i)
  758. if (rows[(std::size_t) i] == keep)
  759. selected = i;
  760. hovered = -1;
  761. return true;
  762. }
  763. juce::File selectedFile() const
  764. {
  765. return juce::isPositiveAndBelow (selected, (int) rows.size()) ? rows[(std::size_t) selected]->file : juce::File();
  766. }
  767. // the top-level folder on disk that holds the selection (none: the selection is not a file)
  768. juce::File selectedRoot() const
  769. {
  770. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  771. return {};
  772. for (auto* n = rows[(std::size_t) selected]; n != nullptr; n = n->parent)
  773. if (n->kind == Kind::fsFolder && n->depth == 0)
  774. return n->file;
  775. return {};
  776. }
  777. bool selectedIsFolder() const { return juce::isPositiveAndBelow (selected, (int) rows.size()) && rows[(std::size_t) selected]->folder; }
  778. int numRows() const { return (int) rows.size(); }
  779. int getSelectedRow() const { return selected; }
  780. void select (int row, bool preview)
  781. {
  782. row = rows.empty() ? -1 : juce::jlimit (0, (int) rows.size() - 1, row);
  783. if (row != selected)
  784. {
  785. repaintRow (selected);
  786. selected = row;
  787. repaintRow (selected);
  788. }
  789. scrollToRow (row);
  790. if (row >= 0)
  791. browser.fileSelected (rows[(std::size_t) row]->file, preview && ! rows[(std::size_t) row]->folder);
  792. }
  793. // Left / Right: close the selected folder (or go to its parent) / open it
  794. void openSelected (bool open)
  795. {
  796. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  797. return;
  798. auto* n = rows[(std::size_t) selected];
  799. if (n->folder && n->expanded != open)
  800. {
  801. toggle (*n);
  802. return;
  803. }
  804. if (! open && n->parent != nullptr && n->parent != root.get())
  805. for (int i = 0; i < (int) rows.size(); ++i)
  806. if (rows[(std::size_t) i] == n->parent)
  807. {
  808. select (i, false);
  809. return;
  810. }
  811. }
  812. void collapseAll()
  813. {
  814. if (root == nullptr)
  815. return;
  816. std::function<void (Node&)> close = [&close] (Node& n) {
  817. for (auto& c : n.children)
  818. {
  819. c->expanded = false;
  820. close (*c);
  821. }
  822. };
  823. close (*root);
  824. selected = hovered = -1;
  825. rebuild();
  826. }
  827. void expandAll (Node& n)
  828. {
  829. n.expanded = true;
  830. load (n);
  831. if (n.kind == Kind::project || n.kind == Kind::category)
  832. for (auto& c : n.children)
  833. if (c->folder && c->kind != Kind::fsFolder)
  834. expandAll (*c);
  835. rebuild();
  836. }
  837. // FL's folder "Expand all": the folder and its sub-folders open (on disk: down to `depth` levels, so a big
  838. // library is not scanned at once)
  839. // --snapshot: opens the top-level folder `f` and its sub-folders (round 164)
  840. void expandTop (const juce::File& f, int depth)
  841. {
  842. if (root != nullptr)
  843. for (auto& c : root->children)
  844. if (c->kind == Kind::fsFolder && c->file == f)
  845. expandFolder (*c, depth);
  846. }
  847. // Opens the folders down to `file` (a file or folder under one of the top-level folders) and returns its row, or
  848. // -1 when no folder shown here holds it (round 190ce: hot-swap shows the linked sample, "Show in its folder").
  849. int revealFile (const juce::File& file)
  850. {
  851. if (root == nullptr || flat)
  852. return -1;
  853. for (auto& top : root->children)
  854. {
  855. if (top->kind != Kind::fsFolder)
  856. continue;
  857. juce::Array<juce::File> bases { top->file };
  858. bases.addArray (top->also);
  859. const auto holds = [&file] (const juce::File& folder) { return folder.isDirectory() && (file == folder || file.isAChildOf (folder)); };
  860. if (std::none_of (bases.begin(), bases.end(), holds))
  861. continue;
  862. auto* node = top.get();
  863. for (int guard = 0; guard < 64 && node != nullptr; ++guard)
  864. {
  865. node->expanded = true;
  866. load (*node);
  867. Node* next = nullptr;
  868. for (auto& c : node->children)
  869. if (c->file == file)
  870. {
  871. rebuild();
  872. return rowOfFile (file);
  873. }
  874. else if (c->folder && file.isAChildOf (c->file))
  875. next = c.get();
  876. node = next;
  877. }
  878. rebuild();
  879. }
  880. return -1;
  881. }
  882. void expandFolder (Node& n, int depth)
  883. {
  884. n.expanded = true;
  885. load (n);
  886. if (depth > 1)
  887. for (auto& c : n.children)
  888. if (c->folder)
  889. expandFolder (*c, depth - 1);
  890. rebuild();
  891. }
  892. void rebuild()
  893. {
  894. rows.clear();
  895. if (flat)
  896. for (auto& n : flatNodes)
  897. rows.push_back (n.get());
  898. else if (root != nullptr)
  899. addRows (*root);
  900. updateSize();
  901. repaint();
  902. }
  903. void updateSize()
  904. {
  905. if (auto* parent = getParentComponent())
  906. {
  907. const auto width = parent->getWidth();
  908. const auto viewHeight = parent->getParentComponent() != nullptr ? parent->getParentComponent()->getHeight() : parent->getHeight();
  909. setSize (width, juce::jmax (viewHeight, (int) rows.size() * rowHeight));
  910. }
  911. }
  912. // The project changed: the open sections are listed again (only those whose items changed), keeping what is
  913. // open and selected.
  914. void refreshProject()
  915. {
  916. if (root == nullptr)
  917. return;
  918. bool changed = false;
  919. const auto key = selectionKey();
  920. std::function<void (Node&)> visit = [&] (Node& n) {
  921. if (n.kind == Kind::category)
  922. {
  923. Node fresh;
  924. fresh.kind = Kind::category;
  925. fresh.category = n.category;
  926. fresh.depth = n.depth;
  927. listCategory (fresh, browser.engine.getSong(), &browser.engine, ! n.loaded);
  928. if (n.detail != fresh.detail)
  929. {
  930. n.detail = fresh.detail;
  931. changed = true;
  932. }
  933. if (! n.loaded)
  934. return;
  935. if (signature (fresh) != signature (n))
  936. {
  937. n.children = std::move (fresh.children);
  938. for (auto& c : n.children)
  939. c->parent = &n;
  940. changed = true;
  941. }
  942. else
  943. for (std::size_t i = 0; i < n.children.size(); ++i) // the same items: only the "current" marks
  944. n.children[i]->current = fresh.children[i]->current;
  945. return;
  946. }
  947. for (auto& c : n.children)
  948. if (c->kind == Kind::project || c->kind == Kind::category)
  949. visit (*c);
  950. };
  951. visit (*root);
  952. pendingKey = key;
  953. if (changed)
  954. {
  955. rebuild();
  956. restoreSelection (pendingKey);
  957. }
  958. else
  959. repaint();
  960. }
  961. void paint (juce::Graphics& g) override
  962. {
  963. using namespace theme::colour;
  964. g.fillAll (bg2);
  965. const auto clip = g.getClipBounds();
  966. const auto first = juce::jmax (0, clip.getY() / rowHeight), last = juce::jmin ((int) rows.size() - 1, clip.getBottom() / rowHeight);
  967. const auto previewing = browser.isPreviewPlaying() ? browser.previewedFile : juce::File();
  968. for (int i = first; i <= last; ++i)
  969. {
  970. const auto& n = *rows[(std::size_t) i];
  971. auto r = juce::Rectangle<int> (0, i * rowHeight, getWidth(), rowHeight);
  972. // an open project section sits on a slightly raised band (FL draws its open folders on a band)
  973. if ((n.kind == Kind::project || n.kind == Kind::category) && n.expanded)
  974. {
  975. g.setColour (bg3);
  976. g.fillRect (r);
  977. }
  978. if (i == selected)
  979. {
  980. g.setColour (accentMuted);
  981. g.fillRect (r);
  982. g.setColour (accent);
  983. g.fillRect (r.withWidth (2));
  984. }
  985. else if (i == hovered)
  986. {
  987. g.setColour (bg4);
  988. g.fillRect (r);
  989. }
  990. const auto indent = flat ? 6 : 6 + n.depth * 14;
  991. auto x = (float) indent;
  992. if (n.folder) // a chevron: right when closed, down when open
  993. {
  994. juce::Path p;
  995. const auto c = juce::Point<float> (x + 5.0f, (float) r.getCentreY());
  996. if (n.expanded)
  997. p.addTriangle (c.x - 3.5f, c.y - 2.0f, c.x + 3.5f, c.y - 2.0f, c.x, c.y + 2.5f);
  998. else
  999. p.addTriangle (c.x - 2.0f, c.y - 3.5f, c.x - 2.0f, c.y + 3.5f, c.x + 2.5f, c.y);
  1000. g.setColour (i == hovered || i == selected ? textPrimary : textSecondary);
  1001. g.fillPath (p);
  1002. }
  1003. if (! flat || n.kind != Kind::item)
  1004. x += 12.0f;
  1005. const auto playing = ! n.folder && n.file != juce::File() && n.file == previewing;
  1006. const auto hasColour = ! n.colour.isTransparent();
  1007. auto iconColour = playing ? accent : hasColour ? readable (n.colour) : n.folder ? warning.withAlpha (0.85f) : textSecondary;
  1008. if (n.missing)
  1009. iconColour = meterClip;
  1010. const auto icon = n.icon != Icon::none ? n.icon : iconFor (n.file, n.folder);
  1011. if (n.kind == Kind::collection) // a collection's heading: its colour as a square
  1012. {
  1013. g.setColour (n.colour);
  1014. g.fillRoundedRectangle (juce::Rectangle<float> (x + 3.0f, (float) r.getY() + 6.0f, 10.0f, 10.0f), 2.0f);
  1015. }
  1016. else
  1017. icons::draw (g, icon, juce::Rectangle<float> (x, (float) r.getY() + 3.0f, 16.0f, 16.0f), iconColour);
  1018. x += 21.0f;
  1019. auto text = r.withLeft ((int) x).withTrimmedRight (6);
  1020. // the collections the row is in: one small square per colour at the right edge (round 190ce)
  1021. if (const auto item = itemOf (n); ! item.empty())
  1022. if (const auto bits = BrowserComponent::collectionStore().mask (item); bits != 0)
  1023. {
  1024. for (int c = collections::count - 1; c >= 0; --c)
  1025. if ((bits >> c & 1) != 0)
  1026. {
  1027. const auto chip = text.removeFromRight (9).withSizeKeepingCentre (7, 7);
  1028. g.setColour (BrowserComponent::collectionColour (c));
  1029. g.fillRoundedRectangle (chip.toFloat(), 1.5f);
  1030. }
  1031. text.removeFromRight (3);
  1032. }
  1033. const auto flatDetail = flat && n.kind == Kind::file && n.detail.isNotEmpty(); // "87%" of a similar sample
  1034. if (flat && n.kind == Kind::file) // the folder it lives in, on the right (similar samples: how similar)
  1035. {
  1036. const auto where = flatDetail ? n.detail : n.file.getParentDirectory().getRelativePathFrom (baseOf (n.file));
  1037. g.setFont (theme::font (theme::type::caption));
  1038. g.setColour (textDisabled);
  1039. const auto w = juce::jmin (text.getWidth() / 2, juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), where) + 4);
  1040. g.drawText (where, text.removeFromRight (w), juce::Justification::centredRight, true);
  1041. }
  1042. const auto name = n.label.isNotEmpty() ? n.label
  1043. : n.folder || ! isAudio (n.file) ? n.file.getFileName()
  1044. : n.file.getFileNameWithoutExtension();
  1045. const auto bold = (n.folder && n.expanded) || n.current || n.kind == Kind::project;
  1046. const juce::Font font (theme::font (theme::type::body, bold));
  1047. g.setFont (font);
  1048. auto nameColour = playing ? accentHover : n.folder || i == hovered || i == selected ? textPrimary : textPrimary.withAlpha (0.86f);
  1049. if (n.kind == Kind::item && hasColour && n.item.kind == projectcontents::Kind::pattern)
  1050. nameColour = readable (n.colour); // FL writes the patterns in their colours
  1051. if (n.missing)
  1052. nameColour = meterClip.withAlpha (0.9f);
  1053. if (n.kind == Kind::item && n.history && ! n.current && n.item.index > browser.engine.getHistoryPosition())
  1054. nameColour = textDisabled; // undone steps (redo)
  1055. g.setColour (nameColour);
  1056. const auto nameWidth = juce::GlyphArrangement::getStringWidthInt (font, name);
  1057. g.drawText (name, text, juce::Justification::centredLeft, true);
  1058. // the detail after the name, dimmed: "(insert)", "3x", "missing", a section's count
  1059. if (n.detail.isNotEmpty() && ! flatDetail && nameWidth + 12 < text.getWidth())
  1060. {
  1061. g.setFont (theme::font (theme::type::small));
  1062. g.setColour (n.missing ? meterClip.withAlpha (0.7f) : textDisabled);
  1063. const auto shown = n.kind == Kind::category || n.kind == Kind::project ? n.detail : "(" + n.detail + ")";
  1064. if (n.kind == Kind::category) // the count on the right
  1065. g.drawText (shown, text, juce::Justification::centredRight, true);
  1066. else
  1067. g.drawText (shown, text.withTrimmedLeft (nameWidth + 6), juce::Justification::centredLeft, true);
  1068. }
  1069. }
  1070. if (juce::isPositiveAndBelow (dropRow, (int) rows.size())) // files from the system would go here
  1071. {
  1072. g.setColour (accent);
  1073. g.drawRect (juce::Rectangle<int> (0, dropRow * rowHeight, getWidth(), rowHeight), 2);
  1074. }
  1075. if (rows.empty() && status.isNotEmpty())
  1076. {
  1077. g.setColour (textDisabled);
  1078. g.setFont (theme::font (theme::type::small));
  1079. g.drawFittedText (status, getLocalBounds().reduced (10).withHeight (60), juce::Justification::centredTop, 3);
  1080. }
  1081. }
  1082. int rowAt (int y) const
  1083. {
  1084. const auto row = y / rowHeight;
  1085. return y >= 0 && row < (int) rows.size() ? row : -1;
  1086. }
  1087. // --- files dragged in from the system (issue #12): copied into the folder under the mouse ----------------------
  1088. // The folder row a drop at y lands in: a folder on disk, or a file's own folder; -1 = nowhere to copy to.
  1089. int dropFolderRow (int y) const
  1090. {
  1091. auto row = rowAt (y);
  1092. if (row < 0)
  1093. return -1;
  1094. const Node* n = rows[(std::size_t) row];
  1095. if (n->kind == Kind::file)
  1096. n = n->parent;
  1097. if (n == nullptr || n->kind != Kind::fsFolder || ! n->file.isDirectory())
  1098. return -1;
  1099. const auto it = std::find (rows.begin(), rows.end(), n);
  1100. return it != rows.end() ? (int) (it - rows.begin()) : -1;
  1101. }
  1102. bool isInterestedInFileDrag (const juce::StringArray& files) override
  1103. {
  1104. // the files the Browser lists (samples, MIDI, projects, presets): an other file would not show in the folder
  1105. return ! flat && std::any_of (files.begin(), files.end(), [] (const juce::String& f) {
  1106. const juce::File file (f);
  1107. return file.existsAsFile() && isListed (file);
  1108. });
  1109. }
  1110. void fileDragMove (const juce::StringArray&, int, int y) override
  1111. {
  1112. if (const auto row = dropFolderRow (y); row != dropRow)
  1113. {
  1114. dropRow = row;
  1115. repaint();
  1116. }
  1117. }
  1118. void fileDragExit (const juce::StringArray&) override
  1119. {
  1120. dropRow = -1;
  1121. repaint();
  1122. }
  1123. void filesDropped (const juce::StringArray& files, int, int y) override
  1124. {
  1125. dropRow = -1;
  1126. repaint();
  1127. const auto row = dropFolderRow (y);
  1128. if (row < 0)
  1129. {
  1130. browser.showNote (tr ("Drop the files on a folder to copy them there"));
  1131. return;
  1132. }
  1133. auto* folderNode = rows[(std::size_t) row];
  1134. const auto folder = folderNode->file;
  1135. int copied = 0;
  1136. juce::File first;
  1137. for (const auto& path : files)
  1138. {
  1139. const juce::File source (path);
  1140. if (! source.existsAsFile() || ! isListed (source) || source.getParentDirectory() == folder)
  1141. continue;
  1142. // never over a file that is there: "Kick (2).wav"
  1143. auto target = folder.getChildFile (source.getFileName());
  1144. if (target.exists())
  1145. target = folder.getNonexistentChildFile (source.getFileNameWithoutExtension(), source.getFileExtension(), true);
  1146. if (source.copyFileTo (target))
  1147. {
  1148. ++copied;
  1149. if (first == juce::File())
  1150. first = target;
  1151. }
  1152. }
  1153. if (copied == 0)
  1154. {
  1155. browser.showNote (tr ("Nothing was copied to {0}", { folder.getFileName() }));
  1156. return;
  1157. }
  1158. // the folder lists again, open, with the first copy selected
  1159. folderNode->children.clear();
  1160. folderNode->loaded = false;
  1161. folderNode->expanded = true;
  1162. load (*folderNode);
  1163. rebuild();
  1164. for (int i = 0; i < (int) rows.size(); ++i)
  1165. if (rows[(std::size_t) i]->file == first)
  1166. {
  1167. select (i, false);
  1168. break;
  1169. }
  1170. browser.showNote (copied == 1 ? tr ("Copied 1 file to {0}", { folder.getFileName() })
  1171. : tr ("Copied {0} files to {1}", { juce::String (copied), folder.getFileName() }));
  1172. }
  1173. void mouseMove (const juce::MouseEvent& e) override { setHovered (rowAt (e.y)); }
  1174. void mouseExit (const juce::MouseEvent&) override { setHovered (-1); }
  1175. void mouseDown (const juce::MouseEvent& e) override
  1176. {
  1177. dragStarted = false;
  1178. const auto row = rowAt (e.y);
  1179. pressedRow = row;
  1180. if (row < 0)
  1181. return;
  1182. auto& n = *rows[(std::size_t) row];
  1183. if (e.mods.isPopupMenu())
  1184. {
  1185. select (row, false);
  1186. showMenu (n);
  1187. return;
  1188. }
  1189. if (n.folder)
  1190. {
  1191. select (row, false);
  1192. if (e.getNumberOfClicks() == 1) // a click opens / closes it (the second click of a double click does not undo it)
  1193. toggle (n);
  1194. return;
  1195. }
  1196. if (n.kind == Kind::item)
  1197. {
  1198. select (row, n.item.kind == projectcontents::Kind::sample && ! n.missing);
  1199. itemClicked (n);
  1200. return;
  1201. }
  1202. if (n.kind == Kind::plugin)
  1203. {
  1204. select (row, false);
  1205. return;
  1206. }
  1207. // a click previews, even when the file is already selected (click again: hear it again)
  1208. select (row, true);
  1209. }
  1210. void mouseDrag (const juce::MouseEvent& e) override
  1211. {
  1212. if (dragStarted || e.getDistanceFromDragStart() < 5 || ! juce::isPositiveAndBelow (pressedRow, (int) rows.size()))
  1213. return;
  1214. const auto& n = *rows[(std::size_t) pressedRow];
  1215. auto* container = juce::DragAndDropContainer::findParentDragContainerFor (this);
  1216. if (n.folder || container == nullptr)
  1217. return;
  1218. if (n.kind == Kind::plugin && (n.generator || n.effect)) // a plugin onto the Channel Rack / the Mixer (round 162)
  1219. {
  1220. dragStarted = true;
  1221. draggedPlugin() = { n.generator, n.effect };
  1222. container->startDragging (juce::String (n.generator ? generatorDragDescription : effectDragDescription) + "|" + n.label, this,
  1223. juce::ScaledImage (dragImage (n)), true);
  1224. return;
  1225. }
  1226. if (n.kind == Kind::item && n.item.kind == projectcontents::Kind::pattern) // a pattern onto the Playlist
  1227. {
  1228. dragStarted = true;
  1229. container->startDragging (juce::String (patternDragDescription) + "|" + juce::String (n.item.index), this,
  1230. juce::ScaledImage (dragImage (n)), true);
  1231. return;
  1232. }
  1233. if (n.file.existsAsFile())
  1234. {
  1235. dragStarted = true;
  1236. container->startDragging (juce::String (dragDescription) + "|" + n.file.getFullPathName(), this, juce::ScaledImage (dragImage (n)),
  1237. true);
  1238. }
  1239. }
  1240. void mouseDoubleClick (const juce::MouseEvent& e) override
  1241. {
  1242. const auto row = rowAt (e.y);
  1243. if (row < 0 || rows[(std::size_t) row]->folder || ! e.mods.isLeftButtonDown())
  1244. return;
  1245. const auto& n = *rows[(std::size_t) row];
  1246. if (browser.isHotSwapping() && (n.kind == Kind::plugin || n.kind == Kind::file)) // round 190ce: it replaces the linked device
  1247. {
  1248. select (row, false);
  1249. browser.hotSwapLoadSelected();
  1250. return;
  1251. }
  1252. if (n.kind == Kind::plugin)
  1253. {
  1254. if (n.activate)
  1255. n.activate();
  1256. return;
  1257. }
  1258. if (n.kind != Kind::item)
  1259. {
  1260. browser.openFile (n.file);
  1261. return;
  1262. }
  1263. const auto& item = n.item;
  1264. switch (item.kind)
  1265. {
  1266. case projectcontents::Kind::pattern:
  1267. if (browser.onOpenPattern)
  1268. browser.onOpenPattern (item.index);
  1269. break;
  1270. case projectcontents::Kind::sample:
  1271. if (! n.missing)
  1272. browser.openFile (n.file);
  1273. break;
  1274. case projectcontents::Kind::generator:
  1275. if (browser.onOpenChannel)
  1276. browser.onOpenChannel (item.index);
  1277. break;
  1278. case projectcontents::Kind::effect:
  1279. if (browser.onOpenEffect)
  1280. browser.onOpenEffect (item.index, item.slot);
  1281. break;
  1282. case projectcontents::Kind::automation:
  1283. if (! n.history && ! n.initial && browser.onOpenAutomation)
  1284. browser.onOpenAutomation (item.index);
  1285. break;
  1286. }
  1287. }
  1288. ui::Hint hintAt (juce::Point<int> p) override
  1289. {
  1290. ui::Hint h;
  1291. const auto row = rowAt (p.y);
  1292. if (row < 0)
  1293. {
  1294. 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");
  1295. return h;
  1296. }
  1297. const auto& n = *rows[(std::size_t) row];
  1298. h.hasMenu = true;
  1299. switch (n.kind)
  1300. {
  1301. case Kind::project:
  1302. h.text = tr ("Current project: what this project uses (patterns, effects, generators, automation, audio files) [LMB] open [RMB] expand / collapse all");
  1303. return h;
  1304. case Kind::category:
  1305. h.text = categoryHint (n.category) + " " + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open"));
  1306. h.value = n.detail;
  1307. return h;
  1308. case Kind::fsFolder:
  1309. if (n.depth == 0 || (n.parent != nullptr && n.parent->kind == Kind::project))
  1310. {
  1311. h.text = n.label + ": " + n.file.getFullPathName() + " " + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open")) + " " + tr ("[RMB] menu");
  1312. return h;
  1313. }
  1314. break;
  1315. case Kind::item:
  1316. return itemHint (n);
  1317. case Kind::plugins:
  1318. h.text = tr ("Plugin database: LYNX SHARE's built-in generators and effects, FL's engines and the installed plugins") + " "
  1319. + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open"));
  1320. h.value = n.detail;
  1321. return h;
  1322. case Kind::plugin:
  1323. h.text = n.label + " (" + n.detail + ") "
  1324. + (n.generator ? tr ("[double-click] add it as a new channel, or drag it onto the Channel Rack")
  1325. : tr ("[double-click] add it to the selected insert, or drag it onto a mixer insert or an effect slot"));
  1326. h.hasMenu = true;
  1327. return h;
  1328. case Kind::collection:
  1329. h.text = tr ("Collection: the items you put in it (right-click an item > Collections, or the keys 1-7 on a selected row)") + " "
  1330. + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open")) + " " + tr ("[RMB] menu");
  1331. h.value = n.detail;
  1332. return h;
  1333. case Kind::file:
  1334. break;
  1335. }
  1336. h.text = rowHint (n.file, n.folder, n.expanded);
  1337. h.value = n.folder ? juce::String() : n.file.getFileExtension().substring (1).toUpperCase();
  1338. return h;
  1339. }
  1340. // for snapshots: the first audio file under the first folders on disk (opening them)
  1341. int firstAudioRow()
  1342. {
  1343. for (int pass = 0; pass < 3; ++pass)
  1344. {
  1345. for (int i = 0; i < (int) rows.size(); ++i)
  1346. if (rows[(std::size_t) i]->kind == Kind::file && isAudio (rows[(std::size_t) i]->file))
  1347. return i;
  1348. for (auto* n : rows)
  1349. if (n->kind == Kind::fsFolder && ! n->expanded)
  1350. {
  1351. toggle (*n);
  1352. break;
  1353. }
  1354. }
  1355. return -1;
  1356. }
  1357. // the first row labelled `label`, or -1
  1358. int rowOfFile (const juce::File& file) const
  1359. {
  1360. for (int i = 0; i < (int) rows.size(); ++i)
  1361. if (rows[(std::size_t) i]->file == file)
  1362. return i;
  1363. return -1;
  1364. }
  1365. int rowLabelled (const juce::String& label) const
  1366. {
  1367. for (int i = 0; i < (int) rows.size(); ++i)
  1368. if (rows[(std::size_t) i]->label == label)
  1369. return i;
  1370. return -1;
  1371. }
  1372. // for snapshots: opens these project sections; returns the first row of a sample item
  1373. int openProjectSections (std::initializer_list<Category> open)
  1374. {
  1375. for (auto* n : std::vector<Node*> (rows))
  1376. if (n->kind == Kind::category && std::find (open.begin(), open.end(), n->category) != open.end() && ! n->expanded)
  1377. {
  1378. n->expanded = true;
  1379. load (*n);
  1380. }
  1381. rebuild();
  1382. for (int i = 0; i < (int) rows.size(); ++i)
  1383. if (rows[(std::size_t) i]->kind == Kind::item && rows[(std::size_t) i]->item.kind == projectcontents::Kind::sample)
  1384. return i;
  1385. return -1;
  1386. }
  1387. void setHovered (int row)
  1388. {
  1389. if (row != hovered)
  1390. {
  1391. repaintRow (hovered);
  1392. hovered = row;
  1393. repaintRow (hovered);
  1394. }
  1395. }
  1396. // flat mode, PROJECT tab search: every project item whose name matches
  1397. static std::vector<std::unique_ptr<Node>> projectMatches (const Song& song, const juce::String& query)
  1398. {
  1399. const auto parsed = search::parse (query.toStdString());
  1400. std::vector<std::unique_ptr<Node>> found;
  1401. for (auto c : categories)
  1402. {
  1403. if (c == Category::history)
  1404. continue;
  1405. Node section;
  1406. section.kind = Kind::category;
  1407. section.category = c;
  1408. listCategory (section, song, {});
  1409. for (auto& child : section.children)
  1410. if (search::matches (parsed, child->label.toStdString()))
  1411. {
  1412. child->parent = nullptr;
  1413. found.push_back (std::move (child));
  1414. }
  1415. }
  1416. return found;
  1417. }
  1418. private:
  1419. juce::File baseOf (const juce::File& f) const
  1420. {
  1421. for (const auto& b : bases)
  1422. if (f.isAChildOf (b))
  1423. return b;
  1424. return f.getParentDirectory();
  1425. }
  1426. void load (Node& n)
  1427. {
  1428. if (n.loaded)
  1429. return;
  1430. n.loaded = true;
  1431. if (n.kind == Kind::project)
  1432. {
  1433. for (auto c : categories)
  1434. {
  1435. auto child = std::make_unique<Node>();
  1436. child->kind = Kind::category;
  1437. child->folder = true;
  1438. child->category = c;
  1439. child->label = categoryName (c);
  1440. child->icon = categoryIcon (c);
  1441. child->depth = n.depth + 1;
  1442. child->parent = &n;
  1443. listCategory (*child, browser.engine.getSong(), &browser.engine, true); // the counts show while closed
  1444. child->children.clear();
  1445. n.children.push_back (std::move (child));
  1446. if (c == Category::initialized && browser.projectFile.existsAsFile()) // then the project's folder (FL's "Project data")
  1447. {
  1448. auto folder = makeFolder (browser.projectFile.getParentDirectory(), tr ("Project folder"), juce::Colour());
  1449. folder->icon = Icon::folder;
  1450. folder->depth = n.depth + 1;
  1451. folder->parent = &n;
  1452. n.children.push_back (std::move (folder));
  1453. }
  1454. }
  1455. return;
  1456. }
  1457. if (n.kind == Kind::category)
  1458. {
  1459. loadCategory (n);
  1460. return;
  1461. }
  1462. auto list = [] (const juce::File& folder, juce::Array<juce::File>& folders, juce::Array<juce::File>& files) {
  1463. #if JUCE_MAC
  1464. // not JUCE's iterator on macOS: one name NSString rejects would end the app as the folder opens (issue #42)
  1465. for (const auto& c : childrenOf (folder))
  1466. (c.isDirectory() ? folders : files).add (c);
  1467. #else
  1468. folders = folder.findChildFiles (juce::File::findDirectories, false, "*", juce::File::FollowSymlinks::noCycles);
  1469. files = folder.findChildFiles (juce::File::findFiles, false, "*", juce::File::FollowSymlinks::noCycles);
  1470. #endif
  1471. };
  1472. juce::Array<juce::File> folders, files;
  1473. std::map<juce::String, juce::Array<juce::File>> alsoOf; // a merged subfolder's other copies (by its path)
  1474. if (n.also.isEmpty())
  1475. list (n.file, folders, files);
  1476. else
  1477. {
  1478. // a merged root (FL's Scores, Mixer presets): the union of its folders, the first one's entry on a clash
  1479. juce::Array<juce::File> sources { n.file };
  1480. sources.addArray (n.also);
  1481. std::vector<juce::Array<juce::File>> srcFolders (sources.size()), srcFiles (sources.size());
  1482. std::vector<browserview::Listing> listings (sources.size());
  1483. for (int i = 0; i < sources.size(); ++i)
  1484. {
  1485. list (sources[i], srcFolders[(std::size_t) i], srcFiles[(std::size_t) i]);
  1486. for (const auto& f : srcFolders[(std::size_t) i])
  1487. listings[(std::size_t) i].folders.push_back (f.getFileName().toStdString());
  1488. for (const auto& f : srcFiles[(std::size_t) i])
  1489. listings[(std::size_t) i].files.push_back (f.getFileName().toStdString());
  1490. }
  1491. auto find = [] (const juce::Array<juce::File>& in, const std::string& name) {
  1492. for (const auto& f : in)
  1493. if (f.getFileName().equalsIgnoreCase (juce::String (name)))
  1494. return f;
  1495. return juce::File();
  1496. };
  1497. const auto merged = browserview::mergeListings (listings);
  1498. for (const auto& e : merged.folders)
  1499. {
  1500. const auto f = find (srcFolders[(std::size_t) e.from], e.name);
  1501. folders.add (f);
  1502. for (const auto a : e.also)
  1503. alsoOf[f.getFullPathName()].add (find (srcFolders[(std::size_t) a], e.name));
  1504. }
  1505. for (const auto& e : merged.files)
  1506. files.add (find (srcFiles[(std::size_t) e.from], e.name));
  1507. }
  1508. auto byName = [] (const juce::File& a, const juce::File& b) { return a.getFileName().compareNatural (b.getFileName()) < 0; };
  1509. std::sort (folders.begin(), folders.end(), byName);
  1510. std::sort (files.begin(), files.end(), byName);
  1511. for (const auto& f : folders)
  1512. {
  1513. if (f.isHidden() || f.getFileName().startsWithChar ('.'))
  1514. continue;
  1515. const auto also = alsoOf.count (f.getFullPathName()) ? alsoOf[f.getFullPathName()] : juce::Array<juce::File>();
  1516. if (browser.filterHides (f) && std::all_of (also.begin(), also.end(), [this] (const juce::File& a) { return browser.filterHides (a); }))
  1517. continue; // nothing in it is listed under the content filter (round 164)
  1518. auto c = std::make_unique<Node>();
  1519. c->kind = Kind::fsFolder;
  1520. c->file = f;
  1521. c->also = also;
  1522. c->folder = true;
  1523. c->depth = n.depth + 1;
  1524. c->parent = &n;
  1525. n.children.push_back (std::move (c));
  1526. }
  1527. for (const auto& f : files)
  1528. if (browser.lists (f))
  1529. {
  1530. auto c = std::make_unique<Node>();
  1531. c->file = f;
  1532. c->depth = n.depth + 1;
  1533. c->parent = &n;
  1534. n.children.push_back (std::move (c));
  1535. }
  1536. }
  1537. void loadCategory (Node& n)
  1538. {
  1539. n.loaded = true;
  1540. n.children.clear();
  1541. listCategory (n, browser.engine.getSong(), &browser.engine);
  1542. }
  1543. // The items of one project section (history needs the engine; the PROJECT search passes none).
  1544. static void listCategory (Node& n, const Song& song, AudioEngine* engine, bool countOnly = false)
  1545. {
  1546. auto add = [&n] (projectcontents::Item item, Icon icon, juce::Colour colour) -> Node& {
  1547. auto c = std::make_unique<Node>();
  1548. c->kind = Kind::item;
  1549. c->label = juce::String::fromUTF8 (item.name.c_str());
  1550. c->detail = juce::String::fromUTF8 (item.detail.c_str());
  1551. c->colour = colour;
  1552. c->icon = icon;
  1553. c->depth = n.depth + 1;
  1554. c->parent = &n;
  1555. c->item = std::move (item);
  1556. n.children.push_back (std::move (c));
  1557. return *n.children.back();
  1558. };
  1559. switch (n.category)
  1560. {
  1561. case Category::history:
  1562. if (engine != nullptr)
  1563. {
  1564. // each label compares two whole states: only listed while the section is open, the last 30
  1565. const auto size = engine->getHistorySize(), at = engine->getHistoryPosition();
  1566. for (int i = size - 1; ! countOnly && i >= juce::jmax (0, size - 30); --i) // newest first, as FL lists it
  1567. {
  1568. const auto l = engine->getHistoryLabel (i);
  1569. projectcontents::Item item;
  1570. item.kind = projectcontents::Kind::automation; // (unused for history rows)
  1571. item.index = i;
  1572. item.name = tr (l.text, { juce::String::fromUTF8 (l.arg.c_str()) }).toStdString();
  1573. auto& node = add (std::move (item), Icon::undo, juce::Colour());
  1574. node.history = true;
  1575. node.current = i == at;
  1576. }
  1577. n.detail = juce::String (size);
  1578. }
  1579. break;
  1580. case Category::patterns:
  1581. for (auto& item : projectcontents::patterns (song))
  1582. {
  1583. const auto colour = PlaylistComponent::patternColour (song, item.index);
  1584. const auto current = item.index == song.currentPattern;
  1585. if (item.uses == 0)
  1586. item.detail = tr ("not in the Playlist").toStdString();
  1587. add (std::move (item), Icon::pattern, colour).current = current;
  1588. }
  1589. break;
  1590. case Category::effects:
  1591. for (auto& item : projectcontents::effects (song))
  1592. add (item, item.plugin ? Icon::plugin : Icon::mixer, item.colour != 0 ? juce::Colour (item.colour) : juce::Colour());
  1593. break;
  1594. case Category::generators:
  1595. for (auto& item : projectcontents::generators (song))
  1596. {
  1597. const auto& channel = song.channels[(std::size_t) item.index];
  1598. const auto icon = item.plugin ? Icon::plugin
  1599. : projectcontents::playsSampleFile (channel.instrument) ? Icon::audioFile
  1600. : Icon::keyboard;
  1601. const auto colour = channel.instrument == InstrumentKind::audioClip ? PlaylistComponent::audioClipColour (channel)
  1602. : item.colour != 0 ? juce::Colour (item.colour)
  1603. : juce::Colour();
  1604. const auto selected = engine != nullptr && engine->getSelectedChannel() == item.index;
  1605. add (std::move (item), icon, colour).current = selected;
  1606. }
  1607. break;
  1608. case Category::automation:
  1609. for (auto& item : projectcontents::automations (song))
  1610. add (item, Icon::automate, item.colour != 0 ? juce::Colour (item.colour) : theme::colour::automation);
  1611. break;
  1612. case Category::initialized:
  1613. for (int i = 0; i < (int) song.initialValues.size(); ++i)
  1614. {
  1615. const auto& v = song.initialValues[(std::size_t) i];
  1616. projectcontents::Item item;
  1617. item.kind = projectcontents::Kind::automation;
  1618. item.index = i;
  1619. item.name = (engine != nullptr ? describeAutomationTarget (*engine, v.target) : juce::String ("?")).toStdString();
  1620. item.detail = std::to_string ((int) std::lround (v.value * 100.0f)) + "%";
  1621. add (std::move (item), Icon::automate, theme::colour::automation).initial = true;
  1622. }
  1623. break;
  1624. case Category::samples:
  1625. for (auto& item : projectcontents::samples (song))
  1626. {
  1627. const juce::String path = juce::String::fromUTF8 (item.path.c_str());
  1628. const juce::File file (juce::File::isAbsolutePath (path) ? path : juce::String());
  1629. auto colour = item.colour != 0 ? juce::Colour (item.colour) : theme::colour::audioClip;
  1630. if (item.index >= 0 && song.channels[(std::size_t) item.index].instrument == InstrumentKind::audioClip)
  1631. colour = PlaylistComponent::audioClipColour (song.channels[(std::size_t) item.index]);
  1632. auto& node = add (std::move (item), Icon::audioFile, colour);
  1633. node.file = file;
  1634. node.missing = ! countOnly && ! file.existsAsFile();
  1635. if (node.missing)
  1636. node.detail = tr ("missing");
  1637. }
  1638. break;
  1639. }
  1640. if (n.category != Category::history)
  1641. n.detail = juce::String ((int) n.children.size());
  1642. }
  1643. static juce::String signature (const Node& n)
  1644. {
  1645. juce::String s;
  1646. for (const auto& c : n.children)
  1647. s << c->label << '|' << c->detail << '|' << (int) c->colour.getARGB() << '|' << (int) c->missing << '|' << c->item.index << '|'
  1648. << c->item.slot << '\n';
  1649. return s;
  1650. }
  1651. juce::String selectionKey() const
  1652. {
  1653. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  1654. return {};
  1655. const auto& n = *rows[(std::size_t) selected];
  1656. if (n.kind != Kind::item)
  1657. return "f:" + n.file.getFullPathName() + n.label;
  1658. return "i:" + juce::String ((int) n.item.kind) + ":" + juce::String (n.item.index) + ":" + juce::String (n.item.slot) + ":"
  1659. + juce::String::fromUTF8 (n.item.path.c_str()) + (n.history ? "h" : "");
  1660. }
  1661. void restoreSelection (const juce::String& key)
  1662. {
  1663. if (key.isEmpty())
  1664. return;
  1665. const auto keep = selected;
  1666. selected = -1;
  1667. for (int i = 0; i < (int) rows.size(); ++i)
  1668. {
  1669. selected = i;
  1670. if (selectionKey() == key)
  1671. return;
  1672. }
  1673. selected = -1;
  1674. juce::ignoreUnused (keep);
  1675. }
  1676. void itemClicked (Node& n)
  1677. {
  1678. auto& engine = browser.engine;
  1679. const auto& item = n.item;
  1680. if (n.history)
  1681. {
  1682. engine.jumpToHistory (item.index);
  1683. return;
  1684. }
  1685. if (n.initial)
  1686. return;
  1687. switch (item.kind)
  1688. {
  1689. case projectcontents::Kind::pattern: // FL: clicking a pattern makes it the current one
  1690. if (item.index != engine.getSong().currentPattern && item.index < (int) engine.getSong().patterns.size())
  1691. engine.editSong ([index = item.index] (Song& s) { s.currentPattern = index; }, false);
  1692. break;
  1693. case projectcontents::Kind::generator:
  1694. if (item.index < (int) engine.getSong().channels.size())
  1695. engine.setSelectedChannel (item.index);
  1696. break;
  1697. case projectcontents::Kind::sample:
  1698. case projectcontents::Kind::effect:
  1699. case projectcontents::Kind::automation:
  1700. break;
  1701. }
  1702. }
  1703. ui::Hint itemHint (const Node& n) const
  1704. {
  1705. ui::Hint h;
  1706. h.hasMenu = true;
  1707. const auto& item = n.item;
  1708. if (n.initial)
  1709. {
  1710. h.text = n.label + ": " + tr ("reset to this value when the song starts [RMB] delete the initial value");
  1711. h.value = n.detail;
  1712. return h;
  1713. }
  1714. if (n.history)
  1715. {
  1716. h.text = tr ("Undo history: [LMB] go back to this step");
  1717. h.value = tr ("Level {0}/{1}", { juce::String (item.index + 1), juce::String (browser.engine.getHistorySize()) });
  1718. return h;
  1719. }
  1720. switch (item.kind)
  1721. {
  1722. case projectcontents::Kind::pattern:
  1723. h.text = n.label + ": " + tr ("[LMB] make it the current pattern [2xLMB] open in the Piano Roll drag into the Playlist [RMB] pattern menu");
  1724. h.value = item.uses == 0 ? tr ("not in the Playlist") : tr ("{0} clips", { juce::String (item.uses) });
  1725. break;
  1726. case projectcontents::Kind::sample:
  1727. h.text = juce::String::fromUTF8 (item.path.c_str()) + " "
  1728. + (n.missing ? tr ("(missing: File > Missing files... finds it)")
  1729. : tr ("[LMB] preview [2xLMB] new channel drag to the Playlist or the Channel Rack [RMB] menu"));
  1730. h.value = tr ("used {0}x", { juce::String (item.uses) });
  1731. break;
  1732. case projectcontents::Kind::generator:
  1733. h.text = n.label + (n.detail.isNotEmpty() ? " (" + n.detail + ")" : juce::String()) + ": "
  1734. + tr ("[LMB] select the channel [2xLMB] open its settings [RMB] menu");
  1735. break;
  1736. case projectcontents::Kind::effect:
  1737. h.text = n.label + " (" + n.detail + "): " + tr ("[2xLMB] open its editor [RMB] menu");
  1738. h.value = tr ("slot {0}", { juce::String (item.slot + 1) });
  1739. break;
  1740. case projectcontents::Kind::automation:
  1741. h.text = n.label + ": " + tr ("[2xLMB] open the automation editor");
  1742. h.value = item.uses == 0 ? tr ("not in the Playlist") : tr ("{0} clips", { juce::String (item.uses) });
  1743. break;
  1744. }
  1745. return h;
  1746. }
  1747. // --- round 166f (issue #16): the user's Plugin database folders (FL's folders, shown as headings in the slot menus)
  1748. void setPluginFolder (const std::string& key, bool instruments, const std::string& path)
  1749. {
  1750. auto& host = browser.engine.getPluginHost();
  1751. auto folders = host.databaseFolders();
  1752. plugincatalog::moveToFolder (folders, instruments, key, path);
  1753. host.setDatabaseFolders (folders);
  1754. browser.rebuildTree();
  1755. }
  1756. void askFolderName (const juce::String& title, const juce::String& initial, std::function<void (const std::string&)> done)
  1757. {
  1758. 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\")."),
  1759. juce::MessageBoxIconType::NoIcon);
  1760. window->addTextEditor ("name", initial);
  1761. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1762. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  1763. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, done] (int result) {
  1764. const auto name = plugincatalog::cleanFolder (window->getTextEditorContents ("name").toStdString());
  1765. if (result == 1 && ! name.empty() && done) done (name);
  1766. }),
  1767. true);
  1768. }
  1769. void addFolderItems (juce::PopupMenu& menu, Node& n)
  1770. {
  1771. auto safe = juce::Component::SafePointer<FileTree> (this);
  1772. const bool instruments = n.folderKind == 1;
  1773. const auto path = n.userFolder;
  1774. auto update = [safe, instruments] (std::function<void (plugincatalog::Folders&)> change) {
  1775. if (safe == nullptr) return;
  1776. auto& host = safe->browser.engine.getPluginHost();
  1777. auto folders = host.databaseFolders();
  1778. change (folders);
  1779. host.setDatabaseFolders (folders);
  1780. safe->browser.rebuildTree();
  1781. };
  1782. menu.addSeparator();
  1783. menu.addItem (path.empty() ? tr ("New folder...") : tr ("New subfolder..."), [safe, update, instruments, path] {
  1784. if (safe != nullptr)
  1785. safe->askFolderName (tr ("New folder"), {}, [update, instruments, path] (const std::string& name) {
  1786. update ([=] (plugincatalog::Folders& f) { plugincatalog::addFolder (f, instruments, path.empty() ? name : path + "/" + name); });
  1787. });
  1788. });
  1789. if (! path.empty())
  1790. {
  1791. menu.addItem (tr ("Rename folder..."), [safe, update, instruments, path] {
  1792. if (safe != nullptr)
  1793. safe->askFolderName (tr ("Rename folder"), juce::String::fromUTF8 (path.c_str()), [update, instruments, path] (const std::string& name) {
  1794. update ([=] (plugincatalog::Folders& f) { plugincatalog::renameFolder (f, instruments, path, name); });
  1795. });
  1796. });
  1797. menu.addItem (tr ("Delete folder (its plugins go back to their usual folder)"), [safe, update, instruments, path] {
  1798. if (safe == nullptr) return;
  1799. std::vector<std::string> keys;
  1800. if (instruments) for (const auto& e : quickpick::generatorEntries (safe->browser.engine)) keys.push_back (e.key);
  1801. else for (const auto& e : quickpick::effectEntries (safe->browser.engine)) keys.push_back (e.key);
  1802. update ([=] (plugincatalog::Folders& f) { plugincatalog::removeFolder (f, instruments, path, keys); });
  1803. });
  1804. }
  1805. else
  1806. {
  1807. // FL's own arrangement: the folders of FL Studio's Plugin database (Effects / Generators), when FL is here
  1808. const auto fl = findFlStudio();
  1809. const auto base = fl.userData.getChildFile ("Presets").getChildFile ("Plugin database").getChildFile (instruments ? "Generators" : "Effects");
  1810. menu.addItem (tr ("Folders from FL Studio's Plugin database"), base.isDirectory(), false, [safe, update, instruments, base] {
  1811. if (safe == nullptr) return;
  1812. std::vector<std::string> files;
  1813. for (const auto& entry : juce::RangedDirectoryIterator (base, true, "*.fst", juce::File::findFiles))
  1814. files.push_back (entry.getFile().getRelativePathFrom (base).replaceCharacter ('\\', '/').toStdString());
  1815. std::vector<std::pair<std::string, std::string>> names;
  1816. auto& engine = safe->browser.engine;
  1817. if (instruments) for (const auto& e : quickpick::generatorEntries (engine)) names.push_back ({ e.key, e.label.toStdString() });
  1818. else for (const auto& e : quickpick::effectEntries (engine)) names.push_back ({ e.key, e.label.toStdString() });
  1819. int placed = 0;
  1820. update ([&] (plugincatalog::Folders& f) { placed = plugincatalog::importFlFolders (f, instruments, files, names); });
  1821. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin database"),
  1822. tr ("{0} plugins placed in the folders of FL Studio's Plugin database.", { juce::String (placed) }));
  1823. });
  1824. }
  1825. }
  1826. // FL's "Delete file..." on a Plugin database entry (round 190bf): to the recycle bin after asking; the plugin leaves
  1827. // the menus' folders and the picker (it stays installed), as when the file is deleted in the file manager
  1828. void deleteDatabaseEntry (const juce::File& entry)
  1829. {
  1830. auto safe = juce::Component::SafePointer<FileTree> (this);
  1831. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::WarningIcon, tr ("Delete file"),
  1832. tr ("Move \"{0}\" to the recycle bin?", { entry.getFileName() }), tr ("Delete"), tr ("Cancel"), nullptr,
  1833. juce::ModalCallbackFunction::create ([safe, entry] (int result) {
  1834. if (result == 0 || safe == nullptr)
  1835. return;
  1836. if (! entry.moveToTrash())
  1837. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Delete file"),
  1838. tr ("The file could not be deleted."));
  1839. quickpick::refreshPluginDatabase (safe->browser.engine, true);
  1840. safe->browser.rebuildTree();
  1841. }));
  1842. }
  1843. public:
  1844. void renamePlugin (const std::string& key, const juce::String& original)
  1845. {
  1846. auto safe = juce::Component::SafePointer<FileTree> (this);
  1847. quickpick::rename (browser.engine, key, original, [safe] {
  1848. if (safe != nullptr)
  1849. safe->browser.rebuildTree();
  1850. });
  1851. }
  1852. bool renameSelectedPlugin()
  1853. {
  1854. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  1855. return false;
  1856. const auto& n = *rows[(std::size_t) selected];
  1857. if (n.kind != Kind::plugin || n.pluginKey.empty())
  1858. return false;
  1859. renamePlugin (n.pluginKey, n.original);
  1860. return true;
  1861. }
  1862. // --snapshot (round 190bf): the menu a right-click on that row shows (the Plugin database's), without showing it
  1863. juce::PopupMenu menuForSnapshot (int row)
  1864. {
  1865. juce::PopupMenu out;
  1866. if (! juce::isPositiveAndBelow (row, (int) rows.size()))
  1867. return out;
  1868. captured = &out;
  1869. showMenu (*rows[(std::size_t) row]);
  1870. captured = nullptr;
  1871. return out;
  1872. }
  1873. int firstRowOfKind (bool plugin) const
  1874. {
  1875. for (int i = 0; i < (int) rows.size(); ++i)
  1876. if (rows[(std::size_t) i]->kind == (plugin ? Kind::plugin : Kind::plugins) && (plugin || rows[(std::size_t) i]->folderKind >= 0))
  1877. return i;
  1878. return -1;
  1879. }
  1880. private:
  1881. juce::PopupMenu* captured = nullptr;
  1882. void present (juce::PopupMenu& menu)
  1883. {
  1884. if (captured != nullptr)
  1885. *captured = menu;
  1886. else
  1887. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  1888. }
  1889. void showMenu (Node& n)
  1890. {
  1891. auto& engine = browser.engine;
  1892. juce::PopupMenu menu;
  1893. auto safe = juce::Component::SafePointer<FileTree> (this);
  1894. auto expandItems = [&menu, safe, &n] {
  1895. Node* target = &n;
  1896. while (target != nullptr && target->kind == Kind::item)
  1897. target = target->parent;
  1898. menu.addItem (tr ("Expand all"), [safe, target] {
  1899. if (safe != nullptr && target != nullptr)
  1900. safe->expandAll (*target);
  1901. });
  1902. menu.addItem (tr ("Collapse all"), [safe] {
  1903. if (safe != nullptr)
  1904. safe->collapseAll();
  1905. });
  1906. };
  1907. // (issue #104: the items below act on the Plugin database folder as it is on disk now)
  1908. if (n.kind == Kind::plugin || n.kind == Kind::plugins)
  1909. quickpick::refreshPluginDatabase (engine, true);
  1910. if (n.kind == Kind::plugin)
  1911. {
  1912. menu.addSectionHeader (n.label);
  1913. menu.addItem (tr ("Add"), [act = n.activate] {
  1914. if (act)
  1915. act();
  1916. });
  1917. if (! n.pluginKey.empty()) // FL's renamed plugins (issue #11): "1_EQ" is then picked by typing 1 on an empty slot
  1918. {
  1919. menu.addSeparator();
  1920. menu.addItem (tr ("Rename...") + "\tF2", [safe, key = n.pluginKey, original = n.original] {
  1921. if (safe != nullptr)
  1922. safe->renamePlugin (key, original);
  1923. });
  1924. menu.addItem (tr ("Original name"), n.label != n.original, false, [safe, key = n.pluginKey] {
  1925. if (safe != nullptr)
  1926. {
  1927. safe->browser.engine.getPluginHost().setPluginName (key, {});
  1928. safe->browser.rebuildTree();
  1929. }
  1930. });
  1931. // round 166f (issue #16): FL's Plugin database folders — the slot menus list each folder under a heading
  1932. const bool instruments = (bool) n.generator;
  1933. const auto& folders = engine.getPluginHost().databaseFolders();
  1934. const auto it = folders.of.find (n.pluginKey);
  1935. const auto now = it != folders.of.end() && folders.kind (instruments).count (it->second) ? it->second : std::string();
  1936. juce::PopupMenu move;
  1937. for (const auto& path : folders.kind (instruments))
  1938. move.addItem (juce::String::fromUTF8 (plugincatalog::groupHeading (path).c_str()), true, path == now, [safe, key = n.pluginKey, instruments, path] {
  1939. if (safe != nullptr) safe->setPluginFolder (key, instruments, path);
  1940. });
  1941. if (! folders.kind (instruments).empty()) move.addSeparator();
  1942. move.addItem (tr ("New folder..."), [safe, key = n.pluginKey, instruments] {
  1943. if (safe != nullptr)
  1944. safe->askFolderName (tr ("New folder"), {}, [safe, key, instruments] (const std::string& name) {
  1945. if (safe != nullptr) safe->setPluginFolder (key, instruments, name);
  1946. });
  1947. });
  1948. move.addItem (tr ("No folder"), ! now.empty(), now.empty(), [safe, key = n.pluginKey, instruments] {
  1949. if (safe != nullptr) safe->setPluginFolder (key, instruments, {});
  1950. });
  1951. menu.addSubMenu (tr ("Move to folder"), move);
  1952. }
  1953. if (const auto item = itemOf (n); ! item.empty()) // round 190ce: the collections take Plugin database entries too
  1954. browser.addCollectionItems (menu, item);
  1955. // FL's "System" group on an entry (round 190bf, fl190be q1-entry-menu.png): its file in the Plugin database
  1956. // folder (the Installed one for a plugin in no folder). FL's "Windows shell menu" is left out: LYNX has no
  1957. // shell context menu of its own.
  1958. {
  1959. const auto entry = n.pluginKey.empty() ? juce::File() : quickpick::pluginDatabaseEntry (n.pluginKey, (bool) n.generator);
  1960. const auto ok = entry.existsAsFile();
  1961. menu.addSectionHeader (tr ("System"));
  1962. menu.addItem (tr ("Open parent folder"), ok, false, [entry] { entry.getParentDirectory().startAsProcess(); });
  1963. menu.addItem (tr ("Locate file"), ok, false, [entry] { entry.revealToUser(); });
  1964. menu.addItem (tr ("Delete file..."), ok, false, [safe, entry] {
  1965. if (safe != nullptr)
  1966. safe->deleteDatabaseEntry (entry);
  1967. });
  1968. }
  1969. present (menu);
  1970. return;
  1971. }
  1972. if (n.kind == Kind::collection)
  1973. {
  1974. auto safeBrowser = juce::Component::SafePointer<BrowserComponent> (&browser);
  1975. ui::addItemHeader (menu, tr ("Collection"), n.label, n.colour);
  1976. menu.addItem (tr ("Rename..."), [safeBrowser, c = n.collection] {
  1977. if (safeBrowser != nullptr)
  1978. safeBrowser->renameCollection (c);
  1979. });
  1980. menu.addItem (tr ("Hide this collection"), n.collection != 0 || BrowserComponent::collectionStore().shown().size() > 1, false, [safeBrowser, c = n.collection] {
  1981. if (safeBrowser != nullptr)
  1982. safeBrowser->setCollectionShown (c, false);
  1983. });
  1984. // the collections the STARRED tab lists (round 190cy: here, as Live's Collections › Edit, since the
  1985. // Clip-launch workflow's row menu has only the labels)
  1986. juce::PopupMenu show;
  1987. for (int c = 0; c < collections::count; ++c)
  1988. show.addItem (BrowserComponent::collectionName (c), true, BrowserComponent::collectionStore().isShown (c), [safeBrowser, c] {
  1989. if (safeBrowser != nullptr)
  1990. safeBrowser->setCollectionShown (c, ! BrowserComponent::collectionStore().isShown (c));
  1991. });
  1992. menu.addSubMenu (tr ("Show in the STARRED tab"), show);
  1993. present (menu);
  1994. return;
  1995. }
  1996. if (n.kind == Kind::project || n.kind == Kind::category || n.kind == Kind::plugins)
  1997. {
  1998. menu.addSectionHeader (n.label);
  1999. expandItems();
  2000. juce::File databaseDir; // (a Plugin database folder: its place on disk)
  2001. if (n.kind == Kind::plugins && n.folderKind >= 0) // round 166f (issue #16): the user's folders
  2002. addFolderItems (menu, n);
  2003. if (n.kind == Kind::plugins)
  2004. {
  2005. // round 190ba (issue #104): the Plugin database is a folder the user can arrange in the file manager, as
  2006. // FL's (its Browser opens the folder from this menu too). The database itself, Effects / Generators, one
  2007. // of the user's folders; LYNX's own groups (LYNX SHARE, FL engines, Installed) open the Installed entries
  2008. juce::File dir = quickpick::pluginDatabaseFolder();
  2009. if (n.folderKind >= 0)
  2010. dir = quickpick::pluginDatabaseFolder (n.folderKind == 1, n.userFolder);
  2011. else if (n.isGroup && n.parent != nullptr && n.parent->kind == Kind::plugins && n.parent->folderKind >= 0)
  2012. dir = juce::File (juce::String::fromUTF8 (plugindb::groupFolder (dir.getFullPathName().toStdString(), n.parent->folderKind == 1, n.group).c_str()));
  2013. databaseDir = dir;
  2014. }
  2015. if ((n.kind == Kind::project || n.kind == Kind::plugins) && n.parent == nullptr && browser.tab == allTab) // round 163
  2016. {
  2017. menu.addSeparator();
  2018. browser.addHideItem (menu, n.kind == Kind::project ? browserview::projectRootId : browserview::pluginsRootId, n.label);
  2019. }
  2020. if (n.kind == Kind::plugins)
  2021. {
  2022. // FL's "System" group at the end of a folder's menu (round 190bf, fl190be q1-folder-menu.png): "Open"
  2023. // (FL's "Windows shell menu" is left out: LYNX has no shell context menu of its own)
  2024. menu.addSectionHeader (tr ("System"));
  2025. menu.addItem (tr ("Open"), databaseDir.isDirectory(), false, [dir = databaseDir] { dir.startAsProcess(); });
  2026. }
  2027. present (menu);
  2028. return;
  2029. }
  2030. if (n.kind != Kind::item)
  2031. {
  2032. if (n.folder)
  2033. browser.showFolderMenu (n.file, [safe, node = &n] {
  2034. if (safe != nullptr)
  2035. safe->expandFolder (*node, 3);
  2036. });
  2037. else
  2038. browser.showFileMenu (n.file);
  2039. return;
  2040. }
  2041. const auto item = n.item;
  2042. if (n.history)
  2043. return;
  2044. if (n.initial)
  2045. {
  2046. const auto& values = engine.getSong().initialValues;
  2047. if (! juce::isPositiveAndBelow (item.index, (int) values.size()))
  2048. return;
  2049. menu.addSectionHeader (n.label + ": " + n.detail);
  2050. menu.addItem (tr ("Delete initial value"), [&engine, target = values[(std::size_t) item.index].target] {
  2051. engine.editSong ([target] (Song& s) { s.removeInitialValue (target); });
  2052. });
  2053. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  2054. return;
  2055. }
  2056. switch (item.kind)
  2057. {
  2058. case projectcontents::Kind::pattern: // FL: the right-click makes it the current pattern, then its menu
  2059. itemClicked (n);
  2060. if (browser.onPatternMenu)
  2061. browser.onPatternMenu (item.index);
  2062. return;
  2063. case projectcontents::Kind::sample:
  2064. {
  2065. const auto file = n.file;
  2066. const auto ok = ! n.missing;
  2067. ui::addItemHeader (menu, tr ("Audio file"), n.label, n.colour);
  2068. menu.addItem (tr ("Send to the selected channel"), ok && browser.onLoadIntoChannel != nullptr, false, [safe, file] {
  2069. if (safe != nullptr && safe->browser.onLoadIntoChannel)
  2070. safe->browser.onLoadIntoChannel (file);
  2071. });
  2072. menu.addItem (tr ("Open in a new channel"), ok, false, [safe, file] {
  2073. if (safe != nullptr)
  2074. safe->browser.openFile (file);
  2075. });
  2076. menu.addItem (tr ("Send to the Playlist as an audio clip"), ok && browser.onSendToPlaylist != nullptr, false, [safe, file] {
  2077. if (safe != nullptr && safe->browser.onSendToPlaylist)
  2078. safe->browser.onSendToPlaylist (file);
  2079. });
  2080. menu.addSeparator();
  2081. menu.addItem (tr ("Edit in the audio editor..."), ok, false, [&engine, file] { openAudioEditor (engine, file); });
  2082. if (item.index >= 0)
  2083. menu.addItem (tr ("Show its channel"), [safe, channel = item.index] {
  2084. if (safe != nullptr && channel < (int) safe->browser.engine.getSong().channels.size())
  2085. safe->browser.engine.setSelectedChannel (channel);
  2086. });
  2087. menu.addSeparator();
  2088. menu.addItem (tr ("Show in the file manager"), ok, false, [file] { file.revealToUser(); });
  2089. break;
  2090. }
  2091. case projectcontents::Kind::generator:
  2092. ui::addItemHeader (menu, tr ("Generator"), n.label, n.colour);
  2093. menu.addItem (tr ("Open settings"), [safe, channel = item.index] {
  2094. if (safe != nullptr && safe->browser.onOpenChannel)
  2095. safe->browser.onOpenChannel (channel);
  2096. });
  2097. if (engine.getSong().channels[(std::size_t) item.index].mixerTrack > 0)
  2098. menu.addItem (tr ("Show its mixer insert"), [safe, track = engine.getSong().channels[(std::size_t) item.index].mixerTrack] {
  2099. if (safe != nullptr && safe->browser.onShowInsert)
  2100. safe->browser.onShowInsert (track);
  2101. });
  2102. break;
  2103. case projectcontents::Kind::effect:
  2104. ui::addItemHeader (menu, tr ("Effect") + " - " + n.detail, n.label, n.colour);
  2105. menu.addItem (tr ("View editor"), [safe, track = item.index, slot = item.slot] {
  2106. if (safe != nullptr && safe->browser.onOpenEffect)
  2107. safe->browser.onOpenEffect (track, slot);
  2108. });
  2109. menu.addItem (tr ("Show its mixer insert"), [safe, track = item.index] {
  2110. if (safe != nullptr && safe->browser.onShowInsert)
  2111. safe->browser.onShowInsert (track);
  2112. });
  2113. break;
  2114. case projectcontents::Kind::automation:
  2115. ui::addItemHeader (menu, tr ("Automation clip"), n.label, n.colour);
  2116. menu.addItem (tr ("Open the automation editor"), [safe, index = item.index] {
  2117. if (safe != nullptr && safe->browser.onOpenAutomation)
  2118. safe->browser.onOpenAutomation (index);
  2119. });
  2120. break;
  2121. }
  2122. menu.addSeparator();
  2123. expandItems();
  2124. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  2125. }
  2126. void addRows (Node& n)
  2127. {
  2128. for (auto& c : n.children)
  2129. {
  2130. rows.push_back (c.get());
  2131. if (c->folder && c->expanded)
  2132. addRows (*c);
  2133. }
  2134. }
  2135. void toggle (Node& n)
  2136. {
  2137. const auto keep = selectionKey();
  2138. n.expanded = ! n.expanded;
  2139. if (n.kind == Kind::plugins) // (remembered: the database is built again with the tree)
  2140. {
  2141. const auto key = (n.parent != nullptr && n.parent->kind == Kind::plugins ? n.parent->label + "/" : juce::String()) + n.label;
  2142. if (n.expanded)
  2143. browser.openPluginFolders.insert (key);
  2144. else
  2145. browser.openPluginFolders.erase (key);
  2146. }
  2147. if (n.kind == Kind::collection)
  2148. {
  2149. if (n.expanded)
  2150. browser.closedCollections.erase (n.collection);
  2151. else
  2152. browser.closedCollections.insert (n.collection);
  2153. }
  2154. if (n.expanded)
  2155. load (n);
  2156. rebuild();
  2157. restoreSelection (keep);
  2158. if (n.expanded) // show what opened
  2159. for (int i = 0; i < (int) rows.size(); ++i)
  2160. if (rows[(std::size_t) i] == &n)
  2161. scrollToRow (juce::jmin ((int) rows.size() - 1, i + juce::jmin ((int) n.children.size(), 6)));
  2162. }
  2163. void scrollToRow (int row)
  2164. {
  2165. if (row < 0)
  2166. return;
  2167. if (auto* view = findParentComponentOfClass<juce::Viewport>())
  2168. {
  2169. const auto top = row * rowHeight, bottom = top + rowHeight;
  2170. const auto y = view->getViewPositionY(), h = view->getViewHeight();
  2171. if (top < y)
  2172. view->setViewPosition (0, top);
  2173. else if (bottom > y + h)
  2174. view->setViewPosition (0, bottom - h);
  2175. }
  2176. }
  2177. void repaintRow (int row)
  2178. {
  2179. if (row >= 0)
  2180. repaint (0, row * rowHeight, getWidth(), rowHeight);
  2181. }
  2182. juce::Image dragImage (const Node& n) const
  2183. {
  2184. const auto name = n.label.isNotEmpty() ? n.label : n.file.getFileNameWithoutExtension();
  2185. const auto font = juce::Font (theme::font (theme::type::body));
  2186. const auto width = juce::jlimit (80, 260, juce::GlyphArrangement::getStringWidthInt (font, name) + 36);
  2187. const auto colour = n.colour.isTransparent() ? theme::colour::accent : readable (n.colour);
  2188. juce::Image image (juce::Image::ARGB, width, 24, true);
  2189. juce::Graphics g (image);
  2190. g.setColour (theme::colour::bg4.withAlpha (0.92f));
  2191. g.fillRoundedRectangle (0.5f, 0.5f, (float) width - 1.0f, 23.0f, 5.0f);
  2192. g.setColour (colour);
  2193. g.drawRoundedRectangle (0.5f, 0.5f, (float) width - 1.0f, 23.0f, 5.0f, 1.0f);
  2194. icons::draw (g, n.icon != Icon::none ? n.icon : iconFor (n.file, false), { 6.0f, 4.0f, 16.0f, 16.0f }, colour);
  2195. g.setColour (theme::colour::textPrimary);
  2196. g.setFont (font);
  2197. g.drawText (name, 28, 0, width - 32, 24, juce::Justification::centredLeft, true);
  2198. return image;
  2199. }
  2200. BrowserComponent& browser;
  2201. const bool flat;
  2202. std::unique_ptr<Node> root;
  2203. std::vector<std::unique_ptr<Node>> flatNodes;
  2204. std::vector<Node*> rows;
  2205. juce::Array<juce::File> bases;
  2206. juce::String status, pendingKey;
  2207. int selected = -1, hovered = -1, pressedRow = -1;
  2208. int dropRow = -1; // the folder files dragged in from the system would be copied to
  2209. bool dragStarted = false;
  2210. };
  2211. // --- the tabs: ALL / PROJECT ------------------------------------------------------------------------
  2212. class BrowserComponent::TabBar final : public juce::Component,
  2213. public ui::HintSource
  2214. {
  2215. public:
  2216. explicit TabBar (BrowserComponent& b) : browser (b) { setRepaintsOnMouseActivity (true); }
  2217. juce::Rectangle<int> tabBounds (int t) const
  2218. {
  2219. const auto w = getWidth() / tabCount;
  2220. return { t * w, 0, t == tabCount - 1 ? getWidth() - t * w : w, getHeight() };
  2221. }
  2222. static juce::String name (int t) { return t == allTab ? tr ("ALL") : t == projectTab ? tr ("PROJECT") : tr ("STARRED"); }
  2223. void paint (juce::Graphics& g) override
  2224. {
  2225. using namespace theme;
  2226. const auto mouse = isMouseOver() ? getMouseXYRelative() : juce::Point<int> (-1, -1);
  2227. for (int t = 0; t < tabCount; ++t)
  2228. {
  2229. const auto r = tabBounds (t);
  2230. const auto on = browser.tab == t;
  2231. if (on || r.contains (mouse))
  2232. {
  2233. g.setColour (on ? colour::bg4 : colour::bg3);
  2234. g.fillRoundedRectangle (r.reduced (2, 2).toFloat(), radius::md);
  2235. }
  2236. if (on)
  2237. {
  2238. g.setColour (colour::accent);
  2239. g.fillRoundedRectangle (r.reduced (10, 0).removeFromBottom (2).toFloat(), 1.0f);
  2240. }
  2241. g.setColour (on ? colour::textPrimary : colour::textSecondary);
  2242. g.setFont (font (type::caption, true));
  2243. g.drawText (name (t), r, juce::Justification::centred, false);
  2244. }
  2245. }
  2246. void mouseDown (const juce::MouseEvent& e) override
  2247. {
  2248. for (int t = 0; t < tabCount; ++t)
  2249. if (tabBounds (t).contains (e.getPosition()))
  2250. browser.setTab (t);
  2251. }
  2252. ui::Hint hintAt (juce::Point<int> p) override
  2253. {
  2254. ui::Hint h;
  2255. const auto t = juce::jlimit (0, tabCount - 1, p.x * tabCount / juce::jmax (1, getWidth()));
  2256. h.text = t == allTab ? tr ("Browser: ALL - the current project and every sample folder")
  2257. : t == projectTab ? tr ("Browser: PROJECT - only what the current project uses (patterns, effects, generators, audio files...)")
  2258. : tr ("Browser: STARRED - the files and folders you starred (right-click > Starred)");
  2259. return h;
  2260. }
  2261. private:
  2262. BrowserComponent& browser;
  2263. };
  2264. // --- the preview strip: waveform of the selected sample ----------------------------------------------
  2265. class BrowserComponent::PreviewStrip final : public juce::Component,
  2266. public ui::HintSource,
  2267. private juce::Timer,
  2268. private juce::ChangeListener
  2269. {
  2270. public:
  2271. explicit PreviewStrip (BrowserComponent& b) : browser (b) { ui::WaveformCache::getInstance()->addChangeListener (this); }
  2272. ~PreviewStrip() override
  2273. {
  2274. if (auto* cache = ui::WaveformCache::getInstanceWithoutCreating())
  2275. cache->removeChangeListener (this);
  2276. }
  2277. void changeListenerCallback (juce::ChangeBroadcaster*) override { repaint(); } // the spectral waveform is ready
  2278. // FL 2026's preview strip (audit round 165z-a): over the waveform, bottom left, a Play / Stop toggle and the preview
  2279. // volume slider; they show while the mouse is over the strip or a sample plays
  2280. void adoptControls()
  2281. {
  2282. addChildComponent (browser.stopButton);
  2283. addChildComponent (browser.previewVolume);
  2284. updateControls();
  2285. }
  2286. void updateControls()
  2287. {
  2288. const auto playing = isPlaying();
  2289. const auto show = isAudio (file) && (playing || isMouseOver (true));
  2290. if (playing != shownPlaying) // (only on a change: this runs on every timer tick)
  2291. {
  2292. shownPlaying = playing;
  2293. browser.stopButton.setIcon (playing ? Icon::stop : Icon::play);
  2294. browser.stopButton.setPrimary (playing);
  2295. const auto text = playing ? tr ("Stop the sample preview") : tr ("Play the sample preview");
  2296. browser.stopButton.setTooltip (text);
  2297. ui::setHint (browser.stopButton, text, true);
  2298. }
  2299. if (browser.stopButton.isVisible() != show)
  2300. {
  2301. browser.stopButton.setVisible (show);
  2302. browser.previewVolume.setVisible (show);
  2303. }
  2304. if (show && ! isTimerRunning())
  2305. startTimerHz (30); // (hides them again when the mouse leaves)
  2306. }
  2307. void resized() override
  2308. {
  2309. auto row = getLocalBounds().reduced (8, 6).removeFromBottom (14);
  2310. browser.stopButton.setBounds (row.removeFromLeft (20));
  2311. row.removeFromLeft (6);
  2312. browser.previewVolume.setBounds (row.removeFromLeft (juce::jmin (90, juce::jmax (40, row.getWidth() / 2))));
  2313. }
  2314. void mouseEnter (const juce::MouseEvent&) override { updateControls(); }
  2315. void mouseExit (const juce::MouseEvent&) override { updateControls(); }
  2316. void togglePlay()
  2317. {
  2318. if (isPlaying())
  2319. browser.stopPreview();
  2320. else if (isAudio (file))
  2321. browser.fileSelected (file, true);
  2322. }
  2323. void show (const juce::File& f, bool playing)
  2324. {
  2325. if (f != file)
  2326. {
  2327. file = f;
  2328. peaks.clear();
  2329. seconds = 0.0;
  2330. info.clear();
  2331. if (isAudio (f))
  2332. if (const auto sample = browser.engine.getSampleLibrary().load (f.getFullPathName()); sample != nullptr && sample->frames() > 0)
  2333. {
  2334. // 256 peaks over the whole file
  2335. const auto frames = sample->frames();
  2336. constexpr std::size_t count = 256;
  2337. peaks.assign (count, 0.0f);
  2338. const auto* l = sample->leftData();
  2339. const auto* r = sample->rightData();
  2340. const auto stride = std::max<std::size_t> (1, frames / (count * 64)); // look at up to 64 points per peak
  2341. for (std::size_t i = 0; i < count; ++i)
  2342. {
  2343. const auto from = frames * i / count, to = juce::jmax (from + 1, frames * (i + 1) / count);
  2344. float m = 0.0f;
  2345. for (auto k = from; k < to && k < frames; k += stride)
  2346. m = juce::jmax (m, std::abs (l[k]), std::abs (r[k]));
  2347. peaks[i] = m;
  2348. }
  2349. const auto top = *std::max_element (peaks.begin(), peaks.end());
  2350. if (top > 1.0e-6f) // normalised: quiet files are still readable
  2351. for (auto& p : peaks)
  2352. p /= top;
  2353. seconds = (double) frames / juce::jmax (1.0, sample->sampleRate);
  2354. info = juce::String (seconds, seconds < 10.0 ? 2 : 1) + " s " + juce::String (juce::roundToInt (sample->sampleRate / 100.0) / 10.0, 1)
  2355. + " kHz " + (sample->isStereo() ? tr ("stereo") : tr ("mono"));
  2356. }
  2357. }
  2358. if (playing && seconds > 0.0)
  2359. {
  2360. startedAt = juce::Time::getMillisecondCounterHiRes();
  2361. startTimerHz (30);
  2362. }
  2363. updateControls();
  2364. repaint();
  2365. }
  2366. void paint (juce::Graphics& g) override
  2367. {
  2368. using namespace theme::colour;
  2369. g.fillAll (bg1);
  2370. g.setColour (border);
  2371. g.fillRect (0, 0, getWidth(), 1);
  2372. auto area = getLocalBounds().reduced (6, 4).withTrimmedTop (1);
  2373. if (file == juce::File() || ! isAudio (file))
  2374. {
  2375. g.setColour (textDisabled);
  2376. g.setFont (theme::font (theme::type::small));
  2377. g.drawFittedText (tr ("Click a sample to hear it; its waveform shows here"), area, juce::Justification::centred, 2);
  2378. return;
  2379. }
  2380. auto top = area.removeFromTop (14);
  2381. g.setFont (theme::font (theme::type::caption, true));
  2382. g.setColour (textPrimary);
  2383. g.drawText (file.getFileNameWithoutExtension(), top, juce::Justification::centredLeft, true);
  2384. g.setFont (theme::font (theme::type::caption));
  2385. g.setColour (textSecondary);
  2386. g.drawText (info + tempoText(), top, juce::Justification::centredRight, true);
  2387. area.removeFromTop (2);
  2388. g.setColour (bg0);
  2389. g.fillRoundedRectangle (area.toFloat(), theme::radius::sm);
  2390. if (peaks.empty())
  2391. return;
  2392. const auto wave = area.toFloat().reduced (2.0f, 2.0f);
  2393. const auto mid = wave.getCentreY();
  2394. const auto progress = position();
  2395. const auto playedX = wave.getX() + wave.getWidth() * (float) progress;
  2396. // the detailed, frequency-coloured waveform (ui/WaveformView) once analysed; the quick peaks until then
  2397. const auto path = file.getFullPathName();
  2398. if (const auto summary = ui::WaveformCache::getInstance()->find (path, [this, path] { return browser.engine.getSampleLibrary().load (path); }))
  2399. {
  2400. ui::paintWaveform (g, wave, *summary, 0.0, (double) summary->frames / juce::jmax (1.0f, wave.getWidth()),
  2401. ui::currentWaveStyle (textSecondary, ui::normalisingGain (*summary)));
  2402. if (progress > 0.0)
  2403. {
  2404. g.setColour (accent.withAlpha (0.22f)); // the part already heard
  2405. g.fillRect (juce::Rectangle<float>::leftTopRightBottom (wave.getX(), wave.getY(), playedX, wave.getBottom()));
  2406. g.setColour (textPrimary);
  2407. g.fillRect (playedX, wave.getY(), 1.0f, wave.getHeight());
  2408. }
  2409. return;
  2410. }
  2411. for (int x = 0; x < (int) wave.getWidth(); ++x)
  2412. {
  2413. const auto p = peaks[(std::size_t) (x * (int) peaks.size() / juce::jmax (1, (int) wave.getWidth()))];
  2414. const auto h = juce::jmax (0.5f, p * wave.getHeight() * 0.5f);
  2415. const auto px = wave.getX() + (float) x;
  2416. g.setColour (progress > 0.0 && px <= playedX ? accent : textSecondary.withAlpha (0.75f));
  2417. g.fillRect (px, mid - h, 1.0f, h * 2.0f);
  2418. }
  2419. if (progress > 0.0)
  2420. {
  2421. g.setColour (textPrimary);
  2422. g.fillRect (playedX, wave.getY(), 1.0f, wave.getHeight());
  2423. }
  2424. }
  2425. void mouseDown (const juce::MouseEvent& e) override
  2426. {
  2427. if (isAudio (file) && e.mods.isLeftButtonDown())
  2428. browser.fileSelected (file, true); // hear it again
  2429. }
  2430. void mouseDrag (const juce::MouseEvent& e) override
  2431. {
  2432. if (! dragging && isAudio (file) && e.getDistanceFromDragStart() > 5)
  2433. if (auto* container = juce::DragAndDropContainer::findParentDragContainerFor (this))
  2434. {
  2435. dragging = true;
  2436. container->startDragging (juce::String (dragDescription) + "|" + file.getFullPathName(), this, juce::ScaledImage(), true);
  2437. }
  2438. }
  2439. void mouseUp (const juce::MouseEvent&) override { dragging = false; }
  2440. ui::Hint hintAt (juce::Point<int>) override
  2441. {
  2442. ui::Hint h;
  2443. h.text = isAudio (file) ? tr ("Sample preview: [LMB] hear it again drag it like a file in the list") : tr ("Sample preview");
  2444. h.value = info;
  2445. return h;
  2446. }
  2447. bool isPlaying() const { return position() > 0.0 && position() < 1.0; }
  2448. // "Preview in time" (round 190aq): the tempo found in the file and the project's, after the file's details
  2449. juce::String tempoText() const
  2450. {
  2451. const auto& timing = browser.engine.getPreviewTiming();
  2452. if (! browser.engine.isPreviewInTime() || timing.path != file.getFullPathName() || ! (timing.fileBpm > 0.0))
  2453. return {};
  2454. auto bpm = [] (double v) { return juce::String (v, std::abs (v - std::round (v)) < 0.05 ? 0 : 1); };
  2455. // "120 BPM" at the project's tempo already, else "120 → 140 BPM" (what it is stretched to)
  2456. return " " + tr ("{0} BPM", { timing.ratio == 1.0 ? bpm (timing.fileBpm)
  2457. : bpm (timing.fileBpm) + juce::String::fromUTF8 (" \xe2\x86\x92 ") + bpm (timing.fileBpm / timing.ratio) });
  2458. }
  2459. void stop()
  2460. {
  2461. startedAt = 0.0;
  2462. if (! isMouseOver (true))
  2463. stopTimer();
  2464. updateControls();
  2465. repaint();
  2466. }
  2467. private:
  2468. double position() const
  2469. {
  2470. if (startedAt <= 0.0 || seconds <= 0.0)
  2471. return 0.0;
  2472. // "Preview in time" (round 190aq): the stretched preview starts later (its stretch, then its beat) and lasts
  2473. // another time, so the engine says where it is
  2474. if (const auto& timing = browser.engine.getPreviewTiming(); timing.path == file.getFullPathName() && (timing.pending || timing.inTime))
  2475. {
  2476. const auto p = browser.engine.getPreviewInTimeProgress();
  2477. return p < 0.0 ? 1.0 : juce::jlimit (1.0e-6, 1.0 - 1.0e-6, p);
  2478. }
  2479. return juce::jlimit (0.0, 1.0, (juce::Time::getMillisecondCounterHiRes() - startedAt) / 1000.0 / seconds);
  2480. }
  2481. void timerCallback() override
  2482. {
  2483. if (startedAt > 0.0 && position() >= 1.0)
  2484. {
  2485. stop();
  2486. browser.tree->repaint(); // the "playing" colour goes
  2487. browser.results->repaint();
  2488. }
  2489. updateControls();
  2490. if (startedAt <= 0.0 && ! browser.stopButton.isVisible())
  2491. stopTimer();
  2492. repaint();
  2493. }
  2494. BrowserComponent& browser;
  2495. juce::File file;
  2496. std::vector<float> peaks;
  2497. double seconds = 0.0, startedAt = 0.0;
  2498. juce::String info;
  2499. bool dragging = false;
  2500. std::optional<bool> shownPlaying; // the Play / Stop state the button shows
  2501. };
  2502. // --- the browser -------------------------------------------------------------------------------------
  2503. bool BrowserComponent::isPreviewPlaying() const
  2504. {
  2505. return strip != nullptr && strip->isPlaying();
  2506. }
  2507. // FL's Browser details box (REA round 134/139): what is selected — a column of labels (Date, Size, Version for a
  2508. // project FL saved, Path) and their values, the path wrapping over the last lines. Hidden while nothing is selected.
  2509. class BrowserComponent::DetailsBox final : public juce::Component,
  2510. public ui::HintSource
  2511. {
  2512. public:
  2513. static constexpr int preferredHeight = 70;
  2514. void show (const juce::File& f)
  2515. {
  2516. file = f;
  2517. rows.clear();
  2518. if (file != juce::File())
  2519. {
  2520. rows.push_back ({ tr ("Date"), file.getLastModificationTime().formatted ("%Y-%m-%d %H:%M:%S") });
  2521. if (file.existsAsFile())
  2522. {
  2523. rows.push_back ({ tr ("Size"), juce::File::descriptionOfSizeInBytes (file.getSize()) });
  2524. if (file.hasFileExtension (".flp"))
  2525. {
  2526. juce::MemoryBlock head;
  2527. if (juce::FileInputStream in (file); in.openedOk())
  2528. in.readIntoMemoryBlock (head, 4096);
  2529. const auto version = flp::readSavedVersion ({ (const std::uint8_t*) head.getData(), head.getSize() });
  2530. if (! version.empty())
  2531. rows.push_back ({ tr ("Version"), juce::String (version) });
  2532. }
  2533. }
  2534. rows.push_back ({ tr ("Path"), file.getFullPathName() });
  2535. }
  2536. repaint();
  2537. }
  2538. bool hasFile() const noexcept { return file != juce::File(); }
  2539. ui::Hint hintAt (juce::Point<int>) override
  2540. {
  2541. ui::Hint h;
  2542. if (file != juce::File())
  2543. h.text = tr ("Selected: {0}", { file.getFullPathName() });
  2544. return h;
  2545. }
  2546. void paint (juce::Graphics& g) override
  2547. {
  2548. using namespace theme::colour;
  2549. g.fillAll (bg1);
  2550. g.setColour (border);
  2551. g.fillRect (0, 0, getWidth(), 1);
  2552. auto area = getLocalBounds().reduced (6, 3).withTrimmedTop (1);
  2553. g.setFont (theme::font (theme::type::caption));
  2554. constexpr int line = 13, labelWidth = 48;
  2555. for (std::size_t i = 0; i < rows.size() && area.getHeight() >= line; ++i)
  2556. {
  2557. const auto last = i + 1 == rows.size();
  2558. // the path (last row) takes the lines left and wraps, as FL's box does
  2559. auto r = last ? area : area.removeFromTop (line);
  2560. g.setColour (textDisabled);
  2561. g.drawText (rows[i].first, r.removeFromLeft (labelWidth).withHeight (line), juce::Justification::centredLeft, false);
  2562. g.setColour (textSecondary);
  2563. if (last)
  2564. g.drawFittedText (rows[i].second, r, juce::Justification::topLeft, juce::jmax (1, r.getHeight() / line), 1.0f);
  2565. else
  2566. g.drawText (rows[i].second, r, juce::Justification::centredLeft, true);
  2567. }
  2568. }
  2569. private:
  2570. juce::File file;
  2571. std::vector<std::pair<juce::String, juce::String>> rows;
  2572. };
  2573. // --- Hot-swap (round 190ce): the bar -------------------------------------------------------------------
  2574. // 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
  2575. // (the reference shows a coloured banner at the top of its browser with a close button).
  2576. class BrowserComponent::HotSwapBar final : public juce::Component, public ui::HintSource
  2577. {
  2578. public:
  2579. explicit HotSwapBar (BrowserComponent& b) : browser (b) { setRepaintsOnMouseActivity (true); }
  2580. static constexpr int height = 22;
  2581. void paint (juce::Graphics& g) override
  2582. {
  2583. using namespace theme;
  2584. g.setColour (colour::accent);
  2585. g.fillRoundedRectangle (getLocalBounds().toFloat(), radius::md);
  2586. auto r = getLocalBounds().reduced (6, 0);
  2587. const auto x = closeBounds();
  2588. r.setRight (x.getX() - 4);
  2589. g.setColour (juce::Colours::white);
  2590. g.setFont (font (type::caption, true));
  2591. g.drawText (tr ("Swapping {0}", { browser.hotSwapTargetName() }), r, juce::Justification::centredLeft, true); // (the reference: "Swapping Instrument")
  2592. const auto over = isMouseOver() && x.contains (getMouseXYRelative());
  2593. if (over)
  2594. {
  2595. g.setColour (juce::Colours::white.withAlpha (0.22f));
  2596. g.fillRoundedRectangle (x.toFloat(), 3.0f);
  2597. }
  2598. g.setColour (juce::Colours::white);
  2599. const auto c = x.toFloat().reduced (5.0f);
  2600. g.drawLine (c.getX(), c.getY(), c.getRight(), c.getBottom(), 1.6f);
  2601. g.drawLine (c.getX(), c.getBottom(), c.getRight(), c.getY(), 1.6f);
  2602. }
  2603. void mouseUp (const juce::MouseEvent& e) override
  2604. {
  2605. if (closeBounds().contains (e.getPosition()))
  2606. browser.endHotSwap();
  2607. }
  2608. ui::Hint hintAt (juce::Point<int> p) override
  2609. {
  2610. if (closeBounds().contains (p))
  2611. return { tr ("End hot-swap (Esc)"), {}, false, false };
  2612. 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 };
  2613. }
  2614. private:
  2615. juce::Rectangle<int> closeBounds() const { return getLocalBounds().removeFromRight (height).reduced (2); }
  2616. BrowserComponent& browser;
  2617. };
  2618. BrowserComponent::BrowserComponent (AudioEngine& e, Role r)
  2619. : engine (e), role (r)
  2620. {
  2621. tabs = std::make_unique<TabBar> (*this);
  2622. addAndMakeVisible (*tabs);
  2623. swapBar = std::make_unique<HotSwapBar> (*this);
  2624. addChildComponent (*swapBar);
  2625. liveBrowsers().push_back (this);
  2626. // the search index (round 162): a background pass over every folder a few seconds after start (FL's automatic
  2627. // indexing: only the folders that changed since the last session are listed again)
  2628. searcher = SearchShared::get();
  2629. searcher->statusChanged.addChangeListener (this);
  2630. searcher->indexChanged.addChangeListener (this);
  2631. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<BrowserComponent> (this)] {
  2632. if (safe != nullptr && safe->role == Role::main && ! safe->allRoots.isEmpty())
  2633. safe->searcher->service->refresh (toPaths (safe->withMerged (safe->allRoots)));
  2634. });
  2635. // "Find similar samples" (round 190as): once it was used (its index file exists), the folders are checked for new
  2636. // samples in the background a while after start; before that nothing is analysed
  2637. similar = SimilarShared::get (engine);
  2638. similar->statusChanged.addChangeListener (this);
  2639. juce::Timer::callAfterDelay (20000, [safe = juce::Component::SafePointer<BrowserComponent> (this)] {
  2640. if (safe != nullptr && safe->role == Role::main && ! safe->allRoots.isEmpty() && SimilarShared::file().existsAsFile()
  2641. && ! std::exchange (safe->similar->passAsked, true))
  2642. safe->similar->service->refresh (toPaths (safe->withMerged (safe->allRoots)));
  2643. });
  2644. focusWatcher = std::make_unique<FocusWatcher> (*this);
  2645. searchBox.setTextToShowWhenEmpty (tr ("Search (Ctrl+F): kick -loop, snare OR clap, hat*.wav"), theme::colour::textDisabled);
  2646. searchBox.addListener (this);
  2647. searchBox.setEscapeAndReturnKeysConsumed (true);
  2648. ui::setHint (searchBox, tr ("Search the selected folder (or every folder) and below; in PROJECT, the project's items: words must all match; "
  2649. "OR, -word (not), \"exact phrase\", * and ? wildcards [Enter] to the results [Esc] clear"));
  2650. addAndMakeVisible (searchBox);
  2651. // FL's Browser has a way to silence the preview too (issue #9): a Play / Stop toggle on the preview strip, beside
  2652. // the preview volume, as in FL 2026 (audit round 165z-a); the strip adopts both below
  2653. stopButton.setFlat (true);
  2654. stopButton.setWantsKeyboardFocus (false);
  2655. stopButton.setMouseClickGrabsKeyboardFocus (false);
  2656. stopButton.onClick = [this] {
  2657. if (strip != nullptr)
  2658. strip->togglePlay();
  2659. };
  2660. // what this Browser shows (round 163): content filter, folders shown, the Sample browser window
  2661. viewButton.setFlat (true);
  2662. viewButton.setWantsKeyboardFocus (false);
  2663. viewButton.setMouseClickGrabsKeyboardFocus (false);
  2664. viewButton.setClickingTogglesState (false);
  2665. viewButton.onClick = [this] { showViewMenu(); };
  2666. addAndMakeVisible (viewButton);
  2667. // the sample preview volume (FL's Browser has one too): a slider on the preview strip, as in FL 2026
  2668. previewVolume.setSliderStyle (juce::Slider::LinearHorizontal);
  2669. previewVolume.setRange (0.0, controls::maxUtilityVolume, 0.01);
  2670. previewVolume.setDoubleClickReturnValue (true, 1.0);
  2671. previewVolume.textFromValueFunction = [] (double v) { return ui::utilityVolumeText (v); };
  2672. previewVolume.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  2673. previewVolume.setValue (engine.getPreviewVolume(), juce::dontSendNotification);
  2674. previewVolume.setMouseClickGrabsKeyboardFocus (false);
  2675. previewVolume.setWantsKeyboardFocus (false);
  2676. previewVolume.onValueChange = [this] {
  2677. engine.setPreviewVolume (previewVolume.getValue());
  2678. refreshPreviewVolume();
  2679. if (onPreviewVolumeChanged != nullptr)
  2680. onPreviewVolumeChanged();
  2681. };
  2682. refreshPreviewVolume();
  2683. tree = std::make_unique<FileTree> (*this, false);
  2684. results = std::make_unique<FileTree> (*this, true);
  2685. for (auto [view, list] : { std::pair { &treeView, tree.get() }, std::pair { &resultsView, results.get() } })
  2686. {
  2687. *view = std::make_unique<juce::Viewport>();
  2688. (*view)->setViewedComponent (list, false);
  2689. (*view)->setScrollBarsShown (true, false);
  2690. (*view)->setScrollBarThickness (10);
  2691. (*view)->setWantsKeyboardFocus (false);
  2692. }
  2693. addAndMakeVisible (*treeView);
  2694. addChildComponent (*resultsView);
  2695. strip = std::make_unique<PreviewStrip> (*this);
  2696. addAndMakeVisible (*strip);
  2697. strip->adoptControls();
  2698. details = std::make_unique<DetailsBox>();
  2699. addChildComponent (*details);
  2700. rebuildRoots();
  2701. engine.addChangeListener (this);
  2702. }
  2703. juce::File BrowserComponent::userFoldersFile()
  2704. {
  2705. return PluginHost::settingsFolder().getChildFile ("browser-folders.txt");
  2706. }
  2707. juce::File BrowserComponent::starredFile()
  2708. {
  2709. return PluginHost::settingsFolder().getChildFile ("browser-starred.txt");
  2710. }
  2711. void BrowserComponent::setStarred (const juce::File& file, bool on)
  2712. {
  2713. setInCollection (file.getFullPathName().toStdString(), 0, on);
  2714. }
  2715. // --- Collections (round 190ce) ------------------------------------------------------------------------
  2716. juce::File BrowserComponent::collectionsFile()
  2717. {
  2718. return PluginHost::settingsFolder().getChildFile ("browser-collections.txt");
  2719. }
  2720. collections::Store& BrowserComponent::collectionStore()
  2721. {
  2722. static collections::Store store;
  2723. return store;
  2724. }
  2725. std::vector<BrowserComponent*>& BrowserComponent::liveBrowsers()
  2726. {
  2727. static std::vector<BrowserComponent*> all;
  2728. return all;
  2729. }
  2730. void BrowserComponent::loadCollections()
  2731. {
  2732. if (const auto file = collectionsFile(); file.existsAsFile())
  2733. {
  2734. collectionStore() = collections::Store::fromText (file.loadFileAsString().toStdString());
  2735. return;
  2736. }
  2737. // before round 190ce: one starred path per line
  2738. std::vector<std::string> paths;
  2739. for (const auto& line : juce::StringArray::fromLines (starredFile().loadFileAsString()))
  2740. if (line.trim().isNotEmpty() && juce::File::isAbsolutePath (line.trim()))
  2741. paths.push_back (line.trim().toStdString());
  2742. collectionStore() = collections::Store::fromStarred (paths);
  2743. }
  2744. void BrowserComponent::saveCollections()
  2745. {
  2746. const auto& store = collectionStore();
  2747. collectionsFile().getParentDirectory().createDirectory();
  2748. collectionsFile().replaceWithText (juce::String::fromUTF8 (store.toText().c_str()));
  2749. juce::String starredText; // (an older LYNX SHARE reads this one)
  2750. for (const auto& path : store.starredPaths())
  2751. starredText << juce::String::fromUTF8 (path.c_str()) << "\n";
  2752. starredFile().replaceWithText (starredText);
  2753. }
  2754. juce::String BrowserComponent::collectionName (int collection)
  2755. {
  2756. const auto& store = collectionStore();
  2757. if (store.hasOwnName (collection))
  2758. return juce::String::fromUTF8 (store.name (collection).c_str());
  2759. switch (collection)
  2760. {
  2761. case 0: return tr ("Starred");
  2762. case 1: return tr ("Orange");
  2763. case 2: return tr ("Yellow");
  2764. case 3: return tr ("Green");
  2765. case 4: return tr ("Blue");
  2766. case 5: return tr ("Purple");
  2767. case 6: return tr ("Gray");
  2768. default: return {};
  2769. }
  2770. }
  2771. juce::Colour BrowserComponent::collectionColour (int collection)
  2772. {
  2773. return juce::Colour (collections::colourArgb (collection));
  2774. }
  2775. void BrowserComponent::collectionsChanged()
  2776. {
  2777. for (auto* b : liveBrowsers())
  2778. {
  2779. if (b->tab == starredTab)
  2780. {
  2781. const auto row = b->tree->getSelectedRow();
  2782. const auto scroll = b->treeView->getViewPosition();
  2783. b->rebuildTree();
  2784. if (row >= 0 && b->tree->numRows() > 0)
  2785. b->tree->select (juce::jmin (row, b->tree->numRows() - 1), false);
  2786. b->treeView->setViewPosition (scroll);
  2787. }
  2788. b->tree->repaint();
  2789. b->results->repaint();
  2790. }
  2791. }
  2792. void BrowserComponent::setInCollection (const std::string& item, int collection, bool on)
  2793. {
  2794. if (! collectionStore().label (item, collection, on)) // (a hidden collection shows itself: round 190cy)
  2795. return;
  2796. saveCollections();
  2797. collectionsChanged();
  2798. }
  2799. void BrowserComponent::toggleCollectionOnSelection (int collection)
  2800. {
  2801. auto& list = activeList();
  2802. const auto item = list.selectedItem();
  2803. if (item.empty())
  2804. {
  2805. ui::postHint ({ tr ("Select a file, a folder or a plugin in the Browser first"), {} }, 2500);
  2806. return;
  2807. }
  2808. const auto label = list.selectedLabel();
  2809. const auto on = ! collectionStore().has (item, collection);
  2810. setInCollection (item, collection, on);
  2811. ui::postHint ({ on ? tr ("Added to the collection {0}", { collectionName (collection) }) : tr ("Removed from the collection {0}", { collectionName (collection) }), label }, 2500);
  2812. }
  2813. void BrowserComponent::clearCollectionsOnSelection()
  2814. {
  2815. auto& list = activeList();
  2816. const auto item = list.selectedItem();
  2817. if (item.empty())
  2818. return;
  2819. const auto label = list.selectedLabel();
  2820. if (! collectionStore().clear (item))
  2821. return;
  2822. saveCollections();
  2823. collectionsChanged();
  2824. ui::postHint ({ tr ("Removed from every collection"), label }, 2500);
  2825. }
  2826. void BrowserComponent::setCollectionShown (int collection, bool shown)
  2827. {
  2828. auto& store = collectionStore();
  2829. store.setShown (collection, shown);
  2830. if (store.shown().empty()) // (one stays: Starred)
  2831. store.setShown (0, true);
  2832. saveCollections();
  2833. collectionsChanged();
  2834. }
  2835. void BrowserComponent::renameCollection (int collection)
  2836. {
  2837. auto* window = new juce::AlertWindow (tr ("Rename collection"), tr ("Name of the collection (empty: its default name):"), juce::MessageBoxIconType::NoIcon, this);
  2838. window->addTextEditor ("name", juce::String::fromUTF8 (collectionStore().labels[(std::size_t) juce::jlimit (0, collections::count - 1, collection)].name.c_str()));
  2839. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  2840. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  2841. juce::Component::SafePointer<BrowserComponent> safe (this);
  2842. window->enterModalState (true, juce::ModalCallbackFunction::create ([window, safe, collection] (int result) {
  2843. if (result != 1 || safe == nullptr)
  2844. return;
  2845. collectionStore().rename (collection, window->getTextEditorContents ("name").toStdString());
  2846. saveCollections();
  2847. safe->collectionsChanged();
  2848. }), true);
  2849. }
  2850. // The collections in a row's menu. Clip-launch workflow (round 190cy, Live 12.4.16 live check 190cw shot 05): a flat
  2851. // list in the menu itself, "Clear all colours" (0) then the seven with their keys (1-7), ticked when the item is in
  2852. // one; renaming and showing / hiding are on a collection's heading. Pattern workflow: as round 190ce built it, a
  2853. // "Collections" sub-menu with the seven, "Remove from all", which collections the STARRED tab lists and their names.
  2854. void BrowserComponent::addCollectionItems (juce::PopupMenu& menu, const std::string& item)
  2855. {
  2856. if (item.empty())
  2857. return;
  2858. juce::Component::SafePointer<BrowserComponent> safe (this);
  2859. const auto& store = collectionStore();
  2860. if (liveItemMenus)
  2861. {
  2862. menu.addSeparator();
  2863. menu.addItem (tr ("Clear all colours") + "\t0", store.mask (item) != 0, false, [safe, item] {
  2864. if (safe == nullptr || ! collectionStore().clear (item))
  2865. return;
  2866. saveCollections();
  2867. safe->collectionsChanged();
  2868. });
  2869. for (int c = 0; c < collections::count; ++c)
  2870. {
  2871. juce::PopupMenu::Item entry (collectionName (c) + "\t" + juce::String (c + 1));
  2872. entry.setTicked (store.has (item, c));
  2873. entry.setColour (collectionColour (c).brighter (0.25f));
  2874. entry.setAction ([safe, item, c] {
  2875. if (safe != nullptr)
  2876. safe->setInCollection (item, c, ! collectionStore().has (item, c));
  2877. });
  2878. menu.addItem (entry);
  2879. }
  2880. menu.addSeparator();
  2881. return;
  2882. }
  2883. juce::PopupMenu sub;
  2884. for (int c = 0; c < collections::count; ++c)
  2885. {
  2886. juce::PopupMenu::Item entry (collectionName (c) + "\t" + juce::String (c + 1));
  2887. entry.setTicked (store.has (item, c));
  2888. entry.setColour (collectionColour (c).brighter (0.25f));
  2889. entry.setAction ([safe, item, c] {
  2890. if (safe != nullptr)
  2891. safe->setInCollection (item, c, ! collectionStore().has (item, c));
  2892. });
  2893. sub.addItem (entry);
  2894. }
  2895. sub.addSeparator();
  2896. sub.addItem (tr ("Remove from all") + "\t0", store.mask (item) != 0, false, [safe, item] {
  2897. if (safe == nullptr || ! collectionStore().clear (item))
  2898. return;
  2899. saveCollections();
  2900. safe->collectionsChanged();
  2901. });
  2902. sub.addSeparator();
  2903. juce::PopupMenu show, rename;
  2904. for (int c = 0; c < collections::count; ++c)
  2905. {
  2906. show.addItem (collectionName (c), true, store.isShown (c), [safe, c] {
  2907. if (safe != nullptr)
  2908. safe->setCollectionShown (c, ! collectionStore().isShown (c));
  2909. });
  2910. rename.addItem (collectionName (c), [safe, c] {
  2911. if (safe != nullptr)
  2912. safe->renameCollection (c);
  2913. });
  2914. }
  2915. sub.addSubMenu (tr ("Show in the STARRED tab"), show);
  2916. sub.addSubMenu (tr ("Rename"), rename);
  2917. menu.addSubMenu (tr ("Collections"), sub);
  2918. }
  2919. juce::PopupMenu BrowserComponent::collectionsMenuForSnapshot (const std::string& item)
  2920. {
  2921. juce::PopupMenu menu;
  2922. addCollectionItems (menu, item);
  2923. // (the shot shows the sub-menu's own items: a picture of a menu does not open its sub-menus)
  2924. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  2925. if (it.getItem().subMenu != nullptr)
  2926. return *it.getItem().subMenu;
  2927. return menu;
  2928. }
  2929. void BrowserComponent::selectRowForSnapshot (const juce::String& label)
  2930. {
  2931. auto& list = activeList();
  2932. for (int i = 0; i < list.numRows(); ++i)
  2933. {
  2934. list.select (i, false);
  2935. if (list.selectedLabel() == label)
  2936. return;
  2937. }
  2938. }
  2939. // --- Hot-swap (round 190ce) ---------------------------------------------------------------------------
  2940. juce::String BrowserComponent::hotSwapTargetName() const
  2941. {
  2942. const auto& song = engine.getSong();
  2943. const auto& t = swapSession.target;
  2944. if (t.kind == hotswap::Kind::effect)
  2945. {
  2946. if (const auto at = hotswap::findEffect (song, t.instance); at.found())
  2947. return quickpick::slotName (engine, song.mixer[(std::size_t) at.track].effects[(std::size_t) at.slot]);
  2948. }
  2949. else if (t.kind == hotswap::Kind::channel)
  2950. {
  2951. if (const auto c = hotswap::findChannel (song, t.instance); c >= 0)
  2952. return juce::String::fromUTF8 (song.channels[(std::size_t) c].name.c_str());
  2953. }
  2954. return {};
  2955. }
  2956. void BrowserComponent::beginHotSwap (const hotswap::Target& target)
  2957. {
  2958. const auto& song = engine.getSong();
  2959. if (! hotswap::exists (song, target))
  2960. return;
  2961. swapSession.begin (target, tab, searchBox.getText().toStdString());
  2962. if (searchBox.getText().isNotEmpty())
  2963. {
  2964. searchBox.setText ({}, false);
  2965. runSearch();
  2966. }
  2967. // the Browser goes to what can take the device's place: a sample channel's own sample in its folder, else the
  2968. // Plugin database's effects or generators
  2969. bool shown = false;
  2970. if (target.kind == hotswap::Kind::channel)
  2971. if (const auto c = hotswap::findChannel (song, target.instance); c >= 0 && hotswap::playsSample (song.channels[(std::size_t) c]))
  2972. {
  2973. const juce::File sample (juce::String::fromUTF8 (song.channels[(std::size_t) c].samplePath.c_str()));
  2974. setTab (allTab);
  2975. if (sample.existsAsFile())
  2976. if (const auto row = tree->revealFile (sample); row >= 0)
  2977. {
  2978. tree->select (row, false);
  2979. shown = true;
  2980. }
  2981. shown = shown || sample == juce::File() || ! sample.existsAsFile(); // (no sample yet: the folders as they are)
  2982. }
  2983. // an effect with a preset: that preset, as Live starts hot-swap on the device's current preset (round 190cy)
  2984. if (! shown && target.kind == hotswap::Kind::effect)
  2985. shown = revealCurrentPreset (target);
  2986. if (! shown)
  2987. showPluginDatabase ({}, target.kind == hotswap::Kind::channel ? 1 : 0);
  2988. swapBar->setVisible (true);
  2989. swapBar->repaint();
  2990. resized();
  2991. if (onHotSwapChanged != nullptr)
  2992. onHotSwapChanged();
  2993. }
  2994. bool BrowserComponent::revealCurrentPreset (const hotswap::Target& target)
  2995. {
  2996. const auto& song = engine.getSong();
  2997. const auto at = hotswap::findEffect (song, target.instance);
  2998. if (! at.found())
  2999. return false;
  3000. const auto& fx = song.mixer[(std::size_t) at.track].effects[(std::size_t) at.slot];
  3001. if (fx.presetName.empty())
  3002. return false;
  3003. // the files the effect's presets come from: FL's preset folders of the plugin it stands for (the editor's preset
  3004. // list, round 168r) and LYNX's own saved presets of the effect
  3005. juce::Array<juce::File> files, folders;
  3006. if (const auto roots = findFlStudioRoots(); ! roots.data.empty())
  3007. for (const auto& plugin : flPluginsForEffect (fx.kind))
  3008. {
  3009. const auto paths = presetcycle::pluginPresetFolders (roots, false, plugin);
  3010. for (const auto& folder : paths)
  3011. folders.addIfNotAlreadyThere (juce::File (juce::String::fromUTF8 (folder.c_str())));
  3012. for (const auto& p : presetcycle::listPresets (paths))
  3013. files.add (juce::File (juce::String::fromUTF8 (p.path.c_str())));
  3014. }
  3015. folders.add (pluginheader::userFolder (fx.kind));
  3016. files.addArray (pluginheader::userPresets (fx.kind));
  3017. const auto name = juce::String::fromUTF8 (fx.presetName.c_str());
  3018. const auto current = std::find_if (files.begin(), files.end(), [&name] (const juce::File& f) { return f.getFileNameWithoutExtension() == name; });
  3019. if (current == files.end())
  3020. return false;
  3021. const auto file = *current;
  3022. setTab (allTab);
  3023. if (const auto row = tree->revealFile (file); row >= 0)
  3024. {
  3025. tree->select (row, false);
  3026. return true;
  3027. }
  3028. resultsView->setVisible (true);
  3029. treeView->setVisible (false);
  3030. results->setFiles (files, folders, tr ("Presets of {0}", { hotSwapTargetName() }));
  3031. results->select (files.indexOf (file), false);
  3032. presetsListed = true;
  3033. return true;
  3034. }
  3035. void BrowserComponent::endHotSwap()
  3036. {
  3037. if (! swapSession.active())
  3038. return;
  3039. const auto back = swapSession.end();
  3040. swapBar->setVisible (false);
  3041. setTab (back.tab);
  3042. if (std::exchange (presetsListed, false) || searchBox.getText() != juce::String::fromUTF8 (back.search.c_str()))
  3043. {
  3044. searchBox.setText (juce::String::fromUTF8 (back.search.c_str()), false);
  3045. runSearch();
  3046. }
  3047. resized();
  3048. if (onHotSwapChanged != nullptr)
  3049. onHotSwapChanged();
  3050. }
  3051. void BrowserComponent::hotSwapRefused()
  3052. {
  3053. ui::postHint ({ tr ("Hot-swap: this can't take the place of {0}", { hotSwapTargetName() }), {} }, 3000);
  3054. }
  3055. bool BrowserComponent::hotSwapLoadSelected()
  3056. {
  3057. if (! swapSession.active())
  3058. return false;
  3059. const auto* n = activeList().selectedNode();
  3060. if (n == nullptr || n->folder)
  3061. return true; // (the mode keeps Enter: nothing is added to the project while it is on)
  3062. if (n->kind == FileTree::Kind::plugin)
  3063. {
  3064. if (! hotSwapLoadPlugin (n->generator, n->effect))
  3065. hotSwapRefused();
  3066. return true;
  3067. }
  3068. if (n->kind == FileTree::Kind::file && n->file.existsAsFile())
  3069. {
  3070. if (! hotSwapLoadFile (n->file))
  3071. hotSwapRefused();
  3072. return true;
  3073. }
  3074. hotSwapRefused();
  3075. return true;
  3076. }
  3077. bool BrowserComponent::hotSwapLoadPlugin (const std::function<std::optional<ChannelDef>()>& generator, const std::function<std::optional<EffectSlot>()>& effect)
  3078. {
  3079. const auto target = swapSession.target;
  3080. hotswap::Target now;
  3081. if (target.kind == hotswap::Kind::effect && effect)
  3082. {
  3083. auto fx = effect();
  3084. if (! fx)
  3085. return false;
  3086. engine.editSong ([&now, target, fx = std::move (*fx)] (Song& song) mutable { now = hotswap::swapEffect (song, target, std::move (fx)); });
  3087. }
  3088. else if (target.kind == hotswap::Kind::channel && generator)
  3089. {
  3090. auto c = generator();
  3091. if (! c)
  3092. return false;
  3093. if (const auto channel = hotswap::findChannel (engine.getSong(), target.instance); channel >= 0 && onHotSwapWillReplaceInstrument != nullptr)
  3094. onHotSwapWillReplaceInstrument (channel);
  3095. engine.editSong ([&now, target, c = std::move (*c)] (Song& song) mutable { now = hotswap::swapInstrument (song, target, std::move (c)); });
  3096. }
  3097. else
  3098. return false;
  3099. if (! now.active())
  3100. return false;
  3101. swapSession.retarget (now);
  3102. swapBar->repaint();
  3103. if (onHotSwapChanged != nullptr)
  3104. onHotSwapChanged();
  3105. return true;
  3106. }
  3107. bool BrowserComponent::hotSwapLoadFile (const juce::File& file)
  3108. {
  3109. const auto target = swapSession.target;
  3110. const auto& song = engine.getSong();
  3111. const auto loaded = [this] {
  3112. swapSession.loaded();
  3113. swapBar->repaint();
  3114. return true;
  3115. };
  3116. // a hosted plugin's own preset into the linked plugin (as its window's preset menu loads it)
  3117. if (pluginpresetui::isPresetFile (file) && (! file.hasFileExtension ("lynxpreset") || pluginpresetui::readLynxPreset (file).has_value()))
  3118. {
  3119. juce::AudioPluginInstance* plugin = nullptr;
  3120. if (target.kind == hotswap::Kind::effect)
  3121. {
  3122. if (const auto at = hotswap::findEffect (song, target.instance); at.found())
  3123. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (at.track, at.slot).get()))
  3124. plugin = &p->getInstance();
  3125. }
  3126. else if (const auto c = hotswap::findChannel (song, target.instance); c >= 0)
  3127. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (c).get()))
  3128. plugin = &p->getInstance();
  3129. juce::String error;
  3130. if (plugin == nullptr || ! pluginpresetui::load (*plugin, file, error))
  3131. return false;
  3132. engine.markModified();
  3133. // the device comes in on, as the preset loads it (round 190cy, Live 12.4.16)
  3134. 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)
  3135. engine.editSong ([target] (Song& s) { hotswap::presetLoadedInto (s, target); });
  3136. return loaded();
  3137. }
  3138. switch (hotswap::candidateFor (song, target, file.getFileName().toStdString()))
  3139. {
  3140. case hotswap::Candidate::effectPreset:
  3141. {
  3142. const auto at = hotswap::findEffect (song, target.instance);
  3143. if (file.hasFileExtension ("lynxpreset")) // one of LYNX's presets of this very effect: its settings only
  3144. {
  3145. const auto kind = song.mixer[(std::size_t) at.track].effects[(std::size_t) at.slot].kind;
  3146. const auto preset = presets::fromText (kind, file.loadFileAsString().toStdString());
  3147. if (! preset)
  3148. return false;
  3149. const auto name = preset->name.empty() ? file.getFileNameWithoutExtension().toStdString() : preset->name;
  3150. bool ok = false;
  3151. engine.editSong ([&ok, target, kind, &preset, &name] (Song& s) {
  3152. ok = hotswap::swapEffectPreset (s, target, kind, preset->params, preset->hasState ? &preset->state : nullptr, name);
  3153. });
  3154. return ok && loaded();
  3155. }
  3156. juce::MemoryBlock data;
  3157. if (! file.loadFileAsData (data))
  3158. return false;
  3159. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  3160. auto fx = effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), song.bpm, natives::flDataReader (flStudioAccess()));
  3161. if (! fx)
  3162. return false;
  3163. hotswap::Target now;
  3164. engine.editSong ([&now, target, fx = std::move (*fx)] (Song& s) mutable { now = hotswap::swapEffect (s, target, std::move (fx)); });
  3165. if (! now.active())
  3166. return false;
  3167. swapSession.retarget (now);
  3168. swapBar->repaint();
  3169. if (onHotSwapChanged != nullptr)
  3170. onHotSwapChanged();
  3171. return true;
  3172. }
  3173. case hotswap::Candidate::synthPreset:
  3174. {
  3175. juce::MemoryBlock data;
  3176. if (! file.loadFileAsData (data))
  3177. return false;
  3178. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  3179. const auto synth = synthFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()));
  3180. if (! synth)
  3181. return false;
  3182. ChannelDef c;
  3183. c.name = file.getFileNameWithoutExtension().toStdString();
  3184. c.instrument = InstrumentKind::synth;
  3185. c.synth = *synth;
  3186. return hotSwapLoadPlugin ([c] { return std::optional<ChannelDef> (c); }, {});
  3187. }
  3188. case hotswap::Candidate::sample:
  3189. {
  3190. const auto channel = hotswap::findChannel (song, target.instance);
  3191. if (channel < 0 || onHotSwapSample == nullptr)
  3192. return false;
  3193. onHotSwapSample (channel, file); // (the Channel Rack's own sample load: .speech files ask first)
  3194. return loaded();
  3195. }
  3196. default: break;
  3197. }
  3198. return false;
  3199. }
  3200. // --- what this Browser shows (round 163) ------------------------------------------------------------
  3201. juce::File BrowserComponent::viewFile (Role r)
  3202. {
  3203. return PluginHost::settingsFolder().getChildFile (r == Role::samples ? "sample-browser-view.txt" : "browser-view.txt");
  3204. }
  3205. bool BrowserComponent::sampleBrowserWasOpen()
  3206. {
  3207. return browserview::View::fromText (viewFile (Role::samples).loadFileAsString().toStdString()).open;
  3208. }
  3209. juce::Rectangle<int> BrowserComponent::sampleBrowserBounds()
  3210. {
  3211. const auto v = browserview::View::fromText (viewFile (Role::samples).loadFileAsString().toStdString());
  3212. return { v.x, v.y, v.width, v.height };
  3213. }
  3214. void BrowserComponent::loadView()
  3215. {
  3216. viewLoaded = true;
  3217. const auto file = viewFile (role);
  3218. viewFromFile = file.existsAsFile();
  3219. if (viewFromFile)
  3220. {
  3221. view = browserview::View::fromText (file.loadFileAsString().toStdString());
  3222. return;
  3223. }
  3224. view = {};
  3225. if (role == Role::samples)
  3226. {
  3227. // the Sample browser starts with only the places samples live, listing samples and SoundFonts
  3228. view.filter = browserview::ContentFilter::samples;
  3229. view.setShown (browserview::projectRootId, false);
  3230. view.setShown (browserview::pluginsRootId, false);
  3231. for (int i = 0; i < allRoots.size(); ++i)
  3232. if (! browserview::sampleBrowserShowsByDefault (allRootKinds[(std::size_t) i]))
  3233. view.setShown (allRoots[i].getFullPathName().toStdString(), false);
  3234. }
  3235. }
  3236. void BrowserComponent::saveView() const
  3237. {
  3238. if (! viewLoaded)
  3239. return;
  3240. const auto file = viewFile (role);
  3241. auto v = view;
  3242. if (role == Role::samples) // the window's open state and bounds are the window's to write
  3243. {
  3244. const auto old = browserview::View::fromText (file.loadFileAsString().toStdString());
  3245. v.open = old.open;
  3246. v.x = old.x, v.y = old.y, v.width = old.width, v.height = old.height;
  3247. }
  3248. file.getParentDirectory().createDirectory();
  3249. file.replaceWithText (juce::String::fromUTF8 (v.toText().c_str()));
  3250. }
  3251. bool BrowserComponent::lists (const juce::File& file) const
  3252. {
  3253. return browserview::listed (file.getFileName().toStdString(), view.filter) || file.isDirectory();
  3254. }
  3255. std::shared_ptr<const search::FolderMatches> BrowserComponent::filterMatches() const
  3256. {
  3257. if (view.filter == browserview::ContentFilter::all || searcher == nullptr)
  3258. return nullptr;
  3259. const auto filter = view.filter;
  3260. return searcher->service->folderMatches ((int) filter, [filter] (const std::string& name) { return browserview::listed (name, filter); });
  3261. }
  3262. bool BrowserComponent::filterHides (const juce::File& folder) const
  3263. {
  3264. // from the search index (cached; never waits for it): a folder it doesn't know yet stays listed
  3265. const auto matches = filterMatches();
  3266. return matches != nullptr && matches->of (folder.getFullPathName().toStdString()) == search::FolderMatches::Contents::none;
  3267. }
  3268. void BrowserComponent::applyFilterToTree()
  3269. {
  3270. const auto matches = filterMatches();
  3271. if (matches == nullptr || matches->generation == prunedGeneration)
  3272. return;
  3273. prunedGeneration = matches->generation;
  3274. if (tree->pruneFolders ([this] (const juce::File& f) { return filterHides (f); }))
  3275. treeView->setViewPosition (treeView->getViewPosition()); // (keeps the scroll inside the shorter list)
  3276. }
  3277. void BrowserComponent::setContentFilter (browserview::ContentFilter filter)
  3278. {
  3279. if (filter == view.filter)
  3280. return;
  3281. view.filter = filter;
  3282. saveView();
  3283. refreshViewButton();
  3284. prunedGeneration = 0;
  3285. rebuildTree();
  3286. refreshFoldersPanel();
  3287. if (searchBox.getText().trim().isNotEmpty())
  3288. runSearch();
  3289. }
  3290. void BrowserComponent::setRootShown (const juce::String& id, bool shown)
  3291. {
  3292. if (view.shows (id.toStdString()) == shown)
  3293. return;
  3294. view.setShown (id.toStdString(), shown);
  3295. saveView();
  3296. rebuildRoots();
  3297. if (searchBox.getText().trim().isNotEmpty())
  3298. runSearch();
  3299. }
  3300. void BrowserComponent::showAllRoots()
  3301. {
  3302. view.hidden.clear();
  3303. view.excluded.clear(); // (and every folder of the merged roots, round 178a)
  3304. saveView();
  3305. rebuildRoots();
  3306. }
  3307. juce::String BrowserComponent::rootId (const juce::File& folder) const
  3308. {
  3309. return allRoots.contains (folder) ? folder.getFullPathName() : juce::String();
  3310. }
  3311. void BrowserComponent::refreshViewButton()
  3312. {
  3313. const auto filtered = view.filter != browserview::ContentFilter::all;
  3314. int hidden = 0;
  3315. for (const auto& id : view.hidden)
  3316. hidden += id == browserview::projectRootId || id == browserview::pluginsRootId
  3317. || allRoots.contains (juce::File (juce::String::fromUTF8 (id.c_str())))
  3318. ? 1 : 0;
  3319. viewButton.setToggleState (filtered || hidden > 0, juce::dontSendNotification);
  3320. juce::String text = tr ("Browser options: what to list, which folders to show");
  3321. if (filtered)
  3322. text << " (" << tr (browserview::contentFilterLabel (view.filter)) << ")";
  3323. if (hidden > 0)
  3324. text << " (" << (hidden == 1 ? tr ("1 folder hidden") : tr ("{0} folders hidden", { juce::String (hidden) })) << ")";
  3325. viewButton.setTooltip (text);
  3326. ui::setHint (viewButton, text, true);
  3327. }
  3328. void BrowserComponent::addHideItem (juce::PopupMenu& menu, const juce::String& id, const juce::String& label)
  3329. {
  3330. menu.addItem (tr ("Hide \"{0}\" from this Browser", { label }), [safe = juce::Component::SafePointer<BrowserComponent> (this), id] {
  3331. if (safe != nullptr)
  3332. safe->setRootShown (id, false);
  3333. });
  3334. }
  3335. void BrowserComponent::addViewItems (juce::PopupMenu& menu)
  3336. {
  3337. juce::Component::SafePointer<BrowserComponent> safe (this);
  3338. // what is listed (folders are always listed)
  3339. juce::PopupMenu filters;
  3340. for (int i = 0; i < browserview::contentFilterCount; ++i)
  3341. {
  3342. const auto f = (browserview::ContentFilter) i;
  3343. filters.addItem (tr (browserview::contentFilterLabel (f)), true, view.filter == f, [safe, f] {
  3344. if (safe != nullptr)
  3345. safe->setContentFilter (f);
  3346. });
  3347. }
  3348. menu.addSubMenu (tr ("Show") + ": " + tr (browserview::contentFilterLabel (view.filter)), filters);
  3349. // which top-level entries are shown and the user's own folders: a window (round 164; a checklist sub-menu before)
  3350. menu.addItem (tr ("Show folders..."), [safe] {
  3351. if (safe != nullptr)
  3352. safe->showFoldersDialog();
  3353. });
  3354. }
  3355. // --- the "Show folders" window (round 164) --------------------------------------------------------------
  3356. // Which top-level entries this Browser shows, as a checklist (ticks apply at once), the user's own folders with a
  3357. // Remove button, Add folder..., Show all. Each entry says where it is and, under a content filter, whether it holds
  3358. // anything to list (those folders are left out of the tree while the filter is on).
  3359. class BrowserComponent::FoldersPanel final : public juce::Component
  3360. {
  3361. public:
  3362. using Entry = FolderEntry;
  3363. explicit FoldersPanel (BrowserComponent* b) : browser (b)
  3364. {
  3365. title.setFont (theme::font (theme::type::body, true));
  3366. title.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  3367. addAndMakeVisible (title);
  3368. note.setFont (theme::font (theme::type::small));
  3369. note.setColour (juce::Label::textColourId, theme::colour::textSecondary);
  3370. note.setJustificationType (juce::Justification::topLeft);
  3371. addAndMakeVisible (note);
  3372. list.setViewedComponent (&rows, false);
  3373. list.setScrollBarsShown (true, false);
  3374. list.setScrollBarThickness (10);
  3375. addAndMakeVisible (list);
  3376. addFolder.setButtonText (tr ("Add folder..."));
  3377. addFolder.setTooltip (tr ("Add one of your own folders to the Browsers (samples, projects, SoundFonts...)"));
  3378. addFolder.onClick = [this] { if (browser != nullptr) browser->addUserFolder(); };
  3379. showAll.setButtonText (tr ("Show all"));
  3380. showAll.setTooltip (tr ("Tick every folder"));
  3381. showAll.onClick = [this] { if (browser != nullptr) browser->showAllRoots(); };
  3382. close.setButtonText (tr ("Close"));
  3383. close.setColour (juce::TextButton::buttonColourId, theme::colour::accent);
  3384. close.setColour (juce::TextButton::textColourOffId, theme::colour::onAccent);
  3385. close.onClick = [this] { closeToolWindowOf (*this); };
  3386. for (auto* button : { &addFolder, &showAll, &close })
  3387. addAndMakeVisible (button);
  3388. refresh();
  3389. setSize (520, 470);
  3390. }
  3391. // the browser's entries again (a tick, an added / removed folder, the filter changed)
  3392. void refresh()
  3393. {
  3394. if (browser == nullptr)
  3395. return;
  3396. setEntries (browser->folderEntries(), browser->role == Role::samples,
  3397. browser->view.filter == browserview::ContentFilter::all ? juce::String() : tr (browserview::contentFilterLabel (browser->view.filter)));
  3398. }
  3399. void setEntries (std::vector<Entry> newEntries, bool sampleBrowser, const juce::String& filterName)
  3400. {
  3401. entries = std::move (newEntries);
  3402. title.setText (sampleBrowser ? tr ("Folders shown in the Sample browser") : tr ("Folders shown in the Browser"), juce::dontSendNotification);
  3403. auto text = tr ("Untick what you don't use: it leaves this Browser and its searches. Nothing is deleted.");
  3404. if (filterName.isNotEmpty())
  3405. text << "\n" << tr ("Listing \"{0}\": folders with nothing of that kind are left out of the tree.", { filterName });
  3406. note.setText (text, juce::dontSendNotification);
  3407. int shown = 0;
  3408. for (const auto& e : entries)
  3409. shown += e.shown ? 1 : 0;
  3410. showAll.setEnabled (shown < (int) entries.size());
  3411. rows.deleteAllChildren();
  3412. for (int i = 0; i < (int) entries.size(); ++i)
  3413. rows.addAndMakeVisible (new Row (*this, i));
  3414. layoutRows();
  3415. }
  3416. void resized() override
  3417. {
  3418. auto area = getLocalBounds().reduced (14, 12);
  3419. title.setBounds (area.removeFromTop (22));
  3420. note.setBounds (area.removeFromTop (note.getText().containsChar ('\n') ? 36 : 20));
  3421. area.removeFromTop (6);
  3422. auto bottom = area.removeFromBottom (28);
  3423. close.setBounds (bottom.removeFromRight (90));
  3424. addFolder.setBounds (bottom.removeFromLeft (120));
  3425. bottom.removeFromLeft (8);
  3426. showAll.setBounds (bottom.removeFromLeft (90));
  3427. area.removeFromBottom (10);
  3428. list.setBounds (area);
  3429. layoutRows();
  3430. }
  3431. void paint (juce::Graphics& g) override
  3432. {
  3433. g.fillAll (theme::colour::bg2);
  3434. g.setColour (theme::colour::border);
  3435. g.drawRect (list.getBounds().expanded (1), 1);
  3436. }
  3437. static constexpr int rowHeight = 34;
  3438. private:
  3439. struct Row final : public juce::Component
  3440. {
  3441. Row (FoldersPanel& p, int i) : panel (p), index (i)
  3442. {
  3443. const auto& e = panel.entries[(std::size_t) i];
  3444. tick.setToggleState (e.shown, juce::dontSendNotification);
  3445. tick.setTooltip (e.shown ? tr ("Shown: untick to hide it from this Browser") : tr ("Hidden: tick to show it"));
  3446. tick.onClick = [this] { panel.toggle (index, tick.getToggleState()); };
  3447. addAndMakeVisible (tick);
  3448. if (e.user)
  3449. {
  3450. remove.setTooltip (tr ("Remove this folder from the Browsers (the folder itself stays on the disk)"));
  3451. remove.setFlat (true);
  3452. remove.onClick = [this] { panel.remove (index); };
  3453. addAndMakeVisible (remove);
  3454. }
  3455. }
  3456. void resized() override
  3457. {
  3458. auto area = getLocalBounds().reduced (6, 0);
  3459. tick.setBounds (area.removeFromLeft (26).withSizeKeepingCentre (24, 24));
  3460. if (remove.isVisible())
  3461. remove.setBounds (area.removeFromRight (26).withSizeKeepingCentre (22, 22));
  3462. }
  3463. void paint (juce::Graphics& g) override
  3464. {
  3465. const auto& e = panel.entries[(std::size_t) index];
  3466. if (index % 2 == 1)
  3467. g.fillAll (theme::colour::bg2.brighter (0.06f));
  3468. auto area = getLocalBounds().reduced (6, 2).withTrimmedLeft (32).withTrimmedRight (remove.isVisible() ? 30 : 0);
  3469. auto top = area.removeFromTop (area.getHeight() / 2 + 1);
  3470. g.setFont (theme::font (theme::type::body, e.shown));
  3471. g.setColour (e.shown ? theme::colour::textPrimary : theme::colour::textDisabled);
  3472. juce::String name = e.name;
  3473. if (e.user)
  3474. name << " " << tr ("(your folder)");
  3475. g.drawText (name, top, juce::Justification::bottomLeft, true);
  3476. g.setFont (theme::font (theme::type::small));
  3477. g.setColour (theme::colour::textDisabled);
  3478. auto detail = e.path;
  3479. if (e.empty)
  3480. detail = tr ("nothing to list under the filter") + " · " + detail;
  3481. g.drawFittedText (detail, area, juce::Justification::topLeft, 1, 0.9f);
  3482. }
  3483. void mouseUp (const juce::MouseEvent& e) override
  3484. {
  3485. if (e.mouseWasClicked() && ! e.mods.isPopupMenu())
  3486. tick.triggerClick(); // the whole row ticks
  3487. }
  3488. FoldersPanel& panel;
  3489. int index;
  3490. juce::ToggleButton tick;
  3491. IconButton remove { "remove folder", Icon::close };
  3492. };
  3493. void layoutRows()
  3494. {
  3495. const auto width = list.getWidth() - (entries.size() * (std::size_t) rowHeight > (std::size_t) list.getHeight() ? 10 : 0);
  3496. rows.setSize (juce::jmax (0, width), (int) entries.size() * rowHeight);
  3497. for (int i = 0; i < rows.getNumChildComponents(); ++i)
  3498. rows.getChildComponent (i)->setBounds (0, i * rowHeight, rows.getWidth(), rowHeight);
  3499. }
  3500. void toggle (int index, bool shown)
  3501. {
  3502. if (browser != nullptr && juce::isPositiveAndBelow (index, (int) entries.size()))
  3503. {
  3504. const auto id = entries[(std::size_t) index].id;
  3505. juce::MessageManager::callAsync ([safe = browser, id, shown] { // (rebuilds the rows: not inside a row's click)
  3506. if (safe != nullptr)
  3507. safe->setRootShown (id, shown);
  3508. });
  3509. }
  3510. }
  3511. void remove (int index)
  3512. {
  3513. if (browser != nullptr && juce::isPositiveAndBelow (index, (int) entries.size()))
  3514. {
  3515. const juce::File folder (entries[(std::size_t) index].path);
  3516. juce::MessageManager::callAsync ([safe = browser, folder] {
  3517. if (safe != nullptr)
  3518. safe->removeUserFolder (folder);
  3519. });
  3520. }
  3521. }
  3522. juce::Component::SafePointer<BrowserComponent> browser;
  3523. std::vector<Entry> entries;
  3524. juce::Label title, note;
  3525. juce::Viewport list;
  3526. juce::Component rows;
  3527. juce::TextButton addFolder, showAll, close;
  3528. };
  3529. std::vector<BrowserComponent::FolderEntry> BrowserComponent::folderEntries() const
  3530. {
  3531. std::vector<FolderEntry> out;
  3532. out.push_back ({ browserview::projectRootId, tr ("Current project"), tr ("the project's patterns, channels, samples and history"),
  3533. view.shows (browserview::projectRootId), false, false });
  3534. out.push_back ({ browserview::pluginsRootId, tr ("Plugin database"), tr ("LYNX SHARE's, FL's and your installed plugins"),
  3535. view.shows (browserview::pluginsRootId), false, false });
  3536. for (int i = 0; i < allRoots.size(); ++i)
  3537. {
  3538. FolderEntry e;
  3539. e.id = e.path = allRoots[i].getFullPathName();
  3540. e.name = allRootNames[i];
  3541. e.shown = view.shows (e.id.toStdString());
  3542. e.user = allRootKinds[(std::size_t) i] == browserview::RootKind::user;
  3543. const auto merged = withMerged ({ allRoots[i] });
  3544. e.empty = std::all_of (merged.begin(), merged.end(), [this] (const juce::File& f) { return filterHides (f); });
  3545. out.push_back (std::move (e));
  3546. }
  3547. return out;
  3548. }
  3549. void BrowserComponent::refreshFoldersPanel()
  3550. {
  3551. if (auto* panel = dynamic_cast<FoldersPanel*> (foldersPanel.getComponent()))
  3552. panel->refresh();
  3553. }
  3554. void BrowserComponent::showFoldersDialog()
  3555. {
  3556. auto panel = std::make_unique<FoldersPanel> (this);
  3557. foldersPanel = panel.get();
  3558. openToolWindow (std::move (panel), role == Role::samples ? tr ("Sample browser folders") : tr ("Browser folders"),
  3559. role == Role::samples ? "sample-browser-folders" : "browser-folders");
  3560. }
  3561. std::unique_ptr<juce::Component> BrowserComponent::makeFoldersPanelForSnapshot()
  3562. {
  3563. auto panel = std::make_unique<FoldersPanel> (this);
  3564. // a user folder (with its Remove button) and one hidden entry, whatever this machine has
  3565. auto entries = folderEntries();
  3566. entries.push_back ({ "D:\\Samples\\Drums", "Drums", "D:\\Samples\\Drums", true, true, false });
  3567. if (entries.size() > 3)
  3568. entries[2].shown = false;
  3569. panel->setEntries (std::move (entries), false, {});
  3570. return panel;
  3571. }
  3572. void BrowserComponent::showViewMenu()
  3573. {
  3574. buildViewMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&viewButton));
  3575. }
  3576. juce::PopupMenu BrowserComponent::buildViewMenu()
  3577. {
  3578. juce::PopupMenu menu;
  3579. addViewItems (menu);
  3580. juce::Component::SafePointer<BrowserComponent> safe (this);
  3581. menu.addSeparator();
  3582. // round 190ce (the reference's preview switch): off = a selected file is shown, not played; Play on the strip plays it
  3583. menu.addItem (tr ("Preview files when they are selected"), true, autoPreview, [safe] {
  3584. autoPreview = ! autoPreview;
  3585. if (! autoPreview && safe != nullptr)
  3586. safe->stopPreview();
  3587. if (safe != nullptr && safe->onPreviewVolumeChanged != nullptr)
  3588. safe->onPreviewVolumeChanged(); // (saved with the preview volume)
  3589. });
  3590. // LYNX's own (round 190aq, off by default): loops are auditioned at the project's tempo, starting on the beat
  3591. menu.addItem (tr ("Preview in time (loops play at the project's tempo, on the beat)"), true, engine.isPreviewInTime(), [safe] {
  3592. if (safe == nullptr)
  3593. return;
  3594. safe->engine.setPreviewInTime (! safe->engine.isPreviewInTime());
  3595. if (safe->onPreviewVolumeChanged != nullptr)
  3596. safe->onPreviewVolumeChanged(); // (saved with the preview volume)
  3597. });
  3598. menu.addSeparator();
  3599. menu.addItem (tr ("Refresh"), [safe] { if (safe != nullptr) safe->rebuildRoots(); });
  3600. menu.addItem (tr ("Refresh search index"), [safe] { if (safe != nullptr) safe->refreshSearchIndex (false); });
  3601. if (onToggleSampleBrowser != nullptr)
  3602. {
  3603. menu.addSeparator();
  3604. menu.addItem (role == Role::samples ? tr ("Close the Sample browser") : tr ("Sample browser (separate window)"),
  3605. [safe] { if (safe != nullptr && safe->onToggleSampleBrowser != nullptr) safe->onToggleSampleBrowser(); });
  3606. }
  3607. return menu;
  3608. }
  3609. namespace
  3610. {
  3611. // The Sample browser window's content: a drag container (samples dragged out of this window reach the Channel Rack,
  3612. // the Playlist and the Mixer of the main window) holding the Browser; it keeps the window's bounds and whether the
  3613. // user closed it.
  3614. class SampleBrowserHost final : public juce::Component,
  3615. public juce::DragAndDropContainer
  3616. {
  3617. public:
  3618. SampleBrowserHost (AudioEngine& engine, const std::function<void (BrowserComponent&)>& wire)
  3619. : browser (engine, BrowserComponent::Role::samples)
  3620. {
  3621. if (wire != nullptr)
  3622. wire (browser);
  3623. addAndMakeVisible (browser);
  3624. setSize (340, 620);
  3625. }
  3626. ~SampleBrowserHost() override
  3627. {
  3628. // a window the user closed is hidden first (ToolWindow::closeSoon); one deleted while visible goes with LYNX
  3629. // and opens again at the next start
  3630. auto* window = getTopLevelComponent();
  3631. auto v = browser.getView();
  3632. v.open = window != this && window->isVisible();
  3633. if (window != this)
  3634. {
  3635. const auto b = window->getBounds();
  3636. v.x = b.getX();
  3637. v.y = b.getY();
  3638. v.width = b.getWidth();
  3639. v.height = b.getHeight();
  3640. }
  3641. file().getParentDirectory().createDirectory();
  3642. file().replaceWithText (juce::String::fromUTF8 (v.toText().c_str()));
  3643. }
  3644. void resized() override { browser.setBounds (getLocalBounds()); }
  3645. static juce::File file() { return PluginHost::settingsFolder().getChildFile ("sample-browser-view.txt"); }
  3646. BrowserComponent browser;
  3647. };
  3648. } // namespace
  3649. std::unique_ptr<juce::Component> BrowserComponent::makeSampleBrowserContent (AudioEngine& engine, const std::function<void (BrowserComponent&)>& wire)
  3650. {
  3651. auto host = std::make_unique<SampleBrowserHost> (engine, wire);
  3652. auto v = host->browser.getView();
  3653. v.open = true; // (written at once: a crash keeps it open next time too)
  3654. SampleBrowserHost::file().getParentDirectory().createDirectory();
  3655. SampleBrowserHost::file().replaceWithText (juce::String::fromUTF8 (v.toText().c_str()));
  3656. return host;
  3657. }
  3658. juce::File BrowserComponent::firstSampleFolder() const
  3659. {
  3660. using browserview::RootKind;
  3661. for (auto wanted : { RootKind::flSamples, RootKind::user, RootKind::music })
  3662. for (int i = 0; i < allRoots.size() && i < (int) allRootKinds.size(); ++i)
  3663. if (allRootKinds[(std::size_t) i] == wanted && allRoots[i].isDirectory())
  3664. return allRoots[i];
  3665. return {};
  3666. }
  3667. void BrowserComponent::rebuildRoots()
  3668. {
  3669. roots.clear();
  3670. rootNames.clear();
  3671. allRoots.clear();
  3672. allRootNames.clear();
  3673. allRootKinds.clear();
  3674. rootAlso.clear();
  3675. using browserview::RootKind;
  3676. // FL folders (if installed) and user folders. Round 190bj (QA: the FL folders were listed with LYNX_NO_FL=1): the
  3677. // installation comes from findFlStudio, as everywhere else (FL's own install path, Program Files\Image-Line, Wine,
  3678. // LYNX_FL_INSTALL; none with LYNX_NO_FL)
  3679. const auto flInstall = findFlStudio();
  3680. const auto fl = flInstall.installDir;
  3681. auto add = [this] (const juce::String& name, const juce::File& folder, RootKind kind) {
  3682. if (folder.isDirectory() && ! allRoots.contains (folder))
  3683. {
  3684. allRoots.add (folder);
  3685. allRootNames.add (name);
  3686. allRootKinds.push_back (kind);
  3687. }
  3688. };
  3689. // one root for several folders, as FL's Browser shows its Scores and Mixer presets (the user's Presets folder and
  3690. // its own Data\\Patches one, round 178a): the first folder that exists is the root, the others are merged into it
  3691. auto addMerged = [this, &add] (const juce::String& name, juce::Array<juce::File> folders, RootKind kind) {
  3692. folders.removeIf ([] (const juce::File& f) { return ! f.isDirectory(); });
  3693. if (folders.isEmpty())
  3694. return;
  3695. const auto root = folders.removeAndReturn (0);
  3696. add (name, root, kind);
  3697. if (! folders.isEmpty() && allRoots.contains (root))
  3698. rootAlso[root.getFullPathName()] = folders;
  3699. };
  3700. const auto data = fl.getChildFile ("Data");
  3701. add (tr ("FL samples (Packs)"), data.getChildFile ("Patches").getChildFile ("Packs"), RootKind::flSamples);
  3702. add (tr ("FL demo projects"), data.getChildFile ("Demo projects"), RootKind::flDemos);
  3703. const auto userData = flInstall.userData;
  3704. auto userPresets = [&userData] (const char* folder) {
  3705. return userData.isDirectory() ? userData.getChildFile ("Presets").getChildFile (folder) : juce::File();
  3706. };
  3707. addMerged (tr ("Scores"), { userPresets ("Scores"), data.getChildFile ("Patches").getChildFile ("Scores") }, RootKind::flMidi);
  3708. add (tr ("3x Osc presets (FL)"), data.getChildFile ("Patches").getChildFile ("Channel presets").getChildFile ("3x Osc"), RootKind::flPresets);
  3709. add (tr ("Synth presets (FL)"), data.getChildFile ("Patches").getChildFile ("Plugin presets").getChildFile ("Generators"), RootKind::flPresets);
  3710. add (tr ("Speech (FL)"), data.getChildFile ("Patches").getChildFile ("Speech"), RootKind::speech);
  3711. speechui::userSpeechFolder().createDirectory(); // (the Speech properties save there; round 168b)
  3712. add (tr ("Speech"), speechui::userSpeechFolder(), RootKind::speech);
  3713. // FL's Browser folder "Mixer presets" (REA round 167q, FUN_009db5b0: the user's and the installation's, one root)
  3714. addMerged (tr ("Mixer presets"), { userPresets ("Mixer presets"), data.getChildFile ("Patches").getChildFile ("Mixer presets") },
  3715. RootKind::flPresets);
  3716. pluginpresetui::presetsRoot().createDirectory(); // (the plugin window saves presets there; round 162d)
  3717. add (tr ("Plugin presets"), pluginpresetui::presetsRoot(), RootKind::pluginPresets);
  3718. audioclipboard::folder().createDirectory(); // (Tools › Clipboard saves there; round 181b)
  3719. add (tr ("Clipboard files"), audioclipboard::folder(), RootKind::clipboardFiles);
  3720. add (tr ("Documents"), juce::File::getSpecialLocation (juce::File::userDocumentsDirectory), RootKind::documents);
  3721. add (tr ("Music"), juce::File::getSpecialLocation (juce::File::userMusicDirectory), RootKind::music);
  3722. add (tr ("Desktop"), juce::File::getSpecialLocation (juce::File::userDesktopDirectory), RootKind::desktop);
  3723. add (tr ("Downloads"), juce::File::getSpecialLocation (juce::File::userHomeDirectory).getChildFile ("Downloads"), RootKind::downloads);
  3724. for (const auto& line : juce::StringArray::fromLines (userFoldersFile().loadFileAsString()))
  3725. if (line.trim().isNotEmpty())
  3726. add (juce::File (line.trim()).getFileName(), juce::File (line.trim()), RootKind::user);
  3727. if (! viewLoaded)
  3728. loadView();
  3729. bool migrated = false; // (round 178a: the old "FL MIDI" / "Mixer presets (FL)" roots' hidden state)
  3730. for (const auto& [rootPath, folders] : rootAlso)
  3731. migrated = browserview::migrateMergedRoot (view, rootPath.toStdString(), toPaths (folders)) || migrated;
  3732. if (migrated && viewFromFile)
  3733. saveView();
  3734. for (int i = 0; i < allRoots.size(); ++i)
  3735. if (view.shows (allRoots[i].getFullPathName().toStdString()))
  3736. {
  3737. roots.add (allRoots[i]);
  3738. rootNames.add (allRootNames[i]);
  3739. }
  3740. refreshViewButton();
  3741. refreshFoldersPanel();
  3742. loadCollections();
  3743. rebuildTree();
  3744. }
  3745. void BrowserComponent::rebuildTree()
  3746. {
  3747. std::vector<std::unique_ptr<FileTree::Node>> top;
  3748. if (tab == starredTab)
  3749. {
  3750. // A collection's items: folders first (each opens like the ALL tab's), then files, then Plugin database
  3751. // entries, each by name; missing files and plugins that are gone are left out.
  3752. const auto& store = collectionStore();
  3753. const auto itemsOf = [this, &store] (int collection) {
  3754. std::vector<std::unique_ptr<FileTree::Node>> out;
  3755. juce::Array<juce::File> folders, files;
  3756. std::vector<std::unique_ptr<FileTree::Node>> plugins;
  3757. for (const auto& item : store.itemsOf (collection))
  3758. {
  3759. if (collections::isPluginItem (item))
  3760. {
  3761. if (auto n = FileTree::makePluginItem (*this, collections::pluginKeyOf (item)))
  3762. plugins.push_back (std::move (n));
  3763. continue;
  3764. }
  3765. if (const juce::File f (juce::String::fromUTF8 (item.c_str())); f.isDirectory())
  3766. folders.add (f);
  3767. else if (f.existsAsFile())
  3768. files.add (f);
  3769. }
  3770. const auto byName = [] (const juce::File& a, const juce::File& b) { return a.getFileName().compareNatural (b.getFileName()) < 0; };
  3771. std::sort (folders.begin(), folders.end(), byName);
  3772. std::sort (files.begin(), files.end(), byName);
  3773. std::sort (plugins.begin(), plugins.end(), [] (const auto& a, const auto& b) { return a->label.compareNatural (b->label) < 0; });
  3774. for (const auto& f : folders)
  3775. out.push_back (FileTree::makeFolder (f, f.getFileName(), collectionColour (collection)));
  3776. for (const auto& f : files)
  3777. {
  3778. auto n = std::make_unique<FileTree::Node>();
  3779. n->file = f;
  3780. out.push_back (std::move (n));
  3781. }
  3782. for (auto& n : plugins)
  3783. out.push_back (std::move (n));
  3784. return out;
  3785. };
  3786. // Only Starred switched on (as it is at first): its items alone, the tab as it always was. More than one (or
  3787. // another one): each collection under its heading.
  3788. const auto shown = store.shown();
  3789. if (shown.size() == 1 && shown.front() == 0)
  3790. top = itemsOf (0);
  3791. else
  3792. for (const auto c : shown)
  3793. {
  3794. auto items = itemsOf (c);
  3795. auto heading = FileTree::makeCollection (c, (int) items.size(), closedCollections.count (c) == 0);
  3796. heading->children = std::move (items);
  3797. top.push_back (std::move (heading));
  3798. }
  3799. tree->setTopLevel (std::move (top));
  3800. treeView->setViewPosition (0, 0);
  3801. return;
  3802. }
  3803. if (tab == projectTab || view.shows (browserview::projectRootId))
  3804. top.push_back (FileTree::makeProject (tab == projectTab));
  3805. // FL's Plugin database, under the project (round 142); always while hot-swap is on (round 190ce: it is what the
  3806. // linked device is replaced from, also when the user's view leaves it out)
  3807. if (tab == allTab && (view.shows (browserview::pluginsRootId) || swapSession.active()))
  3808. top.push_back (FileTree::makePluginDatabase (*this, openPluginFolders));
  3809. if (tab == allTab)
  3810. for (int i = 0; i < allRoots.size(); ++i)
  3811. {
  3812. if (! roots.contains (allRoots[i]))
  3813. continue; // hidden from this Browser (round 163)
  3814. if (const auto merged = withMerged ({ allRoots[i] });
  3815. std::all_of (merged.begin(), merged.end(), [this] (const juce::File& f) { return filterHides (f); }))
  3816. continue; // nothing in it is listed under the content filter (round 164)
  3817. // the FL folders keep their colour by position; the user's own folders share one
  3818. auto colour = rootColour (i < 9 ? i : 99);
  3819. auto n = FileTree::makeFolder (allRoots[i], allRootNames[i], colour);
  3820. n->also = mergedInto (allRoots[i]);
  3821. if (allRootKinds[(std::size_t) i] == browserview::RootKind::flMidi)
  3822. n->icon = Icon::note; // (FL's Scores folder has a note)
  3823. top.push_back (std::move (n));
  3824. }
  3825. tree->setTopLevel (std::move (top));
  3826. treeView->setViewPosition (0, 0);
  3827. }
  3828. void BrowserComponent::setTab (int newTab)
  3829. {
  3830. newTab = juce::jlimit (0, tabCount - 1, newTab);
  3831. if (newTab == tab)
  3832. return;
  3833. tab = newTab;
  3834. rebuildTree();
  3835. tabs->repaint();
  3836. if (searchBox.getText().isNotEmpty())
  3837. runSearch();
  3838. }
  3839. void BrowserComponent::setProjectFile (const juce::File& file)
  3840. {
  3841. if (file == projectFile)
  3842. return;
  3843. projectFile = file;
  3844. rebuildTree(); // the "Project folder" entry follows the project
  3845. }
  3846. void BrowserComponent::changeListenerCallback (juce::ChangeBroadcaster* source)
  3847. {
  3848. if (source == &searcher->statusChanged)
  3849. {
  3850. indexStatusChanged();
  3851. return;
  3852. }
  3853. if (source == &similar->statusChanged)
  3854. {
  3855. similarStatusChanged();
  3856. return;
  3857. }
  3858. if (source == &searcher->indexChanged)
  3859. {
  3860. applyFilterToTree();
  3861. // the background check found changed folders: the results shown are searched again, in place
  3862. if (resultsView->isVisible() && tab != projectTab && searchBox.getText().trim().isNotEmpty())
  3863. runSearch (true);
  3864. return;
  3865. }
  3866. // round 190ce: the device the Browser is linked to was deleted (or the project replaced): the link ends
  3867. if (swapSession.active())
  3868. {
  3869. if (! swapSession.stillValid (engine.getSong()))
  3870. endHotSwap();
  3871. else
  3872. swapBar->repaint();
  3873. }
  3874. // the project changed: its sections are listed again a moment later (not on every knob step)
  3875. projectDirty = true;
  3876. if (! isTimerRunning())
  3877. startTimer (300);
  3878. }
  3879. void BrowserComponent::addUserFolder()
  3880. {
  3881. chooser = lynx::ui::makeFileChooser (tr ("Add a folder to the Browser"), juce::File::getSpecialLocation (juce::File::userMusicDirectory));
  3882. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories, [this] (const juce::FileChooser& fc) {
  3883. const auto folder = fc.getResult();
  3884. if (! folder.isDirectory())
  3885. return;
  3886. auto lines = juce::StringArray::fromLines (userFoldersFile().loadFileAsString());
  3887. lines.removeEmptyStrings();
  3888. lines.addIfNotAlreadyThere (folder.getFullPathName());
  3889. userFoldersFile().replaceWithText (lines.joinIntoString ("\n"));
  3890. setTab (allTab);
  3891. rebuildRoots();
  3892. });
  3893. }
  3894. void BrowserComponent::removeUserFolder (const juce::File& folder)
  3895. {
  3896. auto lines = juce::StringArray::fromLines (userFoldersFile().loadFileAsString());
  3897. lines.removeEmptyStrings();
  3898. for (int i = lines.size(); --i >= 0;)
  3899. if (juce::File (lines[i].trim()) == folder)
  3900. lines.remove (i);
  3901. userFoldersFile().replaceWithText (lines.joinIntoString ("\n"));
  3902. if (view.hidden.erase (folder.getFullPathName().toStdString()) > 0) // (a hidden mark of a folder no longer listed)
  3903. saveView();
  3904. rebuildRoots();
  3905. }
  3906. BrowserComponent::~BrowserComponent()
  3907. {
  3908. std::erase (liveBrowsers(), this);
  3909. engine.removeChangeListener (this);
  3910. searcher->statusChanged.removeChangeListener (this);
  3911. searcher->indexChanged.removeChangeListener (this);
  3912. searcher->service->cancelSearch();
  3913. similar->statusChanged.removeChangeListener (this);
  3914. if (similarId != 0)
  3915. similar->service->cancel();
  3916. focusWatcher.reset();
  3917. engine.previewFile ({});
  3918. }
  3919. void BrowserComponent::waitForListing (int)
  3920. {
  3921. // the tree lists folders synchronously when they open
  3922. }
  3923. void BrowserComponent::resized()
  3924. {
  3925. auto area = getLocalBounds().reduced (4);
  3926. if (swapBar->isVisible()) // round 190ce: the hot-swap bar over the tabs
  3927. {
  3928. swapBar->setBounds (area.removeFromTop (HotSwapBar::height));
  3929. area.removeFromTop (3);
  3930. }
  3931. tabs->setBounds (area.removeFromTop (26));
  3932. area.removeFromTop (4);
  3933. {
  3934. auto row = area.removeFromTop (24);
  3935. viewButton.setBounds (row.removeFromRight (22));
  3936. row.removeFromRight (4);
  3937. searchBox.setBounds (row);
  3938. }
  3939. // indexing progress / what the search found (round 162)
  3940. statusArea = statusLine.isNotEmpty() ? area.removeFromTop (16).withTrimmedLeft (2) : juce::Rectangle<int>();
  3941. area.removeFromTop (4);
  3942. strip->setBounds (getLocalBounds().removeFromBottom (juce::jmin (64, getHeight() / 4)));
  3943. area.setBottom (strip->getY() - 2);
  3944. // FL's details box (date, size / version, folder) just above the preview strip, while something is selected
  3945. details->setVisible (details->hasFile() && area.getHeight() > 120);
  3946. if (details->isVisible())
  3947. details->setBounds (area.removeFromBottom (DetailsBox::preferredHeight).withX (0).withWidth (getWidth()));
  3948. treeView->setBounds (area);
  3949. resultsView->setBounds (area);
  3950. for (auto* list : { tree.get(), results.get() })
  3951. {
  3952. list->setSize (area.getWidth() - 10, list->getHeight());
  3953. list->updateSize();
  3954. }
  3955. }
  3956. void BrowserComponent::refreshPreviewVolume()
  3957. {
  3958. previewVolume.setValue (engine.getPreviewVolume(), juce::dontSendNotification);
  3959. const auto text = tr ("Sample preview volume: {0}", { ui::utilityVolumeText (engine.getPreviewVolume()) });
  3960. previewVolume.setTooltip (text);
  3961. ui::setHint (previewVolume, text + " " + tr ("[LMB] drag [Wheel] step [2xLMB] 100% [RMB] type a value"), true);
  3962. }
  3963. void BrowserComponent::paint (juce::Graphics& g)
  3964. {
  3965. const uitrace::Scope trace ("BrowserComponent paint", true, g.getClipBounds());
  3966. g.fillAll (theme::colour::bg2);
  3967. if (! statusArea.isEmpty())
  3968. {
  3969. g.setFont (theme::font (theme::type::caption));
  3970. g.setColour (theme::colour::textDisabled);
  3971. g.drawText (statusLine, statusArea, juce::Justification::centredLeft, true);
  3972. }
  3973. }
  3974. void BrowserComponent::showPreviewForSnapshot (const juce::File& file)
  3975. {
  3976. strip->show (file, false);
  3977. }
  3978. void BrowserComponent::fileSelected (const juce::File& file, bool preview)
  3979. {
  3980. preview = previewWanted (preview); // (round 190ce: the automatic preview can be switched off)
  3981. if (details != nullptr && file != juce::File())
  3982. {
  3983. const auto wasVisible = details->hasFile();
  3984. details->show (file);
  3985. if (! wasVisible)
  3986. resized();
  3987. }
  3988. if (preview && file.hasFileExtension ("sf2;sf3;sfz") && file.existsAsFile())
  3989. {
  3990. int bank = 0, program = 0;
  3991. if (firstSoundFontPreset (file.getFullPathName().toStdString(), bank, program))
  3992. previewSoundFontPreset (engine, file.getFullPathName().toStdString(), bank, program);
  3993. return;
  3994. }
  3995. if (! isAudio (file))
  3996. return;
  3997. if (preview && file.existsAsFile())
  3998. {
  3999. engine.previewFile (file);
  4000. previewedFile = file;
  4001. }
  4002. strip->show (file, preview);
  4003. tree->repaint();
  4004. results->repaint();
  4005. }
  4006. // FL's Browser menus (REA round 143b, [EXEC] FL 2026: right-click on a sample, a folder, a plugin): the file's actions
  4007. // first, then a "System" section (open the parent folder, locate the file, delete it) and a "Tags" section (Favorite);
  4008. // a folder: Expand all / Collapse all, then System (Open). LYNX keeps its own "Add folder..." and "Refresh".
  4009. // Round 163 (user feedback: "this sort of UI has a ton of wasted space"): no "System" / "Tags" titles any more; the
  4010. // rarely used system actions sit in one "File" sub-menu, Starred stays one click away.
  4011. void BrowserComponent::addSystemItems (juce::PopupMenu& menu, const juce::File& file)
  4012. {
  4013. menu.addSeparator();
  4014. menu.addItem (tr ("Starred"), true, isStarred (file), [this, file] { setStarred (file, ! isStarred (file)); });
  4015. addCollectionItems (menu, file.getFullPathName().toStdString());
  4016. if (resultsView->isVisible() && tab != projectTab) // round 190ce: from a search result to its place in the folders
  4017. menu.addItem (tr ("Show in its folder"), [safe = juce::Component::SafePointer<BrowserComponent> (this), file] {
  4018. if (safe == nullptr)
  4019. return;
  4020. safe->searchBox.setText ({}, false);
  4021. safe->runSearch();
  4022. safe->setTab (allTab);
  4023. if (const auto row = safe->tree->revealFile (file); row >= 0)
  4024. safe->tree->select (row, false);
  4025. else
  4026. safe->showNote (tr ("This file is not in a folder the Browser shows"));
  4027. });
  4028. juce::PopupMenu system;
  4029. system.addItem (tr ("Open parent folder"), [file] { file.getParentDirectory().startAsProcess(); });
  4030. system.addItem (tr ("Locate file"), [file] { file.revealToUser(); });
  4031. system.addItem (tr ("Copy the file path"), [file] { juce::SystemClipboard::copyTextToClipboard (file.getFullPathName()); });
  4032. system.addSeparator();
  4033. system.addItem (tr ("Delete file..."), file.existsAsFile(), false, [this, file] { confirmDeleteFile (file); });
  4034. menu.addSubMenu (tr ("File"), system);
  4035. }
  4036. void BrowserComponent::showNote (const juce::String& text)
  4037. {
  4038. const auto relayout = text.isEmpty() != statusLine.isEmpty();
  4039. statusLine = text;
  4040. if (relayout)
  4041. resized();
  4042. repaint();
  4043. // it goes away by itself (unless something else wrote there meanwhile)
  4044. juce::Timer::callAfterDelay (5000, [safe = juce::Component::SafePointer<BrowserComponent> (this), text] {
  4045. if (safe != nullptr && safe->statusLine == text)
  4046. safe->showNote ({});
  4047. });
  4048. }
  4049. void BrowserComponent::confirmDeleteFile (const juce::File& file)
  4050. {
  4051. juce::Component::SafePointer<BrowserComponent> safe (this);
  4052. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::WarningIcon, tr ("Delete file"),
  4053. tr ("Move \"{0}\" to the recycle bin?", { file.getFileName() }), tr ("Delete"), tr ("Cancel"), nullptr,
  4054. juce::ModalCallbackFunction::create ([safe, file] (int result) {
  4055. if (result == 0 || safe == nullptr)
  4056. return;
  4057. if (! file.moveToTrash())
  4058. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Delete file"),
  4059. tr ("The file could not be deleted."));
  4060. safe->rebuildRoots();
  4061. }));
  4062. }
  4063. void BrowserComponent::showFileMenu (const juce::File& file)
  4064. {
  4065. juce::PopupMenu menu;
  4066. menu.addSectionHeader (file.getFileName());
  4067. if (isAudio (file))
  4068. {
  4069. menu.addItem (tr ("Send to the selected channel"), onLoadIntoChannel != nullptr, false, [this, file] { onLoadIntoChannel (file); });
  4070. menu.addItem (tr ("Open in a new channel"), [this, file] { openFile (file); });
  4071. menu.addSeparator();
  4072. menu.addItem (tr ("Send to the Playlist as an audio clip"), onSendToPlaylist != nullptr, false, [this, file] { onSendToPlaylist (file); });
  4073. menu.addSeparator();
  4074. menu.addItem (tr ("Edit in the audio editor..."), [this, file] { openAudioEditor (engine, file); });
  4075. // FL's Sounds tab menu: "Open/Edit in...", then "Find similar samples" (FL asks FL Cloud; LYNX looks through
  4076. // the Browser's own folders, round 190as)
  4077. if (! file.hasFileExtension ("speech"))
  4078. menu.addItem (tr ("Find similar samples"), [this, file] { findSimilar (file); });
  4079. }
  4080. else if (file.hasFileExtension ("lynx;flp;als;flm"))
  4081. menu.addItem (tr ("Open project"), onOpenProject != nullptr, false, [this, file] { onOpenProject (file); });
  4082. else if (file.hasFileExtension ("mid;midi"))
  4083. menu.addItem (tr ("Open MIDI file"), onOpenProject != nullptr, false, [this, file] { onOpenProject (file); });
  4084. else if (file.hasFileExtension ("fst;gmsynth"))
  4085. menu.addItem (tr ("Open in a new channel"), [this, file] { openFile (file); });
  4086. else if (file.hasFileExtension ("sf2;sf3;sfz"))
  4087. {
  4088. const auto selected = engine.getSelectedChannel();
  4089. const auto& song = engine.getSong();
  4090. const auto selectedIsFont = selected >= 0 && selected < (int) song.channels.size()
  4091. && song.channels[(std::size_t) selected].instrument == InstrumentKind::soundfont;
  4092. menu.addItem (tr ("Open in a new channel"), [this, file] { openSoundFontFile (engine, file); });
  4093. menu.addItem (tr ("Send to the selected channel"), selectedIsFont, false, [this, file, selected] { openSoundFontFile (engine, file, selected); });
  4094. }
  4095. addSystemItems (menu, file);
  4096. menu.addItem (tr ("Collapse all folders"), [this] { tree->collapseAll(); });
  4097. juce::PopupMenu browserMenu;
  4098. addViewItems (browserMenu);
  4099. menu.addSubMenu (tr ("Browser"), browserMenu);
  4100. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  4101. }
  4102. void BrowserComponent::showFolderMenu (const juce::File& folder, std::function<void()> expandAll)
  4103. {
  4104. // compact (round 163): the folder's name as the only title, its actions, then the Browser's own options
  4105. juce::PopupMenu menu;
  4106. menu.addSectionHeader (folder.getFileName());
  4107. menu.addItem (tr ("Expand all"), expandAll != nullptr, false, [expandAll] { expandAll(); });
  4108. menu.addItem (tr ("Collapse all"), [this] { tree->collapseAll(); });
  4109. menu.addItem (tr ("Starred"), folder.isDirectory(), isStarred (folder), [this, folder] { setStarred (folder, ! isStarred (folder)); });
  4110. if (folder.isDirectory())
  4111. addCollectionItems (menu, folder.getFullPathName().toStdString());
  4112. menu.addItem (tr ("Open in the file manager"), [folder] { folder.startAsProcess(); });
  4113. menu.addItem (tr ("Copy the file path"), [folder] { juce::SystemClipboard::copyTextToClipboard (folder.getFullPathName()); });
  4114. menu.addSeparator();
  4115. if (const auto id = rootId (folder); id.isNotEmpty() && tab == allTab)
  4116. {
  4117. addHideItem (menu, id, allRootNames[allRoots.indexOf (folder)]);
  4118. if (allRootKinds[(std::size_t) allRoots.indexOf (folder)] == browserview::RootKind::user)
  4119. menu.addItem (tr ("Remove this folder from the Browsers"), [safe = juce::Component::SafePointer<BrowserComponent> (this), folder] {
  4120. if (safe != nullptr)
  4121. safe->removeUserFolder (folder);
  4122. });
  4123. if (const auto merged = rootAlso.find (folder.getFullPathName()); merged != rootAlso.end())
  4124. {
  4125. // a LYNX extra (FL has no exclusion; round 178a): the folders this root merges, each one ticked in or out;
  4126. // the root's own folder stays (Hide... hides the root)
  4127. juce::PopupMenu folders;
  4128. folders.addItem (folder.getFullPathName(), false, true, nullptr);
  4129. for (const auto& f : merged->second)
  4130. {
  4131. const auto path = f.getFullPathName().toStdString();
  4132. folders.addItem (f.getFullPathName(), true, view.excluded.count (path) == 0,
  4133. [safe = juce::Component::SafePointer<BrowserComponent> (this), path] {
  4134. if (safe == nullptr)
  4135. return;
  4136. if (safe->view.excluded.erase (path) == 0)
  4137. safe->view.excluded.insert (path);
  4138. safe->saveView();
  4139. safe->rebuildRoots();
  4140. safe->searcher->service->refresh (toPaths (safe->withMerged (safe->allRoots)));
  4141. if (safe->searchBox.getText().trim().isNotEmpty())
  4142. safe->runSearch();
  4143. });
  4144. }
  4145. menu.addSubMenu (tr ("Folders"), folders);
  4146. }
  4147. }
  4148. juce::PopupMenu browserMenu;
  4149. addViewItems (browserMenu);
  4150. browserMenu.addSeparator();
  4151. browserMenu.addItem (tr ("Refresh"), [this] { rebuildRoots(); });
  4152. browserMenu.addItem (tr ("Refresh search index"), [this] { refreshSearchIndex (false); });
  4153. menu.addSubMenu (tr ("Browser"), browserMenu);
  4154. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  4155. }
  4156. BrowserComponent::FileTree& BrowserComponent::activeList() const
  4157. {
  4158. return resultsView->isVisible() ? *results : *tree;
  4159. }
  4160. // --- search ------------------------------------------------------------------------------------------
  4161. void BrowserComponent::focusSearch()
  4162. {
  4163. searchBox.grabKeyboardFocus();
  4164. searchBox.selectAll();
  4165. }
  4166. juce::Array<juce::File> BrowserComponent::searchRoots() const
  4167. {
  4168. // the top-level folder holding the selection; nothing selected there: every folder
  4169. if (const auto root = tree->selectedRoot(); root.isDirectory())
  4170. return withMerged ({ root });
  4171. if (tab == starredTab) // the folders of the collections shown
  4172. {
  4173. juce::Array<juce::File> folders;
  4174. for (const auto c : collectionStore().shown())
  4175. for (const auto& item : collectionStore().itemsOf (c))
  4176. if (const juce::File f (juce::String::fromUTF8 (item.c_str())); ! collections::isPluginItem (item) && f.isDirectory())
  4177. folders.addIfNotAlreadyThere (f);
  4178. return folders;
  4179. }
  4180. return withMerged (roots);
  4181. }
  4182. juce::Array<juce::File> BrowserComponent::mergedInto (const juce::File& root) const
  4183. {
  4184. const auto it = rootAlso.find (root.getFullPathName());
  4185. if (it == rootAlso.end())
  4186. return {};
  4187. auto folders = it->second; // (less the folders this view leaves out: a hidden "FL MIDI" before round 178a)
  4188. folders.removeIf ([this] (const juce::File& f) { return view.excluded.count (f.getFullPathName().toStdString()) > 0; });
  4189. return folders;
  4190. }
  4191. juce::Array<juce::File> BrowserComponent::withMerged (const juce::Array<juce::File>& folders) const
  4192. {
  4193. auto out = folders;
  4194. for (const auto& f : folders)
  4195. out.addArray (mergedInto (f));
  4196. return out;
  4197. }
  4198. void BrowserComponent::setSearchForSnapshot (const juce::String& text)
  4199. {
  4200. // synchronous: the snapshot is drawn before any message is dispatched
  4201. searchBox.setText (text, juce::dontSendNotification);
  4202. searcher->service->cancelSearch();
  4203. resultsView->setVisible (text.isNotEmpty());
  4204. treeView->setVisible (text.isEmpty());
  4205. if (text.isEmpty() || roots.isEmpty())
  4206. return;
  4207. const juce::Array<juce::File> scope { roots[0] }; // the FL samples: the same results on every machine with FL
  4208. auto answer = std::make_shared<std::pair<std::mutex, search::SearchResult>>();
  4209. searcher->service->search (text.toStdString(), toPaths (scope), (std::size_t) maxResults, [answer] (const search::SearchResult& r) {
  4210. const std::lock_guard<std::mutex> guard (answer->first);
  4211. answer->second = r;
  4212. });
  4213. searcher->service->waitIdle (120000);
  4214. auto found = collectionMatches (text); // (round 190ce: as searchAnswered, the collections' names first)
  4215. {
  4216. const std::lock_guard<std::mutex> guard (answer->first);
  4217. for (const auto& path : answer->second.paths)
  4218. found.addIfNotAlreadyThere (juce::File (juce::String::fromUTF8 (path.c_str())));
  4219. }
  4220. results->setFiles (found, scope, found.isEmpty() ? tr ("Nothing found for \"{0}\".", { text }) : juce::String());
  4221. if (! found.isEmpty())
  4222. results->select (0, false);
  4223. }
  4224. void BrowserComponent::selectFirstSampleForSnapshot()
  4225. {
  4226. if (const auto row = tree->firstAudioRow(); row >= 0)
  4227. {
  4228. tree->select (row, false);
  4229. strip->show (tree->selectedFile(), false);
  4230. tree->setHovered (row + 1 < tree->numRows() ? row + 1 : -1);
  4231. }
  4232. }
  4233. void BrowserComponent::showFilterForSnapshot (const juce::File& folder, browserview::ContentFilter filter)
  4234. {
  4235. // a folder of the user's (not saved) listed under `filter` once the index knows it (nothing saved either)
  4236. if (! allRoots.contains (folder))
  4237. {
  4238. allRoots.add (folder);
  4239. allRootNames.add (folder.getFileName());
  4240. allRootKinds.push_back (browserview::RootKind::user);
  4241. }
  4242. roots.clear();
  4243. roots.add (folder);
  4244. view.filter = filter;
  4245. view.setShown (browserview::projectRootId, false);
  4246. view.setShown (browserview::pluginsRootId, false);
  4247. searcher->service->refresh (toPaths ({ folder }));
  4248. searcher->service->waitIdle (60000);
  4249. prunedGeneration = 0;
  4250. setTab (allTab);
  4251. rebuildTree();
  4252. tree->expandTop (folder, 3);
  4253. refreshViewButton();
  4254. }
  4255. void BrowserComponent::resetViewForSnapshot()
  4256. {
  4257. viewLoaded = false; // (read again: the snapshot's changes were never saved)
  4258. prunedGeneration = 0;
  4259. rebuildRoots();
  4260. }
  4261. std::vector<juce::PopupMenu> BrowserComponent::pluginDatabaseMenusForSnapshot()
  4262. {
  4263. // a folder of the user's (else Effects / Generators) and the first plugin entry shown, as a right-click opens them
  4264. showPluginDatabaseForSnapshot();
  4265. std::vector<juce::PopupMenu> out;
  4266. out.push_back (tree->menuForSnapshot (tree->firstRowOfKind (false)));
  4267. out.push_back (tree->menuForSnapshot (tree->firstRowOfKind (true)));
  4268. return out;
  4269. }
  4270. void BrowserComponent::showPluginDatabaseForSnapshot()
  4271. {
  4272. openPluginFolders = { tr ("Plugin database"), tr ("Plugin database") + "/" + tr ("Generators"), tr ("Generators") + "/" + tr ("FL engines"),
  4273. tr ("Plugin database") + "/" + tr ("Effects"), tr ("Effects") + "/" + tr ("FL engines") };
  4274. setTab (allTab);
  4275. rebuildTree();
  4276. }
  4277. void BrowserComponent::showPluginDatabase (const juce::String& folder, int generators)
  4278. {
  4279. const auto db = tr ("Plugin database");
  4280. openPluginFolders.insert (db);
  4281. openPluginFolders.insert (db + "/" + tr ("Generators"));
  4282. openPluginFolders.insert (db + "/" + tr ("Effects"));
  4283. // the Plugin picker's tab clicked (round 171c, FL opens its Browser on that category): that folder of the user's,
  4284. // else the Generators / Effects heading
  4285. const auto kind = generators > 0 ? tr ("Generators") : tr ("Effects");
  4286. if (generators >= 0 && folder.isNotEmpty())
  4287. openPluginFolders.insert (kind + "/" + folder);
  4288. setTab (allTab);
  4289. rebuildTree();
  4290. auto row = generators >= 0 && folder.isNotEmpty() ? tree->rowLabelled (folder) : -1;
  4291. if (row < 0)
  4292. row = tree->rowLabelled (generators >= 0 ? kind : db);
  4293. if (row >= 0)
  4294. {
  4295. tree->select (row, false);
  4296. tree->grabKeyboardFocus();
  4297. }
  4298. }
  4299. bool BrowserComponent::locateFile (const juce::File& file)
  4300. {
  4301. if (searchBox.getText().isNotEmpty())
  4302. {
  4303. searchBox.setText ({}, false);
  4304. runSearch();
  4305. }
  4306. setTab (allTab);
  4307. if (const auto row = tree->revealFile (file); row >= 0)
  4308. {
  4309. tree->select (row, false);
  4310. tree->grabKeyboardFocus();
  4311. return true;
  4312. }
  4313. showNote (tr ("This file is not in a folder the Browser shows"));
  4314. return false;
  4315. }
  4316. void BrowserComponent::showScores (const juce::String& subfolder)
  4317. {
  4318. // the Piano roll's File › Browse scores (round 168g; FL: FUN_0123a580 opens its browser at the Scores folder): the
  4319. // "Scores" root shown, opened and selected. With a subfolder (the Event editor's File › Browse automations: FL
  4320. // opens Scores\\Automation, the user's when there is one; REA round 178a) that folder's row is selected
  4321. for (int i = 0; i < allRoots.size(); ++i)
  4322. if (i < (int) allRootKinds.size() && allRootKinds[(std::size_t) i] == browserview::RootKind::flMidi)
  4323. {
  4324. const auto folder = allRoots[i];
  4325. if (const auto id = rootId (folder); id.isNotEmpty())
  4326. setRootShown (id, true);
  4327. setTab (allTab);
  4328. rebuildTree();
  4329. tree->expandTop (folder, 1);
  4330. int row = -1;
  4331. if (subfolder.isNotEmpty())
  4332. for (const auto& f : withMerged ({ folder })) // (the merged row is the first folder's that has it)
  4333. if (row < 0)
  4334. row = tree->rowOfFile (f.getChildFile (subfolder));
  4335. if (row < 0)
  4336. row = tree->rowLabelled (allRootNames[i]);
  4337. if (row >= 0)
  4338. {
  4339. tree->select (row, false);
  4340. tree->grabKeyboardFocus();
  4341. }
  4342. return;
  4343. }
  4344. showNote (tr ("FL Studio's scores were not found (FL Studio is not installed)"));
  4345. }
  4346. void BrowserComponent::showProjectForSnapshot()
  4347. {
  4348. setTab (projectTab);
  4349. if (const auto row = tree->openProjectSections ({ Category::patterns, Category::generators, Category::samples }); row >= 0)
  4350. {
  4351. tree->select (row, false);
  4352. strip->show (tree->selectedFile(), false);
  4353. tree->setHovered (row + 1 < tree->numRows() ? row + 1 : -1);
  4354. }
  4355. }
  4356. void BrowserComponent::textEditorTextChanged (juce::TextEditor&)
  4357. {
  4358. searchPending = true;
  4359. startTimer (250); // search once typing pauses
  4360. }
  4361. void BrowserComponent::textEditorEscapeKeyPressed (juce::TextEditor&)
  4362. {
  4363. // Esc: clears the search and gives the keyboard back (Space plays again)
  4364. searchPending = false;
  4365. searchBox.clear();
  4366. runSearch();
  4367. leaveSearchBox();
  4368. }
  4369. void BrowserComponent::textEditorReturnKeyPressed (juce::TextEditor&)
  4370. {
  4371. // Enter: searches now and leaves the box, so Up / Down step through the results (and Space plays)
  4372. searchPending = false;
  4373. runSearch();
  4374. leaveSearchBox();
  4375. }
  4376. bool BrowserComponent::isTypingInSearch() const
  4377. {
  4378. return searchBox.hasKeyboardFocus (true);
  4379. }
  4380. void BrowserComponent::leaveSearchBox()
  4381. {
  4382. if (! isTypingInSearch())
  4383. return;
  4384. // the window's first ancestor that takes keys (the main window's content: the shortcuts, the transport) gets them
  4385. for (auto* p = getParentComponent(); p != nullptr; p = p->getParentComponent())
  4386. if (p->getWantsKeyboardFocus() && p->isShowing())
  4387. {
  4388. p->grabKeyboardFocus();
  4389. if (! isTypingInSearch())
  4390. return;
  4391. }
  4392. searchBox.giveAwayKeyboardFocus();
  4393. }
  4394. void BrowserComponent::timerCallback()
  4395. {
  4396. stopTimer();
  4397. if (std::exchange (searchPending, false))
  4398. runSearch();
  4399. if (std::exchange (projectDirty, false))
  4400. {
  4401. tree->refreshProject();
  4402. if (tab == projectTab && resultsView->isVisible())
  4403. runSearch();
  4404. }
  4405. }
  4406. void BrowserComponent::runSearch (bool quiet)
  4407. {
  4408. searcher->service->cancelSearch();
  4409. searchId = 0;
  4410. if (similarTo != juce::File())
  4411. {
  4412. // similar samples are listed while the box still says so; any other text is an ordinary search again
  4413. if (tab != projectTab && searchBox.getText() == similarLabel())
  4414. {
  4415. runSimilar (quiet);
  4416. return;
  4417. }
  4418. similarTo = juce::File();
  4419. similarPartial = false;
  4420. if (std::exchange (similarId, 0) != 0)
  4421. similar->service->cancel();
  4422. }
  4423. const auto query = searchBox.getText().trim();
  4424. resultsView->setVisible (query.isNotEmpty());
  4425. treeView->setVisible (query.isEmpty());
  4426. if (query.isEmpty())
  4427. {
  4428. searchPartial = false;
  4429. indexStatusChanged();
  4430. return;
  4431. }
  4432. if (tab == projectTab) // the project's own items, at once
  4433. {
  4434. auto found = FileTree::projectMatches (engine.getSong(), query);
  4435. const auto none = found.empty();
  4436. results->setNodes (std::move (found), none ? tr ("Nothing found for \"{0}\".", { query }) : juce::String());
  4437. return;
  4438. }
  4439. const auto scope = searchRoots();
  4440. if (scope.isEmpty())
  4441. {
  4442. // round 190ce: no folder to search, but the collections are still searched by their names
  4443. const auto tagged = collectionMatches (query);
  4444. results->setFiles (tagged, {}, tagged.isEmpty() ? tr ("Nothing found for \"{0}\".", { query }) : juce::String());
  4445. return;
  4446. }
  4447. if (! quiet)
  4448. {
  4449. results->setFiles ({}, scope, tr ("Searching {0}...", { scope.size() == 1 ? scope[0].getFullPathName() : tr ("every folder") }));
  4450. resultsView->setViewPosition (0, 0);
  4451. }
  4452. // the worker answers on its thread: the answer comes to the message thread (and is dropped if this Browser went)
  4453. searchId = searcher->service->search (query.toStdString(), toPaths (scope), (std::size_t) maxResults,
  4454. [safe = juce::Component::SafePointer<BrowserComponent> (this), query, scope] (const search::SearchResult& r) {
  4455. juce::MessageManager::callAsync ([safe, query, scope, r] {
  4456. if (safe != nullptr)
  4457. safe->searchAnswered (r, query, scope);
  4458. });
  4459. });
  4460. }
  4461. juce::Array<juce::File> BrowserComponent::collectionMatches (const juce::String& query) const
  4462. {
  4463. std::array<std::string, collections::count> names;
  4464. for (int c = 0; c < collections::count; ++c)
  4465. names[(std::size_t) c] = collectionName (c).toStdString();
  4466. juce::Array<juce::File> out;
  4467. for (const auto& item : collectionStore().search (query.toStdString(), &names))
  4468. if (! collections::isPluginItem (item))
  4469. if (const juce::File f (juce::String::fromUTF8 (item.c_str())); f.existsAsFile() && (view.filter == browserview::ContentFilter::all || lists (f)))
  4470. out.add (f);
  4471. return out;
  4472. }
  4473. void BrowserComponent::searchAnswered (const search::SearchResult& r, const juce::String& query, const juce::Array<juce::File>& scope)
  4474. {
  4475. if (r.id != searchId || searchBox.getText().trim() != query)
  4476. return;
  4477. // round 190ce: first the files found through the name of a collection they are in ("starred kick"), then the
  4478. // files found by their own names
  4479. auto found = collectionMatches (query);
  4480. for (const auto& path : r.paths)
  4481. if (juce::File f (juce::String::fromUTF8 (path.c_str())); view.filter == browserview::ContentFilter::all || lists (f))
  4482. found.addIfNotAlreadyThere (f);
  4483. // (partial answers and re-searches keep the selection and the scroll position)
  4484. const auto selected = results->selectedFile();
  4485. const auto scroll = resultsView->getViewPosition();
  4486. results->setFiles (found, scope,
  4487. found.isEmpty() ? (r.partial ? tr ("Indexing the folders... nothing found for \"{0}\" yet.", { query })
  4488. : tr ("Nothing found for \"{0}\".", { query }))
  4489. : juce::String());
  4490. if (selected != juce::File())
  4491. if (const auto row = found.indexOf (selected); row >= 0)
  4492. results->select (row, false);
  4493. resultsView->setViewPosition (scroll);
  4494. searchPartial = r.partial;
  4495. if (! r.partial && ! found.isEmpty())
  4496. // FL's hint bar after a search: "Found 51 files" (REA round 134)
  4497. ui::postHint ({ r.truncated ? tr ("Found more than {0} files", { juce::String (found.size()) })
  4498. : found.size() == 1 ? tr ("Found 1 file") : tr ("Found {0} files", { juce::String (found.size()) }),
  4499. {}, false, false },
  4500. 4000);
  4501. // the line under the search box
  4502. juce::String line;
  4503. if (r.partial)
  4504. line = tr ("Indexing... {0} found so far", { juce::String (found.size()) });
  4505. else if (r.truncated)
  4506. line = tr ("Showing the first {0} results.", { juce::String (maxResults) });
  4507. else
  4508. line = found.size() == 1 ? tr ("Found 1 file") : tr ("Found {0} files", { juce::String (found.size()) });
  4509. const auto st = searcher->service->status();
  4510. if (st.busy && ! r.partial)
  4511. line << " · " << tr ("checking the index...");
  4512. if (line != statusLine)
  4513. {
  4514. const auto relayout = line.isEmpty() != statusLine.isEmpty();
  4515. statusLine = line;
  4516. if (relayout)
  4517. resized();
  4518. repaint (statusArea);
  4519. }
  4520. }
  4521. void BrowserComponent::indexStatusChanged()
  4522. {
  4523. applyFilterToTree(); // the index changed: folders found empty under the content filter go (round 164)
  4524. if (similarTo != juce::File() && resultsView->isVisible())
  4525. return; // similar samples are listed: their own line stays
  4526. const auto st = searcher->service->status();
  4527. juce::String line;
  4528. if (resultsView->isVisible() && tab != projectTab && searchBox.getText().trim().isNotEmpty())
  4529. {
  4530. // a search is shown: its line stays; while the folders are indexed, the progress is added
  4531. line = statusLine.upToFirstOccurrenceOf (" · ", false, false);
  4532. if (st.busy)
  4533. line << " · " << (searchPartial ? tr ("{0} folders indexed", { juce::String ((int) st.listed) }) : tr ("checking the index..."));
  4534. }
  4535. else if (st.busy && (st.rebuilding || st.listed > 0))
  4536. line = tr ("Indexing the Browser's folders for search: {0} folders...", { juce::String ((int) st.listed) });
  4537. if (line != statusLine)
  4538. {
  4539. const auto relayout = line.isEmpty() != statusLine.isEmpty();
  4540. statusLine = line;
  4541. if (relayout)
  4542. resized();
  4543. repaint();
  4544. }
  4545. }
  4546. // --- "Find similar samples" (round 190as) ------------------------------------------------------------------------
  4547. juce::String BrowserComponent::similarLabel() const
  4548. {
  4549. return tr ("Similar to {0}", { similarTo.getFileNameWithoutExtension() });
  4550. }
  4551. juce::Array<juce::File> BrowserComponent::similarScope() const
  4552. {
  4553. return withMerged (roots); // every folder this Browser shows, wherever the sample itself is
  4554. }
  4555. void BrowserComponent::findSimilar (const juce::File& file)
  4556. {
  4557. if (! file.existsAsFile())
  4558. return;
  4559. if (tab == projectTab)
  4560. setTab (allTab);
  4561. similarTo = file;
  4562. searchPending = false;
  4563. searchBox.setText (similarLabel(), juce::dontSendNotification);
  4564. // the first use starts the analysis of the Browser's folders (the clicked file is analysed first, at once)
  4565. if (! allRoots.isEmpty() && ! std::exchange (similar->passAsked, true))
  4566. similar->service->refresh (toPaths (withMerged (allRoots)));
  4567. runSearch();
  4568. }
  4569. void BrowserComponent::findSimilarSamples (const juce::File& file, std::function<void (juce::Array<juce::File>)> done)
  4570. {
  4571. BrowserComponent* main = nullptr;
  4572. for (auto* b : liveBrowsers())
  4573. if (b->role == Role::main)
  4574. main = b;
  4575. if (main == nullptr || main->similar == nullptr || ! file.existsAsFile())
  4576. {
  4577. if (done)
  4578. juce::MessageManager::callAsync ([done] { done ({}); });
  4579. return;
  4580. }
  4581. if (! main->allRoots.isEmpty() && ! std::exchange (main->similar->passAsked, true))
  4582. main->similar->service->refresh (toPaths (main->withMerged (main->allRoots)));
  4583. main->similar->service->findSimilar (file.getFullPathName().toStdString(), toPaths (main->similarScope()), (std::size_t) maxSimilar,
  4584. [done] (const similarity::Result& r) {
  4585. juce::Array<juce::File> found;
  4586. for (const auto& m : r.matches)
  4587. found.add (juce::File (juce::String::fromUTF8 (m.path.c_str())));
  4588. juce::MessageManager::callAsync ([done, found] {
  4589. if (done)
  4590. done (found);
  4591. });
  4592. });
  4593. }
  4594. void BrowserComponent::runSimilar (bool quiet)
  4595. {
  4596. resultsView->setVisible (true);
  4597. treeView->setVisible (false);
  4598. const auto scope = similarScope();
  4599. if (! quiet)
  4600. {
  4601. results->setFiles ({}, scope, tr ("Listening to \"{0}\"...", { similarTo.getFileName() }));
  4602. resultsView->setViewPosition (0, 0);
  4603. }
  4604. similarAskedAt = juce::Time::getMillisecondCounter();
  4605. // the worker answers on its thread: the answer comes to the message thread (and is dropped if this Browser went)
  4606. similarId = similar->service->findSimilar (similarTo.getFullPathName().toStdString(), toPaths (scope), (std::size_t) maxSimilar,
  4607. [safe = juce::Component::SafePointer<BrowserComponent> (this)] (const similarity::Result& r) {
  4608. juce::MessageManager::callAsync ([safe, r] {
  4609. if (safe != nullptr)
  4610. safe->similarAnswered (r);
  4611. });
  4612. });
  4613. }
  4614. void BrowserComponent::similarAnswered (const similarity::Result& r)
  4615. {
  4616. if (r.id != similarId || similarTo == juce::File() || r.query != similarTo.getFullPathName().toStdString())
  4617. return;
  4618. juce::Array<juce::File> found;
  4619. juce::StringArray details;
  4620. for (const auto& m : r.matches)
  4621. if (juce::File f (juce::String::fromUTF8 (m.path.c_str())); view.filter == browserview::ContentFilter::all || lists (f))
  4622. {
  4623. found.add (f);
  4624. details.add (juce::String (similarity::percent (m.distance)) + "%");
  4625. }
  4626. const auto name = similarTo.getFileName();
  4627. // (partial answers keep the selection and the scroll position)
  4628. const auto selected = results->selectedFile();
  4629. const auto scroll = resultsView->getViewPosition();
  4630. results->setFiles (found, similarScope(),
  4631. r.failed ? tr ("\"{0}\" can't be compared: it is silent or can't be read.", { name })
  4632. : found.isEmpty() ? (r.partial ? tr ("Listening to the Browser's samples... nothing like \"{0}\" yet.", { name })
  4633. : tr ("No other samples to compare \"{0}\" with.", { name }))
  4634. : juce::String(),
  4635. details);
  4636. if (selected != juce::File())
  4637. if (const auto row = found.indexOf (selected); row >= 0)
  4638. results->select (row, false);
  4639. resultsView->setViewPosition (scroll);
  4640. similarPartial = r.partial && ! r.failed;
  4641. juce::String line;
  4642. if (! r.failed)
  4643. {
  4644. line = found.size() == 1 ? tr ("1 similar sample, most similar first") : tr ("{0} similar samples, most similar first", { juce::String (found.size()) });
  4645. if (r.partial)
  4646. line << " · " << tr ("{0} samples analysed so far", { juce::String ((int) r.searched) });
  4647. else if (! found.isEmpty())
  4648. ui::postHint ({ tr ("Compared with {0} samples", { juce::String ((int) r.searched) }), {}, false, false }, 4000);
  4649. }
  4650. if (line != statusLine)
  4651. {
  4652. const auto relayout = line.isEmpty() != statusLine.isEmpty();
  4653. statusLine = line;
  4654. if (relayout)
  4655. resized();
  4656. repaint (statusArea);
  4657. }
  4658. }
  4659. void BrowserComponent::similarStatusChanged()
  4660. {
  4661. // the background analysis moved on: a list still marked "so far" is asked again (not more than every 3 s; the
  4662. // last time when the pass ends)
  4663. if (similarTo == juce::File() || ! similarPartial || ! resultsView->isVisible())
  4664. return;
  4665. const auto busy = similar->service->status().busy;
  4666. if (! busy || juce::Time::getMillisecondCounter() - similarAskedAt > 3000)
  4667. runSimilar (true);
  4668. }
  4669. void BrowserComponent::findSimilarForSnapshot (const juce::File& file, const juce::File& folder)
  4670. {
  4671. similar->passAsked = true;
  4672. similar->service->refresh (toPaths ({ folder }));
  4673. similar->service->waitIdle (300000);
  4674. if (tab == projectTab)
  4675. setTab (allTab);
  4676. similarTo = file;
  4677. searchBox.setText (similarLabel(), juce::dontSendNotification);
  4678. resultsView->setVisible (true);
  4679. treeView->setVisible (false);
  4680. auto answer = std::make_shared<std::pair<std::mutex, similarity::Result>>();
  4681. similarId = similar->service->findSimilar (file.getFullPathName().toStdString(), toPaths ({ folder }), (std::size_t) maxSimilar,
  4682. [answer] (const similarity::Result& r) {
  4683. const std::lock_guard<std::mutex> hold (answer->first);
  4684. answer->second = r;
  4685. });
  4686. similar->service->waitIdle (120000);
  4687. const std::lock_guard<std::mutex> hold (answer->first);
  4688. similarAnswered (answer->second);
  4689. }
  4690. void BrowserComponent::refreshSearchIndex (bool rebuild)
  4691. {
  4692. // the index is shared by every Browser: it covers every folder, hidden ones too
  4693. if (! allRoots.isEmpty())
  4694. searcher->service->refresh (toPaths (withMerged (allRoots)), rebuild);
  4695. ui::postHint ({ rebuild ? tr ("Rebuilding the Browser's search index in the background...")
  4696. : tr ("Checking the Browser's search index in the background (only changed folders are read again)..."),
  4697. {}, false, false },
  4698. 4000);
  4699. }
  4700. juce::String BrowserComponent::searchIndexStatus() const
  4701. {
  4702. const auto st = searcher->service->status();
  4703. if (! st.loaded)
  4704. return tr ("Search index: loading...");
  4705. auto text = tr ("Search index: {0} files in {1} folders", { juce::String ((juce::int64) st.files), juce::String ((juce::int64) st.folders) });
  4706. if (st.busy)
  4707. text << " (" << tr ("updating: {0} folders read", { juce::String ((int) st.listed) }) << ")";
  4708. else if (st.checkedAt > 0)
  4709. text << " (" << tr ("checked at {0}", { juce::Time (st.checkedAt).formatted ("%H:%M") }) << ")";
  4710. return text;
  4711. }
  4712. bool BrowserComponent::renameSelectedPlugin()
  4713. {
  4714. return activeList().renameSelectedPlugin();
  4715. }
  4716. void BrowserComponent::stopPreview()
  4717. {
  4718. engine.previewFile ({});
  4719. if (strip != nullptr)
  4720. strip->stop();
  4721. tree->repaint();
  4722. results->repaint();
  4723. }
  4724. // --- keys --------------------------------------------------------------------------------------------
  4725. juce::File BrowserComponent::getSelectedFile() const
  4726. {
  4727. return activeList().selectedFile();
  4728. }
  4729. void BrowserComponent::step (int delta, bool load)
  4730. {
  4731. auto& list = activeList();
  4732. const auto count = list.numRows();
  4733. if (count == 0)
  4734. return;
  4735. // the next row in that direction, as in FL: Up / Down walk every row (folders too: Right opens one, Left closes
  4736. // it), previewing each sample; Shift+Up / Down (loading each file into the channel) skips the folders
  4737. auto row = list.getSelectedRow();
  4738. for (int guard = 0; guard < count; ++guard)
  4739. {
  4740. row = row < 0 ? (delta > 0 ? 0 : count - 1) : row + delta;
  4741. if (row < 0 || row >= count)
  4742. return;
  4743. list.select (row, false);
  4744. if (! load || ! list.selectedIsFolder())
  4745. break;
  4746. }
  4747. const auto file = list.selectedFile();
  4748. if (file.existsAsFile())
  4749. fileSelected (file, true);
  4750. if (load && file.existsAsFile() && onLoadIntoChannel)
  4751. onLoadIntoChannel (file);
  4752. }
  4753. void BrowserComponent::openFolder (bool open)
  4754. {
  4755. if (! resultsView->isVisible())
  4756. tree->openSelected (open);
  4757. }
  4758. void BrowserComponent::loadSelected()
  4759. {
  4760. if (hotSwapLoadSelected()) // round 190ce: while linked, Enter replaces the linked device
  4761. return;
  4762. const auto file = getSelectedFile();
  4763. if (! file.existsAsFile())
  4764. return;
  4765. if (file.hasFileExtension ("sf2;sf3;sfz"))
  4766. {
  4767. // Enter: into the selected LYNX Soundfont channel, else a new one
  4768. if (! openSoundFontFile (engine, file, engine.getSelectedChannel()))
  4769. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Load SoundFont"), tr ("This file is not a SoundFont LYNX SHARE can read."));
  4770. return;
  4771. }
  4772. if (! onLoadIntoChannel || ! onLoadIntoChannel (file))
  4773. openFile (file);
  4774. }
  4775. bool BrowserComponent::isAudioFile (const juce::File& file)
  4776. {
  4777. return isAudio (file);
  4778. }
  4779. bool BrowserComponent::isBrowserDrag (const juce::DragAndDropTarget::SourceDetails& details)
  4780. {
  4781. const auto text = details.description.toString();
  4782. return text == dragDescription || text.startsWith (juce::String (dragDescription) + "|");
  4783. }
  4784. juce::File BrowserComponent::draggedFile (const juce::DragAndDropTarget::SourceDetails& details)
  4785. {
  4786. const auto text = details.description.toString();
  4787. if (text.startsWith (juce::String (dragDescription) + "|"))
  4788. return juce::File (text.fromFirstOccurrenceOf ("|", false, false));
  4789. return {};
  4790. }
  4791. bool BrowserComponent::startPluginDrag (juce::Component& source, std::function<std::optional<ChannelDef>()> generator,
  4792. std::function<std::optional<EffectSlot>()> effect, const juce::String& label, const juce::Image& image,
  4793. juce::Component* containerOwner)
  4794. {
  4795. // (`containerOwner`: the Plugin picker is its own window, outside the main window's drag container)
  4796. // (findParentDragContainerFor looks from the parent up, so the owner itself is tried first)
  4797. auto* container = dynamic_cast<juce::DragAndDropContainer*> (containerOwner);
  4798. if (container == nullptr)
  4799. container = juce::DragAndDropContainer::findParentDragContainerFor (containerOwner != nullptr ? containerOwner : &source);
  4800. if (container == nullptr || (generator == nullptr && effect == nullptr))
  4801. return false;
  4802. const auto isGenerator = generator != nullptr;
  4803. draggedPlugin() = { std::move (generator), std::move (effect) };
  4804. container->startDragging (juce::String (isGenerator ? generatorDragDescription : effectDragDescription) + "|" + label, &source,
  4805. juce::ScaledImage (image), true);
  4806. return true;
  4807. }
  4808. bool BrowserComponent::isGeneratorDrag (const juce::DragAndDropTarget::SourceDetails& details)
  4809. {
  4810. return details.description.toString().startsWith (juce::String (generatorDragDescription) + "|") && draggedPlugin().generator != nullptr;
  4811. }
  4812. bool BrowserComponent::isEffectDrag (const juce::DragAndDropTarget::SourceDetails& details)
  4813. {
  4814. return details.description.toString().startsWith (juce::String (effectDragDescription) + "|") && draggedPlugin().effect != nullptr;
  4815. }
  4816. std::optional<ChannelDef> BrowserComponent::draggedGenerator (const juce::DragAndDropTarget::SourceDetails& details)
  4817. {
  4818. return isGeneratorDrag (details) ? draggedPlugin().generator() : std::nullopt;
  4819. }
  4820. std::optional<EffectSlot> BrowserComponent::draggedEffect (const juce::DragAndDropTarget::SourceDetails& details)
  4821. {
  4822. return isEffectDrag (details) ? draggedPlugin().effect() : std::nullopt;
  4823. }
  4824. int BrowserComponent::draggedPattern (const juce::DragAndDropTarget::SourceDetails& details)
  4825. {
  4826. const auto text = details.description.toString();
  4827. if (text.startsWith (juce::String (patternDragDescription) + "|"))
  4828. return text.fromFirstOccurrenceOf ("|", false, false).getIntValue();
  4829. return -1;
  4830. }
  4831. void BrowserComponent::newSampleChannel (const juce::File& file)
  4832. {
  4833. const auto path = file.getFullPathName().toStdString();
  4834. const auto name = file.getFileNameWithoutExtension().toStdString();
  4835. engine.editSong ([&] (Song& s) {
  4836. ChannelDef c;
  4837. c.name = name;
  4838. c.instrument = InstrumentKind::sampler;
  4839. c.samplePath = path;
  4840. c.mixerTrack = s.claimFreeInsert();
  4841. s.channels.push_back (c);
  4842. });
  4843. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  4844. }
  4845. void BrowserComponent::openFile (const juce::File& file)
  4846. {
  4847. // a hosted plugin's preset (round 162d, issue #8): into the plugin it belongs to
  4848. if (pluginpresetui::isPresetFile (file) && (! file.hasFileExtension ("lynxpreset") || pluginpresetui::readLynxPreset (file).has_value()))
  4849. {
  4850. juce::String message;
  4851. if (! pluginpresetui::applyFromBrowser (engine, file, message) && message.isNotEmpty())
  4852. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin preset"), message);
  4853. return;
  4854. }
  4855. if (file.hasFileExtension ("sf2;sf3;sfz"))
  4856. {
  4857. if (! openSoundFontFile (engine, file))
  4858. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Load SoundFont"), tr ("This file is not a SoundFont LYNX SHARE can read."));
  4859. return;
  4860. }
  4861. if (isAudio (file) && file.hasFileExtension ("speech"))
  4862. {
  4863. // FL's .speech: the Speech properties first, then a new channel with the file it returns (round 168b)
  4864. speechui::editThenLoad (engine, file, [safe = juce::Component::SafePointer<BrowserComponent> (this)] (const juce::File& f) {
  4865. if (safe != nullptr && f.existsAsFile())
  4866. {
  4867. safe->newSampleChannel (f);
  4868. safe->rebuildTree(); // (an edited copy appears in the Speech folder)
  4869. }
  4870. });
  4871. return;
  4872. }
  4873. if (isAudio (file))
  4874. {
  4875. newSampleChannel (file);
  4876. return;
  4877. }
  4878. // FL's mixer preset (REA round 167q) or LYNX's mixer track state: onto the selected mixer tracks
  4879. if (file.hasFileExtension ("fst;lynxtrack") && onOpenMixerPreset && onOpenMixerPreset (file))
  4880. return;
  4881. // preset of an FL synth that LYNX converts (3x Osc, Sytrus, GMS...): new channel with the built-in synth
  4882. if (file.hasFileExtension ("fst;gmsynth"))
  4883. {
  4884. juce::MemoryBlock data;
  4885. if (! file.loadFileAsData (data))
  4886. return;
  4887. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  4888. if (auto synth = synthFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize())))
  4889. {
  4890. const auto name = file.getFileNameWithoutExtension().toStdString();
  4891. engine.editSong ([&] (Song& s) {
  4892. ChannelDef c;
  4893. c.name = name;
  4894. c.instrument = InstrumentKind::synth;
  4895. c.synth = *synth;
  4896. c.mixerTrack = s.claimFreeInsert();
  4897. s.channels.push_back (c);
  4898. });
  4899. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  4900. }
  4901. else
  4902. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Preset"),
  4903. tr ("LYNX SHARE reads presets from 3x Osc, Sytrus, Harmor, GMS, Harmless, MiniSynth, DX10, Fruit Kick, Ogun and Sakura."));
  4904. return;
  4905. }
  4906. if (file.hasFileExtension ("lynx;flp;als;flm;mid;midi") && onOpenProject)
  4907. onOpenProject (file);
  4908. }
  4909. } // namespace lynx