BrowserComponent.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. #include "ui/BrowserComponent.h"
  2. #include "core/FlpImport.h"
  3. #include "core/SearchQuery.h"
  4. #include "engine/PluginHost.h"
  5. #include "engine/Text.h"
  6. #include "ui/I18n.h"
  7. #include "ui/Theme.h"
  8. namespace lynx
  9. {
  10. namespace
  11. {
  12. bool isAudio (const juce::File& f)
  13. {
  14. return f.hasFileExtension ("wav;flac;ogg;mp3;aif;aiff;wv");
  15. }
  16. bool isListed (const juce::File& f)
  17. {
  18. return f.hasFileExtension ("wav;flac;ogg;mp3;aif;aiff;mid;midi;lynx;flp;fst");
  19. }
  20. constexpr int maxResults = 500;
  21. juce::Array<juce::File> searchFiles (const juce::File& root, const juce::String& query, bool& truncated, const std::function<bool()>& shouldStop)
  22. {
  23. const auto parsed = search::parse (query.toStdString());
  24. juce::Array<juce::File> found;
  25. truncated = false;
  26. for (const auto& entry : juce::RangedDirectoryIterator (root, true, "*", juce::File::findFiles))
  27. {
  28. if (shouldStop())
  29. break;
  30. const auto file = entry.getFile();
  31. if (! isListed (file) || ! search::matches (parsed, file.getFileName().toStdString()))
  32. continue;
  33. found.add (file);
  34. if (found.size() >= maxResults)
  35. {
  36. truncated = true;
  37. break;
  38. }
  39. }
  40. return found;
  41. }
  42. } // namespace
  43. // --- search: a background walk of the current folder ------------------------------------------------
  44. class BrowserComponent::SearchJob final : public juce::Thread
  45. {
  46. public:
  47. SearchJob (juce::File r, juce::String q, std::function<void (juce::Array<juce::File>, bool)> d)
  48. : juce::Thread ("LYNX browser search"), root (std::move (r)), query (std::move (q)), done (std::move (d))
  49. {
  50. }
  51. ~SearchJob() override { stopThread (3000); }
  52. void run() override
  53. {
  54. bool truncated = false;
  55. const auto found = searchFiles (root, query, truncated, [this] { return threadShouldExit(); });
  56. if (threadShouldExit())
  57. return;
  58. juce::MessageManager::callAsync ([done = done, found, truncated] { done (found, truncated); });
  59. }
  60. private:
  61. juce::File root;
  62. juce::String query;
  63. std::function<void (juce::Array<juce::File>, bool)> done;
  64. };
  65. class BrowserComponent::Results final : public juce::ListBox,
  66. private juce::ListBoxModel
  67. {
  68. public:
  69. explicit Results (BrowserComponent& b) : browser (b)
  70. {
  71. setModel (this);
  72. setRowHeight (22);
  73. setColour (juce::ListBox::backgroundColourId, theme::colour::bg2);
  74. setOutlineThickness (0);
  75. setWantsKeyboardFocus (false);
  76. setMouseClickGrabsKeyboardFocus (false);
  77. }
  78. juce::Array<juce::File> files;
  79. juce::File root;
  80. juce::String status;
  81. juce::File selected() const
  82. {
  83. const auto row = getSelectedRow();
  84. return juce::isPositiveAndBelow (row, files.size()) ? files[row] : juce::File();
  85. }
  86. int getNumRows() override { return files.size(); }
  87. void paintListBoxItem (int row, juce::Graphics& g, int width, int height, bool isSelected) override
  88. {
  89. if (! juce::isPositiveAndBelow (row, files.size()))
  90. return;
  91. if (isSelected)
  92. {
  93. g.setColour (theme::colour::accentMuted);
  94. g.fillRect (0, 0, width, height);
  95. }
  96. const auto& f = files[row];
  97. g.setFont (theme::font (theme::type::body));
  98. g.setColour (theme::colour::textPrimary);
  99. g.drawText (f.getFileName(), 6, 0, width - 12, height, juce::Justification::centredLeft, true);
  100. g.setFont (theme::font (theme::type::caption));
  101. g.setColour (theme::colour::textDisabled);
  102. g.drawText (f.getParentDirectory().getRelativePathFrom (root), 6, 0, width - 12, height, juce::Justification::centredRight, true);
  103. }
  104. void paint (juce::Graphics& g) override
  105. {
  106. juce::ListBox::paint (g);
  107. if (files.isEmpty())
  108. {
  109. g.setColour (theme::colour::textDisabled);
  110. g.setFont (theme::font (theme::type::small));
  111. g.drawFittedText (status, getLocalBounds().reduced (10), juce::Justification::centredTop, 3);
  112. }
  113. }
  114. void selectedRowsChanged (int row) override
  115. {
  116. if (juce::isPositiveAndBelow (row, files.size()) && isAudio (files[row]))
  117. browser.engine.previewFile (files[row]);
  118. }
  119. void listBoxItemDoubleClicked (int row, const juce::MouseEvent&) override
  120. {
  121. if (juce::isPositiveAndBelow (row, files.size()))
  122. browser.openFile (files[row]);
  123. }
  124. juce::var getDragSourceDescription (const juce::SparseSet<int>& rows) override
  125. {
  126. if (rows.isEmpty() || ! juce::isPositiveAndBelow (rows[0], files.size()))
  127. return {};
  128. return juce::String (dragDescription) + "|" + files[rows[0]].getFullPathName();
  129. }
  130. private:
  131. BrowserComponent& browser;
  132. };
  133. BrowserComponent::BrowserComponent (AudioEngine& e)
  134. : engine (e)
  135. {
  136. rebuildRoots();
  137. rootBox.onChange = [this] {
  138. const auto id = rootBox.getSelectedId();
  139. if (id == addFolderId)
  140. {
  141. rootBox.setSelectedId (currentRoot + 1, juce::dontSendNotification);
  142. addUserFolder();
  143. return;
  144. }
  145. setRoot (id - 1);
  146. if (searchBox.getText().isNotEmpty())
  147. runSearch();
  148. };
  149. rootBox.setWantsKeyboardFocus (false);
  150. rootBox.setMouseClickGrabsKeyboardFocus (false);
  151. addAndMakeVisible (rootBox);
  152. searchBox.setTextToShowWhenEmpty (tr ("Search (Ctrl+F): kick -loop, snare OR clap, hat*.wav"), theme::colour::textDisabled);
  153. searchBox.addListener (this);
  154. searchBox.setEscapeAndReturnKeysConsumed (true);
  155. addAndMakeVisible (searchBox);
  156. results = std::make_unique<Results> (*this);
  157. addChildComponent (*results);
  158. tree.setItemHeight (20);
  159. tree.setDragAndDropDescription (dragDescription);
  160. tree.addListener (this);
  161. tree.setColour (juce::TreeView::backgroundColourId, theme::colour::bg2);
  162. tree.setWantsKeyboardFocus (false);
  163. addAndMakeVisible (tree);
  164. thread.startThread (juce::Thread::Priority::low);
  165. if (! roots.isEmpty())
  166. {
  167. rootBox.setSelectedId (1, juce::dontSendNotification);
  168. setRoot (0);
  169. }
  170. }
  171. juce::File BrowserComponent::userFoldersFile()
  172. {
  173. return PluginHost::settingsFolder().getChildFile ("browser-folders.txt");
  174. }
  175. void BrowserComponent::rebuildRoots()
  176. {
  177. roots.clear();
  178. rootBox.clear (juce::dontSendNotification);
  179. // FL folders (if installed) and user folders
  180. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  181. juce::File fl;
  182. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  183. if (dir.getChildFile ("Data").isDirectory() && dir.getFileName() > fl.getFileName()) // "FL Studio ASIO" is the driver
  184. fl = dir;
  185. auto add = [this] (const juce::String& name, const juce::File& folder) {
  186. if (folder.isDirectory())
  187. {
  188. roots.add (folder);
  189. rootBox.addItem (name, roots.size());
  190. }
  191. };
  192. const auto data = fl.getChildFile ("Data");
  193. add (tr ("FL samples (Packs)"), data.getChildFile ("Patches").getChildFile ("Packs"));
  194. add (tr ("FL demo projects"), data.getChildFile ("Demo projects"));
  195. add (tr ("FL MIDI"), data.getChildFile ("Patches").getChildFile ("Scores"));
  196. add (tr ("3x Osc presets (FL)"), data.getChildFile ("Patches").getChildFile ("Channel presets").getChildFile ("3x Osc"));
  197. add (tr ("Synth presets (FL)"), data.getChildFile ("Patches").getChildFile ("Plugin presets").getChildFile ("Generators"));
  198. add (tr ("Documents"), juce::File::getSpecialLocation (juce::File::userDocumentsDirectory));
  199. add (tr ("Music"), juce::File::getSpecialLocation (juce::File::userMusicDirectory));
  200. add (tr ("Desktop"), juce::File::getSpecialLocation (juce::File::userDesktopDirectory));
  201. add (tr ("Downloads"), juce::File::getSpecialLocation (juce::File::userHomeDirectory).getChildFile ("Downloads"));
  202. for (const auto& line : juce::StringArray::fromLines (userFoldersFile().loadFileAsString()))
  203. if (line.trim().isNotEmpty())
  204. add (juce::File (line.trim()).getFileName(), juce::File (line.trim()));
  205. rootBox.addSeparator();
  206. rootBox.addItem (tr ("Add folder..."), addFolderId);
  207. }
  208. void BrowserComponent::addUserFolder()
  209. {
  210. chooser = std::make_unique<juce::FileChooser> (tr ("Add a folder to the Browser"), juce::File::getSpecialLocation (juce::File::userMusicDirectory));
  211. chooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories, [this] (const juce::FileChooser& fc) {
  212. const auto folder = fc.getResult();
  213. if (! folder.isDirectory())
  214. return;
  215. auto lines = juce::StringArray::fromLines (userFoldersFile().loadFileAsString());
  216. lines.removeEmptyStrings();
  217. lines.addIfNotAlreadyThere (folder.getFullPathName());
  218. userFoldersFile().replaceWithText (lines.joinIntoString ("\n"));
  219. rebuildRoots();
  220. for (int i = 0; i < roots.size(); ++i)
  221. if (roots[i] == folder)
  222. {
  223. rootBox.setSelectedId (i + 1, juce::dontSendNotification);
  224. setRoot (i);
  225. }
  226. });
  227. }
  228. BrowserComponent::~BrowserComponent()
  229. {
  230. job.reset();
  231. tree.removeListener (this);
  232. engine.previewFile ({});
  233. thread.stopThread (2000);
  234. }
  235. void BrowserComponent::setRoot (int index)
  236. {
  237. if (juce::isPositiveAndBelow (index, roots.size()))
  238. {
  239. currentRoot = index;
  240. list.setDirectory (roots[index], true, true);
  241. }
  242. }
  243. void BrowserComponent::waitForListing (int timeoutMs)
  244. {
  245. const auto end = juce::Time::getMillisecondCounter() + (juce::uint32) timeoutMs;
  246. while (list.isStillLoading() && juce::Time::getMillisecondCounter() < end)
  247. juce::Thread::sleep (20);
  248. list.dispatchPendingMessages();
  249. // the tree lays new items out asynchronously; re-setting the root item does it now
  250. if (auto* root = tree.getRootItem())
  251. {
  252. tree.setRootItem (nullptr);
  253. tree.setRootItem (root);
  254. }
  255. }
  256. void BrowserComponent::resized()
  257. {
  258. auto area = getLocalBounds().reduced (4);
  259. rootBox.setBounds (area.removeFromTop (26));
  260. area.removeFromTop (4);
  261. searchBox.setBounds (area.removeFromTop (24));
  262. area.removeFromTop (4);
  263. tree.setBounds (area);
  264. results->setBounds (area);
  265. }
  266. void BrowserComponent::paint (juce::Graphics& g)
  267. {
  268. g.fillAll (theme::colour::bg2);
  269. }
  270. void BrowserComponent::selectionChanged()
  271. {
  272. const auto file = tree.getSelectedFile();
  273. if (isAudio (file))
  274. engine.previewFile (file);
  275. }
  276. void BrowserComponent::fileDoubleClicked (const juce::File& file)
  277. {
  278. openFile (file);
  279. }
  280. // --- search ------------------------------------------------------------------------------------------
  281. void BrowserComponent::focusSearch()
  282. {
  283. searchBox.grabKeyboardFocus();
  284. searchBox.selectAll();
  285. }
  286. void BrowserComponent::setSearchForSnapshot (const juce::String& text)
  287. {
  288. // synchronous: the snapshot is drawn before any message is dispatched
  289. searchBox.setText (text, juce::dontSendNotification);
  290. job.reset();
  291. results->setVisible (text.isNotEmpty());
  292. tree.setVisible (text.isEmpty());
  293. if (text.isEmpty() || ! juce::isPositiveAndBelow (currentRoot, roots.size()))
  294. return;
  295. bool truncated = false;
  296. results->root = roots[currentRoot];
  297. results->files = searchFiles (roots[currentRoot], text, truncated, [] { return false; });
  298. results->status = results->files.isEmpty() ? tr ("Nothing found for \"{0}\".", { text }) : juce::String();
  299. results->updateContent();
  300. results->selectRow (results->files.isEmpty() ? -1 : 0, true, true);
  301. }
  302. void BrowserComponent::textEditorTextChanged (juce::TextEditor&)
  303. {
  304. startTimer (250); // search once typing pauses
  305. }
  306. void BrowserComponent::textEditorEscapeKeyPressed (juce::TextEditor&)
  307. {
  308. searchBox.clear();
  309. runSearch();
  310. }
  311. void BrowserComponent::textEditorReturnKeyPressed (juce::TextEditor&)
  312. {
  313. stopTimer();
  314. runSearch();
  315. }
  316. void BrowserComponent::timerCallback()
  317. {
  318. stopTimer();
  319. runSearch();
  320. }
  321. void BrowserComponent::runSearch()
  322. {
  323. job.reset();
  324. const auto query = searchBox.getText().trim();
  325. results->setVisible (query.isNotEmpty());
  326. tree.setVisible (query.isEmpty());
  327. if (query.isEmpty() || ! juce::isPositiveAndBelow (currentRoot, roots.size()))
  328. return;
  329. results->files.clear();
  330. results->root = roots[currentRoot];
  331. results->status = tr ("Searching {0}...", { roots[currentRoot].getFullPathName() });
  332. results->updateContent();
  333. results->repaint();
  334. job = std::make_unique<SearchJob> (roots[currentRoot], query, [safe = juce::Component::SafePointer<BrowserComponent> (this), query] (juce::Array<juce::File> found, bool truncated) {
  335. if (safe == nullptr || safe->searchBox.getText().trim() != query)
  336. return;
  337. auto& r = *safe->results;
  338. r.files = found;
  339. r.status = found.isEmpty() ? tr ("Nothing found for \"{0}\".", { query }) : juce::String();
  340. r.updateContent();
  341. r.selectRow (-1);
  342. r.repaint();
  343. if (truncated)
  344. r.status = tr ("Showing the first {0} results.", { juce::String (maxResults) });
  345. });
  346. job->startThread (juce::Thread::Priority::low);
  347. }
  348. // --- keys --------------------------------------------------------------------------------------------
  349. juce::File BrowserComponent::getSelectedFile() const
  350. {
  351. return results->isVisible() ? results->selected() : tree.getSelectedFile();
  352. }
  353. void BrowserComponent::step (int delta, bool load)
  354. {
  355. juce::File file;
  356. if (results->isVisible())
  357. {
  358. const auto count = results->files.size();
  359. if (count == 0)
  360. return;
  361. const auto row = juce::jlimit (0, count - 1, results->getSelectedRow() < 0 ? 0 : results->getSelectedRow() + delta);
  362. results->selectRow (row);
  363. results->scrollToEnsureRowIsOnscreen (row);
  364. file = results->selected();
  365. }
  366. else
  367. {
  368. // walk the visible rows of the tree, skipping folders
  369. auto* selected = tree.getSelectedItem (0);
  370. auto row = selected != nullptr ? selected->getRowNumberInTree() : -1;
  371. for (int guard = 0; guard < tree.getNumRowsInTree(); ++guard)
  372. {
  373. row += delta;
  374. auto* item = tree.getItemOnRow (row);
  375. if (item == nullptr)
  376. return;
  377. item->setSelected (true, true);
  378. tree.scrollToKeepItemVisible (item);
  379. file = tree.getSelectedFile();
  380. if (! file.isDirectory())
  381. break;
  382. }
  383. }
  384. if (load && file.existsAsFile() && onLoadIntoChannel)
  385. onLoadIntoChannel (file);
  386. }
  387. void BrowserComponent::loadSelected()
  388. {
  389. const auto file = getSelectedFile();
  390. if (! file.existsAsFile())
  391. return;
  392. if (! onLoadIntoChannel || ! onLoadIntoChannel (file))
  393. openFile (file);
  394. }
  395. bool BrowserComponent::isBrowserDrag (const juce::DragAndDropTarget::SourceDetails& details)
  396. {
  397. const auto text = details.description.toString();
  398. return text == dragDescription || text.startsWith (juce::String (dragDescription) + "|");
  399. }
  400. juce::File BrowserComponent::draggedFile (const juce::DragAndDropTarget::SourceDetails& details)
  401. {
  402. const auto text = details.description.toString();
  403. if (text.startsWith (juce::String (dragDescription) + "|"))
  404. return juce::File (text.fromFirstOccurrenceOf ("|", false, false));
  405. if (auto* tree = dynamic_cast<juce::FileTreeComponent*> (details.sourceComponent.get()))
  406. return tree->getSelectedFile();
  407. return {};
  408. }
  409. void BrowserComponent::openFile (const juce::File& file)
  410. {
  411. if (isAudio (file))
  412. {
  413. const auto path = file.getFullPathName().toStdString();
  414. const auto name = file.getFileNameWithoutExtension().toStdString();
  415. engine.editSong ([&] (Song& s) {
  416. ChannelDef c;
  417. c.name = name;
  418. c.instrument = InstrumentKind::sampler;
  419. c.samplePath = path;
  420. c.mixerTrack = s.nextFreeInsert();
  421. s.channels.push_back (c);
  422. });
  423. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  424. return;
  425. }
  426. // preset of an FL synth that LYNX converts (3x Osc, Sytrus, GMS...): new channel with the built-in synth
  427. if (file.hasFileExtension ("fst;gmsynth"))
  428. {
  429. juce::MemoryBlock data;
  430. if (! file.loadFileAsData (data))
  431. return;
  432. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  433. if (auto synth = synthFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize())))
  434. {
  435. const auto name = file.getFileNameWithoutExtension().toStdString();
  436. engine.editSong ([&] (Song& s) {
  437. ChannelDef c;
  438. c.name = name;
  439. c.instrument = InstrumentKind::synth;
  440. c.synth = *synth;
  441. c.mixerTrack = s.nextFreeInsert();
  442. s.channels.push_back (c);
  443. });
  444. engine.setSelectedChannel ((int) engine.getSong().channels.size() - 1);
  445. }
  446. else
  447. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Preset"),
  448. tr ("LYNX reads presets from 3x Osc, Sytrus, Harmor, GMS, Harmless, MiniSynth, DX10, Fruit Kick, Ogun and Sakura."));
  449. return;
  450. }
  451. if (file.hasFileExtension ("lynx;flp;mid;midi") && onOpenProject)
  452. onOpenProject (file);
  453. }
  454. } // namespace lynx