PianoRollComponent.cpp 129 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377
  1. #include "ui/PianoRollComponent.h"
  2. #include "core/EditorPolish.h"
  3. #include "core/EventEdit.h"
  4. #include "core/NoteEdit.h"
  5. #include "core/NoteTools.h"
  6. #include "engine/MidiFileIo.h"
  7. #include "ui/Dialogs.h"
  8. #include "engine/Text.h"
  9. #include "ui/AutomationUi.h"
  10. #include "ui/EventEditor.h"
  11. #include "ui/HintBar.h"
  12. #include "ui/I18n.h"
  13. #include "ui/Theme.h"
  14. namespace lynx
  15. {
  16. namespace
  17. {
  18. bool isBlackKey (int key)
  19. {
  20. const auto n = key % 12;
  21. return n == 1 || n == 3 || n == 6 || n == 8 || n == 10;
  22. }
  23. // FL-style name: key 60 = C5.
  24. juce::String keyName (int key)
  25. {
  26. static const char* names[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  27. return juce::String (names[key % 12]) + juce::String (key / 12);
  28. }
  29. const Pattern& currentPattern (const Song& s)
  30. {
  31. return s.patterns[(std::size_t) s.currentPattern];
  32. }
  33. Pattern& currentPattern (Song& s)
  34. {
  35. return s.patterns[(std::size_t) s.currentPattern];
  36. }
  37. struct NamedIntervals
  38. {
  39. const char* name;
  40. std::vector<int> intervals;
  41. };
  42. const std::vector<NamedIntervals>& chords()
  43. {
  44. static const std::vector<NamedIntervals> list {
  45. { TR_NOOP ("Note"), { 0 } }, { TR_NOOP ("Major"), { 0, 4, 7 } }, { TR_NOOP ("Minor"), { 0, 3, 7 } }, { "Dim", { 0, 3, 6 } },
  46. { "Aug", { 0, 4, 8 } }, { "Sus2", { 0, 2, 7 } }, { "Sus4", { 0, 5, 7 } }, { "7", { 0, 4, 7, 10 } },
  47. { "Maj7", { 0, 4, 7, 11 } }, { "m7", { 0, 3, 7, 10 } }, { "m9", { 0, 3, 7, 10, 14 } }, { TR_NOOP ("Octave"), { 0, 12 } },
  48. };
  49. return list;
  50. }
  51. const std::vector<notetools::ScaleInfo>& scales()
  52. {
  53. return notetools::scales();
  54. }
  55. } // namespace
  56. PianoRollComponent::PianoRollComponent (AudioEngine& e)
  57. : engine (e)
  58. {
  59. auto sender = [this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on); };
  60. previewNotes.setSender (sender);
  61. listenNotes.setSender (sender);
  62. setWantsKeyboardFocus (false);
  63. setMouseClickGrabsKeyboardFocus (false);
  64. for (auto* bar : { &hBar, &vBar })
  65. {
  66. bar->addListener (this);
  67. bar->setAutoHide (false);
  68. addAndMakeVisible (bar);
  69. }
  70. // the overview strip is the horizontal scroller (FL's Piano Roll has its preview bar on top)
  71. hBar.setVisible (false);
  72. overview.paintContent = [this] (juce::Graphics& g, juce::Rectangle<float> area, double total) { paintOverview (g, area, total); };
  73. overview.onChange = [this] (double start, double length) {
  74. const auto width = (double) gridArea().getWidth();
  75. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, width / juce::jmax (1.0, length));
  76. scrollTicks = juce::jmax (0.0, start);
  77. updateScrollBars();
  78. repaint();
  79. };
  80. overview.onShowAll = [this] { zoomAll(); };
  81. addAndMakeVisible (overview);
  82. grid::fillEditorBox (snapBox);
  83. snapBox.setTooltip (tr ("Piano Roll grid: follows the global grid in the toolbar, or its own; hold Alt while dragging to ignore it"));
  84. snapBox.setWantsKeyboardFocus (false);
  85. snapBox.setMouseClickGrabsKeyboardFocus (false);
  86. snapBox.onChange = [this] { repaint(); };
  87. addAndMakeVisible (snapBox);
  88. tools.onChange = [this] (EditTool) {
  89. stopListening();
  90. updateCursor (juce::ModifierKeys::currentModifiers);
  91. };
  92. addAndMakeVisible (tools);
  93. channelBox.setTooltip (tr ("Channel being edited (marked: has notes in this pattern). Wheel: channels with notes; Ctrl+wheel: all"));
  94. channelBox.setWantsKeyboardFocus (false);
  95. channelBox.setMouseClickGrabsKeyboardFocus (false);
  96. channelBox.onChange = [this] {
  97. const auto channel = channelBox.getSelectedId() - 1;
  98. if (channel >= 0 && channel < (int) engine.getSong().channels.size() && channel != engine.getSelectedChannel())
  99. engine.setSelectedChannel (channel);
  100. };
  101. channelBox.onStep = [this] (int direction, bool all) { stepChannel (direction, ! all); };
  102. addAndMakeVisible (channelBox);
  103. ghostButton.setClickingTogglesState (true);
  104. ghostButton.setToggleState (showGhosts, juce::dontSendNotification);
  105. ghostButton.setOnColour (theme::colour::bg6);
  106. ghostButton.setIconColourWhenOn (theme::colour::textPrimary);
  107. ghostButton.setFlat (true);
  108. ghostButton.setTooltip (tr ("Ghost notes: show the other channels' notes (Alt+V) and, outlined, this channel's notes in the clips "
  109. "playing at the same time; double right-click one to edit its channel; Ctrl+Alt+V makes them editable"));
  110. ui::setQuickTip (ghostButton, tr ("Ghost notes"), "Alt+V");
  111. ui::setQuickTip (moreButton, tr ("Note tools"));
  112. ui::setQuickTip (scaleSnapButton, tr ("Snap to scale"));
  113. ghostButton.onClick = [this] {
  114. showGhosts = ghostButton.getToggleState();
  115. repaint();
  116. };
  117. moreButton.setFlat (true);
  118. moreButton.setTooltip (tr ("Note operations, left-edge resizing and MIDI import/export"));
  119. moreButton.onClick = [this] { showMoreMenu(); };
  120. scaleSnapButton.setOnColour (theme::colour::bg6);
  121. scaleSnapButton.setIconColourWhenOn (theme::colour::accent);
  122. scaleSnapButton.setFlat (true);
  123. scaleSnapButton.setTooltip (tr ("Snap notes to the scale: new and moved notes, and incoming MIDI, land on the chosen scale"));
  124. scaleSnapButton.onClick = [this] { setScaleSnap (! scaleSnap); };
  125. for (auto* b : { &ghostButton, &scaleSnapButton, &moreButton })
  126. {
  127. b->setWantsKeyboardFocus (false);
  128. b->setMouseClickGrabsKeyboardFocus (false);
  129. addAndMakeVisible (*b);
  130. }
  131. for (int i = 0; i < (int) chords().size(); ++i)
  132. chordBox.addItem (tr (chords()[(std::size_t) i].name), i + 1);
  133. chordBox.setSelectedId (1, juce::dontSendNotification);
  134. chordBox.setTooltip (tr ("Clicking creates this chord (the clicked note is the root)"));
  135. // scale: root x type
  136. static const char* noteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  137. for (int s = 0; s < (int) scales().size(); ++s)
  138. {
  139. if (s == 0)
  140. {
  141. scaleBox.addItem (tr (scales()[0].name), 1);
  142. continue;
  143. }
  144. for (int root = 0; root < 12; ++root)
  145. scaleBox.addItem (tr ("{0} {1}", { juce::String (noteNames[root]), tr (scales()[(std::size_t) s].name) }), s * 100 + root + 1);
  146. }
  147. scaleBox.setSelectedId (1, juce::dontSendNotification);
  148. scaleSnapButton.setEnabled (false); // until a scale is chosen
  149. scaleBox.setTooltip (tr ("Highlights the notes of a scale"));
  150. slideButton.setClickingTogglesState (true);
  151. slideButton.setTooltip (tr ("New notes are \"slide\" notes: the currently sounding note glides to them (808 glide)"));
  152. slideButton.setWantsKeyboardFocus (false);
  153. slideButton.setMouseClickGrabsKeyboardFocus (false);
  154. slideButton.setButtonText (tr ("Slide"));
  155. slideButton.setColour (juce::TextButton::buttonOnColourId, theme::colour::accent);
  156. addAndMakeVisible (slideButton);
  157. colourButton.setTooltip (tr ("Note colour: new notes get this colour. Click: choose it, colour the selection (Alt+C), "
  158. "select by colour (Shift+C)"));
  159. ui::setQuickTip (colourButton, tr ("Note colour"));
  160. colourButton.setWantsKeyboardFocus (false);
  161. colourButton.setMouseClickGrabsKeyboardFocus (false);
  162. colourButton.onClick = [this] { showColourMenu(); };
  163. addAndMakeVisible (colourButton);
  164. chordLabel.setJustificationType (juce::Justification::centred);
  165. chordLabel.setFont (theme::font (theme::type::caption, true));
  166. chordLabel.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  167. chordLabel.setTooltip (tr ("Chord: the chord of the keys held on the MIDI keyboard or the typing piano, else of the selected notes"));
  168. chordLabel.setInterceptsMouseClicks (true, false);
  169. addAndMakeVisible (chordLabel);
  170. for (auto* box : { &chordBox, &scaleBox })
  171. {
  172. box->setWantsKeyboardFocus (false);
  173. box->setMouseClickGrabsKeyboardFocus (false);
  174. box->onChange = [this] {
  175. publishScale();
  176. scaleSnapButton.setEnabled (scaleIndex() > 0);
  177. repaint();
  178. };
  179. addAndMakeVisible (box);
  180. }
  181. laneBox.addItem (tr ("Velocity"), 1);
  182. laneBox.addItem (tr ("Pan"), 2);
  183. laneBox.addItem (tr ("Fine pitch"), 3);
  184. laneBox.setTooltip (tr ("What the bottom lane edits"));
  185. laneBox.setSelectedId (1, juce::dontSendNotification);
  186. laneBox.setWantsKeyboardFocus (false);
  187. laneBox.setMouseClickGrabsKeyboardFocus (false);
  188. laneBox.onChange = [this] { repaint(); };
  189. addAndMakeVisible (laneBox);
  190. setOpaque (true); // paints every pixel: nothing behind it is redrawn while scrolling
  191. engine.addChangeListener (this);
  192. EditorGlobals::get().addChangeListener (this);
  193. refreshChannelBox();
  194. startTimerHz (30);
  195. }
  196. PianoRollComponent::~PianoRollComponent()
  197. {
  198. stopListening();
  199. previewNotes.releaseAll();
  200. EditorGlobals::get().removeChangeListener (this);
  201. engine.removeChangeListener (this);
  202. }
  203. juce::Rectangle<int> PianoRollComponent::gridArea() const
  204. {
  205. return getLocalBounds().withTrimmedLeft (keyboardWidth).withTrimmedTop (headerHeight)
  206. .withTrimmedRight (scrollBarSize).withTrimmedBottom (velocityHeight);
  207. }
  208. juce::Rectangle<int> PianoRollComponent::velocityArea() const
  209. {
  210. const auto grid = gridArea();
  211. return { grid.getX(), grid.getBottom(), grid.getWidth(), velocityHeight };
  212. }
  213. double PianoRollComponent::tickToX (double tick) const
  214. {
  215. return keyboardWidth + (tick - scrollTicks) * pixelsPerTick;
  216. }
  217. double PianoRollComponent::xToTick (int x) const
  218. {
  219. return (x - keyboardWidth) / pixelsPerTick + scrollTicks;
  220. }
  221. int PianoRollComponent::keyToY (int key) const
  222. {
  223. return headerHeight + (127 - key) * rowHeight - scrollY;
  224. }
  225. int PianoRollComponent::yToKey (int y) const
  226. {
  227. return juce::jlimit (0, 127, 127 - (y - headerHeight + scrollY) / rowHeight);
  228. }
  229. std::int64_t PianoRollComponent::gridTicks() const
  230. {
  231. const auto bar = (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  232. const auto& option = grid::resolve (snapBox);
  233. switch (option.kind)
  234. {
  235. case grid::Kind::none: return 1;
  236. case grid::Kind::ticks: return option.ticks;
  237. case grid::Kind::bar: return bar;
  238. case grid::Kind::screen:
  239. case grid::Kind::nearest: break;
  240. }
  241. return noteedit::screenStep (pixelsPerTick, bar);
  242. }
  243. std::vector<std::int64_t> PianoRollComponent::snapCandidates() const
  244. {
  245. // edges of this channel's notes (except the ones being dragged) and of the visible ghosts
  246. std::vector<std::int64_t> out;
  247. const auto& notes = currentPattern (engine.getSong()).notes;
  248. const auto channel = engine.getSelectedChannel();
  249. for (int i = 0; i < (int) notes.size(); ++i)
  250. {
  251. const auto& n = notes[(std::size_t) i];
  252. if ((n.channel != channel && ! showGhosts) || std::find (dragIndices.begin(), dragIndices.end(), i) != dragIndices.end())
  253. continue;
  254. out.push_back (n.start);
  255. out.push_back (n.start + n.length);
  256. }
  257. return out;
  258. }
  259. std::int64_t PianoRollComponent::snap (double tick, bool enabled) const
  260. {
  261. if (! enabled)
  262. return (std::int64_t) std::floor (tick);
  263. if (grid::resolve (snapBox).kind == grid::Kind::nearest)
  264. return noteedit::snapNearest (tick, snapCandidates(), 10.0 / pixelsPerTick, gridTicks());
  265. return noteedit::snapDown (tick, gridTicks());
  266. }
  267. std::int64_t PianoRollComponent::newNoteLength() const
  268. {
  269. const auto fixed = EditorGlobals::get().getDefaultNoteLength();
  270. return fixed > 0 ? fixed : lastLength;
  271. }
  272. std::int64_t PianoRollComponent::viewLengthTicks() const
  273. {
  274. const auto& song = engine.getSong();
  275. const auto bar = (std::int64_t) ppq * song.beatsPerBar;
  276. // pattern + 4 bars of headroom to grow
  277. return currentPattern (song).effectiveLength (song.beatsPerBar) + 4 * bar;
  278. }
  279. void PianoRollComponent::updateScrollBars()
  280. {
  281. const auto grid = gridArea();
  282. const auto total = (double) viewLengthTicks();
  283. hBar.setRangeLimits (0.0, total, juce::dontSendNotification);
  284. hBar.setCurrentRange (scrollTicks, grid.getWidth() / pixelsPerTick, juce::dontSendNotification);
  285. vBar.setRangeLimits (0.0, 128.0 * rowHeight, juce::dontSendNotification);
  286. vBar.setCurrentRange (scrollY, grid.getHeight(), juce::dontSendNotification);
  287. scrollTicks = hBar.getCurrentRangeStart();
  288. scrollY = (int) vBar.getCurrentRangeStart();
  289. overview.minLength = grid.getWidth() / (120.0 / ticksPerStep);
  290. overview.setRange (total, scrollTicks, grid.getWidth() / pixelsPerTick);
  291. }
  292. void PianoRollComponent::setTitleBarInsets (int left, int right)
  293. {
  294. if (left != titleInsetLeft || right != titleInsetRight)
  295. {
  296. titleInsetLeft = left;
  297. titleInsetRight = right;
  298. resized();
  299. }
  300. }
  301. void PianoRollComponent::resized()
  302. {
  303. const auto h = toolbarHeight - 6;
  304. auto bar = juce::Rectangle<int> (4 + titleInsetLeft, 3, juce::jmax (0, getWidth() - 8 - titleInsetLeft - titleInsetRight), h);
  305. // groups that don't fit in a narrow window are hidden (the tools and the grid always show)
  306. auto place = [&bar] (juce::Component& c, int width, bool optional = false) {
  307. const auto fits = ! optional || width <= bar.getWidth();
  308. c.setVisible (fits);
  309. c.setBounds (fits ? bar.removeFromLeft (juce::jmin (width, bar.getWidth())) : juce::Rectangle<int>());
  310. bar.removeFromLeft (juce::jmin (6, bar.getWidth()));
  311. };
  312. place (channelBox, 150);
  313. place (tools, tools.getIdealWidth (h));
  314. place (snapBox, 128);
  315. place (ghostButton, h);
  316. place (slideButton, 54, true);
  317. place (colourButton, h, true);
  318. place (chordBox, 86, true);
  319. place (scaleBox, 150, true);
  320. if (scaleBox.isVisible())
  321. place (scaleSnapButton, h);
  322. else
  323. scaleSnapButton.setVisible (false);
  324. place (moreButton, h);
  325. place (chordLabel, 84, true);
  326. laneBox.setBounds (2, velocityArea().getY() + 4, keyboardWidth - 4, 20);
  327. overview.setBounds (keyboardWidth, toolbarHeight, getWidth() - keyboardWidth - scrollBarSize, overviewHeight);
  328. vBar.setBounds (getWidth() - scrollBarSize, headerHeight, scrollBarSize, getHeight() - headerHeight - velocityHeight);
  329. updateScrollBars();
  330. }
  331. void PianoRollComponent::scrollToNotes (bool fitPattern)
  332. {
  333. const auto& song = engine.getSong();
  334. const auto channel = engine.getSelectedChannel();
  335. int low = 128, high = -1;
  336. for (const auto& n : currentPattern (song).notes)
  337. if (n.channel == channel)
  338. {
  339. low = juce::jmin (low, n.key);
  340. high = juce::jmax (high, n.key);
  341. }
  342. refreshChannelBox();
  343. const auto centreKey = high >= 0 ? (low + high) / 2 : 66;
  344. scrollY = (127 - centreKey) * rowHeight - gridArea().getHeight() / 2;
  345. scrollTicks = 0.0;
  346. // FL opens the Piano Roll with the whole pattern across the view (at least one bar)
  347. if (fitPattern && gridArea().getWidth() > 0)
  348. {
  349. const auto bar = (double) ppq * juce::jmax (1, song.beatsPerBar);
  350. const auto length = juce::jmax (bar, (double) currentPattern (song).effectiveLength (song.beatsPerBar));
  351. pixelsPerTick = juce::jlimit (4.0 / ticksPerStep, 64.0 / ticksPerStep, gridArea().getWidth() / length);
  352. }
  353. updateScrollBars();
  354. repaint();
  355. }
  356. // --- selection ---------------------------------------------------------------
  357. std::vector<int> PianoRollComponent::chordIntervals() const
  358. {
  359. const auto index = juce::jlimit (0, (int) chords().size() - 1, chordBox.getSelectedId() - 1);
  360. return chords()[(std::size_t) index].intervals;
  361. }
  362. int PianoRollComponent::scaleIndex() const
  363. {
  364. const auto id = scaleBox.getSelectedId();
  365. return id <= 1 ? 0 : id / 100;
  366. }
  367. int PianoRollComponent::scaleRoot() const
  368. {
  369. const auto id = scaleBox.getSelectedId();
  370. return id <= 1 ? 0 : (id % 100) - 1;
  371. }
  372. bool PianoRollComponent::inScale (int key) const
  373. {
  374. return scaleIndex() > 0 && notetools::inScale (key, scaleRoot(), scaleIndex());
  375. }
  376. int PianoRollComponent::snapKey (int key) const
  377. {
  378. return scaleSnap ? notetools::snapToScale (key, scaleRoot(), scaleIndex()) : key;
  379. }
  380. void PianoRollComponent::setScaleSnap (bool on)
  381. {
  382. scaleSnap = on;
  383. scaleSnapButton.setToggleState (on, juce::dontSendNotification);
  384. publishScale();
  385. repaint();
  386. }
  387. void PianoRollComponent::publishScale()
  388. {
  389. engine.setInputScale (scaleSnap ? scaleIndex() : 0, scaleRoot());
  390. }
  391. bool PianoRollComponent::isSelected (int index) const
  392. {
  393. return std::binary_search (selection.begin(), selection.end(), index);
  394. }
  395. std::vector<int> PianoRollComponent::channelNotes() const
  396. {
  397. const auto& notes = currentPattern (engine.getSong()).notes;
  398. const auto channel = engine.getSelectedChannel();
  399. std::vector<int> out;
  400. for (int i = 0; i < (int) notes.size(); ++i)
  401. if (notes[(std::size_t) i].channel == channel)
  402. out.push_back (i);
  403. return out;
  404. }
  405. std::vector<int> PianoRollComponent::selectionOrAll() const
  406. {
  407. return selection.empty() ? channelNotes() : selection;
  408. }
  409. void PianoRollComponent::setSelection (std::vector<int> indices)
  410. {
  411. std::sort (indices.begin(), indices.end());
  412. indices.erase (std::unique (indices.begin(), indices.end()), indices.end());
  413. selection = std::move (indices);
  414. repaint();
  415. }
  416. void PianoRollComponent::selectAll()
  417. {
  418. setSelection (channelNotes());
  419. }
  420. void PianoRollComponent::editNotes (const std::function<void (Pattern&)>& edit, bool undoable)
  421. {
  422. engine.editSong ([&edit] (Song& s) { edit (currentPattern (s)); }, undoable);
  423. knownNoteCount = currentPattern (engine.getSong()).notes.size();
  424. }
  425. void PianoRollComponent::sortNotes()
  426. {
  427. auto tracked = selection;
  428. tracked.push_back (dragNote);
  429. // only reorders: no undo step of its own needed
  430. engine.editSong ([&tracked] (Song& s) { noteedit::sortTracking (currentPattern (s), tracked); }, false);
  431. dragNote = tracked.back();
  432. tracked.pop_back();
  433. setSelection (tracked);
  434. }
  435. juce::Rectangle<float> PianoRollComponent::stretchHandle() const
  436. {
  437. // a tab on the right end of the selection, vertically centred on it (clamped into the grid)
  438. const auto& notes = currentPattern (engine.getSong()).notes;
  439. const auto channel = engine.getSelectedChannel();
  440. std::int64_t start = 0, end = 0;
  441. int top = -1, bottom = 128;
  442. bool any = false;
  443. for (auto i : selection)
  444. {
  445. if (i < 0 || i >= (int) notes.size() || notes[(std::size_t) i].channel != channel)
  446. continue;
  447. const auto& n = notes[(std::size_t) i];
  448. start = any ? juce::jmin (start, n.start) : n.start;
  449. end = any ? juce::jmax (end, n.start + n.length) : n.start + n.length;
  450. top = juce::jmax (top, n.key);
  451. bottom = juce::jmin (bottom, n.key);
  452. any = true;
  453. }
  454. if (! any || end <= start)
  455. return {};
  456. const auto grid = gridArea().toFloat();
  457. const auto x = (float) tickToX ((double) end);
  458. const auto y0 = (float) keyToY (top), y1 = (float) (keyToY (bottom) + rowHeight);
  459. const auto cy = juce::jlimit (grid.getY() + 10.0f, juce::jmax (grid.getY() + 10.0f, grid.getBottom() - 10.0f), (y0 + y1) * 0.5f);
  460. const auto r = juce::Rectangle<float> (x + 2.0f, cy - 9.0f, 9.0f, 18.0f);
  461. return grid.intersects (r) ? r : juce::Rectangle<float>();
  462. }
  463. void PianoRollComponent::drumPaintAt (juce::Point<int> p, bool snapOn)
  464. {
  465. // one short hit per grid cell and key, on whatever key is under the mouse (FL's drum painting)
  466. const auto cell = juce::jmax<std::int64_t> (1, snapOn ? gridTicks() : ticksPerStep);
  467. const auto start = juce::jmax<std::int64_t> (0, snapOn ? snap (xToTick (p.x), true) : noteedit::snapDown (xToTick (p.x), cell));
  468. const auto key = snapKey (yToKey (p.y));
  469. if (start == lastDrumCell && key == lastDrumKey)
  470. return;
  471. lastDrumCell = start;
  472. lastDrumKey = key;
  473. const auto channel = engine.getSelectedChannel();
  474. if (polish::hasNoteInCell (currentPattern (engine.getSong()), channel, key, start, cell))
  475. return;
  476. Note n;
  477. n.start = start;
  478. n.length = cell;
  479. n.key = key;
  480. n.channel = channel;
  481. n.colour = noteColour;
  482. editNotes ([&n] (Pattern& pat) { noteedit::paste (pat, { n }, 0); });
  483. if (key != previewKey)
  484. previewOn (key, n.velocity);
  485. }
  486. // --- painting ------------------------------------------------------------------
  487. void PianoRollComponent::paintOverview (juce::Graphics& g, juce::Rectangle<float> area, double total)
  488. {
  489. // the channel's notes across the whole view length, pitch mapped onto the strip's height; the part past
  490. // the pattern's end is darker; bar lines every bar (every 4 when they get dense)
  491. using namespace theme::colour;
  492. const auto& song = engine.getSong();
  493. const auto& pattern = currentPattern (song);
  494. const auto channel = engine.getSelectedChannel();
  495. const auto scale = area.getWidth() / juce::jmax (1.0, total);
  496. const auto bar = (double) ppq * juce::jmax (1, song.beatsPerBar);
  497. const auto end = (float) (pattern.effectiveLength (song.beatsPerBar) * scale);
  498. g.setColour (bg2);
  499. g.fillRect (area.withWidth (juce::jmin (area.getWidth(), end)));
  500. const auto every = bar * scale < 6.0 ? 4 : 1;
  501. g.setColour (gridBar.withAlpha (0.6f));
  502. for (int b = every; b * bar < total; b += every)
  503. g.fillRect ((float) (area.getX() + b * bar * scale), area.getY(), 1.0f, area.getHeight());
  504. int low = 128, high = -1;
  505. for (const auto& n : pattern.notes)
  506. if (n.channel == channel)
  507. {
  508. low = juce::jmin (low, n.key);
  509. high = juce::jmax (high, n.key);
  510. }
  511. if (high < 0)
  512. return;
  513. const auto span = (float) juce::jmax (12, high - low + 1);
  514. const auto mid = (low + high) / 2.0f;
  515. const auto inner = area.reduced (0.0f, 2.0f);
  516. auto colour = accent;
  517. if (channel < (int) song.channels.size() && song.channels[(std::size_t) channel].colour != 0)
  518. colour = theme::tame (juce::Colour (song.channels[(std::size_t) channel].colour));
  519. colour = colour.interpolatedWith (textPrimary, 0.35f); // reads on the dark strip at any channel colour
  520. for (const auto& n : pattern.notes)
  521. {
  522. if (n.channel != channel)
  523. continue;
  524. const auto y = inner.getCentreY() - ((float) n.key - mid) / span * inner.getHeight();
  525. const auto x = area.getX() + (float) (n.start * scale);
  526. g.setColour (n.muted ? colour.withAlpha (0.35f) : colour);
  527. g.fillRect (x, juce::jlimit (inner.getY(), inner.getBottom() - 2.0f, y - 1.0f),
  528. juce::jmax (1.0f, (float) (n.length * scale) - 0.5f), 2.0f);
  529. }
  530. }
  531. void PianoRollComponent::paint (juce::Graphics& g)
  532. {
  533. const auto& song = engine.getSong();
  534. const auto& pattern = currentPattern (song);
  535. const auto channel = engine.getSelectedChannel();
  536. const auto grid = gridArea();
  537. const auto patternLength = pattern.effectiveLength (song.beatsPerBar);
  538. const auto bar = (std::int64_t) ppq * song.beatsPerBar;
  539. const auto snapGrid = gridTicks();
  540. // the overview follows the notes (edits, undo, another channel or pattern) and the view
  541. {
  542. auto signature = (std::size_t) song.currentPattern * 1000003u + (std::size_t) channel * 7919u + pattern.notes.size();
  543. for (const auto& n : pattern.notes)
  544. signature = signature * 31u + (std::size_t) (n.start * 131 + n.length * 7 + n.key + n.channel * 257 + (n.muted ? 1 : 0));
  545. if (signature != overviewSignature)
  546. {
  547. overviewSignature = signature;
  548. overview.repaint();
  549. }
  550. overview.setRange ((double) viewLengthTicks(), scrollTicks, grid.getWidth() / pixelsPerTick);
  551. }
  552. using namespace theme::colour;
  553. g.fillAll (bg1);
  554. g.setColour (bg3);
  555. g.fillRect (0, 0, getWidth(), toolbarHeight);
  556. g.setColour (border);
  557. g.fillRect (0, toolbarHeight - 1, getWidth(), 1);
  558. auto drawVerticalGrid = [&] (juce::Rectangle<int> area) {
  559. // grid lines: bar > beat > snap (unless too dense)
  560. const auto step = snapGrid * pixelsPerTick >= 6.0 ? snapGrid : (std::int64_t) ppq;
  561. const auto first = (std::int64_t) std::floor (scrollTicks / (double) step);
  562. const auto last = (std::int64_t) std::ceil (xToTick (area.getRight()) / (double) step);
  563. for (auto i = first; i <= last; ++i)
  564. {
  565. const auto tick = i * step;
  566. const auto x = (float) tickToX ((double) tick);
  567. g.setColour (tick % bar == 0 ? gridBar : tick % ppq == 0 ? gridBeat : gridStep);
  568. g.drawVerticalLine ((int) x, (float) area.getY(), (float) area.getBottom());
  569. }
  570. };
  571. // --- grid ------------------------------------------------------------
  572. {
  573. juce::Graphics::ScopedSaveState state (g);
  574. g.reduceClipRegion (grid);
  575. for (int key = 0; key < 128; ++key)
  576. {
  577. const auto y = keyToY (key);
  578. if (y > grid.getBottom() || y + rowHeight < grid.getY())
  579. continue;
  580. auto row = isBlackKey (key) ? rowBlack : rowWhite;
  581. if (inScale (key))
  582. row = row.interpolatedWith (info, 0.10f);
  583. if (key == hover.key && drag == Drag::none)
  584. row = row.interpolatedWith (textPrimary, 0.04f); // the row under the mouse
  585. g.setColour (row);
  586. g.fillRect (grid.getX(), y, grid.getWidth(), rowHeight);
  587. if (key % 12 == 0)
  588. {
  589. g.setColour (gridBeat);
  590. g.drawHorizontalLine (y + rowHeight - 1, (float) grid.getX(), (float) grid.getRight());
  591. }
  592. }
  593. drawVerticalGrid (grid);
  594. // outside the pattern is darkened
  595. const auto endX = (float) tickToX ((double) patternLength);
  596. g.setColour (bg0.withAlpha (0.55f));
  597. g.fillRect (juce::Rectangle<float> (endX, (float) grid.getY(), (float) grid.getRight() - endX, (float) grid.getHeight()));
  598. // ghost notes (Alt+V). This channel's notes in the other clips that play at the same time in the
  599. // Playlist: hollow outlines. The other channels of this pattern: solid grey (a bit brighter, with
  600. // their channel colour on the edge, when Ctrl+Alt+V makes them editable)
  601. if (showGhosts)
  602. {
  603. for (const auto& n : polish::clipGhostNotes (song, song.currentPattern, channel))
  604. {
  605. const auto r = juce::Rectangle<float> ((float) tickToX ((double) n.start), (float) keyToY (n.key) + 1,
  606. juce::jmax (4.0f, (float) (n.length * pixelsPerTick) - 1.0f), (float) rowHeight - 2);
  607. if (r.getRight() < (float) grid.getX() || r.getX() > (float) grid.getRight())
  608. continue;
  609. g.setColour (textPrimary.withAlpha (0.30f));
  610. g.drawRoundedRectangle (r.reduced (0.5f), 2.0f, 1.0f);
  611. }
  612. }
  613. for (const auto& n : pattern.notes)
  614. {
  615. if (n.channel == channel || ! showGhosts)
  616. continue;
  617. const auto r = juce::Rectangle<float> ((float) tickToX ((double) n.start), (float) keyToY (n.key) + 1,
  618. (float) (n.length * pixelsPerTick), (float) rowHeight - 2);
  619. const auto hovered = &n - pattern.notes.data() == hover.ghost;
  620. g.setColour (textPrimary.withAlpha (hovered ? 0.16f : editGhosts ? 0.12f : 0.09f));
  621. g.fillRoundedRectangle (r, 2.0f);
  622. g.setColour (textPrimary.withAlpha (hovered ? 0.35f : editGhosts ? 0.22f : 0.12f));
  623. g.drawRoundedRectangle (r, 2.0f, 1.0f);
  624. if (editGhosts && n.channel >= 0 && n.channel < (int) song.channels.size() && song.channels[(std::size_t) n.channel].colour != 0)
  625. {
  626. g.setColour (theme::tame (juce::Colour (song.channels[(std::size_t) n.channel].colour)).withAlpha (0.7f));
  627. g.fillRect (r.withWidth (2.0f).reduced (0.0f, 1.0f));
  628. }
  629. }
  630. for (int i = 0; i < (int) pattern.notes.size(); ++i)
  631. {
  632. const auto& n = pattern.notes[(std::size_t) i];
  633. if (n.channel != channel)
  634. continue;
  635. const auto selected = isSelected (i);
  636. const auto hovered = i == hover.note && drag == Drag::none;
  637. const auto r = juce::Rectangle<float> ((float) tickToX ((double) n.start), (float) keyToY (n.key) + 1,
  638. juce::jmax (4.0f, (float) (n.length * pixelsPerTick) - 1.0f), (float) rowHeight - 2);
  639. auto fill = selected ? accentHover.brighter (0.15f) : n.muted ? noteMuted : theme::noteGroupColour (n.colour, n.velocity);
  640. if (hovered)
  641. fill = fill.brighter (0.18f);
  642. g.setColour (fill);
  643. g.fillRoundedRectangle (r, 2.5f);
  644. g.setColour (selected ? textPrimary : hovered ? textPrimary.withAlpha (0.75f) : bg0.withAlpha (0.6f));
  645. g.drawRoundedRectangle (r, 2.5f, 1.0f);
  646. // the edge under the mouse shows its grip
  647. if (hovered && (hover.zone == gesture::Zone::rightEdge || hover.zone == gesture::Zone::leftEdge))
  648. {
  649. const auto gripX = hover.zone == gesture::Zone::rightEdge ? r.getRight() - 3.0f : r.getX() + 1.0f;
  650. g.setColour (textPrimary);
  651. g.fillRoundedRectangle (gripX, r.getY() + 2.0f, 2.0f, juce::jmax (2.0f, r.getHeight() - 4.0f), 1.0f);
  652. }
  653. if (n.porta) // porta: slanted stroke at the start, like the glide
  654. {
  655. g.setColour (bg0.withAlpha (0.65f));
  656. g.drawLine (r.getX() + 2.0f, r.getBottom() - 2.0f, r.getX() + 9.0f, r.getY() + 2.0f, 2.0f);
  657. }
  658. if (n.slide) // slide arrow at the start of the note
  659. {
  660. juce::Path arrow;
  661. arrow.addTriangle (r.getX() + 2.0f, r.getBottom() - 2.0f, r.getX() + 2.0f, r.getY() + 2.0f, r.getX() + 9.0f, r.getCentreY());
  662. g.setColour (bg0.withAlpha (0.65f));
  663. g.fillPath (arrow);
  664. }
  665. if (gesture::noteLabelFits (r.getWidth(), rowHeight)) // the note's name, readable on its colour
  666. {
  667. g.setColour (fill.getPerceivedBrightness() > 0.55f ? bg0.withAlpha (0.85f) : textPrimary.withAlpha (0.9f));
  668. g.setFont (theme::font (gesture::labelHeight (rowHeight) - 1.0f));
  669. g.drawText (keyName (n.key), r.reduced (n.slide || n.porta ? 11.0f : 4.0f, 0.0f), juce::Justification::centredLeft, true);
  670. }
  671. }
  672. // the selection's stretch handle: a tab at its right end with two grips
  673. if (const auto handle = stretchHandle(); ! handle.isEmpty() && (drag == Drag::none || drag == Drag::stretch))
  674. {
  675. const auto lit = hover.stretch || drag == Drag::stretch;
  676. g.setColour (lit ? accentHover : accent.withAlpha (0.85f));
  677. g.fillRoundedRectangle (handle, 3.0f);
  678. g.setColour (onAccent.withAlpha (0.9f));
  679. g.fillRect (handle.getCentreX() - 2.0f, handle.getY() + 5.0f, 1.0f, handle.getHeight() - 10.0f);
  680. g.fillRect (handle.getCentreX() + 1.0f, handle.getY() + 5.0f, 1.0f, handle.getHeight() - 10.0f);
  681. if (lit) // the stretched span, from the anchor to the handle
  682. {
  683. g.setColour (accent.withAlpha (0.5f));
  684. const auto x0 = (float) tickToX ((double) (drag == Drag::stretch ? stretchAnchor : 0));
  685. if (drag == Drag::stretch)
  686. g.drawVerticalLine ((int) x0, (float) grid.getY(), (float) grid.getBottom());
  687. g.drawVerticalLine ((int) handle.getX() - 2, (float) grid.getY(), (float) grid.getBottom());
  688. }
  689. }
  690. if (! rubberBand.isEmpty())
  691. {
  692. g.setColour (selectionFill);
  693. g.fillRect (rubberBand);
  694. g.setColour (theme::colour::selection);
  695. g.drawRect (rubberBand);
  696. }
  697. if (drag == Drag::knife)
  698. {
  699. juce::Path cut;
  700. cut.startNewSubPath (knifeFrom.toFloat());
  701. cut.lineTo (knifeTo.toFloat());
  702. juce::Path dashed;
  703. const float dash[] = { 5.0f, 3.0f };
  704. juce::PathStrokeType (1.5f).createDashedStroke (dashed, cut, dash, 2);
  705. g.setColour (textPrimary);
  706. g.fillPath (dashed);
  707. }
  708. if (playheadTick >= 0.0)
  709. {
  710. g.setColour (playhead);
  711. g.drawVerticalLine ((int) tickToX (playheadTick), (float) grid.getY(), (float) grid.getBottom());
  712. }
  713. }
  714. // --- velocity lane -----------------------------------------------------
  715. {
  716. const auto lane = velocityArea();
  717. g.setColour (bg0);
  718. g.fillRect (lane);
  719. juce::Graphics::ScopedSaveState state (g);
  720. g.reduceClipRegion (lane);
  721. drawVerticalGrid (lane);
  722. g.setColour (border);
  723. g.drawHorizontalLine (lane.getY(), (float) lane.getX(), (float) lane.getRight());
  724. const auto usable = (float) lane.getHeight() - 8.0f;
  725. const auto bipolar = laneIsBipolar();
  726. const auto base = bipolar ? (float) lane.getBottom() - 2.0f - usable * 0.5f : (float) lane.getBottom();
  727. if (bipolar)
  728. {
  729. g.setColour (textPrimary.withAlpha (0.15f));
  730. g.drawHorizontalLine ((int) base, (float) lane.getX(), (float) lane.getRight());
  731. }
  732. if (const auto target = eventLaneTarget()) // pattern events: held values, a dot on each event
  733. {
  734. const auto* events = eventedit::findLane (pattern, *target);
  735. if (events != nullptr && ! events->events.empty())
  736. {
  737. juce::Path held;
  738. const auto yOf = [&] (float v) { return (float) lane.getBottom() - 2.0f - usable * v; };
  739. auto x = (float) tickToX (0.0);
  740. auto y = yOf (events->events.front().value);
  741. held.startNewSubPath (x, y);
  742. for (const auto& ev : events->events)
  743. {
  744. const auto ex = (float) tickToX ((double) ev.tick);
  745. held.lineTo (ex, y);
  746. y = yOf (ev.value);
  747. held.lineTo (ex, y);
  748. }
  749. held.lineTo ((float) lane.getRight(), y);
  750. g.setColour (accent.withAlpha (0.85f));
  751. g.strokePath (held, juce::PathStrokeType (1.5f));
  752. for (const auto& ev : events->events)
  753. g.fillEllipse ((float) tickToX ((double) ev.tick) - 2.5f, yOf (ev.value) - 2.5f, 5.0f, 5.0f);
  754. }
  755. else
  756. {
  757. g.setColour (textDisabled);
  758. g.setFont (theme::font (theme::type::small));
  759. g.drawText (tr ("No events yet: draw them here"), lane.reduced (8, 4), juce::Justification::centredLeft, true);
  760. }
  761. }
  762. // the lane's name in it, as FL writes it next to "Control" (round 149: the box on the left is narrow)
  763. g.setColour (theme::colour::textSecondary.withAlpha (0.8f));
  764. g.setFont (theme::font (theme::type::caption, true));
  765. g.drawText (laneBox.getText(), lane.reduced (8, 3).removeFromTop (14), juce::Justification::topLeft, true);
  766. for (int i = 0; i < (int) pattern.notes.size() && ! eventLaneTarget(); ++i)
  767. {
  768. const auto& n = pattern.notes[(std::size_t) i];
  769. if (n.channel != channel)
  770. continue;
  771. const auto x = (float) tickToX ((double) n.start);
  772. const auto top = (float) lane.getBottom() - 2.0f - usable * laneValue (n);
  773. auto colour = isSelected (i) ? accentHover.brighter (0.15f) : theme::noteGroupColour (n.colour, n.velocity);
  774. if (n.muted)
  775. colour = noteMuted;
  776. const auto hovered = i == hover.note && drag == Drag::none;
  777. g.setColour (hovered ? colour.brighter (0.3f) : colour.withAlpha (0.8f));
  778. g.fillRect (juce::Rectangle<float> (x, juce::jmin (top, base), hovered ? 3.0f : 2.0f, std::abs (base - top)));
  779. g.fillEllipse (x - 3.0f, top - 3.0f, 7.0f, 7.0f);
  780. if (hovered)
  781. g.drawEllipse (x - 5.0f, top - 5.0f, 11.0f, 11.0f, 1.0f);
  782. }
  783. if (drag == Drag::velocityLine) // the line being drawn
  784. {
  785. g.setColour (textPrimary.withAlpha (0.8f));
  786. g.drawLine (juce::Line<int> (knifeFrom, knifeTo).toFloat(), 1.5f);
  787. }
  788. }
  789. // --- time ruler --------------------------------------------------------
  790. {
  791. const auto ruler = juce::Rectangle<int> (keyboardWidth, rulerTop, grid.getWidth(), timelineHeight);
  792. g.setColour (bg2);
  793. g.fillRect (ruler);
  794. g.setColour (border);
  795. g.fillRect (ruler.withTop (ruler.getBottom() - 1));
  796. juce::Graphics::ScopedSaveState state (g);
  797. g.reduceClipRegion (ruler);
  798. g.setFont (theme::font (theme::type::caption));
  799. const auto firstBar = (std::int64_t) std::floor (scrollTicks / (double) bar);
  800. const auto lastBar = (std::int64_t) std::ceil (xToTick (grid.getRight()) / (double) bar);
  801. for (auto b = firstBar; b <= lastBar; ++b)
  802. {
  803. const auto x = (int) tickToX ((double) (b * bar));
  804. g.setColour (textSecondary);
  805. g.drawVerticalLine (x, (float) rulerTop + 10.0f, (float) headerHeight);
  806. g.drawText (juce::String (b + 1), x + 3, rulerTop + 2, 40, timelineHeight - 4, juce::Justification::centredLeft);
  807. }
  808. if (playheadTick >= 0.0)
  809. {
  810. const auto x = (float) tickToX (playheadTick);
  811. juce::Path tri;
  812. tri.addTriangle (x - 5, (float) rulerTop, x + 5, (float) rulerTop, x, (float) rulerTop + 8);
  813. g.setColour (playhead);
  814. g.fillPath (tri);
  815. }
  816. }
  817. // --- keyboard ------------------------------------------------------------
  818. // flat keys; every C is labelled with its octave, the other white keys too when the rows are tall
  819. // enough; the key under the mouse (and the one sounding) are lit
  820. {
  821. const auto keys = juce::Rectangle<int> (0, headerHeight, keyboardWidth, grid.getHeight());
  822. juce::Graphics::ScopedSaveState state (g);
  823. g.reduceClipRegion (keys);
  824. g.setColour (bg0);
  825. g.fillRect (keys);
  826. const auto fontHeight = gesture::labelHeight (rowHeight);
  827. const auto blackWidth = keyboardWidth * 3 / 5;
  828. for (int key = 0; key < 128; ++key)
  829. {
  830. const auto y = keyToY (key);
  831. if (y > keys.getBottom() || y + rowHeight < keys.getY())
  832. continue;
  833. const auto black = isBlackKey (key);
  834. const auto pressed = key == previewKey;
  835. const auto hovered = key == hover.key && ! pressed;
  836. auto colour = black ? keyBlack : keyWhite;
  837. if (inScale (key))
  838. colour = colour.interpolatedWith (info, black ? 0.18f : 0.12f);
  839. if (hovered)
  840. colour = colour.interpolatedWith (accent, black ? 0.35f : 0.22f);
  841. if (pressed)
  842. colour = accent;
  843. const auto width = black ? blackWidth : keyboardWidth - 1;
  844. g.setColour (colour);
  845. g.fillRect (0, y, width, rowHeight);
  846. g.setColour (black ? bg0 : keyWhite.darker (0.3f));
  847. g.drawHorizontalLine (y + rowHeight - 1, 0.0f, (float) width);
  848. const auto isC = key % 12 == 0;
  849. if (isC || hovered || pressed || (! black && rowHeight >= 16))
  850. {
  851. g.setFont (theme::font (fontHeight, isC));
  852. g.setColour (pressed ? onAccent : black ? textPrimary : isC ? bg0 : bg0.withAlpha (0.55f));
  853. const auto area = black ? juce::Rectangle<int> (2, y, blackWidth - 4, rowHeight)
  854. : juce::Rectangle<int> (blackWidth, y, keyboardWidth - blackWidth - 5, rowHeight);
  855. g.drawText (keyName (key), area, black ? juce::Justification::centredLeft : juce::Justification::centredRight, false);
  856. }
  857. }
  858. g.setColour (border);
  859. g.fillRect (keyboardWidth - 1, keys.getY(), 1, keys.getHeight());
  860. }
  861. // velocity lane label
  862. {
  863. const auto lane = velocityArea();
  864. g.setColour (bg2);
  865. g.fillRect (0, lane.getY(), keyboardWidth, lane.getHeight());
  866. juce::ignoreUnused (lane); // the property combo sits here
  867. }
  868. // top-left corner: channel name
  869. g.setColour (bg3);
  870. g.fillRect (0, 0, keyboardWidth, toolbarHeight);
  871. g.setColour (bg2);
  872. g.fillRect (0, toolbarHeight, keyboardWidth, headerHeight - toolbarHeight);
  873. g.setColour (border);
  874. g.fillRect (0, headerHeight - 1, keyboardWidth, 1);
  875. g.fillRect (keyboardWidth - 1, 0, 1, headerHeight);
  876. if (channel < (int) song.channels.size())
  877. {
  878. const auto& ch = song.channels[(std::size_t) channel];
  879. g.setColour (ch.colour != 0 ? theme::tame (juce::Colour (ch.colour)) : accent);
  880. g.fillRoundedRectangle (4.0f, (float) toolbarHeight + 6.0f, 3.0f, (float) (headerHeight - toolbarHeight) - 12.0f, 1.0f);
  881. g.setColour (textPrimary);
  882. g.setFont (theme::font (theme::type::caption, true));
  883. g.drawFittedText (juce::String::fromUTF8 (ch.name.c_str()), 11, toolbarHeight, keyboardWidth - 14, headerHeight - toolbarHeight,
  884. juce::Justification::centredLeft, 2, 0.8f);
  885. }
  886. }
  887. // --- mouse -------------------------------------------------------------------
  888. int PianoRollComponent::noteAt (int x, int y, bool& onRightEdge) const
  889. {
  890. bool left = false;
  891. return noteAt (x, y, onRightEdge, left);
  892. }
  893. int PianoRollComponent::noteAt (int x, int y, bool& onRightEdge, bool& onLeftEdge) const
  894. {
  895. // the same hit test as the hover (cursor and highlight), so a click does what the cursor showed
  896. const auto h = hoverAt ({ x, y });
  897. onRightEdge = h.zone == gesture::Zone::rightEdge;
  898. onLeftEdge = h.zone == gesture::Zone::leftEdge;
  899. return gridArea().contains (x, y) ? h.note : -1;
  900. }
  901. int PianoRollComponent::ghostAt (int x, int y) const
  902. {
  903. if (! showGhosts)
  904. return -1;
  905. const auto& notes = currentPattern (engine.getSong()).notes;
  906. const auto channel = engine.getSelectedChannel();
  907. const auto key = yToKey (y);
  908. for (int i = (int) notes.size() - 1; i >= 0; --i)
  909. {
  910. const auto& n = notes[(std::size_t) i];
  911. if (n.channel != channel && n.key == key && x >= tickToX ((double) n.start) && x < tickToX ((double) (n.start + n.length)))
  912. return i;
  913. }
  914. return -1;
  915. }
  916. void PianoRollComponent::previewOn (int key, float velocity)
  917. {
  918. // one preview note at a time; it remembers its channel, so a channel switch meanwhile can't strand it
  919. previewNotes.releaseAll();
  920. previewKey = key;
  921. previewNotes.press (engine.getSelectedChannel(), key, velocity);
  922. repaint (0, headerHeight, keyboardWidth, getHeight());
  923. }
  924. void PianoRollComponent::previewOff()
  925. {
  926. previewNotes.releaseAll();
  927. if (previewKey >= 0)
  928. {
  929. previewKey = -1;
  930. repaint (0, headerHeight, keyboardWidth, getHeight());
  931. }
  932. }
  933. void PianoRollComponent::visibilityChanged()
  934. {
  935. if (! isShowing()) // hidden mid-gesture (window closed, tab switched): nothing keeps sounding
  936. {
  937. previewOff();
  938. stopListening();
  939. }
  940. }
  941. float PianoRollComponent::laneValue (const Note& n) const
  942. {
  943. switch (laneBox.getSelectedId())
  944. {
  945. case 2: return (n.pan + 1.0f) * 0.5f;
  946. case 3: return (n.finePitch + 120.0f) / 240.0f;
  947. default: return n.velocity;
  948. }
  949. }
  950. void PianoRollComponent::setLaneValue (Note& n, float v) const
  951. {
  952. v = juce::jlimit (0.0f, 1.0f, v);
  953. switch (laneBox.getSelectedId())
  954. {
  955. case 2: n.pan = std::abs (v - 0.5f) < 0.02f ? 0.0f : v * 2.0f - 1.0f; break; // snaps to center
  956. case 3: n.finePitch = std::round (v * 240.0f - 120.0f); break;
  957. default: n.velocity = v; break;
  958. }
  959. }
  960. bool PianoRollComponent::laneIsBipolar() const
  961. {
  962. return laneBox.getSelectedId() != 1;
  963. }
  964. void PianoRollComponent::applyVelocity (int fromX, int toX, int y)
  965. {
  966. const auto lane = velocityArea();
  967. applyLaneValue (toX, juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - y) / (float) (lane.getHeight() - 8)), fromX);
  968. }
  969. void PianoRollComponent::applyLaneValue (int toX, float value, int fromX)
  970. {
  971. const auto lo = juce::jmin (fromX, toX) - 3, hi = juce::jmax (fromX, toX) + 3;
  972. const auto& notes = currentPattern (engine.getSong()).notes;
  973. std::vector<int> hits;
  974. for (auto i : selectionOrAll())
  975. {
  976. const auto x = (int) tickToX ((double) notes[(std::size_t) i].start);
  977. if (x >= lo && x <= hi)
  978. hits.push_back (i);
  979. }
  980. if (! hits.empty())
  981. editNotes ([this, &hits, value] (Pattern& p) {
  982. for (auto i : hits)
  983. setLaneValue (p.notes[(std::size_t) i], value);
  984. });
  985. }
  986. void PianoRollComponent::togglePorta()
  987. {
  988. const auto target = selectionOrAll();
  989. if (target.empty())
  990. return;
  991. // like mute: if any note lacks porta, enable it on all; otherwise disable
  992. const auto& notes = currentPattern (engine.getSong()).notes;
  993. const auto porta = std::any_of (target.begin(), target.end(), [&notes] (int i) { return ! notes[(std::size_t) i].porta; });
  994. editNotes ([&target, porta] (Pattern& p) {
  995. for (auto i : target)
  996. p.notes[(std::size_t) i].porta = porta;
  997. });
  998. }
  999. void PianoRollComponent::toggleMute()
  1000. {
  1001. const auto target = selectionOrAll();
  1002. if (target.empty())
  1003. return;
  1004. // if any is playing, mute all; otherwise unmute
  1005. const auto& notes = currentPattern (engine.getSong()).notes;
  1006. const auto mute = std::any_of (target.begin(), target.end(), [&notes] (int i) { return ! notes[(std::size_t) i].muted; });
  1007. editNotes ([&target, mute] (Pattern& p) {
  1008. for (auto i : target)
  1009. p.notes[(std::size_t) i].muted = mute;
  1010. });
  1011. }
  1012. void PianoRollComponent::paintNoteAt (std::int64_t start, int key, bool monophonic)
  1013. {
  1014. // a brush stroke lays single notes (or the chosen chord) at the default length
  1015. Note n;
  1016. n.start = juce::jmax<std::int64_t> (0, start);
  1017. n.length = paintLength;
  1018. n.key = key;
  1019. n.channel = engine.getSelectedChannel();
  1020. n.slide = slideButton.getToggleState();
  1021. n.colour = noteColour;
  1022. std::vector<Note> stamp;
  1023. for (auto interval : chordIntervals())
  1024. if (n.key + interval <= 127)
  1025. {
  1026. auto chordNote = n;
  1027. chordNote.key = snapKey (n.key + interval); // with scale snap the chord follows the scale
  1028. if (std::none_of (stamp.begin(), stamp.end(), [&chordNote] (const Note& o) { return o.key == chordNote.key; }))
  1029. stamp.push_back (chordNote);
  1030. }
  1031. editNotes ([&] (Pattern& p) {
  1032. if (monophonic) // Shift: the new note replaces whatever this channel plays at that time
  1033. {
  1034. std::vector<int> overlapping;
  1035. for (int i = 0; i < (int) p.notes.size(); ++i)
  1036. {
  1037. const auto& o = p.notes[(std::size_t) i];
  1038. if (o.channel == n.channel && o.start < n.start + n.length && o.start + o.length > n.start)
  1039. overlapping.push_back (i);
  1040. }
  1041. noteedit::remove (p, overlapping);
  1042. }
  1043. noteedit::paste (p, stamp, 0);
  1044. });
  1045. }
  1046. void PianoRollComponent::mouseDown (const juce::MouseEvent& e)
  1047. {
  1048. if (engine.getSong().channels.empty())
  1049. return;
  1050. downMods = e.mods;
  1051. startedOnEmpty = erasedSomething = holdExpired = false;
  1052. const auto onKeyboard = e.x < keyboardWidth && e.y >= headerHeight && e.y < gridArea().getBottom();
  1053. hover = {};
  1054. gliding = false;
  1055. if (e.mods.isMiddleButtonDown())
  1056. {
  1057. if (onKeyboard) // middle-drag on the keyboard zooms vertically around the clicked key
  1058. {
  1059. drag = Drag::keyZoom;
  1060. keyZoomKey = yToKey (e.y);
  1061. keyZoomStartRow = rowHeight;
  1062. setMouseCursor (juce::MouseCursor::UpDownResizeCursor);
  1063. return;
  1064. }
  1065. drag = Drag::pan; // elsewhere it pans both ways, in every tool
  1066. panStartTicks = scrollTicks;
  1067. panStartY = scrollY;
  1068. setMouseCursor (editorCursor (gesture::Cursor::pan));
  1069. return;
  1070. }
  1071. if (onKeyboard)
  1072. {
  1073. if (e.mods.isCtrlDown()) // Ctrl+click / drag: selects the notes of a key (range)
  1074. {
  1075. drag = Drag::keySelect;
  1076. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  1077. mouseDrag (e);
  1078. return;
  1079. }
  1080. if (e.mods.isLeftButtonDown())
  1081. {
  1082. drag = Drag::keyboard;
  1083. previewOn (yToKey (e.y), 0.8f);
  1084. }
  1085. return;
  1086. }
  1087. // ruler: Ctrl+drag selects the notes in a time range
  1088. if (e.y >= rulerTop && e.y < headerHeight && e.x >= keyboardWidth && e.mods.isCtrlDown() && e.mods.isLeftButtonDown())
  1089. {
  1090. drag = Drag::rulerSelect;
  1091. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  1092. return;
  1093. }
  1094. if (velocityArea().contains (e.getPosition()) && eventLaneTarget())
  1095. {
  1096. // pattern events: drag draws one event per grid step, right-drag erases
  1097. lastVelocityX = e.x;
  1098. drag = e.mods.isRightButtonDown() ? Drag::eventErase : Drag::eventDraw;
  1099. drawEvents (e.x, e.x, e.y, drag == Drag::eventErase);
  1100. return;
  1101. }
  1102. if (velocityArea().contains (e.getPosition()))
  1103. {
  1104. const auto lane = velocityArea();
  1105. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  1106. lastVelocityX = e.x;
  1107. if (e.mods.isAltDown() && e.mods.isLeftButtonDown()) // Alt+click resets the notes under the mouse
  1108. {
  1109. drag = Drag::velocity;
  1110. applyLaneValue (e.x, laneBox.getSelectedId() == 1 ? Note().velocity : 0.5f, e.x);
  1111. drag = Drag::none;
  1112. return;
  1113. }
  1114. laneOriginals = currentPattern (engine.getSong()).notes;
  1115. if (e.mods.isRightButtonDown()) // right-drag draws a straight line of values
  1116. {
  1117. drag = Drag::velocityLine;
  1118. laneSetValue = value;
  1119. return;
  1120. }
  1121. if (e.mods.isShiftDown()) // Shift+drag: every note crossed gets the value of the press
  1122. {
  1123. drag = Drag::velocitySet;
  1124. laneSetValue = value;
  1125. applyLaneValue (e.x, value, e.x);
  1126. return;
  1127. }
  1128. drag = Drag::velocity;
  1129. applyVelocity (e.x, e.x, e.y);
  1130. return;
  1131. }
  1132. if (! gridArea().contains (e.getPosition()))
  1133. return;
  1134. // the selection's stretch handle: drag scales the selected notes in time from the selection's start
  1135. if (e.mods.isLeftButtonDown() && ! e.mods.isCtrlDown() && stretchHandle().expanded (2.0f).contains (e.position))
  1136. {
  1137. const auto& notes = currentPattern (engine.getSong()).notes;
  1138. dragIndices.clear();
  1139. dragOriginals.clear();
  1140. for (auto i : selection)
  1141. if (i >= 0 && i < (int) notes.size() && notes[(std::size_t) i].channel == engine.getSelectedChannel())
  1142. {
  1143. dragIndices.push_back (i);
  1144. dragOriginals.push_back (notes[(std::size_t) i]);
  1145. }
  1146. noteedit::span (dragOriginals, stretchAnchor, stretchEnd);
  1147. dragNote = dragIndices.empty() ? -1 : dragIndices.front();
  1148. drag = Drag::stretch;
  1149. setMouseCursor (juce::MouseCursor::LeftRightResizeCursor);
  1150. return;
  1151. }
  1152. bool rightEdge = false, leftEdge = false;
  1153. const auto hit = noteAt (e.x, e.y, rightEdge, leftEdge);
  1154. const auto tool = tools.getTool();
  1155. // editable ghost notes (Ctrl+Alt+V): a left press on one switches to its channel and grabs the note there
  1156. if (hit < 0 && editGhosts && e.mods.isLeftButtonDown() && ! e.mods.isCtrlDown())
  1157. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  1158. {
  1159. engine.setSelectedChannel (currentPattern (engine.getSong()).notes[(std::size_t) ghost].channel);
  1160. if (noteAt (e.x, e.y, rightEdge, leftEdge) >= 0) // now it is one of this channel's notes
  1161. mouseDown (e);
  1162. return;
  1163. }
  1164. // Zoom tool: right-click zooms out around the point (a click zooms in, a drag zooms to the range)
  1165. if (tool == EditTool::zoom && e.mods.isRightButtonDown() && ! e.mods.isCtrlDown())
  1166. {
  1167. zoomOut (e.x);
  1168. return;
  1169. }
  1170. // every tool: right click deletes (double right-click on a ghost note switches to its channel; with
  1171. // editable ghost notes a right-click deletes the ghost note itself)
  1172. if (e.mods.isRightButtonDown())
  1173. {
  1174. if (hit < 0 && editGhosts)
  1175. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  1176. {
  1177. setSelection ({});
  1178. editNotes ([ghost] (Pattern& p) { noteedit::remove (p, { ghost }); });
  1179. return;
  1180. }
  1181. if (hit < 0 && e.getNumberOfClicks() >= 2)
  1182. if (const auto ghost = ghostAt (e.x, e.y); ghost >= 0)
  1183. {
  1184. engine.setSelectedChannel (currentPattern (engine.getSong()).notes[(std::size_t) ghost].channel);
  1185. return;
  1186. }
  1187. drag = Drag::erase;
  1188. startedOnEmpty = hit < 0;
  1189. setSelection ({}); // indices change while deleting
  1190. if (hit >= 0)
  1191. {
  1192. erasedSomething = true;
  1193. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  1194. }
  1195. return;
  1196. }
  1197. // every tool: Ctrl+click on a note adds/removes it from the selection; Ctrl+drag selects (Shift adds)
  1198. if (hit >= 0 && e.mods.isCtrlDown())
  1199. {
  1200. auto s = selection;
  1201. if (isSelected (hit))
  1202. s.erase (std::find (s.begin(), s.end(), hit));
  1203. else
  1204. s.push_back (hit);
  1205. setSelection (s);
  1206. return;
  1207. }
  1208. if ((hit < 0 && e.mods.isCtrlDown()) || tool == EditTool::lasso
  1209. || (hit < 0 && e.mods.isShiftDown() && tool != EditTool::brush && tool != EditTool::drumPaint))
  1210. {
  1211. drag = Drag::select;
  1212. dragNote = hit; // a click without dragging selects this note (Lasso)
  1213. selectionBefore = e.mods.isShiftDown() ? selection : std::vector<int> {};
  1214. rubberBand = {};
  1215. setSelection (selectionBefore);
  1216. return;
  1217. }
  1218. const auto snapOn = ! e.mods.isAltDown();
  1219. switch (tool)
  1220. {
  1221. case EditTool::eraser:
  1222. drag = Drag::erase;
  1223. setSelection ({});
  1224. if (hit >= 0)
  1225. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  1226. return;
  1227. case EditTool::mute:
  1228. drag = Drag::muting;
  1229. touchedNotes.clear();
  1230. if (hit >= 0)
  1231. {
  1232. muteTarget = ! currentPattern (engine.getSong()).notes[(std::size_t) hit].muted;
  1233. touchedNotes.push_back (hit);
  1234. editNotes ([hit, m = muteTarget] (Pattern& p) { p.notes[(std::size_t) hit].muted = m; });
  1235. }
  1236. else
  1237. muteTarget = true;
  1238. return;
  1239. case EditTool::knife:
  1240. drag = Drag::knife;
  1241. knifeFrom = knifeTo = e.getPosition();
  1242. repaint();
  1243. return;
  1244. case EditTool::zoom:
  1245. drag = Drag::zoomRange;
  1246. rubberBand = {};
  1247. return;
  1248. case EditTool::listen:
  1249. drag = Drag::listen;
  1250. listenAt (e.x);
  1251. return;
  1252. case EditTool::pencil:
  1253. case EditTool::brush:
  1254. case EditTool::drumPaint:
  1255. case EditTool::lasso:
  1256. case EditTool::slip:
  1257. break;
  1258. }
  1259. // Pencil (and Brush on an existing note): Shift+drag on a note drags a copy
  1260. if (hit >= 0 && e.mods.isShiftDown() && ! rightEdge && ! leftEdge)
  1261. {
  1262. const auto sources = isSelected (hit) ? selection : std::vector<int> { hit };
  1263. const auto grabbedAt = (std::size_t) (std::find (sources.begin(), sources.end(), hit) - sources.begin());
  1264. std::vector<int> added;
  1265. // the copy comes out in the same order as the originals (copy sorts by start)
  1266. std::vector<Note> ordered;
  1267. for (auto i : sources)
  1268. ordered.push_back (currentPattern (engine.getSong()).notes[(std::size_t) i]);
  1269. editNotes ([&] (Pattern& p) { added = noteedit::paste (p, ordered, 0); });
  1270. setSelection (added);
  1271. dragIndices = added;
  1272. dragOriginals = ordered;
  1273. dragNote = added[grabbedAt];
  1274. drag = Drag::move;
  1275. grabOffset = ordered[grabbedAt].start - snap (xToTick (e.x), snapOn);
  1276. previewOn (ordered[grabbedAt].key, ordered[grabbedAt].velocity);
  1277. return;
  1278. }
  1279. if (hit >= 0)
  1280. {
  1281. if (! isSelected (hit))
  1282. setSelection ({});
  1283. const auto& notes = currentPattern (engine.getSong()).notes;
  1284. const auto& n = notes[(std::size_t) hit];
  1285. dragNote = hit;
  1286. dragIndices = selection.empty() ? std::vector<int> { hit } : selection;
  1287. dragOriginals.clear();
  1288. for (auto i : dragIndices)
  1289. dragOriginals.push_back (notes[(std::size_t) i]);
  1290. drag = rightEdge ? Drag::resize : leftEdge ? Drag::resizeLeft : Drag::move;
  1291. grabOffset = n.start - snap (xToTick (e.x), snapOn);
  1292. lastLength = n.length;
  1293. previewOn (n.key, n.velocity);
  1294. return;
  1295. }
  1296. // new note (or the chosen chord, with the clicked note as the root)
  1297. setSelection ({});
  1298. createdAt = juce::Time::getMillisecondCounter();
  1299. if (tool == EditTool::drumPaint)
  1300. {
  1301. drag = Drag::drumPaint;
  1302. lastDrumCell = -1;
  1303. lastDrumKey = -1;
  1304. drumPaintAt (e.getPosition(), snapOn);
  1305. return;
  1306. }
  1307. if (tool == EditTool::brush)
  1308. {
  1309. drag = Drag::paint;
  1310. paintLength = juce::jmax<std::int64_t> (1, newNoteLength());
  1311. const auto start = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  1312. paintNoteAt (start, snapKey (yToKey (e.y)), e.mods.isShiftDown());
  1313. nextPaintTick = start + paintLength;
  1314. previewOn (snapKey (yToKey (e.y)), 0.78f);
  1315. return;
  1316. }
  1317. Note n;
  1318. n.start = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn));
  1319. n.length = newNoteLength();
  1320. n.key = snapKey (yToKey (e.y));
  1321. n.channel = engine.getSelectedChannel();
  1322. n.slide = slideButton.getToggleState();
  1323. n.colour = noteColour;
  1324. std::vector<Note> stamp;
  1325. for (auto interval : chordIntervals())
  1326. if (n.key + interval <= 127)
  1327. {
  1328. auto chordNote = n;
  1329. chordNote.key = snapKey (n.key + interval); // with scale snap the chord follows the scale
  1330. if (std::none_of (stamp.begin(), stamp.end(), [&chordNote] (const Note& o) { return o.key == chordNote.key; }))
  1331. stamp.push_back (chordNote);
  1332. }
  1333. std::vector<int> added;
  1334. editNotes ([&] (Pattern& p) { added = noteedit::paste (p, stamp, 0); });
  1335. dragNote = added.front(); // the root leads the drag
  1336. dragIndices = added;
  1337. dragOriginals = stamp;
  1338. if (added.size() > 1)
  1339. setSelection (added);
  1340. drag = Drag::move;
  1341. grabOffset = 0;
  1342. previewOn (n.key, n.velocity);
  1343. }
  1344. void PianoRollComponent::mouseDrag (const juce::MouseEvent& e)
  1345. {
  1346. const auto snapOn = ! e.mods.isAltDown();
  1347. // after the step below, the hint bar says what the gesture is doing
  1348. const struct PostAfter
  1349. {
  1350. PianoRollComponent& roll;
  1351. const juce::MouseEvent& event;
  1352. ~PostAfter() { roll.postDragHint (event); }
  1353. } postAfter { *this, e };
  1354. switch (drag)
  1355. {
  1356. case Drag::none:
  1357. return;
  1358. case Drag::pan:
  1359. scrollTicks = juce::jmax (0.0, panStartTicks - e.getDistanceFromDragStartX() / pixelsPerTick);
  1360. scrollY = juce::jlimit (0, juce::jmax (0, 128 * rowHeight - gridArea().getHeight()), panStartY - e.getDistanceFromDragStartY());
  1361. updateScrollBars();
  1362. repaint();
  1363. return;
  1364. case Drag::keyboard:
  1365. {
  1366. const auto key = yToKey (e.y);
  1367. if (key != previewKey)
  1368. previewOn (key, 0.8f);
  1369. return;
  1370. }
  1371. case Drag::keyZoom:
  1372. {
  1373. // up = taller keys; the clicked key stays under the mouse
  1374. const auto offset = e.getMouseDownY() - headerHeight;
  1375. rowHeight = juce::jlimit (6, 32, keyZoomStartRow - e.getDistanceFromDragStartY() / 8);
  1376. scrollY = juce::jmax (0, (127 - keyZoomKey) * rowHeight + rowHeight / 2 - offset);
  1377. updateScrollBars();
  1378. repaint();
  1379. return;
  1380. }
  1381. case Drag::keySelect:
  1382. {
  1383. const auto k0 = yToKey (e.getMouseDownY()), k1 = yToKey (e.y);
  1384. const auto& notes = currentPattern (engine.getSong()).notes;
  1385. auto s = selectionBefore;
  1386. for (auto i : channelNotes())
  1387. if (const auto k = notes[(std::size_t) i].key; k >= juce::jmin (k0, k1) && k <= juce::jmax (k0, k1))
  1388. s.push_back (i);
  1389. setSelection (s);
  1390. return;
  1391. }
  1392. case Drag::rulerSelect:
  1393. {
  1394. const auto t0 = (double) snap (xToTick (juce::jmin (e.getMouseDownX(), e.x)), snapOn);
  1395. const auto t1 = (double) snap (xToTick (juce::jmax (e.getMouseDownX(), e.x)) + (snapOn ? (double) gridTicks() : 0.0), snapOn);
  1396. const auto& notes = currentPattern (engine.getSong()).notes;
  1397. auto s = selectionBefore;
  1398. for (auto i : channelNotes())
  1399. if (const auto& n = notes[(std::size_t) i]; (double) n.start >= t0 && (double) n.start < t1)
  1400. s.push_back (i);
  1401. rubberBand = juce::Rectangle<int>::leftTopRightBottom ((int) tickToX (t0), gridArea().getY(), (int) tickToX (t1), gridArea().getBottom());
  1402. setSelection (s);
  1403. return;
  1404. }
  1405. case Drag::velocity:
  1406. applyVelocity (lastVelocityX, e.x, e.y);
  1407. lastVelocityX = e.x;
  1408. return;
  1409. case Drag::eventDraw:
  1410. case Drag::eventErase:
  1411. drawEvents (lastVelocityX, e.x, e.y, drag == Drag::eventErase);
  1412. lastVelocityX = e.x;
  1413. return;
  1414. case Drag::velocitySet:
  1415. applyLaneValue (e.x, laneSetValue, lastVelocityX);
  1416. lastVelocityX = e.x;
  1417. return;
  1418. case Drag::velocityLine:
  1419. {
  1420. // from the press to the mouse: notes in between follow the line, the others keep their value
  1421. const auto lane = velocityArea();
  1422. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  1423. const auto x0 = e.getMouseDownX(), x1 = e.x;
  1424. const auto lo = juce::jmin (x0, x1) - 3, hi = juce::jmax (x0, x1) + 3;
  1425. const auto targets = selectionOrAll();
  1426. knifeFrom = { x0, juce::roundToInt ((float) lane.getBottom() - 2.0f - laneSetValue * (float) (lane.getHeight() - 8)) };
  1427. knifeTo = e.getPosition();
  1428. editNotes ([&] (Pattern& p) {
  1429. for (auto i : targets)
  1430. {
  1431. if ((std::size_t) i >= laneOriginals.size() || (std::size_t) i >= p.notes.size())
  1432. continue;
  1433. auto& n = p.notes[(std::size_t) i];
  1434. n = laneOriginals[(std::size_t) i];
  1435. const auto x = (int) tickToX ((double) n.start);
  1436. if (x >= lo && x <= hi)
  1437. setLaneValue (n, (float) gesture::lineValue (x0, laneSetValue, x1, value, x));
  1438. }
  1439. });
  1440. repaint();
  1441. return;
  1442. }
  1443. case Drag::select:
  1444. case Drag::zoomRange:
  1445. {
  1446. if (e.getDistanceFromDragStart() < 3 && rubberBand.isEmpty())
  1447. return;
  1448. const auto area = gridArea();
  1449. rubberBand = juce::Rectangle<int> (e.getMouseDownPosition(), e.getPosition()).getIntersection (area);
  1450. if (drag == Drag::zoomRange)
  1451. {
  1452. rubberBand = rubberBand.withY (area.getY()).withHeight (area.getHeight());
  1453. repaint();
  1454. return;
  1455. }
  1456. const auto t0 = xToTick (rubberBand.getX()), t1 = xToTick (rubberBand.getRight());
  1457. const auto kTop = yToKey (rubberBand.getY()), kBottom = yToKey (rubberBand.getBottom());
  1458. const auto& notes = currentPattern (engine.getSong()).notes;
  1459. auto s = selectionBefore;
  1460. for (auto i : channelNotes())
  1461. {
  1462. const auto& n = notes[(std::size_t) i];
  1463. if ((double) (n.start + n.length) > t0 && (double) n.start < t1 && n.key <= kTop && n.key >= kBottom)
  1464. s.push_back (i);
  1465. }
  1466. setSelection (s);
  1467. return;
  1468. }
  1469. case Drag::erase:
  1470. {
  1471. // right press-and-hold on empty grid, then drag: a temporary Knife
  1472. if (e.mods.isRightButtonDown() && startedOnEmpty && ! erasedSomething && ! holdExpired)
  1473. {
  1474. if (e.getLengthOfMousePress() >= 350)
  1475. {
  1476. drag = Drag::knife;
  1477. knifeFrom = e.getMouseDownPosition();
  1478. knifeTo = e.getPosition();
  1479. repaint();
  1480. return;
  1481. }
  1482. if (e.getDistanceFromDragStart() > 3)
  1483. holdExpired = true; // moved right away: it is an erase stroke
  1484. }
  1485. bool edge = false;
  1486. const auto hit = noteAt (e.x, e.y, edge);
  1487. if (hit >= 0)
  1488. {
  1489. erasedSomething = true;
  1490. editNotes ([hit] (Pattern& p) { noteedit::remove (p, { hit }); });
  1491. }
  1492. return;
  1493. }
  1494. case Drag::muting:
  1495. {
  1496. bool edge = false;
  1497. const auto hit = noteAt (e.x, e.y, edge);
  1498. if (hit >= 0 && std::find (touchedNotes.begin(), touchedNotes.end(), hit) == touchedNotes.end())
  1499. {
  1500. touchedNotes.push_back (hit);
  1501. editNotes ([hit, m = muteTarget] (Pattern& p) { p.notes[(std::size_t) hit].muted = m; });
  1502. }
  1503. return;
  1504. }
  1505. case Drag::knife:
  1506. knifeTo = e.getPosition();
  1507. repaint();
  1508. return;
  1509. case Drag::listen:
  1510. listenAt (e.x);
  1511. return;
  1512. case Drag::drumPaint:
  1513. drumPaintAt (e.getPosition(), snapOn);
  1514. return;
  1515. case Drag::stretch:
  1516. {
  1517. if (dragOriginals.empty() || stretchEnd <= stretchAnchor)
  1518. return;
  1519. // the new end of the selection: on the grid (the nearest line), or free with Alt
  1520. const auto minimum = snapOn ? juce::jmax<std::int64_t> (1, gridTicks()) : (std::int64_t) 10;
  1521. auto end = snapOn ? snap (xToTick (e.x) + (double) gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  1522. end = juce::jmax (stretchAnchor + minimum, end);
  1523. const auto stretched = polish::stretchNotes (dragOriginals, stretchAnchor, stretchEnd, end);
  1524. editNotes ([this, &stretched] (Pattern& p) {
  1525. for (std::size_t j = 0; j < dragIndices.size() && j < stretched.size(); ++j)
  1526. if ((std::size_t) dragIndices[j] < p.notes.size())
  1527. p.notes[(std::size_t) dragIndices[j]] = stretched[j];
  1528. });
  1529. repaint();
  1530. return;
  1531. }
  1532. case Drag::paint:
  1533. {
  1534. // lays notes to the right, one per default length, at the pitch under the mouse
  1535. const auto tick = snap (xToTick (e.x), snapOn);
  1536. for (int guard = 0; tick >= nextPaintTick && guard < 64; ++guard)
  1537. {
  1538. paintNoteAt (nextPaintTick, snapKey (yToKey (e.y)), e.mods.isShiftDown());
  1539. nextPaintTick += paintLength;
  1540. }
  1541. if (snapKey (yToKey (e.y)) != previewKey)
  1542. previewOn (snapKey (yToKey (e.y)), 0.78f);
  1543. return;
  1544. }
  1545. case Drag::move:
  1546. {
  1547. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  1548. auto deltaTicks = juce::jmax<std::int64_t> (0, snap (xToTick (e.x), snapOn) + grabOffset) - grabbed.start;
  1549. auto deltaKeys = snapKey (yToKey (e.y)) - grabbed.key;
  1550. // locks: Shift pressed after the click keeps the pitch, Ctrl keeps the time
  1551. if (e.mods.isShiftDown() && ! downMods.isShiftDown())
  1552. deltaKeys = 0;
  1553. if (e.mods.isCtrlDown() && ! downMods.isCtrlDown())
  1554. deltaTicks = 0;
  1555. const auto& current = currentPattern (engine.getSong()).notes[(std::size_t) dragNote];
  1556. if (current.start == grabbed.start + deltaTicks && current.key == grabbed.key + deltaKeys)
  1557. return;
  1558. const auto oldKey = current.key;
  1559. // from the original positions: the group keeps its shape even when hitting the limits
  1560. editNotes ([this, &deltaTicks, &deltaKeys] (Pattern& p) {
  1561. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  1562. p.notes[(std::size_t) dragIndices[j]] = dragOriginals[j];
  1563. noteedit::move (p, dragIndices, deltaTicks, deltaKeys);
  1564. });
  1565. const auto& moved = currentPattern (engine.getSong()).notes[(std::size_t) dragNote];
  1566. if (moved.key != oldKey)
  1567. previewOn (moved.key, moved.velocity);
  1568. return;
  1569. }
  1570. case Drag::resize:
  1571. {
  1572. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  1573. const auto minimum = snapOn ? gridTicks() : (std::int64_t) 10;
  1574. const auto end = snapOn ? snap (xToTick (e.x) + (double) gridTicks() / 2.0, true) : (std::int64_t) xToTick (e.x);
  1575. const auto delta = juce::jmax (minimum, end - grabbed.start) - grabbed.length;
  1576. if (currentPattern (engine.getSong()).notes[(std::size_t) dragNote].length == grabbed.length + delta)
  1577. return;
  1578. lastLength = grabbed.length + delta;
  1579. editNotes ([this, delta, minimum] (Pattern& p) {
  1580. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  1581. p.notes[(std::size_t) dragIndices[j]].length = juce::jmax (minimum, dragOriginals[j].length + delta);
  1582. });
  1583. return;
  1584. }
  1585. case Drag::resizeLeft:
  1586. {
  1587. // the start moves, the end stays (selected notes together)
  1588. const auto& grabbed = dragOriginals[(std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin())];
  1589. const auto minimum = snapOn ? gridTicks() : (std::int64_t) 10;
  1590. auto delta = juce::jmax<std::int64_t> (0, snap (xToTick (e.x) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn)) - grabbed.start;
  1591. for (const auto& o : dragOriginals)
  1592. delta = juce::jlimit (-o.start, o.length - juce::jmin (minimum, o.length), delta);
  1593. if (currentPattern (engine.getSong()).notes[(std::size_t) dragNote].start == grabbed.start + delta)
  1594. return;
  1595. editNotes ([this, delta] (Pattern& p) {
  1596. for (std::size_t j = 0; j < dragIndices.size(); ++j)
  1597. {
  1598. auto& n = p.notes[(std::size_t) dragIndices[j]];
  1599. n.start = dragOriginals[j].start + delta;
  1600. n.length = dragOriginals[j].length - delta;
  1601. }
  1602. });
  1603. lastLength = grabbed.length - delta;
  1604. return;
  1605. }
  1606. }
  1607. }
  1608. void PianoRollComponent::postDragHint (const juce::MouseEvent& e)
  1609. {
  1610. const auto& notes = currentPattern (engine.getSong()).notes;
  1611. const auto count = juce::String ((int) juce::jmax<std::size_t> (1, dragIndices.size()));
  1612. auto steps = [] (std::int64_t ticks) {
  1613. const auto value = (double) ticks / ticksPerStep;
  1614. return (value > 0 ? "+" : "") + juce::String (value, std::abs (value - std::round (value)) < 1e-9 ? 0 : 2);
  1615. };
  1616. ui::Hint hint;
  1617. switch (drag)
  1618. {
  1619. case Drag::move:
  1620. {
  1621. const auto at = (std::size_t) (std::find (dragIndices.begin(), dragIndices.end(), dragNote) - dragIndices.begin());
  1622. if (dragNote < 0 || dragNote >= (int) notes.size() || at >= dragOriginals.size())
  1623. return;
  1624. const auto& now = notes[(std::size_t) dragNote];
  1625. const auto& was = dragOriginals[at];
  1626. hint.text = tr ("Moving {0} note(s): then [Shift] keeps the pitch [Ctrl] keeps the time [Alt] no snap", { count });
  1627. hint.value = keyName (now.key) + " " + juce::String (now.key - was.key >= 0 ? "+" : "") + juce::String (now.key - was.key) + " st "
  1628. + steps (now.start - was.start) + " " + tr ("steps");
  1629. break;
  1630. }
  1631. case Drag::resize:
  1632. case Drag::resizeLeft:
  1633. if (dragNote < 0 || dragNote >= (int) notes.size())
  1634. return;
  1635. hint.text = tr ("Resizing {0} note(s) [Alt] no snap", { count });
  1636. hint.value = juce::String ((double) notes[(std::size_t) dragNote].length / ticksPerStep, 2) + " " + tr ("steps");
  1637. break;
  1638. case Drag::eventDraw:
  1639. case Drag::eventErase:
  1640. {
  1641. const auto lane = velocityArea();
  1642. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  1643. hint.text = drag == Drag::eventErase ? tr ("Deleting events") : tr ("Drawing events: {0}", { laneBox.getText() });
  1644. hint.value = juce::String (juce::roundToInt (value * 100.0f)) + "%";
  1645. break;
  1646. }
  1647. case Drag::velocity:
  1648. case Drag::velocitySet:
  1649. case Drag::velocityLine:
  1650. {
  1651. const auto lane = velocityArea();
  1652. const auto value = drag == Drag::velocitySet ? laneSetValue
  1653. : juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
  1654. hint.text = tr ("Setting {0}", { laneBox.getText() });
  1655. hint.value = juce::String (juce::roundToInt (value * 100.0f)) + "%";
  1656. break;
  1657. }
  1658. case Drag::select:
  1659. case Drag::keySelect:
  1660. case Drag::rulerSelect:
  1661. hint.text = tr ("Selecting [Shift] adds to the selection");
  1662. hint.value = tr ("{0} selected", { juce::String ((int) selection.size()) });
  1663. break;
  1664. case Drag::erase: hint.text = tr ("Deleting what the mouse crosses"); break;
  1665. case Drag::muting: hint.text = tr ("Muting / unmuting what the mouse crosses"); break;
  1666. case Drag::knife: hint.text = tr ("Cutting along the line [Alt] no snap"); break;
  1667. case Drag::paint: hint.text = tr ("Painting notes [Alt] no snap"); break;
  1668. case Drag::drumPaint: hint.text = tr ("Drum brush: one hit per grid cell, on the key under the mouse [Alt] no snap"); break;
  1669. case Drag::stretch:
  1670. {
  1671. std::int64_t from = 0, to = 0;
  1672. std::vector<Note> now;
  1673. for (auto i : dragIndices)
  1674. if (i >= 0 && i < (int) notes.size())
  1675. now.push_back (notes[(std::size_t) i]);
  1676. noteedit::span (now, from, to);
  1677. hint.text = tr ("Stretching {0} note(s) in time [Alt] no snap", { count });
  1678. hint.value = "x" + juce::String ((double) (to - stretchAnchor) / (double) juce::jmax<std::int64_t> (1, stretchEnd - stretchAnchor), 2);
  1679. break;
  1680. }
  1681. case Drag::keyZoom: hint.text = tr ("Key height"); hint.value = juce::String (rowHeight) + " px"; break;
  1682. case Drag::pan:
  1683. case Drag::keyboard:
  1684. case Drag::listen:
  1685. case Drag::zoomRange:
  1686. case Drag::none: return;
  1687. }
  1688. ui::postHint (hint);
  1689. }
  1690. void PianoRollComponent::mouseUp (const juce::MouseEvent& e)
  1691. {
  1692. ui::clearPostedHint();
  1693. if (drag == Drag::knife)
  1694. cutWithKnife (knifeFrom, knifeTo, ! e.mods.isAltDown());
  1695. if (drag == Drag::zoomRange)
  1696. {
  1697. if (rubberBand.getWidth() > 4)
  1698. zoomToTicks (xToTick (rubberBand.getX()), xToTick (rubberBand.getRight()));
  1699. else
  1700. zoomIn (e.x); // a click zooms in around the point (right-click zooms out)
  1701. }
  1702. if (drag == Drag::select && rubberBand.isEmpty() && dragNote >= 0)
  1703. {
  1704. // Lasso click on a note: selects it (Shift: adds / removes)
  1705. auto s = selectionBefore;
  1706. if (auto it = std::find (s.begin(), s.end(), dragNote); it != s.end())
  1707. s.erase (it);
  1708. else
  1709. s.push_back (dragNote);
  1710. setSelection (s);
  1711. }
  1712. if (drag == Drag::listen)
  1713. stopListening();
  1714. if (drag == Drag::move || drag == Drag::resize || drag == Drag::resizeLeft || drag == Drag::paint || drag == Drag::drumPaint
  1715. || drag == Drag::stretch)
  1716. sortNotes();
  1717. previewOff();
  1718. drag = Drag::none;
  1719. dragNote = -1;
  1720. dragIndices.clear();
  1721. dragOriginals.clear();
  1722. touchedNotes.clear();
  1723. laneOriginals.clear();
  1724. rubberBand = {};
  1725. hover = {};
  1726. updateHover (e.getPosition(), e.mods); // the cursor of what is under the mouse now
  1727. repaint();
  1728. }
  1729. void PianoRollComponent::mouseMove (const juce::MouseEvent& e)
  1730. {
  1731. updateHover (e.getPosition(), e.mods);
  1732. }
  1733. void PianoRollComponent::mouseExit (const juce::MouseEvent&)
  1734. {
  1735. lastMouse = { -1, -1 };
  1736. if (! (hover == Hover {}))
  1737. {
  1738. hover = {};
  1739. repaint();
  1740. }
  1741. }
  1742. void PianoRollComponent::modifierKeysChanged (const juce::ModifierKeys& mods)
  1743. {
  1744. // Ctrl / Shift / Alt change what a click would do: the cursor follows without moving the mouse
  1745. if (drag == Drag::none && lastMouse.x >= 0)
  1746. updateCursor (mods);
  1747. }
  1748. PianoRollComponent::Hover PianoRollComponent::hoverAt (juce::Point<int> p) const
  1749. {
  1750. Hover h;
  1751. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  1752. {
  1753. h.key = yToKey (p.y);
  1754. return h;
  1755. }
  1756. if (velocityArea().contains (p))
  1757. {
  1758. // the stem nearest to the mouse (within a few pixels)
  1759. const auto& notes = currentPattern (engine.getSong()).notes;
  1760. auto best = 5.0;
  1761. for (auto i : channelNotes())
  1762. if (const auto d = std::abs (tickToX ((double) notes[(std::size_t) i].start) - p.x); d < best)
  1763. {
  1764. best = d;
  1765. h.note = i;
  1766. }
  1767. return h;
  1768. }
  1769. if (! gridArea().contains (p))
  1770. return h;
  1771. h.key = yToKey (p.y);
  1772. if (stretchHandle().expanded (2.0f).contains (p.toFloat()))
  1773. {
  1774. h.stretch = true;
  1775. return h;
  1776. }
  1777. const auto& notes = currentPattern (engine.getSong()).notes;
  1778. const auto channel = engine.getSelectedChannel();
  1779. gesture::EdgeRules rules;
  1780. rules.allowLeft = resizeFromLeft;
  1781. // back to front: the note drawn on top wins
  1782. for (int i = (int) notes.size() - 1; i >= 0; --i)
  1783. {
  1784. const auto& n = notes[(std::size_t) i];
  1785. if (n.channel != channel || n.key != h.key)
  1786. continue;
  1787. if (const auto zone = gesture::zoneAt (p.x, tickToX ((double) n.start), tickToX ((double) (n.start + n.length)), rules);
  1788. zone != gesture::Zone::outside)
  1789. {
  1790. h.note = i;
  1791. h.zone = zone;
  1792. return h;
  1793. }
  1794. }
  1795. h.ghost = ghostAt (p.x, p.y);
  1796. return h;
  1797. }
  1798. gesture::Target PianoRollComponent::targetAt (const Hover& h) const
  1799. {
  1800. return h.note >= 0 ? gesture::targetFor (h.zone) : gesture::Target::empty;
  1801. }
  1802. void PianoRollComponent::updateHover (juce::Point<int> p, juce::ModifierKeys mods)
  1803. {
  1804. lastMouse = p;
  1805. const auto h = hoverAt (p);
  1806. if (! (h == hover))
  1807. {
  1808. // repaint only what changed: the old and new note rows, the keyboard, the lane
  1809. auto dirty = [this] (const Hover& o) {
  1810. if (o.key >= 0)
  1811. repaint (0, keyToY (o.key) - 1, getWidth(), rowHeight + 2);
  1812. const auto& notes = currentPattern (engine.getSong()).notes;
  1813. for (auto i : { o.note, o.ghost })
  1814. if (i >= 0 && i < (int) notes.size())
  1815. {
  1816. repaint (0, keyToY (notes[(std::size_t) i].key) - 1, getWidth(), rowHeight + 2);
  1817. repaint (velocityArea());
  1818. }
  1819. };
  1820. dirty (hover);
  1821. hover = h;
  1822. dirty (hover);
  1823. }
  1824. if (drag == Drag::none)
  1825. updateCursor (mods);
  1826. }
  1827. void PianoRollComponent::updateCursor (juce::ModifierKeys mods)
  1828. {
  1829. const auto p = lastMouse;
  1830. auto cursor = gesture::Cursor::normal;
  1831. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  1832. cursor = mods.isCtrlDown() ? gesture::Cursor::select : gesture::Cursor::point;
  1833. else if (velocityArea().contains (p))
  1834. cursor = gesture::Cursor::draw;
  1835. else if (gridArea().contains (p) && hover.stretch && ! mods.isCtrlDown())
  1836. cursor = gesture::Cursor::resizeH;
  1837. else if (gridArea().contains (p) && editGhosts && hover.note < 0 && hover.ghost >= 0 && ! mods.isCtrlDown())
  1838. cursor = gesture::Cursor::move;
  1839. else if (gridArea().contains (p))
  1840. {
  1841. const gesture::Mods m { mods.isShiftDown(), mods.isCtrlDown(), mods.isAltDown() };
  1842. const auto tool = tools.getTool();
  1843. cursor = gesture::cursorFor (gesture::leftAction (tool, targetAt (hover), m, false), tool);
  1844. }
  1845. else if (p.y >= rulerTop && p.y < headerHeight && p.x >= keyboardWidth && mods.isCtrlDown())
  1846. cursor = gesture::Cursor::select;
  1847. setMouseCursor (editorCursor (cursor));
  1848. }
  1849. ui::Hint PianoRollComponent::hintAt (juce::Point<int> p)
  1850. {
  1851. ui::Hint hint;
  1852. const auto mods = juce::ModifierKeys::currentModifiers;
  1853. const auto& song = engine.getSong();
  1854. const auto& notes = currentPattern (song).notes;
  1855. const auto h = hoverAt (p);
  1856. auto noteValue = [&] (int i) {
  1857. const auto& n = notes[(std::size_t) i];
  1858. return keyName (n.key) + " " + juce::String (juce::roundToInt (n.velocity * 100.0f)) + "%";
  1859. };
  1860. if (p.x < keyboardWidth && p.y >= headerHeight && p.y < gridArea().getBottom())
  1861. {
  1862. hint.text = tr ("Keyboard: [LMB] hear the key [Ctrl][LMB] select its notes [MMB] drag: taller / shorter keys");
  1863. hint.value = keyName (h.key);
  1864. return hint;
  1865. }
  1866. if (velocityArea().contains (p))
  1867. {
  1868. hint.text = tr ("{0} lane: [LMB] drag draws [RMB] drag draws a line [Shift][LMB] one value [Alt][LMB] reset [Alt][Wheel] over a note: adjust",
  1869. { laneBox.getText() });
  1870. if (h.note >= 0)
  1871. hint.value = noteValue (h.note);
  1872. return hint;
  1873. }
  1874. if (p.y >= rulerTop && p.y < headerHeight && p.x >= keyboardWidth)
  1875. {
  1876. hint.text = tr ("Ruler: [Ctrl][LMB] drag selects the notes in a time range [Ctrl][Wheel] zoom [Shift][Wheel] scroll");
  1877. return hint;
  1878. }
  1879. if (! gridArea().contains (p))
  1880. return hint;
  1881. if (h.stretch)
  1882. {
  1883. hint.text = tr ("Stretch handle: [LMB] drag stretches or squeezes the selected notes in time (from the selection's start) [Alt] no snap");
  1884. hint.value = tr ("{0} selected", { juce::String ((int) selection.size()) });
  1885. return hint;
  1886. }
  1887. if (h.note < 0 && h.ghost >= 0)
  1888. {
  1889. const auto ghostChannel = notes[(std::size_t) h.ghost].channel;
  1890. const auto name = ghostChannel >= 0 && ghostChannel < (int) song.channels.size()
  1891. ? juce::String::fromUTF8 (song.channels[(std::size_t) ghostChannel].name.c_str())
  1892. : juce::String();
  1893. hint.text = editGhosts ? tr ("Ghost note of {0} (editable): [LMB] edit it (switches to {0}) [RMB] deletes it [Ctrl][Alt][V] read-only ghosts",
  1894. { name })
  1895. : tr ("Ghost note of {0}: double [RMB] edits that channel [Alt][V] hides ghost notes [Ctrl][Alt][V] makes them editable",
  1896. { name });
  1897. hint.value = keyName (notes[(std::size_t) h.ghost].key);
  1898. return hint;
  1899. }
  1900. const gesture::Mods m { mods.isShiftDown(), mods.isCtrlDown(), mods.isAltDown() };
  1901. hint.text = actionHint (gesture::leftAction (tools.getTool(), targetAt (h), m, false), false);
  1902. hint.value = h.note >= 0 ? noteValue (h.note) : keyName (h.key);
  1903. return hint;
  1904. }
  1905. void PianoRollComponent::mouseDoubleClick (const juce::MouseEvent& e)
  1906. {
  1907. if (! gridArea().contains (e.getPosition()) || e.mods.isRightButtonDown() || e.mods.isCtrlDown())
  1908. return;
  1909. // the first click of this double click created the note: that was drawing, not opening it
  1910. if (juce::Time::getMillisecondCounter() - createdAt < 800)
  1911. return;
  1912. bool edge = false;
  1913. const auto hit = noteAt (e.x, e.y, edge);
  1914. if (hit < 0)
  1915. return;
  1916. const auto indices = isSelected (hit) ? selection : std::vector<int> { hit };
  1917. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) hit];
  1918. const auto area = juce::Rectangle<int> ((int) tickToX ((double) n.start), keyToY (n.key), juce::jmax (8, (int) (n.length * pixelsPerTick)), rowHeight);
  1919. showNoteInspector (engine, indices, hit, localAreaToGlobal (area));
  1920. }
  1921. std::unique_ptr<juce::Component> PianoRollComponent::makeNoteInspectorForSnapshot (bool singleNote)
  1922. {
  1923. if (selection.empty())
  1924. selectAll();
  1925. if (selection.empty())
  1926. return nullptr;
  1927. return makeNoteInspector (engine, singleNote ? std::vector<int> { selection.front() } : selection, selection.front());
  1928. }
  1929. ui::Hint PianoRollComponent::hoverForSnapshot()
  1930. {
  1931. rowHeight = 18;
  1932. pixelsPerTick = 64.0 / ticksPerStep;
  1933. scrollToNotes (false);
  1934. const auto notes = channelNotes();
  1935. if (notes.empty())
  1936. return {};
  1937. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) notes.front()];
  1938. const auto at = juce::Point<int> ((int) tickToX ((double) (n.start + n.length)) - 2, keyToY (n.key) + rowHeight / 2);
  1939. updateHover (at, {});
  1940. return hintAt (at);
  1941. }
  1942. // --- tools ---------------------------------------------------------------------------
  1943. void PianoRollComponent::cutWithKnife (juce::Point<int> from, juce::Point<int> to, bool snapOn)
  1944. {
  1945. const auto& notes = currentPattern (engine.getSong()).notes;
  1946. const auto channel = engine.getSelectedChannel();
  1947. std::vector<std::pair<int, std::int64_t>> cuts;
  1948. if (from.getDistanceFrom (to) < 3)
  1949. {
  1950. // a click: cuts the note under the cursor
  1951. bool edge = false;
  1952. if (const auto hit = noteAt (from.x, from.y, edge); hit >= 0)
  1953. cuts.push_back ({ hit, snap (xToTick (from.x) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn) });
  1954. }
  1955. else
  1956. {
  1957. // a line: every note row it crosses is cut where the line passes
  1958. const auto top = juce::jmin (from.y, to.y), bottom = juce::jmax (from.y, to.y);
  1959. for (int i = 0; i < (int) notes.size(); ++i)
  1960. {
  1961. const auto& n = notes[(std::size_t) i];
  1962. if (n.channel != channel)
  1963. continue;
  1964. const auto rowY = keyToY (n.key) + rowHeight / 2;
  1965. if (rowY < top - rowHeight / 2 || rowY > bottom + rowHeight / 2)
  1966. continue;
  1967. const auto y = juce::jlimit (top, bottom, rowY);
  1968. const auto x = from.y == to.y ? (double) from.x : from.x + (double) (y - from.y) * (to.x - from.x) / (double) (to.y - from.y);
  1969. const auto tick = snap (xToTick ((int) std::round (x)) + (snapOn ? (double) gridTicks() / 2.0 : 0.0), snapOn);
  1970. if (tick > n.start && tick < n.start + n.length)
  1971. cuts.push_back ({ i, tick });
  1972. }
  1973. }
  1974. if (cuts.empty())
  1975. return;
  1976. setSelection ({});
  1977. editNotes ([&cuts] (Pattern& p) {
  1978. for (auto [index, tick] : cuts)
  1979. noteedit::split (p, index, tick);
  1980. });
  1981. sortNotes();
  1982. }
  1983. void PianoRollComponent::zoomToTicks (double from, double to)
  1984. {
  1985. if (to - from < 1.0)
  1986. return;
  1987. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, gridArea().getWidth() / (to - from));
  1988. scrollTicks = juce::jmax (0.0, from);
  1989. updateScrollBars();
  1990. repaint();
  1991. }
  1992. void PianoRollComponent::zoomIn (int anchorX)
  1993. {
  1994. const auto anchor = xToTick (anchorX);
  1995. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * 2.0);
  1996. scrollTicks = juce::jmax (0.0, anchor - (anchorX - keyboardWidth) / pixelsPerTick);
  1997. updateScrollBars();
  1998. repaint();
  1999. }
  2000. void PianoRollComponent::zoomOut (int anchorX)
  2001. {
  2002. const auto anchor = xToTick (anchorX);
  2003. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick / 2.0);
  2004. scrollTicks = juce::jmax (0.0, anchor - (anchorX - keyboardWidth) / pixelsPerTick);
  2005. updateScrollBars();
  2006. repaint();
  2007. }
  2008. void PianoRollComponent::listenAt (int x)
  2009. {
  2010. // plays the channel's notes that sound at the tick under the mouse
  2011. const auto tick = (std::int64_t) xToTick (x);
  2012. const auto& notes = currentPattern (engine.getSong()).notes;
  2013. const auto channel = engine.getSelectedChannel();
  2014. std::vector<int> keys;
  2015. std::vector<float> velocities;
  2016. for (const auto& n : notes)
  2017. if (n.channel == channel && ! n.muted && n.start <= tick && n.start + n.length > tick
  2018. && std::find (keys.begin(), keys.end(), n.key) == keys.end())
  2019. {
  2020. keys.push_back (n.key);
  2021. velocities.push_back (n.velocity);
  2022. }
  2023. for (auto k : listenKeys)
  2024. if (std::find (keys.begin(), keys.end(), k) == keys.end())
  2025. listenNotes.release (listenChannel, k);
  2026. if (channel != listenChannel)
  2027. listenNotes.releaseAll();
  2028. for (std::size_t i = 0; i < keys.size(); ++i)
  2029. if (! listenNotes.isHeld (channel, keys[i]))
  2030. listenNotes.press (channel, keys[i], velocities[i]);
  2031. listenKeys = keys;
  2032. listenChannel = channel;
  2033. }
  2034. void PianoRollComponent::stopListening()
  2035. {
  2036. listenNotes.releaseAll();
  2037. listenKeys.clear();
  2038. }
  2039. void PianoRollComponent::refreshChannelBox()
  2040. {
  2041. const auto& song = engine.getSong();
  2042. std::vector<bool> hasNotes (song.channels.size(), false);
  2043. for (const auto& n : currentPattern (song).notes)
  2044. if (n.channel >= 0 && n.channel < (int) hasNotes.size())
  2045. hasNotes[(std::size_t) n.channel] = true;
  2046. juce::StringArray names;
  2047. for (std::size_t c = 0; c < song.channels.size(); ++c)
  2048. names.add ((hasNotes[c] ? juce::String::fromUTF8 ("\xe2\x97\x8f ") : juce::String (" ")) + juce::String::fromUTF8 (song.channels[c].name.c_str()));
  2049. // only rebuilds when something changed (rebuilding closes an open menu)
  2050. bool same = channelBox.getNumItems() == names.size();
  2051. for (int i = 0; same && i < names.size(); ++i)
  2052. same = channelBox.getItemText (i) == names[i];
  2053. if (! same)
  2054. {
  2055. channelBox.clear (juce::dontSendNotification);
  2056. for (int i = 0; i < names.size(); ++i)
  2057. channelBox.addItem (names[i], i + 1);
  2058. }
  2059. channelBox.setSelectedId (engine.getSelectedChannel() + 1, juce::dontSendNotification);
  2060. }
  2061. void PianoRollComponent::stepChannel (int direction, bool withNotesOnly)
  2062. {
  2063. const auto& song = engine.getSong();
  2064. const auto count = (int) song.channels.size();
  2065. if (count == 0)
  2066. return;
  2067. std::vector<bool> hasNotes ((std::size_t) count, false);
  2068. for (const auto& n : currentPattern (song).notes)
  2069. if (n.channel >= 0 && n.channel < count)
  2070. hasNotes[(std::size_t) n.channel] = true;
  2071. auto channel = engine.getSelectedChannel();
  2072. for (int step = 0; step < count; ++step)
  2073. {
  2074. channel += direction;
  2075. if (channel < 0 || channel >= count)
  2076. return; // stops at the ends
  2077. if (! withNotesOnly || hasNotes[(std::size_t) channel])
  2078. {
  2079. engine.setSelectedChannel (channel);
  2080. return;
  2081. }
  2082. }
  2083. }
  2084. void PianoRollComponent::runOperation (const std::function<std::vector<int> (Pattern&, const std::vector<int>&)>& op)
  2085. {
  2086. const auto target = selectionOrAll();
  2087. if (target.empty())
  2088. return;
  2089. const auto hadSelection = ! selection.empty();
  2090. std::vector<int> result;
  2091. editNotes ([&] (Pattern& p) { result = op (p, target); });
  2092. setSelection (hadSelection ? result : std::vector<int> {});
  2093. sortNotes();
  2094. }
  2095. void PianoRollComponent::showMoreMenu()
  2096. {
  2097. const auto grid = gridTicks();
  2098. const auto bar = (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  2099. juce::PopupMenu menu;
  2100. menu.addSectionHeader (tr ("Note operations (selection, or all notes)"));
  2101. menu.addItem (tr ("Chop to grid") + "\tCtrl+U", [this, grid] { runOperation ([grid] (Pattern& p, const std::vector<int>& t) { return noteedit::chop (p, t, grid); }); });
  2102. menu.addItem (tr ("Join touching notes") + "\tCtrl+G", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::join (p, t); return std::vector<int> {}; }); });
  2103. menu.addItem (tr ("Make legato") + "\tCtrl+L", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; }); });
  2104. menu.addItem (tr ("Shrink to grid") + "\tShift+D", [this, grid] { runOperation ([grid] (Pattern& p, const std::vector<int>& t) { noteedit::shrinkToGrid (p, t, grid); return t; }); });
  2105. menu.addItem (tr ("Quantise starts") + "\tShift+Q", [this, grid] { runOperation ([grid] (Pattern& p, const std::vector<int>& t) { noteedit::quantize (p, t, grid); return t; }); });
  2106. menu.addItem (tr ("Quantise starts and lengths") + "\tCtrl+Q", [this, grid] { runOperation ([grid] (Pattern& p, const std::vector<int>& t) { noteedit::quantizeFull (p, t, grid); return t; }); });
  2107. menu.addItem (tr ("Rotate left within the bar") + "\tCtrl+Shift+Left", [this, grid, bar] { runOperation ([grid, bar] (Pattern& p, const std::vector<int>& t) { noteedit::rotate (p, t, grid, bar, -1); return t; }); });
  2108. menu.addItem (tr ("Rotate right within the bar") + "\tCtrl+Shift+Right", [this, grid, bar] { runOperation ([grid, bar] (Pattern& p, const std::vector<int>& t) { noteedit::rotate (p, t, grid, bar, 1); return t; }); });
  2109. menu.addSeparator();
  2110. menu.addSubMenu (tr ("Tools"), toolsMenu());
  2111. menu.addSubMenu (tr ("Select"), selectMenu());
  2112. {
  2113. juce::PopupMenu zoom;
  2114. zoom.addItem (tr ("Zoom in") + "\tPageUp", [this] { runAction ("pianoRoll.zoomIn"); });
  2115. zoom.addItem (tr ("Zoom out") + "\tPageDown", [this] { runAction ("pianoRoll.zoomOut"); });
  2116. zoom.addItem (tr ("Zoom: one bar") + "\tShift+1", [this] { runAction ("pianoRoll.zoom1"); });
  2117. zoom.addItem (tr ("Zoom: four bars") + "\tShift+2", [this] { runAction ("pianoRoll.zoom2"); });
  2118. zoom.addItem (tr ("Zoom: sixteen bars") + "\tShift+3", [this] { runAction ("pianoRoll.zoom3"); });
  2119. zoom.addItem (tr ("Zoom to show everything") + "\tShift+4", [this] { runAction ("pianoRoll.zoomAll"); });
  2120. zoom.addItem (tr ("Zoom to the selection") + "\tShift+5", [this] { runAction ("pianoRoll.zoomSelection"); });
  2121. zoom.addItem (tr ("Centre the view on the playhead") + "\tShift+0", [this] { runAction ("pianoRoll.centrePlayhead"); });
  2122. zoom.addSeparator();
  2123. zoom.addItem (tr ("Taller keys") + "\tCtrl+Alt+Wheel", [this] { rowHeight = juce::jmin (32, rowHeight + 2); updateScrollBars(); repaint(); });
  2124. zoom.addItem (tr ("Shorter keys"), [this] { rowHeight = juce::jmax (6, rowHeight - 2); updateScrollBars(); repaint(); });
  2125. menu.addSubMenu (tr ("Zoom"), zoom);
  2126. }
  2127. menu.addSeparator();
  2128. menu.addItem (tr ("Snap notes to the scale"), scaleIndex() > 0, scaleSnap, [this] { setScaleSnap (! scaleSnap); });
  2129. menu.addItem (tr ("Move the notes onto the scale"), scaleIndex() > 0, false, [this] {
  2130. const auto root = scaleRoot(), scale = scaleIndex();
  2131. runOperation ([root, scale] (Pattern& p, const std::vector<int>& t) { notetools::snapNotesToScale (p, t, root, scale); return t; });
  2132. });
  2133. menu.addSeparator();
  2134. menu.addItem (tr ("Resize notes from the left edge too") + "\tCtrl+Alt+Home", true, resizeFromLeft, [this] { resizeFromLeft = ! resizeFromLeft; });
  2135. menu.addItem (tr ("Show ghost notes") + "\tAlt+V", true, showGhosts,
  2136. [this] { ghostButton.setToggleState (! ghostButton.getToggleState(), juce::sendNotificationSync); });
  2137. menu.addItem (tr ("Ghost notes are editable") + "\tCtrl+Alt+V", true, editGhosts, [this] {
  2138. editGhosts = ! editGhosts;
  2139. if (editGhosts && ! showGhosts)
  2140. ghostButton.setToggleState (true, juce::sendNotificationSync);
  2141. repaint();
  2142. });
  2143. menu.addSeparator();
  2144. menu.addSubMenu ("MIDI", midiMenu());
  2145. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&moreButton));
  2146. }
  2147. juce::PopupMenu PianoRollComponent::toolsMenu()
  2148. {
  2149. // FL's piano roll Tools menu (REA round 143, EXEC capture): its groups and keys, in its order
  2150. juce::PopupMenu menu;
  2151. const auto grid = gridTicks();
  2152. auto tool = [this, &menu] (NoteTool t, const char* key) {
  2153. menu.addItem (tr (noteToolTitle (t)) + "..." + (key != nullptr ? juce::String ("\t") + key : juce::String()), [this, t] { openNoteTool (t); });
  2154. };
  2155. menu.addSectionHeader (tr ("Built-in"));
  2156. tool (NoteTool::riffMachine, "Alt+E");
  2157. menu.addItem (tr ("Generate chord progression...") + "\tAlt+P", [this] { openNoteTool (NoteTool::chordProgression); });
  2158. menu.addSeparator();
  2159. menu.addItem (tr ("Quick legato") + "\tCtrl+L", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; }); });
  2160. tool (NoteTool::articulate, "Alt+L");
  2161. menu.addSeparator();
  2162. menu.addItem (tr ("Quick quantize") + "\tCtrl+Q", [this, grid] { runOperation ([grid] (Pattern& p, const std::vector<int>& t) { noteedit::quantizeFull (p, t, grid); return t; }); });
  2163. menu.addItem (tr ("Quick quantize start times") + "\tShift+Q", [this, grid] { runOperation ([grid] (Pattern& p, const std::vector<int>& t) { noteedit::quantize (p, t, grid); return t; }); });
  2164. tool (NoteTool::quantize, "Alt+Q");
  2165. menu.addSeparator();
  2166. menu.addItem (tr ("Quick chop") + "\tCtrl+U", [this, grid] { runOperation ([grid] (Pattern& p, const std::vector<int>& t) { return noteedit::chop (p, t, grid); }); });
  2167. tool (NoteTool::chop, "Alt+U");
  2168. menu.addSeparator();
  2169. menu.addItem (tr ("Glue notes") + "\tCtrl+G", [this] { runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::join (p, t); return std::vector<int> {}; }); });
  2170. menu.addSeparator();
  2171. tool (NoteTool::arpeggiate, "Alt+A");
  2172. tool (NoteTool::strum, "Alt+S");
  2173. tool (NoteTool::flam, "Alt+F");
  2174. tool (NoteTool::claw, "Alt+W");
  2175. tool (NoteTool::limit, "Alt+K");
  2176. tool (NoteTool::flip, "Alt+Y");
  2177. tool (NoteTool::randomise, "Alt+R");
  2178. menu.addSeparator();
  2179. tool (NoteTool::scaleLevels, "Alt+X");
  2180. tool (NoteTool::lfo, "Alt+O");
  2181. // FL's second column ("Scripts": Python tools shipped with FL); LYNX has its own built-in versions
  2182. menu.addSectionHeader (tr ("More tools"));
  2183. tool (NoteTool::euclidean, nullptr);
  2184. tool (NoteTool::humanize, nullptr);
  2185. tool (NoteTool::noteRepeat, nullptr);
  2186. {
  2187. juce::PopupMenu velocity;
  2188. auto choose = [this] (std::function<std::vector<int> (const Pattern&, const std::vector<int>&)> pick) {
  2189. const auto& song = engine.getSong();
  2190. setSelection (pick (song.patterns[(std::size_t) song.currentPattern], channelNotes()));
  2191. };
  2192. velocity.addItem (tr ("Loudest quarter"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectLoudest (p, t, 0.25f, true); }); });
  2193. velocity.addItem (tr ("Quietest quarter"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectLoudest (p, t, 0.25f, false); }); });
  2194. velocity.addSeparator();
  2195. for (const auto& [label, lo, hi] : { std::tuple { "75-100%", 0.75f, 1.0f }, { "50-75%", 0.5f, 0.75f }, { "25-50%", 0.25f, 0.5f }, { "0-25%", 0.0f, 0.25f } })
  2196. velocity.addItem (tr ("Velocity {0}", { juce::String (label) }), [choose, lo = lo, hi = hi] {
  2197. choose ([lo, hi] (const Pattern& p, const std::vector<int>& t) { return notetools::selectByVelocity (p, t, lo, hi); });
  2198. });
  2199. if (! selection.empty())
  2200. {
  2201. const auto& notes = engine.getSong().patterns[(std::size_t) engine.getSong().currentPattern].notes;
  2202. const auto v = selection.front() < (int) notes.size() ? notes[(std::size_t) selection.front()].velocity : 0.0f;
  2203. velocity.addSeparator();
  2204. velocity.addItem (tr ("Same velocity as the selected note ({0}%)", { juce::String (juce::roundToInt (v * 100.0f)) }), [choose, v] {
  2205. choose ([v] (const Pattern& p, const std::vector<int>& t) { return notetools::selectByVelocity (p, t, v - 0.005f, v + 0.005f); });
  2206. });
  2207. }
  2208. menu.addSubMenu (tr ("Select by velocity"), velocity);
  2209. }
  2210. menu.addSeparator();
  2211. menu.addItem (tr ("Edit events..."), [this] {
  2212. openEventEditor (engine, { AutomationTargetKind::channelVolume, engine.getSelectedChannel() });
  2213. });
  2214. return menu;
  2215. }
  2216. void PianoRollComponent::openNoteTool (NoteTool tool)
  2217. {
  2218. const auto target = selectionOrAll();
  2219. if (target.empty() && ! noteToolGenerates (tool))
  2220. return;
  2221. showNoteTool (engine, tool, target, gridTicks(), [safe = juce::Component::SafePointer<PianoRollComponent> (this)] {
  2222. if (safe != nullptr)
  2223. safe->setSelection ({});
  2224. });
  2225. }
  2226. void PianoRollComponent::zoomAroundCentre (double factor)
  2227. {
  2228. const auto grid = gridArea();
  2229. const auto centre = xToTick (grid.getCentreX());
  2230. pixelsPerTick = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * factor);
  2231. scrollTicks = juce::jmax (0.0, centre - (grid.getCentreX() - keyboardWidth) / pixelsPerTick);
  2232. updateScrollBars();
  2233. repaint();
  2234. }
  2235. void PianoRollComponent::zoomToBars (int bars)
  2236. {
  2237. const auto bar = (double) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  2238. const auto from = std::floor (scrollTicks / bar) * bar;
  2239. zoomToTicks (from, from + bars * bar);
  2240. }
  2241. void PianoRollComponent::zoomAll()
  2242. {
  2243. const auto& song = engine.getSong();
  2244. zoomToTicks (0.0, (double) currentPattern (song).effectiveLength (song.beatsPerBar));
  2245. }
  2246. void PianoRollComponent::zoomToSelection()
  2247. {
  2248. const auto target = selectionOrAll();
  2249. if (target.empty())
  2250. return zoomAll();
  2251. const auto& notes = currentPattern (engine.getSong()).notes;
  2252. std::int64_t from = INT64_MAX, to = 0;
  2253. int low = 127, high = 0;
  2254. for (auto i : target)
  2255. {
  2256. const auto& n = notes[(std::size_t) i];
  2257. from = juce::jmin (from, n.start);
  2258. to = juce::jmax (to, n.start + n.length);
  2259. low = juce::jmin (low, n.key);
  2260. high = juce::jmax (high, n.key);
  2261. }
  2262. const auto margin = (double) ticksPerStep;
  2263. zoomToTicks (juce::jmax (0.0, (double) from - margin), (double) to + margin);
  2264. scrollY = juce::jmax (0, (127 - (low + high) / 2) * rowHeight - gridArea().getHeight() / 2);
  2265. updateScrollBars();
  2266. repaint();
  2267. }
  2268. void PianoRollComponent::centreOnPlayhead()
  2269. {
  2270. const auto& song = engine.getSong();
  2271. const auto length = (double) juce::jmax<std::int64_t> (1, currentPattern (song).effectiveLength (song.beatsPerBar));
  2272. const auto tick = std::fmod (engine.getTransport().positionTicks.load(), length);
  2273. scrollTicks = juce::jmax (0.0, tick - gridArea().getWidth() / pixelsPerTick / 2.0);
  2274. updateScrollBars();
  2275. repaint();
  2276. }
  2277. void PianoRollComponent::ColourSwatch::paintButton (juce::Graphics& g, bool over, bool down)
  2278. {
  2279. auto r = getLocalBounds().toFloat().reduced (3.0f);
  2280. g.setColour (theme::noteGroupColour (colourIndex, 0.85f));
  2281. g.fillRoundedRectangle (r, 3.0f);
  2282. g.setColour (over || down ? theme::colour::textPrimary : theme::colour::bg0.withAlpha (0.7f));
  2283. g.drawRoundedRectangle (r, 3.0f, 1.0f);
  2284. g.setColour (theme::colour::bg0.withAlpha (0.85f));
  2285. g.setFont (theme::font (theme::type::caption, true));
  2286. g.drawText (juce::String (colourIndex + 1), r, juce::Justification::centred, false);
  2287. }
  2288. void PianoRollComponent::colourSelection (int colour)
  2289. {
  2290. const auto target = selection;
  2291. if (target.empty())
  2292. return;
  2293. editNotes ([&] (Pattern& p) { notetools::setColour (p, target, colour); });
  2294. repaint();
  2295. }
  2296. void PianoRollComponent::selectByColour (int colour)
  2297. {
  2298. setSelection (notetools::selectByColour (currentPattern (engine.getSong()), channelNotes(), colour));
  2299. }
  2300. void PianoRollComponent::showColourMenu()
  2301. {
  2302. juce::PopupMenu menu;
  2303. menu.addSectionHeader (tr ("Colour for new notes"));
  2304. for (int c = 0; c < noteColourCount; ++c)
  2305. menu.addColouredItem (c + 1, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f), true, c == noteColour);
  2306. menu.addSeparator();
  2307. menu.addItem (1000, tr ("Colour the selected notes with it") + "\tAlt+C", ! selection.empty());
  2308. {
  2309. juce::PopupMenu colourAs;
  2310. for (int c = 0; c < noteColourCount; ++c)
  2311. colourAs.addColouredItem (2001 + c, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f), true, false);
  2312. menu.addSubMenu (tr ("Colour the selected notes"), colourAs, ! selection.empty());
  2313. }
  2314. {
  2315. juce::PopupMenu select;
  2316. const auto& pattern = currentPattern (engine.getSong());
  2317. for (int c = 0; c < noteColourCount; ++c)
  2318. select.addColouredItem (3001 + c, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f),
  2319. ! notetools::selectByColour (pattern, channelNotes(), c).empty(), false);
  2320. menu.addSubMenu (tr ("Select by colour") + "\tShift+C", select);
  2321. }
  2322. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&colourButton), [safe = juce::Component::SafePointer (this)] (int id) {
  2323. if (safe == nullptr || id <= 0)
  2324. return;
  2325. if (id <= noteColourCount)
  2326. {
  2327. safe->noteColour = id - 1;
  2328. safe->colourButton.colourIndex = id - 1;
  2329. safe->colourButton.repaint();
  2330. }
  2331. else if (id == 1000)
  2332. safe->colourSelection (safe->noteColour);
  2333. else if (id > 2000 && id <= 2000 + noteColourCount)
  2334. safe->colourSelection (id - 2001);
  2335. else if (id > 3000 && id <= 3000 + noteColourCount)
  2336. safe->selectByColour (id - 3001);
  2337. });
  2338. }
  2339. juce::PopupMenu PianoRollComponent::selectMenu()
  2340. {
  2341. // FL's piano roll Select submenu (its manual): all, invert, odd, random, muted, overlapping, stacked, by colour
  2342. juce::PopupMenu menu;
  2343. auto choose = [this] (std::function<std::vector<int> (const Pattern&, const std::vector<int>&)> pick) {
  2344. setSelection (pick (currentPattern (engine.getSong()), channelNotes()));
  2345. };
  2346. menu.addItem (tr ("All") + "\tCtrl+A", [this] { selectAll(); });
  2347. menu.addItem (tr ("Invert selection") + "\tShift+I", [this] { runAction ("pianoRoll.invertSelection"); });
  2348. menu.addItem (tr ("Deselect") + "\tEsc", ! selection.empty(), false, [this] { setSelection ({}); });
  2349. menu.addSeparator();
  2350. menu.addItem (tr ("Odd notes (every other one)"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectOdd (p, t); }); });
  2351. menu.addItem (tr ("Even notes"), [choose] {
  2352. choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::invertSelection (t, notetools::selectOdd (p, t)); });
  2353. });
  2354. menu.addItem (tr ("Random (half of the notes)"), [choose] {
  2355. const auto seed = (std::uint32_t) juce::Random::getSystemRandom().nextInt();
  2356. choose ([seed] (const Pattern& p, const std::vector<int>& t) { return notetools::selectRandom (p, t, 0.5f, seed); });
  2357. });
  2358. menu.addItem (tr ("Muted notes"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectMuted (p, t); }); });
  2359. menu.addItem (tr ("Overlapping notes"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectOverlapping (p, t); }); });
  2360. menu.addItem (tr ("Stacked notes (hidden duplicates)"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectStacked (p, t); }); });
  2361. menu.addItem (tr ("Same colour as the selection") + "\tShift+C", [this] { runAction ("pianoRoll.selectByColour"); });
  2362. return menu;
  2363. }
  2364. void PianoRollComponent::updateChordReadout()
  2365. {
  2366. auto keys = engine.heldInputKeys();
  2367. if (keys.size() < 2)
  2368. {
  2369. keys.clear();
  2370. const auto& notes = currentPattern (engine.getSong()).notes;
  2371. for (auto i : selection)
  2372. if (i >= 0 && i < (int) notes.size())
  2373. keys.push_back (notes[(std::size_t) i].key);
  2374. }
  2375. const auto chord = prtools::detectChord (keys);
  2376. const auto text = chord ? juce::String (chord->name) : juce::String();
  2377. if (chordLabel.getText() != text)
  2378. chordLabel.setText (text, juce::dontSendNotification);
  2379. }
  2380. bool PianoRollComponent::runAction (const std::string& id)
  2381. {
  2382. auto is = [&id] (const char* name) { return id == name; };
  2383. if (is ("pianoRoll.arpeggiate")) openNoteTool (NoteTool::arpeggiate);
  2384. else if (is ("pianoRoll.strum")) openNoteTool (NoteTool::strum);
  2385. else if (is ("pianoRoll.flip")) openNoteTool (NoteTool::flip);
  2386. else if (is ("pianoRoll.randomise")) openNoteTool (NoteTool::randomise);
  2387. else if (is ("pianoRoll.scaleLevels")) openNoteTool (NoteTool::scaleLevels);
  2388. else if (is ("pianoRoll.limit")) openNoteTool (NoteTool::limit);
  2389. else if (is ("pianoRoll.quantize")) openNoteTool (NoteTool::quantize);
  2390. else if (is ("pianoRoll.chop")) openNoteTool (NoteTool::chop);
  2391. else if (is ("pianoRoll.flam")) openNoteTool (NoteTool::flam);
  2392. else if (is ("pianoRoll.claw")) openNoteTool (NoteTool::claw);
  2393. else if (is ("pianoRoll.lfo")) openNoteTool (NoteTool::lfo);
  2394. else if (is ("pianoRoll.articulate")) openNoteTool (NoteTool::articulate);
  2395. else if (is ("pianoRoll.riffMachine")) openNoteTool (NoteTool::riffMachine);
  2396. else if (is ("pianoRoll.chordProgression")) openNoteTool (NoteTool::chordProgression);
  2397. else if (is ("pianoRoll.zoomIn")) zoomAroundCentre (1.25);
  2398. else if (is ("pianoRoll.zoomOut")) zoomAroundCentre (1.0 / 1.25);
  2399. else if (is ("pianoRoll.zoom1")) zoomToBars (1);
  2400. else if (is ("pianoRoll.zoom2")) zoomToBars (4);
  2401. else if (is ("pianoRoll.zoom3")) zoomToBars (16);
  2402. else if (is ("pianoRoll.zoomAll")) zoomAll();
  2403. else if (is ("pianoRoll.zoomSelection")) zoomToSelection();
  2404. else if (is ("pianoRoll.centrePlayhead")) centreOnPlayhead();
  2405. else if (is ("pianoRoll.colourSelected")) colourSelection (noteColour);
  2406. else if (is ("pianoRoll.selectByColour"))
  2407. {
  2408. // the colour of the selected note (FL: the selection's colour), else the current note colour
  2409. const auto& notes = currentPattern (engine.getSong()).notes;
  2410. selectByColour (! selection.empty() && selection.front() < (int) notes.size() ? notes[(std::size_t) selection.front()].colour : noteColour);
  2411. }
  2412. else if (is ("pianoRoll.invertSelection")) setSelection (notetools::invertSelection (channelNotes(), selection));
  2413. else
  2414. return false;
  2415. return true;
  2416. }
  2417. void PianoRollComponent::wheelNoteProperty (int note, float deltaY, bool fine)
  2418. {
  2419. // the hovered note, or the whole selection when the hovered note is part of it
  2420. const auto targets = isSelected (note) ? selection : std::vector<int> { note };
  2421. const auto now = juce::Time::getMillisecondCounter();
  2422. const auto newBurst = now - lastWheelEdit > 700; // one undo step per burst of wheel moves
  2423. lastWheelEdit = now;
  2424. editNotes ([&] (Pattern& p) {
  2425. for (auto i : targets)
  2426. {
  2427. auto& n = p.notes[(std::size_t) i];
  2428. setLaneValue (n, (float) gesture::wheelStepValue (laneValue (n), deltaY, fine));
  2429. }
  2430. }, newBurst);
  2431. }
  2432. void PianoRollComponent::glideBy (double ticks, double pixels)
  2433. {
  2434. if (! gliding)
  2435. {
  2436. glideX.jumpTo (scrollTicks);
  2437. glideY.jumpTo (scrollY);
  2438. gliding = true;
  2439. }
  2440. const auto grid = gridArea();
  2441. glideX.target = juce::jlimit (0.0, juce::jmax (0.0, (double) viewLengthTicks() - grid.getWidth() / pixelsPerTick), glideX.target + ticks);
  2442. glideY.target = juce::jlimit (0.0, juce::jmax (0.0, 128.0 * rowHeight - grid.getHeight()), glideY.target + pixels);
  2443. glideFrame();
  2444. }
  2445. void PianoRollComponent::glideFrame()
  2446. {
  2447. if (! gliding)
  2448. return;
  2449. // someone else moved the view (scroll bar, zoom, pan): the glide gives way
  2450. if (std::abs (scrollTicks - glideX.current) > 1e-6 || std::abs ((double) scrollY - std::round (glideY.current)) > 0.5)
  2451. {
  2452. gliding = false;
  2453. return;
  2454. }
  2455. scrollTicks = glideX.step (0.45, 0.5 / pixelsPerTick);
  2456. scrollY = (int) std::round (glideY.step (0.45, 1.0));
  2457. glideY.current = scrollY;
  2458. updateScrollBars();
  2459. glideX.current = scrollTicks; // the scroll bar may have clamped it
  2460. gliding = glideX.isMoving() || glideY.isMoving();
  2461. repaint();
  2462. }
  2463. void PianoRollComponent::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  2464. {
  2465. const auto ctrl = e.mods.isCtrlDown(), alt = e.mods.isAltDown(), shift = e.mods.isShiftDown();
  2466. const auto overGrid = gridArea().contains (e.getPosition()) || velocityArea().contains (e.getPosition());
  2467. // Alt+wheel over a note: its velocity (or the lane's property); Ctrl+Alt: fine steps
  2468. if (alt && ! shift && overGrid && wheel.deltaY != 0.0f)
  2469. if (const auto note = hoverAt (e.getPosition()).note; note >= 0)
  2470. {
  2471. wheelNoteProperty (note, wheel.deltaY, ctrl);
  2472. return;
  2473. }
  2474. if (shift && alt) // nudge the selection by the grid
  2475. {
  2476. if (wheel.deltaY != 0.0f && ! selection.empty())
  2477. {
  2478. const auto now = juce::Time::getMillisecondCounter();
  2479. const auto newBurst = now - lastWheelEdit > 700;
  2480. lastWheelEdit = now;
  2481. const auto ticks = (wheel.deltaY > 0 ? 1 : -1) * gridTicks();
  2482. editNotes ([this, ticks] (Pattern& p) {
  2483. auto deltaTicks = ticks;
  2484. auto deltaKeys = 0;
  2485. noteedit::move (p, selection, deltaTicks, deltaKeys);
  2486. }, newBurst);
  2487. sortNotes();
  2488. }
  2489. return;
  2490. }
  2491. gliding = false;
  2492. if (ctrl && alt)
  2493. {
  2494. // vertical zoom keeping the key under the mouse in place
  2495. const auto key = yToKey (e.y);
  2496. const auto offset = e.y - keyToY (key);
  2497. rowHeight = juce::jlimit (6, 32, rowHeight + (wheel.deltaY > 0 ? 2 : -2));
  2498. scrollY = juce::jmax (0, (127 - key) * rowHeight + offset - (e.y - headerHeight));
  2499. }
  2500. else if (ctrl)
  2501. {
  2502. // zoom keeping the tick under the mouse in place
  2503. const auto anchorPixels = (double) juce::jmax (0, e.x - keyboardWidth);
  2504. const auto zoomed = juce::jlimit (2.0 / ticksPerStep, 120.0 / ticksPerStep, pixelsPerTick * gesture::wheelZoomFactor (wheel.deltaY, wheel.isSmooth));
  2505. scrollTicks = gesture::zoomAnchored (scrollTicks, pixelsPerTick, zoomed, anchorPixels);
  2506. pixelsPerTick = zoomed;
  2507. }
  2508. else
  2509. {
  2510. // plain wheel: up/down (Shift: left/right); a horizontal wheel or trackpad swipe scrolls sideways
  2511. const auto vertical = gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 3.0 * rowHeight);
  2512. const auto sideways = gesture::wheelScrollPixels (wheel.deltaX, wheel.isSmooth, 60.0);
  2513. if (shift)
  2514. glideBy (gesture::wheelScrollPixels (wheel.deltaY, wheel.isSmooth, 80.0) / pixelsPerTick, 0.0);
  2515. else
  2516. glideBy (sideways / pixelsPerTick, vertical);
  2517. return;
  2518. }
  2519. updateScrollBars();
  2520. repaint();
  2521. }
  2522. // --- keyboard ----------------------------------------------------------------
  2523. void PianoRollComponent::deleteSelection()
  2524. {
  2525. if (selection.empty())
  2526. return;
  2527. const auto doomed = selection;
  2528. setSelection ({});
  2529. editNotes ([&doomed] (Pattern& p) { noteedit::remove (p, doomed); });
  2530. }
  2531. void PianoRollComponent::copySelection()
  2532. {
  2533. clipboard = noteedit::copy (currentPattern (engine.getSong()), selectionOrAll());
  2534. }
  2535. void PianoRollComponent::paste()
  2536. {
  2537. if (clipboard.empty())
  2538. return;
  2539. // as in FL: pastes at the same position, already selected for dragging
  2540. std::vector<int> added;
  2541. const auto channel = engine.getSelectedChannel();
  2542. editNotes ([&added, channel] (Pattern& p) { added = noteedit::paste (p, clipboard, 0, channel); });
  2543. setSelection (added);
  2544. sortNotes();
  2545. }
  2546. void PianoRollComponent::duplicateSelection()
  2547. {
  2548. const auto source = selectionOrAll();
  2549. if (source.empty())
  2550. return;
  2551. std::vector<int> added;
  2552. const auto grid = gridTicks();
  2553. editNotes ([&added, &source, grid] (Pattern& p) { added = noteedit::duplicate (p, source, grid); });
  2554. setSelection (added);
  2555. sortNotes();
  2556. }
  2557. void PianoRollComponent::quantizeSelection()
  2558. {
  2559. const auto target = selectionOrAll();
  2560. const auto grid = gridTicks();
  2561. if (! target.empty())
  2562. {
  2563. editNotes ([&target, grid] (Pattern& p) { noteedit::quantize (p, target, grid); });
  2564. sortNotes();
  2565. }
  2566. }
  2567. void PianoRollComponent::nudge (std::int64_t ticks, int keys)
  2568. {
  2569. if (selection.empty())
  2570. return;
  2571. editNotes ([this, &ticks, &keys] (Pattern& p) { noteedit::move (p, selection, ticks, keys); });
  2572. if (keys != 0 && selection.size() == 1)
  2573. {
  2574. const auto& n = currentPattern (engine.getSong()).notes[(std::size_t) selection[0]];
  2575. previewOn (n.key, n.velocity);
  2576. juce::Timer::callAfterDelay (150, [safe = juce::Component::SafePointer<PianoRollComponent> (this)] {
  2577. if (safe != nullptr)
  2578. safe->previewOff();
  2579. });
  2580. }
  2581. sortNotes();
  2582. }
  2583. bool PianoRollComponent::handleKey (const juce::KeyPress& key)
  2584. {
  2585. const auto mods = key.getModifiers();
  2586. const auto cmd = mods.isCommandDown();
  2587. const auto alt = mods.isAltDown();
  2588. const auto shift = mods.isShiftDown();
  2589. const auto code = key.getKeyCode();
  2590. const auto letter = (int) juce::CharacterFunctions::toUpperCase ((juce::juce_wchar) code);
  2591. const auto grid = gridTicks();
  2592. const auto bar = (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  2593. if (code == juce::KeyPress::backspaceKey)
  2594. {
  2595. EditorGlobals::get().toggleGrid();
  2596. return true;
  2597. }
  2598. if (code == juce::KeyPress::deleteKey)
  2599. {
  2600. deleteSelection();
  2601. return true;
  2602. }
  2603. if (code == juce::KeyPress::escapeKey)
  2604. {
  2605. setSelection ({});
  2606. return true;
  2607. }
  2608. if (alt && cmd && letter == 'V') // editable ghost notes
  2609. {
  2610. editGhosts = ! editGhosts;
  2611. if (editGhosts && ! showGhosts)
  2612. ghostButton.setToggleState (true, juce::sendNotificationSync);
  2613. repaint();
  2614. return true;
  2615. }
  2616. if (alt && ! cmd && letter == 'V')
  2617. {
  2618. ghostButton.setToggleState (! ghostButton.getToggleState(), juce::sendNotificationSync);
  2619. return true;
  2620. }
  2621. if (cmd && alt && code == juce::KeyPress::homeKey)
  2622. {
  2623. resizeFromLeft = ! resizeFromLeft;
  2624. return true;
  2625. }
  2626. if (cmd && letter == 'A')
  2627. {
  2628. selectAll();
  2629. return true;
  2630. }
  2631. if (cmd && letter == 'C')
  2632. {
  2633. copySelection();
  2634. return true;
  2635. }
  2636. if (cmd && letter == 'X')
  2637. {
  2638. copySelection();
  2639. deleteSelection();
  2640. return true;
  2641. }
  2642. if (cmd && letter == 'V')
  2643. {
  2644. paste();
  2645. return true;
  2646. }
  2647. if (cmd && letter == 'B')
  2648. {
  2649. duplicateSelection();
  2650. return true;
  2651. }
  2652. // quick note operations: one undo step each, on the selection (or all notes)
  2653. if (cmd && letter == 'Q')
  2654. {
  2655. runOperation ([grid] (Pattern& p, const std::vector<int>& t) { noteedit::quantizeFull (p, t, grid); return t; });
  2656. return true;
  2657. }
  2658. if (shift && ! cmd && ! alt && letter == 'Q')
  2659. {
  2660. quantizeSelection();
  2661. return true;
  2662. }
  2663. if (cmd && letter == 'U')
  2664. {
  2665. runOperation ([grid] (Pattern& p, const std::vector<int>& t) { return noteedit::chop (p, t, grid); });
  2666. return true;
  2667. }
  2668. if (cmd && letter == 'G')
  2669. {
  2670. runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::join (p, t); return std::vector<int> {}; });
  2671. return true;
  2672. }
  2673. if (cmd && letter == 'L')
  2674. {
  2675. runOperation ([] (Pattern& p, const std::vector<int>& t) { noteedit::legato (p, t); return t; });
  2676. return true;
  2677. }
  2678. if (shift && ! cmd && ! alt && letter == 'D')
  2679. {
  2680. runOperation ([grid] (Pattern& p, const std::vector<int>& t) { noteedit::shrinkToGrid (p, t, grid); return t; });
  2681. return true;
  2682. }
  2683. if (cmd && shift && (code == juce::KeyPress::leftKey || code == juce::KeyPress::rightKey))
  2684. {
  2685. const auto steps = code == juce::KeyPress::rightKey ? 1 : -1;
  2686. runOperation ([grid, bar, steps] (Pattern& p, const std::vector<int>& t) { noteedit::rotate (p, t, grid, bar, steps); return t; });
  2687. return true;
  2688. }
  2689. if (cmd && letter == 'M')
  2690. {
  2691. toggleMute();
  2692. return true;
  2693. }
  2694. if (cmd && letter == 'P')
  2695. {
  2696. togglePorta();
  2697. return true;
  2698. }
  2699. if (! cmd && ! alt && ! selection.empty())
  2700. {
  2701. if (code == juce::KeyPress::upKey || code == juce::KeyPress::downKey)
  2702. {
  2703. nudge (0, (code == juce::KeyPress::upKey ? 1 : -1) * (shift ? 12 : 1));
  2704. return true;
  2705. }
  2706. if (code == juce::KeyPress::leftKey || code == juce::KeyPress::rightKey)
  2707. {
  2708. const auto amount = shift ? bar : grid;
  2709. nudge ((code == juce::KeyPress::rightKey ? 1 : -1) * amount, 0);
  2710. return true;
  2711. }
  2712. }
  2713. // single letters: only while the typing piano is off (otherwise they play notes)
  2714. if (! cmd && ! alt && ! shift && ! EditorGlobals::get().typingPiano)
  2715. {
  2716. for (const auto& t : editTools())
  2717. if (t.tool != EditTool::slip && letter == t.key)
  2718. {
  2719. tools.setTool (t.tool);
  2720. return true;
  2721. }
  2722. switch (letter)
  2723. {
  2724. case 'S': slideButton.setToggleState (! slideButton.getToggleState(), juce::dontSendNotification); return true;
  2725. case 'G': stepChannel (-1, false); return true; // previous channel
  2726. case 'K': stepChannel (1, false); return true; // next channel
  2727. case 'H': stepChannel (-1, true); return true; // previous channel with notes
  2728. case 'J': stepChannel (1, true); return true; // next channel with notes
  2729. default: break;
  2730. }
  2731. }
  2732. return false;
  2733. }
  2734. juce::PopupMenu PianoRollComponent::midiMenu()
  2735. {
  2736. juce::PopupMenu menu;
  2737. menu.addItem (tr ("Import .mid into this channel..."), [this] {
  2738. chooser = std::make_unique<juce::FileChooser> (tr ("Import MIDI"), juce::File(), "*.mid;*.midi");
  2739. chooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [this] (const juce::FileChooser& fc) {
  2740. if (! fc.getResult().existsAsFile())
  2741. return;
  2742. juce::String error;
  2743. const auto file = fc.getResult();
  2744. const auto midi = MidiFileIo::parseFile (file, error);
  2745. if (! midi)
  2746. {
  2747. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", error);
  2748. return;
  2749. }
  2750. // FL's "Import MIDI data" window with Blend (REA round 146b): which tracks / channels / controller
  2751. static midiimport::Options remembered;
  2752. juce::Component::SafePointer<PianoRollComponent> safe (this);
  2753. showMidiImportDialog (file.getFileName(), *midi, remembered, true, [safe, midi = *midi] (const midiimport::Options& o) {
  2754. remembered = o;
  2755. if (safe == nullptr)
  2756. return;
  2757. std::vector<int> added;
  2758. std::string err;
  2759. const auto channel = safe->engine.getSelectedChannel();
  2760. safe->engine.editSong ([&] (Song& s) { added = midiimport::importIntoChannel (s, channel, midi, o, err); });
  2761. if (added.empty())
  2762. {
  2763. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", juce::String::fromUTF8 (err.c_str()));
  2764. return;
  2765. }
  2766. safe->knownNoteCount = currentPattern (safe->engine.getSong()).notes.size();
  2767. safe->setSelection (added);
  2768. safe->scrollToNotes();
  2769. safe->repaint();
  2770. });
  2771. });
  2772. });
  2773. menu.addItem (tr ("Export pattern as .mid..."), [this] {
  2774. const auto& song = engine.getSong();
  2775. const auto name = juce::String::fromUTF8 (song.patterns[(std::size_t) song.currentPattern].name.c_str());
  2776. chooser = std::make_unique<juce::FileChooser> (tr ("Export MIDI"), juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile (name + ".mid"),
  2777. "*.mid");
  2778. chooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting, [this] (const juce::FileChooser& fc) {
  2779. auto file = fc.getResult();
  2780. if (file == juce::File())
  2781. return;
  2782. if (! file.hasFileExtension ("mid;midi"))
  2783. file = file.withFileExtension (".mid");
  2784. juce::String error;
  2785. if (! MidiFileIo::savePattern (engine.getSong(), engine.getSong().currentPattern, file, error))
  2786. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, "MIDI", error);
  2787. });
  2788. });
  2789. return menu;
  2790. }
  2791. // --- other -------------------------------------------------------------------
  2792. void PianoRollComponent::scrollBarMoved (juce::ScrollBar* bar, double start)
  2793. {
  2794. if (bar == &hBar)
  2795. scrollTicks = start;
  2796. else
  2797. scrollY = (int) start;
  2798. repaint();
  2799. }
  2800. void PianoRollComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  2801. {
  2802. // pattern/channel switched or the pattern changed externally (undo, another window): the selection no longer applies
  2803. const auto& song = engine.getSong();
  2804. const auto count = currentPattern (song).notes.size();
  2805. if (song.currentPattern != knownPattern || engine.getSelectedChannel() != knownChannel || count != knownNoteCount)
  2806. {
  2807. if (engine.getSelectedChannel() != knownChannel)
  2808. stopListening();
  2809. knownPattern = song.currentPattern;
  2810. knownChannel = engine.getSelectedChannel();
  2811. knownNoteCount = count;
  2812. if (drag == Drag::none)
  2813. selection.clear();
  2814. }
  2815. refreshChannelBox();
  2816. rebuildLaneBox();
  2817. updateScrollBars();
  2818. repaint();
  2819. }
  2820. std::optional<AutomationTarget> PianoRollComponent::eventLaneTarget() const
  2821. {
  2822. const auto k = laneBox.getSelectedId() - eventLaneIdBase;
  2823. if (k >= 0 && k < (int) eventTargets.size())
  2824. return eventTargets[(std::size_t) k];
  2825. return std::nullopt;
  2826. }
  2827. void PianoRollComponent::rebuildLaneBox (std::optional<AutomationTarget> shown, bool force)
  2828. {
  2829. // the pattern's event lanes, plus the one shown (it may have no events yet)
  2830. if (! shown)
  2831. shown = eventLaneTarget();
  2832. std::vector<AutomationTarget> targets;
  2833. for (const auto& lane : currentPattern (engine.getSong()).events)
  2834. if (lane.target.kind != AutomationTargetKind::none && ! lane.events.empty())
  2835. targets.push_back (lane.target);
  2836. if (shown && std::find (targets.begin(), targets.end(), *shown) == targets.end())
  2837. targets.push_back (*shown);
  2838. if (targets == eventTargets && ! force)
  2839. return;
  2840. eventTargets = targets;
  2841. const auto previous = laneBox.getSelectedId();
  2842. laneBox.clear (juce::dontSendNotification);
  2843. laneBox.addItem (tr ("Velocity"), 1);
  2844. laneBox.addItem (tr ("Pan"), 2);
  2845. laneBox.addItem (tr ("Fine pitch"), 3);
  2846. if (! eventTargets.empty())
  2847. laneBox.addSectionHeading (tr ("Pattern events"));
  2848. for (int k = 0; k < (int) eventTargets.size(); ++k)
  2849. laneBox.addItem (describeAutomationTarget (engine, eventTargets[(std::size_t) k]), eventLaneIdBase + k);
  2850. auto id = previous >= 1 && previous <= 3 ? previous : 1;
  2851. if (shown)
  2852. id = eventLaneIdBase + (int) (std::find (eventTargets.begin(), eventTargets.end(), *shown) - eventTargets.begin());
  2853. laneBox.setSelectedId (id, juce::dontSendNotification);
  2854. }
  2855. void PianoRollComponent::showEventLane (const AutomationTarget& target)
  2856. {
  2857. rebuildLaneBox (target, true);
  2858. repaint();
  2859. }
  2860. void PianoRollComponent::drawEvents (int fromX, int toX, int y, bool erase)
  2861. {
  2862. const auto target = eventLaneTarget();
  2863. if (! target)
  2864. return;
  2865. const auto lane = velocityArea();
  2866. const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - y) / (float) (lane.getHeight() - 8));
  2867. const auto step = std::max<std::int64_t> (1, gridTicks());
  2868. const auto t0 = std::max<std::int64_t> (0, (std::int64_t) std::floor (xToTick (juce::jmin (fromX, toX)) / (double) step) * step);
  2869. const auto t1 = std::max (t0 + step, (std::int64_t) std::floor (xToTick (juce::jmax (fromX, toX)) / (double) step) * step + step);
  2870. const auto pattern = engine.getSong().currentPattern;
  2871. engine.editSong ([&] (Song& s) {
  2872. if (pattern < 0 || pattern >= (int) s.patterns.size())
  2873. return;
  2874. auto& p = s.patterns[(std::size_t) pattern];
  2875. if (erase)
  2876. {
  2877. if (auto* l = eventedit::findLane (p, *target))
  2878. eventedit::erase (*l, t0, t1);
  2879. eventedit::removeEmptyLanes (p);
  2880. }
  2881. else
  2882. eventedit::fill (eventedit::laneFor (p, *target), t0, t1, value, step);
  2883. });
  2884. repaint (velocityArea());
  2885. }
  2886. void PianoRollComponent::timerCallback()
  2887. {
  2888. if (channelBox.getSelectedId() != engine.getSelectedChannel() + 1)
  2889. refreshChannelBox();
  2890. updateChordReadout();
  2891. auto& transport = engine.getTransport();
  2892. auto tick = -1.0;
  2893. if (transport.playing.load() && isShowing() && engine.getSong().mode == PlayMode::pattern)
  2894. {
  2895. const auto& song = engine.getSong();
  2896. tick = std::fmod (transport.positionTicks.load(), (double) currentPattern (song).effectiveLength (song.beatsPerBar));
  2897. }
  2898. if (tick != playheadTick)
  2899. {
  2900. auto dirty = [this] (double t) {
  2901. if (t >= 0.0)
  2902. repaint ((int) tickToX (t) - 7, 0, 14, getHeight());
  2903. };
  2904. dirty (playheadTick);
  2905. playheadTick = tick;
  2906. dirty (tick);
  2907. }
  2908. }
  2909. } // namespace lynx