Toolbar.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. #include "ui/Toolbar.h"
  2. #include <juce_dsp/juce_dsp.h>
  3. #include "ui/HintBar.h"
  4. #include "ui/I18n.h"
  5. #include "ui/Icons.h"
  6. #include "ui/Theme.h"
  7. namespace lynx::toolbar
  8. {
  9. namespace
  10. {
  11. juce::String barBeatStep (const Song& song, double ticks, int beatsPerBar)
  12. {
  13. const auto beats = ticks / ppq;
  14. int bar = 0, beat = 0;
  15. if (song.mode == PlayMode::song) // the Playlist ruler applies (with time signature changes)
  16. {
  17. const auto current = song.barAt ((std::int64_t) ticks);
  18. bar = current.number;
  19. beat = (int) ((ticks - (double) current.tick) / ppq) + 1;
  20. }
  21. else
  22. {
  23. const auto perBar = juce::jmax (1, beatsPerBar);
  24. bar = (int) (beats / perBar) + 1;
  25. beat = (int) std::fmod (beats, (double) perBar) + 1;
  26. }
  27. const auto step = (int) (std::fmod (beats, 1.0) * stepsPerBeat) + 1;
  28. return juce::String::formatted ("%d : %d : %d", bar, beat, step);
  29. }
  30. double loopLength (const Song& song)
  31. {
  32. if (song.patterns.empty())
  33. return 1.0;
  34. const auto length = song.mode == PlayMode::song
  35. ? song.songLength()
  36. : song.patterns[(std::size_t) juce::jlimit (0, (int) song.patterns.size() - 1, song.currentPattern)].effectiveLength (song.beatsPerBar);
  37. return (double) juce::jmax<std::int64_t> (1, length);
  38. }
  39. double playheadTicks (AudioEngine& engine)
  40. {
  41. return std::fmod (juce::jmax (0.0, engine.getTransport().positionTicks.load()), loopLength (engine.getSong()));
  42. }
  43. juce::String centsText (double cents)
  44. {
  45. const auto c = juce::roundToInt (cents);
  46. return (c > 0 ? "+" : "") + juce::String (c) + " " + tr ("cents");
  47. }
  48. } // namespace
  49. // --- song position -------------------------------------------------------------------------------
  50. SongPositionBar::SongPositionBar (AudioEngine& e) : engine (e)
  51. {
  52. setMouseCursor (juce::MouseCursor::PointingHandCursor);
  53. }
  54. double SongPositionBar::length() const { return loopLength (engine.getSong()); }
  55. double SongPositionBar::position() const { return playheadTicks (engine); }
  56. juce::Rectangle<float> SongPositionBar::track() const
  57. {
  58. return getLocalBounds().toFloat().reduced (5.0f, 0.0f).withSizeKeepingCentre ((float) getWidth() - 10.0f, 4.0f);
  59. }
  60. void SongPositionBar::update()
  61. {
  62. const auto fraction = position() / length();
  63. if (std::abs (fraction - shownFraction) * getWidth() >= 0.5)
  64. {
  65. shownFraction = fraction;
  66. repaint();
  67. }
  68. }
  69. void SongPositionBar::paint (juce::Graphics& g)
  70. {
  71. using namespace theme;
  72. const auto t = track();
  73. const auto& song = engine.getSong();
  74. const auto active = dragging || isMouseOver();
  75. g.setColour (colour::bg0);
  76. g.fillRoundedRectangle (t.expanded (0.0f, 1.0f), 2.5f);
  77. // the Playlist loop (Song mode)
  78. if (song.mode == PlayMode::song && song.hasLoop())
  79. {
  80. const auto x0 = t.getX() + t.getWidth() * (float) ((double) song.loopStart / length());
  81. const auto x1 = t.getX() + t.getWidth() * (float) juce::jmin (1.0, (double) song.loopEnd / length());
  82. g.setColour (colour::info.withAlpha (0.35f));
  83. g.fillRect (juce::Rectangle<float> (x0, t.getY() - 1.0f, juce::jmax (1.0f, x1 - x0), t.getHeight() + 2.0f));
  84. }
  85. const auto fraction = (float) juce::jlimit (0.0, 1.0, position() / length());
  86. const auto x = t.getX() + t.getWidth() * fraction;
  87. g.setColour (engine.getTransport().playing.load() ? colour::accent : colour::accent.withMultipliedSaturation (0.55f).withMultipliedBrightness (0.8f));
  88. g.fillRoundedRectangle (t.withRight (juce::jmax (t.getX() + 1.0f, x)), 2.0f);
  89. const auto radius = active ? 5.0f : 3.5f;
  90. g.setColour (active ? colour::textPrimary : colour::textSecondary);
  91. g.fillEllipse (juce::Rectangle<float> (radius * 2.0f, radius * 2.0f).withCentre ({ x, t.getCentreY() }));
  92. }
  93. void SongPositionBar::seekTo (int x)
  94. {
  95. const auto t = track();
  96. const auto fraction = juce::jlimit (0.0, 1.0, (double) ((float) x - t.getX()) / juce::jmax (1.0f, t.getWidth()));
  97. auto ticks = fraction * length();
  98. if (! juce::ModifierKeys::currentModifiers.isAltDown()) // Alt: no snap (as everywhere)
  99. ticks = std::round (ticks / ticksPerStep) * ticksPerStep;
  100. engine.seek (juce::jlimit (0.0, length() - 1.0, ticks));
  101. update();
  102. repaint();
  103. }
  104. void SongPositionBar::mouseDown (const juce::MouseEvent& e)
  105. {
  106. if (! e.mods.isLeftButtonDown())
  107. return;
  108. dragging = true;
  109. seekTo (e.x);
  110. }
  111. void SongPositionBar::mouseDrag (const juce::MouseEvent& e)
  112. {
  113. if (dragging)
  114. seekTo (e.x);
  115. }
  116. void SongPositionBar::mouseUp (const juce::MouseEvent&)
  117. {
  118. dragging = false;
  119. repaint();
  120. }
  121. void SongPositionBar::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  122. {
  123. const auto delta = std::abs (wheel.deltaY) >= std::abs (wheel.deltaX) ? wheel.deltaY : -wheel.deltaX;
  124. if (delta == 0.0f)
  125. return;
  126. const auto bar = (double) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  127. const auto current = std::round (position() / bar) * bar;
  128. engine.seek (juce::jlimit (0.0, juce::jmax (0.0, length() - bar), current + (delta > 0.0f ? -bar : bar) * (wheel.isReversed ? -1.0 : 1.0)));
  129. update();
  130. }
  131. ui::Hint SongPositionBar::hintAt (juce::Point<int>)
  132. {
  133. const auto& song = engine.getSong();
  134. ui::Hint h;
  135. h.text = (song.mode == PlayMode::song ? tr ("Song position") : tr ("Pattern position"))
  136. + ": " + tr ("[LMB] click or drag to move the playhead [Wheel] one bar [Alt] no snap");
  137. const auto bars = juce::jmax (1, juce::roundToInt (length() / ((double) ppq * juce::jmax (1, song.beatsPerBar))));
  138. h.value = tr ("Bar {0} of {1}", { barBeatStep (song, position(), song.beatsPerBar).upToFirstOccurrenceOf (" ", false, false), juce::String (bars) });
  139. return h;
  140. }
  141. // --- time display --------------------------------------------------------------------------------
  142. juce::String TimeDisplay::text() const
  143. {
  144. const auto& song = engine.getSong();
  145. const auto ticks = playheadTicks (engine);
  146. if (! clockMode)
  147. return barBeatStep (song, ticks, engine.getTransport().beatsPerBar.load());
  148. const auto seconds = song.secondsForTicks ((std::int64_t) ticks);
  149. const auto whole = (int) seconds;
  150. return juce::String::formatted ("%d : %02d : %02d", whole / 60, whole % 60, (int) ((seconds - whole) * 100.0));
  151. }
  152. void TimeDisplay::update()
  153. {
  154. if (const auto t = text(); t != shown)
  155. {
  156. shown = t;
  157. repaint();
  158. }
  159. }
  160. void TimeDisplay::paint (juce::Graphics& g)
  161. {
  162. using namespace theme;
  163. const auto area = getLocalBounds();
  164. g.setColour (colour::bg1);
  165. g.fillRoundedRectangle (area.toFloat(), radius::md);
  166. if (isMouseOver())
  167. {
  168. g.setColour (colour::borderStrong);
  169. g.drawRoundedRectangle (area.toFloat().reduced (0.5f), radius::md, 1.0f);
  170. }
  171. g.setColour (colour::textPrimary);
  172. g.setFont (monoFont (juce::jmin (17.0f, (float) area.getHeight() * 0.45f)));
  173. g.drawText (shown.isEmpty() ? text() : shown, area.withTrimmedBottom (11), juce::Justification::centred, false);
  174. g.setColour (colour::textDisabled);
  175. g.setFont (font (type::caption - 1.0f));
  176. g.drawText (clockMode ? tr ("MIN : SEC : CS") : tr ("BAR : BEAT : STEP"), area.withTrimmedTop (area.getHeight() - 14).withTrimmedBottom (2),
  177. juce::Justification::centred, false);
  178. }
  179. void TimeDisplay::mouseUp (const juce::MouseEvent& e)
  180. {
  181. if (e.mods.isPopupMenu() || ! getLocalBounds().contains (e.getPosition()))
  182. return;
  183. clockMode = ! clockMode;
  184. shown = {};
  185. update();
  186. repaint();
  187. }
  188. ui::Hint TimeDisplay::hintAt (juce::Point<int>)
  189. {
  190. ui::Hint h;
  191. h.text = (clockMode ? tr ("Time: minutes : seconds : hundredths") : tr ("Time: bar : beat : step"))
  192. + " " + tr ("[LMB] switch between bars and minutes");
  193. h.value = text();
  194. return h;
  195. }
  196. // --- master volume and pitch ---------------------------------------------------------------------
  197. MasterKnob::MasterKnob (AudioEngine& e, Kind k) : engine (e), kind (k)
  198. {
  199. setRepaintsOnMouseActivity (true);
  200. }
  201. bool MasterKnob::available() const
  202. {
  203. return kind == Kind::pitch || ! engine.getSong().mixer.empty();
  204. }
  205. double MasterKnob::value() const
  206. {
  207. const auto& song = engine.getSong();
  208. if (kind == Kind::pitch)
  209. return song.masterPitch;
  210. return song.mixer.empty() ? (double) unityFader : (double) song.mixer.front().volume;
  211. }
  212. void MasterKnob::setValue (double v)
  213. {
  214. const auto s = spec();
  215. v = juce::jlimit (s.minimum, s.maximum, v);
  216. if (! available() || std::abs (v - value()) < 1e-9)
  217. return;
  218. if (kind == Kind::pitch)
  219. engine.editSong ([v] (Song& song) { song.masterPitch = (float) v; });
  220. else
  221. engine.editSong ([v] (Song& song) {
  222. if (! song.mixer.empty())
  223. song.mixer.front().volume = (float) v;
  224. });
  225. update();
  226. }
  227. ui::ValueSpec MasterKnob::spec() const
  228. {
  229. if (kind == Kind::volume)
  230. {
  231. auto s = ui::faderSpec (tr ("Master volume"), unityFader);
  232. s.target = AutomationTarget { AutomationTargetKind::mixerVolume, 0 };
  233. return s;
  234. }
  235. ui::ValueSpec s;
  236. s.name = tr ("Master pitch");
  237. s.minimum = -1200.0;
  238. s.maximum = 1200.0;
  239. s.defaultValue = 0.0;
  240. s.pixelsForRange = 360.0;
  241. s.toText = [] (double v) { return centsText (v); };
  242. s.fromText = [] (const juce::String& t) -> std::optional<double> {
  243. const auto number = t.retainCharacters ("+-0123456789.");
  244. if (number.isEmpty())
  245. return std::nullopt;
  246. return number.getDoubleValue();
  247. };
  248. return s;
  249. }
  250. void MasterKnob::update()
  251. {
  252. if (const auto v = value(); v != shown)
  253. {
  254. shown = v;
  255. repaint();
  256. }
  257. }
  258. void MasterKnob::paint (juce::Graphics& g)
  259. {
  260. using namespace theme;
  261. auto area = getLocalBounds().toFloat();
  262. const auto knob = area.removeFromLeft (juce::jmin (area.getHeight(), 26.0f));
  263. const auto s = spec();
  264. const auto v = value();
  265. const auto hover = isMouseOver() || drag.isActive();
  266. const auto value01 = (float) ((v - s.minimum) / (s.maximum - s.minimum));
  267. drawKnob (g, knob, value01, kind == Kind::pitch, available() ? colour::knobArc : colour::textDisabled, hover && available());
  268. area.removeFromLeft (5.0f);
  269. auto caption = area.removeFromTop (area.getHeight() / 2.0f);
  270. g.setColour (colour::textDisabled);
  271. g.setFont (font (type::caption - 1.0f, true));
  272. g.drawText (kind == Kind::volume ? tr ("MASTER") : tr ("PITCH"), caption.withTrimmedTop (1.0f), juce::Justification::bottomLeft, true);
  273. g.setColour (drag.isActive() ? colour::textPrimary : colour::textSecondary);
  274. g.setFont (font (type::caption));
  275. g.drawText (available() ? s.text (v) : tr ("no mixer"), area, juce::Justification::topLeft, true);
  276. }
  277. void MasterKnob::mouseDown (const juce::MouseEvent& e)
  278. {
  279. if (! available())
  280. return;
  281. if (e.mods.isPopupMenu())
  282. {
  283. ui::showValueMenu (*this, kind == Kind::volume ? &engine : nullptr, spec(), value(), [this] (double v) { setValue (v); });
  284. return;
  285. }
  286. if (ui::isResetClick (e))
  287. {
  288. setValue (spec().defaultValue);
  289. return;
  290. }
  291. drag.begin (e, value());
  292. repaint();
  293. }
  294. void MasterKnob::mouseDrag (const juce::MouseEvent& e)
  295. {
  296. if (! drag.isActive())
  297. return;
  298. auto v = drag.update (e, spec());
  299. if (kind == Kind::pitch && ! e.mods.isShiftDown()) // semitone steps; Shift: free (as FL's master pitch)
  300. v = std::round (v / 100.0) * 100.0;
  301. setValue (v);
  302. }
  303. void MasterKnob::mouseUp (const juce::MouseEvent&)
  304. {
  305. drag.end();
  306. repaint();
  307. }
  308. void MasterKnob::mouseDoubleClick (const juce::MouseEvent& e)
  309. {
  310. if (available() && ! e.mods.isPopupMenu() && ! ui::isResetClick (e))
  311. ui::typeValue (*this, spec(), value(), [this] (double v) { setValue (v); });
  312. }
  313. void MasterKnob::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  314. {
  315. if (! available())
  316. return;
  317. if (kind == Kind::pitch)
  318. {
  319. const auto delta = std::abs (wheel.deltaY) >= std::abs (wheel.deltaX) ? wheel.deltaY : -wheel.deltaX;
  320. if (delta != 0.0f)
  321. setValue (value() + (delta > 0.0f ? 1.0 : -1.0) * (wheel.isReversed ? -1.0 : 1.0) * (e.mods.isCtrlDown() ? 1.0 : 100.0));
  322. return;
  323. }
  324. if (const auto v = ui::wheelValue (value(), e, wheel, spec()))
  325. setValue (*v);
  326. }
  327. ui::Hint MasterKnob::hintAt (juce::Point<int>)
  328. {
  329. if (! available())
  330. return { tr ("Master volume: this project has no mixer"), {}, false, false };
  331. const auto gesture = kind == Kind::volume
  332. ? tr ("level of everything you hear (the Master insert's fader)") + " " + ui::valueGestures()
  333. : tr ("tunes the built-in instruments [LMB] drag (semitones) [Shift] cents [Wheel] semitone [Ctrl][Wheel] cent [Alt][LMB] reset [RMB] menu");
  334. return ui::valueHint (spec(), value(), gesture);
  335. }
  336. // --- CPU, memory, polyphony ----------------------------------------------------------------------
  337. void PerformanceMeter::setValues (double cpu01, std::int64_t memoryBytes, int polyphony)
  338. {
  339. cpu = cpu01;
  340. cpuSmoothed = cpuSmoothed <= 0.0 ? cpu01 : cpuSmoothed * 0.8 + cpu01 * 0.2;
  341. memory = memoryBytes;
  342. voices = polyphony;
  343. peakVoices = juce::jmax (peakVoices, polyphony);
  344. repaint();
  345. }
  346. void PerformanceMeter::setRealtime (std::uint64_t over, std::uint64_t late, double peak, const juce::StringArray& units)
  347. {
  348. if (over > overDeadline || late > lateCalls)
  349. lastGlitchAt = juce::jmax<juce::uint32> (1, juce::Time::getMillisecondCounter());
  350. overDeadline = over;
  351. lateCalls = late;
  352. peakLoad = peak;
  353. heaviest = units;
  354. repaint();
  355. }
  356. void PerformanceMeter::paint (juce::Graphics& g)
  357. {
  358. using namespace theme;
  359. auto area = getLocalBounds();
  360. auto row1 = area.removeFromTop (area.getHeight() / 2).reduced (0, 4);
  361. auto row2 = area.reduced (0, 4);
  362. const juce::Font caption (font (type::caption - 1.0f, true)), number (font (type::caption));
  363. // CPU: caption, bar, percent
  364. g.setFont (caption);
  365. g.setColour (colour::textDisabled);
  366. g.drawText (tr ("CPU"), row1.removeFromLeft (30), juce::Justification::centredLeft, false);
  367. g.setFont (number);
  368. g.setColour (colour::textSecondary);
  369. g.drawText (juce::String (juce::roundToInt (cpuSmoothed * 100.0)) + "%", row1.removeFromRight (34), juce::Justification::centredRight, false);
  370. const auto bar = row1.reduced (2, 3).toFloat();
  371. g.setColour (colour::bg0);
  372. g.fillRoundedRectangle (bar, 2.0f);
  373. const auto load = (float) juce::jlimit (0.0, 1.0, cpuSmoothed);
  374. g.setColour (load < 0.6f ? colour::meterLow : load < 0.85f ? colour::meterMid : colour::meterClip);
  375. if (load > 0.0f)
  376. g.fillRoundedRectangle (bar.withWidth (juce::jmax (2.0f, bar.getWidth() * load)), 2.0f);
  377. // the highest callback load since the last update (a thin mark), and a red edge for a few seconds after a
  378. // callback missed its deadline (an audible crackle)
  379. if (peakLoad > 0.0)
  380. {
  381. const auto x = bar.getX() + bar.getWidth() * (float) juce::jlimit (0.0, 1.0, peakLoad);
  382. g.setColour (peakLoad < 0.85 ? colour::textSecondary : colour::meterClip);
  383. g.fillRect (juce::Rectangle<float> (x - 1.0f, bar.getY(), 2.0f, bar.getHeight()));
  384. }
  385. if (lastGlitchAt != 0 && juce::Time::getMillisecondCounter() - lastGlitchAt < 5000)
  386. {
  387. g.setColour (colour::meterClip);
  388. g.drawRoundedRectangle (bar.expanded (1.0f), 2.0f, 1.0f);
  389. }
  390. // memory and polyphony
  391. auto left = row2.removeFromLeft (row2.getWidth() * 58 / 100);
  392. g.setFont (caption);
  393. g.setColour (colour::textDisabled);
  394. g.drawText (tr ("RAM"), left.removeFromLeft (30), juce::Justification::centredLeft, false);
  395. g.setFont (number);
  396. g.setColour (colour::textSecondary);
  397. g.drawText (memory > 0 ? juce::String (juce::roundToInt ((double) memory / (1024.0 * 1024.0))) + " MB" : juce::String ("-"), left,
  398. juce::Justification::centredLeft, false);
  399. g.setFont (caption);
  400. g.setColour (colour::textDisabled);
  401. g.drawText (tr ("POLY"), row2.removeFromLeft (32), juce::Justification::centredLeft, false);
  402. g.setFont (number);
  403. g.setColour (voices > 0 ? colour::textPrimary : colour::textSecondary);
  404. g.drawText (juce::String (voices), row2, juce::Justification::centredRight, false);
  405. }
  406. ui::Hint PerformanceMeter::hintAt (juce::Point<int> p)
  407. {
  408. ui::Hint h;
  409. if (p.y < getHeight() / 2)
  410. {
  411. h.text = tr ("CPU: how much of the audio deadline the processing takes; near 100% the sound breaks up");
  412. if (overDeadline > 0 || lateCalls > 0)
  413. h.text << " " << tr ("{0} audio blocks missed the deadline (crackles), the device called late {1} times; log: audio-glitches.log",
  414. { juce::String ((juce::int64) overDeadline), juce::String ((juce::int64) lateCalls) });
  415. if (! heaviest.isEmpty())
  416. h.text << " " << tr ("Heaviest: {0}", { heaviest.joinIntoString (", ") });
  417. h.value = juce::String (cpu * 100.0, 1) + "%" + (peakLoad > 0.0 ? " (" + tr ("peak {0}%", { juce::String (juce::roundToInt (peakLoad * 100.0)) }) + ")" : juce::String());
  418. }
  419. else if (p.x < getWidth() * 58 / 100)
  420. {
  421. h.text = tr ("RAM: memory used by LYNX (samples, plugins, undo history)");
  422. h.value = juce::String ((double) memory / (1024.0 * 1024.0), 0) + " MB";
  423. }
  424. else
  425. {
  426. h.text = tr ("Polyphony: notes sounding now in the song and from the keyboard (voices still releasing are not counted)");
  427. h.value = juce::String (voices) + " (" + tr ("max {0}", { juce::String (peakVoices) }) + ")";
  428. }
  429. return h;
  430. }
  431. // --- output monitor ------------------------------------------------------------------------------
  432. void OutputMonitor::update()
  433. {
  434. if (! isShowing() || getWidth() <= 0)
  435. return;
  436. engine.copyScope (samples.data(), (int) samples.size());
  437. float now = 0.0f;
  438. for (auto s : samples)
  439. now = juce::jmax (now, std::abs (s));
  440. peak = juce::jmax (now, peak * 0.82f); // fast attack, smooth fall
  441. if (now >= held || holdFrames <= 0)
  442. {
  443. held = now;
  444. holdFrames = 30; // about a second at 30 Hz
  445. }
  446. else
  447. --holdFrames;
  448. if (now >= 0.999f)
  449. clipFrames = 60;
  450. else if (clipFrames > 0)
  451. --clipFrames;
  452. // long view: the level scrolls from right to left
  453. std::rotate (history.begin(), history.begin() + 1, history.end());
  454. history.back() = now;
  455. if (mode == spectrum)
  456. {
  457. // Hann-windowed FFT of the last 1024 samples, folded into log-spaced bands (20 Hz..20 kHz)
  458. static juce::dsp::FFT fft (10);
  459. std::array<float, 2048> data {};
  460. for (std::size_t i = 0; i < samples.size(); ++i)
  461. data[i] = samples[i] * (0.5f - 0.5f * std::cos (juce::MathConstants<float>::twoPi * (float) i / (float) (samples.size() - 1)));
  462. fft.performFrequencyOnlyForwardTransform (data.data(), true);
  463. const auto rate = juce::jmax (8000.0, engine.getTransport().sampleRate.load());
  464. for (std::size_t b = 0; b < bands.size(); ++b)
  465. {
  466. const auto f0 = 20.0 * std::pow (1000.0, (double) b / (double) bands.size());
  467. const auto f1 = 20.0 * std::pow (1000.0, (double) (b + 1) / (double) bands.size());
  468. auto i0 = (int) (f0 / rate * 1024.0), i1 = juce::jmax (i0 + 1, (int) (f1 / rate * 1024.0));
  469. i0 = juce::jlimit (1, 511, i0);
  470. i1 = juce::jlimit (i0 + 1, 512, i1);
  471. float m = 0.0f;
  472. for (auto i = i0; i < i1; ++i)
  473. m = juce::jmax (m, data[(std::size_t) i]);
  474. const auto db = juce::Decibels::gainToDecibels (m / 256.0f, -72.0f);
  475. const auto level = juce::jlimit (0.0f, 1.0f, (db + 72.0f) / 72.0f);
  476. bands[b] = juce::jmax (level, bands[b] * 0.85f); // fast up, smooth fall
  477. }
  478. }
  479. repaint();
  480. }
  481. juce::String OutputMonitor::modeName (int m)
  482. {
  483. switch (m)
  484. {
  485. case longView: return tr ("Long view (level over time)");
  486. case spectrum: return tr ("Spectrum (low frequencies on the left)");
  487. default: return tr ("Oscilloscope (waveform)");
  488. }
  489. }
  490. void OutputMonitor::setMode (int newMode)
  491. {
  492. mode = juce::jlimit (0, modeCount - 1, newMode);
  493. bands.fill (0.0f);
  494. repaint();
  495. if (onModeChanged)
  496. onModeChanged();
  497. }
  498. void OutputMonitor::mouseDown (const juce::MouseEvent& e)
  499. {
  500. if (e.mods.isPopupMenu())
  501. {
  502. juce::PopupMenu menu;
  503. menu.addSectionHeader (tr ("Output display"));
  504. for (int m = 0; m < modeCount; ++m)
  505. menu.addItem (modeName (m), true, mode == m, [this, m] { setMode (m); });
  506. menu.addSeparator();
  507. menu.addItem (tr ("Reset the peak hold and clip light"), [this] {
  508. held = 0.0f;
  509. clipFrames = holdFrames = 0;
  510. repaint();
  511. });
  512. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this));
  513. return;
  514. }
  515. if (e.mods.isLeftButtonDown())
  516. setMode ((mode + 1) % modeCount);
  517. }
  518. void OutputMonitor::paint (juce::Graphics& g)
  519. {
  520. using namespace theme;
  521. auto area = getLocalBounds().toFloat();
  522. g.setColour (colour::bg0);
  523. g.fillRoundedRectangle (area, radius::md);
  524. // peak meter on the right: -60..0 dB, the top segment red while it clipped recently
  525. auto meter = area.removeFromRight (8.0f).reduced (1.5f, 4.0f);
  526. auto level = [] (float gain) { return juce::jlimit (0.0f, 1.0f, (juce::Decibels::gainToDecibels (gain, -60.0f) + 60.0f) / 60.0f); };
  527. g.setColour (colour::bg3);
  528. g.fillRoundedRectangle (meter, 1.5f);
  529. const auto filled = meter.withTop (meter.getBottom() - meter.getHeight() * level (peak));
  530. g.setGradientFill (juce::ColourGradient::vertical (colour::meterMid, meter.getY() + meter.getHeight() * 0.1f, colour::meterLow,
  531. meter.getY() + meter.getHeight() * 0.4f));
  532. g.fillRect (filled);
  533. if (held > 0.0f)
  534. {
  535. g.setColour (colour::textSecondary);
  536. g.fillRect (meter.withHeight (1.0f).withY (meter.getBottom() - meter.getHeight() * level (held)));
  537. }
  538. if (clipFrames > 0)
  539. {
  540. g.setColour (colour::meterClip);
  541. g.fillRoundedRectangle (meter.withHeight (4.0f), 1.0f);
  542. }
  543. auto scope = area.reduced (4.0f, 3.0f);
  544. const auto lineColour = (clipFrames > 0 ? colour::meterClip : colour::accent).withAlpha (0.9f);
  545. if (mode == longView) // the level of the last seconds, newest on the right, mirrored around the centre
  546. {
  547. g.setColour (colour::border);
  548. g.drawHorizontalLine ((int) scope.getCentreY(), scope.getX(), scope.getRight());
  549. const auto columns = juce::jmax (1, (int) scope.getWidth());
  550. g.setColour (lineColour.withAlpha (0.75f));
  551. for (int x = 0; x < columns; ++x)
  552. {
  553. const auto index = (std::size_t) (x * (int) history.size() / columns);
  554. const auto h = juce::jmax (0.5f, level (history[index]) * scope.getHeight() * 0.5f);
  555. g.fillRect (scope.getX() + (float) x, scope.getCentreY() - h, 1.0f, h * 2.0f);
  556. }
  557. return;
  558. }
  559. if (mode == spectrum) // bars per log-spaced band
  560. {
  561. const auto w = scope.getWidth() / (float) bands.size();
  562. g.setColour (lineColour.withAlpha (0.8f));
  563. for (std::size_t b = 0; b < bands.size(); ++b)
  564. {
  565. const auto h = bands[b] * scope.getHeight();
  566. g.fillRect (scope.getX() + (float) b * w, scope.getBottom() - h, juce::jmax (1.0f, w - 0.5f), h);
  567. }
  568. return;
  569. }
  570. // oscilloscope
  571. g.setColour (colour::border);
  572. g.drawHorizontalLine ((int) scope.getCentreY(), scope.getX(), scope.getRight());
  573. juce::Path wave;
  574. const auto mid = scope.getCentreY();
  575. const auto half = scope.getHeight() * 0.47f;
  576. const auto width = juce::jmax (1, (int) scope.getWidth());
  577. for (int x = 0; x < width; ++x)
  578. {
  579. const auto index = (std::size_t) (x * (int) samples.size() / width);
  580. const auto y = mid - juce::jlimit (-1.0f, 1.0f, samples[index]) * half;
  581. if (x == 0)
  582. wave.startNewSubPath (scope.getX(), y);
  583. else
  584. wave.lineTo (scope.getX() + (float) x, y);
  585. }
  586. g.setColour (lineColour);
  587. g.strokePath (wave, juce::PathStrokeType (1.3f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  588. }
  589. ui::Hint OutputMonitor::hintAt (juce::Point<int>)
  590. {
  591. ui::Hint h;
  592. h.text = tr ("Output: {0} and the peak level of what you hear (the meter's top turns red when it clipped) [LMB] next display [RMB] display menu",
  593. { modeName (mode).toLowerCase() });
  594. h.hasMenu = true;
  595. h.value = held <= 1.0e-5f ? juce::String ("-inf dB") : juce::String (juce::Decibels::gainToDecibels (held), 1) + " dB";
  596. return h;
  597. }
  598. // --- customize -------------------------------------------------------------------------------------
  599. CustomizePanel::CustomizePanel (const toolbarlayout::Layout& l) : layout (l)
  600. {
  601. setWantsKeyboardFocus (true);
  602. upButton.setButtonText (tr ("Move up"));
  603. downButton.setButtonText (tr ("Move down"));
  604. resetButton.setButtonText (tr ("Reset to default"));
  605. upButton.onClick = [this] { move (-1); };
  606. downButton.onClick = [this] { move (1); };
  607. resetButton.onClick = [this] {
  608. layout = toolbarlayout::Layout::makeDefault();
  609. iconSizeBox.setSelectedId ((int) layout.iconSize + 1, juce::dontSendNotification);
  610. scaleBox.setSelectedId (layout.uiScale, juce::dontSendNotification);
  611. rebuild();
  612. changed();
  613. };
  614. iconSizeBox.addItem (tr ("Small icons"), 1);
  615. iconSizeBox.addItem (tr ("Medium icons"), 2);
  616. iconSizeBox.addItem (tr ("Large icons"), 3);
  617. iconSizeBox.setSelectedId ((int) layout.iconSize + 1, juce::dontSendNotification);
  618. iconSizeBox.onChange = [this] {
  619. layout.iconSize = (toolbarlayout::IconSize) (iconSizeBox.getSelectedId() - 1);
  620. changed();
  621. };
  622. for (auto percent : toolbarlayout::uiScales)
  623. scaleBox.addItem (juce::String (percent) + "%", percent);
  624. if (scaleBox.indexOfItemId (layout.uiScale) < 0)
  625. scaleBox.addItem (juce::String (layout.uiScale) + "%", layout.uiScale);
  626. scaleBox.setSelectedId (layout.uiScale, juce::dontSendNotification);
  627. scaleBox.onChange = [this] {
  628. layout.uiScale = toolbarlayout::clampScale (scaleBox.getSelectedId());
  629. changed();
  630. };
  631. for (auto* c : std::initializer_list<juce::Component*> { &upButton, &downButton, &resetButton, &iconSizeBox, &scaleBox })
  632. addAndMakeVisible (c);
  633. ui::setHint (iconSizeBox, tr ("Size of the toolbar icons and of the editors' tool icons (Piano Roll, Playlist)"));
  634. ui::setHint (scaleBox, tr ("Scales the whole interface: text, icons and windows. Useful on high-resolution screens"));
  635. rebuild();
  636. setSize (460, 2 * 16 + 24 + toolbarlayout::groupCount * rowHeight + rowHeight + 16 + 2 * 34 + 12 + 30);
  637. }
  638. juce::Rectangle<int> CustomizePanel::listArea() const
  639. {
  640. return getLocalBounds().reduced (16).withTrimmedTop (24).withHeight ((toolbarlayout::groupCount + 1) * rowHeight).withTrimmedRight (140);
  641. }
  642. void CustomizePanel::rebuild()
  643. {
  644. checks.clear();
  645. for (const auto& entry : layout.entries)
  646. {
  647. auto* check = checks.add (new juce::ToggleButton (tr (toolbarlayout::groupName (entry.group))));
  648. check->setToggleState (entry.shown, juce::dontSendNotification);
  649. check->setWantsKeyboardFocus (false);
  650. const auto group = entry.group;
  651. check->onClick = [this, check, group] {
  652. layout.setShown (group, check->getToggleState());
  653. select (group);
  654. changed();
  655. };
  656. // the transport can be hidden, but it is the last group to drop when the window is narrow
  657. addAndMakeVisible (check);
  658. }
  659. resized();
  660. repaint();
  661. }
  662. void CustomizePanel::select (toolbarlayout::Group g)
  663. {
  664. selected = g;
  665. const auto at = layout.indexOf (g);
  666. upButton.setEnabled (at > 0);
  667. downButton.setEnabled (at >= 0 && at < (int) layout.entries.size() - 1);
  668. repaint();
  669. }
  670. void CustomizePanel::changed()
  671. {
  672. if (onChange)
  673. onChange (layout);
  674. }
  675. void CustomizePanel::move (int delta)
  676. {
  677. if (layout.move (selected, delta))
  678. {
  679. rebuild();
  680. select (selected);
  681. changed();
  682. }
  683. }
  684. void CustomizePanel::resized()
  685. {
  686. auto list = listArea();
  687. list.removeFromTop (rowHeight); // the fixed first row: the menu and the hint bar
  688. for (auto* check : checks)
  689. check->setBounds (list.removeFromTop (rowHeight).reduced (8, 3));
  690. auto side = getLocalBounds().reduced (16).withTrimmedTop (24 + rowHeight).withLeft (listArea().getRight() + 12);
  691. upButton.setBounds (side.removeFromTop (28));
  692. side.removeFromTop (6);
  693. downButton.setBounds (side.removeFromTop (28));
  694. auto bottom = getLocalBounds().reduced (16).withTop (listArea().getBottom() + 16);
  695. auto row = bottom.removeFromTop (28);
  696. row.removeFromLeft (110);
  697. iconSizeBox.setBounds (row.removeFromLeft (140));
  698. bottom.removeFromTop (6);
  699. row = bottom.removeFromTop (28);
  700. row.removeFromLeft (110);
  701. scaleBox.setBounds (row.removeFromLeft (140));
  702. bottom.removeFromTop (12);
  703. resetButton.setBounds (bottom.removeFromTop (28).removeFromLeft (160));
  704. select (selected);
  705. }
  706. void CustomizePanel::paint (juce::Graphics& g)
  707. {
  708. using namespace theme;
  709. g.fillAll (colour::bg2);
  710. auto area = getLocalBounds().reduced (16);
  711. g.setFont (font (type::small, true));
  712. g.setColour (colour::textSecondary);
  713. g.drawText (tr ("Toolbar groups, left to right (uncheck to hide):"), area.removeFromTop (20), juce::Justification::centredLeft);
  714. auto list = listArea();
  715. g.setColour (colour::bg1);
  716. g.fillRoundedRectangle (list.toFloat(), radius::md);
  717. auto first = list.removeFromTop (rowHeight).reduced (8, 3);
  718. g.setFont (font (type::body));
  719. g.setColour (colour::textDisabled);
  720. g.drawText (tr ("Menu and hint bar (always first)"), first.withTrimmedLeft (28), juce::Justification::centredLeft);
  721. const auto at = layout.indexOf (selected);
  722. if (at >= 0)
  723. {
  724. g.setColour (colour::accent.withAlpha (0.18f));
  725. g.fillRoundedRectangle (list.withY (list.getY() + at * rowHeight).withHeight (rowHeight).reduced (2).toFloat(), radius::md);
  726. }
  727. auto bottom = getLocalBounds().reduced (16).withTop (listArea().getBottom() + 16);
  728. g.setColour (colour::textSecondary);
  729. g.drawText (tr ("Icon size"), bottom.removeFromTop (28).withWidth (104), juce::Justification::centredLeft);
  730. bottom.removeFromTop (6);
  731. g.drawText (tr ("UI scale"), bottom.removeFromTop (28).withWidth (104), juce::Justification::centredLeft);
  732. }
  733. void CustomizePanel::mouseDown (const juce::MouseEvent& e)
  734. {
  735. auto list = listArea();
  736. list.removeFromTop (rowHeight);
  737. if (list.contains (e.getPosition()))
  738. {
  739. const auto row = (e.y - list.getY()) / rowHeight;
  740. if (row >= 0 && row < (int) layout.entries.size())
  741. select (layout.entries[(std::size_t) row].group);
  742. }
  743. }
  744. bool CustomizePanel::keyPressed (const juce::KeyPress& key)
  745. {
  746. const auto up = key.getKeyCode() == juce::KeyPress::upKey, down = key.getKeyCode() == juce::KeyPress::downKey;
  747. if (! up && ! down)
  748. return false;
  749. if (key.getModifiers().isAltDown())
  750. move (up ? -1 : 1);
  751. else
  752. {
  753. const auto at = juce::jlimit (0, (int) layout.entries.size() - 1, layout.indexOf (selected) + (up ? -1 : 1));
  754. select (layout.entries[(std::size_t) at].group);
  755. }
  756. return true;
  757. }
  758. } // namespace lynx::toolbar
  759. // The process memory comes from the OS; its headers go last (windows.h defines macros such as `small`).
  760. #if JUCE_WINDOWS
  761. #ifndef NOMINMAX
  762. #define NOMINMAX
  763. #endif
  764. #define PSAPI_VERSION 2 // GetProcessMemoryInfo from kernel32 (K32GetProcessMemoryInfo): no extra library
  765. #include <windows.h>
  766. #include <psapi.h>
  767. #endif
  768. std::int64_t lynx::toolbar::PerformanceMeter::processMemoryBytes()
  769. {
  770. #if JUCE_WINDOWS
  771. PROCESS_MEMORY_COUNTERS counters {};
  772. if (GetProcessMemoryInfo (GetCurrentProcess(), &counters, sizeof (counters)))
  773. return (std::int64_t) counters.WorkingSetSize;
  774. return 0;
  775. #elif JUCE_LINUX
  776. // resident pages, from /proc
  777. const auto fields = juce::StringArray::fromTokens (juce::File ("/proc/self/statm").loadFileAsString(), " ", "");
  778. return fields.size() > 1 ? (std::int64_t) fields[1].getLargeIntValue() * 4096 : 0;
  779. #else
  780. return 0;
  781. #endif
  782. }