PianoRollComponent.cpp 155 KB

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