SimpleWorkflow.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. #include "ui/SimpleWorkflow.h"
  2. #include <algorithm>
  3. #include "core/LoopStarter.h"
  4. #include "core/MidiImport.h"
  5. #include "engine/AudioEngine.h"
  6. #include "engine/MidiFileIo.h"
  7. #include "ui/FileChoosers.h"
  8. #include "ui/I18n.h"
  9. #include "ui/LoopStarterWindow.h"
  10. #include "ui/QuickPick.h"
  11. #include "ui/Theme.h"
  12. namespace lynx
  13. {
  14. namespace
  15. {
  16. using simpletracks::Kind;
  17. // --- the tiles' pictures: LYNX's own simple line drawings in a 1×1 box ------------------------------------------------
  18. enum class Glyph { voice, instrument, drums, sampler, guitar, import, loops };
  19. juce::Path glyphPath (Glyph glyph)
  20. {
  21. juce::Path p;
  22. switch (glyph)
  23. {
  24. case Glyph::voice: // a microphone on its stand
  25. p.addRoundedRectangle (0.36f, 0.08f, 0.28f, 0.48f, 0.14f);
  26. p.startNewSubPath (0.24f, 0.44f);
  27. p.cubicTo (0.24f, 0.78f, 0.76f, 0.78f, 0.76f, 0.44f);
  28. p.startNewSubPath (0.5f, 0.72f);
  29. p.lineTo (0.5f, 0.9f);
  30. p.startNewSubPath (0.34f, 0.9f);
  31. p.lineTo (0.66f, 0.9f);
  32. break;
  33. case Glyph::instrument: // three octave keys
  34. p.addRectangle (0.1f, 0.22f, 0.8f, 0.56f);
  35. for (float x : { 0.3f, 0.5f, 0.7f })
  36. {
  37. p.startNewSubPath (x, 0.22f);
  38. p.lineTo (x, 0.78f);
  39. }
  40. for (float x : { 0.25f, 0.45f, 0.65f })
  41. p.addRectangle (x, 0.22f, 0.1f, 0.3f);
  42. break;
  43. case Glyph::drums: // a drum with two sticks
  44. p.addEllipse (0.16f, 0.4f, 0.68f, 0.2f);
  45. p.startNewSubPath (0.16f, 0.5f);
  46. p.lineTo (0.16f, 0.78f);
  47. p.quadraticTo (0.5f, 0.94f, 0.84f, 0.78f);
  48. p.lineTo (0.84f, 0.5f);
  49. p.startNewSubPath (0.28f, 0.1f);
  50. p.lineTo (0.46f, 0.42f);
  51. p.startNewSubPath (0.72f, 0.1f);
  52. p.lineTo (0.54f, 0.42f);
  53. break;
  54. case Glyph::sampler: // a waveform over a key
  55. {
  56. const float h[] { 0.1f, 0.24f, 0.4f, 0.18f, 0.32f, 0.12f, 0.06f };
  57. for (int i = 0; i < 7; ++i)
  58. {
  59. const auto x = 0.14f + 0.12f * (float) i;
  60. p.startNewSubPath (x, 0.42f - h[i]);
  61. p.lineTo (x, 0.42f + h[i]);
  62. }
  63. p.addRectangle (0.14f, 0.7f, 0.72f, 0.16f);
  64. break;
  65. }
  66. case Glyph::guitar: // a body and a neck
  67. p.addEllipse (0.1f, 0.5f, 0.34f, 0.34f);
  68. p.addEllipse (0.22f, 0.36f, 0.26f, 0.26f);
  69. p.startNewSubPath (0.38f, 0.56f);
  70. p.lineTo (0.84f, 0.1f);
  71. p.addEllipse (0.24f, 0.62f, 0.08f, 0.08f);
  72. break;
  73. case Glyph::import: // an arrow into a tray
  74. p.startNewSubPath (0.5f, 0.1f);
  75. p.lineTo (0.5f, 0.6f);
  76. p.startNewSubPath (0.32f, 0.44f);
  77. p.lineTo (0.5f, 0.62f);
  78. p.lineTo (0.68f, 0.44f);
  79. p.startNewSubPath (0.14f, 0.62f);
  80. p.lineTo (0.14f, 0.86f);
  81. p.lineTo (0.86f, 0.86f);
  82. p.lineTo (0.86f, 0.62f);
  83. break;
  84. case Glyph::loops: // a circle of arrows
  85. p.addCentredArc (0.5f, 0.5f, 0.32f, 0.32f, 0.0f, 0.4f, 5.6f, true);
  86. p.startNewSubPath (0.62f, 0.12f);
  87. p.lineTo (0.7f, 0.22f);
  88. p.lineTo (0.56f, 0.28f);
  89. break;
  90. }
  91. return p;
  92. }
  93. void drawGlyph (juce::Graphics& g, Glyph glyph, juce::Rectangle<float> box, juce::Colour tint)
  94. {
  95. g.setColour (tint.withAlpha (0.2f));
  96. g.fillRoundedRectangle (box, theme::radius::lg);
  97. g.setColour (tint.withAlpha (0.55f));
  98. g.drawRoundedRectangle (box.reduced (0.5f), theme::radius::lg, 1.0f);
  99. const auto inner = box.reduced (box.getWidth() * 0.18f);
  100. auto path = glyphPath (glyph);
  101. path.applyTransform (juce::AffineTransform::scale (inner.getWidth(), inner.getHeight()).translated (inner.getX(), inner.getY()));
  102. g.setColour (theme::colour::textPrimary);
  103. g.strokePath (path, juce::PathStrokeType (1.6f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  104. }
  105. // A tile: picture, name, one line of help. Clicking anywhere on it runs `onClick`.
  106. class Tile final : public juce::Component,
  107. public juce::SettableTooltipClient
  108. {
  109. public:
  110. Tile (Glyph g, juce::Colour c, juce::String n, juce::String h) : glyph (g), tint (c), name (std::move (n)), help (std::move (h))
  111. {
  112. setWantsKeyboardFocus (true);
  113. setMouseCursor (juce::MouseCursor::PointingHandCursor);
  114. setTitle (name);
  115. setDescription (help);
  116. setTooltip (help);
  117. }
  118. std::function<void()> onClick;
  119. // the part of the tile on the right that holds other controls (the Guitar | Bass switch): the text stops before it
  120. int rightReserve = 0;
  121. void paint (juce::Graphics& g) override
  122. {
  123. auto r = getLocalBounds().toFloat().reduced (1.0f);
  124. const auto hover = isMouseOver (true), down = isMouseButtonDown();
  125. g.setColour (down ? theme::colour::bg5 : hover ? theme::colour::bg4 : theme::colour::bg3);
  126. g.fillRoundedRectangle (r, theme::radius::lg);
  127. g.setColour (hasKeyboardFocus (false) ? theme::colour::accent : hover ? theme::colour::borderStrong : theme::colour::border);
  128. g.drawRoundedRectangle (r.reduced (0.5f), theme::radius::lg, 1.0f);
  129. const auto side = juce::jmin (44.0f, r.getHeight() - 16.0f);
  130. drawGlyph (g, glyph, { r.getX() + 10.0f, r.getCentreY() - side / 2.0f, side, side }, tint);
  131. auto text = getLocalBounds().withTrimmedLeft ((int) side + 22).withTrimmedRight (8 + rightReserve).reduced (0, 8);
  132. g.setColour (theme::colour::textPrimary);
  133. g.setFont (theme::font (theme::type::title, true));
  134. g.drawFittedText (name, text.removeFromTop (20), juce::Justification::centredLeft, 1, 0.85f);
  135. g.setColour (theme::colour::textSecondary);
  136. g.setFont (theme::font (theme::type::small));
  137. g.drawFittedText (help, text, juce::Justification::topLeft, 2, 0.9f);
  138. }
  139. void mouseEnter (const juce::MouseEvent&) override { repaint(); }
  140. void mouseExit (const juce::MouseEvent&) override { repaint(); }
  141. void mouseDown (const juce::MouseEvent&) override { repaint(); }
  142. void mouseUp (const juce::MouseEvent& e) override
  143. {
  144. repaint();
  145. if (e.mouseWasClicked() && getLocalBounds().contains (e.getPosition()) && onClick)
  146. onClick();
  147. }
  148. bool keyPressed (const juce::KeyPress& key) override
  149. {
  150. if ((key == juce::KeyPress::returnKey || key == juce::KeyPress::spaceKey) && onClick)
  151. {
  152. onClick();
  153. return true;
  154. }
  155. return false;
  156. }
  157. void focusGained (FocusChangeType) override { repaint(); }
  158. void focusLost (FocusChangeType) override { repaint(); }
  159. private:
  160. Glyph glyph;
  161. juce::Colour tint;
  162. juce::String name, help;
  163. };
  164. juce::Colour kindColour (Kind kind) { return juce::Colour (simpletracks::defaultColour (kind)); }
  165. // The name a new track of `kind` takes, in the UI's language
  166. std::string trackNameFor (Kind kind)
  167. {
  168. switch (kind)
  169. {
  170. case Kind::voice: return tr ("Voice").toStdString();
  171. case Kind::instrument: return tr ("Instrument").toStdString();
  172. case Kind::drums: return tr ("Drums").toStdString();
  173. case Kind::sampler: return tr ("Sampler").toStdString();
  174. case Kind::guitar: return tr ("Guitar").toStdString();
  175. case Kind::bass: return trc ("@instrument: Bass").toStdString();
  176. case Kind::audio: break;
  177. }
  178. return tr ("Audio").toStdString();
  179. }
  180. } // namespace
  181. // --- the chooser: the tiles, then (after Drums) the starter beats -----------------------------------------------------
  182. class SimpleWorkflow::Chooser final : public juce::Component
  183. {
  184. public:
  185. explicit Chooser (SimpleWorkflow& w)
  186. : owner (w),
  187. voice (Glyph::voice, kindColour (Kind::voice), tr ("Voice / audio"), tr ("Record your voice or any sound from a microphone.")),
  188. instrument (Glyph::instrument, kindColour (Kind::instrument), tr ("Instrument"), tr ("Play a sound with the computer keys, the mouse or a MIDI keyboard.")),
  189. drums (Glyph::drums, kindColour (Kind::drums), tr ("Drums"), tr ("Make a beat on a step grid, or start from a starter beat.")),
  190. sampler (Glyph::sampler, kindColour (Kind::sampler), tr ("Sampler"), tr ("Turn any sound into an instrument you play on keys.")),
  191. guitar (Glyph::guitar, kindColour (Kind::guitar), tr ("Guitar / bass"), tr ("Plug in a guitar or a bass and play it through the track's effects.")),
  192. import (Glyph::import, kindColour (Kind::audio), tr ("Import"), tr ("Bring in audio or MIDI files: one track each.")),
  193. loops (Glyph::loops, kindColour (Kind::audio), tr ("Loops"), tr ("Browse loops and drag them onto the timeline."))
  194. {
  195. setWantsKeyboardFocus (true);
  196. title.setText (tr ("New track"), juce::dontSendNotification);
  197. title.setFont (theme::font (theme::type::display, true));
  198. title.setJustificationType (juce::Justification::centred);
  199. footer.setText (tr ("Each track gets its own channel and mixer track."), juce::dontSendNotification);
  200. footer.setFont (theme::font (theme::type::small));
  201. footer.setColour (juce::Label::textColourId, theme::colour::textSecondary);
  202. footer.setJustificationType (juce::Justification::centred);
  203. close.setButtonText (juce::String::fromUTF8 ("\xc3\x97"));
  204. close.setTooltip (tr ("Close"));
  205. close.onClick = [this] { owner.closeByHand(); };
  206. voice.onClick = [this] { owner.addAudio (Kind::voice); };
  207. instrument.onClick = [this] { owner.chooseInstrument (instrument); };
  208. drums.onClick = [this] { showStarterPage(); };
  209. sampler.onClick = [this] { owner.chooseSample(); };
  210. guitar.onClick = [this] { owner.addAudio (bassButton.getToggleState() ? Kind::bass : Kind::guitar); };
  211. import.onClick = [this] { owner.importFiles(); };
  212. loops.onClick = [this] {
  213. if (owner.host.showLoops)
  214. owner.host.showLoops();
  215. };
  216. guitar.rightReserve = 168;
  217. guitarButton.setButtonText (tr ("Guitar"));
  218. bassButton.setButtonText (trc ("@instrument: Bass"));
  219. for (auto* b : { &guitarButton, &bassButton })
  220. {
  221. b->setClickingTogglesState (true);
  222. b->setRadioGroupId (1184);
  223. guitar.addAndMakeVisible (*b);
  224. }
  225. guitarButton.setToggleState (true, juce::dontSendNotification);
  226. for (auto* c : std::initializer_list<juce::Component*> { &title, &close, &voice, &instrument, &drums, &sampler, &guitar, &import, &loops, &footer })
  227. addAndMakeVisible (*c);
  228. // the starter-beat page
  229. starterTitle.setText (tr ("Starter beat"), juce::dontSendNotification);
  230. starterTitle.setFont (theme::font (theme::type::display, true));
  231. starterTitle.setJustificationType (juce::Justification::centred);
  232. back.setButtonText (juce::String::fromUTF8 ("\xe2\x80\xb9 ") + tr ("Back"));
  233. back.onClick = [this] { showTilesPage(); };
  234. useTempo.setButtonText (tr ("Use the suggested tempo"));
  235. useTempo.setToggleState (true, juce::dontSendNotification);
  236. addDrums.setButtonText (tr ("Add drums"));
  237. addDrums.onClick = [this] {
  238. const auto picked = std::find_if (genreButtons.begin(), genreButtons.end(), [] (const auto& b) { return b->getToggleState(); });
  239. const auto index = picked == genreButtons.end() ? 0 : (int) (picked - genreButtons.begin());
  240. owner.addDrums (index == 0 ? std::string() : genreIds[(std::size_t) index], index != 0, useTempo.getToggleState());
  241. };
  242. for (auto* c : std::initializer_list<juce::Component*> { &starterTitle, &back, &useTempo, &addDrums })
  243. addChildComponent (*c);
  244. }
  245. void showStarterPage()
  246. {
  247. if (genreButtons.empty())
  248. {
  249. // Empty, then Loop Starter's genres (FL's when installed, else LYNX's own) with their suggested tempo
  250. genreIds.push_back ({});
  251. genreButtons.push_back (std::make_unique<juce::TextButton> (tr ("Empty grid")));
  252. if (const auto* config = loopstarterui::sources().config)
  253. for (const auto* genre : config->listed())
  254. {
  255. genreIds.push_back (genre->id);
  256. genreButtons.push_back (std::make_unique<juce::TextButton> (juce::String::fromUTF8 (genre->label.c_str()) + " "
  257. + tr ("{0} BPM", { juce::String (juce::roundToInt (genre->defaultTempo)) })));
  258. }
  259. for (auto& b : genreButtons)
  260. {
  261. b->setClickingTogglesState (true);
  262. b->setRadioGroupId (2184);
  263. addChildComponent (*b);
  264. }
  265. genreButtons[genreButtons.size() > 1 ? 1 : 0]->setToggleState (true, juce::dontSendNotification);
  266. }
  267. starterPage = true;
  268. updatePage();
  269. }
  270. void showTilesPage()
  271. {
  272. starterPage = false;
  273. updatePage();
  274. }
  275. void paint (juce::Graphics& g) override
  276. {
  277. g.fillAll (theme::colour::bg0.withAlpha (0.72f)); // the timeline stays faintly visible behind
  278. const auto c = card().toFloat();
  279. g.setColour (juce::Colours::black.withAlpha (0.35f));
  280. g.fillRoundedRectangle (c.translated (0.0f, 4.0f).expanded (2.0f), theme::radius::lg + 2.0f);
  281. g.setColour (theme::colour::bg2);
  282. g.fillRoundedRectangle (c, theme::radius::lg);
  283. g.setColour (theme::colour::borderStrong);
  284. g.drawRoundedRectangle (c.reduced (0.5f), theme::radius::lg, 1.0f);
  285. g.setColour (theme::colour::accent);
  286. g.fillRect (c.getX() + 24.0f, c.getY() + 52.0f, c.getWidth() - 48.0f, 1.0f);
  287. }
  288. void resized() override
  289. {
  290. auto c = card().reduced (20, 14);
  291. auto top = c.removeFromTop (34);
  292. close.setBounds (top.removeFromRight (28).withSizeKeepingCentre (28, 28));
  293. back.setBounds (top.removeFromLeft (90).withSizeKeepingCentre (90, 28));
  294. title.setBounds (top);
  295. starterTitle.setBounds (top);
  296. c.removeFromTop (16);
  297. footer.setBounds (c.removeFromBottom (20));
  298. c.removeFromBottom (6);
  299. // tiles: two columns, then Guitar / bass across, then Import and Loops
  300. const auto gap = 10;
  301. const auto rowH = juce::jlimit (56, 78, (c.getHeight() - 4 * gap) / 5);
  302. auto tiles = c;
  303. auto row = [&] { auto r = tiles.removeFromTop (rowH); tiles.removeFromTop (gap); return r; };
  304. auto pair = [&] (juce::Component& a, juce::Component& b) {
  305. auto r = row();
  306. a.setBounds (r.removeFromLeft ((r.getWidth() - gap) / 2));
  307. r.removeFromLeft (gap);
  308. b.setBounds (r);
  309. };
  310. pair (voice, instrument);
  311. pair (drums, sampler);
  312. auto g = row();
  313. guitar.setBounds (g);
  314. pair (import, loops);
  315. auto sw = guitar.getLocalBounds().removeFromRight (guitar.rightReserve).reduced (8, 0).withSizeKeepingCentre (guitar.rightReserve - 16, 28);
  316. guitarButton.setBounds (sw.removeFromLeft (sw.getWidth() / 2));
  317. bassButton.setBounds (sw);
  318. // the starter-beat page: genres in three columns, the tempo switch and Add
  319. auto s = card().reduced (20, 14).withTrimmedTop (50);
  320. auto bottom = s.removeFromBottom (34);
  321. addDrums.setBounds (bottom.removeFromRight (140));
  322. useTempo.setBounds (bottom.removeFromLeft (bottom.getWidth() - 10));
  323. s.removeFromBottom (10);
  324. const auto columns = 3, buttonH = 32;
  325. const auto w = (s.getWidth() - (columns - 1) * gap) / columns;
  326. for (int i = 0; i < (int) genreButtons.size(); ++i)
  327. genreButtons[(std::size_t) i]->setBounds (s.getX() + (i % columns) * (w + gap), s.getY() + (i / columns) * (buttonH + 8), w, buttonH);
  328. }
  329. bool keyPressed (const juce::KeyPress& key) override
  330. {
  331. if (key == juce::KeyPress::escapeKey)
  332. {
  333. if (starterPage)
  334. showTilesPage();
  335. else
  336. owner.closeByHand();
  337. return true;
  338. }
  339. return false;
  340. }
  341. // clicks on the dimmed area outside the card close the chooser
  342. void mouseUp (const juce::MouseEvent& e) override
  343. {
  344. if (e.mouseWasClicked() && ! card().contains (e.getPosition()))
  345. owner.closeByHand();
  346. }
  347. private:
  348. juce::Rectangle<int> card() const
  349. {
  350. const auto w = juce::jmin (680, getWidth() - 24), h = juce::jmin (520, getHeight() - 24);
  351. return getLocalBounds().withSizeKeepingCentre (juce::jmax (320, w), juce::jmax (300, h));
  352. }
  353. void updatePage()
  354. {
  355. for (auto* c : std::initializer_list<juce::Component*> { &title, &voice, &instrument, &drums, &sampler, &guitar, &import, &loops, &footer })
  356. c->setVisible (! starterPage);
  357. for (auto* c : std::initializer_list<juce::Component*> { &starterTitle, &back, &useTempo, &addDrums })
  358. c->setVisible (starterPage);
  359. for (auto& b : genreButtons)
  360. b->setVisible (starterPage);
  361. resized();
  362. repaint();
  363. }
  364. SimpleWorkflow& owner;
  365. juce::Label title, footer, starterTitle;
  366. juce::TextButton close, back, addDrums, guitarButton, bassButton;
  367. juce::ToggleButton useTempo;
  368. Tile voice, instrument, drums, sampler, guitar, import, loops;
  369. std::vector<std::unique_ptr<juce::TextButton>> genreButtons;
  370. std::vector<std::string> genreIds;
  371. bool starterPage = false;
  372. friend class SimpleWorkflow;
  373. };
  374. // --- the workflow ------------------------------------------------------------------------------------------------------
  375. namespace
  376. {
  377. // "+ Add track" in the Playlist's title bar
  378. class AddTrackButton final : public juce::TextButton
  379. {
  380. public:
  381. AddTrackButton() : juce::TextButton ("+ " + tr ("Add track"))
  382. {
  383. setTooltip (tr ("Add a track: voice, instrument, drums, sampler, guitar or bass, or import files"));
  384. }
  385. };
  386. } // namespace
  387. SimpleWorkflow::SimpleWorkflow (AudioEngine& e, Host h) : engine (e), host (std::move (h))
  388. {
  389. instances.fetch_add (1, std::memory_order_relaxed);
  390. auto button = std::make_unique<AddTrackButton>();
  391. button->onClick = [this] { showChooser(); };
  392. addButton = std::move (button);
  393. }
  394. SimpleWorkflow::~SimpleWorkflow()
  395. {
  396. if (active)
  397. left();
  398. }
  399. void SimpleWorkflow::entered()
  400. {
  401. active = true;
  402. if (host.setTitleAccessory)
  403. host.setTitleAccessory (addButton.get(), 110);
  404. songChanged();
  405. }
  406. void SimpleWorkflow::left()
  407. {
  408. active = false;
  409. hideChooser();
  410. if (host.setTitleAccessory)
  411. host.setTitleAccessory (nullptr, 0);
  412. }
  413. void SimpleWorkflow::songChanged()
  414. {
  415. if (! active)
  416. return;
  417. const auto& song = engine.getSong();
  418. if (simpletracks::isEmptySong (song))
  419. {
  420. if (song.projectId != dismissedFor && ! isChooserShowing())
  421. showChooser();
  422. }
  423. else if (isChooserShowing() && ! chooser->starterPage)
  424. hideChooser(); // (something was added some other way: an undo, a drop, a loaded project)
  425. }
  426. void SimpleWorkflow::showChooser()
  427. {
  428. if (chooser == nullptr)
  429. chooser = std::make_unique<Chooser> (*this);
  430. chooser->showTilesPage();
  431. if (host.setOverlay)
  432. host.setOverlay (chooser.get());
  433. if (chooser->isShowing())
  434. chooser->grabKeyboardFocus();
  435. }
  436. void SimpleWorkflow::hideChooser()
  437. {
  438. if (chooser != nullptr && chooser->getParentComponent() != nullptr && host.setOverlay)
  439. host.setOverlay (nullptr);
  440. }
  441. bool SimpleWorkflow::isChooserShowing() const noexcept { return chooser != nullptr && chooser->getParentComponent() != nullptr; }
  442. void SimpleWorkflow::closeByHand()
  443. {
  444. dismissedFor = engine.getSong().projectId;
  445. hideChooser();
  446. }
  447. juce::Component* SimpleWorkflow::chooserForSnapshot()
  448. {
  449. if (chooser == nullptr)
  450. chooser = std::make_unique<Chooser> (*this);
  451. return chooser.get();
  452. }
  453. void SimpleWorkflow::showStarterPageForSnapshot()
  454. {
  455. chooserForSnapshot();
  456. chooser->showStarterPage();
  457. }
  458. bool SimpleWorkflow::add (simpletracks::Request request)
  459. {
  460. // tried on a copy first, so a refused track leaves no undo step behind
  461. auto trial = engine.getSong();
  462. if (const auto r = simpletracks::addTrack (trial, request); ! r.ok())
  463. {
  464. const auto text = r.error == simpletracks::Error::mixerFull ? tr ("There are no available mixer tracks.")
  465. : r.error == simpletracks::Error::noFreeTrack ? tr ("No free Playlist track is left.")
  466. : tr ("This sound can't be played as an instrument.");
  467. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("New track"), text);
  468. return false;
  469. }
  470. simpletracks::Result r;
  471. engine.editSong ([&] (Song& s) { r = simpletracks::addTrack (s, request); });
  472. if (! r.ok())
  473. return false;
  474. if (simpletracks::isAudioKind (request.kind) && request.kind != Kind::audio && r.insert > 0)
  475. engine.setInsertArmed (r.insert, true);
  476. if (! r.channels.empty() && ! simpletracks::isAudioKind (request.kind))
  477. engine.setSelectedChannel (r.channels.front());
  478. hideChooser();
  479. if (host.trackAdded)
  480. host.trackAdded (r.track);
  481. return true;
  482. }
  483. void SimpleWorkflow::addAudio (Kind kind)
  484. {
  485. simpletracks::Request q;
  486. q.kind = kind;
  487. q.name = trackNameFor (kind);
  488. q.input = 0; // the device's first input, mono (a microphone or an instrument cable)
  489. q.inputStereo = false;
  490. add (std::move (q));
  491. }
  492. void SimpleWorkflow::chooseInstrument (juce::Component& tile)
  493. {
  494. // the Channel Rack's own generator list (the same instruments, plugins and Soundfonts)
  495. juce::PopupMenu menu;
  496. quickpick::addGeneratorMenu (
  497. menu, engine,
  498. [this] (ChannelDef c) {
  499. simpletracks::Request q;
  500. q.kind = c.instrument == InstrumentKind::sampler ? Kind::sampler : Kind::instrument;
  501. q.name = trackNameFor (q.kind);
  502. q.channel = std::move (c);
  503. add (std::move (q));
  504. },
  505. [this] { chooseSample(); }, nullptr, chooser.get());
  506. quickpick::showMenu (menu, juce::PopupMenu::Options().withTargetComponent (&tile), {});
  507. }
  508. void SimpleWorkflow::chooseSample()
  509. {
  510. fileChooser = ui::makeFileChooser (tr ("Choose sample"), juce::File(), engine.getSampleLibrary().wildcard());
  511. ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  512. [this] (const juce::FileChooser& fc) {
  513. const auto file = fc.getResult();
  514. if (! file.existsAsFile())
  515. return;
  516. if (engine.getSampleLibrary().load (file.getFullPathName()) == nullptr)
  517. {
  518. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"),
  519. tr ("Could not read {0}", { file.getFileName() }));
  520. return;
  521. }
  522. ChannelDef c;
  523. c.instrument = InstrumentKind::sampler;
  524. c.samplePath = file.getFullPathName().toStdString();
  525. simpletracks::Request q;
  526. q.kind = Kind::sampler;
  527. q.name = file.getFileNameWithoutExtension().toStdString();
  528. q.channel = std::move (c);
  529. add (std::move (q));
  530. });
  531. }
  532. void SimpleWorkflow::importFiles()
  533. {
  534. fileChooser = ui::makeFileChooser (tr ("Import audio or MIDI"), juce::File(), engine.getSampleLibrary().wildcard() + ";*.mid;*.midi");
  535. ui::launchChooser (fileChooser,
  536. juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles | juce::FileBrowserComponent::canSelectMultipleItems,
  537. [this] (const juce::FileChooser& fc) {
  538. juce::StringArray failed;
  539. for (const auto& file : fc.getResults())
  540. {
  541. if (file.hasFileExtension ("mid;midi"))
  542. {
  543. // one instrument track (LYNX's synth) per MIDI track with notes, from the song's start
  544. juce::String error;
  545. const auto midi = MidiFileIo::parseFile (file, error);
  546. if (! midi)
  547. {
  548. failed.add (file.getFileName());
  549. continue;
  550. }
  551. midiimport::Options options;
  552. bool any = false;
  553. for (auto& group : midiimport::groups (*midi, options))
  554. {
  555. if (group.notes.empty())
  556. continue;
  557. simpletracks::Request q;
  558. q.kind = Kind::instrument;
  559. q.name = group.name.empty() ? file.getFileNameWithoutExtension().toStdString() : group.name;
  560. ChannelDef synth;
  561. synth.instrument = InstrumentKind::synth;
  562. q.channel = synth;
  563. Pattern notes;
  564. notes.notes = std::move (group.notes);
  565. q.pattern = std::move (notes);
  566. any = add (std::move (q)) || any;
  567. }
  568. if (! any)
  569. failed.add (file.getFileName());
  570. continue;
  571. }
  572. const auto data = engine.getSampleLibrary().load (file.getFullPathName());
  573. if (data == nullptr)
  574. {
  575. failed.add (file.getFileName());
  576. continue;
  577. }
  578. // the file's length in ticks at the project's tempo (as a drop on the Playlist)
  579. const auto seconds = (double) data->frames() / data->sampleRate;
  580. simpletracks::Request q;
  581. q.kind = Kind::audio;
  582. q.name = file.getFileNameWithoutExtension().toStdString();
  583. q.audioFile = file.getFullPathName().toStdString();
  584. q.audioLength = juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) (seconds * engine.getSong().bpm / 60.0 * ppq));
  585. add (std::move (q));
  586. }
  587. if (! failed.isEmpty())
  588. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"),
  589. tr ("Could not read {0}", { failed.joinIntoString (", ") }));
  590. });
  591. }
  592. void SimpleWorkflow::addDrums (const std::string& genre, bool steps, bool useTempo)
  593. {
  594. // a Loop Starter plan for the genre (FL's configuration and presets when installed, else LYNX's own); an empty grid
  595. // takes the default genre's kit without its steps
  596. const auto& sources = loopstarterui::sources();
  597. if (sources.config == nullptr)
  598. return;
  599. const auto id = genre.empty() ? sources.config->defaultGenre : genre;
  600. const auto plan = loopstarter::generate (sources, id, (std::uint64_t) juce::Random::getSystemRandom().nextInt64());
  601. simpletracks::Request q;
  602. q.kind = Kind::drums;
  603. q.name = trackNameFor (Kind::drums);
  604. q.kit = loopstarter::kitChannels (plan);
  605. auto pattern = loopstarter::kitPattern (plan);
  606. if (! steps)
  607. {
  608. pattern.notes.clear();
  609. pattern.lengthTicks = 16 * ticksPerStep;
  610. }
  611. q.pattern = std::move (pattern);
  612. if (q.kit.empty())
  613. return;
  614. if (useTempo && steps)
  615. q.bpm = plan.bpm; // (in the same undo step as the track)
  616. add (std::move (q));
  617. }
  618. } // namespace lynx