BrowserComponent.cpp 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106
  1. #include "ui/PluginPresetMenu.h"
  2. #include "ui/BrowserComponent.h"
  3. #include "ui/UiTrace.h"
  4. #include "core/FlpImport.h"
  5. #include "core/ProjectContents.h"
  6. #include "core/SearchIndex.h"
  7. #include "core/SearchQuery.h"
  8. #include "core/SearchService.h"
  9. #include "core/ValueMath.h"
  10. #include "platform/Paths.h"
  11. #include <mutex>
  12. #include "engine/PluginHost.h"
  13. #include "engine/Text.h"
  14. #include "ui/HintBar.h"
  15. #include "ui/I18n.h"
  16. #include "ui/Icons.h"
  17. #include "ui/PlaylistComponent.h"
  18. #include "ui/Theme.h"
  19. #include "ui/ValueControl.h"
  20. #include "ui/WaveformView.h"
  21. #include "ui/AudioEditor.h"
  22. #include "ui/AutomationUi.h"
  23. #include "ui/ChannelRackComponent.h"
  24. #include "ui/MixerComponent.h"
  25. #include "ui/SoundFontEditor.h"
  26. namespace lynx
  27. {
  28. namespace
  29. {
  30. bool isAudio (const juce::File& f)
  31. {
  32. return f.hasFileExtension ("wav;flac;ogg;mp3;aif;aiff;wv");
  33. }
  34. bool isListed (const juce::File& f)
  35. {
  36. return f.hasFileExtension ("wav;flac;ogg;mp3;aif;aiff;wv;mid;midi;lynx;flp;fst;sf2;sf3");
  37. }
  38. constexpr int maxResults = 500;
  39. search::FileSystem diskFileSystem()
  40. {
  41. search::FileSystem fs;
  42. fs.separator = juce::File::getSeparatorChar() == '\\' ? '\\' : '/';
  43. fs.folderTime = [] (const std::string& path) -> std::int64_t {
  44. const juce::File folder (juce::String::fromUTF8 (path.c_str()));
  45. return folder.isDirectory() ? folder.getLastModificationTime().toMilliseconds() : -1;
  46. };
  47. fs.list = [] (const std::string& path) {
  48. search::FolderListing listing;
  49. const juce::File folder (juce::String::fromUTF8 (path.c_str()));
  50. if (! folder.isDirectory())
  51. return listing;
  52. listing.exists = true;
  53. listing.time = folder.getLastModificationTime().toMilliseconds();
  54. auto children = folder.findChildFiles (juce::File::findFilesAndDirectories, false, "*");
  55. children.sort();
  56. for (const auto& c : children)
  57. {
  58. if (c.isDirectory())
  59. {
  60. // junctions and links (Windows' "My Music" inside Documents points back to itself) are not followed
  61. if (! c.isSymbolicLink())
  62. listing.subfolders.push_back (c.getFileName().toStdString());
  63. }
  64. else if (isListed (c))
  65. listing.files.push_back (c.getFileName().toStdString());
  66. }
  67. return listing;
  68. };
  69. return fs;
  70. }
  71. std::vector<std::string> toPaths (const juce::Array<juce::File>& folders)
  72. {
  73. std::vector<std::string> paths;
  74. for (const auto& f : folders)
  75. paths.push_back (f.getFullPathName().toStdString());
  76. return paths;
  77. }
  78. Icon iconFor (const juce::File& f, bool folder)
  79. {
  80. if (folder)
  81. return Icon::folder;
  82. if (isAudio (f))
  83. return Icon::audioFile;
  84. if (f.hasFileExtension ("mid;midi"))
  85. return Icon::pianoRoll;
  86. if (f.hasFileExtension ("lynx;flp"))
  87. return Icon::project;
  88. if (f.hasFileExtension ("fst;sf2;sf3;lynxpreset;fxp;fxb;vstpreset"))
  89. return Icon::preset;
  90. return Icon::file;
  91. }
  92. // The hint for a file or folder row: what the mouse can do with it.
  93. juce::String rowHint (const juce::File& f, bool folder, bool expanded)
  94. {
  95. if (folder)
  96. return (expanded ? tr ("Folder: [LMB] close") : tr ("Folder: [LMB] open")) + " " + tr ("[RMB] menu (collapse all, show in the file manager)");
  97. if (isAudio (f))
  98. return tr ("Sample: [LMB] preview [2xLMB] new channel drag to the Channel Rack or the Playlist [Enter] into the selected channel "
  99. "[Shift][Up] / [Shift][Down] swap through the files");
  100. if (f.hasFileExtension ("mid;midi"))
  101. return tr ("MIDI file: [2xLMB] open it as a project");
  102. if (f.hasFileExtension ("lynx;flp"))
  103. return tr ("Project: [2xLMB] open it");
  104. if (f.hasFileExtension ("fst"))
  105. return tr ("Preset: [2xLMB] new channel with it (FL synth presets) drag onto a mixer insert: effect preset");
  106. if (f.hasFileExtension ("lynxpreset;fxp;fxb;vstpreset"))
  107. return tr ("Plugin preset: [2xLMB] load it into its plugin (an open plugin window, or the selected channel's plugin)");
  108. if (f.hasFileExtension ("sf2;sf3"))
  109. return tr ("SoundFont: [LMB] preview its first preset [2xLMB] new LYNX Soundfont channel (or into the selected one) drag to the Channel Rack");
  110. return {};
  111. }
  112. // A user / channel colour made readable as text and icons on the Browser's dark rows.
  113. juce::Colour readable (juce::Colour c)
  114. {
  115. return c.withMultipliedSaturation (0.8f).withBrightness (juce::jlimit (0.72f, 0.92f, c.getBrightness() + 0.15f));
  116. }
  117. // The Current project's sections, in FL's order (REA_rodada115).
  118. enum class Category
  119. {
  120. history,
  121. patterns,
  122. effects,
  123. generators,
  124. automation,
  125. initialized, // FL's "Initialized controls" (REA round 146)
  126. samples
  127. };
  128. constexpr Category categories[] = { Category::history, Category::patterns, Category::effects, Category::generators,
  129. Category::automation, Category::initialized, Category::samples };
  130. juce::String categoryName (Category c)
  131. {
  132. switch (c)
  133. {
  134. case Category::history: return tr ("History");
  135. case Category::patterns: return tr ("Patterns");
  136. case Category::effects: return tr ("Effects");
  137. case Category::generators: return tr ("Generators");
  138. case Category::automation: return tr ("Automation");
  139. case Category::initialized: return tr ("Initialized controls");
  140. case Category::samples: return tr ("Audio files");
  141. }
  142. return {};
  143. }
  144. juce::String categoryHint (Category c)
  145. {
  146. switch (c)
  147. {
  148. case Category::history: return tr ("Undo history of this project: [LMB] go back to that step");
  149. case Category::patterns: return tr ("Patterns of this project, in their colours");
  150. case Category::effects: return tr ("Effects in use, with the insert they sit on");
  151. case Category::generators: return tr ("Generators in use (the Channel Rack's channels), with the insert they play into");
  152. case Category::automation: return tr ("Automation clips of this project");
  153. case Category::initialized: return tr ("Initialized controls: to be reset when the song starts (a control's menu > Init song with this position)");
  154. case Category::samples: return tr ("Audio files used by this project (samples, audio clips), in the colour of the channel that plays them");
  155. }
  156. return {};
  157. }
  158. Icon categoryIcon (Category c)
  159. {
  160. switch (c)
  161. {
  162. case Category::history: return Icon::undo;
  163. case Category::patterns: return Icon::pattern;
  164. case Category::effects: return Icon::mixer;
  165. case Category::generators: return Icon::keyboard;
  166. case Category::automation: return Icon::automate;
  167. case Category::initialized: return Icon::automate;
  168. case Category::samples: return Icon::audioFile;
  169. }
  170. return Icon::folder;
  171. }
  172. // Each top-level folder has its own colour (FL colours its Browser's folders by kind; LYNX uses its own set).
  173. juce::Colour rootColour (int index)
  174. {
  175. static const juce::Colour colours[] = { juce::Colour (0xff6ea8fe), juce::Colour (0xff3ddc84), juce::Colour (0xffe58fd0),
  176. juce::Colour (0xffb39ddb), juce::Colour (0xffb39ddb), juce::Colour (0xfff5b942),
  177. juce::Colour (0xff4cc9c0), juce::Colour (0xfff2a65a), juce::Colour (0xff9fb7d0) };
  178. return index >= 0 && index < (int) std::size (colours) ? colours[index] : juce::Colour (0xff8fd18c);
  179. }
  180. } // namespace
  181. namespace
  182. {
  183. // The plugin being dragged from the Plugin database (one drag at a time; message thread).
  184. struct DraggedPlugin
  185. {
  186. std::function<std::optional<ChannelDef>()> generator;
  187. std::function<std::optional<EffectSlot>()> effect;
  188. };
  189. DraggedPlugin& draggedPlugin()
  190. {
  191. static DraggedPlugin d;
  192. return d;
  193. }
  194. } // namespace
  195. // --- search: the process's search worker ------------------------------------------------------------
  196. // The Browser's search index and its worker (core/SearchService.h, round 162): one per process while a Browser exists,
  197. // the index kept in the settings folder between sessions. Its news reach the Browsers through two broadcasters (they
  198. // are thread-safe and coalesce); the worker is joined (never killed) before they go.
  199. struct BrowserComponent::SearchShared
  200. {
  201. juce::ChangeBroadcaster statusChanged, indexChanged;
  202. std::unique_ptr<search::Service> service; // (last: goes first)
  203. ~SearchShared() { service.reset(); }
  204. static juce::File file() { return platform::settingsFile ("browser-index.txt"); }
  205. static std::shared_ptr<SearchShared> get()
  206. {
  207. static std::weak_ptr<SearchShared> current; // (message thread)
  208. if (auto s = current.lock())
  209. return s;
  210. auto s = std::make_shared<SearchShared>();
  211. search::Service::Callbacks cb;
  212. cb.load = [] {
  213. const auto f = file();
  214. juce::MemoryBlock data;
  215. if (! f.existsAsFile() || f.getSize() > 256 * 1024 * 1024 || ! f.loadFileAsData (data))
  216. return std::string();
  217. return std::string (static_cast<const char*> (data.getData()), data.getSize());
  218. };
  219. cb.save = [] (const std::string& text) {
  220. const auto f = file();
  221. const auto temp = f.getSiblingFile (f.getFileName() + ".tmp");
  222. if (temp.replaceWithData (text.data(), text.size()))
  223. temp.moveFileTo (f);
  224. };
  225. cb.statusChanged = [raw = s.get()] { raw->statusChanged.sendChangeMessage(); };
  226. cb.indexChanged = [raw = s.get()] { raw->indexChanged.sendChangeMessage(); };
  227. s->service = std::make_unique<search::Service> (diskFileSystem(), std::move (cb));
  228. current = s;
  229. return s;
  230. }
  231. };
  232. // A click anywhere outside the search box (another panel, the toolbar, the Browser's own list) takes the keyboard
  233. // back from it, so Space plays / stops again (issue #9; FL ends typing in its search field the same way).
  234. class BrowserComponent::FocusWatcher final : public juce::MouseListener
  235. {
  236. public:
  237. explicit FocusWatcher (BrowserComponent& b) : browser (b) { juce::Desktop::getInstance().addGlobalMouseListener (this); }
  238. ~FocusWatcher() override { juce::Desktop::getInstance().removeGlobalMouseListener (this); }
  239. void mouseDown (const juce::MouseEvent& e) override
  240. {
  241. auto* clicked = e.eventComponent;
  242. if (! browser.isTypingInSearch() || clicked == nullptr)
  243. return;
  244. if (clicked == &browser.searchBox || browser.searchBox.isParentOf (clicked))
  245. return;
  246. // a menu (the box's own right-click menu: Paste...) keeps it
  247. if (clicked->getTopLevelComponent() != browser.getTopLevelComponent() && clicked->getTopLevelComponent()->isAlwaysOnTop()
  248. && dynamic_cast<juce::ResizableWindow*> (clicked->getTopLevelComponent()) == nullptr)
  249. return;
  250. browser.leaveSearchBox();
  251. }
  252. private:
  253. BrowserComponent& browser;
  254. };
  255. // --- the tree (and, flat, the search results) ---------------------------------------------------------
  256. class BrowserComponent::FileTree final : public juce::Component,
  257. public ui::HintSource
  258. {
  259. public:
  260. static constexpr int rowHeight = 22;
  261. FileTree (BrowserComponent& b, bool isFlat) : browser (b), flat (isFlat)
  262. {
  263. setWantsKeyboardFocus (false);
  264. setMouseClickGrabsKeyboardFocus (false);
  265. }
  266. enum class Kind
  267. {
  268. fsFolder, // a folder on disk (top-level ones carry their own name and colour)
  269. file, // a file on disk
  270. project, // "Current project"
  271. category, // one of its sections
  272. item, // something of the project (pattern, sample, generator, effect, automation clip, undo step)
  273. plugins, // the Plugin database and its folders (round 142): built-in, FL engines, installed plugins
  274. plugin // one of its plugins (double-click adds it)
  275. };
  276. struct Node
  277. {
  278. Kind kind = Kind::file;
  279. juce::File file;
  280. bool folder = false, expanded = false, loaded = false;
  281. int depth = 0;
  282. Node* parent = nullptr;
  283. std::vector<std::unique_ptr<Node>> children;
  284. juce::String label, detail; // display name (empty: the file's) and the dimmed detail after it
  285. juce::Colour colour; // transparent: the default
  286. Icon icon = Icon::none; // none: by file type
  287. Category category = Category::samples;
  288. projectcontents::Item item; // kind == item (history: item.index = the step)
  289. bool history = false, missing = false, current = false;
  290. bool initial = false; // an initialized control (item.index = into Song::initialValues)
  291. std::function<void()> activate; // kind == plugin: adds it
  292. // kind == plugin: what it adds (one of them), also when it is dragged (round 162)
  293. std::function<std::optional<ChannelDef>()> generator;
  294. std::function<std::optional<EffectSlot>()> effect;
  295. };
  296. // tree mode: the given top-level nodes
  297. void setTopLevel (std::vector<std::unique_ptr<Node>> nodes)
  298. {
  299. root = std::make_unique<Node>();
  300. root->kind = Kind::fsFolder;
  301. root->folder = root->expanded = root->loaded = true;
  302. root->depth = -1;
  303. for (auto& n : nodes)
  304. {
  305. n->parent = root.get();
  306. n->depth = 0;
  307. if (n->expanded)
  308. load (*n);
  309. root->children.push_back (std::move (n));
  310. }
  311. selected = hovered = -1;
  312. rebuild();
  313. }
  314. static std::unique_ptr<Node> makeFolder (const juce::File& folder, const juce::String& label, juce::Colour colour)
  315. {
  316. auto n = std::make_unique<Node>();
  317. n->kind = Kind::fsFolder;
  318. n->file = folder;
  319. n->folder = true;
  320. n->label = label;
  321. n->colour = colour;
  322. return n;
  323. }
  324. // FL's "Plugin database", interpreted (round 142, issue #5): Generators and Effects, each with LYNX's built-in ones,
  325. // FL's engines (those the user's FL installation provides) and the installed VST3 / CLAP plugins
  326. static std::unique_ptr<Node> makePluginDatabase (BrowserComponent& browser, const std::set<juce::String>& open)
  327. {
  328. auto folder = [&open] (Node* parent, const juce::String& label, Icon icon) {
  329. auto n = std::make_unique<Node>();
  330. n->kind = Kind::plugins;
  331. n->folder = n->loaded = true;
  332. n->label = label;
  333. n->icon = icon;
  334. n->parent = parent;
  335. n->depth = parent != nullptr ? parent->depth + 1 : 0;
  336. n->expanded = open.count ((parent != nullptr && parent->kind == Kind::plugins ? parent->label + "/" : juce::String()) + label) > 0;
  337. return n;
  338. };
  339. auto node = [] (Node& parent, const juce::String& label, const juce::String& detail, Icon icon) -> Node& {
  340. auto n = std::make_unique<Node>();
  341. n->kind = Kind::plugin;
  342. n->label = label;
  343. n->detail = detail;
  344. n->icon = icon;
  345. n->parent = &parent;
  346. n->depth = parent.depth + 1;
  347. parent.children.push_back (std::move (n));
  348. return *parent.children.back();
  349. };
  350. auto root = folder (nullptr, tr ("Plugin database"), Icon::plugin);
  351. root->colour = theme::colour::info;
  352. auto safe = juce::Component::SafePointer<BrowserComponent> (&browser);
  353. // a generator / an effect: double-click adds it (to the rack / the selected insert), or drag it there
  354. auto generatorEntry = [&node, safe] (Node& parent, const juce::String& label, const juce::String& detail, Icon icon,
  355. std::function<std::optional<ChannelDef>()> make) {
  356. auto& n = node (parent, label, detail, icon);
  357. n.generator = make;
  358. n.activate = [safe, make] {
  359. if (auto c = make(); c && safe != nullptr && safe->onAddInstrument)
  360. safe->onAddInstrument (std::move (*c));
  361. };
  362. };
  363. auto effectEntry = [&node, safe] (Node& parent, const juce::String& label, const juce::String& detail, Icon icon,
  364. std::function<std::optional<EffectSlot>()> make) {
  365. auto& n = node (parent, label, detail, icon);
  366. n.effect = make;
  367. n.activate = [safe, make] {
  368. if (auto fx = make(); fx && safe != nullptr && safe->onAddEffect)
  369. safe->onAddEffect (std::move (*fx));
  370. };
  371. };
  372. const auto bpm = browser.engine.getSong().bpm;
  373. const auto& fl = flStudioAccess();
  374. auto types = browser.engine.getPluginHost().getKnownPlugins().getTypes();
  375. std::sort (types.begin(), types.end(), [] (const auto& a, const auto& b) { return a.name.compareIgnoreCase (b.name) < 0; });
  376. // Generators
  377. {
  378. auto gens = folder (root.get(), tr ("Generators"), Icon::keyboard);
  379. auto lynxGens = folder (gens.get(), "LYNX", Icon::folder);
  380. const std::pair<InstrumentKind, const char*> builtIn[] = { { InstrumentKind::synth, TR_NOOP ("Synth") }, { InstrumentKind::kick, TR_NOOP ("Kick") },
  381. { InstrumentKind::snare, TR_NOOP ("Snare") }, { InstrumentKind::hat, TR_NOOP ("Hat") },
  382. { InstrumentKind::clap, TR_NOOP ("Clap") } };
  383. for (const auto& [kind, name] : builtIn)
  384. generatorEntry (*lynxGens, tr (name), tr ("built-in"), Icon::keyboard, [kind = kind, english = std::string (name)] {
  385. ChannelDef c;
  386. c.name = english;
  387. c.instrument = kind;
  388. return std::optional<ChannelDef> (c);
  389. });
  390. auto flGens = folder (gens.get(), tr ("FL engines"), Icon::folder);
  391. for (const auto& e : natives::instrumentEngines())
  392. if (natives::available (e, fl))
  393. generatorEntry (*flGens, flEngineName (e), tr ("built-in FL engine"), Icon::keyboard,
  394. [kind = e.kind] { return std::optional<ChannelDef> (natives::makeChannel (kind, flStudioAccess())); });
  395. auto installed = folder (gens.get(), tr ("Installed"), Icon::folder);
  396. for (const auto& t : types)
  397. if (t.isInstrument)
  398. generatorEntry (*installed, t.name, t.manufacturerName + " · " + t.pluginFormatName, Icon::plugin,
  399. [id = t.createIdentifierString().toStdString(), name = t.name.toStdString()] {
  400. ChannelDef c;
  401. c.name = name;
  402. c.instrument = InstrumentKind::plugin;
  403. c.plugin.id = id;
  404. c.plugin.name = name;
  405. return std::optional<ChannelDef> (c);
  406. });
  407. for (auto* f : { &lynxGens, &flGens, &installed })
  408. if (! (*f)->children.empty())
  409. gens->children.push_back (std::move (*f));
  410. root->children.push_back (std::move (gens));
  411. }
  412. // Effects
  413. {
  414. auto fxs = folder (root.get(), tr ("Effects"), Icon::mixer);
  415. auto lynxFx = folder (fxs.get(), "LYNX", Icon::folder);
  416. auto flFx = folder (fxs.get(), tr ("FL engines"), Icon::folder);
  417. for (const auto kind : addableEffects())
  418. if (addableEffectAvailable (kind))
  419. {
  420. const auto flEngine = natives::effectEngine (kind) != nullptr;
  421. effectEntry (flEngine ? *flFx : *lynxFx, addableEffectName (kind), flEngine ? tr ("built-in FL engine") : tr ("built-in"), Icon::mixer,
  422. [kind, bpm] { return std::optional<EffectSlot> (newAddableEffect (kind, bpm)); });
  423. }
  424. auto installed = folder (fxs.get(), tr ("Installed"), Icon::folder);
  425. for (const auto& t : types)
  426. if (! t.isInstrument)
  427. effectEntry (*installed, t.name, t.manufacturerName + " · " + t.pluginFormatName, Icon::plugin,
  428. [id = t.createIdentifierString().toStdString(), name = t.name.toStdString()] {
  429. EffectSlot fx;
  430. fx.kind = EffectKind::plugin;
  431. fx.plugin.id = id;
  432. fx.plugin.name = name;
  433. return std::optional<EffectSlot> (fx);
  434. });
  435. for (auto* f : { &lynxFx, &flFx, &installed })
  436. if (! (*f)->children.empty())
  437. fxs->children.push_back (std::move (*f));
  438. root->children.push_back (std::move (fxs));
  439. }
  440. // (the counts, dimmed after each folder)
  441. std::function<int (Node&)> count = [&count] (Node& n) {
  442. int total = 0;
  443. for (auto& c : n.children)
  444. total += c->kind == Kind::plugin ? 1 : count (*c);
  445. if (n.kind == Kind::plugins)
  446. n.detail = juce::String (total);
  447. return total;
  448. };
  449. count (*root);
  450. return root;
  451. }
  452. static std::unique_ptr<Node> makeProject (bool open)
  453. {
  454. auto n = std::make_unique<Node>();
  455. n->kind = Kind::project;
  456. n->folder = true;
  457. n->expanded = open;
  458. n->label = tr ("Current project");
  459. n->icon = Icon::project;
  460. n->colour = theme::colour::accent;
  461. return n;
  462. }
  463. // flat mode: a list of files with their path relative to the folder searched that holds them
  464. void setFiles (const juce::Array<juce::File>& files, const juce::Array<juce::File>& newBases, const juce::String& newStatus)
  465. {
  466. bases = newBases;
  467. status = newStatus;
  468. flatNodes.clear();
  469. for (const auto& f : files)
  470. {
  471. auto n = std::make_unique<Node>();
  472. n->file = f;
  473. flatNodes.push_back (std::move (n));
  474. }
  475. selected = hovered = -1;
  476. rebuild();
  477. }
  478. // flat mode: project items (the PROJECT tab's search)
  479. void setNodes (std::vector<std::unique_ptr<Node>> nodes, const juce::String& newStatus)
  480. {
  481. bases.clear();
  482. status = newStatus;
  483. flatNodes = std::move (nodes);
  484. selected = hovered = -1;
  485. rebuild();
  486. }
  487. void setStatus (const juce::String& text)
  488. {
  489. status = text;
  490. repaint();
  491. }
  492. juce::File selectedFile() const
  493. {
  494. return juce::isPositiveAndBelow (selected, (int) rows.size()) ? rows[(std::size_t) selected]->file : juce::File();
  495. }
  496. // the top-level folder on disk that holds the selection (none: the selection is not a file)
  497. juce::File selectedRoot() const
  498. {
  499. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  500. return {};
  501. for (auto* n = rows[(std::size_t) selected]; n != nullptr; n = n->parent)
  502. if (n->kind == Kind::fsFolder && n->depth == 0)
  503. return n->file;
  504. return {};
  505. }
  506. bool selectedIsFolder() const { return juce::isPositiveAndBelow (selected, (int) rows.size()) && rows[(std::size_t) selected]->folder; }
  507. int numRows() const { return (int) rows.size(); }
  508. int getSelectedRow() const { return selected; }
  509. void select (int row, bool preview)
  510. {
  511. row = rows.empty() ? -1 : juce::jlimit (0, (int) rows.size() - 1, row);
  512. if (row != selected)
  513. {
  514. repaintRow (selected);
  515. selected = row;
  516. repaintRow (selected);
  517. }
  518. scrollToRow (row);
  519. if (row >= 0)
  520. browser.fileSelected (rows[(std::size_t) row]->file, preview && ! rows[(std::size_t) row]->folder);
  521. }
  522. // Left / Right: close the selected folder (or go to its parent) / open it
  523. void openSelected (bool open)
  524. {
  525. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  526. return;
  527. auto* n = rows[(std::size_t) selected];
  528. if (n->folder && n->expanded != open)
  529. {
  530. toggle (*n);
  531. return;
  532. }
  533. if (! open && n->parent != nullptr && n->parent != root.get())
  534. for (int i = 0; i < (int) rows.size(); ++i)
  535. if (rows[(std::size_t) i] == n->parent)
  536. {
  537. select (i, false);
  538. return;
  539. }
  540. }
  541. void collapseAll()
  542. {
  543. if (root == nullptr)
  544. return;
  545. std::function<void (Node&)> close = [&close] (Node& n) {
  546. for (auto& c : n.children)
  547. {
  548. c->expanded = false;
  549. close (*c);
  550. }
  551. };
  552. close (*root);
  553. selected = hovered = -1;
  554. rebuild();
  555. }
  556. void expandAll (Node& n)
  557. {
  558. n.expanded = true;
  559. load (n);
  560. if (n.kind == Kind::project || n.kind == Kind::category)
  561. for (auto& c : n.children)
  562. if (c->folder && c->kind != Kind::fsFolder)
  563. expandAll (*c);
  564. rebuild();
  565. }
  566. // FL's folder "Expand all": the folder and its sub-folders open (on disk: down to `depth` levels, so a big
  567. // library is not scanned at once)
  568. void expandFolder (Node& n, int depth)
  569. {
  570. n.expanded = true;
  571. load (n);
  572. if (depth > 1)
  573. for (auto& c : n.children)
  574. if (c->folder)
  575. expandFolder (*c, depth - 1);
  576. rebuild();
  577. }
  578. void rebuild()
  579. {
  580. rows.clear();
  581. if (flat)
  582. for (auto& n : flatNodes)
  583. rows.push_back (n.get());
  584. else if (root != nullptr)
  585. addRows (*root);
  586. updateSize();
  587. repaint();
  588. }
  589. void updateSize()
  590. {
  591. if (auto* parent = getParentComponent())
  592. {
  593. const auto width = parent->getWidth();
  594. const auto viewHeight = parent->getParentComponent() != nullptr ? parent->getParentComponent()->getHeight() : parent->getHeight();
  595. setSize (width, juce::jmax (viewHeight, (int) rows.size() * rowHeight));
  596. }
  597. }
  598. // The project changed: the open sections are listed again (only those whose items changed), keeping what is
  599. // open and selected.
  600. void refreshProject()
  601. {
  602. if (root == nullptr)
  603. return;
  604. bool changed = false;
  605. const auto key = selectionKey();
  606. std::function<void (Node&)> visit = [&] (Node& n) {
  607. if (n.kind == Kind::category)
  608. {
  609. Node fresh;
  610. fresh.kind = Kind::category;
  611. fresh.category = n.category;
  612. fresh.depth = n.depth;
  613. listCategory (fresh, browser.engine.getSong(), &browser.engine, ! n.loaded);
  614. if (n.detail != fresh.detail)
  615. {
  616. n.detail = fresh.detail;
  617. changed = true;
  618. }
  619. if (! n.loaded)
  620. return;
  621. if (signature (fresh) != signature (n))
  622. {
  623. n.children = std::move (fresh.children);
  624. for (auto& c : n.children)
  625. c->parent = &n;
  626. changed = true;
  627. }
  628. else
  629. for (std::size_t i = 0; i < n.children.size(); ++i) // the same items: only the "current" marks
  630. n.children[i]->current = fresh.children[i]->current;
  631. return;
  632. }
  633. for (auto& c : n.children)
  634. if (c->kind == Kind::project || c->kind == Kind::category)
  635. visit (*c);
  636. };
  637. visit (*root);
  638. pendingKey = key;
  639. if (changed)
  640. {
  641. rebuild();
  642. restoreSelection (pendingKey);
  643. }
  644. else
  645. repaint();
  646. }
  647. void paint (juce::Graphics& g) override
  648. {
  649. using namespace theme::colour;
  650. g.fillAll (bg2);
  651. const auto clip = g.getClipBounds();
  652. const auto first = juce::jmax (0, clip.getY() / rowHeight), last = juce::jmin ((int) rows.size() - 1, clip.getBottom() / rowHeight);
  653. const auto previewing = browser.isPreviewPlaying() ? browser.previewedFile : juce::File();
  654. for (int i = first; i <= last; ++i)
  655. {
  656. const auto& n = *rows[(std::size_t) i];
  657. auto r = juce::Rectangle<int> (0, i * rowHeight, getWidth(), rowHeight);
  658. // an open project section sits on a slightly raised band (FL draws its open folders on a band)
  659. if ((n.kind == Kind::project || n.kind == Kind::category) && n.expanded)
  660. {
  661. g.setColour (bg3);
  662. g.fillRect (r);
  663. }
  664. if (i == selected)
  665. {
  666. g.setColour (accentMuted);
  667. g.fillRect (r);
  668. g.setColour (accent);
  669. g.fillRect (r.withWidth (2));
  670. }
  671. else if (i == hovered)
  672. {
  673. g.setColour (bg4);
  674. g.fillRect (r);
  675. }
  676. const auto indent = flat ? 6 : 6 + n.depth * 14;
  677. auto x = (float) indent;
  678. if (n.folder) // a chevron: right when closed, down when open
  679. {
  680. juce::Path p;
  681. const auto c = juce::Point<float> (x + 5.0f, (float) r.getCentreY());
  682. if (n.expanded)
  683. p.addTriangle (c.x - 3.5f, c.y - 2.0f, c.x + 3.5f, c.y - 2.0f, c.x, c.y + 2.5f);
  684. else
  685. p.addTriangle (c.x - 2.0f, c.y - 3.5f, c.x - 2.0f, c.y + 3.5f, c.x + 2.5f, c.y);
  686. g.setColour (i == hovered || i == selected ? textPrimary : textSecondary);
  687. g.fillPath (p);
  688. }
  689. if (! flat || n.kind != Kind::item)
  690. x += 12.0f;
  691. const auto playing = ! n.folder && n.file != juce::File() && n.file == previewing;
  692. const auto hasColour = ! n.colour.isTransparent();
  693. auto iconColour = playing ? accent : hasColour ? readable (n.colour) : n.folder ? warning.withAlpha (0.85f) : textSecondary;
  694. if (n.missing)
  695. iconColour = meterClip;
  696. const auto icon = n.icon != Icon::none ? n.icon : iconFor (n.file, n.folder);
  697. icons::draw (g, icon, juce::Rectangle<float> (x, (float) r.getY() + 3.0f, 16.0f, 16.0f), iconColour);
  698. x += 21.0f;
  699. auto text = r.withLeft ((int) x).withTrimmedRight (6);
  700. if (flat && n.kind == Kind::file) // the folder it lives in, on the right
  701. {
  702. const auto where = n.file.getParentDirectory().getRelativePathFrom (baseOf (n.file));
  703. g.setFont (theme::font (theme::type::caption));
  704. g.setColour (textDisabled);
  705. const auto w = juce::jmin (text.getWidth() / 2, juce::GlyphArrangement::getStringWidthInt (g.getCurrentFont(), where) + 4);
  706. g.drawText (where, text.removeFromRight (w), juce::Justification::centredRight, true);
  707. }
  708. const auto name = n.label.isNotEmpty() ? n.label
  709. : n.folder || ! isAudio (n.file) ? n.file.getFileName()
  710. : n.file.getFileNameWithoutExtension();
  711. const auto bold = (n.folder && n.expanded) || n.current || n.kind == Kind::project;
  712. const juce::Font font (theme::font (theme::type::body, bold));
  713. g.setFont (font);
  714. auto nameColour = playing ? accentHover : n.folder || i == hovered || i == selected ? textPrimary : textPrimary.withAlpha (0.86f);
  715. if (n.kind == Kind::item && hasColour && n.item.kind == projectcontents::Kind::pattern)
  716. nameColour = readable (n.colour); // FL writes the patterns in their colours
  717. if (n.missing)
  718. nameColour = meterClip.withAlpha (0.9f);
  719. if (n.kind == Kind::item && n.history && ! n.current && n.item.index > browser.engine.getHistoryPosition())
  720. nameColour = textDisabled; // undone steps (redo)
  721. g.setColour (nameColour);
  722. const auto nameWidth = juce::GlyphArrangement::getStringWidthInt (font, name);
  723. g.drawText (name, text, juce::Justification::centredLeft, true);
  724. // the detail after the name, dimmed: "(insert)", "3x", "missing", a section's count
  725. if (n.detail.isNotEmpty() && nameWidth + 12 < text.getWidth())
  726. {
  727. g.setFont (theme::font (theme::type::small));
  728. g.setColour (n.missing ? meterClip.withAlpha (0.7f) : textDisabled);
  729. const auto shown = n.kind == Kind::category || n.kind == Kind::project ? n.detail : "(" + n.detail + ")";
  730. if (n.kind == Kind::category) // the count on the right
  731. g.drawText (shown, text, juce::Justification::centredRight, true);
  732. else
  733. g.drawText (shown, text.withTrimmedLeft (nameWidth + 6), juce::Justification::centredLeft, true);
  734. }
  735. }
  736. if (rows.empty() && status.isNotEmpty())
  737. {
  738. g.setColour (textDisabled);
  739. g.setFont (theme::font (theme::type::small));
  740. g.drawFittedText (status, getLocalBounds().reduced (10).withHeight (60), juce::Justification::centredTop, 3);
  741. }
  742. }
  743. int rowAt (int y) const
  744. {
  745. const auto row = y / rowHeight;
  746. return y >= 0 && row < (int) rows.size() ? row : -1;
  747. }
  748. void mouseMove (const juce::MouseEvent& e) override { setHovered (rowAt (e.y)); }
  749. void mouseExit (const juce::MouseEvent&) override { setHovered (-1); }
  750. void mouseDown (const juce::MouseEvent& e) override
  751. {
  752. dragStarted = false;
  753. const auto row = rowAt (e.y);
  754. pressedRow = row;
  755. if (row < 0)
  756. return;
  757. auto& n = *rows[(std::size_t) row];
  758. if (e.mods.isPopupMenu())
  759. {
  760. select (row, false);
  761. showMenu (n);
  762. return;
  763. }
  764. if (n.folder)
  765. {
  766. select (row, false);
  767. if (e.getNumberOfClicks() == 1) // a click opens / closes it (the second click of a double click does not undo it)
  768. toggle (n);
  769. return;
  770. }
  771. if (n.kind == Kind::item)
  772. {
  773. select (row, n.item.kind == projectcontents::Kind::sample && ! n.missing);
  774. itemClicked (n);
  775. return;
  776. }
  777. if (n.kind == Kind::plugin)
  778. {
  779. select (row, false);
  780. return;
  781. }
  782. // a click previews, even when the file is already selected (click again: hear it again)
  783. select (row, true);
  784. }
  785. void mouseDrag (const juce::MouseEvent& e) override
  786. {
  787. if (dragStarted || e.getDistanceFromDragStart() < 5 || ! juce::isPositiveAndBelow (pressedRow, (int) rows.size()))
  788. return;
  789. const auto& n = *rows[(std::size_t) pressedRow];
  790. auto* container = juce::DragAndDropContainer::findParentDragContainerFor (this);
  791. if (n.folder || container == nullptr)
  792. return;
  793. if (n.kind == Kind::plugin && (n.generator || n.effect)) // a plugin onto the Channel Rack / the Mixer (round 162)
  794. {
  795. dragStarted = true;
  796. draggedPlugin() = { n.generator, n.effect };
  797. container->startDragging (juce::String (n.generator ? generatorDragDescription : effectDragDescription) + "|" + n.label, this,
  798. juce::ScaledImage (dragImage (n)), true);
  799. return;
  800. }
  801. if (n.kind == Kind::item && n.item.kind == projectcontents::Kind::pattern) // a pattern onto the Playlist
  802. {
  803. dragStarted = true;
  804. container->startDragging (juce::String (patternDragDescription) + "|" + juce::String (n.item.index), this,
  805. juce::ScaledImage (dragImage (n)), true);
  806. return;
  807. }
  808. if (n.file.existsAsFile())
  809. {
  810. dragStarted = true;
  811. container->startDragging (juce::String (dragDescription) + "|" + n.file.getFullPathName(), this, juce::ScaledImage (dragImage (n)),
  812. true);
  813. }
  814. }
  815. void mouseDoubleClick (const juce::MouseEvent& e) override
  816. {
  817. const auto row = rowAt (e.y);
  818. if (row < 0 || rows[(std::size_t) row]->folder || ! e.mods.isLeftButtonDown())
  819. return;
  820. const auto& n = *rows[(std::size_t) row];
  821. if (n.kind == Kind::plugin)
  822. {
  823. if (n.activate)
  824. n.activate();
  825. return;
  826. }
  827. if (n.kind != Kind::item)
  828. {
  829. browser.openFile (n.file);
  830. return;
  831. }
  832. const auto& item = n.item;
  833. switch (item.kind)
  834. {
  835. case projectcontents::Kind::pattern:
  836. if (browser.onOpenPattern)
  837. browser.onOpenPattern (item.index);
  838. break;
  839. case projectcontents::Kind::sample:
  840. if (! n.missing)
  841. browser.openFile (n.file);
  842. break;
  843. case projectcontents::Kind::generator:
  844. if (browser.onOpenChannel)
  845. browser.onOpenChannel (item.index);
  846. break;
  847. case projectcontents::Kind::effect:
  848. if (browser.onOpenEffect)
  849. browser.onOpenEffect (item.index, item.slot);
  850. break;
  851. case projectcontents::Kind::automation:
  852. if (! n.history && ! n.initial && browser.onOpenAutomation)
  853. browser.onOpenAutomation (item.index);
  854. break;
  855. }
  856. }
  857. ui::Hint hintAt (juce::Point<int> p) override
  858. {
  859. ui::Hint h;
  860. const auto row = rowAt (p.y);
  861. if (row < 0)
  862. {
  863. 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");
  864. return h;
  865. }
  866. const auto& n = *rows[(std::size_t) row];
  867. h.hasMenu = true;
  868. switch (n.kind)
  869. {
  870. case Kind::project:
  871. h.text = tr ("Current project: what this project uses (patterns, effects, generators, automation, audio files) [LMB] open [RMB] expand / collapse all");
  872. return h;
  873. case Kind::category:
  874. h.text = categoryHint (n.category) + " " + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open"));
  875. h.value = n.detail;
  876. return h;
  877. case Kind::fsFolder:
  878. if (n.depth == 0 || (n.parent != nullptr && n.parent->kind == Kind::project))
  879. {
  880. h.text = n.label + ": " + n.file.getFullPathName() + " " + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open")) + " " + tr ("[RMB] menu");
  881. return h;
  882. }
  883. break;
  884. case Kind::item:
  885. return itemHint (n);
  886. case Kind::plugins:
  887. h.text = tr ("Plugin database: LYNX's built-in generators and effects, FL's engines and the installed plugins") + " "
  888. + (n.expanded ? tr ("[LMB] close") : tr ("[LMB] open"));
  889. h.value = n.detail;
  890. return h;
  891. case Kind::plugin:
  892. h.text = n.label + " (" + n.detail + ") "
  893. + (n.generator ? tr ("[double-click] add it as a new channel, or drag it onto the Channel Rack")
  894. : tr ("[double-click] add it to the selected insert, or drag it onto a mixer insert or an effect slot"));
  895. h.hasMenu = true;
  896. return h;
  897. case Kind::file:
  898. break;
  899. }
  900. h.text = rowHint (n.file, n.folder, n.expanded);
  901. h.value = n.folder ? juce::String() : n.file.getFileExtension().substring (1).toUpperCase();
  902. return h;
  903. }
  904. // for snapshots: the first audio file under the first folders on disk (opening them)
  905. int firstAudioRow()
  906. {
  907. for (int pass = 0; pass < 3; ++pass)
  908. {
  909. for (int i = 0; i < (int) rows.size(); ++i)
  910. if (rows[(std::size_t) i]->kind == Kind::file && isAudio (rows[(std::size_t) i]->file))
  911. return i;
  912. for (auto* n : rows)
  913. if (n->kind == Kind::fsFolder && ! n->expanded)
  914. {
  915. toggle (*n);
  916. break;
  917. }
  918. }
  919. return -1;
  920. }
  921. // for snapshots: opens these project sections; returns the first row of a sample item
  922. int openProjectSections (std::initializer_list<Category> open)
  923. {
  924. for (auto* n : std::vector<Node*> (rows))
  925. if (n->kind == Kind::category && std::find (open.begin(), open.end(), n->category) != open.end() && ! n->expanded)
  926. {
  927. n->expanded = true;
  928. load (*n);
  929. }
  930. rebuild();
  931. for (int i = 0; i < (int) rows.size(); ++i)
  932. if (rows[(std::size_t) i]->kind == Kind::item && rows[(std::size_t) i]->item.kind == projectcontents::Kind::sample)
  933. return i;
  934. return -1;
  935. }
  936. void setHovered (int row)
  937. {
  938. if (row != hovered)
  939. {
  940. repaintRow (hovered);
  941. hovered = row;
  942. repaintRow (hovered);
  943. }
  944. }
  945. // flat mode, PROJECT tab search: every project item whose name matches
  946. static std::vector<std::unique_ptr<Node>> projectMatches (const Song& song, const juce::String& query)
  947. {
  948. const auto parsed = search::parse (query.toStdString());
  949. std::vector<std::unique_ptr<Node>> found;
  950. for (auto c : categories)
  951. {
  952. if (c == Category::history)
  953. continue;
  954. Node section;
  955. section.kind = Kind::category;
  956. section.category = c;
  957. listCategory (section, song, {});
  958. for (auto& child : section.children)
  959. if (search::matches (parsed, child->label.toStdString()))
  960. {
  961. child->parent = nullptr;
  962. found.push_back (std::move (child));
  963. }
  964. }
  965. return found;
  966. }
  967. private:
  968. juce::File baseOf (const juce::File& f) const
  969. {
  970. for (const auto& b : bases)
  971. if (f.isAChildOf (b))
  972. return b;
  973. return f.getParentDirectory();
  974. }
  975. void load (Node& n)
  976. {
  977. if (n.loaded)
  978. return;
  979. n.loaded = true;
  980. if (n.kind == Kind::project)
  981. {
  982. for (auto c : categories)
  983. {
  984. auto child = std::make_unique<Node>();
  985. child->kind = Kind::category;
  986. child->folder = true;
  987. child->category = c;
  988. child->label = categoryName (c);
  989. child->icon = categoryIcon (c);
  990. child->depth = n.depth + 1;
  991. child->parent = &n;
  992. listCategory (*child, browser.engine.getSong(), &browser.engine, true); // the counts show while closed
  993. child->children.clear();
  994. n.children.push_back (std::move (child));
  995. if (c == Category::initialized && browser.projectFile.existsAsFile()) // then the project's folder (FL's "Project data")
  996. {
  997. auto folder = makeFolder (browser.projectFile.getParentDirectory(), tr ("Project folder"), juce::Colour());
  998. folder->icon = Icon::folder;
  999. folder->depth = n.depth + 1;
  1000. folder->parent = &n;
  1001. n.children.push_back (std::move (folder));
  1002. }
  1003. }
  1004. return;
  1005. }
  1006. if (n.kind == Kind::category)
  1007. {
  1008. loadCategory (n);
  1009. return;
  1010. }
  1011. auto folders = n.file.findChildFiles (juce::File::findDirectories, false, "*", juce::File::FollowSymlinks::noCycles);
  1012. auto files = n.file.findChildFiles (juce::File::findFiles, false, "*", juce::File::FollowSymlinks::noCycles);
  1013. auto byName = [] (const juce::File& a, const juce::File& b) { return a.getFileName().compareNatural (b.getFileName()) < 0; };
  1014. std::sort (folders.begin(), folders.end(), byName);
  1015. std::sort (files.begin(), files.end(), byName);
  1016. for (const auto& f : folders)
  1017. {
  1018. if (f.isHidden() || f.getFileName().startsWithChar ('.'))
  1019. continue;
  1020. auto c = std::make_unique<Node>();
  1021. c->kind = Kind::fsFolder;
  1022. c->file = f;
  1023. c->folder = true;
  1024. c->depth = n.depth + 1;
  1025. c->parent = &n;
  1026. n.children.push_back (std::move (c));
  1027. }
  1028. for (const auto& f : files)
  1029. if (browser.lists (f))
  1030. {
  1031. auto c = std::make_unique<Node>();
  1032. c->file = f;
  1033. c->depth = n.depth + 1;
  1034. c->parent = &n;
  1035. n.children.push_back (std::move (c));
  1036. }
  1037. }
  1038. void loadCategory (Node& n)
  1039. {
  1040. n.loaded = true;
  1041. n.children.clear();
  1042. listCategory (n, browser.engine.getSong(), &browser.engine);
  1043. }
  1044. // The items of one project section (history needs the engine; the PROJECT search passes none).
  1045. static void listCategory (Node& n, const Song& song, AudioEngine* engine, bool countOnly = false)
  1046. {
  1047. auto add = [&n] (projectcontents::Item item, Icon icon, juce::Colour colour) -> Node& {
  1048. auto c = std::make_unique<Node>();
  1049. c->kind = Kind::item;
  1050. c->label = juce::String::fromUTF8 (item.name.c_str());
  1051. c->detail = juce::String::fromUTF8 (item.detail.c_str());
  1052. c->colour = colour;
  1053. c->icon = icon;
  1054. c->depth = n.depth + 1;
  1055. c->parent = &n;
  1056. c->item = std::move (item);
  1057. n.children.push_back (std::move (c));
  1058. return *n.children.back();
  1059. };
  1060. switch (n.category)
  1061. {
  1062. case Category::history:
  1063. if (engine != nullptr)
  1064. {
  1065. // each label compares two whole states: only listed while the section is open, the last 30
  1066. const auto size = engine->getHistorySize(), at = engine->getHistoryPosition();
  1067. for (int i = size - 1; ! countOnly && i >= juce::jmax (0, size - 30); --i) // newest first, as FL lists it
  1068. {
  1069. const auto l = engine->getHistoryLabel (i);
  1070. projectcontents::Item item;
  1071. item.kind = projectcontents::Kind::automation; // (unused for history rows)
  1072. item.index = i;
  1073. item.name = tr (l.text, { juce::String::fromUTF8 (l.arg.c_str()) }).toStdString();
  1074. auto& node = add (std::move (item), Icon::undo, juce::Colour());
  1075. node.history = true;
  1076. node.current = i == at;
  1077. }
  1078. n.detail = juce::String (size);
  1079. }
  1080. break;
  1081. case Category::patterns:
  1082. for (auto& item : projectcontents::patterns (song))
  1083. {
  1084. const auto colour = PlaylistComponent::patternColour (song, item.index);
  1085. const auto current = item.index == song.currentPattern;
  1086. if (item.uses == 0)
  1087. item.detail = tr ("not in the Playlist").toStdString();
  1088. add (std::move (item), Icon::pattern, colour).current = current;
  1089. }
  1090. break;
  1091. case Category::effects:
  1092. for (auto& item : projectcontents::effects (song))
  1093. add (item, item.plugin ? Icon::plugin : Icon::mixer, item.colour != 0 ? juce::Colour (item.colour) : juce::Colour());
  1094. break;
  1095. case Category::generators:
  1096. for (auto& item : projectcontents::generators (song))
  1097. {
  1098. const auto& channel = song.channels[(std::size_t) item.index];
  1099. const auto icon = item.plugin ? Icon::plugin
  1100. : projectcontents::playsSampleFile (channel.instrument) ? Icon::audioFile
  1101. : Icon::keyboard;
  1102. const auto colour = channel.instrument == InstrumentKind::audioClip ? PlaylistComponent::audioClipColour (channel)
  1103. : item.colour != 0 ? juce::Colour (item.colour)
  1104. : juce::Colour();
  1105. const auto selected = engine != nullptr && engine->getSelectedChannel() == item.index;
  1106. add (std::move (item), icon, colour).current = selected;
  1107. }
  1108. break;
  1109. case Category::automation:
  1110. for (auto& item : projectcontents::automations (song))
  1111. add (item, Icon::automate, item.colour != 0 ? juce::Colour (item.colour) : theme::colour::automation);
  1112. break;
  1113. case Category::initialized:
  1114. for (int i = 0; i < (int) song.initialValues.size(); ++i)
  1115. {
  1116. const auto& v = song.initialValues[(std::size_t) i];
  1117. projectcontents::Item item;
  1118. item.kind = projectcontents::Kind::automation;
  1119. item.index = i;
  1120. item.name = (engine != nullptr ? describeAutomationTarget (*engine, v.target) : juce::String ("?")).toStdString();
  1121. item.detail = std::to_string ((int) std::lround (v.value * 100.0f)) + "%";
  1122. add (std::move (item), Icon::automate, theme::colour::automation).initial = true;
  1123. }
  1124. break;
  1125. case Category::samples:
  1126. for (auto& item : projectcontents::samples (song))
  1127. {
  1128. const juce::String path = juce::String::fromUTF8 (item.path.c_str());
  1129. const juce::File file (juce::File::isAbsolutePath (path) ? path : juce::String());
  1130. auto colour = item.colour != 0 ? juce::Colour (item.colour) : theme::colour::audioClip;
  1131. if (item.index >= 0 && song.channels[(std::size_t) item.index].instrument == InstrumentKind::audioClip)
  1132. colour = PlaylistComponent::audioClipColour (song.channels[(std::size_t) item.index]);
  1133. auto& node = add (std::move (item), Icon::audioFile, colour);
  1134. node.file = file;
  1135. node.missing = ! countOnly && ! file.existsAsFile();
  1136. if (node.missing)
  1137. node.detail = tr ("missing");
  1138. }
  1139. break;
  1140. }
  1141. if (n.category != Category::history)
  1142. n.detail = juce::String ((int) n.children.size());
  1143. }
  1144. static juce::String signature (const Node& n)
  1145. {
  1146. juce::String s;
  1147. for (const auto& c : n.children)
  1148. s << c->label << '|' << c->detail << '|' << (int) c->colour.getARGB() << '|' << (int) c->missing << '|' << c->item.index << '|'
  1149. << c->item.slot << '\n';
  1150. return s;
  1151. }
  1152. juce::String selectionKey() const
  1153. {
  1154. if (! juce::isPositiveAndBelow (selected, (int) rows.size()))
  1155. return {};
  1156. const auto& n = *rows[(std::size_t) selected];
  1157. if (n.kind != Kind::item)
  1158. return "f:" + n.file.getFullPathName() + n.label;
  1159. return "i:" + juce::String ((int) n.item.kind) + ":" + juce::String (n.item.index) + ":" + juce::String (n.item.slot) + ":"
  1160. + juce::String::fromUTF8 (n.item.path.c_str()) + (n.history ? "h" : "");
  1161. }
  1162. void restoreSelection (const juce::String& key)
  1163. {
  1164. if (key.isEmpty())
  1165. return;
  1166. const auto keep = selected;
  1167. selected = -1;
  1168. for (int i = 0; i < (int) rows.size(); ++i)
  1169. {
  1170. selected = i;
  1171. if (selectionKey() == key)
  1172. return;
  1173. }
  1174. selected = -1;
  1175. juce::ignoreUnused (keep);
  1176. }
  1177. void itemClicked (Node& n)
  1178. {
  1179. auto& engine = browser.engine;
  1180. const auto& item = n.item;
  1181. if (n.history)
  1182. {
  1183. engine.jumpToHistory (item.index);
  1184. return;
  1185. }
  1186. if (n.initial)
  1187. return;
  1188. switch (item.kind)
  1189. {
  1190. case projectcontents::Kind::pattern: // FL: clicking a pattern makes it the current one
  1191. if (item.index != engine.getSong().currentPattern && item.index < (int) engine.getSong().patterns.size())
  1192. engine.editSong ([index = item.index] (Song& s) { s.currentPattern = index; }, false);
  1193. break;
  1194. case projectcontents::Kind::generator:
  1195. if (item.index < (int) engine.getSong().channels.size())
  1196. engine.setSelectedChannel (item.index);
  1197. break;
  1198. case projectcontents::Kind::sample:
  1199. case projectcontents::Kind::effect:
  1200. case projectcontents::Kind::automation:
  1201. break;
  1202. }
  1203. }
  1204. ui::Hint itemHint (const Node& n) const
  1205. {
  1206. ui::Hint h;
  1207. h.hasMenu = true;
  1208. const auto& item = n.item;
  1209. if (n.initial)
  1210. {
  1211. h.text = n.label + ": " + tr ("reset to this value when the song starts [RMB] delete the initial value");
  1212. h.value = n.detail;
  1213. return h;
  1214. }
  1215. if (n.history)
  1216. {
  1217. h.text = tr ("Undo history: [LMB] go back to this step");
  1218. h.value = tr ("Level {0}/{1}", { juce::String (item.index + 1), juce::String (browser.engine.getHistorySize()) });
  1219. return h;
  1220. }
  1221. switch (item.kind)
  1222. {
  1223. case projectcontents::Kind::pattern:
  1224. h.text = n.label + ": " + tr ("[LMB] make it the current pattern [2xLMB] open in the Piano Roll drag into the Playlist [RMB] pattern menu");
  1225. h.value = item.uses == 0 ? tr ("not in the Playlist") : tr ("{0} clips", { juce::String (item.uses) });
  1226. break;
  1227. case projectcontents::Kind::sample:
  1228. h.text = juce::String::fromUTF8 (item.path.c_str()) + " "
  1229. + (n.missing ? tr ("(missing: File > Missing files... finds it)")
  1230. : tr ("[LMB] preview [2xLMB] new channel drag to the Playlist or the Channel Rack [RMB] menu"));
  1231. h.value = tr ("used {0}x", { juce::String (item.uses) });
  1232. break;
  1233. case projectcontents::Kind::generator:
  1234. h.text = n.label + (n.detail.isNotEmpty() ? " (" + n.detail + ")" : juce::String()) + ": "
  1235. + tr ("[LMB] select the channel [2xLMB] open its settings [RMB] menu");
  1236. break;
  1237. case projectcontents::Kind::effect:
  1238. h.text = n.label + " (" + n.detail + "): " + tr ("[2xLMB] open its editor [RMB] menu");
  1239. h.value = tr ("slot {0}", { juce::String (item.slot + 1) });
  1240. break;
  1241. case projectcontents::Kind::automation:
  1242. h.text = n.label + ": " + tr ("[2xLMB] open the automation editor");
  1243. h.value = item.uses == 0 ? tr ("not in the Playlist") : tr ("{0} clips", { juce::String (item.uses) });
  1244. break;
  1245. }
  1246. return h;
  1247. }
  1248. void showMenu (Node& n)
  1249. {
  1250. auto& engine = browser.engine;
  1251. juce::PopupMenu menu;
  1252. auto safe = juce::Component::SafePointer<FileTree> (this);
  1253. auto expandItems = [&menu, safe, &n] {
  1254. Node* target = &n;
  1255. while (target != nullptr && target->kind == Kind::item)
  1256. target = target->parent;
  1257. menu.addItem (tr ("Expand all"), [safe, target] {
  1258. if (safe != nullptr && target != nullptr)
  1259. safe->expandAll (*target);
  1260. });
  1261. menu.addItem (tr ("Collapse all"), [safe] {
  1262. if (safe != nullptr)
  1263. safe->collapseAll();
  1264. });
  1265. };
  1266. if (n.kind == Kind::plugin)
  1267. {
  1268. menu.addSectionHeader (n.label);
  1269. menu.addItem (tr ("Add"), [act = n.activate] {
  1270. if (act)
  1271. act();
  1272. });
  1273. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  1274. return;
  1275. }
  1276. if (n.kind == Kind::project || n.kind == Kind::category || n.kind == Kind::plugins)
  1277. {
  1278. menu.addSectionHeader (n.label);
  1279. expandItems();
  1280. if ((n.kind == Kind::project || n.kind == Kind::plugins) && n.parent == nullptr && browser.tab == allTab) // round 163
  1281. {
  1282. menu.addSeparator();
  1283. browser.addHideItem (menu, n.kind == Kind::project ? browserview::projectRootId : browserview::pluginsRootId, n.label);
  1284. }
  1285. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  1286. return;
  1287. }
  1288. if (n.kind != Kind::item)
  1289. {
  1290. if (n.folder)
  1291. browser.showFolderMenu (n.file, [safe, node = &n] {
  1292. if (safe != nullptr)
  1293. safe->expandFolder (*node, 3);
  1294. });
  1295. else
  1296. browser.showFileMenu (n.file);
  1297. return;
  1298. }
  1299. const auto item = n.item;
  1300. if (n.history)
  1301. return;
  1302. if (n.initial)
  1303. {
  1304. const auto& values = engine.getSong().initialValues;
  1305. if (! juce::isPositiveAndBelow (item.index, (int) values.size()))
  1306. return;
  1307. menu.addSectionHeader (n.label + ": " + n.detail);
  1308. menu.addItem (tr ("Delete initial value"), [&engine, target = values[(std::size_t) item.index].target] {
  1309. engine.editSong ([target] (Song& s) { s.removeInitialValue (target); });
  1310. });
  1311. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  1312. return;
  1313. }
  1314. switch (item.kind)
  1315. {
  1316. case projectcontents::Kind::pattern: // FL: the right-click makes it the current pattern, then its menu
  1317. itemClicked (n);
  1318. if (browser.onPatternMenu)
  1319. browser.onPatternMenu (item.index);
  1320. return;
  1321. case projectcontents::Kind::sample:
  1322. {
  1323. const auto file = n.file;
  1324. const auto ok = ! n.missing;
  1325. ui::addItemHeader (menu, tr ("Audio file"), n.label, n.colour);
  1326. menu.addItem (tr ("Send to the selected channel"), ok && browser.onLoadIntoChannel != nullptr, false, [safe, file] {
  1327. if (safe != nullptr && safe->browser.onLoadIntoChannel)
  1328. safe->browser.onLoadIntoChannel (file);
  1329. });
  1330. menu.addItem (tr ("Open in a new channel"), ok, false, [safe, file] {
  1331. if (safe != nullptr)
  1332. safe->browser.openFile (file);
  1333. });
  1334. menu.addItem (tr ("Send to the Playlist as an audio clip"), ok && browser.onSendToPlaylist != nullptr, false, [safe, file] {
  1335. if (safe != nullptr && safe->browser.onSendToPlaylist)
  1336. safe->browser.onSendToPlaylist (file);
  1337. });
  1338. menu.addSeparator();
  1339. menu.addItem (tr ("Edit in the audio editor..."), ok, false, [&engine, file] { openAudioEditor (engine, file); });
  1340. if (item.index >= 0)
  1341. menu.addItem (tr ("Show its channel"), [safe, channel = item.index] {
  1342. if (safe != nullptr && channel < (int) safe->browser.engine.getSong().channels.size())
  1343. safe->browser.engine.setSelectedChannel (channel);
  1344. });
  1345. menu.addSeparator();
  1346. menu.addItem (tr ("Show in the file manager"), ok, false, [file] { file.revealToUser(); });
  1347. break;
  1348. }
  1349. case projectcontents::Kind::generator:
  1350. ui::addItemHeader (menu, tr ("Generator"), n.label, n.colour);
  1351. menu.addItem (tr ("Open settings"), [safe, channel = item.index] {
  1352. if (safe != nullptr && safe->browser.onOpenChannel)
  1353. safe->browser.onOpenChannel (channel);
  1354. });
  1355. if (engine.getSong().channels[(std::size_t) item.index].mixerTrack > 0)
  1356. menu.addItem (tr ("Show its mixer insert"), [safe, track = engine.getSong().channels[(std::size_t) item.index].mixerTrack] {
  1357. if (safe != nullptr && safe->browser.onShowInsert)
  1358. safe->browser.onShowInsert (track);
  1359. });
  1360. break;
  1361. case projectcontents::Kind::effect:
  1362. ui::addItemHeader (menu, tr ("Effect") + " - " + n.detail, n.label, n.colour);
  1363. menu.addItem (tr ("View editor"), [safe, track = item.index, slot = item.slot] {
  1364. if (safe != nullptr && safe->browser.onOpenEffect)
  1365. safe->browser.onOpenEffect (track, slot);
  1366. });
  1367. menu.addItem (tr ("Show its mixer insert"), [safe, track = item.index] {
  1368. if (safe != nullptr && safe->browser.onShowInsert)
  1369. safe->browser.onShowInsert (track);
  1370. });
  1371. break;
  1372. case projectcontents::Kind::automation:
  1373. ui::addItemHeader (menu, tr ("Automation clip"), n.label, n.colour);
  1374. menu.addItem (tr ("Open the automation editor"), [safe, index = item.index] {
  1375. if (safe != nullptr && safe->browser.onOpenAutomation)
  1376. safe->browser.onOpenAutomation (index);
  1377. });
  1378. break;
  1379. }
  1380. menu.addSeparator();
  1381. expandItems();
  1382. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  1383. }
  1384. void addRows (Node& n)
  1385. {
  1386. for (auto& c : n.children)
  1387. {
  1388. rows.push_back (c.get());
  1389. if (c->folder && c->expanded)
  1390. addRows (*c);
  1391. }
  1392. }
  1393. void toggle (Node& n)
  1394. {
  1395. const auto keep = selectionKey();
  1396. n.expanded = ! n.expanded;
  1397. if (n.kind == Kind::plugins) // (remembered: the database is built again with the tree)
  1398. {
  1399. const auto key = (n.parent != nullptr && n.parent->kind == Kind::plugins ? n.parent->label + "/" : juce::String()) + n.label;
  1400. if (n.expanded)
  1401. browser.openPluginFolders.insert (key);
  1402. else
  1403. browser.openPluginFolders.erase (key);
  1404. }
  1405. if (n.expanded)
  1406. load (n);
  1407. rebuild();
  1408. restoreSelection (keep);
  1409. if (n.expanded) // show what opened
  1410. for (int i = 0; i < (int) rows.size(); ++i)
  1411. if (rows[(std::size_t) i] == &n)
  1412. scrollToRow (juce::jmin ((int) rows.size() - 1, i + juce::jmin ((int) n.children.size(), 6)));
  1413. }
  1414. void scrollToRow (int row)
  1415. {
  1416. if (row < 0)
  1417. return;
  1418. if (auto* view = findParentComponentOfClass<juce::Viewport>())
  1419. {
  1420. const auto top = row * rowHeight, bottom = top + rowHeight;
  1421. const auto y = view->getViewPositionY(), h = view->getViewHeight();
  1422. if (top < y)
  1423. view->setViewPosition (0, top);
  1424. else if (bottom > y + h)
  1425. view->setViewPosition (0, bottom - h);
  1426. }
  1427. }
  1428. void repaintRow (int row)
  1429. {
  1430. if (row >= 0)
  1431. repaint (0, row * rowHeight, getWidth(), rowHeight);
  1432. }
  1433. juce::Image dragImage (const Node& n) const
  1434. {
  1435. const auto name = n.label.isNotEmpty() ? n.label : n.file.getFileNameWithoutExtension();
  1436. const auto font = juce::Font (theme::font (theme::type::body));
  1437. const auto width = juce::jlimit (80, 260, juce::GlyphArrangement::getStringWidthInt (font, name) + 36);
  1438. const auto colour = n.colour.isTransparent() ? theme::colour::accent : readable (n.colour);
  1439. juce::Image image (juce::Image::ARGB, width, 24, true);
  1440. juce::Graphics g (image);
  1441. g.setColour (theme::colour::bg4.withAlpha (0.92f));
  1442. g.fillRoundedRectangle (0.5f, 0.5f, (float) width - 1.0f, 23.0f, 5.0f);
  1443. g.setColour (colour);
  1444. g.drawRoundedRectangle (0.5f, 0.5f, (float) width - 1.0f, 23.0f, 5.0f, 1.0f);
  1445. icons::draw (g, n.icon != Icon::none ? n.icon : iconFor (n.file, false), { 6.0f, 4.0f, 16.0f, 16.0f }, colour);
  1446. g.setColour (theme::colour::textPrimary);
  1447. g.setFont (font);
  1448. g.drawText (name, 28, 0, width - 32, 24, juce::Justification::centredLeft, true);
  1449. return image;
  1450. }
  1451. BrowserComponent& browser;
  1452. const bool flat;
  1453. std::unique_ptr<Node> root;
  1454. std::vector<std::unique_ptr<Node>> flatNodes;
  1455. std::vector<Node*> rows;
  1456. juce::Array<juce::File> bases;
  1457. juce::String status, pendingKey;
  1458. int selected = -1, hovered = -1, pressedRow = -1;
  1459. bool dragStarted = false;
  1460. };
  1461. // --- the tabs: ALL / PROJECT ------------------------------------------------------------------------
  1462. class BrowserComponent::TabBar final : public juce::Component,
  1463. public ui::HintSource
  1464. {
  1465. public:
  1466. explicit TabBar (BrowserComponent& b) : browser (b) { setRepaintsOnMouseActivity (true); }
  1467. juce::Rectangle<int> tabBounds (int t) const
  1468. {
  1469. const auto w = getWidth() / tabCount;
  1470. return { t * w, 0, t == tabCount - 1 ? getWidth() - t * w : w, getHeight() };
  1471. }
  1472. static juce::String name (int t) { return t == allTab ? tr ("ALL") : t == projectTab ? tr ("PROJECT") : tr ("STARRED"); }
  1473. void paint (juce::Graphics& g) override
  1474. {
  1475. using namespace theme;
  1476. const auto mouse = isMouseOver() ? getMouseXYRelative() : juce::Point<int> (-1, -1);
  1477. for (int t = 0; t < tabCount; ++t)
  1478. {
  1479. const auto r = tabBounds (t);
  1480. const auto on = browser.tab == t;
  1481. if (on || r.contains (mouse))
  1482. {
  1483. g.setColour (on ? colour::bg4 : colour::bg3);
  1484. g.fillRoundedRectangle (r.reduced (2, 2).toFloat(), radius::md);
  1485. }
  1486. if (on)
  1487. {
  1488. g.setColour (colour::accent);
  1489. g.fillRoundedRectangle (r.reduced (10, 0).removeFromBottom (2).toFloat(), 1.0f);
  1490. }
  1491. g.setColour (on ? colour::textPrimary : colour::textSecondary);
  1492. g.setFont (font (type::caption, true));
  1493. g.drawText (name (t), r, juce::Justification::centred, false);
  1494. }
  1495. }
  1496. void mouseDown (const juce::MouseEvent& e) override
  1497. {
  1498. for (int t = 0; t < tabCount; ++t)
  1499. if (tabBounds (t).contains (e.getPosition()))
  1500. browser.setTab (t);
  1501. }
  1502. ui::Hint hintAt (juce::Point<int> p) override
  1503. {
  1504. ui::Hint h;
  1505. const auto t = juce::jlimit (0, tabCount - 1, p.x * tabCount / juce::jmax (1, getWidth()));
  1506. h.text = t == allTab ? tr ("Browser: ALL - the current project and every sample folder")
  1507. : t == projectTab ? tr ("Browser: PROJECT - only what the current project uses (patterns, effects, generators, audio files...)")
  1508. : tr ("Browser: STARRED - the files and folders you starred (right-click > Starred)");
  1509. return h;
  1510. }
  1511. private:
  1512. BrowserComponent& browser;
  1513. };
  1514. // --- the preview strip: waveform of the selected sample ----------------------------------------------
  1515. class BrowserComponent::PreviewStrip final : public juce::Component,
  1516. public ui::HintSource,
  1517. private juce::Timer,
  1518. private juce::ChangeListener
  1519. {
  1520. public:
  1521. explicit PreviewStrip (BrowserComponent& b) : browser (b) { ui::WaveformCache::getInstance()->addChangeListener (this); }
  1522. ~PreviewStrip() override
  1523. {
  1524. if (auto* cache = ui::WaveformCache::getInstanceWithoutCreating())
  1525. cache->removeChangeListener (this);
  1526. }
  1527. void changeListenerCallback (juce::ChangeBroadcaster*) override { repaint(); } // the spectral waveform is ready
  1528. void show (const juce::File& f, bool playing)
  1529. {
  1530. if (f != file)
  1531. {
  1532. file = f;
  1533. peaks.clear();
  1534. seconds = 0.0;
  1535. info.clear();
  1536. if (isAudio (f))
  1537. if (const auto sample = browser.engine.getSampleLibrary().load (f.getFullPathName()); sample != nullptr && sample->frames() > 0)
  1538. {
  1539. // 256 peaks over the whole file
  1540. const auto frames = sample->frames();
  1541. constexpr std::size_t count = 256;
  1542. peaks.assign (count, 0.0f);
  1543. const auto* l = sample->leftData();
  1544. const auto* r = sample->rightData();
  1545. const auto stride = juce::jmax<std::size_t> (1, frames / (count * 64)); // look at up to 64 points per peak
  1546. for (std::size_t i = 0; i < count; ++i)
  1547. {
  1548. const auto from = frames * i / count, to = juce::jmax (from + 1, frames * (i + 1) / count);
  1549. float m = 0.0f;
  1550. for (auto k = from; k < to && k < frames; k += stride)
  1551. m = juce::jmax (m, std::abs (l[k]), std::abs (r[k]));
  1552. peaks[i] = m;
  1553. }
  1554. const auto top = *std::max_element (peaks.begin(), peaks.end());
  1555. if (top > 1.0e-6f) // normalised: quiet files are still readable
  1556. for (auto& p : peaks)
  1557. p /= top;
  1558. seconds = (double) frames / juce::jmax (1.0, sample->sampleRate);
  1559. info = juce::String (seconds, seconds < 10.0 ? 2 : 1) + " s " + juce::String (juce::roundToInt (sample->sampleRate / 100.0) / 10.0, 1)
  1560. + " kHz " + (sample->isStereo() ? tr ("stereo") : tr ("mono"));
  1561. }
  1562. }
  1563. if (playing && seconds > 0.0)
  1564. {
  1565. startedAt = juce::Time::getMillisecondCounterHiRes();
  1566. startTimerHz (30);
  1567. }
  1568. repaint();
  1569. }
  1570. void paint (juce::Graphics& g) override
  1571. {
  1572. using namespace theme::colour;
  1573. g.fillAll (bg1);
  1574. g.setColour (border);
  1575. g.fillRect (0, 0, getWidth(), 1);
  1576. auto area = getLocalBounds().reduced (6, 4).withTrimmedTop (1);
  1577. if (file == juce::File() || ! isAudio (file))
  1578. {
  1579. g.setColour (textDisabled);
  1580. g.setFont (theme::font (theme::type::small));
  1581. g.drawFittedText (tr ("Click a sample to hear it; its waveform shows here"), area, juce::Justification::centred, 2);
  1582. return;
  1583. }
  1584. auto top = area.removeFromTop (14);
  1585. g.setFont (theme::font (theme::type::caption, true));
  1586. g.setColour (textPrimary);
  1587. g.drawText (file.getFileNameWithoutExtension(), top, juce::Justification::centredLeft, true);
  1588. g.setFont (theme::font (theme::type::caption));
  1589. g.setColour (textSecondary);
  1590. g.drawText (info, top, juce::Justification::centredRight, true);
  1591. area.removeFromTop (2);
  1592. g.setColour (bg0);
  1593. g.fillRoundedRectangle (area.toFloat(), theme::radius::sm);
  1594. if (peaks.empty())
  1595. return;
  1596. const auto wave = area.toFloat().reduced (2.0f, 2.0f);
  1597. const auto mid = wave.getCentreY();
  1598. const auto progress = position();
  1599. const auto playedX = wave.getX() + wave.getWidth() * (float) progress;
  1600. // the detailed, frequency-coloured waveform (ui/WaveformView) once analysed; the quick peaks until then
  1601. const auto path = file.getFullPathName();
  1602. if (const auto summary = ui::WaveformCache::getInstance()->find (path, [this, path] { return browser.engine.getSampleLibrary().load (path); }))
  1603. {
  1604. ui::paintWaveform (g, wave, *summary, 0.0, (double) summary->frames / juce::jmax (1.0f, wave.getWidth()),
  1605. ui::currentWaveStyle (textSecondary, ui::normalisingGain (*summary)));
  1606. if (progress > 0.0)
  1607. {
  1608. g.setColour (accent.withAlpha (0.22f)); // the part already heard
  1609. g.fillRect (juce::Rectangle<float>::leftTopRightBottom (wave.getX(), wave.getY(), playedX, wave.getBottom()));
  1610. g.setColour (textPrimary);
  1611. g.fillRect (playedX, wave.getY(), 1.0f, wave.getHeight());
  1612. }
  1613. return;
  1614. }
  1615. for (int x = 0; x < (int) wave.getWidth(); ++x)
  1616. {
  1617. const auto p = peaks[(std::size_t) (x * (int) peaks.size() / juce::jmax (1, (int) wave.getWidth()))];
  1618. const auto h = juce::jmax (0.5f, p * wave.getHeight() * 0.5f);
  1619. const auto px = wave.getX() + (float) x;
  1620. g.setColour (progress > 0.0 && px <= playedX ? accent : textSecondary.withAlpha (0.75f));
  1621. g.fillRect (px, mid - h, 1.0f, h * 2.0f);
  1622. }
  1623. if (progress > 0.0)
  1624. {
  1625. g.setColour (textPrimary);
  1626. g.fillRect (playedX, wave.getY(), 1.0f, wave.getHeight());
  1627. }
  1628. }
  1629. void mouseDown (const juce::MouseEvent& e) override
  1630. {
  1631. if (isAudio (file) && e.mods.isLeftButtonDown())
  1632. browser.fileSelected (file, true); // hear it again
  1633. }
  1634. void mouseDrag (const juce::MouseEvent& e) override
  1635. {
  1636. if (! dragging && isAudio (file) && e.getDistanceFromDragStart() > 5)
  1637. if (auto* container = juce::DragAndDropContainer::findParentDragContainerFor (this))
  1638. {
  1639. dragging = true;
  1640. container->startDragging (juce::String (dragDescription) + "|" + file.getFullPathName(), this, juce::ScaledImage(), true);
  1641. }
  1642. }
  1643. void mouseUp (const juce::MouseEvent&) override { dragging = false; }
  1644. ui::Hint hintAt (juce::Point<int>) override
  1645. {
  1646. ui::Hint h;
  1647. h.text = isAudio (file) ? tr ("Sample preview: [LMB] hear it again drag it like a file in the list") : tr ("Sample preview");
  1648. h.value = info;
  1649. return h;
  1650. }
  1651. bool isPlaying() const { return position() > 0.0 && position() < 1.0; }
  1652. void stop()
  1653. {
  1654. stopTimer();
  1655. startedAt = 0.0;
  1656. repaint();
  1657. }
  1658. private:
  1659. double position() const
  1660. {
  1661. if (startedAt <= 0.0 || seconds <= 0.0)
  1662. return 0.0;
  1663. return juce::jlimit (0.0, 1.0, (juce::Time::getMillisecondCounterHiRes() - startedAt) / 1000.0 / seconds);
  1664. }
  1665. void timerCallback() override
  1666. {
  1667. if (position() >= 1.0)
  1668. {
  1669. stop();
  1670. browser.tree->repaint(); // the "playing" colour goes
  1671. browser.results->repaint();
  1672. }
  1673. repaint();
  1674. }
  1675. BrowserComponent& browser;
  1676. juce::File file;
  1677. std::vector<float> peaks;
  1678. double seconds = 0.0, startedAt = 0.0;
  1679. juce::String info;
  1680. bool dragging = false;
  1681. };
  1682. // --- the browser -------------------------------------------------------------------------------------
  1683. bool BrowserComponent::isPreviewPlaying() const
  1684. {
  1685. return strip != nullptr && strip->isPlaying();
  1686. }
  1687. // FL's Browser details box (REA round 134/139): what is selected — a column of labels (Date, Size, Version for a
  1688. // project FL saved, Path) and their values, the path wrapping over the last lines. Hidden while nothing is selected.
  1689. class BrowserComponent::DetailsBox final : public juce::Component,
  1690. public ui::HintSource
  1691. {
  1692. public:
  1693. static constexpr int preferredHeight = 70;
  1694. void show (const juce::File& f)
  1695. {
  1696. file = f;
  1697. rows.clear();
  1698. if (file != juce::File())
  1699. {
  1700. rows.push_back ({ tr ("Date"), file.getLastModificationTime().formatted ("%Y-%m-%d %H:%M:%S") });
  1701. if (file.existsAsFile())
  1702. {
  1703. rows.push_back ({ tr ("Size"), juce::File::descriptionOfSizeInBytes (file.getSize()) });
  1704. if (file.hasFileExtension (".flp"))
  1705. {
  1706. juce::MemoryBlock head;
  1707. if (juce::FileInputStream in (file); in.openedOk())
  1708. in.readIntoMemoryBlock (head, 4096);
  1709. const auto version = flp::readSavedVersion ({ (const std::uint8_t*) head.getData(), head.getSize() });
  1710. if (! version.empty())
  1711. rows.push_back ({ tr ("Version"), juce::String (version) });
  1712. }
  1713. }
  1714. rows.push_back ({ tr ("Path"), file.getFullPathName() });
  1715. }
  1716. repaint();
  1717. }
  1718. bool hasFile() const noexcept { return file != juce::File(); }
  1719. ui::Hint hintAt (juce::Point<int>) override
  1720. {
  1721. ui::Hint h;
  1722. if (file != juce::File())
  1723. h.text = tr ("Selected: {0}", { file.getFullPathName() });
  1724. return h;
  1725. }
  1726. void paint (juce::Graphics& g) override
  1727. {
  1728. using namespace theme::colour;
  1729. g.fillAll (bg1);
  1730. g.setColour (border);
  1731. g.fillRect (0, 0, getWidth(), 1);
  1732. auto area = getLocalBounds().reduced (6, 3).withTrimmedTop (1);
  1733. g.setFont (theme::font (theme::type::caption));
  1734. constexpr int line = 13, labelWidth = 48;
  1735. for (std::size_t i = 0; i < rows.size() && area.getHeight() >= line; ++i)
  1736. {
  1737. const auto last = i + 1 == rows.size();
  1738. // the path (last row) takes the lines left and wraps, as FL's box does
  1739. auto r = last ? area : area.removeFromTop (line);
  1740. g.setColour (textDisabled);
  1741. g.drawText (rows[i].first, r.removeFromLeft (labelWidth).withHeight (line), juce::Justification::centredLeft, false);
  1742. g.setColour (textSecondary);
  1743. if (last)
  1744. g.drawFittedText (rows[i].second, r, juce::Justification::topLeft, juce::jmax (1, r.getHeight() / line), 1.0f);
  1745. else
  1746. g.drawText (rows[i].second, r, juce::Justification::centredLeft, true);
  1747. }
  1748. }
  1749. private:
  1750. juce::File file;
  1751. std::vector<std::pair<juce::String, juce::String>> rows;
  1752. };
  1753. BrowserComponent::BrowserComponent (AudioEngine& e, Role r)
  1754. : engine (e), role (r)
  1755. {
  1756. tabs = std::make_unique<TabBar> (*this);
  1757. addAndMakeVisible (*tabs);
  1758. // the search index (round 162): a background pass over every folder a few seconds after start (FL's automatic
  1759. // indexing: only the folders that changed since the last session are listed again)
  1760. searcher = SearchShared::get();
  1761. searcher->statusChanged.addChangeListener (this);
  1762. searcher->indexChanged.addChangeListener (this);
  1763. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<BrowserComponent> (this)] {
  1764. if (safe != nullptr && safe->role == Role::main && ! safe->allRoots.isEmpty())
  1765. safe->searcher->service->refresh (toPaths (safe->allRoots));
  1766. });
  1767. focusWatcher = std::make_unique<FocusWatcher> (*this);
  1768. searchBox.setTextToShowWhenEmpty (tr ("Search (Ctrl+F): kick -loop, snare OR clap, hat*.wav"), theme::colour::textDisabled);
  1769. searchBox.addListener (this);
  1770. searchBox.setEscapeAndReturnKeysConsumed (true);
  1771. ui::setHint (searchBox, tr ("Search the selected folder (or every folder) and below; in PROJECT, the project's items: words must all match; "
  1772. "OR, -word (not), \"exact phrase\", * and ? wildcards [Enter] to the results [Esc] clear"));
  1773. addAndMakeVisible (searchBox);
  1774. // FL's Browser has a way to silence the preview too: a Stop button beside the preview volume (issue #9)
  1775. stopButton.setFlat (true);
  1776. stopButton.setWantsKeyboardFocus (false);
  1777. stopButton.setMouseClickGrabsKeyboardFocus (false);
  1778. stopButton.setTooltip (tr ("Stop the sample preview"));
  1779. ui::setHint (stopButton, tr ("Stop the sample preview"), true);
  1780. stopButton.onClick = [this] { stopPreview(); };
  1781. addAndMakeVisible (stopButton);
  1782. // what this Browser shows (round 163): content filter, folders shown, the Sample browser window
  1783. viewButton.setFlat (true);
  1784. viewButton.setWantsKeyboardFocus (false);
  1785. viewButton.setMouseClickGrabsKeyboardFocus (false);
  1786. viewButton.setClickingTogglesState (false);
  1787. viewButton.onClick = [this] { showViewMenu(); };
  1788. addAndMakeVisible (viewButton);
  1789. // the sample preview volume (FL's Browser has one too): a small knob at the end of the search row
  1790. previewVolume.setRange (0.0, controls::maxUtilityVolume, 0.01);
  1791. previewVolume.setDoubleClickReturnValue (true, 1.0);
  1792. previewVolume.textFromValueFunction = [] (double v) { return ui::utilityVolumeText (v); };
  1793. previewVolume.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  1794. previewVolume.setValue (engine.getPreviewVolume(), juce::dontSendNotification);
  1795. previewVolume.setMouseClickGrabsKeyboardFocus (false);
  1796. previewVolume.setWantsKeyboardFocus (false);
  1797. previewVolume.onValueChange = [this] {
  1798. engine.setPreviewVolume (previewVolume.getValue());
  1799. refreshPreviewVolume();
  1800. if (onPreviewVolumeChanged != nullptr)
  1801. onPreviewVolumeChanged();
  1802. };
  1803. addAndMakeVisible (previewVolume);
  1804. refreshPreviewVolume();
  1805. tree = std::make_unique<FileTree> (*this, false);
  1806. results = std::make_unique<FileTree> (*this, true);
  1807. for (auto [view, list] : { std::pair { &treeView, tree.get() }, std::pair { &resultsView, results.get() } })
  1808. {
  1809. *view = std::make_unique<juce::Viewport>();
  1810. (*view)->setViewedComponent (list, false);
  1811. (*view)->setScrollBarsShown (true, false);
  1812. (*view)->setScrollBarThickness (10);
  1813. (*view)->setWantsKeyboardFocus (false);
  1814. }
  1815. addAndMakeVisible (*treeView);
  1816. addChildComponent (*resultsView);
  1817. strip = std::make_unique<PreviewStrip> (*this);
  1818. addAndMakeVisible (*strip);
  1819. details = std::make_unique<DetailsBox>();
  1820. addChildComponent (*details);
  1821. rebuildRoots();
  1822. engine.addChangeListener (this);
  1823. }
  1824. juce::File BrowserComponent::userFoldersFile()
  1825. {
  1826. return PluginHost::settingsFolder().getChildFile ("browser-folders.txt");
  1827. }
  1828. juce::File BrowserComponent::starredFile()
  1829. {
  1830. return PluginHost::settingsFolder().getChildFile ("browser-starred.txt");
  1831. }
  1832. void BrowserComponent::setStarred (const juce::File& file, bool on)
  1833. {
  1834. const auto path = file.getFullPathName();
  1835. if (on == starred.contains (path))
  1836. return;
  1837. if (on)
  1838. starred.add (path);
  1839. else
  1840. starred.removeString (path);
  1841. starredFile().getParentDirectory().createDirectory();
  1842. starredFile().replaceWithText (starred.joinIntoString ("\n") + "\n");
  1843. if (tab == starredTab)
  1844. rebuildTree();
  1845. }
  1846. // --- what this Browser shows (round 163) ------------------------------------------------------------
  1847. juce::File BrowserComponent::viewFile (Role r)
  1848. {
  1849. return PluginHost::settingsFolder().getChildFile (r == Role::samples ? "sample-browser-view.txt" : "browser-view.txt");
  1850. }
  1851. bool BrowserComponent::sampleBrowserWasOpen()
  1852. {
  1853. return browserview::View::fromText (viewFile (Role::samples).loadFileAsString().toStdString()).open;
  1854. }
  1855. juce::Rectangle<int> BrowserComponent::sampleBrowserBounds()
  1856. {
  1857. const auto v = browserview::View::fromText (viewFile (Role::samples).loadFileAsString().toStdString());
  1858. return { v.x, v.y, v.width, v.height };
  1859. }
  1860. void BrowserComponent::loadView()
  1861. {
  1862. viewLoaded = true;
  1863. const auto file = viewFile (role);
  1864. viewFromFile = file.existsAsFile();
  1865. if (viewFromFile)
  1866. {
  1867. view = browserview::View::fromText (file.loadFileAsString().toStdString());
  1868. return;
  1869. }
  1870. view = {};
  1871. if (role == Role::samples)
  1872. {
  1873. // the Sample browser starts with only the places samples live, listing samples and SoundFonts
  1874. view.filter = browserview::ContentFilter::samples;
  1875. view.setShown (browserview::projectRootId, false);
  1876. view.setShown (browserview::pluginsRootId, false);
  1877. for (int i = 0; i < allRoots.size(); ++i)
  1878. if (! browserview::sampleBrowserShowsByDefault (allRootKinds[(std::size_t) i]))
  1879. view.setShown (allRoots[i].getFullPathName().toStdString(), false);
  1880. }
  1881. }
  1882. void BrowserComponent::saveView() const
  1883. {
  1884. if (! viewLoaded)
  1885. return;
  1886. const auto file = viewFile (role);
  1887. auto v = view;
  1888. if (role == Role::samples) // the window's open state and bounds are the window's to write
  1889. {
  1890. const auto old = browserview::View::fromText (file.loadFileAsString().toStdString());
  1891. v.open = old.open;
  1892. v.x = old.x, v.y = old.y, v.width = old.width, v.height = old.height;
  1893. }
  1894. file.getParentDirectory().createDirectory();
  1895. file.replaceWithText (juce::String::fromUTF8 (v.toText().c_str()));
  1896. }
  1897. bool BrowserComponent::lists (const juce::File& file) const
  1898. {
  1899. return browserview::listed (file.getFileName().toStdString(), view.filter) || file.isDirectory();
  1900. }
  1901. void BrowserComponent::setContentFilter (browserview::ContentFilter filter)
  1902. {
  1903. if (filter == view.filter)
  1904. return;
  1905. view.filter = filter;
  1906. saveView();
  1907. refreshViewButton();
  1908. rebuildTree();
  1909. if (searchBox.getText().trim().isNotEmpty())
  1910. runSearch();
  1911. }
  1912. void BrowserComponent::setRootShown (const juce::String& id, bool shown)
  1913. {
  1914. if (view.shows (id.toStdString()) == shown)
  1915. return;
  1916. view.setShown (id.toStdString(), shown);
  1917. saveView();
  1918. rebuildRoots();
  1919. if (searchBox.getText().trim().isNotEmpty())
  1920. runSearch();
  1921. }
  1922. void BrowserComponent::showAllRoots()
  1923. {
  1924. view.hidden.clear();
  1925. saveView();
  1926. rebuildRoots();
  1927. }
  1928. juce::String BrowserComponent::rootId (const juce::File& folder) const
  1929. {
  1930. return allRoots.contains (folder) ? folder.getFullPathName() : juce::String();
  1931. }
  1932. void BrowserComponent::refreshViewButton()
  1933. {
  1934. const auto filtered = view.filter != browserview::ContentFilter::all;
  1935. int hidden = 0;
  1936. for (const auto& id : view.hidden)
  1937. hidden += id == browserview::projectRootId || id == browserview::pluginsRootId
  1938. || allRoots.contains (juce::File (juce::String::fromUTF8 (id.c_str())))
  1939. ? 1 : 0;
  1940. viewButton.setToggleState (filtered || hidden > 0, juce::dontSendNotification);
  1941. juce::String text = tr ("Browser options: what to list, which folders to show");
  1942. if (filtered)
  1943. text << " (" << tr (browserview::contentFilterLabel (view.filter)) << ")";
  1944. if (hidden > 0)
  1945. text << " (" << (hidden == 1 ? tr ("1 folder hidden") : tr ("{0} folders hidden", { juce::String (hidden) })) << ")";
  1946. viewButton.setTooltip (text);
  1947. ui::setHint (viewButton, text, true);
  1948. }
  1949. void BrowserComponent::addHideItem (juce::PopupMenu& menu, const juce::String& id, const juce::String& label)
  1950. {
  1951. menu.addItem (tr ("Hide \"{0}\" from this Browser", { label }), [safe = juce::Component::SafePointer<BrowserComponent> (this), id] {
  1952. if (safe != nullptr)
  1953. safe->setRootShown (id, false);
  1954. });
  1955. }
  1956. void BrowserComponent::addViewItems (juce::PopupMenu& menu)
  1957. {
  1958. juce::Component::SafePointer<BrowserComponent> safe (this);
  1959. // what is listed (folders are always listed)
  1960. juce::PopupMenu filters;
  1961. for (int i = 0; i < browserview::contentFilterCount; ++i)
  1962. {
  1963. const auto f = (browserview::ContentFilter) i;
  1964. filters.addItem (tr (browserview::contentFilterLabel (f)), true, view.filter == f, [safe, f] {
  1965. if (safe != nullptr)
  1966. safe->setContentFilter (f);
  1967. });
  1968. }
  1969. menu.addSubMenu (tr ("Show") + ": " + tr (browserview::contentFilterLabel (view.filter)), filters);
  1970. // which top-level entries are shown (a checklist; hidden ones come back from here)
  1971. juce::PopupMenu folders;
  1972. auto toggle = [safe] (const juce::String& id) {
  1973. if (safe != nullptr)
  1974. safe->setRootShown (id, ! safe->view.shows (id.toStdString()));
  1975. };
  1976. folders.addItem (tr ("Current project"), true, view.shows (browserview::projectRootId), [toggle] { toggle (browserview::projectRootId); });
  1977. folders.addItem (tr ("Plugin database"), true, view.shows (browserview::pluginsRootId), [toggle] { toggle (browserview::pluginsRootId); });
  1978. for (int i = 0; i < allRoots.size(); ++i)
  1979. {
  1980. const auto id = allRoots[i].getFullPathName();
  1981. juce::PopupMenu::Item item (allRootNames[i]);
  1982. item.setTicked (view.shows (id.toStdString())).setAction ([toggle, id] { toggle (id); });
  1983. item.shortcutKeyDescription = allRoots[i].getParentDirectory().getFileName();
  1984. folders.addItem (std::move (item));
  1985. }
  1986. folders.addSeparator();
  1987. folders.addItem (tr ("Show all folders"), ! view.hidden.empty(), false, [safe] {
  1988. if (safe != nullptr)
  1989. safe->showAllRoots();
  1990. });
  1991. folders.addItem (tr ("Add folder..."), [safe] {
  1992. if (safe != nullptr)
  1993. safe->addUserFolder();
  1994. });
  1995. menu.addSubMenu (tr ("Show folders"), folders);
  1996. }
  1997. void BrowserComponent::showViewMenu()
  1998. {
  1999. juce::PopupMenu menu;
  2000. addViewItems (menu);
  2001. juce::Component::SafePointer<BrowserComponent> safe (this);
  2002. menu.addSeparator();
  2003. menu.addItem (tr ("Refresh"), [safe] { if (safe != nullptr) safe->rebuildRoots(); });
  2004. menu.addItem (tr ("Refresh search index"), [safe] { if (safe != nullptr) safe->refreshSearchIndex (false); });
  2005. if (onToggleSampleBrowser != nullptr)
  2006. {
  2007. menu.addSeparator();
  2008. menu.addItem (role == Role::samples ? tr ("Close the Sample browser") : tr ("Sample browser (separate window)"),
  2009. [safe] { if (safe != nullptr && safe->onToggleSampleBrowser != nullptr) safe->onToggleSampleBrowser(); });
  2010. }
  2011. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&viewButton));
  2012. }
  2013. namespace
  2014. {
  2015. // The Sample browser window's content: a drag container (samples dragged out of this window reach the Channel Rack,
  2016. // the Playlist and the Mixer of the main window) holding the Browser; it keeps the window's bounds and whether the
  2017. // user closed it.
  2018. class SampleBrowserHost final : public juce::Component,
  2019. public juce::DragAndDropContainer
  2020. {
  2021. public:
  2022. SampleBrowserHost (AudioEngine& engine, const std::function<void (BrowserComponent&)>& wire)
  2023. : browser (engine, BrowserComponent::Role::samples)
  2024. {
  2025. if (wire != nullptr)
  2026. wire (browser);
  2027. addAndMakeVisible (browser);
  2028. setSize (340, 620);
  2029. }
  2030. ~SampleBrowserHost() override
  2031. {
  2032. // a window the user closed is hidden first (ToolWindow::closeSoon); one deleted while visible goes with LYNX
  2033. // and opens again at the next start
  2034. auto* window = getTopLevelComponent();
  2035. auto v = browser.getView();
  2036. v.open = window != this && window->isVisible();
  2037. if (window != this)
  2038. {
  2039. const auto b = window->getBounds();
  2040. v.x = b.getX();
  2041. v.y = b.getY();
  2042. v.width = b.getWidth();
  2043. v.height = b.getHeight();
  2044. }
  2045. file().getParentDirectory().createDirectory();
  2046. file().replaceWithText (juce::String::fromUTF8 (v.toText().c_str()));
  2047. }
  2048. void resized() override { browser.setBounds (getLocalBounds()); }
  2049. static juce::File file() { return PluginHost::settingsFolder().getChildFile ("sample-browser-view.txt"); }
  2050. BrowserComponent browser;
  2051. };
  2052. } // namespace
  2053. std::unique_ptr<juce::Component> BrowserComponent::makeSampleBrowserContent (AudioEngine& engine, const std::function<void (BrowserComponent&)>& wire)
  2054. {
  2055. auto host = std::make_unique<SampleBrowserHost> (engine, wire);
  2056. auto v = host->browser.getView();
  2057. v.open = true; // (written at once: a crash keeps it open next time too)
  2058. SampleBrowserHost::file().getParentDirectory().createDirectory();
  2059. SampleBrowserHost::file().replaceWithText (juce::String::fromUTF8 (v.toText().c_str()));
  2060. return host;
  2061. }
  2062. void BrowserComponent::rebuildRoots()
  2063. {
  2064. roots.clear();
  2065. rootNames.clear();
  2066. allRoots.clear();
  2067. allRootNames.clear();
  2068. allRootKinds.clear();
  2069. using browserview::RootKind;
  2070. // FL folders (if installed) and user folders
  2071. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  2072. juce::File fl;
  2073. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  2074. if (dir.getChildFile ("Data").isDirectory() && dir.getFileName() > fl.getFileName()) // "FL Studio ASIO" is the driver
  2075. fl = dir;
  2076. auto add = [this] (const juce::String& name, const juce::File& folder, RootKind kind) {
  2077. if (folder.isDirectory() && ! allRoots.contains (folder))
  2078. {
  2079. allRoots.add (folder);
  2080. allRootNames.add (name);
  2081. allRootKinds.push_back (kind);
  2082. }
  2083. };
  2084. const auto data = fl.getChildFile ("Data");
  2085. add (tr ("FL samples (Packs)"), data.getChildFile ("Patches").getChildFile ("Packs"), RootKind::flSamples);
  2086. add (tr ("FL demo projects"), data.getChildFile ("Demo projects"), RootKind::flDemos);
  2087. add (tr ("FL MIDI"), data.getChildFile ("Patches").getChildFile ("Scores"), RootKind::flMidi);
  2088. add (tr ("3x Osc presets (FL)"), data.getChildFile ("Patches").getChildFile ("Channel presets").getChildFile ("3x Osc"), RootKind::flPresets);
  2089. add (tr ("Synth presets (FL)"), data.getChildFile ("Patches").getChildFile ("Plugin presets").getChildFile ("Generators"), RootKind::flPresets);
  2090. pluginpresetui::presetsRoot().createDirectory(); // (the plugin window saves presets there; round 162d)
  2091. add (tr ("Plugin presets"), pluginpresetui::presetsRoot(), RootKind::pluginPresets);
  2092. add (tr ("Documents"), juce::File::getSpecialLocation (juce::File::userDocumentsDirectory), RootKind::documents);
  2093. add (tr ("Music"), juce::File::getSpecialLocation (juce::File::userMusicDirectory), RootKind::music);
  2094. add (tr ("Desktop"), juce::File::getSpecialLocation (juce::File::userDesktopDirectory), RootKind::desktop);
  2095. add (tr ("Downloads"), juce::File::getSpecialLocation (juce::File::userHomeDirectory).getChildFile ("Downloads"), RootKind::downloads);
  2096. for (const auto& line : juce::StringArray::fromLines (userFoldersFile().loadFileAsString()))
  2097. if (line.trim().isNotEmpty())
  2098. add (juce::File (line.trim()).getFileName(), juce::File (line.trim()), RootKind::user);
  2099. if (! viewLoaded)
  2100. loadView();
  2101. for (int i = 0; i < allRoots.size(); ++i)
  2102. if (view.shows (allRoots[i].getFullPathName().toStdString()))
  2103. {
  2104. roots.add (allRoots[i]);
  2105. rootNames.add (allRootNames[i]);
  2106. }
  2107. refreshViewButton();
  2108. starred.clear();
  2109. for (const auto& line : juce::StringArray::fromLines (starredFile().loadFileAsString()))
  2110. if (line.trim().isNotEmpty() && juce::File::isAbsolutePath (line.trim()))
  2111. starred.addIfNotAlreadyThere (line.trim());
  2112. rebuildTree();
  2113. }
  2114. void BrowserComponent::rebuildTree()
  2115. {
  2116. std::vector<std::unique_ptr<FileTree::Node>> top;
  2117. if (tab == starredTab)
  2118. {
  2119. // folders first (each opens like the ALL tab's), then files, both by name; missing ones are left out
  2120. juce::Array<juce::File> folders, files;
  2121. for (const auto& path : starred)
  2122. if (const juce::File f (path); f.isDirectory())
  2123. folders.add (f);
  2124. else if (f.existsAsFile())
  2125. files.add (f);
  2126. const auto byName = [] (const juce::File& a, const juce::File& b) { return a.getFileName().compareNatural (b.getFileName()) < 0; };
  2127. std::sort (folders.begin(), folders.end(), byName);
  2128. std::sort (files.begin(), files.end(), byName);
  2129. for (const auto& f : folders)
  2130. top.push_back (FileTree::makeFolder (f, f.getFileName(), theme::colour::accent));
  2131. for (const auto& f : files)
  2132. {
  2133. auto n = std::make_unique<FileTree::Node>();
  2134. n->file = f;
  2135. top.push_back (std::move (n));
  2136. }
  2137. tree->setTopLevel (std::move (top));
  2138. treeView->setViewPosition (0, 0);
  2139. return;
  2140. }
  2141. if (tab == projectTab || view.shows (browserview::projectRootId))
  2142. top.push_back (FileTree::makeProject (tab == projectTab));
  2143. if (tab == allTab && view.shows (browserview::pluginsRootId)) // FL's Plugin database, under the project (round 142)
  2144. top.push_back (FileTree::makePluginDatabase (*this, openPluginFolders));
  2145. if (tab == allTab)
  2146. for (int i = 0; i < allRoots.size(); ++i)
  2147. {
  2148. if (! roots.contains (allRoots[i]))
  2149. continue; // hidden from this Browser (round 163)
  2150. // the FL folders keep their colour by position; the user's own folders share one
  2151. auto colour = rootColour (i < 9 ? i : 99);
  2152. top.push_back (FileTree::makeFolder (allRoots[i], allRootNames[i], colour));
  2153. }
  2154. tree->setTopLevel (std::move (top));
  2155. treeView->setViewPosition (0, 0);
  2156. }
  2157. void BrowserComponent::setTab (int newTab)
  2158. {
  2159. newTab = juce::jlimit (0, tabCount - 1, newTab);
  2160. if (newTab == tab)
  2161. return;
  2162. tab = newTab;
  2163. rebuildTree();
  2164. tabs->repaint();
  2165. if (searchBox.getText().isNotEmpty())
  2166. runSearch();
  2167. }
  2168. void BrowserComponent::setProjectFile (const juce::File& file)
  2169. {
  2170. if (file == projectFile)
  2171. return;
  2172. projectFile = file;
  2173. rebuildTree(); // the "Project folder" entry follows the project
  2174. }
  2175. void BrowserComponent::changeListenerCallback (juce::ChangeBroadcaster* source)
  2176. {
  2177. if (source == &searcher->statusChanged)
  2178. {
  2179. indexStatusChanged();
  2180. return;
  2181. }
  2182. if (source == &searcher->indexChanged)
  2183. {
  2184. // the background check found changed folders: the results shown are searched again, in place
  2185. if (resultsView->isVisible() && tab != projectTab && searchBox.getText().trim().isNotEmpty())
  2186. runSearch (true);
  2187. return;
  2188. }
  2189. // the project changed: its sections are listed again a moment later (not on every knob step)
  2190. projectDirty = true;
  2191. if (! isTimerRunning())
  2192. startTimer (300);
  2193. }
  2194. void BrowserComponent::addUserFolder()
  2195. {
  2196. chooser = std::make_unique<juce::FileChooser> (tr ("Add a folder to the Browser"), juce::File::getSpecialLocation (juce::File::userMusicDirectory));
  2197. chooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories, [this] (const juce::FileChooser& fc) {
  2198. const auto folder = fc.getResult();
  2199. if (! folder.isDirectory())
  2200. return;
  2201. auto lines = juce::StringArray::fromLines (userFoldersFile().loadFileAsString());
  2202. lines.removeEmptyStrings();
  2203. lines.addIfNotAlreadyThere (folder.getFullPathName());
  2204. userFoldersFile().replaceWithText (lines.joinIntoString ("\n"));
  2205. setTab (allTab);
  2206. rebuildRoots();
  2207. });
  2208. }
  2209. BrowserComponent::~BrowserComponent()
  2210. {
  2211. engine.removeChangeListener (this);
  2212. searcher->statusChanged.removeChangeListener (this);
  2213. searcher->indexChanged.removeChangeListener (this);
  2214. searcher->service->cancelSearch();
  2215. focusWatcher.reset();
  2216. engine.previewFile ({});
  2217. }
  2218. void BrowserComponent::waitForListing (int)
  2219. {
  2220. // the tree lists folders synchronously when they open
  2221. }
  2222. void BrowserComponent::resized()
  2223. {
  2224. auto area = getLocalBounds().reduced (4);
  2225. tabs->setBounds (area.removeFromTop (26));
  2226. area.removeFromTop (4);
  2227. {
  2228. auto row = area.removeFromTop (24);
  2229. previewVolume.setBounds (row.removeFromRight (24));
  2230. stopButton.setBounds (row.removeFromRight (22));
  2231. viewButton.setBounds (row.removeFromRight (22));
  2232. row.removeFromRight (4);
  2233. searchBox.setBounds (row);
  2234. }
  2235. // indexing progress / what the search found (round 162)
  2236. statusArea = statusLine.isNotEmpty() ? area.removeFromTop (16).withTrimmedLeft (2) : juce::Rectangle<int>();
  2237. area.removeFromTop (4);
  2238. strip->setBounds (getLocalBounds().removeFromBottom (juce::jmin (64, getHeight() / 4)));
  2239. area.setBottom (strip->getY() - 2);
  2240. // FL's details box (date, size / version, folder) just above the preview strip, while something is selected
  2241. details->setVisible (details->hasFile() && area.getHeight() > 120);
  2242. if (details->isVisible())
  2243. details->setBounds (area.removeFromBottom (DetailsBox::preferredHeight).withX (0).withWidth (getWidth()));
  2244. treeView->setBounds (area);
  2245. resultsView->setBounds (area);
  2246. for (auto* list : { tree.get(), results.get() })
  2247. {
  2248. list->setSize (area.getWidth() - 10, list->getHeight());
  2249. list->updateSize();
  2250. }
  2251. }
  2252. void BrowserComponent::refreshPreviewVolume()
  2253. {
  2254. previewVolume.setValue (engine.getPreviewVolume(), juce::dontSendNotification);
  2255. const auto text = tr ("Sample preview volume: {0}", { ui::utilityVolumeText (engine.getPreviewVolume()) });
  2256. previewVolume.setTooltip (text);
  2257. ui::setHint (previewVolume, text + " " + tr ("[LMB] drag [Wheel] step [2xLMB] 100% [RMB] type a value"), true);
  2258. }
  2259. void BrowserComponent::paint (juce::Graphics& g)
  2260. {
  2261. const uitrace::Scope trace ("BrowserComponent paint", true, g.getClipBounds());
  2262. g.fillAll (theme::colour::bg2);
  2263. if (! statusArea.isEmpty())
  2264. {
  2265. g.setFont (theme::font (theme::type::caption));
  2266. g.setColour (theme::colour::textDisabled);
  2267. g.drawText (statusLine, statusArea, juce::Justification::centredLeft, true);
  2268. }
  2269. }
  2270. void BrowserComponent::showPreviewForSnapshot (const juce::File& file)
  2271. {
  2272. strip->show (file, false);
  2273. }
  2274. void BrowserComponent::fileSelected (const juce::File& file, bool preview)
  2275. {
  2276. if (details != nullptr && file != juce::File())
  2277. {
  2278. const auto wasVisible = details->hasFile();
  2279. details->show (file);
  2280. if (! wasVisible)
  2281. resized();
  2282. }
  2283. if (preview && file.hasFileExtension ("sf2;sf3") && file.existsAsFile())
  2284. {
  2285. int bank = 0, program = 0;
  2286. if (firstSoundFontPreset (file.getFullPathName().toStdString(), bank, program))
  2287. previewSoundFontPreset (engine, file.getFullPathName().toStdString(), bank, program);
  2288. return;
  2289. }
  2290. if (! isAudio (file))
  2291. return;
  2292. if (preview && file.existsAsFile())
  2293. {
  2294. engine.previewFile (file);
  2295. previewedFile = file;
  2296. }
  2297. strip->show (file, preview);
  2298. tree->repaint();
  2299. results->repaint();
  2300. }
  2301. // FL's Browser menus (REA round 143b, [EXEC] FL 2026: right-click on a sample, a folder, a plugin): the file's actions
  2302. // first, then a "System" section (open the parent folder, locate the file, delete it) and a "Tags" section (Favorite);
  2303. // a folder: Expand all / Collapse all, then System (Open). LYNX keeps its own "Add folder..." and "Refresh".
  2304. // Round 163 (user feedback: "this sort of UI has a ton of wasted space"): no "System" / "Tags" titles any more; the
  2305. // rarely used system actions sit in one "File" sub-menu, Starred stays one click away.
  2306. void BrowserComponent::addSystemItems (juce::PopupMenu& menu, const juce::File& file)
  2307. {
  2308. menu.addSeparator();
  2309. menu.addItem (tr ("Starred"), true, isStarred (file), [this, file] { setStarred (file, ! isStarred (file)); });
  2310. juce::PopupMenu system;
  2311. system.addItem (tr ("Open parent folder"), [file] { file.getParentDirectory().startAsProcess(); });
  2312. system.addItem (tr ("Locate file"), [file] { file.revealToUser(); });
  2313. system.addItem (tr ("Copy the file path"), [file] { juce::SystemClipboard::copyTextToClipboard (file.getFullPathName()); });
  2314. system.addSeparator();
  2315. system.addItem (tr ("Delete file..."), file.existsAsFile(), false, [this, file] { confirmDeleteFile (file); });
  2316. menu.addSubMenu (tr ("File"), system);
  2317. }
  2318. void BrowserComponent::confirmDeleteFile (const juce::File& file)
  2319. {
  2320. juce::Component::SafePointer<BrowserComponent> safe (this);
  2321. juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::WarningIcon, tr ("Delete file"),
  2322. tr ("Move \"{0}\" to the recycle bin?", { file.getFileName() }), tr ("Delete"), tr ("Cancel"), nullptr,
  2323. juce::ModalCallbackFunction::create ([safe, file] (int result) {
  2324. if (result == 0 || safe == nullptr)
  2325. return;
  2326. if (! file.moveToTrash())
  2327. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Delete file"),
  2328. tr ("The file could not be deleted."));
  2329. safe->rebuildRoots();
  2330. }));
  2331. }
  2332. void BrowserComponent::showFileMenu (const juce::File& file)
  2333. {
  2334. juce::PopupMenu menu;
  2335. menu.addSectionHeader (file.getFileName());
  2336. if (isAudio (file))
  2337. {
  2338. menu.addItem (tr ("Send to the selected channel"), onLoadIntoChannel != nullptr, false, [this, file] { onLoadIntoChannel (file); });
  2339. menu.addItem (tr ("Open in a new channel"), [this, file] { openFile (file); });
  2340. menu.addSeparator();
  2341. menu.addItem (tr ("Send to the Playlist as an audio clip"), onSendToPlaylist != nullptr, false, [this, file] { onSendToPlaylist (file); });
  2342. menu.addSeparator();
  2343. menu.addItem (tr ("Edit in the audio editor..."), [this, file] { openAudioEditor (engine, file); });
  2344. }
  2345. else if (file.hasFileExtension ("lynx;flp"))
  2346. menu.addItem (tr ("Open project"), onOpenProject != nullptr, false, [this, file] { onOpenProject (file); });
  2347. else if (file.hasFileExtension ("mid;midi"))
  2348. menu.addItem (tr ("Open MIDI file"), onOpenProject != nullptr, false, [this, file] { onOpenProject (file); });
  2349. else if (file.hasFileExtension ("fst;gmsynth"))
  2350. menu.addItem (tr ("Open in a new channel"), [this, file] { openFile (file); });
  2351. else if (file.hasFileExtension ("sf2;sf3"))
  2352. {
  2353. const auto selected = engine.getSelectedChannel();
  2354. const auto& song = engine.getSong();
  2355. const auto selectedIsFont = selected >= 0 && selected < (int) song.channels.size()
  2356. && song.channels[(std::size_t) selected].instrument == InstrumentKind::soundfont;
  2357. menu.addItem (tr ("Open in a new channel"), [this, file] { openSoundFontFile (engine, file); });
  2358. menu.addItem (tr ("Send to the selected channel"), selectedIsFont, false, [this, file, selected] { openSoundFontFile (engine, file, selected); });
  2359. }
  2360. addSystemItems (menu, file);
  2361. menu.addItem (tr ("Collapse all folders"), [this] { tree->collapseAll(); });
  2362. juce::PopupMenu browserMenu;
  2363. addViewItems (browserMenu);
  2364. menu.addSubMenu (tr ("Browser"), browserMenu);
  2365. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  2366. }
  2367. void BrowserComponent::showFolderMenu (const juce::File& folder, std::function<void()> expandAll)
  2368. {
  2369. // compact (round 163): the folder's name as the only title, its actions, then the Browser's own options
  2370. juce::PopupMenu menu;
  2371. menu.addSectionHeader (folder.getFileName());
  2372. menu.addItem (tr ("Expand all"), expandAll != nullptr, false, [expandAll] { expandAll(); });
  2373. menu.addItem (tr ("Collapse all"), [this] { tree->collapseAll(); });
  2374. menu.addItem (tr ("Starred"), folder.isDirectory(), isStarred (folder), [this, folder] { setStarred (folder, ! isStarred (folder)); });
  2375. menu.addItem (tr ("Open in the file manager"), [folder] { folder.startAsProcess(); });
  2376. menu.addItem (tr ("Copy the file path"), [folder] { juce::SystemClipboard::copyTextToClipboard (folder.getFullPathName()); });
  2377. menu.addSeparator();
  2378. if (const auto id = rootId (folder); id.isNotEmpty() && tab == allTab)
  2379. addHideItem (menu, id, allRootNames[allRoots.indexOf (folder)]);
  2380. juce::PopupMenu browserMenu;
  2381. addViewItems (browserMenu);
  2382. browserMenu.addSeparator();
  2383. browserMenu.addItem (tr ("Refresh"), [this] { rebuildRoots(); });
  2384. browserMenu.addItem (tr ("Refresh search index"), [this] { refreshSearchIndex (false); });
  2385. menu.addSubMenu (tr ("Browser"), browserMenu);
  2386. menu.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  2387. }
  2388. BrowserComponent::FileTree& BrowserComponent::activeList() const
  2389. {
  2390. return resultsView->isVisible() ? *results : *tree;
  2391. }
  2392. // --- search ------------------------------------------------------------------------------------------
  2393. void BrowserComponent::focusSearch()
  2394. {
  2395. searchBox.grabKeyboardFocus();
  2396. searchBox.selectAll();
  2397. }
  2398. juce::Array<juce::File> BrowserComponent::searchRoots() const
  2399. {
  2400. // the top-level folder holding the selection; nothing selected there: every folder
  2401. if (const auto root = tree->selectedRoot(); root.isDirectory())
  2402. return { root };
  2403. if (tab == starredTab) // the starred folders
  2404. {
  2405. juce::Array<juce::File> folders;
  2406. for (const auto& path : starred)
  2407. if (const juce::File f (path); f.isDirectory())
  2408. folders.add (f);
  2409. return folders;
  2410. }
  2411. return roots;
  2412. }
  2413. void BrowserComponent::setSearchForSnapshot (const juce::String& text)
  2414. {
  2415. // synchronous: the snapshot is drawn before any message is dispatched
  2416. searchBox.setText (text, juce::dontSendNotification);
  2417. searcher->service->cancelSearch();
  2418. resultsView->setVisible (text.isNotEmpty());
  2419. treeView->setVisible (text.isEmpty());
  2420. if (text.isEmpty() || roots.isEmpty())
  2421. return;
  2422. const juce::Array<juce::File> scope { roots[0] }; // the FL samples: the same results on every machine with FL
  2423. auto answer = std::make_shared<std::pair<std::mutex, search::SearchResult>>();
  2424. searcher->service->search (text.toStdString(), toPaths (scope), (std::size_t) maxResults, [answer] (const search::SearchResult& r) {
  2425. const std::lock_guard<std::mutex> guard (answer->first);
  2426. answer->second = r;
  2427. });
  2428. searcher->service->waitIdle (120000);
  2429. juce::Array<juce::File> found;
  2430. {
  2431. const std::lock_guard<std::mutex> guard (answer->first);
  2432. for (const auto& path : answer->second.paths)
  2433. found.add (juce::File (juce::String::fromUTF8 (path.c_str())));
  2434. }
  2435. results->setFiles (found, scope, found.isEmpty() ? tr ("Nothing found for \"{0}\".", { text }) : juce::String());
  2436. if (! found.isEmpty())
  2437. results->select (0, false);
  2438. }
  2439. void BrowserComponent::selectFirstSampleForSnapshot()
  2440. {
  2441. if (const auto row = tree->firstAudioRow(); row >= 0)
  2442. {
  2443. tree->select (row, false);
  2444. strip->show (tree->selectedFile(), false);
  2445. tree->setHovered (row + 1 < tree->numRows() ? row + 1 : -1);
  2446. }
  2447. }
  2448. void BrowserComponent::showPluginDatabaseForSnapshot()
  2449. {
  2450. openPluginFolders = { tr ("Plugin database"), tr ("Plugin database") + "/" + tr ("Generators"), tr ("Generators") + "/" + tr ("FL engines"),
  2451. tr ("Plugin database") + "/" + tr ("Effects"), tr ("Effects") + "/" + tr ("FL engines") };
  2452. setTab (allTab);
  2453. rebuildTree();
  2454. }
  2455. void BrowserComponent::showProjectForSnapshot()
  2456. {
  2457. setTab (projectTab);
  2458. if (const auto row = tree->openProjectSections ({ Category::patterns, Category::generators, Category::samples }); row >= 0)
  2459. {
  2460. tree->select (row, false);
  2461. strip->show (tree->selectedFile(), false);
  2462. tree->setHovered (row + 1 < tree->numRows() ? row + 1 : -1);
  2463. }
  2464. }
  2465. void BrowserComponent::textEditorTextChanged (juce::TextEditor&)
  2466. {
  2467. searchPending = true;
  2468. startTimer (250); // search once typing pauses
  2469. }
  2470. void BrowserComponent::textEditorEscapeKeyPressed (juce::TextEditor&)
  2471. {
  2472. // Esc: clears the search and gives the keyboard back (Space plays again)
  2473. searchPending = false;
  2474. searchBox.clear();
  2475. runSearch();
  2476. leaveSearchBox();
  2477. }
  2478. void BrowserComponent::textEditorReturnKeyPressed (juce::TextEditor&)
  2479. {
  2480. // Enter: searches now and leaves the box, so Up / Down step through the results (and Space plays)
  2481. searchPending = false;
  2482. runSearch();
  2483. leaveSearchBox();
  2484. }
  2485. bool BrowserComponent::isTypingInSearch() const
  2486. {
  2487. return searchBox.hasKeyboardFocus (true);
  2488. }
  2489. void BrowserComponent::leaveSearchBox()
  2490. {
  2491. if (! isTypingInSearch())
  2492. return;
  2493. // the window's first ancestor that takes keys (the main window's content: the shortcuts, the transport) gets them
  2494. for (auto* p = getParentComponent(); p != nullptr; p = p->getParentComponent())
  2495. if (p->getWantsKeyboardFocus() && p->isShowing())
  2496. {
  2497. p->grabKeyboardFocus();
  2498. if (! isTypingInSearch())
  2499. return;
  2500. }
  2501. searchBox.giveAwayKeyboardFocus();
  2502. }
  2503. void BrowserComponent::timerCallback()
  2504. {
  2505. stopTimer();
  2506. if (std::exchange (searchPending, false))
  2507. runSearch();
  2508. if (std::exchange (projectDirty, false))
  2509. {
  2510. tree->refreshProject();
  2511. if (tab == projectTab && resultsView->isVisible())
  2512. runSearch();
  2513. }
  2514. }
  2515. void BrowserComponent::runSearch (bool quiet)
  2516. {
  2517. searcher->service->cancelSearch();
  2518. searchId = 0;
  2519. const auto query = searchBox.getText().trim();
  2520. resultsView->setVisible (query.isNotEmpty());
  2521. treeView->setVisible (query.isEmpty());
  2522. if (query.isEmpty())
  2523. {
  2524. searchPartial = false;
  2525. indexStatusChanged();
  2526. return;
  2527. }
  2528. if (tab == projectTab) // the project's own items, at once
  2529. {
  2530. auto found = FileTree::projectMatches (engine.getSong(), query);
  2531. const auto none = found.empty();
  2532. results->setNodes (std::move (found), none ? tr ("Nothing found for \"{0}\".", { query }) : juce::String());
  2533. return;
  2534. }
  2535. const auto scope = searchRoots();
  2536. if (scope.isEmpty())
  2537. return;
  2538. if (! quiet)
  2539. {
  2540. results->setFiles ({}, scope, tr ("Searching {0}...", { scope.size() == 1 ? scope[0].getFullPathName() : tr ("every folder") }));
  2541. resultsView->setViewPosition (0, 0);
  2542. }
  2543. // the worker answers on its thread: the answer comes to the message thread (and is dropped if this Browser went)
  2544. searchId = searcher->service->search (query.toStdString(), toPaths (scope), (std::size_t) maxResults,
  2545. [safe = juce::Component::SafePointer<BrowserComponent> (this), query, scope] (const search::SearchResult& r) {
  2546. juce::MessageManager::callAsync ([safe, query, scope, r] {
  2547. if (safe != nullptr)
  2548. safe->searchAnswered (r, query, scope);
  2549. });
  2550. });
  2551. }
  2552. void BrowserComponent::searchAnswered (const search::SearchResult& r, const juce::String& query, const juce::Array<juce::File>& scope)
  2553. {
  2554. if (r.id != searchId || searchBox.getText().trim() != query)
  2555. return;
  2556. juce::Array<juce::File> found;
  2557. for (const auto& path : r.paths)
  2558. if (juce::File f (juce::String::fromUTF8 (path.c_str())); view.filter == browserview::ContentFilter::all || lists (f))
  2559. found.add (f);
  2560. // (partial answers and re-searches keep the selection and the scroll position)
  2561. const auto selected = results->selectedFile();
  2562. const auto scroll = resultsView->getViewPosition();
  2563. results->setFiles (found, scope,
  2564. found.isEmpty() ? (r.partial ? tr ("Indexing the folders... nothing found for \"{0}\" yet.", { query })
  2565. : tr ("Nothing found for \"{0}\".", { query }))
  2566. : juce::String());
  2567. if (selected != juce::File())
  2568. if (const auto row = found.indexOf (selected); row >= 0)
  2569. results->select (row, false);
  2570. resultsView->setViewPosition (scroll);
  2571. searchPartial = r.partial;
  2572. if (! r.partial && ! found.isEmpty())
  2573. // FL's hint bar after a search: "Found 51 files" (REA round 134)
  2574. ui::postHint ({ r.truncated ? tr ("Found more than {0} files", { juce::String (found.size()) })
  2575. : found.size() == 1 ? tr ("Found 1 file") : tr ("Found {0} files", { juce::String (found.size()) }),
  2576. {}, false, false },
  2577. 4000);
  2578. // the line under the search box
  2579. juce::String line;
  2580. if (r.partial)
  2581. line = tr ("Indexing... {0} found so far", { juce::String (found.size()) });
  2582. else if (r.truncated)
  2583. line = tr ("Showing the first {0} results.", { juce::String (maxResults) });
  2584. else
  2585. line = found.size() == 1 ? tr ("Found 1 file") : tr ("Found {0} files", { juce::String (found.size()) });
  2586. const auto st = searcher->service->status();
  2587. if (st.busy && ! r.partial)
  2588. line << " · " << tr ("checking the index...");
  2589. if (line != statusLine)
  2590. {
  2591. const auto relayout = line.isEmpty() != statusLine.isEmpty();
  2592. statusLine = line;
  2593. if (relayout)
  2594. resized();
  2595. repaint (statusArea);
  2596. }
  2597. }
  2598. void BrowserComponent::indexStatusChanged()
  2599. {
  2600. const auto st = searcher->service->status();
  2601. juce::String line;
  2602. if (resultsView->isVisible() && tab != projectTab && searchBox.getText().trim().isNotEmpty())
  2603. {
  2604. // a search is shown: its line stays; while the folders are indexed, the progress is added
  2605. line = statusLine.upToFirstOccurrenceOf (" · ", false, false);
  2606. if (st.busy)
  2607. line << " · " << (searchPartial ? tr ("{0} folders indexed", { juce::String ((int) st.listed) }) : tr ("checking the index..."));
  2608. }
  2609. else if (st.busy && (st.rebuilding || st.listed > 0))
  2610. line = tr ("Indexing the Browser's folders for search: {0} folders...", { juce::String ((int) st.listed) });
  2611. if (line != statusLine)
  2612. {
  2613. const auto relayout = line.isEmpty() != statusLine.isEmpty();
  2614. statusLine = line;
  2615. if (relayout)
  2616. resized();
  2617. repaint();
  2618. }
  2619. }
  2620. void BrowserComponent::refreshSearchIndex (bool rebuild)
  2621. {
  2622. // the index is shared by every Browser: it covers every folder, hidden ones too
  2623. if (! allRoots.isEmpty())
  2624. searcher->service->refresh (toPaths (allRoots), rebuild);
  2625. ui::postHint ({ rebuild ? tr ("Rebuilding the Browser's search index in the background...")
  2626. : tr ("Checking the Browser's search index in the background (only changed folders are read again)..."),
  2627. {}, false, false },
  2628. 4000);
  2629. }
  2630. juce::String BrowserComponent::searchIndexStatus() const
  2631. {
  2632. const auto st = searcher->service->status();
  2633. if (! st.loaded)
  2634. return tr ("Search index: loading...");
  2635. auto text = tr ("Search index: {0} files in {1} folders", { juce::String ((juce::int64) st.files), juce::String ((juce::int64) st.folders) });
  2636. if (st.busy)
  2637. text << " (" << tr ("updating: {0} folders read", { juce::String ((int) st.listed) }) << ")";
  2638. else if (st.checkedAt > 0)
  2639. text << " (" << tr ("checked at {0}", { juce::Time (st.checkedAt).formatted ("%H:%M") }) << ")";
  2640. return text;
  2641. }
  2642. void BrowserComponent::stopPreview()
  2643. {
  2644. engine.previewFile ({});
  2645. if (strip != nullptr)
  2646. strip->stop();
  2647. tree->repaint();
  2648. results->repaint();
  2649. }
  2650. // --- keys --------------------------------------------------------------------------------------------
  2651. juce::File BrowserComponent::getSelectedFile() const
  2652. {
  2653. return activeList().selectedFile();
  2654. }
  2655. void BrowserComponent::step (int delta, bool load)
  2656. {
  2657. auto& list = activeList();
  2658. const auto count = list.numRows();
  2659. if (count == 0)
  2660. return;
  2661. // the next row in that direction, as in FL: Up / Down walk every row (folders too: Right opens one, Left closes
  2662. // it), previewing each sample; Shift+Up / Down (loading each file into the channel) skips the folders
  2663. auto row = list.getSelectedRow();
  2664. for (int guard = 0; guard < count; ++guard)
  2665. {
  2666. row = row < 0 ? (delta > 0 ? 0 : count - 1) : row + delta;
  2667. if (row < 0 || row >= count)
  2668. return;
  2669. list.select (row, false);
  2670. if (! load || ! list.selectedIsFolder())
  2671. break;
  2672. }
  2673. const auto file = list.selectedFile();
  2674. if (file.existsAsFile())
  2675. fileSelected (file, true);
  2676. if (load && file.existsAsFile() && onLoadIntoChannel)
  2677. onLoadIntoChannel (file);
  2678. }
  2679. void BrowserComponent::openFolder (bool open)
  2680. {
  2681. if (! resultsView->isVisible())
  2682. tree->openSelected (open);
  2683. }
  2684. void BrowserComponent::loadSelected()
  2685. {
  2686. const auto file = getSelectedFile();
  2687. if (! file.existsAsFile())
  2688. return;
  2689. if (file.hasFileExtension ("sf2;sf3"))
  2690. {
  2691. // Enter: into the selected LYNX Soundfont channel, else a new one
  2692. if (! openSoundFontFile (engine, file, engine.getSelectedChannel()))
  2693. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Load SoundFont"), tr ("This file is not a SoundFont LYNX can read."));
  2694. return;
  2695. }
  2696. if (! onLoadIntoChannel || ! onLoadIntoChannel (file))
  2697. openFile (file);
  2698. }
  2699. bool BrowserComponent::isAudioFile (const juce::File& file)
  2700. {
  2701. return isAudio (file);
  2702. }
  2703. bool BrowserComponent::isBrowserDrag (const juce::DragAndDropTarget::SourceDetails& details)
  2704. {
  2705. const auto text = details.description.toString();
  2706. return text == dragDescription || text.startsWith (juce::String (dragDescription) + "|");
  2707. }
  2708. juce::File BrowserComponent::draggedFile (const juce::DragAndDropTarget::SourceDetails& details)
  2709. {
  2710. const auto text = details.description.toString();
  2711. if (text.startsWith (juce::String (dragDescription) + "|"))
  2712. return juce::File (text.fromFirstOccurrenceOf ("|", false, false));
  2713. return {};
  2714. }
  2715. bool BrowserComponent::isGeneratorDrag (const juce::DragAndDropTarget::SourceDetails& details)
  2716. {
  2717. return details.description.toString().startsWith (juce::String (generatorDragDescription) + "|") && draggedPlugin().generator != nullptr;
  2718. }
  2719. bool BrowserComponent::isEffectDrag (const juce::DragAndDropTarget::SourceDetails& details)
  2720. {
  2721. return details.description.toString().startsWith (juce::String (effectDragDescription) + "|") && draggedPlugin().effect != nullptr;
  2722. }
  2723. std::optional<ChannelDef> BrowserComponent::draggedGenerator (const juce::DragAndDropTarget::SourceDetails& details)
  2724. {
  2725. return isGeneratorDrag (details) ? draggedPlugin().generator() : std::nullopt;
  2726. }
  2727. std::optional<EffectSlot> BrowserComponent::draggedEffect (const juce::DragAndDropTarget::SourceDetails& details)
  2728. {
  2729. return isEffectDrag (details) ? draggedPlugin().effect() : std::nullopt;
  2730. }
  2731. int BrowserComponent::draggedPattern (const juce::DragAndDropTarget::SourceDetails& details)
  2732. {
  2733. const auto text = details.description.toString();
  2734. if (text.startsWith (juce::String (patternDragDescription) + "|"))
  2735. return text.fromFirstOccurrenceOf ("|", false, false).getIntValue();
  2736. return -1;
  2737. }
  2738. void BrowserComponent::openFile (const juce::File& file)
  2739. {
  2740. // a hosted plugin's preset (round 162d, issue #8): into the plugin it belongs to
  2741. if (pluginpresetui::isPresetFile (file) && (! file.hasFileExtension ("lynxpreset") || pluginpresetui::readLynxPreset (file).has_value()))
  2742. {
  2743. juce::String message;
  2744. if (! pluginpresetui::applyFromBrowser (engine, file, message) && message.isNotEmpty())
  2745. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin preset"), message);
  2746. return;
  2747. }
  2748. if (file.hasFileExtension ("sf2;sf3"))
  2749. {
  2750. if (! openSoundFontFile (engine, file))
  2751. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Load SoundFont"), tr ("This file is not a SoundFont LYNX can read."));
  2752. return;
  2753. }
  2754. if (isAudio (file))
  2755. {
  2756. const auto path = file.getFullPathName().toStdString();
  2757. const auto name = file.getFileNameWithoutExtension().toStdString();
  2758. engine.editSong ([&] (Song& s) {
  2759. ChannelDef c;
  2760. c.name = name;
  2761. c.instrument = InstrumentKind::sampler;
  2762. c.samplePath = path;
  2763. c.mixerTrack = s.claimFreeInsert();
  2764. s.channels.push_back (c);
  2765. });
  2766. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  2767. return;
  2768. }
  2769. // preset of an FL synth that LYNX converts (3x Osc, Sytrus, GMS...): new channel with the built-in synth
  2770. if (file.hasFileExtension ("fst;gmsynth"))
  2771. {
  2772. juce::MemoryBlock data;
  2773. if (! file.loadFileAsData (data))
  2774. return;
  2775. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  2776. if (auto synth = synthFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize())))
  2777. {
  2778. const auto name = file.getFileNameWithoutExtension().toStdString();
  2779. engine.editSong ([&] (Song& s) {
  2780. ChannelDef c;
  2781. c.name = name;
  2782. c.instrument = InstrumentKind::synth;
  2783. c.synth = *synth;
  2784. c.mixerTrack = s.claimFreeInsert();
  2785. s.channels.push_back (c);
  2786. });
  2787. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  2788. }
  2789. else
  2790. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Preset"),
  2791. tr ("LYNX reads presets from 3x Osc, Sytrus, Harmor, GMS, Harmless, MiniSynth, DX10, Fruit Kick, Ogun and Sakura."));
  2792. return;
  2793. }
  2794. if (file.hasFileExtension ("lynx;flp;mid;midi") && onOpenProject)
  2795. onOpenProject (file);
  2796. }
  2797. } // namespace lynx