Main.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  1. #include <juce_gui_basics/juce_gui_basics.h>
  2. #include "core/Effects.h"
  3. #include "core/SynthPresets.h"
  4. #include "core/FlWrapper.h"
  5. #include "engine/AudioEngine.h"
  6. #include "engine/Exporter.h"
  7. #include "engine/MidiFileIo.h"
  8. #include "engine/PluginHost.h"
  9. #include "engine/PluginSandbox.h"
  10. #include "engine/ProjectFile.h"
  11. #include "engine/SampleLibrary.h"
  12. #include "engine/Text.h"
  13. #include "platform/FileTypes.h"
  14. #include "ui/AutomationUi.h"
  15. #include "ui/ChannelSettings.h"
  16. #include "ui/Dialogs.h"
  17. #include "core/RackOps.h"
  18. #include "ui/ExportDialog.h"
  19. #include "ui/I18n.h"
  20. #include "ui/MainComponent.h"
  21. #include "ui/ParametricEqEditor.h"
  22. #include "ui/Splash.h"
  23. #include "ui/Theme.h"
  24. #include "ui/WindowOwner.h"
  25. namespace
  26. {
  27. lynx::AudioEngine* crashEngine = nullptr;
  28. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  29. void onCrash (void*)
  30. {
  31. const auto folder = juce::File::getSpecialLocation (juce::File::userApplicationDataDirectory).getChildFile ("LYNX/autosave");
  32. folder.createDirectory();
  33. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  34. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace());
  35. if (crashEngine != nullptr)
  36. {
  37. juce::String error;
  38. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  39. }
  40. }
  41. } // namespace
  42. class LynxApplication final : public juce::JUCEApplication
  43. {
  44. public:
  45. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  46. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  47. // the plugin scan runs copies of LYNX as child processes
  48. bool moreThanOneInstanceAllowed() override { return true; }
  49. void initialise (const juce::String& commandLine) override
  50. {
  51. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
  52. juce::SystemStats::setApplicationCrashHandler (onCrash);
  53. // child process of a sandboxed plugin: no window or audio of its own
  54. if (lynx::runPluginSandboxWorker (commandLine))
  55. return;
  56. const auto args = juce::StringArray::fromTokens (commandLine, true);
  57. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  58. lynx::i18n::initialise (args);
  59. if (args.contains ("--showcase"))
  60. {
  61. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  62. const auto i = args.indexOf ("--showcase");
  63. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  64. return;
  65. }
  66. if (args.contains ("--sandboxtest"))
  67. {
  68. const auto i = args.indexOf ("--sandboxtest");
  69. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  70. return;
  71. }
  72. if (args.contains ("--selftest"))
  73. {
  74. const auto i = args.indexOf ("--selftest");
  75. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  76. return;
  77. }
  78. if (args.contains ("--scan-one"))
  79. {
  80. // child process of the plugin scan (see PluginHost::scan)
  81. const auto i = args.indexOf ("--scan-one");
  82. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  83. setApplicationReturnValue (0);
  84. quit();
  85. return;
  86. }
  87. if (args.contains ("--paths"))
  88. {
  89. // diagnostics: folders LYNX searches
  90. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  91. juce::String report;
  92. report << "programs=" << programs.getFullPathName() << "\n";
  93. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  94. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  95. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  96. quit();
  97. return;
  98. }
  99. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  100. {
  101. // diagnostics: driver types and output devices JUCE offers (without opening any)
  102. juce::AudioDeviceManager manager;
  103. juce::String report;
  104. for (auto* type : manager.getAvailableDeviceTypes())
  105. {
  106. type->scanForDevices();
  107. report << "type=" << type->getTypeName() << "\n";
  108. for (const auto& name : type->getDeviceNames (false))
  109. report << " output=" << name << "\n";
  110. }
  111. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  112. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  113. quit();
  114. return;
  115. }
  116. if (args.contains ("--devicetest"))
  117. {
  118. // LYNX.exe --devicetest "type" "device" report.txt: opens that output device, receives 1 s of callbacks
  119. // writing silence, closes it and reports rate, block size, latency and callbacks (driver check, no sound)
  120. const auto i = args.indexOf ("--devicetest");
  121. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  122. juce::String report;
  123. const juce::File reportFile (args[i + 3].unquoted());
  124. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  125. step ("step=start");
  126. juce::AudioDeviceManager manager;
  127. std::unique_ptr<juce::AudioIODevice> device;
  128. for (auto* type : manager.getAvailableDeviceTypes())
  129. if (type->getTypeName() == typeName)
  130. {
  131. type->scanForDevices();
  132. step ("step=create");
  133. device.reset (type->createDevice (deviceName, {}));
  134. step ("step=created");
  135. }
  136. struct Silence final : juce::AudioIODeviceCallback
  137. {
  138. std::atomic<int> calls { 0 };
  139. void audioDeviceIOCallbackWithContext (const float* const*, int, float* const* out, int channels, int n,
  140. const juce::AudioIODeviceCallbackContext&) override
  141. {
  142. for (int c = 0; c < channels; ++c)
  143. if (out[c] != nullptr)
  144. juce::FloatVectorOperations::clear (out[c], n);
  145. ++calls;
  146. }
  147. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  148. void audioDeviceStopped() override {}
  149. } silence;
  150. bool ok = false;
  151. if (device == nullptr)
  152. step ("error=device not found");
  153. else
  154. {
  155. step ("step=open");
  156. juce::BigInteger outputs;
  157. outputs.setRange (0, 2, true);
  158. const auto rates = device->getAvailableSampleRates();
  159. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  160. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  161. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  162. const auto error = device->open ({}, outputs, rate, device->getDefaultBufferSize());
  163. if (error.isNotEmpty())
  164. step ("error=" + error);
  165. else
  166. {
  167. step ("step=start_callbacks");
  168. device->start (&silence);
  169. juce::Thread::sleep (1000);
  170. device->stop();
  171. report << "rate=" << device->getCurrentSampleRate() << "\n"
  172. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  173. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  174. << "callbacks=" << silence.calls.load() << "\n";
  175. ok = silence.calls.load() > 0;
  176. device->close();
  177. }
  178. }
  179. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  180. setApplicationReturnValue (ok ? 0 : 1);
  181. quit();
  182. return;
  183. }
  184. if (args.contains ("--scantest"))
  185. {
  186. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  187. const auto i = args.indexOf ("--scantest");
  188. lynx::PluginHost host (false);
  189. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  190. juce::String report;
  191. report << "found=" << found << "\n";
  192. for (const auto& t : host.getKnownPlugins().getTypes())
  193. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  194. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  195. report << " blacklisted: " << f << "\n";
  196. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  197. setApplicationReturnValue (found > 0 ? 0 : 1);
  198. quit();
  199. return;
  200. }
  201. if (args.contains ("--wrappertest"))
  202. {
  203. const auto i = args.indexOf ("--wrappertest");
  204. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  205. return;
  206. }
  207. if (args.contains ("--plugintest"))
  208. {
  209. const auto i = args.indexOf ("--plugintest");
  210. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  211. return;
  212. }
  213. if (args.contains ("--snapshot"))
  214. {
  215. const auto i = args.indexOf ("--snapshot");
  216. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  217. return;
  218. }
  219. if (args.contains ("--stems"))
  220. {
  221. // LYNX.exe --stems project base.wav: one WAV per insert that has sound (like "Export stems")
  222. const auto i = args.indexOf ("--stems");
  223. juce::String error, report;
  224. int written = 0;
  225. {
  226. lynx::AudioEngine loader (false);
  227. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  228. auto ok = input.hasFileExtension ("flp") ? loader.importFlpFile (input, error) : false;
  229. if (! input.hasFileExtension ("flp"))
  230. if (auto song = lynx::ProjectFile::load (input, error))
  231. {
  232. loader.setSong (std::move (*song));
  233. ok = true;
  234. }
  235. const auto& song = loader.getSong();
  236. for (int t = 1; ok && t < (int) song.mixer.size(); ++t)
  237. {
  238. if (std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  239. continue;
  240. const auto file = base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav");
  241. lynx::ExportSettings settings;
  242. lynx::ExportJob job (lynx::makeBounceSong (song, t), settings, file);
  243. if (job.run ({}, error))
  244. {
  245. ++written;
  246. report << file.getFileName() << " peak=" << job.getPeak() << "\n";
  247. }
  248. }
  249. }
  250. report << "stems=" << written << "\n";
  251. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  252. setApplicationReturnValue (written > 0 ? 0 : 1);
  253. quit();
  254. return;
  255. }
  256. if (args.contains ("--export"))
  257. {
  258. const auto i = args.indexOf ("--export");
  259. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  260. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  261. return;
  262. }
  263. if (args.contains ("--render"))
  264. {
  265. const auto i = args.indexOf ("--render");
  266. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  267. return;
  268. }
  269. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  270. startupOptions = lynx::StartupOptions::load();
  271. lynx::registerFileTypes();
  272. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument.
  273. if (args.size() > 0 && juce::File::isAbsolutePath (args[0].unquoted()))
  274. fileToOpen = juce::File (args[0].unquoted());
  275. if (! startupOptions.splash)
  276. {
  277. startEngine();
  278. createMainWindow();
  279. mainWindow->reveal();
  280. openStartupFile();
  281. return;
  282. }
  283. // the splash first, so it is on screen while the audio device opens; the main window is built
  284. // once the pepper has landed (the scene is still for a moment then) and shown when the splash ends
  285. splash = std::make_unique<lynx::SplashScreen>();
  286. splash->showOnDesktop();
  287. juce::Timer::callAfterDelay (40, [this] {
  288. startEngine();
  289. if (splash == nullptr) // quit meanwhile
  290. return;
  291. splash->setStatus (lynx::tr ("Loading the workspace..."));
  292. splash->startClock();
  293. juce::Timer::callAfterDelay (1050, [this] {
  294. if (splash == nullptr || engine == nullptr)
  295. return;
  296. createMainWindow();
  297. const auto wait = juce::jmax (0.0, lynx::SplashScreen::minimumDuration - splash->getElapsed());
  298. juce::Timer::callAfterDelay ((int) (wait * 1000.0), [this] {
  299. if (splash == nullptr || mainWindow == nullptr)
  300. return;
  301. mainWindow->reveal();
  302. splash->toFront (false);
  303. splash->finish ([this] { splash = nullptr; });
  304. openStartupFile();
  305. });
  306. });
  307. });
  308. }
  309. void startEngine()
  310. {
  311. engine = std::make_unique<lynx::AudioEngine>();
  312. crashEngine = engine.get();
  313. if (startupOptions.sound)
  314. engine->previewSample (lynx::makeStartupSample());
  315. }
  316. void createMainWindow()
  317. {
  318. mainWindow = std::make_unique<MainWindow> (getApplicationName(), *engine);
  319. lynx::setMainWindowForOwnership (mainWindow.get());
  320. }
  321. void openStartupFile()
  322. {
  323. if (fileToOpen != juce::File() && mainWindow != nullptr)
  324. mainWindow->openFile (fileToOpen);
  325. }
  326. void shutdown() override
  327. {
  328. lynx::shutdownPluginSandboxWorker();
  329. splash = nullptr;
  330. mainWindow = nullptr; // the UI goes before the engine
  331. crashEngine = nullptr;
  332. engine = nullptr;
  333. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  334. }
  335. void systemRequestedQuit() override
  336. {
  337. if (mainWindow != nullptr)
  338. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  339. else
  340. quit();
  341. }
  342. private:
  343. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  344. // Exit code 0 = audio came out, 1 = silence.
  345. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  346. {
  347. lynx::AudioEngine offline (false);
  348. const auto peak = offline.renderOffline (2.0, 48000.0);
  349. const auto audioOk = peak > 0.01f && peak < 10.0f;
  350. // project format round trip, with accents in the name
  351. auto original = lynx::Song::makeDefault();
  352. original.channels[0].name = "Bumbo ação";
  353. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  354. original.mode = lynx::PlayMode::song;
  355. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  356. original.mixer[3].effects[0].params[1] = 0.25f;
  357. lynx::Automation automation;
  358. automation.name = "Pan";
  359. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  360. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  361. original.automations.push_back (automation);
  362. lynx::Clip automationClip;
  363. automationClip.kind = lynx::ClipKind::automation;
  364. automationClip.automation = 0;
  365. automationClip.track = 4;
  366. automationClip.length = 3840;
  367. original.playlist.push_back (automationClip);
  368. original.loopStart = 960;
  369. original.loopEnd = 7680;
  370. juce::String error;
  371. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  372. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  373. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  374. const auto projectOk = reloaded && reloaded->channels.size() == original.channels.size()
  375. && reloaded->channels[0].name == original.channels[0].name
  376. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  377. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  378. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  379. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  380. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  381. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  382. && reloaded->automations[0].points[1].tick == 3840
  383. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  384. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  385. && reloaded->mixer[3].effects.size() == 1
  386. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  387. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  388. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  389. auto rich = lynx::Song::makeDefault();
  390. auto& synth = rich.channels[4].synth;
  391. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  392. synth.filterType = 2;
  393. synth.mono = true;
  394. synth.portaBeats = 0.125f;
  395. synth.am = true;
  396. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  397. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  398. auto& sampler = rich.channels[0].sampler;
  399. sampler.cutoff = 1200.0f;
  400. sampler.resonance = 0.3f;
  401. sampler.filterType = 1;
  402. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  403. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  404. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  405. rich.mixer[2].eq.hz[1] = 2200.0f;
  406. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  407. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  408. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  409. rich.mixer[2].effects.push_back (peqSlot);
  410. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  411. utilitySlot.params[1] = 0.2f;
  412. rich.mixer[2].effects.push_back (utilitySlot);
  413. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  414. for (int i = 0; i < 300; ++i)
  415. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  416. vocodexSlot.sidechain = 1;
  417. vocodexSlot.sidechain2 = 2;
  418. rich.mixer[3].effects.push_back (vocodexSlot);
  419. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  420. rich.addMarker ({ 7680, {}, 7, 8 });
  421. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  422. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  423. for (std::size_t i = 0; i < a.size(); ++i)
  424. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  425. return false;
  426. return true;
  427. };
  428. const auto richOk = richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  429. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  430. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  431. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  432. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  433. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  434. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  435. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  436. && richBack->markers() == rich.markers();
  437. // undo/redo
  438. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  439. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  440. offline.undo();
  441. const auto afterUndo = offline.getSong().bpm;
  442. offline.redo();
  443. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  444. && offline.isModified();
  445. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  446. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  447. offline.setRecording (true);
  448. offline.play();
  449. offline.getTransport().positionTicks.store (960.0);
  450. offline.sendLiveNote (2, 72, 0.9f, true, true);
  451. offline.getTransport().positionTicks.store (1920.0);
  452. offline.sendLiveNote (2, 72, 0.0f, false, true);
  453. offline.setRecording (false);
  454. offline.stop();
  455. const auto& recorded = offline.getSong().patterns[0].notes;
  456. const auto recordOk = recorded.size() == notesBefore + 1
  457. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  458. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  459. });
  460. offline.undo();
  461. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  462. // MIDI: exporting the pattern and importing it back gives the same notes
  463. bool midiOk = false;
  464. {
  465. auto source = lynx::Song::makeDefault();
  466. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  467. source.patterns[0].sortNotes();
  468. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  469. juce::String midiError;
  470. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  471. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  472. midiFile.deleteFile();
  473. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  474. && std::abs (song->bpm - source.bpm) < 0.01)
  475. {
  476. midiOk = true;
  477. const auto& a = source.patterns[0].notes;
  478. const auto& b = song->patterns[0].notes;
  479. for (std::size_t i = 0; i < a.size(); ++i)
  480. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  481. }
  482. }
  483. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  484. juce::String wavpack = "NO_FL";
  485. {
  486. const auto roots = lynx::findFlStudioRoots();
  487. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  488. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  489. if (! found.isEmpty())
  490. {
  491. lynx::SampleLibrary library;
  492. const auto sample = library.load (found.getFirst().getFullPathName());
  493. float peakWv = 0.0f;
  494. if (sample != nullptr)
  495. for (std::size_t i = 0; i < sample->frames(); ++i)
  496. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  497. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  498. }
  499. }
  500. const auto ok = audioOk && projectOk && richOk && undoOk && recordOk && recordUndoOk && midiOk && wavpack != "ERROR";
  501. juce::String report;
  502. report << "connections=" << offline.getNumGraphConnections() << "\n"
  503. << "peak=" << peak << "\n"
  504. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  505. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  506. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  507. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  508. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  509. << "wavpack=" << wavpack << "\n"
  510. << "result=" << (ok ? "OK" : "FAILED") << "\n";
  511. if (reportPath.isNotEmpty())
  512. juce::File (reportPath).replaceWithText (report);
  513. setApplicationReturnValue (ok ? 0 : 1);
  514. quit();
  515. }
  516. // LYNX.exe --plugintest plugin.vst3 report.txt: loads the plugin, plays notes if it is an
  517. // instrument (and runs audio through it if it is an effect) and measures the audio.
  518. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath)
  519. {
  520. juce::String report;
  521. bool ok = false;
  522. {
  523. lynx::AudioEngine offline (false);
  524. auto& host = offline.getPluginHost();
  525. const auto added = host.addPluginFile (juce::File (pluginPath));
  526. report << "plugins_in_file=" << added << "\n";
  527. juce::PluginDescription instrument, effect;
  528. bool hasInstrument = false, hasEffect = false;
  529. for (const auto& type : host.getKnownPlugins().getTypes())
  530. {
  531. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  532. continue;
  533. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  534. << ") in " << type.fileOrIdentifier << "\n";
  535. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  536. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  537. }
  538. auto song = lynx::Song::makeDefault();
  539. if (hasInstrument)
  540. {
  541. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  542. c.instrument = lynx::InstrumentKind::plugin;
  543. c.plugin.id = instrument.createIdentifierString().toStdString();
  544. c.plugin.name = instrument.name.toStdString();
  545. c.volume = 1.0f;
  546. for (int i = 0; i < 4; ++i) // one chord per beat
  547. for (int key : { 60, 64, 67 })
  548. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  549. song.patterns[0].sortNotes();
  550. }
  551. if (hasEffect)
  552. {
  553. lynx::EffectSlot slot;
  554. slot.kind = lynx::EffectKind::plugin;
  555. slot.plugin.id = effect.createIdentifierString().toStdString();
  556. slot.plugin.name = effect.name.toStdString();
  557. song.mixer[0].effects.push_back (slot);
  558. }
  559. offline.setSong (song);
  560. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  561. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, 0).get());
  562. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  563. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  564. const auto peak = offline.renderOffline (3.0, 48000.0);
  565. report << "peak=" << peak << "\n";
  566. offline.capturePluginStates();
  567. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  568. report << "state_bytes_base64=" << (int) stateSize << "\n";
  569. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  570. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  571. }
  572. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  573. juce::File (reportPath).replaceWithText (report);
  574. setApplicationReturnValue (ok ? 0 : 1);
  575. quit();
  576. }
  577. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  578. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  579. // that the plugin comes back with the changed parameter.
  580. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  581. {
  582. juce::String report;
  583. bool ok = false;
  584. {
  585. lynx::AudioEngine offline (false);
  586. auto& host = offline.getPluginHost();
  587. host.addPluginFile (juce::File (pluginPath));
  588. const juce::PluginDescription* vst3 = nullptr;
  589. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  590. for (const auto& type : types)
  591. if (type.pluginFormatName == "VST3" && type.isInstrument)
  592. vst3 = &type;
  593. if (vst3 != nullptr)
  594. {
  595. juce::String error;
  596. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  597. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  598. if (parameter != nullptr)
  599. {
  600. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  601. parameter->setValueNotifyingHost (target);
  602. juce::MemoryBlock juceState;
  603. plugin->getStateInformation (juceState);
  604. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  605. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  606. std::vector<std::uint8_t> flState;
  607. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  608. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  609. put32 (id);
  610. put32 ((std::uint32_t) data.getSize());
  611. put32 (0);
  612. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  613. };
  614. put32 (1);
  615. record (1, juce::MemoryBlock (64, true));
  616. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  617. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  618. juce::MemoryBlock slots;
  619. const auto paramId = [&] (int i) {
  620. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  621. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  622. };
  623. const bool reorder = plugin->getParameters().size() >= 3;
  624. if (reorder)
  625. {
  626. for (auto v : { 2u, paramId (2), paramId (0) })
  627. slots.append (&v, 4);
  628. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  629. }
  630. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  631. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  632. if (auto* child = xml->getChildByName (tag))
  633. {
  634. juce::MemoryBlock data;
  635. data.fromBase64Encoding (child->getAllSubText());
  636. record (id, data);
  637. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  638. }
  639. if (reorder)
  640. record (4, slots);
  641. plugin.reset();
  642. auto song = lynx::Song::makeDefault();
  643. auto& f = song.channels[4].plugin.foreign;
  644. f.format = lynx::ForeignPlugin::Format::vst3;
  645. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  646. f.state = flState;
  647. {
  648. std::vector<std::uint8_t> comp, ctrl;
  649. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  650. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  651. }
  652. for (int k = 0; k < 3; ++k)
  653. {
  654. lynx::Automation a;
  655. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  656. song.automations.push_back (a);
  657. }
  658. const auto adopted = host.adoptFlPlugins (song);
  659. report << "adopted=" << adopted << "\n";
  660. juce::String mapped;
  661. for (const auto& a : song.automations)
  662. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  663. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  664. report << "slot_positions=" << mapped << "\n";
  665. const auto slotsOk = ! reorder || mapped == "2,0,1";
  666. offline.setSong (song);
  667. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  668. {
  669. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  670. report << "restored_value=" << value << "\n";
  671. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  672. }
  673. }
  674. }
  675. }
  676. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  677. juce::File (reportPath).replaceWithText (report);
  678. setApplicationReturnValue (ok ? 0 : 1);
  679. quit();
  680. }
  681. void runShowcase (const juce::String& outputPath, int currentPattern)
  682. {
  683. using namespace lynx;
  684. Song song;
  685. song.bpm = 124.0;
  686. song.mixer = Song::defaultMixer();
  687. const auto presets = synthPresets();
  688. auto preset = [&] (const char* name) {
  689. for (const auto& [n, sset] : presets)
  690. if (n == name)
  691. return sset;
  692. return SynthSettings {};
  693. };
  694. auto channel = [&] (const char* name, InstrumentKind kind, float volume, int track, std::uint32_t colour) {
  695. ChannelDef c;
  696. c.name = name;
  697. c.instrument = kind;
  698. c.volume = volume;
  699. c.mixerTrack = track;
  700. c.colour = colour;
  701. song.channels.push_back (c);
  702. return (int) song.channels.size() - 1;
  703. };
  704. const auto kick = channel ("Kick", InstrumentKind::kick, 0.9f, 1, 0xffd9534f);
  705. const auto clap = channel ("Clap", InstrumentKind::clap, 0.75f, 2, 0xfff0ad4e);
  706. const auto hat = channel ("Hat", InstrumentKind::hat, 0.6f, 3, 0xfff7d774);
  707. const auto snare = channel ("Snare", InstrumentKind::snare, 0.7f, 4, 0xffe8835a);
  708. const auto bass = channel ("Reese Bass", InstrumentKind::synth, 0.8f, 5, 0xff5bc0de);
  709. song.channels[(std::size_t) bass].synth = preset ("Reese Bass"); // preset name as defined in core/SynthPresets
  710. const auto pad = channel ("Pad", InstrumentKind::synth, 0.7f, 6, 0xff9b7fd6);
  711. song.channels[(std::size_t) pad].synth = preset ("Pad");
  712. const auto pluck = channel ("Pluck", InstrumentKind::synth, 0.72f, 7, 0xff5cb85c);
  713. song.channels[(std::size_t) pluck].synth = preset ("Pluck");
  714. const auto lead = channel ("Supersaw", InstrumentKind::synth, 0.6f, 8, 0xff4fc3a1);
  715. song.channels[(std::size_t) lead].synth = preset ("Supersaw");
  716. auto addPattern = [&] (const char* name, std::uint32_t colour) {
  717. auto& p = song.patterns.emplace_back();
  718. p.name = name;
  719. p.colour = colour;
  720. return (int) song.patterns.size() - 1;
  721. };
  722. auto note = [&] (int pattern, int ch, double beat, double beats, int key, float velocity = 0.8f) {
  723. Note n;
  724. n.channel = ch;
  725. n.start = (std::int64_t) (beat * ppq);
  726. n.length = (std::int64_t) (beats * ppq);
  727. n.key = key;
  728. n.velocity = velocity;
  729. song.patterns[(std::size_t) pattern].notes.push_back (n);
  730. };
  731. const auto beat = addPattern ("Beat", 0xffd9534f);
  732. for (int s = 0; s < 16; s += 4)
  733. song.patterns[(std::size_t) beat].toggleStep (kick, s);
  734. for (int s : { 4, 12 })
  735. song.patterns[(std::size_t) beat].toggleStep (clap, s);
  736. for (int s = 2; s < 16; s += 4)
  737. song.patterns[(std::size_t) beat].toggleStep (hat, s);
  738. for (int s : { 7, 15 })
  739. song.patterns[(std::size_t) beat].toggleStep (snare, s);
  740. const auto groove = addPattern ("Groove", 0xfff0ad4e);
  741. for (int s = 0; s < 16; ++s)
  742. song.patterns[(std::size_t) groove].toggleStep (hat, s);
  743. for (int s : { 4, 12 })
  744. song.patterns[(std::size_t) groove].toggleStep (clap, s);
  745. // Am – F – C – G, one bar each
  746. const int roots[4] = { 45, 41, 48, 43 };
  747. const int chords[4][3] = { { 57, 60, 64 }, { 53, 57, 60 }, { 55, 60, 64 }, { 55, 59, 62 } };
  748. const auto bassline = addPattern ("Bass", 0xff5bc0de);
  749. for (int bar = 0; bar < 4; ++bar)
  750. for (int e = 0; e < 8; ++e)
  751. if (e != 3)
  752. note (bassline, bass, bar * 4 + e * 0.5, 0.4, roots[bar] - 12 + (e == 6 ? 12 : 0), e % 2 == 0 ? 0.9f : 0.65f);
  753. const auto chordsPattern = addPattern ("Chords", 0xff9b7fd6);
  754. for (int bar = 0; bar < 4; ++bar)
  755. for (int k = 0; k < 3; ++k)
  756. note (chordsPattern, pad, bar * 4, 3.9, chords[bar][k], 0.7f);
  757. const auto melody = addPattern ("Melody", 0xff5cb85c);
  758. const int line[] = { 69, 72, 76, 74, 72, 69, 67, 69, 65, 69, 72, 74, 72, 69, 67, 64,
  759. 72, 76, 79, 76, 74, 72, 74, 76, 71, 74, 79, 78, 76, 74, 71, 67 };
  760. for (int k = 0; k < 32; ++k)
  761. if (k % 8 != 7)
  762. note (melody, pluck, k * 0.5, k % 4 == 3 ? 0.9 : 0.4, line[k], k % 2 == 0 ? 0.85f : 0.65f);
  763. const auto hook = addPattern ("Hook", 0xff4fc3a1);
  764. for (int bar = 0; bar < 4; ++bar)
  765. for (int k = 0; k < 3; ++k)
  766. note (hook, lead, bar * 4 + k * 1.5, k == 2 ? 1.0 : 1.4, chords[bar][2] + 12 - k * 3, 0.8f);
  767. // Playlist: intro, verse, drop, breakdown, final drop
  768. song.playlistTracks = { { "Drums" }, { "Groove" }, { "Bass" }, { "Chords" }, { "Melody" }, { "Hook" }, { "Automation" } };
  769. const auto bar = (std::int64_t) ppq * 4;
  770. auto clip = [&] (int pattern, int track, int fromBar, int bars) {
  771. const auto length = song.patterns[(std::size_t) pattern].effectiveLength (song.beatsPerBar);
  772. for (int b = fromBar; b < fromBar + bars;)
  773. {
  774. Clip c;
  775. c.pattern = pattern;
  776. c.track = track;
  777. c.start = b * bar;
  778. c.length = length;
  779. song.playlist.push_back (c);
  780. b += (int) std::max<std::int64_t> (1, length / bar);
  781. }
  782. };
  783. clip (chordsPattern, 3, 0, 8);
  784. clip (melody, 4, 4, 4);
  785. clip (beat, 0, 8, 16);
  786. clip (groove, 1, 12, 12);
  787. clip (bassline, 2, 8, 8);
  788. clip (melody, 4, 8, 8);
  789. clip (chordsPattern, 3, 16, 4);
  790. clip (bassline, 2, 20, 4);
  791. clip (hook, 5, 20, 4);
  792. clip (melody, 4, 20, 4);
  793. song.addMarker ({ 0, "Intro" });
  794. song.addMarker ({ 8 * bar, "Drop" });
  795. song.addMarker ({ 16 * bar, "Breakdown" });
  796. song.addMarker ({ 20 * bar, "Final" });
  797. // automation: the pad volume opens up during the intro
  798. Automation a;
  799. a.name = "Pad Volume";
  800. a.target = { AutomationTargetKind::mixerVolume, 6, 0, 0 };
  801. a.points = { { 0, 0.15f, 0.4f }, { 8 * bar, 0.8f, 0.0f } };
  802. song.automations.push_back (a);
  803. Clip ac;
  804. ac.kind = ClipKind::automation;
  805. ac.automation = 0;
  806. ac.track = 6;
  807. ac.start = 0;
  808. ac.length = 8 * bar;
  809. song.playlist.push_back (ac);
  810. // mixer: names, colours and effects (bass compressor sidechained to the kick)
  811. const char* names[] = { "Master", "Kick", "Clap", "Hat", "Snare", "Bass", "Pad", "Pluck", "Lead" };
  812. for (int t = 0; t < 9; ++t)
  813. {
  814. song.mixer[(std::size_t) t].name = names[t];
  815. if (t > 0)
  816. song.mixer[(std::size_t) t].colour = song.channels[(std::size_t) t - 1].colour;
  817. }
  818. auto fx = [&] (int track, EffectKind kind) -> EffectSlot& {
  819. song.mixer[(std::size_t) track].effects.push_back (makeEffectSlot (kind));
  820. return song.mixer[(std::size_t) track].effects.back();
  821. };
  822. {
  823. // kick EQ: cut below 30 Hz, weight at 60 Hz, remove the "boxiness" at 350 Hz, brightness at 4 kHz
  824. auto& eq = fx (1, EffectKind::parametricEq);
  825. auto band = [&] (int b, peq::BandType type, double hz, double db, double q) {
  826. eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (type);
  827. eq.params[(std::size_t) peq::param (b, 1)] = peq::hzValue (hz);
  828. eq.params[(std::size_t) peq::param (b, 2)] = peq::gainValue (db);
  829. eq.params[(std::size_t) peq::param (b, 3)] = peq::qValue (q);
  830. };
  831. band (0, peq::BandType::lowCut, 30.0, 0.0, 0.7);
  832. band (1, peq::BandType::peak, 62.0, 5.0, 1.2);
  833. band (2, peq::BandType::peak, 350.0, -6.0, 2.0);
  834. band (3, peq::BandType::peak, 4200.0, 3.5, 1.5);
  835. band (4, peq::BandType::highCut, 14000.0, 0.0, 0.7);
  836. for (int b = 5; b < peq::bands; ++b)
  837. eq.params[(std::size_t) peq::param (b, 0)] = peq::typeValue (peq::BandType::off);
  838. }
  839. fx (1, EffectKind::distortion).mix = 0.3f;
  840. auto& comp = fx (5, EffectKind::compressor);
  841. comp.params[0] = 0.55f;
  842. comp.params[1] = 0.8f;
  843. comp.sidechain = 1;
  844. fx (5, EffectKind::parametricEq);
  845. fx (6, EffectKind::chorus);
  846. fx (6, EffectKind::reverb);
  847. fx (7, EffectKind::delay);
  848. fx (7, EffectKind::reverb).mix = 0.4f;
  849. fx (8, EffectKind::effector);
  850. fx (8, EffectKind::delay);
  851. fx (0, EffectKind::parametricEq);
  852. auto& limiter = fx (0, EffectKind::limiter);
  853. limiter.params = { 11.7f / 12.0f, 0.1f, 0.5f };
  854. song.mixer[1].volume = 0.78f;
  855. song.mixer[5].volume = 0.72f;
  856. song.mixer[6].volume = 0.6f;
  857. song.mixer[6].pan = -0.2f;
  858. song.mixer[7].pan = 0.25f;
  859. song.mode = PlayMode::song;
  860. song.currentPattern = std::clamp (currentPattern, 0, (int) song.patterns.size() - 1);
  861. juce::String error;
  862. const auto ok = ProjectFile::save (song, juce::File (outputPath), error);
  863. setApplicationReturnValue (ok ? 0 : 1);
  864. quit();
  865. }
  866. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  867. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  868. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  869. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  870. {
  871. juce::String report;
  872. bool ok = false;
  873. lynx::setPluginSandboxAlerts (false);
  874. const juce::File log (reportPath + ".log");
  875. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  876. log.deleteFile();
  877. {
  878. lynx::PluginHost host (false);
  879. host.addPluginFile (juce::File (pluginPath));
  880. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  881. const juce::PluginDescription* instrument = nullptr;
  882. for (const auto& type : types)
  883. if (type.isInstrument)
  884. instrument = &type;
  885. step ("host");
  886. juce::String error;
  887. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  888. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  889. step ("created");
  890. if (remote != nullptr)
  891. {
  892. auto& proxy = *remote;
  893. lynx::PluginInstrument voice (std::move (remote), 512);
  894. std::vector<float> l (48000), r (48000);
  895. auto peakOf = [&] {
  896. float peak = 0.0f;
  897. for (std::size_t k = 0; k < l.size(); ++k)
  898. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  899. return peak;
  900. };
  901. const auto start = juce::Time::getMillisecondCounterHiRes();
  902. voice.noteOn (60, 0.9f);
  903. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  904. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  905. const auto peak = peakOf();
  906. step ("played");
  907. report << "parameters=" << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  908. // parameter -> state -> in-process plugin
  909. bool stateOk = false;
  910. if (! proxy.getParameters().isEmpty())
  911. {
  912. auto* p = proxy.getParameters()[0];
  913. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  914. p->setValue (target);
  915. std::fill (l.begin(), l.end(), 0.0f);
  916. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  917. juce::MemoryBlock state;
  918. proxy.getStateInformation (state);
  919. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  920. {
  921. local->setStateInformation (state.getData(), (int) state.getSize());
  922. const auto back = local->getParameters()[0]->getValue();
  923. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << "\n";
  924. stateOk = std::abs (back - target) < 0.02f;
  925. }
  926. }
  927. step ("state");
  928. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  929. lynx::hangSandboxedPluginForTest (proxy);
  930. juce::Thread::sleep (200);
  931. std::fill (l.begin(), l.end(), 1.0f);
  932. std::fill (r.begin(), r.end(), 1.0f);
  933. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  934. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  935. std::fill (l.begin(), l.end(), 0.0f);
  936. std::fill (r.begin(), r.end(), 0.0f);
  937. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  938. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  939. const auto dead = lynx::isSandboxedPluginDead (proxy);
  940. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  941. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && peakOf() == 0.0f;
  942. }
  943. }
  944. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  945. juce::File (reportPath).replaceWithText (report);
  946. setApplicationReturnValue (ok ? 0 : 1);
  947. quit();
  948. }
  949. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  950. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  951. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  952. {
  953. lynx::AudioEngine offline (false);
  954. const juce::File input (inputPath);
  955. juce::String error, report;
  956. bool ok = false;
  957. if (input.hasFileExtension ("flp"))
  958. ok = offline.importFlpFile (input, error);
  959. else if (auto song = lynx::ProjectFile::load (input, error))
  960. {
  961. offline.setSong (std::move (*song));
  962. ok = true;
  963. }
  964. int samplers = 0, samplersLoaded = 0;
  965. if (ok)
  966. {
  967. for (const auto& c : offline.getSong().channels)
  968. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  969. {
  970. ++samplers;
  971. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  972. }
  973. const juce::File output (outputPath);
  974. output.deleteFile();
  975. juce::WavAudioFormat wav;
  976. std::unique_ptr<juce::AudioFormatWriter> writer (
  977. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  978. if (writer == nullptr)
  979. {
  980. ok = false;
  981. error = lynx::utf8 ("could not create ") + outputPath;
  982. }
  983. else
  984. {
  985. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  986. report << "peak=" << peak << "\n";
  987. ok = peak > 0.001f;
  988. }
  989. }
  990. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  991. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  992. juce::File (outputPath + ".txt").replaceWithText (report);
  993. setApplicationReturnValue (ok ? 0 : 1);
  994. quit();
  995. }
  996. // LYNX.exe --export project.(flp|lynx) output.(wav|flac|ogg) [--pattern] [--insert N]
  997. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail.
  998. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  999. {
  1000. juce::String error, report;
  1001. bool ok = false;
  1002. const auto started = juce::Time::getMillisecondCounterHiRes();
  1003. {
  1004. lynx::AudioEngine loader (false);
  1005. const juce::File input (inputPath);
  1006. if (input.hasFileExtension ("flp"))
  1007. ok = loader.importFlpFile (input, error);
  1008. else if (auto song = lynx::ProjectFile::load (input, error))
  1009. {
  1010. loader.setSong (std::move (*song));
  1011. ok = true;
  1012. }
  1013. if (ok)
  1014. {
  1015. const juce::File output (outputPath);
  1016. lynx::ExportSettings settings;
  1017. settings.wholeSong = ! patternOnly;
  1018. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  1019. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  1020. : lynx::ExportSettings::Format::wav24;
  1021. // --insert N: only that insert's output (what "Render to audio" records)
  1022. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  1023. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  1024. loader.editSong ([] (lynx::Song& s) {
  1025. for (auto& t : s.mixer)
  1026. t.effects.clear();
  1027. }, false);
  1028. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  1029. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  1030. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  1031. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  1032. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), settings, output);
  1033. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  1034. int lastPercent = -1;
  1035. ok = job.run ([&lastPercent] (double p) {
  1036. lastPercent = (int) (p * 100.0);
  1037. return true;
  1038. }, error);
  1039. auto joined = [] (const std::map<std::string, int>& items) {
  1040. juce::StringArray names;
  1041. for (const auto& [name, count] : items)
  1042. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  1043. return names.joinIntoString (", ");
  1044. };
  1045. const auto& importReport = loader.getImportReport();
  1046. report << "converted=" << joined (importReport.converted) << "\n"
  1047. << "approximated=" << joined (importReport.approximated) << "\n"
  1048. << "unsupported=" << joined (importReport.unsupported) << "\n"
  1049. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  1050. << "missing_samples=" << importReport.missingSamples << "\n";
  1051. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  1052. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  1053. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  1054. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  1055. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  1056. << "song_seconds=" << job.getMusicSeconds() << "\n"
  1057. << "peak=" << job.getPeak() << "\n"
  1058. << "final_progress=" << lastPercent << "\n"
  1059. << "bytes=" << output.getSize() << "\n";
  1060. ok = ok && job.getPeak() > 0.001f;
  1061. }
  1062. }
  1063. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  1064. juce::File (outputPath + ".txt").replaceWithText (report);
  1065. setApplicationReturnValue (ok ? 0 : 1);
  1066. quit();
  1067. }
  1068. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  1069. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  1070. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  1071. {
  1072. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1073. {
  1074. lynx::AudioEngine offline (false);
  1075. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  1076. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  1077. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  1078. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  1079. if (projectPath.isNotEmpty())
  1080. ui.openFile (juce::File (projectPath));
  1081. offline.dispatchPendingMessages(); // change notifications are asynchronous
  1082. ui.waitForBrowserForSnapshot();
  1083. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  1084. // (and a sample hint in the status strip, as when hovering a knob)
  1085. ui.showDesktopForSnapshot (false);
  1086. offline.dispatchPendingMessages();
  1087. saveSnapshot (ui, prefix + "-desktop.png");
  1088. ui.showDesktopForSnapshot (true);
  1089. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  1090. saveSnapshot (ui, prefix + "-desktop-all.png");
  1091. ui.selectTabForSnapshot (0);
  1092. saveSnapshot (ui, prefix + "-rack.png");
  1093. ui.selectTabForSnapshot (1);
  1094. saveSnapshot (ui, prefix + "-pianoroll.png");
  1095. ui.selectTabForSnapshot (2);
  1096. saveSnapshot (ui, prefix + "-playlist.png");
  1097. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  1098. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  1099. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  1100. offline.dispatchPendingMessages();
  1101. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  1102. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  1103. ui.selectTabForSnapshot (3);
  1104. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  1105. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  1106. {
  1107. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  1108. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  1109. offline.dispatchPendingMessages();
  1110. }
  1111. saveSnapshot (ui, prefix + "-mixer.png");
  1112. // standalone windows, with the theme background
  1113. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  1114. juce::Component frame;
  1115. frame.setSize (c->getWidth(), c->getHeight());
  1116. frame.setOpaque (true);
  1117. frame.addAndMakeVisible (*c);
  1118. c->setTopLeftPosition (0, 0);
  1119. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  1120. {
  1121. juce::Graphics g (image);
  1122. g.fillAll (lynx::theme::panel);
  1123. frame.paintEntireComponent (g, false);
  1124. }
  1125. const juce::File file (prefix + name);
  1126. file.deleteFile();
  1127. juce::PNGImageFormat png;
  1128. if (auto out = file.createOutputStream())
  1129. png.writeImageToStream (image, *out);
  1130. };
  1131. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  1132. saveSplashFrames (prefix);
  1133. saveIconSheet (prefix + "-icons.png", 1.0f);
  1134. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  1135. saveWindow (lynx::MainComponent::makeHelpContent(), "-help.png");
  1136. saveMenus (ui, prefix + "-menus.png");
  1137. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  1138. alert->setOpaque (true);
  1139. saveWindow (std::move (alert), name);
  1140. };
  1141. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  1142. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  1143. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  1144. if (! offline.getSong().automations.empty())
  1145. {
  1146. auto editor = lynx::makeAutomationEditor (offline, 0);
  1147. editor->setSize (760, 300);
  1148. saveWindow (std::move (editor), "-automation.png");
  1149. }
  1150. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  1151. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  1152. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  1153. {
  1154. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  1155. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  1156. break;
  1157. }
  1158. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  1159. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  1160. {
  1161. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  1162. break;
  1163. }
  1164. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  1165. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  1166. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  1167. {
  1168. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  1169. break;
  1170. }
  1171. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  1172. {
  1173. int bestTrack = -1, bestSlot = -1;
  1174. double bestShape = -1.0;
  1175. const auto& mixer = offline.getSong().mixer;
  1176. for (int t = 0; t < (int) mixer.size(); ++t)
  1177. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  1178. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  1179. {
  1180. double shape = 0.0;
  1181. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  1182. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  1183. if (shape > bestShape)
  1184. {
  1185. bestShape = shape;
  1186. bestTrack = t;
  1187. bestSlot = s;
  1188. }
  1189. }
  1190. if (bestTrack >= 0)
  1191. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  1192. }
  1193. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  1194. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  1195. saveWindow (std::move (inspector), "-noteinspector.png");
  1196. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  1197. saveWindow (std::move (inspector), "-noteinspector-one.png");
  1198. }
  1199. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  1200. quit();
  1201. }
  1202. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  1203. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  1204. {
  1205. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  1206. const auto names = ui.getMenuNamesForSnapshot();
  1207. struct Laid
  1208. {
  1209. juce::PopupMenu menu;
  1210. int width = 0, height = 0;
  1211. };
  1212. std::vector<Laid> menus;
  1213. const auto border = lf.getPopupMenuBorderSize();
  1214. const auto itemHeight = 26;
  1215. for (int m = 0; m < names.size(); ++m)
  1216. {
  1217. Laid laid { ui.getMenuForSnapshot (m) };
  1218. int width = 160, height = 2 * border;
  1219. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  1220. {
  1221. const auto& item = it.getItem();
  1222. int w = 0, h = 0;
  1223. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? 22 : itemHeight, w, h);
  1224. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  1225. w += 90;
  1226. width = juce::jmax (width, w + 10);
  1227. height += h;
  1228. }
  1229. laid.width = width;
  1230. laid.height = height;
  1231. menus.push_back (std::move (laid));
  1232. }
  1233. int totalWidth = 16, totalHeight = 0;
  1234. for (const auto& l : menus)
  1235. {
  1236. totalWidth += l.width + 16;
  1237. totalHeight = juce::jmax (totalHeight, l.height + 32);
  1238. }
  1239. juce::Image image (juce::Image::ARGB, totalWidth, totalHeight, true);
  1240. {
  1241. juce::Graphics g (image);
  1242. g.fillAll (lynx::theme::colour::bg1);
  1243. int x = 16;
  1244. for (int m = 0; m < (int) menus.size(); ++m)
  1245. {
  1246. const auto& l = menus[(std::size_t) m];
  1247. g.setColour (lynx::theme::colour::textSecondary);
  1248. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  1249. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  1250. {
  1251. juce::Graphics::ScopedSaveState state (g);
  1252. g.reduceClipRegion (x, 24, l.width, l.height);
  1253. g.setOrigin (x, 24);
  1254. lf.drawPopupMenuBackground (g, l.width, l.height);
  1255. int y = border;
  1256. bool first = true;
  1257. for (juce::PopupMenu::MenuItemIterator it (l.menu); it.next();)
  1258. {
  1259. const auto& item = it.getItem();
  1260. int w = 0, h = 0;
  1261. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? 22 : itemHeight, w, h);
  1262. const juce::Rectangle<int> r (0, y, l.width, h);
  1263. auto text = item.text, shortcut = item.shortcutKeyDescription;
  1264. if (text.containsChar ('\t'))
  1265. {
  1266. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  1267. text = text.upToFirstOccurrenceOf ("\t", false, false);
  1268. }
  1269. if (item.isSectionHeader)
  1270. lf.drawPopupMenuSectionHeader (g, r, text);
  1271. else
  1272. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  1273. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  1274. first = false;
  1275. y += h;
  1276. }
  1277. }
  1278. x += l.width + 16;
  1279. }
  1280. }
  1281. const juce::File file (path);
  1282. file.deleteFile();
  1283. juce::PNGImageFormat png;
  1284. if (auto out = file.createOutputStream())
  1285. png.writeImageToStream (image, *out);
  1286. }
  1287. static void writePng (const juce::Image& image, const juce::String& path)
  1288. {
  1289. const juce::File file (path);
  1290. file.deleteFile();
  1291. juce::PNGImageFormat png;
  1292. if (auto out = file.createOutputStream())
  1293. png.writeImageToStream (image, *out);
  1294. }
  1295. // the splash screen: one settled frame, and a strip of frames through its animation
  1296. static void saveSplashFrames (const juce::String& prefix)
  1297. {
  1298. lynx::SplashScreen splash;
  1299. splash.setStatus (lynx::tr ("Loading the workspace..."));
  1300. splash.setTimeForSnapshot (1.6);
  1301. writePng (splash.createComponentSnapshot (splash.getLocalBounds()), prefix + "-splash.png");
  1302. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  1303. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  1304. juce::Image strip (juce::Image::ARGB, 4 * (w + 8) + 8, 2 * (h + 8) + 8, true);
  1305. {
  1306. juce::Graphics g (strip);
  1307. g.fillAll (lynx::theme::colour::bg1);
  1308. for (int i = 0; i < 8; ++i)
  1309. {
  1310. splash.setTimeForSnapshot (times[i]);
  1311. const auto frame = splash.createComponentSnapshot (splash.getLocalBounds());
  1312. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  1313. }
  1314. }
  1315. writePng (strip, prefix + "-splash-frames.png");
  1316. }
  1317. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  1318. // colours: at rest, hovered and switched on
  1319. static void saveIconSheet (const juce::String& path, float scale)
  1320. {
  1321. const int sizes[] = { 16, 20, 24 };
  1322. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  1323. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  1324. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  1325. {
  1326. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  1327. g.addTransform (juce::AffineTransform::scale (scale));
  1328. g.fillAll (lynx::theme::colour::bg3);
  1329. g.setFont (lynx::theme::font (lynx::theme::type::small));
  1330. for (int i = 1; i < lynx::iconCount; ++i)
  1331. {
  1332. const auto y = 8 + (i - 1) * cell;
  1333. g.setColour (lynx::theme::colour::textDisabled);
  1334. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  1335. for (int v = 0; v < 3; ++v)
  1336. for (int s = 0; s < 3; ++s)
  1337. {
  1338. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  1339. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  1340. g.setColour (bg);
  1341. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  1342. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  1343. : lynx::theme::colour::textSecondary.brighter (0.25f);
  1344. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  1345. }
  1346. }
  1347. }
  1348. writePng (image, path);
  1349. }
  1350. static void saveSnapshot (juce::Component& c, const juce::String& path)
  1351. {
  1352. const juce::File file (path);
  1353. file.deleteFile();
  1354. juce::PNGImageFormat png;
  1355. if (auto out = file.createOutputStream())
  1356. png.writeImageToStream (c.createComponentSnapshot (c.getLocalBounds()), *out);
  1357. }
  1358. class MainWindow final : public juce::DocumentWindow
  1359. {
  1360. public:
  1361. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  1362. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons)
  1363. {
  1364. setUsingNativeTitleBar (true);
  1365. setIcon (lynx::logoImage());
  1366. content = new lynx::MainComponent (engine);
  1367. setContentOwned (content, true);
  1368. setResizable (true, true);
  1369. setResizeLimits (800, 400, 10000, 10000);
  1370. // ~88% of the main display's usable area (at least the UI's design size)
  1371. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  1372. {
  1373. const auto area = display->userArea;
  1374. setSize (juce::jmax (getWidth(), (int) (area.getWidth() * 0.88)), juce::jmax (getHeight(), (int) (area.getHeight() * 0.88)));
  1375. }
  1376. centreWithSize (getWidth(), getHeight());
  1377. }
  1378. // Shows the window (built hidden while the splash screen is up).
  1379. void reveal()
  1380. {
  1381. setVisible (true);
  1382. lynx::applyWindowChrome (*this);
  1383. toFront (true);
  1384. content->grabKeyboardFocus();
  1385. }
  1386. void openFile (const juce::File& file) { content->openFile (file); }
  1387. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  1388. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  1389. private:
  1390. lynx::MainComponent* content = nullptr; // owned by the window
  1391. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  1392. };
  1393. lynx::theme::LookAndFeel lookAndFeel;
  1394. std::unique_ptr<lynx::AudioEngine> engine;
  1395. std::unique_ptr<MainWindow> mainWindow;
  1396. std::unique_ptr<lynx::SplashScreen> splash;
  1397. lynx::StartupOptions startupOptions;
  1398. juce::File fileToOpen;
  1399. };
  1400. START_JUCE_APPLICATION (LynxApplication)